Files
rosetta/docs/guide/tilemap.md
T

11 KiB

Tile maps (Tiled TMX / TMJ)

Tiled maps load as a TileMap: the map grid, its tilesets, and a list of layers (tile layers, object layers, image layers and groups) with Tiled's custom properties. The XML flavour (TMX) and the JSON flavour (TMJ) decode to the same value, so converting between them is a load and a save. Standalone tileset files (TSX / TSJ) load too.

local map = assert(F.load(tmxText))
print(map.width, map.height, map.tileWidth, map.tileHeight)   -- 4 3 16 16
local ground = map.layers[1]
local gid = ground.data[1 + 0 * map.width + 2]          -- the tile at column 2, row 0
assert(gid == 2)
local json = assert(F.saveString(map, { format = "tmj" }))
assert(F.detect(json, { name = "level.tmj" }) == "tiled")

The type

TileMap

Field Type Meaning
kind "tilemap"
width, height number the map size in tiles (for infinite maps: the bounds Tiled stored)
tileWidth, tileHeight number the grid cell size in pixels
orientation string "orthogonal", "isometric", "staggered", "hexagonal"
renderOrder string "right-down", "right-up", "left-down", "left-up"
infinite boolean tile layers use chunks instead of data
tilesets { Tileset } sorted by firstGid
layers { TileLayer } in Tiled's order: the first is drawn first (at the bottom)
properties { [name]: value } custom properties (below)
propertyTypes { [name]: type }? the Tiled type of each non-string property
meta table source.format ("tmx" or "tmj"), tileset = true for a TSX / TSJ file

Other Tiled map attributes keep their Tiled names in camel case: version, tiledVersion, class, nextLayerId, nextObjectId, backgroundColor, parallaxOriginX / Y, hexSideLength, staggerAxis, staggerIndex.

Tileset

Field Type Meaning
firstGid number the gid of the tileset's tile 0
name, class string
tileWidth, tileHeight number pixels
columns, count number tiles per row of the image, total tiles
spacing, margin number pixels between tiles / around the image
imageSource string? the tileset image's path as written in the file (relative to the map)
imageWidth, imageHeight number?
image Image? never set by the decoder: load the image yourself (below)
source string? an external tileset (.tsx / .tsj): only firstGid and source are known
tiles { { id, class, properties, imageSource?, animation?, objectGroup? } } per-tile data; id is 0-based within the tileset; animation = { { tileId, duration } } with durations in milliseconds
tileOffset, objectAlignment, transparentColor, properties as in Tiled

TileLayer (every layer)

Field Type Meaning
type string "tiles", "objects", "image" or "group"
id, name, class
visible, locked boolean
opacity number 0..1
offsetX, offsetY, parallaxX, parallaxY, tintColor as in Tiled (pixels, factors, "#rrggbb" / "#aarrggbb")
properties, propertyTypes custom properties

By type:

Type Fields
"tiles" width, height (tiles); data = width * height gids, row by row from the top-left (data[1 + x + y * width], x and y 0-based); or chunks = { { x, y, width, height, data } } on infinite maps (x, y in tiles, may be negative); encoding / compression as stored
"objects" objects, drawOrder ("topdown" / "index"), color
"image" imageSource, imageWidth, imageHeight, repeatX, repeatY, transparentColor
"group" layers (the child layers)

An object: id, name, class, x, y, width, height (pixels), rotation (degrees clockwise), visible, shape ("rectangle", "ellipse", "point", "polygon", "polyline", "text"), points ({ { x, y } }, relative to the object, for polygons and polylines), text ({ text, fontFamily, pixelSize, color, ... }), gid (tile objects), template, properties.

Custom properties are plain values: strings, numbers (int, float), booleans, colours as "#aarrggbb" strings, files as path strings, objects as object ids, and class properties as { class, properties, propertyTypes }. propertyTypes remembers the Tiled type of each non-string property, so a save writes the same types back.

local map = assert(F.load(tmxText))
assert(map.properties.music == "cave.ogg" and map.properties.gravity == 9.8)
assert(map.propertyTypes.gravity == "float")
local ts = map.tilesets[1]
assert(ts.firstGid == 1 and ts.columns == 4 and ts.imageSource == "tiles.png")
local things = map.layers[2]
assert(things.type == "objects")
local spawn = things.objects[1]
assert(spawn.shape == "point" and spawn.class == "Spawn" and spawn.x == 24 and spawn.y == 16)

Gids and flip flags

A gid (global tile id) of 0 is an empty cell. Otherwise the low 28 bits name a tile across all tilesets: the tile belongs to the tileset with the largest firstGid not above it, and its index there is gid - firstGid. The top bits are flags, kept as they are in data:

Bit Value Meaning
31 0x80000000 flipped horizontally
30 0x40000000 flipped vertically
29 0x20000000 flipped diagonally (with the other two: rotations)
28 0x10000000 rotated 120 degrees (hexagonal maps)
local map = assert(F.load(tmjText))
local raw = map.layers[1].data[4]                      -- 2147483652 = 0x80000004
local FLAGS = 0xF0000000
local gid = bit32.band(raw, bit32.bnot(FLAGS))
local flipH = bit32.btest(raw, 0x80000000)
assert(gid == 4 and flipH)

