TableTower/docs/ARCHITECTURE.md

213 lines
15 KiB
Markdown
Raw Normal View History

# TableTower — Architecture and Features
Read on demand (not every session). Status and plan: `docs/DESIGN.md`.
## 2. Feature summary (all on `main`)
**Board and rolling**
- **Cards and pipes.** Cards show their numbered results and a die button. Drag from a
result's ● onto another card to lay a pipe. A result can pipe into several cards (fan-out),
on ranged and weighted tables alike; one roll runs them all.
- **Rolling.** Results flicker and land, and a bead travels each pipe. **Shift-click** fast-rolls with no animation.
- **Play / Build modes.** Collapse a card, or every table from **View ▾**. Pan, zoom (8%–150%) with the
**− 90% ▾ +** control (the percentage opens Fit board, Zoom to 100% and the minimap), minimap (M).
- **Top bar.** Search (icon, Ctrl+F), **View ▾** (rules as Plain words or Rule text, Collapse/Expand
all tables, Striped rows, Minimap), **Help ▾** and the zoom control. Build adds undo/redo, + Card ▾
and Board ▾ (Test board, Reset sample, Pack collapsed groups, import, export).
- **Striped rows.** Every second result row on a card is tinted (`Style.STRIPE`); lit, flicker and
selection paint over it. On by default; the `striped_rows` local setting.
- **Help.** Help ▾ lists the topics; F1 opens the window. Text in `help/topics.txt` (a small markup,
see `HelpDialog`), included in exports via the preset's include filter.
- **Table types.** Weighted plain tables, ranged dice tables (`1d100`, `2d6`, any
expression such as `2d6 + dm(@str)`), and card mode (a deck with no repeats, with Reshuffle).
- **Roll modifiers** (`dice_mod`, LOGIC.md §3c). A ranged table adds a modifier such as `@luck` to
its dice. Ranges may run past the dice (−3 to 24 on a d20); totals past the ends use the end
result. The card shows chances for the modifier's value now, and Why says "+3 for Luck".
- **Pipe options.** A count (a number or an expression), "save as", **Only if** conditions,
and **Otherwise**. A result's conditions and counts are evaluated once, as a snapshot,
before any pipe runs.
- **Text in results.** `[[Table]]` inline references, `{@var}` / `{hero}` values, and BBCode formatting.
- **The result tray** shows the chain as chips with effect lines, a sheet headline,
Earlier rolls, a Variables tab, Copy (text, BBCode, with details) and **Why this?** on each step.
- **Resizable panels.** Drag the tray's top edge or the inspector's left edge (double-click for the
default). The sizes are kept in local settings (`tray_height`, `inspector_width`). Every part of
the tray scrolls inside it.
**Logic cards** (`docs/LOGIC.md`)
- **Choice:** "Which option" (pick, with Random), "How many" (a number) or "Open
ended" (text). The pop-up can be minimized, and its options preview where they lead.
- **Loop:** repeat N times, while a condition holds, or until it does. Then "Afterwards".
- **Router:** if / else if / otherwise cases; the first true case runs.
- **Check:** roll + modifier against a target, with Success and Failure outlets. Sets `nat`, `total` and `effect`.
- **Variable** cards (with a starting value) and **Collection** cards (e.g. Skills, whose members are `@skill_*`).
- **Sheet:** a live template, e.g. a character sheet.
- **Changes** (stored as `effects`) on any result: `@x = …`, `+=`, `-=`, `reset @prefix_*`, list add/remove, and `@[expr]` indirect names.
- **Dynamic pick options** from a collection or list (`options_from`, `options_where`), plus `show_if` on any option.
- **Card inputs:** a card declares inputs, and pipes pass values (`with`), scoped to that pipe's part of the roll.
- **A 10,000-action limit** per roll. The roller uses an explicit stack, so long loops don't overflow.
**Building** (Build mode)
- **The inspector,** docked right. It edits the selected card, result or pipe:
- effects as rows ("[Subtract] [1] from [Luck]")
- a roll or check modifier as "[Add ▾] [Luck ▾]" (ModifierEditor)
- conditions as rows ("[Luck] [is at least] [2]", with and/or)
- pipe inputs, Otherwise, count and saves-as
- kind-specific card fields
- a value picker with "+ New value…"
- "Edit as text" everywhere
- **Plain / Text** in View ▾ → Rules.
- **Card ⋯ menu** (Build): Table settings…, Save as template…, Collapse, Delete table. A row's ×
shows only on hover, keyboard focus or when the row is selected.
- **Undo/redo** (Ctrl+Z, Ctrl+Shift+Z / Ctrl+Y, or ↶ ↷) for every board edit. Typing and dragging merge into one step.
- Collapse/expand isn't undoable.
- Rolls, variables and decks aren't undoable.
- Collection members aren't undoable either.
- **Group cards.** Frames that collapse whole blocks. Ctrl/Shift-click or Ctrl-drag to
select, Ctrl+G to group, then drag cards in or out, rename, ungroup or delete. Board ▾ → Pack collapsed groups.
- **Templates.** Save a card, group or selection, with `{$param}` fill-ins. Insert from
"+ Card ▾ → From template…". The library is in `user://templates/`, and generic built-ins are in `templates/`:
skill check (a Check card, 2d6 + modifier vs target), ask-and-repeat, pick menu, counter
and simple sheet.
- **Search** (button or Ctrl+F) jumps to cards, opens groups and flashes the card.
- **Test board** (Board ▾): hundreds of random rolls plus static checks. It reports
errors, dead ends, unreached cards and lint, and clicking an item jumps to the card.
- **Collections** (switcher in the top bar). Import and export via Board ▾: TableTower
JSON, JSON Canvas, GraphML (both ways), plus Mermaid and DOT (export only).
## 3. Architecture
```
core/ engine, no UI, testable headless
tower_board.gd a collection (tables, groups), JSON, format v2 + migration
roll_table.gd a card: kind, dice, entries, logic fields, factories (RollTable.create)
roll_range.gd a ranged card's numbers: span, natural range, labels, chances, the roll
modifier (shared with check cards), range problems
table_entry.gd a result: text, weight, range, effects, pipes (+count/save/when/otherwise/with), show_if, when
roller.gd coroutine roller with an explicit stack (_chain loop, roll/pipe steps,
apply_starting_values) plus delegators to its parts:
roll_pipes.gd pipe_plan snapshot, card inputs (`with`)
roll_cards.gd weighted picks, router, check, loops
roll_choice.gd choice requests, dynamic options, show_if, asking
roll_tree.gd flatten, step lookups, lit keys, pipe/entry keys
roll_lint.gd lint_*, endless_cycles
roll_context.gd per-roll state: chain and board variables, prompt hook, actions, depth
expr.gd / effects.gd expression evaluation (Godot Expression + rewrites), effect statements
text_expander.gd [[refs]], {vars}, {@prefix_*}, {= expr}; formatter.gd: BBCode safety and stripping
dice.gd / deck_state.gd dice parsing and distributions, card-mode decks
describe.gd rules → plain words, labels, why sentences; kind_label / choice_label
(the only place card-kind and choice-type names are defined)
builder.gd effect/condition models ↔ text, known_values
board_tester.gd simulation and static checks (used by the Test board UI and the CLI)
library_store.gd / state_store.gd collections on disk / local state (decks, variables, history, settings)
table_group.gd, template_kit.gd, template_library.gd, sample_board.gd
io/ json_io (canonical + import), canvas_io, graphml_io, mermaid_exporter, dot_exporter
ui/ main.gd: the app shell (shared fields, _ready, cards, collapse, input) with one-line
delegators to RefCounted helpers that hold `m: Main`:
main_cli (every CLI/screenshot flag), main_rolling, main_editing, main_groups,
main_history (undo), main_navigation (search/focus/minimap/arrange),
main_top_bar (bar, toast, endless-loop chip), main_state (decks, variables),
main_collections, main_templates, main_inspector
top bar parts: view_menu (View ▾), zoom_control, help_menu + help_dialog
table_card.gd + table_card_{header,rows,editing,value,text}.gd
result_tray.gd + tray_chips, tray_text, earlier_rolls
table_settings_dialog.gd + table_settings_rules (validation/apply), settings_kind_fields
inspector_card (card fields) + inspector_roll (roll dice and modifier);
modifier_editor (the plain modifier builder); panel_splitter (drag handles)
and: board_view, card_layer, pipe_layer, port_layer, group_layer, group_card, minimap,
why_popover, choice_dialog, table_preview, details_popup, inspector*, value_picker,
rules_view, search_panel, board_search, board_layout, edit_history, test_board_dialog,
template_*, io_menu, collection_switcher, variables_panel, modal_card, rich_text, style
help/ topics.txt: the Help window's text (# Title per topic)
tools/ simulate_board.gd (headless simulator CLI), test_window.sh (background test windows)
tests/ test_*.gd: 27 headless suites
templates/ built-in templates · examples/logic_demo.json (original demo board) · assets/fonts (OFL)
```
**Key implementation facts**
- **Lazy cards.** Cards hidden inside collapsed groups aren't built, so
`main.card_for(id)` can return null. Pipe, port and card layers redraw only when something changes.
- **Undo** (`ui/edit_history.gd`) snapshots each table and group separately, sharing unchanged ones.
- **Prompts.** The roller awaits `ctx.prompt` for choices, and the UI shows progress before each pop-up.
- **Rules display.** The UI reads plain or text mode through `RulesView` and `main.rules_plain()`,
and `main.rules_view_changed` signals a switch.
- **Shared builders, use them rather than copying:** `Style.menu_button`, `Style.font_colors`,
`Style.field_colors`, `TableCard.vbox/hbox`, `InspectorKit.*` (fields, `focused_tag`/`refocus`,
`as_text_link`), `Main.file_dialog`/`export_dialog`, `JsonIO.entry_line`/`finish_import`.
- **Keep files small.** Aim for under ~400 lines; split by area into helper objects as above.
Next candidates, all 530–730 lines:
- core: describe (731, the largest now), roll_table, expr
- ui: choice_dialog, inspector_card, inspector, main, edit_history
- io: json_io
## 3b. Modules added 2026-11-10
- **Theme:** `ui/style.gd` (tokens, `fill_texture`, `panel_box`), `ui/theme_store.gd`,
`ui/builtin_themes.gd`, `ui/theme_dialog.gd`, `ui/fill_editor.gd`, `ui/color_choice.gd`.
- **Card visuals and input:** `ui/card_frame.gd` (border + shader), `ui/card_grip.gd` (resize),
`ui/card_shield.gd` (zoomed out), `ui/sparkles.gd`; TableCard helpers `table_card_skin/input/
geometry/list/kind_rows.gd` (next to header/rows/editing/value/text).
- **Menus and selection:** `ui/actions.gd` (all menus), `ui/main_selection.gd` (groups in the
selection), `ui/main_layout.gd` (Main's layout, saving, mode, input; Main keeps delegators).
- **Lists and phones:** `ui/list_view.gd`, `ui/list_tree.gd`, `ui/list_order.gd`,
`ui/mobile_layout.gd`, `ui/touch_input.gd`.
- **Book and pictures:** `core/book_page.gd`, `core/board_images.gd`, `ui/book_panel.gd`,
`ui/page_editor.gd`, `ui/image_field.gd`. `TowerBoard` has `book`, `images`, nesting helpers
(`tables_in`, `groups_in`, `hidden_by`, `set_group_parent`).
- **Roll features:** `core/roll_combine.gd` (Roller.OP_COMBINE), `core/roll_costs.gd`, pause in
`core/roller.gd` (OP_PAUSE) + `ui/roll_pauses.gd`, `RollRange.limit` (floor/ceiling),
`ui/batch_roll.gd`. Each roll's token lives in a holder dict in MainRolling so a paused roll
can be revived.
- **Output and help:** `ui/sheet_export.gd`, `core/demo_spreads.gd`, `ui/demo_mode.gd`.
- **Splits (audit):** `ui/inspector_result/thread/sync.gd`, `ui/inspector_threads.gd`,
`core/describe_cards.gd`, `core/describe_why.gd`, `io/json_canon.gd`, `io/json_links.gd`,
`ui/choice_preview/chrome/option_row.gd`, `ui/edit_labels.gd`.
- **New JSON keys** (all optional; JsonCanon passes them through): spread `book`, `images`;
group `parent`; table `color`, `w`, `list_h`, `roll_floor`, `roll_ceiling`, `deck_empty_text`;
result `page`, `image`, `cost {value, amount}`; thread `color`, `combine`, `pause`.
## 3c. Modules added 2026-11-10 (book tables)
- **Scales:** `core/scales.gd` (store/read step names), `core/expr_base.gd` (Expression's base
instance, split out of `expr.gd`: `_lit` turns a step name beside a scale into its number,
`toward()`), `Effects._assign_scale`, `RollContext.scale_steps`.
- **Columns:** `core/roll_columns.gd` (fills the other columns after a roll), `RollTable.columns`
/ `column_rolls` / `cell_text`, `TableEntry.cells`.
- **Thread dice and rerolls:** `TableEntry.pipe_dice` / `pipe_reroll`, `RollCards.pick_for`,
`RollRange.roll_value(…, dice_text)`.
- **Checks and IO:** `core/roll_lint_book.gd`; `core/roll_table_io.gd` (RollTable to/from JSON,
split out of `roll_table.gd`). JSON keys: table `columns`, `column_rolls`, `steps`; result
`cells`; thread `dice`, `reroll`. Spec: LOGIC.md §3e, §3f, §5.4.
## 4. Data and storage
- **Collections:** `user://collections/<id>.json`, format_version 2 (`{format_version, id,
name, tables, groups?}`). On Linux that's `~/.local/share/godot/app_userdata/TableTower/`.
- **Local state** (never exported): `user://state/state.json` holds decks, board
variables, history (cap 50) and settings (`last_collection`, minimap, inspector collapsed,
`rules_view`, `striped_rows`). Templates live in `user://templates/`.
- **Installed collections today:** `my-tables` (migrated from the old `board.json`, backed
up as `board.json.bak`) and `traveller-chargen`. Backups of earlier Traveller boards are
`traveller-chargen.before-*.json.bak` in the app data folder.
## 7. Known gaps and bugs
- **Only one pipe per target per result.** Pipes are keyed by target id, so the mockup's
two pipes into Loot (Tier 3 "only if", Tier 1 "otherwise") can't be built. Lifting this
needs pipe ids in the model, the file format, the UI keys (`tid:eid>to`) and undo.
- Long pipe labels are cut with "…" in narrow gaps, and labels draw behind cards.
- The Why pop-over opens above the tray and can cover the bottom of the board.
- Not tried by hand yet: all of this was verified with headless tests and screenshots
only. A hands-on playtest with a checklist is overdue.
- The Linux export preset exists, but the 4.7.2 export templates aren't installed. They're a
large download and the user hasn't approved it. There are no Windows or Mac presets.
- Loading a big board with every group expanded takes about 5 s (building `TableCard` nodes).
- Group frames are rectangles, so a non-member card lying inside one looks like a member.
Pipes into a collapsed group can't be clicked.
- Groups aren't kept in the Canvas and GraphML exports. Logic keys survive only in TableTower JSON.
- `{= }` dice in live sheet and variable displays re-roll when the display refreshes.
- The simulator and Test board list results that only a modifier reaches as "never chosen" when
the modifier stays small in the runs (the demo's luck-only vault, for example).
- **Not yet looked into: Coderstanding warnings.**
- Signals emitted but never connected: `ModalCard.closed`, `SearchPanel.closed`.
- A possible wrong handler in `ModalCard.segmented` (`pressed` → `on_change`; probably a
false positive from a bound callable).
- Large class cycles in ui/ (expected from the `main` back-references).