TableTower/io/json_io.gd
RobinFiredrake 6f583ea4f5 Plain Build engine: Describe, Builder, checks, inputs, collections, why trace
Implements docs/PLAIN.md sections 1-5 (the engine half of the usability pass):

- core/describe.gd (Describe): rules in plain words, labelled from variable
  cards, collections and card inputs, falling back to the original text.
- core/builder.gd (Builder): effect and condition models that round-trip
  with the rule text, a rule tokenizer, and known_values(board).
- Collections: variable cards with var_type "collection" label their
  members and don't declare their stem.
- Check cards (kind "check"): dice + modifier vs target, Success/Failure,
  chain values nat/total/effect, node "check" info, lint and static checks.
- Card inputs and pipe "with" values, scoped over the pipe's subtree on the
  explicit work stack (OP_RESTORE frames), with defaults and snapshot
  evaluation.
- nat on every roll-table roll; dice faces recorded through ctx.faces.
- Why trace: facts on nodes and steps (input, roll, check, case, show_if,
  options_where, effect, when, otherwise).
- StateStore rules_view setting; JSON for the new keys; LOGIC.md and
  PLAIN.md updated (deviations in PLAIN.md 5a).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:01:24 -06:00

587 lines
21 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name JsonIO
extends RefCounted
## JSON import and export of a collection, plus the shared helpers every other
## exporter uses. Everything works on plain collection Dictionaries (the JSON
## form), never on the model classes.
##
## Canonical collection form:
## {"format_version": 2, "id", "name", "tables": [table, ...], ["groups": [group, ...]]}
## group: id, name, x, y, w, h, [collapsed], [details], members (table ids)
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from],
## [options_where], [min], [max],
## [loop], [loop_expr], [var_name], [var_type], [initial],
## [check_dice], [check_mod], [check_cmp], [check_target],
## [inputs: [{name, [label], [default]}, ...]], entries
## entry: id, text, [details], [weight], [range], [effects], [when], [show_if],
## [pipes]
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
## "save_as": name, "when": "<expression>", "otherwise": true,
## "with": {input name: "<expression>"}}
## ("otherwise" is dropped when the pipe has a "when")
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
## they have their default value.
const FORMAT_VERSION := 2
const _DICE_RE := "^\\s*(\\d+)\\s*[dD]\\s*(\\d+)\\s*$"
const _BBCODE_RE := "(?<!\\[)\\[/?[A-Za-z_]+(?:[= ][^\\]\\[]*)?\\](?!\\])"
const _REF_RE := "\\[\\[(.+?)\\]\\]"
# ---------------------------------------------------------------- export
## Pretty JSON text for a collection. Only known keys are written, so local
## state (card draws, variables, history) can never leak into an export.
static func export_json(collection: Dictionary) -> String:
return JSON.stringify(canonical(collection), " ", false)
## Returns {"ok": bool, "collection": Dictionary, "errors": Array[String],
## "warnings": Array[String]}. `sanitize` is called with every user-visible
## string (names, details, tags, entry text, variable names) and must return
## the cleaned string. The default leaves strings unchanged.
static func import_json(text: String, sanitize: Callable = Callable()) -> Dictionary:
var json := JSON.new()
var errors: Array[String] = []
var warnings: Array[String] = []
if json.parse(text) != OK:
errors.append("Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()])
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
if not (json.data is Dictionary):
errors.append("The file is not a collection (expected a JSON object).")
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
return import_dict(json.data, sanitize)
## Validates and cleans an already-parsed collection (used by every importer).
## Gives tables and entries fresh ids where they are missing or collide, and
## keeps pipes pointing at the right tables. Same result shape as import_json.
static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Dictionary:
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
var fv: Variant = _num(data.get("format_version", 1), 1)
if (fv is int or fv is float) and fv > FORMAT_VERSION:
errors.append("format_version %s is newer than this version supports (%d)." % [str(fv), FORMAT_VERSION])
if not (data.get("tables") is Array):
errors.append("The collection has no \"tables\" list.")
return result
var raw_tables: Array = data["tables"]
for ti in raw_tables.size():
var rt: Variant = raw_tables[ti]
if not (rt is Dictionary):
errors.append("Table #%d is not an object." % (ti + 1))
continue
var re_list: Variant = rt.get("entries", [])
if not (re_list is Array):
errors.append("Table #%d: \"entries\" is not a list." % (ti + 1))
continue
for ei in (re_list as Array).size():
var re: Variant = re_list[ei]
if not (re is Dictionary or re is String):
errors.append("Table #%d, entry #%d is not an object or text." % [ti + 1, ei + 1])
if not errors.is_empty():
return result
var c := canonical(data)
var clean := func(s: String) -> String:
if sanitize.is_null():
return s
return str(sanitize.call(s))
c["name"] = clean.call(str(c["name"]))
if str(c["name"]) == "":
c["name"] = "Untitled collection"
warnings.append("The collection had no name; called it \"Untitled collection\".")
if str(c["id"]) == "":
c["id"] = slug(str(c["name"]), "collection")
var tables: Array = c["tables"]
# Reserve the first occurrence of every given table id, then hand out new ones.
var used := {}
var id_map := {} # original id -> final id
var needs_id: Array[int] = []
for i in tables.size():
var t: Dictionary = tables[i]
var tid: String = t["id"]
if tid != "" and not used.has(tid):
used[tid] = true
id_map[tid] = tid
else:
needs_id.append(i)
for i in needs_id:
var t2: Dictionary = tables[i]
var old: String = t2["id"]
var fresh := unique_id(slug(str(t2["name"]), "table"), used)
if old != "":
warnings.append("Table id \"%s\" was used twice; \"%s\" is now \"%s\"." % [old, str(t2["name"]), fresh])
t2["id"] = fresh
var by_name := {}
for t3 in tables:
var key := str(t3["name"]).to_lower()
if not by_name.has(key):
by_name[key] = t3["id"]
for t4 in tables:
var t5: Dictionary = t4
t5["name"] = clean.call(str(t5["name"]))
if t5.has("details"):
t5["details"] = clean.call(str(t5["details"]))
for key in ["prompt", "initial"]:
if t5.has(key):
t5[key] = clean.call(str(t5[key]))
if t5.has("inputs"):
for inp: Dictionary in t5["inputs"]:
for key in ["name", "label", "default"]:
if inp.has(key):
inp[key] = clean.call(str(inp[key]))
if t5.has("tags"):
var tags: Array = []
for tag in t5["tags"]:
tags.append(clean.call(str(tag)))
t5["tags"] = tags
var elist: Array = t5["entries"]
# Entry ids only need to be unique within their table.
var seen := {}
var redo: Array[Dictionary] = []
for e in elist:
var eid: String = e["id"]
if eid == "" or seen.has(eid):
redo.append(e)
else:
seen[eid] = true
var enext := 1
for e1 in redo:
while seen.has("e%d" % enext):
enext += 1
e1["id"] = "e%d" % enext
seen[e1["id"]] = true
for e2 in elist:
var ed: Dictionary = e2
ed["text"] = clean.call(str(ed["text"]))
if ed.has("details"):
ed["details"] = clean.call(str(ed["details"]))
if ed.has("effects"):
ed["effects"] = clean.call(str(ed["effects"]))
if ed.has("when"):
ed["when"] = clean.call(str(ed["when"]))
if ed.has("show_if"):
ed["show_if"] = clean.call(str(ed["show_if"]))
if ed.has("range"):
var r: Array = ed["range"]
if int(r[0]) > int(r[1]):
warnings.append("\"%s\": range %d-%d is backwards; dropped." % [str(ed["text"]), int(r[0]), int(r[1])])
ed.erase("range")
if ed.has("pipes"):
var pipes: Array = []
for p in ed["pipes"]:
var info := pipe_info(p)
var target: String = info["table"]
if id_map.has(target):
target = id_map[target]
elif by_name.has(target.to_lower()):
target = by_name[target.to_lower()]
else:
warnings.append("\"%s\" pipes to unknown table \"%s\"." % [str(ed["text"]), target])
if p is Dictionary:
var np: Dictionary = (p as Dictionary).duplicate()
np["table"] = target
if np.has("save_as"):
np["save_as"] = clean.call(str(np["save_as"]))
if np.has("when"):
np["when"] = clean.call(str(np["when"]))
if np.get("with") is Dictionary:
var wd := {}
for k: String in np["with"]:
wd[clean.call(k)] = clean.call(str(np["with"][k]))
np["with"] = wd
pipes.append(np)
else:
pipes.append(target)
ed["pipes"] = pipes
_import_groups(c, id_map, by_name, clean, warnings)
result["ok"] = true
result["collection"] = c
return result
## Groups on import: members follow renamed table ids (or match a table by
## name); unknown members are dropped, a table stays in its first group only,
## and group ids are made unique.
static func _import_groups(c: Dictionary, id_map: Dictionary, by_name: Dictionary, clean: Callable, warnings: Array[String]) -> void:
if not c.has("groups"):
return
var taken := {}
var gids := {}
for g: Dictionary in c["groups"]:
g["name"] = clean.call(str(g["name"]))
if g.has("details"):
g["details"] = clean.call(str(g["details"]))
var gid := str(g["id"])
if gid == "" or gids.has(gid):
gid = unique_id(slug(str(g["name"]), "group"), gids)
g["id"] = gid
else:
gids[gid] = true
var keep: Array = []
for m: String in g["members"]:
var target := ""
if id_map.has(m):
target = id_map[m]
elif by_name.has(m.to_lower()):
target = by_name[m.to_lower()]
if target == "":
warnings.append("Group \"%s\" lists unknown table \"%s\"; left out." % [str(g["name"]), m])
elif taken.has(target):
warnings.append("\"%s\" was in more than one group; kept in the first." % m)
else:
taken[target] = true
keep.append(target)
g["members"] = keep
# ------------------------------------------------------------ canonical
## 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": 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
return out
static func _canon_group(gd: Dictionary) -> Dictionary:
var g := {
"id": str(gd.get("id", "")),
"name": str(gd.get("name", "")),
"x": int(_num(gd.get("x", 0), 0)),
"y": int(_num(gd.get("y", 0), 0)),
"w": int(_num(gd.get("w", 320), 320)),
"h": int(_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
return g
static func _canon_table(td: Dictionary) -> Dictionary:
var t := {
"id": str(td.get("id", "")),
"name": str(td.get("name", "")),
"x": int(_num(td.get("x", 0), 0)),
"y": int(_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 = _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 := {"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
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 = _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(_num(r[0], 0)), int(_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 = _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
pipes.append(np)
if not pipes.is_empty():
e["pipes"] = pipes
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
# -------------------------------------------------------------- helpers
## Turns whole floats (as JSON parsing gives) into ints; returns `fallback`
## for anything that isn't a number.
static func _num(v: Variant, fallback: Variant) -> Variant:
if v is int:
return v
if v is float:
return int(v) if is_equal_approx(v, roundf(v)) else v
if v is String and (v as String).is_valid_float():
return _num((v as String).to_float(), fallback)
return fallback
## Lower-case identifier text: "Melee Weapons" -> "melee_weapons".
static func slug(text: String, fallback: String = "item") -> String:
var re := RegEx.create_from_string("[^a-z0-9]+")
var s := re.sub(text.to_lower(), "_", true)
s = s.trim_prefix("_").trim_suffix("_")
return s if s != "" else fallback
## `base`, or `base_2`, `base_3`... whichever isn't in `used`; marks it used.
static func unique_id(base: String, used: Dictionary) -> String:
var id := base
var n := 2
while used.has(id):
id = "%s_%d" % [base, n]
n += 1
used[id] = true
return id
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
## "count_expr", "when", "otherwise", "with"} ("with": {name: expression},
## {} for none). An expression count ("@terms") reads as
## count 1, with the expression in "count_expr" ("" otherwise). "when" is the
## pipe's condition ("" for none); "otherwise" is true only without one.
static func pipe_info(p: Variant) -> Dictionary:
if p is Dictionary:
var c: Variant = p.get("count", 1)
var expr := ""
if c is String and _num(c, null) == null and (c as String).strip_edges() != "":
expr = (c as String).strip_edges()
var w := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr,
"when": w, "otherwise": w == "" and p.get("otherwise", false) is bool and bool(p.get("otherwise", false)),
"with": _canon_with(p.get("with"))}
return {"table": str(p), "count": 1, "save_as": "", "count_expr": "", "when": "", "otherwise": false, "with": {}}
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
## ("×@terms" for an expression count), led by "if <condition>" or
## "otherwise" on a conditional pipe ("if @str >= 8 ×2").
static func pipe_label(info: Dictionary) -> String:
var parts: Array[String] = []
if str(info.get("when", "")) != "":
parts.append("if " + str(info["when"]))
elif bool(info.get("otherwise", false)):
parts.append("otherwise")
if str(info.get("count_expr", "")) != "":
parts.append("×" + str(info["count_expr"]))
elif int(info["count"]) != 1:
parts.append("×%d" % int(info["count"]))
if str(info["save_as"]) != "":
parts.append("→ " + str(info["save_as"]))
var wv: Dictionary = info.get("with", {})
for k: String in wv:
parts.append("%s=%s" % [k, wv[k]])
return " ".join(parts)
## Removes BBCode tags such as [b] or [color=red]. `[[Table]]` references stay.
static func strip_bbcode(text: String) -> String:
return RegEx.create_from_string(_BBCODE_RE).sub(text, "", true)
## Inline references in entry text: Array of {"name", "var"}.
static func find_refs(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for m in RegEx.create_from_string(_REF_RE).search_all(text):
var inner := m.get_string(1)
var parts := inner.split("->", true, 1)
var ref_name := parts[0].strip_edges()
if ref_name == "":
continue
out.append({"name": ref_name, "var": parts[1].strip_edges() if parts.size() > 1 else ""})
return out
## Highest value a dice string can roll ("1d100" -> 100, "2d6" -> 12); 0 if unparsable.
static func dice_max(dice: String) -> int:
var m := RegEx.create_from_string(_DICE_RE).search(dice)
if m == null:
return 0
return m.get_string(1).to_int() * m.get_string(2).to_int()
## Id of the table whose name matches (case-insensitive), or "".
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
var want := table_name.strip_edges().to_lower()
for t in collection.get("tables", []):
if str(t.get("name", "")).to_lower() == want:
return str(t.get("id", ""))
return ""
## Every connection in a collection, pipes and inline references, in
## table/entry order. Each item: kind ("pipe" or "ref"), table_index,
## entry_index, from_table, from_entry (ids), target (table id, or "" when the
## table is missing), target_name (as written), label, count, save_as,
## entry_text (BBCode stripped). Expects a canonical collection.
static func links(collection: Dictionary) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var tables: Array = collection.get("tables", [])
var ids := {}
for t in tables:
ids[str(t["id"])] = true
for ti in tables.size():
var t2: Dictionary = tables[ti]
var elist: Array = t2.get("entries", [])
for ei in elist.size():
var e: Dictionary = elist[ei]
for p in e.get("pipes", []):
var info := pipe_info(p)
var tgt: String = info["table"]
out.append({
"kind": "pipe", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": tgt if ids.has(tgt) else "", "target_name": tgt,
"label": pipe_label(info), "count": info["count"], "save_as": info["save_as"],
"entry_text": strip_bbcode(str(e["text"])),
})
for ref in find_refs(str(e["text"])):
var rid := table_id_by_name(collection, ref["name"])
out.append({
"kind": "ref", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": rid, "target_name": ref["name"],
"label": ("ref → " + ref["var"]) if ref["var"] != "" else "ref",
"count": 1, "save_as": ref["var"],
"entry_text": strip_bbcode(str(e["text"])),
})
return out
## Display label for a table number range, zero padded; the top of a d100 or
## d1000 reads as zeros ("96–00").
static func range_text(lo: int, hi: int, dmax: int) -> String:
return "%s–%s" % [_num_text(lo, dmax), _num_text(hi, dmax)]
static func _num_text(n: int, dmax: int) -> String:
if dmax >= 100 and _is_power_of_ten(dmax):
if n == dmax:
return "0".repeat(str(dmax - 1).length())
return str(n).pad_zeros(str(dmax - 1).length())
return str(n).pad_zeros(str(maxi(dmax, 1)).length())
static func _is_power_of_ten(n: int) -> bool:
while n >= 10 and n % 10 == 0:
n /= 10
return n == 1