-- the tileset and the tile's pixel rectangle in the tileset image
local function lookup(m, g)
	local found = nil
	for _, t in m.tilesets do
		if t.firstGid <= g then
			found = t
		end
	end
	local index = g - found.firstGid
	local col, row = index % found.columns, index // found.columns
	return found, (found.margin or 0) + col * (found.tileWidth + (found.spacing or 0)),
		(found.margin or 0) + row * (found.tileHeight + (found.spacing or 0))
end
local ts, sx, sy = lookup(map, gid)
assert(ts.name == "t" and sx == 8 and sy == 8)        -- tile 3 of a 2-column tileset

Tileset images

Tilesets keep their image as a path (imageSource), relative to the map file: a map format never decodes images. Read the image yourself and attach it:

local mapPath = "assets/level.tmx"
local map = assert(F.load(mapPath))
local dir = string.match(mapPath, "^(.*/)") or ""
for _, ts in map.tilesets do
	if ts.imageSource and F.host.exists(dir .. ts.imageSource) then
		ts.image = assert(F.image.load(dir .. ts.imageSource))
	end
end
assert(map.tilesets[1].image.width == 64)

On Roblox and in the luau CLI, fetch the bytes your own way and call F.image.load(bytes). External tilesets (ts.source) work the same way: F.load(dir .. ts.source) gives a TileMap with meta.tileset = true and the tileset in tilesets[1].

Load and save

F.load detects TMX (<map) and TMJ (a JSON object with "type": "map" or Tiled's keys). JSON without those keys is plain data; pass { format = "tiled" } or a .tmj name to force it. Option: maxBytes (default 256 MB).

F.save writes the source's flavour unless opts.format says otherwise:

Option Meaning
format "tmx" / "tsx" (XML) or "tmj" / "tsj" / "json" (JSON)
encoding tile data: "csv" (TMX default), "base64", "xml" (TMX only); TMJ writes arrays unless "base64"
compression for base64 data: nil, "zlib" or "gzip"
level deflate level for compressed data (default 6)
indent spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON)
local map = assert(F.load(tmxText))
local tmj = assert(F.saveString(map, { format = "tmj", indent = 0 }))
local back = assert(F.load(tmj, { format = "tiled" }))
assert(back.layers[1].data[12] == 6 and back.properties.gravity == 9.8)

local packed = assert(F.saveString(map, { encoding = "base64", compression = "zlib" }))
assert(string.find(packed, 'compression="zlib"', 1, true))

Build a map from scratch with F.Types.TileMap.new(width, height, tileWidth, tileHeight):

local map = F.Types.TileMap.new(3, 2, 16, 16)
table.insert(map.tilesets, { name = "terrain", firstGid = 1, tileWidth = 16, tileHeight = 16, columns = 8,
	count = 64, imageSource = "terrain.png", imageWidth = 128, imageHeight = 128 })
table.insert(map.layers, { type = "tiles", name = "floor", width = 3, height = 2, visible = true, opacity = 1,
	properties = {}, data = { 1, 1, 2, 0, 9, bit32.bor(9, 0x80000000) } })
local tmx = assert(F.saveString(map, { format = "tmx" }))
local back = assert(F.load(tmx))
assert(back.layers[1].data[6] == 0x80000009)

Wolfenstein 3D maps

Wolfenstein 3D / Spear of Destiny maps are two files: GAMEMAPS.WL6 (the Carmack + RLEW compressed planes) and MAPHEAD.WL6 (the RLEW tag and where each map starts). Load either one: the other comes through files / resolve (loading a path finds it next to the file) or mapHead / gameMaps. A map loads as a TileMap with one tile layer per plane (walls, objects, plane3) holding the raw tile values (1..63 walls, 90..101 doors, 106+ floor areas; things in objects), without a tileset; map picks the slot (default: the first present) and F.format("gamemaps").maps lists them.

local files = { ["MAPHEAD.WL6"] = mapheadBytes }
local level = assert(F.load(gamemapsBytes, { name = "GAMEMAPS.WL6", files = files }))
assert(level.kind == "tilemap" and level.width == 16 and level.properties.name == "Tiny map")
assert(level.layers[1].name == "walls" and level.layers[1].data[1] == 1)   -- the border wall
local maps = assert(F.format("gamemaps").maps(F.Bytes.reader(mapheadBytes), { gameMaps = gamemapsBytes }))
assert(#maps == 1 and maps[1].slot == 1)

Formats

Format Read Write Notes
TMX / TSX yes yes CSV, base64 (raw, zlib, gzip) and <tile> data; zstd data returns UNSUPPORTED
TMJ / TSJ yes yes
Wolfenstein 3D GAMEMAPS + MAPHEAD yes the gamemaps format: raw tile values, no tileset

TMX and TMJ are the tiled format in FORMATS.md. Wang sets and terrains are dropped.

Gotchas

  • data is 1-based in Luau but cells are 0-based: cell (x, y) is data[1 + x + y * width].
  • Always mask the flag bits before looking a gid up; a flipped tile's raw gid is over 2^31.
  • Infinite maps have no data on their tile layers, only chunks.
  • Object y is the bottom-left corner for tile objects (gid set) and the top-left for everything else (Tiled's convention).
  • Tile animation durations are milliseconds (Tiled's unit), unlike the seconds used elsewhere in the library.
  • Colours are strings ("#rrggbb" or "#aarrggbb"), not tables.