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)

This commit is contained in:
4DBug committed 2026-11-01 19:00:07 -06:00
1 parent 1f74419ccf
commit 9c02ebdee5
15 files changed
+1596 -4

No files matched your search

+12
View File
@@ -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",
+403
View File
@@ -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
+352
View File
@@ -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
+117
View File
@@ -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