files-game/table/game_table.gd
2026-10-01 23:01:56 -04:00

1115 lines
42 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 GameTable
extends Node3D
## The 3D table: the playmat with its locations, lines, gateways and Firewalls, and every card you
## can see (godot-plan.md §4). sync() snaps it to a player view, so no rule lives here. Clicking
## and hovering report the same keys as Moves (`loc:C2`, `anomaly:0:1`, `hand:Hotfix`, `gate:A2-B1`).
const CARD_SCENE := preload("res://table/card_3d.tscn")
const PLAYMAT_SCENE := preload("res://table/playmat.tscn")
const TILE_SHADER := preload("res://table/tile.gdshader")
const VOID_SHADER := preload("res://table/void_grid.gdshader")
## Colors come from Style (ui-plan.md §0.1): owners, marks and the chrome.
## Your hand, held in front of the camera: distance and how much of a card shows at the bottom.
const HAND_DISTANCE := 8.2
const HAND_SHOWN := 0.74
## Hardware peeks out from under its wearer by this much each.
const HARDWARE_PEEK := 0.3
const PROGRAM_STEP := 0.42
const BOT_HAND_SHOWN := 14
## Seconds a pop-up stays, and a capture pulse lasts.
const POP_TIME := 2.2
const FLASH_TIME := 1.4
## Pop-ups showing at once; a new one past this drops the oldest.
const MAX_POPS := 8
## How each motion style moves a card (see _path_for): seconds for each leg of the curve.
const PATH_TIMES := {
"move": [0.2, 0.3, 0.16], "slam": [0.18, 0.12, 0.09], "reveal": [0.24, 0.7, 0.2],
"discard": [0.13, 0.2, 0.16], "destroy": [0.12, 0.34, 0.18], "draw": [0.22, 0.34, 0.18],
"deal": [0.2, 0.18], "stack": [0.24, 0.6, 0.2],
}
## How far in front of the camera a revealed card is held up.
const REVEAL_DISTANCE := 5.2
var camera: Camera3D
## The player sitting at the table (whose hand is held up, whose side the camera is on).
var me := 0
## "seat" (angled over your side) or "top" (straight down).
var view_mode := "seat"
## What the mouse is over: {key, card} (card is the card name for the inspector, or ""), or {}.
var hovered := {}
var _hand_root: Node3D
var _board: Node3D
var _cards_root: Node3D
var _tile_material: ShaderMaterial
var _mat: Node3D
var _floor_material: ShaderMaterial
var _tiles := {}
var _gates := {}
var _lines := {}
var _cards := {}
var _piles := {}
var _hover_body: Object = null
## Your hand's cards in hand order, and the Executions waiting on the stack, oldest first.
var _hand_order: Array[Card3D] = []
var _stack_order: Array[Card3D] = []
var _zoom := 1.0
## Your hand drops out of sight while the HUD's hand-focus row shows it instead.
var _hand_tucked := false
var _cam_tween: Tween
var _view: Dictionary = {}
var _font: Font
var _tag_font: Font
var _overlay: Control
## 2D readouts pinned to points on the table: key → {box, label, world, used}.
var _tags := {}
## Pop-ups rising from the table (damage, roll results): {label, world, born}.
var _pops: Array = []
## Tiles pulsing after a capture: location → {color, born}.
var _flashes := {}
var _last_marks := {}
## Set by the presenter just before a sync, used by it once: how a card should get to its new spot
## (node key → {style, delay, p, from}), and when each gateway's Firewall should change (line →
## seconds). Anything without one just glides.
var motions := {}
var gate_delays := {}
## Seconds before each player's Bandwidth bar on the mat moves (player → seconds); also the presenter's.
var bandwidth_delays := {}
var _strips: Array[BandwidthStrip] = []
func _ready() -> void:
_font = Style.body_font(600)
_tag_font = Style.body_font(500)
_build_room()
var layer := CanvasLayer.new()
layer.layer = 0
add_child(layer)
_overlay = Control.new()
_overlay.set_anchors_preset(Control.PRESET_FULL_RECT)
_overlay.mouse_filter = Control.MOUSE_FILTER_IGNORE
layer.add_child(_overlay)
_board = Node3D.new()
_board.name = "Board"
add_child(_board)
_cards_root = Node3D.new()
_cards_root.name = "Cards"
add_child(_cards_root)
_build_board()
set_seat(me, true)
get_viewport().size_changed.connect(func(): _place_camera(true))
# ---------------------------------------------------------------------------------------------
# Building
func _build_room() -> void:
add_child(make_environment())
var sun := DirectionalLight3D.new()
sun.light_color = Color(0.9, 0.95, 1.0)
sun.light_energy = 1.2
sun.shadow_enabled = true
sun.shadow_opacity = 0.7
sun.directional_shadow_max_distance = 60.0
add_child(sun)
sun.look_at_from_position(Vector3(6, 20, 9), Vector3.ZERO, Vector3.UP)
var ground := make_floor()
_floor_material = ground.material_override
add_child(ground)
_mat = PLAYMAT_SCENE.instantiate()
add_child(_mat)
camera = Camera3D.new()
camera.fov = 45.0
camera.far = 200.0
add_child(camera)
camera.current = true
_hand_root = Node3D.new()
_hand_root.name = "Hand"
camera.add_child(_hand_root)
func _build_board() -> void:
BoardLayout.update()
_fit_grid()
_tile_material = ShaderMaterial.new()
_tile_material.shader = TILE_SHADER
_tile_material.set_shader_parameter("size", BoardLayout.tile_size)
_tile_material.render_priority = -1
var plane := PlaneMesh.new()
plane.size = BoardLayout.tile_size
# The lines between locations, as dim circuit traces.
var line_material := StandardMaterial3D.new()
line_material.albedo_color = Color(Style.ACCENT, 0.42)
line_material.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
line_material.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
line_material.render_priority = -2
var half := BoardLayout.tile_size / 2.0
for line in GameMap.LINES:
var a: Vector3 = BoardLayout.at[line.a]
var b: Vector3 = BoardLayout.at[line.b]
var d := b - a
var len := d.length()
var t0 := _exit_t(d, half)
var t1 := 1.0 - _exit_t(-d, half)
if t1 <= t0:
continue
var seg := MeshInstance3D.new()
var m := BoxMesh.new()
m.size = Vector3(0.07, 0.002, len * (t1 - t0))
seg.mesh = m
seg.material_override = line_material
seg.position = a + d * (t0 + t1) / 2.0 + Vector3(0, 0.002, 0)
seg.rotation.y = atan2(d.x, d.z)
seg.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
_board.add_child(seg)
_lines[line.id] = seg
if line.gateway:
_gates[line.id] = _make_gate(line, seg.rotation.y)
# Printed card spots beside each start: Anomaly slots and piles.
var spot_material := ShaderMaterial.new()
spot_material.shader = TILE_SHADER
var spot_size := BoardLayout.CARD_SIZE + Vector2(0.14, 0.14)
spot_material.set_shader_parameter("size", spot_size)
spot_material.set_shader_parameter("chamfer", BoardLayout.CARD_SIZE.x * Style.CHAMFER_RATIO * 2.0)
spot_material.set_shader_parameter("edge_width", 0.035)
spot_material.set_shader_parameter("inner_line", 0.0)
spot_material.render_priority = -1
var spot_plane := PlaneMesh.new()
spot_plane.size = spot_size
for p in [0, 1]:
var spots := []
for slot in range(1, 5):
spots.append(BoardLayout.zone_spot(p, "slot", slot))
for zone in ["deck", "serverPile", "discard"]:
spots.append(BoardLayout.zone_spot(p, zone))
var names := ["1", "2", "3", "4", "DECK", "SERVERS", "DISCARD"]
for i in spots.size():
var at: Vector3 = spots[i]
# The spot's name, printed in the gap between it and the first row.
var name := _flat_label(30)
name.text = names[i]
name.modulate = Color(Style.OWNER[p], 0.8)
name.rotation.y = BoardLayout.yaw_for(p)
var inward := -1.0 if p == 0 else 1.0
name.position = Vector3(at.x, 0.004, at.z + inward * (BoardLayout.CARD_SIZE.y / 2 + 0.17))
_board.add_child(name)
var m := MeshInstance3D.new()
m.mesh = spot_plane
m.material_override = spot_material
m.position = Vector3(at.x, 0.003, at.z)
m.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
_board.add_child(m)
m.set_instance_shader_parameter("fill_color", Color(Style.OWNER[p] * 0.18, 0.55))
m.set_instance_shader_parameter("edge_color", Color(Style.OWNER[p], 0.6))
m.set_instance_shader_parameter("pattern", 1.0 + p)
# Each player's Bandwidth bar, just off their edge of the mat.
for p in [0, 1]:
var strip := BandwidthStrip.new()
var toward := 1.0 if p == 0 else -1.0
strip.position = Vector3(0, -0.1, toward * (BoardLayout.MAT_SIZE.y / 2.0 + 0.36))
strip.rotation.y = BoardLayout.yaw_for(p)
_board.add_child(strip)
_strips.append(strip)
for loc in GameMap.LOCATIONS:
var tile := MeshInstance3D.new()
tile.mesh = plane
tile.material_override = _tile_material
tile.position = BoardLayout.at[loc] + Vector3(0, 0.003, 0)
tile.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
_board.add_child(tile)
var body := StaticBody3D.new()
var shape := CollisionShape3D.new()
var bs := BoxShape3D.new()
bs.size = Vector3(BoardLayout.tile_size.x, 0.01, BoardLayout.tile_size.y)
shape.shape = bs
body.add_child(shape)
body.set_meta("key", Moves.loc_key(loc))
tile.add_child(body)
# The location's id as microtext in the socket's corner.
var label := _flat_label(58)
label.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
label.vertical_alignment = VERTICAL_ALIGNMENT_TOP
label.modulate = Color(Style.SECONDARY, 0.85)
_board.add_child(label)
_tiles[loc] = {"mesh": tile, "label": label}
## Cyberspace (gameplay-plan.md §B1): a black void with a cool, even light so the cards stay
## readable; neon emission is what blooms. The menu uses it too, so both read as one world.
static func make_environment() -> WorldEnvironment:
var env := Environment.new()
env.background_mode = Environment.BG_COLOR
env.background_color = Color("#010304")
env.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR
env.ambient_light_color = Color(0.66, 0.76, 0.86)
env.ambient_light_energy = 0.8
env.tonemap_mode = Environment.TONE_MAPPER_FILMIC
env.glow_enabled = true
env.glow_intensity = 0.75
env.glow_strength = 1.05
env.glow_bloom = 0.0
env.glow_hdr_threshold = 1.1
env.glow_blend_mode = Environment.GLOW_BLEND_MODE_ADDITIVE
for i in 7:
env.set_glow_level(i, [0.0, 1.0, 1.0, 0.7, 0.5, 0.0, 0.0][i])
var we := WorldEnvironment.new()
we.environment = env
return we
## The floor under the mat: the neon grid running out into the void.
static func make_floor(size := 240.0) -> MeshInstance3D:
var ground := MeshInstance3D.new()
var plane := PlaneMesh.new()
plane.size = Vector2(size, size)
ground.mesh = plane
var m := ShaderMaterial.new()
m.shader = VOID_SHADER
m.render_priority = -4
ground.material_override = m
ground.position = Vector3(0, -0.14, 0)
ground.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
return ground
## Lines the mat's and floor's grids up with the locations: half a column pitch across and a row
## pitch deep, crossing between the rows.
func _fit_grid() -> void:
var pitch := Vector2(BoardLayout.col_pitch / 2.0, BoardLayout.row_pitch)
var origin := Vector2(0, BoardLayout.row_pitch / 2.0)
var mats: Array = [_floor_material]
for mi in _mat.find_children("*", "MeshInstance3D", true, false):
var m: Material = (mi as MeshInstance3D).get_surface_override_material(0)
if m is ShaderMaterial:
mats.append(m)
for m in mats:
m.set_shader_parameter("pitch", pitch)
m.set_shader_parameter("origin", origin)
m.set_shader_parameter("half_size", BoardLayout.MAT_SIZE / 2.0)
## How far along d (from a tile's centre) the segment leaves a tile of half-size `half`.
static func _exit_t(d: Vector3, half: Vector2) -> float:
var tx := INF if is_zero_approx(d.x) else half.x / absf(d.x)
var tz := INF if is_zero_approx(d.z) else half.y / absf(d.z)
return minf(tx, tz) + 0.012
func _make_gate(line: Dictionary, yaw: float) -> Dictionary:
var at := BoardLayout.line_mid(line)
var port := FirewallPort.new()
port.position = at
port.rotation.y = yaw
_board.add_child(port)
var body := StaticBody3D.new()
var shape := CollisionShape3D.new()
var bs := BoxShape3D.new()
bs.size = Vector3(0.7, 0.4, 0.7)
shape.shape = bs
body.add_child(shape)
body.position = at + Vector3(0, 0.2, 0)
body.set_meta("key", Moves.gate_key(line.id))
_board.add_child(body)
return {"port": port, "at": at}
func _flat_label(size: int) -> Label3D:
var l := Label3D.new()
l.font = _font
l.font_size = size
l.pixel_size = 0.004
l.rotation.x = -PI / 2
l.modulate = Color(Style.SECONDARY, 0.8)
l.outline_size = 0
l.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
return l
# ---------------------------------------------------------------------------------------------
# Camera
## Sits player `p` at the table: the camera on their side, their hand held up.
func set_seat(p: int, instant := false) -> void:
me = p
_place_camera(instant)
func toggle_view() -> void:
view_mode = "top" if view_mode == "seat" else "seat"
_place_camera(false)
func zoom(by: float) -> void:
_zoom = clampf(_zoom * by, 0.55, 1.5)
_place_camera(false)
func _place_camera(instant: bool) -> void:
var xf := _fit_camera()
if _cam_tween != null:
_cam_tween.kill()
if instant:
camera.transform = xf
else:
_cam_tween = create_tween().set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_IN_OUT)
_cam_tween.tween_property(camera, "transform", xf, 0.45)
## The camera spot that fits the mat (and the bot's hand past it) into the screen the panels leave
## free, from your side: angled for "seat", straight down for "top". Tries a few aim points and
## keeps the closest camera that fits, then applies the zoom.
func _fit_camera() -> Transform3D:
var side := 1.0 if me == 0 else -1.0
var vp := get_viewport().get_visible_rect().size
var region := Style.table_region(vp)
var hx := BoardLayout.MAT_SIZE.x / 2
var hz := BoardLayout.MAT_SIZE.y / 2
var points := [Vector3(-hx, 0, -hz), Vector3(hx, 0, -hz), Vector3(-hx, 0, hz), Vector3(hx, 0, hz),
Vector3(-3.5, 0, -(hz + 1.8) * side), Vector3(3.5, 0, -(hz + 1.8) * side)]
var top := view_mode == "top"
var pitch := deg_to_rad(89.0 if top else 56.0)
var dir := Vector3(0, sin(pitch), cos(pitch) * side)
var up := Vector3(0, 0, -side) if top else Vector3.UP
var saved := camera.transform
var best := Transform3D()
var best_d := INF
for i in 13:
var target := Vector3(0, 0, (i - 6) * 0.6 * side)
var lo := 5.0
var hi := 80.0
for _k in 22:
var d := (lo + hi) / 2.0
camera.transform = Transform3D(Basis.IDENTITY, target + dir * d).looking_at(target, up)
var fits := true
for pt in points:
if not region.has_point(camera.unproject_position(pt)):
fits = false
break
if fits:
hi = d
else:
lo = d
if hi < best_d:
best_d = hi
best = Transform3D(Basis.IDENTITY, target + dir * hi * _zoom).looking_at(target, up)
camera.transform = saved
return best
# ---------------------------------------------------------------------------------------------
# Picking
func _physics_process(_delta: float) -> void:
var mouse := get_viewport().get_mouse_position()
var from := camera.project_ray_origin(mouse)
var to := from + camera.project_ray_normal(mouse) * 150.0
var q := PhysicsRayQueryParameters3D.create(from, to)
var hit := get_world_3d().direct_space_state.intersect_ray(q)
var body: Object = hit.get("collider")
# Nothing on the table is under the mouse while it's over a panel.
if get_viewport().gui_get_hovered_control() != null:
body = null
if body == _hover_body:
return
var was_hand := _is_hand_body(_hover_body)
_hover_body = body
if body == null or not body.has_meta("key"):
hovered = {}
else:
var card = body.get_meta("card") if body.has_meta("card") else null
hovered = {"key": body.get_meta("key"), "card": card.card_name if card != null else ""}
if was_hand or _is_hand_body(body):
_layout_hand()
func _is_hand_body(body: Object) -> bool:
if body == null or not is_instance_valid(body) or not body.has_meta("card"):
return false
var card: Node = body.get_meta("card")
return card.get_parent() == _hand_root
# ---------------------------------------------------------------------------------------------
# Syncing to a view
## The view the table shows now ({} before the first sync).
func shown_view() -> Dictionary:
return _view
## Snaps the table to `view` (as seen by `me`), with `marks` from key to a mark name (see
## Style.MARK).
func sync(v: Dictionary, marks: Dictionary) -> void:
_view = v
_last_marks = marks
for k in _tags:
_tags[k].used = false
_sync_tiles(v, marks)
_sync_gates(v, marks)
for p in [0, 1]:
var pl: Dictionary = v.players[p]
if _strips[p].get_meta("ticks", []) != v.rules.firewallCost:
_strips[p].set_ticks(v.rules.firewallCost)
_strips[p].set_meta("ticks", v.rules.firewallCost)
var reach := Query.reachable_bandwidth(v, p) if p == me else int(pl.bandwidth)
_strips[p].set_value(pl.bandwidth, reach, Style.OWNER[p], bandwidth_delays.get(p, 0.0))
bandwidth_delays = {}
var want := {}
_want_board_cards(v, want)
_want_zones(v, want)
_want_stack(v, want)
_apply_cards(want, marks)
_layout_hand()
_layout_stack()
motions = {}
for k in _tags.keys():
if not _tags[k].used:
_tags[k].box.queue_free()
_tags.erase(k)
_place_tags()
func _sync_tiles(v: Dictionary, marks: Dictionary) -> void:
for loc in GameMap.LOCATIONS:
var tile: MeshInstance3D = _tiles[loc].mesh
var owner = v.locations[loc].owner
# An open socket is dim chrome; a held one takes its owner's color and pattern.
var fill := Color(Style.BG, 0.62)
var edge := Color(Style.ACCENT, 0.5)
if owner != null:
fill = Color(Style.OWNER[owner] * 0.2, 0.72)
edge = Color(Style.OWNER[owner], 0.9)
tile.set_instance_shader_parameter("pattern", 0.0 if owner == null else 1.0 + owner)
var glow := 0.0
var mark = marks.get(Moves.loc_key(loc))
if mark != null:
edge = Style.MARK[mark]
glow = Style.MARK_STRENGTH[mark]
tile.set_instance_shader_parameter("fill_color", fill)
tile.set_instance_shader_parameter("edge_color", edge)
tile.set_instance_shader_parameter("glow", glow)
var label: Label3D = _tiles[loc].label
if GameMap.is_start(loc):
label.text = "%s · %s" % [loc, "YOUR START" if loc == GameMap.START_LOC[me] else "START"]
else:
label.text = "%s · LV %d" % [loc, GameMap.level_for(me, loc)]
# In the socket's far right corner as you sit.
var toward := 1.0 if me == 0 else -1.0
var half := BoardLayout.tile_size / 2.0 - Vector2(0.28, 0.16)
label.position = BoardLayout.at[loc] + Vector3(half.x * toward, 0.004, -half.y * toward)
label.rotation.y = 0.0 if me == 0 else PI
func _sync_gates(v: Dictionary, marks: Dictionary) -> void:
# The LED count comes from the rules, so a longer Firewall cost list shows every level.
var levels: int = v.rules.firewallCost.size()
for line_id in _gates:
var g: Dictionary = _gates[line_id]
var level: int = v.firewalls.get(line_id, 0)
var port: FirewallPort = g.port
port.set_level(level, levels, true, gate_delays.get(line_id, 0.0))
var mark = marks.get(Moves.gate_key(line_id))
if mark != null:
port.set_mark(Style.MARK[mark], Style.MARK_STRENGTH[mark])
elif not port.busy():
port.set_mark(Color(0, 0, 0, 0), 0.0)
var seg: MeshInstance3D = _lines[line_id]
seg.transparency = 0.6 if level > 0 else 0.0
gate_delays = {}
## Cards on the mat: Servers, Programs, Anomalies in play and their Hardware.
func _want_board_cards(v: Dictionary, want: Dictionary) -> void:
var standing := {}
for p in [0, 1]:
for r in State.refs_in_play(v, p):
var at: String = State.anomaly(v, r).at
if not standing.has(at):
standing[at] = []
standing[at].append(r)
for loc in GameMap.LOCATIONS:
var L: Dictionary = v.locations[loc]
var owner = L.owner
var yaw := BoardLayout.yaw_for(owner if owner != null else 0)
if L.server != null:
var name := State.name_of(v, L.server)
want["card:%d" % L.server] = {"name": name, "pos": BoardLayout.server_spot(loc), "yaw": yaw,
"key": Moves.loc_key(loc)}
var progs: Array = L.programs
for i in progs.size():
var id: int = progs[i]
var name := State.name_of(v, id)
var pos := BoardLayout.program_spot(loc, i, progs.size())
want["card:%d" % id] = {"name": name, "pos": pos, "yaw": yaw, "key": Moves.loc_key(loc),
"dim": 0.0 if Query.program_active(v, id) else 0.7}
var refs: Array = standing.get(loc, [])
if refs.is_empty():
continue
# Lay the Anomalies out between the Server and the Programs, each with its Hardware.
var widths := []
var total := 0.0
for r in refs:
var w := BoardLayout.CARD_SIZE.x + (0.0 if State.is_copy(r) else State.hardware_of(v, r).size() * HARDWARE_PEEK)
widths.append(w)
total += w
var left := BoardLayout.server_spot(loc).x + BoardLayout.CARD_SIZE.x / 2 + 0.1
var right: float = BoardLayout.at[loc].x + BoardLayout.tile_size.x / 2 - 0.08
if not progs.is_empty():
right -= BoardLayout.CARD_SIZE.x + (progs.size() - 1) * PROGRAM_STEP + 0.05
var gap := 0.09
var room: float = right - left
var squeeze := 1.0
if total + gap * (refs.size() - 1) > room:
squeeze = maxf(0.3, (room - gap * (refs.size() - 1)) / total)
var x := left
for i in refs.size():
var r: Dictionary = refs[i]
var w: float = widths[i] * squeeze
var cx: float = x + BoardLayout.CARD_SIZE.x * squeeze / 2.0
var y := BoardLayout.CARD_Y + 4 * BoardLayout.LAYER + i * BoardLayout.LAYER * 3
_want_anomaly(v, r, Vector3(cx, y, BoardLayout.at[loc].z), BoardLayout.yaw_for(r.player), want, true)
x += w + gap
## An Anomaly card (in play or in its slot) and its Hardware, tucked under it and peeking out to
## its right.
func _want_anomaly(v: Dictionary, r: Dictionary, pos: Vector3, yaw: float, want: Dictionary, in_play: bool) -> void:
var av := State.anomaly(v, r)
var name := State.name_of(v, av.card) if av.card >= 0 and av.faceUp else ""
var key := Moves.anomaly_key(r)
want[key] = {"name": name, "pos": pos, "yaw": yaw + (PI / 2 if in_play and State.is_disabled_anomaly(v, r) else 0.0),
"key": key, "face_down": name == "", "badge": in_play or name != ""}
if State.is_copy(r):
return
var hw: Array = av.hardware
var side := Vector3.RIGHT
for j in hw.size():
var id: int = hw[j]
var hname := State.name_of(v, id)
var hpos := pos + side * HARDWARE_PEEK * (j + 1) - Vector3(0, BoardLayout.LAYER * (j + 1), 0)
want["card:%d" % id] = {"name": hname, "pos": hpos, "yaw": yaw, "key": key,
"dim": 0.0 if Query.hardware_active(v, id) else 0.7}
## Off the mat: Anomaly slots, piles, your hand and the bot's.
func _want_zones(v: Dictionary, want: Dictionary) -> void:
for p in [0, 1]:
var pl: Dictionary = v.players[p]
var yaw := BoardLayout.yaw_for(p)
for i in 4:
var r := State.ref(p, i + 1)
var av := State.anomaly(v, r)
if av.at == null:
_want_anomaly(v, r, BoardLayout.zone_spot(p, "slot", i + 1), yaw, want, false)
_want_pile(p, "deck", pl.deck.size(), -1, want)
_want_pile(p, "serverPile", pl.serverPile.size(), -1, want)
_want_pile(p, "discard", pl.discard.size(), pl.discard.back() if not pl.discard.is_empty() else -1, want)
if p == me:
for id in pl.hand:
var name := State.name_of(v, id)
want["card:%d" % id] = {"name": name, "hand": true, "key": Moves.hand_key(name)}
else:
var n := mini(pl.hand.size(), BOT_HAND_SHOWN)
var base := BoardLayout.zone_spot(p, "hand")
var dir := 1.0 if p == 0 else -1.0
for i in n:
var off := (i - (n - 1) / 2.0) * 0.55
want["bothand:%d:%d" % [p, i]] = {"name": "", "pos": base + Vector3(off * dir, i * BoardLayout.LAYER, 0),
"yaw": yaw, "face_down": true, "key": "pile:%d:hand" % p}
## Executions waiting on the stack, held up beside the table until they resolve: their card is in
## no zone meanwhile. Not clickable, so they never cover a click on the board.
func _want_stack(v: Dictionary, want: Dictionary) -> void:
for it in v.stack:
if it.kind == "execution" and it.get("card", -1) >= 0:
want["card:%d" % it.card] = {"name": State.name_of(v, it.card), "held": "stack", "key": ""}
## A pile: a block as tall as the count, with its top card on it (face up for the discard).
func _want_pile(p: int, zone: String, count: int, top: int, want: Dictionary) -> void:
var spot := BoardLayout.zone_spot(p, zone)
var key := "%d:%s" % [p, zone]
if not _piles.has(key):
_piles[key] = _make_pile(spot)
var pile: Dictionary = _piles[key]
var h := maxf(0.0, (count - 1) * BoardLayout.LAYER)
pile.block.visible = count > 1
pile.block.scale = Vector3(1, maxf(h, 0.001), 1)
pile.block.position = spot + Vector3(0, h / 2.0, 0)
_tag("pile:" + key, str(count), Color(0.85, 0.88, 0.92), spot + Vector3(0, h, 0))
if count == 0:
return
var pos := spot + Vector3(0, h + BoardLayout.CARD_Y, 0)
var pick := "pile:%d:%s" % [p, zone]
if top >= 0:
var name := State.name_of(_view, top)
want["card:%d" % top] = {"name": name, "pos": pos, "yaw": BoardLayout.yaw_for(p), "key": pick}
else:
want["%s:top" % key] = {"name": "", "pos": pos, "yaw": BoardLayout.yaw_for(p), "face_down": true, "key": pick}
func _make_pile(spot: Vector3) -> Dictionary:
var block := MeshInstance3D.new()
var m := BoxMesh.new()
m.size = Vector3(BoardLayout.CARD_SIZE.x, 1, BoardLayout.CARD_SIZE.y)
block.mesh = m
block.material_override = CardFaces.edge()
block.position = spot
_board.add_child(block)
return {"block": block}
## Creates, moves and removes Card3Ds to match `want` (node key → spot).
func _apply_cards(want: Dictionary, marks: Dictionary) -> void:
_hand_order = []
_stack_order = []
for key in _cards.keys():
if not want.has(key):
var card: Card3D = _cards[key]
var spec: Dictionary = motions.get(key, {})
if spec.get("style", "") == "leave":
# Back into a hidden pile: it goes there, then it's gone.
if card.get_parent() != _cards_root:
card.reparent(_cards_root, true)
card.pick_key = ""
var goal := _zone_xf(spec.get("p", me), spec.get("to", "deck"))
card.travel(_path_for(card, goal, {"style": "discard"}, false), PATH_TIMES.discard, spec.get("delay", 0.0), true, Style.ACCENT, true)
else:
card.queue_free()
_cards.erase(key)
for key in want:
var w: Dictionary = want[key]
var card: Card3D = _cards.get(key)
var fresh := card == null
if fresh:
card = CARD_SCENE.instantiate()
_cards[key] = card
var held: bool = w.get("hand", false) or w.has("held")
var parent: Node = _hand_root if held else _cards_root
if card.get_parent() != parent:
if card.get_parent() == null:
parent.add_child(card)
else:
card.reparent(parent, true)
card.set_shadows(parent != _hand_root)
card.card_name = w.name
card.pick_key = w.key
card.set_meta("node_key", key)
if w.get("hand", false):
_hand_order.append(card)
elif w.get("held", "") == "stack":
_stack_order.append(card)
card.dim = w.get("dim", 0.0)
var mark = marks.get(w.key) if not w.key.begins_with("loc:") else null
# Only the card a hand key names glows, and only an Anomaly's own card, not its Hardware.
if mark != null and w.key.begins_with("anomaly:") and key != w.key:
mark = null
var strength: float = Style.MARK_STRENGTH[mark] * (0.55 if w.get("hand", false) else 1.0) if mark != null else 0.0
card.highlight = Color(Style.MARK[mark], strength) if mark != null else Color(0, 0, 0, 0)
if not held:
var basis := Basis.from_euler(Vector3(0, w.yaw, PI if w.get("face_down", false) else 0.0))
var xf := Transform3D(basis, w.pos)
var spec: Dictionary = motions.get(key, {})
if not spec.is_empty():
var style: String = spec.style
card.travel(_path_for(card, xf, spec, fresh), PATH_TIMES.get(style, PATH_TIMES.move), spec.get("delay", 0.0),
true, spec.get("color", Style.ACCENT))
if style == "destroy":
card.flash(Style.BAD, 0.6, spec.get("delay", 0.0))
else:
if fresh:
card.transform = xf
card.glide(xf, fresh)
_sync_badge(key, w)
## The way a card travels to `goal` (world space) for a motion spec. See PATH_TIMES for timing.
func _path_for(card: Card3D, goal: Transform3D, spec: Dictionary, fresh: bool) -> Array:
var start := goal if fresh else card.global_transform
if spec.get("from", "") != "":
start = _zone_xf(spec.get("p", me), spec.from)
var up := Vector3.UP
match spec.style:
"slam":
# Straight over its spot, then down hard.
var over := Transform3D(goal.basis, goal.origin + up * 1.5)
return [start, over, over.translated(-up * 0.25), goal]
"reveal":
# Up in front of you, face up, held there to read, then down to its spot.
var show := _present_xf()
return [start, show, show.translated(camera.global_transform.basis.z * 0.3), goal]
"discard", "destroy":
var rise := Transform3D(start.basis, start.origin + up * 0.7)
return [start, rise, Transform3D(goal.basis, goal.origin + up * 0.9), goal]
"deal":
return [start, Transform3D(goal.basis, start.origin.lerp(goal.origin, 0.5) + up * 0.8), goal]
# "move": lift off, drift over the destination, set down.
var lift := Transform3D(start.basis, start.origin.lerp(goal.origin, 0.2) + up * 1.3)
return [start, lift, Transform3D(goal.basis, goal.origin + up * 0.8), goal]
## Where a card held up for you to read sits: in front of the camera, upright.
func _present_xf() -> Transform3D:
return camera.global_transform * Transform3D(Basis(Vector3.RIGHT, PI / 2), Vector3(0, 0.45, -REVEAL_DISTANCE))
## The top of player `p`'s pile `zone` ("deck", "serverPile", "discard", "hand"), face down, in
## world space. Your own "hand" is the held hand in front of the camera.
func _zone_xf(p: int, zone: String) -> Transform3D:
if zone == "hand" and p == me:
var half_h := HAND_DISTANCE * tan(deg_to_rad(camera.fov / 2.0))
return camera.global_transform * Transform3D(Basis(Vector3.RIGHT, PI / 2), Vector3(0, -half_h, -HAND_DISTANCE))
if zone == "play":
zone = "hand"
var count := 1
if not _view.is_empty() and _view.players[p].has(zone):
count = maxi(1, _view.players[p][zone].size())
var h := (count - 1) * BoardLayout.LAYER + BoardLayout.CARD_Y if zone != "hand" else BoardLayout.CARD_Y
return Transform3D(Basis.from_euler(Vector3(0, BoardLayout.yaw_for(p), PI)), BoardLayout.zone_spot(p, zone) + Vector3(0, h, 0))
## A table point for a key ("anomaly:…", "card:…", "loc:…"): the card now, or the location.
func anchor_of(key: String) -> Variant:
var c: Card3D = _cards.get(key)
if c != null and is_instance_valid(c):
return c.global_position
if key.begins_with("loc:") and BoardLayout.at.has(key.substr(4)):
return BoardLayout.at[key.substr(4)]
if key.begins_with("gate:") and _gates.has(key.substr(5)):
return _gates[key.substr(5)].at
return null
## A flash on the card at node key `key`.
func flash_card(key: String, color: Color, delay := 0.0) -> void:
var c: Card3D = _cards.get(key)
if c != null and is_instance_valid(c):
c.flash(color, 0.55, delay)
## Whether anything on the table is still moving.
func animating() -> bool:
for k in _cards:
if is_instance_valid(_cards[k]) and _cards[k].moving():
return true
for g in _gates.values():
if g.port.busy():
return true
return false
## Jumps every animation to its end (a click skips the show).
func finish_animations() -> void:
for k in _cards:
if is_instance_valid(_cards[k]):
_cards[k].finish()
for g in _gates.values():
g.port.finish()
for pop in _pops:
pop.label.queue_free()
_pops = []
_flashes = {}
if not _view.is_empty():
_sync_tiles(_view, _last_marks)
## A readout under an Anomaly: Cores, Health and status.
func _sync_badge(key: String, w: Dictionary) -> void:
if not w.get("badge", false):
return
var r = Moves.ref_of_key(key)
if r == null:
return
var toward := 1.0 if me == 0 else -1.0
var card: Card3D = _cards[key]
_tag(key, badge_text(_view, r), Style.OWNER[r.player].lightened(0.3), Vector3(0, 0.05, 0.72 * toward), false, card)
## Shows `text` in a small 2D box pinned under the table point `world`, or with `follow`, at
## `world` from that node, so it rides along while a card slides. Tags not set during a sync are
## removed at its end.
func _tag(key: String, text: String, color: Color, world: Vector3, above := false, follow: Node3D = null) -> void:
var t: Dictionary = _tags.get(key, {})
if t.is_empty():
var box := PanelContainer.new()
box.mouse_filter = Control.MOUSE_FILTER_IGNORE
var sb := Style.chamfer_box(Color(color, 0.45), Color(Style.BG, 0.82), 1.0, 0.0, 4.0)
sb.content_margin_left = 5
sb.content_margin_right = 5
sb.content_margin_top = 1
sb.content_margin_bottom = 1
box.add_theme_stylebox_override("panel", sb)
var label := Label.new()
label.add_theme_font_override("font", _tag_font)
label.add_theme_font_size_override("font_size", 13)
box.add_child(label)
_overlay.add_child(box)
t = {"box": box, "label": label}
_tags[key] = t
t.label.text = text
# Only on a change: an override restyles the label, which reshapes its text.
if t.get("color") != color:
t.color = color
t.label.add_theme_color_override("font_color", color)
t.world = world
t.above = above
t.used = true
t.follow = follow
t.box.visible = text != ""
func _process(_delta: float) -> void:
_place_tags()
_place_pops()
_pulse_tiles()
# ---------------------------------------------------------------------------------------------
# Pop-ups
## Damage over an Anomaly: "−7", or "−7 destroyed". Shows where the card is now, or at `loc` if
## it has left the board.
func pop_damage(r: Dictionary, amount: int, destroyed: bool, loc: Variant, delay := 0.0) -> void:
var card: Card3D = _cards.get(Moves.anomaly_key(r))
var world: Vector3
if card != null and not destroyed:
world = card.global_position
elif loc != null and BoardLayout.at.has(loc):
world = BoardLayout.at[loc]
else:
return
pop_text(world, "−%d%s" % [amount, " destroyed" if destroyed else ""], Style.BAD, delay, 26)
## A short message rising from a table point, e.g. who won a roll.
func pop_text(world: Vector3, text: String, color: Color, delay := 0.0, size := 20) -> void:
var label := Label.new()
label.text = text
label.add_theme_font_override("font", _tag_font)
label.add_theme_font_size_override("font_size", size)
label.add_theme_color_override("font_color", color)
label.add_theme_color_override("font_outline_color", Color(0, 0, 0, 0.95))
label.add_theme_constant_override("outline_size", 7)
label.mouse_filter = Control.MOUSE_FILTER_IGNORE
label.visible = false
_overlay.add_child(label)
while _pops.size() >= MAX_POPS:
_pops.pop_front().label.queue_free()
_pops.append({"label": label, "world": world, "born": Time.get_ticks_msec() + int(Motion.secs(delay) * 1000)})
## The location at `loc` pulses in its new owner's color, after `delay` seconds.
func flash_capture(loc: String, p: int, delay := 0.0) -> void:
if _tiles.has(loc) and not Motion.instant():
_flashes[loc] = {"color": Style.OWNER[p], "born": Time.get_ticks_msec() + int(Motion.secs(delay) * 1000)}
func _place_pops() -> void:
var now := Time.get_ticks_msec()
for pop in _pops.duplicate():
var age: float = (now - pop.born) / 1000.0
var label: Label = pop.label
if age > POP_TIME:
label.queue_free()
_pops.erase(pop)
continue
if age < 0 or camera.is_position_behind(pop.world):
label.visible = false
continue
label.visible = true
label.reset_size()
var sp := camera.unproject_position(pop.world)
label.position = sp - Vector2(label.size.x / 2, label.size.y + 18 + 26 * age)
label.modulate.a = clampf((POP_TIME - age) / 0.6, 0.0, 1.0)
func _pulse_tiles() -> void:
if _flashes.is_empty():
return
var now := Time.get_ticks_msec()
for loc in _flashes.keys():
var f: Dictionary = _flashes[loc]
var age: float = (now - f.born) / 1000.0
var tile: MeshInstance3D = _tiles[loc].mesh
if age < 0.0:
continue
if age > FLASH_TIME:
_flashes.erase(loc)
_sync_tiles(_view, _last_marks)
continue
var k := 1.0 - age / FLASH_TIME
tile.set_instance_shader_parameter("edge_color", f.color)
tile.set_instance_shader_parameter("fill_color", Color(f.color, 0.075 + 0.25 * k))
tile.set_instance_shader_parameter("glow", 2.5 * k)
func _place_tags() -> void:
for k in _tags:
var t: Dictionary = _tags[k]
var world: Vector3 = t.world
if t.follow != null and is_instance_valid(t.follow):
world += t.follow.global_position
if t.label.text == "" or camera.is_position_behind(world):
t.box.visible = false
continue
t.box.visible = true
t.box.reset_size()
var p := camera.unproject_position(world)
t.box.position = p - Vector2(t.box.size.x / 2, t.box.size.y if t.above else t.box.size.y * 0.5)
## "3⚙ 8/10♥ ☣1": Cores, Health and status for an Anomaly.
static func badge_text(v: Dictionary, r: Dictionary) -> String:
var av := State.anomaly(v, r)
if av.card < 0 or not State.anomaly(v, State.original_of(r)).faceUp:
return ""
var parts := []
var cores := RulesEngine.anomaly_cores(v, r.player, r.slot, "defend")
parts.append("%d⚙" % cores)
if v.rules.health.on:
if av.at != null:
parts.append("%d/%d♥" % [Query.health_left(v, r), Query.health_of(v, r)])
else:
parts.append("%d♥" % Query.health_of(v, r))
var infection := State.infection_of(av)
if infection:
parts.append("☣%d" % infection)
if av.get("bugs", 0):
parts.append("✱%d" % av.bugs)
if av.at != null and State.is_rooted(v, r):
parts.append("⚓")
if av.at != null and State.is_disabled_anomaly(v, r):
parts.append("⏻")
var mods := 0
for m in State.active_mods(v, av):
mods += m.cores
if mods:
parts.append("%+d" % mods)
if State.is_copy(r):
parts.append("copy")
return " ".join(parts)
## Lays out the Executions on the stack at the right of the table, newest in front. One that
## just went on is held up in the middle for you to read first.
func _layout_stack() -> void:
var n := _stack_order.size()
if n == 0:
return
var vp := get_viewport().get_visible_rect().size
var d := HAND_DISTANCE + 2.2
var half_h := d * tan(deg_to_rad(camera.fov / 2.0))
var half_w := half_h * vp.x / vp.y
var region := Style.table_region(vp)
var right := half_w - 2.0 * half_w * (vp.x - region.end.x) / vp.x - BoardLayout.CARD_SIZE.x * 0.8
for i in n:
var c: Card3D = _stack_order[i]
if not is_instance_valid(c) or c.is_queued_for_deletion():
continue
var tilt := Basis(Vector3.RIGHT, PI / 2).rotated(Vector3.BACK, 0.06 - 0.05 * i)
var xf := Transform3D(tilt, Vector3(right - i * 0.6, half_h * 0.25 - i * 0.18, -d + i * 0.02))
var spec: Dictionary = motions.get(c.get_meta("node_key", ""), {})
if spec.get("style", "") == "stack":
var start := c.transform
if spec.get("from", "") != "":
start = camera.global_transform.affine_inverse() * _zone_xf(spec.get("p", me), spec.from)
var show := Transform3D(Basis(Vector3.RIGHT, PI / 2), Vector3(0, 0.45, -REVEAL_DISTANCE))
c.travel([start, show, show.translated(Vector3(0, 0, 0.25)), xf], PATH_TIMES.stack, spec.get("delay", 0.0),
true, spec.get("color", Style.ACCENT))
continue
if not c.has_goal():
c.transform = xf
c.glide(xf)
## Drops your held hand out of sight (true) or brings it back.
func set_hand_tucked(on: bool) -> void:
if on == _hand_tucked:
return
_hand_tucked = on
_layout_hand()
## Lays out your hand in front of the camera, the hovered card lifted.
func _layout_hand() -> void:
var cards := _hand_order.filter(func(c): return is_instance_valid(c) and not c.is_queued_for_deletion())
var n := cards.size()
if n == 0:
return
var vp := get_viewport().get_visible_rect().size
var half_h := HAND_DISTANCE * tan(deg_to_rad(camera.fov / 2.0))
var half_w := half_h * vp.x / vp.y
# Keep clear of the side panels (Style's panel geometry, as the HUD draws them).
var region := Style.table_region(vp)
var left := -half_w + 2.0 * half_w * region.position.x / vp.x + BoardLayout.CARD_SIZE.x / 2
var right := half_w - 2.0 * half_w * (vp.x - region.end.x) / vp.x - BoardLayout.CARD_SIZE.x / 2
var step := 1.34 if n == 1 else minf(1.34, (right - left) / (n - 1))
var mid := (left + right) / 2.0
var y0 := -half_h + BoardLayout.CARD_SIZE.y * (HAND_SHOWN - 0.5)
var hover_card: Node = _hover_body.get_meta("card") if _hover_body != null and is_instance_valid(_hover_body) and _hover_body.has_meta("card") else null
for i in n:
var c: Card3D = cards[i]
var x := mid + (i - (n - 1) / 2.0) * step
var lift := c == hover_card
var y := y0 + (BoardLayout.CARD_SIZE.y * 0.42 if lift else 0.0)
if c.highlight.a > 0 and not lift:
y += 0.12
if _hand_tucked:
y = -half_h - BoardLayout.CARD_SIZE.y
var pos := Vector3(x, y, -HAND_DISTANCE + i * 0.004 + (0.25 if lift else 0.0))
var xf := Transform3D(Basis(Vector3.RIGHT, PI / 2), pos)
var spec: Dictionary = motions.get(c.get_meta("node_key", ""), {})
if spec.get("style", "") == "draw":
# Drawn: off the deck, held up to you, then into the hand.
var deck := camera.global_transform.affine_inverse() * _zone_xf(me, "deck")
var hold := Transform3D(Basis(Vector3.RIGHT, PI / 2), Vector3(x * 0.45, -0.25, -REVEAL_DISTANCE - 0.3))
c.travel([deck, hold, hold.translated(Vector3(0, 0.06, 0.25)), xf], PATH_TIMES.draw, spec.get("delay", 0.0))
continue
if not c.has_goal():
# A card just drawn comes up from below.
c.transform = xf.translated(Vector3(0, -2.5, 0))
c.glide(xf)
## A screen point, clear of the side panels, where a click lands on `key`; null if there's none.
## Tries spots across each object with that key and raycasts each, as a click would. For tests.
func screen_point_for(key: String) -> Variant:
var vp := get_viewport().get_visible_rect().size
var region := Style.table_region(vp, 0.0)
var points := []
var grid := func(xf: Transform3D, half: Vector2, y: float) -> void:
for fz in [0.0, -0.6, 0.6, -0.85, 0.85]:
for fx in [0.0, -0.45, 0.45, -0.8, 0.8, -0.95, 0.95]:
points.append(xf * Vector3(fx * half.x, y, fz * half.y))
if key.begins_with("loc:") and _tiles.has(key.substr(4)):
grid.call(Transform3D(Basis.IDENTITY, BoardLayout.at[key.substr(4)]), BoardLayout.tile_size / 2, 0.004)
elif key.begins_with("gate:") and _gates.has(key.substr(5)):
points.append(_gates[key.substr(5)].at + Vector3(0, 0.05, 0))
for k in _cards:
var c: Card3D = _cards[k]
if c.pick_key == key and not c.is_queued_for_deletion():
grid.call(c.global_transform, BoardLayout.CARD_SIZE / 2, 0.006)
for pt in points:
if camera.is_position_behind(pt):
continue
var sp := camera.unproject_position(pt)
if region.has_point(sp) and key_at(sp) == key:
return sp
return null
## The key a click at screen point `sp` lands on, or "".
func key_at(sp: Vector2) -> String:
var from := camera.project_ray_origin(sp)
var q := PhysicsRayQueryParameters3D.create(from, from + camera.project_ray_normal(sp) * 150.0)
var body: Object = get_world_3d().direct_space_state.intersect_ray(q).get("collider")
return body.get_meta("key") if body != null and body.has_meta("key") else ""