diff --git a/README.md b/README.md index 1adf644..8181f6b 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,58 @@ # TableTower -A Godot 4.7 project. +Random roll tables for tabletop games, built as a board of table cards joined by pipes. +Click the die on any table and the result flows down its pipes into the next table. -## Getting started +Made with Godot 4.7 (GDScript). -Open `project.godot` with Godot 4.7.x. +## Running + +Open `project.godot` in Godot 4.7.x and press Play, or from a terminal: + +```sh +godot --path . +``` + +## Using it + +- **Play mode** is for the game table. Click a die to roll. The results flicker, one lands, + and a bead runs down any pipe into the next table. The tray at the bottom shows the whole + chain and the last few rolls. +- **Build mode** is for setting up tables. Edit names and results in place, add or delete + results and tables, and drag a card by its header. Drag from a result's ● onto another + table to lay a pipe. Click a pipe to remove it. Deletions can be undone from the toast. +- **Ranged tables** (like *Wilderness Travel*) roll a d100 where each range's size sets its + chance. Each range takes one pipe; laying a new one replaces the old. +- **Collapsing:** the arrow beside a table's name collapses it. A collapsed table still shows + its last result. **Collapse all / Expand all** in the top bar does every table at once. +- **Moving around:** drag the felt to pan, use the mouse wheel to scroll (Shift for sideways), + Ctrl+wheel or pinch to zoom, and **Fit** to see every table. + +The board saves automatically to `user://board.json` +(on Linux, `~/.local/share/godot/app_userdata/TableTower/board.json`). +**Reset sample** in Build mode restores the example tables. + +## Layout + +``` +core/ data model and roller (no UI; testable headless) +ui/ main scene, board view, cards, pipes, ports, result tray, styles +assets/ fonts (Rokkitt and Atkinson Hyperlegible, both SIL OFL) +tests/ headless checks +docs/ design document +``` + +## Tests + +```sh +godot --headless --path . -s res://tests/test_roller.gd +``` + +## Screenshots from the command line + +```sh +godot --path . -- --screenshot=/tmp/board.png [--build] [--expand-all] [--collapse-all] \ + [--roll=wilderness] [--shot-delay=0.75] +``` + +This uses the sample board and doesn't save anything. diff --git a/assets/fonts/AtkinsonHyperlegible-Bold.ttf b/assets/fonts/AtkinsonHyperlegible-Bold.ttf new file mode 100644 index 0000000..ca3f613 Binary files /dev/null and b/assets/fonts/AtkinsonHyperlegible-Bold.ttf differ diff --git a/assets/fonts/AtkinsonHyperlegible-Bold.ttf.import b/assets/fonts/AtkinsonHyperlegible-Bold.ttf.import new file mode 100644 index 0000000..5f769db --- /dev/null +++ b/assets/fonts/AtkinsonHyperlegible-Bold.ttf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dtio22kq04sn1" +path="res://.godot/imported/AtkinsonHyperlegible-Bold.ttf-88b8e4bce39666c760f25dd9a57aebce.fontdata" + +[deps] + +source_file="res://assets/fonts/AtkinsonHyperlegible-Bold.ttf" +dest_files=["res://.godot/imported/AtkinsonHyperlegible-Bold.ttf-88b8e4bce39666c760f25dd9a57aebce.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/assets/fonts/AtkinsonHyperlegible-Italic.ttf b/assets/fonts/AtkinsonHyperlegible-Italic.ttf new file mode 100644 index 0000000..9ee6818 Binary files /dev/null and b/assets/fonts/AtkinsonHyperlegible-Italic.ttf differ diff --git a/assets/fonts/AtkinsonHyperlegible-Italic.ttf.import b/assets/fonts/AtkinsonHyperlegible-Italic.ttf.import new file mode 100644 index 0000000..d9e20e0 --- /dev/null +++ b/assets/fonts/AtkinsonHyperlegible-Italic.ttf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dx0nfkms7uiws" +path="res://.godot/imported/AtkinsonHyperlegible-Italic.ttf-14142505a6f176216bb2ba0d516c771b.fontdata" + +[deps] + +source_file="res://assets/fonts/AtkinsonHyperlegible-Italic.ttf" +dest_files=["res://.godot/imported/AtkinsonHyperlegible-Italic.ttf-14142505a6f176216bb2ba0d516c771b.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/assets/fonts/AtkinsonHyperlegible-Regular.ttf b/assets/fonts/AtkinsonHyperlegible-Regular.ttf new file mode 100644 index 0000000..b3cc420 Binary files /dev/null and b/assets/fonts/AtkinsonHyperlegible-Regular.ttf differ diff --git a/assets/fonts/AtkinsonHyperlegible-Regular.ttf.import b/assets/fonts/AtkinsonHyperlegible-Regular.ttf.import new file mode 100644 index 0000000..f74522d --- /dev/null +++ b/assets/fonts/AtkinsonHyperlegible-Regular.ttf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dtl7o3ylmr57k" +path="res://.godot/imported/AtkinsonHyperlegible-Regular.ttf-b1b81e810f770645a511deee33c11e03.fontdata" + +[deps] + +source_file="res://assets/fonts/AtkinsonHyperlegible-Regular.ttf" +dest_files=["res://.godot/imported/AtkinsonHyperlegible-Regular.ttf-b1b81e810f770645a511deee33c11e03.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/assets/fonts/OFL-AtkinsonHyperlegible.txt b/assets/fonts/OFL-AtkinsonHyperlegible.txt new file mode 100644 index 0000000..2befc89 --- /dev/null +++ b/assets/fonts/OFL-AtkinsonHyperlegible.txt @@ -0,0 +1,92 @@ +Copyright 2020 Braille Institute of America, Inc. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/OFL-Rokkitt.txt b/assets/fonts/OFL-Rokkitt.txt new file mode 100644 index 0000000..ec245f9 --- /dev/null +++ b/assets/fonts/OFL-Rokkitt.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Rokkit Project Authors (https://github.com/googlefonts/RokkittFont) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/Rokkitt-Variable.ttf b/assets/fonts/Rokkitt-Variable.ttf new file mode 100644 index 0000000..689edc4 Binary files /dev/null and b/assets/fonts/Rokkitt-Variable.ttf differ diff --git a/assets/fonts/Rokkitt-Variable.ttf.import b/assets/fonts/Rokkitt-Variable.ttf.import new file mode 100644 index 0000000..c96a44b --- /dev/null +++ b/assets/fonts/Rokkitt-Variable.ttf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://5yn578714rcd" +path="res://.godot/imported/Rokkitt-Variable.ttf-14be251d11ed80b2da988301fba43b0d.fontdata" + +[deps] + +source_file="res://assets/fonts/Rokkitt-Variable.ttf" +dest_files=["res://.godot/imported/Rokkitt-Variable.ttf-14be251d11ed80b2da988301fba43b0d.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/core/roll_table.gd b/core/roll_table.gd new file mode 100644 index 0000000..16c774c --- /dev/null +++ b/core/roll_table.gd @@ -0,0 +1,125 @@ +class_name RollTable +extends RefCounted +## A named list of entries placed on the board. +## +## Plain tables roll one die face per entry (6 entries = d6). If any entry has a +## range, the table becomes a ranged dice table (d100 by default) where the size +## of each range sets its chance. + +var id: String = "" +var name: String = "" +var position: Vector2 = Vector2.ZERO +var collapsed: bool = false +## Die size for ranged tables. 0 means the default (100). +var die: int = 0 +var entries: Array[TableEntry] = [] + + +func _init(p_id: String = "", p_name: String = "") -> void: + id = p_id + name = p_name + + +func is_ranged() -> bool: + for e in entries: + if e.has_range: + return true + return false + + +func die_size() -> int: + if is_ranged(): + return die if die > 0 else 100 + return entries.size() + + +## Formats a die value the way printed tables do: d100 values are two digits +## and 100 is written "00". +func fmt(value: int) -> String: + if die_size() == 100: + return "00" if value == 100 else "%02d" % value + return str(value) + + +func num_label(e: TableEntry, index: int) -> String: + if not e.has_range: + return fmt(index + 1) + if e.range_lo == e.range_hi: + return fmt(e.range_lo) + return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)] + + +func chance(e: TableEntry) -> float: + return float(e.span()) / float(maxi(1, die_size())) + + +func entry_index_for(value: int) -> int: + for i in entries.size(): + var e := entries[i] + if e.has_range and value >= e.range_lo and value <= e.range_hi: + return i + return -1 + + +func find_entry(eid: String) -> TableEntry: + for e in entries: + if e.id == eid: + return e + return null + + +## Describes gaps and overlaps in a ranged table, or "" when the ranges are clean. +func range_problems() -> String: + if not is_ranged(): + return "" + var n := die_size() + var hits := PackedInt32Array() + hits.resize(n + 1) + for e in entries: + if e.has_range: + for v in range(maxi(1, e.range_lo), mini(n, e.range_hi) + 1): + hits[v] += 1 + var gaps := _runs(hits, n, func(h: int) -> bool: return h == 0) + var overlaps := _runs(hits, n, func(h: int) -> bool: return h > 1) + var parts := PackedStringArray() + if gaps != "": + parts.append("No result for %s." % gaps) + if overlaps != "": + parts.append("%s matches more than one result." % overlaps) + return " ".join(parts) + + +func _runs(hits: PackedInt32Array, n: int, test: Callable) -> String: + var out := PackedStringArray() + var start := -1 + for v in range(1, n + 2): + var on: bool = v <= n and test.call(hits[v]) + if on and start < 0: + start = v + elif not on and start >= 0: + out.append(fmt(start) if start == v - 1 else "%s–%s" % [fmt(start), fmt(v - 1)]) + start = -1 + return ", ".join(out) + + +func to_dict() -> Dictionary: + var list: Array = [] + for e in entries: + list.append(e.to_dict()) + var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y), "entries": list} + if collapsed: + d["collapsed"] = true + if die > 0: + d["die"] = die + return d + + +static func from_dict(d: Dictionary) -> RollTable: + var t := RollTable.new(str(d.get("id", "")), str(d.get("name", ""))) + t.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0))) + t.collapsed = bool(d.get("collapsed", false)) + t.die = int(d.get("die", 0)) + for ed in d.get("entries", []): + if ed is Dictionary: + t.entries.append(TableEntry.from_dict(ed)) + return t diff --git a/core/roll_table.gd.uid b/core/roll_table.gd.uid new file mode 100644 index 0000000..b451749 --- /dev/null +++ b/core/roll_table.gd.uid @@ -0,0 +1 @@ +uid://ccjtqk3cakkc2 diff --git a/core/roller.gd b/core/roller.gd new file mode 100644 index 0000000..5cec5f0 --- /dev/null +++ b/core/roller.gd @@ -0,0 +1,89 @@ +class_name Roller +extends RefCounted +## Rolls a table and follows its pipes, producing a result tree. +## +## Each node is a Dictionary: +## table: RollTable, value: int (die value), index: int, entry: TableEntry, +## children: Array of nodes, and "stop": String when the chain couldn't continue. + +const MAX_DEPTH := 12 + + +static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0) -> Dictionary: + var t := board.get_table(table_id) + if t == null: + return {} + if depth > MAX_DEPTH: + return {"table": t, "stop": "Chain stopped after %d tables" % MAX_DEPTH, "children": []} + if t.entries.is_empty(): + return {"table": t, "stop": "This table has no results", "children": []} + var index: int + var value: int + if t.is_ranged(): + value = rng.randi_range(1, t.die_size()) + index = t.entry_index_for(value) + if index < 0: + return {"table": t, "value": value, "stop": "No result for %s" % t.fmt(value), "children": []} + else: + index = rng.randi_range(0, t.entries.size() - 1) + value = index + 1 + var e := t.entries[index] + var children: Array = [] + for p in e.pipes: + var child := roll(board, p, rng, depth + 1) + if not child.is_empty(): + children.append(child) + return {"table": t, "index": index, "value": value, "entry": e, "children": children} + + +## One line of the result tray for a single node. +static func step_of(n: Dictionary) -> Dictionary: + var t: RollTable = n["table"] + var text: String = n["stop"] if n.has("stop") else (n["entry"] as TableEntry).text + return { + "table": t.name, + "num": t.fmt(n["value"]) if n.has("value") else "", + "die": t.die_size(), + "text": text, + } + + +## The whole chain in the order it was rolled. +static func flatten(n: Dictionary, out: Array = []) -> Array: + if n.is_empty(): + return out + out.append(step_of(n)) + for c in n["children"]: + flatten(c, out) + return out + + +static func reaches(n: Dictionary, table_id: String) -> bool: + if n.is_empty(): + return false + if (n["table"] as RollTable).id == table_id: + return true + for c in n["children"]: + if reaches(c, table_id): + return true + return false + + +## Marks every entry and pipe along the chain as lit. +static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary) -> void: + if n.is_empty() or n.has("stop"): + return + var t: RollTable = n["table"] + var e: TableEntry = n["entry"] + entries[entry_key(t.id, e.id)] = true + for c in n["children"]: + pipes[pipe_key(t.id, e.id, (c["table"] as RollTable).id)] = true + collect_lit(c, entries, pipes) + + +static func entry_key(table_id: String, entry_id: String) -> String: + return table_id + ":" + entry_id + + +static func pipe_key(table_id: String, entry_id: String, to_id: String) -> String: + return "%s:%s>%s" % [table_id, entry_id, to_id] diff --git a/core/roller.gd.uid b/core/roller.gd.uid new file mode 100644 index 0000000..fca9ed3 --- /dev/null +++ b/core/roller.gd.uid @@ -0,0 +1 @@ +uid://dioyoj7ibpqsa diff --git a/core/sample_board.gd b/core/sample_board.gd new file mode 100644 index 0000000..88a4a73 --- /dev/null +++ b/core/sample_board.gd @@ -0,0 +1,83 @@ +class_name SampleBoard +extends RefCounted +## The example board: road encounters, loot chains, a d100 ranged travel table +## and a d100 table of 100 unique trinkets. + +const TRINKETS := [ + "A brass key that's warm to the touch", "A glass eye that follows movement", "A tin whistle only dogs can hear", "A pressed flower that never wilts", + "A tiny portrait of a stranger", "A compass that points to the nearest well", "A wooden die with seven sides", "A silver spoon bent into a ring", + "A sealed letter addressed to you", "A bell with no clapper that still rings", "A jar of buttons from a hundred coats", "A dragon scale the size of a coin", + "A candle that burns cold", "A deck of cards missing every queen", "A bird skull painted gold", "A map of a city that doesn't exist", + "A thimble of sand that never spills", "A ribbon embroidered with your name", "A clockwork beetle that wants winding", "A pebble that is always wet", + "A fishhook carved from bone", "A coin from a kingdom that fell", "A lock of silver hair tied with string", "A broken hourglass, sand still falling", + "A soup recipe written in blood", "A doll with one button eye", "A chess piece shaped like a crow", "A vial of fog", + "A tooth with a tiny keyhole", "A feather that falls upward", "An empty locket that hums", "A spool of thread that never runs out", + "A ring too small for any finger", "A wax seal of a three-eyed owl", "A shell that whispers in a strange tongue", "A rusted crown sized for a cat", + "A knot no blade can cut", "A page torn from a spellbook", "A marble with a storm inside", "A tiny saddle for a mouse", + "A mirror shard that shows yesterday", "A reed flute that plays by itself", "A holed stone that shows stars at noon", "A child's drawing of you", + "A spice tin of dried fireflies", "A wooden sword notched for every win", "A pair of dice that always roll the same", "An acorn that grows back each night", + "A tarnished medal for bravery", "A bottle with a ship of bones inside", "A glove that's always warm", "A bookmark from a library that burned", + "A walnut that rattles", "A copper ring stamped with a moon", "A lantern wick that relights itself", "A painted egg that is far too heavy", + "A bag of salt from a distant sea", "A wanted poster with no face", "A spinning top that never falls", "A snuff box full of teeth", + "A crystal that glows near goblins", "A riddle carved into a spoon handle", "A scarf that smells of summer rain", "A key with no teeth", + "A thumb-sized statue of a sleeping god", "A bone flute with one hole", "An inkwell that refills with black water", "A quill that writes only in red", + "A pocket watch running backwards", "A wedding ring with both names scratched out", "An eggshell painted with a map", "A pouch of mismatched dice", + "A tinderbox that sparks blue", "A prayer bead from an unknown faith", "A playing card with your face on it", "A cracked monocle", + "A tiny cage with the door open", "A pressed four-leaf clover", "A seashell found far inland", "A gold tooth", + "A badge from the city watch", "A charm bracelet with one charm missing", "A bundle of letters tied with twine", "A chip of a giant's fingernail", + "A rope that ties itself", "A stone that floats", "A song trapped in a bottle", "A carved wooden fish", + "A toy soldier missing an arm", "A coin that always lands on its edge", "A candle stub that smells of home", "A brooch shaped like a spider", + "A sliver of moonlight in a vial", "An arrowhead made of glass", "A dried rose from a grave", "A bone die marked with runes", + "A tiny shield with an unknown crest", "A horseshoe for a six-legged horse", "A note: “Don't trust the innkeeper”", "An egg that is warm and ticking", +] + + +static func create() -> TowerBoard: + var trinket_rows: Array = [] + for s in TRINKETS: + trinket_rows.append([s]) + # [id, name, position, entries: [text, pipes?, range?], options?] + var spec: Array = [ + ["wilderness", "Wilderness Travel", Vector2(40, 180), [ + ["Travelers on the road", ["road"], [1, 30]], + ["Beasts on the hunt", ["monsters"], [31, 50]], + ["A peddler's cart", ["wares"], [51, 65]], + ["Something glints in the grass", ["loot"], [66, 80]], + ["A stranger at the campfire", ["names"], [81, 95]], + ["An odd find", ["trinkets"], [96, 100]], + ], {"die": 100}], + ["road", "Road Encounter", Vector2(390, 40), [ + ["Bandits ambush the party", ["loot"]], ["A merchant caravan", ["wares"]], + ["Something big in the trees", ["monsters"]], ["A quiet stretch of road"], + ["A sudden storm rolls in"], ["A lost traveler", ["names"]], + ]], + ["trinkets", "Curious Trinkets", Vector2(390, 420), trinket_rows, {"collapsed": true}], + ["monsters", "Monsters", Vector2(740, 20), [["Owlbear", ["loot"]], ["Giant spider"], ["Troll", ["loot"]], ["Wyvern"]]], + ["wares", "Merchant Wares", Vector2(740, 300), [["Bolts of silk"], ["Rare spices"], ["Lamp oil"], ["A crate of strange eggs"]]], + ["loot", "Loot", Vector2(1090, 60), [ + ["A pouch of gold"], ["A weapon", ["weapons"]], ["A healing potion"], + ["A torn map"], ["A gemstone"], ["Nothing but lint"], + ]], + ["names", "Traveler Names", Vector2(1090, 400), [["Aldric"], ["Brenna"], ["Corvin"], ["Dagny"], ["Elowen"], ["Fenn"]]], + ["weapons", "Weapons", Vector2(1440, 60), [["Dagger"], ["Sword", ["quality"]], ["Hand axe"], ["Shortbow"]]], + ["quality", "Sword Quality", Vector2(1790, 130), [["Rusty"], ["Notched"], ["Fine"], ["Elven-forged"]]], + ] + var board := TowerBoard.new() + for s in spec: + var t := RollTable.new(s[0], s[1]) + t.position = s[2] + var opts: Dictionary = s[4] if s.size() > 4 else {} + t.die = int(opts.get("die", 0)) + t.collapsed = bool(opts.get("collapsed", false)) + for row in s[3]: + var e := TableEntry.new(TowerBoard.new_id("e"), row[0]) + if row.size() > 1: + for p in row[1]: + e.pipes.append(p) + if row.size() > 2: + e.has_range = true + e.range_lo = row[2][0] + e.range_hi = row[2][1] + t.entries.append(e) + board.tables.append(t) + return board diff --git a/core/sample_board.gd.uid b/core/sample_board.gd.uid new file mode 100644 index 0000000..5165369 --- /dev/null +++ b/core/sample_board.gd.uid @@ -0,0 +1 @@ +uid://dn40x65nhjxqj diff --git a/core/table_entry.gd b/core/table_entry.gd new file mode 100644 index 0000000..969f1a9 --- /dev/null +++ b/core/table_entry.gd @@ -0,0 +1,43 @@ +class_name TableEntry +extends RefCounted +## One possible result on a table. An entry may pipe into other tables, and on a +## ranged (dice) table it covers a span of die values such as 01–30. + +var id: String = "" +var text: String = "" +## IDs of the tables this entry rolls on next. +var pipes: Array[String] = [] +var has_range: bool = false +var range_lo: int = 1 +var range_hi: int = 1 + + +func _init(p_id: String = "", p_text: String = "") -> void: + id = p_id + text = p_text + + +## How many die faces this entry covers. Plain entries cover exactly one. +func span() -> int: + return range_hi - range_lo + 1 if has_range else 1 + + +func to_dict() -> Dictionary: + var d := {"id": id, "text": text} + if not pipes.is_empty(): + d["pipes"] = pipes.duplicate() + if has_range: + d["range"] = [range_lo, range_hi] + return d + + +static func from_dict(d: Dictionary) -> TableEntry: + var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", ""))) + for p in d.get("pipes", []): + e.pipes.append(str(p)) + var r: Variant = d.get("range") + if r is Array and r.size() == 2: + e.has_range = true + e.range_lo = int(r[0]) + e.range_hi = int(r[1]) + return e diff --git a/core/table_entry.gd.uid b/core/table_entry.gd.uid new file mode 100644 index 0000000..38fc336 --- /dev/null +++ b/core/table_entry.gd.uid @@ -0,0 +1 @@ +uid://de7ufd65vpyxu diff --git a/core/tower_board.gd b/core/tower_board.gd new file mode 100644 index 0000000..bdb63f4 --- /dev/null +++ b/core/tower_board.gd @@ -0,0 +1,78 @@ +class_name TowerBoard +extends RefCounted +## Every table on the board, plus loading and saving as JSON. + +const SAVE_PATH := "user://board.json" +const FORMAT_VERSION := 1 + +static var _counter: int = 0 +static var _salt: String = "" + +var tables: Array[RollTable] = [] + + +static func new_id(prefix: String) -> String: + if _salt == "": + _salt = "%x" % (int(Time.get_unix_time_from_system()) % 0xfffff) + _counter += 1 + return "%s%s_%d" % [prefix, _salt, _counter] + + +func get_table(id: String) -> RollTable: + for t in tables: + if t.id == id: + return t + return null + + +## Removes a table and every pipe that pointed at it. +func remove_table(id: String) -> void: + for i in range(tables.size() - 1, -1, -1): + if tables[i].id == id: + tables.remove_at(i) + for t in tables: + for e in t.entries: + e.pipes.erase(id) + + +func to_dict() -> Dictionary: + var list: Array = [] + for t in tables: + list.append(t.to_dict()) + return {"format_version": FORMAT_VERSION, "tables": list} + + +func to_json() -> String: + return JSON.stringify(to_dict(), " ") + + +## Replaces the board's tables from JSON text. Returns false if the text isn't a board. +func load_json(text: String) -> bool: + var parsed: Variant = JSON.parse_string(text) + if not (parsed is Dictionary) or not (parsed.get("tables") is Array): + return false + var loaded: Array[RollTable] = [] + for td in parsed["tables"]: + if td is Dictionary: + loaded.append(RollTable.from_dict(td)) + tables = loaded + return true + + +func save(path: String = SAVE_PATH) -> bool: + var f := FileAccess.open(path, FileAccess.WRITE) + if f == null: + push_warning("Couldn't save the board to %s: %s" % [path, error_string(FileAccess.get_open_error())]) + return false + f.store_string(to_json()) + return true + + +## Loads the saved board, or returns null if there isn't a usable one. +static func load_saved(path: String = SAVE_PATH) -> TowerBoard: + if not FileAccess.file_exists(path): + return null + var b := TowerBoard.new() + if not b.load_json(FileAccess.get_file_as_string(path)) or b.tables.is_empty(): + return null + return b diff --git a/core/tower_board.gd.uid b/core/tower_board.gd.uid new file mode 100644 index 0000000..0d4d968 --- /dev/null +++ b/core/tower_board.gd.uid @@ -0,0 +1 @@ +uid://c76ox3vxujfce diff --git a/project.godot b/project.godot index 94fd606..0b97927 100644 --- a/project.godot +++ b/project.godot @@ -11,5 +11,16 @@ config_version=5 [application] config/name="TableTower" +run/main_scene="res://ui/main.tscn" config/features=PackedStringArray("4.7", "Forward Plus") +boot_splash/bg_color=Color(0.0706, 0.1882, 0.1216, 1) config/icon="res://icon.svg" + +[display] + +window/size/viewport_width=1440 +window/size/viewport_height=900 + +[rendering] + +environment/defaults/default_clear_color=Color(0.0706, 0.1882, 0.1216, 1) diff --git a/tests/test_roller.gd b/tests/test_roller.gd new file mode 100644 index 0000000..0c7ade0 --- /dev/null +++ b/tests/test_roller.gd @@ -0,0 +1,103 @@ +extends SceneTree +## Headless checks for the data model and roller. +## Run: godot --headless --path . -s res://tests/test_roller.gd + +var _failures := 0 + + +func _init() -> void: + var board := SampleBoard.create() + var rng := RandomNumberGenerator.new() + rng.seed = 12345 + + var trinkets := board.get_table("trinkets") + _check(trinkets.entries.size() == 100, "trinkets has 100 entries") + _check(trinkets.die_size() == 100, "trinkets rolls a d100") + var unique := {} + for e in trinkets.entries: + unique[e.text] = true + _check(unique.size() == 100, "trinket entries are unique") + _check(trinkets.num_label(trinkets.entries[0], 0) == "01", "first trinket is numbered 01") + _check(trinkets.num_label(trinkets.entries[99], 99) == "00", "last trinket is numbered 00") + + var wild := board.get_table("wilderness") + _check(wild.is_ranged() and wild.die_size() == 100, "wilderness is a ranged d100") + _check(wild.range_problems() == "", "wilderness ranges have no gaps or overlaps") + _check(wild.num_label(wild.entries[5], 5) == "96–00", "last range reads 96–00") + for e in wild.entries: + _check(e.pipes.size() == 1, "range %s has exactly one pipe" % e.text) + + # Range weighting: 01–30 should come up about 30% of the time. + var counts := {} + for i in 20000: + var n := Roller.roll(board, "wilderness", rng) + var text: String = (n["entry"] as TableEntry).text + counts[text] = counts.get(text, 0) + 1 + var share := float(counts.get("Travelers on the road", 0)) / 20000.0 + _check(absf(share - 0.30) < 0.02, "01–30 rolls about 30%% of the time (got %.3f)" % share) + var rare := float(counts.get("An odd find", 0)) / 20000.0 + _check(absf(rare - 0.05) < 0.01, "96–00 rolls about 5%% of the time (got %.3f)" % rare) + + # Chains follow pipes. + var reached := false + for i in 500: + var n := Roller.roll(board, "wilderness", rng) + if Roller.reaches(n, "trinkets"): + reached = true + _check(Roller.flatten(n, []).size() == 2, "wilderness → trinkets chain has two steps") + break + _check(reached, "wilderness can reach trinkets") + + # Gaps and overlaps are reported. + wild.entries[1].range_lo = 35 + _check(wild.range_problems() == "No result for 31–34.", "gap reported: %s" % wild.range_problems()) + wild.entries[1].range_lo = 25 + _check(wild.range_problems() == "25–30 matches more than one result.", "overlap reported: %s" % wild.range_problems()) + wild.entries[1].range_lo = 31 + var n_gap := RollTable.new("g", "Gappy") + var only := TableEntry.new("e1", "Low") + only.has_range = true + only.range_lo = 1 + only.range_hi = 50 + n_gap.entries.append(only) + var stops := 0 + for i in 200: + var b2 := TowerBoard.new() + b2.tables.append(n_gap) + if Roller.roll(b2, "g", rng).has("stop"): + stops += 1 + _check(stops > 50 and stops < 150, "rolls into a gap stop with a message (%d/200)" % stops) + + # A self-pipe stops at the depth limit instead of looping forever. + var loop := RollTable.new("loop", "Loop") + var again := TableEntry.new("e1", "Again") + again.pipes.append("loop") + loop.entries.append(again) + var b3 := TowerBoard.new() + b3.tables.append(loop) + var steps := Roller.flatten(Roller.roll(b3, "loop", rng), []) + _check(steps.size() == Roller.MAX_DEPTH + 2, "self-pipe stops after the depth limit (%d steps)" % steps.size()) + + # JSON round trip keeps everything. + var copy := TowerBoard.new() + _check(copy.load_json(board.to_json()), "board JSON loads back") + _check(copy.to_json() == board.to_json(), "board JSON round-trips unchanged") + _check(copy.get_table("trinkets").collapsed, "collapsed state is saved") + + # Removing a table removes pipes into it. + copy.remove_table("loot") + var dangling := false + for t in copy.tables: + for e in t.entries: + if e.pipes.has("loot"): + dangling = true + _check(not dangling and copy.get_table("loot") == null, "removing a table removes pipes into it") + + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print(" ✗ ", what) diff --git a/tests/test_roller.gd.uid b/tests/test_roller.gd.uid new file mode 100644 index 0000000..7f07271 --- /dev/null +++ b/tests/test_roller.gd.uid @@ -0,0 +1 @@ +uid://dsu5lvppc8ixo diff --git a/ui/board_view.gd b/ui/board_view.gd new file mode 100644 index 0000000..245f35f --- /dev/null +++ b/ui/board_view.gd @@ -0,0 +1,154 @@ +class_name BoardView +extends Control +## The felt board. Holds a scaled "world" with three layers: pipes behind the +## cards, the cards, and the ports (pipe ends) on top. Drag the felt to pan, +## Ctrl+wheel or pinch to zoom. + +const MIN_ZOOM := 0.35 +const MAX_ZOOM := 1.5 +const WORLD_SIZE := 40000.0 + +var main: Main +var world: Control +var pipes: PipeLayer +var cards: CardLayer +var ports: PortLayer +var zoom: float = 1.0 + +var _panning := false +var _glow: GradientTexture2D +var _dots: ImageTexture + + +func setup(p_main: Main) -> void: + main = p_main + clip_contents = true + mouse_filter = MOUSE_FILTER_STOP + size_flags_vertical = SIZE_EXPAND_FILL + texture_repeat = CanvasItem.TEXTURE_REPEAT_ENABLED + + world = Control.new() + world.mouse_filter = MOUSE_FILTER_IGNORE + add_child(world) + pipes = PipeLayer.new() + pipes.main = main + world.add_child(pipes) + cards = CardLayer.new() + world.add_child(cards) + ports = PortLayer.new() + ports.main = main + world.add_child(ports) + + var img := Image.create(6, 6, false, Image.FORMAT_RGBA8) + img.fill(Color(0, 0, 0, 0)) + img.set_pixel(1, 1, Color(1, 1, 1, 0.06)) + _dots = ImageTexture.create_from_image(img) + var g := Gradient.new() + g.set_color(0, Color(1, 1, 1, 0.06)) + g.set_color(1, Color(1, 1, 1, 0)) + _glow = GradientTexture2D.new() + _glow.gradient = g + _glow.fill = GradientTexture2D.FILL_RADIAL + _glow.fill_from = Vector2(0.35, 0.3) + _glow.fill_to = Vector2(0.8, 0.3) + _glow.width = 256 + _glow.height = 256 + resized.connect(queue_redraw) + + +func _draw() -> void: + var r := Rect2(Vector2.ZERO, size) + draw_rect(r, Style.FELT) + draw_texture_rect(_glow, r, false) + draw_texture_rect(_dots, r, true) + + +func world_mouse() -> Vector2: + return world.get_local_mouse_position() + + +func screen_to_world(p: Vector2) -> Vector2: + return (p - world.position) / zoom + + +func set_zoom(z: float, around: Vector2 = Vector2(-1, -1)) -> void: + if around.x < 0.0: + around = size / 2.0 + var anchor := screen_to_world(around) + zoom = clampf(snappedf(z, 0.01), MIN_ZOOM, MAX_ZOOM) + world.scale = Vector2(zoom, zoom) + world.position = around - anchor * zoom + + +## Zooms to show every table, centred horizontally. +func fit() -> void: + var first := true + var bounds := Rect2() + for c in cards.get_children(): + var card := c as Control + var r := Rect2(card.position, card.size) + bounds = r if first else bounds.merge(r) + first = false + if first: + return + bounds = bounds.grow(20.0) + zoom = clampf(minf(1.0, minf((size.x - 16.0) / bounds.size.x, (size.y - 16.0) / bounds.size.y)), MIN_ZOOM, MAX_ZOOM) + world.scale = Vector2(zoom, zoom) + world.position = Vector2(maxf(8.0, (size.x - bounds.size.x * zoom) / 2.0), 8.0) - bounds.position * zoom + + +func _gui_input(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb: + match mb.button_index: + MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MIDDLE: + if mb.pressed: + if mb.button_index == MOUSE_BUTTON_LEFT and main.mode == Main.Mode.BUILD: + var key := pipes.pipe_at(world_mouse(), 11.0) + if key != "": + main.remove_pipe(key) + accept_event() + return + _panning = true + mouse_default_cursor_shape = CURSOR_DRAG + else: + _panning = false + mouse_default_cursor_shape = CURSOR_ARROW + accept_event() + MOUSE_BUTTON_WHEEL_UP, MOUSE_BUTTON_WHEEL_DOWN: + if mb.pressed: + var up := mb.button_index == MOUSE_BUTTON_WHEEL_UP + if mb.ctrl_pressed: + set_zoom(zoom * (1.1 if up else 1.0 / 1.1), mb.position) + elif mb.shift_pressed: + world.position.x += 60.0 if up else -60.0 + else: + world.position.y += 60.0 if up else -60.0 + accept_event() + MOUSE_BUTTON_WHEEL_LEFT, MOUSE_BUTTON_WHEEL_RIGHT: + if mb.pressed: + world.position.x += 60.0 if mb.button_index == MOUSE_BUTTON_WHEEL_LEFT else -60.0 + accept_event() + return + var mm := ev as InputEventMouseMotion + if mm: + if _panning: + world.position += mm.relative + elif main.mode == Main.Mode.BUILD: + pipes.hover_key = pipes.pipe_at(world_mouse(), 11.0) + mouse_default_cursor_shape = CURSOR_POINTING_HAND if pipes.hover_key != "" else CURSOR_ARROW + return + var pan := ev as InputEventPanGesture + if pan: + world.position -= pan.delta * 16.0 + accept_event() + return + var mag := ev as InputEventMagnifyGesture + if mag: + set_zoom(zoom * mag.factor, mag.position) + accept_event() + + +func _notification(what: int) -> void: + if what == NOTIFICATION_MOUSE_EXIT and pipes: + pipes.hover_key = "" diff --git a/ui/board_view.gd.uid b/ui/board_view.gd.uid new file mode 100644 index 0000000..e71f9ed --- /dev/null +++ b/ui/board_view.gd.uid @@ -0,0 +1 @@ +uid://dpaqwq3fuc00 diff --git a/ui/card_layer.gd b/ui/card_layer.gd new file mode 100644 index 0000000..13a039a --- /dev/null +++ b/ui/card_layer.gd @@ -0,0 +1,23 @@ +class_name CardLayer +extends Control +## Holds the table cards and paints their hard drop shadow underneath them. + +var _shadow: StyleBoxFlat + + +func _init() -> void: + mouse_filter = MOUSE_FILTER_IGNORE + # Controls only draw inside their own rect, so cover the whole world. + size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) + _shadow = Style.box(Color(0, 0, 0, 0.22), 10) + + +func _process(_delta: float) -> void: + queue_redraw() + + +func _draw() -> void: + for c in get_children(): + var card := c as Control + if card and card.visible: + draw_style_box(_shadow, Rect2(card.position + Vector2(0, 5), card.size)) diff --git a/ui/card_layer.gd.uid b/ui/card_layer.gd.uid new file mode 100644 index 0000000..2c204c3 --- /dev/null +++ b/ui/card_layer.gd.uid @@ -0,0 +1 @@ +uid://b1tlofrm8dg8a diff --git a/ui/chevron_button.gd b/ui/chevron_button.gd new file mode 100644 index 0000000..1219b02 --- /dev/null +++ b/ui/chevron_button.gd @@ -0,0 +1,29 @@ +class_name ChevronButton +extends Button +## Collapse/expand toggle: a chevron pointing down when open, right when collapsed. + +var open: bool = true: + set(value): + open = value + queue_redraw() + + +func _init() -> void: + custom_minimum_size = Vector2(26, 26) + flat = false + focus_mode = FOCUS_ALL + var normal := Style.box(Color(0, 0, 0, 0), 6) + var hover := Style.box(Color("#e6dfcd"), 6) + Style.skin_button(self, normal, hover, hover, Style.MUTED) + mouse_entered.connect(queue_redraw) + mouse_exited.connect(queue_redraw) + + +func _draw() -> void: + var c := size / 2.0 + var pts: PackedVector2Array + if open: + pts = PackedVector2Array([c + Vector2(-4, -2), c + Vector2(0, 2), c + Vector2(4, -2)]) + else: + pts = PackedVector2Array([c + Vector2(-2, -4), c + Vector2(2, 0), c + Vector2(-2, 4)]) + draw_polyline(pts, Style.INK if is_hovered() else Style.MUTED, 2.0, true) diff --git a/ui/chevron_button.gd.uid b/ui/chevron_button.gd.uid new file mode 100644 index 0000000..e381523 --- /dev/null +++ b/ui/chevron_button.gd.uid @@ -0,0 +1 @@ +uid://gmcbyiw30505 diff --git a/ui/die_icon.gd b/ui/die_icon.gd new file mode 100644 index 0000000..779168a --- /dev/null +++ b/ui/die_icon.gd @@ -0,0 +1,46 @@ +class_name DieIcon +extends Control +## A three-pip die face. Tumbles while `spinning` is on. + +var color: Color = Style.BRASS +var spinning: bool = false: + set(value): + spinning = value + if not value: + _angle = 0.0 + set_process(value) + queue_redraw() + +var _angle: float = 0.0 +var _frame: StyleBoxFlat + + +func _init() -> void: + custom_minimum_size = Vector2(20, 20) + size = custom_minimum_size + mouse_filter = MOUSE_FILTER_IGNORE + _frame = StyleBoxFlat.new() + _frame.draw_center = false + _frame.set_border_width_all(2) + _frame.set_corner_radius_all(3) + _frame.anti_aliasing = true + set_process(false) + + +func _ready() -> void: + # Godot turns processing on for nodes with _process when they become ready. + set_process(spinning) + + +func _process(delta: float) -> void: + _angle = fmod(_angle + delta * TAU * 2.0, TAU) + queue_redraw() + + +func _draw() -> void: + draw_set_transform(size / 2.0, _angle) + _frame.border_color = color + draw_style_box(_frame, Rect2(-7.5, -7.5, 15, 15)) + for p in [Vector2(-3, -3), Vector2(0, 0), Vector2(3, 3)]: + draw_circle(p, 1.45, color) + draw_set_transform(Vector2.ZERO) diff --git a/ui/die_icon.gd.uid b/ui/die_icon.gd.uid new file mode 100644 index 0000000..0ff9cba --- /dev/null +++ b/ui/die_icon.gd.uid @@ -0,0 +1 @@ +uid://d3cq3mih7ocns diff --git a/ui/icons.gd b/ui/icons.gd new file mode 100644 index 0000000..94d1ad1 --- /dev/null +++ b/ui/icons.gd @@ -0,0 +1,20 @@ +class_name Icons +extends RefCounted +## Small vector icons drawn with CanvasItem calls. + + +## The TableTower mark: a tower outline with a brass doorway. Drawn in a 22x26 box. +static func draw_tower(ci: CanvasItem, origin: Vector2, scale: float, color: Color, accent: Color) -> void: + var pts := PackedVector2Array([ + Vector2(3, 25), Vector2(3, 8), Vector2(6, 6), Vector2(6, 2), Vector2(9, 2), Vector2(9, 5), + Vector2(13, 5), Vector2(13, 2), Vector2(16, 2), Vector2(16, 6), Vector2(19, 8), Vector2(19, 25), Vector2(3, 25), + ]) + for i in pts.size(): + pts[i] = origin + pts[i] * scale + ci.draw_polyline(pts, color, 1.7 * scale, true) + var door := PackedVector2Array([origin + Vector2(7, 25) * scale, origin + Vector2(7, 19) * scale]) + for k in range(17): + var a := PI + PI * k / 16.0 + door.append(origin + (Vector2(11, 19) + Vector2(cos(a), sin(a)) * 4.0) * scale) + door.append(origin + Vector2(15, 25) * scale) + ci.draw_polyline(door, accent, 1.7 * scale, true) diff --git a/ui/icons.gd.uid b/ui/icons.gd.uid new file mode 100644 index 0000000..6e67abb --- /dev/null +++ b/ui/icons.gd.uid @@ -0,0 +1 @@ +uid://bny3o5yhddwbm diff --git a/ui/main.gd b/ui/main.gd new file mode 100644 index 0000000..21fef27 --- /dev/null +++ b/ui/main.gd @@ -0,0 +1,624 @@ +class_name Main +extends Control +## The app window: top bar, felt board and result tray. Owns the board data, +## the Play/Build mode, roll animation, and editing actions with undo. + +enum Mode { PLAY, BUILD } + +const HISTORY_SIZE := 6 +const SAVE_DELAY := 0.6 +const HINTS := { + Mode.PLAY: "Click a die to roll. Results flow down the pipes.", + Mode.BUILD: "Type to edit. Drag from a ● to another table to lay a pipe. Click a pipe to remove it.", +} + +var data: TowerBoard +var mode: Mode = Mode.PLAY +var cards: Dictionary = {} # table id -> TableCard +var lit_entries: Dictionary = {} # "tid:eid" -> true +var lit_pipes: Dictionary = {} # "tid:eid>to" -> true +var current: Dictionary = {} +var history: Array = [] +var rng := RandomNumberGenerator.new() + +var board: BoardView +var tray: ResultTray + +var _token := 0 +var _pulse_tween: Tween +var _link_from: Dictionary = {} +var _drop_card: TableCard +var _hint: Label +var _play_button: Button +var _build_button: Button +var _build_tools: Control +var _collapse_all: Button +var _toast: PanelContainer +var _toast_label: Label +var _toast_undo: Button +var _toast_timer: Timer +var _save_timer: Timer +var _undo_snapshot := "" +var _saving_enabled := true + + +func _ready() -> void: + rng.randomize() + theme = Style.app_theme() + var args := OS.get_cmdline_user_args() + if args.has("--sample") or _arg_value(args, "--screenshot") != "": + _saving_enabled = false + if _saving_enabled: + data = TowerBoard.load_saved() + if data == null: + data = SampleBoard.create() + + _build_ui() + _rebuild_cards() + _seed_session() + _update_collapse_all() + # Let the cards lay out before fitting them to the window. + await get_tree().process_frame + await get_tree().process_frame + board.fit() + _run_cli(args) + + +func _exit_tree() -> void: + if _saving_enabled and data: + data.save() + + +# ---------- UI ---------- + +func _build_ui() -> void: + set_anchors_and_offsets_preset(PRESET_FULL_RECT) + var root := VBoxContainer.new() + root.set_anchors_and_offsets_preset(PRESET_FULL_RECT) + root.add_theme_constant_override("separation", 0) + add_child(root) + root.add_child(_build_top_bar()) + board = BoardView.new() + board.setup(self) + root.add_child(board) + tray = ResultTray.new() + tray.setup(self) + root.add_child(tray) + _build_toast() + + _save_timer = Timer.new() + _save_timer.one_shot = true + _save_timer.wait_time = SAVE_DELAY + _save_timer.timeout.connect(func() -> void: + if _saving_enabled: + data.save() + ) + add_child(_save_timer) + resized.connect(_place_toast) + + +func _build_top_bar() -> Control: + var bar := PanelContainer.new() + var sb := Style.box(Style.FELT_DEEP, 0, [16, 10, 16, 10]) + sb.border_width_bottom = 1 + sb.border_color = Color(1, 1, 1, 0.07) + bar.add_theme_stylebox_override("panel", sb) + var h := HBoxContainer.new() + h.add_theme_constant_override("separation", 16) + bar.add_child(h) + + var brand := HBoxContainer.new() + brand.add_theme_constant_override("separation", 9) + var mark := Control.new() + mark.custom_minimum_size = Vector2(20, 24) + mark.size_flags_vertical = SIZE_SHRINK_CENTER + mark.draw.connect(func() -> void: Icons.draw_tower(mark, Vector2(0, 0), 20.0 / 22.0, Style.ON_FELT, Style.BRASS)) + brand.add_child(mark) + var title := Style.make_label("TableTower", Style.display(), 23, Style.ON_FELT) + title.size_flags_vertical = SIZE_SHRINK_CENTER + brand.add_child(title) + h.add_child(brand) + + var seg := PanelContainer.new() + seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.28), 9, [3, 3, 3, 3])) + seg.size_flags_vertical = SIZE_SHRINK_CENTER + var seg_row := HBoxContainer.new() + seg_row.add_theme_constant_override("separation", 0) + seg.add_child(seg_row) + var group := ButtonGroup.new() + _play_button = _seg_button("Play", group) + _build_button = _seg_button("Build", group) + _play_button.button_pressed = true + _play_button.pressed.connect(func() -> void: set_mode(Mode.PLAY)) + _build_button.pressed.connect(func() -> void: set_mode(Mode.BUILD)) + seg_row.add_child(_play_button) + seg_row.add_child(_build_button) + h.add_child(seg) + + _hint = Style.make_label(HINTS[mode], Style.body(), 15, Style.ON_FELT_MUTED) + _hint.size_flags_horizontal = SIZE_EXPAND_FILL + _hint.size_flags_vertical = SIZE_SHRINK_CENTER + _hint.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + _hint.custom_minimum_size = Vector2(60, 0) + h.add_child(_hint) + + var tools := HBoxContainer.new() + tools.add_theme_constant_override("separation", 6) + _build_tools = tools + var add := Style.bar_button("+ Table", true) + add.pressed.connect(add_table) + tools.add_child(add) + var reset := Style.bar_button("Reset sample") + reset.pressed.connect(reset_sample) + tools.add_child(reset) + tools.visible = false + h.add_child(tools) + + _collapse_all = Style.bar_button("Collapse all") + _collapse_all.tooltip_text = "Collapse or expand every table at once" + _collapse_all.pressed.connect(func() -> void: set_all_collapsed(_any_expanded())) + h.add_child(_collapse_all) + + var zoom := HBoxContainer.new() + zoom.add_theme_constant_override("separation", 6) + var zout := Style.bar_button("−") + zout.tooltip_text = "Zoom out" + zout.custom_minimum_size = Vector2(34, 0) + zout.pressed.connect(func() -> void: board.set_zoom(board.zoom / 1.15)) + var zfit := Style.bar_button("Fit") + zfit.tooltip_text = "Show every table" + zfit.pressed.connect(func() -> void: board.fit()) + var zin := Style.bar_button("+") + zin.tooltip_text = "Zoom in" + zin.custom_minimum_size = Vector2(34, 0) + zin.pressed.connect(func() -> void: board.set_zoom(board.zoom * 1.15)) + for b in [zout, zfit, zin]: + zoom.add_child(b) + h.add_child(zoom) + return bar + + +func _seg_button(text: String, group: ButtonGroup) -> Button: + var b := Button.new() + b.text = text + b.toggle_mode = true + b.button_group = group + b.add_theme_font_override("font", Style.body_bold()) + b.add_theme_font_size_override("font_size", 16) + var normal := Style.box(Color(0, 0, 0, 0), 7, [16, 6, 16, 6]) + var hover := Style.box(Color(1, 1, 1, 0.06), 7, [16, 6, 16, 6]) + var pressed := Style.box(Style.CARD, 7, [16, 6, 16, 6]) + Style.skin_button(b, normal, hover, pressed, Style.ON_FELT_MUTED, Style.ON_FELT, Style.INK) + return b + + +func _build_toast() -> void: + _toast = PanelContainer.new() + var sb := Style.box(Style.CARD, 10, [16, 9, 10, 9]) + sb.shadow_color = Color(0, 0, 0, 0.4) + sb.shadow_size = 18 + sb.shadow_offset = Vector2(0, 8) + _toast.add_theme_stylebox_override("panel", sb) + var h := HBoxContainer.new() + h.add_theme_constant_override("separation", 12) + _toast.add_child(h) + _toast_label = Style.make_label("", Style.body(), 15, Style.INK) + _toast_label.size_flags_vertical = SIZE_SHRINK_CENTER + h.add_child(_toast_label) + _toast_undo = Button.new() + _toast_undo.text = "Undo" + _toast_undo.add_theme_font_override("font", Style.body_bold()) + _toast_undo.add_theme_font_size_override("font_size", 15) + var un := Style.box(Style.FELT, 7, [12, 5, 12, 5]) + var uh := Style.box(Style.FELT_HOVER, 7, [12, 5, 12, 5]) + Style.skin_button(_toast_undo, un, uh, uh, Style.BRASS) + _toast_undo.pressed.connect(_undo) + h.add_child(_toast_undo) + _toast.hide() + add_child(_toast) + _toast_timer = Timer.new() + _toast_timer.one_shot = true + _toast_timer.wait_time = 5.0 + _toast_timer.timeout.connect(func() -> void: + _toast.hide() + _undo_snapshot = "" + ) + add_child(_toast_timer) + + +func toast(message: String, snapshot: String = "") -> void: + _undo_snapshot = snapshot + _toast_label.text = message + _toast_undo.visible = snapshot != "" + _toast.show() + _toast.reset_size() + _place_toast() + _toast_timer.start() + + +func _place_toast() -> void: + if _toast and _toast.visible: + _toast.reset_size() + _toast.position = Vector2((size.x - _toast.size.x) / 2.0, size.y - _toast.size.y - 20.0) + + +func _undo() -> void: + if _undo_snapshot == "": + return + data.load_json(_undo_snapshot) + _undo_snapshot = "" + _toast.hide() + _rebuild_cards() + mark_dirty() + + +func _snapshot() -> String: + return data.to_json() + + +# ---------- Cards ---------- + +func card_for(id: String) -> TableCard: + return cards.get(id) + + +func is_entry_lit(tid: String, eid: String) -> bool: + return lit_entries.has(Roller.entry_key(tid, eid)) + + +func _rebuild_cards() -> void: + for c in board.cards.get_children(): + board.cards.remove_child(c) + c.queue_free() + cards.clear() + for t in data.tables: + var card := TableCard.new() + board.cards.add_child(card) + card.setup(self, t) + cards[t.id] = card + _update_collapse_all() + + +func _refresh_lit() -> void: + for card in cards.values(): + (card as TableCard).refresh_lit() + + +func set_mode(m: Mode) -> void: + mode = m + _play_button.set_pressed_no_signal(m == Mode.PLAY) + _build_button.set_pressed_no_signal(m == Mode.BUILD) + _hint.text = HINTS[m] + _build_tools.visible = m == Mode.BUILD + board.pipes.hover_key = "" + for card in cards.values(): + (card as TableCard).rebuild() + + +func mark_dirty() -> void: + if _saving_enabled: + _save_timer.start() + _update_collapse_all() + + +func _any_expanded() -> bool: + for t in data.tables: + if not t.collapsed: + return true + return false + + +func _update_collapse_all() -> void: + if _collapse_all: + _collapse_all.text = "Collapse all" if _any_expanded() else "Expand all" + + +# ---------- Editing actions ---------- + +func toggle_collapse(tid: String) -> void: + var t := data.get_table(tid) + if t == null: + return + t.collapsed = not t.collapsed + card_for(tid).rebuild() + mark_dirty() + + +func set_all_collapsed(collapsed: bool) -> void: + for t in data.tables: + if t.collapsed != collapsed: + t.collapsed = collapsed + card_for(t.id).rebuild() + mark_dirty() + + +func add_table() -> void: + var center := board.screen_to_world(board.size / 2.0) + var t := RollTable.new(TowerBoard.new_id("t"), "New table") + t.position = Vector2(maxf(20.0, roundf(center.x - 128.0)), maxf(20.0, roundf(center.y - 120.0))) + for n in range(1, 5): + t.entries.append(TableEntry.new(TowerBoard.new_id("e"), "Result %d" % n)) + data.tables.append(t) + var card := TableCard.new() + board.cards.add_child(card) + card.setup(self, t) + cards[t.id] = card + mark_dirty() + + +func reset_sample() -> void: + var snap := _snapshot() + data = SampleBoard.create() + lit_entries.clear() + lit_pipes.clear() + _rebuild_cards() + mark_dirty() + await get_tree().process_frame + await get_tree().process_frame + board.fit() + toast("Board reset to the sample tables", snap) + + +func add_entry(tid: String) -> void: + var t := data.get_table(tid) + var e := TableEntry.new(TowerBoard.new_id("e"), "Result %d" % (t.entries.size() + 1)) + if t.is_ranged(): + var hi := 0 + for x in t.entries: + hi = maxi(hi, x.range_hi) + e.has_range = true + e.range_lo = mini(t.die_size(), hi + 1) + e.range_hi = e.range_lo + e.text = "New range" + t.entries.append(e) + t.collapsed = false + card_for(tid).rebuild() + mark_dirty() + + +func delete_entry(tid: String, eid: String) -> void: + var t := data.get_table(tid) + var e := t.find_entry(eid) + if e == null: + return + var snap := _snapshot() + t.entries.erase(e) + card_for(tid).rebuild() + mark_dirty() + toast("Deleted “%s”" % e.text, snap) + + +func delete_table(tid: String) -> void: + var t := data.get_table(tid) + if t == null: + return + var snap := _snapshot() + data.remove_table(tid) + var card := card_for(tid) + cards.erase(tid) + card.queue_free() + for c in cards.values(): + (c as TableCard).rebuild() + mark_dirty() + toast("Deleted %s" % t.name, snap) + + +func remove_pipe(key: String) -> void: + var from := key.get_slice(">", 0) + var to := key.get_slice(">", 1) + var t := data.get_table(from.get_slice(":", 0)) + var target := data.get_table(to) + if t == null: + return + var e := t.find_entry(from.get_slice(":", 1)) + if e == null: + return + var snap := _snapshot() + e.pipes.erase(to) + lit_pipes.erase(key) + board.pipes.hover_key = "" + card_for(t.id).rebuild() + mark_dirty() + toast("Removed pipe from “%s” to %s" % [e.text, target.name if target else to], snap) + + +func start_link(tid: String, eid: String) -> void: + _link_from = {"tid": tid, "eid": eid} + + +func update_link() -> void: + var over := _card_under_mouse() + if over != _drop_card: + if is_instance_valid(_drop_card): + _drop_card.set_drop_target(false) + _drop_card = over + if _drop_card: + _drop_card.set_drop_target(true) + + +func finish_link() -> void: + var over := _card_under_mouse() + if is_instance_valid(_drop_card): + _drop_card.set_drop_target(false) + _drop_card = null + if _link_from.is_empty() or over == null: + _link_from = {} + return + var t := data.get_table(_link_from["tid"]) + var e := t.find_entry(_link_from["eid"]) if t else null + _link_from = {} + if e == null or e.pipes.has(over.table.id): + return + # Each range on a ranged table takes a single pipe, so a new one replaces the old. + var replaced: RollTable = null + if t.is_ranged(): + if not e.pipes.is_empty(): + replaced = data.get_table(e.pipes[0]) + e.pipes.clear() + e.pipes.append(over.table.id) + card_for(t.id).rebuild() + mark_dirty() + var msg := "“%s” now rolls on %s" % [e.text, over.table.name] + if replaced: + msg += " instead of %s" % replaced.name + toast(msg) + + +func _card_under_mouse() -> TableCard: + var gp := get_global_mouse_position() + var kids := board.cards.get_children() + for i in range(kids.size() - 1, -1, -1): + var card := kids[i] as TableCard + if card and card.get_global_rect().has_point(gp): + return card + return null + + +# ---------- Rolling ---------- + +func start_roll(tid: String) -> void: + var t := data.get_table(tid) + if t == null: + return + _archive_current() + _token += 1 + var my := _token + if _pulse_tween and _pulse_tween.is_valid(): + _pulse_tween.kill() + board.pipes.pulse_key = "" + for c in cards.values(): + (c as TableCard).set_rolling(false) + (c as TableCard).clear_flick() + var tree := Roller.roll(data, tid, rng) + lit_entries.clear() + lit_pipes.clear() + _refresh_lit() + current = {"root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(), + "steps": [], "all": Roller.flatten(tree, []), "done": false} + tray.render() + await _play_node(tree, my) + if my == _token: + current["steps"] = current["all"] + current["done"] = true + tray.render() + + +func _play_node(n: Dictionary, my: int) -> void: + if my != _token or n.is_empty(): + return + var t: RollTable = n["table"] + var stopped := n.has("stop") + var card := card_for(t.id) + if not stopped and card: + card.set_rolling(true) + for k in 8: + card = card_for(t.id) + if card == null: + break + if t.collapsed: + card.set_more_text("Rolling… %s" % t.fmt(rng.randi_range(1, t.die_size()))) + else: + card.flick_random() + await get_tree().create_timer((40.0 + k * 16.0) / 1000.0).timeout + if my != _token: + return + card = card_for(t.id) + if card: + card.clear_flick() + card.set_rolling(false) + if not stopped: + var e: TableEntry = n["entry"] + lit_entries[Roller.entry_key(t.id, e.id)] = true + _refresh_lit() + if card: + card.reveal(e.id) + (current["steps"] as Array).append(Roller.step_of(n)) + tray.render() + for c in n["children"]: + var key := Roller.pipe_key(t.id, (n["entry"] as TableEntry).id, (c["table"] as RollTable).id) + lit_pipes[key] = true + await _pulse(key, my) + await _play_node(c, my) + + +func _pulse(key: String, my: int) -> void: + var length := board.pipes.path_length(key) + if length <= 0.0 or my != _token: + return + board.pipes.pulse_key = key + board.pipes.pulse_t = 0.0 + _pulse_tween = create_tween().set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_IN_OUT) + _pulse_tween.tween_property(board.pipes, "pulse_t", 1.0, clampf(length * 0.8, 260.0, 650.0) / 1000.0) + await _pulse_tween.finished + if board.pipes.pulse_key == key: + board.pipes.pulse_key = "" + + +func _archive_current() -> void: + if current.is_empty() or current.get("archived", false): + return + current["archived"] = true + var rec := current.duplicate() + rec["steps"] = current["all"] + history.push_front(rec) + if history.size() > HISTORY_SIZE: + history.resize(HISTORY_SIZE) + + +## A game already under way: a couple of earlier rolls, and a current roll that +## runs through the d100 travel table into the collapsed trinket table. +func _seed_session() -> void: + var now := Time.get_unix_time_from_system() + for seed_roll in [["monsters", 9], ["loot", 4]]: + if data.get_table(seed_roll[0]): + var tree := Roller.roll(data, seed_roll[0], rng) + var steps := Roller.flatten(tree, []) + history.push_front({"root": seed_roll[0], "root_name": data.get_table(seed_roll[0]).name, + "time": now - seed_roll[1] * 60, "steps": steps, "all": steps, "archived": true}) + var start := "wilderness" if data.get_table("wilderness") else (data.tables[0].id if not data.tables.is_empty() else "") + if start == "": + tray.render() + return + var best := Roller.roll(data, start, rng) + for i in 400: + if Roller.reaches(best, "trinkets"): + break + best = Roller.roll(data, start, rng) + var all := Roller.flatten(best, []) + current = {"root": start, "root_name": data.get_table(start).name, "time": now - 60, + "steps": all, "all": all, "done": true} + Roller.collect_lit(best, lit_entries, lit_pipes) + _refresh_lit() + tray.render() + + +# ---------- Command line (used for screenshots and checks) ---------- +# godot --path . -- --screenshot=/tmp/shot.png [--build] [--expand-all] [--collapse-all] +# [--roll=] [--shot-delay=] + +func _arg_value(args: PackedStringArray, name: String) -> String: + for a in args: + if a.begins_with(name + "="): + return a.substr(name.length() + 1) + return "" + + +func _run_cli(args: PackedStringArray) -> void: + if args.has("--build"): + set_mode(Mode.BUILD) + if args.has("--expand-all"): + set_all_collapsed(false) + if args.has("--collapse-all"): + set_all_collapsed(true) + var roll := _arg_value(args, "--roll") + if roll != "": + start_roll(roll) + var shot := _arg_value(args, "--screenshot") + if shot == "": + return + var delay := _arg_value(args, "--shot-delay") + await get_tree().create_timer(delay.to_float() if delay != "" else (2.5 if roll != "" else 0.8)).timeout + var img := get_viewport().get_texture().get_image() + img.save_png(shot) + print("Saved screenshot to ", shot) + get_tree().quit() diff --git a/ui/main.gd.uid b/ui/main.gd.uid new file mode 100644 index 0000000..7cb17e8 --- /dev/null +++ b/ui/main.gd.uid @@ -0,0 +1 @@ +uid://b8w14kan84qjw diff --git a/ui/main.tscn b/ui/main.tscn new file mode 100644 index 0000000..0df0292 --- /dev/null +++ b/ui/main.tscn @@ -0,0 +1,12 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://ui/main.gd" id="1_main"] + +[node name="Main" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1_main") diff --git a/ui/pipe_layer.gd b/ui/pipe_layer.gd new file mode 100644 index 0000000..8e9ab11 --- /dev/null +++ b/ui/pipe_layer.gd @@ -0,0 +1,115 @@ +class_name PipeLayer +extends Control +## Draws the copper pipes between cards, lit pipes in brass, and the glowing bead +## that travels down a pipe during a roll. Sits behind the cards. + +const SAMPLES := 40 + +var main: Main +var hover_key: String = "" +var pulse_key: String = "" +var pulse_t: float = 0.0 + +## pipe key -> polyline in world coordinates, from the last frame. +var _paths: Dictionary = {} + + +func _init() -> void: + mouse_filter = MOUSE_FILTER_IGNORE + # Controls only draw inside their own rect, so cover the whole world. + size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) + + +func _process(_delta: float) -> void: + queue_redraw() + + +static func curve(a: Vector2, b: Vector2) -> PackedVector2Array: + var dx := maxf(70.0, absf(b.x - a.x) / 2.0) + var c1 := a + Vector2(dx, 0) + var c2 := b - Vector2(dx, 0) + var pts := PackedVector2Array() + for i in SAMPLES + 1: + pts.append(a.bezier_interpolate(c1, c2, b, float(i) / SAMPLES)) + return pts + + +func _draw() -> void: + _paths.clear() + var lit_list: Array = [] + var build := main.mode == Main.Mode.BUILD + for t in main.data.tables: + var card := main.card_for(t.id) + if card == null: + continue + for e in t.entries: + for to in e.pipes: + var target := main.card_for(to) + if target == null: + continue + var a := card.anchor_for(e.id) + if a.is_empty(): + continue + var key := Roller.pipe_key(t.id, e.id, to) + var pts := curve(a["pos"], target.inlet_point()) + _paths[key] = pts + if main.lit_pipes.has(key): + lit_list.append(pts) + else: + _draw_pipe(pts, false, build and key == hover_key) + # Lit pipes go on top so the path of the last roll reads clearly. + for pts in lit_list: + _draw_pipe(pts, true, false) + if pulse_key != "" and _paths.has(pulse_key): + var p := point_along(_paths[pulse_key], pulse_t) + draw_circle(p, 13.0, Color(Style.BRASS, 0.3)) + draw_circle(p, 9.0, Color(Style.BRASS, 0.5)) + draw_circle(p, 7.0, Style.PULSE) + + +func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void: + if lit: + draw_polyline(pts, Color(Style.BRASS, 0.18), 20.0, true) + draw_polyline(pts, Style.BRASS_DARK if lit else Style.COPPER_DARK, 11.0, true) + var inner := Style.BRASS if lit else Style.COPPER + if hovered: + inner = Style.DANGER + draw_polyline(pts, inner, 6.0, true) + draw_set_transform(Vector2(0, -1.5)) + draw_polyline(pts, Color(1.0, 0.886, 0.745, 0.4), 1.5, true) + draw_set_transform(Vector2.ZERO) + + +func path_length(key: String) -> float: + if not _paths.has(key): + return 0.0 + var pts: PackedVector2Array = _paths[key] + var total := 0.0 + for i in range(1, pts.size()): + total += pts[i - 1].distance_to(pts[i]) + return total + + +static func point_along(pts: PackedVector2Array, t: float) -> Vector2: + if pts.size() < 2: + return pts[0] if pts.size() == 1 else Vector2.ZERO + var total := 0.0 + for i in range(1, pts.size()): + total += pts[i - 1].distance_to(pts[i]) + var want := clampf(t, 0.0, 1.0) * total + for i in range(1, pts.size()): + var seg := pts[i - 1].distance_to(pts[i]) + if want <= seg and seg > 0.0: + return pts[i - 1].lerp(pts[i], want / seg) + want -= seg + return pts[pts.size() - 1] + + +## The pipe under a world-space point, or "" if none is within `tolerance`. +func pipe_at(p: Vector2, tolerance: float) -> String: + for key in _paths: + var pts: PackedVector2Array = _paths[key] + for i in range(1, pts.size()): + if Geometry2D.get_closest_point_to_segment(p, pts[i - 1], pts[i]).distance_to(p) <= tolerance: + return key + return "" diff --git a/ui/pipe_layer.gd.uid b/ui/pipe_layer.gd.uid new file mode 100644 index 0000000..de0190d --- /dev/null +++ b/ui/pipe_layer.gd.uid @@ -0,0 +1 @@ +uid://b8evnm8lbgvlj diff --git a/ui/port_layer.gd b/ui/port_layer.gd new file mode 100644 index 0000000..2363379 --- /dev/null +++ b/ui/port_layer.gd @@ -0,0 +1,117 @@ +class_name PortLayer +extends Control +## Draws pipe ends on top of the cards: an inlet on each card and an outlet on +## each result. In Build mode, dragging from an outlet lays a new pipe. +## Only the ports themselves take mouse input; everything else passes through. + +const GRAB_RADIUS := 10.0 + +var main: Main +var _grab: Array = [] # [{pos, tid, eid}] outlets that can start a pipe +var _linking := false +var _ghost_from := Vector2.ZERO +var _ghost_to := Vector2.ZERO + + +func _init() -> void: + mouse_filter = MOUSE_FILTER_STOP + mouse_default_cursor_shape = CURSOR_CROSS + # Controls only draw inside their own rect, so cover the whole world. + size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) + + +func _process(_delta: float) -> void: + queue_redraw() + + +func _has_point(p: Vector2) -> bool: + if _linking: + return true + if main == null or main.mode != Main.Mode.BUILD: + return false + for g in _grab: + if p.distance_to(g["pos"]) <= GRAB_RADIUS: + return true + return false + + +func _draw() -> void: + _grab.clear() + var build := main.mode == Main.Mode.BUILD + var mouse := get_local_mouse_position() + for t in main.data.tables: + var card := main.card_for(t.id) + if card == null or not card.is_inside_tree(): + continue + _port(card.inlet_point(), Style.COPPER, Style.COPPER_DARK, 1.0) + for e in t.entries: + if not card.rows.has(e.id): + continue + var a := card.anchor_for(e.id) + if a.is_empty() or not a["visible"]: + continue + var on := not e.pipes.is_empty() + if not build and not on: + continue + var pos: Vector2 = a["pos"] + var fill := Style.COPPER if on else Style.CARD + var ring := Style.COPPER_DARK + var s := 1.0 + if on and main.is_entry_lit(t.id, e.id): + fill = Style.BRASS + ring = Style.BRASS_DARK + if build and pos.distance_to(mouse) <= GRAB_RADIUS and not _linking: + fill = Style.BRASS + s = 1.2 + _port(pos, fill, ring, s) + if build: + _grab.append({"pos": pos, "tid": t.id, "eid": e.id}) + if card.more_row != null: + var m := card.anchor_for("") + var on_hidden := card.hidden_has_pipes() + if not m.is_empty() and (on_hidden or build): + _port(m["pos"], Style.COPPER if on_hidden else Style.CARD, Style.COPPER_DARK, 1.0) + if _linking: + _draw_ghost(PipeLayer.curve(_ghost_from, _ghost_to)) + + +func _port(pos: Vector2, fill: Color, ring: Color, s: float) -> void: + draw_circle(pos, 8.0 * s, ring) + draw_circle(pos, 5.0 * s, fill) + + +func _draw_ghost(pts: PackedVector2Array) -> void: + var carry := 0.0 + for i in range(1, pts.size()): + var a := pts[i - 1] + var b := pts[i] + var seg := a.distance_to(b) + var d := carry + while d < seg: + draw_circle(a.lerp(b, d / seg), 2.5, Style.BRASS) + d += 11.0 + carry = d - seg + + +func _gui_input(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb and mb.button_index == MOUSE_BUTTON_LEFT: + if mb.pressed: + for g in _grab: + if mb.position.distance_to(g["pos"]) <= GRAB_RADIUS: + _linking = true + _ghost_from = g["pos"] + _ghost_to = mb.position + main.start_link(g["tid"], g["eid"]) + accept_event() + return + elif _linking: + _linking = false + main.finish_link() + accept_event() + return + var mm := ev as InputEventMouseMotion + if mm and _linking: + _ghost_to = mm.position + main.update_link() + accept_event() diff --git a/ui/port_layer.gd.uid b/ui/port_layer.gd.uid new file mode 100644 index 0000000..ae9df99 --- /dev/null +++ b/ui/port_layer.gd.uid @@ -0,0 +1 @@ +uid://2k7jy6gpuaob diff --git a/ui/result_tray.gd b/ui/result_tray.gd new file mode 100644 index 0000000..d13d29e --- /dev/null +++ b/ui/result_tray.gd @@ -0,0 +1,166 @@ +class_name ResultTray +extends PanelContainer +## The strip along the bottom: the current roll as a chain of result chips +## joined by brass pipe pieces, and a short list of earlier rolls. + +var main: Main +var _title: Label +var _again: Button +var _flow: HFlowContainer +var _empty: Label +var _earlier: VBoxContainer +var _earlier_empty: Label +var _shown_for: Dictionary = {} +var _shown_count := 0 + + +func setup(p_main: Main) -> void: + main = p_main + var sb := Style.box(Style.FELT_DEEP, 0, [16, 14, 16, 16]) + sb.border_width_top = 1 + sb.border_color = Color(1, 1, 1, 0.08) + add_theme_stylebox_override("panel", sb) + + var h := HBoxContainer.new() + h.add_theme_constant_override("separation", 28) + add_child(h) + + var now := VBoxContainer.new() + now.add_theme_constant_override("separation", 10) + now.size_flags_horizontal = SIZE_EXPAND_FILL + h.add_child(now) + var head := HBoxContainer.new() + head.add_theme_constant_override("separation", 12) + now.add_child(head) + _title = Style.make_label("RESULT", Style.caps(), 12, Style.ON_FELT_MUTED) + _title.size_flags_vertical = SIZE_SHRINK_CENTER + head.add_child(_title) + _again = Style.bar_button("Roll again") + _again.pressed.connect(func() -> void: + if not main.current.is_empty(): + main.start_roll(main.current["root"]) + ) + head.add_child(_again) + _flow = HFlowContainer.new() + _flow.add_theme_constant_override("h_separation", 0) + _flow.add_theme_constant_override("v_separation", 8) + # Keep the tray's height steady while a new roll's chips arrive. + _flow.custom_minimum_size = Vector2(0, 58) + now.add_child(_flow) + _empty = Style.make_label("Click a die on any table to roll.", Style.body(), 16, Style.ON_FELT_MUTED) + now.add_child(_empty) + + var earlier := VBoxContainer.new() + earlier.add_theme_constant_override("separation", 8) + earlier.custom_minimum_size = Vector2(300, 0) + h.add_child(earlier) + earlier.add_child(Style.make_label("EARLIER", Style.caps(), 12, Style.ON_FELT_MUTED)) + _earlier = VBoxContainer.new() + _earlier.add_theme_constant_override("separation", 6) + earlier.add_child(_earlier) + _earlier_empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED) + earlier.add_child(_earlier_empty) + + +func render() -> void: + var current := main.current + var steps: Array = current.get("steps", []) + var fresh_from := 0 + if is_same(current, _shown_for): + fresh_from = _shown_count + _shown_for = current + _shown_count = steps.size() + + for c in _flow.get_children(): + _flow.remove_child(c) + c.queue_free() + _empty.visible = current.is_empty() + if current.is_empty(): + _title.text = "RESULT" + _again.hide() + else: + var root_name: String = current["root_name"] + _title.text = ("Result · %s" % root_name).to_upper() + _again.text = "Roll %s again" % root_name + _again.visible = main.data.get_table(current["root"]) != null + var done: bool = current.get("done", false) + for i in steps.size(): + if i > 0: + _flow.add_child(_link()) + var chip := _chip(steps[i], done and i == steps.size() - 1) + _flow.add_child(chip) + if i >= fresh_from: + chip.modulate.a = 0.3 + create_tween().tween_property(chip, "modulate:a", 1.0, 0.25) + + for c in _earlier.get_children(): + _earlier.remove_child(c) + c.queue_free() + _earlier_empty.visible = main.history.is_empty() + for rec in main.history: + var row := HBoxContainer.new() + row.add_theme_constant_override("separation", 8) + var time := Style.make_label(clock(rec["time"]), Style.body(), 14, Style.ON_FELT_MUTED) + time.custom_minimum_size = Vector2(44, 0) + time.size_flags_vertical = SIZE_SHRINK_BEGIN + row.add_child(time) + var texts := PackedStringArray() + for s in rec["steps"]: + texts.append(s["text"]) + var line := RichTextLabel.new() + line.bbcode_enabled = true + line.fit_content = true + line.scroll_active = false + line.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + line.size_flags_horizontal = SIZE_EXPAND_FILL + line.add_theme_font_override("normal_font", Style.body()) + line.add_theme_font_size_override("normal_font_size", 14) + line.add_theme_color_override("default_color", Style.ON_FELT) + line.text = "[color=#%s]%s:[/color] %s" % [Style.ON_FELT_MUTED.to_html(false), _bb(rec["root_name"]), _bb(" → ".join(texts))] + row.add_child(line) + _earlier.add_child(row) + + +func _chip(step: Dictionary, last: bool) -> Control: + var p := PanelContainer.new() + var sb := Style.box(Style.LIT if last else Style.CARD, 9, [12, 7, 12, 8]) + sb.shadow_color = Color(0, 0, 0, 0.25) + sb.shadow_size = 1 + sb.shadow_offset = Vector2(0, 3) + if last: + Style.bordered(sb, 2, Style.BRASS) + sb.set_expand_margin_all(2) + p.add_theme_stylebox_override("panel", sb) + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 1) + p.add_child(v) + var num: String = step["num"] + var caption: String = step["table"] + if num != "": + caption += " · rolled %s on d%d" % [num, step["die"]] + v.add_child(Style.make_label(caption, Style.body(), 12, Style.MUTED)) + v.add_child(Style.make_label(step["text"], Style.display(), 20, Style.INK)) + return p + + +func _link() -> Control: + var link := Panel.new() + var sb := Style.box(Style.BRASS) + sb.border_width_top = 2 + sb.border_width_bottom = 2 + sb.border_color = Style.BRASS_DARK + link.add_theme_stylebox_override("panel", sb) + link.custom_minimum_size = Vector2(22, 8) + link.size_flags_vertical = SIZE_SHRINK_CENTER + link.mouse_filter = MOUSE_FILTER_IGNORE + return link + + +static func _bb(text: String) -> String: + return text.replace("[", "[lb]") + + +static func clock(unix: float) -> String: + var bias: int = Time.get_time_zone_from_system().get("bias", 0) + var d := Time.get_datetime_dict_from_unix_time(int(unix) + bias * 60) + return "%02d:%02d" % [d["hour"], d["minute"]] diff --git a/ui/result_tray.gd.uid b/ui/result_tray.gd.uid new file mode 100644 index 0000000..c75d89a --- /dev/null +++ b/ui/result_tray.gd.uid @@ -0,0 +1 @@ +uid://htxsmwhs2m5y diff --git a/ui/style.gd b/ui/style.gd new file mode 100644 index 0000000..236a071 --- /dev/null +++ b/ui/style.gd @@ -0,0 +1,188 @@ +class_name Style +extends RefCounted +## Palette, fonts and stylebox helpers for the felt-board look. + +const FELT := Color("#1f4a39") +const FELT_DEEP := Color("#12301f") +const FELT_HOVER := Color("#276048") +const CARD := Color("#efece2") +const INK := Color("#1c2520") +const MUTED := Color("#69726b") +const RULE := Color("#d8d3c3") +const COPPER := Color("#b8703a") +const COPPER_DARK := Color("#4f2b12") +const BRASS := Color("#f3c450") +const BRASS_DARK := Color("#6e5410") +const LIT := Color("#f8e4a2") +const FLICK := Color(0.953, 0.769, 0.314, 0.35) +const HOVER_ROW := Color("#e9e4d6") +const ON_FELT := Color("#e9efe9") +const ON_FELT_MUTED := Color("#a8bdb1") +const DANGER := Color("#e0574a") +const DANGER_INK := Color("#a33a2c") +const WARN_BG := Color("#f4dacb") +const WARN_INK := Color("#8a2f1d") +const DASH := Color("#bdb6a2") +const PULSE := Color("#fff6d2") + +const FONT_DIR := "res://assets/fonts/" + +static var _fonts: Dictionary = {} + + +# ---------- Fonts ---------- +# Cards live on the zoomable board, so they use MSDF fonts that stay sharp at any scale. + +static func _file(file: String, msdf: bool) -> FontFile: + var key := "%s|%s" % [file, msdf] + if not _fonts.has(key): + var f: FontFile = load(FONT_DIR + file) + if msdf: + f = f.duplicate() as FontFile + f.multichannel_signed_distance_field = true + _fonts[key] = f + return _fonts[key] + + +static func body(msdf: bool = false) -> Font: + return _file("AtkinsonHyperlegible-Regular.ttf", msdf) + + +static func body_bold(msdf: bool = false) -> Font: + return _file("AtkinsonHyperlegible-Bold.ttf", msdf) + + +static func body_italic(msdf: bool = false) -> Font: + return _file("AtkinsonHyperlegible-Italic.ttf", msdf) + + +## Rokkitt, the slab display face. It's a variable font with overlapping +## outlines, which MSDF renders badly, so on cards it is oversampled instead. +static func display(zoomable: bool = false, weight: int = 700) -> Font: + var key := "display|%d|%s" % [weight, zoomable] + if not _fonts.has(key): + var v := FontVariation.new() + var base := _file("Rokkitt-Variable.ttf", false) + if zoomable: + base = base.duplicate() as FontFile + base.oversampling = 2.0 + v.base_font = base + v.variation_opentype = {TextServerManager.get_primary_interface().name_to_tag("wght"): weight} + _fonts[key] = v + return _fonts[key] + + +## Bold body face with a little letter-spacing, for small uppercase labels. +static func caps() -> Font: + if not _fonts.has("caps"): + var v := FontVariation.new() + v.base_font = body_bold() + v.spacing_glyph = 1 + _fonts["caps"] = v + return _fonts["caps"] + + +# ---------- Styleboxes ---------- + +## margins: [left, top, right, bottom] +static func box(bg: Color, radius: int = 0, margins: Array = [0, 0, 0, 0]) -> StyleBoxFlat: + var s := StyleBoxFlat.new() + s.bg_color = bg + s.set_corner_radius_all(radius) + s.content_margin_left = margins[0] + s.content_margin_top = margins[1] + s.content_margin_right = margins[2] + s.content_margin_bottom = margins[3] + s.anti_aliasing = true + return s + + +static func bordered(s: StyleBoxFlat, width: int, color: Color) -> StyleBoxFlat: + s.set_border_width_all(width) + s.border_color = color + return s + + +static func focus_ring(radius: int = 8) -> StyleBoxFlat: + var s := box(Color(0, 0, 0, 0), radius) + s.draw_center = false + bordered(s, 2, BRASS) + s.set_expand_margin_all(2) + return s + + +static func skin_button(b: Button, normal: StyleBox, hover: StyleBox, pressed: StyleBox, + fg: Color, fg_hover: Color = Color(0, 0, 0, 0), fg_pressed: Color = Color(0, 0, 0, 0)) -> void: + if fg_hover.a == 0.0: + fg_hover = fg + if fg_pressed.a == 0.0: + fg_pressed = fg_hover + b.add_theme_stylebox_override("normal", normal) + b.add_theme_stylebox_override("hover", hover) + b.add_theme_stylebox_override("pressed", pressed) + b.add_theme_stylebox_override("hover_pressed", pressed) + b.add_theme_stylebox_override("disabled", normal) + b.add_theme_stylebox_override("focus", focus_ring()) + b.add_theme_color_override("font_color", fg) + b.add_theme_color_override("font_hover_color", fg_hover) + b.add_theme_color_override("font_focus_color", fg) + b.add_theme_color_override("font_pressed_color", fg_pressed) + b.add_theme_color_override("font_hover_pressed_color", fg_pressed) + b.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND + + +static func make_label(text: String, font: Font, font_size: int, color: Color) -> Label: + var l := Label.new() + l.text = text + l.add_theme_font_override("font", font) + l.add_theme_font_size_override("font_size", font_size) + l.add_theme_color_override("font_color", color) + return l + + +## A top-bar button: translucent on felt, or brass when primary. +static func bar_button(text: String, primary: bool = false) -> Button: + var b := Button.new() + b.text = text + var normal := bordered(box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16)) + var hover := bordered(box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16)) + var fg := ON_FELT + if primary: + normal = bordered(box(BRASS, 8, [12, 6, 12, 6]), 1, BRASS) + hover = bordered(box(BRASS.lightened(0.15), 8, [12, 6, 12, 6]), 1, BRASS.lightened(0.15)) + fg = INK + b.add_theme_font_override("font", body_bold()) + skin_button(b, normal, hover, hover, fg) + b.add_theme_font_size_override("font_size", 15) + return b + + +# ---------- Themes ---------- + +static func app_theme() -> Theme: + var th := Theme.new() + th.default_font = body() + th.default_font_size = 16 + th.set_color("font_color", "Label", ON_FELT) + th.set_stylebox("panel", "TooltipPanel", box(CARD, 6, [8, 5, 8, 5])) + th.set_color("font_color", "TooltipLabel", INK) + return th + + +static func card_theme() -> Theme: + var th := Theme.new() + th.default_font = body(true) + th.default_font_size = 16 + th.set_color("font_color", "Label", INK) + var normal := bordered(box(Color(1, 1, 1, 0), 5, [6, 3, 6, 3]), 1, Color(1, 1, 1, 0)) + var focus := bordered(box(Color.WHITE, 5, [6, 3, 6, 3]), 1, COPPER) + th.set_stylebox("normal", "LineEdit", normal) + th.set_stylebox("focus", "LineEdit", focus) + th.set_stylebox("read_only", "LineEdit", normal) + th.set_color("font_color", "LineEdit", INK) + th.set_color("caret_color", "LineEdit", INK) + th.set_color("selection_color", "LineEdit", Color(BRASS, 0.55)) + th.set_color("font_placeholder_color", "LineEdit", MUTED) + # Card fields are sized by their containers, not by a minimum character count. + th.set_constant("minimum_character_width", "LineEdit", 0) + return th diff --git a/ui/style.gd.uid b/ui/style.gd.uid new file mode 100644 index 0000000..04f92ea --- /dev/null +++ b/ui/style.gd.uid @@ -0,0 +1 @@ +uid://bpj6lb2k0d6fo diff --git a/ui/table_card.gd b/ui/table_card.gd new file mode 100644 index 0000000..76bd7e8 --- /dev/null +++ b/ui/table_card.gd @@ -0,0 +1,571 @@ +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. + +const WIDTH := 256.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 + + +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_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])) + + minimum_size_changed.connect(func() -> void: _shrink.call_deferred()) + 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 = "" + + var build := main.mode == Main.Mode.BUILD + var ranged := table.is_ranged() + var col := _vbox(0) + add_child(col) + col.add_child(_make_header(build, ranged)) + + 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 table.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 table.collapsed and not lit: + continue + _list_box.add_child(_make_row(e, i, build, ranged, numw)) + _set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL) + if table.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() + if list_scroll != null: + for eid in rows: + if main.is_entry_lit(table.id, eid): + _reveal_when_laid_out.call_deferred(eid) + break + + +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) + header.add_child(row) + + 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) + + 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) + else: + var titles := _vbox(3) + titles.size_flags_horizontal = SIZE_EXPAND_FILL + titles.size_flags_vertical = SIZE_SHRINK_CENTER + var title := Style.make_label(table.name, Style.display(true), 20, Style.INK) + title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + titles.add_child(title) + if ranged or table.collapsed: + var count := "%d %s" % [table.entries.size(), "ranges" if ranged else "results"] + titles.add_child(Style.make_label(count, Style.body(true), 12, Style.MUTED)) + row.add_child(titles) + + var die := table.die_size() + var roll := Button.new() + roll.text = "d%d" % die + roll.tooltip_text = "Roll d%d on %s" % [die, table.name] + roll.size_flags_vertical = SIZE_SHRINK_CENTER + roll.add_theme_font_override("font", Style.display(true)) + roll.add_theme_font_size_override("font_size", 17) + var rn := Style.box(Style.FELT, 8, [34, 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(roll, rn, rh, rp, Style.BRASS) + _die_icon = DieIcon.new() + _die_icon.spinning = _rolling + roll.add_child(_die_icon) + roll.resized.connect(func() -> void: _die_icon.position = Vector2(8, (roll.size.y - 20.0) / 2.0 - 1.0)) + roll.pressed.connect(func() -> void: main.start_roll(table.id)) + row.add_child(roll) + return header + + +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) + + 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: + num = Style.make_label(table.num_label(e, index), 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 + h.add_child(num) + + var text: Label = null + if build: + var edit := LineEdit.new() + edit.text = e.text + 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) + edit.text_changed.connect(func(s: String) -> void: + e.text = s + main.mark_dirty() + ) + h.add_child(edit) + var x := Button.new() + x.text = "×" + x.tooltip_text = "Delete this result" + x.custom_minimum_size = Vector2(22, 22) + x.size_flags_vertical = SIZE_SHRINK_CENTER + x.add_theme_font_size_override("font_size", 18) + Style.skin_button(x, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK) + x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id)) + h.add_child(x) + else: + text = Style.make_label(e.text, Style.body(true), 16, Style.INK) + text.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + text.size_flags_horizontal = SIZE_EXPAND_FILL + text.size_flags_vertical = SIZE_SHRINK_CENTER + h.add_child(text) + if ranged: + 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} + return row + + +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(), 1, 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() + _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) + var add := _footer_button("+ Add range" if ranged else "+ Add result", Style.INK) + add.pressed.connect(func() -> void: main.add_entry(table.id)) + h.add_child(add) + 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 table", Style.DANGER_INK) + 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 + (rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[state]) + 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: Label = parts["text"] + if text: + text.add_theme_font_override("font", Style.body_bold(true) if state == RowState.LIT else Style.body(true)) + + +func _apply_style() -> void: + var s := _style_normal + if _drop_target: + s = _style_drop + elif _rolling: + s = _style_rolling + elif _dragging: + s = _style_dragging + add_theme_stylebox_override("panel", s) + + +func _shrink() -> void: + size = Vector2(WIDTH, 0) + + +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: + if table.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: + _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(): + 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() + + +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: + _dragging = true + _drag_offset = main.board.world_mouse() - position + get_parent().move_child(self, -1) + else: + _dragging = false + 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 + position = Vector2(maxf(10.0, roundf(p.x)), maxf(10.0, roundf(p.y))) + table.position = position + header.accept_event() diff --git a/ui/table_card.gd.uid b/ui/table_card.gd.uid new file mode 100644 index 0000000..fad3712 --- /dev/null +++ b/ui/table_card.gd.uid @@ -0,0 +1 @@ +uid://d3m72ntlmi6t6