From 9c02ebdee5be68027c6a096ac4c29cbe1bf7c3e2 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 19:00:07 -0600 Subject: [PATCH] vector/ogmo: Ogmo Editor 3 levels and projects read + write as a TileMap (tile / grid / entity / decal layers, every save layout, values; HaxeFlixel TurnBasedRPG sample, MIT) --- README.md | 3 +- docs/FORMATS.md | 1 + docs/guide/tilemap.md | 32 ++ licenses/NOTICE.md | 1 + licenses/flixel-demos-LICENSE.txt | 20 ++ src/Rosetta/Registry.luau | 12 + src/Rosetta/vector/ogmo/Read.luau | 403 ++++++++++++++++++++++++++ src/Rosetta/vector/ogmo/Write.luau | 352 ++++++++++++++++++++++ src/Rosetta/vector/ogmo/init.luau | 117 ++++++++ tests/fixtures/ogmo/room-001.json | 58 ++++ tests/fixtures/ogmo/turnBasedRPG.ogmo | 187 ++++++++++++ tests/vector/ogmo.luau | 212 ++++++++++++++ tools/fixtures/_ogmo_encode.luau | 28 ++ tools/fixtures/docs_engines.py | 9 +- tools/fixtures/ogmo.py | 165 +++++++++++ 15 files changed, 1596 insertions(+), 4 deletions(-) create mode 100644 licenses/flixel-demos-LICENSE.txt create mode 100644 src/Rosetta/vector/ogmo/Read.luau create mode 100644 src/Rosetta/vector/ogmo/Write.luau create mode 100644 src/Rosetta/vector/ogmo/init.luau create mode 100644 tests/fixtures/ogmo/room-001.json create mode 100644 tests/fixtures/ogmo/turnBasedRPG.ogmo create mode 100644 tests/vector/ogmo.luau create mode 100644 tools/fixtures/_ogmo_encode.luau create mode 100644 tools/fixtures/ogmo.py diff --git a/README.md b/README.md index 8809bb7..2cb925b 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -177 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +178 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | @@ -195,6 +195,7 @@ adds each format's capabilities. | Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | | Data | yaml | .yaml .yml | yes | yes | | Vector graphics and tile maps | ldtk | .ldtk | yes | yes | +| Vector graphics and tile maps | ogmo | .ogmo | yes | yes | | Vector graphics and tile maps | svg | .svg | yes | yes | | Vector graphics and tile maps | tiled | .tmx .tmj .tsx .tsj | yes | yes | | Layered images | aseprite | .aseprite .ase | yes | yes | diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 4259416..245e1dd 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -151,6 +151,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | | vector | ldtk | .ldtk | yes | yes | levels: true, worlds: true, intGrid: true, entities: true | `tests/vector/ldtk.luau` | +| vector | ogmo | .ogmo | yes | yes | projects: true, entities: true, decals: true | `tests/vector/ogmo.luau` | | vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.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` | diff --git a/docs/guide/tilemap.md b/docs/guide/tilemap.md index 8b04fcc..9146de3 100644 --- a/docs/guide/tilemap.md +++ b/docs/guide/tilemap.md @@ -240,6 +240,37 @@ local back = assert(F.load(ldtk)) assert(back.layers[1].layers[1].tiles[2].tile == 3) ``` +## Ogmo Editor 3 + +[Ogmo Editor 3](https://ogmo-editor-3.github.io) keeps a project (`.ogmo`: layer definitions, entity templates, +tilesets with their images embedded) and one JSON file per level. A level loads as a `TileMap`; pass its project as +`opts.project` (bytes or decoded JSON) to get the tilesets (gids), the map grid, entity template sizes and value +types. Without it tile layers keep `id + 1` as their gids. A project alone loads with `meta.project = true`, its +tilesets and one empty layer per definition. + +| Ogmo layer | `TileLayer` (`ogmoType`) | +|---|---| +| tile (ids or coords, 1D or 2D) | `"tiles"` (`"tile"`): `data` gids, `tileset`, the tile flags as Tiled flip bits | +| grid | `"tiles"` (`"grid"`): `grid` (the cell strings, `"0"` empty), `data` (their numbers), `legend` | +| entity | `"objects"` (`"entity"`): `x` / `y` top-left (position minus `originX` / `originY`), `width`, `height`, `rotation` in degrees, `flippedX` / `flippedY`, `nodes` (`{ { x, y } }`), values as `properties` | +| decal | `"objects"` (`"decal"`): `texture`, `x` / `y`, `scaleX` / `scaleY`, `rotation` in degrees, `originX` / `originY` | + +Ogmo's first layer is drawn on top, so the layers are reversed (bottom first, as everywhere in `TileMap`). Layers keep +their cell size (`cellWidth`, `cellHeight`) and save layout (`exportMode`, `arrayMode`). Tileset images stay bytes +(`tileset.imageData`, a PNG) next to their `imageSource` path. + +```luau +local map = assert(F.load(ogmoLevelText, { format = "ogmo", project = ogmoProjectText })) +assert(map.pxWidth == 640 and map.tileWidth == 8) -- the project's grid +local walls = map.layers[1] +assert(walls.ogmoType == "tile" and walls.tileset == "tiles" and walls.width == 40) +local things = map.layers[2] +assert(things.objects[1].class == "player" and things.objects[1].x == 128) +local level = assert(F.save(map, nil, { format = "ogmo" })) -- a level +local project = assert(F.save(map, nil, { format = "ogmo", kind = "project" })) -- a project for any map +assert(F.detect(project) == "ogmo") +``` + ## Formats | Format | Read | Write | Notes | @@ -247,6 +278,7 @@ assert(back.layers[1].layers[1].tiles[2].tile == 3) | TMX / TSX | yes | yes | CSV, base64 (raw, zlib, gzip) and `` data; zstd data returns `UNSUPPORTED` | | TMJ / TSJ | yes | yes | | | LDtk (`.ldtk`) | yes | yes | levels as groups, worlds, IntGrid / auto / tile / entity layers, fields; `.ldtkl` through `resolve`; writes embedded levels | +| Ogmo Editor 3 (`.ogmo`, level `.json`) | yes | yes | tile / grid / entity / decal layers, values; the project through `opts.project` | TMX and TMJ are both the `tiled` format in [FORMATS.md](../FORMATS.md) (Wang sets and terrains are dropped). diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index fb5e437..f3d8a08 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -29,6 +29,7 @@ | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | | `tests/fixtures/vox/{chr_knight,chr_sword,deer,maze}.vox`, `tests/fixtures/vox/MagicaVoxel-file-format-vox*.txt` (the format spec) | ephtracy/voxel-model (MagicaVoxel sample models) | MIT: [voxel-model-LICENSE.txt](voxel-model-LICENSE.txt) | | `tests/fixtures/vox/ogt_*.vox` | jpaver/opengametools `demo/vox/` (files saved by MagicaVoxel 0.99.x) | MIT: [opengametools-LICENSE.txt](opengametools-LICENSE.txt) | +| `tests/fixtures/ogmo/{turnBasedRPG.ogmo,room-001.json}` | HaxeFlixel/flixel-demos `Tutorials/TurnBasedRPG/assets/data/` (an Ogmo Editor 3.3 project and level) | MIT: [flixel-demos-LICENSE.txt](flixel-demos-LICENSE.txt) | | `tests/fixtures/gltf/` | KhronosGroup/glTF-Sample-Assets `Models/` (one LICENSE.md per model folder; `UnicodeTest` is `Unicode❤♻Test` renamed) | CC-BY-4.0 or CC0-1.0 per model, see each folder's LICENSE.md | | `src/Rosetta/codecs/Vp8/` (Decode, Yuv, Tables), `src/Rosetta/codecs/Vp8L/Decode.luau`, `src/Rosetta/image/webp/` (Alpha unfilters, Anim.coalesce) | ports of libwebp 1.6.0 (Google): src/dec, src/dsp, src/utils, src/demux/anim_decode.c | BSD-3-Clause + patent grant: [libwebp-LICENSE.txt](libwebp-LICENSE.txt) | | `src/Rosetta/codecs/Tracker/`, `src/Rosetta/music/{mod,s3m,xm,it}/` | written for this library from the format documents: ProTracker 2.3 effect docs, the XM specification (Mr.H / Triton) and FT2 behaviour notes, ST3 TECH.DOC (Sami Tammilehto / Future Crew), ITTECH.TXT (Jeffrey Lim); OpenMPT (libopenmpt, BSD) was used only as the reference player in the tests, and its documented playback quirks (mix levels, MOD panning, FT2 E6x / tremor / instrument behaviour) are matched | no third-party code | diff --git a/licenses/flixel-demos-LICENSE.txt b/licenses/flixel-demos-LICENSE.txt new file mode 100644 index 0000000..6308e93 --- /dev/null +++ b/licenses/flixel-demos-LICENSE.txt @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 5805e93..999cca5 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -1766,6 +1766,18 @@ local list: { Entry } = { return require("@rosetta/vector/ldtk") end, }, + { + name = "ogmo", + category = "vector", + path = "vector/ogmo", + extensions = { "ogmo" }, + mime = { "application/x-ogmo+json" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "core/Base64", "Types", "codecs/text/Json" }, + caps = { decode = true, encode = true, projects = true, entities = true, decals = true }, + load = function() + return require("@rosetta/vector/ogmo") + end, + }, { name = "svg", category = "vector", diff --git a/src/Rosetta/vector/ogmo/Read.luau b/src/Rosetta/vector/ogmo/Read.luau new file mode 100644 index 0000000..8d296d4 --- /dev/null +++ b/src/Rosetta/vector/ogmo/Read.luau @@ -0,0 +1,403 @@ +--!strict +-- vector/ogmo/Read: Ogmo Editor 3 projects (.ogmo) and levels (.json) into a Types.TileMap (layer save / load as in +-- OgmoEditor3-CE src/modules/*/ *Layer.hx). Ogmo's first layer is drawn on top: layers are reversed (bottom first). +-- Tile ids -1 are empty; tileFlags 4 / 2 / 1 (flip H / V / diagonal) become Tiled's 0x80000000 / 0x40000000 / +-- 0x20000000. +local Types = require("@rosetta/Types") +local Json = require("@rosetta/codecs/text/Json") +local Base64 = require("@rosetta/core/Base64") + +local Read = {} + +local NULL = Json.null +local FLIP_H, FLIP_V, FLIP_D = 0x80000000, 0x40000000, 0x20000000 + +local function tab(v: any): boolean + return type(v) == "table" and v ~= NULL +end +local function list(v: any): { any } + return if tab(v) then v else {} +end +local function n(v: any, default: number): number + return if type(v) == "number" and v == v then v else default +end +local function s(v: any): string? + return if type(v) == "string" then v else nil +end +local function vec(v: any, dx: number, dy: number): (number, number) + if tab(v) then + return n(v.x, dx), n(v.y, dy) + end + return dx, dy +end + +-- PNG IHDR width / height of an embedded tileset image (data: URI) +local function pngSize(b: buffer): (number?, number?) + if buffer.len(b) >= 24 and buffer.readstring(b, 0, 8) == "\137PNG\r\n\26\n" and buffer.readstring(b, 12, 4) == "IHDR" then + local function be(o: number): number + return buffer.readu8(b, o) * 16777216 + buffer.readu8(b, o + 1) * 65536 + buffer.readu8(b, o + 2) * 256 + buffer.readu8(b, o + 3) + end + return be(16), be(20) + end + return nil, nil +end + +local VALUE_TYPES: { [string]: string } = { Integer = "int", Float = "float", Boolean = "bool", Color = "color", Filepath = "file", String = "string", Text = "string", Enum = "string" } + +function Read.tilesets(project: any): { Types.Tileset } + local out: { Types.Tileset } = {} + local gid = 1 + for _, t in list(project and project.tilesets) do + if tab(t) then + local tw, th = math.max(1, n(t.tileWidth, 16)), math.max(1, n(t.tileHeight, 16)) + local sx, sy = n(t.tileSeparationX, 0), n(t.tileSeparationY, 0) + local mx, my = n(t.tileMarginX, 0), n(t.tileMarginY, 0) + local data: buffer? = nil + local iw, ih = nil, nil + if type(t.image) == "string" and string.sub(t.image, 1, 5) == "data:" then + data = Base64.decodeDataUri(t.image) + if data then + iw, ih = pngSize(data) + end + end + local cols = if iw then math.max(1, (iw - 2 * mx + sx) // (tw + sx)) else 1 + local rows = if ih then math.max(1, (ih - 2 * my + sy) // (th + sy)) else 1 + local ts: Types.Tileset = { + name = s(t.label) or ("tileset" .. #out), + firstGid = gid, + tileWidth = tw, + tileHeight = th, + columns = cols, + count = cols * rows, + imageSource = s(t.path), + imageWidth = iw, + imageHeight = ih, + imageData = data, + spacing = sx, + spacingY = if sy ~= sx then sy else nil, + margin = mx, + marginY = if my ~= mx then my else nil, + } + gid += ts.count + table.insert(out, ts) + end + end + return out +end + +local function valueTypes(defs: any): { [string]: string }? + local out: { [string]: string }? = nil + for _, d in list(defs) do + if tab(d) and type(d.name) == "string" and type(d.definition) == "string" then + local typ = VALUE_TYPES[d.definition] + if typ and typ ~= "string" then + out = out or {} + ;(out :: any)[d.name] = typ + end + end + end + return out +end + +local function values(v: any): { [string]: any } + local out: { [string]: any } = {} + if tab(v) then + for k, x in v do + if type(k) == "string" then + out[k] = x + end + end + end + return out +end + +type Ctx = { project: any, tilesets: { Types.Tileset }, byName: { [string]: Types.Tileset }, layerDefs: { [string]: any }, entityDefs: { [string]: any }, radians: boolean, maxCells: number } + +local function cells2D(v: any, w: number, h: number): { any } + local out = table.create(w * h) + for y, row in list(v) do + for x, c in list(row) do + if x <= w and y <= h then + out[(y - 1) * w + x] = c + end + end + end + return out +end + +local function tileLayer(ctx: Ctx, li: any, l: Types.TileLayer, w: number, h: number) + local ts = ctx.byName[s(li.tileset) or ""] or ctx.tilesets[1] + l.tileset = s(li.tileset) + local exportMode, arrayMode = n(li.exportMode, 0), n(li.arrayMode, 0) + local raw: { any } + if exportMode == 1 then + raw = if arrayMode == 1 then cells2D(li.dataCoords2D, w, h) else list(li.dataCoords) + else + raw = if arrayMode == 1 then cells2D(li.data2D, w, h) else list(li.data) + end + local flags = if arrayMode == 1 then cells2D(li.tileFlags2D, w, h) else list(li.tileFlags) + local data = table.create(w * h, 0) + for i = 1, w * h do + local c = raw[i] + local id = -1 + if exportMode == 1 then + if tab(c) and n(c[1], -1) >= 0 then + id = n(c[2], 0) * (if ts then ts.columns else 1) + n(c[1], 0) + end + else + id = n(c, -1) + end + if id >= 0 and ts then + local gid = ts.firstGid + id + local f = n(flags[i], 0) + if bit32.btest(f, 4) then + gid += FLIP_H + end + if bit32.btest(f, 2) then + gid += FLIP_V + end + if bit32.btest(f, 1) then + gid += FLIP_D + end + data[i] = gid + elseif id >= 0 then + data[i] = id + 1 + end + end + l.data = data +end + +local function entity(ctx: Ctx, e: any): { [string]: any } + local def = ctx.entityDefs[s(e.name) or ""] + local dw, dh = vec(def and def.size, 16, 16) + local dox, doy = vec(def and def.origin, 0, 0) + local w, h = n(e.width, dw), n(e.height, dh) + local ox, oy = n(e.originX, dox), n(e.originY, doy) + local rot = n(e.rotation, 0) + if ctx.radians then + rot = math.deg(rot) + end + local nodes = nil + if tab(e.nodes) then + nodes = {} + for i, p in e.nodes do + nodes[i] = { n(tab(p) and p.x, 0), n(tab(p) and p.y, 0) } + end + end + return { + id = e.id, + name = s(e.name) or "", + class = s(e.name) or "", + x = n(e.x, 0) - ox, + y = n(e.y, 0) - oy, + width = w, + height = h, + rotation = rot, + visible = true, + shape = "rectangle", + originX = ox, + originY = oy, + flippedX = if type(e.flippedX) == "boolean" then e.flippedX else nil, + flippedY = if type(e.flippedY) == "boolean" then e.flippedY else nil, + color = s(e.color), + nodes = nodes, + eid = s(e._eid), + properties = values(e.values), + propertyTypes = if def then valueTypes(def.values) else nil, + } +end + +local function decal(ctx: Ctx, d: any): { [string]: any } + local rot = n(d.rotation, 0) + if ctx.radians then + rot = math.deg(rot) + end + return { + name = s(d.texture) or "", + class = "decal", + shape = "decal", + texture = s(d.texture), + x = n(d.x, 0), + y = n(d.y, 0), + width = 0, + height = 0, + originX = n(d.originX, 0.5), + originY = n(d.originY, 0.5), + scaleX = n(d.scaleX, 1), + scaleY = n(d.scaleY, 1), + rotation = rot, + visible = true, + properties = values(d.values), + } +end + +local function layer(ctx: Ctx, li: any): (Types.TileLayer?, string?) + local name = s(li.name) or "" + local def = ctx.layerDefs[name] + local kind = (def and s(def.definition)) or (if li.entities ~= nil then "entity" + elseif li.decals ~= nil then "decal" + elseif li.grid ~= nil or li.grid2D ~= nil then "grid" + else "tile") + local w, h = n(li.gridCellsX, 0), n(li.gridCellsY, 0) + if w < 0 or h < 0 or w * h > ctx.maxCells then + return nil, "limit: layer of " .. w .. " x " .. h .. " cells" + end + local l: Types.TileLayer = { + name = name, + type = if kind == "entity" or kind == "decal" then "objects" else "tiles", + visible = true, + opacity = 1, + properties = {}, + offsetX = n(li.offsetX, 0), + offsetY = n(li.offsetY, 0), + ogmoType = kind, + cellWidth = n(li.gridCellWidth, 0), + cellHeight = n(li.gridCellHeight, 0), + eid = s(li._eid), + exportMode = if type(li.exportMode) == "number" then li.exportMode else nil, + arrayMode = if type(li.arrayMode) == "number" then li.arrayMode else nil, + } + if kind == "entity" then + local objs = {} + for _, e in list(li.entities) do + if tab(e) then + table.insert(objs, entity(ctx, e)) + end + end + l.objects = objs + elseif kind == "decal" then + local objs = {} + for _, d in list(li.decals) do + if tab(d) then + table.insert(objs, decal(ctx, d)) + end + end + l.objects = objs + l.folder = s(li.folder) + elseif kind == "grid" then + l.width, l.height = w, h + local raw = if n(li.arrayMode, 0) == 1 then cells2D(li.grid2D, w, h) else list(li.grid) + local grid = table.create(w * h, "0") + local data = table.create(w * h, 0) + for i = 1, w * h do + local c = raw[i] + local v = if type(c) == "string" then c elseif type(c) == "number" then tostring(c) else "0" + grid[i] = v + data[i] = tonumber(v) or 0 + end + l.grid = grid + l.data = data + if def and tab(def.legend) then + l.legend = values(def.legend) + end + else + l.width, l.height = w, h + tileLayer(ctx, li, l, w, h) + end + return l, nil +end + +local function context(project: any, opts: any): Ctx + local ts = Read.tilesets(project) + local ctx: Ctx = { project = project, tilesets = ts, byName = {}, layerDefs = {}, entityDefs = {}, radians = true, maxCells = opts.maxCells or 2 ^ 26 } + for _, t in ts do + ctx.byName[t.name] = t + end + if tab(project) then + ctx.radians = project.anglesRadians ~= false + for _, d in list(project.layers) do + if tab(d) and type(d.name) == "string" then + ctx.layerDefs[d.name] = d + end + end + for _, d in list(project.entities) do + if tab(d) and type(d.name) == "string" then + ctx.entityDefs[d.name] = d + end + end + end + return ctx +end + +local function gridSize(project: any, layers: { any }): (number, number) + if tab(project) and tab(project.layerGridDefaultSize) then + local x, y = vec(project.layerGridDefaultSize, 16, 16) + return math.max(1, x), math.max(1, y) + end + for _, l in layers do + if tab(l) and type(l.gridCellWidth) == "number" then + return math.max(1, l.gridCellWidth), math.max(1, n(l.gridCellHeight, l.gridCellWidth)) + end + end + return 16, 16 +end + +function Read.level(v: any, project: any, opts: any): (Types.TileMap?, string?) + if not tab(v) or not tab(v.layers) then + return nil, "no layers: not an Ogmo level" + end + local ctx = context(project, opts) + local tw, th = gridSize(project, v.layers) + local pw, ph = n(v.width, 0), n(v.height, 0) + local map = Types.TileMap.new(math.ceil(pw / tw), math.ceil(ph / th), tw, th) + map.tilesets = ctx.tilesets + map.pxWidth, map.pxHeight = pw, ph + map.offsetX, map.offsetY = n(v.offsetX, 0), n(v.offsetY, 0) + map.properties = values(v.values) + if tab(project) then + map.propertyTypes = valueTypes(project.levelValues) + end + local ls = v.layers + for i = #ls, 1, -1 do + if tab(ls[i]) then + local l, err = layer(ctx, ls[i]) + if not l then + return nil, err + end + table.insert(map.layers, l) + end + end + map.meta.source = { format = "ogmo", version = s(v.ogmoVersion), level = true, anglesRadians = ctx.radians } + if tab(project) then + map.ogmo = project + end + return map, nil +end + +function Read.project(v: any, opts: any): (Types.TileMap?, string?) + local ctx = context(v, opts) + local tw, th = gridSize(v, {}) + local lw, lh = vec(v.levelDefaultSize, 0, 0) + local map = Types.TileMap.new(math.ceil(lw / tw), math.ceil(lh / th), tw, th) + map.tilesets = ctx.tilesets + map.name = s(v.name) + map.backgroundColor = s(v.backgroundColor) + local defs = list(v.layers) + for i = #defs, 1, -1 do + local d = defs[i] + if tab(d) and type(d.name) == "string" then + local kind = s(d.definition) or "tile" + local gx, gy = vec(d.gridSize, tw, th) + local l: Types.TileLayer = { + name = d.name, + type = if kind == "entity" or kind == "decal" then "objects" else "tiles", + visible = true, + opacity = 1, + properties = {}, + ogmoType = kind, + cellWidth = gx, + cellHeight = gy, + eid = s(d.exportID), + tileset = s(d.defaultTileset), + } + table.insert(map.layers, l) + end + end + map.entities = list(v.entities) + map.ogmo = v + map.meta.source = { format = "ogmo", version = s(v.ogmoVersion), project = true, anglesRadians = ctx.radians } + map.meta.project = true + return map, nil +end + +return Read diff --git a/src/Rosetta/vector/ogmo/Write.luau b/src/Rosetta/vector/ogmo/Write.luau new file mode 100644 index 0000000..7677b38 --- /dev/null +++ b/src/Rosetta/vector/ogmo/Write.luau @@ -0,0 +1,352 @@ +--!strict +-- vector/ogmo/Write: a Types.TileMap as an Ogmo Editor 3 level (.json) or project (.ogmo), in the shapes Ogmo 3.4 +-- saves (Layer.save / TileLayer.save / GridLayer.save / Entity.save / Decal.save). A project read from Ogmo is +-- written back with its own definitions; otherwise layers, tilesets and entity templates are made from the map. +local Types = require("@rosetta/Types") +local Json = require("@rosetta/codecs/text/Json") +local Base64 = require("@rosetta/core/Base64") + +local Write = {} + +local NULL = Json.null +local FLAGS = 0xF0000000 +local VERSION = "3.4.0" + +local function tab(v: any): boolean + return type(v) == "table" and v ~= NULL +end +local function list(v: any): { any } + return if tab(v) then v else {} +end +local function n(v: any, default: number): number + return if type(v) == "number" and v == v then v else default +end + +-- key / value pairs; a nil value (an absent optional field) is skipped +local function obj(pairs_: { any }): any + local out, keys = {}, {} + local i = 1 + while pairs_[i] ~= nil do + if pairs_[i + 1] ~= nil then + table.insert(keys, pairs_[i]) + out[pairs_[i]] = pairs_[i + 1] + end + i += 2 + end + return Json.object(out, keys) +end + +local function values(props: any): any + local out = {} + local keys = {} + if tab(props) then + for k, v in props do + if type(k) == "string" then + out[k] = v + table.insert(keys, k) + end + end + end + table.sort(keys) + return Json.object(out, keys) +end + +local function eid(l: any, i: number): string + return if type(l.eid) == "string" then l.eid else tostring(10000000 + i) +end + +local function flat(layers: { any }, into: { any }) + for _, l in layers do + if l.type == "group" then + flat(list(l.layers), into) + elseif l.type == "tiles" or l.type == "objects" then + table.insert(into, l) + end + end +end + +local function tilesetOf(map: Types.TileMap, gid: number): Types.Tileset? + local best: Types.Tileset? = nil + for _, ts in map.tilesets do + if ts.firstGid <= gid and (best == nil or ts.firstGid > (best :: Types.Tileset).firstGid) then + best = ts + end + end + return best +end + +local function layerTileset(map: Types.TileMap, l: any): Types.Tileset? + if type(l.tileset) == "string" then + for _, ts in map.tilesets do + if ts.name == l.tileset then + return ts + end + end + end + for _, raw in list(l.data) do + local gid = bit32.band(n(raw, 0), bit32.bnot(FLAGS)) + if gid ~= 0 then + return tilesetOf(map, gid) + end + end + return map.tilesets[1] +end + +local function kindOf(l: any): string + if type(l.ogmoType) == "string" then + return l.ogmoType + elseif l.type == "objects" then + for _, o in list(l.objects) do + if o.shape == "decal" then + return "decal" + end + end + return "entity" + elseif tab(l.grid) then + return "grid" + end + return "tile" +end + +-- ------------------------------------------------------------------------------------------------ level +local function rows2D(flatList: { any }, w: number, h: number): { any } + local out = {} + for y = 1, h do + local row = {} + for x = 1, w do + row[x] = flatList[(y - 1) * w + x] + end + out[y] = row + end + return out +end + +local function tileLayer(map: Types.TileMap, l: any, i: number, gw: number, gh: number): any + local ts = layerTileset(map, l) + local w, h = n(l.width, math.ceil(n(map.pxWidth, map.width * map.tileWidth) / gw)), n(l.height, math.ceil(n(map.pxHeight, map.height * map.tileHeight) / gh)) + local ids, coords, flags = table.create(w * h, -1), table.create(w * h), table.create(w * h, 0) + local anyFlag = false + local data = list(l.data) + for k = 1, w * h do + local raw = n(data[k], 0) + local gid = bit32.band(raw, bit32.bnot(FLAGS)) + local id = -1 + if gid ~= 0 then + id = if ts then gid - ts.firstGid else gid - 1 + if ts and (id < 0 or id >= math.max(ts.count, 1)) then + id = -1 + end + end + ids[k] = id + if id >= 0 then + local cols = if ts then math.max(1, ts.columns) else 1 + coords[k] = { id % cols, id // cols } + local f = (if bit32.btest(raw, 0x80000000) then 4 else 0) + (if bit32.btest(raw, 0x40000000) then 2 else 0) + (if bit32.btest(raw, 0x20000000) then 1 else 0) + flags[k] = f + anyFlag = anyFlag or f ~= 0 + else + coords[k] = { -1 } + end + end + local exportMode, arrayMode = n(l.exportMode, 0), n(l.arrayMode, 0) + local fields: { any } = { + "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, + "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "tileset", if ts then ts.name else "", + } + local key = if exportMode == 1 then (if arrayMode == 1 then "dataCoords2D" else "dataCoords") else (if arrayMode == 1 then "data2D" else "data") + local body = if exportMode == 1 then coords else ids + table.insert(fields, key) + table.insert(fields, if arrayMode == 1 then rows2D(body, w, h) else body) + if anyFlag then + table.insert(fields, if arrayMode == 1 then "tileFlags2D" else "tileFlags") + table.insert(fields, if arrayMode == 1 then rows2D(flags, w, h) else flags) + end + table.insert(fields, "exportMode") + table.insert(fields, exportMode) + table.insert(fields, "arrayMode") + table.insert(fields, arrayMode) + return obj(fields) +end + +local function gridLayer(map: Types.TileMap, l: any, i: number, gw: number, gh: number): any + local w, h = n(l.width, map.width), n(l.height, map.height) + local cells = table.create(w * h, "0") + local grid, data = list(l.grid), list(l.data) + for k = 1, w * h do + local g = grid[k] + cells[k] = if type(g) == "string" then g else tostring(math.floor(n(data[k], 0))) + end + local arrayMode = n(l.arrayMode, 0) + return obj({ + "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, + "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, + if arrayMode == 1 then "grid2D" else "grid", if arrayMode == 1 then rows2D(cells, w, h) else cells, + "arrayMode", arrayMode, + }) +end + +local function entities(l: any, i: number, gw: number, gh: number, w: number, h: number, radians: boolean): any + local out = {} + for k, o in list(l.objects) do + local ox, oy = n(o.originX, 0), n(o.originY, 0) + local nodes = nil + if tab(o.nodes) then + nodes = {} + for j, p in o.nodes do + nodes[j] = obj({ "x", n(p[1], 0), "y", n(p[2], 0) }) + end + end + local rot = n(o.rotation, 0) + table.insert(out, obj({ + "name", if type(o.class) == "string" and o.class ~= "" then o.class else (o.name or "entity"), + "id", if type(o.id) == "number" then o.id else k - 1, + "_eid", if type(o.eid) == "string" then o.eid else tostring(20000000 + k), + "x", n(o.x, 0) + ox, "y", n(o.y, 0) + oy, "width", n(o.width, gw), "height", n(o.height, gh), + "originX", ox, "originY", oy, "rotation", if radians then math.rad(rot) else rot, + "flippedX", o.flippedX, "flippedY", o.flippedY, "color", o.color, "nodes", nodes, + "values", if tab(o.properties) and next(o.properties) then values(o.properties) else nil, + })) + end + return obj({ + "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, + "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "entities", out, + }) +end + +local function decals(l: any, i: number, gw: number, gh: number, w: number, h: number, radians: boolean): any + local out = {} + for _, o in list(l.objects) do + local rot = n(o.rotation, 0) + table.insert(out, obj({ + "x", n(o.x, 0), "y", n(o.y, 0), "scaleX", n(o.scaleX, 1), "scaleY", n(o.scaleY, 1), + "rotation", if radians then math.rad(rot) else rot, "texture", o.texture or o.name or "", + "originX", n(o.originX, 0.5), "originY", n(o.originY, 0.5), + "values", if tab(o.properties) and next(o.properties) then values(o.properties) else nil, + })) + end + return obj({ + "name", l.name, "_eid", eid(l, i), "offsetX", n(l.offsetX, 0), "offsetY", n(l.offsetY, 0), "gridCellWidth", gw, + "gridCellHeight", gh, "gridCellsX", w, "gridCellsY", h, "decals", out, "folder", l.folder or "", + }) +end + +local function radiansOf(map: any): boolean + local src = if tab(map.meta) and tab(map.meta.source) then map.meta.source else {} + if type(src.anglesRadians) == "boolean" then + return src.anglesRadians + end + return true +end + +function Write.level(map: Types.TileMap): (any, string?) + local layers = {} + flat(map.layers, layers) + local radians = radiansOf(map) + local pw = n(map.pxWidth, map.width * map.tileWidth) + local ph = n(map.pxHeight, map.height * map.tileHeight) + local out = {} + for i = #layers, 1, -1 do + local l = layers[i] + local gw = n(l.cellWidth, map.tileWidth) + local gh = n(l.cellHeight, map.tileHeight) + local cw, ch = math.ceil(pw / math.max(gw, 1)), math.ceil(ph / math.max(gh, 1)) + local kind = kindOf(l) + local li + if kind == "entity" then + li = entities(l, i, gw, gh, cw, ch, radians) + elseif kind == "decal" then + li = decals(l, i, gw, gh, cw, ch, radians) + elseif kind == "grid" then + li = gridLayer(map, l, i, gw, gh) + else + li = tileLayer(map, l, i, gw, gh) + end + table.insert(out, li) + end + return obj({ + "ogmoVersion", if tab(map.meta) and tab(map.meta.source) and type(map.meta.source.version) == "string" then map.meta.source.version else VERSION, + "width", pw, "height", ph, "offsetX", n(map.offsetX, 0), "offsetY", n(map.offsetY, 0), + "values", if tab(map.properties) and next(map.properties) then values(map.properties) else nil, + "layers", out, + }), nil +end + +-- ------------------------------------------------------------------------------------------------ project +local function tileset(ts: any): any + local image = "" + if type(ts.imageData) == "buffer" then + image = Base64.dataUri(ts.imageData, "image/png") + end + return obj({ + "label", ts.name, "path", ts.imageSource or "", "image", image, "tileWidth", n(ts.tileWidth, 16), + "tileHeight", n(ts.tileHeight, 16), "tileSeparationX", n(ts.spacing, 0), "tileSeparationY", n(ts.spacingY, n(ts.spacing, 0)), + "tileMarginX", n(ts.margin, 0), "tileMarginY", n(ts.marginY, n(ts.margin, 0)), + }) +end + +local function entityTemplate(name: string, o: any, i: number): any + local w, h = math.max(1, n(o.width, 16)), math.max(1, n(o.height, 16)) + return obj({ + "exportID", tostring(30000000 + i), "name", name, "limit", -1, "size", obj({ "x", w, "y", h }), + "origin", obj({ "x", n(o.originX, 0), "y", n(o.originY, 0) }), "originAnchored", true, + "shape", obj({ "label", "Rectangle", "points", { + obj({ "x", -1, "y", -1 }), obj({ "x", 1, "y", -1 }), obj({ "x", -1, "y", 1 }), + obj({ "x", 1, "y", -1 }), obj({ "x", -1, "y", 1 }), obj({ "x", 1, "y", 1 }), + } }), + "color", if type(o.color) == "string" then o.color else "#ff0000ff", "tileX", false, "tileY", false, + "tileSize", obj({ "x", 16, "y", 16 }), "resizeableX", true, "resizeableY", true, "rotatable", true, + "rotationDegrees", 360, "canFlipX", true, "canFlipY", true, "canSetColor", false, "hasNodes", true, + "nodeLimit", 0, "nodeDisplay", 0, "nodeGhost", true, "tags", {}, "values", {}, + }) +end + +function Write.project(map: any): (any, string?) + if tab(map.ogmo) and map.meta and map.meta.project then + return map.ogmo, nil + end + local layers = {} + flat(map.layers, layers) + local defs = {} + local ents, seen = {}, {} + for i = #layers, 1, -1 do + local l = layers[i] + local kind = kindOf(l) + local gs = obj({ "x", n(l.cellWidth, map.tileWidth), "y", n(l.cellHeight, map.tileHeight) }) + local d: any + if kind == "tile" then + local ts = layerTileset(map, l) + d = obj({ "definition", "tile", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "exportMode", n(l.exportMode, 0), "arrayMode", n(l.arrayMode, 0), "defaultTileset", if ts then ts.name else "" }) + elseif kind == "grid" then + local legend = if tab(l.legend) then values(l.legend) else obj({ "0", "#00000000", "1", "#000000ff" }) + d = obj({ "definition", "grid", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "arrayMode", n(l.arrayMode, 0), "legend", legend }) + elseif kind == "decal" then + d = obj({ "definition", "decal", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "folder", l.folder or "", "includeImageSequence", true, "scaleable", true, "rotatable", true, "values", {} }) + else + d = obj({ "definition", "entity", "name", l.name, "gridSize", gs, "exportID", eid(l, i), "requiredTags", {}, "excludedTags", {} }) + for _, o in list(l.objects) do + local name = if type(o.class) == "string" and o.class ~= "" then o.class else (o.name or "entity") + if not seen[name] then + seen[name] = true + table.insert(ents, entityTemplate(name, o, #ents)) + end + end + end + table.insert(defs, d) + end + local tss = {} + for _, ts in map.tilesets do + table.insert(tss, tileset(ts)) + end + local grid = obj({ "x", map.tileWidth, "y", map.tileHeight }) + local size = obj({ "x", n(map.pxWidth, map.width * map.tileWidth), "y", n(map.pxHeight, map.height * map.tileHeight) }) + return obj({ + "name", if type(map.name) == "string" then map.name else "Project", "ogmoVersion", VERSION, "levelPaths", { "." }, + "backgroundColor", if type(map.backgroundColor) == "string" then map.backgroundColor else "#282c34ff", + "gridColor", "#3c4049cc", "anglesRadians", radiansOf(map), "directoryDepth", 5, "layerGridDefaultSize", grid, + "levelDefaultSize", size, "levelMinSize", obj({ "x", 128, "y", 128 }), "levelMaxSize", obj({ "x", 4096, "y", 4096 }), + "levelValues", {}, "defaultExportMode", ".json", "compactExport", false, "externalScript", "", "playCommand", "", + "entityTags", {}, "layers", defs, "entities", ents, "tilesets", tss, + }), nil +end + +return Write diff --git a/src/Rosetta/vector/ogmo/init.luau b/src/Rosetta/vector/ogmo/init.luau new file mode 100644 index 0000000..5355dce --- /dev/null +++ b/src/Rosetta/vector/ogmo/init.luau @@ -0,0 +1,117 @@ +--!strict +-- vector/ogmo: Ogmo Editor 3 levels (.json) and projects (.ogmo) as a TileMap, read + write (OgmoEditor3-CE 3.x +-- save format). Supports: tile layers (ids / coords, 1D / 2D arrays, tile flags), grid layers, entity layers (origin, +-- rotation, flips, nodes, values), decal layers, level values; the project through opts.project for tilesets and +-- entity templates. Not supported: loading tileset images (embedded PNGs stay bytes: tileset.imageData). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Sniff = require("@rosetta/core/Sniff") +local Types = require("@rosetta/Types") +local Json = require("@rosetta/codecs/text/Json") +local Read = require("@rosetta/vector/ogmo/Read") +local Write = require("@rosetta/vector/ogmo/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogmo = { + name = "ogmo", + category = "vector", + extensions = { "ogmo" }, + mime = { "application/x-ogmo+json" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "core/Base64", "Types", "codecs/text/Json" }, + caps = { decode = true, encode = true, projects = true, entities = true, decals = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- default 2^28 + maxCells: number?, -- per layer, default 2^26 + project: (string | buffer | { [string]: any })?, -- the .ogmo project of a level (bytes or decoded JSON) +} +export type EncodeOptions = { + kind: ("level" | "project")?, -- default: "project" for a map read from a .ogmo, else "level" + indent: number?, -- default 2; 0 = compact +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ogmo.sniff(r: Bytes.Reader): number + local h = Sniff.text(r, 2048) + if not string.match(h, "^%s*{") or not string.find(h, "\"ogmoVersion\"", 1, true) then + return 0 + end + if string.find(h, "\"layerGridDefaultSize\"", 1, true) or string.find(h, "\"levelPaths\"", 1, true) then + return 1 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function json(src: any): (any, Err.Err?) + if type(src) == "table" then + return src, nil + end + if type(src) ~= "string" and type(src) ~= "buffer" then + return nil, Err.new(Err.ARG, "project must be bytes or a table") + end + return Json.decode(src, { ordered = true }) +end + +function Ogmo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) + local o: any = opts or {} + if r.limit - r.base > (o.maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local v, jerr = Json.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), { ordered = true }) + if v == nil then + return nil, jerr + end + if type(v) ~= "table" then + return nil, Err.new(Err.CORRUPT, "not a JSON object") + end + local isProject = v.layerGridDefaultSize ~= nil or v.levelPaths ~= nil or v.tilesets ~= nil and v.layers ~= nil and v.width == nil + local project: any = nil + if not isProject and o.project ~= nil then + local p, perr = json(o.project) + if p == nil then + return nil, perr + end + project = p + end + local run: (any, any) -> (any, string?) = if isProject then Read.project else function(x: any, oo: any): (any, string?) + return Read.level(x, project, oo) + end + local ok, map, msg = pcall(run, v, o) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(map)) + end + if not map then + return nil, Err.from(msg) + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ogmo.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 kind = opts and opts.kind or (if type(map.meta) == "table" and map.meta.project then "project" else "level") + if kind ~= "level" and kind ~= "project" then + return nil, Err.new(Err.ARG, "kind must be level or project") + end + local ok, v, msg = pcall(if kind == "project" then Write.project else Write.level, map) + if not ok then + return nil, Err.new(Err.ARG, "bad map: " .. tostring(v)) + end + if v == nil then + return nil, Err.new(Err.ARG, msg or "bad map") + end + local indent = if opts and opts.indent == 0 then nil else (opts and opts.indent or 2) + local s, jerr = Json.encode(v, { indent = indent }) + if not s then + return nil, jerr + end + return buffer.fromstring(s), nil +end + +return Ogmo diff --git a/tests/fixtures/ogmo/room-001.json b/tests/fixtures/ogmo/room-001.json new file mode 100644 index 0000000..b99e25a --- /dev/null +++ b/tests/fixtures/ogmo/room-001.json @@ -0,0 +1,58 @@ +{ + "ogmoVersion": "3.3.0", + "width": 640, + "height": 480, + "offsetX": 0, + "offsetY": 0, + "layers": [ + { + "name": "entities", + "_eid": "40110095", + "offsetX": 0, + "offsetY": 0, + "gridCellWidth": 16, + "gridCellHeight": 16, + "gridCellsX": 40, + "gridCellsY": 30, + "entities": [ + {"name": "player", "id": 0, "_eid": "40117707", "x": 128, "y": 144, "originX": 0, "originY": 0}, + {"name": "coin", "id": 1, "_eid": "40304284", "x": 320, "y": 96, "originX": 0, "originY": 0}, + {"name": "coin", "id": 2, "_eid": "40304284", "x": 352, "y": 80, "originX": 0, "originY": 0}, + {"name": "coin", "id": 3, "_eid": "40304284", "x": 192, "y": 144, "originX": 0, "originY": 0}, + {"name": "coin", "id": 4, "_eid": "40304284", "x": 224, "y": 144, "originX": 0, "originY": 0}, + {"name": "coin", "id": 5, "_eid": "40304284", "x": 256, "y": 144, "originX": 0, "originY": 0}, + {"name": "coin", "id": 6, "_eid": "40304284", "x": 288, "y": 144, "originX": 0, "originY": 0}, + {"name": "coin", "id": 7, "_eid": "40304284", "x": 304, "y": 160, "originX": 0, "originY": 0}, + {"name": "coin", "id": 8, "_eid": "40304284", "x": 304, "y": 192, "originX": 0, "originY": 0}, + {"name": "coin", "id": 9, "_eid": "40304284", "x": 304, "y": 224, "originX": 0, "originY": 0}, + {"name": "coin", "id": 10, "_eid": "40304284", "x": 304, "y": 256, "originX": 0, "originY": 0}, + {"name": "coin", "id": 11, "_eid": "40304284", "x": 304, "y": 304, "originX": 0, "originY": 0}, + {"name": "coin", "id": 12, "_eid": "40304284", "x": 320, "y": 288, "originX": 0, "originY": 0}, + {"name": "coin", "id": 13, "_eid": "40304284", "x": 336, "y": 304, "originX": 0, "originY": 0}, + {"name": "coin", "id": 14, "_eid": "40304284", "x": 288, "y": 288, "originX": 0, "originY": 0}, + {"name": "coin", "id": 15, "_eid": "40304284", "x": 272, "y": 304, "originX": 0, "originY": 0}, + {"name": "coin", "id": 16, "_eid": "40304284", "x": 256, "y": 224, "originX": 0, "originY": 0}, + {"name": "coin", "id": 17, "_eid": "40304284", "x": 256, "y": 192, "originX": 0, "originY": 0}, + {"name": "coin", "id": 18, "_eid": "40304284", "x": 208, "y": 192, "originX": 0, "originY": 0}, + {"name": "coin", "id": 19, "_eid": "40304284", "x": 208, "y": 224, "originX": 0, "originY": 0}, + {"name": "enemy", "id": 20, "_eid": "40444291", "x": 304, "y": 112, "originX": 0, "originY": 0}, + {"name": "enemy", "id": 21, "_eid": "40444291", "x": 272, "y": 208, "originX": 0, "originY": 0}, + {"name": "boss", "id": 22, "_eid": "40444462", "x": 304, "y": 288, "originX": 0, "originY": 0} + ] + }, + { + "name": "walls", + "_eid": "40116503", + "offsetX": 0, + "offsetY": 0, + "gridCellWidth": 16, + "gridCellHeight": 16, + "gridCellsX": 40, + "gridCellsY": 30, + "tileset": "tiles", + "data": [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 2, 2, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 1, 1, 1, 1, 1, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], + "exportMode": 0, + "arrayMode": 0 + } + ] +} \ No newline at end of file diff --git a/tests/fixtures/ogmo/turnBasedRPG.ogmo b/tests/fixtures/ogmo/turnBasedRPG.ogmo new file mode 100644 index 0000000..ee52ccb --- /dev/null +++ b/tests/fixtures/ogmo/turnBasedRPG.ogmo @@ -0,0 +1,187 @@ +{ + "name": "HaxeFlixel Tutorial", + "ogmoVersion": "3.3.0", + "levelPaths": ["."], + "backgroundColor": "#282c34ff", + "gridColor": "#3c4049cc", + "anglesRadians": true, + "directoryDepth": 5, + "layerGridDefaultSize": {"x": 8, "y": 8}, + "levelDefaultSize": {"x": 320, "y": 240}, + "levelMinSize": {"x": 640, "y": 480}, + "levelMaxSize": {"x": 640, "y": 480}, + "levelValues": [], + "defaultExportMode": ".json", + "compactExport": false, + "externalScript": "", + "playCommand": "", + "entityTags": [], + "layers": [ + { + "definition": "entity", + "name": "entities", + "gridSize": {"x": 16, "y": 16}, + "exportID": "40110095", + "requiredTags": [], + "excludedTags": [] + }, + { + "definition": "tile", + "name": "walls", + "gridSize": {"x": 16, "y": 16}, + "exportID": "40116503", + "exportMode": 0, + "arrayMode": 0, + "defaultTileset": "tiles" + } + ], + "entities": [ + { + "exportID": "40117707", + "name": "player", + "limit": -1, + "size": {"x": 16, "y": 16}, + "origin": {"x": 0, "y": 0}, + "originAnchored": true, + "shape": { + "label": "Rectangle", + "points": [ + {"x": -1, "y": -1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": 1} + ] + }, + "color": "#ff0000ff", + "tileX": false, + "tileY": false, + "tileSize": {"x": 16, "y": 16}, + "resizeableX": false, + "resizeableY": false, + "rotatable": false, + "rotationDegrees": 360, + "canFlipX": false, + "canFlipY": false, + "canSetColor": false, + "hasNodes": false, + "nodeLimit": 0, + "nodeDisplay": 0, + "nodeGhost": true, + "tags": [], + "values": [] + }, + { + "exportID": "40304284", + "name": "coin", + "limit": -1, + "size": {"x": 16, "y": 16}, + "origin": {"x": 0, "y": 0}, + "originAnchored": true, + "shape": { + "label": "Rectangle", + "points": [ + {"x": -1, "y": -1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": 1} + ] + }, + "color": "#ffcc00ff", + "tileX": false, + "tileY": false, + "tileSize": {"x": 16, "y": 16}, + "resizeableX": false, + "resizeableY": false, + "rotatable": false, + "rotationDegrees": 360, + "canFlipX": false, + "canFlipY": false, + "canSetColor": false, + "hasNodes": false, + "nodeLimit": 0, + "nodeDisplay": 0, + "nodeGhost": true, + "tags": [], + "values": [] + }, + { + "exportID": "40444291", + "name": "enemy", + "limit": -1, + "size": {"x": 16, "y": 16}, + "origin": {"x": 0, "y": 0}, + "originAnchored": true, + "shape": { + "label": "Rectangle", + "points": [ + {"x": -1, "y": -1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": 1} + ] + }, + "color": "#0dbc0aff", + "tileX": false, + "tileY": false, + "tileSize": {"x": 16, "y": 16}, + "resizeableX": false, + "resizeableY": false, + "rotatable": false, + "rotationDegrees": 360, + "canFlipX": false, + "canFlipY": false, + "canSetColor": false, + "hasNodes": false, + "nodeLimit": 0, + "nodeDisplay": 0, + "nodeGhost": true, + "tags": [], + "values": [] + }, + { + "exportID": "40444462", + "name": "boss", + "limit": -1, + "size": {"x": 16, "y": 16}, + "origin": {"x": 0, "y": 0}, + "originAnchored": true, + "shape": { + "label": "Rectangle", + "points": [ + {"x": -1, "y": -1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": -1}, + {"x": -1, "y": 1}, + {"x": 1, "y": 1} + ] + }, + "color": "#00e3ffff", + "tileX": false, + "tileY": false, + "tileSize": {"x": 16, "y": 16}, + "resizeableX": false, + "resizeableY": false, + "rotatable": false, + "rotationDegrees": 360, + "canFlipX": false, + "canFlipY": false, + "canSetColor": false, + "hasNodes": false, + "nodeLimit": 0, + "nodeDisplay": 0, + "nodeGhost": true, + "tags": [], + "values": [] + } + ], + "tilesets": [ + {"label": "tiles", "path": "../images/tiles.png", "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAQCAYAAABQrvyxAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6ODRBQjNDODZENDhCMTFFMzk5N0RDMzAxQTc5NEM5RkMiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ODRBQjNDODdENDhCMTFFMzk5N0RDMzAxQTc5NEM5RkMiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo4NEFCM0M4NEQ0OEIxMUUzOTk3REMzMDFBNzk0QzlGQyIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo4NEFCM0M4NUQ0OEIxMUUzOTk3REMzMDFBNzk0QzlGQyIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PrOLMN8AAACUSURBVHja7JWhDoAgEEBPRrERbVYCX+If8Z8Eqo2IyYi7wOYYTncYuI3XD94bDKaUErSwWZtWY0izu3NAnc3zEhpBAVyIQvAeWuKPEEAAQ7I8IjjLswso5RHZq2iNUp7lFRoBI2AEQN+vEL5A+EM/MSvV7wm8ySNnjH0GfJGvRQhu8mWE/GPz2g/5hUVrkvw94hJgALO2Vr1s43dIAAAAAElFTkSuQmCC", "tileWidth": 16, "tileHeight": 16, "tileSeparationX": 0, "tileSeparationY": 0} + ] +} \ No newline at end of file diff --git a/tests/vector/ogmo.luau b/tests/vector/ogmo.luau new file mode 100644 index 0000000..d087a38 --- /dev/null +++ b/tests/vector/ogmo.luau @@ -0,0 +1,212 @@ +-- vector/ogmo tests: Ogmo Editor 3 levels (HaxeFlixel's TurnBasedRPG and levels made in every save layout) against a +-- Python reading of the editor's format; projects; our writer's output (level + project) read by the same Python; +-- round trips; errors; fuzz. Fixtures: tools/fixtures/ogmo.py. +local T = require("@tests/T") +local F = require("@rosetta") +local Ogmo = require("@rosetta/vector/ogmo") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/ogmo") +local Ours = require("@tests/gen/ogmo_ours") + +local t = T.suite("ogmo") + +local function decode(s: string | buffer, opts: any?): (any, any) + local b = if type(s) == "string" then buffer.fromstring(s) else s + return Ogmo.decode(Bytes.reader(b), opts) +end + +t:eq(Ogmo.name, "ogmo", "name") +t:eq(Ogmo.category, "vector", "category") +t:check(Ogmo.caps.decode and Ogmo.caps.encode, "caps") + +local function fmt(v: number): string + if v == math.floor(v) then + return string.format("%d", v) + end + return string.format("%.6g", v) +end + +local function jsonValue(v: any): string + if type(v) == "string" then + return "\"" .. v .. "\"" + elseif type(v) == "boolean" then + return tostring(v) + end + return if v == math.floor(v) then string.format("%d", v) else string.format("%.17g", v) +end + +local function valuesStr(props: any): string + local keys = {} + for k in props do + table.insert(keys, k) + end + table.sort(keys) + local out = {} + for _, k in keys do + table.insert(out, k .. "=" .. jsonValue(props[k])) + end + return table.concat(out, ",") +end + +-- our TileMap summarised like tools/fixtures/ogmo.py summarises a level +local function stats(map: any): any + local layers = {} + for _, l in map.layers do + local d: any = { name = l.name, kind = l.ogmoType } + if l.ogmoType == "entity" then + d.items = {} + for _, o in l.objects do + table.insert(d.items, string.format("%s@%s,%s %sx%s r%d n%d %s", o.class, fmt(o.x), fmt(o.y), fmt(o.width), fmt(o.height), math.floor(o.rotation + 0.5), if o.nodes then #o.nodes else 0, valuesStr(o.properties))) + end + elseif l.ogmoType == "decal" then + d.items = {} + for _, o in l.objects do + table.insert(d.items, string.format("%s@%s,%s s%s,%s r%d", o.texture, fmt(o.x), fmt(o.y), fmt(o.scaleX), fmt(o.scaleY), math.floor(o.rotation + 0.5))) + end + elseif l.ogmoType == "grid" then + d.cells = table.concat(l.grid) + else + local ts + for _, x in map.tilesets do + if x.name == l.tileset then + ts = x + end + end + local ne, ids, fl = 0, 0, 0 + for k, g in l.data do + local gid = bit32.band(g, 0x0FFFFFFF) + local id = if gid == 0 then -1 else gid - (if ts then ts.firstGid else 1) + if id >= 0 then + ne += 1 + end + ids += (id + 1) * ((k - 1) % 7 + 1) + local f = (if bit32.btest(g, 0x80000000) then 4 else 0) + (if bit32.btest(g, 0x40000000) then 2 else 0) + (if bit32.btest(g, 0x20000000) then 1 else 0) + fl += f * ((k - 1) % 5 + 1) + end + d.tileset, d.nonEmpty, d.idSum, d.flagSum = l.tileset or "", ne, ids, fl + end + table.insert(layers, d) + end + return { width = map.pxWidth, height = map.pxHeight, values = valuesStr(map.properties), layers = layers } +end + +local function diff(a: any, b: any, path: string, out: { string }) + if #out > 6 then + return + end + if type(a) == "table" and type(b) == "table" then + for k, v in a do + diff(v, b[k], path .. "." .. tostring(k), out) + end + for k, v in b do + if a[k] == nil then + diff(nil, v, path .. "." .. tostring(k), out) + end + end + elseif a ~= b then + table.insert(out, path .. ": " .. tostring(a) .. " vs " .. tostring(b)) + end +end + +local function same(got: any, want: any, label: string) + -- w / h are compared through the layer data sizes + for _, x in { got, want } do + for _, l in x.layers do + l.w, l.h = nil, nil + end + end + local out = {} + diff(got, want, "", out) + t:check(#out == 0, label .. ": " .. table.concat(out, "; ")) +end + +local samples = {} +local maps = {} +for _, c in Fx.cases do + local map, err = decode(c.data, { project = c.project }) + t:check(map, c.name .. ": decode: " .. tostring(err)) + if map then + maps[c.name] = map + same(stats(map), c.stats, c.name .. ": = the editor's layout (Python)") + local out = assert(Ogmo.encode(map)) + local back = assert(decode(out, { project = c.project })) + same(stats(back), c.stats, c.name .. ": round trip") + end + t:eq(Ogmo.sniff(Bytes.reader(buffer.fromstring(c.data))), 0.9, c.name .. ": sniff level") + table.insert(samples, c.data) +end +for _, o in Ours do + local want + for _, c in Fx.cases do + if c.name == o.name then + want = c.stats + end + end + same(o.stats, want, o.name .. ": our level + project (Python)") +end +t:eq(#Ours, #Fx.cases, "every level written") + +for _, p in Fx.projects do + local m, err = decode(p.data) + t:check(m and m.meta.project, p.name .. ": project: " .. tostring(err)) + t:eq(Ogmo.sniff(Bytes.reader(buffer.fromstring(p.data))), 1, p.name .. ": sniff project") + if m then + local back = assert(decode(assert(Ogmo.encode(m)))) + t:check(back.meta.project and #back.layers == #m.layers and #back.tilesets == #m.tilesets, p.name .. ": project round trip") + end + table.insert(samples, p.data) +end + +do + local m = maps["made/level0"] + local ents + for _, l in m.layers do + if l.ogmoType == "entity" then + ents = l + end + end + local p = ents.objects[1] + t:check(p.class == "player" and p.x == 16 and p.y == 16 and p.width == 8 and p.height == 16, "entity: origin, template size") + t:check(math.abs(p.rotation - 90) < 1e-9 and p.flippedX == true and #p.nodes == 2, "entity: radians -> degrees, flip, nodes") + t:eq(p.propertyTypes.hp, "int", "entity value types from the template") + t:eq(m.propertyTypes.gravity, "float", "level value types") + t:eq(m.layers[#m.layers].ogmoType, "entity", "Ogmo's first layer is on top") + local small = m.tilesets[2] + t:check(small.columns == 3 and small.imageWidth == 36 and type(small.imageData) == "buffer", "tileset from the embedded PNG") + local rpg = maps["turnBasedRPG/room-001"] + t:check(rpg.width == 80 and rpg.tileWidth == 8 and rpg.pxWidth == 640, "map size from the project grid") + -- without the project: tiles keep their ids + local c = Fx.cases[1] + local bare = assert(decode(c.data)) + t:check(#bare.tilesets == 0 and bare.layers[1].data ~= nil, "level without a project") +end + +-- a Tiled-style map as an Ogmo level +do + local map = Types.TileMap.new(2, 2, 16, 16) + table.insert(map.tilesets, { name = "t", firstGid = 1, tileWidth = 16, tileHeight = 16, columns = 2, count = 4 }) + table.insert(map.layers, { type = "tiles", name = "ground", width = 2, height = 2, visible = true, opacity = 1, properties = {}, data = { 1, 0, bit32.bor(4, 0x80000000), 2 } }) + table.insert(map.layers, { type = "objects", name = "things", visible = true, opacity = 1, properties = {}, objects = { { class = "coin", x = 4, y = 6, width = 8, height = 8, properties = { value = 10 } } } }) + local out = assert(F.save(map, nil, { format = "ogmo" })) + local back = assert(decode(out, { project = assert(Ogmo.encode(map, { kind = "project" })) })) + t:eq(back.layers[1].data[3], bit32.bor(4, 0x80000000), "tile + flip") + t:check(back.layers[2].objects[1].properties.value == 10 and back.layers[2].objects[1].x == 4, "object") +end + +do + local _, e = decode("{\"ogmoVersion\": \"3.4.0\"}") + t:check(e and e.code == Err.CORRUPT, "no layers") + local _, e2 = decode("[1]") + t:check(e2 and e2.code == Err.CORRUPT, "not an object") + local _, e3 = Ogmo.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "encode arg") + local _, e4 = Ogmo.encode(maps["made/level0"], { kind = "x" :: any }) + t:check(e4 and e4.code == Err.ARG, "bad kind") +end + +t:fuzz("decode", function(b: buffer) + return decode(b, { project = Fx.projects[2].data }) +end, samples, { mutations = 60, garbage = 20 }) +t:done() diff --git a/tools/fixtures/_ogmo_encode.luau b/tools/fixtures/_ogmo_encode.luau new file mode 100644 index 0000000..ab33be7 --- /dev/null +++ b/tools/fixtures/_ogmo_encode.luau @@ -0,0 +1,28 @@ +-- tools/fixtures/_ogmo_encode: run by tools/fixtures/ogmo.py (luau CLI, repo root): decodes every Ogmo level with its +-- project and writes the level and a project made from the map with our encoder, printing ".json\t" and +-- ".ogmo\t" lines for Python to read. +local Ogmo = require("@rosetta/vector/ogmo") +local Bytes = require("@rosetta/core/Bytes") +local Fx = require("@tests/gen/ogmo") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + return (string.gsub(s, ".", function(c: string): string + return HEX[string.byte(c)] + end)) +end + +for _, c in Fx.cases do + local map = Ogmo.decode(Bytes.reader(buffer.fromstring(c.data)), { project = c.project }) + if map then + local lv = Ogmo.encode(map) + local pj = Ogmo.encode(map, { kind = "project" }) + if lv and pj then + print(c.name .. ".json\t" .. hex(buffer.tostring(lv))) + print(c.name .. ".ogmo\t" .. hex(buffer.tostring(pj))) + end + end +end diff --git a/tools/fixtures/docs_engines.py b/tools/fixtures/docs_engines.py index ad8ae97..9ea2794 100644 --- a/tools/fixtures/docs_engines.py +++ b/tools/fixtures/docs_engines.py @@ -1,9 +1,10 @@ # Docs inputs for the engine / level-editor sections of the scene, tile map, archive and data pages (tools/fixtures.py, -# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py, LDtk's AutoLayers_2_stamps sample (tools/fixtures/ldtk.py). +# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py, LDtk's AutoLayers_2_stamps sample (tools/fixtures/ldtk.py), +# HaxeFlixel's TurnBasedRPG Ogmo project and level (tests/fixtures/ogmo). # tests/gen/docs_engines.luau { files = { [name] = bytes }, vars = { aseText = "hand.ase", ... } } import importlib.util, os -INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py"] +INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py", "tests/fixtures/ogmo"] def mod(ctx, name): @@ -17,5 +18,7 @@ def generate(ctx): check = mod(ctx, "../docs_check") files = {"hand.ase": mod(ctx, "ase").HAND.encode()} files["stamps.ldtk"] = open(os.path.join(mod(ctx, "ldtk").samples_dir(ctx), "AutoLayers_2_stamps.ldtk"), "rb").read() - vars = {"aseText": "hand.ase", "ldtkText": "stamps.ldtk"} + for f in ("turnBasedRPG.ogmo", "room-001.json"): + files[f] = ctx.read("tests/fixtures/ogmo/" + f) + vars = {"aseText": "hand.ase", "ldtkText": "stamps.ldtk", "ogmoProjectText": "turnBasedRPG.ogmo", "ogmoLevelText": "room-001.json"} check.emit_inputs(ctx, files, vars) diff --git a/tools/fixtures/ogmo.py b/tools/fixtures/ogmo.py new file mode 100644 index 0000000..aeaa09f --- /dev/null +++ b/tools/fixtures/ogmo.py @@ -0,0 +1,165 @@ +# 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)