TableTower/io/canvas_io.gd

375 lines
13 KiB
GDScript3
Raw Normal View History

class_name CanvasIO
extends RefCounted
## JSON Canvas 1.0 (jsoncanvas.org) export and import.
##
## Each table is a group node, each entry a text node inside it, each pipe an
## edge from the entry to the target group. Inline [[references]] become edges
## too, coloured and labelled "ref". TableTower's own data rides along in a
## "tabletower" object on nodes, so a round trip is exact; without it, import
## rebuilds what it can from the visible text and labels.
const GROUP_W := 340
const ENTRY_W := 300
const PAD := 20
const GAP := 10
const REF_COLOR := "6"
const _CHARS_PER_LINE := 34
const _RANGE_RE := "^\\s*(\\d+)\\s*[–—-]\\s*(\\d+)\\s*:\\s*(.*)$"
const _WEIGHT_RE := "^\\s*(\\d+(?:\\.\\d+)?)\\s*[×xX]\\s+(.*)$"
const _LABEL_RE := "^\\s*(?:[×xX]\\s*(\\d+))?\\s*(?:(?:→|->)\\s*(.*?))?\\s*$"
# ---------------------------------------------------------------- export
## JSON Canvas text for a collection Dictionary.
static func export_canvas(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var nodes: Array = []
var edges: Array = []
var group_ids := {} # table id -> node id
var entry_ids := {} # "tableid\tentryid" -> node id
var tables: Array = c["tables"]
for ti in tables.size():
var t: Dictionary = tables[ti]
var gid := "t%d" % ti
group_ids[t["id"]] = gid
var dmax := JsonIO.dice_max(str(t.get("dice", "")))
var y := int(t["y"]) + PAD
var x := int(t["x"]) + PAD
var entries: Array = t["entries"]
for ei in entries.size():
var e: Dictionary = entries[ei]
var text := JsonIO.entry_line(e, dmax)
var h := _node_height(text)
var nid := "t%de%d" % [ti, ei]
entry_ids["%s\t%s" % [t["id"], e["id"]]] = nid
nodes.append({
"id": nid, "type": "text", "text": text,
"x": x, "y": y, "width": ENTRY_W, "height": h,
"tabletower": _entry_extra(e),
})
y += h + GAP
var group_h := maxi(y - int(t["y"]) + (PAD - GAP if not entries.is_empty() else 40), 80)
var extra := {"id": t["id"]}
for key in ["details", "tags", "dice", "card_mode", "deck_empty", "collapsed"]:
if t.has(key):
extra[key] = t[key]
nodes.push_front({
"id": gid, "type": "group", "label": t["name"],
"x": t["x"], "y": t["y"], "width": GROUP_W, "height": group_h,
"tabletower": extra,
})
# Groups first in the file so they draw underneath their entries.
var ordered: Array = []
for n in nodes:
if n["type"] == "group":
ordered.append(n)
ordered.reverse()
for n in nodes:
if n["type"] != "group":
ordered.append(n)
var edge_n := 0
for link in JsonIO.links(c):
var target := str(link["target"])
if target == "" or not group_ids.has(target):
continue
var from_id: String = entry_ids["%s\t%s" % [link["from_table"], link["from_entry"]]]
var edge := {
"id": "edge%d" % edge_n, "fromNode": from_id, "fromSide": "right",
"toNode": group_ids[target], "toSide": "left",
"tabletower": {"kind": link["kind"]},
}
if link["label"] != "":
edge["label"] = link["label"]
if link["kind"] == "ref":
edge["color"] = REF_COLOR
edges.append(edge)
edge_n += 1
var doc := {
"nodes": ordered, "edges": edges,
"tabletower": {"format_version": JsonIO.FORMAT_VERSION, "id": c["id"], "name": c["name"]},
}
return JSON.stringify(doc, "\t", false)
static func _entry_extra(e: Dictionary) -> Dictionary:
var extra := {"id": e["id"], "text": e["text"]}
for key in ["details", "weight", "range", "pipes"]:
if e.has(key):
extra[key] = e[key]
return extra
static func _node_height(text: String) -> int:
var lines := 0
for part in text.split("\n"):
lines += maxi(1, ceili(float(part.length()) / _CHARS_PER_LINE))
return 40 + 22 * (lines - 1)
# ---------------------------------------------------------------- import
## Returns {"ok": bool, "collection": Dictionary, "guesses": Array[String],
## "errors": Array[String], "warnings": Array[String]}. Collection ids and
## names fall back to defaults when the canvas has no TableTower data.
static func import_canvas(text: String, sanitize: Callable = Callable()) -> Dictionary:
var guesses: Array[String] = []
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "guesses": guesses, "errors": errors, "warnings": warnings}
var json := JSON.new()
if json.parse(text) != OK:
errors.append("Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()])
return result
if not (json.data is Dictionary):
errors.append("Not a JSON Canvas (expected an object with nodes and edges).")
return result
var doc: Dictionary = json.data
var raw_nodes: Variant = doc.get("nodes", [])
var raw_edges: Variant = doc.get("edges", [])
if not (raw_nodes is Array) or not (raw_edges is Array):
errors.append("Not a JSON Canvas (\"nodes\" and \"edges\" must be lists).")
return result
var groups: Array[Dictionary] = []
var texts: Array[Dictionary] = []
var skipped := 0
for n in raw_nodes:
if not (n is Dictionary) or not n.has("id"):
continue
var type := str(n.get("type", ""))
if type == "group":
groups.append(n)
elif type == "text":
texts.append(n)
else:
skipped += 1
if skipped > 0:
guesses.append("Ignored %d file/link node(s); only groups and text nodes become tables and entries." % skipped)
if groups.is_empty():
errors.append("The canvas has no group nodes, so there are no tables to import.")
return result
var doc_extra: Dictionary = doc.get("tabletower", {}) if doc.get("tabletower") is Dictionary else {}
var used := {}
var group_table := {} # group node id -> table dict
var tables: Array = []
var used_fallback_ids := false
for g in groups:
var extra: Dictionary = g.get("tabletower", {}) if g.get("tabletower") is Dictionary else {}
var t := {"x": int(JsonIO._num(g.get("x", 0), 0)), "y": int(JsonIO._num(g.get("y", 0), 0)), "entries": []}
var label := str(g.get("label", "")).strip_edges()
if label == "":
label = "Table %d" % (tables.size() + 1)
guesses.append("A group had no label; named it \"%s\"." % label)
t["name"] = label
var gid := str(extra.get("id", ""))
if gid == "" or used.has(gid):
gid = JsonIO.unique_id(JsonIO.slug(label, "table"), used)
used_fallback_ids = true
else:
used[gid] = true
t["id"] = gid
for key in ["details", "tags", "dice", "card_mode", "deck_empty", "collapsed"]:
if extra.has(key):
t[key] = extra[key]
t["_rich"] = not extra.is_empty()
group_table[str(g["id"])] = t
tables.append(t)
if used_fallback_ids:
guesses.append("Table ids were made up from the group labels.")
# Assign text nodes to the group containing their centre; reading order is top to bottom.
var sorted_texts := texts.duplicate()
var order := {}
for i in sorted_texts.size():
order[str(sorted_texts[i]["id"])] = i
sorted_texts.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
var ya := float(a.get("y", 0))
var yb := float(b.get("y", 0))
if ya != yb:
return ya < yb
var xa := float(a.get("x", 0))
var xb := float(b.get("x", 0))
if xa != xb:
return xa < xb
return order[str(a["id"])] < order[str(b["id"])])
var node_entry := {} # text node id -> {table, entry}
var loose := 0
for tn in sorted_texts:
var owner := _containing_group(tn, groups)
if owner.is_empty():
loose += 1
continue
var table: Dictionary = group_table[str(owner["id"])]
var entry := _entry_from_node(tn, table)
(table["entries"] as Array).append(entry)
node_entry[str(tn["id"])] = {"table": table, "entry": entry}
if loose > 0:
guesses.append("Ignored %d text node(s) that are not inside any group." % loose)
# Fallback structure for groups without TableTower data.
for t2 in tables:
if t2["_rich"]:
continue
_infer_dice(t2, guesses)
for t3 in tables:
t3.erase("_rich")
# Pipes from edges, only for entries that did not carry their own pipes.
var edge_pipes := 0
for ed in raw_edges:
if not (ed is Dictionary):
continue
var from_id := str(ed.get("fromNode", ""))
var to_id := str(ed.get("toNode", ""))
var edge_extra: Dictionary = ed.get("tabletower", {}) if ed.get("tabletower") is Dictionary else {}
var label2 := str(ed.get("label", "")).strip_edges()
if edge_extra.get("kind", "") == "ref" or _is_ref_label(label2):
continue # references come back from the entry text
if not node_entry.has(from_id):
continue
var holder: Dictionary = node_entry[from_id]
var entry2: Dictionary = holder["entry"]
if entry2.get("_has_pipes", false):
continue
var target := _edge_target_table(to_id, group_table, node_entry)
if target.is_empty():
continue
if not group_table.has(to_id):
guesses.append("An edge pointed at an entry; used its table \"%s\" instead." % str(target["name"]))
var pipe: Variant = _pipe_from_label(str(target["id"]), label2)
if not entry2.has("pipes"):
entry2["pipes"] = []
(entry2["pipes"] as Array).append(pipe)
edge_pipes += 1
for t4 in tables:
for e in t4["entries"]:
e.erase("_has_pipes")
if edge_pipes > 0:
guesses.append("Built %d pipe(s) from edges and their labels." % edge_pipes)
var raw := {
"format_version": JsonIO.FORMAT_VERSION,
"id": str(doc_extra.get("id", "")),
"name": str(doc_extra.get("name", "")),
"tables": tables,
}
if doc_extra.is_empty():
guesses.append("No collection name in the canvas; using a default.")
return JsonIO.finish_import(raw, sanitize, result)
static func _containing_group(node: Dictionary, groups: Array[Dictionary]) -> Dictionary:
var cx := float(node.get("x", 0)) + float(node.get("width", 0)) / 2.0
var cy := float(node.get("y", 0)) + float(node.get("height", 0)) / 2.0
var best: Dictionary = {}
var best_area := INF
for g in groups:
var gx := float(g.get("x", 0))
var gy := float(g.get("y", 0))
var gw := float(g.get("width", 0))
var gh := float(g.get("height", 0))
if cx >= gx and cx <= gx + gw and cy >= gy and cy <= gy + gh and gw * gh < best_area:
best = g
best_area = gw * gh
return best
## Builds an entry; uses the node's tabletower data when present, else parses its text.
static func _entry_from_node(tn: Dictionary, table: Dictionary) -> Dictionary:
var extra: Dictionary = tn.get("tabletower", {}) if tn.get("tabletower") is Dictionary else {}
if extra.has("text"):
var e := {"id": str(extra.get("id", "")), "text": str(extra["text"])}
for key in ["details", "weight", "range", "pipes"]:
if extra.has(key):
e[key] = extra[key]
e["_has_pipes"] = extra.has("pipes")
return e
var raw := str(tn.get("text", "")).strip_edges()
var e2 := {"id": "", "text": raw}
var m := RegEx.create_from_string(_RANGE_RE).search(raw)
if m != null:
e2["text"] = m.get_string(3).strip_edges()
e2["range"] = [m.get_string(1), m.get_string(2)] # raw digits, fixed up in _infer_dice
else:
var wm := RegEx.create_from_string(_WEIGHT_RE).search(raw)
if wm != null:
e2["text"] = wm.get_string(2).strip_edges()
e2["weight"] = JsonIO._num(wm.get_string(1).to_float(), 1)
e2["_has_pipes"] = false
return e2
## For tables rebuilt from text: fixes up range numbers ("00" wraps to the top
## of the die) and infers the dice from the highest range.
static func _infer_dice(t: Dictionary, guesses: Array[String]) -> void:
var ranged: Array = []
for e in t["entries"]:
if e.has("range") and e["range"][0] is String:
ranged.append(e)
if ranged.is_empty():
return
var top := 0
for e in ranged:
for v in e["range"]:
top = maxi(top, int(v))
var wrap := 10
while wrap < top:
wrap *= 10
var any_wrapped := false
for e in ranged:
var r: Array = e["range"]
var nums: Array = []
for v in r:
var s: String = v
var n := s.to_int()
if n == 0:
n = wrap
any_wrapped = true
nums.append(n)
e["range"] = nums
top = maxi(top, int(nums[1]))
if not t.has("dice"):
t["dice"] = "1d%d" % top
guesses.append("Table \"%s\": ranges found, so it is a ranged table; guessed dice 1d%d." % [str(t["name"]), top])
if any_wrapped:
guesses.append("Table \"%s\": read \"00\" as %d." % [str(t["name"]), wrap])
if ranged.size() < (t["entries"] as Array).size():
guesses.append("Table \"%s\": only some entries have ranges; the rest are kept without one." % str(t["name"]))
static func _is_ref_label(label: String) -> bool:
var l := label.to_lower()
return l == "ref" or l.begins_with("ref ") or l.begins_with("ref→")
static func _edge_target_table(to_id: String, group_table: Dictionary, node_entry: Dictionary) -> Dictionary:
if group_table.has(to_id):
return group_table[to_id]
if node_entry.has(to_id):
return node_entry[to_id]["table"]
return {}
## "×2 → weapon" -> {"table", "count": 2, "save_as": "weapon"}; "" -> plain table id.
static func _pipe_from_label(table_id: String, label: String) -> Variant:
if label == "":
return table_id
var m := RegEx.create_from_string(_LABEL_RE).search(label)
if m == null:
return table_id
var count := m.get_string(1).to_int() if m.get_string(1) != "" else 1
var save_as := m.get_string(2).strip_edges()
if count == 1 and save_as == "":
return table_id
var p := {"table": table_id}
if m.get_string(1) != "":
p["count"] = count
if save_as != "":
p["save_as"] = save_as
return p