class_name Roller extends RefCounted ## Rolls a table and follows its pipes and inline references, producing a ## result tree. ## ## Each node is a Dictionary: ## table: RollTable, value: int (die value), index: int, entry: TableEntry, ## summary: String (the entry text with [[refs]] and {vars} expanded, as ## BBCode with TextExpander's internal [url] markers), ## children: Array of nodes (inline reference rolls first, marked ## "inline": true, then pipe rolls in pipe order), ## and "stop": String when the chain couldn't continue (its summary then ## explains why). ## Logic-card keys (docs/LOGIC.md), present only when they apply: ## kind: "choice" | "loop" | "sheet" | "router" (plain roll nodes have no kind) ## case: int, on a router node: the index of the case that matched ## effects: Array of {"text": String, "error": true?}, the effect log ## answer: the player's answer on a number/text choice (int or String) ## picked: true when the player picked a pick option; random: true for Random ## option: on a pick node for a dynamic option (options_from), its label ## passes: int, on a loop's header node ("Repeated N times"); its children ## are one node per pass ("pass": i, "value": i) and then the Afterwards ## node ("after": true) ## limit: true on the "Stopped after 10,000 actions" stop node ## cancelled: true on the "Cancelled" stop node ## check: on a check card's node, {nat, mod, total, target, success} ## (its "value" is the total; "index" 0 is Success, 1 Failure) ## inputs: {name: value}, the card inputs bound while this node's subtree ## ran (docs/PLAIN.md §4.2) ## why: Array of trace facts (plain Dictionaries with a "type"; see ## docs/LOGIC.md §10 and Describe.why()), present when there are any ## ## The roller is a coroutine with an explicit work stack: pipes and loop passes ## never recurse in GDScript, so chains of thousands of steps are fine. Only ## inline [[references]] nest (at most RollContext.max_depth deep). ## ## The parts: RollPipes (pipe snapshots, card inputs, pipe and pause frames), ## RollCards (plain picks, routers, checks, loops), RollChoice (choice cards), ## RollNodes (building result nodes), RollLive (live values for variable and ## sheet cards), RollTree (reading the result tree, lit keys) and RollLint ## (static board checks). ## ## roll_async() is the main entry point. It awaits ctx.prompt for choice cards ## and fills in ctx.root as it goes. roll() is the plain form: it never waits ## (choices get the headless answers) and returns the tree directly. ## Deepest level inline references can nest (matches RollContext). const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH ## Most actions one top-level roll may take (matches RollContext). const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS const CANCELLED := "Cancelled" const NO_CASE := "No case matched" const NO_OPTIONS := "No options available" enum { OP_ROLL, OP_PIPE, OP_LOOP, OP_RESTORE, OP_COMBINE, OP_PAUSE } ## A paused thread the player chose not to continue. const STOPPED_HERE := "Stopped here" ## A RollContext wired to this board: it resolves [[names]] against the board's ## tables and rolls inline references through the roller. `persistent` is the ## collection's persistent variables (name without "@" -> {value, source}), ## shared, not copied. `decks` maps table id to DeckState for card-mode tables, ## also shared. Set ctx.prompt to ask the player on choice cards. static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persistent: Dictionary = {}, decks: Dictionary = {}) -> RollContext: var ctx := RollContext.new(persistent, rng) ctx.max_depth = MAX_DEPTH ctx.board = board ctx.set_meta("decks", decks) # A weak reference, so the context doesn't keep itself alive through its hooks. var wr: WeakRef = weakref(ctx) ctx.resolve_table = func(name_or_id: String) -> String: return resolve(board, name_or_id) ctx.roll_table = func(id: String, depth: int) -> Dictionary: var c: RollContext = wr.get_ref() return {} if c == null else _chain_sync(board, id, depth, c) ctx.roll_table_async = func(id: String, depth: int) -> Dictionary: var c: RollContext = wr.get_ref() if c == null: return {} return await _chain(board, id, depth, c) return ctx ## Table id for a [[reference]]: an exact id, or a name matched ## case-insensitively without BBCode. "" if there's no such table. static func resolve(board: TowerBoard, name_or_id: String) -> String: var key := name_or_id.strip_edges() if board.get_table(key) != null: return key var want := RollContext.normalize_name(key) if want == "": return "" for t in board.tables: if RollContext.normalize_name(t.name) == want: return t.id return "" ## Rolls `table_id` and everything its pipes and references lead to, without ## ever waiting: choice cards get the headless answers (Random, min, ""). ## `decks` maps table id to DeckState for card-mode tables; missing decks are ## created in it on demand. `ctx` carries the variables for the whole chain. ## Without one, a fresh context (no persistent variables) is made around ## `decks`; a context from new_context() brings its own decks and `decks` is ## then ignored. Extra node keys: "save_as" (on nodes reached through a pipe ## that saves), "reshuffled" (card deck was refilled for this draw), "inline" ## (rolled by a [[reference]] in the parent's text), and the logic-card keys ## listed at the top of this file. static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0, decks: Dictionary = {}, ctx: RollContext = null) -> Dictionary: if ctx == null: ctx = new_context(board, rng, {}, decks) elif not ctx.has_meta("decks"): ctx.set_meta("decks", decks) var was := ctx.no_prompt ctx.no_prompt = true var r: Variant = Callable(Roller, "roll_async").call(board, table_id, ctx, depth) ctx.no_prompt = was return r if r is Dictionary else {} ## The coroutine roll: `await Roller.roll_async(board, id, ctx)`. Choice cards ## await ctx.prompt (see RollChoice.ask()); with no prompt hook it finishes without ## waiting a frame. ctx.root holds the tree so far while it runs (see ## progress()). Resets the action counter, ctx.halted and ctx.root unless it's ## called from inside a running roll. static func roll_async(board: TowerBoard, table_id: String, ctx: RollContext, depth: int = 0) -> Dictionary: if ctx.board == null: ctx.board = board if not ctx.has_meta("decks"): ctx.set_meta("decks", {}) if ctx.running == 0: ctx.actions = 0 ctx.halted = "" ctx.root = {} ctx.forget_declarations() apply_starting_values(board, ctx) return await _chain(board, table_id, depth, ctx) ## Sets declared variables to their starting values (RollLive). static func apply_starting_values(board: TowerBoard, ctx: RollContext) -> void: RollLive.apply_starting_values(board, ctx) ## The steps of the tree built so far (ctx.root), e.g. while a prompt is open. static func progress(ctx: RollContext) -> Array: return RollTree.flatten(ctx.root, []) ## "Stopped after 10,000 actions". static func limit_text(n: int = MAX_ACTIONS) -> String: var s := str(n) var out := "" while s.length() > 3: out = "," + s.substr(s.length() - 3) + out s = s.substr(0, s.length() - 3) return "Stopped after %s actions" % (s + out) static func _chain_sync(board: TowerBoard, id: String, depth: int, ctx: RollContext) -> Dictionary: var was := ctx.no_prompt ctx.no_prompt = true var r: Variant = Callable(Roller, "_chain").call(board, id, depth, ctx) ctx.no_prompt = was return r if r is Dictionary else {} ## Runs one chain (a top-level roll, or one inline reference) on its own work ## stack. Returns its first node, or {} when the table is missing or is a ## variable card. static func _chain(board: TowerBoard, table_id: String, depth: int, ctx: RollContext) -> Dictionary: ctx.running += 1 var holder := {"children": []} var stack: Array = [{"op": OP_ROLL, "id": table_id, "parent": holder, "save": "", "depth": depth, "top": ctx.running == 1}] while not stack.is_empty() and ctx.halted == "": var f: Dictionary = stack.pop_back() match int(f["op"]): OP_ROLL: await _do_roll(board, f, ctx, stack) OP_PIPE: RollPipes.do_pipe(board, f, stack) OP_LOOP: await RollCards.do_loop(f, ctx, stack) OP_RESTORE: RollPipes.restore(f, ctx) OP_COMBINE: var keep: Dictionary = await RollCombine.run(f, ctx) if not keep.is_empty(): RollPipes.queue_pipes(keep, ctx, stack, int(f["depth"])) OP_PAUSE: await RollPipes.do_pause(board, f, ctx, stack) # A halted roll leaves frames behind: put back any card inputs they hid. while not stack.is_empty(): var rest: Dictionary = stack.pop_back() if int(rest["op"]) == OP_RESTORE: RollPipes.restore(rest, ctx) ctx.running -= 1 var kids: Array = holder["children"] return kids[0] if not kids.is_empty() else {} # Node helpers (RollNodes); the other roll parts call these too. static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary: return RollNodes.stop(t, why, extra) static func _attach(f: Dictionary, node: Dictionary, ctx: RollContext) -> void: RollNodes.attach(f, node, ctx) ## Counts one action, or stops the roll at the limit. False when it has to stop. static func _take_action(f: Dictionary, t: RollTable, ctx: RollContext) -> bool: return RollNodes.take_action(f, t, ctx) static func _why(node: Dictionary, facts: Array) -> void: RollNodes.add_why(node, facts) static func _log(node: Dictionary, lines: Array) -> void: RollNodes.add_log(node, lines) static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void: var t := board.get_table(str(f["id"])) if t == null or t.kind == RollTable.KIND_VARIABLE: return if not _take_action(f, t, ctx): return RollPipes.bind_inputs(t, f, ctx, stack) if not await RollCosts.card_gate(board, t, f, ctx): return if t.entries.is_empty(): _attach(f, _stop(t, "This table has no results"), ctx) return match t.kind: RollTable.KIND_CHOICE: await RollChoice.run(t, f, ctx, stack) RollTable.KIND_LOOP: RollCards.start_loop(t, f, ctx, stack) RollTable.KIND_ROUTER: await RollCards.do_router(t, f, ctx, stack) RollTable.KIND_CHECK: await RollCards.do_check(t, f, ctx, stack) RollTable.KIND_SHEET: var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "", "kind": RollTable.KIND_SHEET} _attach(f, sheet, ctx) await _enter(sheet, f, ctx, stack, true, true) _: var node := RollCards.pick_for(t, ctx, f) if node.has("nat"): ctx.chain_vars["nat"] = node["nat"] node.erase("nat") _attach(f, node, ctx) if not node.has("stop"): await _enter(node, f, ctx, stack) ## The chosen entry happens: its effects run, its text expands (unless ## `expand` is false, for answers) and its pipes are queued. `live` renders the ## text without rolling references (sheet cards). ## ## Before any pipe runs, every pipe's condition and count is worked out once, ## as a snapshot (see RollPipes.pipe_plan()), so what an earlier pipe's subtree does to ## the variables can't change whether or how often a later pipe runs. static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Array, expand: bool = true, live: bool = false) -> void: var t: RollTable = node["table"] var e: TableEntry = node["entry"] var depth := int(f.get("depth", 0)) if e.effects.strip_edges() != "": var facts: Array = [] _log(node, Effects.run(e.effects, ctx, t.id, facts)) _why(node, facts) if expand: ctx.depth = depth + 1 var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live) ctx.depth = depth var kids: Array = node["children"] for c: Dictionary in ex["children"]: c["inline"] = true kids.append(c) node["summary"] = ex["text"] if t.has_columns() and not node.has("kind"): await RollColumns.fill(node, f, ctx, depth) ctx.depth = depth # The Chosen entry of a dynamic pick reads as the option's label unless # it has text of its own. if node.has("option"): var plain := Formatter.strip_tags(e.text).strip_edges() if plain == "" or plain == RollChoice.CHOSEN: node["summary"] = Formatter.escape_literal(str(node["option"])) if ctx.halted != "": return var save := str(f.get("save", "")) if save != "": var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"])) ctx.save_result(save, v, t.id) # A picked option is saved under the choice's save_as before the pipe # snapshot, so its own pipe conditions can read it. if t.kind == RollTable.KIND_CHOICE and t.save_as != "" and not node.has("answer"): if node.has("option"): ctx.save_result(t.save_as, str(node["option"]), t.id) else: ctx.save_result(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id) if e.pipes.is_empty(): return # A roll that is being combined with others (RollCombine) waits: only the # one that's kept follows its threads. if f.get("no_follow", false): return RollPipes.queue_pipes(node, ctx, stack, depth) ## A context for showing values live (variable and sheet cards, previews; RollLive). static func live_context(board: TowerBoard, persistent: Dictionary) -> RollContext: return RollLive.live_context(board, persistent) ## A variable card's live value: {"text", "set", "error"} (RollLive). static func variable_display(board: TowerBoard, persistent: Dictionary, t: RollTable) -> Dictionary: return RollLive.variable_display(board, persistent, t) ## A sheet card's template rendered with current values (RollLive). static func render_sheet(board: TowerBoard, persistent: Dictionary, t: RollTable) -> String: return RollLive.render_sheet(board, persistent, t) # ---------- Delegators (the parts live in RollChoice, RollTree, RollLint) ---------- ## The default text of a dynamic card's Chosen entry (RollChoice.CHOSEN). const CHOSEN := RollChoice.CHOSEN static func request_for(t: RollTable, ctx: RollContext) -> Dictionary: return RollChoice.request_for(t, ctx) static func dynamic_options(t: RollTable, ctx: RollContext, log: Array = [], why: Array = []) -> Array: return RollChoice.dynamic_options(t, ctx, log, why) static func available_count(t: RollTable, ctx: RollContext) -> int: return RollChoice.available_count(t, ctx) static func ask(ctx: RollContext, req: Dictionary) -> Variant: return await RollChoice.ask(ctx, req) static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: return RollTree.step_of(n, depth) static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array: return RollTree.flatten(n, out, depth) static func reaches(n: Dictionary, table_id: String) -> bool: return RollTree.reaches(n, table_id) static func last_sheet(n: Dictionary) -> Dictionary: return RollTree.last_sheet(n) static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary, texts: Dictionary = {}) -> void: RollTree.collect_lit(n, entries, pipes, texts) static func entry_key(table_id: String, entry_id: String) -> String: return RollTree.entry_key(table_id, entry_id) static func pipe_key(table_id: String, entry_id: String, to_id: String) -> String: return RollTree.pipe_key(table_id, entry_id, to_id) static func ref_key(table_id: String, entry_id: String, to_id: String) -> String: return RollTree.ref_key(table_id, entry_id, to_id) static func is_ref_key(key: String) -> bool: return RollTree.is_ref_key(key) static func link_key(table_id: String, entry_id: String, c: Dictionary) -> String: return RollTree.link_key(table_id, entry_id, c) static func ref_targets(board: TowerBoard, text: String) -> Array[String]: return RollTree.ref_targets(board, text) static func endless_cycles(board: TowerBoard) -> Array[String]: return RollLint.endless_cycles(board) static func lint_pipes(board: TowerBoard) -> Array[Dictionary]: return RollLint.lint_pipes(board) static func lint_router(t: RollTable) -> Array[Dictionary]: return RollLint.lint_router(t) static func lint_options(t: RollTable) -> Array[Dictionary]: return RollLint.lint_options(t) static func lint_check(t: RollTable) -> Array[Dictionary]: return RollLint.lint_check(t) static func lint_inputs(board: TowerBoard, t: RollTable) -> Array[Dictionary]: return RollLint.lint_inputs(board, t)