Spreads can roll cards from other spreads: [[Spread::Card]]

A result's text can name a card in another spread, as "[[Treasure::Loot]]".
It rolls there (its own threads and references resolve in that spread)
and its changes apply to this spread's values. The inspector has
"+ Roll a card from another spread…" to pick one. Links show as
"Treasure › Loot" chips; nodes from there are marked so this spread's
cards aren't lit for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-14 14:45:01 -06:00
parent a2f0d3a016
commit 2ed91e7acd
19 changed files with 265 additions and 13 deletions

View file

@ -34,6 +34,8 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
step["save_as"] = n["save_as"]
if n.has("kind"):
step["kind"] = n["kind"]
if n.has("spread"):
step["spread"] = n["spread"]
if n.has("effects"):
step["effects"] = (n["effects"] as Array).duplicate(true)
for k in ["answer", "passes", "pass", "after", "picked", "only_option", "random", "limit", "cancelled", "deck_empty", "dropped", "kept", "combined", "stopped_before", "case", "option", "check", "inputs", "columns"]:
@ -138,7 +140,7 @@ static func link_key(table_id: String, entry_id: String, c: Dictionary) -> Strin
## Ids of the tables an entry's text references, resolved against the board,
## without duplicates or missing tables.
## without duplicates, missing tables or cards from other spreads.
static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
var out: Array[String] = []
if not text.contains("[[") and not text.contains("|"):
@ -146,6 +148,6 @@ static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
var res := func(name: String) -> String: return Roller.resolve(board, name)
for name in TextExpander.references(text, res):
var id := Roller.resolve(board, name)
if id != "" and not out.has(id):
if id != "" and not SpreadLinks.is_link(id) and not out.has(id):
out.append(id)
return out

View file

@ -69,16 +69,25 @@ static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persisten
ctx.set_meta("decks", decks)
# A weak reference, so the context doesn't keep itself alive through its hooks.
var wr: WeakRef = weakref(ctx)
# The hooks use the context's spread, which is another spread's while a
# [[Spread::Card]] link rolls (SpreadLinks).
ctx.resolve_table = func(name_or_id: String) -> String:
return resolve(board, name_or_id)
var c: RollContext = wr.get_ref()
return resolve(c.board if c and c.board else board, name_or_id)
ctx.roll_table = func(id: String, depth: int) -> Dictionary:
var c: RollContext = wr.get_ref()
return {} if c == null else _chain_sync(board, id, depth, c)
if c == null:
return {}
if SpreadLinks.is_link(id):
return SpreadLinks.roll_sync(id, depth, c)
return _chain_sync(c.board if c.board else board, id, depth, c)
ctx.roll_table_async = func(id: String, depth: int) -> Dictionary:
var c: RollContext = wr.get_ref()
if c == null:
return {}
return await _chain(board, id, depth, c)
if SpreadLinks.is_link(id):
return await SpreadLinks.roll_async(id, depth, c)
return await _chain(c.board if c.board else board, id, depth, c)
return ctx
@ -86,6 +95,8 @@ static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persisten
## case-insensitively without BBCode. "" if there's no such table.
static func resolve(board: TowerBoard, name_or_id: String) -> String:
var key := name_or_id.strip_edges()
if SpreadLinks.is_link(key):
return SpreadLinks.resolve(key)
if board.get_table(key) != null:
return key
var want := RollContext.normalize_name(key)

91
core/spread_links.gd Normal file
View file

