TableTower/ui/pipe_layer.gd

317 lines
12 KiB
GDScript3
Raw Normal View History

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.
##
## [[References]] in an entry's text draw as thinner dashed pipes. They come from
## the text, so they can't be clicked or removed here.
##
## Conditional pipes (an "Only if" condition, or "otherwise") have a small
## diamond at their source end, and pipes with options a label, so the
## branches of an entry read at a glance. Labels read in plain words
## (Describe.pipe: "Tier 3 · only if Luck is 2 or more", "otherwise") or as
## the stored text ("if @luck >= 2"), following RulesView.plain(main).
##
## Pipes to or from tables hidden in a collapsed group attach to that group's
## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so
## they still light up and carry the bead; pipes inside one collapsed group
## aren't drawn.
var main: Main
var hover_key: String = ""
## The pipe whose options are open in Build mode.
var select_key: String = ""
var pulse_key: String = ""
var pulse_t: float = 0.0
var _trail: CPUParticles2D
## pipe key -> polyline in world coordinates, from the last frame.
var _paths: Dictionary = {}
## Keys of pipes drawn to or from a collapsed group card (not clickable: many
## share one line).
var _rerouted: Dictionary = {}
## Vector2i -> lit: where pipes leave collapsed group cards, for PortLayer.
var group_ports: Dictionary = {}
var _label_box: StyleBoxFlat
var _lit_label_box: StyleBoxFlat
## What the last redraw was drawn from (see _process).
var _drawn_state: Array = []
## Draws the unlit pipes, each in a canvas item of its own (PipeBatch), so the
## renderer skips the ones out of view; lit pipes, labels and the bead are
## drawn by _draw on top.
var _batch := PipeBatch.new(self)
func _init() -> void:
mouse_filter = MOUSE_FILTER_IGNORE
BoardView.cover_world(self)
_label_box = Style.box(Style.CARD, 7, [6, 1, 6, 2])
Style.bordered(_label_box, 1, Style.THREAD_DARK)
_lit_label_box = Style.box(Style.LIT, 7, [6, 1, 6, 2])
Style.bordered(_lit_label_box, 1, Style.ACCENT_DARK)
## Redraws only when something it draws changed: the board's geometry
## (BoardView.geometry_rev: cards moved, resized, rebuilt or scrolled, lit
## results, edits), the hovered or selected pipe, or the travelling bead.
func _process(_delta: float) -> void:
if main == null or main.board == null:
return
_move_trail()
var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far, RulesView.plain(main)]
if state != _drawn_state:
_drawn_state = state
queue_redraw()
## Sparkles follow the pulse up the thread (Sparkles.trail).
func _move_trail() -> void:
var on := pulse_key != "" and _paths.has(pulse_key)
if on and _trail == null:
_trail = Sparkles.trail()
add_child(_trail)
if _trail:
if on:
_trail.global_position = get_global_transform() * point_along(_paths[pulse_key], pulse_t)
_trail.emitting = on
func _notification(what: int) -> void:
if what == NOTIFICATION_PREDELETE:
_batch.free_items()
## A smooth curve between two points (PipeGeometry.curve).
static func curve(start: Vector2, end: Vector2, down: bool = false) -> PackedVector2Array:
return PipeGeometry.curve(start, end, down)
func _draw() -> void:
_batch.begin(main.board.cards.far)
_paths.clear()
_rerouted.clear()
group_ports.clear()
var lit_list: Array = []
var lit_refs: Array = []
var labels: Array = []
var diamonds: Array = [] # [point, lit, otherwise]
var drawn := {} # endpoints of rerouted pipes already drawn (they overlap)
var build := main.mode == Main.Mode.BUILD
var plain := RulesView.plain(main)
# Tables hidden in a collapsed group -> that group's card. Their pipes leave
# from the group card's right edge and arrive at its inlet.
var hidden := main.hidden_groups()
for t in main.data.tables:
# Tables hidden in a collapsed group have no card (Main builds them
# lazily); their pipes leave from the group card.
var card := main.card_for(t.id)
var src_g: GroupCard = hidden.get(t.id)
if card == null and src_g == null:
continue
for e in t.thread_sources():
var refs := main.ref_targets_for(e)
if e.pipes.is_empty() and refs.is_empty():
continue
var a: Dictionary
if src_g:
a = {"pos": src_g.anchor_for(t.id, e.id), "visible": true}
else:
a = card.anchor_for(e.id)
if a.is_empty():
continue
for i in refs.size() + e.pipes.size():
var is_ref := i < refs.size()
var to: String = refs[i] if is_ref else e.pipes[i - refs.size()]
var target := main.card_for(to)
var dst_g: GroupCard = hidden.get(to)
if target == null and dst_g == null:
continue
if src_g != null and dst_g == src_g:
continue # inside one collapsed group
var key := Roller.ref_key(t.id, e.id, to) if is_ref else Roller.pipe_key(t.id, e.id, to)
var end: Vector2 = dst_g.inlet_point() if dst_g else target.inlet_point()
var pts := curve(a["pos"], end, e == t.outlet and src_g == null)
_paths[key] = pts
var lit := main.lit_pipes.has(key)
var rerouted := src_g != null or dst_g != null
if rerouted:
_rerouted[key] = true
if src_g:
var pk := Vector2i(a["pos"])
group_ports[pk] = bool(group_ports.get(pk, false)) or main.is_entry_lit(t.id, e.id)
if not is_ref and not rerouted and e.is_conditional(to):
diamonds.append([pts, lit, e.is_otherwise(to)])
if lit:
(lit_refs if is_ref else lit_list).append(pts)
if not is_ref and not rerouted:
var lt := RulesView.pipe_label(e, to, main.data, plain)
if lt != "":
labels.append([pts, lt, true])
continue
if rerouted:
var dk := "%s|%s|%s" % [Vector2i(a["pos"]), Vector2i(end), is_ref]
if drawn.has(dk):
continue
drawn[dk] = true
if is_ref:
_batch.add_ref(pts)
elif rerouted:
_batch.add_bundle(pts)
else:
_batch.add_pipe(pts, build and (key == hover_key or key == select_key), str(e.pipe_color.get(to, "")))
if not is_ref and not rerouted:
var tag := RulesView.pipe_label(e, to, main.data, plain)
if tag != "":
labels.append([pts, tag, false])
# Lit pipes go on top so the path of the last roll reads clearly.
for pts in lit_refs:
_draw_ref(pts, true)
for pts in lit_list:
_draw_pipe(pts, true, false)
for d in diamonds:
_draw_diamond(d[0], d[1], d[2])
var placed: Array[Rect2] = []
for l in labels:
_draw_tag(l[0], l[1], l[2], placed)
if pulse_key != "" and _paths.has(pulse_key):
var p := point_along(_paths[pulse_key], pulse_t)
var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0
draw_circle(p, 13.0 * r, Color(Style.ACCENT, 0.3))
draw_circle(p, 9.0 * r, Color(Style.ACCENT, 0.5))
draw_circle(p, 7.0 * r, Style.PULSE)
## The text-mode label: "tier=3 if @str >= 8 ×2 → foe" / "otherwise" for a
## pipe with options, or "".
static func _pipe_tag(e: TableEntry, to: String) -> String:
var parts := PackedStringArray()
var wv := e.with_for(to)
for nm: String in wv:
parts.append("%s=%s" % [nm, RulesView.cut(str(wv[nm]), 12)])
var w := e.when_for(to)
if w != "":
parts.append("if " + (w if w.length() <= 24 else w.substr(0, 23) + "…"))
elif e.is_otherwise(to):
parts.append("otherwise")
Logic cards UI: choice pop-up, card kinds, Build creation and settings, tray - ChoiceDialog: card-styled pop-up for pick (option rows with details, Random, 1-9 / R keys), number (spin box with min/max/default, Enter) and text. Cancel, Esc, freeing the dialog, a new roll or a collection switch all answer null through a separate Reply object, so a roll never hangs. - Main: real prompt hook; the steps so far light on the board and in the tray before each question; a roll with questions shows the rest at once; a new roll cancels an open question cleanly; refresh_live() re-renders variable, sheet and question text only after rolls and edits. - TableCard: "?" badge and question for choice cards, loop icon, rule chip and Each time / Afterwards rows, compact live variable cards (reset in Build), live sheet cards with one outlet, expression-dice subtitles, effect chips in Play and a validated effects editor in Build. - Build: "+ Table" menu for every kind; kind-specific settings (choice type, question, save as, min/max; loop mode and rule; variable name, type, starting value; sheet template) checked with Expr.check; expression pipe counts in the pipe popover and on pipe labels. - Tray: effect lines under chips, last 12 steps behind "+N earlier steps", sheet headline, Cancelled / action-limit pill, capped indents and Earlier rows; Variables tab lists every board variable with Reset all. - RichText: error markers in red; previews show {@x_*} and {= expr}. - examples/logic_demo.json and tests/test_logic_ui.gd. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 14:07:57 -06:00
if e.count_expr(to) != "":
var ex := e.count_expr(to)
parts.append("×" + (ex if ex.length() <= 18 else ex.substr(0, 17) + "…"))
elif e.count_for(to) > 1:
parts.append("×%d" % e.count_for(to))
if e.save_for(to) != "":
parts.append("→ " + e.save_for(to))
return " ".join(parts)
## A label on a pipe, at its middle, or a little along it when that spot
## overlaps a label already drawn (`placed`, which it adds to).
func _draw_tag(pts: PackedVector2Array, text: String, lit: bool = false, placed: Array[Rect2] = []) -> void:
var font := Style.body_bold(true)
var fs := 12
var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
# Labels sit behind the cards, so a long one is cut to the gap between
# the cards it joins (the whole rule shows in the row's hover summary).
var room := maxf(80.0, absf(pts[pts.size() - 1].x - pts[0].x) - 30.0) if pts.size() > 1 else 200.0
while w + 12.0 > room and text.length() > 6:
text = text.substr(0, text.length() - 2).strip_edges() + "…"
w = font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var r := Rect2()
for t: float in [0.5, 0.62, 0.38, 0.74, 0.26]:
var mid := point_along(pts, t)
r = Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
var clear := true
for q in placed:
if q.grow(2.0).intersects(r):
clear = false
break
if clear:
break
placed.append(r)
draw_style_box(_lit_label_box if lit else _label_box, r)
draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.INK if lit else Style.THREAD_DARK)
## The mark of a conditional pipe: a small diamond near its source end
## (hollow for "otherwise", filled for a condition), far enough along that
## the branches of one entry have started to fan out.
func _draw_diamond(pts: PackedVector2Array, lit: bool, otherwise: bool) -> void:
if pts.size() < 2:
return
var c := point_along(pts, 0.2)
var r := 7.5
var poly := PackedVector2Array([c + Vector2(0, -r), c + Vector2(r, 0), c + Vector2(0, r), c + Vector2(-r, 0)])
var edge := Style.ACCENT_DARK if lit else Style.THREAD_DARK
draw_colored_polygon(poly, edge)
var inner_r := r - 2.5
var inner := PackedVector2Array([c + Vector2(0, -inner_r), c + Vector2(inner_r, 0), c + Vector2(0, inner_r), c + Vector2(-inner_r, 0)])
var fill := Style.CARD if otherwise else (Style.ACCENT if lit else Style.THREAD.lightened(0.25))
draw_colored_polygon(inner, fill)
func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void:
if ThreadStrip.active and not _batch.far:
_strip_pipe(pts, lit, hovered)
return
if lit:
draw_polyline(pts, Color(Style.ACCENT, 0.18), 20.0, true)
draw_polyline(pts, Style.ACCENT_DARK if lit else Style.THREAD_DARK, 11.0, true)
var inner := Style.ACCENT if lit else Style.THREAD
if hovered:
inner = Style.THREAD.lightened(0.35)
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)
## A lit or hovered pipe in the theme's thread picture. Its own canvas items
## (made after the unlit ones, so drawn over them) keep the material off labels.
func _strip_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void:
if lit:
PipeBatch.line(_batch.item(), pts, Color(Style.ACCENT, 0.18), ThreadStrip.active.width * 2.0)
var trim := Style.ACCENT if lit else (Style.THREAD.lightened(0.35) if hovered else Style.THREAD)
ThreadStrip.active.add_to(_batch.item(), pts, trim, Style.ACCENT_DARK if lit else Style.THREAD_DARK)
ThreadStrip.active.add_pins(_batch.item(), pts)
## An unlit pipe to or from a collapsed group: thinner and quieter, so the
## lit path of the last roll stands out on a big board.
func _draw_bundle(pts: PackedVector2Array) -> void:
draw_polyline(pts, Color(Style.THREAD_DARK, 0.55), 6.0, true)
draw_polyline(pts, Color(Style.THREAD, 0.6), 3.0, true)
## A reference pipe: thinner, in dashes.
func _draw_ref(pts: PackedVector2Array, lit: bool) -> void:
if lit:
draw_polyline(pts, Color(Style.ACCENT, 0.14), 12.0, true)
var dashes := PipeGeometry.dashes(pts, 12.0, 7.0)
for d in dashes:
draw_polyline(d, Style.ACCENT_DARK if lit else Style.THREAD_DARK, 6.0, true)
for d in dashes:
draw_polyline(d, Style.ACCENT if lit else Style.THREAD, 3.0, true)
func path_length(key: String) -> float:
if not _paths.has(key):
return 0.0
return PipeGeometry.length(_paths[key])
## The point a fraction `fraction` of the way along a polyline (PipeGeometry.point_along).
static func point_along(pts: PackedVector2Array, fraction: float) -> Vector2:
return PipeGeometry.point_along(pts, fraction)
## The pipe under a world-space point, or "" if none is within `tolerance`.
## Reference pipes come from entry text, so they're never picked.
func pipe_at(p: Vector2, tolerance: float) -> String:
for key: String in _paths:
if Roller.is_ref_key(key) or _rerouted.has(key):
continue
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 ""