Files
sor/Client/origin-client/scenes/game/game_screen.gd
T

1062 lines
45 KiB
GDScript

extends Node3D
## GameScreen — slim orchestrator.
## All gameplay logic lives in components under scenes/game/components/.
## This script instantiates them, sets their external refs, wires their signals,
## and fans out Game signals to the appropriate handler.
##
## Components owned:
## _board_ctrl BoardController — tile mesh build, affinity updates
## _cam_ctrl CameraController — yaw/pitch/distance, tweens
## _pathfinder Pathfinder — coord↔world, BFS, raycasts
## _unit_reg UnitRegistry — O(1) ownership lookups
## _tile_resolver TileTargetResolver — valid move/attack/play tile sets
## _mesh_builder UnitMeshBuilder — unit StaticBody3D + mesh lifecycle
## _animator UnitAnimator — move/damage/hitsplat animations
## _input_handler BoardInputHandler — mouse/touch → typed signals
## _hud_ctrl HudController — HUD labels, turn strip, discard viewer
## _hand_mgr HandManager — fan arc hand, card popups, spin btns
## _tile_drawer TileDrawer — slide-in tile detail panel
## _skybox SkyboxController — procedural / CDN / live skybox
## _game_over GameOverOverlay — Victory / Defeat overlay
## _inactive_dlgs InactiveDialogs — inactivity / elimination dialogs
## _sel_ctrl SelectionController — mode state, board-click dispatch
## _abt AbilityTargeting — ability panel, targeting UI, send
## _prompt_handler ServerPromptHandler — server-driven ability-pause prompts
# ── Component node vars ───────────────────────────────────────────────────────
var _board_ctrl : BoardController = null
var _cam_ctrl : CameraController = null
var _pathfinder : Pathfinder = null
var _unit_reg : UnitRegistry = null
var _tile_resolver : TileTargetResolver = null
var _mesh_builder : UnitMeshBuilder = null
var _animator : UnitAnimator = null
var _input_handler : BoardInputHandler = null
var _hud_ctrl : HudController = null
var _hand_mgr : HandManager = null
var _tile_drawer : TileDrawer = null
var _skybox : SkyboxController = null
var _game_over : GameOverOverlay = null
var _inactive_dlgs : InactiveDialogs = null
var _sel_ctrl : SelectionController = null
var _abt : AbilityTargeting = null
var _prompt_handler: ServerPromptHandler = null
# ── @onready node refs (bound to scene tree) ──────────────────────────────────
@onready var _camera_rig : Node3D = $CameraRig
@onready var _camera : Camera3D = $CameraRig/Camera3D
@onready var _tiles_root : Node3D = $BoardRoot/TilesRoot
@onready var _units_root : Node3D = $BoardRoot/UnitsRoot
@onready var _hi_root : Node3D = $BoardRoot/HighlightsRoot
@onready var _hold_timer : Timer = $HoldTimer
@onready var _cam_gesture_timer : Timer = $CamGestureTimer
@onready var _cam_ctrl_panel : Control = %CamCtrlPanel
@onready var _cam_orbit_btn : Button = %CamOrbitBtn
@onready var _cam_pan_btn : Button = %CamPanBtn
@onready var _cam_zoom_btn : Button = %CamZoomBtn
@onready var _phase_lbl : Label = %PhaseLabel
@onready var _turn_lbl : Label = %TurnLabel
@onready var _turn_order_strip : HBoxContainer = %TurnOrderStrip
@onready var _opp_panel : HBoxContainer = %OpponentPanel
@onready var _opp_name_lbl : Label = %OppNameLabel
@onready var _opp_hand_lbl : Label = %OppHandLabel
@onready var _opp_deck_lbl : Label = %OppDeckLabel
@onready var _opp_discard_btn : Button = %OppDiscardBtn
@onready var _hand_cards : Control = %HandCards
@onready var _sp_lbl : Label = %SpLabel
@onready var _st_lbl : Label = %StLabel
@onready var _deck_lbl : Label = %DeckLabel
@onready var _discard_btn : Button = %DiscardBtn
@onready var _discard_lbl : Label = %DiscardLabel
@onready var _draw_btn : Button = %DrawBtn
@onready var _end_turn_btn : Button = %EndTurnBtn
@onready var _settings_btn : Button = %SettingsBtn
@onready var _chat_bubble_host : Control = %ChatBubbleHost
@onready var _tile_drawer_toggle_btn : Button = %TileDrawerToggleBtn
@onready var _in_game_settings: PanelContainer = %InGameSettings
@onready var _ctx_popup : PanelContainer = %ContextPopup
@onready var _ctx_tile_lbl : Label = %ContextTileLabel
@onready var _ctx_unit_lbl : Label = %ContextUnitLabel
@onready var _ctx_abil_lbl : Label = %ContextAbilitiesLabel
@onready var _ctx_close_btn : Button = %ContextClose
@onready var _dv_overlay : PanelContainer = %DiscardViewer
@onready var _dv_title : Label = %DVTitle
@onready var _dv_list : VBoxContainer = %DVList
@onready var _dv_close_btn : Button = %DVCloseBtn
@onready var _go_overlay : PanelContainer = %GameOverOverlay
@onready var _go_result_lbl : Label = %GOResultLabel
@onready var _go_rank_lbl : Label = %GORankLabel
@onready var _go_menu_btn : Button = %GOMainMenuBtn
@onready var _hud : CanvasLayer = $HUD
@onready var _hand_area : PanelContainer = $HUD/HandArea
@onready var _hand_spin_left : TextureButton = %HandSpinLeft
@onready var _hand_spin_right : TextureButton = %HandSpinRight
@onready var _sp_st_panel : PanelContainer = $"HUD/SP-ST Panel Container"
@onready var _deck_discard_panel : Control = $"HUD/ActionRail/RailMargin/RailHBox/Deck-Discard Panel Container"
@onready var _spectator_panel : PanelContainer = %SpectatorPlayersPanel
@onready var _spectator_list : VBoxContainer = %SpectatorPlayerList
@onready var _spectator_leave_btn : Button = %SpectatorLeaveBtn
# ── Preloaded assets ──────────────────────────────────────────────────────────
const _CARD_WIDGET_SCENE := preload("res://scenes/collection/components/CardWidget.tscn")
const _HAND_ARROW_REGULAR := preload("res://ui/icons/Green_Gem_Arrow_Button_Regular.png")
const _HAND_ARROW_HOVER := preload("res://ui/icons/Green_Gem_Arrow_Button_Hover.png")
const _HAND_ARROW_PRESSED := preload("res://ui/icons/Green_Gem_Arrow_Button_Click.png")
const _HITSPLAT_SHIELD_ICON := preload("res://ui/icons/Shield_Overlay_Gradient.png")
const _HITSPLAT_HEART_ICON := preload("res://ui/icons/Heart_Overlay_Gradient.png")
# ── Constants shared across components ────────────────────────────────────────
const TILE_SPACING : float = 1.1
const HEX_TILE_RADIUS : float = 0.577
const HEX_TILE_SPACING : float = 1.0
const MOVE_STEP_SECS : float = 0.28
const POST_ANIM_SECS : float = 1.2
const SKY_ROTATION_SPEED : float = 0.026
# ── Minimal orchestrator state ────────────────────────────────────────────────
var _is_spectating : bool = false
var _camera_oriented : bool = false
var _local_is_p1 : bool = false
var _last_click_frame : int = -1
var _last_click_iid : String = ""
var _rebuild_pending : bool = false
var _pending_rebuild_state: Dictionary = {}
# Hover cursor quads (permanently allocated, managed inline here)
var _cursor_highlight : MeshInstance3D = null
var _hover_team_overlay : MeshInstance3D = null
var _hovered_coord : Vector2i = Vector2i(-1, -1)
var _hovered_unit_mesh : MeshInstance3D = null
# ── Lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
# ── 1. Critical game signals (connect before anything that can error) ──────
Game.state_updated.connect(_on_state_updated)
Game.game_over.connect(_on_game_over)
Game.session_abandoned.connect(_on_session_abandoned)
Game.opponent_inactive.connect(_on_opponent_inactive)
Game.inactive_warning.connect(_on_inactive_warning)
Game.both_idle_warning.connect(_on_both_idle_warning)
Game.player_eliminated.connect(_on_player_eliminated)
HighlightConfig.texture_loaded.connect(_on_highlight_texture_loaded)
# ── 2. Instantiate and configure components ────────────────────────────────
# Pathfinder
_pathfinder = Pathfinder.new()
_pathfinder.camera = _camera
add_child(_pathfinder)
# UnitRegistry
_unit_reg = UnitRegistry.new()
add_child(_unit_reg)
# TileTargetResolver
_tile_resolver = TileTargetResolver.new()
_tile_resolver.pathfinder = _pathfinder
_tile_resolver.unit_registry = _unit_reg
add_child(_tile_resolver)
# BoardController
_board_ctrl = BoardController.new()
_board_ctrl.tiles_root = _tiles_root
_board_ctrl.units_root = _units_root
_board_ctrl.hi_root = _hi_root
_board_ctrl.pathfinder = _pathfinder
add_child(_board_ctrl)
# UnitMeshBuilder
_mesh_builder = UnitMeshBuilder.new()
_mesh_builder.units_root = _units_root
_mesh_builder.unit_registry = _unit_reg
_mesh_builder.pathfinder = _pathfinder
add_child(_mesh_builder)
# UnitAnimator
_animator = UnitAnimator.new()
_animator.mesh_builder = _mesh_builder
_animator.camera = _camera
add_child(_animator)
_animator.ensure_hitsplat_layer()
_animator.rebuild_scheduled.connect(_on_rebuild_scheduled)
_mesh_builder.play_anim_requested.connect(_animator.play_unit_anim)
# CameraController
_cam_ctrl = CameraController.new()
_cam_ctrl.camera_rig = _camera_rig
_cam_ctrl.camera = _camera
_cam_ctrl.cam_ctrl_panel = _cam_ctrl_panel
_cam_ctrl.cam_orbit_btn = _cam_orbit_btn
_cam_ctrl.cam_pan_btn = _cam_pan_btn
_cam_ctrl.cam_zoom_btn = _cam_zoom_btn
add_child(_cam_ctrl)
_cam_ctrl.deactivate_touch_modes_requested.connect(
func() -> void: _input_handler.touch_cam_orbit = false
)
# SkyboxController
_skybox = SkyboxController.new()
_skybox.world_environment = $WorldEnvironment
add_child(_skybox)
# HudController
_hud_ctrl = HudController.new()
_hud_ctrl.phase_lbl = _phase_lbl
_hud_ctrl.turn_lbl = _turn_lbl
_hud_ctrl.turn_order_strip = _turn_order_strip
_hud_ctrl.opp_panel = _opp_panel
_hud_ctrl.opp_name_lbl = _opp_name_lbl
_hud_ctrl.opp_hand_lbl = _opp_hand_lbl
_hud_ctrl.opp_deck_lbl = _opp_deck_lbl
_hud_ctrl.opp_discard_btn = _opp_discard_btn
_hud_ctrl.sp_lbl = _sp_lbl
_hud_ctrl.st_lbl = _st_lbl
_hud_ctrl.deck_lbl = _deck_lbl
_hud_ctrl.discard_btn = _discard_btn
_hud_ctrl.discard_lbl = _discard_lbl
_hud_ctrl.draw_btn = _draw_btn
_hud_ctrl.end_turn_btn = _end_turn_btn
_hud_ctrl.dv_overlay = _dv_overlay
_hud_ctrl.dv_title = _dv_title
_hud_ctrl.dv_list = _dv_list
_hud_ctrl.dv_close_btn = _dv_close_btn
_hud_ctrl.spectator_panel = _spectator_panel
_hud_ctrl.spectator_list = _spectator_list
add_child(_hud_ctrl)
# HandManager
_hand_mgr = HandManager.new()
_hand_mgr.hand_cards = _hand_cards
_hand_mgr.hand_area = _hand_area
_hand_mgr.hand_spin_left = _hand_spin_left
_hand_mgr.hand_spin_right = _hand_spin_right
_hand_mgr.hud = _hud
add_child(_hand_mgr)
_hand_mgr.hand_card_clicked.connect(_on_hand_card_clicked)
# TileDrawer
_tile_drawer = TileDrawer.new()
_tile_drawer.hud = _hud
_tile_drawer.tile_drawer_toggle_btn = _tile_drawer_toggle_btn
add_child(_tile_drawer)
_tile_drawer.create_tile_drawer()
_tile_drawer.focus_camera_on_tile.connect(
func(world_pos: Vector3) -> void: _cam_ctrl.tween_to_pivot(world_pos)
)
# GameOverOverlay
_game_over = GameOverOverlay.new()
_game_over.go_overlay = _go_overlay
_game_over.go_result_lbl = _go_result_lbl
_game_over.go_rank_lbl = _go_rank_lbl
_game_over.go_menu_btn = _go_menu_btn
add_child(_game_over)
# InactiveDialogs
_inactive_dlgs = InactiveDialogs.new()
add_child(_inactive_dlgs)
_inactive_dlgs.spectator_mode_requested.connect(_on_spectator_mode_requested)
# SelectionController
_sel_ctrl = SelectionController.new()
_sel_ctrl.unit_registry = _unit_reg
_sel_ctrl.pathfinder = _pathfinder
_sel_ctrl.tile_target_resolver = _tile_resolver
_sel_ctrl.tile_bodies = _board_ctrl.tile_bodies
add_child(_sel_ctrl)
_sel_ctrl.highlights_cleared.connect(_clear_highlights)
_sel_ctrl.highlight_add_requested.connect(_add_highlight)
_sel_ctrl.highlight_tiles_requested.connect(_highlight_tiles)
_sel_ctrl.tile_drawer_open_requested.connect(
func(tile_data: Dictionary) -> void:
_tile_drawer.open_tile_drawer(tile_data)
)
_sel_ctrl.tile_drawer_close_requested.connect(_tile_drawer.close_tile_drawer)
_sel_ctrl.camera_follow_requested.connect(
func(world_pos: Vector3) -> void: _cam_ctrl.tween_to_pivot(world_pos)
)
_sel_ctrl.hand_selection_refresh_requested.connect(_refresh_hand_selection)
# AbilityTargeting
_abt = AbilityTargeting.new()
_abt.selection_controller = _sel_ctrl
_abt.unit_registry = _unit_reg
_abt.pathfinder = _pathfinder
_abt.hud = _hud
_abt.unit_bodies = _mesh_builder.unit_bodies
_abt.camera = _camera
add_child(_abt)
_sel_ctrl.ability_targeting = _abt
_abt.highlight_add_requested.connect(_add_highlight)
_abt.highlights_cleared.connect(_clear_highlights)
# ServerPromptHandler
_prompt_handler = ServerPromptHandler.new()
_prompt_handler.selection_controller = _sel_ctrl
_prompt_handler.ability_targeting = _abt
_prompt_handler.pathfinder = _pathfinder
_prompt_handler.hud = _hud
add_child(_prompt_handler)
_prompt_handler.highlight_add_requested.connect(_add_highlight)
_prompt_handler.highlights_cleared.connect(_clear_highlights)
# BoardInputHandler
_input_handler = BoardInputHandler.new()
_input_handler.hold_timer = _hold_timer
_input_handler.cam_gesture_timer = _cam_gesture_timer
_input_handler.hand_area = _hand_area
_input_handler.camera_rig = _camera_rig
_input_handler.cam_distance = _cam_ctrl.cam_distance
_input_handler.fn_mouse_to_tile_coord = func(pos: Vector2) -> Vector2i:
return _pathfinder.mouse_to_tile_coord(pos, _board_ctrl.tile_bodies)
_input_handler.fn_mouse_to_unit_id = func(pos: Vector2) -> String:
return _mouse_to_unit_id(pos)
add_child(_input_handler)
_input_handler.board_clicked.connect(_on_board_clicked)
_input_handler.board_held.connect(_on_board_held)
_input_handler.board_orbit.connect(_on_board_orbit)
_input_handler.board_pan.connect(_on_board_pan)
_input_handler.board_zoom.connect(_on_board_zoom)
_input_handler.hand_scroll.connect(_on_hand_scroll)
_input_handler.deselect_pending.connect(_on_deselect_pending)
# ── 3. Route server prompt signals to components ───────────────────────────
Game.triggered_target_request.connect(_abt.on_triggered_target_request)
Game.cost_pick_request.connect(_prompt_handler.on_cost_pick_request)
Game.cost_group_pick_request.connect(_prompt_handler.on_cost_group_pick_request)
Game.action_group_pick_request.connect(_prompt_handler.on_action_group_pick_request)
Game.branch_pick_request.connect(_prompt_handler.on_branch_pick_request)
Game.target_pick_request.connect(_prompt_handler.on_target_pick_request)
Game.tile_pick_request.connect(_prompt_handler.on_tile_pick_request)
Game.player_pick_request.connect(_prompt_handler.on_player_pick_request)
Game.reveal_choice_pick_request.connect(_prompt_handler.on_reveal_choice_pick_request)
# ── 4. HUD button wiring ──────────────────────────────────────────────────
_draw_btn.pressed.connect(_on_draw_pressed)
_end_turn_btn.pressed.connect(_on_end_turn_pressed)
_settings_btn.pressed.connect(func() -> void: _in_game_settings.open())
_discard_btn.pressed.connect(
func() -> void: _hud_ctrl.show_own_discard(Game.state))
_opp_discard_btn.pressed.connect(
func() -> void: _hud_ctrl.show_opp_discard(Game.state))
_ctx_close_btn.pressed.connect(func() -> void: _ctx_popup.visible = false)
_dv_close_btn.pressed.connect(func() -> void: _dv_overlay.visible = false)
_go_menu_btn.pressed.connect(func() -> void:
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn"))
_hold_timer.timeout.connect(_on_hold_timer_fired)
_cam_gesture_timer.timeout.connect(
func() -> void: _cam_ctrl.on_cam_gesture_timer_fired(_input_handler.gesture_finger_count)
)
_cam_orbit_btn.toggled.connect(
func(p: bool) -> void:
_cam_ctrl.on_cam_orbit_btn_toggled(p)
_input_handler.touch_cam_orbit = p and _cam_ctrl.cam_orbit_btn.button_pressed
)
_cam_pan_btn.toggled.connect(
func(p: bool) -> void:
_cam_ctrl.on_cam_pan_btn_toggled(p)
_input_handler.touch_cam_pan = p and _cam_ctrl.cam_pan_btn.button_pressed
)
_cam_zoom_btn.toggled.connect(
func(p: bool) -> void:
_cam_ctrl.on_cam_zoom_btn_toggled(p)
_input_handler.touch_cam_zoom = p and _cam_ctrl.cam_zoom_btn.button_pressed
)
_hand_area.resized.connect(_hand_mgr.queue_hand_layout)
_hand_area.resized.connect(_hand_mgr.layout_hand_spin_buttons)
_hand_cards.resized.connect(_hand_mgr.queue_hand_layout)
_hand_mgr.configure_hand_spin_buttons()
_tile_drawer_toggle_btn.pressed.connect(_tile_drawer.on_tile_drawer_toggle_pressed)
# ── 5. Camera, skybox, hover, chat ────────────────────────────────────────
_cam_ctrl.sync_cam_ctrl_panel()
Settings.settings_changed.connect(
func() -> void:
_cam_ctrl.sync_cam_ctrl_panel()
_skybox.on_skybox_setting_changed()
)
_cam_ctrl.apply_camera()
_skybox.setup_environment()
_init_cursor_nodes()
Chat.claim_bubble_visibility(self)
Chat.set_bubble_host(_chat_bubble_host)
# ── 6. Spectator / initial state ──────────────────────────────────────────
if Game.is_spectating:
_is_spectating = true
_setup_spectator_ui()
Game.request_sync()
if not Game.state.is_empty():
_on_state_updated(Game.state)
return
if not Game.state.is_empty():
_on_state_updated(Game.state)
else:
Game.send_ready()
func _process(delta: float) -> void:
var env: Environment = $WorldEnvironment.environment as Environment
if env != null:
env.sky_rotation.y += delta * SKY_ROTATION_SPEED
func _exit_tree() -> void:
if _is_spectating:
Game.stop_spectating()
# Disconnect game signals (Godot auto-disconnects on queue_free, but be explicit).
if Game.state_updated.is_connected(_on_state_updated):
Game.state_updated.disconnect(_on_state_updated)
if Game.game_over.is_connected(_on_game_over):
Game.game_over.disconnect(_on_game_over)
if Game.session_abandoned.is_connected(_on_session_abandoned):
Game.session_abandoned.disconnect(_on_session_abandoned)
if Game.opponent_inactive.is_connected(_on_opponent_inactive):
Game.opponent_inactive.disconnect(_on_opponent_inactive)
if Game.inactive_warning.is_connected(_on_inactive_warning):
Game.inactive_warning.disconnect(_on_inactive_warning)
if Game.both_idle_warning.is_connected(_on_both_idle_warning):
Game.both_idle_warning.disconnect(_on_both_idle_warning)
if Game.player_eliminated.is_connected(_on_player_eliminated):
Game.player_eliminated.disconnect(_on_player_eliminated)
if Game.game_activity.is_connected(_skybox.on_game_activity):
Game.game_activity.disconnect(_skybox.on_game_activity)
if Game.triggered_target_request.is_connected(_abt.on_triggered_target_request):
Game.triggered_target_request.disconnect(_abt.on_triggered_target_request)
if Game.cost_pick_request.is_connected(_prompt_handler.on_cost_pick_request):
Game.cost_pick_request.disconnect(_prompt_handler.on_cost_pick_request)
if Game.cost_group_pick_request.is_connected(_prompt_handler.on_cost_group_pick_request):
Game.cost_group_pick_request.disconnect(_prompt_handler.on_cost_group_pick_request)
if Game.action_group_pick_request.is_connected(_prompt_handler.on_action_group_pick_request):
Game.action_group_pick_request.disconnect(_prompt_handler.on_action_group_pick_request)
if Game.branch_pick_request.is_connected(_prompt_handler.on_branch_pick_request):
Game.branch_pick_request.disconnect(_prompt_handler.on_branch_pick_request)
if Game.target_pick_request.is_connected(_prompt_handler.on_target_pick_request):
Game.target_pick_request.disconnect(_prompt_handler.on_target_pick_request)
if Game.tile_pick_request.is_connected(_prompt_handler.on_tile_pick_request):
Game.tile_pick_request.disconnect(_prompt_handler.on_tile_pick_request)
if Game.player_pick_request.is_connected(_prompt_handler.on_player_pick_request):
Game.player_pick_request.disconnect(_prompt_handler.on_player_pick_request)
if Game.reveal_choice_pick_request.is_connected(_prompt_handler.on_reveal_choice_pick_request):
Game.reveal_choice_pick_request.disconnect(_prompt_handler.on_reveal_choice_pick_request)
_skybox.clear_stars()
_reset_unit_hover_glow()
Chat.set_bubble_host(null)
Chat.release_bubble_visibility(self)
# ── State → scene orchestration ───────────────────────────────────────────────
func _on_state_updated(state: Dictionary) -> void:
print("[GameScreen] state_updated phase=", state.get("phase", "?"),
" mode=", _sel_ctrl.mode if _sel_ctrl != null else "n/a")
_unit_reg.rebuild_ownership(state)
# Orient camera on first state that has playerOneAccountId.
var p1_id: String = str(state.get("playerOneAccountId", ""))
if not p1_id.is_empty():
_local_is_p1 = Auth.user_id.to_lower() == p1_id.to_lower()
_mesh_builder.local_is_p1 = _local_is_p1
if not _camera_oriented and not p1_id.is_empty():
_camera_oriented = true
_orient_camera_to_player(state)
# Board build / affinity update.
var board: Dictionary = state.get("board", {})
if _board_ctrl.tile_bodies.is_empty() and not board.is_empty():
_board_ctrl.build_board(board)
# Push grid info to pathfinder and sel_ctrl after board is known.
_pathfinder.grid_type = str(board.get("gridType", "Square"))
_pathfinder.hex_sides = int(board.get("hexSides", 0))
_sel_ctrl.board_grid_type = _pathfinder.grid_type
elif not board.is_empty():
for tile: Dictionary in board.get("tiles", []):
var c: Dictionary = tile.get("coord", {})
_board_ctrl.update_tile_affinity(
c.get("x", 0), c.get("y", 0),
tile.get("resolvedAffinity", "Void"))
# Sync tile height maps into mesh_builder.
_mesh_builder.tile_heights = _board_ctrl.tile_heights
_mesh_builder.tile_y_bases = _board_ctrl.tile_y_bases
# Fire animations on existing nodes before rebuild.
var move_dur: float = _animator.play_move_animations(
state, _board_ctrl.tile_heights, _board_ctrl.tile_y_bases,
_pathfinder, _board_ctrl.tile_bodies)
var dmg_played: bool = _animator.play_damage_animations(state)
# Immediate UI updates (hand / HUD don't wait for animations).
_hand_mgr.rebuild_hand(Game.get_hand(), _is_spectating)
_hud_ctrl.update_hud(state)
# Enter Placement mode whenever we haven't placed yet (simultaneous phase).
var phase: String = str(state.get("phase", ""))
if phase == "Placement" and not _is_spectating:
var my_arch: Dictionary = Game.get_my_player().get("archSpirit", {})
var i_have_placed: bool = not my_arch.is_empty() and my_arch.get("position") != null
if not i_have_placed and _sel_ctrl.mode != SelectionController.Mode.PLACEMENT:
_sel_ctrl.set_mode(SelectionController.Mode.PLACEMENT)
_clear_highlights()
_highlight_tiles(_tile_resolver.valid_placement_tiles(), "movement")
# Snapshot state for next frame's diff.
_animator.update_prev_state(state)
# Schedule delayed board rebuild to let animations finish.
var delay: float = move_dur
if dmg_played:
delay = maxf(delay, POST_ANIM_SECS)
_animator.schedule_rebuild(state, delay)
# Selection preservation across server pushes.
var cur_mode: SelectionController.Mode = _sel_ctrl.mode
match cur_mode:
SelectionController.Mode.NONE, SelectionController.Mode.PLACEMENT:
pass
SelectionController.Mode.CARD_FROM_HAND, SelectionController.Mode.TERRAMORPHA_SELECT:
var sel_card: Dictionary = _hand_mgr.find_hand_card(_sel_ctrl.sel_card_id)
if sel_card.is_empty():
_sel_ctrl.set_mode(SelectionController.Mode.NONE)
else:
_clear_highlights()
_highlight_tiles(
_tile_resolver.valid_play_tiles(sel_card, _board_ctrl.tile_bodies),
"movement")
_refresh_hand_selection()
SelectionController.Mode.ABILITY_TARGET_FORCED:
_clear_highlights()
_abt.start_ability_targeting()
_:
_sel_ctrl.set_mode(SelectionController.Mode.NONE)
# Auto-draw.
if state.get("phase", "") == "Draw" and Game.is_my_turn():
await get_tree().create_timer(0.3).timeout
Game.send_draw()
func _on_rebuild_scheduled(state: Dictionary, delay: float) -> void:
if delay <= 0.0:
# If a delayed rebuild is already in flight (protecting a move tween),
# just update its state — do NOT call rebuild_units now, which would
# kill the in-progress tween and freeze the unit mid-path.
if _rebuild_pending:
_pending_rebuild_state = state
return
_mesh_builder.rebuild_units(state)
return
# Delayed rebuild: protect any concurrent move tween from premature kills.
_pending_rebuild_state = state
if _rebuild_pending:
# A timer is already running; updating the state is enough.
return
_rebuild_pending = true
var t: SceneTreeTimer = get_tree().create_timer(delay + 0.1)
t.timeout.connect(func() -> void:
_rebuild_pending = false
_mesh_builder.rebuild_units(_pending_rebuild_state))
# ── Camera orientation helper ─────────────────────────────────────────────────
func _orient_camera_to_player(state: Dictionary) -> void:
var bw: float = float(Game.board_width())
var bh: float = float(Game.board_height())
var max_dim: float = max(bw, bh)
_cam_ctrl.cam_distance = clampf(max(max_dim, 10.0) * 1.5, 12.0, 30.0)
var pivot_len: float = clampf(max_dim * 0.2, 1.0, 5.0)
var board_d: Dictionary = Game.get_board()
var sz_raw: Dictionary = board_d.get("startingZones", {}) as Dictionary
var my_seat: int = int(Game.get_my_player().get("seatIndex", 0))
var zone: Array = (sz_raw.get(str(my_seat), []) as Array) if not sz_raw.is_empty() else []
if not zone.is_empty():
var cx: float = 0.0
var cz_v: float = 0.0
for coord: Dictionary in zone:
cx += float(coord.get("x", 0)) * TILE_SPACING - (bw - 1.0) * TILE_SPACING * 0.5
cz_v += float(coord.get("y", 0)) * TILE_SPACING - (bh - 1.0) * TILE_SPACING * 0.5
cx /= zone.size()
cz_v /= zone.size()
_cam_ctrl.cam_yaw = rad_to_deg(atan2(cx, cz_v))
var len2d: float = sqrt(cx * cx + cz_v * cz_v)
if len2d > 0.001:
_cam_ctrl.cam_pivot = Vector3(cx / len2d * pivot_len, 0.0, cz_v / len2d * pivot_len)
else:
if _local_is_p1:
_cam_ctrl.cam_yaw = 180.0
_cam_ctrl.cam_pivot = Vector3(0.0, 0.0, -pivot_len)
else:
_cam_ctrl.cam_pivot = Vector3(0.0, 0.0, pivot_len)
_cam_ctrl.apply_camera()
# ── Input delegation ──────────────────────────────────────────────────────────
func _unhandled_input(event: InputEvent) -> void:
if _input_handler != null:
_input_handler._unhandled_input(event)
func _input(event: InputEvent) -> void:
if _input_handler != null:
_input_handler._input(event)
func _on_board_clicked(screen_pos: Vector2) -> void:
var coord: Vector2i = _pathfinder.mouse_to_tile_coord(screen_pos, _board_ctrl.tile_bodies)
var unit_id: String = _mouse_to_unit_id(screen_pos)
_sel_ctrl.handle_board_click(screen_pos, coord, unit_id)
_update_hover(screen_pos)
func _on_board_held(coord: Vector2i) -> void:
_held_coord_show_popup(coord)
func _on_board_orbit(delta: Vector2) -> void:
_cam_ctrl.apply_orbit(delta)
func _on_board_pan(delta: Vector2, cam_dist: float) -> void:
_cam_ctrl.apply_pan(delta, cam_dist)
func _on_board_zoom(amount: float) -> void:
_cam_ctrl.zoom(amount)
func _on_hand_scroll(direction: int) -> void:
_hand_mgr.spin_hand(direction)
func _on_deselect_pending() -> void:
var cm: SelectionController.Mode = _sel_ctrl.mode
if cm == SelectionController.Mode.CARD_FROM_HAND \
or cm == SelectionController.Mode.TERRAMORPHA_SELECT:
_sel_ctrl.set_mode(SelectionController.Mode.NONE)
# ── Hand card click routing ───────────────────────────────────────────────────
func _on_hand_card_clicked(card_data: Dictionary) -> void:
var iid: String = str(card_data.get("instanceId", ""))
# Dedup: same card, same frame.
var cf: int = Engine.get_process_frames()
if cf == _last_click_frame and _last_click_iid == iid:
return
_last_click_frame = cf
_last_click_iid = iid
var card: Dictionary = _hand_mgr.find_hand_card(iid)
if card.is_empty():
return
if not Game.is_my_turn() and card.get("cardType", "") != "Instinct":
return
# ArchSpirit → Ascend / Transition.
if card.get("cardType", "") == "ArchSpirit":
var tier: int = int(card.get("tier", 0))
var cur_tier: int = _sel_ctrl._get_my_arch_tier()
if tier == cur_tier + 1:
_sel_ctrl._confirm_ascend(card)
elif tier == 1 and cur_tier >= 1:
_sel_ctrl._confirm_transition(card)
return
# Terramorpha → multi-tile flow.
if card.get("cardType", "") == "Terramorpha":
if Game.get_my_player().get("currentSp", 0) < card.get("spCost", 0):
return
_sel_ctrl.sel_card_id = iid
_sel_ctrl.terra_targets = []
_sel_ctrl.set_mode(SelectionController.Mode.TERRAMORPHA_SELECT)
_sel_ctrl.terra_count = _terra_count_for_card(card)
_clear_highlights()
_highlight_tiles(_tile_resolver.valid_play_tiles(card, _board_ctrl.tile_bodies), "movement")
return
# Ruin → preflight + confirm.
if card.get("cardType", "") == "Ruin":
_sel_ctrl.channel_ruin(card)
return
# Repentance / Instinct — may have an active ability.
if card.get("cardType", "") in ["Repentance", "Instinct"]:
var ab_mode: SelectionController.Mode = _sel_ctrl.mode
if (ab_mode == SelectionController.Mode.ABILITY_TARGET and _abt.ability_card_id == iid) \
or (ab_mode == SelectionController.Mode.CARD_FROM_HAND and _sel_ctrl.sel_card_id == iid):
_sel_ctrl.set_mode(SelectionController.Mode.NONE)
return
if ab_mode in [SelectionController.Mode.CARD_FROM_HAND,
SelectionController.Mode.TERRAMORPHA_SELECT] \
or (ab_mode == SelectionController.Mode.ABILITY_TARGET
and not _abt.ability_card_id.is_empty()):
_sel_ctrl.set_mode(SelectionController.Mode.NONE)
# Parse abilitiesJson for the first Active ability.
var abs_v: Variant = card.get("abilitiesJson")
var abs_raw: String = "" if abs_v == null else str(abs_v)
if not abs_raw.is_empty():
var parsed_v: Variant = JSON.parse_string(abs_raw)
if parsed_v is Array:
var parsed: Array = _abt.normalize_keys(parsed_v) as Array
for ab_var: Variant in parsed:
if not (ab_var is Dictionary):
continue
var ab: Dictionary = ab_var as Dictionary
if ab.get("type", "").to_lower() != "active":
continue
var tgt_conds: Array = []
for cv: Variant in ab.get("activationconditions", []):
if not (cv is Dictionary):
continue
var cd: Dictionary = cv as Dictionary
if cd.get("subject", "") == "target":
tgt_conds.append(cd)
_abt.ability_card_id = iid
_abt.ability_unit_id = ""
_abt.ability_idx = 0
_abt.ability_def = _abt.get_ability_actions(ab)
_abt.ability_range = {}
_abt.ability_target_conditions = tgt_conds
_abt.ability_targets = []
_abt.ability_cur_action_idx = 0
_sel_ctrl.sel_card_id = iid
_sel_ctrl.set_mode(SelectionController.Mode.ABILITY_TARGET)
_clear_highlights()
_abt.start_ability_targeting()
return
# No active ability — channel immediately.
Game.send_play_card(iid, 0, 0)
return
# Deselect if same card clicked again.
if _sel_ctrl.mode == SelectionController.Mode.CARD_FROM_HAND \
and _sel_ctrl.sel_card_id == iid:
_sel_ctrl.set_mode(SelectionController.Mode.NONE)
return
# Standard card — enter CARD_FROM_HAND mode with tile highlights.
_sel_ctrl.sel_card_id = iid
_sel_ctrl.set_mode(SelectionController.Mode.CARD_FROM_HAND)
_clear_highlights()
_highlight_tiles(_tile_resolver.valid_play_tiles(card, _board_ctrl.tile_bodies), "movement")
func _refresh_hand_selection() -> void:
if _sel_ctrl == null or _abt == null:
return
var cur_mode: SelectionController.Mode = _sel_ctrl.mode
var sel_card_id: String = _sel_ctrl.sel_card_id
var ability_card_id: String = _abt.ability_card_id
var needs_layout: bool = false
for widget: Node in _hand_cards.get_children():
if not widget.has_meta("card_instance_id"):
continue
var iid: String = str(widget.get_meta("card_instance_id"))
var sel: bool = (
(cur_mode == SelectionController.Mode.CARD_FROM_HAND
or cur_mode == SelectionController.Mode.TERRAMORPHA_SELECT
or (cur_mode == SelectionController.Mode.ABILITY_TARGET
and not ability_card_id.is_empty()))
and sel_card_id == iid)
if widget.has_method("set_selected"):
widget.set_selected(sel)
if sel != bool(widget.get_meta("_sel", false)):
widget.set_meta("_sel", sel)
needs_layout = true
if needs_layout:
_hand_mgr.queue_hand_layout()
# ── Highlight system (board overlay quads) ────────────────────────────────────
func _clear_highlights() -> void:
var children: Array = _hi_root.get_children()
for c: Node in children:
if c != _cursor_highlight and c != _hover_team_overlay:
c.queue_free()
func _add_highlight(x: int, y: int, type_key: String) -> void:
var mi: MeshInstance3D = MeshInstance3D.new()
if _pathfinder.grid_type == "Hexagon":
var hm: CylinderMesh = CylinderMesh.new()
hm.radial_segments = 6
hm.top_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING * 0.95
hm.bottom_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING * 0.95
hm.height = 0.02
mi.mesh = hm
else:
var pm: PlaneMesh = PlaneMesh.new()
pm.size = Vector2(0.96, 0.96)
mi.mesh = pm
var mat: StandardMaterial3D = StandardMaterial3D.new()
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
mat.emission_enabled = true
mat.emission_energy_multiplier = 1.5
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
mat.cull_mode = BaseMaterial3D.CULL_DISABLED
var tex: Texture2D = HighlightConfig.get_texture(type_key)
var col: Color = HighlightConfig.get_color(type_key)
if tex != null:
mat.albedo_texture = tex
mat.albedo_color = Color(col.r, col.g, col.b, col.a)
else:
mat.albedo_color = col
mat.emission = Color(col.r, col.g, col.b)
mi.material_override = mat
var tile_top: float = _board_ctrl.tile_visual_tops.get(
"%d,%d" % [x, y],
_board_ctrl.tile_y_bases.get("%d,%d" % [x, y], 0.0)
+ _board_ctrl.tile_heights.get("%d,%d" % [x, y], 1.0))
mi.position = _pathfinder.coord_to_world(x, y) + Vector3(0, tile_top + 0.05, 0)
_hi_root.add_child(mi)
func _highlight_tiles(coords: Array, type_key: String) -> void:
for coord: Variant in coords:
if coord is Vector2i:
_add_highlight((coord as Vector2i).x, (coord as Vector2i).y, type_key)
elif coord is Dictionary:
_add_highlight(
int((coord as Dictionary).get("x", 0)),
int((coord as Dictionary).get("y", 0)),
type_key)
func _on_highlight_texture_loaded(_type: String) -> void:
if _sel_ctrl == null:
return
var cm: SelectionController.Mode = _sel_ctrl.mode
match cm:
SelectionController.Mode.UNIT_SELECTED:
if not _sel_ctrl.sel_unit_id.is_empty():
_sel_ctrl.select_unit(_sel_ctrl.sel_unit_id)
SelectionController.Mode.CARD_FROM_HAND, SelectionController.Mode.TERRAMORPHA_SELECT:
var sel_card: Dictionary = _hand_mgr.find_hand_card(_sel_ctrl.sel_card_id)
if not sel_card.is_empty():
_clear_highlights()
_highlight_tiles(
_tile_resolver.valid_play_tiles(sel_card, _board_ctrl.tile_bodies),
"movement")
SelectionController.Mode.PLACEMENT:
_clear_highlights()
_highlight_tiles(_tile_resolver.valid_placement_tiles(), "movement")
_:
pass
if _hovered_coord.x >= 0:
_hovered_coord = Vector2i(-1, -1)
# ── Hover cursor ──────────────────────────────────────────────────────────────
func _init_cursor_nodes() -> void:
_cursor_highlight = _make_highlight_quad(Color(1, 1, 1, 0.25))
_hover_team_overlay = _make_highlight_quad(Color(0, 0, 0, 0))
_hi_root.add_child(_cursor_highlight)
_hi_root.add_child(_hover_team_overlay)
_cursor_highlight.visible = false
_hover_team_overlay.visible = false
func _make_highlight_quad(fallback: Color) -> MeshInstance3D:
var mi: MeshInstance3D = MeshInstance3D.new()
var pm: PlaneMesh = PlaneMesh.new()
pm.size = Vector2(0.96, 0.96)
mi.mesh = pm
var mat: StandardMaterial3D = StandardMaterial3D.new()
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
mat.albedo_color = fallback
mat.emission_enabled = true
mat.emission = Color(fallback.r, fallback.g, fallback.b)
mat.emission_energy_multiplier = 1.5
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
mat.cull_mode = BaseMaterial3D.CULL_DISABLED
mi.material_override = mat
return mi
func _update_hover(mouse_pos: Vector2) -> void:
if _cursor_highlight == null or _hover_team_overlay == null:
return
if _input_handler != null and (_input_handler.drag_active or _input_handler.pan_active):
_cursor_highlight.visible = false
_hover_team_overlay.visible = false
_reset_unit_hover_glow()
_hovered_coord = Vector2i(-1, -1)
return
var coord: Vector2i = _pathfinder.mouse_to_tile_coord(mouse_pos, _board_ctrl.tile_bodies)
if coord == _hovered_coord:
return
_reset_unit_hover_glow()
_hovered_coord = coord
if coord.x < 0:
_cursor_highlight.visible = false
_hover_team_overlay.visible = false
return
var sel_tex: Texture2D = HighlightConfig.get_texture("selector")
var sel_col: Color = HighlightConfig.get_color("selector")
_place_highlight_quad(_cursor_highlight, coord.x, coord.y, sel_col, sel_tex)
var tile: Dictionary = Game.get_tile(coord.x, coord.y)
var raw_occ: Variant = tile.get("occupantId")
var occ_id: String = str(raw_occ) if raw_occ != null else ""
if occ_id.is_empty():
_hover_team_overlay.visible = false
return
var is_enemy: bool = _unit_reg.enemy_unit_ids.has(occ_id)
var team_col: Color = Color(1.0, 0.35, 0.35, 0.35) if is_enemy else Color(0.3, 0.5, 1.0, 0.35)
_place_highlight_quad(_hover_team_overlay, coord.x, coord.y, team_col)
if _mesh_builder.unit_meshes.has(occ_id):
var mesh: MeshInstance3D = _mesh_builder.unit_meshes[occ_id] as MeshInstance3D
if mesh != null:
var orig_mat: Material = mesh.get_active_material(0)
if orig_mat != null:
var glow_mat: StandardMaterial3D = orig_mat.duplicate() as StandardMaterial3D
glow_mat.emission_enabled = true
glow_mat.emission = Color(team_col.r, team_col.g, team_col.b)
glow_mat.emission_energy_multiplier = 2.5
mesh.set_surface_override_material(0, glow_mat)
_hovered_unit_mesh = mesh
func _reset_unit_hover_glow() -> void:
if _hovered_unit_mesh != null and is_instance_valid(_hovered_unit_mesh):
_hovered_unit_mesh.set_surface_override_material(0, null)
_hovered_unit_mesh = null
func _place_highlight_quad(quad: MeshInstance3D, x: int, y: int,
col: Color, texture: Texture2D = null) -> void:
var tile_top: float = _board_ctrl.tile_visual_tops.get(
"%d,%d" % [x, y],
_board_ctrl.tile_y_bases.get("%d,%d" % [x, y], 0.0)
+ _board_ctrl.tile_heights.get("%d,%d" % [x, y], 1.0))
quad.position = _pathfinder.coord_to_world(x, y) + Vector3(0, tile_top + 0.05, 0)
var mat: StandardMaterial3D = quad.material_override as StandardMaterial3D
mat.albedo_color = col
mat.emission = Color(col.r, col.g, col.b)
if texture != null:
mat.albedo_texture = texture
quad.visible = true
# ── Hold-timer context popup ──────────────────────────────────────────────────
func _on_hold_timer_fired() -> void:
var coord: Vector2i = _input_handler.held_coord if _input_handler != null else Vector2i(-1, -1)
if coord.x < 0:
return
_held_coord_show_popup(coord)
func _held_coord_show_popup(coord: Vector2i) -> void:
var tile: Dictionary = Game.get_tile(coord.x, coord.y)
if tile.is_empty():
return
var aff: String = tile.get("resolvedAffinity", "Void")
_ctx_tile_lbl.text = "Tile (%d,%d) — %s" % [coord.x, coord.y, aff]
var raw_occ: Variant = tile.get("occupantId")
var occupant_id: String = raw_occ if raw_occ is String else ""
if occupant_id.is_empty():
_ctx_unit_lbl.text = ""
_ctx_abil_lbl.text = ""
else:
var unit: Dictionary = Game.get_unit_by_id(occupant_id)
_ctx_unit_lbl.text = "%s HP %d/%d DEF %d/%d ATK %d" % [
unit.get("name", "?"),
int(unit.get("currentHealth", 0)), int(unit.get("maxHealth", 0)),
int(unit.get("currentDefense", 0)), int(unit.get("maxDefense", 0)),
int(unit.get("damage", 0))]
var abil_str: String = ""
var raw_abil: Variant = unit.get("abilitiesJson")
var parsed: Variant = JSON.parse_string("[]" if raw_abil == null else str(raw_abil))
if parsed is Array:
for ab: Dictionary in parsed:
abil_str += "• %s\n" % str(ab.get("name", ""))
_ctx_abil_lbl.text = abil_str.strip_edges()
_ctx_popup.visible = true
# ── Game-over / session signals ───────────────────────────────────────────────
func _on_game_over(winner_id: String, win_condition: String,
winner_delta: int, loser_delta: int, player_outcomes: Array = []) -> void:
_game_over.show_result(winner_id, win_condition, winner_delta, loser_delta, player_outcomes)
func _on_session_abandoned(reason: String) -> void:
_game_over.on_session_abandoned(reason)
func _on_opponent_inactive(sid: String) -> void:
_inactive_dlgs.on_opponent_inactive(sid)
func _on_inactive_warning(sid: String) -> void:
_inactive_dlgs.on_inactive_warning(sid)
func _on_both_idle_warning(sid: String) -> void:
_inactive_dlgs.on_both_idle_warning(sid)
func _on_player_eliminated(session_id: String, elim_id: String,
seat_idx: int, team_idx: int) -> void:
_inactive_dlgs.on_player_eliminated(session_id, elim_id, seat_idx, team_idx)
func _on_spectator_mode_requested() -> void:
_is_spectating = true
_setup_spectator_ui()
# ── Spectator ─────────────────────────────────────────────────────────────────
func _setup_spectator_ui() -> void:
_pending_popup_cards_clear()
var lbl: Label = Label.new()
lbl.text = "SPECTATING"
lbl.modulate = Color(1.0, 0.76, 0.2)
lbl.add_theme_font_size_override("font_size", 18)
lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
lbl.set_anchors_preset(Control.PRESET_TOP_WIDE)
lbl.position = Vector2(0, 8)
_hud.add_child(lbl)
_hand_area.visible = false
_sp_st_panel.visible = false
_deck_discard_panel.visible = false
_draw_btn.visible = false
_end_turn_btn.visible = false
_spectator_panel.visible = true
_spectator_leave_btn.visible = true
_spectator_leave_btn.pressed.connect(func() -> void:
Game.stop_spectating()
get_tree().change_scene_to_file("res://scenes/free_play/FreePlayScreen.tscn"))
func _pending_popup_cards_clear() -> void:
if _hand_mgr != null:
_hand_mgr.pending_popup_cards.clear()
if is_instance_valid(_hand_mgr.popup_layer):
_hand_mgr.popup_layer.visible = false
# ── Action buttons ────────────────────────────────────────────────────────────
func _on_draw_pressed() -> void:
Game.send_draw()
func _on_end_turn_pressed() -> void:
_sel_ctrl.set_mode(SelectionController.Mode.NONE)
Game.send_end_turn()
# ── Helpers ───────────────────────────────────────────────────────────────────
func _mouse_to_unit_id(mouse_pos: Vector2) -> String:
var body: PhysicsBody3D = _pathfinder.raycast_body(mouse_pos)
if body == null:
return ""
return str(body.get_meta("unit_id", ""))
func _terra_count_for_card(card: Dictionary) -> int:
match card.get("terramorphaMode", ""):
"Mono": return 1
"Di": return 2
"Tri": return 3
return 1