@ -0,0 +1,91 @@
class_name SpreadLinks
extends RefCounted
## Rolling a card from another spread: [[Treasure::Loot]] in result text rolls
## the Loot card of the spread called Treasure and puts its result in the text
## (with its own threads and references, which resolve inside Treasure). The
## roll uses this spread's values, so the other spread's changes (@gold += 10)
## land here; its decks are not kept between rolls.
##
## A linked card's id is "<spread id>::<card id>". The app sets `loader` (a
## spread's id or name -> TowerBoard or null); without it, links are missing.
const SEP := "::"
## func(spread_id_or_name: String) -> TowerBoard (or null). Set by Main.
static var loader: Callable = Callable()
static func is_link(name_or_id: String) -> bool:
return name_or_id.contains(SEP)
## "Treasure::Loot" -> the linked id "treasure::t12", or "" when the spread or
## the card can't be found.
static func resolve(name_or_id: String) -> String:
var parts := name_or_id.split(SEP, true, 1)
if parts.size() != 2:
return ""
var other := load_board(parts[0])
if other == null:
return ""
var card_id := Roller.resolve(other, parts[1])
return "" if card_id == "" else "%s%s%s" % [other.id, SEP, card_id]
static func load_board(spread: String) -> TowerBoard:
if not loader.is_valid() or spread.strip_edges() == "":
return null
var found: Variant = loader.call(spread.strip_edges())
return found if found is TowerBoard else null
## The card a linked id names, or null.
static func card(linked_id: String) -> RollTable:
var parts := linked_id.split(SEP, true, 1)
var other := load_board(parts[0]) if parts.size() == 2 else null
return other.get_table(parts[1]) if other else null
## Rolls a linked card inside its own spread: while it runs, the context's
## spread (and its decks) are the other spread's; then they're put back.
static func roll_async(linked_id: String, depth: int, ctx: RollContext) -> Dictionary:
var visit := _enter(linked_id, ctx)
if visit.is_empty():
return {}
var node: Dictionary = await Roller._chain(visit["board"], visit["card"], depth, ctx)
return _leave(visit, node, ctx)
## The same without waiting (headless rolls: tests, Test spread).
static func roll_sync(linked_id: String, depth: int, ctx: RollContext) -> Dictionary:
var visit := _enter(linked_id, ctx)
if visit.is_empty():
return {}
var node: Dictionary = Roller._chain_sync(visit["board"], visit["card"], depth, ctx)
return _leave(visit, node, ctx)
static func _enter(linked_id: String, ctx: RollContext) -> Dictionary:
var parts := linked_id.split(SEP, true, 1)
var other := load_board(parts[0]) if parts.size() == 2 else null
if other == null or other.get_table(parts[1]) == null:
return {}
var visit := {"board": other, "card": parts[1], "home": ctx.board, "decks": ctx.get_meta("decks", {})}
ctx.board = other
ctx.set_meta("decks", {})
ctx.forget_declarations()
return visit
static func _leave(visit: Dictionary, node: Dictionary, ctx: RollContext) -> Dictionary:
ctx.board = visit["home"]
ctx.set_meta("decks", visit["decks"])
ctx.forget_declarations()
# Every node from the other spread is marked, so this spread's cards with
# the same ids aren't lit or animated for them.
var stack: Array = [] if node.is_empty() else [node]
while not stack.is_empty():
var each: Dictionary = stack.pop_back()
each["spread"] = (visit["board"] as TowerBoard).name
stack.append_array(each.get("children", []))
return node

1
core/spread_links.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bdj04p1iyb8vd

View file

