TableTower/ui/pipe_layer.gd
RobinFiredrake 61a548902f Theme tiers 1-2: theme folders, mascot recolour, background scene and tile, frame sets, picture threads, sounds; nine new built-in themes
- ThemeAssets loads a theme's files; FrameSet + GradientMap (3-stop) generalise the card frame;
  ThreadStrip draws threads from a picture; BoardBackdrop draws scene and tile; MascotArt
  recolours Morgan by role (logo SVG now uses the Keep File importer); SoundBoard plays
  roll / card turn / thread / click / ambient with View > Sound levels.
- Vaporwave, Synthwave, Cozy Autumn, Rustic, Woodsy, Sky Blue, Frutiger Aero, Gothic, Terminal:
  generated art (tools/theme_art), sounds (tools/theme_sounds), settings (tools/theme_defs).
- Ten OFL fonts; --theme=<id> flag; docs/THEMES.md format spec; test_theme_assets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:05:40 -06:00

456 lines
17 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name 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.
const SAMPLES := 40
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 = []
## Unlit pipes each go in a canvas item of their own (see _batch_item), so the
## renderer skips the ones out of view; lit pipes, labels and the bead are
## drawn by _draw on top. A pool reused between redraws.
var _items: Array[RID] = []
var _items_used := 0
## Zoomed far out (BoardView.FAR_ZOOM): unlit pipes draw as one coarse line.
var _far := false
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)
_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
# ---------- Batched unlit pipes (performance) ----------
func _begin_batch() -> void:
_far = main.board.cards.far
for i in _items_used:
RenderingServer.canvas_item_clear(_items[i])
_items_used = 0
## The next free canvas item for one pipe: a child of this layer's item drawn
## behind it, so lit pipes and labels stay on top. Its bounds come from what's
## drawn in it, so the renderer culls it when the pipe is out of view.
func _batch_item() -> RID:
if _items_used == _items.size():
var rid := RenderingServer.canvas_item_create()
RenderingServer.canvas_item_set_parent(rid, get_canvas_item())
RenderingServer.canvas_item_set_draw_behind_parent(rid, true)
_items.append(rid)
_items_used += 1
# A theme's thread strip sets a material on its item; reused items start clean.
RenderingServer.canvas_item_set_material(_items[_items_used - 1], RID())
return _items[_items_used - 1]
func _line(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void:
RenderingServer.canvas_item_add_polyline(rid, pts, PackedColorArray([color]), width, true)
## Far out: one plain line through every fourth point.
func _coarse(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void:
var c := PackedVector2Array()
for i in range(0, pts.size(), 4):
c.append(pts[i])
if (pts.size() - 1) % 4 != 0:
c.append(pts[pts.size() - 1])
RenderingServer.canvas_item_add_polyline(rid, c, PackedColorArray([color]), width, false)
## An unlit pipe (as _draw_pipe draws it), in its own canvas item.
## `own` is the thread's own colour ("" = the theme's THREAD).
func _batch_pipe(pts: PackedVector2Array, hovered: bool, own: String = "") -> void:
var rid := _batch_item()
var col := Color.from_string(own, Style.THREAD) if own != "" else Style.THREAD
var dark := col.darkened(0.6) if own != "" else Style.THREAD_DARK
if _far:
_coarse(rid, pts, col, 10.0)
return
if ThreadStrip.active:
ThreadStrip.active.add_to(rid, pts, col.lightened(0.35) if hovered else col, dark)
ThreadStrip.active.add_pins(_batch_item(), pts)
return
_line(rid, pts, dark, 11.0)
_line(rid, pts, col.lightened(0.35) if hovered else col, 6.0)
RenderingServer.canvas_item_add_set_transform(rid, Transform2D(0.0, Vector2(0, -1.5)))
_line(rid, pts, Color(1.0, 0.886, 0.745, 0.4), 1.5)
RenderingServer.canvas_item_add_set_transform(rid, Transform2D.IDENTITY)
## An unlit pipe to or from a collapsed group (as _draw_bundle draws it).
func _batch_bundle(pts: PackedVector2Array) -> void:
var rid := _batch_item()
if _far:
_coarse(rid, pts, Color(Style.THREAD, 0.6), 6.0)
return
_line(rid, pts, Color(Style.THREAD_DARK, 0.55), 6.0)
_line(rid, pts, Color(Style.THREAD, 0.6), 3.0)
## An unlit reference pipe (as _draw_ref draws it).
func _batch_ref(pts: PackedVector2Array) -> void:
var rid := _batch_item()
if _far:
_coarse(rid, pts, Color(Style.THREAD, 0.7), 4.0)
return
var dashes := _dashes(pts, 12.0, 7.0)
for d in dashes:
_line(rid, d, Style.THREAD_DARK, 6.0)
for d in dashes:
_line(rid, d, Style.THREAD, 3.0)
func _notification(what: int) -> void:
if what == NOTIFICATION_PREDELETE:
for rid in _items:
RenderingServer.free_rid(rid)
_items.clear()
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:
_begin_batch()
_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.entries:
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)
_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_ref(pts)
elif rerouted:
_batch_bundle(pts)
else:
_batch_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")
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 _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:
_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 := _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)
## Splits a polyline into dashes `on` long with gaps `off` long.
static func _dashes(pts: PackedVector2Array, on: float, off: float) -> Array[PackedVector2Array]:
var out: Array[PackedVector2Array] = []
var cur := PackedVector2Array()
var drawing := true
var left := on
for i in range(1, pts.size()):
var a := pts[i - 1]
var b := pts[i]
var seg := a.distance_to(b)
var pos := 0.0
if drawing and cur.is_empty():
cur.append(a)
while seg - pos > left:
pos += left
var p := a.lerp(b, pos / seg)
if drawing:
cur.append(p)
out.append(cur)
cur = PackedVector2Array()
else:
cur = PackedVector2Array([p])
drawing = not drawing
left = on if drawing else off
left -= seg - pos
if drawing:
cur.append(b)
if drawing and cur.size() > 1:
out.append(cur)
return out
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`.
## 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 ""