files-game/table/game_table.gd
2026-10-01 17:22:18 -04:00

900 lines
32 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")
## Okabe–Ito sky blue and orange, as in the browser app: they stay apart for color-blind players.
const OWNER_COLORS: Array[Color] = [Color("#56b4e9"), Color("#e69f00")]
const MARK_COLORS := {
"source": Color("#2de2c4"), "respond": Color("#ffb454"), "selected": Color("#ffffff"),
"target": Color("#2de2c4"), "attack": Color("#ff5c7a"), "fight": Color("#ff5c7a"),
}
const MARK_STRENGTH := {"source": 1.0, "respond": 1.2, "selected": 2.0, "target": 1.5, "attack": 1.8, "fight": 1.2}
const FIREWALL_COLORS: Array[Color] = [Color("#ffb454"), Color("#ff7a45"), Color("#ff3d3d")]
## Your hand, held in front of the camera: distance and how much of a card shows at the bottom.
const HAND_DISTANCE := 9.0
const HAND_SHOWN := 0.62
## Screen space the 2D panels cover, in pixels at the 1600 × 900 base size. The camera fits the
## mat into what's left.
const PANEL_LEFT := 300.0
const PANEL_RIGHT := 345.0
const PANEL_TOP := 48.0
const PANEL_BOTTOM := 150.0
## 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 := 6
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 _tiles := {}
var _gates := {}
var _lines := {}
var _cards := {}
var _piles := {}
var _hover_body: Object = null
## Your hand's cards in hand order.
var _hand_order: Array[Card3D] = []
var _zoom := 1.0
var _cam_tween: Tween
var _view: Dictionary = {}
var _font: SystemFont
var _tag_font: SystemFont
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 := {}
func _ready() -> void:
_font = SystemFont.new()
_font.font_names = PackedStringArray(["DejaVu Sans", "Noto Sans", "sans-serif"])
_tag_font = SystemFont.new()
_tag_font.font_names = PackedStringArray(["DejaVu Sans Mono", "Adwaita Mono", "monospace"])
_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:
var env := Environment.new()
env.background_mode = Environment.BG_COLOR
env.background_color = Color(0.035, 0.035, 0.045)
env.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR
env.ambient_light_color = Color(0.72, 0.75, 0.82)
env.ambient_light_energy = 0.85
env.tonemap_mode = Environment.TONE_MAPPER_FILMIC
env.glow_enabled = true
env.glow_intensity = 0.4
env.glow_hdr_threshold = 1.2
var we := WorldEnvironment.new()
we.environment = env
add_child(we)
var sun := DirectionalLight3D.new()
sun.light_color = Color(0.9, 0.87, 0.82)
sun.light_energy = 1.35
sun.shadow_enabled = true
sun.directional_shadow_max_distance = 60.0
add_child(sun)
sun.look_at_from_position(Vector3(6, 20, 9), Vector3.ZERO, Vector3.UP)
# The table under the mat: dark wood.
var top := MeshInstance3D.new()
var box := BoxMesh.new()
box.size = Vector3(64, 1, 52)
top.mesh = box
var wood := StandardMaterial3D.new()
wood.albedo_color = Color(0.16, 0.105, 0.07)
wood.roughness = 0.62
top.material_override = wood
top.position = Vector3(0, -0.6, 0)
add_child(top)
add_child(PLAYMAT_SCENE.instantiate())
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()
_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
var line_material := StandardMaterial3D.new()
line_material.albedo_color = Color(0.85, 0.88, 0.92, 0.32)
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("radius", 0.1)
spot_material.set_shader_parameter("edge_width", 0.04)
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(34)
name.text = names[i]
name.modulate = Color(OWNER_COLORS[p], 0.75)
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(OWNER_COLORS[p], 0.06))
m.set_instance_shader_parameter("edge_color", Color(OWNER_COLORS[p], 0.5))
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)
var label := _flat_label(64)
label.position = BoardLayout.at[loc] + Vector3(BoardLayout.tile_size.x / 2 - 1.0, 0.004, 0)
_board.add_child(label)
_tiles[loc] = {"mesh": tile, "label": label}
## 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 diamond := MeshInstance3D.new()
var dm := PlaneMesh.new()
dm.size = Vector2(0.34, 0.34)
diamond.mesh = dm
var mat := StandardMaterial3D.new()
mat.albedo_color = Color(0.85, 0.88, 0.92, 0.55)
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
mat.emission_enabled = true
mat.emission = Color.BLACK
mat.render_priority = -1
diamond.material_override = mat
diamond.position = at + Vector3(0, 0.004, 0)
diamond.rotation.y = PI / 4
diamond.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
_board.add_child(diamond)
var wall := MeshInstance3D.new()
var wm := BoxMesh.new()
wm.size = Vector3(1.0, 1.0, 0.14)
wall.mesh = wm
var wall_mat := StandardMaterial3D.new()
wall_mat.albedo_color = FIREWALL_COLORS[0]
wall_mat.emission_enabled = true
wall_mat.emission = FIREWALL_COLORS[0]
wall_mat.emission_energy_multiplier = 0.35
wall_mat.roughness = 0.4
wall.material_override = wall_mat
wall.position = at
wall.rotation.y = yaw
wall.visible = false
_board.add_child(wall)
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 {"diamond": diamond, "mat": mat, "wall": wall, "wall_mat": wall_mat, "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(0.85, 0.88, 0.92, 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 sx := vp.x / 1600.0
var sy := vp.y / 900.0
var region := Rect2(PANEL_LEFT * sx, PANEL_TOP * sy, vp.x - (PANEL_LEFT + PANEL_RIGHT) * sx, vp.y - (PANEL_TOP + PANEL_BOTTOM) * sy)
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
## Snaps the table to `view` (as seen by `me`), with `marks` from key to a mark name (see
## MARK_COLORS).
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)
var want := {}
_want_board_cards(v, want)
_want_zones(v, want)
_apply_cards(want, marks)
_layout_hand()
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
var fill := Color(1, 1, 1, 0.018)
var edge := Color(0.82, 0.85, 0.9, 0.4)
if owner != null:
fill = Color(OWNER_COLORS[owner], 0.075)
edge = Color(OWNER_COLORS[owner], 0.85)
var glow := 0.0
var mark = marks.get(Moves.loc_key(loc))
if mark != null:
edge = MARK_COLORS[mark]
glow = 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)]
label.rotation.y = 0.0 if me == 0 else PI
func _sync_gates(v: Dictionary, marks: Dictionary) -> void:
for line_id in _gates:
var g: Dictionary = _gates[line_id]
var level: int = v.firewalls.get(line_id, 0)
var mark = marks.get(Moves.gate_key(line_id))
var mat: StandardMaterial3D = g.mat
if mark != null:
mat.albedo_color = MARK_COLORS[mark]
mat.emission = MARK_COLORS[mark] * MARK_STRENGTH[mark]
else:
mat.albedo_color = Color(0.85, 0.88, 0.92, 0.55) if level == 0 else Color(FIREWALL_COLORS[level - 1], 0.9)
mat.emission = Color.BLACK
var wall: MeshInstance3D = g.wall
wall.visible = level > 0
if level > 0:
var h := 0.22 + 0.2 * level
wall.scale = Vector3(1, h, 1)
wall.position.y = h / 2.0
var c := FIREWALL_COLORS[mini(level, FIREWALL_COLORS.size()) - 1]
g.wall_mat.albedo_color = c
g.wall_mat.emission = c
_tag("gate:" + line_id, "Lv %d" % level, c.lightened(0.3), g.at + Vector3(0, h + 0.1, 0), true)
var seg: MeshInstance3D = _lines[line_id]
seg.transparency = 0.6 if level > 0 else 0.0
## 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}
## 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 = []
for key in _cards.keys():
if not want.has(key):
_cards[key].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 parent: Node = _hand_root if w.get("hand", false) 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
if w.get("hand", false):
_hand_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 = MARK_STRENGTH[mark] * (0.55 if w.get("hand", false) else 1.0) if mark != null else 0.0
card.highlight = Color(MARK_COLORS[mark], strength) if mark != null else Color(0, 0, 0, 0)
if not w.get("hand", false):
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)
if fresh:
card.transform = xf
card.glide(xf, fresh)
_sync_badge(key, w)
## 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), OWNER_COLORS[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 := StyleBoxFlat.new()
sb.bg_color = Color(0.02, 0.03, 0.04, 0.78)
sb.set_corner_radius_all(4)
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
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 ""], Color("#ff6b6b"), 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(delay * 1000)})
## The location at `loc` pulses in its new owner's color.
func flash_capture(loc: String, p: int) -> void:
if _tiles.has(loc):
_flashes[loc] = {"color": OWNER_COLORS[p], "born": Time.get_ticks_msec()}
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 > 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 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 (see the HUD): 300 px on the left, 340 on the right.
var left := -half_w + 2.0 * half_w * 300.0 / vp.x + BoardLayout.CARD_SIZE.x / 2
var right := half_w - 2.0 * half_w * 340.0 / 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
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)
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 sx := vp.x / 1600.0
var region := Rect2(PANEL_LEFT * sx, PANEL_TOP * vp.y / 900.0, vp.x - (PANEL_LEFT + PANEL_RIGHT) * sx, vp.y)
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 ""