TableTower/ui/table_card.gd
RobinFiredrake adb93c545c Join the inspector and display halves; starting values apply to rolls
- Cards read the inspector's selection ({kind, tid, eid}) and the
  inspector marks the selected row on every card when it changes.
- A variable card's starting value now applies: before a top-level
  roll, each declared variable that isn't set yet and has a starting
  value is set to it (a "starts at 9" Strength no longer reads as 0).
- Check cards in Build no longer repeat "Success Success": a result
  text equal to the outlet name shows as an empty field with a hint.
- test_options switches to the Text view through Main.

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

1697 lines
65 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 TableCard
extends PanelContainer
## One table on the board: a header with the collapse toggle, name and die
## button, then its numbered results. Rebuilt from the RollTable whenever the
## mode, the table's shape, or (when collapsed) the lit result changes.
##
## Logic cards (docs/LOGIC.md) share the layout: a choice card has a "?"
## badge, its question and its options (or one Answer row); a loop card shows
## its rule and the Each time / Afterwards rows; a variable card shows its
## live value and has no rows; a sheet card's one row is its rendered
## template; a router card has a fork icon in place of the die and one row
## per case, showing its condition ("if @str >= 8", "Otherwise") with its
## outlet. Live text (values, sheets, prompts) is only re-rendered by
## refresh_live(), which Main calls after rolls and edits, never per frame.
## A pick card whose options come from variables (docs/LOGIC.md §2a) says
## "Options from @skill_* · where …" (in Play with how many are available
## now) and has a Chosen row first; any pick option can have a Show only if
## condition, shown under its row ("only if …").
##
## Rules read in plain words (docs/PLAIN.md §6, Describe) or as their stored
## text, following RulesView.plain(main); cards rebuild on Main's
## rules_view_changed. Build mode only edits result text and the card's name
## inline; everything else (effects, conditions, details, card fields) is
## edited in Main's inspector, so rows show plain chips instead. Clicking a
## result row in Build calls main.select_result(table id, entry id) when Main
## has it; the selected row gets a copper bar on its left, from
## main.inspector_selection() ({"table_id", "entry_id"}) at rebuild time or
## set_selected_entry(entry id), which the inspector can call on any card.
##
## Check cards have a "2D" badge, their rule as a sentence and two outlet rows,
## Success and Failure. Collection cards list their members with live values
## (and "+ Add" in Build, which selects the card for the inspector). A card
## with inputs shows them in a dashed box under the header.
const WIDTH := 256.0
## Build mode has more controls per row, so cards are a little wider there.
const BUILD_WIDTH := 300.0
const LONG_LIST := 12
const LIST_HEIGHT := 432.0
const INLET_Y := 30.0
enum RowState { NORMAL, FLICK, LIT }
var main: Main
var table: RollTable
## entry id -> row PanelContainer, for the rows currently shown.
var rows: Dictionary = {}
var more_row: PanelContainer
var list_scroll: ScrollContainer
var _row_parts: Dictionary = {}
var _row_styles: Array[StyleBoxFlat] = []
var _list_box: VBoxContainer
var _more_label: Label
var _warn_panel: Control
var _warn_label: Label
var _die_icon: DieIcon
var _rolling := false
var _dragging := false
var _drop_target := false
var _drag_offset := Vector2.ZERO
var _flick_id := ""
var _style_normal: StyleBoxFlat
var _style_rolling: StyleBoxFlat
var _style_dragging: StyleBoxFlat
var _style_drop: StyleBoxFlat
var _style_selected: StyleBoxFlat
var _selected := false
var _deck_row: Control
var _deck_label: Label
## Unused since the inspector took over the inline editors; kept because
## Main's screenshot flags (--edit-details, --edit-effects) still set them.
var _open_details: Dictionary = {}
var _open_effects: Dictionary = {}
var _open_show_if: Dictionary = {}
## Play mode: "3 available now" on a dynamic pick card.
var _options_label: Label
var _table_details_open := false
## Live parts, updated by refresh_live().
var _prompt_label: RichTextLabel
var _var_value: Label
var _var_hint: Label
var _sheet_label: RichTextLabel
var _live_cache: Dictionary = {}
## Rules in plain words (read from RulesView at each rebuild).
var _plain := true
## The result picked in the inspector (copper bar), or "".
var _selected_eid := ""
## Collection cards: the member list, refilled by refresh_live().
var _members_box: VBoxContainer
var _members_cache := ""
func setup(p_main: Main, p_table: RollTable) -> void:
main = p_main
table = p_table
custom_minimum_size = Vector2(WIDTH, 0)
mouse_filter = MOUSE_FILTER_PASS
theme = Style.card_theme()
position = table.position
_style_normal = Style.box(Style.CARD, 10)
_style_normal.shadow_color = Color(0, 0, 0, 0.32)
_style_normal.shadow_size = 16
_style_normal.shadow_offset = Vector2(0, 8)
_style_rolling = _style_normal.duplicate() as StyleBoxFlat
Style.bordered(_style_rolling, 3, Style.BRASS)
_style_rolling.set_expand_margin_all(3)
_style_rolling.shadow_color = Color(Style.BRASS, 0.45)
_style_rolling.shadow_size = 26
_style_rolling.shadow_offset = Vector2.ZERO
_style_drop = _style_rolling.duplicate() as StyleBoxFlat
_style_drop.shadow_color = Color(0, 0, 0, 0.32)
_style_drop.shadow_size = 16
_style_drop.shadow_offset = Vector2(0, 8)
_style_selected = _style_normal.duplicate() as StyleBoxFlat
Style.bordered(_style_selected, 3, Style.COPPER)
_style_selected.set_expand_margin_all(4)
_style_selected.shadow_color = Color(Style.COPPER, 0.5)
_style_selected.shadow_size = 14
_style_selected.shadow_offset = Vector2.ZERO
_style_dragging = _style_normal.duplicate() as StyleBoxFlat
_style_dragging.shadow_color = Color(0, 0, 0, 0.4)
_style_dragging.shadow_size = 26
_style_dragging.shadow_offset = Vector2(0, 16)
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
_row_styles.append(Style.box(c, 0, [12, 6, 22, 6]))
# The same, with the copper bar of the inspector's selected result.
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
var sel := Style.box(c, 0, [12, 6, 22, 6])
sel.border_width_left = 3
sel.border_color = Style.COPPER
sel.anti_aliasing = false
_row_styles.append(sel)
minimum_size_changed.connect(func() -> void: _shrink.call_deferred())
RulesView.watch(main, _on_rules_view_changed)
rebuild()
func _on_rules_view_changed(_v: Variant = null) -> void:
rebuild()
func rebuild() -> void:
for c in get_children():
remove_child(c)
c.queue_free()
rows.clear()
_row_parts.clear()
more_row = null
_more_label = null
list_scroll = null
_flick_id = ""
_deck_row = null
_deck_label = null
_prompt_label = null
_var_value = null
_var_hint = null
_sheet_label = null
_options_label = null
_members_box = null
_members_cache = ""
_live_cache.clear()
_plain = RulesView.plain(main)
if main.has_method("inspector_selection"):
var sel: Variant = main.call("inspector_selection")
_selected_eid = ""
# The inspector reports {kind, tid, eid}; older callers used {table_id, entry_id}.
if sel is Dictionary:
var d := sel as Dictionary
var tid := str(d.get("tid", d.get("table_id", "")))
if tid == table.id and str(d.get("kind", "result")) == "result":
_selected_eid = str(d.get("eid", d.get("entry_id", "")))
var build := main.mode == Main.Mode.BUILD
custom_minimum_size = Vector2(card_width(), 0)
_shrink.call_deferred()
var ranged := table.is_ranged()
var collapsed := is_collapsed()
var col := _vbox(0)
add_child(col)
col.add_child(_make_header(build, ranged))
if not table.inputs.is_empty() and table.kind != RollTable.KIND_VARIABLE:
col.add_child(_make_inputs_box())
if table.kind == RollTable.KIND_VARIABLE:
col.add_child(_make_collection_body(build) if table.is_collection() else _make_variable_body(build))
_warn_panel = _make_warning()
col.add_child(_warn_panel)
_update_warning()
if build:
col.add_child(_make_footer(ranged))
_apply_style()
refresh_live()
return
var pad := MarginContainer.new()
pad.mouse_filter = MOUSE_FILTER_PASS
pad.add_theme_constant_override("margin_top", 6)
pad.add_theme_constant_override("margin_bottom", 8)
_list_box = _vbox(0)
pad.add_child(_list_box)
if not collapsed and table.entries.size() > LONG_LIST:
list_scroll = ScrollContainer.new()
list_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
list_scroll.custom_minimum_size = Vector2(0, LIST_HEIGHT)
list_scroll.mouse_filter = MOUSE_FILTER_PASS
_skin_scrollbar(list_scroll.get_v_scroll_bar())
pad.size_flags_horizontal = SIZE_EXPAND_FILL
list_scroll.add_child(pad)
col.add_child(list_scroll)
else:
col.add_child(pad)
var numw := _num_width(build, ranged)
for i in table.entries.size():
var e := table.entries[i]
var lit := main.is_entry_lit(table.id, e.id)
if collapsed and not lit:
continue
if table.kind == RollTable.KIND_SHEET:
_list_box.add_child(_make_sheet_row(e, build))
elif table.kind == RollTable.KIND_ROUTER and build:
_list_box.add_child(_make_case_row(e, i, numw))
elif table.kind == RollTable.KIND_CHECK:
_list_box.add_child(_make_check_row(e, i, build, numw))
else:
_list_box.add_child(_make_row(e, i, build, ranged, numw))
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
if collapsed:
_list_box.add_child(_make_more_row(numw))
_warn_panel = _make_warning()
col.add_child(_warn_panel)
_update_warning()
if build:
col.add_child(_make_footer(ranged))
_apply_style()
refresh_live()
if list_scroll != null:
for eid in rows:
if main.is_entry_lit(table.id, eid):
_reveal_when_laid_out.call_deferred(eid)
break
## Variable and sheet cards always show everything; other cards collapse.
func is_collapsed() -> bool:
return table.collapsed and can_collapse()
func can_collapse() -> bool:
return table.kind != RollTable.KIND_VARIABLE and table.kind != RollTable.KIND_SHEET
func _reveal_when_laid_out(eid: String) -> void:
await get_tree().process_frame
if is_instance_valid(list_scroll):
reveal(eid)
# ---------- Building blocks ----------
func _vbox(sep: int) -> VBoxContainer:
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", sep)
v.mouse_filter = MOUSE_FILTER_PASS
return v
func _hbox(sep: int) -> HBoxContainer:
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", sep)
h.mouse_filter = MOUSE_FILTER_PASS
return h
func _num_width(build: bool, ranged: bool) -> float:
var wide := table.die_size() >= 100
if build and ranged:
return 90.0
if ranged:
return 52.0 if wide else 40.0
return 24.0 if wide else 22.0
func _make_header(build: bool, ranged: bool) -> Control:
var header := PanelContainer.new()
var hs := Style.box(Color(0, 0, 0, 0), 0, [12, 10, 10, 9])
hs.border_width_bottom = 1
hs.border_color = Style.RULE
header.add_theme_stylebox_override("panel", hs)
header.mouse_filter = MOUSE_FILTER_PASS
header.mouse_default_cursor_shape = CURSOR_MOVE
header.gui_input.connect(_on_header_input.bind(header))
var row := _hbox(8)
var head_box := _vbox(4)
header.add_child(head_box)
head_box.add_child(row)
if can_collapse():
var chevron := ChevronButton.new()
chevron.open = not table.collapsed
chevron.tooltip_text = ("Expand " if table.collapsed else "Collapse ") + table.name
chevron.size_flags_vertical = SIZE_SHRINK_CENTER
chevron.pressed.connect(func() -> void: main.toggle_collapse(table.id))
row.add_child(chevron)
header.mouse_entered.connect(func() -> void:
if not _dragging and main.mode == Main.Mode.PLAY:
main.details().show_table(header, table.id, true)
)
if build:
var name_edit := LineEdit.new()
name_edit.text = table.name
name_edit.size_flags_horizontal = SIZE_EXPAND_FILL
name_edit.size_flags_vertical = SIZE_SHRINK_CENTER
name_edit.custom_minimum_size = Vector2(40, 0)
name_edit.add_theme_font_override("font", Style.display(true))
name_edit.add_theme_font_size_override("font_size", 18)
name_edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 6, [7, 3, 7, 3]), 1, Style.RULE))
name_edit.text_changed.connect(func(s: String) -> void:
table.name = s
main.mark_dirty()
)
row.add_child(name_edit)
var gear := Button.new()
gear.text = "⚙"
gear.tooltip_text = "Table settings"
gear.custom_minimum_size = Vector2(26, 26)
gear.size_flags_vertical = SIZE_SHRINK_CENTER
gear.add_theme_font_size_override("font_size", 16)
Style.skin_button(gear, Style.box(Color(0, 0, 0, 0), 6), Style.box(Color("#e6dfcd"), 6), Style.box(Color("#e6dfcd"), 6), Style.MUTED, Style.INK)
gear.pressed.connect(func() -> void: main.request_table_settings(table.id))
row.add_child(gear)
else:
var titles := _vbox(3)
titles.size_flags_horizontal = SIZE_EXPAND_FILL
titles.size_flags_vertical = SIZE_SHRINK_CENTER
titles.mouse_filter = MOUSE_FILTER_IGNORE
var title := Style.make_label(Formatter.strip_tags(table.name), Style.display(true), 20, Style.INK)
title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
if table.details.strip_edges() != "":
# A small ⓘ after the name says hovering shows the table's details.
var name_row := _hbox(4)
name_row.mouse_filter = MOUSE_FILTER_IGNORE
title.size_flags_horizontal = SIZE_EXPAND_FILL
name_row.add_child(title)
var mark := Style.make_label(RichText.INFO_MARK, Style.body(true), 12, Color("#9a9483"))
mark.size_flags_vertical = SIZE_SHRINK_CENTER
name_row.add_child(mark)
titles.add_child(name_row)
else:
titles.add_child(title)
var sub := _subtitle()
if sub != "":
var cl := Style.make_label(sub, Style.body(true), 12, Style.MUTED)
cl.mouse_filter = MOUSE_FILTER_IGNORE
cl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
titles.add_child(cl)
row.add_child(titles)
if table.card_mode:
_deck_row = _make_deck_row()
var go := _make_go_button()
if go != null:
row.add_child(go)
if _deck_row != null:
head_box.add_child(_deck_row)
var extra := _make_kind_header(build)
if extra != null:
head_box.add_child(extra)
return header
## The small line under the title in Play mode ("2d6 + dm(@end) · 2 ranges").
func _subtitle() -> String:
match table.kind:
RollTable.KIND_ROLL:
if table.is_ranged():
var n := "%d ranges" % table.entries.size()
if table.is_expr_dice():
var dl := ("Roll " + Describe.dice(table.dice, main.data)) if _plain else table.dice_label()
return "%s · %s" % [dl, n]
return n
if table.collapsed:
return "%d results" % table.entries.size()
RollTable.KIND_CHOICE:
if table.collapsed:
return "%d options" % table.entries.size()
RollTable.KIND_ROUTER:
return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"]
RollTable.KIND_CHECK:
return "Check card"
return ""
## The header button that starts a roll: the die on roll tables, a "?" badge on
## choice cards, a loop arrow on loop cards and "Print" on sheets. Variable
## cards have none.
func _make_go_button() -> Button:
_die_icon = null
if table.kind == RollTable.KIND_VARIABLE:
return null
var b := Button.new()
b.size_flags_vertical = SIZE_SHRINK_CENTER
b.add_theme_font_override("font", Style.display(true))
b.add_theme_font_size_override("font_size", 17)
var left := 10
match table.kind:
RollTable.KIND_CHOICE:
b.text = "?"
b.add_theme_font_size_override("font_size", 20)
b.custom_minimum_size = Vector2(36, 0)
b.tooltip_text = "Ask: %s" % Formatter.strip_tags(table.prompt if table.prompt != "" else table.name)
RollTable.KIND_LOOP:
b.custom_minimum_size = Vector2(38, 32)
b.tooltip_text = "Run %s" % Formatter.strip_tags(table.name)
var icon := Control.new()
icon.mouse_filter = MOUSE_FILTER_IGNORE
icon.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
icon.draw.connect(func() -> void: Icons.draw_loop(icon, icon.size / 2.0 + Vector2(0, -1), 7.0, Style.BRASS, 2.2))
b.add_child(icon)
RollTable.KIND_ROUTER:
b.custom_minimum_size = Vector2(38, 32)
b.tooltip_text = "Route %s: the first case that's true is chosen" % Formatter.strip_tags(table.name)
var fork := Control.new()
fork.mouse_filter = MOUSE_FILTER_IGNORE
fork.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
fork.draw.connect(func() -> void: draw_fork(fork, fork.size / 2.0 + Vector2(0, 0), 8.0, Style.BRASS, 2.2))
b.add_child(fork)
RollTable.KIND_SHEET:
b.text = "Print"
b.add_theme_font_override("font", Style.body_bold(true))
b.add_theme_font_size_override("font_size", 14)
b.tooltip_text = "Print this sheet in the tray"
RollTable.KIND_CHECK:
b.text = check_badge(table)
b.custom_minimum_size = Vector2(38, 0)
b.tooltip_text = "Roll the check: %s\nShift-click to skip the animation" % RulesView.check_line(table, main.data, _plain)
_:
left = 34
var label := "d%d" % table.die_size()
if table.is_expr_dice():
label = table.dice_label() if table.dice_label().length() <= 5 else "Roll"
b.text = label
b.tooltip_text = "Roll %s on %s\nShift-click to skip the animation" % [table.dice_label(), table.name]
var rn := Style.box(Style.FELT, 8, [left, 6, 10, 6])
rn.border_width_bottom = 2
rn.border_color = Style.FELT_DEEP
var rh := rn.duplicate() as StyleBoxFlat
rh.bg_color = Style.FELT_HOVER
var rp := rn.duplicate() as StyleBoxFlat
rp.border_width_bottom = 1
rp.content_margin_top = 7
rp.content_margin_bottom = 5
Style.skin_button(b, rn, rh, rp, Style.BRASS)
if table.kind == RollTable.KIND_ROLL:
var die := DieIcon.new()
die.spinning = _rolling
_die_icon = die
b.add_child(die)
b.resized.connect(func() -> void: die.position = Vector2(8, (b.size.y - 20.0) / 2.0 - 1.0))
b.pressed.connect(func() -> void: main.start_roll(table.id))
return b
## Kind-specific lines under the header: a choice card's question, a loop's
## rule, a variable's name.
func _make_kind_header(_build: bool) -> Control:
match table.kind:
RollTable.KIND_CHOICE:
var v := _vbox(3)
_prompt_label = RichText.label("", 15, Style.INK, true)
_prompt_label.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_prompt_label)
var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"}
var info := str(kinds.get(table.choice, ""))
if table.choice == "number":
info += " · %s to %s" % [RulesView.dice(table.min_expr, main.data, _plain), RulesView.dice(table.max_expr, main.data, _plain)]
if table.save_as != "":
info += " · saves %s" % RulesView.value_name(table.save_as, main.data, _plain)
var l := Style.make_label(info, Style.body(true), 12, Style.MUTED)
l.mouse_filter = MOUSE_FILTER_IGNORE
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
v.add_child(l)
if table.is_dynamic():
var bad := not Roller.lint_options(table).is_empty()
var ol := Style.make_label(RulesView.options_line(table, main.data, _plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
ol.mouse_filter = MOUSE_FILTER_PASS
ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
ol.tooltip_text = "One option per %s; the Chosen row runs for whichever is picked (option, option_label and option_value hold it)" % table.options_description()
v.add_child(ol)
if not _build:
_options_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
_options_label.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_options_label)
return v
RollTable.KIND_LOOP:
var chip := PanelContainer.new()
chip.mouse_filter = MOUSE_FILTER_PASS
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35)))
var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet"
var rule := RulesView.loop_rule(table, main.data, _plain)
var l := Style.make_label(rule, Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK)
l.mouse_filter = MOUSE_FILTER_IGNORE
if rule.length() > 26:
# A long plain rule wraps across the card instead of widening it.
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
chip.size_flags_horizontal = SIZE_FILL
chip.add_child(l)
chip.tooltip_text = err if err != "" else (loop_rule(table) if _plain else "")
return chip
RollTable.KIND_ROUTER:
if not _build:
return null
var rl := Style.make_label("Router · the first true case is chosen", Style.body(true), 12, Style.MUTED)
rl.mouse_filter = MOUSE_FILTER_IGNORE
rl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
return rl
RollTable.KIND_VARIABLE:
var txt := "@%s · %s" % [table.var_name, table.var_type]
if table.is_collection():
txt = "Collection · kept between rolls" if _plain else "@%s_* (board values)" % table.var_name
elif _plain:
txt = "%s · kept between rolls" % table.var_type.capitalize()
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
l.mouse_filter = MOUSE_FILTER_IGNORE
l.tooltip_text = "@" + table.var_name if _plain and not table.is_collection() else ""
if l.tooltip_text != "":
l.mouse_filter = MOUSE_FILTER_PASS
return l
RollTable.KIND_CHECK:
var cl := RichText.label(check_sentence(table, main.data, _plain), 14, Style.INK, true)
cl.mouse_filter = MOUSE_FILTER_IGNORE
return cl
return null
## The check card's "2D" badge (its dice in plain words, "Roll" when long).
static func check_badge(t: RollTable) -> String:
var d := Describe.dice(t.check_dice, null)
return d if d.length() <= 5 else "Roll"
## The check card's sentence under its header, as BBCode: "Roll 2D +
## Strength modifier, need [b]8 or more[/b]" (plain) or "[code]2d6 + dm(@str)
## vs 8+[/code]" style text.
static func check_sentence(t: RollTable, board: TowerBoard, plain: bool) -> String:
var s := RulesView.check_line(t, board, plain)
if not plain:
return "[color=#%s]%s[/color]" % [Style.COPPER_DARK.to_html(false), RichText.plain(s)]
var at := s.rfind(", need ")
if at < 0:
return RichText.plain(s)
return "%s, need [b]%s[/b]" % [RichText.plain(s.substr(0, at)), RichText.plain(s.substr(at + 7))]
## A dashed box under the header naming the card's inputs: "Input Tier ·
## starts at 1" (plain) or "input tier · default 1" (text), one line each.
func _make_inputs_box() -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 10)
wrap.add_theme_constant_override("margin_right", 10)
wrap.add_theme_constant_override("margin_top", 8)
var p := PanelContainer.new()
p.mouse_filter = MOUSE_FILTER_PASS
p.add_theme_stylebox_override("panel", DashedBox.new())
p.tooltip_text = "Values a pipe into this card can pass (\"with\"); a roll that starts here uses the starting values"
wrap.add_child(p)
var v := _vbox(2)
p.add_child(v)
for inp: Dictionary in table.inputs:
var line := RichText.label(input_line(inp, main.data, _plain), 13, Style.MUTED, true)
line.mouse_filter = MOUSE_FILTER_IGNORE
line.set_meta("input_line", true)
v.add_child(line)
wrap.set_meta("inputs_box", true)
return wrap
## One input as BBCode: "Input [b]Tier[/b] · starts at [b]1[/b]".
static func input_line(inp: Dictionary, board: TowerBoard, plain: bool) -> String:
var nm := str(inp.get("name", ""))
var def := str(inp.get("default", "")).strip_edges()
var ink := Style.INK.to_html(false)
if not plain:
return "input [color=#%s]%s[/color] · default [color=#%s]%s[/color]" % [ink, RichText.plain(nm), ink, RichText.plain(def if def != "" else "0")]
var lab := str(inp.get("label", "")).strip_edges()
if lab == "":
lab = Describe.label(nm, board)
var shown := Describe.dice(def, board) if def != "" else "0"
return "Input [color=#%s][b]%s[/b][/color] · starts at [color=#%s][b]%s[/b][/color]" % [ink, RichText.plain(lab), ink, RichText.plain(shown)]
## A dashed rounded outline (the inputs box), since StyleBoxFlat has no
## dashes.
class DashedBox extends StyleBox:
func _init() -> void:
content_margin_left = 9
content_margin_right = 9
content_margin_top = 6
content_margin_bottom = 6
func _draw(to_canvas_item: RID, rect: Rect2) -> void:
var r := rect.grow(-0.5)
var pts := PackedVector2Array([r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y), r.position])
var col := Style.DASH
for i in 4:
var a := pts[i]
var b := pts[i + 1]
var seg_len := a.distance_to(b)
var d := 0.0
while d < seg_len:
var e := minf(d + 5.0, seg_len)
RenderingServer.canvas_item_add_line(to_canvas_item, a.lerp(b, d / seg_len), a.lerp(b, e / seg_len), col, 1.2, true)
d += 9.0
## A fork: one stem splitting into two branches, each ending in a dot (the
## router card's go button). `r` is about half the icon's height.
static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void:
var base := c + Vector2(-r, 0)
var split := c + Vector2(-r * 0.15, 0)
ci.draw_line(base, split, color, width, true)
var up := c + Vector2(r * 0.85, -r * 0.75)
var down := c + Vector2(r * 0.85, r * 0.75)
for tip: Vector2 in [up, down]:
var pts := PackedVector2Array()
for k in 9:
var u := float(k) / 8.0
pts.append(split.bezier_interpolate(split + Vector2(r * 0.5, 0), tip - Vector2(r * 0.45, 0), tip, u))
ci.draw_polyline(pts, color, width, true)
ci.draw_circle(tip, width * 1.25, color)
ci.draw_circle(base, width * 0.9, color)
## "Options from @skill_* · where option_value >= 1" for a dynamic pick card.
static func options_line(t: RollTable) -> String:
var s := "Options from " + t.options_from.strip_edges()
if t.options_where.strip_edges() != "":
s += " · where " + t.options_where.strip_edges()
return s
func _is_pick() -> bool:
return table.kind == RollTable.KIND_CHOICE and table.choice == "pick"
## True for the Chosen row of a dynamic pick card.
func _is_chosen_row(index: int) -> bool:
return index == 0 and table.is_dynamic()
## A router case's condition as shown: "if @str >= 8", or "Otherwise".
static func case_label(e: TableEntry) -> String:
var w := e.when.strip_edges()
return "Otherwise" if w == "" else "if " + w
## "× @answer", "while @alive = 1", "until @done".
static func loop_rule(t: RollTable) -> String:
var e := t.loop_expr.strip_edges()
if e == "":
e = "?"
match t.loop_mode:
"while":
return "while " + e
"until":
return "until " + e
return "× " + e
## Card mode: "4 / 6 left" and a small Reshuffle link under the title.
func _make_deck_row() -> Control:
var h := _hbox(6)
var pad := Control.new()
pad.custom_minimum_size = Vector2(26, 0)
pad.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(pad)
_deck_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
_deck_label.size_flags_vertical = SIZE_SHRINK_CENTER
_deck_label.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(_deck_label)
var b := Button.new()
b.text = "↻ Reshuffle"
b.tooltip_text = "Put every card back in the deck"
b.add_theme_font_override("font", Style.body(true))
b.add_theme_font_size_override("font_size", 12)
b.size_flags_vertical = SIZE_SHRINK_CENTER
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
Style.skin_button(b, n, hv, hv, Style.COPPER, Style.INK)
b.pressed.connect(func() -> void: main.reshuffle_table(table.id))
h.add_child(b)
update_deck()
return h
## Refreshes the cards-left count of a card-mode table.
func update_deck() -> void:
if _deck_label == null or not is_instance_valid(_deck_label):
return
var left := main.cards_left(table.id)
_deck_label.text = "%d / %d left" % [left.x, left.y]
_deck_label.add_theme_color_override("font_color", Style.DANGER_INK if left.x == 0 else Style.MUTED)
func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var h := _hbox(8)
row.add_child(h)
# Loop rows and the Answer row of number/text choices are fixed: no number,
# weight or delete.
var fixed := table.kind == RollTable.KIND_LOOP or (table.kind == RollTable.KIND_CHOICE and table.choice != "pick")
var chosen := _is_chosen_row(index)
var num: Label = null
if build and ranged:
var r := _hbox(2)
r.custom_minimum_size = Vector2(numw, 0)
r.size_flags_vertical = SIZE_SHRINK_CENTER
r.add_child(_range_edit(e, true))
r.add_child(Style.make_label("–", Style.display(true), 15, Style.MUTED))
r.add_child(_range_edit(e, false))
h.add_child(r)
else:
var nl := "" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index))
if table.is_dynamic() and not ranged:
nl = "★" if chosen else str(index)
num = Style.make_label(nl, Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER
if fixed:
num.text = "↻" if table.kind == RollTable.KIND_LOOP and index == 0 else "→"
num.add_theme_font_override("font", Style.body_bold(true))
num.add_theme_font_size_override("font_size", 14)
h.add_child(num)
var text: RichTextLabel = null
if build:
h.add_theme_constant_override("separation", 4)
var col := _vbox(2)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(col)
if table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED)
al.size_flags_horizontal = SIZE_EXPAND_FILL
al.size_flags_vertical = SIZE_SHRINK_CENTER
al.mouse_filter = MOUSE_FILTER_PASS
al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)"
col.add_child(al)
else:
if chosen:
# A caption over the text field, so the field keeps its width.
var cl := Style.make_label("Chosen · runs for the picked option", Style.body_italic(true), 11, Style.COPPER_DARK)
cl.mouse_filter = MOUSE_FILTER_PASS
cl.tooltip_text = "Runs for whichever option from %s is picked: option, option_label and option_value hold it" % table.options_from.strip_edges()
col.add_child(cl)
col.add_child(_text_edit(e, index, chosen))
_add_rule_chips(col, e)
if not ranged and not fixed:
h.add_child(_weight_edit(e))
if not fixed and not chosen:
h.add_child(_mini_button("×", "Delete this result", true, func() -> void: main.delete_entry(table.id, e.id)))
_hook_select(row, e.id)
else:
var col := _vbox(3)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
text = RichText.label(_row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
_add_rule_chips(col, e)
h.add_child(col)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
if ranged and table.has_chances():
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
pct.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(pct)
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
return row
## Build mode: the inline result-text field of a row. Focusing it selects the
## result for the inspector.
func _text_edit(e: TableEntry, index: int, chosen: bool) -> LineEdit:
var edit := LineEdit.new()
edit.text = e.text
if chosen:
edit.placeholder_text = "(the option's name)"
edit.tooltip_text = "The result text. Leave it as Chosen (or empty) to show the picked option's name; {option_label}, {option_value} and {@[option]} work"
edit.size_flags_horizontal = SIZE_EXPAND_FILL
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.custom_minimum_size = Vector2(40, 0)
edit.add_theme_font_size_override("font_size", 15)
if table.kind == RollTable.KIND_LOOP:
edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)]
edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1]
elif table.kind == RollTable.KIND_ROUTER:
edit.placeholder_text = "Result text"
edit.text_changed.connect(func(s: String) -> void:
e.text = s
main.mark_dirty()
)
edit.focus_entered.connect(func() -> void: _select_entry(e.id))
return edit
## The plain chips under a row's text: a pick option's "only if …" and the
## entry's effects ("Luck −1"). Used in Play and Build alike.
func _add_rule_chips(col: VBoxContainer, e: TableEntry) -> void:
if _is_pick() and e.show_if.strip_edges() != "":
var bad := Expr.check(TemplateKit.probe(e.show_if.strip_edges())) != ""
var si := Style.make_label(RulesView.show_if_line(e, main.data, _plain), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
si.mouse_filter = MOUSE_FILTER_PASS
si.tooltip_text = ("only if " + e.show_if.strip_edges()) if _plain else ""
si.set_meta("show_if_line", true)
col.add_child(si)
if e.effects.strip_edges() != "":
col.add_child(_effects_chip(e))
## Build mode: a click on a row (outside its fields) selects the result for
## the inspector.
func _hook_select(row: Control, eid: String) -> void:
row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed:
_select_entry(eid)
)
## Selects a result for the inspector: main.select_result(table id, entry id)
## when Main has it, and the copper bar on this row (cleared on other cards).
func _select_entry(eid: String) -> void:
if main.mode != Main.Mode.BUILD:
return
if main.has_method("select_result"):
main.call("select_result", table.id, eid)
for c: Variant in main.cards.values():
if c is TableCard and c != self:
(c as TableCard).set_selected_entry("")
set_selected_entry(eid)
## Shows the copper selection bar on one result row ("" for none). The
## inspector may call this on every card when its selection changes.
func set_selected_entry(eid: String) -> void:
if _selected_eid == eid:
return
var old := _selected_eid
_selected_eid = eid
for k: String in [old, eid]:
if k != "" and rows.has(k):
_set_row_state(k, RowState.LIT if main.is_entry_lit(table.id, k) else RowState.NORMAL)
func selected_entry() -> String:
return _selected_eid
## Build mode: one router case. The first line is its condition, in plain
## words or as written (edited in the inspector), with move up / down and
## delete; the second is its result text, then its effects chip.
func _make_case_row(e: TableEntry, index: int, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var outer := _hbox(4)
row.add_child(outer)
var num := Style.make_label(str(index + 1), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_BEGIN
outer.add_child(num)
var v := _vbox(3)
v.size_flags_horizontal = SIZE_EXPAND_FILL
outer.add_child(v)
var top := _hbox(4)
v.add_child(top)
var w := e.when.strip_edges()
var bad := w != "" and Expr.check(TemplateKit.probe(w)) != ""
var cond := Style.make_label(RulesView.case_label(e, main.data, _plain), Style.body_bold(true), 14, Style.DANGER_INK if bad else Style.COPPER_DARK)
cond.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
cond.size_flags_horizontal = SIZE_EXPAND_FILL
cond.size_flags_vertical = SIZE_SHRINK_CENTER
cond.mouse_filter = MOUSE_FILTER_PASS
cond.tooltip_text = ("⚠ " + Expr.check(TemplateKit.probe(w))) if bad else (("if " + w) if _plain and w != "" else "Cases are checked top to bottom; the first true one is chosen")
cond.set_meta("case_line", true)
top.add_child(cond)
top.add_child(_mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1)))
top.add_child(_mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1)))
top.add_child(_mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id)))
v.add_child(_text_edit(e, index, false))
_add_rule_chips(v, e)
_hook_select(row, e.id)
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": null, "entry": e, "index": index}
return row
## One outlet of a check card: "8+ Success · the bars give" / "≤7 Failure",
## with the outlet named in green or red. Build edits the text after the name.
func _make_check_row(e: TableEntry, index: int, build: bool, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var h := _hbox(8)
row.add_child(h)
var outs := RulesView.check_outlets(table)
var num := Style.make_label(outs[index] if index < 2 else str(index + 1), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(maxf(numw, 34.0), 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(num)
var col := _vbox(2)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(col)
var text: RichTextLabel = null
if build:
var line := _hbox(6)
col.add_child(line)
var nm := Style.make_label(check_outlet_name(index), Style.body_bold(true), 15, check_outlet_color(index))
nm.size_flags_vertical = SIZE_SHRINK_CENTER
line.add_child(nm)
var edit := _text_edit(e, index, false)
# The outlet name is already shown, so a result text that just repeats
# it ("Success") shows as an empty field with a hint instead.
if e.text.strip_edges() == check_outlet_name(index):
edit.text = ""
edit.placeholder_text = "What happens on a %s (optional)" % check_outlet_name(index).to_lower()
line.add_child(edit)
_add_rule_chips(col, e)
_hook_select(row, e.id)
else:
text = RichText.label(_row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
_add_rule_chips(col, e)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
return row
static func check_outlet_name(index: int) -> String:
return "Success" if index == 0 else ("Failure" if index == 1 else "Result %d" % (index + 1))
static func check_outlet_color(index: int) -> Color:
return Style.OK_INK if index == 0 else Style.NO_INK
func _mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button:
var b := Button.new()
b.text = glyph
b.tooltip_text = tip
b.disabled = not enabled
b.custom_minimum_size = Vector2(22, 22)
b.size_flags_vertical = SIZE_SHRINK_CENTER
b.add_theme_font_size_override("font_size", 16 if glyph == "×" else 13)
Style.skin_button(b, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK if glyph == "×" else Style.INK)
b.add_theme_color_override("font_disabled_color", Color(Style.MUTED, 0.35))
b.pressed.connect(on_press)
return b
## Moves router case `index` up (-1) or down (+1).
func _move_case(index: int, by: int) -> void:
var to := index + by
if to < 0 or to >= table.entries.size():
return
var e := table.entries[index]
table.entries.remove_at(index)
table.entries.insert(to, e)
rebuild()
main.mark_dirty()
## Adds a router case just before the Otherwise case (or at the end). It
## starts as "if false", so it never matches until its condition is written.
func add_case() -> void:
var e := TableEntry.new(TowerBoard.new_id("e"), "New case")
e.when = "false"
var at := table.otherwise_index()
if at < 0 or at != table.entries.size() - 1:
at = table.entries.size()
table.entries.insert(at, e)
table.collapsed = false
rebuild()
main.mark_dirty()
const LOOP_ROWS := ["Each time", "Afterwards"]
## Longest effects summary shown on a chip.
const CHIP_CHARS := 30
const PLAIN_CHIP_CHARS := 38
## Play-mode text of a row: the last rolled (expanded) text when the row is
## lit, otherwise the entry as written with its references shown readably.
## Loop rows read "Each time · …"; a number/text choice's row is its answer;
## a router case leads with its condition, a check outlet with its name.
func _row_text(e: TableEntry) -> String:
var rolled := main.lit_text(table.id, e.id)
var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data)
var muted := Style.MUTED.to_html(false)
if table.kind == RollTable.KIND_LOOP:
var index := table.entries.find(e)
var cap: String = LOOP_ROWS[clampi(index, 0, 1)]
var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == cap:
s = "[b]%s[/b]" % cap
else:
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
elif table.kind == RollTable.KIND_ROUTER:
var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != ""
var label := RulesView.case_label(e, main.data, _plain)
var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(label)]
var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == case_label(e) or plain_text == label or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""):
s = cond
else:
s = "%s\n%s" % [cond, s]
elif table.kind == RollTable.KIND_CHECK:
var index := table.entries.find(e)
var nm := check_outlet_name(index)
var head := "[color=#%s][b]%s[/b][/color]" % [check_outlet_color(index).to_html(false), nm]
var own := Formatter.strip_tags(rolled if rolled != "" else e.text).strip_edges()
s = head if own == "" or own == nm else "%s · %s" % [head, s]
elif table.is_dynamic() and table.entries.find(e) == 0:
var own := Formatter.strip_tags(e.text).strip_edges()
if rolled != "":
s = "[color=#%s]Chosen ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
elif own == "" or own == Roller.CHOSEN:
s = "[i][color=#%s]Chosen: the picked option[/color][/i]" % muted
else:
s = "[color=#%s]Chosen ·[/color] %s" % [muted, s]
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
if rolled != "":
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
else:
s = "[i][color=#%s]Answer[/color][/i]" % muted
if e.details.strip_edges() != "":
s += RichText.info_mark()
return s
## A subtle brass chip summarising an entry's effects: "Luck −1 · Gold + 2D"
## in plain words, "@luck -= 1 · @gold += 2d6" as text. Its tooltip has the
## other form, every statement on its own line.
func _effects_chip(e: TableEntry) -> Control:
var bad := not Effects.validate(TemplateKit.probe(e.effects)).is_empty()
var chip := PanelContainer.new()
chip.mouse_filter = MOUSE_FILTER_PASS
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2)
var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3)
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line))
var summary := RulesView.effects_line(e.effects, main.data, table, _plain)
# Cut long summaries by hand: a clipped Label would collapse to nothing.
summary = RulesView.cut(summary, PLAIN_CHIP_CHARS if _plain else CHIP_CHARS)
var l := Style.make_label(summary, Style.body_bold(true) if _plain else Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
l.mouse_filter = MOUSE_FILTER_IGNORE
chip.add_child(l)
chip.set_meta("effects_chip", summary)
if _plain:
chip.tooltip_text = "\n".join(Effects.split(e.effects))
else:
chip.tooltip_text = "\n".join(Describe.effects(e.effects, main.data, table))
return chip
## A short summary of effect text as written: the first two statements, with
## declared variables by their card's name ("STR = 2d6 · Terms += 1 · +3").
static func effect_summary(text: String, board: TowerBoard) -> String:
var list := Effects.split(text)
var parts := PackedStringArray()
for k in mini(2, list.size()):
var st := Effects.parse_statement(list[k])
if st.has("error"):
parts.append("⚠ " + list[k])
continue
var target: String = st["target"]
var shown := target
if board != null and target.begins_with("@") and not target.ends_with("*"):
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == target.substr(1):
shown = Formatter.strip_tags(t.name).strip_edges()
break
if st["op"] == "reset":
parts.append("reset " + shown)
else:
parts.append("%s %s %s" % [shown, st["op"], st["expr"]])
if list.size() > 2:
parts.append("+%d" % (list.size() - 2))
return " · ".join(parts)
## A sheet card's one row: the rendered template in Play, its editor in Build.
func _make_sheet_row(e: TableEntry, build: bool) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var v := _vbox(6)
row.add_child(v)
if build:
var te := TextEdit.new()
te.text = e.text
te.placeholder_text = "[b]Name[/b] {@name}\nHP {@hp} · Skills {@skill_*}"
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 90)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 14)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER))
te.tooltip_text = "The sheet's template: BBCode with {@var}, {@prefix_*} and {= expr}"
te.text_changed.connect(func() -> void:
e.text = te.text
main.mark_dirty()
)
te.focus_entered.connect(func() -> void: _select_entry(e.id))
v.add_child(te)
var tools := _vbox(2)
if e.effects.strip_edges() != "":
tools.add_child(_effects_chip(e))
var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED)
pv.size_flags_vertical = SIZE_SHRINK_CENTER
tools.add_child(pv)
v.add_child(tools)
_hook_select(row, e.id)
_sheet_label = null
else:
_sheet_label = RichText.label("", 15, Style.INK, true)
_sheet_label.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(_sheet_label, main)
v.add_child(_sheet_label)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
rows[e.id] = row
_row_parts[e.id] = {"num": null, "text": null, "entry": e, "index": 0}
return row
## A variable card's body: its live value, big, and in Build its starting value
## and a reset button.
func _make_variable_body(build: bool) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 14)
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 6)
wrap.add_theme_constant_override("margin_bottom", 10)
var v := _vbox(2)
wrap.add_child(v)
_var_value = Style.make_label("", Style.display(true), 34, Style.INK)
_var_value.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_var_value.mouse_filter = MOUSE_FILTER_PASS
v.add_child(_var_value)
_var_hint = Style.make_label("", Style.body(true), 12, Style.MUTED)
_var_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_var_hint.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_var_hint)
if build:
var h := _hbox(8)
var init := RulesView.dice(table.initial, main.data, _plain) if table.initial.strip_edges() != "" else ""
var start := Style.make_label("Starts at %s" % (init if init != "" else ("0" if table.var_type == "number" else "nothing")),
Style.body(true), 12, Style.MUTED)
start.size_flags_horizontal = SIZE_EXPAND_FILL
start.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(start)
var reset := Button.new()
reset.text = "↺ Reset"
reset.tooltip_text = "Set @%s back to its starting value" % table.var_name
reset.add_theme_font_override("font", Style.body(true))
reset.add_theme_font_size_override("font_size", 12)
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
Style.skin_button(reset, n, hv, hv, Style.COPPER, Style.INK)
reset.pressed.connect(func() -> void: main.reset_variable(table.var_name))
h.add_child(reset)
v.add_child(h)
return wrap
## A collection card's body: its members with their live values (refilled by
## refresh_live()), and in Build "+ Add …", which selects the card so the
## inspector can add a member.
func _make_collection_body(build: bool) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 14)
wrap.add_theme_constant_override("margin_top", 6)
wrap.add_theme_constant_override("margin_bottom", 10)
var v := _vbox(6)
wrap.add_child(v)
_members_box = _vbox(0)
v.add_child(_members_box)
if build:
var add := _footer_button("+ Add " + Describe._singular(Formatter.strip_tags(table.name).strip_edges().to_lower()), Style.INK)
add.size_flags_horizontal = SIZE_FILL
add.tooltip_text = "Add a member in the inspector"
add.set_meta("collection_add", true)
add.pressed.connect(func() -> void:
if main.has_method("select_card"):
main.call("select_card", table.id)
else:
main.request_table_settings(table.id)
)
v.add_child(add)
return wrap
## A collection's members: [{name ("@skill_pilot"), label ("Pilot"), value
## (Variant or null when not set)}], set members first, then members only
## named by the board's rules, each sorted by label.
static func collection_members(t: RollTable, board: TowerBoard, vars: Dictionary) -> Array[Dictionary]:
var out: Array[Dictionary] = []
if t == null or not t.is_collection() or t.var_name == "":
return out
var seen := {}
for v: Dictionary in RollContext.vars_with_prefix(vars, t.var_name + "_"):
var nm := "@" + str(v["name"])
seen[nm] = true
out.append({"name": nm, "label": Describe.label(nm, board), "value": v["value"]})
var named: Array[Dictionary] = []
for kv: Dictionary in Builder.known_values(board):
if str(kv.get("collection", "")) == "@%s_*" % t.var_name and not seen.has(str(kv["name"])):
seen[str(kv["name"])] = true
named.append({"name": str(kv["name"]), "label": str(kv["label"]), "value": null})
var by_label := func(a: Dictionary, b: Dictionary) -> bool: return str(a["label"]).naturalnocasecmp_to(str(b["label"])) < 0
out.sort_custom(by_label)
named.sort_custom(by_label)
out.append_array(named)
return out
func _refresh_members() -> void:
var list := collection_members(table, main.data, main.persistent_vars)
var key := var_to_str(list) + str(_plain)
if key == _members_cache:
return
_members_cache = key
for c in _members_box.get_children():
_members_box.remove_child(c)
c.queue_free()
if list.is_empty():
var none := Style.make_label("No members yet", Style.body_italic(true), 14, Style.MUTED)
none.mouse_filter = MOUSE_FILTER_IGNORE
_members_box.add_child(none)
return
for m: Dictionary in list:
var h := _hbox(8)
h.custom_minimum_size = Vector2(0, 28)
h.set_meta("member", str(m["name"]))
var nl := Style.make_label(str(m["label"]) if _plain else str(m["name"]), Style.body(true), 15, Style.INK)
nl.size_flags_horizontal = SIZE_EXPAND_FILL
nl.size_flags_vertical = SIZE_SHRINK_CENTER
nl.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(nl)
var val: Variant = m["value"]
var vl := Style.make_label("—" if val == null else Expr.format_value(val), Style.display(true), 17, Style.INK if val != null else Style.MUTED)
vl.size_flags_vertical = SIZE_SHRINK_CENTER
vl.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(vl)
_members_box.add_child(h)
## Re-renders the live parts (a variable's value, a sheet, a choice's
## question) from the current variables. Only touches labels whose text
## changed. Main calls it after rolls and edits, never per frame.
func refresh_live() -> void:
if is_instance_valid(_members_box):
_refresh_members()
if is_instance_valid(_var_value):
var d := Roller.variable_display(main.data, main.persistent_vars, table)
var shown := str(d["text"]) if str(d["text"]) != "" else "—"
if _var_value.text != shown:
_var_value.text = shown
var size_px := 34 if shown.length() <= 8 else (24 if shown.length() <= 18 else 17)
_var_value.add_theme_font_size_override("font_size", size_px)
_var_value.add_theme_color_override("font_color", Style.INK if d["set"] else Style.MUTED)
var hint := ""
if str(d["error"]) != "":
hint = "⚠ " + str(d["error"])
elif not d["set"]:
hint = "Not set yet · starts at this"
_var_hint.text = hint
_var_hint.add_theme_color_override("font_color", Style.DANGER_INK if str(d["error"]) != "" else Style.MUTED)
_var_hint.visible = hint != ""
if is_instance_valid(_sheet_label):
var s := RichText.decorate(Roller.render_sheet(main.data, main.persistent_vars, table))
if _sheet_label.text != s:
_sheet_label.text = s
if is_instance_valid(_options_label):
var n := Roller.available_count(table, Roller.live_context(main.data, main.persistent_vars))
var txt := "No options available now" if n == 0 else ("1 option available now" if n == 1 else "%d options available now" % n)
if _options_label.text != txt:
_options_label.text = txt
if is_instance_valid(_prompt_label):
var p: String
if main.mode == Main.Mode.BUILD:
p = RichText.preview(table.prompt, main.data)
else:
p = RichText.decorate(TextExpander.render(table.prompt, Roller.live_context(main.data, main.persistent_vars)))
if _prompt_label.text != p:
_prompt_label.text = p
_prompt_label.visible = table.prompt.strip_edges() != ""
## Weight on a plain table, shown as ×N. Also the number of copies in card mode.
func _weight_edit(e: TableEntry) -> LineEdit:
var edit := LineEdit.new()
edit.text = "×%d" % e.weight
edit.custom_minimum_size = Vector2(34, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 4
edit.tooltip_text = "Weight: how likely this result is, relative to the others (0 = never)"
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 14)
edit.add_theme_color_override("font_color", Style.MUTED)
var commit := func() -> void:
var digits := ""
for ch in edit.text:
if ch >= "0" and ch <= "9":
digits += ch
var w := clampi(digits.to_int(), 0, 999) if digits != "" else e.weight
edit.text = "×%d" % w
if w != e.weight:
e.weight = w
update_deck()
main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit:
var edit := LineEdit.new()
edit.text = str(e.range_lo if is_lo else e.range_hi)
edit.custom_minimum_size = Vector2(40, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 3
edit.tooltip_text = "Range start" if is_lo else "Range end"
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 15)
edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.RULE))
edit.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.COPPER))
var commit := func() -> void:
var v := clampi(edit.text.to_int(), table.min_value(), table.die_size())
if is_lo:
e.range_lo = v
else:
e.range_hi = v
if e.range_lo > e.range_hi:
var tmp := e.range_lo
e.range_lo = e.range_hi
e.range_hi = tmp
edit.text = str(e.range_lo if is_lo else e.range_hi)
_update_warning()
main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
func _make_more_row(numw: float) -> Control:
more_row = PanelContainer.new()
var normal := Style.box(Color(0, 0, 0, 0), 0, [12, 6, 22, 6])
var hover := Style.box(Style.HOVER_ROW, 0, [12, 6, 22, 6])
more_row.add_theme_stylebox_override("panel", normal)
more_row.custom_minimum_size = Vector2(0, 36)
more_row.mouse_filter = MOUSE_FILTER_STOP
more_row.mouse_default_cursor_shape = CURSOR_POINTING_HAND
more_row.tooltip_text = "Show every result"
more_row.mouse_entered.connect(func() -> void: more_row.add_theme_stylebox_override("panel", hover))
more_row.mouse_exited.connect(func() -> void: more_row.add_theme_stylebox_override("panel", normal))
more_row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT and not mb.pressed:
main.toggle_collapse.call_deferred(table.id)
)
var h := _hbox(8)
more_row.add_child(h)
var dots := Style.make_label("…", Style.display(true), 16, Style.MUTED)
dots.custom_minimum_size = Vector2(numw, 0)
dots.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
h.add_child(dots)
_more_label = Style.make_label(_more_text(), Style.body_italic(true), 14, Style.MUTED)
_more_label.size_flags_horizontal = SIZE_EXPAND_FILL
_more_label.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(_more_label)
return more_row
func _more_text() -> String:
var hidden := table.entries.size() - rows.size()
if rows.size() > 0:
return "%d more · show all" % hidden
return "%d %s · show all" % [table.entries.size(), "ranges" if table.is_ranged() else "results"]
func _make_warning() -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_bottom", 10)
var panel := PanelContainer.new()
panel.add_theme_stylebox_override("panel", Style.box(Style.WARN_BG, 6, [9, 6, 9, 6]))
panel.mouse_filter = MOUSE_FILTER_PASS
_warn_label = Style.make_label("", Style.body(true), 13, Style.WARN_INK)
_warn_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
panel.add_child(_warn_label)
wrap.add_child(panel)
return wrap
func _update_warning() -> void:
var problems := table.range_problems()
var lines := PackedStringArray()
for item: Dictionary in Roller.lint_router(table):
lines.append(str(item["message"]))
for item: Dictionary in Roller.lint_options(table):
lines.append(str(item["message"]))
if not lines.is_empty():
problems = ("%s\n" % problems if problems != "" else "") + "\n".join(lines)
_warn_label.text = problems
_warn_panel.visible = problems != ""
func _make_footer(ranged: bool) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 10)
wrap.add_theme_constant_override("margin_bottom", 10)
var h := _hbox(8)
wrap.add_child(h)
# Loops, sheets, variables and number/text choices have fixed rows.
if table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and table.choice == "pick"):
var label := "+ Add range" if ranged else ("+ Add option" if table.kind == RollTable.KIND_CHOICE else "+ Add result")
var add := _footer_button(label, Style.INK)
add.pressed.connect(func() -> void: main.add_entry(table.id))
h.add_child(add)
elif table.kind == RollTable.KIND_ROUTER:
var addc := _footer_button("+ Add case", Style.INK)
addc.tooltip_text = "Add a case before Otherwise"
addc.pressed.connect(add_case)
h.add_child(addc)
var spacer := Control.new()
spacer.size_flags_horizontal = SIZE_EXPAND_FILL
spacer.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(spacer)
var del := _footer_button("Delete", Style.DANGER_INK)
del.tooltip_text = "Delete this table"
del.pressed.connect(func() -> void: main.delete_table(table.id))
h.add_child(del)
return wrap
func _footer_button(text: String, hover_color: Color) -> Button:
var b := Button.new()
b.text = text
b.add_theme_font_size_override("font_size", 14)
var normal := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, Style.DASH)
var hover := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, hover_color if hover_color != Style.INK else Style.MUTED)
Style.skin_button(b, normal, hover, hover, Style.MUTED, hover_color)
return b
func _skin_scrollbar(bar: VScrollBar) -> void:
var track := Style.box(Color(0, 0, 0, 0), 3, [3, 0, 3, 0])
var grab := Style.box(Color(0, 0, 0, 0.22), 3, [3, 0, 3, 0])
var grab_hi := Style.box(Color(0, 0, 0, 0.35), 3, [3, 0, 3, 0])
bar.add_theme_stylebox_override("scroll", track)
bar.add_theme_stylebox_override("scroll_focus", track)
bar.add_theme_stylebox_override("grabber", grab)
bar.add_theme_stylebox_override("grabber_highlight", grab_hi)
bar.add_theme_stylebox_override("grabber_pressed", grab_hi)
# ---------- State ----------
func _set_row_state(eid: String, state: RowState) -> void:
if not rows.has(eid):
return
var k := int(state) + (3 if eid == _selected_eid else 0)
(rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[k])
var parts: Dictionary = _row_parts[eid]
var num: Label = parts["num"]
if num:
num.add_theme_color_override("font_color", Style.INK if state == RowState.LIT else Style.MUTED)
var text: RichTextLabel = parts["text"]
if text:
RichText.set_fonts(text, 16, true, state == RowState.LIT)
## Re-renders a Play-mode row's text (it shows the rolled text while lit).
func _update_row_text(eid: String) -> void:
var parts: Dictionary = _row_parts.get(eid, {})
var text: RichTextLabel = parts.get("text")
if text:
var want := _row_text(parts["entry"])
if text.text != want:
text.text = want
func _apply_style() -> void:
var s := _style_normal
if _drop_target:
s = _style_drop
elif _rolling:
s = _style_rolling
elif _selected:
s = _style_selected
elif _dragging:
s = _style_dragging
add_theme_stylebox_override("panel", s)
## Build-mode selection (Main.selection): a copper ring around the card.
func set_selected(on: bool) -> void:
if _selected != on:
_selected = on
_apply_style()
func is_selected() -> bool:
return _selected
func _shrink() -> void:
size = Vector2(card_width(), 0)
func card_width() -> float:
return BUILD_WIDTH if main.mode == Main.Mode.BUILD else WIDTH
func set_rolling(on: bool) -> void:
_rolling = on
if is_instance_valid(_die_icon):
_die_icon.spinning = on
_apply_style()
func set_drop_target(on: bool) -> void:
_drop_target = on
_apply_style()
func flick_random() -> void:
clear_flick()
if rows.is_empty():
return
var keys := rows.keys()
_flick_id = keys[main.rng.randi_range(0, keys.size() - 1)]
_set_row_state(_flick_id, RowState.FLICK)
func clear_flick() -> void:
if _flick_id != "":
_set_row_state(_flick_id, RowState.LIT if main.is_entry_lit(table.id, _flick_id) else RowState.NORMAL)
_flick_id = ""
func set_more_text(text: String) -> void:
if _more_label:
_more_label.text = text
## Updates highlights after a roll. Collapsed cards rebuild so the rolled result shows.
func refresh_lit() -> void:
update_deck()
if is_collapsed():
var want: Array = []
for e in table.entries:
if main.is_entry_lit(table.id, e.id):
want.append(e.id)
if want != rows.keys():
rebuild()
elif _more_label:
_more_label.text = _more_text()
return
for eid in rows:
_update_row_text(eid)
_set_row_state(eid, RowState.LIT if main.is_entry_lit(table.id, eid) else RowState.NORMAL)
## Scrolls a long list so the given result sits in the middle.
func reveal(eid: String) -> void:
if list_scroll == null or not rows.has(eid):
return
var row: Control = rows[eid]
list_scroll.scroll_vertical = int(row.position.y + 6.0 - list_scroll.size.y / 2.0 + row.size.y / 2.0)
func hidden_has_pipes() -> bool:
for e in table.entries:
if not rows.has(e.id) and (not e.pipes.is_empty() or not main.ref_targets_for(e).is_empty()):
return true
return false
# ---------- Geometry (world coordinates) ----------
func inlet_point() -> Vector2:
return Vector2(position.x, position.y + INLET_Y)
## Where a pipe leaves this card for an entry: its row, or the "more" row when the
## entry is hidden in a collapsed card. Rows scrolled out of a long list clamp to
## its edge. Returns {} if there's nowhere to anchor.
func anchor_for(eid: String) -> Dictionary:
var row: Control = rows.get(eid, more_row)
if row == null or not row.is_inside_tree():
return {}
var to_world := main.board.world.get_global_transform().affine_inverse()
var r := row.get_global_rect()
var y := (to_world * (r.position + Vector2(0, r.size.y / 2.0))).y
var shown := true
if list_scroll != null and rows.has(eid):
var sr := list_scroll.get_global_rect()
var top := (to_world * sr.position).y + 14.0
var bottom := (to_world * sr.end).y - 14.0
shown = y >= top - 4.0 and y <= bottom + 4.0
y = clampf(y, top, bottom)
return {"pos": Vector2(position.x + size.x, y), "visible": shown}
# ---------- Input ----------
func _gui_input(ev: InputEvent) -> void:
# Clicks on the card body shouldn't pan the board; the wheel still passes through.
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
accept_event()
## Dragging the header moves the card (and, in Build, every selected card).
## In Build, Ctrl- or Shift-click adds the card to the selection or takes it
## out; dropping a card into a group frame adds it to that group (Main).
func _on_header_input(ev: InputEvent, header: Control) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
if mb.pressed:
main.details().hide_for()
var build := main.mode == Main.Mode.BUILD
if build and (mb.ctrl_pressed or mb.shift_pressed or mb.meta_pressed):
main.toggle_selected(table.id)
header.accept_event()
return
if build and not main.is_selected(table.id):
main.clear_selection()
_dragging = true
_drag_offset = main.board.world_mouse() - position
get_parent().move_child(self, -1)
main.begin_card_drag(self)
elif _dragging:
_dragging = false
main.end_card_drag(self)
else:
main.mark_dirty()
_apply_style()
header.accept_event()
return
var mm := ev as InputEventMouseMotion
if mm and _dragging:
var p := main.board.world_mouse() - _drag_offset
main.drag_card(self, Vector2(maxf(10.0, roundf(p.x)), maxf(10.0, roundf(p.y))))
header.accept_event()