@ -427,6 +427,12 @@ statement shows a red marker in the tray and in Build mode rather than stopping
- `{@[expr]}` shows the variable named by `expr`, e.g. `{@[option]}`; unset shows its
`{@name?}` marker, a bad name an error marker.
- The existing `{@var|Table}`, `{hero}` and `[[refs]]` work as before.
- `[[Spread::Card]]` (2026-11-14, `SpreadLinks`) rolls a card of another spread (by name or
id, any capitals): its id is `<spread id>::<card id>`; while it rolls, `ctx.board` is that
spread (its references resolve there; its decks aren't kept) and it reads and changes this
spread's values. Its nodes carry `spread` (the spread's name), so the board doesn't light or
animate same-id cards here. The app's `SpreadLoader` finds spreads (cached until the file
changes); without a loader (`--sample`, tests) links show the missing marker.
### 5.4 Scales (ordered steps)
A variable card with `var_type: "scale"` lists `steps`, lowest first (Supercold, Cold,

View file

@ -168,6 +168,7 @@ Use [b]Test spread[/b] to check that a spread of logic cards works. See [topic]T
Result text can do more than plain words:
- `[[Traveler Names]]` rolls that table and puts its result in the text.
- `[[Traveler Names -> patron]]` also saves it as patron, so later text can say `{patron}`.
- `[[Treasure::Loot]]` rolls the Loot card from another spread, called Treasure, so one spread can use another's tables (a dungeon calling a loot spread). Its own threads and references work there, and its changes apply to this spread's values. In the result's inspector, [b]+ Roll a card from another spread…[/b] picks the spread and card for you.
- `{@town}` shows a value. `{@town|Towns}` shows it, or rolls Towns once and remembers the answer if it isn't set yet.
- `{= @gold * 2}` shows a worked-out number.
- Formatting: `[b]bold[/b]` and `[i]italic[/i]`. [b]Right-click[/b] any text field and use [b]Format[/b] to wrap the selected words: Bold, Italic, Underline, Strike-through, Colour, Size and Effect.

View file

@ -0,0 +1,39 @@
extends TestBase
## Rolling a card from another spread: [[Treasure::Loot]] rolls Loot in the
## Treasure spread (its own references resolve there), changes this spread's
## values, and a missing spread or card shows the missing marker.
## Run: godot --headless --path . -s res://tests/test_spread_links.gd
func _init() -> void:
var treasure := TowerBoard.new()
treasure.id = "treasure"
treasure.name = "Treasure"
treasure.load_dict({"tables": [
{"id": "loot", "name": "Loot", "entries": [{"id": "l1", "text": "A [[Gem]] worth gold", "effects": "@gold += 10"}]},
{"id": "gem", "name": "Gem", "entries": [{"id": "g1", "text": "ruby"}]},
]})
var dungeon := TowerBoard.new()
dungeon.id = "dungeon"
dungeon.name = "Dungeon"
dungeon.load_dict({"tables": [
{"id": "room", "name": "Room", "entries": [{"id": "r1", "text": "A chest: [[Treasure::Loot]]"}]},
{"id": "lost", "name": "Lost", "entries": [{"id": "x1", "text": "[[Nowhere::Loot]] and [[Treasure::Nothing]]"}]},
]})
SpreadLinks.loader = func(key: String) -> TowerBoard:
return treasure if key.to_lower() in ["treasure", "treasure"] else null
_eq(Roller.resolve(dungeon, "Treasure::Loot"), "treasure::loot", "a link resolves to the other spread's card")
_check(Roller.ref_targets(dungeon, "[[Treasure::Loot]]").is_empty(), "links draw no reference line on this spread")
var ctx := Roller.new_context(dungeon, RandomNumberGenerator.new(), {"gold": {"value": 1}})
var tree: Dictionary = await Roller.roll_async(dungeon, "room", ctx)
_eq(Formatter.strip_tags(str(tree["summary"])), "A chest: A ruby worth gold", "the other spread's card rolls, with its own references")
_eq(int(ctx.lookup("@gold")), 11, "its changes land on this spread's values")
_check(ctx.board == dungeon, "the roll ends back on this spread")
var linked: Dictionary = (tree["children"] as Array)[0]
_check(linked.get("spread") == "Treasure" and ((linked["children"] as Array)[0] as Dictionary).get("spread") == "Treasure", "every node from there is marked with its spread")
var sync_tree := Roller.roll(dungeon, "room", RandomNumberGenerator.new())
_check(Formatter.strip_tags(str(sync_tree["summary"])).contains("ruby"), "headless rolls follow links too")
var lost := Roller.roll(dungeon, "lost", RandomNumberGenerator.new())
_check(str(lost["summary"]).contains("missing:"), "a missing spread or card shows the missing marker")
SpreadLinks.loader = Callable()
finish()

View file

@ -0,0 +1 @@
uid://dsmnft4015lrf

View file

@ -138,7 +138,7 @@ func preview_for_option(k: int) -> Control:
var mentioned: Array[String] = []
for name in TextExpander.references(e.text, func(n: String) -> String: return Roller.resolve(d.board, n)):
var rid := Roller.resolve(d.board, name)
if rid != "" and not shown.has(rid) and not mentioned.has(rid):
if rid != "" and not SpreadLinks.is_link(rid) and not shown.has(rid) and not mentioned.has(rid):
mentioned.append(rid)
if not mentioned.is_empty():
any = true

View file

@ -136,7 +136,7 @@ func _place() -> void:
# ---------- Content ----------
func show_table(owner: Control, tid: String, only_if_details: bool = false) -> void:
var t := main.data.get_table(tid) if main.data else null
var t := SpreadLinks.card(tid) if SpreadLinks.is_link(tid) else (main.data.get_table(tid) if main.data else null)
if t == null:
return
if only_if_details and t.details.strip_edges() == "":

View file

@ -71,8 +71,13 @@ static func section(insp: Inspector, t: RollTable, e: TableEntry) -> void:
FormatMenu.attach(le)
InspectorKit.tag(le, "res.text")
le.text_changed.connect(insp.set_entry_text)
var link := InspectorKit.link("+ Roll a card from another spread…", "Puts [[Spread::Card]] in the text: that card rolls when this result comes up")
link.pressed.connect(func() -> void: SpreadLinkDialog.open(insp.main, func(ref: String) -> void:
le.text = (le.text.strip_edges() + " " + ref).strip_edges()
insp.set_entry_text(le.text)))
insp.fields["text"] = le
insp._content.add_child(InspectorKit.field(Inspector._title_of(str(t.columns[0].get("name", "")), "Text") if t.has_columns() else "Text", le))
insp._content.add_child(link)
InspectorColumns.result_cells(insp, t, e)
var det := InspectorKit.text_box(e.details, "Shown on hover (optional)", 36.0)

View file

@ -15,6 +15,7 @@ func _init(p_main: Main) -> void:
func _open_library() -> void:
m.state = StateStore.new()
m.library = LibraryStore.new("user://", m.state)
SpreadLinks.loader = SpreadLoader.new(m).find
m.library.migrate_legacy()
var last := str(m.state.get_setting("last_collection", ""))
if last != "":

View file

@ -213,7 +213,7 @@ func _play_node(root_node: Dictionary, my: int) -> void:
var tid := (n["table"] as RollTable).id
for k in range(kids.size() - 1, -1, -1):
var c: Dictionary = kids[k]
var ck := "" if (c.has("pass") or c.has("after")) else Roller.link_key(tid, eid, c)
var ck := "" if (c.has("pass") or c.has("after") or c.has("spread")) else Roller.link_key(tid, eid, c)
stack.append([c, int(top[1]) + 1, ck])
if _relit:
_relit = false
@ -225,8 +225,10 @@ func _play_node(root_node: Dictionary, my: int) -> void:
## lights. A node already animated (before a pause) only lights again, at once.
func _play_one(n: Dictionary, my: int, depth: int) -> void:
var t: RollTable = n["table"]
var stopped := n.has("stop")
var card := m.card_for(t.id)
# A card from another spread ([[Spread::Card]]) has no card here to animate.
var elsewhere := n.has("spread")
var stopped := n.has("stop") or elsewhere
var card: TableCard = null if elsewhere else m.card_for(t.id)
var replay: bool = n.get("animated", false)
n["animated"] = true
var tumble: bool = (not n.has("kind") or bool(n.get("random", false))) and not replay

View file

@ -69,7 +69,7 @@ func _light_steps(steps: Array) -> void:
var d := int(s.get("depth", 0))
stack.resize(d)
stack.append(s)
if s.get("stop", false) or not s.has("entry_id"):
if s.get("stop", false) or not s.has("entry_id") or s.has("spread"):
continue
var tid := str(s.get("table_id", ""))
var ek := Roller.entry_key(tid, str(s["entry_id"]))

View file

@ -171,8 +171,13 @@ static func _ref_chip(body: String, board: TowerBoard) -> String:
id = Roller.resolve(board, name)
if id == "":
return _bad(TextExpander.missing_marker(name), false)
var t := board.get_table(id)
var label_text := count + plain(Formatter.strip_tags(t.name))
var linked := SpreadLinks.is_link(id)
var t := SpreadLinks.card(id) if linked else board.get_table(id)
var shown := Formatter.strip_tags(t.name) if t else name
if linked:
# A card from another spread names its spread too: "Treasure › Loot".
shown = name.get_slice(SpreadLinks.SEP, 0).strip_edges() + " › " + shown
var label_text := count + plain(shown)
if save != "":
label_text += " → " + plain(save)
return "[url=table:%s][bgcolor=#%s][color=#%s] %s [/color][/bgcolor][/url]" % [id, Style.REF_BG.to_html(false), Style.REF_INK.to_html(false), label_text]

45
ui/spread_link_dialog.gd Normal file
View file

@ -0,0 +1,45 @@
class_name SpreadLinkDialog
extends RefCounted
## "Roll a card from another spread…" in a result's inspector: pick a spread,
## then one of its cards; on Insert, [[Spread::Card]] goes at the end of the
## result's text (SpreadLinks rolls it).
static func open(main: Main, on_pick: Callable) -> void:
if main.library == null:
main.toast("Other spreads can't be read in this session")
return
var spreads: Array = main.library.list().filter(func(entry: Dictionary) -> bool: return str(entry["id"]) != main.data.id)
if spreads.is_empty():
main.toast("There's no other spread yet")
return
var dialog := ModalCard.new("Roll a card from another spread", 440.0)
var spread_pick := OptionButton.new()
ModalCard.style_popup(spread_pick.get_popup())
for entry: Dictionary in spreads:
spread_pick.add_item(str(entry["name"]))
dialog.body.add_child(ModalCard.field("Spread", spread_pick))
var card_pick := OptionButton.new()
ModalCard.style_popup(card_pick.get_popup())
dialog.body.add_child(ModalCard.field("Card", card_pick))
dialog.body.add_child(ModalCard.note("When this result comes up, that card rolls in its own spread, and its result goes into this text. Its changes apply to this spread's values."))
var names: Array[String] = []
var fill_cards := func(index: int) -> void:
card_pick.clear()
names.clear()
var board := main.library.load_collection(str(spreads[index]["id"]))
if board == null:
return
for table in board.tables:
if table.kind != RollTable.KIND_VARIABLE:
names.append(Formatter.strip_tags(table.name).strip_edges())
card_pick.add_item(names.back())
spread_pick.item_selected.connect(fill_cards)
fill_cards.call(0)
dialog.add_button("Cancel", "plain", dialog.close)
dialog.add_button("Insert", "primary", func() -> void:
if card_pick.selected < 0:
return
dialog.close()
on_pick.call("[[%s%s%s]]" % [str(spreads[spread_pick.selected]["name"]), SpreadLinks.SEP, names[card_pick.selected]]))
main._add_modal(dialog)

View file

@ -0,0 +1 @@
uid://dqq2dyi1a5e1e

40
ui/spread_loader.gd Normal file
View file

@ -0,0 +1,40 @@
class_name SpreadLoader
extends RefCounted
## Finds spreads for [[Spread::Card]] links (SpreadLinks.loader): by id or by
## name (any capitals). The open spread is used as it is in memory; others are
## read from disk and kept until their file changes.
var m: Main
## id -> [modified time, TowerBoard]
var _cache: Dictionary = {}
func _init(p_main: Main) -> void:
m = p_main
func find(key: String) -> TowerBoard:
if m.data and (key == m.data.id or RollContext.normalize_name(key) == RollContext.normalize_name(m.data.name)):
return m.data
if m.library == null:
return null
var id := key if m.library.exists(key) else _id_by_name(key)
if id == "":
return null
var stamp := FileAccess.get_modified_time(m.library.path_for(id))
var kept: Array = _cache.get(id, [])
if kept.is_empty() or int(kept[0]) != stamp:
var board := m.library.load_collection(id)
if board == null:
return null
kept = [stamp, board]
_cache[id] = kept
return kept[1]
func _id_by_name(spread_name: String) -> String:
var want := RollContext.normalize_name(spread_name)
for entry in m.library.list():
if RollContext.normalize_name(str(entry["name"])) == want:
return str(entry["id"])
return ""

1
ui/spread_loader.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c71hj7iqmlh8j