TableTower/io/json_canon.gd

208 lines
7.4 KiB
GDScript3
Raw Normal View History

class_name JsonCanon
extends RefCounted
## Collection normaliser behind JsonIO.canonical() (format version 2).
## Normalizes a collection to format version 2: legacy keys are converted
## (`die` -> `dice`, `triggers` -> `pipes`, `collection` -> `name`), missing
## optional keys are tolerated and unknown keys are dropped.
static func canonical(src: Dictionary) -> Dictionary:
var tables: Array = []
var src_tables: Variant = src.get("tables", [])
if src_tables is Array:
for t in src_tables:
if t is Dictionary:
tables.append(_canon_table(t))
var cname := str(src.get("name", src.get("collection", "")))
var out := {"format_version": JsonIO.FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
var groups: Array = []
var src_groups: Variant = src.get("groups", [])
if src_groups is Array:
for g in src_groups:
if g is Dictionary:
groups.append(_canon_group(g))
if not groups.is_empty():
out["groups"] = groups
# The Book and pictures (2026-11-10): taken as they are; TowerBoard checks them.
if src.get("book") is Array:
out["book"] = (src["book"] as Array).filter(func(v: Variant) -> bool: return v is Dictionary)
if src.get("images") is Dictionary:
var pics := {}
for k: Variant in src["images"]:
if src["images"][k] is String:
pics[str(k)] = src["images"][k]
out["images"] = pics
return out
## Copies the keys that are present and not empty (newer optional keys that
## need no conversion).
static func _keep(src: Dictionary, dst: Dictionary, keys: Array) -> void:
for k: String in keys:
var v: Variant = src.get(k)
if v != null and not (v is String and (v as String).strip_edges() == "") and not (v is bool and not v):
dst[k] = v
static func _canon_group(gd: Dictionary) -> Dictionary:
var g := {
"id": str(gd.get("id", "")),
"name": str(gd.get("name", "")),
"x": int(JsonIO._num(gd.get("x", 0), 0)),
"y": int(JsonIO._num(gd.get("y", 0), 0)),
"w": int(JsonIO._num(gd.get("w", 320), 320)),
"h": int(JsonIO._num(gd.get("h", 200), 200)),
}
if bool(gd.get("collapsed", false)):
g["collapsed"] = true
var details := str(gd.get("details", ""))
if details != "":
g["details"] = details
var members: Array = []
var src: Variant = gd.get("members", [])
if src is Array:
for m in src:
if str(m) != "" and not members.has(str(m)):
members.append(str(m))
g["members"] = members
_keep(gd, g, ["parent", "color"])
return g
static func _canon_table(td: Dictionary) -> Dictionary:
var t := {
"id": str(td.get("id", "")),
"name": str(td.get("name", "")),
"x": int(JsonIO._num(td.get("x", 0), 0)),
"y": int(JsonIO._num(td.get("y", 0), 0)),
}
if bool(td.get("collapsed", false)):
t["collapsed"] = true
var details := str(td.get("details", ""))
if details != "":
t["details"] = details
var tags: Array = []
var src_tags: Variant = td.get("tags", [])
if src_tags is Array:
for tag in src_tags:
tags.append(str(tag))
if not tags.is_empty():
t["tags"] = tags
var dice := str(td.get("dice", "")).strip_edges()
if dice == "" and td.has("die"):
var die: Variant = JsonIO._num(td["die"], 0)
if (die is int or die is float) and die > 0:
dice = "1d%d" % int(die)
if dice != "":
t["dice"] = dice
for key in ["card_mode", "deck_empty"]:
var v: Variant = td.get(key)
if v != null and not (v is bool and not v) and not (v is String and v == ""):
t[key] = v
# Logic cards (docs/LOGIC.md §9). Defaults are left out.
var kind := str(td.get("kind", "roll"))
if RollTable.KINDS.has(kind) and kind != "roll":
t["kind"] = kind
var defaults := {"dice_mod": "", "choice": "pick", "prompt": "", "save_as": "", "options_from": "", "options_where": "", "min": "0", "max": "99",
"loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": "",
"check_dice": RollTable.CHECK_DEFAULT_DICE, "check_mod": "", "check_cmp": "ge", "check_target": RollTable.CHECK_DEFAULT_TARGET}
for key: String in defaults:
if not td.has(key) or td[key] == null:
continue
var s := RollTable.expr_text(td[key], str(defaults[key]))
if s != str(defaults[key]):
t[key] = s
var inputs := RollTable.clean_inputs(td.get("inputs", []))
if not inputs.is_empty():
var list: Array = []
for inp: Dictionary in inputs:
var o := {"name": inp["name"]}
if str(inp["label"]) != "":
o["label"] = inp["label"]
if str(inp["default"]) != "":
o["default"] = inp["default"]
list.append(o)
t["inputs"] = list
var entries: Array = []
var src_entries: Variant = td.get("entries", [])
if src_entries is Array:
for e in src_entries:
entries.append(_canon_entry(e))
t["entries"] = entries
_keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps", "members", "repeats"])
# A separator may be just a space, so it isn't trimmed.
if td.get("column_join") is String and td["column_join"] != "":
t["column_join"] = td["column_join"]
return t
static func _canon_entry(ev: Variant) -> Dictionary:
if ev is String:
return {"id": "", "text": ev}
var ed: Dictionary = ev
var e := {"id": str(ed.get("id", "")), "text": str(ed.get("text", ""))}
var details := str(ed.get("details", ""))
if details != "":
e["details"] = details
var w: Variant = JsonIO._num(ed.get("weight", 1), 1)
if (w is int or w is float) and w != 1:
e["weight"] = w
var r: Variant = ed.get("range")
if r is Array and (r as Array).size() == 2:
e["range"] = [int(JsonIO._num(r[0], 0)), int(JsonIO._num(r[1], 0))]
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
if effects.strip_edges() != "":
e["effects"] = effects
var when := str(ed.get("when", "")).strip_edges() if ed.get("when") != null else ""
if when != "":
e["when"] = when
var show_if := str(ed.get("show_if", "")).strip_edges() if ed.get("show_if") != null else ""
if show_if != "":
e["show_if"] = show_if
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
var pipes: Array = []
if src_pipes is Array:
for p in src_pipes:
if p is String and p != "":
pipes.append(p)
elif p is Dictionary and str(p.get("table", "")) != "":
var np := {"table": str(p["table"])}
if p.has("count"):
var cnt: Variant = JsonIO._num(p["count"], null)
if cnt == null and p["count"] is String and (p["count"] as String).strip_edges() != "":
np["count"] = (p["count"] as String).strip_edges() # an expression
else:
np["count"] = int(cnt if cnt != null else 1)
if str(p.get("save_as", "")) != "":
np["save_as"] = str(p["save_as"])
var pw := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
if pw != "":
np["when"] = pw
elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)):
np["otherwise"] = true
var wv := _canon_with(p.get("with"))
if not wv.is_empty():
np["with"] = wv
_keep(p, np, ["color", "combine", "pause", "dice", "reroll", "distinct"])
pipes.append(np)
if not pipes.is_empty():
e["pipes"] = pipes
_keep(ed, e, ["page", "image", "cells", "repeat"])
if ed.get("cost") is Dictionary:
e["cost"] = ed["cost"]
return e
## A pipe's "with" object: {input name: expression text}, names trimmed (a
## leading "@" dropped), numbers as text, empty names and values left out.
static func _canon_with(v: Variant) -> Dictionary:
var out := {}
if not (v is Dictionary):
return out
for k: Variant in v:
var nm := str(k).strip_edges().trim_prefix("@")
var ex := RollTable.expr_text(v[k], "").strip_edges()
if nm != "" and ex != "":
out[nm] = ex
return out