4240 lines
168 KiB
GDScript
4240 lines
168 KiB
GDScript
extends Node3D
|
||
## GameScreen — 3D ranked game board with 2D HUD overlay.
|
||
##
|
||
## Selection modes:
|
||
## NONE — nothing selected
|
||
## CARD_FROM_HAND — hand card selected, waiting for tile target
|
||
## TERRAMORPHA_SELECT — accumulating tile targets for a Terramorpha card
|
||
## UNIT_SELECTED — friendly unit selected, shows move/attack ranges
|
||
## PLACEMENT — placing ArchSpirit during Placement phase
|
||
## SACRIFICE_SELECT — waiting for the player to pick a spirit to sacrifice
|
||
## ABILITY_TARGET — waiting for ability target (blue highlights)
|
||
|
||
# ── Selection mode ────────────────────────────────────────────────────────────
|
||
|
||
enum Mode {
|
||
NONE,
|
||
CARD_FROM_HAND,
|
||
TERRAMORPHA_SELECT,
|
||
UNIT_SELECTED,
|
||
PLACEMENT,
|
||
SACRIFICE_SELECT,
|
||
ABILITY_TARGET,
|
||
}
|
||
|
||
# ── Node refs ─────────────────────────────────────────────────────────────────
|
||
|
||
@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
|
||
|
||
# HUD
|
||
@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 : HBoxContainer = %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 _draw_btn : Button = %DrawBtn
|
||
@onready var _end_turn_btn : Button = %EndTurnBtn
|
||
@onready var _settings_btn : Button = %SettingsBtn
|
||
@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
|
||
|
||
var count : int = 0
|
||
var _cam_tween : Tween = null
|
||
var _last_click_frame : int = -1
|
||
var _last_click_iid : String = ""
|
||
var _is_spectating : bool = false
|
||
# ── Affinity colors ───────────────────────────────────────────────────────────
|
||
|
||
const AFFINITY_COLORS : Dictionary = {
|
||
"Void": Color(0.18, 0.18, 0.22),
|
||
"Aether": Color(0.60, 0.45, 0.85),
|
||
"Lake": Color(0.28, 0.52, 0.88),
|
||
"Hill": Color(0.58, 0.44, 0.26),
|
||
"Forest": Color(0.22, 0.52, 0.24),
|
||
"Field": Color(0.62, 0.72, 0.28),
|
||
"Ocean": Color(0.10, 0.20, 0.72),
|
||
"Island": Color(0.38, 0.68, 0.84),
|
||
"Marsh": Color(0.38, 0.52, 0.34),
|
||
"Swamp": Color(0.24, 0.33, 0.20),
|
||
"Mountain": Color(0.50, 0.44, 0.38),
|
||
"Steppe": Color(0.72, 0.63, 0.38),
|
||
"Fort": Color(0.40, 0.34, 0.30),
|
||
"Plains": Color(0.78, 0.74, 0.50),
|
||
"Grove": Color(0.33, 0.58, 0.28),
|
||
"Jungle": Color(0.15, 0.42, 0.20),
|
||
"PerfectAether": Color(0.88, 0.72, 1.00),
|
||
"PureVoid": Color(0.05, 0.05, 0.10),
|
||
"UnstableAether":Color(0.70, 0.55, 0.90),
|
||
"GatewayLake": Color(0.22, 0.42, 0.70),
|
||
"GatewayHill": Color(0.46, 0.34, 0.18),
|
||
"GatewayForest": Color(0.18, 0.42, 0.18),
|
||
"GatewayField": Color(0.52, 0.60, 0.22),
|
||
}
|
||
|
||
const _CARD_WIDGET_SCENE := preload("res://scenes/collection/components/CardWidget.tscn")
|
||
const _CHAT_OVERLAY_SCENE := preload("res://scenes/chat/ChatOverlay.tscn")
|
||
|
||
const HI_GREEN := Color(0.20, 0.90, 0.20, 0.40)
|
||
const HI_RED := Color(1.00, 0.25, 0.25, 0.50)
|
||
const HI_BLUE := Color(0.20, 0.50, 1.00, 0.40)
|
||
const HI_YELLOW := Color(1.00, 0.85, 0.10, 0.50)
|
||
const HI_ORANGE := Color(1.00, 0.60, 0.10, 0.45)
|
||
|
||
# ── Camera state ──────────────────────────────────────────────────────────────
|
||
|
||
var _cam_yaw : float = 0.0
|
||
var _cam_pitch : float = 40.0
|
||
var _cam_distance : float = 14.0
|
||
var _cam_pivot : Vector3 = Vector3.ZERO
|
||
var _drag_active : bool = false
|
||
var _press_was_on_board: bool = false # true only when the PRESS came from unhandled_input (board, not a UI card)
|
||
var _camera_oriented : bool = false
|
||
var _pan_active : bool = false
|
||
var _orbit_active : bool = false # right-mouse drag → camera orbit on desktop
|
||
var _last_mouse : Vector2 = Vector2.ZERO
|
||
var _touch_points : Dictionary = {}
|
||
var _pinch_dist : float = 0.0
|
||
# True from the moment a second finger lands until ALL fingers lift.
|
||
# Prevents single-finger orbit from triggering during a pinch gesture even
|
||
# if a ScreenDrag for finger-0 arrives before finger-1's ScreenTouch is processed.
|
||
var _was_multi_touch : bool = false
|
||
var _touch_drag_active : bool = false # camera mode fired during this touch; suppresses tap-click
|
||
var _touch_drag_total : float = 0.0 # cumulative drag distance since last touch-down (gates camera actions)
|
||
var _touch_start_pos : Vector2 = Vector2.ZERO # finger position at touch-down (for start-to-end tap detection)
|
||
|
||
# Touch camera mode — which camera action is currently active on touch
|
||
var _touch_cam_orbit : bool = false # single-finger drag → orbit
|
||
var _touch_cam_pan : bool = false # single-finger drag → pan
|
||
var _touch_cam_zoom : bool = false # single-finger drag up/down → zoom
|
||
# Gesture-hold detection
|
||
var _gesture_move_accum : float = 0.0 # cumulative movement since fingers last settled
|
||
var _gesture_finger_count : int = 0 # finger count when _cam_gesture_timer was last started
|
||
|
||
# ── Selection state ───────────────────────────────────────────────────────────
|
||
|
||
var _mode : Mode = Mode.NONE
|
||
var _sel_card_id : String = ""
|
||
var _sel_unit_id : String = ""
|
||
var _held_coord : Vector2i = Vector2i(-1, -1)
|
||
|
||
# Terramorpha
|
||
var _terra_targets : Array = [] # Array[Vector2i]
|
||
var _terra_count : int = 0 # total tiles needed (1/2/3)
|
||
|
||
# Sacrifice
|
||
var _sac_arch_coord : Vector2i = Vector2i(-1, -1)
|
||
|
||
# Ability
|
||
var _ability_unit_id : String = ""
|
||
var _ability_idx : int = -1
|
||
var _ability_panel : Control = null
|
||
var _ability_def : Array = [] # Actions array from parsed ability JSON
|
||
var _ability_range : Dictionary = {} # Top-level range {min, max, linearonly, requireslos}
|
||
var _ability_targets : Array = [] # collected AbilityTarget dicts to send
|
||
var _ability_cur_action_idx : int = 0 # which Action we are currently collecting for
|
||
var _ability_card_id : String = "" # non-empty when targeting for a card's active ability
|
||
var _ability_target_conditions: Array = [] # target-side ActivationConditions from card ability
|
||
var _ability_target_n : int = 1 # count.N for current action
|
||
var _ability_target_up_to : bool = false # count.upTo for current action
|
||
var _ability_targets_this_action : int = 0 # targets collected for current action so far
|
||
var _ability_confirm_btn : Control = null # "Done" button shown for UpTo selections
|
||
var _ability_branch_panel : Control = null # ChooseOne branch selector panel
|
||
var _player_panel : Control = null
|
||
|
||
# Triggered ability target prompting
|
||
var _is_triggered_target : bool = false # true when targeting for a server-paused trigger
|
||
var _triggered_request_id : String = "" # requestId to echo back in the response
|
||
|
||
# Tile detail drawer (right-side slide-in panel)
|
||
var _tile_drawer : PanelContainer = null
|
||
var _tile_drawer_open : bool = false
|
||
var _tile_drawer_tween : Tween = null
|
||
var _tile_drawer_lbl_coord : Label = null
|
||
var _tile_drawer_lbl_aff : Label = null
|
||
var _tile_drawer_lbl_b1 : Label = null
|
||
var _tile_drawer_lbl_b2 : Label = null
|
||
var _tile_drawer_lbl_ruin : Label = null
|
||
var _tile_drawer_lbl_occ : Label = null
|
||
|
||
# ── Unit ownership lookup ─────────────────────────────────────────────────────
|
||
# Rebuilt on each state update for O(1) ownership checks.
|
||
var _enemy_unit_ids : Dictionary = {} # instanceId → true
|
||
var _friendly_unit_ids: Dictionary = {} # instanceId → true
|
||
|
||
# ── Scene refs ────────────────────────────────────────────────────────────────
|
||
var _tile_bodies : Dictionary = {} # "x,y" → StaticBody3D
|
||
var _unit_meshes : Dictionary = {} # instanceId → Node3D (placeholder or real model)
|
||
var _unit_bodies : Dictionary = {} # instanceId → StaticBody3D
|
||
var _anim_players : Dictionary = {} # instanceId → AnimationPlayer (null if none)
|
||
var _unit_def_ids : Dictionary = {} # instanceId → card definition ID string
|
||
|
||
# ── Skybox state ───────────────────────────────────────────────────────────────
|
||
const SKY_ROTATION_SPEED := 0.026 # rad/sec — ~4 min per full revolution
|
||
var _skybox_sky : Sky = null # the Sky object created in _setup_environment
|
||
var _skybox_frames : Array = [] # Array[ImageTexture] for animated skybox frames
|
||
var _skybox_frame_idx : int = 0
|
||
var _skybox_timer : Timer = null
|
||
var _stars : Dictionary = {} # sessionId (String) → MeshInstance3D (live mode)
|
||
var _ambient_star_timer : Timer = null
|
||
var _ambient_star_ctr : int = 0 # counter for unique ambient IDs
|
||
|
||
# ── Animation / facing state ───────────────────────────────────────────────────
|
||
var _local_is_p1 : bool = false # true when Auth.user_id == playerOneAccountId
|
||
var _prev_unit_hp : Dictionary = {} # instanceId → int, HP snapshot for damage detection
|
||
var _prev_unit_pos: Dictionary = {} # instanceId → Vector2i, position snapshot for move detection
|
||
var _move_anims : Dictionary = {} # instanceId → Tween (active movement tweens)
|
||
var _last_attack_target_iid : String = "" # target of the most recent send_attack() call
|
||
var _tile_heights : Dictionary = {} # "x,y" → float, height of tile block
|
||
var _tile_y_bases : Dictionary = {} # "x,y" → float, vertical stagger offset
|
||
var _tile_visual_tops : Dictionary = {} # "x,y" → float, actual visual top Y in world space (updated after model loads)
|
||
|
||
# Delayed rebuild: when animations need time to play we don't destroy unit nodes immediately.
|
||
var _pending_rebuild : Dictionary = {} # latest state waiting for the delayed rebuild
|
||
var _rebuild_tween : Tween = null
|
||
|
||
## Seconds per grid step when animating unit movement along the BFS path.
|
||
const MOVE_STEP_SECS : float = 0.28
|
||
## How long to hold after one-shot animations (attack / damaged / dying) before rebuilding.
|
||
const POST_ANIM_SECS : float = 1.2
|
||
## Seconds to skip at the start of looping animations on subsequent loop iterations.
|
||
## GLB animations use the first N frames as a transition-in from idle; on repeat loops
|
||
## we jump past them to avoid the bind-pose flash.
|
||
const ANIM_TRANSITION_SECS : float = 5.0 / 30.0 # 5 frames at 30 fps
|
||
|
||
# Per-unit animation loop tracking.
|
||
var _idle_entry_done : Dictionary = {} # iid → true once the first idle entry has played
|
||
var _idle_callbacks : Dictionary = {} # iid → Callable (active loop reconnect, to cancel on interrupt)
|
||
var _oneshot_callbacks : Dictionary = {} # iid → Callable (animation_finished → next action, replaceable)
|
||
# Per-unit model config.
|
||
var _model_base_angles : Dictionary = {} # iid → float (base facing angle, radians)
|
||
var _needs_face_rot : Dictionary = {} # iid → bool (team-based 180° flip flag)
|
||
# Model retry tracking (when real GLB failed to download at placement time).
|
||
var _unit_model_retries : Dictionary = {} # iid → attempt number (1-based, capped at 10)
|
||
|
||
# ── Cursor & hover state ───────────────────────────────────────────────────────
|
||
## The selector highlight follows the mouse tile at all times.
|
||
var _cursor_highlight : MeshInstance3D = null
|
||
## Team-colour overlay shown when hovering an occupied tile or unit.
|
||
var _hover_team_overlay : MeshInstance3D = null
|
||
## Currently hovered tile coord (updated every mouse-motion event).
|
||
var _hovered_coord : Vector2i = Vector2i(-1, -1)
|
||
## The MeshInstance3D of the unit currently receiving a hover-glow override.
|
||
var _hovered_unit_mesh : MeshInstance3D = null
|
||
|
||
## Animation name aliases: maps the canonical lower-case action to fallback track names.
|
||
## The AnimationPlayer track list is matched case-insensitively against each entry.
|
||
const ANIM_ALIASES : Dictionary = {
|
||
"idle": ["idle", "idle_a", "idle1", "idle_loop"],
|
||
"attack": ["attack", "attack_a", "attack1", "attack_b", "strike"],
|
||
"damaged": ["damaged", "attacked", "hit", "hurt", "flinch"],
|
||
"dying": ["dying", "death", "die", "dead"],
|
||
"moving": ["moving", "move", "walk", "run", "walk_cycle"],
|
||
}
|
||
|
||
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
||
|
||
func _ready() -> void:
|
||
_setup_environment()
|
||
_apply_camera()
|
||
_init_cursor_nodes()
|
||
|
||
_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: _show_own_discard())
|
||
_opp_discard_btn.pressed.connect(func() -> void: _show_opp_discard())
|
||
_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(_on_cam_gesture_timer_fired)
|
||
_cam_orbit_btn.toggled.connect(_on_cam_orbit_btn_toggled)
|
||
_cam_pan_btn.toggled.connect(_on_cam_pan_btn_toggled)
|
||
_cam_zoom_btn.toggled.connect(_on_cam_zoom_btn_toggled)
|
||
_sync_cam_ctrl_panel()
|
||
Settings.settings_changed.connect(_sync_cam_ctrl_panel)
|
||
_create_tile_drawer()
|
||
Game.triggered_target_request.connect(_on_triggered_target_request)
|
||
|
||
# Chat overlay — add to viewport root so it renders above everything.
|
||
var _chat_overlay := _CHAT_OVERLAY_SCENE.instantiate()
|
||
get_tree().get_root().add_child(_chat_overlay)
|
||
|
||
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)
|
||
|
||
if Game.is_spectating:
|
||
_is_spectating = true
|
||
_setup_spectator_ui()
|
||
# State was already applied via game.spectate ack — re-emit if present.
|
||
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 := $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()
|
||
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(_on_game_activity):
|
||
Game.game_activity.disconnect(_on_game_activity)
|
||
if Game.triggered_target_request.is_connected(_on_triggered_target_request):
|
||
Game.triggered_target_request.disconnect(_on_triggered_target_request)
|
||
if Settings.settings_changed.is_connected(_on_skybox_setting_changed):
|
||
Settings.settings_changed.disconnect(_on_skybox_setting_changed)
|
||
_reset_unit_hover_glow()
|
||
# Unsubscribe from activity feed and free star nodes.
|
||
if _ambient_star_timer != null and is_instance_valid(_ambient_star_timer):
|
||
_ambient_star_timer.queue_free()
|
||
_ambient_star_timer = null
|
||
if Settings.skybox_mode == "live":
|
||
Network.request("game.unsubscribe_activity", {},
|
||
func(_t: String, _r: Variant) -> void: pass,
|
||
func(_c: String, _m: String) -> void: pass)
|
||
_clear_stars()
|
||
# Remove chat overlay added to the viewport root.
|
||
var root := get_tree().get_root()
|
||
for child in root.get_children():
|
||
if child.name == "ChatOverlay":
|
||
child.queue_free()
|
||
|
||
|
||
func _setup_spectator_ui() -> void:
|
||
# "SPECTATING" label at top-center.
|
||
var lbl := 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)
|
||
|
||
# "Leave" button for spectators (top-right corner).
|
||
var leave_btn := Button.new()
|
||
leave_btn.text = "Leave"
|
||
leave_btn.set_anchors_preset(Control.PRESET_TOP_RIGHT)
|
||
leave_btn.position = Vector2(-90, 8)
|
||
leave_btn.custom_minimum_size = Vector2(80, 32)
|
||
leave_btn.pressed.connect(func() -> void:
|
||
Game.stop_spectating()
|
||
get_tree().change_scene_to_file("res://scenes/free_play/FreePlayScreen.tscn"))
|
||
_hud.add_child(leave_btn)
|
||
|
||
# Hide action buttons and the settings panel — spectators cannot interact with the game.
|
||
_draw_btn.visible = false
|
||
_end_turn_btn.visible = false
|
||
_settings_btn.visible = false
|
||
|
||
# ── Environment ───────────────────────────────────────────────────────────────
|
||
|
||
func _setup_environment() -> void:
|
||
var env := Environment.new()
|
||
_skybox_sky = Sky.new()
|
||
env.background_mode = Environment.BG_SKY
|
||
env.sky = _skybox_sky
|
||
env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY
|
||
$WorldEnvironment.environment = env
|
||
|
||
match Settings.skybox_mode:
|
||
"live":
|
||
_setup_live_skybox(env)
|
||
"cdn":
|
||
_setup_procedural_sky(env)
|
||
_apply_skybox_from_cache()
|
||
_: # "off" or any unknown value
|
||
_setup_procedural_sky(env)
|
||
|
||
# Re-apply skybox whenever the user changes the setting mid-game.
|
||
if not Settings.settings_changed.is_connected(_on_skybox_setting_changed):
|
||
Settings.settings_changed.connect(_on_skybox_setting_changed)
|
||
|
||
## Dark blue procedural sky — shown for "off" mode and as the CDN loading placeholder.
|
||
func _setup_procedural_sky(env: Environment = null) -> void:
|
||
if _skybox_timer != null:
|
||
_skybox_timer.queue_free()
|
||
_skybox_timer = null
|
||
_skybox_frames.clear()
|
||
var proc := ProceduralSkyMaterial.new()
|
||
proc.sky_top_color = Color(0.08, 0.10, 0.20)
|
||
proc.sky_horizon_color = Color(0.28, 0.38, 0.55)
|
||
proc.ground_bottom_color = Color(0.373, 0.374, 0.484, 1.0)
|
||
proc.ground_horizon_color = Color(0.20, 0.28, 0.38)
|
||
if is_instance_valid(_skybox_sky):
|
||
_skybox_sky.sky_material = proc
|
||
var e : Environment = env if env != null else $WorldEnvironment.environment
|
||
if e != null:
|
||
e.ambient_light_energy = 0.6
|
||
|
||
## Near-black star sky — shown for "live" mode.
|
||
## Subscribes to game.activity pushes to add/remove star nodes.
|
||
func _setup_live_skybox(env: Environment) -> void:
|
||
_clear_stars()
|
||
var proc := ProceduralSkyMaterial.new()
|
||
proc.sky_top_color = Color(0.0, 0.0, 0.02)
|
||
proc.sky_horizon_color = Color(0.01, 0.0, 0.03)
|
||
proc.ground_bottom_color = Color(0.0, 0.0, 0.01)
|
||
proc.ground_horizon_color = Color(0.01, 0.01, 0.02)
|
||
if is_instance_valid(_skybox_sky):
|
||
_skybox_sky.sky_material = proc
|
||
env.ambient_light_energy = 0.25
|
||
|
||
if not Game.game_activity.is_connected(_on_game_activity):
|
||
Game.game_activity.connect(_on_game_activity)
|
||
|
||
Network.request("game.subscribe_activity", {},
|
||
func(_type: String, resp: Variant) -> void:
|
||
var ids : Array = (resp as Dictionary).get("activeSessionIds", [])
|
||
for sid in ids:
|
||
_add_star(str(sid), true),
|
||
func(code: String, msg: String) -> void:
|
||
push_warning("[GameScreen] subscribe_activity failed — %s: %s" % [code, msg]))
|
||
|
||
_start_ambient_star_cycle()
|
||
|
||
func _on_skybox_setting_changed() -> void:
|
||
# Tear down current live subscriptions / stars before switching mode.
|
||
if Game.game_activity.is_connected(_on_game_activity):
|
||
Game.game_activity.disconnect(_on_game_activity)
|
||
_clear_stars()
|
||
if _ambient_star_timer != null and is_instance_valid(_ambient_star_timer):
|
||
_ambient_star_timer.queue_free()
|
||
_ambient_star_timer = null
|
||
if _skybox_timer != null:
|
||
_skybox_timer.queue_free()
|
||
_skybox_timer = null
|
||
_skybox_frames.clear()
|
||
|
||
var env := $WorldEnvironment.environment as Environment
|
||
match Settings.skybox_mode:
|
||
"live":
|
||
_setup_live_skybox(env)
|
||
"cdn":
|
||
_setup_procedural_sky()
|
||
_apply_skybox_from_cache()
|
||
_:
|
||
_setup_procedural_sky()
|
||
|
||
func _on_game_activity(event_type: String, session_id: String) -> void:
|
||
match event_type:
|
||
"started": _add_star(session_id, false)
|
||
"ended": _remove_star(session_id)
|
||
|
||
## Schedules the next ambient star spawn (1-2 per 5 s on average).
|
||
func _start_ambient_star_cycle() -> void:
|
||
if _ambient_star_timer != null and is_instance_valid(_ambient_star_timer):
|
||
_ambient_star_timer.queue_free()
|
||
_ambient_star_timer = Timer.new()
|
||
_ambient_star_timer.wait_time = randf_range(2.5, 5.0)
|
||
_ambient_star_timer.one_shot = true
|
||
add_child(_ambient_star_timer)
|
||
_ambient_star_timer.timeout.connect(_on_ambient_star_timer)
|
||
_ambient_star_timer.start()
|
||
|
||
## Spawns one ambient star, schedules its removal, then re-arms the cycle.
|
||
func _on_ambient_star_timer() -> void:
|
||
var fake_id := "~ambient~%d" % _ambient_star_ctr
|
||
_ambient_star_ctr += 1
|
||
_add_star(fake_id, false)
|
||
# Each ambient star lives for 15–30 s before it fades out.
|
||
get_tree().create_timer(randf_range(15.0, 30.0)).timeout.connect(
|
||
func() -> void: _remove_star(fake_id))
|
||
_start_ambient_star_cycle()
|
||
|
||
# ── Live-star skybox helpers ───────────────────────────────────────────────────
|
||
|
||
## Returns a deterministic spherical position from a session ID hash.
|
||
func _session_star_pos(session_id: String) -> Vector3:
|
||
var rng := RandomNumberGenerator.new()
|
||
rng.seed = session_id.hash()
|
||
var theta := rng.randf() * TAU
|
||
var phi := rng.randf_range(0.15, 0.85) * PI # avoid poles
|
||
var r := 280.0
|
||
return Vector3(r * sin(phi) * cos(theta), r * cos(phi), r * sin(phi) * sin(theta))
|
||
|
||
## Adds an emissive sphere star for the given session. instant=true skips the fade-in.
|
||
func _add_star(session_id: String, instant: bool) -> void:
|
||
if _stars.has(session_id):
|
||
return
|
||
var mesh := MeshInstance3D.new()
|
||
var sphere := SphereMesh.new()
|
||
sphere.radius = 0.6
|
||
sphere.height = 1.2
|
||
sphere.radial_segments = 6
|
||
sphere.rings = 4
|
||
mesh.mesh = sphere
|
||
var mat := StandardMaterial3D.new()
|
||
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
|
||
mat.emission_enabled = true
|
||
mat.emission = Color(0.85, 0.90, 1.0) # blue-white
|
||
mat.emission_energy_multiplier = 0.0
|
||
mesh.material_override = mat
|
||
mesh.global_position = _session_star_pos(session_id)
|
||
add_child(mesh)
|
||
_stars[session_id] = mesh
|
||
|
||
if instant:
|
||
mat.emission_energy_multiplier = 1.0
|
||
_start_star_twinkle(mesh)
|
||
else:
|
||
var tw := create_tween()
|
||
tw.tween_property(mat, "emission_energy_multiplier", 1.0, 2.0) \
|
||
.set_trans(Tween.TRANS_CUBIC)
|
||
tw.finished.connect(func() -> void: _start_star_twinkle(mesh))
|
||
|
||
## Starts the looping gentle brightness oscillation on a star.
|
||
func _start_star_twinkle(mesh: MeshInstance3D) -> void:
|
||
if not is_instance_valid(mesh):
|
||
return
|
||
var mat := mesh.material_override as StandardMaterial3D
|
||
var rng := RandomNumberGenerator.new()
|
||
rng.seed = hash(mesh.global_position.x)
|
||
var period := rng.randf_range(2.0, 5.5)
|
||
var tw := create_tween().set_loops()
|
||
tw.tween_property(mat, "emission_energy_multiplier", 1.6, period * 0.5) \
|
||
.set_trans(Tween.TRANS_SINE)
|
||
tw.tween_property(mat, "emission_energy_multiplier", 0.6, period * 0.5) \
|
||
.set_trans(Tween.TRANS_SINE)
|
||
|
||
## Removes a star with a bright explosion flash then fade.
|
||
func _remove_star(session_id: String) -> void:
|
||
if not _stars.has(session_id):
|
||
return
|
||
var mesh : MeshInstance3D = _stars[session_id]
|
||
_stars.erase(session_id)
|
||
var mat := mesh.material_override as StandardMaterial3D
|
||
var tw := create_tween()
|
||
tw.tween_property(mat, "emission_energy_multiplier", 12.0, 0.12)
|
||
tw.tween_property(mat, "emission_energy_multiplier", 0.0, 1.8) \
|
||
.set_trans(Tween.TRANS_EXPO)
|
||
tw.finished.connect(mesh.queue_free)
|
||
|
||
## Queue-frees all active star nodes (called on mode switch or scene exit).
|
||
func _clear_stars() -> void:
|
||
for mesh in _stars.values():
|
||
if is_instance_valid(mesh):
|
||
mesh.queue_free()
|
||
_stars.clear()
|
||
|
||
# ── CDN skybox helpers ─────────────────────────────────────────────────────────
|
||
|
||
func _apply_skybox_from_cache() -> void:
|
||
var skybox := ContentCache.get_random_skybox()
|
||
if skybox.is_empty():
|
||
print("[GameScreen] No active skybox — keeping procedural sky.")
|
||
return
|
||
var sky_type := str(skybox.get("type", "Panoramic"))
|
||
print("[GameScreen] Applying skybox type=%s" % sky_type)
|
||
if sky_type == "Cubemap":
|
||
_load_cubemap_skybox(skybox)
|
||
elif bool(skybox.get("isAnimated", false)) or sky_type == "AnimatedPanorama":
|
||
_load_animated_skybox(
|
||
str(skybox.get("cdnPath", "")),
|
||
int(skybox.get("frameCount", 1)),
|
||
float(skybox.get("fps", 24.0)))
|
||
else:
|
||
_load_static_skybox(str(skybox.get("cdnPath", "")))
|
||
|
||
func _load_cubemap_skybox(skybox: Dictionary) -> void:
|
||
# Face order for Godot 4 Cubemap.create_from_images():
|
||
# index 0=+X(Right) 1=-X(Left) 2=+Y(Top) 3=-Y(Bottom) 4=+Z(Front) 5=-Z(Back)
|
||
var urls := [
|
||
str(skybox.get("cubePxUrl", "")),
|
||
str(skybox.get("cubeNxUrl", "")),
|
||
str(skybox.get("cubePyUrl", "")),
|
||
str(skybox.get("cubeNyUrl", "")),
|
||
str(skybox.get("cubePzUrl", "")),
|
||
str(skybox.get("cubeNzUrl", "")),
|
||
]
|
||
var images: Array = []
|
||
images.resize(6)
|
||
# Wrap pending in an Array so closures capture the container (always a reference),
|
||
# avoiding GDScript's unreliable primitive-int capture across async callbacks.
|
||
var pending := [6]
|
||
for i in 6:
|
||
var idx := i
|
||
var url : String = urls[idx]
|
||
if url.is_empty():
|
||
images[idx] = null
|
||
pending[0] -= 1
|
||
if pending[0] == 0:
|
||
_apply_cubemap_images(images)
|
||
continue
|
||
# Download face image directly — avoids ImageTexture.get_image() round-trip
|
||
# which can silently return null in some Godot 4 builds.
|
||
var http := HTTPRequest.new()
|
||
add_child(http)
|
||
http.request_completed.connect(func(_res: int, code: int, _hdrs: PackedStringArray, data: PackedByteArray):
|
||
http.queue_free()
|
||
if code >= 200 and code < 300 and not data.is_empty():
|
||
var img := Image.new()
|
||
var ext := url.split("?")[0].get_extension().to_lower()
|
||
var load_err: Error
|
||
if ext in ["jpg", "jpeg"]:
|
||
load_err = img.load_jpg_from_buffer(data)
|
||
elif ext == "webp":
|
||
load_err = img.load_webp_from_buffer(data)
|
||
else:
|
||
load_err = img.load_png_from_buffer(data)
|
||
if load_err == OK:
|
||
images[idx] = img
|
||
else:
|
||
push_warning("[GameScreen] Cubemap face %d decode failed (ext=%s)" % [idx, ext])
|
||
images[idx] = null
|
||
else:
|
||
push_warning("[GameScreen] Cubemap face %d download failed: HTTP %d" % [idx, code])
|
||
images[idx] = null
|
||
pending[0] -= 1
|
||
if pending[0] == 0:
|
||
_apply_cubemap_images.call_deferred(images))
|
||
http.request(url)
|
||
|
||
func _apply_cubemap_images(raw: Array) -> void:
|
||
# Convert to typed array — create_from_images() requires Array[Image].
|
||
var images: Array[Image] = []
|
||
images.resize(6)
|
||
|
||
# Determine face size from the first valid image.
|
||
var face_size := 1
|
||
for i in 6:
|
||
if raw[i] is Image:
|
||
face_size = (raw[i] as Image).get_width()
|
||
break
|
||
|
||
for i in 6:
|
||
if raw[i] is Image:
|
||
var img := raw[i] as Image
|
||
# All faces must be the same size and format.
|
||
if img.get_width() != face_size or img.get_height() != face_size:
|
||
img.resize(face_size, face_size, Image.INTERPOLATE_LANCZOS)
|
||
img.convert(Image.FORMAT_RGB8)
|
||
images[i] = img
|
||
else:
|
||
# Fill missing face with a solid black image of matching size.
|
||
var placeholder := Image.create(face_size, face_size, false, Image.FORMAT_RGB8)
|
||
placeholder.fill(Color.BLACK)
|
||
images[i] = placeholder
|
||
|
||
var cubemap := Cubemap.new()
|
||
var err := cubemap.create_from_images(images)
|
||
if err != OK:
|
||
push_warning("[GameScreen] Cubemap.create_from_images failed: %d" % err)
|
||
return
|
||
_apply_cubemap_material(cubemap)
|
||
|
||
func _apply_cubemap_material(cubemap: Cubemap) -> void:
|
||
var shader := Shader.new()
|
||
shader.code = """
|
||
shader_type sky;
|
||
uniform samplerCube environment : filter_linear, repeat_disable;
|
||
void sky() { COLOR = texture(environment, EYEDIR).rgb; }
|
||
"""
|
||
var mat := ShaderMaterial.new()
|
||
mat.shader = shader
|
||
mat.set_shader_parameter("environment", cubemap)
|
||
var new_sky := Sky.new()
|
||
new_sky.sky_material = mat
|
||
_skybox_sky = new_sky # keep _skybox_sky in sync so _setup_procedural_sky can clean up
|
||
$WorldEnvironment.environment.sky = new_sky
|
||
$WorldEnvironment.environment.background_mode = Environment.BG_SKY
|
||
print("[GameScreen] Cubemap sky applied.")
|
||
|
||
func _load_static_skybox(url: String) -> void:
|
||
var http := HTTPRequest.new()
|
||
add_child(http)
|
||
http.request_completed.connect(
|
||
func(_result: int, code: int, _headers: PackedStringArray, data: PackedByteArray) -> void:
|
||
http.queue_free()
|
||
if code < 200 or code >= 300 or data.is_empty():
|
||
push_warning("[GameScreen] Failed to download skybox: HTTP %d" % code)
|
||
return
|
||
var img := Image.new()
|
||
# Strip query string before checking extension (CDN URLs may include ?v=… etc.)
|
||
var clean_url := url.split("?")[0]
|
||
var ext := clean_url.get_extension().to_lower()
|
||
var err : int
|
||
if ext in ["jpg", "jpeg"]:
|
||
err = img.load_jpg_from_buffer(data)
|
||
elif ext == "webp":
|
||
err = img.load_webp_from_buffer(data)
|
||
else:
|
||
err = img.load_png_from_buffer(data)
|
||
if err != OK:
|
||
push_warning("[GameScreen] Failed to decode skybox image (ext=%s)" % ext)
|
||
return
|
||
var tex := ImageTexture.create_from_image(img)
|
||
var mat := PanoramaSkyMaterial.new()
|
||
mat.panorama = tex
|
||
if is_instance_valid(_skybox_sky):
|
||
_skybox_sky.sky_material = mat
|
||
print("[GameScreen] CDN skybox applied."))
|
||
http.request(url)
|
||
|
||
func _load_animated_skybox(base_url: String, frame_count: int, fps: float) -> void:
|
||
_skybox_frames.clear()
|
||
_skybox_frame_idx = 0
|
||
var loaded : int = 0
|
||
var frames_arr: Array = []
|
||
frames_arr.resize(frame_count)
|
||
|
||
for i in frame_count:
|
||
var url := "%s/%d.png" % [base_url, i]
|
||
var http := HTTPRequest.new()
|
||
var frame_idx := i
|
||
add_child(http)
|
||
http.request_completed.connect(
|
||
func(_result: int, code: int, _headers: PackedStringArray, data: PackedByteArray) -> void:
|
||
http.queue_free()
|
||
loaded += 1
|
||
if code >= 200 and code < 300 and not data.is_empty():
|
||
var img := Image.new()
|
||
if img.load_png_from_buffer(data) == OK:
|
||
frames_arr[frame_idx] = ImageTexture.create_from_image(img)
|
||
if loaded == frame_count:
|
||
_skybox_frames = frames_arr.filter(func(f: Variant) -> bool: return f != null)
|
||
if not _skybox_frames.is_empty():
|
||
_start_skybox_animation(fps))
|
||
http.request(url)
|
||
|
||
func _start_skybox_animation(fps: float) -> void:
|
||
_apply_skybox_frame(0)
|
||
if _skybox_frames.size() <= 1:
|
||
return
|
||
if _skybox_timer != null:
|
||
_skybox_timer.queue_free()
|
||
_skybox_timer = Timer.new()
|
||
_skybox_timer.wait_time = 1.0 / maxf(fps, 1.0)
|
||
_skybox_timer.autostart = true
|
||
_skybox_timer.timeout.connect(_on_skybox_frame_tick)
|
||
add_child(_skybox_timer)
|
||
|
||
func _apply_skybox_frame(idx: int) -> void:
|
||
if _skybox_frames.is_empty() or not is_instance_valid(_skybox_sky):
|
||
return
|
||
var tex : ImageTexture = _skybox_frames[idx % _skybox_frames.size()]
|
||
if tex == null:
|
||
return
|
||
var mat := _skybox_sky.sky_material
|
||
if not (mat is PanoramaSkyMaterial):
|
||
mat = PanoramaSkyMaterial.new()
|
||
_skybox_sky.sky_material = mat
|
||
(mat as PanoramaSkyMaterial).panorama = tex
|
||
|
||
func _on_skybox_frame_tick() -> void:
|
||
_skybox_frame_idx = (_skybox_frame_idx + 1) % _skybox_frames.size()
|
||
_apply_skybox_frame(_skybox_frame_idx)
|
||
|
||
# ── Camera ────────────────────────────────────────────────────────────────────
|
||
|
||
func _apply_camera() -> void:
|
||
var pitch_rad := deg_to_rad(_cam_pitch)
|
||
_camera_rig.position = _cam_pivot
|
||
_camera_rig.rotation_degrees = Vector3(0.0, _cam_yaw, 0.0)
|
||
_camera.position = Vector3(0.0,
|
||
_cam_distance * sin(pitch_rad),
|
||
_cam_distance * cos(pitch_rad))
|
||
_camera.rotation_degrees = Vector3(-_cam_pitch, 0.0, 0.0)
|
||
|
||
|
||
func _zoom(delta: float) -> void:
|
||
_cam_distance = clampf(_cam_distance - delta, 4.0, 22.0)
|
||
_apply_camera()
|
||
|
||
|
||
func _sync_cam_ctrl_panel() -> void:
|
||
_cam_ctrl_panel.visible = (Settings.touch_camera_mode == "buttons")
|
||
if Settings.touch_camera_mode != "buttons":
|
||
_deactivate_touch_cam_modes()
|
||
|
||
|
||
func _deactivate_touch_cam_modes() -> void:
|
||
_touch_cam_orbit = false
|
||
_touch_cam_pan = false
|
||
_touch_cam_zoom = false
|
||
if is_instance_valid(_cam_orbit_btn): _cam_orbit_btn.set_pressed_no_signal(false)
|
||
if is_instance_valid(_cam_pan_btn): _cam_pan_btn.set_pressed_no_signal(false)
|
||
if is_instance_valid(_cam_zoom_btn): _cam_zoom_btn.set_pressed_no_signal(false)
|
||
|
||
|
||
func _on_cam_orbit_btn_toggled(pressed: bool) -> void:
|
||
_touch_cam_orbit = pressed
|
||
if pressed:
|
||
_touch_cam_pan = false
|
||
_touch_cam_zoom = false
|
||
_cam_pan_btn.set_pressed_no_signal(false)
|
||
_cam_zoom_btn.set_pressed_no_signal(false)
|
||
|
||
|
||
func _on_cam_pan_btn_toggled(pressed: bool) -> void:
|
||
_touch_cam_pan = pressed
|
||
if pressed:
|
||
_touch_cam_orbit = false
|
||
_touch_cam_zoom = false
|
||
_cam_orbit_btn.set_pressed_no_signal(false)
|
||
_cam_zoom_btn.set_pressed_no_signal(false)
|
||
|
||
|
||
func _on_cam_zoom_btn_toggled(pressed: bool) -> void:
|
||
_touch_cam_zoom = pressed
|
||
if pressed:
|
||
_touch_cam_orbit = false
|
||
_touch_cam_pan = false
|
||
_cam_orbit_btn.set_pressed_no_signal(false)
|
||
_cam_pan_btn.set_pressed_no_signal(false)
|
||
|
||
|
||
func _on_cam_gesture_timer_fired() -> void:
|
||
if Settings.touch_camera_mode != "gesture":
|
||
return
|
||
match _gesture_finger_count:
|
||
1:
|
||
_touch_cam_orbit = true
|
||
_touch_cam_pan = false
|
||
_touch_cam_zoom = false
|
||
2:
|
||
_touch_cam_zoom = true
|
||
_touch_cam_orbit = false
|
||
_touch_cam_pan = false
|
||
3:
|
||
_touch_cam_pan = true
|
||
_touch_cam_orbit = false
|
||
_touch_cam_zoom = false
|
||
# The user deliberately held — mark as drag so release won't fire a board click.
|
||
_touch_drag_active = true
|
||
_hold_timer.stop()
|
||
|
||
|
||
# ── Input ─────────────────────────────────────────────────────────────────────
|
||
|
||
func _unhandled_input(event: InputEvent) -> void:
|
||
if event is InputEventMouseButton:
|
||
var mb := event as InputEventMouseButton
|
||
if mb.button_index == MOUSE_BUTTON_WHEEL_UP:
|
||
if _hand_area.get_global_rect().has_point(mb.position): return
|
||
_zoom(1.5); return
|
||
elif mb.button_index == MOUSE_BUTTON_WHEEL_DOWN:
|
||
if _hand_area.get_global_rect().has_point(mb.position): return
|
||
_zoom(-1.5); return
|
||
elif mb.button_index == MOUSE_BUTTON_MIDDLE:
|
||
_pan_active = mb.pressed
|
||
_last_mouse = mb.position
|
||
elif mb.button_index == MOUSE_BUTTON_RIGHT:
|
||
_orbit_active = mb.pressed
|
||
_last_mouse = mb.position
|
||
elif mb.button_index == MOUSE_BUTTON_LEFT:
|
||
if mb.pressed:
|
||
# Double-click on a battlefield unit → show full card detail popup.
|
||
if mb.double_click:
|
||
var dbl_unit_id := _mouse_to_unit_id(mb.position)
|
||
if not dbl_unit_id.is_empty():
|
||
_show_unit_detail_popup(dbl_unit_id)
|
||
return
|
||
_last_mouse = mb.position
|
||
_drag_active = false
|
||
_press_was_on_board = true # unhandled press = board area, not a UI card
|
||
var coord := _mouse_to_tile_coord(mb.position)
|
||
if coord.x >= 0:
|
||
_held_coord = coord
|
||
_hold_timer.start()
|
||
else:
|
||
_held_coord = Vector2i(-1, -1)
|
||
else:
|
||
_hold_timer.stop()
|
||
if not _drag_active and not _touch_drag_active and _press_was_on_board:
|
||
_handle_board_click(mb.position)
|
||
_drag_active = false
|
||
_touch_drag_active = false
|
||
_touch_drag_total = 0.0
|
||
_press_was_on_board = false
|
||
|
||
elif event is InputEventMouseMotion:
|
||
var mm := event as InputEventMouseMotion
|
||
var delta := mm.position - _last_mouse
|
||
_last_mouse = mm.position
|
||
# On some mobile browsers, pinch emits synthetic mouse-motion/left-drag
|
||
# alongside touch/gesture events. Ignore mouse-orbit while touch is active
|
||
# Right-mouse drag orbits camera on desktop; left-click is reserved for board actions.
|
||
if _orbit_active and _touch_points.is_empty() and not _was_multi_touch:
|
||
_cam_yaw -= delta.x * 0.4
|
||
_cam_pitch = clampf(_cam_pitch + delta.y * 0.3, 15.0, 75.0)
|
||
_apply_camera()
|
||
# Always update cursor/hover on mouse move (even while drag — hides during drag).
|
||
_update_hover(mm.position)
|
||
if _pan_active:
|
||
var ps := _cam_distance * 0.0015
|
||
var right := _camera_rig.global_basis.x * delta.x * ps
|
||
var fwd := Vector3(_camera_rig.global_basis.z.x, 0,
|
||
_camera_rig.global_basis.z.z).normalized()
|
||
_cam_pivot += right + fwd * -delta.y * ps
|
||
var pan_lim := clampf(max(Game.board_width(), Game.board_height()) * TILE_SPACING * 0.5, 6.0, 20.0)
|
||
_cam_pivot.x = clampf(_cam_pivot.x, -pan_lim, pan_lim)
|
||
_cam_pivot.z = clampf(_cam_pivot.z, -pan_lim, pan_lim)
|
||
_apply_camera()
|
||
|
||
elif event is InputEventScreenTouch:
|
||
var st := event as InputEventScreenTouch
|
||
if st.pressed:
|
||
_touch_points[st.index] = st.position
|
||
if _touch_points.size() == 1:
|
||
# Single-touch start: arm tap + hold (touch right-click) behavior.
|
||
_touch_drag_active = false
|
||
_touch_drag_total = 0.0
|
||
_touch_start_pos = st.position
|
||
_press_was_on_board = true
|
||
_last_mouse = st.position
|
||
var touch_coord := _mouse_to_tile_coord(st.position)
|
||
if touch_coord.x >= 0:
|
||
_held_coord = touch_coord
|
||
_hold_timer.start()
|
||
else:
|
||
_held_coord = Vector2i(-1, -1)
|
||
elif _touch_points.size() >= 2:
|
||
_pinch_dist = _touch_pair_dist()
|
||
_last_mouse = _touch_pair_mid()
|
||
_was_multi_touch = true
|
||
_held_coord = Vector2i(-1, -1)
|
||
_hold_timer.stop()
|
||
# Gesture mode: (re)start timer whenever finger count changes.
|
||
if Settings.touch_camera_mode == "gesture":
|
||
_gesture_finger_count = _touch_points.size()
|
||
_gesture_move_accum = 0.0
|
||
_cam_gesture_timer.start()
|
||
else:
|
||
var released_pos := st.position
|
||
var had_single_touch := (_touch_points.size() == 1 and _touch_points.has(st.index))
|
||
_touch_points.erase(st.index)
|
||
if had_single_touch and not _was_multi_touch and _press_was_on_board:
|
||
# Use start-to-end distance, not cumulative, to detect taps.
|
||
# Cumulative distance mis-classifies natural finger jitter (A→B→A) as a drag.
|
||
var tap_dist := released_pos.distance_to(_touch_start_pos)
|
||
if tap_dist < 50.0 and not _touch_drag_active:
|
||
_hold_timer.stop()
|
||
_handle_board_click(released_pos)
|
||
if _touch_points.is_empty():
|
||
_was_multi_touch = false
|
||
_touch_drag_active = false
|
||
_touch_drag_total = 0.0
|
||
_touch_start_pos = Vector2.ZERO
|
||
_press_was_on_board = false
|
||
_held_coord = Vector2i(-1, -1)
|
||
_hold_timer.stop()
|
||
_cam_gesture_timer.stop()
|
||
# Gesture mode: deactivate camera mode when all fingers lift.
|
||
if Settings.touch_camera_mode == "gesture":
|
||
_deactivate_touch_cam_modes()
|
||
_gesture_move_accum = 0.0
|
||
_gesture_finger_count = 0
|
||
|
||
elif event is InputEventScreenDrag:
|
||
var sd := event as InputEventScreenDrag
|
||
_touch_points[sd.index] = sd.position
|
||
|
||
# Cancel gesture timer if fingers move significantly before the hold activates.
|
||
_gesture_move_accum += sd.relative.length()
|
||
if _gesture_move_accum > 50.0:
|
||
_cam_gesture_timer.stop()
|
||
|
||
if _touch_points.size() == 1 and not _was_multi_touch:
|
||
_touch_drag_total += sd.relative.length()
|
||
if _touch_drag_total > 36.0:
|
||
_hold_timer.stop()
|
||
# Only suppress the tap click when a camera action will actually happen.
|
||
# Without this, a normal swipe with no camera mode active silently eats the touch.
|
||
if _touch_cam_orbit or _touch_cam_pan or _touch_cam_zoom:
|
||
_touch_drag_active = true
|
||
if _touch_drag_active:
|
||
if _touch_cam_orbit:
|
||
_cam_yaw -= sd.relative.x * 0.4
|
||
_cam_pitch = clampf(_cam_pitch + sd.relative.y * 0.3, 15.0, 75.0)
|
||
_apply_camera()
|
||
elif _touch_cam_pan:
|
||
var ps_p := _cam_distance * 0.002
|
||
var right_p := _camera_rig.global_basis.x * -sd.relative.x * ps_p
|
||
var fwd_p := Vector3(_camera_rig.global_basis.z.x, 0,
|
||
_camera_rig.global_basis.z.z).normalized()
|
||
_cam_pivot += right_p + fwd_p * sd.relative.y * ps_p
|
||
var pan_lim_p := clampf(max(Game.board_width(), Game.board_height()) * TILE_SPACING * 0.5, 6.0, 20.0)
|
||
_cam_pivot.x = clampf(_cam_pivot.x, -pan_lim_p, pan_lim_p)
|
||
_cam_pivot.z = clampf(_cam_pivot.z, -pan_lim_p, pan_lim_p)
|
||
_apply_camera()
|
||
elif _touch_cam_zoom:
|
||
_zoom(sd.relative.y * -0.05)
|
||
elif _touch_points.size() == 3 and _touch_cam_pan:
|
||
# 3-finger pan (gesture mode): only process the leading finger to avoid triple-apply.
|
||
var keys3 := _touch_points.keys()
|
||
keys3.sort()
|
||
if sd.index == keys3[0]:
|
||
var ps3 := _cam_distance * 0.002
|
||
var right3 := _camera_rig.global_basis.x * -sd.relative.x * ps3
|
||
var fwd3 := Vector3(_camera_rig.global_basis.z.x, 0,
|
||
_camera_rig.global_basis.z.z).normalized()
|
||
_cam_pivot += right3 + fwd3 * sd.relative.y * ps3
|
||
var pan_lim3 := clampf(max(Game.board_width(), Game.board_height()) * TILE_SPACING * 0.5, 6.0, 20.0)
|
||
_cam_pivot.x = clampf(_cam_pivot.x, -pan_lim3, pan_lim3)
|
||
_cam_pivot.z = clampf(_cam_pivot.z, -pan_lim3, pan_lim3)
|
||
_apply_camera()
|
||
elif _touch_points.size() >= 2:
|
||
var keys := _touch_points.keys()
|
||
var pos_a : Vector2 = _touch_points[keys[0]]
|
||
var pos_b : Vector2 = _touch_points[keys[1]]
|
||
var mid := (pos_a + pos_b) * 0.5
|
||
var nd := pos_a.distance_to(pos_b)
|
||
_zoom((nd - _pinch_dist) * 0.03)
|
||
_pinch_dist = nd
|
||
var ps := _cam_distance * 0.002
|
||
var cdelta := mid - _last_mouse
|
||
_last_mouse = mid
|
||
var right := _camera_rig.global_basis.x * -cdelta.x * ps
|
||
var fwd := Vector3(_camera_rig.global_basis.z.x, 0,
|
||
_camera_rig.global_basis.z.z).normalized()
|
||
_cam_pivot += right + fwd * cdelta.y * ps
|
||
var pan_lim2 := clampf(max(Game.board_width(), Game.board_height()) * TILE_SPACING * 0.5, 6.0, 20.0)
|
||
_cam_pivot.x = clampf(_cam_pivot.x, -pan_lim2, pan_lim2)
|
||
_cam_pivot.z = clampf(_cam_pivot.z, -pan_lim2, pan_lim2)
|
||
_apply_camera()
|
||
|
||
|
||
# ── Browser high-level gesture events (Chromium / WebKit) ──────────────────
|
||
# Browsers sometimes emit these *instead of* dual ScreenDrag events.
|
||
# factor > 1.0 = spreading (zoom in), < 1.0 = pinching (zoom out).
|
||
elif event is InputEventMagnifyGesture:
|
||
var mg := event as InputEventMagnifyGesture
|
||
_zoom((mg.factor - 1.0) * 8.0)
|
||
|
||
elif event is InputEventPanGesture:
|
||
# On touch devices, treat pan-gesture as two-finger pan only.
|
||
# Some browsers emit PanGesture during single-finger movement;
|
||
# ignore that so single-finger remains orbit.
|
||
if _touch_points.size() == 1 and not _was_multi_touch:
|
||
return
|
||
var pg := event as InputEventPanGesture
|
||
var ps := _cam_distance * 0.004
|
||
var right := _camera_rig.global_basis.x * -pg.delta.x * ps
|
||
var fwd := Vector3(_camera_rig.global_basis.z.x, 0,
|
||
_camera_rig.global_basis.z.z).normalized()
|
||
_cam_pivot += right + fwd * pg.delta.y * ps
|
||
var pan_lim3 := clampf(max(Game.board_width(), Game.board_height()) * TILE_SPACING * 0.5, 6.0, 20.0)
|
||
_cam_pivot.x = clampf(_cam_pivot.x, -pan_lim3, pan_lim3)
|
||
_cam_pivot.z = clampf(_cam_pivot.z, -pan_lim3, pan_lim3)
|
||
_apply_camera()
|
||
|
||
|
||
func _touch_pair_dist() -> float:
|
||
var keys := _touch_points.keys()
|
||
if keys.size() < 2: return 0.0
|
||
return (_touch_points[keys[0]] as Vector2).distance_to(_touch_points[keys[1]])
|
||
|
||
|
||
func _touch_pair_mid() -> Vector2:
|
||
var keys := _touch_points.keys()
|
||
if keys.size() < 2: return Vector2.ZERO
|
||
return ((_touch_points[keys[0]] as Vector2) + (_touch_points[keys[1]] as Vector2)) * 0.5
|
||
|
||
# ── Coord helpers ─────────────────────────────────────────────────────────────
|
||
|
||
## Grid spacing: 1.0 tile + 0.1 gap between tiles (visual only).
|
||
const TILE_SPACING := 1.1
|
||
|
||
func _coord_to_world(x: int, y: int) -> Vector3:
|
||
return Vector3(
|
||
x * TILE_SPACING - (Game.board_width() - 1) * TILE_SPACING * 0.5, 0.0,
|
||
y * TILE_SPACING - (Game.board_height() - 1) * TILE_SPACING * 0.5)
|
||
|
||
|
||
func _mouse_to_tile_coord(mouse_pos: Vector2) -> Vector2i:
|
||
var body := _raycast_body(mouse_pos)
|
||
if body == null: return Vector2i(-1, -1)
|
||
if body.has_meta("tile_coord"):
|
||
return body.get_meta("tile_coord") as Vector2i
|
||
return Vector2i(-1, -1)
|
||
|
||
|
||
func _mouse_to_unit_id(mouse_pos: Vector2) -> String:
|
||
var body := _raycast_body(mouse_pos)
|
||
if body == null: return ""
|
||
if body.has_meta("unit_id"):
|
||
return str(body.get_meta("unit_id"))
|
||
return ""
|
||
|
||
|
||
func _raycast_body(mouse_pos: Vector2) -> PhysicsBody3D:
|
||
var space := get_world_3d().direct_space_state
|
||
var from := _camera.project_ray_origin(mouse_pos)
|
||
var to := from + _camera.project_ray_normal(mouse_pos) * 100.0
|
||
var query := PhysicsRayQueryParameters3D.create(from, to)
|
||
var result := space.intersect_ray(query)
|
||
if result.is_empty(): return null
|
||
return result.get("collider") as PhysicsBody3D
|
||
|
||
# ── Ownership helpers ─────────────────────────────────────────────────────────
|
||
|
||
func _is_enemy_unit(instance_id: String) -> bool:
|
||
return _enemy_unit_ids.has(instance_id)
|
||
|
||
|
||
func _is_friendly_unit(instance_id: String) -> bool:
|
||
return _friendly_unit_ids.has(instance_id)
|
||
|
||
|
||
func _safe_arch(player: Dictionary) -> Dictionary:
|
||
var arch = player.get("archSpirit")
|
||
return arch as Dictionary if arch is Dictionary else {}
|
||
|
||
|
||
func _rebuild_ownership(state: Dictionary) -> void:
|
||
_enemy_unit_ids.clear()
|
||
_friendly_unit_ids.clear()
|
||
var my_id := Auth.user_id
|
||
for p: Dictionary in state.get("players", []):
|
||
var is_mine : bool = str(p.get("accountId", "")).to_lower() == my_id.to_lower()
|
||
var target : Dictionary = _enemy_unit_ids if not is_mine else _friendly_unit_ids
|
||
for u: Dictionary in p.get("field", []):
|
||
var iid : String = u.get("instanceId", "")
|
||
if not iid.is_empty(): target[iid] = true
|
||
var arch : Dictionary = _safe_arch(p)
|
||
var aid : String = arch.get("instanceId", "")
|
||
if not aid.is_empty(): target[aid] = true
|
||
|
||
# ── Board building ────────────────────────────────────────────────────────────
|
||
|
||
func _build_board(board: Dictionary) -> void:
|
||
for c in _tiles_root.get_children(): c.queue_free()
|
||
for c in _units_root.get_children(): c.queue_free()
|
||
for c : Node in _hi_root.get_children():
|
||
if c != _cursor_highlight and c != _hover_team_overlay:
|
||
c.queue_free()
|
||
_tile_bodies.clear()
|
||
_unit_meshes.clear()
|
||
_unit_bodies.clear()
|
||
_tile_heights.clear()
|
||
_tile_y_bases.clear()
|
||
_tile_visual_tops.clear()
|
||
for tile: Dictionary in board.get("tiles", []):
|
||
var coord : Dictionary = tile.get("coord", {})
|
||
_add_tile(coord.get("x", 0), coord.get("y", 0),
|
||
tile.get("resolvedAffinity", "Void"))
|
||
|
||
|
||
func _add_tile(x: int, y: int, affinity: String) -> void:
|
||
var wp := _coord_to_world(x, y)
|
||
|
||
# Every tile gets a seeded RNG for deterministic variety.
|
||
# First roll: height (0.8-1.0 for model tiles, fixed 0.5 for placeholders).
|
||
# Second roll: vertical stagger (±0.15) so the board isn't completely flat.
|
||
var has_model : bool = not ContentCache.get_tile_model_url(affinity, "Square").is_empty()
|
||
var rng := RandomNumberGenerator.new()
|
||
rng.seed = hash("%d_%d" % [x, y])
|
||
var h : float = rng.randf_range(0.8, 1.0) if has_model else 0.5
|
||
var y_base : float = rng.randf_range(-0.15, 0.15)
|
||
_tile_heights["%d,%d" % [x, y]] = h
|
||
_tile_y_bases["%d,%d" % [x, y]] = y_base
|
||
_tile_visual_tops["%d,%d" % [x, y]] = y_base + h # default = collision-box top; updated after 3D model loads
|
||
|
||
var body := StaticBody3D.new()
|
||
body.position = wp + Vector3(0, y_base + h * 0.5, 0)
|
||
body.set_meta("tile_coord", Vector2i(x, y))
|
||
body.set_meta("tile_height", h) # used by bottom-model loader
|
||
|
||
var shape := CollisionShape3D.new()
|
||
var box := BoxShape3D.new()
|
||
box.size = Vector3(0.98, h, 0.98)
|
||
shape.shape = box
|
||
body.add_child(shape)
|
||
|
||
# Placeholder: affinity-coloured flat box, swapped out if a 3D model loads.
|
||
var mi := MeshInstance3D.new()
|
||
var bm := BoxMesh.new()
|
||
bm.size = Vector3(0.98, h, 0.98)
|
||
mi.mesh = bm
|
||
var mat := StandardMaterial3D.new()
|
||
mat.albedo_color = AFFINITY_COLORS.get(affinity, Color(0.2, 0.2, 0.2))
|
||
mat.roughness = 0.85
|
||
mi.material_override = mat
|
||
body.add_child(mi)
|
||
|
||
_tiles_root.add_child(body)
|
||
_tile_bodies["%d,%d" % [x, y]] = body
|
||
|
||
# ── Try to load a 3D tile model for this affinity ──────────────────────
|
||
_try_load_tile_model(body, affinity)
|
||
|
||
|
||
## Load (or replace) the 3D model on a tile body for the given affinity.
|
||
## Also attaches a random stalagmite bottom model below the tile when available.
|
||
## Safe to call any time affinity changes — replaces existing mesh if present.
|
||
## PureVoid tiles never receive a stalagmite bottom model.
|
||
func _try_load_tile_model(body: StaticBody3D, affinity: String) -> void:
|
||
var want_bottom : bool = affinity != "PureVoid"
|
||
var model_url := ContentCache.get_tile_model_url(affinity, "Square")
|
||
if model_url.is_empty():
|
||
# No 3D model — apply a 2D texture to the placeholder box and attach
|
||
# a stalagmite bottom so undecorated tiles still look coherent.
|
||
var tex_url := ContentCache.get_tile_texture_url(affinity, "Square")
|
||
if not tex_url.is_empty():
|
||
_apply_tile_texture(body, tex_url)
|
||
if want_bottom:
|
||
var bottom_url := ContentCache.get_random_tile_bottom_url()
|
||
if not bottom_url.is_empty():
|
||
_try_load_tile_bottom(weakref(body), bottom_url)
|
||
return
|
||
|
||
var body_ref : Variant = weakref(body)
|
||
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
|
||
var b := body_ref.get_ref() as StaticBody3D
|
||
if not is_instance_valid(b):
|
||
if model_node != null:
|
||
model_node.queue_free()
|
||
return
|
||
if model_node == null:
|
||
return
|
||
|
||
# Remove any existing mesh (placeholder or previously loaded model),
|
||
# but leave the CollisionShape3D so click detection still works.
|
||
for child in b.get_children():
|
||
if not (child is CollisionShape3D):
|
||
child.queue_free()
|
||
|
||
b.add_child(model_node)
|
||
# Scale so the XZ footprint fits the 0.98-unit tile square.
|
||
_fit_model_to_tile(model_node, 0.98)
|
||
# Update the visual-top cache so highlights land just above the model surface,
|
||
# not the collision box top (the two can differ when model height ≠ box height).
|
||
var _tc : Vector2i = b.get_meta("tile_coord", Vector2i(-1, -1))
|
||
if _tc.x >= 0:
|
||
var _ma := _model_local_aabb(model_node)
|
||
if _ma.size != Vector3.ZERO:
|
||
_tile_visual_tops["%d,%d" % [_tc.x, _tc.y]] = \
|
||
b.position.y + _ma.size.y * model_node.scale.y
|
||
|
||
# Attach a random stalagmite bottom model below the tile (if any are configured).
|
||
# PureVoid tiles are skipped — they float in empty space with no decoration below.
|
||
if want_bottom:
|
||
var bottom_url : String = ContentCache.get_random_tile_bottom_url()
|
||
if not bottom_url.is_empty():
|
||
_try_load_tile_bottom(body_ref, bottom_url)
|
||
)
|
||
|
||
|
||
## Loads a stalagmite bottom model and attaches it below the tile body.
|
||
func _try_load_tile_bottom(body_ref: Variant, url: String) -> void:
|
||
ModelCache.load_model(url, func(bottom_node: Node3D) -> void:
|
||
var b := body_ref.get_ref() as StaticBody3D
|
||
if not is_instance_valid(b):
|
||
if bottom_node != null:
|
||
bottom_node.queue_free()
|
||
return
|
||
if bottom_node == null:
|
||
return
|
||
# IMPORTANT: add_child BEFORE _fit_model_to_tile / _model_local_aabb.
|
||
# MeshInstance3D.get_aabb() returns a zero AABB until the node is in the
|
||
# scene tree, so both functions must run after the node is parented.
|
||
var tile_h : float = float(b.get_meta("tile_height", 1.0))
|
||
b.add_child(bottom_node)
|
||
|
||
# Scale to fit the tile footprint. Now that the node is in the tree,
|
||
# the internal _model_local_aabb call returns a valid AABB.
|
||
_fit_model_to_tile(bottom_node, 0.98)
|
||
|
||
# After _fit_model_to_tile: the model's AABB bottom (spike tip) is at
|
||
# body-local Y=0 and the AABB top (wide base) is at body-local Y = scaled_h.
|
||
# The affinity model's visual base sits at body-local Y=0 (tile centre,
|
||
# world Y = tile_h/2), so we want the stalagmite base there too.
|
||
# Shift down by exactly scaled_h to bring the AABB top to body-local Y=0.
|
||
var btm_aabb := _model_local_aabb(bottom_node)
|
||
if btm_aabb.size != Vector3.ZERO:
|
||
var scaled_h := bottom_node.scale.y * btm_aabb.size.y
|
||
bottom_node.position.y -= scaled_h
|
||
)
|
||
|
||
|
||
## Downloads a CDN image and applies it as the albedo texture on the
|
||
## placeholder BoxMesh of a tile body (used when no 3D model is assigned).
|
||
func _apply_tile_texture(body: StaticBody3D, tex_url: String) -> void:
|
||
var mi : MeshInstance3D = null
|
||
for child in body.get_children():
|
||
if child is MeshInstance3D:
|
||
mi = child as MeshInstance3D
|
||
break
|
||
if mi == null or tex_url.is_empty():
|
||
return
|
||
var requester := HTTPRequest.new()
|
||
add_child(requester)
|
||
requester.request_completed.connect(
|
||
func(_result: int, code: int, _headers: PackedStringArray, data: PackedByteArray) -> void:
|
||
requester.queue_free()
|
||
if code < 200 or code >= 300 or not is_instance_valid(mi):
|
||
return
|
||
var img := Image.new()
|
||
var ext := tex_url.get_extension().to_lower()
|
||
var err : int
|
||
if ext in ["jpg", "jpeg"]:
|
||
err = img.load_jpg_from_buffer(data)
|
||
elif ext == "webp":
|
||
err = img.load_webp_from_buffer(data)
|
||
else:
|
||
err = img.load_png_from_buffer(data)
|
||
if err != OK:
|
||
return
|
||
var tex := ImageTexture.create_from_image(img)
|
||
var mat := mi.material_override as StandardMaterial3D
|
||
if mat == null:
|
||
mat = StandardMaterial3D.new()
|
||
mat.roughness = 0.85
|
||
mi.material_override = mat
|
||
mat.albedo_texture = tex
|
||
)
|
||
requester.request(tex_url)
|
||
|
||
|
||
## Scales model so its largest XZ dimension equals `tile_size`, then centres
|
||
## it on XZ and seats the bottom at y = 0 in the parent body's local space.
|
||
func _fit_model_to_tile(model: Node3D, tile_size: float) -> void:
|
||
var aabb := _model_local_aabb(model)
|
||
if aabb.size == Vector3.ZERO:
|
||
return
|
||
var footprint :float = max(aabb.size.x, aabb.size.z)
|
||
if footprint <= 0.0:
|
||
return
|
||
var s := tile_size / footprint
|
||
model.scale = Vector3.ONE * s
|
||
var c := aabb.get_center()
|
||
model.position = Vector3(-c.x * s, -aabb.position.y * s, -c.z * s)
|
||
|
||
|
||
## Returns the combined AABB of all VisualInstance3D descendants expressed
|
||
## in the root node's own local coordinate space (before root.scale/position).
|
||
func _model_local_aabb(root: Node3D) -> AABB:
|
||
var result := AABB()
|
||
var first := true
|
||
# Each entry: { n: Node3D, x: Transform3D } where x transforms from
|
||
# that node's local space to root's local space.
|
||
var stack : Array = [{ "n": root, "x": Transform3D.IDENTITY }]
|
||
while not stack.is_empty():
|
||
var e : Dictionary = stack.pop_back()
|
||
var node : Node3D = e["n"]
|
||
var xform : Transform3D = e["x"]
|
||
if node is VisualInstance3D:
|
||
var local_aabb := xform * (node as VisualInstance3D).get_aabb()
|
||
result = local_aabb if first else result.merge(local_aabb)
|
||
first = false
|
||
for child in node.get_children():
|
||
if child is Node3D:
|
||
stack.push_back({ "n": child, "x": xform * (child as Node3D).transform })
|
||
return result
|
||
|
||
|
||
func _update_tile_affinity(x: int, y: int, affinity: String) -> void:
|
||
var body := _tile_bodies.get("%d,%d" % [x, y]) as StaticBody3D
|
||
if body == null: return
|
||
|
||
# Update the placeholder colour in case there is no model for this affinity.
|
||
for child in body.get_children():
|
||
if child is MeshInstance3D:
|
||
var mat := child.material_override as StandardMaterial3D
|
||
if mat: mat.albedo_color = AFFINITY_COLORS.get(affinity, Color(0.2, 0.2, 0.2))
|
||
|
||
# Attempt to swap in a real 3D model.
|
||
_try_load_tile_model(body, affinity)
|
||
|
||
# ── Unit meshes ───────────────────────────────────────────────────────────────
|
||
|
||
func _rebuild_units(state: Dictionary) -> void:
|
||
# Kill any in-flight movement tweens.
|
||
for iid : String in _move_anims:
|
||
var t := _move_anims[iid] as Tween
|
||
if t != null: t.kill()
|
||
_move_anims.clear()
|
||
|
||
# ── Incremental rebuild: only remove/add; never recreate unchanged units ──
|
||
# Recreating a unit body interrupts its running animation (idle/move/attack),
|
||
# causing a one-frame bind-pose flash on every state echo.
|
||
|
||
# 1. Collect the desired unit set from the new state.
|
||
var my_id := Auth.user_id
|
||
var desired : Dictionary = {} # iid → {unit, color, is_enemy}
|
||
for player: Dictionary in state.get("players", []):
|
||
var is_mine : bool = str(player.get("accountId", "")).to_lower() == my_id.to_lower()
|
||
var color : Color = Color(0.3, 0.5, 1.0) if is_mine else Color(1.0, 0.35, 0.35)
|
||
var arch : Dictionary = _safe_arch(player)
|
||
for unit: Dictionary in ([arch] + player.get("field", [])):
|
||
if unit.is_empty() or unit.get("position") == null: continue
|
||
var iid : String = str(unit.get("instanceId", ""))
|
||
if iid.is_empty(): continue
|
||
desired[iid] = {"unit": unit, "color": color, "is_enemy": not is_mine}
|
||
|
||
# 2. Remove units that are no longer on the board.
|
||
var to_remove : Array[String] = []
|
||
for iid : String in _unit_bodies:
|
||
if not desired.has(iid):
|
||
to_remove.append(iid)
|
||
for iid : String in to_remove:
|
||
var body := _unit_bodies[iid] as StaticBody3D
|
||
if is_instance_valid(body):
|
||
body.queue_free()
|
||
_unit_bodies.erase(iid)
|
||
_unit_meshes.erase(iid)
|
||
_anim_players.erase(iid)
|
||
_unit_def_ids.erase(iid)
|
||
_idle_entry_done.erase(iid)
|
||
_idle_callbacks.erase(iid)
|
||
_oneshot_callbacks.erase(iid)
|
||
_model_base_angles.erase(iid)
|
||
_needs_face_rot.erase(iid)
|
||
_unit_model_retries.erase(iid)
|
||
|
||
# 3. Add units not yet present (newly played, or first render after connect).
|
||
for iid : String in desired:
|
||
if not _unit_bodies.has(iid):
|
||
var d := desired[iid] as Dictionary
|
||
_add_unit_mesh(d["unit"] as Dictionary, d["color"] as Color, d["is_enemy"] as bool)
|
||
|
||
|
||
func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false) -> void:
|
||
var pd : Dictionary = unit.get("position", {})
|
||
if pd.is_empty(): return
|
||
var px : int = pd.get("x", 0)
|
||
var py : int = pd.get("y", 0)
|
||
var wp := _coord_to_world(px, py)
|
||
var tile_h : float = _tile_heights.get("%d,%d" % [px, py], 1.0)
|
||
var tile_base : float = _tile_y_bases.get("%d,%d" % [px, py], 0.0)
|
||
var card_type : String = unit.get("cardType", "Spirit")
|
||
var iid : String = unit.get("instanceId", "")
|
||
var exhausted : bool = unit.get("isExhausted", false)
|
||
|
||
var body := StaticBody3D.new()
|
||
body.set_meta("unit_id", iid)
|
||
|
||
var shape := CollisionShape3D.new()
|
||
var mi := MeshInstance3D.new()
|
||
var mat := StandardMaterial3D.new()
|
||
mat.roughness = 0.65
|
||
|
||
var above_tile : float # how far above the tile top the body centre sits
|
||
match card_type:
|
||
"ArchSpirit":
|
||
var cyl := CylinderMesh.new()
|
||
cyl.top_radius = 0.22; cyl.bottom_radius = 0.22; cyl.height = 0.8
|
||
mi.mesh = cyl
|
||
mat.albedo_color = team_color.lightened(0.25)
|
||
mat.emission_enabled = true
|
||
mat.emission = team_color * 0.4
|
||
var cs := CylinderShape3D.new()
|
||
cs.radius = 0.22; cs.height = 0.8
|
||
shape.shape = cs
|
||
above_tile = 0.4
|
||
"Ruin":
|
||
var bm := BoxMesh.new()
|
||
bm.size = Vector3(0.25, 1.0, 0.25)
|
||
mi.mesh = bm
|
||
mat.albedo_color = Color(0.35, 0.32, 0.30)
|
||
var bs := BoxShape3D.new()
|
||
bs.size = Vector3(0.25, 1.0, 0.25)
|
||
shape.shape = bs
|
||
above_tile = 0.5
|
||
_:
|
||
var sm := SphereMesh.new()
|
||
sm.radius = 0.28; sm.height = 0.28
|
||
mi.mesh = sm
|
||
mat.albedo_color = team_color
|
||
var ss := SphereShape3D.new()
|
||
ss.radius = 0.28
|
||
shape.shape = ss
|
||
above_tile = 0.28
|
||
|
||
mi.material_override = mat
|
||
if exhausted:
|
||
mat.albedo_color = mat.albedo_color.darkened(0.45)
|
||
|
||
body.add_child(shape)
|
||
body.add_child(mi)
|
||
body.set_meta("above_tile", above_tile)
|
||
body.position = wp + Vector3(0, tile_base + tile_h + above_tile, 0)
|
||
_units_root.add_child(body)
|
||
_unit_meshes[iid] = mi
|
||
_unit_bodies[iid] = body
|
||
|
||
# ── Try to load the real 3D model from the card definition ──────────────
|
||
var def_id : String = str(unit.get("cardDefinitionId", ""))
|
||
if not def_id.is_empty():
|
||
_unit_def_ids[iid] = def_id
|
||
if def_id.is_empty():
|
||
return
|
||
var def := ContentCache.get_definition(def_id)
|
||
var model_asset := _find_model3d_asset(def)
|
||
var model_url := str(model_asset.get("cdnUrl", ""))
|
||
var model_etag := str(model_asset.get("contentETag", ""))
|
||
if model_url.is_empty():
|
||
return
|
||
|
||
# Asset-level config (model-file specific).
|
||
var facing_dir : String = str(model_asset.get("modelFacingDirection", "north"))
|
||
# Card-level config (visual identity of this card, not the shared mesh file).
|
||
var model_scale : float = float(def.get("modelScale", 1.0))
|
||
var tint_str : String = str(def.get("modelTintColor", ""))
|
||
var model_tint : Color = Color.WHITE
|
||
if not tint_str.is_empty() and tint_str != "null":
|
||
model_tint = Color(tint_str)
|
||
|
||
# Team-based facing: P1 units face +Z (toward P2), P2 units face -Z (toward P1).
|
||
# Rotate if: (local is P1 AND friendly) OR (local is P2 AND enemy).
|
||
var needs_face_rotation : bool = _local_is_p1 != is_enemy
|
||
var base_angle : float = _facing_to_base_angle(facing_dir)
|
||
|
||
# Pre-set facing config so _schedule_model_retry can use it even if load fails.
|
||
_model_base_angles[iid] = base_angle
|
||
_needs_face_rot[iid] = needs_face_rotation
|
||
|
||
var body_ref : Variant = weakref(body)
|
||
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
|
||
# Guard: body may have been freed by a state rebuild before load finished.
|
||
var b := body_ref.get_ref() as StaticBody3D
|
||
if not is_instance_valid(b):
|
||
if model_node != null:
|
||
model_node.queue_free()
|
||
return
|
||
if model_node == null:
|
||
# Download failed — schedule a background retry.
|
||
_schedule_model_retry(iid, model_url, 1, model_etag)
|
||
return
|
||
|
||
# Remove the placeholder MeshInstance3D.
|
||
for child in b.get_children():
|
||
if child is MeshInstance3D:
|
||
child.queue_free()
|
||
|
||
# Apply uniform scale if configured.
|
||
if not is_equal_approx(model_scale, 1.0):
|
||
model_node.scale = Vector3.ONE * model_scale
|
||
|
||
# Facing config was already stored above; no need to repeat.
|
||
|
||
# Apply idle/team rotation (facing toward opponent).
|
||
model_node.rotation.y = _idle_rotation(iid)
|
||
|
||
# Apply multiplicative tint to all StandardMaterial3D surfaces.
|
||
_apply_model_tint(model_node, model_tint)
|
||
|
||
# Restore the body to its correct world height. Skip if a move tween
|
||
# is currently driving the body.
|
||
if not _move_anims.has(iid):
|
||
b.position = wp + Vector3(0, tile_base + tile_h + above_tile, 0)
|
||
b.add_child(model_node)
|
||
# Seat the model's AABB bottom (feet) on the tile surface.
|
||
# body-local Y=0 is the tile top; feet target = -above_tile.
|
||
var m_aabb := _model_local_aabb(model_node)
|
||
if m_aabb.size != Vector3.ZERO:
|
||
model_node.position.y = -above_tile - model_node.scale.y * m_aabb.position.y
|
||
_unit_meshes[iid] = model_node
|
||
|
||
# Find and store the AnimationPlayer, then start the Idle loop.
|
||
var ap := _find_animation_player(model_node)
|
||
_anim_players[iid] = ap
|
||
if ap != null:
|
||
_play_unit_anim(iid, "idle", true)
|
||
, model_etag)
|
||
|
||
|
||
## Schedule a retry to (re)download the real GLB model for a unit.
|
||
## attempt is 1-based; retries stop after MAX_RETRIES.
|
||
## Only schedules if no equal-or-later retry is already pending for this unit.
|
||
func _schedule_model_retry(iid: String, model_url: String, attempt: int, etag: String = "") -> void:
|
||
const MAX_RETRIES := 10
|
||
if attempt > MAX_RETRIES:
|
||
return
|
||
# Don't override a retry already queued at this or a higher attempt number.
|
||
if _unit_model_retries.get(iid, 0) >= attempt:
|
||
return
|
||
_unit_model_retries[iid] = attempt
|
||
print("[GameScreen] Model retry %d/%d scheduled for %s in 60s" % [attempt, MAX_RETRIES, iid])
|
||
get_tree().create_timer(60.0).timeout.connect(
|
||
func() -> void: _do_model_retry(iid, model_url, attempt, etag),
|
||
CONNECT_ONE_SHOT)
|
||
|
||
|
||
## Execute one model retry attempt. Evicts the URL so ModelCache re-downloads it.
|
||
## If successful, swaps out the placeholder and starts idle animation.
|
||
## If it fails again, schedules the next attempt.
|
||
func _do_model_retry(iid: String, model_url: String, attempt: int, etag: String = "") -> void:
|
||
# Was this attempt superseded by a later scheduled retry?
|
||
if _unit_model_retries.get(iid, -1) != attempt:
|
||
return
|
||
# Unit may have left the board while we were waiting.
|
||
if not _unit_bodies.has(iid):
|
||
_unit_model_retries.erase(iid)
|
||
return
|
||
print("[GameScreen] Model retry %d — downloading %s" % [attempt, model_url])
|
||
ModelCache.evict(model_url, etag)
|
||
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
|
||
if model_node == null:
|
||
# Still failing — try again later.
|
||
_unit_model_retries.erase(iid)
|
||
_schedule_model_retry(iid, model_url, attempt + 1, etag)
|
||
return
|
||
_unit_model_retries.erase(iid)
|
||
# Use the CURRENT body (may differ from when the retry was first scheduled).
|
||
var body := _unit_bodies.get(iid) as StaticBody3D
|
||
if not is_instance_valid(body):
|
||
model_node.queue_free()
|
||
return
|
||
# Remove placeholder mesh.
|
||
for child in body.get_children():
|
||
if child is MeshInstance3D:
|
||
child.queue_free()
|
||
# Re-read card config in case ContentCache was refreshed since placement.
|
||
var def_id : String = _unit_def_ids.get(iid, "")
|
||
var def := ContentCache.get_definition(def_id)
|
||
var model_scale : float = float(def.get("modelScale", 1.0))
|
||
var tint_str : String = str(def.get("modelTintColor", ""))
|
||
var model_tint : Color = Color.WHITE
|
||
if not tint_str.is_empty() and tint_str != "null":
|
||
model_tint = Color(tint_str)
|
||
if not is_equal_approx(model_scale, 1.0):
|
||
model_node.scale = Vector3.ONE * model_scale
|
||
model_node.rotation.y = _idle_rotation(iid)
|
||
_apply_model_tint(model_node, model_tint)
|
||
var above_tile : float = body.get_meta("above_tile", 0.28)
|
||
body.add_child(model_node)
|
||
var m_aabb := _model_local_aabb(model_node)
|
||
if m_aabb.size != Vector3.ZERO:
|
||
model_node.position.y = -above_tile - model_node.scale.y * m_aabb.position.y
|
||
_unit_meshes[iid] = model_node
|
||
var ap := _find_animation_player(model_node)
|
||
_anim_players[iid] = ap
|
||
if ap != null:
|
||
_play_unit_anim(iid, "idle", true)
|
||
print("[GameScreen] Model retry %d succeeded for %s" % [attempt, iid])
|
||
, etag)
|
||
|
||
|
||
## Returns the first Model3D asset dict for a card definition, or {} if none.
|
||
func _find_model3d_asset(def: Dictionary) -> Dictionary:
|
||
for asset: Variant in def.get("assets", []):
|
||
var d := asset as Dictionary
|
||
if d == null: continue
|
||
if str(d.get("assetType", "")) == "Model3D":
|
||
return d
|
||
return {}
|
||
|
||
|
||
## Apply a multiplicative colour tint to all StandardMaterial3D surfaces in a
|
||
## model subtree. Materials are duplicated per-instance to avoid cross-unit
|
||
## bleed. White (default) is a no-op.
|
||
func _apply_model_tint(model: Node3D, tint: Color) -> void:
|
||
if tint.is_equal_approx(Color.WHITE):
|
||
return
|
||
var stack : Array = [model]
|
||
while not stack.is_empty():
|
||
var n = stack.pop_back()
|
||
if n is MeshInstance3D:
|
||
var mi := n as MeshInstance3D
|
||
if mi.mesh != null:
|
||
for i in mi.mesh.get_surface_count():
|
||
var mat := mi.get_active_material(i)
|
||
if mat is StandardMaterial3D:
|
||
var dup := mat.duplicate() as StandardMaterial3D
|
||
dup.albedo_color = dup.albedo_color * tint
|
||
mi.set_surface_override_material(i, dup)
|
||
for child in n.get_children():
|
||
stack.append(child)
|
||
|
||
|
||
## Recursively find the first AnimationPlayer in a model subtree.
|
||
func _find_animation_player(node: Node) -> AnimationPlayer:
|
||
if node is AnimationPlayer:
|
||
return node as AnimationPlayer
|
||
for child in node.get_children():
|
||
var found := _find_animation_player(child)
|
||
if found != null:
|
||
return found
|
||
return null
|
||
|
||
|
||
## Case-insensitive track name resolver with fallback aliases.
|
||
## Returns the exact track name in the AnimationPlayer, or "" if not found.
|
||
## Handles multiple naming conventions exported from DCC tools:
|
||
## "Idle" — bare name
|
||
## "lib/Idle" — library-prefixed (GLTF named library)
|
||
## "Merlock.Attack" — dot-prefixed model name (e.g. Blender action sets)
|
||
## "Merlock_IDLE" — underscore-prefixed model name
|
||
func _resolve_anim_track(ap: AnimationPlayer, action_lower: String) -> String:
|
||
# Try: canonical action name first, then aliases.
|
||
var to_try : Array[String] = [action_lower]
|
||
for alias: String in ANIM_ALIASES.get(action_lower, []):
|
||
if alias != action_lower:
|
||
to_try.append(alias)
|
||
|
||
for candidate: String in to_try:
|
||
for full_name: String in ap.get_animation_list():
|
||
# Strip library prefix (e.g. "lib/Idle" → "Idle").
|
||
var s := full_name.get_slice("/", full_name.get_slice_count("/") - 1)
|
||
# 1. Direct match after library strip.
|
||
if s.to_lower() == candidate:
|
||
return full_name
|
||
# 2. Dot-prefix stripped (e.g. "Merlock.Attack" → "Attack" → "attack").
|
||
if "." in s:
|
||
if s.get_slice(".", s.get_slice_count(".") - 1).to_lower() == candidate:
|
||
return full_name
|
||
# 3. First-underscore-prefix stripped (e.g. "Merlock_IDLE" → "IDLE" → "idle").
|
||
if "_" in s:
|
||
if s.substr(s.find("_") + 1).to_lower() == candidate:
|
||
return full_name
|
||
return ""
|
||
|
||
|
||
## Convert a model's exported facing direction string to a base angle in radians.
|
||
## The angle represents atan2(dir.x, -dir.z) for the direction the model faces
|
||
## when rotation.y == 0. All animations and movement share this offset.
|
||
## GLB models exported from Blender arrive in Godot facing +Z (south) by default,
|
||
## so "south" / unset / null all map to PI. Explicitly pass "north" for -Z models.
|
||
func _facing_to_base_angle(facing: String) -> float:
|
||
match facing.to_lower():
|
||
"north": return 0.0 # model faces -Z (Godot's natural forward)
|
||
"east": return PI / 2.0
|
||
"west": return -PI / 2.0
|
||
_: return PI # "south" / default / null — model faces +Z (Blender GLB)
|
||
|
||
## Returns the rotation.y (radians) that makes a unit's model face its opponent
|
||
## across the board, given its stored base angle and team-flip flag.
|
||
func _idle_rotation(iid: String) -> float:
|
||
var base : float = float(_model_base_angles.get(iid, 0.0))
|
||
var flip : bool = bool(_needs_face_rot.get(iid, false))
|
||
# flip=true → unit should face +Z (south, toward P2) atan2(0,-1)=π
|
||
# flip=false → unit should face -Z (north, toward P1) atan2(0, 1)=0
|
||
var dir := Vector3(0, 0, 1) if flip else Vector3(0, 0, -1)
|
||
return atan2(dir.x, -dir.z) - base
|
||
|
||
## Play an animation on a unit by action name. Uses card's AnimationTrackName
|
||
## override when set, then falls back to case-insensitive convention matching.
|
||
## Pass loop=true for looping animations (e.g. idle, moving).
|
||
## GLB convention: the first ANIM_TRANSITION_SECS of any animation are
|
||
## "entry frames" that blend from idle into the action. For looping animations
|
||
## those frames are played once on entry, then skipped on every subsequent loop.
|
||
func _play_unit_anim(iid: String, action: String, loop: bool = false) -> void:
|
||
var ap : AnimationPlayer = _anim_players.get(iid, null)
|
||
if ap == null or not is_instance_valid(ap):
|
||
return
|
||
# Resolve via CardAnimationBinding override first.
|
||
var def_id : String = _unit_def_ids.get(iid, "")
|
||
var desired := action
|
||
if not def_id.is_empty():
|
||
var override := ContentCache.get_anim_track(def_id, action)
|
||
if not override.is_empty():
|
||
desired = override
|
||
var track := _resolve_anim_track(ap, desired.to_lower())
|
||
if track.is_empty():
|
||
return
|
||
var anim := ap.get_animation(track)
|
||
if anim == null:
|
||
return
|
||
|
||
# All animations are managed with LOOP_NONE; looping is handled manually
|
||
# so we can seek past the transition frames on subsequent iterations.
|
||
anim.loop_mode = Animation.LOOP_NONE
|
||
|
||
# Disconnect any stale idle loop callback that would restart idle unexpectedly.
|
||
if _idle_callbacks.has(iid):
|
||
var old_cb := _idle_callbacks[iid] as Callable
|
||
if ap.animation_finished.is_connected(old_cb):
|
||
ap.animation_finished.disconnect(old_cb)
|
||
_idle_callbacks.erase(iid)
|
||
|
||
# Don't restart the same animation while it's already playing correctly.
|
||
if ap.current_animation == track and ap.is_playing():
|
||
return
|
||
|
||
# Starting a non-loop animation: reset entry-done so the NEXT idle play
|
||
# uses the transition frames to blend back from the action pose.
|
||
if not loop:
|
||
_idle_entry_done.erase(iid)
|
||
|
||
ap.play(track)
|
||
|
||
if loop:
|
||
# On subsequent loop iterations skip the GLB entry frames.
|
||
if _idle_entry_done.get(iid, false):
|
||
ap.seek(ANIM_TRANSITION_SECS, true)
|
||
else:
|
||
_idle_entry_done[iid] = true
|
||
# Schedule the next loop iteration via animation_finished.
|
||
var cb := func(_n: String) -> void: _play_unit_anim(iid, action, true)
|
||
ap.animation_finished.connect(cb, CONNECT_ONE_SHOT)
|
||
_idle_callbacks[iid] = cb
|
||
else:
|
||
# For one-shot non-death animations: return to idle via animation_finished.
|
||
var action_l := action.to_lower()
|
||
var is_death := action_l == "dying" or action_l == "death" or action_l == "die"
|
||
if not is_death:
|
||
# Disconnect any prior oneshot callback — allows _play_damage_animations to
|
||
# replace "return-to-idle" with "play-damaged-then-idle" on an attacking unit.
|
||
if _oneshot_callbacks.has(iid):
|
||
var old_os := _oneshot_callbacks[iid] as Callable
|
||
if ap.animation_finished.is_connected(old_os):
|
||
ap.animation_finished.disconnect(old_os)
|
||
_oneshot_callbacks.erase(iid)
|
||
var os_cb := func(_n: String) -> void: _play_unit_anim(iid, "idle", true)
|
||
ap.animation_finished.connect(os_cb, CONNECT_ONE_SHOT)
|
||
_oneshot_callbacks[iid] = os_cb
|
||
|
||
|
||
## Returns the SFX CDN URL for a given unit and sound key, or "" if none assigned.
|
||
## [param sfx_key] is the camelCase DTO field name, e.g. "attackSoundUrl".
|
||
func _sfx_for_unit(iid: String, sfx_key: String) -> String:
|
||
var def_id : String = _unit_def_ids.get(iid, "")
|
||
if def_id.is_empty():
|
||
return ""
|
||
var def := ContentCache.get_definition(def_id)
|
||
return str(def.get(sfx_key, ""))
|
||
|
||
|
||
## Returns true if the AnimationPlayer's current track is an "attack" animation.
|
||
func _is_attack_track(full_name: String) -> bool:
|
||
var s := full_name.get_slice("/", full_name.get_slice_count("/") - 1)
|
||
for alias: String in ANIM_ALIASES.get("attack", []):
|
||
if s.to_lower() == alias: return true
|
||
if "." in s and s.get_slice(".", s.get_slice_count(".") - 1).to_lower() == alias: return true
|
||
if "_" in s and s.substr(s.find("_") + 1).to_lower() == alias: return true
|
||
return false
|
||
|
||
|
||
## Replaces the pending animation_finished one-shot callback for [param iid].
|
||
## Disconnects the previous callback (stored in _oneshot_callbacks) and
|
||
## connects [param cb] as a new CONNECT_ONE_SHOT handler.
|
||
func _override_oneshot(iid: String, cb: Callable) -> void:
|
||
var ap : AnimationPlayer = _anim_players.get(iid, null)
|
||
if ap == null or not is_instance_valid(ap):
|
||
return
|
||
if _oneshot_callbacks.has(iid):
|
||
var old_cb := _oneshot_callbacks[iid] as Callable
|
||
if ap.animation_finished.is_connected(old_cb):
|
||
ap.animation_finished.disconnect(old_cb)
|
||
_oneshot_callbacks.erase(iid)
|
||
ap.animation_finished.connect(cb, CONNECT_ONE_SHOT)
|
||
_oneshot_callbacks[iid] = cb
|
||
|
||
|
||
## Counterattack phase 2: defender plays "attack", then triggers attacker "damaged".
|
||
func _play_counter_attack(defender_iid: String, attacker_iid: String) -> void:
|
||
if not _unit_bodies.has(defender_iid): return
|
||
if not is_instance_valid(_unit_bodies.get(defender_iid) as Node): return
|
||
_play_unit_anim(defender_iid, "attack", false)
|
||
SFX.play(_sfx_for_unit(defender_iid, "attackSoundUrl"))
|
||
# After the counter-attack finishes: defender → idle, attacker → damaged.
|
||
_override_oneshot(defender_iid, func(_n: String) -> void:
|
||
_play_unit_anim(defender_iid, "idle", true)
|
||
if _unit_bodies.has(attacker_iid) and \
|
||
is_instance_valid(_unit_bodies.get(attacker_iid) as Node):
|
||
_play_unit_anim(attacker_iid, "damaged", false)
|
||
SFX.play(_sfx_for_unit(attacker_iid, "damagedSoundUrl"))
|
||
)
|
||
|
||
|
||
## Full counterattack chain (starts after [param delay] seconds):
|
||
## delay → defender "damaged" → defender "attack" → attacker "damaged" + defender "idle"
|
||
func _play_counter_chain(defender_iid: String, attacker_iid: String, delay: float) -> void:
|
||
var t := create_tween()
|
||
t.tween_callback(func() -> void:
|
||
if not _unit_bodies.has(defender_iid) or \
|
||
not is_instance_valid(_unit_bodies.get(defender_iid) as Node):
|
||
return
|
||
_play_unit_anim(defender_iid, "damaged", false)
|
||
SFX.play(_sfx_for_unit(defender_iid, "damagedSoundUrl"))
|
||
_override_oneshot(defender_iid, func(_n: String) -> void:
|
||
_play_counter_attack(defender_iid, attacker_iid)
|
||
)
|
||
).set_delay(delay)
|
||
|
||
|
||
## Detect HP decreases and unit deaths vs previous state, and fire animations.
|
||
##
|
||
## Counterattack scenario (attacker AND a second unit both took damage this update):
|
||
## delay(attack_remaining) → defender "damaged" → defender "attack" → attacker "damaged"
|
||
##
|
||
## Simple damage scenario:
|
||
## attacker mid-attack + took damage → queue "damaged" behind its attack
|
||
## other unit, attack in progress → delay "damaged" by attack_remaining
|
||
## no attack in progress → play "damaged" immediately
|
||
##
|
||
## Returns true if any animation was triggered (used to decide rebuild delay).
|
||
func _play_damage_animations(state: Dictionary) -> bool:
|
||
if _prev_unit_hp.is_empty():
|
||
return false
|
||
|
||
# ── Find any currently-playing attack animation ──────────────────────────
|
||
var attacker_iid : String = ""
|
||
var attack_remaining : float = 0.0
|
||
for iid: String in _anim_players:
|
||
var ap2 : AnimationPlayer = _anim_players[iid] as AnimationPlayer
|
||
if ap2 == null or not is_instance_valid(ap2) or not ap2.is_playing(): continue
|
||
if _is_attack_track(ap2.current_animation):
|
||
attacker_iid = iid
|
||
attack_remaining = maxf(0.0,
|
||
ap2.current_animation_length - ap2.current_animation_position)
|
||
break
|
||
|
||
# ── Collect who took damage / died ───────────────────────────────────────
|
||
var damaged_iids : Dictionary = {}
|
||
var seen_iids : Dictionary = {}
|
||
for player: Dictionary in state.get("players", []):
|
||
var _arch_raw = player.get("archSpirit")
|
||
var _arch_list : Array = [] if _arch_raw == null else [_arch_raw]
|
||
for unit: Dictionary in (_arch_list + player.get("field", [])):
|
||
if unit.is_empty(): continue
|
||
var iid := str(unit.get("instanceId", ""))
|
||
var _hp_v = unit.get("currentHealth")
|
||
var new_hp := 0 if _hp_v == null else int(_hp_v)
|
||
var old_hp : int = _prev_unit_hp.get(iid, new_hp)
|
||
seen_iids[iid] = true
|
||
if new_hp < old_hp:
|
||
damaged_iids[iid] = true
|
||
|
||
var dying_iids : Dictionary = {}
|
||
for iid: String in _prev_unit_hp:
|
||
if not seen_iids.has(iid):
|
||
dying_iids[iid] = true
|
||
|
||
# Consume tracked target before any early return so it never bleeds into
|
||
# the next state update (e.g. a fully-blocked hit with 0 HP change).
|
||
var tracked_target : String = _last_attack_target_iid
|
||
_last_attack_target_iid = ""
|
||
|
||
if damaged_iids.is_empty() and dying_iids.is_empty():
|
||
# Fully-blocked attack: attacker is mid-swing but the defender's defense
|
||
# absorbed all damage → no HP change, but play the blocked SFX.
|
||
if attacker_iid != "" and not tracked_target.is_empty() \
|
||
and tracked_target != attacker_iid:
|
||
var blocked_iid := tracked_target
|
||
if attack_remaining > 0.0:
|
||
var tb := create_tween()
|
||
tb.tween_callback(func() -> void:
|
||
SFX.play(_sfx_for_unit(blocked_iid, "blockedSoundUrl"))
|
||
).set_delay(attack_remaining)
|
||
else:
|
||
SFX.play(_sfx_for_unit(blocked_iid, "blockedSoundUrl"))
|
||
return false
|
||
|
||
# ── Detect counterattack: attacker took damage while mid-attack ─────────
|
||
# The defender may have blocked all HP damage (defense stat), so we can't
|
||
# rely on them being in damaged_iids. Use the tracked target from the last
|
||
# send_attack() call as the primary source, and fall back to any other
|
||
# damaged unit if the tracked target isn't available.
|
||
var is_counterattack : bool = false
|
||
var defender_iid : String = ""
|
||
if attacker_iid != "" and damaged_iids.has(attacker_iid):
|
||
# Prefer the unit we explicitly attacked (works even when they took 0 damage).
|
||
if tracked_target != "" and tracked_target != attacker_iid:
|
||
defender_iid = tracked_target
|
||
else:
|
||
# Fallback: any other damaged unit (original behaviour).
|
||
for iid: String in damaged_iids:
|
||
if iid != attacker_iid:
|
||
defender_iid = iid
|
||
break
|
||
is_counterattack = defender_iid != ""
|
||
|
||
# ── Schedule animations ───────────────────────────────────────────────────
|
||
if is_counterattack:
|
||
# Full chain handles the attacker and primary defender.
|
||
_play_counter_chain(defender_iid, attacker_iid, attack_remaining)
|
||
# Any other simultaneously-damaged units get a simple delay (uncommon).
|
||
for iid: String in damaged_iids:
|
||
if iid == attacker_iid or iid == defender_iid:
|
||
continue
|
||
var hit_iid := iid
|
||
var t2 := create_tween()
|
||
t2.tween_callback(func() -> void:
|
||
if _unit_bodies.has(hit_iid) and \
|
||
is_instance_valid(_unit_bodies.get(hit_iid) as Node):
|
||
_play_unit_anim(hit_iid, "damaged")
|
||
SFX.play(_sfx_for_unit(hit_iid, "damagedSoundUrl"))
|
||
).set_delay(attack_remaining)
|
||
else:
|
||
for iid: String in damaged_iids:
|
||
var ap : AnimationPlayer = _anim_players.get(iid, null)
|
||
if ap != null and is_instance_valid(ap) and ap.is_playing() \
|
||
and _is_attack_track(ap.current_animation):
|
||
# This unit is mid-attack and took damage (self-damage or similar).
|
||
# Queue "damaged" to play right after the attack finishes.
|
||
if _oneshot_callbacks.has(iid):
|
||
var old_cb := _oneshot_callbacks[iid] as Callable
|
||
if ap.animation_finished.is_connected(old_cb):
|
||
ap.animation_finished.disconnect(old_cb)
|
||
_oneshot_callbacks.erase(iid)
|
||
var cap_iid := iid
|
||
var dmg_cb := func(_n: String) -> void:
|
||
_play_unit_anim(cap_iid, "damaged", false)
|
||
SFX.play(_sfx_for_unit(cap_iid, "damagedSoundUrl"))
|
||
ap.animation_finished.connect(dmg_cb, CONNECT_ONE_SHOT)
|
||
_oneshot_callbacks[iid] = dmg_cb
|
||
elif attack_remaining > 0.0:
|
||
# Bystander — delay "damaged" until after the attack lands.
|
||
var hit_iid := iid
|
||
var t := create_tween()
|
||
t.tween_callback(func() -> void:
|
||
if _unit_bodies.has(hit_iid) and \
|
||
is_instance_valid(_unit_bodies.get(hit_iid) as Node):
|
||
_play_unit_anim(hit_iid, "damaged")
|
||
SFX.play(_sfx_for_unit(hit_iid, "damagedSoundUrl"))
|
||
).set_delay(attack_remaining)
|
||
else:
|
||
_play_unit_anim(iid, "damaged")
|
||
SFX.play(_sfx_for_unit(iid, "damagedSoundUrl"))
|
||
|
||
for iid: String in dying_iids:
|
||
_play_unit_anim(iid, "dying")
|
||
SFX.play(_sfx_for_unit(iid, "deathSoundUrl"))
|
||
|
||
return true
|
||
|
||
|
||
## Update _prev_unit_hp and _prev_unit_pos from the given state snapshot.
|
||
## Call immediately when a new state arrives so the next state update has
|
||
## correct baselines, independent of when the delayed rebuild fires.
|
||
func _update_prev_state(state: Dictionary) -> void:
|
||
_prev_unit_hp.clear()
|
||
_prev_unit_pos.clear()
|
||
for player: Dictionary in state.get("players", []):
|
||
var arch : Dictionary = _safe_arch(player)
|
||
for unit: Dictionary in ([arch] + player.get("field", [])):
|
||
if unit.is_empty(): continue
|
||
var iid := str(unit.get("instanceId", ""))
|
||
if iid.is_empty(): continue
|
||
_prev_unit_hp[iid] = int(unit.get("currentHealth", 0))
|
||
var pd = unit.get("position")
|
||
if pd is Dictionary and not (pd as Dictionary).is_empty():
|
||
_prev_unit_pos[iid] = Vector2i((pd as Dictionary).get("x", 0),
|
||
(pd as Dictionary).get("y", 0))
|
||
|
||
|
||
## 4-directional BFS on the game grid.
|
||
## blocked: Dictionary[Vector2i → true] of impassable tiles;
|
||
## the destination 'to' is always reachable regardless.
|
||
## Returns the path steps NOT including 'from', including 'to'.
|
||
## Falls back to [to] if no path found (shouldn't happen on a connected grid).
|
||
func _bfs_path(from: Vector2i, to: Vector2i, blocked: Dictionary) -> Array[Vector2i]:
|
||
if from == to:
|
||
return []
|
||
var bw := Game.board_width()
|
||
var bh := Game.board_height()
|
||
var DIRS : Array[Vector2i] = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)]
|
||
var visited : Dictionary = {from: true}
|
||
# Queue entries: [pos: Vector2i, path: Array[Vector2i]]
|
||
var queue : Array = [[from, []]]
|
||
while not queue.is_empty():
|
||
var front = queue.pop_front()
|
||
var cur : Vector2i = front[0]
|
||
var path : Array = front[1] # untyped — stored in a plain Array queue
|
||
for d : Vector2i in DIRS:
|
||
var nxt := cur + d
|
||
if nxt.x < 0 or nxt.x >= bw or nxt.y < 0 or nxt.y >= bh:
|
||
continue
|
||
if not _tile_bodies.has("%d,%d" % [nxt.x, nxt.y]):
|
||
continue
|
||
if visited.has(nxt):
|
||
continue
|
||
if blocked.has(nxt) and nxt != to:
|
||
continue
|
||
visited[nxt] = true
|
||
var new_path : Array = path.duplicate()
|
||
new_path.append(nxt)
|
||
if nxt == to:
|
||
var typed : Array[Vector2i] = []
|
||
typed.assign(new_path)
|
||
return typed
|
||
queue.append([nxt, new_path])
|
||
return [to] # fallback: direct jump
|
||
|
||
|
||
## Animate a single unit moving from from_coord to to_coord along a BFS path.
|
||
## blocked: tiles occupied by other units (their old positions).
|
||
## Returns the total tween duration in seconds.
|
||
func _animate_unit_move(iid: String, from_coord: Vector2i, to_coord: Vector2i,
|
||
blocked: Dictionary) -> float:
|
||
var body := _unit_bodies.get(iid) as StaticBody3D
|
||
if not is_instance_valid(body):
|
||
return 0.0
|
||
var path := _bfs_path(from_coord, to_coord, blocked)
|
||
if path.is_empty():
|
||
return 0.0
|
||
var duration := path.size() * MOVE_STEP_SECS
|
||
# Cancel any existing move tween for this unit.
|
||
if _move_anims.has(iid) and _move_anims[iid] != null:
|
||
(_move_anims[iid] as Tween).kill()
|
||
# Play the looping move animation and its SFX.
|
||
_play_unit_anim(iid, "moving", true)
|
||
SFX.play(_sfx_for_unit(iid, "moveSoundUrl"))
|
||
# Pre-compute per-step facing angles so the closures capture the correct values.
|
||
var base_angle := float(_model_base_angles.get(iid, 0.0))
|
||
var prev_coord := from_coord
|
||
var step_angles : Array[float] = []
|
||
for step : Vector2i in path:
|
||
var step_wp := _coord_to_world(step.x, step.y)
|
||
var prev_wp := _coord_to_world(prev_coord.x, prev_coord.y)
|
||
var dir := step_wp - prev_wp # XZ direction in world space
|
||
step_angles.append(atan2(dir.x, -dir.z) - base_angle)
|
||
prev_coord = step
|
||
# Tween the body through each grid step, rotating the model to face each direction.
|
||
# Use the stored "above_tile" constant so rapid state updates cannot skew the
|
||
# height by back-calculating from a mid-tween body position.
|
||
var unit_above : float = body.get_meta("above_tile", 0.28)
|
||
# Pre-compute per-step Y positions.
|
||
var step_ys : Array[float] = []
|
||
for step : Vector2i in path:
|
||
var key := "%d,%d" % [step.x, step.y]
|
||
step_ys.append(_tile_y_bases.get(key, 0.0) + _tile_heights.get(key, 1.0) + unit_above)
|
||
var tween := create_tween()
|
||
tween.set_ease(Tween.EASE_IN_OUT)
|
||
tween.set_trans(Tween.TRANS_SINE)
|
||
for i in path.size():
|
||
var step : Vector2i = path[i]
|
||
var wp := _coord_to_world(step.x, step.y)
|
||
var facing_angle : float = step_angles[i]
|
||
var step_y : float = step_ys[i]
|
||
# Snap model rotation to face the movement direction before each step.
|
||
tween.tween_callback(func() -> void:
|
||
var m := _unit_meshes.get(iid) as Node3D
|
||
if is_instance_valid(m):
|
||
m.rotation.y = facing_angle)
|
||
tween.tween_property(body, "position", Vector3(wp.x, step_y, wp.z), MOVE_STEP_SECS)
|
||
# Return to idle rotation and idle animation once movement finishes.
|
||
tween.tween_callback(func() -> void:
|
||
_move_anims.erase(iid)
|
||
var m := _unit_meshes.get(iid) as Node3D
|
||
if is_instance_valid(m):
|
||
m.rotation.y = _idle_rotation(iid)
|
||
_play_unit_anim(iid, "idle", true))
|
||
_move_anims[iid] = tween
|
||
return duration
|
||
|
||
|
||
## Detect position changes vs _prev_unit_pos and start move animations.
|
||
## Returns the maximum movement duration across all movers (seconds).
|
||
func _play_move_animations(state: Dictionary) -> float:
|
||
if _prev_unit_pos.is_empty():
|
||
return 0.0
|
||
# Build the set of blocked tiles from old unit positions.
|
||
var blocked : Dictionary = {}
|
||
for prev_iid : String in _prev_unit_pos:
|
||
blocked[_prev_unit_pos[prev_iid]] = true
|
||
var max_dur := 0.0
|
||
for player: Dictionary in state.get("players", []):
|
||
var arch : Dictionary = _safe_arch(player)
|
||
for unit: Dictionary in ([arch] + player.get("field", [])):
|
||
if unit.is_empty(): continue
|
||
var iid := str(unit.get("instanceId", ""))
|
||
var pd = unit.get("position")
|
||
if not (pd is Dictionary) or (pd as Dictionary).is_empty(): continue
|
||
var new_coord := Vector2i((pd as Dictionary).get("x", 0),
|
||
(pd as Dictionary).get("y", 0))
|
||
if not _prev_unit_pos.has(iid):
|
||
continue
|
||
var old_coord : Vector2i = _prev_unit_pos[iid]
|
||
if old_coord == new_coord: continue
|
||
# Mover has left its old tile — unblock it for BFS.
|
||
blocked.erase(old_coord)
|
||
var dur := _animate_unit_move(iid, old_coord, new_coord, blocked)
|
||
max_dur = maxf(max_dur, dur)
|
||
return max_dur
|
||
|
||
|
||
## Schedule a delayed call to _rebuild_units.
|
||
## If delay <= 0 and a tween is already pending, just update the target state
|
||
## but DO NOT cancel the running tween — this prevents rapid echo state-updates
|
||
## (phase changes, turn ticks) from killing an in-progress movement animation.
|
||
func _schedule_rebuild(state: Dictionary, delay: float) -> void:
|
||
_pending_rebuild = state # always target the latest state
|
||
if delay <= 0.0:
|
||
if _rebuild_tween != null:
|
||
return # let the existing animation tween finish; it will use _pending_rebuild
|
||
_rebuild_units(state)
|
||
return
|
||
# A new positive delay: cancel any old tween and start a fresh one.
|
||
if _rebuild_tween != null:
|
||
_rebuild_tween.kill()
|
||
_rebuild_tween = null
|
||
_rebuild_tween = create_tween()
|
||
_rebuild_tween.tween_callback(func() -> void:
|
||
_rebuild_tween = null
|
||
_rebuild_units(_pending_rebuild)).set_delay(delay)
|
||
|
||
|
||
# ── Highlights ────────────────────────────────────────────────────────────────
|
||
|
||
func _clear_highlights() -> void:
|
||
# Preserve the two permanently-allocated hover quads (last two children).
|
||
var children := _hi_root.get_children()
|
||
for i in range(children.size()):
|
||
var c : Node = children[i]
|
||
if c != _cursor_highlight and c != _hover_team_overlay:
|
||
c.queue_free()
|
||
|
||
|
||
## Update the always-visible cursor/hover state based on the current mouse position.
|
||
## Called on every InputEventMouseMotion event.
|
||
func _update_hover(mouse_pos: Vector2) -> void:
|
||
if _cursor_highlight == null or _hover_team_overlay == null:
|
||
return
|
||
|
||
# If dragging (camera rotation / pan), hide highlights.
|
||
if _drag_active or _pan_active:
|
||
_cursor_highlight.visible = false
|
||
_hover_team_overlay.visible = false
|
||
_reset_unit_hover_glow()
|
||
_hovered_coord = Vector2i(-1, -1)
|
||
return
|
||
|
||
var coord := _mouse_to_tile_coord(mouse_pos)
|
||
if coord == _hovered_coord:
|
||
return
|
||
|
||
# Reset previous unit glow.
|
||
_reset_unit_hover_glow()
|
||
|
||
_hovered_coord = coord
|
||
if coord.x < 0:
|
||
_cursor_highlight.visible = false
|
||
_hover_team_overlay.visible = false
|
||
return
|
||
|
||
# Move selector cursor.
|
||
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)
|
||
|
||
# Check for an occupant on this tile and highlight with team colour.
|
||
var tile : Dictionary = Game.get_tile(coord.x, coord.y)
|
||
var _raw_occ = 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 = _is_enemy_unit(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)
|
||
|
||
# Boost emission on the unit mesh.
|
||
if _unit_meshes.has(occ_id):
|
||
var mesh : MeshInstance3D = _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
|
||
|
||
|
||
## Create the two permanently-allocated hover/cursor quads.
|
||
## Called once in _ready() after the scene is set up.
|
||
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
|
||
|
||
|
||
## Build a flat (PlaneMesh) highlight quad with the given fallback colour.
|
||
## The caller positions it; the mesh is 0.96 × 0.96 lying flat (rotated -90° on X).
|
||
func _make_highlight_quad(fallback: Color) -> MeshInstance3D:
|
||
var mi := MeshInstance3D.new()
|
||
var pm := PlaneMesh.new()
|
||
pm.size = Vector2(0.96, 0.96)
|
||
mi.mesh = pm
|
||
var mat := 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
|
||
|
||
|
||
## Add a textured highlight quad above tile (x, y) for the given game-action type.
|
||
## type_key: "movement" | "attack" | "ability" | "terramorpha"
|
||
## Falls back to HighlightConfig colours when no texture is loaded yet.
|
||
func _add_highlight(x: int, y: int, type_key: String) -> void:
|
||
var mi := MeshInstance3D.new()
|
||
var pm := PlaneMesh.new()
|
||
pm.size = Vector2(0.96, 0.96)
|
||
mi.mesh = pm
|
||
var mat := 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 _hi_tile_top : float = _tile_visual_tops.get("%d,%d" % [x, y],
|
||
_tile_y_bases.get("%d,%d" % [x, y], 0.0) + _tile_heights.get("%d,%d" % [x, y], 1.0))
|
||
mi.position = _coord_to_world(x, y) + Vector3(0, _hi_tile_top + 0.05, 0)
|
||
_hi_root.add_child(mi)
|
||
|
||
|
||
func _highlight_tiles(coords: Array, type_key: String) -> void:
|
||
for coord in coords:
|
||
if coord is Vector2i:
|
||
_add_highlight(coord.x, coord.y, type_key)
|
||
elif coord is Dictionary:
|
||
_add_highlight(coord.get("x", 0), coord.get("y", 0), type_key)
|
||
|
||
|
||
## Position a permanently-allocated highlight quad above tile (x, y).
|
||
func _place_highlight_quad(quad: MeshInstance3D, x: int, y: int, col: Color, texture: Texture2D = null) -> void:
|
||
var tile_top : float = _tile_visual_tops.get("%d,%d" % [x, y],
|
||
_tile_y_bases.get("%d,%d" % [x, y], 0.0) + _tile_heights.get("%d,%d" % [x, y], 1.0))
|
||
quad.position = _coord_to_world(x, y) + Vector3(0, tile_top + 0.05, 0)
|
||
var mat := 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
|
||
|
||
# ── Valid target computation ──────────────────────────────────────────────────
|
||
|
||
func _valid_play_tiles(card: Dictionary) -> Array:
|
||
var results : Array = []
|
||
var card_type : String = card.get("cardType", "")
|
||
var board : Dictionary = Game.get_board()
|
||
var bw : int = board.get("width", 8)
|
||
var bh : int = board.get("height", 8)
|
||
var arch : Dictionary = Game.get_my_player().get("archSpirit", {})
|
||
var arch_pos : Dictionary = arch.get("position", {})
|
||
|
||
match card_type:
|
||
"Spirit":
|
||
if arch_pos.is_empty(): return results
|
||
var ax : int = arch_pos.get("x", 0)
|
||
var ay : int = arch_pos.get("y", 0)
|
||
# Channel range is a property of the ArchSpirit.
|
||
# dict.get(key, default) only uses the default when the key is ABSENT.
|
||
# The server sends nullable ints (e.g. "minChannelRange": null), so the
|
||
# key EXISTS but its value is null — GDScript returns null, which silently
|
||
# coerces to 0 on a typed int variable, collapsing the range to nothing.
|
||
# Read as Variant first, then substitute the default explicitly.
|
||
var raw_min = arch.get("minChannelRange")
|
||
var raw_max = arch.get("maxChannelRange")
|
||
var min_r : int = 1 if raw_min == null else int(raw_min)
|
||
var max_r : int = 1 if raw_max == null else int(raw_max)
|
||
var card_affinity : String = card.get("affinity", "")
|
||
for tx in range(bw):
|
||
for ty in range(bh):
|
||
if not _tile_bodies.has("%d,%d" % [tx, ty]): continue
|
||
var dist : int = abs(tx - ax) + abs(ty - ay)
|
||
if dist < min_r or dist > max_r: continue
|
||
var tile : Dictionary = Game.get_tile(tx, ty)
|
||
if tile.get("occupantId"): continue
|
||
if card_affinity != "" and tile.get("resolvedAffinity", "Void") != card_affinity: continue
|
||
results.append(Vector2i(tx, ty))
|
||
|
||
"Terramorpha":
|
||
for tx in range(bw):
|
||
for ty in range(bh):
|
||
results.append(Vector2i(tx, ty))
|
||
|
||
"Repentance", "Instinct", "Ruin":
|
||
pass # No tile target — played directly (server handles placement).
|
||
|
||
return results
|
||
|
||
|
||
func _terra_count_for_card(card: Dictionary) -> int:
|
||
match card.get("terramorphaMode", ""):
|
||
"Mono": return 1
|
||
"Di": return 2
|
||
"Tri": return 3
|
||
return 1
|
||
|
||
|
||
func _valid_move_tiles(unit: Dictionary) -> Array:
|
||
var results : Array = []
|
||
var pos : Dictionary = unit.get("position", {})
|
||
if pos.is_empty(): return results
|
||
var ux : int = pos.get("x", 0)
|
||
var uy : int = pos.get("y", 0)
|
||
var mp : int = unit.get("currentMp", 0)
|
||
var bw : int = Game.board_width()
|
||
var bh : int = Game.board_height()
|
||
if mp <= 0: return results
|
||
for tx in range(bw):
|
||
for ty in range(bh):
|
||
if not _tile_bodies.has("%d,%d" % [tx, ty]): continue
|
||
var dist : int = abs(tx - ux) + abs(ty - uy)
|
||
if dist == 0 or dist > mp: continue
|
||
if Game.get_tile(tx, ty).get("occupantId"): continue
|
||
results.append(Vector2i(tx, ty))
|
||
return results
|
||
|
||
|
||
func _valid_attack_target_coords(unit: Dictionary) -> Array:
|
||
var results : Array = []
|
||
var pos : Dictionary = unit.get("position", {})
|
||
if pos.is_empty(): return results
|
||
var ux : int = pos.get("x", 0)
|
||
var uy : int = pos.get("y", 0)
|
||
var min_r : int = unit.get("minAttackRange", 1)
|
||
var max_r : int = unit.get("maxAttackRange", 1)
|
||
if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0:
|
||
return results
|
||
var to_check : Array = Game.get_all_enemy_units()
|
||
for t: Dictionary in to_check:
|
||
if not t.get("canBeAttacked", true): continue
|
||
var _tpos = t.get("position")
|
||
if not (_tpos is Dictionary): continue # null when unit removed from board
|
||
var tp : Dictionary = _tpos
|
||
if tp.is_empty(): continue
|
||
var dist : int = abs(tp.get("x", 0) - ux) + abs(tp.get("y", 0) - uy)
|
||
if dist >= min_r and dist <= max_r:
|
||
results.append(tp)
|
||
return results
|
||
|
||
|
||
func _valid_attack_target_ids(unit: Dictionary) -> Array:
|
||
var results : Array = []
|
||
var pos : Dictionary = unit.get("position", {})
|
||
if pos.is_empty(): return results
|
||
var ux : int = pos.get("x", 0)
|
||
var uy : int = pos.get("y", 0)
|
||
var min_r : int = unit.get("minAttackRange", 1)
|
||
var max_r : int = unit.get("maxAttackRange", 1)
|
||
if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0:
|
||
return results
|
||
var to_check : Array = Game.get_all_enemy_units()
|
||
for t: Dictionary in to_check:
|
||
if not t.get("canBeAttacked", true): continue
|
||
var tp : Dictionary = t.get("position", {})
|
||
if tp.is_empty(): continue
|
||
var dist : int = abs(tp.get("x", 0) - ux) + abs(tp.get("y", 0) - uy)
|
||
if dist >= min_r and dist <= max_r:
|
||
results.append(t.get("instanceId", ""))
|
||
return results
|
||
|
||
|
||
## All tiles within a unit's attack range (regardless of occupancy).
|
||
## Used to show the orange reach area for ranged units.
|
||
func _attack_range_tiles(unit: Dictionary) -> Array:
|
||
var results : Array = []
|
||
var pos : Dictionary = unit.get("position", {})
|
||
if pos.is_empty(): return results
|
||
var ux : int = pos.get("x", 0)
|
||
var uy : int = pos.get("y", 0)
|
||
var min_r : int = unit.get("minAttackRange", 1)
|
||
var max_r : int = unit.get("maxAttackRange", 1)
|
||
if max_r <= 1: return results # skip melee — no separate range indicator needed
|
||
var bw : int = Game.board_width()
|
||
var bh : int = Game.board_height()
|
||
for tx in range(bw):
|
||
for ty in range(bh):
|
||
if not _tile_bodies.has("%d,%d" % [tx, ty]): continue
|
||
var dist : int = abs(tx - ux) + abs(ty - uy)
|
||
if dist >= min_r and dist <= max_r:
|
||
results.append(Vector2i(tx, ty))
|
||
return results
|
||
|
||
|
||
func _valid_placement_tiles() -> Array:
|
||
var results : Array = []
|
||
var my_id := Auth.user_id
|
||
var my_seat : int = int(Game.get_my_player().get("seatIndex", 0))
|
||
var board : Dictionary = Game.get_board()
|
||
var sz_raw : Dictionary = board.get("startingZones", {})
|
||
|
||
if not sz_raw.is_empty():
|
||
# N-player: use the StartingZones dict keyed by seatIndex.
|
||
var seat_key : String = str(my_seat)
|
||
var zone : Array = sz_raw.get(seat_key, []) as Array
|
||
for coord: Dictionary in zone:
|
||
var tx : int = int(coord.get("x", -1))
|
||
var ty : int = int(coord.get("y", -1))
|
||
if tx >= 0 and not Game.get_tile(tx, ty).get("occupantId"):
|
||
results.append(Vector2i(tx, ty))
|
||
else:
|
||
# Legacy 1v1 fallback.
|
||
var p1_id : String = str(Game.state.get("playerOneAccountId", ""))
|
||
var bw : int = Game.board_width()
|
||
var bh : int = Game.board_height()
|
||
var row : int = 0 if my_id == p1_id else bh - 1
|
||
for tx in range(bw):
|
||
if not Game.get_tile(tx, row).get("occupantId"):
|
||
results.append(Vector2i(tx, row))
|
||
return results
|
||
|
||
|
||
## Friendly spirits adjacent to own ArchSpirit (sacrifice candidates).
|
||
func _valid_sacrifice_spirits() -> Array:
|
||
var results : Array = []
|
||
var arch : Dictionary = Game.get_my_player().get("archSpirit", {})
|
||
var arch_pos : Dictionary = arch.get("position", {})
|
||
if arch_pos.is_empty(): return results
|
||
var ax : int = arch_pos.get("x", 0)
|
||
var ay : int = arch_pos.get("y", 0)
|
||
for unit: Dictionary in Game.get_field():
|
||
var up : Dictionary = unit.get("position", {})
|
||
if up.is_empty(): continue
|
||
var ux : int = up.get("x", 0)
|
||
var uy : int = up.get("y", 0)
|
||
if abs(ux - ax) + abs(uy - ay) == 1:
|
||
results.append(unit)
|
||
return results
|
||
|
||
# ── Tile detail drawer ────────────────────────────────────────────────────────
|
||
|
||
func _create_tile_drawer() -> void:
|
||
var panel := PanelContainer.new()
|
||
panel.anchor_left = 1.0
|
||
panel.anchor_right = 1.0
|
||
panel.anchor_top = 0.0
|
||
panel.anchor_bottom = 1.0
|
||
panel.offset_left = 0.0
|
||
panel.offset_right = 0.0
|
||
panel.offset_top = 0.0
|
||
panel.offset_bottom = 0.0
|
||
panel.visible = false
|
||
_hud.add_child(panel)
|
||
_tile_drawer = panel
|
||
|
||
var margin := MarginContainer.new()
|
||
margin.layout_mode = 2
|
||
margin.add_theme_constant_override("margin_left", 12)
|
||
margin.add_theme_constant_override("margin_right", 12)
|
||
margin.add_theme_constant_override("margin_top", 12)
|
||
margin.add_theme_constant_override("margin_bottom", 12)
|
||
panel.add_child(margin)
|
||
|
||
var vbox := VBoxContainer.new()
|
||
vbox.layout_mode = 2
|
||
vbox.add_theme_constant_override("separation", 6)
|
||
margin.add_child(vbox)
|
||
|
||
# Title row with close button.
|
||
var title_row := HBoxContainer.new()
|
||
title_row.layout_mode = 2
|
||
var title_lbl := Label.new()
|
||
title_lbl.text = "Tile Detail"
|
||
title_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
||
title_lbl.add_theme_font_size_override("font_size", 15)
|
||
var close_btn := Button.new()
|
||
close_btn.text = "×"
|
||
close_btn.custom_minimum_size = Vector2(28, 28)
|
||
close_btn.pressed.connect(_close_tile_drawer)
|
||
title_row.add_child(title_lbl)
|
||
title_row.add_child(close_btn)
|
||
vbox.add_child(title_row)
|
||
|
||
var sep := HSeparator.new()
|
||
sep.layout_mode = 2
|
||
vbox.add_child(sep)
|
||
|
||
# Detail labels.
|
||
_tile_drawer_lbl_coord = Label.new()
|
||
_tile_drawer_lbl_aff = Label.new()
|
||
_tile_drawer_lbl_b1 = Label.new()
|
||
_tile_drawer_lbl_b2 = Label.new()
|
||
_tile_drawer_lbl_ruin = Label.new()
|
||
_tile_drawer_lbl_occ = Label.new()
|
||
for lbl: Label in [_tile_drawer_lbl_coord, _tile_drawer_lbl_aff,
|
||
_tile_drawer_lbl_b1, _tile_drawer_lbl_b2,
|
||
_tile_drawer_lbl_ruin, _tile_drawer_lbl_occ]:
|
||
lbl.layout_mode = 2
|
||
lbl.add_theme_font_size_override("font_size", 12)
|
||
lbl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||
vbox.add_child(lbl)
|
||
|
||
|
||
func _open_tile_drawer(tile: Dictionary) -> void:
|
||
if not is_instance_valid(_tile_drawer): return
|
||
var coord : Dictionary = tile.get("coord", {})
|
||
var cx : int = int(coord.get("x", 0))
|
||
var cy : int = int(coord.get("y", 0))
|
||
var aff : String = str(tile.get("resolvedAffinity", "?"))
|
||
var b1 : String = str(tile.get("base1", "?"))
|
||
var b2 : String = str(tile.get("base2", "?"))
|
||
var ruin_id : String = str(tile.get("ruinId", ""))
|
||
var occ_id : String = str(tile.get("occupantId", ""))
|
||
|
||
_tile_drawer_lbl_coord.text = "(%d, %d)" % [cx, cy]
|
||
_tile_drawer_lbl_aff.text = "Affinity: %s" % aff
|
||
_tile_drawer_lbl_b1.text = "Base1: %s" % b1
|
||
_tile_drawer_lbl_b2.text = "Base2: %s" % b2
|
||
|
||
if not ruin_id.is_empty() and ruin_id != "null":
|
||
_tile_drawer_lbl_ruin.text = "Ruin: %s" % ruin_id
|
||
_tile_drawer_lbl_ruin.visible = true
|
||
else:
|
||
_tile_drawer_lbl_ruin.visible = false
|
||
|
||
if not occ_id.is_empty() and occ_id != "null":
|
||
var occ_unit := Game.get_unit_by_id(occ_id)
|
||
_tile_drawer_lbl_occ.text = "Occupant: %s" % (
|
||
occ_unit.get("name", occ_id) if not occ_unit.is_empty() else occ_id)
|
||
_tile_drawer_lbl_occ.visible = true
|
||
else:
|
||
_tile_drawer_lbl_occ.visible = false
|
||
|
||
if _tile_drawer_open:
|
||
return # already open, content updated above
|
||
_tile_drawer_open = true
|
||
_tile_drawer.visible = true
|
||
if _tile_drawer_tween: _tile_drawer_tween.kill()
|
||
_tile_drawer.offset_left = 0.0
|
||
_tile_drawer_tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC)
|
||
_tile_drawer_tween.tween_property(_tile_drawer, "offset_left", -260.0, 0.3)
|
||
|
||
|
||
func _close_tile_drawer() -> void:
|
||
if not is_instance_valid(_tile_drawer) or not _tile_drawer_open: return
|
||
_tile_drawer_open = false
|
||
if _tile_drawer_tween: _tile_drawer_tween.kill()
|
||
_tile_drawer_tween = create_tween().set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_CUBIC)
|
||
_tile_drawer_tween.tween_property(_tile_drawer, "offset_left", 0.0, 0.25)
|
||
_tile_drawer_tween.tween_callback(func() -> void:
|
||
if is_instance_valid(_tile_drawer): _tile_drawer.visible = false)
|
||
|
||
|
||
func _focus_camera_on_tile(x: int, y: int) -> void:
|
||
var target := _coord_to_world(x, y)
|
||
var from := _cam_pivot
|
||
if _cam_tween: _cam_tween.kill()
|
||
_cam_tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC)
|
||
_cam_tween.tween_method(
|
||
func(v: Vector3) -> void: _cam_pivot = v; _apply_camera(),
|
||
from, target, 0.4)
|
||
|
||
|
||
# ── Click handling ────────────────────────────────────────────────────────────
|
||
|
||
func _handle_board_click(mouse_pos: Vector2) -> void:
|
||
var coord := _mouse_to_tile_coord(mouse_pos)
|
||
var unit_id := _mouse_to_unit_id(mouse_pos)
|
||
|
||
match _mode:
|
||
|
||
Mode.NONE:
|
||
# Occupied tile with no direct unit-mesh hit → redirect to the occupant.
|
||
if unit_id.is_empty() and coord.x >= 0:
|
||
var _t := Game.get_tile(coord.x, coord.y)
|
||
var _raw_occ = _t.get("occupantId")
|
||
var _occ := _raw_occ if _raw_occ is String else ""
|
||
if not _occ.is_empty() and _occ != "null":
|
||
unit_id = _occ
|
||
# Show tile detail drawer and optionally pan camera.
|
||
if coord.x >= 0:
|
||
_open_tile_drawer(Game.get_tile(coord.x, coord.y))
|
||
if Settings.click_to_focus_camera:
|
||
_focus_camera_on_tile(coord.x, coord.y)
|
||
# Unit selection.
|
||
if not unit_id.is_empty() and _is_friendly_unit(unit_id) \
|
||
and Game.is_my_turn() and Game.get_phase() != "Placement":
|
||
_select_unit(unit_id)
|
||
|
||
Mode.CARD_FROM_HAND:
|
||
var card := _find_hand_card(_sel_card_id)
|
||
if card.is_empty():
|
||
print("Card empty, mode none")
|
||
_set_mode(Mode.NONE); return
|
||
var card_type : String = card.get("cardType", "")
|
||
if card_type in ["Repentance", "Instinct", "Ruin"]:
|
||
Game.send_play_card(_sel_card_id, 0, 0)
|
||
_set_mode(Mode.NONE); return
|
||
if coord.x < 0:
|
||
print("x coor < 0")
|
||
_set_mode(Mode.NONE); return
|
||
Game.send_play_card(_sel_card_id, coord.x, coord.y)
|
||
print("Send play card")
|
||
_set_mode(Mode.NONE)
|
||
|
||
Mode.TERRAMORPHA_SELECT:
|
||
if coord.x < 0:
|
||
_set_mode(Mode.NONE); return
|
||
# Validate adjacency to previous target for Di/Tri.
|
||
if _terra_targets.size() > 0:
|
||
print("_terra_targets: ", _terra_targets.size())
|
||
var last : Vector2i = _terra_targets.back()
|
||
if abs(coord.x - last.x) + abs(coord.y - last.y) != 1:
|
||
return # must be adjacent
|
||
# Avoid duplicates.
|
||
print("Handle Board Click: terra targets: ", _terra_targets)
|
||
if _terra_targets.has(coord): return
|
||
_terra_targets.append(coord)
|
||
print("Added Target")
|
||
if _terra_targets.size() >= _terra_count:
|
||
print("Entering here")
|
||
print("_terra_count: ", _terra_count)
|
||
# All tiles selected — send play.
|
||
var targets := _terra_targets.map(func(v: Vector2i) -> Dictionary:
|
||
return { "x": v.x, "y": v.y })
|
||
Game.send_play_card_multi(_sel_card_id, targets)
|
||
_set_mode(Mode.NONE)
|
||
else:
|
||
# More tiles needed — re-highlight: orange for picked, green for valid next.
|
||
_clear_highlights()
|
||
for t: Vector2i in _terra_targets:
|
||
_add_highlight(t.x, t.y, "terramorpha")
|
||
var last2 : Vector2i = _terra_targets.back()
|
||
var bw2 := Game.board_width()
|
||
var bh2 := Game.board_height()
|
||
for d: Vector2i in [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)]:
|
||
var nx := last2.x + d.x
|
||
var ny := last2.y + d.y
|
||
if nx < 0 or ny < 0 or nx >= bw2 or ny >= bh2: continue
|
||
if _terra_targets.has(Vector2i(nx, ny)): continue
|
||
_add_highlight(nx, ny, "movement")
|
||
|
||
Mode.UNIT_SELECTED:
|
||
# Occupied tile with no direct unit-mesh hit → redirect to the occupant.
|
||
if unit_id.is_empty() and coord.x >= 0:
|
||
var _t2 := Game.get_tile(coord.x, coord.y)
|
||
var _raw_occ2 = _t2.get("occupantId")
|
||
var _occ2 := _raw_occ2 if _raw_occ2 is String else ""
|
||
if not _occ2.is_empty() and _occ2 != "null":
|
||
unit_id = _occ2
|
||
if not unit_id.is_empty():
|
||
if _is_enemy_unit(unit_id):
|
||
_last_attack_target_iid = unit_id
|
||
_play_unit_anim(_sel_unit_id, "attack")
|
||
SFX.play(_sfx_for_unit(_sel_unit_id, "attackSoundUrl"))
|
||
Game.send_attack(_sel_unit_id, unit_id)
|
||
_set_mode(Mode.NONE)
|
||
elif unit_id == _sel_unit_id:
|
||
# Re-click same unit → toggle ability panel.
|
||
if is_instance_valid(_ability_panel):
|
||
_hide_ability_panel()
|
||
else:
|
||
var resel_unit := Game.get_unit_by_id(unit_id)
|
||
if not resel_unit.is_empty():
|
||
_show_ability_panel(unit_id, resel_unit)
|
||
elif _is_friendly_unit(unit_id):
|
||
_select_unit(unit_id) # switch to new unit
|
||
elif coord.x >= 0:
|
||
Game.send_move_unit(_sel_unit_id, coord.x, coord.y)
|
||
_set_mode(Mode.NONE)
|
||
|
||
Mode.PLACEMENT:
|
||
if coord.x >= 0:
|
||
Game.send_place_arch_spirit(coord.x, coord.y)
|
||
_set_mode(Mode.NONE)
|
||
|
||
Mode.SACRIFICE_SELECT:
|
||
# Player clicks a highlighted friendly spirit adjacent to ArchSpirit.
|
||
if unit_id.is_empty() or not _is_friendly_unit(unit_id):
|
||
_set_mode(Mode.NONE); return
|
||
var unit := Game.get_unit_by_id(unit_id)
|
||
if unit.is_empty() or unit.get("cardType", "") == "ArchSpirit":
|
||
_set_mode(Mode.NONE); return
|
||
_confirm_sacrifice(unit_id, unit.get("name", "this spirit"))
|
||
|
||
Mode.ABILITY_TARGET:
|
||
# Collect the clicked board target; advance only when N targets have been gathered.
|
||
var _collected := false
|
||
if not unit_id.is_empty():
|
||
_ability_targets.append({
|
||
"actionIndex": _ability_cur_action_idx,
|
||
"instanceId": unit_id
|
||
})
|
||
_ability_targets_this_action += 1
|
||
_collected = true
|
||
elif coord.x >= 0:
|
||
_ability_targets.append({
|
||
"actionIndex": _ability_cur_action_idx,
|
||
"coord": { "x": coord.x, "y": coord.y }
|
||
})
|
||
_ability_targets_this_action += 1
|
||
_collected = true
|
||
|
||
if not _collected:
|
||
_set_mode(Mode.NONE)
|
||
elif _ability_targets_this_action >= _ability_target_n:
|
||
# All required targets for this action collected — advance.
|
||
_ability_cur_action_idx += 1
|
||
_advance_ability_targeting()
|
||
# else: more targets needed (or UpTo: confirm button lets player finish early)
|
||
|
||
|
||
func _select_unit(unit_id: String) -> void:
|
||
var unit := Game.get_unit_by_id(unit_id)
|
||
if unit.is_empty(): return
|
||
|
||
_hide_ability_panel()
|
||
_sel_unit_id = unit_id
|
||
_set_mode(Mode.UNIT_SELECTED)
|
||
_clear_highlights()
|
||
|
||
# Highlight own tile.
|
||
var upos : Dictionary = unit.get("position", {})
|
||
if not upos.is_empty():
|
||
_add_highlight(upos.get("x", 0), upos.get("y", 0), "selector")
|
||
# Smoothly pan camera to center on this unit if setting is enabled.
|
||
if Settings.camera_follow_unit:
|
||
var target := _coord_to_world(upos.get("x", 0), upos.get("y", 0))
|
||
var from := _cam_pivot
|
||
if _cam_tween: _cam_tween.kill()
|
||
_cam_tween = create_tween().set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC)
|
||
_cam_tween.tween_method(
|
||
func(v: Vector3) -> void: _cam_pivot = v; _apply_camera(),
|
||
from, target, 0.4)
|
||
|
||
# Movement range.
|
||
_highlight_tiles(_valid_move_tiles(unit), "movement")
|
||
|
||
# Attack range area — visible reach even when no enemies are in range.
|
||
_highlight_tiles(_attack_range_tiles(unit), "terramorpha")
|
||
# Attackable enemies (drawn on top).
|
||
_highlight_tiles(_valid_attack_target_coords(unit), "attack")
|
||
|
||
# Show ability panel if unit has active abilities.
|
||
_show_ability_panel(unit_id, unit)
|
||
|
||
# Own ArchSpirit — offer Sacrifice option via menu.
|
||
if unit.get("cardType", "") == "ArchSpirit" and _is_friendly_unit(unit_id):
|
||
_show_arch_spirit_menu(unit_id, unit)
|
||
|
||
|
||
func _set_mode(new_mode: Mode) -> void:
|
||
print("Setting mode: ", new_mode)
|
||
_mode = new_mode
|
||
_terra_targets = []
|
||
_terra_count = 0
|
||
if new_mode != Mode.NONE:
|
||
_close_tile_drawer()
|
||
if new_mode == Mode.NONE:
|
||
_sel_card_id = ""
|
||
_sel_unit_id = ""
|
||
_ability_unit_id = ""
|
||
_ability_idx = -1
|
||
_ability_def = []
|
||
_ability_range = {}
|
||
_ability_targets = []
|
||
_ability_cur_action_idx = 0
|
||
_ability_card_id = ""
|
||
_ability_target_conditions = []
|
||
_ability_target_n = 1
|
||
_ability_target_up_to = false
|
||
_ability_targets_this_action = 0
|
||
_hide_ability_confirm_btn()
|
||
_hide_branch_panel()
|
||
_clear_highlights()
|
||
_hide_ability_panel()
|
||
_hide_player_panel()
|
||
_refresh_hand_selection()
|
||
|
||
# ── ArchSpirit popup menu (Sacrifice / Ascend / Transition) ───────────────────
|
||
|
||
func _show_arch_spirit_menu(unit_id: String, _unit: Dictionary) -> void:
|
||
var menu := PopupMenu.new()
|
||
add_child(menu)
|
||
|
||
var sac_spirits := _valid_sacrifice_spirits()
|
||
if not sac_spirits.is_empty():
|
||
menu.add_item("Sacrifice a Spirit", 0)
|
||
|
||
# Ascend / Transition from hand.
|
||
var can_ascend := false
|
||
var can_transition := false
|
||
var cur_tier : int = _unit.get("tier", 1)
|
||
for card: Dictionary in Game.get_hand():
|
||
if card.get("cardType", "") != "ArchSpirit": continue
|
||
var t : int = int(card.get("tier", 0))
|
||
if t == cur_tier + 1: can_ascend = true
|
||
if t == 1: can_transition = true
|
||
|
||
if can_ascend:
|
||
menu.add_item("Ascend ArchSpirit", 1)
|
||
if can_transition:
|
||
menu.add_item("Transition ArchSpirit", 2)
|
||
|
||
if menu.item_count == 0:
|
||
menu.queue_free(); return
|
||
|
||
menu.id_pressed.connect(func(id: int) -> void:
|
||
match id:
|
||
0: _start_sacrifice_mode()
|
||
1: _pick_ascend_card()
|
||
2: _pick_transition_card()
|
||
menu.queue_free())
|
||
menu.popup_hide.connect(func() -> void: menu.queue_free())
|
||
menu.position = DisplayServer.mouse_get_position()
|
||
menu.reset_size()
|
||
menu.popup()
|
||
|
||
|
||
func _start_sacrifice_mode() -> void:
|
||
_set_mode(Mode.SACRIFICE_SELECT)
|
||
_clear_highlights()
|
||
for spirit: Dictionary in _valid_sacrifice_spirits():
|
||
var sp : Dictionary = spirit.get("position", {})
|
||
if not sp.is_empty():
|
||
_add_highlight(sp.get("x", 0), sp.get("y", 0), "movement")
|
||
|
||
|
||
func _confirm_sacrifice(unit_id: String, unit_name: String) -> void:
|
||
var dlg := ConfirmationDialog.new()
|
||
dlg.title = "Sacrifice"
|
||
dlg.dialog_text = "Sacrifice %s?" % unit_name
|
||
dlg.ok_button_text = "Sacrifice"
|
||
dlg.cancel_button_text = "Cancel"
|
||
dlg.min_size = Vector2(260, 90)
|
||
add_child(dlg)
|
||
dlg.popup_centered()
|
||
dlg.confirmed.connect(func() -> void:
|
||
Game.send_sacrifice(unit_id)
|
||
dlg.queue_free()
|
||
_set_mode(Mode.NONE))
|
||
dlg.canceled.connect(func() -> void:
|
||
dlg.queue_free()
|
||
_set_mode(Mode.NONE))
|
||
|
||
# ── Ascend / Transition ───────────────────────────────────────────────────────
|
||
|
||
func _pick_ascend_card() -> void:
|
||
var cur_tier : int = _get_my_arch_tier()
|
||
var candidates : Array = Game.get_hand().filter(func(c: Dictionary) -> bool:
|
||
return c.get("cardType", "") == "ArchSpirit" and int(c.get("tier", 0)) == cur_tier + 1)
|
||
if candidates.is_empty(): return
|
||
if candidates.size() == 1:
|
||
_confirm_ascend(candidates[0])
|
||
else:
|
||
_show_card_picker("Choose Ascend Card", candidates,
|
||
func(card: Dictionary) -> void: _confirm_ascend(card))
|
||
|
||
|
||
func _pick_transition_card() -> void:
|
||
var candidates : Array = Game.get_hand().filter(func(c: Dictionary) -> bool:
|
||
return c.get("cardType", "") == "ArchSpirit" and int(c.get("tier", 0)) == 1)
|
||
if candidates.is_empty(): return
|
||
if candidates.size() == 1:
|
||
_confirm_transition(candidates[0])
|
||
else:
|
||
_show_card_picker("Choose Transition Card", candidates,
|
||
func(card: Dictionary) -> void: _confirm_transition(card))
|
||
|
||
|
||
func _confirm_ascend(card: Dictionary) -> void:
|
||
var dlg := ConfirmationDialog.new()
|
||
dlg.title = "Ascend"
|
||
dlg.dialog_text = "Ascend to %s (Tier %d)?" % [
|
||
card.get("name", "?"), int(card.get("tier", 0))]
|
||
dlg.ok_button_text = "Ascend"
|
||
dlg.min_size = Vector2(280, 90)
|
||
add_child(dlg)
|
||
dlg.popup_centered()
|
||
dlg.confirmed.connect(func() -> void:
|
||
Game.send_ascend(card.get("instanceId", ""))
|
||
dlg.queue_free())
|
||
dlg.canceled.connect(func() -> void: dlg.queue_free())
|
||
|
||
|
||
func _confirm_transition(card: Dictionary) -> void:
|
||
var dlg := ConfirmationDialog.new()
|
||
dlg.title = "Transition"
|
||
dlg.dialog_text = "Swap to %s?" % card.get("name", "?")
|
||
dlg.ok_button_text = "Transition"
|
||
dlg.min_size = Vector2(280, 90)
|
||
add_child(dlg)
|
||
dlg.popup_centered()
|
||
dlg.confirmed.connect(func() -> void:
|
||
Game.send_transition(card.get("instanceId", ""))
|
||
dlg.queue_free())
|
||
dlg.canceled.connect(func() -> void: dlg.queue_free())
|
||
|
||
|
||
func _get_my_arch_tier() -> int:
|
||
var arch : Dictionary = _safe_arch(Game.get_my_player())
|
||
return int(arch.get("tier", 1))
|
||
|
||
|
||
## Generic card picker popup for when there are multiple candidates.
|
||
func _show_card_picker(title: String, cards: Array, on_pick: Callable) -> void:
|
||
var dlg := AcceptDialog.new()
|
||
dlg.title = title
|
||
dlg.min_size = Vector2(320, 200)
|
||
var vbox := VBoxContainer.new()
|
||
vbox.add_theme_constant_override("separation", 6)
|
||
for card: Dictionary in cards:
|
||
var btn := Button.new()
|
||
btn.text = "%s (Tier %d)" % [card.get("name", "?"), int(card.get("tier", 0))]
|
||
btn.pressed.connect(func() -> void:
|
||
on_pick.call(card)
|
||
dlg.queue_free())
|
||
vbox.add_child(btn)
|
||
dlg.add_child(vbox)
|
||
add_child(dlg)
|
||
dlg.popup_centered()
|
||
dlg.canceled.connect(func() -> void: dlg.queue_free())
|
||
|
||
# ── Ability panel ─────────────────────────────────────────────────────────────
|
||
|
||
## Recursively normalise all Dictionary keys to lowercase so ability JSON can
|
||
## be read with consistent lowercase lookups regardless of server casing.
|
||
func _normalize_keys(value: Variant) -> Variant:
|
||
if value is Dictionary:
|
||
var result := {}
|
||
for k in (value as Dictionary):
|
||
result[str(k).to_lower()] = _normalize_keys((value as Dictionary)[k])
|
||
return result
|
||
elif value is Array:
|
||
var result : Array = []
|
||
for item in (value as Array):
|
||
result.append(_normalize_keys(item))
|
||
return result
|
||
return value
|
||
|
||
|
||
## Clamp a panel's desired top-left position so it stays within the viewport.
|
||
## Called after the panel has been added to the tree so size is valid.
|
||
func _clamp_panel_pos(desired: Vector2, panel: Control) -> Vector2:
|
||
var vp := get_viewport().get_visible_rect().size
|
||
var sz := panel.size # may still be zero the first frame; safe fallback
|
||
if sz == Vector2.ZERO:
|
||
sz = panel.custom_minimum_size
|
||
return Vector2(
|
||
clampf(desired.x, 4.0, vp.x - sz.x - 4.0),
|
||
clampf(desired.y, 4.0, vp.y - sz.y - 4.0))
|
||
|
||
|
||
func _show_ability_panel(unit_id: String, unit: Dictionary) -> void:
|
||
_hide_ability_panel()
|
||
# Null trap: server sends "abilitiesJson": null for units with no abilities.
|
||
# dict.get(key, default) returns null when key exists with null value.
|
||
var _raw_abil_ap = unit.get("abilitiesJson")
|
||
var abil_json : String = "" if _raw_abil_ap == null else str(_raw_abil_ap)
|
||
if abil_json.is_empty(): return
|
||
var parsed = JSON.parse_string(abil_json)
|
||
if not parsed is Array: return
|
||
# Server may serialise with PascalCase keys — normalise to lowercase.
|
||
var abilities : Array = _normalize_keys(parsed) as Array
|
||
|
||
# Collect Active abilities.
|
||
var actives : Array = []
|
||
for i in abilities.size():
|
||
var ab : Dictionary = abilities[i] as Dictionary
|
||
if ab.get("type", "") == "Active":
|
||
actives.append({ "index": i,
|
||
"name": ab.get("name", "Ability %d" % i),
|
||
"desc": ab.get("description", ""),
|
||
"def": ab })
|
||
|
||
if actives.is_empty(): return
|
||
|
||
# Build a floating panel positioned to the right of the unit in screen space.
|
||
var panel := PanelContainer.new()
|
||
var vbox := VBoxContainer.new()
|
||
vbox.add_theme_constant_override("separation", 4)
|
||
vbox.custom_minimum_size = Vector2(160, 0)
|
||
|
||
var title := Label.new()
|
||
title.text = "Abilities"
|
||
title.add_theme_font_size_override("font_size", 12)
|
||
title.add_theme_color_override("font_color", Color(0.7, 0.8, 1.0))
|
||
vbox.add_child(title)
|
||
vbox.add_child(HSeparator.new())
|
||
|
||
for ab: Dictionary in actives:
|
||
var btn := Button.new()
|
||
btn.text = ab.get("name", "")
|
||
btn.tooltip_text = ab.get("desc", "")
|
||
btn.add_theme_font_size_override("font_size", 12)
|
||
var idx : int = ab.get("index", 0)
|
||
var ab_def : Dictionary = ab.get("def", {})
|
||
btn.pressed.connect(func() -> void:
|
||
_ability_unit_id = unit_id
|
||
_ability_idx = idx
|
||
_ability_def = ab_def.get("actions", [])
|
||
_ability_range = ab_def.get("range", {})
|
||
_ability_targets = []
|
||
_ability_cur_action_idx = 0
|
||
_start_ability_targeting())
|
||
vbox.add_child(btn)
|
||
|
||
panel.add_child(vbox)
|
||
_hud.add_child(panel)
|
||
_ability_panel = panel
|
||
|
||
# Position panel to the right of the unit after one layout frame so size is known.
|
||
var body := _unit_bodies.get(unit_id) as StaticBody3D
|
||
if is_instance_valid(body):
|
||
var screen_pos := _camera.unproject_position(body.global_position)
|
||
panel.set_deferred("position", _clamp_panel_pos(screen_pos + Vector2(36, -40), panel))
|
||
else:
|
||
panel.position = Vector2(12, 420)
|
||
|
||
|
||
func _hide_ability_panel() -> void:
|
||
if is_instance_valid(_ability_panel):
|
||
_ability_panel.queue_free()
|
||
_ability_panel = null
|
||
|
||
|
||
## Determine what input is needed for the current action and either enter
|
||
## ABILITY_TARGET mode (board highlights) or show the player panel.
|
||
func _start_ability_targeting() -> void:
|
||
print("Game_Screen:: _Start targeting")
|
||
if _ability_cur_action_idx >= _ability_def.size():
|
||
_send_ability()
|
||
return
|
||
|
||
var action : Dictionary = {}
|
||
if _ability_def[_ability_cur_action_idx] is Dictionary:
|
||
action = _ability_def[_ability_cur_action_idx] as Dictionary
|
||
|
||
# ChooseOne — present branch buttons; no board highlights needed.
|
||
if action.has("chooseone"):
|
||
_set_mode(Mode.ABILITY_TARGET)
|
||
_clear_highlights()
|
||
_show_branch_panel(action)
|
||
return
|
||
|
||
var target_sel : Dictionary = action.get("target", {})
|
||
var scope : String = target_sel.get("scope", "Battlefield")
|
||
var ownership : String = target_sel.get("ownership", "Any")
|
||
var count_dict : Dictionary = target_sel.get("count", {})
|
||
var count_all : bool = count_dict.get("all", false)
|
||
|
||
# Read target count for this action (used by the input handler for multi-target collection).
|
||
_ability_target_n = maxi(1, int(count_dict.get("n", 1)))
|
||
_ability_target_up_to = bool(count_dict.get("upto", false))
|
||
_ability_targets_this_action = 0
|
||
|
||
# Actions auto-resolved by the server need no player input.
|
||
# "Target" means "owner of the last targeted card" — resolved server-side from ctx.ResolvedTargets.
|
||
var auto_ownerships := ["Self", "ExactSelf", "Random", "Target"]
|
||
if count_all or ownership in auto_ownerships:
|
||
_ability_cur_action_idx += 1
|
||
_start_ability_targeting()
|
||
return
|
||
|
||
# Player / zone selection — show the left-side player panel.
|
||
var zone_scopes := ["Player", "Hand", "Deck", "Discard", "AnyZone"]
|
||
if scope in zone_scopes:
|
||
_set_mode(Mode.ABILITY_TARGET)
|
||
_clear_highlights()
|
||
_show_player_panel(scope, ownership)
|
||
return
|
||
|
||
# Board selection — enter ABILITY_TARGET mode with blue tile highlights.
|
||
_set_mode(Mode.ABILITY_TARGET)
|
||
_clear_highlights()
|
||
_highlight_ability_targets(action)
|
||
|
||
# When the player may select fewer than N targets, show a confirm button.
|
||
if _ability_target_up_to and _ability_target_n > 1:
|
||
_show_ability_confirm_btn()
|
||
|
||
|
||
## Called after each target (or set of targets) is collected; advances to the next action or sends.
|
||
func _advance_ability_targeting() -> void:
|
||
_hide_ability_confirm_btn()
|
||
_hide_branch_panel()
|
||
_hide_player_panel()
|
||
_clear_highlights()
|
||
_ability_targets_this_action = 0
|
||
_start_ability_targeting()
|
||
|
||
|
||
## Highlight valid ability targets in blue.
|
||
func _highlight_ability_targets(action: Dictionary) -> void:
|
||
print("[Highlighter]: action:: ", action)
|
||
var target_sel : Dictionary = action.get("target", {})
|
||
var type_ : String = target_sel.get("type", "Unit")
|
||
var ownership : String = target_sel.get("ownership", "Any")
|
||
var filters : Array = target_sel.get("filters", [])
|
||
|
||
var linear_only : bool = _ability_range.get("linearonly", false)
|
||
var requires_los : bool = _ability_range.get("requireslos", false)
|
||
|
||
# Source position — needed for range, linear, and LOS checks.
|
||
var src_pos_ab : Dictionary = {}
|
||
if not _ability_range.is_empty() or linear_only or requires_los:
|
||
src_pos_ab = Game.get_unit_by_id(_ability_unit_id).get("position", {})
|
||
|
||
# Tile target — paint tiles that pass spatial and range/LOS filters blue.
|
||
if type_ == "Tile":
|
||
var bw := Game.board_width()
|
||
var bh := Game.board_height()
|
||
for tx in range(bw):
|
||
for ty in range(bh):
|
||
if not src_pos_ab.is_empty():
|
||
var sx := int(src_pos_ab.get("x", 0))
|
||
var sy := int(src_pos_ab.get("y", 0))
|
||
if linear_only and not _is_linear(sx, sy, tx, ty): continue
|
||
if requires_los and not _client_has_los(sx, sy, tx, ty): continue
|
||
if _tile_passes_filters(tx, ty, filters):
|
||
_add_highlight(tx, ty, "ability")
|
||
return
|
||
|
||
# Unit-type target — highlight the board position of each matching unit.
|
||
var include_enemy : bool = ownership in ["Enemy", "Any"]
|
||
var include_friendly : bool = ownership in ["Owner", "Ally", "Any"]
|
||
# Fallback: if nothing matched, treat as enemy.
|
||
if not include_enemy and not include_friendly:
|
||
include_enemy = true
|
||
|
||
var targets : Array = []
|
||
if include_enemy:
|
||
targets.append_array(Game.get_all_enemy_units())
|
||
if include_friendly:
|
||
targets.append_array(Game.get_field())
|
||
var my_arch : Dictionary = Game.get_my_player().get("archSpirit", {})
|
||
if not my_arch.is_empty():
|
||
targets.append(my_arch)
|
||
|
||
for u: Dictionary in targets:
|
||
if type_ == "Spirit" || type_ == "ArchSpirit" || type_ == "SpiritToken" || type_ == "Ruin":
|
||
if u.get("cardType", "").to_lower() != type_.to_lower() : continue
|
||
var pos : Dictionary = u.get("position", {})
|
||
if pos.is_empty(): continue
|
||
if not _unit_passes_filters(u, filters): continue
|
||
if not _ability_range.is_empty():
|
||
if src_pos_ab.is_empty(): continue
|
||
var dist := (absi(int(pos.get("x", 0)) - int(src_pos_ab.get("x", 0))) +
|
||
absi(int(pos.get("y", 0)) - int(src_pos_ab.get("y", 0))))
|
||
if dist < int(_ability_range.get("min", 0)) or dist > int(_ability_range.get("max", 999)):
|
||
continue
|
||
# Linear and LOS checks — applied independently of the distance range check.
|
||
if not src_pos_ab.is_empty():
|
||
var ux := int(pos.get("x", 0)); var uy := int(pos.get("y", 0))
|
||
var sx := int(src_pos_ab.get("x", 0)); var sy := int(src_pos_ab.get("y", 0))
|
||
if linear_only and not _is_linear(sx, sy, ux, uy): continue
|
||
if requires_los and not _client_has_los(sx, sy, ux, uy): continue
|
||
_add_highlight(pos.get("x", 0), pos.get("y", 0), "ability")
|
||
|
||
|
||
## Returns true if the unit passes all client-evaluable filters.
|
||
## Spatial filters (withinrange, isadjacenttosource) are checked here so the
|
||
## highlight matches what the server will accept.
|
||
func _unit_passes_filters(unit: Dictionary, filters: Array) -> bool:
|
||
if filters.is_empty(): return true
|
||
var src := Game.get_unit_by_id(_ability_unit_id)
|
||
var src_pos : Dictionary = src.get("position", {})
|
||
for f: Dictionary in filters:
|
||
match f.get("$type", ""):
|
||
"withinrange":
|
||
if src_pos.is_empty(): return false
|
||
var tgt_pos : Dictionary = unit.get("position", {})
|
||
if tgt_pos.is_empty(): return false
|
||
var dist := (absi(int(tgt_pos.get("x", 0)) - int(src_pos.get("x", 0))) +
|
||
absi(int(tgt_pos.get("y", 0)) - int(src_pos.get("y", 0))))
|
||
if dist < int(f.get("min", 0)) or dist > int(f.get("max", 999)):
|
||
return false
|
||
"isadjacenttosource":
|
||
if src_pos.is_empty(): return false
|
||
var tgt_pos : Dictionary = unit.get("position", {})
|
||
if tgt_pos.is_empty(): return false
|
||
var dist := (absi(int(tgt_pos.get("x", 0)) - int(src_pos.get("x", 0))) +
|
||
absi(int(tgt_pos.get("y", 0)) - int(src_pos.get("y", 0))))
|
||
if dist != 1: return false
|
||
# Check ability-level target conditions (e.g. IsOnTileWithAffinity for card abilities).
|
||
for cond: Dictionary in _ability_target_conditions:
|
||
match cond.get("$type", ""):
|
||
"IsOnTileWithAffinity":
|
||
var upos : Dictionary = unit.get("position", {})
|
||
if upos.is_empty(): return false
|
||
var tile : Dictionary = Game.get_tile(int(upos.get("x", 0)), int(upos.get("y", 0)))
|
||
if tile.get("affinity", "") != cond.get("affinity", ""):
|
||
return false
|
||
return true
|
||
|
||
|
||
## Returns true if the tile at (tx, ty) passes all client-evaluable tile filters.
|
||
func _tile_passes_filters(tx: int, ty: int, filters: Array) -> bool:
|
||
if filters.is_empty(): return true
|
||
var src := Game.get_unit_by_id(_ability_unit_id)
|
||
var src_pos : Dictionary = src.get("position", {})
|
||
for f: Dictionary in filters:
|
||
match f.get("$type", ""):
|
||
"tilewithinrange":
|
||
if src_pos.is_empty(): return false
|
||
var dist := (absi(tx - int(src_pos.get("x", 0))) +
|
||
absi(ty - int(src_pos.get("y", 0))))
|
||
if dist < int(f.get("min", 0)) or dist > int(f.get("max", 999)):
|
||
return false
|
||
return true
|
||
|
||
|
||
## Returns true if (tx, ty) lies on the same row, column, or diagonal as (sx, sy).
|
||
## Matches the server's AbilityRange.LinearOnly validation.
|
||
func _is_linear(sx: int, sy: int, tx: int, ty: int) -> bool:
|
||
return sx == tx or sy == ty or absi(tx - sx) == absi(ty - sy)
|
||
|
||
|
||
## Returns true if there is an unobstructed line of sight from (sx, sy) to (tx, ty).
|
||
## Uses the same supercover DDA algorithm as the server's LineOfSight.HasLos.
|
||
## Any unit occupying an intermediate tile blocks LOS (source and destination excluded).
|
||
func _client_has_los(sx: int, sy: int, tx: int, ty: int) -> bool:
|
||
if sx == tx and sy == ty: return true
|
||
var dx := tx - sx; var dy := ty - sy
|
||
var nx := absi(dx); var ny := absi(dy)
|
||
var sign_x := 1 if dx > 0 else -1
|
||
var sign_y := 1 if dy > 0 else -1
|
||
var ix := 0; var iy := 0
|
||
var cx := sx; var cy := sy
|
||
while ix < nx or iy < ny:
|
||
var t_x := (float(ix) + 0.5) / nx if nx > 0 else 1e9
|
||
var t_y := (float(iy) + 0.5) / ny if ny > 0 else 1e9
|
||
if t_x < t_y:
|
||
cx += sign_x; ix += 1
|
||
else:
|
||
cy += sign_y; iy += 1
|
||
if cx == tx and cy == ty: break
|
||
var tile := Game.get_tile(cx, cy)
|
||
if not tile.is_empty() and str(tile.get("occupantId", "")) != "":
|
||
return false
|
||
return true
|
||
|
||
|
||
## Show a "Done" button so the player can finish an UpTo selection with fewer than N targets.
|
||
func _show_ability_confirm_btn() -> void:
|
||
_hide_ability_confirm_btn()
|
||
var btn := Button.new()
|
||
btn.text = "Done Selecting"
|
||
btn.add_theme_font_size_override("font_size", 12)
|
||
btn.modulate = Color(0.4, 1.0, 0.5)
|
||
btn.position = Vector2(8, 330)
|
||
btn.size = Vector2(150, 30)
|
||
btn.pressed.connect(func():
|
||
_hide_ability_confirm_btn()
|
||
_ability_cur_action_idx += 1
|
||
_advance_ability_targeting())
|
||
_hud.add_child(btn)
|
||
_ability_confirm_btn = btn
|
||
|
||
|
||
func _hide_ability_confirm_btn() -> void:
|
||
if is_instance_valid(_ability_confirm_btn):
|
||
_ability_confirm_btn.queue_free()
|
||
_ability_confirm_btn = null
|
||
|
||
|
||
## Show a panel of labelled branch buttons for a ChooseOne action.
|
||
func _show_branch_panel(action: Dictionary) -> void:
|
||
_hide_branch_panel()
|
||
var co : Dictionary = action.get("chooseone", {})
|
||
var branches : Array = co.get("branches", [])
|
||
if branches.is_empty(): return
|
||
|
||
var panel := PanelContainer.new()
|
||
panel.position = Vector2(8, 120)
|
||
var vbox := VBoxContainer.new()
|
||
vbox.add_theme_constant_override("separation", 8)
|
||
vbox.custom_minimum_size = Vector2(190, 0)
|
||
|
||
var title := Label.new()
|
||
title.text = "Choose One:"
|
||
title.add_theme_font_size_override("font_size", 13)
|
||
title.add_theme_color_override("font_color", Color(1.0, 0.9, 0.3))
|
||
vbox.add_child(title)
|
||
vbox.add_child(HSeparator.new())
|
||
|
||
for i in branches.size():
|
||
var branch : Dictionary = branches[i] as Dictionary
|
||
var label_text : String = str(branch.get("label", "Option %d" % (i + 1)))
|
||
var btn := Button.new()
|
||
btn.text = label_text
|
||
btn.add_theme_font_size_override("font_size", 12)
|
||
var cap_idx : int = i
|
||
btn.pressed.connect(func():
|
||
_ability_targets.append({
|
||
"actionIndex": _ability_cur_action_idx,
|
||
"branchIndex": cap_idx
|
||
})
|
||
_ability_cur_action_idx += 1
|
||
_hide_branch_panel()
|
||
_advance_ability_targeting())
|
||
vbox.add_child(btn)
|
||
|
||
panel.add_child(vbox)
|
||
_hud.add_child(panel)
|
||
_ability_branch_panel = panel
|
||
|
||
|
||
func _hide_branch_panel() -> void:
|
||
if is_instance_valid(_ability_branch_panel):
|
||
_ability_branch_panel.queue_free()
|
||
_ability_branch_panel = null
|
||
|
||
|
||
## Fire the ability request with all collected targets.
|
||
func _send_ability() -> void:
|
||
if _is_triggered_target:
|
||
_is_triggered_target = false
|
||
var rid := _triggered_request_id
|
||
_triggered_request_id = ""
|
||
Game.send_triggered_target_response(rid, _ability_targets)
|
||
elif not _ability_card_id.is_empty():
|
||
Game.send_play_card_with_targets(_ability_card_id, _ability_targets)
|
||
else:
|
||
Game.send_activate_ability(_ability_unit_id, _ability_idx, _ability_targets)
|
||
_set_mode(Mode.NONE)
|
||
|
||
|
||
## Called when the server pushes a triggered_target_request for this player.
|
||
## Sets up the standard ability-targeting UI re-using the existing ABILITY_TARGET mode.
|
||
func _on_triggered_target_request(req: Dictionary) -> void:
|
||
# If already in a targeting mode, cancel it first to avoid stacking.
|
||
if _mode != Mode.NONE:
|
||
_set_mode(Mode.NONE)
|
||
|
||
_is_triggered_target = true
|
||
_triggered_request_id = str(req.get("requestId", ""))
|
||
_ability_unit_id = str(req.get("sourceInstanceId", ""))
|
||
_ability_idx = -1
|
||
_ability_card_id = ""
|
||
_ability_target_conditions = []
|
||
|
||
# Parse and normalise the action definition sent by the server.
|
||
var action_json : String = str(req.get("actionJson", "{}"))
|
||
var action_raw = JSON.parse_string(action_json)
|
||
if action_raw is Dictionary:
|
||
_ability_def = [_normalize_keys(action_raw)]
|
||
elif action_raw is Array:
|
||
_ability_def = _normalize_keys(action_raw) as Array
|
||
else:
|
||
_ability_def = []
|
||
|
||
var range_json : String = str(req.get("rangeJson", ""))
|
||
if not range_json.is_empty() and range_json != "null":
|
||
var r = JSON.parse_string(range_json)
|
||
_ability_range = _normalize_keys(r) as Dictionary if r is Dictionary else {}
|
||
else:
|
||
_ability_range = {}
|
||
|
||
_ability_targets = []
|
||
_ability_cur_action_idx = 0
|
||
_ability_target_n = 1
|
||
_ability_target_up_to = false
|
||
_ability_targets_this_action = 0
|
||
|
||
_show_triggered_banner(str(req.get("abilityName", "Triggered Ability")))
|
||
_start_ability_targeting()
|
||
|
||
|
||
## Brief top-centre banner indicating a triggered ability needs player input.
|
||
func _show_triggered_banner(ability_name: String) -> void:
|
||
var lbl := Label.new()
|
||
lbl.text = "Triggered: %s — select a target" % ability_name
|
||
lbl.set_anchors_preset(Control.PRESET_TOP_WIDE)
|
||
lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||
lbl.position = Vector2(0, 72)
|
||
lbl.add_theme_font_size_override("font_size", 15)
|
||
lbl.modulate = Color(1.0, 0.85, 0.2)
|
||
_hud.add_child(lbl)
|
||
get_tree().create_timer(4.0).timeout.connect(func() -> void:
|
||
if is_instance_valid(lbl): lbl.queue_free())
|
||
|
||
|
||
## Show a left-side panel to let the player select a player (and optionally a
|
||
## zone) as the ability target.
|
||
func _show_player_panel(scope: String, ownership: String) -> void:
|
||
_hide_player_panel()
|
||
|
||
var panel := PanelContainer.new()
|
||
panel.position = Vector2(8, 180)
|
||
var vbox := VBoxContainer.new()
|
||
vbox.add_theme_constant_override("separation", 8)
|
||
vbox.custom_minimum_size = Vector2(160, 0)
|
||
|
||
var title := Label.new()
|
||
title.text = "Choose Player"
|
||
title.add_theme_font_size_override("font_size", 13)
|
||
title.add_theme_color_override("font_color", Color(0.7, 0.8, 1.0))
|
||
vbox.add_child(title)
|
||
vbox.add_child(HSeparator.new())
|
||
|
||
var my_id : String = Auth.user_id
|
||
var my_name : String = Auth.display_name if not Auth.display_name.is_empty() else "You"
|
||
|
||
var show_self : bool = ownership in ["Owner", "Ally", "Any"]
|
||
var show_enemy : bool = ownership in ["Enemy", "Any"]
|
||
if not show_self and not show_enemy:
|
||
show_self = true
|
||
show_enemy = true
|
||
|
||
if show_self:
|
||
_add_player_option(vbox, my_name, my_id, scope)
|
||
if show_enemy:
|
||
for ep: Dictionary in Game.get_enemy_players():
|
||
var eid : String = str(ep.get("accountId", ""))
|
||
var ename : String = Game.get_display_name(eid)
|
||
_add_player_option(vbox, ename, eid, scope)
|
||
|
||
panel.add_child(vbox)
|
||
_hud.add_child(panel)
|
||
_player_panel = panel
|
||
|
||
|
||
## Add a player row (name + optional zone buttons) to the player panel vbox.
|
||
func _add_player_option(vbox: VBoxContainer, name_: String,
|
||
account_id: String, scope: String) -> void:
|
||
var zone_scopes := ["Hand", "Deck", "Discard", "AnyZone"]
|
||
if scope in zone_scopes:
|
||
# Player name label + zone buttons on the same row.
|
||
var lbl := Label.new()
|
||
lbl.text = name_
|
||
lbl.add_theme_font_size_override("font_size", 12)
|
||
vbox.add_child(lbl)
|
||
|
||
var zone_hbox := HBoxContainer.new()
|
||
zone_hbox.add_theme_constant_override("separation", 4)
|
||
var zones : Array = ["Hand", "Deck", "Discard"] if scope == "AnyZone" else [scope]
|
||
for zone_name : String in zones:
|
||
var zbtn := Button.new()
|
||
zbtn.text = zone_name
|
||
zbtn.add_theme_font_size_override("font_size", 11)
|
||
var cap_id : String = account_id
|
||
zbtn.pressed.connect(func() -> void:
|
||
_ability_targets.append({
|
||
"actionIndex": _ability_cur_action_idx,
|
||
"instanceId": cap_id
|
||
})
|
||
_ability_cur_action_idx += 1
|
||
_advance_ability_targeting())
|
||
zone_hbox.add_child(zbtn)
|
||
vbox.add_child(zone_hbox)
|
||
else:
|
||
# Pure player target — single button with the player's name.
|
||
var btn := Button.new()
|
||
btn.text = name_
|
||
btn.add_theme_font_size_override("font_size", 12)
|
||
var cap_id : String = account_id
|
||
btn.pressed.connect(func() -> void:
|
||
_ability_targets.append({
|
||
"actionIndex": _ability_cur_action_idx,
|
||
"instanceId": cap_id
|
||
})
|
||
_ability_cur_action_idx += 1
|
||
_advance_ability_targeting())
|
||
vbox.add_child(btn)
|
||
|
||
|
||
func _hide_player_panel() -> void:
|
||
if is_instance_valid(_player_panel):
|
||
_player_panel.queue_free()
|
||
_player_panel = null
|
||
|
||
|
||
func _show_unit_detail_popup(unit_id: String) -> void:
|
||
var unit := Game.get_unit_by_id(unit_id)
|
||
if unit.is_empty(): return
|
||
var name_ : String = unit.get("name", "?")
|
||
var type_ : String = unit.get("cardType", "")
|
||
var aff : String = unit.get("affinity", "")
|
||
_ctx_tile_lbl.text = "%s — %s [%s]" % [name_, type_, aff]
|
||
_ctx_unit_lbl.text = "HP %d/%d DEF %d/%d ATK %d MP %d/%d" % [
|
||
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)),
|
||
int(unit.get("currentMp", 0)), int(unit.get("maxMp", 0))]
|
||
var abil_str := ""
|
||
var _raw = unit.get("abilitiesJson")
|
||
var parsed = JSON.parse_string("[]" if _raw == null else str(_raw))
|
||
if parsed is Array:
|
||
for ab: Dictionary in parsed:
|
||
var ab_name := str(ab.get("name", ab.get("Name", "")))
|
||
var ab_desc := str(ab.get("description", ab.get("Description", "")))
|
||
abil_str += "• %s" % ab_name
|
||
if not ab_desc.is_empty():
|
||
abil_str += ": %s" % ab_desc
|
||
abil_str += "\n"
|
||
_ctx_abil_lbl.text = abil_str.strip_edges()
|
||
_ctx_popup.visible = true
|
||
|
||
# ── Hand card ArchSpirit routing ──────────────────────────────────────────────
|
||
|
||
func _on_hand_card_clicked(iid: String, _panel: PanelContainer) -> void:
|
||
# Dedup: the same physical click can arrive twice if a stale queue_freed widget
|
||
# still overlaps the live one (see _rebuild_hand). Ignore the second call in
|
||
# the same engine frame for the same card instance.
|
||
var cf := Engine.get_process_frames()
|
||
if cf == _last_click_frame and _last_click_iid == iid:
|
||
print("[HandClick] dedup suppressed iid=", iid.substr(0,8))
|
||
return
|
||
_last_click_frame = cf
|
||
_last_click_iid = iid
|
||
print("Clicked x times: ", count)
|
||
count += 1
|
||
if not Game.is_my_turn(): return
|
||
|
||
var card := _find_hand_card(iid)
|
||
#print(card.get("name", "name failed"))
|
||
if card.is_empty(): return
|
||
|
||
# ArchSpirit in hand → Ascend or Transition.
|
||
if card.get("cardType", "") == "ArchSpirit":
|
||
var tier : int = int(card.get("tier", 0))
|
||
var cur_tier : int = _get_my_arch_tier()
|
||
if tier == cur_tier + 1:
|
||
_confirm_ascend(card)
|
||
elif tier == 1 and cur_tier >= 1:
|
||
_confirm_transition(card)
|
||
return
|
||
|
||
# Terramorpha → multi-tile flow (only if player can afford it).
|
||
if card.get("cardType", "") == "Terramorpha":
|
||
if Game.get_my_player().get("currentSp", 0) < card.get("spCost", 0):
|
||
return
|
||
_sel_card_id = iid
|
||
_terra_targets = []
|
||
print("_terra Array clean. _terra_count: ", _terra_count)
|
||
_set_mode(Mode.TERRAMORPHA_SELECT)
|
||
_terra_count = _terra_count_for_card(card)
|
||
_clear_highlights()
|
||
_highlight_tiles(_valid_play_tiles(card), "movement")
|
||
return
|
||
|
||
# Ruin — server auto-places it; channel immediately on click.
|
||
if card.get("cardType", "") == "Ruin":
|
||
Game.send_play_card(iid, 0, 0)
|
||
return
|
||
|
||
# Repentance / Instinct — may have an active ability requiring unit target selection.
|
||
if card.get("cardType", "") in ["Repentance", "Instinct"]:
|
||
# Deselect: same card clicked again.
|
||
if (_mode == Mode.ABILITY_TARGET and _ability_card_id == iid) or \
|
||
(_mode == Mode.CARD_FROM_HAND and _sel_card_id == iid):
|
||
_set_mode(Mode.NONE); return
|
||
# Reset when switching from a previous card-targeting mode.
|
||
if _mode in [Mode.CARD_FROM_HAND, Mode.TERRAMORPHA_SELECT] or \
|
||
(_mode == Mode.ABILITY_TARGET and not _ability_card_id.is_empty()):
|
||
_set_mode(Mode.NONE)
|
||
# Parse abilitiesJson for the first Active ability.
|
||
var _abs_v = card.get("abilitiesJson")
|
||
var abs_raw : String = "" if _abs_v == null else _abs_v
|
||
if not abs_raw.is_empty():
|
||
var parsed_variant : Array = JSON.parse_string(abs_raw)
|
||
if parsed_variant is Array:
|
||
var parsed : Array = _normalize_keys(parsed_variant)
|
||
for ab_var: Variant in parsed:
|
||
if not (ab_var is Dictionary): continue
|
||
var ab : Dictionary = ab_var
|
||
if ab.get("type", "").to_lower() != "active" :
|
||
continue
|
||
# Extract target-side activation conditions.
|
||
var tgt_conds : Array = []
|
||
for cv: Variant in ab.get("activationconditions", []):
|
||
if not (cv is Dictionary): continue
|
||
var cd : Dictionary = cv
|
||
if cd.get("subject", "") == "target":
|
||
tgt_conds.append(cd)
|
||
# Enter unit-target selection mode.
|
||
_ability_card_id = iid
|
||
_ability_unit_id = ""
|
||
_ability_idx = 0
|
||
_ability_def = ab.get("actions", [])
|
||
_ability_range = {}
|
||
_ability_target_conditions = tgt_conds
|
||
_ability_targets = []
|
||
_ability_cur_action_idx = 0
|
||
_sel_card_id = iid
|
||
_set_mode(Mode.ABILITY_TARGET)
|
||
_clear_highlights()
|
||
_start_ability_targeting()
|
||
return
|
||
# No active ability — channel immediately.
|
||
Game.send_play_card(iid, 0, 0)
|
||
return
|
||
|
||
# Deselect if same card clicked again.
|
||
if _mode == Mode.CARD_FROM_HAND and _sel_card_id == iid:
|
||
print("Deselect")
|
||
_set_mode(Mode.NONE); return
|
||
|
||
# If switching cards (or coming from TERRAMORPHA_SELECT), explicitly reset
|
||
# so the previous card's scale-up tween is released before entering the new mode.
|
||
if _mode in [Mode.CARD_FROM_HAND, Mode.TERRAMORPHA_SELECT]:
|
||
print("switching cards catch")
|
||
_set_mode(Mode.NONE)
|
||
|
||
# Normal Spirit / Repentance / Instinct.
|
||
_sel_card_id = iid
|
||
_set_mode(Mode.CARD_FROM_HAND)
|
||
_clear_highlights()
|
||
_highlight_tiles(_valid_play_tiles(card), "movement")
|
||
|
||
# ── Hand display ──────────────────────────────────────────────────────────────
|
||
|
||
func _rebuild_hand(hand: Array) -> void:
|
||
# Use remove_child + queue_free (not queue_free alone) so stale widgets are
|
||
# immediately pulled from the GUI tree. queue_free() alone keeps the node in
|
||
# get_children() and receiving input events until end-of-frame; if two state
|
||
# updates arrive in the same frame we'd have two overlapping CardWidgets at the
|
||
# same position → two card_pressed emissions → double _on_hand_card_clicked.
|
||
for c in _hand_cards.get_children():
|
||
_hand_cards.remove_child(c)
|
||
c.queue_free()
|
||
for card: Dictionary in hand:
|
||
_hand_cards.add_child(_make_hand_card(card))
|
||
|
||
|
||
func _make_hand_card(card: Dictionary) -> Control:
|
||
var iid : String = card.get("instanceId", "")
|
||
var def_id : String = str(card.get("cardDefinitionId", ""))
|
||
|
||
var widget : PanelContainer = _CARD_WIDGET_SCENE.instantiate()
|
||
widget.set_meta("card_instance_id", iid)
|
||
|
||
# Use the full CardDefinitionDto from ContentCache so CardWidget gets the
|
||
# assets array (Art2D cdnUrl) and can load card art. Fall back to the
|
||
# instance data if the definition hasn't been synced yet.
|
||
var def := ContentCache.get_definition(def_id)
|
||
if def.is_empty():
|
||
def = card.duplicate()
|
||
|
||
# CardWidget._load_stats reads "movementPoints"; the CardInstanceDto calls
|
||
# it "maxMp", so alias it into the def dict before passing.
|
||
def["movementPoints"] = card.get("maxMp", def.get("movementPoints", null))
|
||
|
||
widget.setup(card, def)
|
||
|
||
# CardWidget emits card_pressed(definition_id); forward as hand-card click.
|
||
widget.card_pressed.connect(func(_def_id: String) -> void:
|
||
_on_hand_card_clicked(iid, widget))
|
||
|
||
return widget
|
||
|
||
|
||
func _refresh_hand_selection() -> void:
|
||
for widget 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 = ((_mode == Mode.CARD_FROM_HAND
|
||
or _mode == Mode.TERRAMORPHA_SELECT)
|
||
and _sel_card_id == iid)
|
||
var prev_sel : bool = widget.get_meta("_sel", false)
|
||
if widget.has_method("set_selected"):
|
||
widget.set_selected(sel)
|
||
# Tween scale on selection change.
|
||
# IMPORTANT: defer the tween + z_index update so they run AFTER the
|
||
# current input event is fully processed. Setting z_index synchronously
|
||
# while a mouse button is held causes Godot 4 to re-evaluate GUI focus
|
||
# and deliver a synthetic second pressed=true event → immediate deselect.
|
||
if sel != prev_sel:
|
||
widget.set_meta("_sel", sel)
|
||
_tween_hand_card.call_deferred(widget, sel)
|
||
|
||
|
||
func _tween_hand_card(widget: Control, sel: bool) -> void:
|
||
if not is_instance_valid(widget): return
|
||
widget.pivot_offset = widget.size * 0.5
|
||
var tw := create_tween()
|
||
if sel:
|
||
tw.tween_property(widget, "scale", Vector2(1.12, 1.12), 0.14)
|
||
widget.z_index = 20
|
||
else:
|
||
tw.tween_property(widget, "scale", Vector2(1.0, 1.0), 0.10)
|
||
widget.z_index = 0
|
||
|
||
|
||
func _find_hand_card(iid: String) -> Dictionary:
|
||
for card: Dictionary in Game.get_hand():
|
||
if card.get("instanceId", "") == iid:
|
||
return card
|
||
return {}
|
||
|
||
# ── HUD update ────────────────────────────────────────────────────────────────
|
||
|
||
func _update_hud(state: Dictionary) -> void:
|
||
var phase : String = state.get("phase", "")
|
||
var turn : int = state.get("turnNumber", 1)
|
||
var is_mine : bool = (not _is_spectating) and Game.is_my_turn()
|
||
var my : Dictionary = Game.get_my_player()
|
||
var opp : Dictionary = Game.get_opponent()
|
||
|
||
_phase_lbl.text = "Phase: %s" % phase
|
||
if _is_spectating:
|
||
var active_id : String = str(state.get("activePlayerAccountId", ""))
|
||
_turn_lbl.text = "Turn %d — Spectating" % turn
|
||
_turn_lbl.modulate = Color(1.0, 0.76, 0.2)
|
||
else:
|
||
_turn_lbl.text = "Turn %d — %s" % [turn, "Your turn" if is_mine else "Opponent's turn"]
|
||
_turn_lbl.modulate = Color(0.4, 1.0, 0.5) if is_mine else Color(1.0, 0.6, 0.6)
|
||
|
||
_sp_lbl.text = "SP: %d" % int(my.get("currentSp", 0))
|
||
_st_lbl.text = "ST: %d" % int(my.get("currentSt", 0))
|
||
_deck_lbl.text = "Deck: %d" % int(my.get("deckCount", 0))
|
||
|
||
_opp_name_lbl.text = Game.get_display_name(str(opp.get("accountId", "")))
|
||
_opp_hand_lbl.text = "Hand: %d" % int(opp.get("handCount", 0))
|
||
_opp_deck_lbl.text = "Deck: %d" % int(opp.get("deckCount", 0))
|
||
|
||
# Turn order strip — visible only in N-player (>2) games.
|
||
var all_players : Array = state.get("players", [])
|
||
if all_players.size() > 2:
|
||
_opp_panel.visible = false
|
||
_turn_order_strip.visible = true
|
||
_rebuild_turn_order_strip(state)
|
||
else:
|
||
_opp_panel.visible = true
|
||
_turn_order_strip.visible = false
|
||
|
||
if _is_spectating:
|
||
_draw_btn.visible = false
|
||
_end_turn_btn.visible = false
|
||
else:
|
||
_draw_btn.visible = (phase == "Draw" and is_mine)
|
||
_end_turn_btn.visible = (phase == "Main" and is_mine)
|
||
_end_turn_btn.disabled = not is_mine
|
||
|
||
if phase == "Placement":
|
||
var my_arch : Dictionary = my.get("archSpirit", {})
|
||
var i_have_placed : bool = not my_arch.is_empty() and my_arch.get("position") != null
|
||
if not i_have_placed:
|
||
_phase_lbl.text = "Phase: Placement — click a tile to place your ArchSpirit"
|
||
if _mode != Mode.PLACEMENT:
|
||
_set_mode(Mode.PLACEMENT)
|
||
_clear_highlights()
|
||
_highlight_tiles(_valid_placement_tiles(), "movement")
|
||
else:
|
||
_phase_lbl.text = "Phase: Placement — waiting for opponent…"
|
||
if _mode == Mode.PLACEMENT:
|
||
_set_mode(Mode.NONE)
|
||
|
||
|
||
## Rebuild the turn-order chip strip for N-player games.
|
||
## One chip per player sorted by seatIndex; highlights the active player,
|
||
## dims eliminated players, and marks the local player as "You".
|
||
func _rebuild_turn_order_strip(state: Dictionary) -> void:
|
||
for c in _turn_order_strip.get_children():
|
||
c.queue_free()
|
||
|
||
var active_id : String = str(state.get("activePlayerAccountId", ""))
|
||
var players : Array = state.get("players", []).duplicate()
|
||
var team_colors : Dictionary = state.get("teamColors", {})
|
||
|
||
# Sort by seatIndex so chips appear in turn order.
|
||
players.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
|
||
return int(a.get("seatIndex", 0)) < int(b.get("seatIndex", 0)))
|
||
|
||
for p: Dictionary in players:
|
||
var pid : String = str(p.get("accountId", ""))
|
||
var is_me : bool = (not _is_spectating) and pid == Auth.user_id
|
||
var is_active : bool = pid == active_id
|
||
var eliminated : bool = bool(p.get("isEliminated", false))
|
||
var team_idx : int = int(p.get("teamIndex", -1))
|
||
var hex_str : String = str(team_colors.get(str(team_idx), ""))
|
||
var display : String = "You" if is_me else Game.get_display_name(pid)
|
||
|
||
var chip := PanelContainer.new()
|
||
chip.custom_minimum_size = Vector2(72, 36)
|
||
chip.self_modulate = Color(1, 1, 1, 0.3 if eliminated else (0.95 if is_active else 0.6))
|
||
chip.mouse_filter = Control.MOUSE_FILTER_STOP
|
||
|
||
# Team-color left border via StyleBoxFlat.
|
||
var style := StyleBoxFlat.new()
|
||
style.bg_color = Color(0.12, 0.12, 0.14, 0.85)
|
||
style.border_width_left = 3
|
||
if not hex_str.is_empty():
|
||
style.border_color = Color.html("#" + hex_str)
|
||
else:
|
||
style.border_color = Color(0.4, 0.4, 0.4)
|
||
chip.add_theme_stylebox_override("panel", style)
|
||
|
||
var lbl := Label.new()
|
||
lbl.text = ("★ " if is_active else "") + display + (" ✗" if eliminated else "")
|
||
lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||
lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
|
||
lbl.add_theme_font_size_override("font_size", 10)
|
||
lbl.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
||
if is_active:
|
||
lbl.add_theme_color_override("font_color", Color(1.0, 0.9, 0.3))
|
||
elif eliminated:
|
||
lbl.add_theme_color_override("font_color", Color(0.4, 0.4, 0.4))
|
||
elif is_me:
|
||
lbl.add_theme_color_override("font_color", Color(0.5, 1.0, 0.5))
|
||
|
||
# Hover tooltip showing player specs (opponents only).
|
||
if not is_me:
|
||
var sp : int = int(p.get("currentSp", 0))
|
||
var st : int = int(p.get("currentSt", 0))
|
||
var hand : int = int(p.get("handCount", 0))
|
||
var deck : int = int(p.get("deckCount", 0))
|
||
chip.tooltip_text = "%s\nSP: %d ST: %d\nHand: %d Deck: %d" % [
|
||
display, sp, st, hand, deck]
|
||
|
||
chip.add_child(lbl)
|
||
_turn_order_strip.add_child(chip)
|
||
|
||
# ── Discard viewer ────────────────────────────────────────────────────────────
|
||
|
||
func _show_own_discard() -> void:
|
||
_show_discard_for("Your Discard", Game.get_my_player().get("discard", []))
|
||
|
||
func _show_opp_discard() -> void:
|
||
_show_discard_for("Opponent Discard", Game.get_opponent().get("discard", []))
|
||
|
||
func _show_discard_for(title: String, cards: Array) -> void:
|
||
_dv_title.text = "%s (%d)" % [title, cards.size()]
|
||
for c in _dv_list.get_children(): c.queue_free()
|
||
if cards.is_empty():
|
||
var lbl := Label.new()
|
||
lbl.text = "(empty)"
|
||
lbl.add_theme_color_override("font_color", Color(0.55, 0.55, 0.6))
|
||
_dv_list.add_child(lbl)
|
||
else:
|
||
for card: Dictionary in cards:
|
||
_dv_list.add_child(_make_discard_row(card))
|
||
_dv_overlay.visible = true
|
||
|
||
func _make_discard_row(card: Dictionary) -> Control:
|
||
var hbox := HBoxContainer.new()
|
||
hbox.add_theme_constant_override("separation", 8)
|
||
hbox.custom_minimum_size = Vector2(0, 32)
|
||
var type_lbl := Label.new()
|
||
type_lbl.text = "[%s]" % card.get("cardType", "?")
|
||
type_lbl.add_theme_font_size_override("font_size", 11)
|
||
type_lbl.add_theme_color_override("font_color", Color(0.6, 0.6, 0.7))
|
||
type_lbl.custom_minimum_size = Vector2(90, 0)
|
||
type_lbl.size_flags_vertical = Control.SIZE_SHRINK_CENTER
|
||
hbox.add_child(type_lbl)
|
||
var name_lbl := Label.new()
|
||
name_lbl.text = card.get("name", "Unknown")
|
||
name_lbl.add_theme_font_size_override("font_size", 13)
|
||
name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
||
name_lbl.size_flags_vertical = Control.SIZE_SHRINK_CENTER
|
||
hbox.add_child(name_lbl)
|
||
var aff_lbl := Label.new()
|
||
aff_lbl.text = card.get("affinity", "")
|
||
aff_lbl.add_theme_font_size_override("font_size", 11)
|
||
aff_lbl.add_theme_color_override("font_color", Color(0.6, 0.7, 0.85))
|
||
aff_lbl.size_flags_vertical = Control.SIZE_SHRINK_CENTER
|
||
hbox.add_child(aff_lbl)
|
||
return hbox
|
||
|
||
# ── Hold timer → context popup ────────────────────────────────────────────────
|
||
|
||
func _on_hold_timer_fired() -> void:
|
||
if _held_coord.x < 0: return
|
||
var tile := Game.get_tile(_held_coord.x, _held_coord.y)
|
||
if tile.is_empty(): return
|
||
var aff : String = tile.get("resolvedAffinity", "Void")
|
||
_ctx_tile_lbl.text = "Tile (%d,%d) — %s" % [_held_coord.x, _held_coord.y, aff]
|
||
var _raw_occ = 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 := 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 := ""
|
||
var _raw_abil_hud = unit.get("abilitiesJson")
|
||
var parsed = JSON.parse_string("[]" if _raw_abil_hud == null else str(_raw_abil_hud))
|
||
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 ─────────────────────────────────────────────────────────────────
|
||
|
||
func _on_game_over(winner_id: String, win_condition: String,
|
||
winner_delta: int, loser_delta: int,
|
||
player_outcomes: Array = []) -> void:
|
||
var i_won : bool = (winner_id == Auth.user_id)
|
||
_go_result_lbl.text = "Victory!" if i_won else "Defeat"
|
||
_go_result_lbl.modulate = Color(0.4, 1.0, 0.5) if i_won else Color(1.0, 0.4, 0.4)
|
||
|
||
if not player_outcomes.is_empty():
|
||
# N-player: show each player's rank delta
|
||
var outcome_lines : Array = []
|
||
for po: Dictionary in player_outcomes:
|
||
var pid : String = str(po.get("accountId", ""))
|
||
var oc : String = str(po.get("outcome", "?"))
|
||
var rd : int = int(po.get("rankDelta", 0))
|
||
var sign : String = "+" if rd >= 0 else ""
|
||
var label: String = "You" if pid == Auth.user_id else Game.get_display_name(pid)
|
||
outcome_lines.append("%s: %s (%s%d)" % [label, oc, sign, rd])
|
||
_go_rank_lbl.text = "[%s]
|
||
" % win_condition + "
|
||
".join(outcome_lines)
|
||
else:
|
||
var my_delta : int = winner_delta if i_won else loser_delta
|
||
_go_rank_lbl.text = "Win by %s | Rank %s%d" % [
|
||
win_condition, "+" if my_delta >= 0 else "", my_delta]
|
||
_go_overlay.visible = true
|
||
|
||
|
||
func _on_session_abandoned(_reason: String) -> void:
|
||
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")
|
||
|
||
|
||
## Pushed when the opponent (active player) has been inactive ≥ 5 minutes.
|
||
## Offer the player a choice: accept forfeit or continue waiting.
|
||
func _on_opponent_inactive(_sid: String) -> void:
|
||
var dialog := ConfirmationDialog.new()
|
||
dialog.title = "Opponent Inactive"
|
||
dialog.dialog_text = (
|
||
"Your opponent has not acted for 5 minutes.\n"
|
||
+ "Do you want to claim their forfeit?"
|
||
)
|
||
dialog.ok_button_text = "Accept Forfeit"
|
||
dialog.cancel_button_text = "Wait"
|
||
add_child(dialog)
|
||
dialog.confirmed.connect(func() -> void:
|
||
dialog.queue_free()
|
||
Game.send_force_concede()
|
||
)
|
||
dialog.canceled.connect(func() -> void:
|
||
dialog.queue_free()
|
||
)
|
||
dialog.popup_centered()
|
||
|
||
|
||
## Pushed when the local player is the inactive one — warn them.
|
||
func _on_inactive_warning(_sid: String) -> void:
|
||
var dialog := AcceptDialog.new()
|
||
dialog.title = "Inactivity Warning"
|
||
dialog.dialog_text = (
|
||
"You have been inactive for 5 minutes.\n"
|
||
+ "Your opponent may claim a forfeit."
|
||
)
|
||
add_child(dialog)
|
||
dialog.confirmed.connect(func() -> void: dialog.queue_free())
|
||
dialog.popup_centered()
|
||
|
||
|
||
## Pushed when both players have been idle for 10 minutes.
|
||
## Closes any open inactive dialog and shows a Wait-only prompt to both players.
|
||
func _on_both_idle_warning(_sid: String) -> void:
|
||
# Close any lingering inactive dialogs from tier-1.
|
||
for child in get_children():
|
||
if child is ConfirmationDialog or child is AcceptDialog:
|
||
child.queue_free()
|
||
|
||
var dialog := AcceptDialog.new()
|
||
dialog.title = "Both Players Idle"
|
||
dialog.dialog_text = (
|
||
"Both players have been idle for 10 minutes.\n"
|
||
+ "Please return to continue the game."
|
||
)
|
||
dialog.ok_button_text = "Wait"
|
||
add_child(dialog)
|
||
dialog.confirmed.connect(func() -> void: dialog.queue_free())
|
||
dialog.popup_centered()
|
||
|
||
# ── State → scene ─────────────────────────────────────────────────────────────
|
||
|
||
|
||
## Pushed when a player is knocked out mid-game (FFA / team game continues).
|
||
func _on_player_eliminated(session_id: String, elim_id: String, _seat_idx: int, _team_idx: int) -> void:
|
||
if session_id != Game.session_id: return
|
||
var is_me : bool = elim_id == Auth.user_id
|
||
var msg : String = (
|
||
"You have been eliminated!
|
||
You can continue watching the game as a spectator."
|
||
if is_me
|
||
else "Player %s has been eliminated from the game!" % Game.get_display_name(elim_id))
|
||
var dlg := AcceptDialog.new()
|
||
dlg.title = "Player Eliminated"
|
||
dlg.dialog_text = msg
|
||
add_child(dlg)
|
||
dlg.confirmed.connect(func() -> void: dlg.queue_free())
|
||
dlg.popup_centered()
|
||
# If the local player was eliminated, switch to read-only spectator view.
|
||
if is_me:
|
||
_is_spectating = true
|
||
_setup_spectator_ui()
|
||
|
||
func _on_state_updated(state: Dictionary) -> void:
|
||
print("[StateUpdate] phase=", state.get("phase","?"),
|
||
" mode=", _mode, " sel_card=",
|
||
_sel_card_id.substr(0, 8) if not _sel_card_id.is_empty() else "none")
|
||
_rebuild_ownership(state)
|
||
|
||
# Orient camera behind the local player's row on the first state with playerOneAccountId.
|
||
var p1_id : String = str(state.get("playerOneAccountId", ""))
|
||
if not p1_id.is_empty():
|
||
# Update P1/P2 flag every time — used for model facing on full rebuild.
|
||
_local_is_p1 = Auth.user_id.to_lower() == p1_id.to_lower()
|
||
if not _camera_oriented and not p1_id.is_empty():
|
||
_camera_oriented = true
|
||
var bw := float(Game.board_width())
|
||
var bh := float(Game.board_height())
|
||
var max_dim :Variant = max(bw, bh)
|
||
# Auto-scale camera distance: larger boards need more distance to see the whole layout.
|
||
_cam_distance = clampf(max(max_dim, 10.0) * 1.5, 12.0, 30.0)
|
||
# Pivot shifts the look-at point toward the local player so their row stays
|
||
# near the bottom-center of the screen above the hand panel.
|
||
var pivot_len := clampf(max_dim * 0.2, 1.0, 5.0)
|
||
|
||
# Use the local player's starting zone to derive camera yaw for N-player boards.
|
||
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():
|
||
# Compute world-space centroid of this player's starting tiles.
|
||
var cx := 0.0; var cz_v := 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()
|
||
# Yaw places the camera behind the player's zone, looking toward the center.
|
||
_cam_yaw = rad_to_deg(atan2(cx, cz_v))
|
||
var len2d := sqrt(cx * cx + cz_v * cz_v)
|
||
if len2d > 0.001:
|
||
_cam_pivot = Vector3(cx / len2d * pivot_len, 0.0, cz_v / len2d * pivot_len)
|
||
else:
|
||
# Legacy / no-zone fallback: P1 row at -Z, P2 at +Z.
|
||
if _local_is_p1:
|
||
_cam_yaw = 180.0
|
||
_cam_pivot = Vector3(0.0, 0.0, -pivot_len)
|
||
else:
|
||
_cam_pivot = Vector3(0.0, 0.0, pivot_len)
|
||
_apply_camera()
|
||
|
||
var board : Dictionary = state.get("board", {})
|
||
if _tile_bodies.is_empty() and not board.is_empty():
|
||
_build_board(board)
|
||
elif not board.is_empty():
|
||
for tile: Dictionary in board.get("tiles", []):
|
||
var c : Dictionary = tile.get("coord", {})
|
||
_update_tile_affinity(c.get("x", 0), c.get("y", 0),
|
||
tile.get("resolvedAffinity", "Void"))
|
||
|
||
# ── Fire animations on existing nodes before rebuild destroys them ────────
|
||
var move_dur : float = _play_move_animations(state)
|
||
var dmg_played : bool = _play_damage_animations(state)
|
||
|
||
# ── Immediate UI update (hand / HUD don't need to wait for animations) ────
|
||
var hand := Game.get_hand()
|
||
print("[GameScreen] state phase=", state.get("phase","?"),
|
||
" my_player_found=", not Game.get_my_player().is_empty(),
|
||
" hand_size=", hand.size(),
|
||
" my_id=", Auth.user_id.substr(0,8))
|
||
_rebuild_hand(hand)
|
||
_update_hud(state)
|
||
|
||
# ── Update position/HP tracking now so the next state update is correct ───
|
||
_update_prev_state(state)
|
||
|
||
# ── Schedule delayed board rebuild to let animations finish ───────────────
|
||
var delay := move_dur
|
||
if dmg_played:
|
||
delay = maxf(delay, POST_ANIM_SECS)
|
||
_schedule_rebuild(state, delay)
|
||
|
||
# ── Selection preservation (immediate — highlights are tile overlays) ──────
|
||
# After a state update, preserve hand-card and unit selections where possible.
|
||
# A state push from the server (e.g. opponent action, draw echo) must not
|
||
# silently clear tile highlights that the player just set up.
|
||
match _mode:
|
||
Mode.NONE, Mode.PLACEMENT:
|
||
pass # placement highlights are managed in _update_hud above
|
||
|
||
Mode.CARD_FROM_HAND, Mode.TERRAMORPHA_SELECT:
|
||
# Keep selection only if the card is still in our hand.
|
||
var sel_card := _find_hand_card(_sel_card_id)
|
||
if sel_card.is_empty():
|
||
print("[StateUpdate] selected card gone — clearing mode")
|
||
_set_mode(Mode.NONE)
|
||
else:
|
||
# Re-apply highlights: board/units may have changed.
|
||
print("[StateUpdate] preserving CARD_FROM_HAND, re-highlighting")
|
||
_clear_highlights()
|
||
_highlight_tiles(_valid_play_tiles(sel_card), "movement")
|
||
_refresh_hand_selection() # mark the (new) widget as selected
|
||
|
||
_:
|
||
# Unit selected, sacrifice, ability — clear these on any state change
|
||
# because unit positions / health / eligibility may have changed.
|
||
_set_mode(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()
|
||
|
||
# ── Action buttons ────────────────────────────────────────────────────────────
|
||
|
||
func _on_draw_pressed() -> void: Game.send_draw()
|
||
func _on_end_turn_pressed() -> void: _set_mode(Mode.NONE); Game.send_end_turn()
|