TableTower/ui/pipe_layer.gd

357 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.
##
## 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
## 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
## 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.COPPER_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
var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far]
if state != _drawn_state:
_drawn_state = state
queue_redraw()
# ---------- 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
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.
func _batch_pipe(pts: PackedVector2Array, hovered: bool) -> void:
var rid := _batch_item()
if _far:
_coarse(rid, pts, Style.COPPER, 10.0)
return
_line(rid, pts, Style.COPPER_DARK, 11.0)
_line(rid, pts, Style.COPPER.lightened(0.35) if hovered else Style.COPPER, 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.COPPER, 0.6), 6.0)
return
_line(rid, pts, Color(Style.COPPER_DARK, 0.55), 6.0)
_line(rid, pts, Color(Style.COPPER, 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.COPPER, 0.7), 4.0)
return
var dashes := _dashes(pts, 12.0, 7.0)
for d in dashes:
_line(rid, d, Style.COPPER_DARK, 6.0)
for d in dashes:
_line(rid, d, Style.COPPER, 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 drawn := {} # endpoints of rerouted pipes already drawn (they overlap)
var build := main.mode == Main.Mode.BUILD
# 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 lit:
(lit_refs if is_ref else lit_list).append(pts)
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))
if not is_ref and not rerouted:
var tag := _pipe_tag(e, to)
if tag != "":
labels.append([pts, tag])
# 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 l in labels:
_draw_tag(l[0], l[1])
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.BRASS, 0.3))
draw_circle(p, 9.0 * r, Color(Style.BRASS, 0.5))
draw_circle(p, 7.0 * r, Style.PULSE)
## "×2 → foe" for a pipe with options, or "".
static func _pipe_tag(e: TableEntry, to: String) -> String:
var parts := PackedStringArray()
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)
func _draw_tag(pts: PackedVector2Array, text: String) -> void:
var font := Style.body_bold(true)
var fs := 12
var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var mid := point_along(pts, 0.5)
var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
draw_style_box(_label_box, r)
draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.COPPER_DARK)
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.COPPER.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)
## 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.COPPER_DARK, 0.55), 6.0, true)
draw_polyline(pts, Color(Style.COPPER, 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.BRASS, 0.14), 12.0, true)
var dashes := _dashes(pts, 12.0, 7.0)
for d in dashes:
draw_polyline(d, Style.BRASS_DARK if lit else Style.COPPER_DARK, 6.0, true)
for d in dashes:
draw_polyline(d, Style.BRASS if lit else Style.COPPER, 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 ""