From 7d5bd6cbd85bfbea5a64a297720cfd851e7a0da8 Mon Sep 17 00:00:00 2001 From: dingo Date: Tue, 5 May 2026 11:58:09 -0400 Subject: [PATCH] Legal docs draft and Client refactor --- .../game/components/board/board_controller.gd | 276 + .../components/board/board_controller.gd.uid | 1 + .../game/components/board/pathfinder.gd | 229 + .../game/components/board/pathfinder.gd.uid | 1 + .../components/board/tile_target_resolver.gd | 305 + .../board/tile_target_resolver.gd.uid | 1 + .../components/camera/camera_controller.gd | 110 + .../camera/camera_controller.gd.uid | 1 + .../environment/skybox_controller.gd | 438 + .../environment/skybox_controller.gd.uid | 1 + .../scenes/game/components/game_constants.gd | 86 + .../game/components/game_constants.gd.uid | 1 + .../game/components/hud/hand_manager.gd | 506 ++ .../game/components/hud/hand_manager.gd.uid | 1 + .../game/components/hud/hud_controller.gd | 304 + .../game/components/hud/hud_controller.gd.uid | 1 + .../scenes/game/components/hud/tile_drawer.gd | 513 ++ .../game/components/hud/tile_drawer.gd.uid | 1 + .../components/input/board_input_handler.gd | 366 + .../input/board_input_handler.gd.uid | 1 + .../components/overlays/game_over_overlay.gd | 47 + .../overlays/game_over_overlay.gd.uid | 1 + .../components/overlays/inactive_dialogs.gd | 72 + .../overlays/inactive_dialogs.gd.uid | 1 + .../components/selection/ability_targeting.gd | 688 ++ .../selection/ability_targeting.gd.uid | 1 + .../selection/selection_controller.gd | 558 ++ .../selection/selection_controller.gd.uid | 1 + .../selection/server_prompt_handler.gd | 514 ++ .../selection/server_prompt_handler.gd.uid | 1 + .../game/components/units/unit_animator.gd | 712 ++ .../components/units/unit_animator.gd.uid | 1 + .../components/units/unit_mesh_builder.gd | 514 ++ .../components/units/unit_mesh_builder.gd.uid | 1 + .../game/components/units/unit_registry.gd | 121 + .../components/units/unit_registry.gd.uid | 1 + .../origin-client/scenes/game/game_screen.gd | 7068 ++--------------- .../scenes/game/game_screen_revamp_plan.md | 620 ++ Shared/legal/ccpa.md | 120 + Shared/legal/cookie-policy.md | 124 + Shared/legal/coppa.md | 99 + Shared/legal/eula.md | 111 + Shared/legal/gdpr.md | 148 + Shared/legal/payment-compliance.md | 118 + Shared/legal/privacy-policy.md | 175 + Shared/legal/terms-of-service.md | 148 + 46 files changed, 8873 insertions(+), 6235 deletions(-) create mode 100644 Client/origin-client/scenes/game/components/board/board_controller.gd create mode 100644 Client/origin-client/scenes/game/components/board/board_controller.gd.uid create mode 100644 Client/origin-client/scenes/game/components/board/pathfinder.gd create mode 100644 Client/origin-client/scenes/game/components/board/pathfinder.gd.uid create mode 100644 Client/origin-client/scenes/game/components/board/tile_target_resolver.gd create mode 100644 Client/origin-client/scenes/game/components/board/tile_target_resolver.gd.uid create mode 100644 Client/origin-client/scenes/game/components/camera/camera_controller.gd create mode 100644 Client/origin-client/scenes/game/components/camera/camera_controller.gd.uid create mode 100644 Client/origin-client/scenes/game/components/environment/skybox_controller.gd create mode 100644 Client/origin-client/scenes/game/components/environment/skybox_controller.gd.uid create mode 100644 Client/origin-client/scenes/game/components/game_constants.gd create mode 100644 Client/origin-client/scenes/game/components/game_constants.gd.uid create mode 100644 Client/origin-client/scenes/game/components/hud/hand_manager.gd create mode 100644 Client/origin-client/scenes/game/components/hud/hand_manager.gd.uid create mode 100644 Client/origin-client/scenes/game/components/hud/hud_controller.gd create mode 100644 Client/origin-client/scenes/game/components/hud/hud_controller.gd.uid create mode 100644 Client/origin-client/scenes/game/components/hud/tile_drawer.gd create mode 100644 Client/origin-client/scenes/game/components/hud/tile_drawer.gd.uid create mode 100644 Client/origin-client/scenes/game/components/input/board_input_handler.gd create mode 100644 Client/origin-client/scenes/game/components/input/board_input_handler.gd.uid create mode 100644 Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd create mode 100644 Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd.uid create mode 100644 Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd create mode 100644 Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd.uid create mode 100644 Client/origin-client/scenes/game/components/selection/ability_targeting.gd create mode 100644 Client/origin-client/scenes/game/components/selection/ability_targeting.gd.uid create mode 100644 Client/origin-client/scenes/game/components/selection/selection_controller.gd create mode 100644 Client/origin-client/scenes/game/components/selection/selection_controller.gd.uid create mode 100644 Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd create mode 100644 Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd.uid create mode 100644 Client/origin-client/scenes/game/components/units/unit_animator.gd create mode 100644 Client/origin-client/scenes/game/components/units/unit_animator.gd.uid create mode 100644 Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd create mode 100644 Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd.uid create mode 100644 Client/origin-client/scenes/game/components/units/unit_registry.gd create mode 100644 Client/origin-client/scenes/game/components/units/unit_registry.gd.uid create mode 100644 Client/origin-client/scenes/game/game_screen_revamp_plan.md create mode 100644 Shared/legal/ccpa.md create mode 100644 Shared/legal/cookie-policy.md create mode 100644 Shared/legal/coppa.md create mode 100644 Shared/legal/eula.md create mode 100644 Shared/legal/gdpr.md create mode 100644 Shared/legal/payment-compliance.md create mode 100644 Shared/legal/privacy-policy.md create mode 100644 Shared/legal/terms-of-service.md diff --git a/Client/origin-client/scenes/game/components/board/board_controller.gd b/Client/origin-client/scenes/game/components/board/board_controller.gd new file mode 100644 index 0000000..1d19f69 --- /dev/null +++ b/Client/origin-client/scenes/game/components/board/board_controller.gd @@ -0,0 +1,276 @@ +class_name BoardController +extends Node + +var tile_bodies: Dictionary = {} +var tile_heights: Dictionary = {} +var tile_y_bases: Dictionary = {} +var tile_visual_tops: Dictionary = {} + +# Set by parent +var tiles_root: Node3D = null +var units_root: Node3D = null +var hi_root: Node3D = null +var pathfinder: Pathfinder = null +var cursor_highlight_ref: MeshInstance3D = null +var hover_team_overlay_ref: MeshInstance3D = null + + +func build_board(board: Dictionary) -> void: + pathfinder.grid_type = board.get("gridType", "Square") + pathfinder.hex_sides = int(board.get("hexSides", 0)) + 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_ref and c != hover_team_overlay_ref: + c.queue_free() + tile_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: Vector3 = pathfinder.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 shape_key_chk: String = "Hex" if pathfinder.grid_type == "Hexagon" else "Square" + var has_model: bool = not ContentCache.get_tile_model_url(affinity, shape_key_chk).is_empty() + var rng: RandomNumberGenerator = 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 = 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 = CollisionShape3D.new() + var mi: MeshInstance3D = MeshInstance3D.new() + if pathfinder.grid_type == "Hexagon": + var cyl: CylinderMesh = CylinderMesh.new() + cyl.radial_segments = 6 + cyl.top_radius = GameConstants.HEX_TILE_RADIUS * GameConstants.HEX_TILE_SPACING + cyl.bottom_radius = GameConstants.HEX_TILE_RADIUS * GameConstants.HEX_TILE_SPACING + cyl.height = h + mi.mesh = cyl + var cshape: CylinderShape3D = CylinderShape3D.new() + cshape.radius = GameConstants.HEX_TILE_RADIUS * GameConstants.HEX_TILE_SPACING + cshape.height = h + shape.shape = cshape + else: + var box: BoxShape3D = BoxShape3D.new() + box.size = Vector3(0.98, h, 0.98) + shape.shape = box + var bm: BoxMesh = BoxMesh.new() + bm.size = Vector3(0.98, h, 0.98) + mi.mesh = bm + body.add_child(shape) + + # Placeholder: affinity-coloured mesh, swapped out if a 3D model loads. + var mat: StandardMaterial3D = StandardMaterial3D.new() + mat.albedo_color = GameConstants.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 shape_key: String = "Hex" if pathfinder.grid_type == "Hexagon" else "Square" + var model_url: String = ContentCache.get_tile_model_url(affinity, shape_key) + if model_url.is_empty(): + if pathfinder.grid_type == "Hexagon": + # No hex model — keep the affinity-coloured cylinder placeholder. + # Still attach a hex stalagmite below if one is available. + if want_bottom: + var bottom_url: String = ContentCache.get_random_tile_bottom_url("Hex") + if not bottom_url.is_empty(): + try_load_tile_bottom(weakref(body), bottom_url) + return + # Square: apply a 2D texture and attach a stalagmite bottom. + var tex_url: String = 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: String = ContentCache.get_random_tile_bottom_url("Square") + 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: StaticBody3D = 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: AABB = 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(shape_key) + 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: StaticBody3D = 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.75) + + # 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: AABB = model_local_aabb(bottom_node) + if btm_aabb.size != Vector3.ZERO: + var scaled_h: float = 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 = 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 = Image.new() + var ext: String = 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 = ImageTexture.create_from_image(img) + var mat: StandardMaterial3D = 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: 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: float = tile_size / footprint + model.scale = Vector3.ONE * s + var c: Vector3 = 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 = AABB() + var first: bool = 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: 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: StaticBody3D = 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: StandardMaterial3D = child.material_override as StandardMaterial3D + if mat: mat.albedo_color = GameConstants.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) diff --git a/Client/origin-client/scenes/game/components/board/board_controller.gd.uid b/Client/origin-client/scenes/game/components/board/board_controller.gd.uid new file mode 100644 index 0000000..1691d2f --- /dev/null +++ b/Client/origin-client/scenes/game/components/board/board_controller.gd.uid @@ -0,0 +1 @@ +uid://di6lk8rawljgn diff --git a/Client/origin-client/scenes/game/components/board/pathfinder.gd b/Client/origin-client/scenes/game/components/board/pathfinder.gd new file mode 100644 index 0000000..bcb8b24 --- /dev/null +++ b/Client/origin-client/scenes/game/components/board/pathfinder.gd @@ -0,0 +1,229 @@ +class_name Pathfinder +extends Node + +## Encapsulates board math, raycasting, and grid pathfinding. +## +## Must be added as a child of GameScreen (or any Node3D that owns a World3D). +## Set camera, grid_type, and hex_sides before use. + +# Must be set by parent before use. +var camera: Camera3D = null +var grid_type: String = "Square" +var hex_sides: int = 0 + +# ── Coord helpers ───────────────────────────────────────────────────────────── + +## Convert grid coordinate (x, y) to world-space Vector3. +func coord_to_world(x: int, y: int) -> Vector3: + if grid_type == "Hexagon": + var N: int = hex_sides + var q: float = x - (N - 1) + var r: float = y - (N - 1) + var wx: float = GameConstants.HEX_TILE_SPACING * sqrt(3.0) * (q + r * 0.5) + var wz: float = GameConstants.HEX_TILE_SPACING * 1.5 * r + return Vector3(wx, 0.0, wz) + return Vector3( + x * GameConstants.TILE_SPACING - (Game.board_width() - 1) * GameConstants.TILE_SPACING * 0.5, 0.0, + y * GameConstants.TILE_SPACING - (Game.board_height() - 1) * GameConstants.TILE_SPACING * 0.5) + + +## Raycast from camera through mouse_pos and return the tile coord, or Vector2i(-1,-1). +## tile_bodies: the "x,y" → StaticBody3D dictionary owned by GameScreen. +func mouse_to_tile_coord(mouse_pos: Vector2, tile_bodies: Dictionary) -> Vector2i: + var body: PhysicsBody3D = 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 + if body.has_meta("unit_id"): + var unit_id: String = str(body.get_meta("unit_id")) + if not unit_id.is_empty(): + var unit: Dictionary = Game.get_unit_by_id(unit_id) + if not unit.is_empty(): + var pos: Dictionary = unit.get("position", {}) as Dictionary + if not pos.is_empty(): + return Vector2i(int(pos.get("x", -1)), int(pos.get("y", -1))) + return Vector2i(-1, -1) + + +## Raycast from camera through mouse_pos and return the unit instance ID, or "". +func mouse_to_unit_id(mouse_pos: Vector2) -> String: + var body: PhysicsBody3D = raycast_body(mouse_pos) + if body == null: + return "" + if body.has_meta("unit_id"): + return str(body.get_meta("unit_id")) + return "" + + +## Raycast from camera through mouse_pos into the scene's physics world. +## Returns the first PhysicsBody3D hit, or null. +func raycast_body(mouse_pos: Vector2) -> PhysicsBody3D: + var space: PhysicsDirectSpaceState3D = get_tree().get_root().get_world_3d().direct_space_state + var from: Vector3 = camera.project_ray_origin(mouse_pos) + var to: Vector3 = from + camera.project_ray_normal(mouse_pos) * 100.0 + var query: PhysicsRayQueryParameters3D = PhysicsRayQueryParameters3D.create(from, to) + var result: Dictionary = space.intersect_ray(query) + if result.is_empty(): + return null + return result.get("collider") as PhysicsBody3D + +# ── BFS pathfinding ─────────────────────────────────────────────────────────── + +## BFS on the game grid using the correct neighbour set for the current grid type. +## blocked: Dictionary[Vector2i → true] of impassable tiles; +## the destination 'to' is always reachable regardless. +## tile_bodies: the "x,y" → StaticBody3D dictionary owned by GameScreen. +## 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, tile_bodies: Dictionary) -> Array[Vector2i]: + if from == to: + return [] + var bw: int = Game.board_width() + var bh: int = Game.board_height() + var DIRS: Array[Vector2i] + if grid_type == "Hexagon": + DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1), + Vector2i(1,-1), Vector2i(-1,1)] + else: + DIRS = [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: Array = 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: Vector2i = 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 + + +## BFS reachable set — returns all coords reachable within max_mp steps, +## treating blocked_coords as impassable walls (destination included in check). +## tile_bodies: the "x,y" → StaticBody3D dictionary owned by GameScreen. +## Mirrors Pathfinding.GetReachableWithCost on the server. +func bfs_reachable(fx: int, fy: int, max_mp: int, blocked_coords: Dictionary, tile_bodies: Dictionary) -> Array: + var bw: int = Game.board_width() + var bh: int = Game.board_height() + var DIRS: Array[Vector2i] + if grid_type == "Hexagon": + DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1), + Vector2i(1,-1), Vector2i(-1,1)] + else: + DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)] + var cost: Dictionary = { Vector2i(fx, fy): 0 } + var queue: Array = [Vector2i(fx, fy)] + while not queue.is_empty(): + var cur: Vector2i = queue.pop_front() + var cur_cost: int = cost[cur] + if cur_cost >= max_mp: + continue + for d: Vector2i in DIRS: + var nxt: Vector2i = 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 cost.has(nxt): + continue + if blocked_coords.has(nxt): + continue + cost[nxt] = cur_cost + 1 + queue.append(nxt) + var results: Array = [] + for coord in cost.keys(): + if coord != Vector2i(fx, fy): + results.append(coord) + return results + + +## Manhattan distance on square grids; cube-coordinate distance on hexagonal grids. +func board_distance(x1: int, y1: int, x2: int, y2: int) -> int: + if grid_type == "Hexagon": + var N: int = hex_sides + var dq: int = (x1 - (N - 1)) - (x2 - (N - 1)) + var dr: int = (y1 - (N - 1)) - (y2 - (N - 1)) + return (abs(dq) + abs(dr) + abs(dq + dr)) / 2 + return abs(x1 - x2) + abs(y1 - y2) + + +## Line-of-sight check between two grid coordinates. +## Returns true if no occupied tile blocks the line from (sx,sy) to (tx,ty). +func client_has_los(sx: int, sy: int, tx: int, ty: int) -> bool: + if sx == tx and sy == ty: + return true + if grid_type == "Hexagon": + var N: int = hex_sides + var aq: int = sx - (N - 1); var ar: int = sy - (N - 1) + var bq: int = tx - (N - 1); var br: int = ty - (N - 1) + var as_: int = -aq - ar; var bs: int = -bq - br + var n: int = board_distance(sx, sy, tx, ty) + if n == 0: + return true + for i in range(1, n): + var t: float = float(i) / float(n) + var fq: float = aq + (bq - aq) * t + var fr: float = ar + (br - ar) * t + var fs: float = as_ + (bs - as_) * t + var rq: int = roundi(fq) + var rr: int = roundi(fr) + var rs: int = roundi(fs) + if rq + rr + rs != 0: + var eq: float = abs(rq - fq) + var er: float = abs(rr - fr) + var es: float = abs(rs - fs) + if eq >= er and eq >= es: + rq = -rr - rs + elif er >= es: + rr = -rq - rs + else: + rs = -rq - rr + var cx: int = rq + (N - 1) + var cy: int = rr + (N - 1) + var tile: Dictionary = Game.get_tile(cx, cy) + if not tile.is_empty() and str(tile.get("occupantId", "")) != "": + return false + return true + # Square: supercover DDA + var dx: int = tx - sx + var dy: int = ty - sy + var nx: int = absi(dx) + var ny: int = absi(dy) + var sign_x: int = 1 if dx > 0 else -1 + var sign_y: int = 1 if dy > 0 else -1 + var ix: int = 0 + var iy: int = 0 + var cx: int = sx + var cy: int = sy + while ix < nx or iy < ny: + var t_x: float = (float(ix) + 0.5) / nx if nx > 0 else 1e9 + var t_y: float = (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: Dictionary = Game.get_tile(cx, cy) + if not tile.is_empty() and str(tile.get("occupantId", "")) != "": + return false + return true diff --git a/Client/origin-client/scenes/game/components/board/pathfinder.gd.uid b/Client/origin-client/scenes/game/components/board/pathfinder.gd.uid new file mode 100644 index 0000000..0b39b55 --- /dev/null +++ b/Client/origin-client/scenes/game/components/board/pathfinder.gd.uid @@ -0,0 +1 @@ +uid://p60mlwa5sywi diff --git a/Client/origin-client/scenes/game/components/board/tile_target_resolver.gd b/Client/origin-client/scenes/game/components/board/tile_target_resolver.gd new file mode 100644 index 0000000..c549ddb --- /dev/null +++ b/Client/origin-client/scenes/game/components/board/tile_target_resolver.gd @@ -0,0 +1,305 @@ +class_name TileTargetResolver +extends Node + +## Computes valid tile/unit target sets for all game actions. +## +## Requires pathfinder and unit_registry to be set before any method is called. +## tile_bodies must be passed into methods that need physics-body existence checks +## (the "x,y" → StaticBody3D dictionary owned by GameScreen). + +var pathfinder: Pathfinder = null +var unit_registry: UnitRegistry = null + +# ── Spirit card play targets ────────────────────────────────────────────────── + +## Returns the array of Vector2i coords that are valid play targets for the given hand card. +## tile_bodies: "x,y" → StaticBody3D dict from GameScreen. +func valid_play_tiles(card: Dictionary, tile_bodies: 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: Variant = arch.get("minChannelRange") + var raw_max: Variant = 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 = pathfinder.board_distance(tx, ty, ax, ay) + if dist < min_r or dist > max_r: + continue + var tile: Dictionary = Game.get_tile(tx, ty) + print("tile", tile) + print("[GettingAff]", card_affinity) + if not unit_registry.tile_has_blocking_occupant(tile): + continue + if card_affinity != "" and not tile_matches_channel_affinity(tile, card_affinity): + continue + results.append(Vector2i(tx, ty)) + + "Terramorpha": + for tx in range(bw): + for ty in range(bh): + if not tile_bodies.has("%d,%d" % [tx, ty]): + continue + results.append(Vector2i(tx, ty)) + + "Repentance", "Instinct", "Ruin": + pass # No tile target — played directly (server handles placement for Ruins, repentance and Instinct have own target systems). + + return results + + +## Returns the number of tile targets a Terramorpha card requires. +func terra_count_for_card(card: Dictionary) -> int: + match card.get("terramorphaMode", ""): + "Mono": return 1 + "Di": return 2 + "Tri": return 3 + return 1 + + +## Returns true when the tile's resolved affinity matches the card affinity for channelling. +func tile_matches_channel_affinity(tile: Dictionary, card_affinity: String) -> bool: + var resolved_affinity: String = str(tile.get("resolvedAffinity", "Void")) + print("[AFFINITY_TILE]", resolved_affinity, card_affinity) + if resolved_affinity == "PerfectAether" and card_affinity in ["Lake", "Hill", "Forest", "Field"]: + return true + if resolved_affinity == "UnstableAether": + return false + if card_affinity in ["Lake", "Hill", "Forest", "Field"]: + var base1: String = str(tile.get("base1", "Void")) + var base2: String = str(tile.get("base2", "Void")) + return base1 == card_affinity or base2 == card_affinity + return resolved_affinity == card_affinity + +# ── Unit movement targets ───────────────────────────────────────────────────── + +## Returns the array of Vector2i coords that are valid destinations for a unit move. +## tile_bodies: "x,y" → StaticBody3D dict from GameScreen. +func valid_move_tiles(unit: Dictionary, tile_bodies: Dictionary) -> Array: + var pos: Dictionary = unit.get("position", {}) + if pos.is_empty(): + return [] + var ux: int = pos.get("x", 0) + var uy: int = pos.get("y", 0) + var mp: int = unit.get("currentMp", 0) + var mov: String = str(unit.get("movementType", "Walk")).to_lower() + if not bool(unit.get("canMove", false)): + return [] + if mp <= 0: + return [] + + var bw: int = Game.board_width() + var bh: int = Game.board_height() + + # Walk / Flight: BFS — can't pass through blocked tiles + if mov == "walk" or mov == "flight": + # Build blocked set from all occupants, excluding this unit. + var blocked: Dictionary = {} + var extra_obstructors: Dictionary = unit_registry.units_obstructing_movement_type(mov) + var moving_id: String = str(unit.get("instanceId", "")) + for unit_dict: Dictionary in unit_registry.all_board_units(): + var up: Dictionary = unit_dict.get("position", {}) + if up.is_empty(): + continue + var iid: String = str(unit_dict.get("instanceId", "")) + if iid == moving_id: + continue + var cx: int = up.get("x", 0) + var cy: int = up.get("y", 0) + if cx == ux and cy == uy: + continue # don't block own tile + # Flight is blocked by other Flight units or explicit movement obstructors. + if mov == "flight": + var blocks_flight: bool = str(unit_dict.get("movementType", "Walk")).to_lower() == "flight" + if not blocks_flight and not extra_obstructors.has(iid): + continue + blocked[Vector2i(cx, cy)] = true + return pathfinder.bfs_reachable(ux, uy, mp, blocked, tile_bodies) + + # Jump / Teleport: land on any unoccupied tile. Teleport also requires LOS. + var results: Array = [] + if mov != "jump" and mov != "teleport": + return results + for tx in range(bw): + for ty in range(bh): + if not tile_bodies.has("%d,%d" % [tx, ty]): + continue + if tx == ux and ty == uy: + continue + if unit_registry.tile_has_blocking_occupant(Game.get_tile(tx, ty)): + continue + # Teleport additionally requires LOS to the destination. + if mov == "teleport" and not pathfinder.client_has_los(ux, uy, tx, ty): + continue + results.append(Vector2i(tx, ty)) + return results + +# ── Attack targets ──────────────────────────────────────────────────────────── + +## Returns the position Dictionaries of all valid attack targets for a unit. +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 = int(unit.get("minAttackRange") or 1) + var max_r: int = int(unit.get("maxAttackRange") or 1) + var needs_los: bool = bool(unit.get("attackRequiresLos", false)) + if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0: + return results + for t: Dictionary in Game.get_all_enemy_units(): + if unit_registry.is_ruin_unit(t): + continue + if not t.get("canBeAttacked", true): + continue + var _tpos: Variant = t.get("position") + if not (_tpos is Dictionary): + continue + var tp: Dictionary = _tpos + if tp.is_empty(): + continue + var tx: int = tp.get("x", 0) + var ty: int = tp.get("y", 0) + var dist: int = pathfinder.board_distance(tx, ty, ux, uy) + if dist < min_r or dist > max_r: + continue + if needs_los and not pathfinder.client_has_los(ux, uy, tx, ty): + continue + results.append(tp) + return results + + +## Returns the instance IDs of all valid attack target units for a unit. +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 = int(unit.get("minAttackRange") or 1) + var max_r: int = int(unit.get("maxAttackRange") or 1) + var needs_los: bool = bool(unit.get("attackRequiresLos", false)) + if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0: + return results + for t: Dictionary in Game.get_all_enemy_units(): + if not t.get("canBeAttacked", true): + continue + var tp: Dictionary = t.get("position", {}) + if tp.is_empty(): + continue + var tx: int = tp.get("x", 0) + var ty: int = tp.get("y", 0) + var dist: int = pathfinder.board_distance(tx, ty, ux, uy) + if dist < min_r or dist > max_r: + continue + if needs_los and not pathfinder.client_has_los(ux, uy, tx, ty): + continue + 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. +## tile_bodies: "x,y" → StaticBody3D dict from GameScreen. +func attack_range_tiles(unit: Dictionary, tile_bodies: 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) + var needs_los: bool = bool(unit.get("attackRequiresLos", false)) + 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 = pathfinder.board_distance(tx, ty, ux, uy) + if dist < min_r or dist > max_r: + continue + if needs_los and not pathfinder.client_has_los(ux, uy, tx, ty): + continue + results.append(Vector2i(tx, ty)) + return results + +# ── Placement targets ───────────────────────────────────────────────────────── + +## Returns valid ArchSpirit placement tiles for the local player. +func valid_placement_tiles() -> Array: + var results: Array = [] + var my_id: String = 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 + +# ── Sacrifice targets ───────────────────────────────────────────────────────── + +## 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(): + if unit_registry.is_ruin_unit(unit): + continue + 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 pathfinder.board_distance(ux, uy, ax, ay) == 1: + results.append(unit) + return results diff --git a/Client/origin-client/scenes/game/components/board/tile_target_resolver.gd.uid b/Client/origin-client/scenes/game/components/board/tile_target_resolver.gd.uid new file mode 100644 index 0000000..e03dd45 --- /dev/null +++ b/Client/origin-client/scenes/game/components/board/tile_target_resolver.gd.uid @@ -0,0 +1 @@ +uid://s23snjfooow7 diff --git a/Client/origin-client/scenes/game/components/camera/camera_controller.gd b/Client/origin-client/scenes/game/components/camera/camera_controller.gd new file mode 100644 index 0000000..b48c182 --- /dev/null +++ b/Client/origin-client/scenes/game/components/camera/camera_controller.gd @@ -0,0 +1,110 @@ +class_name CameraController +extends Node + +signal deactivate_touch_modes_requested() +signal orbit_btn_toggled(pressed: bool) +signal pan_btn_toggled(pressed: bool) +signal zoom_btn_toggled(pressed: bool) + +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 cam_tween: Tween = null + +# Set by parent +var camera_rig: Node3D = null +var camera: Camera3D = null +var cam_ctrl_panel: Control = null +var cam_orbit_btn: Button = null +var cam_pan_btn: Button = null +var cam_zoom_btn: Button = null + + +func apply_camera() -> void: + var pitch_rad: float = 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_modes_requested.emit() + + +func on_cam_orbit_btn_toggled(pressed: bool) -> void: + if pressed: + cam_pan_btn.set_pressed_no_signal(false) + cam_zoom_btn.set_pressed_no_signal(false) + orbit_btn_toggled.emit(pressed) + + +func on_cam_pan_btn_toggled(pressed: bool) -> void: + if pressed: + cam_orbit_btn.set_pressed_no_signal(false) + cam_zoom_btn.set_pressed_no_signal(false) + pan_btn_toggled.emit(pressed) + + +func on_cam_zoom_btn_toggled(pressed: bool) -> void: + if pressed: + cam_orbit_btn.set_pressed_no_signal(false) + cam_pan_btn.set_pressed_no_signal(false) + zoom_btn_toggled.emit(pressed) + + +func on_cam_gesture_timer_fired(gesture_finger_count: int) -> void: + if Settings.touch_camera_mode != "gesture": + return + match gesture_finger_count: + 1: + orbit_btn_toggled.emit(true) + pan_btn_toggled.emit(false) + zoom_btn_toggled.emit(false) + 2: + zoom_btn_toggled.emit(true) + orbit_btn_toggled.emit(false) + pan_btn_toggled.emit(false) + 3: + pan_btn_toggled.emit(true) + orbit_btn_toggled.emit(false) + zoom_btn_toggled.emit(false) + + +func apply_orbit(delta: Vector2) -> void: + cam_yaw -= delta.x * 0.4 + cam_pitch = clampf(cam_pitch + delta.y * 0.3, 15.0, 75.0) + apply_camera() + + +func apply_pan(delta: Vector2, cam_dist: float) -> void: + var ps: float = cam_dist * 0.0015 + var right: Vector3 = camera_rig.global_basis.x * delta.x * ps + var fwd: Vector3 = Vector3(camera_rig.global_basis.z.x, 0.0, camera_rig.global_basis.z.z).normalized() + cam_pivot += right + fwd * -delta.y * ps + var pan_lim: float = clampf(max(float(Game.board_width()), float(Game.board_height())) * GameConstants.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() + + +func tween_to_pivot(target: Vector3) -> void: + if cam_tween != null: + cam_tween.kill() + cam_tween = create_tween() + cam_tween.tween_method(_set_pivot, cam_pivot, target, 0.35).set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT) + + +func _set_pivot(pos: Vector3) -> void: + cam_pivot = pos + apply_camera() diff --git a/Client/origin-client/scenes/game/components/camera/camera_controller.gd.uid b/Client/origin-client/scenes/game/components/camera/camera_controller.gd.uid new file mode 100644 index 0000000..4b34ca8 --- /dev/null +++ b/Client/origin-client/scenes/game/components/camera/camera_controller.gd.uid @@ -0,0 +1 @@ +uid://ciuhvyg4j67vc diff --git a/Client/origin-client/scenes/game/components/environment/skybox_controller.gd b/Client/origin-client/scenes/game/components/environment/skybox_controller.gd new file mode 100644 index 0000000..c1e88c0 --- /dev/null +++ b/Client/origin-client/scenes/game/components/environment/skybox_controller.gd @@ -0,0 +1,438 @@ +class_name SkyboxController +extends Node + +## Manages all skybox modes: procedural, CDN panoramic/animated, cubemap, +## and the live activity-feed star field. +## +## Call setup_environment() from game_screen._ready(). +## Call process_sky_rotation(delta) from game_screen._process(delta). +## Call cleanup() from game_screen._exit_tree(). + +var skybox_sky: Sky = null +var skybox_frames: Array = [] +var skybox_frame_idx: int = 0 +var skybox_timer: Timer = null +var stars: Dictionary = {} +var ambient_star_timer: Timer = null +var ambient_star_ctr: int = 0 + +# Set by parent before setup_environment() is called. +var world_environment: WorldEnvironment = null + +# ── Setup ───────────────────────────────────────────────────────────────────── + +func setup_environment() -> void: + var env: Environment = Environment.new() + skybox_sky = Sky.new() + env.background_mode = Environment.BG_SKY + env.sky = skybox_sky + env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY + world_environment.environment = env + + match Settings.skybox_mode: + "live": + setup_live_skybox(env) + "cdn": + setup_procedural_sky(env) + apply_skybox_from_cache() + _: + setup_procedural_sky(env) + + 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 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 = 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 world_environment.environment + if e != null: + e.ambient_light_energy = 0.6 + + +## Near-black star sky — shown for "live" mode. +func setup_live_skybox(env: Environment) -> void: + clear_stars() + var proc: ProceduralSkyMaterial = 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: Variant in ids: + add_star(str(sid), true), + func(code: String, msg: String) -> void: + push_warning("[SkyboxController] subscribe_activity failed — %s: %s" % [code, msg])) + + start_ambient_star_cycle() + + +func on_skybox_setting_changed() -> void: + 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: Environment = world_environment.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) + +# ── Ambient star cycle ──────────────────────────────────────────────────────── + +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() + + +func on_ambient_star_timer() -> void: + var fake_id: String = "~ambient~%d" % ambient_star_ctr + ambient_star_ctr += 1 + add_star(fake_id, false) + get_tree().create_timer(randf_range(15.0, 30.0)).timeout.connect( + func() -> void: remove_star(fake_id)) + start_ambient_star_cycle() + +# ── Star helpers ────────────────────────────────────────────────────────────── + +func session_star_pos(session_id: String) -> Vector3: + var rng: RandomNumberGenerator = RandomNumberGenerator.new() + rng.seed = session_id.hash() + var theta: float = rng.randf() * TAU + var phi: float = rng.randf_range(0.15, 0.85) * PI + var r: float = 280.0 + return Vector3(r * sin(phi) * cos(theta), r * cos(phi), r * sin(phi) * sin(theta)) + + +func add_star(session_id: String, instant: bool) -> void: + if stars.has(session_id): + return + var mesh: MeshInstance3D = MeshInstance3D.new() + var sphere: SphereMesh = SphereMesh.new() + sphere.radius = 0.6 + sphere.height = 1.2 + sphere.radial_segments = 6 + sphere.rings = 4 + mesh.mesh = sphere + var mat: StandardMaterial3D = StandardMaterial3D.new() + mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED + mat.emission_enabled = true + mat.emission = Color(0.85, 0.90, 1.0) + 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: Tween = 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)) + + +func start_star_twinkle(mesh: MeshInstance3D) -> void: + if not is_instance_valid(mesh): + return + var mat: StandardMaterial3D = mesh.material_override as StandardMaterial3D + var rng: RandomNumberGenerator = RandomNumberGenerator.new() + rng.seed = hash(mesh.global_position.x) + var period: float = rng.randf_range(2.0, 5.5) + var tw: Tween = 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) + + +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: StandardMaterial3D = mesh.material_override as StandardMaterial3D + var tw: Tween = 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) + + +func clear_stars() -> void: + for mesh: Variant in stars.values(): + if is_instance_valid(mesh): + (mesh as MeshInstance3D).queue_free() + stars.clear() + +# ── CDN skybox ──────────────────────────────────────────────────────────────── + +func apply_skybox_from_cache() -> void: + var skybox: Dictionary = ContentCache.get_random_skybox() + if skybox.is_empty(): + print("[SkyboxController] No active skybox — keeping procedural sky.") + return + var sky_type: String = str(skybox.get("type", "Panoramic")) + print("[SkyboxController] 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: + var urls: Array = [ + 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) + var pending: Array = [6] + for i: int in 6: + var idx: int = 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 + var http: HTTPRequest = HTTPRequest.new() + add_child(http) + http.request_completed.connect(func(_res: int, code: int, _hdrs: PackedStringArray, data: PackedByteArray) -> void: + http.queue_free() + if code >= 200 and code < 300 and not data.is_empty(): + var img: Image = Image.new() + var ext: String = 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("[SkyboxController] Cubemap face %d decode failed (ext=%s)" % [idx, ext]) + images[idx] = null + else: + push_warning("[SkyboxController] 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: + var images: Array[Image] = [] + images.resize(6) + var face_size: int = 1 + for i: int in 6: + if raw[i] is Image: + face_size = (raw[i] as Image).get_width() + break + for i: int in 6: + if raw[i] is Image: + var img: Image = raw[i] as Image + 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: + var placeholder: Image = Image.create(face_size, face_size, false, Image.FORMAT_RGB8) + placeholder.fill(Color.BLACK) + images[i] = placeholder + var cubemap: Cubemap = Cubemap.new() + var err: Error = cubemap.create_from_images(images) + if err != OK: + push_warning("[SkyboxController] Cubemap.create_from_images failed: %d" % err) + return + apply_cubemap_material(cubemap) + + +func apply_cubemap_material(cubemap: Cubemap) -> void: + var shader: 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 = ShaderMaterial.new() + mat.shader = shader + mat.set_shader_parameter("environment", cubemap) + var new_sky: Sky = Sky.new() + new_sky.sky_material = mat + skybox_sky = new_sky + world_environment.environment.sky = new_sky + world_environment.environment.background_mode = Environment.BG_SKY + print("[SkyboxController] Cubemap sky applied.") + + +func load_static_skybox(url: String) -> void: + var http: HTTPRequest = 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("[SkyboxController] Failed to download skybox: HTTP %d" % code) + return + var img: Image = Image.new() + var clean_url: String = url.split("?")[0] + var ext: String = 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("[SkyboxController] Failed to decode skybox image (ext=%s)" % ext) + return + var tex: ImageTexture = ImageTexture.create_from_image(img) + var mat: PanoramaSkyMaterial = PanoramaSkyMaterial.new() + mat.panorama = tex + if is_instance_valid(skybox_sky): + skybox_sky.sky_material = mat + print("[SkyboxController] 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: int in frame_count: + var url: String = "%s/%d.png" % [base_url, i] + var http: HTTPRequest = HTTPRequest.new() + var frame_idx: int = 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 = 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: Variant = 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) + +# ── Per-frame ───────────────────────────────────────────────────────────────── + +func process_sky_rotation(delta: float) -> void: + var env: Environment = world_environment.environment as Environment + if env != null: + env.sky_rotation.y += delta * GameConstants.SKY_ROTATION_SPEED + +# ── Cleanup ─────────────────────────────────────────────────────────────────── + +func cleanup() -> void: + 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 + 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() + if Game.game_activity.is_connected(on_game_activity): + Game.game_activity.disconnect(on_game_activity) + if Settings.settings_changed.is_connected(on_skybox_setting_changed): + Settings.settings_changed.disconnect(on_skybox_setting_changed) diff --git a/Client/origin-client/scenes/game/components/environment/skybox_controller.gd.uid b/Client/origin-client/scenes/game/components/environment/skybox_controller.gd.uid new file mode 100644 index 0000000..dfcd169 --- /dev/null +++ b/Client/origin-client/scenes/game/components/environment/skybox_controller.gd.uid @@ -0,0 +1 @@ +uid://bei06l62sfffw diff --git a/Client/origin-client/scenes/game/components/game_constants.gd b/Client/origin-client/scenes/game/components/game_constants.gd new file mode 100644 index 0000000..4a6539b --- /dev/null +++ b/Client/origin-client/scenes/game/components/game_constants.gd @@ -0,0 +1,86 @@ +class_name GameConstants + +# ── 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), +} + +# ── Highlight colors ────────────────────────────────────────────────────────── + +const HI_GREEN: Color = Color(0.20, 0.90, 0.20, 0.40) +const HI_RED: Color = Color(1.00, 0.25, 0.25, 0.50) +const HI_BLUE: Color = Color(0.20, 0.50, 1.00, 0.40) +const HI_YELLOW: Color = Color(1.00, 0.85, 0.10, 0.50) +const HI_ORANGE: Color = Color(1.00, 0.60, 0.10, 0.45) + +# ── Hitsplat ────────────────────────────────────────────────────────────────── + +const HITSPLAT_LIFETIME: float = 0.75 +const HITSPLAT_RISE_PIXELS: float = 42.0 + +# ── Tile / board geometry ───────────────────────────────────────────────────── + +## Grid spacing: 1.0 tile + 0.1 gap between tiles (visual only). +const TILE_SPACING: float = 1.1 +const HEX_TILE_RADIUS: float = 0.5774 # ≈ 1/√3 — flat-to-flat = TILE_SPACING +const HEX_TILE_SPACING: float = TILE_SPACING * 0.5 # hex boards use tighter spacing + +# ── Animation timing ────────────────────────────────────────────────────────── + +## 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 + +# ── Unit SFX ────────────────────────────────────────────────────────────────── + +const UNIT_SFX_KEYS: Array = [ + "moveSoundUrl", + "attackSoundUrl", + "damagedSoundUrl", + "deathSoundUrl", + "blockedSoundUrl", +] + +# ── Animation aliases ───────────────────────────────────────────────────────── + +## 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"], +} + +# ── Skybox ──────────────────────────────────────────────────────────────────── + +const SKY_ROTATION_SPEED: float = 0.026 # rad/sec — ~4 min per full revolution diff --git a/Client/origin-client/scenes/game/components/game_constants.gd.uid b/Client/origin-client/scenes/game/components/game_constants.gd.uid new file mode 100644 index 0000000..bb80982 --- /dev/null +++ b/Client/origin-client/scenes/game/components/game_constants.gd.uid @@ -0,0 +1 @@ +uid://dveqey2ixrmyb diff --git a/Client/origin-client/scenes/game/components/hud/hand_manager.gd b/Client/origin-client/scenes/game/components/hud/hand_manager.gd new file mode 100644 index 0000000..a3c3900 --- /dev/null +++ b/Client/origin-client/scenes/game/components/hud/hand_manager.gd @@ -0,0 +1,506 @@ +class_name HandManager +extends Node + +signal hand_card_clicked(card_data: Dictionary) + +# ── Preloaded resources ─────────────────────────────────────────────────────── + +const _CARD_WIDGET_SCENE: PackedScene = preload("res://scenes/collection/components/CardWidget.tscn") +const _HAND_ARROW_REGULAR: Texture2D = preload("res://ui/icons/Green_Gem_Arrow_Button_Regular.png") +const _HAND_ARROW_HOVER: Texture2D = preload("res://ui/icons/Green_Gem_Arrow_Button_Hover.png") +const _HAND_ARROW_PRESSED: Texture2D = preload("res://ui/icons/Green_Gem_Arrow_Button_Click.png") + +# ── Hand state ──────────────────────────────────────────────────────────────── + +var hand_focus_index: int = 0 +var hand_scroll_time: float = 0.0 +var hand_hover_iid: String = "" +var cached_hand_iids: Array = [] +var pending_popup_cards: Array = [] +var popup_layer: CanvasLayer = null +var sel_card_id: String = "" # set by selection_controller to highlight + +# ── Node refs (set from parent) ─────────────────────────────────────────────── + +var hand_cards: Control = null +var hand_area: PanelContainer = null +var hand_spin_left: TextureButton = null +var hand_spin_right: TextureButton = null +var hud: CanvasLayer = null + +# ── Public API ──────────────────────────────────────────────────────────────── + +## Called by game_screen when the hand card clicked event fires. +## Emits hand_card_clicked so game_screen can handle routing logic. +func on_hand_card_clicked(iid: String, _panel: PanelContainer) -> void: + var card: Dictionary = find_hand_card(iid) + if card.is_empty(): + return + emit_signal("hand_card_clicked", card) + + +func rebuild_hand(hand: Array, is_spectating: bool) -> void: + # Build new IID list. + var new_iids: Array = [] + for card: Dictionary in hand: + var raw_iid: Variant = card.get("instanceId") + new_iids.append(str(raw_iid) if raw_iid != null else "") + if new_iids == cached_hand_iids: + refresh_hand_selection() + return + + cached_hand_iids = new_iids + + # Spectators have no playable hand — just clear any stale widgets and stop. + if is_spectating: + apply_display_hand([]) + return + + # Detect brand-new cards (not in previous server hand, not already queued). + var pending_iids: Array = [] + for c: Dictionary in pending_popup_cards: + pending_iids.append(c.get("instanceId", "") as String) + + var brand_new: Array = [] + if Settings.draw_card_popup: + for card: Dictionary in hand: + var iid: String = card.get("instanceId", "") + if iid not in cached_hand_iids and iid not in pending_iids: + brand_new.append(card) + + # Drop pending popups for cards that left the hand (avoid typed-array filter). + var kept: Array = [] + for c: Dictionary in pending_popup_cards: + if c.get("instanceId", "") in new_iids: + kept.append(c) + pending_popup_cards = kept + + # Queue brand-new cards for popup; exclude them from the live hand display. + for card: Dictionary in brand_new: + pending_popup_cards.append(card) + + var popup_iids: Array = [] + for c: Dictionary in pending_popup_cards: + popup_iids.append(c.get("instanceId", "") as String) + + # Build the display hand (everything except cards waiting in popup queue). + var display_hand: Array = [] + for card: Dictionary in hand: + if card.get("instanceId", "") not in popup_iids: + display_hand.append(card) + + apply_display_hand(display_hand) + + # Kick off popup for the first pending card if nothing is showing yet. + if not pending_popup_cards.is_empty() and (popup_layer == null or not popup_layer.visible): + show_next_card_popup() + + +func apply_display_hand(hand: Array) -> void: + if hand.is_empty(): + for c in hand_cards.get_children(): + hand_cards.remove_child(c) + c.queue_free() + hand_focus_index = 0 + hand_hover_iid = "" + sync_hand_spin_buttons() + return + + # Map existing widgets by IID so we can reuse them. + var existing: Dictionary = {} + for child in hand_cards.get_children(): + if child.has_meta("card_instance_id"): + existing[str(child.get_meta("card_instance_id"))] = child + + var hand_iids: Array = [] + for card: Dictionary in hand: + hand_iids.append(card.get("instanceId", "") as String) + + # Remove widgets for cards no longer in the display hand. + for iid: String in existing.keys(): + if iid not in hand_iids: + var w: Node = existing[iid] + existing.erase(iid) + hand_cards.remove_child(w) + w.queue_free() + + # Add widgets for new cards, update _fan_slot on all. + var slot: int = 0 + for card: Dictionary in hand: + var iid: String = card.get("instanceId", "") + if not existing.has(iid): + var widget: Control = make_hand_card(card) + widget.set_meta("_fan_slot", slot) + hand_cards.add_child(widget) + else: + (existing[iid] as Control).set_meta("_fan_slot", slot) + slot += 1 + + hand_focus_index = posmod(hand_focus_index, hand.size()) + queue_hand_layout() + sync_hand_spin_buttons() + + +func show_next_card_popup() -> void: + if pending_popup_cards.is_empty(): + return + var card: Dictionary = pending_popup_cards[0] + + # Create (or reuse) a dedicated CanvasLayer above the HUD. + if popup_layer == null or not is_instance_valid(popup_layer): + popup_layer = CanvasLayer.new() + popup_layer.layer = 20 + get_parent().add_child(popup_layer) + + # Clear any previous content. + for c in popup_layer.get_children(): + c.queue_free() + popup_layer.visible = true + + # Dim background — catches clicks that miss the card. + var bg: ColorRect = ColorRect.new() + bg.color = Color(0.0, 0.0, 0.0, 0.65) + bg.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + bg.mouse_filter = Control.MOUSE_FILTER_STOP + popup_layer.add_child(bg) + + # Centred column: label + card. + var vbox: VBoxContainer = VBoxContainer.new() + vbox.set_anchors_preset(Control.PRESET_CENTER) + vbox.grow_horizontal = Control.GROW_DIRECTION_BOTH + vbox.grow_vertical = Control.GROW_DIRECTION_BOTH + vbox.alignment = BoxContainer.ALIGNMENT_CENTER + popup_layer.add_child(vbox) + vbox.add_theme_constant_override("separation", 16) + + var lbl: Label = Label.new() + lbl.text = "Card Drawn — click to add to hand" + lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + vbox.add_child(lbl) + lbl.add_theme_font_size_override("font_size", 16) + + var widget: PanelContainer = _CARD_WIDGET_SCENE.instantiate() + widget.custom_minimum_size = Vector2(200, 320) + widget.mouse_filter = Control.MOUSE_FILTER_STOP + var def_id: String = str(card.get("cardDefinitionId", "")) + var def: Dictionary = ContentCache.get_definition(def_id) + if def.is_empty(): + def = card.duplicate() + def["movementPoints"] = card.get("maxMp", def.get("movementPoints", null)) + widget.setup(card, def) + vbox.add_child(widget) + + # Either clicking the card or the background dismisses the popup. + bg.gui_input.connect(func(ev: InputEvent) -> void: + if ev is InputEventMouseButton and (ev as InputEventMouseButton).pressed: + dismiss_card_popup()) + widget.card_pressed.connect(func(_id: String) -> void: dismiss_card_popup()) + + +func dismiss_card_popup() -> void: + if pending_popup_cards.is_empty(): + return + var card: Dictionary = pending_popup_cards.pop_front() + + # Hide the overlay. + if is_instance_valid(popup_layer): + popup_layer.visible = false + + # Build the updated display hand: currently shown widgets + this newly added card. + var display_iids: Array = [] + for child in hand_cards.get_children(): + if child.has_meta("card_instance_id"): + display_iids.append(str(child.get_meta("card_instance_id"))) + display_iids.append(card.get("instanceId", "") as String) + + # Reconstruct display hand in server order (from cached_hand_iids). + var display_hand: Array = [] + for iid: String in cached_hand_iids: + if iid in display_iids: + # Find the card dict; use the drawn card if it matches. + if iid == card.get("instanceId", ""): + display_hand.append(card) + else: + # Pull from live Game hand for existing cards. + for hc: Dictionary in Game.get_hand(): + if hc.get("instanceId", "") == iid: + display_hand.append(hc) + break + + apply_display_hand(display_hand) + + # Show next queued popup if any. + if not pending_popup_cards.is_empty(): + show_next_card_popup() + + +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.top_level = false + widget.anchor_left = 0.0 + widget.anchor_top = 0.0 + widget.anchor_right = 0.0 + widget.anchor_bottom = 0.0 + widget.position = Vector2.ZERO + widget.size = widget.custom_minimum_size + widget.visible = true + 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: Dictionary = 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. + # Note: focus_hand_card is intentionally NOT called here — clicking a card + # brings it to front visually (via selection z_index boost) without shifting + # its position in the fan rotation. + widget.card_pressed.connect(func(_def_id: String) -> void: + on_hand_card_clicked(iid, widget)) + + return widget + + +func refresh_hand_selection() -> void: + var needs_layout: bool = false + 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 = sel_card_id == iid and not sel_card_id.is_empty() + 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 != bool(widget.get_meta("_sel", false)): + widget.set_meta("_sel", sel) + needs_layout = true + if needs_layout: + queue_hand_layout() + + +func tween_hand_card(widget: Control, sel: bool) -> void: + if not is_instance_valid(widget): + return + widget.set_meta("_sel", sel) + queue_hand_layout() + + +func find_hand_card(iid: String) -> Dictionary: + for card: Dictionary in Game.get_hand(): + if card.get("instanceId", "") == iid: + return card + return {} + + +func configure_hand_spin_buttons() -> void: + hand_spin_left.texture_normal = _HAND_ARROW_REGULAR + hand_spin_left.texture_hover = _HAND_ARROW_HOVER + hand_spin_left.texture_pressed = _HAND_ARROW_PRESSED + hand_spin_left.modulate = Color(1, 1, 1, 0.92) + hand_spin_left.focus_mode = Control.FOCUS_NONE + hand_spin_left.rotation_degrees = 0.0 + + hand_spin_right.texture_normal = _HAND_ARROW_REGULAR + hand_spin_right.texture_hover = _HAND_ARROW_HOVER + hand_spin_right.texture_pressed = _HAND_ARROW_PRESSED + hand_spin_right.modulate = Color(1, 1, 1, 0.92) + hand_spin_right.focus_mode = Control.FOCUS_NONE + hand_spin_right.rotation_degrees = 0.0 + layout_hand_spin_buttons() + + +func layout_hand_spin_buttons() -> void: + hand_spin_left.anchor_left = 0.0 + hand_spin_left.anchor_top = 0.5 + hand_spin_left.anchor_right = 0.0 + hand_spin_left.anchor_bottom = 0.5 + hand_spin_left.offset_left = 8.0 + hand_spin_left.offset_top = -22.0 + hand_spin_left.offset_right = 52.0 + hand_spin_left.offset_bottom = 22.0 + hand_spin_left.custom_minimum_size = Vector2(44, 44) + hand_spin_left.size = Vector2(44, 44) + + hand_spin_right.anchor_left = 1.0 + hand_spin_right.anchor_top = 0.5 + hand_spin_right.anchor_right = 1.0 + hand_spin_right.anchor_bottom = 0.5 + hand_spin_right.offset_left = -52.0 + hand_spin_right.offset_top = -22.0 + hand_spin_right.offset_right = -8.0 + hand_spin_right.offset_bottom = 22.0 + hand_spin_right.custom_minimum_size = Vector2(44, 44) + hand_spin_right.size = Vector2(44, 44) + + +func sync_hand_spin_buttons() -> void: + var enabled: bool = hand_cards.get_child_count() > 1 + hand_spin_left.visible = enabled + hand_spin_right.visible = enabled + hand_spin_left.disabled = not enabled + hand_spin_right.disabled = not enabled + + +func spin_hand(direction: int) -> void: + var card_count: int = hand_cards.get_child_count() + if card_count <= 1: + return + hand_focus_index = posmod(hand_focus_index + direction, card_count) + layout_hand_cards() + + +func focus_hand_card(iid: String) -> void: + var idx: int = 0 + for widget in hand_cards.get_children(): + if str(widget.get_meta("card_instance_id", "")) == iid: + hand_focus_index = idx + layout_hand_cards() + return + idx += 1 + + +func queue_hand_layout() -> void: + if not is_inside_tree(): + return + layout_hand_cards.call_deferred() + + +func layout_hand_cards() -> void: + var widgets: Array = hand_cards.get_children() + var widget_count: int = widgets.size() + if widget_count == 0: + return + + hand_focus_index = posmod(hand_focus_index, widget_count) + hand_cards.position = Vector2.ZERO + hand_cards.size = hand_area.size + var viewport_size: Vector2 = hand_area.size + if viewport_size.x <= 0.0 or viewport_size.y <= 0.0: + return + + var sample: Control = widgets[0] as Control + sample.size = sample.custom_minimum_size + var sample_size: Vector2 = hand_card_size(sample) + var side_margin: float = 40.0 + var usable_width: float = maxf(120.0, viewport_size.x - side_margin * 2.0) + var max_rel: int = 0 + var fan_half_width: float = minf(usable_width * 0.5 - sample_size.x * 0.5, 120.0 + widget_count * 18.0) + fan_half_width = maxf(fan_half_width, 0.0) + var fit_scale: float = minf(0.92, maxf(0.52, (viewport_size.y - 36.0) / sample_size.y)) + var scaled_height: float = sample_size.y * fit_scale + var base_y: float = maxf(0.0, viewport_size.y - scaled_height - 28.0) + var arc_height: float = minf(34.0, viewport_size.y * 0.14) + var max_angle_deg: float = clampf(14.0 + widget_count * 2.4, 18.0, 34.0) + + for i in range(widget_count): + var slot_i: int = int((widgets[i] as Control).get_meta("_fan_slot", i)) + max_rel = max(max_rel, abs(wrapped_hand_delta(slot_i, widget_count))) + + for i in range(widget_count): + var widget: Control = widgets[i] as Control + if widget == null: + continue + widget.size = widget.custom_minimum_size + + var slot: int = int(widget.get_meta("_fan_slot", i)) + var rel: int = wrapped_hand_delta(slot, widget_count) + var t: float = 0.0 if max_rel == 0 else float(rel) / float(max_rel) + var angle_deg: float = t * max_angle_deg + var card_size: Vector2 = hand_card_size(widget) + var edge_factor: float = absf(t) + var lift: float = 0.0 + var scale_amt: float = fit_scale * lerpf(1.0, 0.84, edge_factor) + var is_selected: bool = bool(widget.get_meta("_sel", false)) + + if is_selected: + scale_amt += 0.08 + lift += 16.0 + + var pos: Vector2 = Vector2.ZERO + pos.x = viewport_size.x * 0.5 + t * fan_half_width - (card_size.x * scale_amt) * 0.5 + pos.y = base_y + float(pow(edge_factor, 1.35)) * arc_height - lift + pos.x = clampf(pos.x, side_margin, maxf(side_margin, viewport_size.x - side_margin - card_size.x * scale_amt)) + pos.y = clampf(pos.y, 0.0, maxf(0.0, viewport_size.y - card_size.y * scale_amt)) + var z: int = 20 + int((1.0 - edge_factor) * 100.0) + if is_selected: + z += 120 + widget.set_meta("_hand_stack", z) + + apply_hand_card_transform(widget, pos, deg_to_rad(angle_deg * 0.35), scale_amt, z) + + # Reorder children by z so Godot routes GUI input to the visually topmost card. + # Positions are stable because we use _fan_slot metadata, not child index. + restack_hand_cards() + + +func restack_hand_cards() -> void: + var ordered: Array = [] + for child in hand_cards.get_children(): + if child is Control: + ordered.append(child as Control) + ordered.sort_custom(func(a: Control, b: Control) -> bool: + return int(a.get_meta("_hand_stack", 0)) < int(b.get_meta("_hand_stack", 0)) + ) + for i in range(ordered.size()): + hand_cards.move_child(ordered[i], i) + + +func apply_hand_card_transform(widget: Control, pos: Vector2, rot: float, scale_amt: float, z: int) -> void: + widget.pivot_offset = hand_card_size(widget) * 0.5 + widget.z_index = z + var existing: Variant = widget.get_meta("_hand_tween", null) + if existing is Tween and is_instance_valid(existing): + (existing as Tween).kill() + + # New widgets have never been positioned — snap them in place so they don't + # slide in from (0,0). All subsequent layout calls tween normally. + if not widget.has_meta("_hand_positioned"): + widget.set_meta("_hand_positioned", true) + widget.position = pos + widget.rotation = rot + widget.scale = Vector2.ONE * scale_amt + return + + var tw: Tween = create_tween().set_parallel(true) + tw.set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_OUT) + tw.tween_property(widget, "position", pos, 0.18) + tw.tween_property(widget, "rotation", rot, 0.18) + tw.tween_property(widget, "scale", Vector2.ONE * scale_amt, 0.18) + widget.set_meta("_hand_tween", tw) + + +func hand_card_size(widget: Control) -> Vector2: + var size_v: Vector2 = widget.size + if size_v.x <= 0.0 or size_v.y <= 0.0: + size_v = widget.custom_minimum_size + if size_v.x <= 0.0: + size_v.x = 160.0 + if size_v.y <= 0.0: + size_v.y = 257.0 + return size_v + + +func wrapped_hand_delta(index: int, total: int) -> int: + var delta: int = index - hand_focus_index + if total <= 1: + return 0 + if delta > total / 2: + delta -= total + elif delta < -int(ceil(total * 0.5)): + delta += total + return delta diff --git a/Client/origin-client/scenes/game/components/hud/hand_manager.gd.uid b/Client/origin-client/scenes/game/components/hud/hand_manager.gd.uid new file mode 100644 index 0000000..4dcb080 --- /dev/null +++ b/Client/origin-client/scenes/game/components/hud/hand_manager.gd.uid @@ -0,0 +1 @@ +uid://cjntlh271gouc diff --git a/Client/origin-client/scenes/game/components/hud/hud_controller.gd b/Client/origin-client/scenes/game/components/hud/hud_controller.gd new file mode 100644 index 0000000..af91dc7 --- /dev/null +++ b/Client/origin-client/scenes/game/components/hud/hud_controller.gd @@ -0,0 +1,304 @@ +class_name HudController +extends Node + +# ── Node refs (set from game_screen) ───────────────────────────────────────── + +var phase_lbl: Label = null +var turn_lbl: Label = null +var turn_order_strip: HBoxContainer = null +var opp_panel: HBoxContainer = null +var opp_name_lbl: Label = null +var opp_hand_lbl: Label = null +var opp_deck_lbl: Label = null +var opp_discard_btn: Button = null +var sp_lbl: Label = null +var st_lbl: Label = null +var deck_lbl: Label = null +var discard_btn: Button = null +var discard_lbl: Label = null +var draw_btn: Button = null +var end_turn_btn: Button = null +var dv_overlay: PanelContainer = null +var dv_title: Label = null +var dv_list: VBoxContainer = null +var dv_close_btn: Button = null +var spectator_panel: PanelContainer = null +var spectator_list: VBoxContainer = null +var is_spectating: bool = false + +# ── Public API ──────────────────────────────────────────────────────────────── + +func update_hud(state: Dictionary) -> void: + var phase: String = state.get("phase", "") + var turn: int = state.get("turnNumber", 1) + phase_lbl.text = "Phase: %s" % phase + + if is_spectating: + update_hud_spectator(state) + return + + # ── Player path ─────────────────────────────────────────────────────────── + var is_mine: bool = Game.is_my_turn() + var my: Dictionary = Game.get_my_player() + var opp: Dictionary = Game.get_opponent() + + 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 = "%d" % int(my.get("currentSp", 0)) + st_lbl.text = "%d" % int(my.get("currentSt", 0)) + deck_lbl.text = "%d" % int(my.get("deckCount", 0)) + var discard: Array = my.get("discard", []) + discard_lbl.text = "%d" % max(0, discard.size()) + + 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)) + + 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 + + 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" + else: + phase_lbl.text = "Phase: Placement — waiting for opponent…" + + +func update_hud_spectator(state: Dictionary) -> void: + var turn: int = state.get("turnNumber", 1) + var active_id: String = str(state.get("activePlayerAccountId", "")) + var active_name: String = Game.get_display_name(active_id) + turn_lbl.text = "Turn %d — %s is acting" % [turn, active_name] + turn_lbl.modulate = Color(1.0, 0.76, 0.2) + + # Always hide the 2-player opponent panel; show turn strip for all player counts. + opp_panel.visible = false + var all_players: Array = state.get("players", []) + turn_order_strip.visible = all_players.size() > 1 + if turn_order_strip.visible: + rebuild_turn_order_strip(state) + + draw_btn.visible = false + end_turn_btn.visible = false + + rebuild_spectator_panel(state) + + +## Rebuild the spectator player-summary list. One row per player sorted by seatIndex. +## Shows name (with active-turn highlight), SP, ST, deck count, and a Discard button. +func rebuild_spectator_panel(state: Dictionary) -> void: + for c in spectator_list.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", {}) + + 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_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 = Game.get_display_name(pid) + + var row: PanelContainer = PanelContainer.new() + row.custom_minimum_size = Vector2(0, 40) + row.self_modulate = Color(1, 1, 1, 0.4 if eliminated else 1.0) + + var style: StyleBoxFlat = StyleBoxFlat.new() + style.bg_color = Color(0.18, 0.16, 0.08, 0.92) if is_active else Color(0.10, 0.10, 0.13, 0.85) + style.border_width_left = 4 + style.border_color = Color(1.0, 0.85, 0.2) if is_active \ + else (Color.html("#" + hex_str) if not hex_str.is_empty() else Color(0.4, 0.4, 0.4)) + row.add_theme_stylebox_override("panel", style) + + var margin: MarginContainer = MarginContainer.new() + margin.add_theme_constant_override("margin_left", 8) + margin.add_theme_constant_override("margin_right", 8) + margin.add_theme_constant_override("margin_top", 4) + margin.add_theme_constant_override("margin_bottom", 4) + row.add_child(margin) + + var hbox: HBoxContainer = HBoxContainer.new() + hbox.add_theme_constant_override("separation", 12) + margin.add_child(hbox) + + var name_lbl: Label = Label.new() + name_lbl.text = ("★ " if is_active else "") + display + (" [X]" if eliminated else "") + name_lbl.add_theme_font_size_override("font_size", 12) + name_lbl.custom_minimum_size = Vector2(120, 0) + name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL + name_lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER + if is_active: + name_lbl.add_theme_color_override("font_color", Color(1.0, 0.9, 0.3)) + elif eliminated: + name_lbl.add_theme_color_override("font_color", Color(0.4, 0.4, 0.4)) + hbox.add_child(name_lbl) + + var sp_lbl_row: Label = Label.new() + sp_lbl_row.text = "SP: %d" % int(p.get("currentSp", 0)) + sp_lbl_row.add_theme_font_size_override("font_size", 11) + sp_lbl_row.vertical_alignment = VERTICAL_ALIGNMENT_CENTER + sp_lbl_row.tooltip_text = "Spirit Points" + hbox.add_child(sp_lbl_row) + + var st_lbl_row: Label = Label.new() + st_lbl_row.text = "ST: %d" % int(p.get("currentSt", 0)) + st_lbl_row.add_theme_font_size_override("font_size", 11) + st_lbl_row.vertical_alignment = VERTICAL_ALIGNMENT_CENTER + st_lbl_row.tooltip_text = "Sacrifice Tokens" + hbox.add_child(st_lbl_row) + + var deck_lbl_row: Label = Label.new() + deck_lbl_row.text = "Deck: %d" % int(p.get("deckCount", 0)) + deck_lbl_row.add_theme_font_size_override("font_size", 11) + deck_lbl_row.vertical_alignment = VERTICAL_ALIGNMENT_CENTER + hbox.add_child(deck_lbl_row) + + var disc_cards: Array = p.get("discard", []) + var disc_count: int = disc_cards.size() if not disc_cards.is_empty() else int(p.get("discardCount", 0)) + var disc_btn: Button = Button.new() + disc_btn.text = "Discard: %d" % disc_count + disc_btn.add_theme_font_size_override("font_size", 11) + disc_btn.custom_minimum_size = Vector2(80, 0) + if not disc_cards.is_empty(): + var cap_display: String = display + var cap_cards: Array = disc_cards + disc_btn.pressed.connect(func() -> void: + show_discard_for("%s Discard" % cap_display, cap_cards)) + else: + disc_btn.disabled = true + hbox.add_child(disc_btn) + + spectator_list.add_child(row) + + +## 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 = 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 = 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 = 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) + + +func show_own_discard(state: Dictionary) -> void: + show_discard_for("Your Discard", Game.get_my_player().get("discard", [])) + + +func show_opp_discard(state: Dictionary) -> 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 = 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 = HBoxContainer.new() + hbox.add_theme_constant_override("separation", 8) + hbox.custom_minimum_size = Vector2(0, 32) + var type_lbl: Label = 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 = 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 = 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 diff --git a/Client/origin-client/scenes/game/components/hud/hud_controller.gd.uid b/Client/origin-client/scenes/game/components/hud/hud_controller.gd.uid new file mode 100644 index 0000000..d8a2f55 --- /dev/null +++ b/Client/origin-client/scenes/game/components/hud/hud_controller.gd.uid @@ -0,0 +1 @@ +uid://c0cr5qgneoab1 diff --git a/Client/origin-client/scenes/game/components/hud/tile_drawer.gd b/Client/origin-client/scenes/game/components/hud/tile_drawer.gd new file mode 100644 index 0000000..72d0149 --- /dev/null +++ b/Client/origin-client/scenes/game/components/hud/tile_drawer.gd @@ -0,0 +1,513 @@ +class_name TileDrawer +extends Node + +signal focus_camera_on_tile(world_pos: Vector3) + +const TILE_DRAWER_WIDTH: float = 260.0 +const TILE_DRAWER_TOGGLE_WIDTH: float = 36.0 +const TILE_DRAWER_TOGGLE_MARGIN: float = 12.0 + +var tile_drawer: PanelContainer = null +var tile_drawer_open: bool = false +var tile_drawer_tween: Tween = null +var tile_drawer_last_tile: Dictionary = {} +var tile_drawer_tile_labels: Array = [] +var tile_drawer_spirit_labels: Array = [] +var tile_drawer_token_labels: Array = [] +var tile_drawer_arch_labels: Array = [] +var tile_drawer_ruin_labels: Array = [] +var tile_drawer_tile_section: Dictionary = {} +var tile_drawer_spirit_section: Dictionary = {} +var tile_drawer_token_section: Dictionary = {} +var tile_drawer_arch_section: Dictionary = {} +var tile_drawer_ruin_section: Dictionary = {} +var tile_drawer_spirit_effects_section: Dictionary = {} +var tile_drawer_token_effects_section: Dictionary = {} +var tile_drawer_arch_effects_section: Dictionary = {} +var tile_drawer_ruin_effects_section: Dictionary = {} +var tile_drawer_spirit_effects_labels: Array = [] +var tile_drawer_token_effects_labels: Array = [] +var tile_drawer_arch_effects_labels: Array = [] +var tile_drawer_ruin_effects_labels: Array = [] + +# Set by parent +var hud: CanvasLayer = null +var tile_drawer_toggle_btn: Button = null + + +func create_tile_drawer() -> void: + var panel: PanelContainer = 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 = 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 = 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 = HBoxContainer.new() + title_row.layout_mode = 2 + var title_lbl: Label = Label.new() + title_lbl.text = "Tile Details" + title_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL + title_lbl.add_theme_font_size_override("font_size", 15) + var close_btn: Button = 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 = HSeparator.new() + sep.layout_mode = 2 + vbox.add_child(sep) + + tile_drawer_tile_section = create_tile_drawer_section(vbox, "Tile Details", true) + tile_drawer_spirit_section = create_tile_drawer_section(vbox, "Spirit Details", false) + tile_drawer_spirit_effects_section = create_scrollable_section(vbox, "Active Effects") + tile_drawer_token_section = create_tile_drawer_section(vbox, "Spirit Token Details", false) + tile_drawer_token_effects_section = create_scrollable_section(vbox, "Active Effects") + tile_drawer_arch_section = create_tile_drawer_section(vbox, "ArchSpirit Details", false) + tile_drawer_arch_effects_section = create_scrollable_section(vbox, "Active Effects") + tile_drawer_ruin_section = create_tile_drawer_section(vbox, "Ruin Details", false) + tile_drawer_ruin_effects_section = create_scrollable_section(vbox, "Active Effects") + + tile_drawer_tile_labels = create_detail_labels(tile_drawer_tile_section["content"], 5) + tile_drawer_spirit_labels = create_detail_labels(tile_drawer_spirit_section["content"], 5) + tile_drawer_token_labels = create_detail_labels(tile_drawer_token_section["content"], 5) + tile_drawer_arch_labels = create_detail_labels(tile_drawer_arch_section["content"], 6) + tile_drawer_ruin_labels = create_detail_labels(tile_drawer_ruin_section["content"], 2) + + set_tile_drawer_button_state() + + +func create_tile_drawer_section(parent: VBoxContainer, title: String, + expanded: bool) -> Dictionary: + var section: VBoxContainer = VBoxContainer.new() + section.layout_mode = 2 + section.add_theme_constant_override("separation", 4) + parent.add_child(section) + + var header: Button = Button.new() + header.layout_mode = 2 + header.toggle_mode = true + header.button_pressed = expanded + header.alignment = HORIZONTAL_ALIGNMENT_LEFT + header.text = tile_drawer_section_title(title, expanded) + section.add_child(header) + + var content: VBoxContainer = VBoxContainer.new() + content.layout_mode = 2 + content.visible = expanded + content.add_theme_constant_override("separation", 2) + section.add_child(content) + + section.visible = expanded + + header.toggled.connect(func(is_pressed: bool) -> void: + content.visible = is_pressed + header.text = tile_drawer_section_title(title, is_pressed)) + + return { + "root": section, + "header": header, + "content": content, + "title": title, + } + + +func tile_drawer_section_title(title: String, expanded: bool) -> String: + return "%s %s" % ["[-]" if expanded else "[+]", title] + + +## Creates a collapsible section whose content sits inside a ScrollContainer so that +## long effect lists don't overflow the drawer. The returned dict has the same keys +## as create_tile_drawer_section ("root", "header", "content", "title") plus "scroll" +## and a mutable "count" entry used to keep the header label up-to-date. +func create_scrollable_section(parent: VBoxContainer, title: String) -> Dictionary: + var section: VBoxContainer = VBoxContainer.new() + section.layout_mode = 2 + section.add_theme_constant_override("separation", 4) + parent.add_child(section) + + var header: Button = Button.new() + header.layout_mode = 2 + header.toggle_mode = true + header.button_pressed = false + header.alignment = HORIZONTAL_ALIGNMENT_LEFT + header.text = tile_drawer_section_title(title, false) + section.add_child(header) + + var scroll: ScrollContainer = ScrollContainer.new() + scroll.layout_mode = 2 + scroll.custom_minimum_size = Vector2(0, 90) + scroll.vertical_scroll_mode = ScrollContainer.SCROLL_MODE_AUTO + scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + scroll.visible = false + section.add_child(scroll) + + var content: VBoxContainer = VBoxContainer.new() + content.layout_mode = 2 + content.size_flags_horizontal = Control.SIZE_EXPAND_FILL + content.add_theme_constant_override("separation", 2) + scroll.add_child(content) + + section.visible = false + + var data: Dictionary = { + "root": section, + "header": header, + "scroll": scroll, + "content": content, + "title": title, + "count": 0, + } + + header.toggled.connect(func(is_pressed: bool) -> void: + scroll.visible = is_pressed + var n: int = data.get("count", 0) + var t: String = data.get("title", "Active Effects") + var display: String = ("%s (%d)" % [t, n]) if n > 0 else t + header.text = tile_drawer_section_title(display, is_pressed)) + + return data + + +## Updates the effects section header text (e.g. "Active Effects (3)") and stores +## the count so the toggle signal can rebuild the label correctly. +func update_effects_section_header(section: Dictionary, count: int) -> void: + section["count"] = count + var header: Button = section.get("header") as Button + if not is_instance_valid(header): + return + var title: String = section.get("title", "Active Effects") + var display: String = ("%s (%d)" % [title, count]) if count > 0 else title + header.text = tile_drawer_section_title(display, header.button_pressed) + + +func create_detail_labels(parent: VBoxContainer, count: int) -> Array: + var labels: Array = [] + for _i in range(count): + var lbl: Label = Label.new() + lbl.layout_mode = 2 + lbl.mouse_filter = Control.MOUSE_FILTER_STOP + lbl.add_theme_font_size_override("font_size", 12) + lbl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + parent.add_child(lbl) + labels.append(lbl) + return labels + + +func append_tile_drawer_label(parent: VBoxContainer, labels: Array) -> void: + var lbl: Label = Label.new() + lbl.layout_mode = 2 + lbl.mouse_filter = Control.MOUSE_FILTER_STOP + lbl.add_theme_font_size_override("font_size", 12) + lbl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + parent.add_child(lbl) + labels.append(lbl) + + +func set_tile_drawer_lines(section: Dictionary, labels: Array, lines: Array, + tooltips: Array = []) -> void: + var root: Control = section.get("root") as Control + var content: VBoxContainer = section.get("content") as VBoxContainer + if root == null: + return + if content == null: + return + while labels.size() < lines.size(): + append_tile_drawer_label(content, labels) + root.visible = not lines.is_empty() + for i in range(labels.size()): + var lbl: Label = labels[i] as Label + var show_line: bool = i < lines.size() + lbl.visible = show_line + if show_line: + lbl.text = str(lines[i]) + lbl.tooltip_text = str(tooltips[i]) if i < tooltips.size() else "" + else: + lbl.tooltip_text = "" + + +## Clears a scrollable effects section and resets its cached header/toggle state so +## the next inspected tile does not inherit a stale count or expanded body. +func clear_effects_section(section: Dictionary, labels: Array) -> void: + set_tile_drawer_lines(section, labels, []) + section["count"] = 0 + var header: Button = section.get("header") as Button + if is_instance_valid(header): + header.button_pressed = false + header.text = tile_drawer_section_title(str(section.get("title", "Active Effects")), false) + var scroll: ScrollContainer = section.get("scroll") as ScrollContainer + if is_instance_valid(scroll): + scroll.visible = false + scroll.scroll_vertical = 0 + + +func find_unit_owner_account_id(unit_id: String) -> String: + if unit_id.is_empty(): + return "" + for player: Dictionary in Game.state.get("players", []): + for unit: Dictionary in player.get("field", []): + if str(unit.get("instanceId", "")) == unit_id: + return str(player.get("accountId", "")) + var arch: Dictionary = player.get("archSpirit", {}) + if str(arch.get("instanceId", "")) == unit_id: + return str(player.get("accountId", "")) + return "" + + +func build_unit_detail_lines(unit: Dictionary, owner_id: String, + include_tier: bool = false) -> Dictionary: + var lines: Array = [ + "Name: %s" % str(unit.get("name", "?")), + "Owner: %s" % Game.get_display_name(owner_id), + ] + var tooltips: Array = ["", ""] + if include_tier: + lines.append("Tier: %d" % int(unit.get("tier", 0))) + tooltips.append("") + lines.append("HP: %d / %d" % [int(unit.get("currentHealth", 0)), int(unit.get("maxHealth", 0))]) + lines.append("DEF: %d / %d" % [int(unit.get("currentDefense", 0)), int(unit.get("maxDefense", 0))]) + lines.append("ATK: %d" % int(unit.get("damage", 0))) + lines.append("MP: %d / %d" % [int(unit.get("currentMp", 0)), int(unit.get("maxMp", 0))]) + lines.append("Can Move: %s" % ("Yes" if bool(unit.get("canMove", false)) else "No")) + lines.append("Can Attack: %s" % ("Yes" if bool(unit.get("canAttack", false)) else "No")) + tooltips.append_array(["", "", "", "", "", ""]) + + var raw_abilities: Variant = unit.get("abilitiesJson") + var parsed_abilities: Variant = JSON.parse_string("[]" if raw_abilities == null else str(raw_abilities)) + if parsed_abilities is Array: + for ability_index: int in range((parsed_abilities as Array).size()): + var ability: Dictionary = (parsed_abilities as Array)[ability_index] as Dictionary + var ability_name: String = str(ability.get("name", ability.get("Name", "Ability %d" % ability_index))) + var ability_desc: String = str(ability.get("description", ability.get("Description", ""))) + lines.append("Ability: %s" % ability_name) + tooltips.append(ability_desc) + + return { + "lines": lines, + "tooltips": tooltips, + } + + +## Appends any active effects targeting [param target_ref] (unit instanceId or ruinId) +## into the provided [param lines] and [param tooltips] arrays. +func append_active_effect_lines(target_ref: String, lines: Array, tooltips: Array) -> void: + if target_ref.is_empty(): + return + var all_effects: Variant = Game.state.get("activeEffects") + if not all_effects is Array: + return + for ae: Dictionary in (all_effects as Array): + if str(ae.get("targetRef", "")) != target_ref: + continue + var label: String = str(ae.get("label", "?")) + var source_name: String = str(ae.get("sourceName", "")) + var dur_type: String = str(ae.get("durationType", "")) + var turns: int = int(ae.get("turnsRemaining", 0)) + var dur_text: String + match dur_type: + "ForNTurns": dur_text = "%d turn%s" % [turns, "s" if turns != 1 else ""] + "UntilEndOfTurn": dur_text = "until end of turn" + "UntilStartOfOwnerTurn": dur_text = "until owner's next turn" + "UntilStartOfSourceOwnerTurn": dur_text = "until source's next turn" + "WhileSourceOnBattlefield": dur_text = "while source lives" + "WhileCondition": dur_text = "conditional" + _: dur_text = dur_type.to_lower().replace("_", " ") + var line: String + if source_name.is_empty() or source_name == ae.get("sourceInstanceId", ""): + line = "[Effect] %s (%s)" % [label, dur_text] + else: + line = "[Effect] %s (%s, from %s)" % [label, dur_text, source_name] + lines.append(line) + tooltips.append("") + + +func set_tile_drawer_content(tile_data: Dictionary, state: Dictionary) -> void: + tile_drawer_last_tile = tile_data.duplicate(true) + set_tile_drawer_button_state() + if tile_data.is_empty(): + set_tile_drawer_lines(tile_drawer_tile_section, tile_drawer_tile_labels, []) + set_tile_drawer_lines(tile_drawer_spirit_section, tile_drawer_spirit_labels, []) + set_tile_drawer_lines(tile_drawer_token_section, tile_drawer_token_labels, []) + set_tile_drawer_lines(tile_drawer_arch_section, tile_drawer_arch_labels, []) + set_tile_drawer_lines(tile_drawer_ruin_section, tile_drawer_ruin_labels, []) + clear_effects_section(tile_drawer_spirit_effects_section, tile_drawer_spirit_effects_labels) + clear_effects_section(tile_drawer_token_effects_section, tile_drawer_token_effects_labels) + clear_effects_section(tile_drawer_arch_effects_section, tile_drawer_arch_effects_labels) + clear_effects_section(tile_drawer_ruin_effects_section, tile_drawer_ruin_effects_labels) + return + + var coord: Dictionary = tile_data.get("coord", {}) + var cx: int = int(coord.get("x", 0)) + var cy: int = int(coord.get("y", 0)) + var aff: String = str(tile_data.get("resolvedAffinity", "?")) + var b1: String = str(tile_data.get("base1", "?")) + var b2: String = str(tile_data.get("base2", "?")) + var ruin_id_value: Variant = tile_data.get("ruinId", "") + var ruin_id: String = "" if ruin_id_value == null else str(ruin_id_value) + var ruin_owner_id: String = str(tile_data.get("ruinOwner", "")) + var occ_id: String = str(tile_data.get("occupantId", "")) + var occ_owner_id: String = str(tile_data.get("occupantOwner", "")) + var occ_unit: Dictionary = Game.get_unit_by_id(occ_id) + var occ_type: String = str(occ_unit.get("cardType", "")) + var occ_name: String = str(occ_unit.get("name", occ_id)) + + var tile_lines: Array = [ + "Coord: (%d, %d)" % [cx, cy], + "Affinity: %s" % aff, + "Base1: %s" % b1, + "Base2: %s" % b2, + "Occupant: %s" % ("None" if occ_id.is_empty() or occ_id == "null" else "%s (%s)" % [occ_name, occ_type]), + ] + set_tile_drawer_lines(tile_drawer_tile_section, tile_drawer_tile_labels, tile_lines) + + if not occ_id.is_empty() and occ_id != "null" and occ_type == "Spirit": + var spirit_owner_id: String = occ_owner_id if not occ_owner_id.is_empty() else find_unit_owner_account_id(occ_id) + var spirit_detail: Dictionary = build_unit_detail_lines(occ_unit, spirit_owner_id) + set_tile_drawer_lines( + tile_drawer_spirit_section, tile_drawer_spirit_labels, + spirit_detail.get("lines", []), spirit_detail.get("tooltips", [])) + set_effects_section(occ_id, tile_drawer_spirit_effects_section, tile_drawer_spirit_effects_labels) + else: + set_tile_drawer_lines(tile_drawer_spirit_section, tile_drawer_spirit_labels, []) + clear_effects_section(tile_drawer_spirit_effects_section, tile_drawer_spirit_effects_labels) + + if not occ_id.is_empty() and occ_id != "null" and occ_type == "SpiritToken": + var token_owner_id: String = occ_owner_id if not occ_owner_id.is_empty() else find_unit_owner_account_id(occ_id) + var token_detail: Dictionary = build_unit_detail_lines(occ_unit, token_owner_id) + set_tile_drawer_lines( + tile_drawer_token_section, tile_drawer_token_labels, + token_detail.get("lines", []), token_detail.get("tooltips", [])) + set_effects_section(occ_id, tile_drawer_token_effects_section, tile_drawer_token_effects_labels) + else: + set_tile_drawer_lines(tile_drawer_token_section, tile_drawer_token_labels, []) + clear_effects_section(tile_drawer_token_effects_section, tile_drawer_token_effects_labels) + + if not occ_id.is_empty() and occ_id != "null" and occ_type == "ArchSpirit": + var arch_owner_id: String = occ_owner_id if not occ_owner_id.is_empty() else find_unit_owner_account_id(occ_id) + var arch_detail: Dictionary = build_unit_detail_lines(occ_unit, arch_owner_id, true) + set_tile_drawer_lines( + tile_drawer_arch_section, tile_drawer_arch_labels, + arch_detail.get("lines", []), arch_detail.get("tooltips", [])) + set_effects_section(occ_id, tile_drawer_arch_effects_section, tile_drawer_arch_effects_labels) + else: + set_tile_drawer_lines(tile_drawer_arch_section, tile_drawer_arch_labels, []) + clear_effects_section(tile_drawer_arch_effects_section, tile_drawer_arch_effects_labels) + + if ruin_id_value != null and not ruin_id.is_empty() and ruin_id != "null": + var ruin_lines: Array = ["Ruin: %s" % ruin_id, "Owner: %s" % Game.get_display_name(ruin_owner_id)] + var ruin_tooltips: Array = ["", ""] + set_tile_drawer_lines(tile_drawer_ruin_section, tile_drawer_ruin_labels, ruin_lines, ruin_tooltips) + set_effects_section(ruin_id, tile_drawer_ruin_effects_section, tile_drawer_ruin_effects_labels) + else: + set_tile_drawer_lines(tile_drawer_ruin_section, tile_drawer_ruin_labels, []) + clear_effects_section(tile_drawer_ruin_effects_section, tile_drawer_ruin_effects_labels) + + +## Populates [param section] (a scrollable effects section) with effects targeting +## [param target_ref], then updates the header count badge. +func set_effects_section(target_ref: String, section: Dictionary, labels: Array) -> void: + var effect_lines: Array = [] + var effect_tooltips: Array = [] + append_active_effect_lines(target_ref, effect_lines, effect_tooltips) + set_tile_drawer_lines(section, labels, effect_lines, effect_tooltips) + update_effects_section_header(section, effect_lines.size()) + + +func set_tile_drawer_button_state() -> void: + if not is_instance_valid(tile_drawer_toggle_btn): + return + var has_tile: bool = not tile_drawer_last_tile.is_empty() + tile_drawer_toggle_btn.disabled = not has_tile + tile_drawer_toggle_btn.text = ">" if tile_drawer_open else "<" + layout_tile_drawer_toggle_button() + + +func layout_tile_drawer_toggle_button() -> void: + if not is_instance_valid(tile_drawer_toggle_btn): + return + if tile_drawer_open: + tile_drawer_toggle_btn.offset_left = -TILE_DRAWER_WIDTH - TILE_DRAWER_TOGGLE_WIDTH + tile_drawer_toggle_btn.offset_right = -TILE_DRAWER_WIDTH + else: + tile_drawer_toggle_btn.offset_left = -(TILE_DRAWER_TOGGLE_WIDTH + TILE_DRAWER_TOGGLE_MARGIN) + tile_drawer_toggle_btn.offset_right = -TILE_DRAWER_TOGGLE_MARGIN + tile_drawer_toggle_btn.offset_top = -24.0 + tile_drawer_toggle_btn.offset_bottom = 24.0 + + +func on_tile_drawer_toggle_pressed() -> void: + if tile_drawer_open: + close_tile_drawer() + return + if tile_drawer_last_tile.is_empty(): + return + open_tile_drawer(tile_drawer_last_tile) + + +func open_tile_drawer(tile: Dictionary) -> void: + if not is_instance_valid(tile_drawer): return + set_tile_drawer_content(tile, Game.state) + + if tile_drawer_open: + set_tile_drawer_button_state() + return # already open, content updated above + tile_drawer_open = true + tile_drawer.visible = true + set_tile_drawer_button_state() + 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.parallel().tween_property(tile_drawer, "offset_left", -TILE_DRAWER_WIDTH, 0.3) + tile_drawer_tween.parallel().tween_property( + tile_drawer_toggle_btn, "offset_left", + -TILE_DRAWER_WIDTH - TILE_DRAWER_TOGGLE_WIDTH, 0.3) + tile_drawer_tween.parallel().tween_property( + tile_drawer_toggle_btn, "offset_right", + -TILE_DRAWER_WIDTH, 0.3) + + +func close_tile_drawer() -> void: + if not is_instance_valid(tile_drawer) or not tile_drawer_open: return + tile_drawer_open = false + set_tile_drawer_button_state() + 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.parallel().tween_property(tile_drawer, "offset_left", 0.0, 0.25) + tile_drawer_tween.parallel().tween_property( + tile_drawer_toggle_btn, "offset_left", + -(TILE_DRAWER_TOGGLE_WIDTH + TILE_DRAWER_TOGGLE_MARGIN), 0.25) + tile_drawer_tween.parallel().tween_property( + tile_drawer_toggle_btn, "offset_right", + -TILE_DRAWER_TOGGLE_MARGIN, 0.25) + tile_drawer_tween.tween_callback(func() -> void: + if is_instance_valid(tile_drawer): tile_drawer.visible = false) + + +## Emits focus_camera_on_tile with the world position of the given coord. +## Accepts a pathfinder to resolve the coordinate to world space. +func focus_camera_on_tile_at(coord: Vector2i, state: Dictionary, pathfinder: Pathfinder) -> void: + var world_pos: Vector3 = pathfinder.coord_to_world(coord.x, coord.y) + focus_camera_on_tile.emit(world_pos) diff --git a/Client/origin-client/scenes/game/components/hud/tile_drawer.gd.uid b/Client/origin-client/scenes/game/components/hud/tile_drawer.gd.uid new file mode 100644 index 0000000..aadc509 --- /dev/null +++ b/Client/origin-client/scenes/game/components/hud/tile_drawer.gd.uid @@ -0,0 +1 @@ +uid://cbvcxlj28mwp3 diff --git a/Client/origin-client/scenes/game/components/input/board_input_handler.gd b/Client/origin-client/scenes/game/components/input/board_input_handler.gd new file mode 100644 index 0000000..cc73c53 --- /dev/null +++ b/Client/origin-client/scenes/game/components/input/board_input_handler.gd @@ -0,0 +1,366 @@ +class_name BoardInputHandler +extends Node + +# ── Signals ─────────────────────────────────────────────────────────────────── + +signal board_clicked(screen_pos: Vector2) # tap/click on board (no drag) +signal board_held(coord: Vector2i) # long press on tile (hold timer fired) +signal board_double_clicked(screen_pos: Vector2) # double-click on unit +signal board_orbit(delta: Vector2) # camera orbit delta +signal board_pan(delta: Vector2, cam_distance: float) # camera pan delta +signal board_zoom(amount: float) # scroll/pinch zoom +signal hand_scroll(direction: int) # -1 = left, +1 = right +signal deselect_pending() # left-click outside hand while card selected + +# ── Touch / mouse state ─────────────────────────────────────────────────────── + +var last_mouse: Vector2 = Vector2.ZERO +var drag_active: bool = false +var press_was_on_board: bool = false +var pan_active: bool = false +var orbit_active: bool = false +var touch_points: Dictionary = {} +var pinch_dist: float = 0.0 +var was_multi_touch: bool = false +var touch_drag_active: bool = false +var touch_drag_total: float = 0.0 +var touch_start_pos: Vector2 = Vector2.ZERO +var touch_cam_orbit: bool = false +var touch_cam_pan: bool = false +var touch_cam_zoom: bool = false +var gesture_move_accum: float = 0.0 +var gesture_finger_count: int = 0 + +# ── Internal deselect state ─────────────────────────────────────────────────── + +var _deselect_pending: bool = false +var _hand_scroll_time: float = 0.0 + +# ── References set by parent ────────────────────────────────────────────────── + +# Timers +var hold_timer: Timer = null +var cam_gesture_timer: Timer = null + +# UI reference — used to detect hand-area wheel scrolls / deselect guard +var hand_area: PanelContainer = null + +# Camera rig — used for pan/orbit basis calculations +var camera_rig: Node3D = null + +# Camera distance — kept in sync by camera_controller via property +var cam_distance: float = 14.0 + +# ── Mode flags set by selection_controller ──────────────────────────────────── + +# true when a card is selected in hand +var card_mode_active: bool = false +# true when targeting for a card ability +var ability_card_active: bool = false + +# ── Held-coord (exposed so hold_timer signal handler in parent can read it) ─── + +var held_coord: Vector2i = Vector2i(-1, -1) + +# ── Callbacks set by parent for raycast queries ─────────────────────────────── +# Assign Callables pointing at game_screen's _mouse_to_tile_coord and _mouse_to_unit_id. +# Signature: func(screen_pos: Vector2) -> Vector2i +var fn_mouse_to_tile_coord: Callable = Callable() +# Signature: func(screen_pos: Vector2) -> String +var fn_mouse_to_unit_id: Callable = Callable() + +# ── Camera-button toggles (called by game_screen from button signals) ───────── + +func on_cam_orbit_btn_toggled(pressed: bool) -> void: + touch_cam_orbit = pressed + if pressed: + touch_cam_pan = false + touch_cam_zoom = false + +func on_cam_pan_btn_toggled(pressed: bool) -> void: + touch_cam_pan = pressed + if pressed: + touch_cam_orbit = false + touch_cam_zoom = false + +func on_cam_zoom_btn_toggled(pressed: bool) -> void: + touch_cam_zoom = pressed + if pressed: + touch_cam_orbit = false + touch_cam_pan = false + +# ── Gesture timer callback (called by cam_gesture_timer.timeout) ────────────── + +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 + if is_instance_valid(hold_timer): + hold_timer.stop() + +# ── Deactivate all touch camera modes ──────────────────────────────────────── + +func deactivate_touch_cam_modes() -> void: + touch_cam_orbit = false + touch_cam_pan = false + touch_cam_zoom = false + +# ── _input: intercepts every event first (handles deselect guard) ───────────── + +func _input(event: InputEvent) -> void: + if event is InputEventMouseButton: + var mb: InputEventMouseButton = event as InputEventMouseButton + if mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed and not mb.double_click: + var is_card_active: bool = card_mode_active or ability_card_active + if is_card_active: + if hand_area != null and not hand_area.get_global_rect().has_point(mb.position): + _deselect_pending = true + _do_deselect_if_pending.call_deferred() + +# ── Deselect-if-pending (called deferred so board click can cancel it first) ── + +func _do_deselect_if_pending() -> void: + if _deselect_pending: + _deselect_pending = false + var is_card_active: bool = card_mode_active or ability_card_active + if is_card_active: + emit_signal("deselect_pending") + +# ── _unhandled_input: board-level input, not consumed by UI ────────────────── + +func _unhandled_input(event: InputEvent) -> void: + if event is InputEventMouseButton: + var mb: InputEventMouseButton = event as InputEventMouseButton + # Left-click reaching here is a board click — cancel any pending deselect + # so _do_deselect_if_pending won't wipe selection before the card is played. + if mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed: + _deselect_pending = false + if mb.button_index == MOUSE_BUTTON_WHEEL_UP: + if hand_area != null and hand_area.get_global_rect().has_point(mb.position): + var now: float = Time.get_ticks_msec() / 1000.0 + if now - _hand_scroll_time >= 0.15: + _hand_scroll_time = now + hand_scroll.emit(-1) + return + board_zoom.emit(1.5) + return + elif mb.button_index == MOUSE_BUTTON_WHEEL_DOWN: + if hand_area != null and hand_area.get_global_rect().has_point(mb.position): + var now: float = Time.get_ticks_msec() / 1000.0 + if now - _hand_scroll_time >= 0.15: + _hand_scroll_time = now + hand_scroll.emit(1) + return + board_zoom.emit(-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: String = "" + if fn_mouse_to_unit_id.is_valid(): + dbl_unit_id = fn_mouse_to_unit_id.call(mb.position) + if not dbl_unit_id.is_empty(): + board_double_clicked.emit(mb.position) + return + last_mouse = mb.position + drag_active = false + press_was_on_board = true # unhandled press = board area, not a UI card + var coord: Vector2i = Vector2i(-1, -1) + if fn_mouse_to_tile_coord.is_valid(): + coord = fn_mouse_to_tile_coord.call(mb.position) + if coord.x >= 0: + held_coord = coord + if is_instance_valid(hold_timer): + hold_timer.start() + else: + held_coord = Vector2i(-1, -1) + else: + if is_instance_valid(hold_timer): + hold_timer.stop() + if not drag_active and not touch_drag_active and press_was_on_board: + board_clicked.emit(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: InputEventMouseMotion = event as InputEventMouseMotion + var delta: Vector2 = 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: + board_orbit.emit(delta) + if pan_active: + # Normalise sign convention: receiver applies right = basis.x * d.x, fwd = fwd_vec * d.y + # Mouse: original used +delta.x right, -delta.y forward. + board_pan.emit(Vector2(delta.x, -delta.y), cam_distance) + + elif event is InputEventScreenTouch: + var st: InputEventScreenTouch = 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: Vector2i = Vector2i(-1, -1) + if fn_mouse_to_tile_coord.is_valid(): + touch_coord = fn_mouse_to_tile_coord.call(st.position) + if touch_coord.x >= 0: + held_coord = touch_coord + if is_instance_valid(hold_timer): + 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) + if is_instance_valid(hold_timer): + 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 + if is_instance_valid(cam_gesture_timer): + cam_gesture_timer.start() + else: + var released_pos: Vector2 = st.position + var had_single_touch: bool = (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: float = released_pos.distance_to(touch_start_pos) + if tap_dist < 50.0 and not touch_drag_active: + if is_instance_valid(hold_timer): + hold_timer.stop() + board_clicked.emit(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) + if is_instance_valid(hold_timer): + hold_timer.stop() + if is_instance_valid(cam_gesture_timer): + 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: InputEventScreenDrag = event as InputEventScreenDrag + touch_points[sd.index] = sd.position + + # Cancel gesture timer if fingers move significantly before the hold activates. + if Settings.touch_camera_mode == "gesture": + gesture_move_accum += sd.relative.length() + if gesture_move_accum > 50.0: + if is_instance_valid(cam_gesture_timer): + 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: + if is_instance_valid(hold_timer): + 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: + board_orbit.emit(sd.relative) + elif touch_cam_pan: + # Negate x to match original sign convention (pan right moves camera right). + var pan_delta_touch: Vector2 = Vector2(-sd.relative.x, sd.relative.y) + board_pan.emit(pan_delta_touch, cam_distance) + elif touch_cam_zoom: + board_zoom.emit(sd.relative.y * -0.05) + elif Settings.touch_camera_mode == "gesture" and touch_points.size() == 3 and touch_cam_pan: + # 3-finger pan (gesture mode): only process the leading finger to avoid triple-apply. + var keys3: Array = touch_points.keys() + keys3.sort() + if sd.index == keys3[0]: + var pan_delta3: Vector2 = Vector2(-sd.relative.x, sd.relative.y) + board_pan.emit(pan_delta3, cam_distance) + elif Settings.touch_camera_mode == "gesture" and touch_points.size() >= 2: + var keys: Array = touch_points.keys() + var pos_a: Vector2 = touch_points[keys[0]] + var pos_b: Vector2 = touch_points[keys[1]] + var mid: Vector2 = (pos_a + pos_b) * 0.5 + var nd: float = pos_a.distance_to(pos_b) + board_zoom.emit((nd - pinch_dist) * 0.03) + pinch_dist = nd + var cdelta: Vector2 = mid - last_mouse + last_mouse = mid + var pan_delta2: Vector2 = Vector2(-cdelta.x, cdelta.y) + board_pan.emit(pan_delta2, cam_distance) + + # ── 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: + if Settings.touch_camera_mode == "gesture": + var mg: InputEventMagnifyGesture = event as InputEventMagnifyGesture + board_zoom.emit((mg.factor - 1.0) * 8.0) + + elif event is InputEventPanGesture: + if Settings.touch_camera_mode != "gesture": + return + # 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: InputEventPanGesture = event as InputEventPanGesture + var pan_delta_pg: Vector2 = Vector2(-pg.delta.x, pg.delta.y) + board_pan.emit(pan_delta_pg, cam_distance) + +# ── Helpers ─────────────────────────────────────────────────────────────────── + +func _touch_pair_dist() -> float: + var keys: Array = 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: Array = 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 diff --git a/Client/origin-client/scenes/game/components/input/board_input_handler.gd.uid b/Client/origin-client/scenes/game/components/input/board_input_handler.gd.uid new file mode 100644 index 0000000..11bab2a --- /dev/null +++ b/Client/origin-client/scenes/game/components/input/board_input_handler.gd.uid @@ -0,0 +1 @@ +uid://cqs166tf6n0s0 diff --git a/Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd b/Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd new file mode 100644 index 0000000..19e0bf5 --- /dev/null +++ b/Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd @@ -0,0 +1,47 @@ +class_name GameOverOverlay +extends Node + +## Manages the end-of-game Victory/Defeat overlay. +## Node refs are set by game_screen after scene is ready. + +var go_overlay: PanelContainer = null +var go_result_lbl: Label = null +var go_rank_lbl: Label = null +var go_menu_btn: Button = null + +func show_result(winner_id: String, win_condition: String, + winner_delta: int, loser_delta: int, + player_outcomes: Array = []) -> void: + var i_won: bool + if not player_outcomes.is_empty(): + var my_outcome: String = "" + for po: Dictionary in player_outcomes: + if str(po.get("accountId", "")) == Auth.user_id: + my_outcome = str(po.get("outcome", "")) + break + i_won = (my_outcome == "Winner") + else: + i_won = (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(): + 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]\n" % win_condition + "\n".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") diff --git a/Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd.uid b/Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd.uid new file mode 100644 index 0000000..2c6d6b9 --- /dev/null +++ b/Client/origin-client/scenes/game/components/overlays/game_over_overlay.gd.uid @@ -0,0 +1 @@ +uid://c1acrobstx4i5 diff --git a/Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd b/Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd new file mode 100644 index 0000000..bbcbc6b --- /dev/null +++ b/Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd @@ -0,0 +1,72 @@ +class_name InactiveDialogs +extends Node + +## Creates inactivity and player-elimination dialogs dynamically. +## Dialogs are added as children of this node (which is a child of game_screen). + +signal spectator_mode_requested() # emitted when local player is eliminated + +func on_opponent_inactive(_sid: String) -> void: + var dialog: ConfirmationDialog = 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() + + +func on_inactive_warning(_sid: String) -> void: + var dialog: AcceptDialog = 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() + + +func on_both_idle_warning(_sid: String) -> void: + for child: Node in get_children(): + if child is ConfirmationDialog or child is AcceptDialog: + child.queue_free() + var dialog: AcceptDialog = 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() + + +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!\nYou 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 = 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 is_me: + emit_signal("spectator_mode_requested") diff --git a/Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd.uid b/Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd.uid new file mode 100644 index 0000000..166ea37 --- /dev/null +++ b/Client/origin-client/scenes/game/components/overlays/inactive_dialogs.gd.uid @@ -0,0 +1 @@ +uid://cq32begww8vf5 diff --git a/Client/origin-client/scenes/game/components/selection/ability_targeting.gd b/Client/origin-client/scenes/game/components/selection/ability_targeting.gd new file mode 100644 index 0000000..3dad3b2 --- /dev/null +++ b/Client/origin-client/scenes/game/components/selection/ability_targeting.gd @@ -0,0 +1,688 @@ +class_name AbilityTargeting +extends Node + +## Manages the ability targeting UI and state: +## ability panel, branch panel, player panel, confirm button, +## target collection, and sending ability/trigger responses. +## +## External refs (set by game_screen._ready): +## selection_controller — for set_mode() and mode checks +## unit_registry — for is_friendly / is_enemy queries +## pathfinder — for board_distance, has_los, coord_to_world +## hud — CanvasLayer that owns all 2D HUD children +## unit_bodies — Dictionary instanceId → StaticBody3D +## camera — Camera3D used for unproject_position + +# ── Signals ─────────────────────────────────────────────────────────────────── + +signal highlight_add_requested(x: int, y: int, type_name: String) +signal highlights_cleared() + +# ── External refs ───────────────────────────────────────────────────────────── + +var selection_controller: SelectionController = null +var unit_registry: UnitRegistry = null +var pathfinder: Pathfinder = null +var hud: CanvasLayer = null +var unit_bodies: Dictionary = {} # instanceId → StaticBody3D +var camera: Camera3D = null + +# ── Ability state ───────────────────────────────────────────────────────────── + +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 +var ability_card_id: String = "" # non-empty when targeting a card's active ability +var ability_target_conditions: Array = [] # ActivationConditions from card ability +var ability_target_n: int = 1 +var ability_target_up_to: bool = false +var ability_targets_this_action: int = 0 +var ability_confirm_btn: Control = null +var ability_branch_panel: Control = null +var player_panel: Control = null + +# Triggered ability targeting +var is_triggered_target: bool = false +var triggered_request_id: String = "" + +# Server-driven picks (shared with server_prompt_handler via direct access) +var is_target_pick: bool = false +var is_tile_pick: bool = false +var pending_req_id: String = "" + +# ── Public API ──────────────────────────────────────────────────────────────── + +## Resets all ability state variables to defaults (called by selection_controller on NONE). +func reset_ability_state() -> void: + 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 + + +func show_ability_panel(unit_id: String, unit: Dictionary) -> void: + hide_ability_panel() + + # Collect Active abilities. + var actives: Array = [] + var raw_abil: Variant = unit.get("abilitiesJson") + var abil_json: String = "" if raw_abil == null else str(raw_abil) + if not abil_json.is_empty(): + var parsed: Variant = JSON.parse_string(abil_json) + if parsed is Array: + var abilities: Array = normalize_keys(parsed) as Array + for i: int 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 + }) + + # Collect ArchSpirit actions (Sacrifice / Ascend / Transition). + var arch_actions: Array = [] + if unit.get("cardType", "") == "ArchSpirit" \ + and selection_controller != null \ + and unit_registry != null \ + and unit_registry.friendly_unit_ids.has(unit_id): + var sc: SelectionController = selection_controller + if sc.tile_target_resolver != null: + var sac_spirits: Array = sc.tile_target_resolver.valid_sacrifice_spirits() + if not sac_spirits.is_empty(): + arch_actions.append({ + "label": "Sacrifice a Spirit", + "fn": func() -> void: sc._start_sacrifice_mode() + }) + var cur_tier: int = int(unit.get("tier", 1)) + var can_ascend: bool = false + var can_trans: bool = false + 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_trans = true + if can_ascend: + arch_actions.append({ + "label": "Ascend", + "fn": func() -> void: sc._pick_ascend_card() + }) + if can_trans: + arch_actions.append({ + "label": "Transition", + "fn": func() -> void: sc._pick_transition_card() + }) + + if actives.is_empty() and arch_actions.is_empty(): + return + + # Build panel. + var panel: PanelContainer = PanelContainer.new() + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 4) + vbox.custom_minimum_size = Vector2(160, 0) + + if not actives.is_empty(): + var title: Label = 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 = 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 = get_ability_actions(ab_def) + ability_range = ab_def.get("range", {}) + ability_targets = [] + ability_cur_action_idx = 0 + start_ability_targeting()) + vbox.add_child(btn) + + if not arch_actions.is_empty(): + if not actives.is_empty(): + vbox.add_child(HSeparator.new()) + var arch_title: Label = Label.new() + arch_title.text = "ArchSpirit" + arch_title.add_theme_font_size_override("font_size", 12) + arch_title.add_theme_color_override("font_color", Color(1.0, 0.75, 0.3)) + vbox.add_child(arch_title) + vbox.add_child(HSeparator.new()) + for aa: Dictionary in arch_actions: + var btn: Button = Button.new() + btn.text = aa.get("label", "") + btn.add_theme_font_size_override("font_size", 12) + var fn: Callable = aa.get("fn", Callable()) + btn.pressed.connect(func() -> void: fn.call()) + vbox.add_child(btn) + + panel.add_child(vbox) + if hud != null: + hud.add_child(panel) + ability_panel = panel + + # Position to the right of the unit. + var body: StaticBody3D = unit_bodies.get(unit_id) as StaticBody3D + if is_instance_valid(body) and camera != null: + var screen_pos: Vector2 = 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 + + +func current_target_mode() -> SelectionController.Mode: + if is_triggered_target or is_target_pick or is_tile_pick: + return SelectionController.Mode.ABILITY_TARGET_FORCED + return SelectionController.Mode.ABILITY_TARGET + + +## Advance through ability actions, entering board-target mode, player-pick, or sending. +func start_ability_targeting() -> void: + print("AbilityTargeting:: start_ability_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 — show branch buttons. + var choose_one: Variant = action.get("chooseone") + if choose_one is Dictionary and not (choose_one as Dictionary).get("branches", []).is_empty(): + if selection_controller != null: + selection_controller.set_mode(current_target_mode()) + emit_signal("highlights_cleared") + 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) + + 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 + + # Auto-resolved by server — skip. + var auto_ownerships: Array = ["Self", "ExactSelf", "Random", "Target"] + if count_all or ownership in auto_ownerships: + ability_cur_action_idx += 1 + start_ability_targeting() + return + + # Player / zone selection. + var zone_scopes: Array = ["Player", "Hand", "Deck", "Discard", "AnyZone"] + if scope in zone_scopes: + if selection_controller != null: + selection_controller.set_mode(current_target_mode()) + emit_signal("highlights_cleared") + show_player_panel(scope, ownership) + return + + # Board selection. + if selection_controller != null: + selection_controller.set_mode(current_target_mode()) + emit_signal("highlights_cleared") + highlight_ability_targets(action) + + if ability_target_up_to and ability_target_n > 1: + show_ability_confirm_btn() + + +func advance_ability_targeting() -> void: + hide_ability_confirm_btn() + hide_branch_panel() + hide_player_panel() + emit_signal("highlights_cleared") + ability_targets_this_action = 0 + start_ability_targeting() + + +## Highlight valid ability targets in blue. +func highlight_ability_targets(action: Dictionary) -> void: + 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_v: Variant = target_sel.get("filters", []) + var filters: Array = filters_v as Array if filters_v is Array else [] + + var linear_only: bool = ability_range.get("linearonly", false) + var requires_los: bool = ability_range.get("requireslos", false) + + 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. + if type_ == "Tile": + var bw: int = Game.board_width() + var bh: int = Game.board_height() + for tx: int in range(bw): + for ty: int in range(bh): + if not src_pos_ab.is_empty(): + var sx: int = int(src_pos_ab.get("x", 0)) + var sy: int = int(src_pos_ab.get("y", 0)) + if linear_only and not is_linear(sx, sy, tx, ty): + continue + if requires_los and pathfinder != null and not pathfinder.client_has_los(sx, sy, tx, ty): + continue + if tile_passes_filters(tx, ty, filters): + emit_signal("highlight_add_requested", tx, ty, "ability") + return + + # Unit-type target. + var include_enemy: bool = ownership in ["Enemy", "Any"] + var include_friendly: bool = ownership in ["Owner", "Ally", "Any"] + 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_ in ["Spirit", "ArchSpirit", "SpiritToken", "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: int = 0 + if pathfinder != null: + dist = pathfinder.board_distance( + int(pos.get("x", 0)), int(pos.get("y", 0)), + int(src_pos_ab.get("x", 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 + if not src_pos_ab.is_empty(): + var ux: int = int(pos.get("x", 0)); var uy: int = int(pos.get("y", 0)) + var sx: int = int(src_pos_ab.get("x", 0)); var sy: int = int(src_pos_ab.get("y", 0)) + if linear_only and not is_linear(sx, sy, ux, uy): + continue + if requires_los and pathfinder != null and not pathfinder.client_has_los(sx, sy, ux, uy): + continue + emit_signal("highlight_add_requested", int(pos.get("x", 0)), int(pos.get("y", 0)), "ability") + + +func unit_passes_filters(unit: Dictionary, filters: Array) -> bool: + if filters.is_empty(): + return true + var src: Dictionary = 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: int = 0 + if pathfinder != null: + dist = pathfinder.board_distance( + int(tgt_pos.get("x", 0)), int(tgt_pos.get("y", 0)), + int(src_pos.get("x", 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: int = 0 + if pathfinder != null: + dist = pathfinder.board_distance( + int(tgt_pos.get("x", 0)), int(tgt_pos.get("y", 0)), + int(src_pos.get("x", 0)), int(src_pos.get("y", 0))) + if dist != 1: + return false + 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 + + +func tile_passes_filters(tx: int, ty: int, filters: Array) -> bool: + if filters.is_empty(): + return true + var src: Dictionary = 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: int = 0 + if pathfinder != null: + dist = pathfinder.board_distance(tx, ty, + int(src_pos.get("x", 0)), int(src_pos.get("y", 0))) + if dist < int(f.get("min", 0)) or dist > int(f.get("max", 999)): + return false + return true + + +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) + + +## Show a "Done" button for UpTo selections. +func show_ability_confirm_btn() -> void: + hide_ability_confirm_btn() + var btn: Button = 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() -> void: + hide_ability_confirm_btn() + ability_cur_action_idx += 1 + advance_ability_targeting()) + if hud != null: + 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 + + +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 = PanelContainer.new() + panel.position = Vector2(8, 120) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 8) + vbox.custom_minimum_size = Vector2(190, 0) + + var title: Label = 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: int 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 = Button.new() + btn.text = label_text + btn.add_theme_font_size_override("font_size", 12) + var cap_idx: int = i + btn.pressed.connect(func() -> void: + 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) + if hud != null: + 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: String = triggered_request_id + triggered_request_id = "" + Game.send_triggered_target_response(rid, ability_targets) + elif is_target_pick: + is_target_pick = false + var rid: String = pending_req_id + pending_req_id = "" + Game.send_target_pick_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) + if selection_controller != null: + selection_controller.set_mode(SelectionController.Mode.NONE) + + +## Called when the server pushes a triggered_target_request for this player. +func on_triggered_target_request(req: Dictionary) -> void: + if selection_controller != null and selection_controller.mode != SelectionController.Mode.NONE: + selection_controller.set_mode(SelectionController.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 = [] + + var action_json: String = str(req.get("actionJson", "{}")) + var action_raw: Variant = 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" and range_json != "": + var r: Variant = 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 for triggered ability targeting. +func show_triggered_banner(ability_name: String) -> void: + if hud == null: + return + var lbl: Label = 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 the player-selection panel for zone/player ability targets. +func show_player_panel(scope: String, ownership: String) -> void: + hide_player_panel() + + var panel: PanelContainer = PanelContainer.new() + panel.position = Vector2(8, 180) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 8) + vbox.custom_minimum_size = Vector2(160, 0) + + var title: Label = 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) + if hud != null: + hud.add_child(panel) + player_panel = panel + + +func add_player_option(vbox: VBoxContainer, name_: String, + account_id: String, scope: String) -> void: + var zone_scopes: Array = ["Hand", "Deck", "Discard", "AnyZone"] + if scope in zone_scopes: + var lbl: Label = Label.new() + lbl.text = name_ + lbl.add_theme_font_size_override("font_size", 12) + vbox.add_child(lbl) + + var zone_hbox: HBoxContainer = 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 = 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: + var btn: Button = 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 + +# ── Helpers ─────────────────────────────────────────────────────────────────── + +## Recursively normalise all Dictionary keys to lowercase. +func normalize_keys(value: Variant) -> Variant: + if value is Dictionary: + var result: Dictionary = {} + for k: Variant 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: Variant in (value as Array): + result.append(normalize_keys(item)) + return result + return value + + +## Returns the flat action list from a parsed ability definition. +func get_ability_actions(ab: Dictionary) -> Array: + var legacy: Array = ab.get("actions", []) + if not legacy.is_empty(): + return legacy + var ag: Variant = ab.get("actiongroup") + if ag is Dictionary: + return flatten_and_group(ag as Dictionary) + return [] + + +func flatten_and_group(ag: Dictionary) -> Array: + var logic: String = str(ag.get("logicop", "and")).to_lower() + var result: Array = [] + result.append_array(ag.get("actions", [])) + if logic == "and": + for g: Variant in ag.get("groups", []): + if g is Dictionary: + result.append_array(flatten_and_group(g as Dictionary)) + return result + + +## Clamp a panel's desired top-left so it stays within the viewport. +func clamp_panel_pos(desired: Vector2, panel: Control) -> Vector2: + var vp: Vector2 = get_viewport().get_visible_rect().size + var sz: Vector2 = panel.size + 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)) diff --git a/Client/origin-client/scenes/game/components/selection/ability_targeting.gd.uid b/Client/origin-client/scenes/game/components/selection/ability_targeting.gd.uid new file mode 100644 index 0000000..446db76 --- /dev/null +++ b/Client/origin-client/scenes/game/components/selection/ability_targeting.gd.uid @@ -0,0 +1 @@ +uid://xf03434iiopi diff --git a/Client/origin-client/scenes/game/components/selection/selection_controller.gd b/Client/origin-client/scenes/game/components/selection/selection_controller.gd new file mode 100644 index 0000000..bc67292 --- /dev/null +++ b/Client/origin-client/scenes/game/components/selection/selection_controller.gd @@ -0,0 +1,558 @@ +class_name SelectionController +extends Node + +## Manages board selection state: which mode the player is in, what card/unit +## is selected, and dispatches board-click events to the correct handler. +## Emits signals for highlight changes so game_screen can drive the board visuals. + +# ── Mode enum ───────────────────────────────────────────────────────────────── + +enum Mode { + NONE, + CARD_FROM_HAND, + TERRAMORPHA_SELECT, + UNIT_SELECTED, + PLACEMENT, + SACRIFICE_SELECT, + ABILITY_TARGET, + ABILITY_TARGET_FORCED, +} + +# ── Signals ─────────────────────────────────────────────────────────────────── + +signal mode_changed(new_mode: int) +signal highlights_cleared() +signal highlight_add_requested(x: int, y: int, type_name: String) +signal highlight_tiles_requested(coords: Array, type_name: String) +signal tile_drawer_open_requested(tile_data: Dictionary) +signal tile_drawer_close_requested() +signal camera_follow_requested(world_pos: Vector3) +signal hand_selection_refresh_requested() + +# ── External refs set by game_screen ───────────────────────────────────────── + +## Reference to AbilityTargeting component (set by game_screen._ready). +var ability_targeting: AbilityTargeting = null +## Reference to ServerPromptHandler component (set by game_screen._ready). +var server_prompt_handler: ServerPromptHandler = null +## Reference to TileTargetResolver component (set by game_screen._ready). +var tile_target_resolver: TileTargetResolver = null +## Reference to UnitRegistry component (set by game_screen._ready). +var unit_registry: UnitRegistry = null +## Reference to Pathfinder component (set by game_screen._ready). +var pathfinder: Pathfinder = null +## Grid type string — "Square" or "Hexagon" — set by game_screen after board load. +var board_grid_type: String = "Square" +## Reference to board_ctrl.tile_bodies (Dictionary ref stays in sync automatically). +var tile_bodies: Dictionary = {} + +# ── 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 multi-tile targeting +var terra_targets: Array = [] # Array[Vector2i] +var terra_count: int = 0 # total tiles needed (1/2/3) + +# Sacrifice ArchSpirit coord (unused currently, reserved) +var sac_arch_coord: Vector2i = Vector2i(-1, -1) + +# Dedup tracking +var _last_board_click_frame: int = -1 +var _last_board_click_coord: Vector2i = Vector2i(-999, -999) + +# ── Public API ──────────────────────────────────────────────────────────────── + +## Central mode setter — clears stale selection state when returning to NONE. +func set_mode(new_mode: Mode) -> void: + print("SelectionController:: set_mode: ", new_mode) + mode = new_mode + terra_targets = [] + terra_count = 0 + if new_mode != Mode.NONE and new_mode != Mode.UNIT_SELECTED: + emit_signal("tile_drawer_close_requested") + if new_mode == Mode.NONE: + sel_card_id = "" + sel_unit_id = "" + if ability_targeting != null: + ability_targeting.reset_ability_state() + ability_targeting.hide_ability_confirm_btn() + ability_targeting.hide_branch_panel() + ability_targeting.hide_ability_panel() + ability_targeting.hide_player_panel() + emit_signal("highlights_cleared") + emit_signal("mode_changed", new_mode as int) + emit_signal("hand_selection_refresh_requested") + + +## Selects a friendly unit: sets UNIT_SELECTED mode, highlights move/attack ranges, +## optionally pans the camera, and opens the ability panel. +func select_unit(unit_id: String) -> void: + if mode == Mode.ABILITY_TARGET_FORCED: + return + var unit: Dictionary = Game.get_unit_by_id(unit_id) + if unit.is_empty(): + return + if unit_registry != null and unit_registry.is_ruin_unit(unit): + return + + if ability_targeting != null: + ability_targeting.hide_ability_panel() + sel_unit_id = unit_id + set_mode(Mode.UNIT_SELECTED) + emit_signal("highlights_cleared") + + # Highlight own tile and pan camera. + var upos: Dictionary = unit.get("position", {}) + if not upos.is_empty(): + var ux: int = int(upos.get("x", 0)) + var uy: int = int(upos.get("y", 0)) + emit_signal("highlight_add_requested", ux, uy, "selector") + if Settings.camera_follow_unit and pathfinder != null: + var target: Vector3 = pathfinder.coord_to_world(ux, uy) + emit_signal("camera_follow_requested", target) + + # Movement / attack ranges. + if tile_target_resolver != null: + emit_signal("highlight_tiles_requested", tile_target_resolver.valid_move_tiles(unit, tile_bodies), "movement") + emit_signal("highlight_tiles_requested", tile_target_resolver.attack_range_tiles(unit, tile_bodies), "terramorpha") + emit_signal("highlight_tiles_requested", tile_target_resolver.valid_attack_target_coords(unit), "attack") + + # Ability panel. + if ability_targeting != null: + ability_targeting.show_ability_panel(unit_id, unit) + + +## Primary board-click dispatcher — called from game_screen when a board click arrives. +func handle_board_click(mouse_pos: Vector2, coord: Vector2i, unit_id: String) -> void: + var cf: int = Engine.get_process_frames() + if cf == _last_board_click_frame and coord == _last_board_click_coord: + return + _last_board_click_frame = cf + _last_board_click_coord = coord + + # Resolve occupant when clicking a tile with no direct unit-mesh hit. + var resolved_unit_id: String = unit_id + + if mode == Mode.ABILITY_TARGET_FORCED: + _handle_forced_target_click(coord, resolved_unit_id) + return + + match mode: + Mode.NONE: + _handle_none_click(coord, resolved_unit_id) + Mode.CARD_FROM_HAND: + _handle_card_from_hand_click(coord) + Mode.TERRAMORPHA_SELECT: + _handle_terramorpha_click(coord) + Mode.UNIT_SELECTED: + _handle_unit_selected_click(coord, resolved_unit_id) + Mode.PLACEMENT: + if coord.x >= 0: + Game.send_place_arch_spirit(coord.x, coord.y) + set_mode(Mode.NONE) + Mode.SACRIFICE_SELECT: + _handle_sacrifice_click(coord, resolved_unit_id) + Mode.ABILITY_TARGET: + _handle_ability_target_click(coord, resolved_unit_id) + + +# ── Private click handlers ──────────────────────────────────────────────────── + +func _resolve_occupant(coord: Vector2i, existing_unit_id: String) -> String: + if not existing_unit_id.is_empty() or coord.x < 0: + return existing_unit_id + var tile: Dictionary = Game.get_tile(coord.x, coord.y) + var raw_occ: Variant = tile.get("occupantId") + var occ: String = "" if raw_occ == null else str(raw_occ) + if not occ.is_empty() and occ != "null": + var occ_unit: Dictionary = Game.get_unit_by_id(occ) + if unit_registry != null and not unit_registry.is_ruin_unit(occ_unit): + return occ + return existing_unit_id + + +func _handle_forced_target_click(coord: Vector2i, unit_id: String) -> void: + var resolved: String = _resolve_occupant(coord, unit_id) + + # Server-driven tile pick — send directly. + if ability_targeting != null and ability_targeting.is_tile_pick and coord.x >= 0: + ability_targeting.is_tile_pick = false + var rid: String = ability_targeting.pending_req_id + ability_targeting.pending_req_id = "" + set_mode(Mode.NONE) + emit_signal("highlights_cleared") + Game.send_tile_pick_response(rid, coord.x, coord.y) + return + + # Collect board target. + var collected: bool = false + if ability_targeting != null: + if not resolved.is_empty(): + ability_targeting.ability_targets.append({ + "actionIndex": ability_targeting.ability_cur_action_idx, + "instanceId": resolved + }) + ability_targeting.ability_targets_this_action += 1 + collected = true + elif coord.x >= 0: + ability_targeting.ability_targets.append({ + "actionIndex": ability_targeting.ability_cur_action_idx, + "coord": { "x": coord.x, "y": coord.y } + }) + ability_targeting.ability_targets_this_action += 1 + collected = true + + if not collected: + set_mode(Mode.NONE) + elif ability_targeting.ability_targets_this_action >= ability_targeting.ability_target_n: + ability_targeting.ability_cur_action_idx += 1 + ability_targeting.advance_ability_targeting() + + +func _handle_none_click(coord: Vector2i, unit_id: String) -> void: + var resolved: String = _resolve_occupant(coord, unit_id) + if coord.x >= 0: + emit_signal("tile_drawer_open_requested", Game.get_tile(coord.x, coord.y)) + if Settings.click_to_focus_camera and pathfinder != null: + var world: Vector3 = pathfinder.coord_to_world(coord.x, coord.y) + emit_signal("camera_follow_requested", world) + if not resolved.is_empty() \ + and unit_registry != null and unit_registry.friendly_unit_ids.has(resolved) \ + and Game.is_my_turn() and Game.get_phase() != "Placement": + select_unit(resolved) + + +func _handle_card_from_hand_click(coord: Vector2i) -> void: + var card: Dictionary = _find_hand_card(sel_card_id) + if card.is_empty(): + 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: + set_mode(Mode.NONE) + return + Game.send_play_card(sel_card_id, coord.x, coord.y) + set_mode(Mode.NONE) + + +func _handle_terramorpha_click(coord: Vector2i) -> void: + if coord.x < 0: + set_mode(Mode.NONE) + return + # Validate adjacency. + if terra_targets.size() > 0: + var last: Vector2i = terra_targets.back() as Vector2i + if pathfinder != null and pathfinder.board_distance(coord.x, coord.y, last.x, last.y) != 1: + return + terra_targets.append(coord) + if terra_targets.size() >= terra_count: + var targets: Array = 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: + # Re-highlight: orange for picked, green for valid next. + emit_signal("highlights_cleared") + for t: Vector2i in terra_targets: + emit_signal("highlight_add_requested", t.x, t.y, "terramorpha") + var last2: Vector2i = terra_targets.back() as Vector2i + var bw2: int = Game.board_width() + var bh2: int = Game.board_height() + var terra_dirs: Array[Vector2i] = [] + if board_grid_type == "Hexagon": + terra_dirs = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1), + Vector2i(1,-1), Vector2i(-1,1)] + else: + terra_dirs = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)] + for d: Vector2i in terra_dirs: + var nx: int = last2.x + d.x + var ny: int = last2.y + d.y + if nx < 0 or ny < 0 or nx >= bw2 or ny >= bh2: + continue + emit_signal("highlight_add_requested", nx, ny, "movement") + + +func _handle_unit_selected_click(coord: Vector2i, unit_id: String) -> void: + if coord.x >= 0: + emit_signal("tile_drawer_open_requested", Game.get_tile(coord.x, coord.y)) + var resolved: String = _resolve_occupant(coord, unit_id) + if not resolved.is_empty(): + if unit_registry != null and unit_registry.enemy_unit_ids.has(resolved): + Game.send_attack(sel_unit_id, resolved) + set_mode(Mode.NONE) + elif resolved == sel_unit_id: + # Re-click same unit → toggle ability panel. + if ability_targeting != null: + if is_instance_valid(ability_targeting.ability_panel): + ability_targeting.hide_ability_panel() + else: + var resel_unit: Dictionary = Game.get_unit_by_id(resolved) + if not resel_unit.is_empty(): + ability_targeting.show_ability_panel(resolved, resel_unit) + elif unit_registry != null and unit_registry.friendly_unit_ids.has(resolved): + select_unit(resolved) + elif coord.x >= 0: + Game.send_move_unit(sel_unit_id, coord.x, coord.y) + set_mode(Mode.NONE) + + +func _handle_sacrifice_click(coord: Vector2i, unit_id: String) -> void: + var resolved: String = _resolve_occupant(coord, unit_id) + if resolved.is_empty() or (unit_registry != null and not unit_registry.friendly_unit_ids.has(resolved)): + set_mode(Mode.NONE) + return + var unit: Dictionary = Game.get_unit_by_id(resolved) + if unit.is_empty() or unit.get("cardType", "") == "ArchSpirit": + set_mode(Mode.NONE) + return + _confirm_sacrifice(resolved, unit.get("name", "this spirit")) + + +func _handle_ability_target_click(coord: Vector2i, unit_id: String) -> void: + if ability_targeting == null: + return + # Server-driven tile pick. + if ability_targeting.is_tile_pick and coord.x >= 0: + ability_targeting.is_tile_pick = false + var rid: String = ability_targeting.pending_req_id + ability_targeting.pending_req_id = "" + set_mode(Mode.NONE) + emit_signal("highlights_cleared") + Game.send_tile_pick_response(rid, coord.x, coord.y) + return + + var collected: bool = false + if not unit_id.is_empty(): + ability_targeting.ability_targets.append({ + "actionIndex": ability_targeting.ability_cur_action_idx, + "instanceId": unit_id + }) + ability_targeting.ability_targets_this_action += 1 + collected = true + elif coord.x >= 0: + ability_targeting.ability_targets.append({ + "actionIndex": ability_targeting.ability_cur_action_idx, + "coord": { "x": coord.x, "y": coord.y } + }) + ability_targeting.ability_targets_this_action += 1 + collected = true + + if not collected: + set_mode(Mode.NONE) + elif ability_targeting.ability_targets_this_action >= ability_targeting.ability_target_n: + ability_targeting.ability_cur_action_idx += 1 + ability_targeting.advance_ability_targeting() + +# ── ArchSpirit popup menu ───────────────────────────────────────────────────── + +func show_arch_spirit_menu(unit_id: String, unit: Dictionary) -> void: + var menu: PopupMenu = PopupMenu.new() + add_child(menu) + + var sac_spirits: Array = [] + if tile_target_resolver != null: + sac_spirits = tile_target_resolver.valid_sacrifice_spirits() + if not sac_spirits.is_empty(): + menu.add_item("Sacrifice a Spirit", 0) + + var can_ascend: bool = false + var can_transition: bool = false + var cur_tier: int = 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) + emit_signal("highlights_cleared") + var spirits: Array = [] + if tile_target_resolver != null: + spirits = tile_target_resolver.valid_sacrifice_spirits() + for spirit: Dictionary in spirits: + var sp: Dictionary = spirit.get("position", {}) + if not sp.is_empty(): + emit_signal("highlight_add_requested", int(sp.get("x", 0)), int(sp.get("y", 0)), "movement") + + +func _confirm_sacrifice(unit_id: String, unit_name: String) -> void: + var dlg: ConfirmationDialog = 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 = 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 = 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 channel_ruin(card: Dictionary) -> void: + var card_affinity: String = card.get("affinity", "") + var board: Dictionary = Game.get_board() + var has_valid: bool = false + for tile: Dictionary in board.get("tiles", []): + var ruin_id_v: Variant = tile.get("ruinId", null) + var ruin_id: String = "" if ruin_id_v == null else str(ruin_id_v) + if not ruin_id.is_empty() and ruin_id != "null": + continue + if card_affinity != "" and not _tile_matches_channel_affinity(tile, card_affinity): + continue + has_valid = true + break + + if not has_valid: + var dlg: AcceptDialog = AcceptDialog.new() + dlg.title = "Cannot Channel Ruin" + dlg.dialog_text = "No valid tile available for this Ruin." + dlg.min_size = Vector2(280, 90) + add_child(dlg) + dlg.popup_centered() + dlg.confirmed.connect(func() -> void: dlg.queue_free()) + return + _confirm_channel_ruin(card) + + +func _confirm_channel_ruin(card: Dictionary) -> void: + var dlg: ConfirmationDialog = ConfirmationDialog.new() + dlg.title = "Channel Ruin" + dlg.dialog_text = "Ruin placement is random.\nContinue?" + dlg.ok_button_text = "Channel" + dlg.min_size = Vector2(280, 90) + add_child(dlg) + dlg.popup_centered() + dlg.confirmed.connect(func() -> void: + Game.send_play_card(card.get("instanceId", ""), 0, 0) + dlg.queue_free()) + dlg.canceled.connect(func() -> void: dlg.queue_free()) + + +func _tile_matches_channel_affinity(tile: Dictionary, card_affinity: String) -> bool: + return tile.get("affinity", "") == card_affinity + + +func _get_my_arch_tier() -> int: + var player: Dictionary = Game.get_my_player() + var arch: Dictionary = player.get("archSpirit", {}) as Dictionary + return int(arch.get("tier", 1)) + + +func _show_card_picker(title: String, cards: Array, on_pick: Callable) -> void: + var dlg: AcceptDialog = AcceptDialog.new() + dlg.title = title + dlg.min_size = Vector2(320, 200) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 6) + for card: Dictionary in cards: + var btn: Button = 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()) + +# ── Helpers ─────────────────────────────────────────────────────────────────── + +func _find_hand_card(iid: String) -> Dictionary: + for card: Dictionary in Game.get_hand(): + if str(card.get("instanceId", "")) == iid: + return card + return {} diff --git a/Client/origin-client/scenes/game/components/selection/selection_controller.gd.uid b/Client/origin-client/scenes/game/components/selection/selection_controller.gd.uid new file mode 100644 index 0000000..043bb5c --- /dev/null +++ b/Client/origin-client/scenes/game/components/selection/selection_controller.gd.uid @@ -0,0 +1 @@ +uid://dvgce0i548dvn diff --git a/Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd b/Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd new file mode 100644 index 0000000..f3dd0cb --- /dev/null +++ b/Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd @@ -0,0 +1,514 @@ +class_name ServerPromptHandler +extends Node + +## Handles all server-driven ability-pause prompts: +## PendingCostPick, PendingCostGroupPick, PendingActionGroupPick, +## PendingBranchPick, PendingTargetPick, PendingTilePick, +## PendingPlayerPick, PendingRevealChoicePick. +## +## External refs (set by game_screen._ready): +## selection_controller — for set_mode() calls +## ability_targeting — for target-pick setup and normalize_keys +## pathfinder — for board_distance in tile-pick range checks +## hud — CanvasLayer that owns all 2D HUD children + +# ── Signals ─────────────────────────────────────────────────────────────────── + +signal highlight_add_requested(x: int, y: int, type_name: String) +signal highlights_cleared() + +# ── External refs ───────────────────────────────────────────────────────────── + +var selection_controller: SelectionController = null +var ability_targeting: AbilityTargeting = null +var pathfinder: Pathfinder = null +var hud: CanvasLayer = null + +# ── Prompt state ────────────────────────────────────────────────────────────── + +var pending_req_id: String = "" +var pending_source_id: String = "" +var pending_prompt_panel: Control = null + +# Tile-pick constraints +var tile_pick_max_range: int = 0 +var tile_pick_require_empty: bool = false +var tile_pick_require_occupied: bool = false + +# Cost-pick accumulation +var cost_pick_selected: Array[String] = [] +var cost_pick_amount: int = 1 + +# Reveal-choice ordering +var reveal_ordered_indices: Array = [] +var reveal_total_cards: int = 0 +var reveal_required_count: int = 1 + +# ── Helpers ─────────────────────────────────────────────────────────────────── + +func hide_pending_prompt_panel() -> void: + if is_instance_valid(pending_prompt_panel): + pending_prompt_panel.queue_free() + pending_prompt_panel = null + + +func _normalize_keys(value: Variant) -> Variant: + if ability_targeting != null: + return ability_targeting.normalize_keys(value) + # Fallback inline normaliser. + if value is Dictionary: + var result: Dictionary = {} + for k: Variant 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: Variant in (value as Array): + result.append(_normalize_keys(item)) + return result + return value + + +func _cancel_current_mode() -> void: + if selection_controller != null and selection_controller.mode != SelectionController.Mode.NONE: + selection_controller.set_mode(SelectionController.Mode.NONE) + +# ── PendingCostPick ─────────────────────────────────────────────────────────── + +func on_cost_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + pending_req_id = str(req.get("requestId", "")) + pending_source_id = str(req.get("sourceInstanceId", "")) + cost_pick_selected.clear() + cost_pick_amount = int(req.get("amount", 1)) + var cost_type: String = str(req.get("costType", "")) + var pick_mode: String = str(req.get("pickMode", "SelfPick")) + + hide_pending_prompt_panel() + var panel: PanelContainer = PanelContainer.new() + panel.position = Vector2(8, 160) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 6) + vbox.custom_minimum_size = Vector2(200, 0) + + var title: Label = Label.new() + title.text = "Cost: %s (select %d)" % [cost_type, cost_pick_amount] + title.add_theme_font_size_override("font_size", 13) + title.add_theme_color_override("font_color", Color(1.0, 0.75, 0.2)) + vbox.add_child(title) + vbox.add_child(HSeparator.new()) + + var candidates_raw: Variant = JSON.parse_string(str(req.get("candidatesJson", "[]"))) + var candidates: Array = candidates_raw as Array if candidates_raw is Array else [] + if candidates.is_empty(): + var lbl: Label = Label.new() + lbl.text = "(no candidates)" + lbl.add_theme_font_size_override("font_size", 11) + vbox.add_child(lbl) + else: + for cand: Variant in candidates: + var card_d: Dictionary = cand as Dictionary + var iid: String = str(card_d.get("instanceId", "")) + var name_: String = str(card_d.get("name", iid)) + var btn: Button = Button.new() + btn.text = name_ + btn.add_theme_font_size_override("font_size", 11) + var cap_iid: String = iid + btn.pressed.connect(func() -> void: + if not cap_iid in cost_pick_selected: + cost_pick_selected.append(cap_iid) + btn.modulate = Color(0.4, 1.0, 0.4) + if cost_pick_selected.size() >= cost_pick_amount: + finish_cost_pick()) + vbox.add_child(btn) + + if pick_mode == "SelfPick": + var confirm: Button = Button.new() + confirm.text = "Confirm" + confirm.add_theme_font_size_override("font_size", 12) + confirm.pressed.connect(finish_cost_pick) + vbox.add_child(confirm) + + panel.add_child(vbox) + if hud != null: + hud.add_child(panel) + pending_prompt_panel = panel + + +func finish_cost_pick() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id + pending_req_id = "" + Game.send_cost_pick_response(rid, cost_pick_selected) + cost_pick_selected.clear() + +# ── PendingCostGroupPick ────────────────────────────────────────────────────── + +func on_cost_group_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + pending_req_id = str(req.get("requestId", "")) + pending_source_id = str(req.get("sourceInstanceId", "")) + + var group_raw: Variant = JSON.parse_string(str(req.get("costGroupJson", "{}"))) + var group: Dictionary = _normalize_keys(group_raw) as Dictionary if group_raw is Dictionary else {} + var entries: Array = group.get("entries", []) as Array + var groups: Array = group.get("groups", []) as Array + var logic: String = str(group.get("logicop", group.get("logicOp", "OR"))) + + hide_pending_prompt_panel() + var panel: PanelContainer = PanelContainer.new() + panel.position = Vector2(8, 160) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 8) + vbox.custom_minimum_size = Vector2(200, 0) + + var title: Label = Label.new() + title.text = "Choose Cost (%s):" % logic + title.add_theme_font_size_override("font_size", 13) + title.add_theme_color_override("font_color", Color(1.0, 0.75, 0.2)) + vbox.add_child(title) + vbox.add_child(HSeparator.new()) + + var option_idx: int = 0 + for entry: Variant in entries: + var entry_d: Dictionary = entry as Dictionary + var label: String = str(entry_d.get("typestr", entry_d.get("typeStr", "Option %d" % (option_idx + 1)))) + var btn: Button = Button.new() + btn.text = label + btn.add_theme_font_size_override("font_size", 12) + var cap_idx: int = option_idx + btn.pressed.connect(func() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id; pending_req_id = "" + Game.send_cost_group_pick_response(rid, cap_idx)) + vbox.add_child(btn) + option_idx += 1 + for grp: Variant in groups: + var grp_d: Dictionary = grp as Dictionary + var lop: String = str(grp_d.get("logicop", grp_d.get("logicOp", "OR"))) + var btn: Button = Button.new() + btn.text = "Group (%s)" % lop + btn.add_theme_font_size_override("font_size", 12) + var cap_idx: int = option_idx + btn.pressed.connect(func() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id; pending_req_id = "" + Game.send_cost_group_pick_response(rid, cap_idx)) + vbox.add_child(btn) + option_idx += 1 + + panel.add_child(vbox) + if hud != null: + hud.add_child(panel) + pending_prompt_panel = panel + +# ── PendingActionGroupPick ──────────────────────────────────────────────────── + +func on_action_group_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + pending_req_id = str(req.get("requestId", "")) + pending_source_id = str(req.get("sourceInstanceId", "")) + + var group_raw: Variant = JSON.parse_string(str(req.get("actionGroupJson", "{}"))) + var group: Dictionary = _normalize_keys(group_raw) as Dictionary if group_raw is Dictionary else {} + var actions: Array = group.get("actions", []) as Array + var subgrps: Array = group.get("groups", []) as Array + var logic: String = str(group.get("logicop", group.get("logicOp", "OR"))) + + hide_pending_prompt_panel() + var panel: PanelContainer = PanelContainer.new() + panel.position = Vector2(8, 160) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 8) + vbox.custom_minimum_size = Vector2(200, 0) + + var title: Label = Label.new() + title.text = "Choose Action (%s):" % logic + title.add_theme_font_size_override("font_size", 13) + title.add_theme_color_override("font_color", Color(0.4, 0.8, 1.0)) + vbox.add_child(title) + vbox.add_child(HSeparator.new()) + + var option_idx: int = 0 + for act: Variant in actions: + var act_d: Dictionary = act as Dictionary + var label: String = str(act_d.get("label", "Action %d" % (option_idx + 1))) + if label.is_empty(): + var tgt: Dictionary = act_d.get("target", {}) as Dictionary + label = "%s %s" % [tgt.get("ownership", ""), tgt.get("targetType", "")] + label = label.strip_edges() + if label.is_empty(): + label = "Action %d" % (option_idx + 1) + var btn: Button = Button.new() + btn.text = label + btn.add_theme_font_size_override("font_size", 12) + var cap_idx: int = option_idx + btn.pressed.connect(func() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id; pending_req_id = "" + Game.send_action_group_pick_response(rid, cap_idx)) + vbox.add_child(btn) + option_idx += 1 + for grp: Variant in subgrps: + var grp_d: Dictionary = grp as Dictionary + var lop: String = str(grp_d.get("logicop", grp_d.get("logicOp", "OR"))) + var btn: Button = Button.new() + btn.text = "Group (%s)" % lop + btn.add_theme_font_size_override("font_size", 12) + var cap_idx: int = option_idx + btn.pressed.connect(func() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id; pending_req_id = "" + Game.send_action_group_pick_response(rid, cap_idx)) + vbox.add_child(btn) + option_idx += 1 + + panel.add_child(vbox) + if hud != null: + hud.add_child(panel) + pending_prompt_panel = panel + +# ── PendingBranchPick ───────────────────────────────────────────────────────── + +func on_branch_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + pending_req_id = str(req.get("requestId", "")) + pending_source_id = str(req.get("sourceInstanceId", "")) + + var branches_raw: Variant = JSON.parse_string(str(req.get("branchesJson", "[]"))) + var branches: Array = _normalize_keys(branches_raw) as Array if branches_raw is Array else [] + + hide_pending_prompt_panel() + var panel: PanelContainer = PanelContainer.new() + panel.position = Vector2(8, 120) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 8) + vbox.custom_minimum_size = Vector2(190, 0) + + var title: Label = 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: int in branches.size(): + var branch: Dictionary = branches[i] as Dictionary + var label: String = str(branch.get("label", "Option %d" % (i + 1))) + var btn: Button = Button.new() + btn.text = label + btn.add_theme_font_size_override("font_size", 12) + var cap_idx: int = i + btn.pressed.connect(func() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id; pending_req_id = "" + Game.send_branch_pick_response(rid, cap_idx)) + vbox.add_child(btn) + + panel.add_child(vbox) + if hud != null: + hud.add_child(panel) + pending_prompt_panel = panel + +# ── PendingTargetPick ───────────────────────────────────────────────────────── + +func on_target_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + if ability_targeting == null: + return + + ability_targeting.is_target_pick = true + ability_targeting.pending_req_id = str(req.get("requestId", "")) + pending_req_id = ability_targeting.pending_req_id + pending_source_id = str(req.get("sourceInstanceId", "")) + ability_targeting.ability_unit_id = pending_source_id + ability_targeting.ability_idx = -1 + ability_targeting.ability_card_id = "" + ability_targeting.ability_target_conditions = [] + + var action_json: String = str(req.get("actionJson", "{}")) + var action_raw: Variant = JSON.parse_string(action_json) + if action_raw is Dictionary: + ability_targeting.ability_def = [_normalize_keys(action_raw)] + elif action_raw is Array: + ability_targeting.ability_def = _normalize_keys(action_raw) as Array + else: + ability_targeting.ability_def = [] + + var range_json: String = str(req.get("rangeJson", "")) + if not range_json.is_empty() and range_json != "null": + var r: Variant = JSON.parse_string(range_json) + ability_targeting.ability_range = _normalize_keys(r) as Dictionary if r is Dictionary else {} + else: + ability_targeting.ability_range = {} + + ability_targeting.ability_targets = [] + ability_targeting.ability_cur_action_idx = 0 + ability_targeting.ability_target_n = 1 + ability_targeting.ability_target_up_to = false + ability_targeting.ability_targets_this_action = 0 + ability_targeting.start_ability_targeting() + +# ── PendingTilePick ─────────────────────────────────────────────────────────── + +func on_tile_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + + var req_id: String = str(req.get("requestId", "")) + var source_id: String = str(req.get("sourceInstanceId", "")) + + tile_pick_max_range = int(req.get("maxRange", 0)) + tile_pick_require_empty = bool(req.get("requireEmpty", false)) + tile_pick_require_occupied = bool(req.get("requireOccupied", false)) + + # Write shared state so selection_controller's forced-target click can read it. + if ability_targeting != null: + ability_targeting.is_tile_pick = true + ability_targeting.pending_req_id = req_id + ability_targeting.ability_unit_id = source_id + pending_req_id = req_id + pending_source_id = source_id + + if selection_controller != null: + selection_controller.set_mode(SelectionController.Mode.ABILITY_TARGET_FORCED) + emit_signal("highlights_cleared") + + var bw: int = Game.board_width() + var bh: int = Game.board_height() + var src_pos: Dictionary = {} + if not source_id.is_empty(): + var src_unit: Variant = Game.get_unit_by_id(source_id) + if src_unit is Dictionary: + src_pos = (src_unit as Dictionary).get("position", {}) as Dictionary + + var occupant_ownership: String = str(req.get("occupantOwnership", "Any")) + for tx: int in range(bw): + for ty: int in range(bh): + if tile_pick_max_range > 0 and not src_pos.is_empty() and pathfinder != null: + var dist: int = pathfinder.board_distance( + tx, ty, int(src_pos.get("x", 0)), int(src_pos.get("y", 0))) + if dist > tile_pick_max_range: + continue + var tile: Dictionary = Game.get_tile(tx, ty) + if tile.is_empty(): + continue + var occ_id: String = str(tile.get("occupantId", "")) + if tile_pick_require_empty and not occ_id.is_empty(): + continue + if tile_pick_require_occupied and occ_id.is_empty(): + continue + if tile_pick_require_occupied and not occ_id.is_empty() and occupant_ownership != "Any": + var occ_owner: String = str(tile.get("occupantOwner", "")) + var my_id: String = Auth.user_id + if occupant_ownership == "Self" and occ_owner != my_id: + continue + if occupant_ownership == "Enemy" and occ_owner == my_id: + continue + emit_signal("highlight_add_requested", tx, ty, "ability") + +# ── PendingPlayerPick ───────────────────────────────────────────────────────── + +func on_player_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + pending_req_id = str(req.get("requestId", "")) + pending_source_id = str(req.get("sourceInstanceId", "")) + + var valid_ids_raw: Variant = req.get("validPlayerIds") + var valid_ids: Array = valid_ids_raw as Array if valid_ids_raw is Array else [] + + hide_pending_prompt_panel() + var panel: PanelContainer = PanelContainer.new() + panel.position = Vector2(8, 180) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 8) + vbox.custom_minimum_size = Vector2(160, 0) + + var title: Label = 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()) + + for pid_raw: Variant in valid_ids: + var pid: String = str(pid_raw) + var pname: String = Game.get_display_name(pid) + if pname.is_empty(): + pname = pid.substr(0, 8) + var btn: Button = Button.new() + btn.text = pname + btn.add_theme_font_size_override("font_size", 12) + var cap_pid: String = pid + btn.pressed.connect(func() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id; pending_req_id = "" + Game.send_player_pick_response(rid, cap_pid)) + vbox.add_child(btn) + + panel.add_child(vbox) + if hud != null: + hud.add_child(panel) + pending_prompt_panel = panel + +# ── PendingRevealChoicePick ─────────────────────────────────────────────────── + +func on_reveal_choice_pick_request(req: Dictionary) -> void: + _cancel_current_mode() + pending_req_id = str(req.get("requestId", "")) + pending_source_id = str(req.get("sourceInstanceId", "")) + reveal_required_count = int(req.get("count", 1)) + reveal_ordered_indices.clear() + + var cards_raw: Variant = JSON.parse_string(str(req.get("revealedCardsJson", "[]"))) + var cards: Array = _normalize_keys(cards_raw) as Array if cards_raw is Array else [] + reveal_total_cards = cards.size() + + hide_pending_prompt_panel() + var panel: PanelContainer = PanelContainer.new() + panel.position = Vector2(8, 100) + var vbox: VBoxContainer = VBoxContainer.new() + vbox.add_theme_constant_override("separation", 6) + vbox.custom_minimum_size = Vector2(210, 0) + + var title: Label = Label.new() + title.text = "Order top %d card(s):" % reveal_required_count + title.add_theme_font_size_override("font_size", 13) + title.add_theme_color_override("font_color", Color(0.6, 1.0, 0.8)) + vbox.add_child(title) + vbox.add_child(HSeparator.new()) + + for i: int in cards.size(): + var card_d: Dictionary = cards[i] as Dictionary + var name_: String = str(card_d.get("name", "Card %d" % (i + 1))) + var btn: Button = Button.new() + btn.text = "%d. %s" % [i + 1, name_] + btn.add_theme_font_size_override("font_size", 11) + var cap_i: int = i + var cap_btn: Button = btn + btn.pressed.connect(func() -> void: + if cap_i in reveal_ordered_indices: return + reveal_ordered_indices.append(cap_i) + cap_btn.modulate = Color(0.4, 1.0, 0.5) + cap_btn.text = "#%d %s" % [reveal_ordered_indices.size(), name_] + if reveal_ordered_indices.size() >= reveal_required_count: + finish_reveal_pick()) + vbox.add_child(btn) + + var confirm: Button = Button.new() + confirm.text = "Confirm Order" + confirm.add_theme_font_size_override("font_size", 12) + confirm.pressed.connect(finish_reveal_pick) + vbox.add_child(HSeparator.new()) + vbox.add_child(confirm) + + panel.add_child(vbox) + if hud != null: + hud.add_child(panel) + pending_prompt_panel = panel + + +func finish_reveal_pick() -> void: + hide_pending_prompt_panel() + var rid: String = pending_req_id; pending_req_id = "" + Game.send_reveal_choice_pick_response(rid, reveal_ordered_indices) + reveal_ordered_indices.clear() diff --git a/Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd.uid b/Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd.uid new file mode 100644 index 0000000..7110528 --- /dev/null +++ b/Client/origin-client/scenes/game/components/selection/server_prompt_handler.gd.uid @@ -0,0 +1 @@ +uid://dxl0o2g2aj4bc diff --git a/Client/origin-client/scenes/game/components/units/unit_animator.gd b/Client/origin-client/scenes/game/components/units/unit_animator.gd new file mode 100644 index 0000000..2391b1e --- /dev/null +++ b/Client/origin-client/scenes/game/components/units/unit_animator.gd @@ -0,0 +1,712 @@ +class_name UnitAnimator +extends Node + +## Handles animation orchestration, hitsplat display, and movement animation. +## +## Reads scene dictionaries from mesh_builder (unit_bodies, anim_players, etc.) +## and from unit_registry (unit_def_ids) via mesh_builder.unit_registry. +## Requires mesh_builder and camera to be set by the parent before any call. + +# ── External dependencies (set by parent) ───────────────────────────────────── + +var mesh_builder: UnitMeshBuilder = null +var camera: Camera3D = null + +# ── Hitsplat icons ──────────────────────────────────────────────────────────── + +const _HITSPLAT_SHIELD_ICON: Texture2D = preload("res://ui/icons/Shield_Overlay_Gradient.png") +const _HITSPLAT_HEART_ICON: Texture2D = preload("res://ui/icons/Heart_Overlay_Gradient.png") + +# ── Owned state ─────────────────────────────────────────────────────────────── + +var prev_unit_hp: Dictionary = {} # instanceId → int +var prev_unit_def: Dictionary = {} # instanceId → int +var prev_unit_pos: Dictionary = {} # instanceId → Vector2i +var last_attack_source_iid: String = "" +var last_attack_target_iid: String = "" +var hitsplat_layer: Control = null +var hitsplat_canvas_layer: CanvasLayer = null + +# ── Hitsplat layer ──────────────────────────────────────────────────────────── + +func ensure_hitsplat_layer() -> Control: + if is_instance_valid(hitsplat_layer): + return hitsplat_layer + # Own CanvasLayer (layer 15) so hitsplats always render above the HUD (10) + # and all dynamic panels added to _hud, but below card popups (20). + hitsplat_canvas_layer = CanvasLayer.new() + hitsplat_canvas_layer.layer = 15 + hitsplat_canvas_layer.name = "HitsplatCanvas" + get_parent().add_child(hitsplat_canvas_layer) + hitsplat_layer = Control.new() + hitsplat_layer.name = "HitsplatLayer" + hitsplat_layer.mouse_filter = Control.MOUSE_FILTER_IGNORE + hitsplat_canvas_layer.add_child(hitsplat_layer) + hitsplat_layer.set_anchors_preset(Control.PRESET_FULL_RECT) + return hitsplat_layer + + +func hitsplat_screen_pos(iid: String) -> Vector2: + var body: StaticBody3D = mesh_builder.unit_bodies.get(iid) as StaticBody3D + if not is_instance_valid(body): + return Vector2.ZERO + var above_tile: float = float(body.get_meta("above_tile", 0.28)) + var world_pos: Vector3 = body.global_position + Vector3(0.0, above_tile + 0.9, 0.0) + return camera.unproject_position(world_pos) + + +func queue_hitsplats(iid: String, def_amount: int, hp_amount: int, delay: float = 0.0) -> void: + if def_amount <= 0 and hp_amount <= 0: + return + if delay > 0.0: + var queued_iid: String = iid + var queued_def: int = def_amount + var queued_hp: int = hp_amount + var queued_anchor: Vector2 = hitsplat_screen_pos(iid) + var t: Tween = create_tween() + t.tween_callback(func() -> void: + if queued_anchor == Vector2.ZERO: + show_hitsplats(queued_iid, queued_def, queued_hp) + else: + show_hitsplats_at_anchor(queued_iid, queued_def, queued_hp, queued_anchor) + ).set_delay(delay) + return + show_hitsplats(iid, def_amount, hp_amount) + + +func show_hitsplats_once(shown: Dictionary, iid: String, def_amount: int, hp_amount: int, + delay: float = 0.0) -> void: + if def_amount <= 0 and hp_amount <= 0: + return + if shown.has(iid): + return + shown[iid] = true + queue_hitsplats(iid, def_amount, hp_amount, delay) + + +func show_hitsplats(iid: String, def_amount: int, hp_amount: int) -> void: + print("[HITSPLAT] show_hitsplats iid=%s def=%d hp=%d" % [iid.substr(0, 8), def_amount, hp_amount]) + if not mesh_builder.unit_bodies.has(iid): + print("[HITSPLAT] skipped — iid not in unit_bodies") + return + var anchor: Vector2 = hitsplat_screen_pos(iid) + if anchor == Vector2.ZERO: + print("[HITSPLAT] skipped — anchor is Vector2.ZERO (body invalid or not yet placed)") + return + show_hitsplats_at_anchor(iid, def_amount, hp_amount, anchor) + + +func show_hitsplats_at_anchor(iid: String, def_amount: int, hp_amount: int, anchor: Vector2) -> void: + if def_amount > 0: + spawn_hitsplat(iid, def_amount, "Shield", _HITSPLAT_SHIELD_ICON, Color(0.24, 0.58, 1.0), anchor) + if hp_amount > 0: + # When both fire, delay the heart so shield appears first. + if def_amount > 0: + var q_iid: String = iid + var q_hp: int = hp_amount + var q_anchor: Vector2 = anchor + var t: Tween = create_tween() + t.tween_callback(func() -> void: + spawn_hitsplat(q_iid, q_hp, "Heart", _HITSPLAT_HEART_ICON, Color(0.92, 0.24, 0.24), q_anchor) + ).set_delay(0.2) + else: + spawn_hitsplat(iid, hp_amount, "Heart", _HITSPLAT_HEART_ICON, Color(0.92, 0.24, 0.24), anchor) + + +func spawn_hitsplat(iid: String, amount: int, icon_label: String, icon: Texture2D, tint: Color, anchor: Vector2) -> void: + print("[HITSPLAT] %s amount=%d iid=%s" % [icon_label, amount, iid.substr(0, 8)]) + if amount <= 0: + print("[HITSPLAT] skipped — amount <= 0") + return + var layer: Control = ensure_hitsplat_layer() + if not is_instance_valid(layer): + print("[HITSPLAT] skipped — layer invalid") + return + print("[HITSPLAT] spawning at screen pos %s" % anchor) + var root: Control = Control.new() + root.mouse_filter = Control.MOUSE_FILTER_IGNORE + root.size = Vector2(96.0, 40.0) + root.pivot_offset = root.size * 0.5 + root.position = anchor - root.size * 0.5 + Vector2(0.0, -14.0) + layer.add_child(root) + + var icon_rect: TextureRect = TextureRect.new() + icon_rect.texture = icon + icon_rect.expand_mode = TextureRect.EXPAND_IGNORE_SIZE + icon_rect.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED + icon_rect.position = Vector2(0.0, 2.0) + icon_rect.size = Vector2(34.0, 34.0) + icon_rect.modulate = tint + root.add_child(icon_rect) + + var lbl: Label = Label.new() + lbl.text = str(amount) + lbl.position = Vector2(28.0, 0.0) + lbl.size = Vector2(68.0, 36.0) + lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT + lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER + lbl.add_theme_font_size_override("font_size", 20) + lbl.add_theme_color_override("font_color", Color.WHITE) + root.add_child(lbl) + + var tw: Tween = create_tween() + tw.set_parallel(true) + tw.tween_property(root, "position", root.position + Vector2(0.0, -GameConstants.HITSPLAT_RISE_PIXELS), GameConstants.HITSPLAT_LIFETIME)\ + .set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT) + tw.tween_property(root, "modulate:a", 0.0, GameConstants.HITSPLAT_LIFETIME)\ + .set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN) + tw.finished.connect(func() -> void: + if is_instance_valid(root): + root.queue_free() + ) + +# ── Animation playback ──────────────────────────────────────────────────────── + +## 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 = mesh_builder.anim_players.get(iid, null) as AnimationPlayer + if ap == null or not is_instance_valid(ap): + return + # Resolve via CardAnimationBinding override first. + var def_id: String = mesh_builder.unit_registry.unit_def_ids.get(iid, "") + var desired: String = action + if not def_id.is_empty(): + var override: String = ContentCache.get_anim_track(def_id, action) + if not override.is_empty(): + desired = override + var track: String = mesh_builder.resolve_anim_track(ap, desired.to_lower()) + if track.is_empty(): + return + var anim: Animation = 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 mesh_builder.idle_callbacks.has(iid): + var old_cb: Callable = mesh_builder.idle_callbacks[iid] as Callable + if ap.animation_finished.is_connected(old_cb): + ap.animation_finished.disconnect(old_cb) + mesh_builder.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: + mesh_builder.idle_entry_done.erase(iid) + + ap.play(track) + + if loop: + # On subsequent loop iterations skip the GLB entry frames. + if mesh_builder.idle_entry_done.get(iid, false): + ap.seek(GameConstants.ANIM_TRANSITION_SECS, true) + else: + mesh_builder.idle_entry_done[iid] = true + # Schedule the next loop iteration via animation_finished. + var cb: Callable = func(_n: String) -> void: play_unit_anim(iid, action, true) + ap.animation_finished.connect(cb, CONNECT_ONE_SHOT) + mesh_builder.idle_callbacks[iid] = cb + else: + # For one-shot non-death animations: return to idle via animation_finished. + var action_l: String = action.to_lower() + var is_death: bool = 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 mesh_builder.oneshot_callbacks.has(iid): + var old_os: Callable = mesh_builder.oneshot_callbacks[iid] as Callable + if ap.animation_finished.is_connected(old_os): + ap.animation_finished.disconnect(old_os) + mesh_builder.oneshot_callbacks.erase(iid) + var os_cb: Callable = func(_n: String) -> void: play_unit_anim(iid, "idle", true) + ap.animation_finished.connect(os_cb, CONNECT_ONE_SHOT) + mesh_builder.oneshot_callbacks[iid] = os_cb + + +## Returns the duration of the named animation for iid, or fallback if unavailable. +func unit_action_duration(iid: String, action: String, fallback: float = 0.35) -> float: + var ap: AnimationPlayer = mesh_builder.anim_players.get(iid, null) as AnimationPlayer + if ap == null or not is_instance_valid(ap): + return fallback + var def_id: String = mesh_builder.unit_registry.unit_def_ids.get(iid, "") + var desired: String = action + if not def_id.is_empty(): + var override: String = ContentCache.get_anim_track(def_id, action) + if not override.is_empty(): + desired = override + var track: String = mesh_builder.resolve_anim_track(ap, desired.to_lower()) + if track.is_empty(): + return fallback + var anim: Animation = ap.get_animation(track) + if anim == null: + return fallback + return maxf(fallback, float(anim.length)) + + +## Returns the SFX CDN URL for a given unit and sound key, or "" if none assigned. +## 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 = mesh_builder.unit_registry.unit_def_ids.get(iid, "") + if def_id.is_empty(): + return "" + var def: Dictionary = ContentCache.get_definition(def_id) + return str(def.get(sfx_key, "")) + + +## Prime SFX URLs for a unit definition so they are ready when needed. +func prime_unit_sfx(def: Dictionary) -> void: + if def.is_empty(): + return + for sfx_key: String in GameConstants.UNIT_SFX_KEYS: + var url: String = str(def.get(sfx_key, "")).strip_edges() + if not url.is_empty(): + SFX.prime(url) + + +## Returns true if the AnimationPlayer's current track is an "attack" animation. +func is_attack_track(full_name: String) -> bool: + var s: String = full_name.get_slice("/", full_name.get_slice_count("/") - 1) + for alias: String in GameConstants.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 iid. +## Disconnects the previous callback (stored in oneshot_callbacks) and +## connects cb as a new CONNECT_ONE_SHOT handler. +func override_oneshot(iid: String, cb: Callable) -> void: + var ap: AnimationPlayer = mesh_builder.anim_players.get(iid, null) as AnimationPlayer + if ap == null or not is_instance_valid(ap): + return + if mesh_builder.oneshot_callbacks.has(iid): + var old_cb: Callable = mesh_builder.oneshot_callbacks[iid] as Callable + if ap.animation_finished.is_connected(old_cb): + ap.animation_finished.disconnect(old_cb) + mesh_builder.oneshot_callbacks.erase(iid) + ap.animation_finished.connect(cb, CONNECT_ONE_SHOT) + mesh_builder.oneshot_callbacks[iid] = cb + +# ── Counterattack helpers ───────────────────────────────────────────────────── + +## Counterattack phase 2: defender plays "attack", then triggers attacker "damaged". +func play_counter_attack(defender_iid: String, attacker_iid: String, + attacker_def_loss: int, attacker_hp_loss: int, hitsplats_shown: Dictionary) -> void: + if not mesh_builder.unit_bodies.has(defender_iid): + return + if not is_instance_valid(mesh_builder.unit_bodies.get(defender_iid) as Node): + return + play_unit_anim(defender_iid, "attack", false) + SFX.play(sfx_for_unit(defender_iid, "attackSoundUrl")) + var counter_time: float = unit_action_duration(defender_iid, "attack") + var t: Tween = create_tween() + t.tween_callback(func() -> void: + play_unit_anim(defender_iid, "idle", true) + if mesh_builder.unit_bodies.has(attacker_iid) and \ + is_instance_valid(mesh_builder.unit_bodies.get(attacker_iid) as Node): + play_unit_anim(attacker_iid, "damaged", false) + SFX.play(sfx_for_unit(attacker_iid, "damagedSoundUrl")) + show_hitsplats_once(hitsplats_shown, attacker_iid, attacker_def_loss, attacker_hp_loss) + ).set_delay(counter_time) + + +## Full counterattack chain (starts after delay seconds): +## delay → defender "damaged" → defender "attack" → attacker "damaged" + defender "idle" +func play_counter_chain(defender_iid: String, attacker_iid: String, delay: float, + defender_def_loss: int, defender_hp_loss: int, + attacker_def_loss: int, attacker_hp_loss: int, + hitsplats_shown: Dictionary) -> void: + var t: Tween = create_tween() + t.tween_callback(func() -> void: + if not mesh_builder.unit_bodies.has(defender_iid) or \ + not is_instance_valid(mesh_builder.unit_bodies.get(defender_iid) as Node): + return + play_unit_anim(defender_iid, "damaged", false) + SFX.play(sfx_for_unit(defender_iid, "damagedSoundUrl")) + show_hitsplats_once(hitsplats_shown, defender_iid, defender_def_loss, defender_hp_loss) + var damaged_time: float = unit_action_duration(defender_iid, "damaged") + var td: Tween = create_tween() + td.tween_callback(func() -> void: + play_counter_attack(defender_iid, attacker_iid, attacker_def_loss, attacker_hp_loss, hitsplats_shown) + ).set_delay(damaged_time) + ).set_delay(delay) + +# ── Damage animations ───────────────────────────────────────────────────────── + +## 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 mesh_builder.anim_players: + var ap2: AnimationPlayer = mesh_builder.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 + if attacker_iid.is_empty() and not last_attack_source_iid.is_empty() \ + and mesh_builder.unit_bodies.has(last_attack_source_iid): + attacker_iid = last_attack_source_iid + attack_remaining = unit_action_duration(attacker_iid, "attack") + + # ── Collect who took damage / died ─────────────────────────────────────── + var damaged_iids: Dictionary = {} + var defense_hits: Dictionary = {} + var health_hits: Dictionary = {} + var seen_iids: Dictionary = {} + for player: Dictionary in state.get("players", []): + var _arch_raw: Variant = 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: String = str(unit.get("instanceId", "")) + var _hp_v: Variant = unit.get("currentHealth") + var _def_v: Variant = unit.get("currentDefense") + var new_hp: int = 0 if _hp_v == null else int(_hp_v) + var new_def: int = 0 if _def_v == null else int(_def_v) + var old_hp: int = prev_unit_hp.get(iid, new_hp) + var old_def: int = prev_unit_def.get(iid, new_def) + seen_iids[iid] = true + if new_def < old_def: + defense_hits[iid] = old_def - new_def + if new_hp < old_hp: + health_hits[iid] = old_hp - new_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 + var dying_old_hp: int = int(prev_unit_hp.get(iid, 0)) + if dying_old_hp > 0: + health_hits[iid] = dying_old_hp + + # 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_source: String = last_attack_source_iid + var tracked_target: String = last_attack_target_iid + last_attack_source_iid = "" + last_attack_target_iid = "" + if attacker_iid.is_empty() and not tracked_source.is_empty() and mesh_builder.unit_bodies.has(tracked_source): + attacker_iid = tracked_source + attack_remaining = unit_action_duration(attacker_iid, "attack") + var hitsplats_shown: Dictionary = {} + + if damaged_iids.is_empty() and defense_hits.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: String = tracked_target + if attack_remaining > 0.0: + var tb: Tween = 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 + + if damaged_iids.is_empty() and not defense_hits.is_empty(): + for iid: String in defense_hits: + show_hitsplats_once(hitsplats_shown, iid, int(defense_hits.get(iid, 0)), 0, attack_remaining) + if attacker_iid != "" and not tracked_target.is_empty() \ + and tracked_target != attacker_iid: + var blocked_iid: String = tracked_target + if attack_remaining > 0.0: + var tb2: Tween = create_tween() + tb2.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 != "" + + var display_delay: float = attack_remaining if attacker_iid != "" else 0.0 + for iid: String in seen_iids: + show_hitsplats_once( + hitsplats_shown, + iid, + int(defense_hits.get(iid, 0)), + int(health_hits.get(iid, 0)), + display_delay) + for iid: String in dying_iids: + show_hitsplats_once( + hitsplats_shown, + iid, + int(defense_hits.get(iid, 0)), + int(health_hits.get(iid, 0)), + display_delay) + + # ── Schedule animations ─────────────────────────────────────────────────── + if is_counterattack: + # Full chain handles the attacker and primary defender. + play_counter_chain( + defender_iid, + attacker_iid, + attack_remaining, + int(defense_hits.get(defender_iid, 0)), + int(health_hits.get(defender_iid, 0)), + int(defense_hits.get(attacker_iid, 0)), + int(health_hits.get(attacker_iid, 0)), + hitsplats_shown) + # Any other simultaneously-damaged units get a simple delay (uncommon). + for iid: String in seen_iids: + if iid == attacker_iid or iid == defender_iid: + continue + var def_loss: int = int(defense_hits.get(iid, 0)) + var hp_loss: int = int(health_hits.get(iid, 0)) + if def_loss <= 0 and hp_loss <= 0: + continue + var hit_iid: String = iid + var hit_def: int = def_loss + var hit_hp: int = hp_loss + var t2: Tween = create_tween() + t2.tween_callback(func() -> void: + if mesh_builder.unit_bodies.has(hit_iid) and \ + is_instance_valid(mesh_builder.unit_bodies.get(hit_iid) as Node): + if hit_hp > 0: + play_unit_anim(hit_iid, "damaged") + SFX.play(sfx_for_unit(hit_iid, "damagedSoundUrl")) + show_hitsplats_once(hitsplats_shown, hit_iid, hit_def, hit_hp) + ).set_delay(attack_remaining) + else: + for iid: String in seen_iids: + var def_loss: int = int(defense_hits.get(iid, 0)) + var hp_loss: int = int(health_hits.get(iid, 0)) + if def_loss <= 0 and hp_loss <= 0: + continue + var ap: AnimationPlayer = mesh_builder.anim_players.get(iid, null) as AnimationPlayer + if hp_loss > 0 and 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 mesh_builder.oneshot_callbacks.has(iid): + var old_cb: Callable = mesh_builder.oneshot_callbacks[iid] as Callable + if ap.animation_finished.is_connected(old_cb): + ap.animation_finished.disconnect(old_cb) + mesh_builder.oneshot_callbacks.erase(iid) + var cap_iid: String = iid + var cap_def: int = def_loss + var cap_hp: int = hp_loss + var dmg_cb: Callable = func(_n: String) -> void: + play_unit_anim(cap_iid, "damaged", false) + SFX.play(sfx_for_unit(cap_iid, "damagedSoundUrl")) + show_hitsplats_once(hitsplats_shown, cap_iid, cap_def, cap_hp) + ap.animation_finished.connect(dmg_cb, CONNECT_ONE_SHOT) + mesh_builder.oneshot_callbacks[iid] = dmg_cb + elif attack_remaining > 0.0: + # Bystander — delay "damaged" until after the attack lands. + var hit_iid: String = iid + var hit_def: int = def_loss + var hit_hp: int = hp_loss + var t: Tween = create_tween() + t.tween_callback(func() -> void: + if mesh_builder.unit_bodies.has(hit_iid) and \ + is_instance_valid(mesh_builder.unit_bodies.get(hit_iid) as Node): + if hit_hp > 0: + play_unit_anim(hit_iid, "damaged") + SFX.play(sfx_for_unit(hit_iid, "damagedSoundUrl")) + show_hitsplats_once(hitsplats_shown, hit_iid, hit_def, hit_hp) + ).set_delay(attack_remaining) + else: + if hp_loss > 0: + play_unit_anim(iid, "damaged") + SFX.play(sfx_for_unit(iid, "damagedSoundUrl")) + show_hitsplats_once(hitsplats_shown, iid, def_loss, hp_loss) + + for iid: String in dying_iids: + show_hitsplats_once(hitsplats_shown, iid, int(defense_hits.get(iid, 0)), int(health_hits.get(iid, 0))) + play_unit_anim(iid, "dying") + SFX.play(sfx_for_unit(iid, "deathSoundUrl")) + + return true + + +## Update prev_unit_hp, prev_unit_def, 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_def.clear() + prev_unit_pos.clear() + for player: Dictionary in state.get("players", []): + var arch: Dictionary = mesh_builder.unit_registry.safe_arch(player) + for unit: Dictionary in ([arch] + player.get("field", [])): + if unit.is_empty(): + continue + var iid: String = str(unit.get("instanceId", "")) + if iid.is_empty(): + continue + prev_unit_hp[iid] = int(unit.get("currentHealth") or 0) + prev_unit_def[iid] = int(unit.get("currentDefense") or 0) + var pd: Variant = 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)) + +# ── Movement animation ──────────────────────────────────────────────────────── + +## Animate a single unit moving along a BFS path from from_coord to to_coord. +## tile_heights and tile_y_bases are passed explicitly so this method stays pure +## (the mesh builder owns those dicts and provides them via the parent wiring). +## pathfinder is used for coord_to_world conversion. +## Returns the total tween duration in seconds. +func animate_unit_move(iid: String, from_coord: Vector2i, to_coord: Vector2i, + blocked: Dictionary, tile_heights: Dictionary, tile_y_bases: Dictionary, + pathfinder: Pathfinder, tile_bodies: Dictionary) -> float: + var body: StaticBody3D = mesh_builder.unit_bodies.get(iid) as StaticBody3D + if not is_instance_valid(body): + return 0.0 + var path: Array[Vector2i] = pathfinder.bfs_path(from_coord, to_coord, blocked, tile_bodies) + if path.is_empty(): + return 0.0 + var duration: float = path.size() * GameConstants.MOVE_STEP_SECS + # Cancel any existing move tween for this unit. + if mesh_builder.move_anims.has(iid) and mesh_builder.move_anims[iid] != null: + (mesh_builder.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 = float(mesh_builder.model_base_angles.get(iid, 0.0)) + var prev_coord: Vector2i = from_coord + var step_angles: Array[float] = [] + for step: Vector2i in path: + var step_wp: Vector3 = pathfinder.coord_to_world(step.x, step.y) + var prev_wp: Vector3 = pathfinder.coord_to_world(prev_coord.x, prev_coord.y) + var dir: Vector3 = step_wp - prev_wp # XZ direction in world space + step_angles.append(base_angle - atan2(dir.x, -dir.z)) + 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: String = "%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: Tween = create_tween() + tween.set_ease(Tween.EASE_IN_OUT) + tween.set_trans(Tween.TRANS_SINE) + for i: int in path.size(): + var step: Vector2i = path[i] + var wp: Vector3 = pathfinder.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: Node3D = mesh_builder.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), GameConstants.MOVE_STEP_SECS) + # Return to idle rotation and idle animation once movement finishes. + tween.tween_callback(func() -> void: + mesh_builder.move_anims.erase(iid) + var m: Node3D = mesh_builder.unit_meshes.get(iid) as Node3D + if is_instance_valid(m): + m.rotation.y = mesh_builder.idle_rotation(iid) + play_unit_anim(iid, "idle", true)) + mesh_builder.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, tile_heights: Dictionary, + tile_y_bases: Dictionary, pathfinder: Pathfinder, tile_bodies: 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: float = 0.0 + for player: Dictionary in state.get("players", []): + var arch: Dictionary = mesh_builder.unit_registry.safe_arch(player) + for unit: Dictionary in ([arch] + player.get("field", [])): + if unit.is_empty(): + continue + var iid: String = str(unit.get("instanceId", "")) + var pd: Variant = unit.get("position") + if not (pd is Dictionary) or (pd as Dictionary).is_empty(): + continue + var new_coord: Vector2i = 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: float = animate_unit_move(iid, old_coord, new_coord, blocked, + tile_heights, tile_y_bases, pathfinder, tile_bodies) + max_dur = maxf(max_dur, dur) + return max_dur + + +## Schedule a delayed call to rebuild_units via the provided callback. +## If delay <= 0 and a rebuild is already pending, just store the 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. +## The callback signature: func(state: Dictionary) -> void +## The schedule_callback signature: func(state: Dictionary, delay: float) -> void +## game_screen wires this to its own _schedule_rebuild implementation. +signal rebuild_scheduled(state: Dictionary, delay: float) + +func schedule_rebuild(state: Dictionary, delay: float) -> void: + rebuild_scheduled.emit(state, delay) diff --git a/Client/origin-client/scenes/game/components/units/unit_animator.gd.uid b/Client/origin-client/scenes/game/components/units/unit_animator.gd.uid new file mode 100644 index 0000000..4ba8f1b --- /dev/null +++ b/Client/origin-client/scenes/game/components/units/unit_animator.gd.uid @@ -0,0 +1 @@ +uid://bc0e70q4no7nd diff --git a/Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd b/Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd new file mode 100644 index 0000000..5bf2122 --- /dev/null +++ b/Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd @@ -0,0 +1,514 @@ +class_name UnitMeshBuilder +extends Node + +## Owns all per-unit scene objects and handles incremental unit mesh placement. +## +## Call rebuild_units(state) on each state update. +## Requires units_root, tile_heights, tile_y_bases, unit_registry, pathfinder, +## and local_is_p1 to be set by the parent before any call. + +# ── External dependencies (set by parent) ───────────────────────────────────── + +var units_root: Node3D = null +var tile_heights: Dictionary = {} # "x,y" → float +var tile_y_bases: Dictionary = {} # "x,y" → float +var unit_registry: UnitRegistry = null +var pathfinder: Pathfinder = null +var local_is_p1: bool = false + +# ── Owned scene dictionaries ────────────────────────────────────────────────── + +var unit_bodies: Dictionary = {} # instanceId → StaticBody3D +var unit_meshes: Dictionary = {} # instanceId → Node3D (placeholder or real model) +var anim_players: Dictionary = {} # instanceId → AnimationPlayer (null if none) +var move_anims: Dictionary = {} # instanceId → Tween (active movement tweens) +var idle_entry_done: Dictionary = {} # iid → true once first idle entry has played +var idle_callbacks: Dictionary = {} # iid → Callable (active loop reconnect) +var oneshot_callbacks: Dictionary = {} # iid → Callable (animation_finished → next action) +var model_base_angles: Dictionary = {} # iid → float (base facing angle, radians) +var needs_face_rot: Dictionary = {} # iid → bool (team-based 180° flip flag) +var unit_model_retries: Dictionary = {} # iid → int (attempt number, 1-based, capped at 10) + +# ── Incremental rebuild ─────────────────────────────────────────────────────── + +## Incremental diff: add/remove units without recreating unchanged ones. +## Recreating a unit body interrupts its running animation (idle/move/attack), +## causing a one-frame bind-pose flash on every state echo. +func rebuild_units(state: Dictionary) -> void: + # Kill any in-flight movement tweens. + for iid: String in move_anims: + var t: Tween = move_anims[iid] as Tween + if t != null: + t.kill() + move_anims.clear() + + # 1. Collect the desired unit set from the new state. + var my_id: String = Auth.user_id + var team_colors: Dictionary = state.get("teamColors", {}) + var desired: Dictionary = {} # iid → {unit, color, is_enemy} + # Find my team index for ally detection. + var my_team_idx: int = -1 + for player: Dictionary in state.get("players", []): + if str(player.get("accountId", "")).to_lower() == my_id.to_lower(): + my_team_idx = int(player.get("teamIndex", -1)) + break + for player: Dictionary in state.get("players", []): + var pid: String = str(player.get("accountId", "")).to_lower() + var is_mine: bool = pid == my_id.to_lower() + var team_idx: int = int(player.get("teamIndex", -1)) + var is_ally: bool = (not is_mine) and (my_team_idx >= 0) and (team_idx == my_team_idx) + var is_enemy: bool = not (is_mine or is_ally) + # Use the team's palette color; fall back to blue (friendly) or red (enemy). + var hex_str: String = str(team_colors.get(str(team_idx), "")) + var color: Color + if not hex_str.is_empty(): + color = Color.html("#" + hex_str) + elif is_enemy: + color = Color(1.0, 0.35, 0.35) + else: + color = Color(0.3, 0.5, 1.0) + var arch: Dictionary = unit_registry.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": is_enemy} + + # 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: StaticBody3D = 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_registry.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_registry.unit_team_idx.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: Dictionary = desired[iid] as Dictionary + add_unit_mesh(d["unit"] as Dictionary, d["color"] as Color, d["is_enemy"] as bool) + + # 4. Refresh idle rotation for all units — nearest enemy may have changed. + for iid: String in unit_meshes: + if move_anims.has(iid): + continue # don't interrupt an in-progress move + var m: Node3D = unit_meshes.get(iid) as Node3D + if is_instance_valid(m): + m.rotation.y = idle_rotation(iid) + + +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: Vector3 = pathfinder.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 = StaticBody3D.new() + body.set_meta("unit_id", iid) + + var shape: CollisionShape3D = CollisionShape3D.new() + var mi: MeshInstance3D = MeshInstance3D.new() + var mat: StandardMaterial3D = 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 = 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 = CylinderShape3D.new() + cs.radius = 0.22; cs.height = 0.8 + shape.shape = cs + above_tile = 0.4 + "Ruin": + var bm: BoxMesh = 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 = BoxShape3D.new() + bs.size = Vector3(0.25, 1.0, 0.25) + shape.shape = bs + above_tile = 0.5 + _: + var sm: SphereMesh = SphereMesh.new() + sm.radius = 0.28; sm.height = 0.28 + mi.mesh = sm + mat.albedo_color = team_color + var ss: SphereShape3D = 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_registry.unit_def_ids[iid] = def_id + if def_id.is_empty(): + return + var def: Dictionary = ContentCache.get_definition(def_id) + _prime_unit_sfx(def) + var model_asset: Dictionary = find_model3d_asset(def) + var model_url: String = str(model_asset.get("cdnUrl", "")) + var model_etag: String = 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", "south")) + # 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: StaticBody3D = 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: 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: AnimationPlayer = find_animation_player(model_node) + anim_players[iid] = ap + if ap != null: + _request_play_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: int = 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("[UnitMeshBuilder] 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("[UnitMeshBuilder] 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: StaticBody3D = 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_registry.unit_def_ids.get(iid, "") + var def: Dictionary = 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: 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: AnimationPlayer = find_animation_player(model_node) + anim_players[iid] = ap + if ap != null: + _request_play_anim(iid, "idle", true) + print("[UnitMeshBuilder] Model retry %d succeeded for %s" % [attempt, iid]) + , etag) + +# ── Model helpers ───────────────────────────────────────────────────────────── + +## 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: Dictionary = 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: Variant = stack.pop_back() + if n is MeshInstance3D: + var mi: MeshInstance3D = n as MeshInstance3D + if mi.mesh != null: + for i: int in mi.mesh.get_surface_count(): + var mat: Material = mi.get_active_material(i) + if mat is StandardMaterial3D: + var dup: StandardMaterial3D = mat.duplicate() as StandardMaterial3D + dup.albedo_color = dup.albedo_color * tint + mi.set_surface_override_material(i, dup) + for child: Variant 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: Node in node.get_children(): + var found: AnimationPlayer = 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 GameConstants.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: String = 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 the nearest +## enemy unit on the board. Falls back to the fixed north/south heuristic when +## no enemy body is found (e.g. during initial placement before enemies exist). +func idle_rotation(iid: String) -> float: + var base: float = float(model_base_angles.get(iid, 0.0)) + var my_body: StaticBody3D = unit_bodies.get(iid) as StaticBody3D + if is_instance_valid(my_body): + var my_pos: Vector3 = my_body.global_position + var best_sq: float = INF + var best_dir: Vector3 = Vector3.ZERO + # Build opponent list using team index when available (spectate-safe). + # When spectating, all units land in enemy_unit_ids so friend/enemy split + # is meaningless — instead find any unit whose team differs from ours. + var my_team: int = int(unit_registry.unit_team_idx.get(iid, -1)) + var enemy_ids: Array + if my_team >= 0: + enemy_ids = [] + for eid: String in unit_bodies: + if int(unit_registry.unit_team_idx.get(eid, -1)) != my_team: + enemy_ids.append(eid) + else: + var is_enemy_unit: bool = unit_registry.is_enemy_unit(iid) + enemy_ids = unit_registry.enemy_unit_ids.keys() if not is_enemy_unit \ + else unit_registry.friendly_unit_ids.keys() + var found_bodies: int = 0 + for eid: Variant in enemy_ids: + var eb: StaticBody3D = unit_bodies.get(eid) as StaticBody3D + if not is_instance_valid(eb): + continue + found_bodies += 1 + var d: Vector3 = eb.global_position - my_pos + var sq: float = d.x * d.x + d.z * d.z + if sq < best_sq: + best_sq = sq + best_dir = d + if best_sq < INF and (best_dir.x != 0.0 or best_dir.z != 0.0): + var flat: Vector3 = Vector3(best_dir.x, 0.0, best_dir.z).normalized() + return base - atan2(flat.x, -flat.z) + # Log why closest-enemy failed. + push_warning("[IdleRot] FALLBACK iid=%s team=%d enemy_ids=%d bodies_found=%d best_sq=%s dir_xz=(%s,%s)" \ + % [iid.substr(0,8), my_team, enemy_ids.size(), found_bodies, + str(best_sq), str(best_dir.x), str(best_dir.z)]) + else: + push_warning("[IdleRot] FALLBACK iid=%s — body not in unit_bodies (friendly=%d enemy=%d)" \ + % [iid.substr(0,8), unit_registry.friendly_unit_ids.size(), unit_registry.enemy_unit_ids.size()]) + # Fallback: fixed north/south heuristic. + var flip: bool = bool(needs_face_rot.get(iid, false)) + var dir: Vector3 = Vector3(0, 0, 1) if flip else Vector3(0, 0, -1) + return atan2(dir.x, -dir.z) - base + + +## Returns the AABB of a model in its own local space, accounting for child transforms. +func model_local_aabb(root: Node3D) -> AABB: + var result: AABB = AABB() + var first: bool = true + var stack: Array = [root] + while not stack.is_empty(): + var n: Variant = stack.pop_back() + if n is MeshInstance3D: + var mi: MeshInstance3D = n as MeshInstance3D + if mi.mesh != null: + var local_aabb: AABB = mi.get_transform() * mi.mesh.get_aabb() + if first: + result = local_aabb + first = false + else: + result = result.merge(local_aabb) + for child: Variant in n.get_children(): + stack.append(child) + return result + +# ── Internal helpers ────────────────────────────────────────────────────────── + +## Prime SFX URLs for a unit definition so they are ready when needed. +func _prime_unit_sfx(def: Dictionary) -> void: + if def.is_empty(): + return + for sfx_key: String in GameConstants.UNIT_SFX_KEYS: + var url: String = str(def.get(sfx_key, "")).strip_edges() + if not url.is_empty(): + SFX.prime(url) + + +## Internal: requests the animator (via signal or direct call) to play an animation. +## This indirection is needed because the mesh builder loads models asynchronously +## and needs to trigger idle immediately after a model loads, but does not own the +## animator. The parent (game_screen) wires this after construction. +signal play_anim_requested(iid: String, action: String, loop: bool) + +func _request_play_anim(iid: String, action: String, loop: bool) -> void: + play_anim_requested.emit(iid, action, loop) diff --git a/Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd.uid b/Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd.uid new file mode 100644 index 0000000..eefdfc8 --- /dev/null +++ b/Client/origin-client/scenes/game/components/units/unit_mesh_builder.gd.uid @@ -0,0 +1 @@ +uid://jr1obk6cn100 diff --git a/Client/origin-client/scenes/game/components/units/unit_registry.gd b/Client/origin-client/scenes/game/components/units/unit_registry.gd new file mode 100644 index 0000000..30e09ed --- /dev/null +++ b/Client/origin-client/scenes/game/components/units/unit_registry.gd @@ -0,0 +1,121 @@ +class_name UnitRegistry +extends Node + +## Owns unit ownership tracking and provides O(1) ownership queries. +## +## Call rebuild_ownership(state) on every state update to refresh the lookups. + +# ── Ownership tables ────────────────────────────────────────────────────────── + +var enemy_unit_ids: Dictionary = {} # instanceId → true +var friendly_unit_ids: Dictionary = {} # instanceId → true +var unit_team_idx: Dictionary = {} # instanceId → int (team index) + +# ── Definition ID map (instanceId → card definition ID string) ──────────────── +# Populated by the mesh-builder layer; exposed here for cross-component access. +var unit_def_ids: Dictionary = {} + +# ── Ownership rebuild ───────────────────────────────────────────────────────── + +## Rebuild enemy/friendly/team-index lookup tables from a full game state snapshot. +func rebuild_ownership(state: Dictionary) -> void: + enemy_unit_ids.clear() + friendly_unit_ids.clear() + unit_team_idx.clear() + var my_id: String = Auth.user_id + # Find my team index so allies are treated as friendly too. + var my_team_idx: int = -1 + for p: Dictionary in state.get("players", []): + if str(p.get("accountId", "")).to_lower() == my_id.to_lower(): + my_team_idx = int(p.get("teamIndex", -1)) + break + for p: Dictionary in state.get("players", []): + var pid: String = str(p.get("accountId", "")).to_lower() + var is_mine: bool = pid == my_id.to_lower() + var team_idx: int = int(p.get("teamIndex", -1)) + # In team games (teamIndex matches), treat allies as friendly. + var is_ally: bool = (not is_mine) and (my_team_idx >= 0) and (team_idx == my_team_idx) + var target: Dictionary = friendly_unit_ids if (is_mine or is_ally) else enemy_unit_ids + for u: Dictionary in p.get("field", []): + if is_ruin_unit(u): + continue + var iid: String = u.get("instanceId", "") + if not iid.is_empty(): + target[iid] = true + unit_team_idx[iid] = team_idx + var arch: Dictionary = safe_arch(p) + var aid: String = arch.get("instanceId", "") + if not aid.is_empty(): + target[aid] = true + unit_team_idx[aid] = team_idx + +# ── Ownership queries ───────────────────────────────────────────────────────── + +func is_enemy_unit(iid: String) -> bool: + return enemy_unit_ids.has(iid) + + +func is_friendly_unit(iid: String) -> bool: + return friendly_unit_ids.has(iid) + +# ── Ruin helpers ────────────────────────────────────────────────────────────── + +## Returns true when the unit dictionary represents a Ruin card type. +func is_ruin_unit(unit: Dictionary) -> bool: + return str(unit.get("cardType", "")).to_lower() == "ruin" + + +## Returns true when the given instance ID belongs to a Ruin unit. +func is_ruin_instance(iid: String) -> bool: + if iid.is_empty(): + return false + var unit: Dictionary = Game.get_unit_by_id(iid) + return not unit.is_empty() and is_ruin_unit(unit) + +# ── Tile occupant helper ────────────────────────────────────────────────────── + +## Returns true when the tile has an occupant that blocks movement (i.e. not a Ruin). +func tile_has_blocking_occupant(tile: Dictionary) -> bool: + var occupant_id: String = str(tile.get("occupantId", "")) + if occupant_id.is_empty() or occupant_id == "null": + print("[TileBlock] failing out") + return false + print("[TileBlock] returning this: ", not is_ruin_instance(occupant_id)) + return not is_ruin_instance(occupant_id) + +# ── ArchSpirit helper ───────────────────────────────────────────────────────── + +## Safe accessor for a player's archSpirit — returns {} when absent or wrong type. +func safe_arch(player: Dictionary) -> Dictionary: + var arch: Variant = player.get("archSpirit") + return arch as Dictionary if arch is Dictionary else {} + +# ── Board-unit enumeration ──────────────────────────────────────────────────── + +## Returns all non-Ruin units currently on the board (spirits + arch spirits). +func all_board_units() -> Array: + var units: Array = [] + for player: Dictionary in Game.state.get("players", []): + for unit: Dictionary in player.get("field", []): + if not is_ruin_unit(unit): + units.append(unit) + var arch: Dictionary = safe_arch(player) + if not arch.is_empty(): + units.append(arch) + return units + + +## Returns a Dictionary[instanceId → true] of units whose active effects +## mark them as obstructing the given movement type. +func units_obstructing_movement_type(mov: String) -> Dictionary: + var result: Dictionary = {} + var want_label: String = "obstruct:%s" % mov.to_lower() + var active_effects: Variant = Game.state.get("activeEffects") + if not active_effects is Array: + return result + for effect: Dictionary in active_effects: + if str(effect.get("label", "")).to_lower() == want_label: + var target_ref: String = str(effect.get("targetRef", "")) + if not target_ref.is_empty(): + result[target_ref] = true + return result diff --git a/Client/origin-client/scenes/game/components/units/unit_registry.gd.uid b/Client/origin-client/scenes/game/components/units/unit_registry.gd.uid new file mode 100644 index 0000000..1457c33 --- /dev/null +++ b/Client/origin-client/scenes/game/components/units/unit_registry.gd.uid @@ -0,0 +1 @@ +uid://cdd7w27j5lpog diff --git a/Client/origin-client/scenes/game/game_screen.gd b/Client/origin-client/scenes/game/game_screen.gd index 7b820c8..55cde38 100644 --- a/Client/origin-client/scenes/game/game_screen.gd +++ b/Client/origin-client/scenes/game/game_screen.gd @@ -1,29 +1,49 @@ extends Node3D -## GameScreen — 3D ranked game board with 2D HUD overlay. +## GameScreen — slim orchestrator. +## All gameplay logic lives in components under scenes/game/components/. +## This script instantiates them, sets their external refs, wires their signals, +## and fans out Game signals to the appropriate handler. ## -## 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) +## Components owned: +## _board_ctrl BoardController — tile mesh build, affinity updates +## _cam_ctrl CameraController — yaw/pitch/distance, tweens +## _pathfinder Pathfinder — coord↔world, BFS, raycasts +## _unit_reg UnitRegistry — O(1) ownership lookups +## _tile_resolver TileTargetResolver — valid move/attack/play tile sets +## _mesh_builder UnitMeshBuilder — unit StaticBody3D + mesh lifecycle +## _animator UnitAnimator — move/damage/hitsplat animations +## _input_handler BoardInputHandler — mouse/touch → typed signals +## _hud_ctrl HudController — HUD labels, turn strip, discard viewer +## _hand_mgr HandManager — fan arc hand, card popups, spin btns +## _tile_drawer TileDrawer — slide-in tile detail panel +## _skybox SkyboxController — procedural / CDN / live skybox +## _game_over GameOverOverlay — Victory / Defeat overlay +## _inactive_dlgs InactiveDialogs — inactivity / elimination dialogs +## _sel_ctrl SelectionController — mode state, board-click dispatch +## _abt AbilityTargeting — ability panel, targeting UI, send +## _prompt_handler ServerPromptHandler — server-driven ability-pause prompts -# ── Selection mode ──────────────────────────────────────────────────────────── +# ── Component node vars ─────────────────────────────────────────────────────── -enum Mode { - NONE, - CARD_FROM_HAND, - TERRAMORPHA_SELECT, - UNIT_SELECTED, - PLACEMENT, - SACRIFICE_SELECT, - ABILITY_TARGET, - ABILITY_TARGET_FORCED, -} +var _board_ctrl : BoardController = null +var _cam_ctrl : CameraController = null +var _pathfinder : Pathfinder = null +var _unit_reg : UnitRegistry = null +var _tile_resolver : TileTargetResolver = null +var _mesh_builder : UnitMeshBuilder = null +var _animator : UnitAnimator = null +var _input_handler : BoardInputHandler = null +var _hud_ctrl : HudController = null +var _hand_mgr : HandManager = null +var _tile_drawer : TileDrawer = null +var _skybox : SkyboxController = null +var _game_over : GameOverOverlay = null +var _inactive_dlgs : InactiveDialogs = null +var _sel_ctrl : SelectionController = null +var _abt : AbilityTargeting = null +var _prompt_handler: ServerPromptHandler = null -# ── Node refs ───────────────────────────────────────────────────────────────── +# ── @onready node refs (bound to scene tree) ────────────────────────────────── @onready var _camera_rig : Node3D = $CameraRig @onready var _camera : Camera3D = $CameraRig/Camera3D @@ -37,7 +57,6 @@ enum Mode { @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 @@ -51,7 +70,7 @@ enum Mode { @onready var _st_lbl : Label = %StLabel @onready var _deck_lbl : Label = %DeckLabel @onready var _discard_btn : Button = %DiscardBtn -@onready var _discard_lbl : Label = %DiscardLabel +@onready var _discard_lbl : Label = %DiscardLabel @onready var _draw_btn : Button = %DrawBtn @onready var _end_turn_btn : Button = %EndTurnBtn @onready var _settings_btn : Button = %SettingsBtn @@ -81,47 +100,7 @@ enum Mode { @onready var _spectator_list : VBoxContainer = %SpectatorPlayerList @onready var _spectator_leave_btn : Button = %SpectatorLeaveBtn -var count : int = 0 -var _cam_tween : Tween = null -var _last_click_frame : int = -1 -var _last_click_iid : String = "" -var _last_board_click_frame : int = -1 -var _last_board_click_coord : Vector2i = Vector2i(-999, -999) -var _is_spectating : bool = false -var _hand_focus_index : int = 0 -var _hand_scroll_time : float = 0.0 # monotonic time of last hand scroll -var _deselect_pending : bool = false # set in _input, cleared by board unhandled click -var _hand_hover_iid : String = "" -var _cached_hand_iids : Array[String] = [] -var _pending_popup_cards : Array[Dictionary] = [] -var _popup_layer : CanvasLayer = null -# ── 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), -} +# ── Preloaded assets ────────────────────────────────────────────────────────── const _CARD_WIDGET_SCENE := preload("res://scenes/collection/components/CardWidget.tscn") const _HAND_ARROW_REGULAR := preload("res://ui/icons/Green_Gem_Arrow_Button_Regular.png") @@ -130,216 +109,35 @@ const _HAND_ARROW_PRESSED := preload("res://ui/icons/Green_Gem_Arrow_Button_Cli const _HITSPLAT_SHIELD_ICON := preload("res://ui/icons/Shield_Overlay_Gradient.png") const _HITSPLAT_HEART_ICON := preload("res://ui/icons/Heart_Overlay_Gradient.png") -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) -const HITSPLAT_LIFETIME := 0.75 -const HITSPLAT_RISE_PIXELS := 42.0 +# ── Constants shared across components ──────────────────────────────────────── -# ── Camera state ────────────────────────────────────────────────────────────── +const TILE_SPACING : float = 1.1 +const HEX_TILE_RADIUS : float = 0.577 +const HEX_TILE_SPACING : float = 1.0 +const MOVE_STEP_SECS : float = 0.28 +const POST_ANIM_SECS : float = 1.2 +const SKY_ROTATION_SPEED : float = 0.026 -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) +# ── Minimal orchestrator state ──────────────────────────────────────────────── -# 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 +var _is_spectating : bool = false +var _camera_oriented : bool = false +var _local_is_p1 : bool = false +var _last_click_frame : int = -1 +var _last_click_iid : String = "" +var _rebuild_pending : bool = false +var _pending_rebuild_state: Dictionary = {} -# ── 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 - -# Server-driven ability pause prompts (non-triggered) -var _pending_req_id : String = "" # shared request ID for any active server prompt -var _pending_source_id : String = "" # source unit instance ID -var _pending_prompt_panel : Control = null # choice-panel for cost_group / action_group / branch / player / reveal -var _is_target_pick : bool = false # PendingTargetPick: reuses ABILITY_TARGET mode -var _is_tile_pick : bool = false # PendingTilePick: shows tile highlights -var _tile_pick_max_range : int = 0 -var _tile_pick_require_empty : bool = false -var _tile_pick_require_occupied : bool = false -# For PendingCostPick: accumulated selections -var _cost_pick_selected : Array[String] = [] -var _cost_pick_amount : int = 1 -# For PendingRevealChoicePick: ordered indices collected so far -var _reveal_ordered_indices : Array = [] -var _reveal_total_cards : int = 0 -var _reveal_required_count : int = 1 - -# 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_last_tile : Dictionary = {} -var _tile_drawer_tile_labels : Array = [] -var _tile_drawer_spirit_labels: Array = [] -var _tile_drawer_token_labels : Array = [] -var _tile_drawer_arch_labels : Array = [] -var _tile_drawer_ruin_labels : Array = [] -var _tile_drawer_tile_section : Dictionary = {} -var _tile_drawer_spirit_section : Dictionary = {} -var _tile_drawer_token_section : Dictionary = {} -var _tile_drawer_arch_section : Dictionary = {} -var _tile_drawer_ruin_section : Dictionary = {} -var _tile_drawer_spirit_effects_section : Dictionary = {} -var _tile_drawer_token_effects_section : Dictionary = {} -var _tile_drawer_arch_effects_section : Dictionary = {} -var _tile_drawer_ruin_effects_section : Dictionary = {} -var _tile_drawer_spirit_effects_labels : Array = [] -var _tile_drawer_token_effects_labels : Array = [] -var _tile_drawer_arch_effects_labels : Array = [] -var _tile_drawer_ruin_effects_labels : Array = [] -const _TILE_DRAWER_WIDTH: float = 260.0 -const _TILE_DRAWER_TOGGLE_WIDTH: float = 36.0 -const _TILE_DRAWER_TOGGLE_MARGIN: float = 12.0 - -# ── 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_def: Dictionary = {} # instanceId → int, DEF 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_source_iid : String = "" # source of the most recent send_attack() call -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) -var _hitsplat_layer : Control = null -var _hitsplat_canvas_layer : CanvasLayer = null - -# 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) -var _unit_team_idx : Dictionary = {} # iid → int (team index, for spectate-safe facing) -# 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. +# Hover cursor quads (permanently allocated, managed inline here) 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_coord : Vector2i = Vector2i(-1, -1) var _hovered_unit_mesh : MeshInstance3D = null -const UNIT_SFX_KEYS := [ - "moveSoundUrl", - "attackSoundUrl", - "damagedSoundUrl", - "deathSoundUrl", - "blockedSoundUrl", -] - -## 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: - # Connect critical game signals first — before anything that could error — - # so state pushes are never missed even if later setup fails. + # ── 1. Critical game signals (connect before anything that can error) ────── Game.state_updated.connect(_on_state_updated) Game.game_over.connect(_on_game_over) Game.session_abandoned.connect(_on_session_abandoned) @@ -347,56 +145,254 @@ func _ready() -> void: Game.inactive_warning.connect(_on_inactive_warning) Game.both_idle_warning.connect(_on_both_idle_warning) Game.player_eliminated.connect(_on_player_eliminated) + HighlightConfig.texture_loaded.connect(_on_highlight_texture_loaded) - _setup_environment() - _apply_camera() - _init_cursor_nodes() + # ── 2. Instantiate and configure components ──────────────────────────────── + # Pathfinder + _pathfinder = Pathfinder.new() + _pathfinder.camera = _camera + add_child(_pathfinder) + + # UnitRegistry + _unit_reg = UnitRegistry.new() + add_child(_unit_reg) + + # TileTargetResolver + _tile_resolver = TileTargetResolver.new() + _tile_resolver.pathfinder = _pathfinder + _tile_resolver.unit_registry = _unit_reg + add_child(_tile_resolver) + + # BoardController + _board_ctrl = BoardController.new() + _board_ctrl.tiles_root = _tiles_root + _board_ctrl.units_root = _units_root + _board_ctrl.hi_root = _hi_root + _board_ctrl.pathfinder = _pathfinder + add_child(_board_ctrl) + + # UnitMeshBuilder + _mesh_builder = UnitMeshBuilder.new() + _mesh_builder.units_root = _units_root + _mesh_builder.unit_registry = _unit_reg + _mesh_builder.pathfinder = _pathfinder + add_child(_mesh_builder) + + # UnitAnimator + _animator = UnitAnimator.new() + _animator.mesh_builder = _mesh_builder + _animator.camera = _camera + add_child(_animator) + _animator.ensure_hitsplat_layer() + _animator.rebuild_scheduled.connect(_on_rebuild_scheduled) + _mesh_builder.play_anim_requested.connect(_animator.play_unit_anim) + + # CameraController + _cam_ctrl = CameraController.new() + _cam_ctrl.camera_rig = _camera_rig + _cam_ctrl.camera = _camera + _cam_ctrl.cam_ctrl_panel = _cam_ctrl_panel + _cam_ctrl.cam_orbit_btn = _cam_orbit_btn + _cam_ctrl.cam_pan_btn = _cam_pan_btn + _cam_ctrl.cam_zoom_btn = _cam_zoom_btn + add_child(_cam_ctrl) + _cam_ctrl.deactivate_touch_modes_requested.connect( + func() -> void: _input_handler.touch_cam_orbit = false + ) + + # SkyboxController + _skybox = SkyboxController.new() + _skybox.world_environment = $WorldEnvironment + add_child(_skybox) + + # HudController + _hud_ctrl = HudController.new() + _hud_ctrl.phase_lbl = _phase_lbl + _hud_ctrl.turn_lbl = _turn_lbl + _hud_ctrl.turn_order_strip = _turn_order_strip + _hud_ctrl.opp_panel = _opp_panel + _hud_ctrl.opp_name_lbl = _opp_name_lbl + _hud_ctrl.opp_hand_lbl = _opp_hand_lbl + _hud_ctrl.opp_deck_lbl = _opp_deck_lbl + _hud_ctrl.opp_discard_btn = _opp_discard_btn + _hud_ctrl.sp_lbl = _sp_lbl + _hud_ctrl.st_lbl = _st_lbl + _hud_ctrl.deck_lbl = _deck_lbl + _hud_ctrl.discard_btn = _discard_btn + _hud_ctrl.discard_lbl = _discard_lbl + _hud_ctrl.draw_btn = _draw_btn + _hud_ctrl.end_turn_btn = _end_turn_btn + _hud_ctrl.dv_overlay = _dv_overlay + _hud_ctrl.dv_title = _dv_title + _hud_ctrl.dv_list = _dv_list + _hud_ctrl.dv_close_btn = _dv_close_btn + _hud_ctrl.spectator_panel = _spectator_panel + _hud_ctrl.spectator_list = _spectator_list + add_child(_hud_ctrl) + + # HandManager + _hand_mgr = HandManager.new() + _hand_mgr.hand_cards = _hand_cards + _hand_mgr.hand_area = _hand_area + _hand_mgr.hand_spin_left = _hand_spin_left + _hand_mgr.hand_spin_right = _hand_spin_right + _hand_mgr.hud = _hud + add_child(_hand_mgr) + _hand_mgr.hand_card_clicked.connect(_on_hand_card_clicked) + + # TileDrawer + _tile_drawer = TileDrawer.new() + _tile_drawer.hud = _hud + _tile_drawer.tile_drawer_toggle_btn = _tile_drawer_toggle_btn + add_child(_tile_drawer) + _tile_drawer.create_tile_drawer() + _tile_drawer.focus_camera_on_tile.connect( + func(world_pos: Vector3) -> void: _cam_ctrl.tween_to_pivot(world_pos) + ) + + # GameOverOverlay + _game_over = GameOverOverlay.new() + _game_over.go_overlay = _go_overlay + _game_over.go_result_lbl = _go_result_lbl + _game_over.go_rank_lbl = _go_rank_lbl + _game_over.go_menu_btn = _go_menu_btn + add_child(_game_over) + + # InactiveDialogs + _inactive_dlgs = InactiveDialogs.new() + add_child(_inactive_dlgs) + _inactive_dlgs.spectator_mode_requested.connect(_on_spectator_mode_requested) + + # SelectionController + _sel_ctrl = SelectionController.new() + _sel_ctrl.unit_registry = _unit_reg + _sel_ctrl.pathfinder = _pathfinder + _sel_ctrl.tile_target_resolver = _tile_resolver + _sel_ctrl.tile_bodies = _board_ctrl.tile_bodies + add_child(_sel_ctrl) + _sel_ctrl.highlights_cleared.connect(_clear_highlights) + _sel_ctrl.highlight_add_requested.connect(_add_highlight) + _sel_ctrl.highlight_tiles_requested.connect(_highlight_tiles) + _sel_ctrl.tile_drawer_open_requested.connect( + func(tile_data: Dictionary) -> void: + _tile_drawer.open_tile_drawer(tile_data) + ) + _sel_ctrl.tile_drawer_close_requested.connect(_tile_drawer.close_tile_drawer) + _sel_ctrl.camera_follow_requested.connect( + func(world_pos: Vector3) -> void: _cam_ctrl.tween_to_pivot(world_pos) + ) + _sel_ctrl.hand_selection_refresh_requested.connect(_refresh_hand_selection) + + # AbilityTargeting + _abt = AbilityTargeting.new() + _abt.selection_controller = _sel_ctrl + _abt.unit_registry = _unit_reg + _abt.pathfinder = _pathfinder + _abt.hud = _hud + _abt.unit_bodies = _mesh_builder.unit_bodies + _abt.camera = _camera + add_child(_abt) + _sel_ctrl.ability_targeting = _abt + _abt.highlight_add_requested.connect(_add_highlight) + _abt.highlights_cleared.connect(_clear_highlights) + + # ServerPromptHandler + _prompt_handler = ServerPromptHandler.new() + _prompt_handler.selection_controller = _sel_ctrl + _prompt_handler.ability_targeting = _abt + _prompt_handler.pathfinder = _pathfinder + _prompt_handler.hud = _hud + add_child(_prompt_handler) + _prompt_handler.highlight_add_requested.connect(_add_highlight) + _prompt_handler.highlights_cleared.connect(_clear_highlights) + + # BoardInputHandler + _input_handler = BoardInputHandler.new() + _input_handler.hold_timer = _hold_timer + _input_handler.cam_gesture_timer = _cam_gesture_timer + _input_handler.hand_area = _hand_area + _input_handler.camera_rig = _camera_rig + _input_handler.cam_distance = _cam_ctrl.cam_distance + _input_handler.fn_mouse_to_tile_coord = func(pos: Vector2) -> Vector2i: + return _pathfinder.mouse_to_tile_coord(pos, _board_ctrl.tile_bodies) + _input_handler.fn_mouse_to_unit_id = func(pos: Vector2) -> String: + return _mouse_to_unit_id(pos) + add_child(_input_handler) + _input_handler.board_clicked.connect(_on_board_clicked) + _input_handler.board_held.connect(_on_board_held) + _input_handler.board_orbit.connect(_on_board_orbit) + _input_handler.board_pan.connect(_on_board_pan) + _input_handler.board_zoom.connect(_on_board_zoom) + _input_handler.hand_scroll.connect(_on_hand_scroll) + _input_handler.deselect_pending.connect(_on_deselect_pending) + + # ── 3. Route server prompt signals to components ─────────────────────────── + Game.triggered_target_request.connect(_abt.on_triggered_target_request) + Game.cost_pick_request.connect(_prompt_handler.on_cost_pick_request) + Game.cost_group_pick_request.connect(_prompt_handler.on_cost_group_pick_request) + Game.action_group_pick_request.connect(_prompt_handler.on_action_group_pick_request) + Game.branch_pick_request.connect(_prompt_handler.on_branch_pick_request) + Game.target_pick_request.connect(_prompt_handler.on_target_pick_request) + Game.tile_pick_request.connect(_prompt_handler.on_tile_pick_request) + Game.player_pick_request.connect(_prompt_handler.on_player_pick_request) + Game.reveal_choice_pick_request.connect(_prompt_handler.on_reveal_choice_pick_request) + + # ── 4. HUD button wiring ────────────────────────────────────────────────── _draw_btn.pressed.connect(_on_draw_pressed) _end_turn_btn.pressed.connect(_on_end_turn_pressed) _settings_btn.pressed.connect(func() -> void: _in_game_settings.open()) - _discard_btn.pressed.connect(func() -> void: _show_own_discard()) - _opp_discard_btn.pressed.connect(func() -> void: _show_opp_discard()) - _hand_spin_left.pressed.connect(func() -> void: _spin_hand(-1)) - _hand_spin_right.pressed.connect(func() -> void: _spin_hand(1)) - _tile_drawer_toggle_btn.pressed.connect(_on_tile_drawer_toggle_pressed) + _discard_btn.pressed.connect( + func() -> void: _hud_ctrl.show_own_discard(Game.state)) + _opp_discard_btn.pressed.connect( + func() -> void: _hud_ctrl.show_opp_discard(Game.state)) _ctx_close_btn.pressed.connect(func() -> void: _ctx_popup.visible = false) _dv_close_btn.pressed.connect(func() -> void: _dv_overlay.visible = false) _go_menu_btn.pressed.connect(func() -> void: get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")) _hold_timer.timeout.connect(_on_hold_timer_fired) - _cam_gesture_timer.timeout.connect(_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) - _hand_area.resized.connect(_queue_hand_layout) - _hand_area.resized.connect(_layout_hand_spin_buttons) - _hand_cards.resized.connect(_queue_hand_layout) - _configure_hand_spin_buttons() - _sync_cam_ctrl_panel() - Settings.settings_changed.connect(_sync_cam_ctrl_panel) - _create_tile_drawer() - Game.triggered_target_request.connect(_on_triggered_target_request) - Game.cost_pick_request.connect(_on_cost_pick_request) - Game.cost_group_pick_request.connect(_on_cost_group_pick_request) - Game.action_group_pick_request.connect(_on_action_group_pick_request) - Game.branch_pick_request.connect(_on_branch_pick_request) - Game.target_pick_request.connect(_on_target_pick_request) - Game.tile_pick_request.connect(_on_tile_pick_request) - Game.player_pick_request.connect(_on_player_pick_request) - Game.reveal_choice_pick_request.connect(_on_reveal_choice_pick_request) - HighlightConfig.texture_loaded.connect(_on_highlight_texture_loaded) + _cam_gesture_timer.timeout.connect( + func() -> void: _cam_ctrl.on_cam_gesture_timer_fired(_input_handler.gesture_finger_count) + ) + _cam_orbit_btn.toggled.connect( + func(p: bool) -> void: + _cam_ctrl.on_cam_orbit_btn_toggled(p) + _input_handler.touch_cam_orbit = p and _cam_ctrl.cam_orbit_btn.button_pressed + ) + _cam_pan_btn.toggled.connect( + func(p: bool) -> void: + _cam_ctrl.on_cam_pan_btn_toggled(p) + _input_handler.touch_cam_pan = p and _cam_ctrl.cam_pan_btn.button_pressed + ) + _cam_zoom_btn.toggled.connect( + func(p: bool) -> void: + _cam_ctrl.on_cam_zoom_btn_toggled(p) + _input_handler.touch_cam_zoom = p and _cam_ctrl.cam_zoom_btn.button_pressed + ) + _hand_area.resized.connect(_hand_mgr.queue_hand_layout) + _hand_area.resized.connect(_hand_mgr.layout_hand_spin_buttons) + _hand_cards.resized.connect(_hand_mgr.queue_hand_layout) + _hand_mgr.configure_hand_spin_buttons() + _tile_drawer_toggle_btn.pressed.connect(_tile_drawer.on_tile_drawer_toggle_pressed) - # Chat overlay — add to viewport root so it renders above everything. + # ── 5. Camera, skybox, hover, chat ──────────────────────────────────────── + _cam_ctrl.sync_cam_ctrl_panel() + Settings.settings_changed.connect( + func() -> void: + _cam_ctrl.sync_cam_ctrl_panel() + _skybox.on_skybox_setting_changed() + ) + _cam_ctrl.apply_camera() + _skybox.setup_environment() + _init_cursor_nodes() Chat.claim_bubble_visibility(self) Chat.set_bubble_host(_chat_bubble_host) - _ensure_hitsplat_layer() + # ── 6. Spectator / initial state ────────────────────────────────────────── if Game.is_spectating: _is_spectating = true _setup_spectator_ui() Game.request_sync() - # State was already applied via game.spectate ack — re-emit if present. if not Game.state.is_empty(): _on_state_updated(Game.state) return @@ -408,146 +404,15 @@ func _ready() -> void: func _process(delta: float) -> void: - var env := $WorldEnvironment.environment as Environment + var env: Environment = $WorldEnvironment.environment as Environment if env != null: env.sky_rotation.y += delta * SKY_ROTATION_SPEED -func _ensure_hitsplat_layer() -> Control: - if is_instance_valid(_hitsplat_layer): - return _hitsplat_layer - # Own CanvasLayer (layer 15) so hitsplats always render above the HUD (10) - # and all dynamic panels added to _hud, but below card popups (20). - _hitsplat_canvas_layer = CanvasLayer.new() - _hitsplat_canvas_layer.layer = 15 - _hitsplat_canvas_layer.name = "HitsplatCanvas" - add_child(_hitsplat_canvas_layer) - _hitsplat_layer = Control.new() - _hitsplat_layer.name = "HitsplatLayer" - _hitsplat_layer.mouse_filter = Control.MOUSE_FILTER_IGNORE - _hitsplat_canvas_layer.add_child(_hitsplat_layer) - _hitsplat_layer.set_anchors_preset(Control.PRESET_FULL_RECT) - return _hitsplat_layer - - -func _hitsplat_screen_pos(iid: String) -> Vector2: - var body := _unit_bodies.get(iid) as StaticBody3D - if not is_instance_valid(body): - return Vector2.ZERO - var above_tile := float(body.get_meta("above_tile", 0.28)) - var world_pos := body.global_position + Vector3(0.0, above_tile + 0.9, 0.0) - return _camera.unproject_position(world_pos) - - -func _queue_hitsplats(iid: String, def_amount: int, hp_amount: int, delay: float = 0.0) -> void: - if def_amount <= 0 and hp_amount <= 0: - return - if delay > 0.0: - var queued_iid := iid - var queued_def := def_amount - var queued_hp := hp_amount - var queued_anchor := _hitsplat_screen_pos(iid) - var t := create_tween() - t.tween_callback(func() -> void: - if queued_anchor == Vector2.ZERO: - _show_hitsplats(queued_iid, queued_def, queued_hp) - else: - _show_hitsplats_at_anchor(queued_iid, queued_def, queued_hp, queued_anchor) - ).set_delay(delay) - return - _show_hitsplats(iid, def_amount, hp_amount) - - -func _show_hitsplats_once(shown: Dictionary, iid: String, def_amount: int, hp_amount: int, - delay: float = 0.0) -> void: - if def_amount <= 0 and hp_amount <= 0: - return - if shown.has(iid): - return - shown[iid] = true - _queue_hitsplats(iid, def_amount, hp_amount, delay) - - -func _show_hitsplats(iid: String, def_amount: int, hp_amount: int) -> void: - print("[HITSPLAT] _show_hitsplats iid=%s def=%d hp=%d" % [iid.substr(0, 8), def_amount, hp_amount]) - if not _unit_bodies.has(iid): - print("[HITSPLAT] skipped — iid not in _unit_bodies") - return - var anchor := _hitsplat_screen_pos(iid) - if anchor == Vector2.ZERO: - print("[HITSPLAT] skipped — anchor is Vector2.ZERO (body invalid or not yet placed)") - return - _show_hitsplats_at_anchor(iid, def_amount, hp_amount, anchor) - - -func _show_hitsplats_at_anchor(iid: String, def_amount: int, hp_amount: int, anchor: Vector2) -> void: - if def_amount > 0: - _spawn_hitsplat(iid, def_amount, "Shield", _HITSPLAT_SHIELD_ICON, Color(0.24, 0.58, 1.0), anchor) - if hp_amount > 0: - # When both fire, delay the heart so shield appears first. - if def_amount > 0: - var q_iid := iid - var q_hp := hp_amount - var q_anchor := anchor - var t := create_tween() - t.tween_callback(func() -> void: - _spawn_hitsplat(q_iid, q_hp, "Heart", _HITSPLAT_HEART_ICON, Color(0.92, 0.24, 0.24), q_anchor) - ).set_delay(0.2) - else: - _spawn_hitsplat(iid, hp_amount, "Heart", _HITSPLAT_HEART_ICON, Color(0.92, 0.24, 0.24), anchor) - - -func _spawn_hitsplat(iid: String, amount: int, icon_label: String, icon: Texture2D, tint: Color, anchor: Vector2) -> void: - print("[HITSPLAT] %s amount=%d iid=%s" % [icon_label, amount, iid.substr(0, 8)]) - if amount <= 0: - print("[HITSPLAT] skipped — amount <= 0") - return - var layer := _ensure_hitsplat_layer() - if not is_instance_valid(layer): - print("[HITSPLAT] skipped — layer invalid") - return - print("[HITSPLAT] spawning at screen pos %s" % anchor) - var root := Control.new() - root.mouse_filter = Control.MOUSE_FILTER_IGNORE - root.size = Vector2(96.0, 40.0) - root.pivot_offset = root.size * 0.5 - root.position = anchor - root.size * 0.5 + Vector2(0.0, -14.0) - layer.add_child(root) - - var icon_rect := TextureRect.new() - icon_rect.texture = icon - icon_rect.expand_mode = TextureRect.EXPAND_IGNORE_SIZE - icon_rect.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED - icon_rect.position = Vector2(0.0, 2.0) - icon_rect.size = Vector2(34.0, 34.0) - icon_rect.modulate = tint - root.add_child(icon_rect) - - var lbl := Label.new() - lbl.text = str(amount) - lbl.position = Vector2(28.0, 0.0) - lbl.size = Vector2(68.0, 36.0) - lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT - lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER - lbl.add_theme_font_size_override("font_size", 20) - lbl.add_theme_color_override("font_color", Color.WHITE) - root.add_child(lbl) - - var tw := create_tween() - tw.set_parallel(true) - tw.tween_property(root, "position", root.position + Vector2(0.0, -HITSPLAT_RISE_PIXELS), HITSPLAT_LIFETIME)\ - .set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT) - tw.tween_property(root, "modulate:a", 0.0, HITSPLAT_LIFETIME)\ - .set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN) - tw.finished.connect(func() -> void: - if is_instance_valid(root): - root.queue_free() - ) - - func _exit_tree() -> void: if _is_spectating: Game.stop_spectating() + # Disconnect game signals (Godot auto-disconnects on queue_free, but be explicit). if Game.state_updated.is_connected(_on_state_updated): Game.state_updated.disconnect(_on_state_updated) if Game.game_over.is_connected(_on_game_over): @@ -562,2307 +427,490 @@ func _exit_tree() -> void: 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 Game.cost_pick_request.is_connected(_on_cost_pick_request): - Game.cost_pick_request.disconnect(_on_cost_pick_request) - if Game.cost_group_pick_request.is_connected(_on_cost_group_pick_request): - Game.cost_group_pick_request.disconnect(_on_cost_group_pick_request) - if Game.action_group_pick_request.is_connected(_on_action_group_pick_request): - Game.action_group_pick_request.disconnect(_on_action_group_pick_request) - if Game.branch_pick_request.is_connected(_on_branch_pick_request): - Game.branch_pick_request.disconnect(_on_branch_pick_request) - if Game.target_pick_request.is_connected(_on_target_pick_request): - Game.target_pick_request.disconnect(_on_target_pick_request) - if Game.tile_pick_request.is_connected(_on_tile_pick_request): - Game.tile_pick_request.disconnect(_on_tile_pick_request) - if Game.player_pick_request.is_connected(_on_player_pick_request): - Game.player_pick_request.disconnect(_on_player_pick_request) - if Game.reveal_choice_pick_request.is_connected(_on_reveal_choice_pick_request): - Game.reveal_choice_pick_request.disconnect(_on_reveal_choice_pick_request) - if Settings.settings_changed.is_connected(_on_skybox_setting_changed): - Settings.settings_changed.disconnect(_on_skybox_setting_changed) + if Game.game_activity.is_connected(_skybox.on_game_activity): + Game.game_activity.disconnect(_skybox.on_game_activity) + if Game.triggered_target_request.is_connected(_abt.on_triggered_target_request): + Game.triggered_target_request.disconnect(_abt.on_triggered_target_request) + if Game.cost_pick_request.is_connected(_prompt_handler.on_cost_pick_request): + Game.cost_pick_request.disconnect(_prompt_handler.on_cost_pick_request) + if Game.cost_group_pick_request.is_connected(_prompt_handler.on_cost_group_pick_request): + Game.cost_group_pick_request.disconnect(_prompt_handler.on_cost_group_pick_request) + if Game.action_group_pick_request.is_connected(_prompt_handler.on_action_group_pick_request): + Game.action_group_pick_request.disconnect(_prompt_handler.on_action_group_pick_request) + if Game.branch_pick_request.is_connected(_prompt_handler.on_branch_pick_request): + Game.branch_pick_request.disconnect(_prompt_handler.on_branch_pick_request) + if Game.target_pick_request.is_connected(_prompt_handler.on_target_pick_request): + Game.target_pick_request.disconnect(_prompt_handler.on_target_pick_request) + if Game.tile_pick_request.is_connected(_prompt_handler.on_tile_pick_request): + Game.tile_pick_request.disconnect(_prompt_handler.on_tile_pick_request) + if Game.player_pick_request.is_connected(_prompt_handler.on_player_pick_request): + Game.player_pick_request.disconnect(_prompt_handler.on_player_pick_request) + if Game.reveal_choice_pick_request.is_connected(_prompt_handler.on_reveal_choice_pick_request): + Game.reveal_choice_pick_request.disconnect(_prompt_handler.on_reveal_choice_pick_request) + _skybox.clear_stars() _reset_unit_hover_glow() - # 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() Chat.set_bubble_host(null) Chat.release_bubble_visibility(self) +# ── State → scene orchestration ─────────────────────────────────────────────── -func _setup_spectator_ui() -> void: - # Clear any pending draw popups — spectators have no hand. - _pending_popup_cards.clear() - if is_instance_valid(_popup_layer): - _popup_layer.visible = false +func _on_state_updated(state: Dictionary) -> void: + print("[GameScreen] state_updated phase=", state.get("phase", "?"), + " mode=", _sel_ctrl.mode if _sel_ctrl != null else "n/a") + _unit_reg.rebuild_ownership(state) - # "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) + # Orient camera on first state that has playerOneAccountId. + var p1_id: String = str(state.get("playerOneAccountId", "")) + if not p1_id.is_empty(): + _local_is_p1 = Auth.user_id.to_lower() == p1_id.to_lower() + _mesh_builder.local_is_p1 = _local_is_p1 + if not _camera_oriented and not p1_id.is_empty(): + _camera_oriented = true + _orient_camera_to_player(state) - # Hide player-only HUD areas completely. - _hand_area.visible = false - _sp_st_panel.visible = false - _deck_discard_panel.visible = false + # Board build / affinity update. + var board: Dictionary = state.get("board", {}) + if _board_ctrl.tile_bodies.is_empty() and not board.is_empty(): + _board_ctrl.build_board(board) + # Push grid info to pathfinder and sel_ctrl after board is known. + _pathfinder.grid_type = str(board.get("gridType", "Square")) + _pathfinder.hex_sides = int(board.get("hexSides", 0)) + _sel_ctrl.board_grid_type = _pathfinder.grid_type + elif not board.is_empty(): + for tile: Dictionary in board.get("tiles", []): + var c: Dictionary = tile.get("coord", {}) + _board_ctrl.update_tile_affinity( + c.get("x", 0), c.get("y", 0), + tile.get("resolvedAffinity", "Void")) - # Hide action-only buttons; Settings and Chat remain accessible. - _draw_btn.visible = false - _end_turn_btn.visible = false + # Sync tile height maps into mesh_builder. + _mesh_builder.tile_heights = _board_ctrl.tile_heights + _mesh_builder.tile_y_bases = _board_ctrl.tile_y_bases - # Show the spectator player summary panel and the leave button in the action rail. - _spectator_panel.visible = true - _spectator_leave_btn.visible = true - _spectator_leave_btn.pressed.connect(func() -> void: - Game.stop_spectating() - get_tree().change_scene_to_file("res://scenes/free_play/FreePlayScreen.tscn")) + # Fire animations on existing nodes before rebuild. + var move_dur: float = _animator.play_move_animations( + state, _board_ctrl.tile_heights, _board_ctrl.tile_y_bases, + _pathfinder, _board_ctrl.tile_bodies) + var dmg_played: bool = _animator.play_damage_animations(state) -# ── Environment ─────────────────────────────────────────────────────────────── + # Immediate UI updates (hand / HUD don't wait for animations). + _hand_mgr.rebuild_hand(Game.get_hand(), _is_spectating) + _hud_ctrl.update_hud(state) -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 + # Enter Placement mode whenever we haven't placed yet (simultaneous phase). + var phase: String = str(state.get("phase", "")) + if phase == "Placement" and not _is_spectating: + var my_arch: Dictionary = Game.get_my_player().get("archSpirit", {}) + var i_have_placed: bool = not my_arch.is_empty() and my_arch.get("position") != null + if not i_have_placed and _sel_ctrl.mode != SelectionController.Mode.PLACEMENT: + _sel_ctrl.set_mode(SelectionController.Mode.PLACEMENT) + _clear_highlights() + _highlight_tiles(_tile_resolver.valid_placement_tiles(), "movement") - 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) + # Snapshot state for next frame's diff. + _animator.update_prev_state(state) - # 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) + # Schedule delayed board rebuild to let animations finish. + var delay: float = move_dur + if dmg_played: + delay = maxf(delay, POST_ANIM_SECS) + _animator.schedule_rebuild(state, delay) -## 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() + # Selection preservation across server pushes. + var cur_mode: SelectionController.Mode = _sel_ctrl.mode + match cur_mode: + SelectionController.Mode.NONE, SelectionController.Mode.PLACEMENT: + pass + SelectionController.Mode.CARD_FROM_HAND, SelectionController.Mode.TERRAMORPHA_SELECT: + var sel_card: Dictionary = _hand_mgr.find_hand_card(_sel_ctrl.sel_card_id) + if sel_card.is_empty(): + _sel_ctrl.set_mode(SelectionController.Mode.NONE) + else: + _clear_highlights() + _highlight_tiles( + _tile_resolver.valid_play_tiles(sel_card, _board_ctrl.tile_bodies), + "movement") + _refresh_hand_selection() + SelectionController.Mode.ABILITY_TARGET_FORCED: + _clear_highlights() + _abt.start_ability_targeting() _: - _setup_procedural_sky() + _sel_ctrl.set_mode(SelectionController.Mode.NONE) -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) + # Auto-draw. + if state.get("phase", "") == "Draw" and Game.is_my_turn(): + await get_tree().create_timer(0.3).timeout + Game.send_draw() -## 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): +func _on_rebuild_scheduled(state: Dictionary, delay: float) -> void: + if delay <= 0.0: + # If a delayed rebuild is already in flight (protecting a move tween), + # just update its state — do NOT call rebuild_units now, which would + # kill the in-progress tween and freeze the unit mid-path. + if _rebuild_pending: + _pending_rebuild_state = state + return + _mesh_builder.rebuild_units(state) return - 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 + # Delayed rebuild: protect any concurrent move tween from premature kills. + _pending_rebuild_state = state + if _rebuild_pending: + # A timer is already running; updating the state is enough. + return + _rebuild_pending = true + var t: SceneTreeTimer = get_tree().create_timer(delay + 0.1) + t.timeout.connect(func() -> void: + _rebuild_pending = false + _mesh_builder.rebuild_units(_pending_rebuild_state)) - if instant: - mat.emission_energy_multiplier = 1.0 - _start_star_twinkle(mesh) +# ── Camera orientation helper ───────────────────────────────────────────────── + +func _orient_camera_to_player(state: Dictionary) -> void: + var bw: float = float(Game.board_width()) + var bh: float = float(Game.board_height()) + var max_dim: float = max(bw, bh) + _cam_ctrl.cam_distance = clampf(max(max_dim, 10.0) * 1.5, 12.0, 30.0) + var pivot_len: float = clampf(max_dim * 0.2, 1.0, 5.0) + + var board_d: Dictionary = Game.get_board() + var sz_raw: Dictionary = board_d.get("startingZones", {}) as Dictionary + var my_seat: int = int(Game.get_my_player().get("seatIndex", 0)) + var zone: Array = (sz_raw.get(str(my_seat), []) as Array) if not sz_raw.is_empty() else [] + + if not zone.is_empty(): + var cx: float = 0.0 + var cz_v: float = 0.0 + for coord: Dictionary in zone: + cx += float(coord.get("x", 0)) * TILE_SPACING - (bw - 1.0) * TILE_SPACING * 0.5 + cz_v += float(coord.get("y", 0)) * TILE_SPACING - (bh - 1.0) * TILE_SPACING * 0.5 + cx /= zone.size() + cz_v /= zone.size() + _cam_ctrl.cam_yaw = rad_to_deg(atan2(cx, cz_v)) + var len2d: float = sqrt(cx * cx + cz_v * cz_v) + if len2d > 0.001: + _cam_ctrl.cam_pivot = Vector3(cx / len2d * pivot_len, 0.0, cz_v / len2d * pivot_len) else: - 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 + if _local_is_p1: + _cam_ctrl.cam_yaw = 180.0 + _cam_ctrl.cam_pivot = Vector3(0.0, 0.0, -pivot_len) 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 _input(event: InputEvent) -> void: - if event is InputEventMouseButton: - var mb := event as InputEventMouseButton - if mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed and not mb.double_click: - var _card_mode_active := _mode in [Mode.CARD_FROM_HAND, Mode.TERRAMORPHA_SELECT] or \ - (_mode == Mode.ABILITY_TARGET and not _ability_card_id.is_empty()) - if _card_mode_active: - if not _hand_area.get_global_rect().has_point(mb.position): - _deselect_pending = true - _do_deselect_if_pending.call_deferred() - - -func _do_deselect_if_pending() -> void: - if _deselect_pending: - _deselect_pending = false - 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) + _cam_ctrl.cam_pivot = Vector3(0.0, 0.0, pivot_len) + _cam_ctrl.apply_camera() +# ── Input delegation ────────────────────────────────────────────────────────── func _unhandled_input(event: InputEvent) -> void: - if event is InputEventMouseButton: - var mb := event as InputEventMouseButton - # Left-click reaching here is a board click — cancel any pending deselect - # so _do_deselect_if_pending won't wipe selection before the card is played. - if mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed: - _deselect_pending = false - if mb.button_index == MOUSE_BUTTON_WHEEL_UP: - if _hand_area.get_global_rect().has_point(mb.position): - var now := Time.get_ticks_msec() / 1000.0 - if now - _hand_scroll_time >= 0.15: - _hand_scroll_time = now - _spin_hand(-1) - return - _zoom(1.5); return - elif mb.button_index == MOUSE_BUTTON_WHEEL_DOWN: - if _hand_area.get_global_rect().has_point(mb.position): - var now := Time.get_ticks_msec() / 1000.0 - if now - _hand_scroll_time >= 0.15: - _hand_scroll_time = now - _spin_hand(1) - 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) + if _input_handler != null: + _input_handler._unhandled_input(event) + +func _input(event: InputEvent) -> void: + if _input_handler != null: + _input_handler._input(event) + +func _on_board_clicked(screen_pos: Vector2) -> void: + var coord: Vector2i = _pathfinder.mouse_to_tile_coord(screen_pos, _board_ctrl.tile_bodies) + var unit_id: String = _mouse_to_unit_id(screen_pos) + _sel_ctrl.handle_board_click(screen_pos, coord, unit_id) + _update_hover(screen_pos) + +func _on_board_held(coord: Vector2i) -> void: + _held_coord_show_popup(coord) + +func _on_board_orbit(delta: Vector2) -> void: + _cam_ctrl.apply_orbit(delta) + +func _on_board_pan(delta: Vector2, cam_dist: float) -> void: + _cam_ctrl.apply_pan(delta, cam_dist) + +func _on_board_zoom(amount: float) -> void: + _cam_ctrl.zoom(amount) + +func _on_hand_scroll(direction: int) -> void: + _hand_mgr.spin_hand(direction) + +func _on_deselect_pending() -> void: + var cm: SelectionController.Mode = _sel_ctrl.mode + if cm == SelectionController.Mode.CARD_FROM_HAND \ + or cm == SelectionController.Mode.TERRAMORPHA_SELECT: + _sel_ctrl.set_mode(SelectionController.Mode.NONE) + +# ── Hand card click routing ─────────────────────────────────────────────────── + +func _on_hand_card_clicked(card_data: Dictionary) -> void: + var iid: String = str(card_data.get("instanceId", "")) + # Dedup: same card, same frame. + var cf: int = Engine.get_process_frames() + if cf == _last_click_frame and _last_click_iid == iid: + return + _last_click_frame = cf + _last_click_iid = iid + + var card: Dictionary = _hand_mgr.find_hand_card(iid) + if card.is_empty(): + return + if not Game.is_my_turn() and card.get("cardType", "") != "Instinct": + return + + # ArchSpirit → Ascend / Transition. + if card.get("cardType", "") == "ArchSpirit": + var tier: int = int(card.get("tier", 0)) + var cur_tier: int = _sel_ctrl._get_my_arch_tier() + if tier == cur_tier + 1: + _sel_ctrl._confirm_ascend(card) + elif tier == 1 and cur_tier >= 1: + _sel_ctrl._confirm_transition(card) + return + + # Terramorpha → multi-tile flow. + if card.get("cardType", "") == "Terramorpha": + if Game.get_my_player().get("currentSp", 0) < card.get("spCost", 0): + return + _sel_ctrl.sel_card_id = iid + _sel_ctrl.terra_targets = [] + _sel_ctrl.set_mode(SelectionController.Mode.TERRAMORPHA_SELECT) + _sel_ctrl.terra_count = _terra_count_for_card(card) + _clear_highlights() + _highlight_tiles(_tile_resolver.valid_play_tiles(card, _board_ctrl.tile_bodies), "movement") + return + + # Ruin → preflight + confirm. + if card.get("cardType", "") == "Ruin": + _sel_ctrl.channel_ruin(card) + return + + # Repentance / Instinct — may have an active ability. + if card.get("cardType", "") in ["Repentance", "Instinct"]: + var ab_mode: SelectionController.Mode = _sel_ctrl.mode + if (ab_mode == SelectionController.Mode.ABILITY_TARGET and _abt.ability_card_id == iid) \ + or (ab_mode == SelectionController.Mode.CARD_FROM_HAND and _sel_ctrl.sel_card_id == iid): + _sel_ctrl.set_mode(SelectionController.Mode.NONE) + return + if ab_mode in [SelectionController.Mode.CARD_FROM_HAND, + SelectionController.Mode.TERRAMORPHA_SELECT] \ + or (ab_mode == SelectionController.Mode.ABILITY_TARGET + and not _abt.ability_card_id.is_empty()): + _sel_ctrl.set_mode(SelectionController.Mode.NONE) + # Parse abilitiesJson for the first Active ability. + var abs_v: Variant = card.get("abilitiesJson") + var abs_raw: String = "" if abs_v == null else str(abs_v) + if not abs_raw.is_empty(): + var parsed_v: Variant = JSON.parse_string(abs_raw) + if parsed_v is Array: + var parsed: Array = _abt.normalize_keys(parsed_v) as Array + for ab_var: Variant in parsed: + if not (ab_var is Dictionary): + continue + var ab: Dictionary = ab_var as Dictionary + if ab.get("type", "").to_lower() != "active": + continue + var tgt_conds: Array = [] + for cv: Variant in ab.get("activationconditions", []): + if not (cv is Dictionary): + continue + var cd: Dictionary = cv as Dictionary + if cd.get("subject", "") == "target": + tgt_conds.append(cd) + _abt.ability_card_id = iid + _abt.ability_unit_id = "" + _abt.ability_idx = 0 + _abt.ability_def = _abt.get_ability_actions(ab) + _abt.ability_range = {} + _abt.ability_target_conditions = tgt_conds + _abt.ability_targets = [] + _abt.ability_cur_action_idx = 0 + _sel_ctrl.sel_card_id = iid + _sel_ctrl.set_mode(SelectionController.Mode.ABILITY_TARGET) + _clear_highlights() + _abt.start_ability_targeting() return - _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. - if Settings.touch_camera_mode == "gesture": - _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 Settings.touch_camera_mode == "gesture" and _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 Settings.touch_camera_mode == "gesture" and _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: - if Settings.touch_camera_mode == "gesture": - var mg := event as InputEventMagnifyGesture - _zoom((mg.factor - 1.0) * 8.0) - - elif event is InputEventPanGesture: - if Settings.touch_camera_mode != "gesture": - return - # 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 -const HEX_TILE_RADIUS := 0.5774 # ≈ 1/√3 — flat-to-flat = TILE_SPACING -const HEX_TILE_SPACING := TILE_SPACING * 0.5 # hex boards use tighter spacing - -var _board_grid_type : String = "Square" -var _board_hex_sides : int = 0 - -func _coord_to_world(x: int, y: int) -> Vector3: - if _board_grid_type == "Hexagon": - var N : int = _board_hex_sides - var q : float = x - (N - 1) - var r : float = y - (N - 1) - var wx : float = HEX_TILE_SPACING * sqrt(3.0) * (q + r * 0.5) - var wz : float = HEX_TILE_SPACING * 1.5 * r - return Vector3(wx, 0.0, wz) - 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 - if body.has_meta("unit_id"): - var unit_id := str(body.get_meta("unit_id")) - if not unit_id.is_empty(): - var unit := Game.get_unit_by_id(unit_id) - if not unit.is_empty(): - var pos := unit.get("position", {}) as Dictionary - if not pos.is_empty(): - return Vector2i(int(pos.get("x", -1)), int(pos.get("y", -1))) - 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 _is_ruin_unit(unit: Dictionary) -> bool: - return str(unit.get("cardType", "")).to_lower() == "ruin" - - -func _is_ruin_instance(instance_id: String) -> bool: - if instance_id.is_empty(): - return false - var unit := Game.get_unit_by_id(instance_id) - return not unit.is_empty() and _is_ruin_unit(unit) - - -func _tile_has_blocking_occupant(tile: Dictionary) -> bool: - var occupant_id := str(tile.get("occupantId", "")) - if occupant_id.is_empty() or occupant_id == "null": - print("[TileBlock] failing out") - return false - print("[TileBlock] returning this: ", not _is_ruin_instance(occupant_id)) - return not _is_ruin_instance(occupant_id) - - -func _safe_arch(player: Dictionary) -> Dictionary: - var arch = player.get("archSpirit") - return arch as Dictionary if arch is Dictionary else {} - - -func _all_board_units() -> Array: - var units : Array = [] - for player: Dictionary in Game.state.get("players", []): - for unit: Dictionary in player.get("field", []): - if not _is_ruin_unit(unit): - units.append(unit) - var arch : Dictionary = _safe_arch(player) - if not arch.is_empty(): - units.append(arch) - return units - - -func _units_obstructing_movement_type(mov: String) -> Dictionary: - var result : Dictionary = {} - var want_label := "obstruct:%s" % mov.to_lower() - var active_effects = Game.state.get("activeEffects") - if not active_effects is Array: - return result - for effect: Dictionary in active_effects: - if str(effect.get("label", "")).to_lower() == want_label: - var target_ref := str(effect.get("targetRef", "")) - if not target_ref.is_empty(): - result[target_ref] = true - return result - - -func _rebuild_ownership(state: Dictionary) -> void: - _enemy_unit_ids.clear() - _friendly_unit_ids.clear() - _unit_team_idx.clear() - var my_id := Auth.user_id - # Find my team index so allies are treated as friendly too. - var my_team_idx : int = -1 - for p: Dictionary in state.get("players", []): - if str(p.get("accountId", "")).to_lower() == my_id.to_lower(): - my_team_idx = int(p.get("teamIndex", -1)) - break - for p: Dictionary in state.get("players", []): - var pid : String = str(p.get("accountId", "")).to_lower() - var is_mine : bool = pid == my_id.to_lower() - var team_idx : int = int(p.get("teamIndex", -1)) - # In team games (teamIndex matches), treat allies as friendly. - var is_ally : bool = (not is_mine) and (my_team_idx >= 0) and (team_idx == my_team_idx) - var target : Dictionary = _friendly_unit_ids if (is_mine or is_ally) else _enemy_unit_ids - for u: Dictionary in p.get("field", []): - if _is_ruin_unit(u): - continue - var iid : String = u.get("instanceId", "") - if not iid.is_empty(): - target[iid] = true - _unit_team_idx[iid] = team_idx - var arch : Dictionary = _safe_arch(p) - var aid : String = arch.get("instanceId", "") - if not aid.is_empty(): - target[aid] = true - _unit_team_idx[aid] = team_idx - -# ── Board building ──────────────────────────────────────────────────────────── - -func _build_board(board: Dictionary) -> void: - _board_grid_type = board.get("gridType", "Square") - _board_hex_sides = int(board.get("hexSides", 0)) - 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 _shape_key_chk := "Hex" if _board_grid_type == "Hexagon" else "Square" - var has_model : bool = not ContentCache.get_tile_model_url(affinity, _shape_key_chk).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 mi := MeshInstance3D.new() - if _board_grid_type == "Hexagon": - var cyl := CylinderMesh.new() - cyl.radial_segments = 6 - cyl.top_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING - cyl.bottom_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING - cyl.height = h - mi.mesh = cyl - var cshape := CylinderShape3D.new() - cshape.radius = HEX_TILE_RADIUS * HEX_TILE_SPACING - cshape.height = h - shape.shape = cshape - else: - var box := BoxShape3D.new() - box.size = Vector3(0.98, h, 0.98) - shape.shape = box - var bm := BoxMesh.new() - bm.size = Vector3(0.98, h, 0.98) - mi.mesh = bm - body.add_child(shape) - - # Placeholder: affinity-coloured mesh, swapped out if a 3D model loads. - 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 shape_key := "Hex" if _board_grid_type == "Hexagon" else "Square" - var model_url := ContentCache.get_tile_model_url(affinity, shape_key) - if model_url.is_empty(): - if _board_grid_type == "Hexagon": - # No hex model — keep the affinity-coloured cylinder placeholder. - # Still attach a hex stalagmite below if one is available. - if want_bottom: - var bottom_url := ContentCache.get_random_tile_bottom_url("Hex") - if not bottom_url.is_empty(): - _try_load_tile_bottom(weakref(body), bottom_url) - return - # Square: apply a 2D texture and attach a stalagmite bottom. - 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("Square") - if not bottom_url.is_empty(): - _try_load_tile_bottom(weakref(body), bottom_url) + # No active ability — channel immediately. + Game.send_play_card(iid, 0, 0) 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(shape_key) - 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.75) - - # 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 team_colors : Dictionary = state.get("teamColors", {}) - var desired : Dictionary = {} # iid → {unit, color, is_enemy} - # Find my team index for ally detection. - var my_team_idx : int = -1 - for player: Dictionary in state.get("players", []): - if str(player.get("accountId", "")).to_lower() == my_id.to_lower(): - my_team_idx = int(player.get("teamIndex", -1)) - break - for player: Dictionary in state.get("players", []): - var pid : String = str(player.get("accountId", "")).to_lower() - var is_mine : bool = pid == my_id.to_lower() - var team_idx : int = int(player.get("teamIndex", -1)) - var is_ally : bool = (not is_mine) and (my_team_idx >= 0) and (team_idx == my_team_idx) - var is_enemy : bool = not (is_mine or is_ally) - # Use the team's palette color; fall back to blue (friendly) or red (enemy). - var hex_str : String = str(team_colors.get(str(team_idx), "")) - var color : Color - if not hex_str.is_empty(): - color = Color.html("#" + hex_str) - elif is_enemy: - color = Color(1.0, 0.35, 0.35) - else: - color = Color(0.3, 0.5, 1.0) - 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": is_enemy} - - # 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_team_idx.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) - - # 4. Refresh idle rotation for all units — nearest enemy may have changed. - for iid : String in _unit_meshes: - if _move_anims.has(iid): continue # don't interrupt an in-progress move - var m := _unit_meshes.get(iid) as Node3D - if is_instance_valid(m): - m.rotation.y = _idle_rotation(iid) - - -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) - _prime_unit_sfx(def) - 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(): + # Deselect if same card clicked again. + if _sel_ctrl.mode == SelectionController.Mode.CARD_FROM_HAND \ + and _sel_ctrl.sel_card_id == iid: + _sel_ctrl.set_mode(SelectionController.Mode.NONE) return - # Asset-level config (model-file specific). - var facing_dir : String = str(model_asset.get("modelFacingDirection", "south")) - # 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) + # Standard card — enter CARD_FROM_HAND mode with tile highlights. + _sel_ctrl.sel_card_id = iid + _sel_ctrl.set_mode(SelectionController.Mode.CARD_FROM_HAND) + _clear_highlights() + _highlight_tiles(_tile_resolver.valid_play_tiles(card, _board_ctrl.tile_bodies), "movement") -## 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: +func _refresh_hand_selection() -> void: + if _sel_ctrl == null or _abt == null: 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) + var cur_mode: SelectionController.Mode = _sel_ctrl.mode + var sel_card_id: String = _sel_ctrl.sel_card_id + var ability_card_id: String = _abt.ability_card_id + var needs_layout: bool = false + for widget: Node in _hand_cards.get_children(): + if not widget.has_meta("card_instance_id"): + continue + var iid: String = str(widget.get_meta("card_instance_id")) + var sel: bool = ( + (cur_mode == SelectionController.Mode.CARD_FROM_HAND + or cur_mode == SelectionController.Mode.TERRAMORPHA_SELECT + or (cur_mode == SelectionController.Mode.ABILITY_TARGET + and not ability_card_id.is_empty())) + and sel_card_id == iid) + if widget.has_method("set_selected"): + widget.set_selected(sel) + if sel != bool(widget.get_meta("_sel", false)): + widget.set_meta("_sel", sel) + needs_layout = true + if needs_layout: + _hand_mgr.queue_hand_layout() - -## 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 the nearest -## enemy unit on the board. Falls back to the fixed north/south heuristic when -## no enemy body is found (e.g. during initial placement before enemies exist). -func _idle_rotation(iid: String) -> float: - var base : float = float(_model_base_angles.get(iid, 0.0)) - var my_body := _unit_bodies.get(iid) as StaticBody3D - if is_instance_valid(my_body): - var my_pos : Vector3 = my_body.global_position - var best_sq : float = INF - var best_dir : Vector3 = Vector3.ZERO - # Build opponent list using team index when available (spectate-safe). - # When spectating, all units land in _enemy_unit_ids so friend/enemy split - # is meaningless — instead find any unit whose team differs from ours. - var my_team : int = int(_unit_team_idx.get(iid, -1)) - var enemy_ids : Array - if my_team >= 0: - enemy_ids = [] - for eid in _unit_bodies: - if int(_unit_team_idx.get(eid, -1)) != my_team: - enemy_ids.append(eid) - else: - var is_enemy_unit : bool = _is_enemy_unit(iid) - enemy_ids = _enemy_unit_ids.keys() if not is_enemy_unit \ - else _friendly_unit_ids.keys() - var found_bodies : int = 0 - for eid in enemy_ids: - var eb := _unit_bodies.get(eid) as StaticBody3D - if not is_instance_valid(eb): continue - found_bodies += 1 - var d : Vector3 = eb.global_position - my_pos - var sq : float = d.x * d.x + d.z * d.z - if sq < best_sq: - best_sq = sq - best_dir = d - if best_sq < INF and (best_dir.x != 0.0 or best_dir.z != 0.0): - var flat := Vector3(best_dir.x, 0.0, best_dir.z).normalized() - return atan2(flat.x, -flat.z) - base - # Log why closest-enemy failed. - push_warning("[IdleRot] FALLBACK iid=%s team=%d enemy_ids=%d bodies_found=%d best_sq=%s dir_xz=(%s,%s)" \ - % [iid.substr(0,8), my_team, enemy_ids.size(), found_bodies, - str(best_sq), str(best_dir.x), str(best_dir.z)]) - else: - push_warning("[IdleRot] FALLBACK iid=%s — body not in _unit_bodies (friendly=%d enemy=%d)" \ - % [iid.substr(0,8), _friendly_unit_ids.size(), _enemy_unit_ids.size()]) - # Fallback: fixed north/south heuristic. - var flip : bool = bool(_needs_face_rot.get(iid, false)) - 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, "")) - - -func _prime_unit_sfx(def: Dictionary) -> void: - if def.is_empty(): - return - for sfx_key: String in UNIT_SFX_KEYS: - var url := str(def.get(sfx_key, "")).strip_edges() - if not url.is_empty(): - SFX.prime(url) - - -## 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 - - -func _unit_action_duration(iid: String, action: String, fallback: float = 0.35) -> float: - var ap : AnimationPlayer = _anim_players.get(iid, null) - if ap == null or not is_instance_valid(ap): - return fallback - 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 fallback - var anim := ap.get_animation(track) - if anim == null: - return fallback - return maxf(fallback, float(anim.length)) - - -## Counterattack phase 2: defender plays "attack", then triggers attacker "damaged". -func _play_counter_attack(defender_iid: String, attacker_iid: String, - attacker_def_loss: int, attacker_hp_loss: int, hitsplats_shown: Dictionary) -> 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")) - var counter_time := _unit_action_duration(defender_iid, "attack") - var t := create_tween() - t.tween_callback(func() -> 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")) - _show_hitsplats_once(hitsplats_shown, attacker_iid, attacker_def_loss, attacker_hp_loss) - ).set_delay(counter_time) - - -## 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, - defender_def_loss: int, defender_hp_loss: int, - attacker_def_loss: int, attacker_hp_loss: int, - hitsplats_shown: Dictionary) -> 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")) - _show_hitsplats_once(hitsplats_shown, defender_iid, defender_def_loss, defender_hp_loss) - var damaged_time := _unit_action_duration(defender_iid, "damaged") - var td := create_tween() - td.tween_callback(func() -> void: - _play_counter_attack(defender_iid, attacker_iid, attacker_def_loss, attacker_hp_loss, hitsplats_shown) - ).set_delay(damaged_time) - ).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 - if attacker_iid.is_empty() and not _last_attack_source_iid.is_empty() \ - and _unit_bodies.has(_last_attack_source_iid): - attacker_iid = _last_attack_source_iid - attack_remaining = _unit_action_duration(attacker_iid, "attack") - - # ── Collect who took damage / died ─────────────────────────────────────── - var damaged_iids : Dictionary = {} - var defense_hits : Dictionary = {} - var health_hits : 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 _def_v = unit.get("currentDefense") - var new_hp := 0 if _hp_v == null else int(_hp_v) - var new_def := 0 if _def_v == null else int(_def_v) - var old_hp : int = _prev_unit_hp.get(iid, new_hp) - var old_def : int = _prev_unit_def.get(iid, new_def) - seen_iids[iid] = true - if new_def < old_def: - defense_hits[iid] = old_def - new_def - if new_hp < old_hp: - health_hits[iid] = old_hp - new_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 - var dying_old_hp := int(_prev_unit_hp.get(iid, 0)) - if dying_old_hp > 0: - health_hits[iid] = dying_old_hp - - # 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_source : String = _last_attack_source_iid - var tracked_target : String = _last_attack_target_iid - _last_attack_source_iid = "" - _last_attack_target_iid = "" - if attacker_iid.is_empty() and not tracked_source.is_empty() and _unit_bodies.has(tracked_source): - attacker_iid = tracked_source - attack_remaining = _unit_action_duration(attacker_iid, "attack") - var hitsplats_shown : Dictionary = {} - - if damaged_iids.is_empty() and defense_hits.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 - - if damaged_iids.is_empty() and not defense_hits.is_empty(): - for iid: String in defense_hits: - _show_hitsplats_once(hitsplats_shown, iid, int(defense_hits.get(iid, 0)), 0, attack_remaining) - 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 tb2 := create_tween() - tb2.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 != "" - - var display_delay := attack_remaining if attacker_iid != "" else 0.0 - for iid: String in seen_iids: - _show_hitsplats_once( - hitsplats_shown, - iid, - int(defense_hits.get(iid, 0)), - int(health_hits.get(iid, 0)), - display_delay) - for iid: String in dying_iids: - _show_hitsplats_once( - hitsplats_shown, - iid, - int(defense_hits.get(iid, 0)), - int(health_hits.get(iid, 0)), - display_delay) - - # ── Schedule animations ─────────────────────────────────────────────────── - if is_counterattack: - # Full chain handles the attacker and primary defender. - _play_counter_chain( - defender_iid, - attacker_iid, - attack_remaining, - int(defense_hits.get(defender_iid, 0)), - int(health_hits.get(defender_iid, 0)), - int(defense_hits.get(attacker_iid, 0)), - int(health_hits.get(attacker_iid, 0)), - hitsplats_shown) - # Any other simultaneously-damaged units get a simple delay (uncommon). - for iid: String in seen_iids: - if iid == attacker_iid or iid == defender_iid: - continue - var def_loss := int(defense_hits.get(iid, 0)) - var hp_loss := int(health_hits.get(iid, 0)) - if def_loss <= 0 and hp_loss <= 0: - continue - var hit_iid := iid - var hit_def := def_loss - var hit_hp := hp_loss - 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): - if hit_hp > 0: - _play_unit_anim(hit_iid, "damaged") - SFX.play(_sfx_for_unit(hit_iid, "damagedSoundUrl")) - _show_hitsplats_once(hitsplats_shown, hit_iid, hit_def, hit_hp) - ).set_delay(attack_remaining) - else: - for iid: String in seen_iids: - var def_loss := int(defense_hits.get(iid, 0)) - var hp_loss := int(health_hits.get(iid, 0)) - if def_loss <= 0 and hp_loss <= 0: - continue - var ap : AnimationPlayer = _anim_players.get(iid, null) - if hp_loss > 0 and 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 cap_def := def_loss - var cap_hp := hp_loss - var dmg_cb := func(_n: String) -> void: - _play_unit_anim(cap_iid, "damaged", false) - SFX.play(_sfx_for_unit(cap_iid, "damagedSoundUrl")) - _show_hitsplats_once(hitsplats_shown, cap_iid, cap_def, cap_hp) - 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 hit_def := def_loss - var hit_hp := hp_loss - 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): - if hit_hp > 0: - _play_unit_anim(hit_iid, "damaged") - SFX.play(_sfx_for_unit(hit_iid, "damagedSoundUrl")) - _show_hitsplats_once(hitsplats_shown, hit_iid, hit_def, hit_hp) - ).set_delay(attack_remaining) - else: - if hp_loss > 0: - _play_unit_anim(iid, "damaged") - SFX.play(_sfx_for_unit(iid, "damagedSoundUrl")) - _show_hitsplats_once(hitsplats_shown, iid, def_loss, hp_loss) - - for iid: String in dying_iids: - _show_hitsplats_once(hitsplats_shown, iid, int(defense_hits.get(iid, 0)), int(health_hits.get(iid, 0))) - _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_def.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") or 0) - _prev_unit_def[iid] = int(unit.get("currentDefense") or 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)) - - -## BFS on the game grid using the correct neighbour set for the current grid type. -## 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] - if _board_grid_type == "Hexagon": - DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1), - Vector2i(1,-1), Vector2i(-1,1)] - else: - DIRS = [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 ──────────────────────────────────────────────────────────────── +# ── Highlight system (board overlay quads) ──────────────────────────────────── 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] + var children: Array = _hi_root.get_children() + for c: Node in children: 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 _add_highlight(x: int, y: int, type_key: String) -> void: + var mi: MeshInstance3D = MeshInstance3D.new() + if _pathfinder.grid_type == "Hexagon": + var hm: CylinderMesh = CylinderMesh.new() + hm.radial_segments = 6 + hm.top_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING * 0.95 + hm.bottom_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING * 0.95 + hm.height = 0.02 + mi.mesh = hm + else: + var pm: PlaneMesh = PlaneMesh.new() + pm.size = Vector2(0.96, 0.96) + mi.mesh = pm + var mat: StandardMaterial3D = StandardMaterial3D.new() + mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA + mat.emission_enabled = true + mat.emission_energy_multiplier = 1.5 + mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED + mat.cull_mode = BaseMaterial3D.CULL_DISABLED + var tex: Texture2D = HighlightConfig.get_texture(type_key) + var col: Color = HighlightConfig.get_color(type_key) + if tex != null: + mat.albedo_texture = tex + mat.albedo_color = Color(col.r, col.g, col.b, col.a) + else: + mat.albedo_color = col + mat.emission = Color(col.r, col.g, col.b) + mi.material_override = mat + var tile_top: float = _board_ctrl.tile_visual_tops.get( + "%d,%d" % [x, y], + _board_ctrl.tile_y_bases.get("%d,%d" % [x, y], 0.0) + + _board_ctrl.tile_heights.get("%d,%d" % [x, y], 1.0)) + mi.position = _pathfinder.coord_to_world(x, y) + Vector3(0, tile_top + 0.05, 0) + _hi_root.add_child(mi) + + +func _highlight_tiles(coords: Array, type_key: String) -> void: + for coord: Variant in coords: + if coord is Vector2i: + _add_highlight((coord as Vector2i).x, (coord as Vector2i).y, type_key) + elif coord is Dictionary: + _add_highlight( + int((coord as Dictionary).get("x", 0)), + int((coord as Dictionary).get("y", 0)), + type_key) + + +func _on_highlight_texture_loaded(_type: String) -> void: + if _sel_ctrl == null: + return + var cm: SelectionController.Mode = _sel_ctrl.mode + match cm: + SelectionController.Mode.UNIT_SELECTED: + if not _sel_ctrl.sel_unit_id.is_empty(): + _sel_ctrl.select_unit(_sel_ctrl.sel_unit_id) + SelectionController.Mode.CARD_FROM_HAND, SelectionController.Mode.TERRAMORPHA_SELECT: + var sel_card: Dictionary = _hand_mgr.find_hand_card(_sel_ctrl.sel_card_id) + if not sel_card.is_empty(): + _clear_highlights() + _highlight_tiles( + _tile_resolver.valid_play_tiles(sel_card, _board_ctrl.tile_bodies), + "movement") + SelectionController.Mode.PLACEMENT: + _clear_highlights() + _highlight_tiles(_tile_resolver.valid_placement_tiles(), "movement") + _: + pass + if _hovered_coord.x >= 0: + _hovered_coord = Vector2i(-1, -1) + +# ── Hover cursor ────────────────────────────────────────────────────────────── + +func _init_cursor_nodes() -> void: + _cursor_highlight = _make_highlight_quad(Color(1, 1, 1, 0.25)) + _hover_team_overlay = _make_highlight_quad(Color(0, 0, 0, 0)) + _hi_root.add_child(_cursor_highlight) + _hi_root.add_child(_hover_team_overlay) + _cursor_highlight.visible = false + _hover_team_overlay.visible = false + + +func _make_highlight_quad(fallback: Color) -> MeshInstance3D: + var mi: MeshInstance3D = MeshInstance3D.new() + var pm: PlaneMesh = PlaneMesh.new() + pm.size = Vector2(0.96, 0.96) + mi.mesh = pm + var mat: StandardMaterial3D = StandardMaterial3D.new() + mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA + mat.albedo_color = fallback + mat.emission_enabled = true + mat.emission = Color(fallback.r, fallback.g, fallback.b) + mat.emission_energy_multiplier = 1.5 + mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED + mat.cull_mode = BaseMaterial3D.CULL_DISABLED + mi.material_override = mat + return mi + + func _update_hover(mouse_pos: Vector2) -> void: if _cursor_highlight == null or _hover_team_overlay == null: return - - # If dragging (camera rotation / pan), hide highlights. - if _drag_active or _pan_active: + if _input_handler != null and (_input_handler.drag_active or _input_handler.pan_active): _cursor_highlight.visible = false _hover_team_overlay.visible = false _reset_unit_hover_glow() _hovered_coord = Vector2i(-1, -1) return - - var coord := _mouse_to_tile_coord(mouse_pos) + var coord: Vector2i = _pathfinder.mouse_to_tile_coord(mouse_pos, _board_ctrl.tile_bodies) 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") + 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 "" + var tile: Dictionary = Game.get_tile(coord.x, coord.y) + var raw_occ: Variant = tile.get("occupantId") + var occ_id: String = str(raw_occ) if raw_occ != null else "" if occ_id.is_empty(): _hover_team_overlay.visible = false return - - var is_enemy : bool = _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) - + var is_enemy: bool = _unit_reg.enemy_unit_ids.has(occ_id) + var team_col: Color = Color(1.0, 0.35, 0.35, 0.35) if is_enemy else Color(0.3, 0.5, 1.0, 0.35) _place_highlight_quad(_hover_team_overlay, coord.x, coord.y, team_col) - - # Boost emission on the unit mesh. - if _unit_meshes.has(occ_id): - var mesh : MeshInstance3D = _unit_meshes[occ_id] as MeshInstance3D + if _mesh_builder.unit_meshes.has(occ_id): + var mesh: MeshInstance3D = _mesh_builder.unit_meshes[occ_id] as MeshInstance3D if mesh != null: - var orig_mat : Material = mesh.get_active_material(0) + 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) + 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 @@ -2874,179 +922,135 @@ func _reset_unit_hover_glow() -> void: _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() - if _board_grid_type == "Hexagon": - var hm := CylinderMesh.new() - hm.radial_segments = 6 - hm.top_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING * 0.95 - hm.bottom_radius = HEX_TILE_RADIUS * HEX_TILE_SPACING * 0.95 - hm.height = 0.02 - mi.mesh = hm - else: - var pm := PlaneMesh.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 +func _place_highlight_quad(quad: MeshInstance3D, x: int, y: int, + col: Color, texture: Texture2D = null) -> void: + var tile_top: float = _board_ctrl.tile_visual_tops.get( + "%d,%d" % [x, y], + _board_ctrl.tile_y_bases.get("%d,%d" % [x, y], 0.0) + + _board_ctrl.tile_heights.get("%d,%d" % [x, y], 1.0)) + quad.position = _pathfinder.coord_to_world(x, y) + Vector3(0, tile_top + 0.05, 0) + var mat: StandardMaterial3D = quad.material_override as StandardMaterial3D mat.albedo_color = col mat.emission = Color(col.r, col.g, col.b) if texture != null: mat.albedo_texture = texture quad.visible = true +# ── Hold-timer context popup ────────────────────────────────────────────────── -func _on_highlight_texture_loaded(_type: String) -> void: - match _mode: - Mode.UNIT_SELECTED: - if not _sel_unit_id.is_empty(): - _select_unit(_sel_unit_id) - Mode.CARD_FROM_HAND, Mode.TERRAMORPHA_SELECT: - var sel_card := _find_hand_card(_sel_card_id) - if not sel_card.is_empty(): - _clear_highlights() - _highlight_tiles(_valid_play_tiles(sel_card), "movement") - Mode.PLACEMENT: - _clear_highlights() - _highlight_tiles(_valid_placement_tiles(), "movement") - _: - pass - - if _hovered_coord.x >= 0: - _hovered_coord = Vector2i(-1, -1) - _update_hover(get_viewport().get_mouse_position()) - -# ── 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 = _board_distance(tx, ty, ax, ay) - if dist < min_r or dist > max_r: continue - var tile : Dictionary = Game.get_tile(tx, ty) - print("tile", tile) - print("[GettingAff]", card_affinity) - if not _tile_has_blocking_occupant(tile): continue - if card_affinity != "" and not _tile_matches_channel_affinity(tile, card_affinity): continue - results.append(Vector2i(tx, ty)) - - "Terramorpha": - for tx in range(bw): - for ty in range(bh): - if not _tile_bodies.has("%d,%d" % [tx, ty]): continue - results.append(Vector2i(tx, ty)) - - "Repentance", "Instinct", "Ruin": - pass # No tile target — played directly (server handles placement for Ruins, repentance and Instinct have own target systems). - - return results +func _on_hold_timer_fired() -> void: + var coord: Vector2i = _input_handler.held_coord if _input_handler != null else Vector2i(-1, -1) + if coord.x < 0: + return + _held_coord_show_popup(coord) -func _tile_matches_channel_affinity(tile: Dictionary, card_affinity: String) -> bool: - var resolved_affinity : String = str(tile.get("resolvedAffinity", "Void")) - print("[AFFINITY_TILE]", resolved_affinity, card_affinity) - if resolved_affinity == "PerfectAether" and card_affinity in ["Lake", "Hill", "Forest", "Field"]: - return true - if resolved_affinity == "UnstableAether": - return false +func _held_coord_show_popup(coord: Vector2i) -> void: + var tile: Dictionary = Game.get_tile(coord.x, coord.y) + if tile.is_empty(): + return + var aff: String = tile.get("resolvedAffinity", "Void") + _ctx_tile_lbl.text = "Tile (%d,%d) — %s" % [coord.x, coord.y, aff] + var raw_occ: Variant = tile.get("occupantId") + var occupant_id: String = raw_occ if raw_occ is String else "" + if occupant_id.is_empty(): + _ctx_unit_lbl.text = "" + _ctx_abil_lbl.text = "" + else: + var unit: Dictionary = Game.get_unit_by_id(occupant_id) + _ctx_unit_lbl.text = "%s HP %d/%d DEF %d/%d ATK %d" % [ + unit.get("name", "?"), + int(unit.get("currentHealth", 0)), int(unit.get("maxHealth", 0)), + int(unit.get("currentDefense", 0)), int(unit.get("maxDefense", 0)), + int(unit.get("damage", 0))] + var abil_str: String = "" + var raw_abil: Variant = unit.get("abilitiesJson") + var parsed: Variant = JSON.parse_string("[]" if raw_abil == null else str(raw_abil)) + if parsed is Array: + for ab: Dictionary in parsed: + abil_str += "• %s\n" % str(ab.get("name", "")) + _ctx_abil_lbl.text = abil_str.strip_edges() + _ctx_popup.visible = true - if card_affinity in ["Lake", "Hill", "Forest", "Field"]: - var base1 : String = str(tile.get("base1", "Void")) - var base2 : String = str(tile.get("base2", "Void")) - return base1 == card_affinity or base2 == card_affinity - - return resolved_affinity == card_affinity +# ── Game-over / session signals ─────────────────────────────────────────────── + +func _on_game_over(winner_id: String, win_condition: String, + winner_delta: int, loser_delta: int, player_outcomes: Array = []) -> void: + _game_over.show_result(winner_id, win_condition, winner_delta, loser_delta, player_outcomes) + + +func _on_session_abandoned(reason: String) -> void: + _game_over.on_session_abandoned(reason) + + +func _on_opponent_inactive(sid: String) -> void: + _inactive_dlgs.on_opponent_inactive(sid) + + +func _on_inactive_warning(sid: String) -> void: + _inactive_dlgs.on_inactive_warning(sid) + + +func _on_both_idle_warning(sid: String) -> void: + _inactive_dlgs.on_both_idle_warning(sid) + + +func _on_player_eliminated(session_id: String, elim_id: String, + seat_idx: int, team_idx: int) -> void: + _inactive_dlgs.on_player_eliminated(session_id, elim_id, seat_idx, team_idx) + + +func _on_spectator_mode_requested() -> void: + _is_spectating = true + _setup_spectator_ui() + +# ── Spectator ───────────────────────────────────────────────────────────────── + +func _setup_spectator_ui() -> void: + _pending_popup_cards_clear() + var lbl: Label = Label.new() + lbl.text = "SPECTATING" + lbl.modulate = Color(1.0, 0.76, 0.2) + lbl.add_theme_font_size_override("font_size", 18) + lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + lbl.set_anchors_preset(Control.PRESET_TOP_WIDE) + lbl.position = Vector2(0, 8) + _hud.add_child(lbl) + _hand_area.visible = false + _sp_st_panel.visible = false + _deck_discard_panel.visible = false + _draw_btn.visible = false + _end_turn_btn.visible = false + _spectator_panel.visible = true + _spectator_leave_btn.visible = true + _spectator_leave_btn.pressed.connect(func() -> void: + Game.stop_spectating() + get_tree().change_scene_to_file("res://scenes/free_play/FreePlayScreen.tscn")) + + +func _pending_popup_cards_clear() -> void: + if _hand_mgr != null: + _hand_mgr.pending_popup_cards.clear() + if is_instance_valid(_hand_mgr.popup_layer): + _hand_mgr.popup_layer.visible = false + +# ── Action buttons ──────────────────────────────────────────────────────────── + +func _on_draw_pressed() -> void: + Game.send_draw() + + +func _on_end_turn_pressed() -> void: + _sel_ctrl.set_mode(SelectionController.Mode.NONE) + Game.send_end_turn() + +# ── Helpers ─────────────────────────────────────────────────────────────────── + +func _mouse_to_unit_id(mouse_pos: Vector2) -> String: + var body: PhysicsBody3D = _pathfinder.raycast_body(mouse_pos) + if body == null: + return "" + return str(body.get_meta("unit_id", "")) func _terra_count_for_card(card: Dictionary) -> int: @@ -3055,3409 +1059,3 @@ func _terra_count_for_card(card: Dictionary) -> int: "Di": return 2 "Tri": return 3 return 1 - - -## BFS reachable set — returns all coords reachable within max_mp steps, -## treating blocked_coords as impassable walls (destination included in check). -## Mirrors Pathfinding.GetReachableWithCost on the server. -func _board_distance(x1: int, y1: int, x2: int, y2: int) -> int: - if _board_grid_type == "Hexagon": - var N : int = _board_hex_sides - var dq : int = (x1 - (N - 1)) - (x2 - (N - 1)) - var dr : int = (y1 - (N - 1)) - (y2 - (N - 1)) - return (abs(dq) + abs(dr) + abs(dq + dr)) / 2 - return abs(x1 - x2) + abs(y1 - y2) - - -func _bfs_reachable(fx: int, fy: int, max_mp: int, blocked_coords: Dictionary) -> Array: - var bw := Game.board_width() - var bh := Game.board_height() - var DIRS : Array[Vector2i] - if _board_grid_type == "Hexagon": - DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1), - Vector2i(1,-1), Vector2i(-1,1)] - else: - DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)] - var cost : Dictionary = { Vector2i(fx, fy): 0 } - var queue : Array = [Vector2i(fx, fy)] - while not queue.is_empty(): - var cur : Vector2i = queue.pop_front() - var cur_cost : int = cost[cur] - if cur_cost >= max_mp: continue - 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 cost.has(nxt): continue - if blocked_coords.has(nxt): continue - cost[nxt] = cur_cost + 1 - queue.append(nxt) - var results : Array = [] - for coord in cost.keys(): - if coord != Vector2i(fx, fy): - results.append(coord) - return results - - -func _valid_move_tiles(unit: Dictionary) -> Array: - var pos : Dictionary = unit.get("position", {}) - if pos.is_empty(): return [] - var ux : int = pos.get("x", 0) - var uy : int = pos.get("y", 0) - var mp : int = unit.get("currentMp", 0) - var mov : String = str(unit.get("movementType", "Walk")).to_lower() - if not bool(unit.get("canMove", false)): return [] - if mp <= 0: return [] - - var bw : int = Game.board_width() - var bh : int = Game.board_height() - - # Walk / Flight: BFS — can't pass through blocked tiles - if mov == "walk" or mov == "flight": - # Build blocked set from all occupants, excluding this unit. - var blocked : Dictionary = {} - var extra_obstructors := _units_obstructing_movement_type(mov) - var moving_id := str(unit.get("instanceId", "")) - for unit_dict : Dictionary in _all_board_units(): - var up : Dictionary = unit_dict.get("position", {}) - if up.is_empty(): continue - var iid := str(unit_dict.get("instanceId", "")) - if iid == moving_id: continue - var cx : int = up.get("x", 0) - var cy : int = up.get("y", 0) - if cx == ux and cy == uy: continue # don't block own tile - # Flight is blocked by other Flight units or explicit movement obstructors. - if mov == "flight": - var blocks_flight := str(unit_dict.get("movementType", "Walk")).to_lower() == "flight" - if not blocks_flight and not extra_obstructors.has(iid): - continue - blocked[Vector2i(cx, cy)] = true - return _bfs_reachable(ux, uy, mp, blocked) - - # Jump / Teleport: land on any unoccupied tile. Teleport also requires LOS. - var results : Array = [] - if mov != "jump" and mov != "teleport": - return results - for tx in range(bw): - for ty in range(bh): - if not _tile_bodies.has("%d,%d" % [tx, ty]): continue - if tx == ux and ty == uy: continue - if _tile_has_blocking_occupant(Game.get_tile(tx, ty)): continue - # Teleport additionally requires LOS to the destination. - if mov == "teleport" and not _client_has_los(ux, uy, tx, ty): 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 = int(unit.get("minAttackRange") or 1) - var max_r : int = int(unit.get("maxAttackRange") or 1) - var needs_los : bool = bool(unit.get("attackRequiresLos", false)) - if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0: - return results - for t: Dictionary in Game.get_all_enemy_units(): - if _is_ruin_unit(t): - continue - if not t.get("canBeAttacked", true): continue - var _tpos = t.get("position") - if not (_tpos is Dictionary): continue - var tp : Dictionary = _tpos - if tp.is_empty(): continue - var tx : int = tp.get("x", 0) - var ty : int = tp.get("y", 0) - var dist : int = _board_distance(tx, ty, ux, uy) - if dist < min_r or dist > max_r: continue - if needs_los and not _client_has_los(ux, uy, tx, ty): continue - 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 = int(unit.get("minAttackRange") or 1) - var max_r : int = int(unit.get("maxAttackRange") or 1) - var needs_los : bool = bool(unit.get("attackRequiresLos", false)) - if unit.get("isExhausted", false) and unit.get("extraAttacksRemaining", 0) == 0: - return results - for t: Dictionary in Game.get_all_enemy_units(): - if not t.get("canBeAttacked", true): continue - var tp : Dictionary = t.get("position", {}) - if tp.is_empty(): continue - var tx : int = tp.get("x", 0) - var ty : int = tp.get("y", 0) - var dist : int = _board_distance(tx, ty, ux, uy) - if dist < min_r or dist > max_r: continue - if needs_los and not _client_has_los(ux, uy, tx, ty): continue - 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) - var needs_los : bool = bool(unit.get("attackRequiresLos", false)) - 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 = _board_distance(tx, ty, ux, uy) - if dist < min_r or dist > max_r: continue - if needs_los and not _client_has_los(ux, uy, tx, ty): continue - 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(): - if _is_ruin_unit(unit): - continue - 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 _board_distance(ux, uy, ax, 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 Details" - 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) - - _tile_drawer_tile_section = _create_tile_drawer_section(vbox, "Tile Details", true) - _tile_drawer_spirit_section = _create_tile_drawer_section(vbox, "Spirit Details", false) - _tile_drawer_spirit_effects_section = _create_scrollable_section(vbox, "Active Effects") - _tile_drawer_token_section = _create_tile_drawer_section(vbox, "Spirit Token Details", false) - _tile_drawer_token_effects_section = _create_scrollable_section(vbox, "Active Effects") - _tile_drawer_arch_section = _create_tile_drawer_section(vbox, "ArchSpirit Details", false) - _tile_drawer_arch_effects_section = _create_scrollable_section(vbox, "Active Effects") - _tile_drawer_ruin_section = _create_tile_drawer_section(vbox, "Ruin Details", false) - _tile_drawer_ruin_effects_section = _create_scrollable_section(vbox, "Active Effects") - - _tile_drawer_tile_labels = _create_detail_labels(_tile_drawer_tile_section["content"], 5) - _tile_drawer_spirit_labels = _create_detail_labels(_tile_drawer_spirit_section["content"], 5) - _tile_drawer_token_labels = _create_detail_labels(_tile_drawer_token_section["content"], 5) - _tile_drawer_arch_labels = _create_detail_labels(_tile_drawer_arch_section["content"], 6) - _tile_drawer_ruin_labels = _create_detail_labels(_tile_drawer_ruin_section["content"], 2) - - _set_tile_drawer_button_state() - - -func _create_tile_drawer_section(parent: VBoxContainer, title: String, - expanded: bool) -> Dictionary: - var section: VBoxContainer = VBoxContainer.new() - section.layout_mode = 2 - section.add_theme_constant_override("separation", 4) - parent.add_child(section) - - var header: Button = Button.new() - header.layout_mode = 2 - header.toggle_mode = true - header.button_pressed = expanded - header.alignment = HORIZONTAL_ALIGNMENT_LEFT - header.text = _tile_drawer_section_title(title, expanded) - section.add_child(header) - - var content: VBoxContainer = VBoxContainer.new() - content.layout_mode = 2 - content.visible = expanded - content.add_theme_constant_override("separation", 2) - section.add_child(content) - - section.visible = expanded - - header.toggled.connect(func(is_pressed: bool) -> void: - content.visible = is_pressed - header.text = _tile_drawer_section_title(title, is_pressed)) - - return { - "root": section, - "header": header, - "content": content, - "title": title, - } - - -func _tile_drawer_section_title(title: String, expanded: bool) -> String: - return "%s %s" % ["[-]" if expanded else "[+]", title] - - -## Creates a collapsible section whose content sits inside a ScrollContainer so that -## long effect lists don't overflow the drawer. The returned dict has the same keys -## as _create_tile_drawer_section ("root", "header", "content", "title") plus "scroll" -## and a mutable "count" entry used to keep the header label up-to-date. -func _create_scrollable_section(parent: VBoxContainer, title: String) -> Dictionary: - var section : VBoxContainer = VBoxContainer.new() - section.layout_mode = 2 - section.add_theme_constant_override("separation", 4) - parent.add_child(section) - - var header := Button.new() - header.layout_mode = 2 - header.toggle_mode = true - header.button_pressed = false - header.alignment = HORIZONTAL_ALIGNMENT_LEFT - header.text = _tile_drawer_section_title(title, false) - section.add_child(header) - - var scroll := ScrollContainer.new() - scroll.layout_mode = 2 - scroll.custom_minimum_size = Vector2(0, 90) - scroll.vertical_scroll_mode = ScrollContainer.SCROLL_MODE_AUTO - scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED - scroll.visible = false - section.add_child(scroll) - - var content : VBoxContainer = VBoxContainer.new() - content.layout_mode = 2 - content.size_flags_horizontal = Control.SIZE_EXPAND_FILL - content.add_theme_constant_override("separation", 2) - scroll.add_child(content) - - section.visible = false - - var data: Dictionary = { - "root": section, - "header": header, - "scroll": scroll, - "content": content, - "title": title, - "count": 0, - } - - header.toggled.connect(func(is_pressed: bool) -> void: - scroll.visible = is_pressed - var n: int = data.get("count", 0) - var t: String = data.get("title", "Active Effects") - var display: String = ("%s (%d)" % [t, n]) if n > 0 else t - header.text = _tile_drawer_section_title(display, is_pressed)) - - return data - - -## Updates the effects section header text (e.g. "Active Effects (3)") and stores -## the count so the toggle signal can rebuild the label correctly. -func _update_effects_section_header(section: Dictionary, count: int) -> void: - section["count"] = count - var header: Button = section.get("header") as Button - if not is_instance_valid(header): - return - var title: String = section.get("title", "Active Effects") - var display: String = ("%s (%d)" % [title, count]) if count > 0 else title - header.text = _tile_drawer_section_title(display, header.button_pressed) - - -func _create_detail_labels(parent: VBoxContainer, count: int) -> Array: - var labels: Array = [] - for _i in range(count): - var lbl: Label = Label.new() - lbl.layout_mode = 2 - lbl.mouse_filter = Control.MOUSE_FILTER_STOP - lbl.add_theme_font_size_override("font_size", 12) - lbl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART - parent.add_child(lbl) - labels.append(lbl) - return labels - - -func _append_tile_drawer_label(parent: VBoxContainer, labels: Array) -> void: - var lbl: Label = Label.new() - lbl.layout_mode = 2 - lbl.mouse_filter = Control.MOUSE_FILTER_STOP - lbl.add_theme_font_size_override("font_size", 12) - lbl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART - parent.add_child(lbl) - labels.append(lbl) - - -func _set_tile_drawer_lines(section: Dictionary, labels: Array, lines: Array, - tooltips: Array = []) -> void: - var root: Control = section.get("root") as Control - var content: VBoxContainer = section.get("content") as VBoxContainer - if root == null: - return - if content == null: - return - while labels.size() < lines.size(): - _append_tile_drawer_label(content, labels) - root.visible = not lines.is_empty() - for i in range(labels.size()): - var lbl: Label = labels[i] as Label - var show_line: bool = i < lines.size() - lbl.visible = show_line - if show_line: - lbl.text = str(lines[i]) - lbl.tooltip_text = str(tooltips[i]) if i < tooltips.size() else "" - else: - lbl.tooltip_text = "" - - -## Clears a scrollable effects section and resets its cached header/toggle state so -## the next inspected tile does not inherit a stale count or expanded body. -func _clear_effects_section(section: Dictionary, labels: Array) -> void: - _set_tile_drawer_lines(section, labels, []) - section["count"] = 0 - var header: Button = section.get("header") as Button - if is_instance_valid(header): - header.button_pressed = false - header.text = _tile_drawer_section_title(str(section.get("title", "Active Effects")), false) - var scroll: ScrollContainer = section.get("scroll") as ScrollContainer - if is_instance_valid(scroll): - scroll.visible = false - scroll.scroll_vertical = 0 - - -func _find_unit_owner_account_id(unit_id: String) -> String: - if unit_id.is_empty(): - return "" - for player: Dictionary in Game.state.get("players", []): - for unit: Dictionary in player.get("field", []): - if str(unit.get("instanceId", "")) == unit_id: - return str(player.get("accountId", "")) - var arch: Dictionary = player.get("archSpirit", {}) - if str(arch.get("instanceId", "")) == unit_id: - return str(player.get("accountId", "")) - return "" - - -func _build_unit_detail_lines(unit: Dictionary, owner_id: String, - include_tier: bool = false) -> Dictionary: - var lines: Array = [ - "Name: %s" % str(unit.get("name", "?")), - "Owner: %s" % Game.get_display_name(owner_id), - ] - var tooltips: Array = ["", ""] - if include_tier: - lines.append("Tier: %d" % int(unit.get("tier", 0))) - tooltips.append("") - lines.append("HP: %d / %d" % [int(unit.get("currentHealth", 0)), int(unit.get("maxHealth", 0))]) - lines.append("DEF: %d / %d" % [int(unit.get("currentDefense", 0)), int(unit.get("maxDefense", 0))]) - lines.append("ATK: %d" % int(unit.get("damage", 0))) - lines.append("MP: %d / %d" % [int(unit.get("currentMp", 0)), int(unit.get("maxMp", 0))]) - lines.append("Can Move: %s" % ("Yes" if bool(unit.get("canMove", false)) else "No")) - lines.append("Can Attack: %s" % ("Yes" if bool(unit.get("canAttack", false)) else "No")) - tooltips.append_array(["", "", "", "", "", ""]) - - var raw_abilities: Variant = unit.get("abilitiesJson") - var parsed_abilities: Variant = JSON.parse_string("[]" if raw_abilities == null else str(raw_abilities)) - if parsed_abilities is Array: - for ability_index: int in range((parsed_abilities as Array).size()): - var ability: Dictionary = (parsed_abilities as Array)[ability_index] as Dictionary - var ability_name: String = str(ability.get("name", ability.get("Name", "Ability %d" % ability_index))) - var ability_desc: String = str(ability.get("description", ability.get("Description", ""))) - lines.append("Ability: %s" % ability_name) - tooltips.append(ability_desc) - - return { - "lines": lines, - "tooltips": tooltips, - } - - -## Appends any active effects targeting [param target_ref] (unit instanceId or ruinId) -## into the provided [param lines] and [param tooltips] arrays. -func _append_active_effect_lines(target_ref: String, lines: Array, tooltips: Array) -> void: - if target_ref.is_empty(): - return - var all_effects: Variant = Game.state.get("activeEffects") - if not all_effects is Array: - return - for ae: Dictionary in (all_effects as Array): - if str(ae.get("targetRef", "")) != target_ref: - continue - var label: String = str(ae.get("label", "?")) - var source_name: String = str(ae.get("sourceName", "")) - var dur_type: String = str(ae.get("durationType", "")) - var turns: int = int(ae.get("turnsRemaining", 0)) - var dur_text: String - match dur_type: - "ForNTurns": dur_text = "%d turn%s" % [turns, "s" if turns != 1 else ""] - "UntilEndOfTurn": dur_text = "until end of turn" - "UntilStartOfOwnerTurn": dur_text = "until owner's next turn" - "UntilStartOfSourceOwnerTurn": dur_text = "until source's next turn" - "WhileSourceOnBattlefield": dur_text = "while source lives" - "WhileCondition": dur_text = "conditional" - _: dur_text = dur_type.to_lower().replace("_", " ") - var line: String - if source_name.is_empty() or source_name == ae.get("sourceInstanceId", ""): - line = "[Effect] %s (%s)" % [label, dur_text] - else: - line = "[Effect] %s (%s, from %s)" % [label, dur_text, source_name] - lines.append(line) - tooltips.append("") - - -func _set_tile_drawer_content(tile: Dictionary) -> void: - _tile_drawer_last_tile = tile.duplicate(true) - _set_tile_drawer_button_state() - if tile.is_empty(): - _set_tile_drawer_lines(_tile_drawer_tile_section, _tile_drawer_tile_labels, []) - _set_tile_drawer_lines(_tile_drawer_spirit_section, _tile_drawer_spirit_labels, []) - _set_tile_drawer_lines(_tile_drawer_token_section, _tile_drawer_token_labels, []) - _set_tile_drawer_lines(_tile_drawer_arch_section, _tile_drawer_arch_labels, []) - _set_tile_drawer_lines(_tile_drawer_ruin_section, _tile_drawer_ruin_labels, []) - _clear_effects_section(_tile_drawer_spirit_effects_section, _tile_drawer_spirit_effects_labels) - _clear_effects_section(_tile_drawer_token_effects_section, _tile_drawer_token_effects_labels) - _clear_effects_section(_tile_drawer_arch_effects_section, _tile_drawer_arch_effects_labels) - _clear_effects_section(_tile_drawer_ruin_effects_section, _tile_drawer_ruin_effects_labels) - 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_value: Variant = tile.get("ruinId", "") - var ruin_id : String = "" if ruin_id_value == null else str(ruin_id_value) - var ruin_owner_id : String = str(tile.get("ruinOwner", "")) - var occ_id : String = str(tile.get("occupantId", "")) - var occ_owner_id : String = str(tile.get("occupantOwner", "")) - var occ_unit: Dictionary = Game.get_unit_by_id(occ_id) - var occ_type : String = str(occ_unit.get("cardType", "")) - var occ_name : String = str(occ_unit.get("name", occ_id)) - - var tile_lines : Array = [ - "Coord: (%d, %d)" % [cx, cy], - "Affinity: %s" % aff, - "Base1: %s" % b1, - "Base2: %s" % b2, - "Occupant: %s" % ("None" if occ_id.is_empty() or occ_id == "null" else "%s (%s)" % [occ_name, occ_type]), - ] - _set_tile_drawer_lines(_tile_drawer_tile_section, _tile_drawer_tile_labels, tile_lines) - - if not occ_id.is_empty() and occ_id != "null" and occ_type == "Spirit": - var spirit_owner_id: String = occ_owner_id if not occ_owner_id.is_empty() else _find_unit_owner_account_id(occ_id) - var spirit_detail: Dictionary = _build_unit_detail_lines(occ_unit, spirit_owner_id) - _set_tile_drawer_lines( - _tile_drawer_spirit_section, _tile_drawer_spirit_labels, - spirit_detail.get("lines", []), spirit_detail.get("tooltips", [])) - _set_effects_section(occ_id, _tile_drawer_spirit_effects_section, _tile_drawer_spirit_effects_labels) - else: - _set_tile_drawer_lines(_tile_drawer_spirit_section, _tile_drawer_spirit_labels, []) - _clear_effects_section(_tile_drawer_spirit_effects_section, _tile_drawer_spirit_effects_labels) - - if not occ_id.is_empty() and occ_id != "null" and occ_type == "SpiritToken": - var token_owner_id: String = occ_owner_id if not occ_owner_id.is_empty() else _find_unit_owner_account_id(occ_id) - var token_detail: Dictionary = _build_unit_detail_lines(occ_unit, token_owner_id) - _set_tile_drawer_lines( - _tile_drawer_token_section, _tile_drawer_token_labels, - token_detail.get("lines", []), token_detail.get("tooltips", [])) - _set_effects_section(occ_id, _tile_drawer_token_effects_section, _tile_drawer_token_effects_labels) - else: - _set_tile_drawer_lines(_tile_drawer_token_section, _tile_drawer_token_labels, []) - _clear_effects_section(_tile_drawer_token_effects_section, _tile_drawer_token_effects_labels) - - if not occ_id.is_empty() and occ_id != "null" and occ_type == "ArchSpirit": - var arch_owner_id: String = occ_owner_id if not occ_owner_id.is_empty() else _find_unit_owner_account_id(occ_id) - var arch_detail: Dictionary = _build_unit_detail_lines(occ_unit, arch_owner_id, true) - _set_tile_drawer_lines( - _tile_drawer_arch_section, _tile_drawer_arch_labels, - arch_detail.get("lines", []), arch_detail.get("tooltips", [])) - _set_effects_section(occ_id, _tile_drawer_arch_effects_section, _tile_drawer_arch_effects_labels) - else: - _set_tile_drawer_lines(_tile_drawer_arch_section, _tile_drawer_arch_labels, []) - _clear_effects_section(_tile_drawer_arch_effects_section, _tile_drawer_arch_effects_labels) - - if ruin_id_value != null and not ruin_id.is_empty() and ruin_id != "null": - var ruin_lines : Array = ["Ruin: %s" % ruin_id, "Owner: %s" % Game.get_display_name(ruin_owner_id)] - var ruin_tooltips: Array = ["", ""] - _set_tile_drawer_lines(_tile_drawer_ruin_section, _tile_drawer_ruin_labels, ruin_lines, ruin_tooltips) - _set_effects_section(ruin_id, _tile_drawer_ruin_effects_section, _tile_drawer_ruin_effects_labels) - else: - _set_tile_drawer_lines(_tile_drawer_ruin_section, _tile_drawer_ruin_labels, []) - _clear_effects_section(_tile_drawer_ruin_effects_section, _tile_drawer_ruin_effects_labels) - - -## Populates [param section] (a scrollable effects section) with effects targeting -## [param target_ref], then updates the header count badge. -func _set_effects_section(target_ref: String, section: Dictionary, labels: Array) -> void: - var effect_lines : Array = [] - var effect_tooltips : Array = [] - _append_active_effect_lines(target_ref, effect_lines, effect_tooltips) - _set_tile_drawer_lines(section, labels, effect_lines, effect_tooltips) - _update_effects_section_header(section, effect_lines.size()) - - -func _set_tile_drawer_button_state() -> void: - if not is_instance_valid(_tile_drawer_toggle_btn): - return - var has_tile: bool = not _tile_drawer_last_tile.is_empty() - _tile_drawer_toggle_btn.disabled = not has_tile - _tile_drawer_toggle_btn.text = ">" if _tile_drawer_open else "<" - _layout_tile_drawer_toggle_button() - - -func _layout_tile_drawer_toggle_button() -> void: - if not is_instance_valid(_tile_drawer_toggle_btn): - return - if _tile_drawer_open: - _tile_drawer_toggle_btn.offset_left = -_TILE_DRAWER_WIDTH - _TILE_DRAWER_TOGGLE_WIDTH - _tile_drawer_toggle_btn.offset_right = -_TILE_DRAWER_WIDTH - else: - _tile_drawer_toggle_btn.offset_left = -(_TILE_DRAWER_TOGGLE_WIDTH + _TILE_DRAWER_TOGGLE_MARGIN) - _tile_drawer_toggle_btn.offset_right = -_TILE_DRAWER_TOGGLE_MARGIN - _tile_drawer_toggle_btn.offset_top = -24.0 - _tile_drawer_toggle_btn.offset_bottom = 24.0 - - -func _on_tile_drawer_toggle_pressed() -> void: - if _tile_drawer_open: - _close_tile_drawer() - return - if _tile_drawer_last_tile.is_empty(): - return - _open_tile_drawer(_tile_drawer_last_tile) - - -func _open_tile_drawer(tile: Dictionary) -> void: - if not is_instance_valid(_tile_drawer): return - _set_tile_drawer_content(tile) - - if _tile_drawer_open: - _set_tile_drawer_button_state() - return # already open, content updated above - _tile_drawer_open = true - _tile_drawer.visible = true - _set_tile_drawer_button_state() - 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.parallel().tween_property(_tile_drawer, "offset_left", -_TILE_DRAWER_WIDTH, 0.3) - _tile_drawer_tween.parallel().tween_property( - _tile_drawer_toggle_btn, "offset_left", - -_TILE_DRAWER_WIDTH - _TILE_DRAWER_TOGGLE_WIDTH, 0.3) - _tile_drawer_tween.parallel().tween_property( - _tile_drawer_toggle_btn, "offset_right", - -_TILE_DRAWER_WIDTH, 0.3) - - -func _close_tile_drawer() -> void: - if not is_instance_valid(_tile_drawer) or not _tile_drawer_open: return - _tile_drawer_open = false - _set_tile_drawer_button_state() - 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.parallel().tween_property(_tile_drawer, "offset_left", 0.0, 0.25) - _tile_drawer_tween.parallel().tween_property( - _tile_drawer_toggle_btn, "offset_left", - -(_TILE_DRAWER_TOGGLE_WIDTH + _TILE_DRAWER_TOGGLE_MARGIN), 0.25) - _tile_drawer_tween.parallel().tween_property( - _tile_drawer_toggle_btn, "offset_right", - -_TILE_DRAWER_TOGGLE_MARGIN, 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) - var cf := Engine.get_process_frames() - if cf == _last_board_click_frame and coord == _last_board_click_coord: - return - _last_board_click_frame = cf - _last_board_click_coord = coord - - if _mode == Mode.ABILITY_TARGET_FORCED: - # Occupied tile with no direct unit-mesh hit -> redirect to the occupant. - if unit_id.is_empty() and coord.x >= 0: - var _target_tile := Game.get_tile(coord.x, coord.y) - var _target_raw_occ = _target_tile.get("occupantId") - var _target_occ : Variant = _target_raw_occ if _target_raw_occ is String else "" - if not _target_occ.is_empty() and _target_occ != "null" and not _is_ruin_instance(str(_target_occ)): - unit_id = _target_occ - - # Server-driven tile pick -> send directly and exit. - if _is_tile_pick and coord.x >= 0: - _is_tile_pick = false - var rid := _pending_req_id - _pending_req_id = "" - _set_mode(Mode.NONE) - _clear_highlights() - Game.send_tile_pick_response(rid, coord.x, coord.y) - return - - # 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: - _ability_cur_action_idx += 1 - _advance_ability_targeting() - return - - 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 : Variant = _raw_occ if _raw_occ is String else "" - if not _occ.is_empty() and _occ != "null" and not _is_ruin_instance(str(_occ)): - unit_id = _occ - # Show tile detail drawer and optionally pan camera. - if coord.x >= 0: - _set_tile_drawer_content(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 _board_distance(coord.x, coord.y, last.x, last.y) != 1: - return # must be adjacent - print("Handle Board Click: terra targets: ", _terra_targets) - _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() - var terra_dirs : Array[Vector2i] - if _board_grid_type == "Hexagon": - terra_dirs = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1), - Vector2i(1,-1), Vector2i(-1,1)] - else: - terra_dirs = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)] - for d: Vector2i in terra_dirs: - 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 not _tile_bodies.has("%d,%d" % [nx, ny]): continue - _add_highlight(nx, ny, "movement") - - Mode.UNIT_SELECTED: - if coord.x >= 0: - _set_tile_drawer_content(Game.get_tile(coord.x, coord.y)) - # 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 : Variant = _raw_occ2 if _raw_occ2 is String else "" - if not _occ2.is_empty() and _occ2 != "null" and not _is_ruin_instance(str(_occ2)): - unit_id = _occ2 - if not unit_id.is_empty(): - if _is_enemy_unit(unit_id): - _last_attack_source_iid = _sel_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_FORCED: - return - - Mode.ABILITY_TARGET: - # Server-driven tile pick — send directly and exit. - if _is_tile_pick and coord.x >= 0: - _is_tile_pick = false - var rid := _pending_req_id - _pending_req_id = "" - _set_mode(Mode.NONE) - _clear_highlights() - Game.send_tile_pick_response(rid, coord.x, coord.y) - return - - # 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: - # Server-driven prompt targeting must never collapse into normal unit selection. - if _mode == Mode.ABILITY_TARGET_FORCED: - return - - var unit := Game.get_unit_by_id(unit_id) - if unit.is_empty(): return - if _is_ruin_unit(unit): 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 (abilities + ArchSpirit actions in one panel). - _show_ability_panel(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 and new_mode != Mode.UNIT_SELECTED: - _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()) - - -## 6-B: Preflight check — at least one valid no-ruin tile must exist. -## If valid, shows the Channel Ruin confirmation dialog (6-A). -func _channel_ruin(card: Dictionary) -> void: - var card_affinity : String = card.get("affinity", "") - var board : Dictionary = Game.get_board() - var has_valid : bool = false - for tile: Dictionary in board.get("tiles", []): - var ruin_id_v : Variant = tile.get("ruinId", null) - var ruin_id : String = "" if ruin_id_v == null else str(ruin_id_v) - if not ruin_id.is_empty() and ruin_id != "null": - continue # tile already holds a Ruin - if card_affinity != "" and not _tile_matches_channel_affinity(tile, card_affinity): - continue # wrong affinity - has_valid = true - break - - if not has_valid: - var dlg := AcceptDialog.new() - dlg.title = "Cannot Channel Ruin" - dlg.dialog_text = "No valid tile available for this Ruin." - dlg.min_size = Vector2(280, 90) - add_child(dlg) - dlg.popup_centered() - dlg.confirmed.connect(func() -> void: dlg.queue_free()) - return - - _confirm_channel_ruin(card) - - -## 6-A: Confirmation dialog before channeling a Ruin. -func _confirm_channel_ruin(card: Dictionary) -> void: - var dlg := ConfirmationDialog.new() - dlg.title = "Channel Ruin" - dlg.dialog_text = "Ruin placement is random.\nContinue?" - dlg.ok_button_text = "Channel" - dlg.min_size = Vector2(280, 90) - add_child(dlg) - dlg.popup_centered() - dlg.confirmed.connect(func() -> void: - Game.send_play_card(card.get("instanceId", ""), 0, 0) - 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 - - -## Returns the flat action list to use for client-side target collection. -## Prefers the modern ActionGroup format (flattens AND groups recursively) over -## the legacy flat "actions" array. OR/XOR groups return only their leaf actions — -## the server handles the interactive pick via action_group_pick_request. -func _get_ability_actions(ab: Dictionary) -> Array: - var legacy : Array = ab.get("actions", []) - if not legacy.is_empty(): - return legacy - var ag : Variant = ab.get("actiongroup") - if ag is Dictionary: - return _flatten_and_group(ag as Dictionary) - return [] - -func _flatten_and_group(ag: Dictionary) -> Array: - var logic : String = str(ag.get("logicop", "and")).to_lower() - var result : Array = [] - result.append_array(ag.get("actions", [])) - if logic == "and": - for g: Variant in ag.get("groups", []): - if g is Dictionary: - result.append_array(_flatten_and_group(g as Dictionary)) - return result - - -## 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() - - # ── Collect Active abilities ─────────────────────────────────────────────── - var actives : Array = [] - var _raw_abil_ap = unit.get("abilitiesJson") - var abil_json : String = "" if _raw_abil_ap == null else str(_raw_abil_ap) - if not abil_json.is_empty(): - var parsed = JSON.parse_string(abil_json) - if parsed is Array: - var abilities : Array = _normalize_keys(parsed) as 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 }) - - # ── Collect ArchSpirit actions (Sacrifice / Ascend / Transition) ─────────── - var arch_actions : Array = [] - if unit.get("cardType", "") == "ArchSpirit" and _is_friendly_unit(unit_id): - if not _valid_sacrifice_spirits().is_empty(): - arch_actions.append({ "label": "Sacrifice a Spirit", - "fn": func() -> void: _start_sacrifice_mode() }) - var cur_tier : int = int(unit.get("tier", 1)) - var can_ascend := false - var can_transition := false - 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: - arch_actions.append({ "label": "Ascend", - "fn": func() -> void: _pick_ascend_card() }) - if can_transition: - arch_actions.append({ "label": "Transition", - "fn": func() -> void: _pick_transition_card() }) - - if actives.is_empty() and arch_actions.is_empty(): - return - - # ── Build panel ──────────────────────────────────────────────────────────── - var panel := PanelContainer.new() - var vbox := VBoxContainer.new() - vbox.add_theme_constant_override("separation", 4) - vbox.custom_minimum_size = Vector2(160, 0) - - if not actives.is_empty(): - 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 = _get_ability_actions(ab_def) - _ability_range = ab_def.get("range", {}) - _ability_targets = [] - _ability_cur_action_idx = 0 - _start_ability_targeting()) - vbox.add_child(btn) - - if not arch_actions.is_empty(): - if not actives.is_empty(): - vbox.add_child(HSeparator.new()) - var arch_title := Label.new() - arch_title.text = "ArchSpirit" - arch_title.add_theme_font_size_override("font_size", 12) - arch_title.add_theme_color_override("font_color", Color(1.0, 0.75, 0.3)) - vbox.add_child(arch_title) - vbox.add_child(HSeparator.new()) - for aa: Dictionary in arch_actions: - var btn := Button.new() - btn.text = aa.get("label", "") - btn.add_theme_font_size_override("font_size", 12) - var fn : Callable = aa.get("fn", Callable()) - btn.pressed.connect(func() -> void: fn.call()) - 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 - -func _current_target_mode() -> Mode: - return Mode.ABILITY_TARGET_FORCED if (_is_triggered_target or _is_target_pick or _is_tile_pick) else Mode.ABILITY_TARGET - - -## 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. - var choose_one : Variant = action.get("chooseone") - if choose_one is Dictionary and not (choose_one as Dictionary).get("branches", []).is_empty(): - _set_mode(_current_target_mode()) - _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(_current_target_mode()) - _clear_highlights() - _show_player_panel(scope, ownership) - return - - # Board selection — enter ABILITY_TARGET mode with blue tile highlights. - _set_mode(_current_target_mode()) - _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_v : Variant = target_sel.get("filters", []) - var filters : Array = filters_v as Array if filters_v is Array else [] - - 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 := _board_distance( - int(pos.get("x", 0)), int(pos.get("y", 0)), - int(src_pos_ab.get("x", 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 := _board_distance( - int(tgt_pos.get("x", 0)), int(tgt_pos.get("y", 0)), - int(src_pos.get("x", 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 := _board_distance( - int(tgt_pos.get("x", 0)), int(tgt_pos.get("y", 0)), - int(src_pos.get("x", 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 := _board_distance(tx, ty, int(src_pos.get("x", 0)), 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 - if _board_grid_type == "Hexagon": - var N : int = _board_hex_sides - var aq : int = sx - (N - 1); var ar : int = sy - (N - 1) - var bq : int = tx - (N - 1); var br : int = ty - (N - 1) - var as_ : int = -aq - ar; var bs : int = -bq - br - var n : int = _board_distance(sx, sy, tx, ty) - if n == 0: return true - for i in range(1, n): - var t : float = float(i) / float(n) - var fq : float = aq + (bq - aq) * t - var fr : float = ar + (br - ar) * t - var fs : float = as_ + (bs - as_) * t - var rq : int = roundi(fq) - var rr : int = roundi(fr) - var rs : int = roundi(fs) - if rq + rr + rs != 0: - var eq : float = abs(rq - fq) - var er : float = abs(rr - fr) - var es : float = abs(rs - fs) - if eq >= er and eq >= es: rq = -rr - rs - elif er >= es: rr = -rq - rs - else: rs = -rq - rr - var cx : int = rq + (N - 1) - var cy : int = rr + (N - 1) - var tile := Game.get_tile(cx, cy) - if not tile.is_empty() and str(tile.get("occupantId", "")) != "": - return false - return true - # Square: supercover DDA - 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 _is_target_pick: - _is_target_pick = false - var rid := _pending_req_id - _pending_req_id = "" - Game.send_target_pick_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" and range_json != "": - 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() - - -## ── Server-driven ability-pause prompt handlers ───────────────────────────── - -func _hide_pending_prompt_panel() -> void: - if is_instance_valid(_pending_prompt_panel): - _pending_prompt_panel.queue_free() - _pending_prompt_panel = null - - -## PendingCostPick — player selects N cards/units to satisfy an interactive cost. -func _on_cost_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - _cost_pick_selected.clear() - _cost_pick_amount = int(req.get("amount", 1)) - var cost_type : String = str(req.get("costType", "")) - var pick_mode : String = str(req.get("pickMode", "SelfPick")) - - _hide_pending_prompt_panel() - var panel := PanelContainer.new() - panel.position = Vector2(8, 160) - var vbox := VBoxContainer.new() - vbox.add_theme_constant_override("separation", 6) - vbox.custom_minimum_size = Vector2(200, 0) - - var title := Label.new() - title.text = "Cost: %s (select %d)" % [cost_type, _cost_pick_amount] - title.add_theme_font_size_override("font_size", 13) - title.add_theme_color_override("font_color", Color(1.0, 0.75, 0.2)) - vbox.add_child(title) - vbox.add_child(HSeparator.new()) - - # Use server-supplied candidate list (covers hand, field, and opponent-pick cases). - var candidates_raw = JSON.parse_string(str(req.get("candidatesJson", "[]"))) - var candidates : Array = candidates_raw as Array if candidates_raw is Array else [] - if candidates.is_empty(): - var lbl := Label.new(); lbl.text = "(no candidates)" - lbl.add_theme_font_size_override("font_size", 11) - vbox.add_child(lbl) - else: - for cand in candidates: - var card_d : Dictionary = cand as Dictionary - var iid : String = str(card_d.get("instanceId", "")) - var name_ : String = str(card_d.get("name", iid)) - var btn := Button.new() - btn.text = name_ - btn.add_theme_font_size_override("font_size", 11) - var cap_iid : String = iid - btn.pressed.connect(func() -> void: - if not cap_iid in _cost_pick_selected: - _cost_pick_selected.append(cap_iid) - btn.modulate = Color(0.4, 1.0, 0.4) - if _cost_pick_selected.size() >= _cost_pick_amount: - _finish_cost_pick()) - vbox.add_child(btn) - - # Confirm button for pick_mode variants that allow fewer than max. - if pick_mode == "SelfPick": - var confirm := Button.new() - confirm.text = "Confirm" - confirm.add_theme_font_size_override("font_size", 12) - confirm.pressed.connect(_finish_cost_pick) - vbox.add_child(confirm) - - panel.add_child(vbox) - _hud.add_child(panel) - _pending_prompt_panel = panel - - -func _finish_cost_pick() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id - _pending_req_id = "" - Game.send_cost_pick_response(rid, _cost_pick_selected) - _cost_pick_selected.clear() - - -## PendingCostGroupPick — chooser picks which OR/XOR cost option to pay. -func _on_cost_group_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - - var group_raw = JSON.parse_string(str(req.get("costGroupJson", "{}"))) - var group : Dictionary = _normalize_keys(group_raw) as Dictionary if group_raw is Dictionary else {} - var entries : Array = group.get("entries", []) as Array - var groups : Array = group.get("groups", []) as Array - var logic : String = str(group.get("logicop", group.get("logicOp", "OR"))) - - _hide_pending_prompt_panel() - var panel := PanelContainer.new() - panel.position = Vector2(8, 160) - var vbox := VBoxContainer.new() - vbox.add_theme_constant_override("separation", 8) - vbox.custom_minimum_size = Vector2(200, 0) - - var title := Label.new() - title.text = "Choose Cost (%s):" % logic - title.add_theme_font_size_override("font_size", 13) - title.add_theme_color_override("font_color", Color(1.0, 0.75, 0.2)) - vbox.add_child(title) - vbox.add_child(HSeparator.new()) - - var option_idx := 0 - for entry in entries: - var entry_d : Dictionary = entry as Dictionary - var label : String = str(entry_d.get("typestr", entry_d.get("typeStr", "Option %d" % (option_idx + 1)))) - var btn := Button.new(); btn.text = label - btn.add_theme_font_size_override("font_size", 12) - var cap_idx : int = option_idx - btn.pressed.connect(func() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id; _pending_req_id = "" - Game.send_cost_group_pick_response(rid, cap_idx)) - vbox.add_child(btn) - option_idx += 1 - for grp in groups: - var grp_d : Dictionary = grp as Dictionary - var lop : String = str(grp_d.get("logicop", grp_d.get("logicOp", "OR"))) - var btn := Button.new(); btn.text = "Group (%s)" % lop - btn.add_theme_font_size_override("font_size", 12) - var cap_idx : int = option_idx - btn.pressed.connect(func() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id; _pending_req_id = "" - Game.send_cost_group_pick_response(rid, cap_idx)) - vbox.add_child(btn) - option_idx += 1 - - panel.add_child(vbox) - _hud.add_child(panel) - _pending_prompt_panel = panel - - -## PendingActionGroupPick — chooser picks which OR/XOR action branch to execute. -func _on_action_group_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - - var group_raw = JSON.parse_string(str(req.get("actionGroupJson", "{}"))) - var group : Dictionary = _normalize_keys(group_raw) as Dictionary if group_raw is Dictionary else {} - var actions : Array = group.get("actions", []) as Array - var subgrps : Array = group.get("groups", []) as Array - var logic : String = str(group.get("logicop", group.get("logicOp", "OR"))) - - _hide_pending_prompt_panel() - var panel := PanelContainer.new() - panel.position = Vector2(8, 160) - var vbox := VBoxContainer.new() - vbox.add_theme_constant_override("separation", 8) - vbox.custom_minimum_size = Vector2(200, 0) - - var title := Label.new() - title.text = "Choose Action (%s):" % logic - title.add_theme_font_size_override("font_size", 13) - title.add_theme_color_override("font_color", Color(0.4, 0.8, 1.0)) - vbox.add_child(title) - vbox.add_child(HSeparator.new()) - - var option_idx := 0 - for act in actions: - var act_d : Dictionary = act as Dictionary - var label : String = str(act_d.get("label", "Action %d" % (option_idx + 1))) - if label.is_empty(): - var tgt : Dictionary = act_d.get("target", {}) as Dictionary - label = "%s %s" % [tgt.get("ownership", ""), tgt.get("targetType", "")] - label = label.strip_edges() - if label.is_empty(): label = "Action %d" % (option_idx + 1) - var btn := Button.new(); btn.text = label - btn.add_theme_font_size_override("font_size", 12) - var cap_idx : int = option_idx - btn.pressed.connect(func() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id; _pending_req_id = "" - Game.send_action_group_pick_response(rid, cap_idx)) - vbox.add_child(btn) - option_idx += 1 - for grp in subgrps: - var grp_d : Dictionary = grp as Dictionary - var lop : String = str(grp_d.get("logicop", grp_d.get("logicOp", "OR"))) - var btn := Button.new(); btn.text = "Group (%s)" % lop - btn.add_theme_font_size_override("font_size", 12) - var cap_idx : int = option_idx - btn.pressed.connect(func() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id; _pending_req_id = "" - Game.send_action_group_pick_response(rid, cap_idx)) - vbox.add_child(btn) - option_idx += 1 - - panel.add_child(vbox) - _hud.add_child(panel) - _pending_prompt_panel = panel - - -## PendingBranchPick — server-driven ChooseOne for Opponent/Ally chooser. -func _on_branch_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - - var branches_raw = JSON.parse_string(str(req.get("branchesJson", "[]"))) - var branches : Array = _normalize_keys(branches_raw) as Array if branches_raw is Array else [] - - _hide_pending_prompt_panel() - 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 : String = str(branch.get("label", "Option %d" % (i + 1))) - var btn := Button.new(); btn.text = label - btn.add_theme_font_size_override("font_size", 12) - var cap_idx : int = i - btn.pressed.connect(func() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id; _pending_req_id = "" - Game.send_branch_pick_response(rid, cap_idx)) - vbox.add_child(btn) - - panel.add_child(vbox) - _hud.add_child(panel) - _pending_prompt_panel = panel - - -## PendingTargetPick — opponent/ally must select targets for a paused action. -## Reuses the existing ABILITY_TARGET board mode; _is_target_pick flag routes the send. -func _on_target_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _is_target_pick = true - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - _ability_unit_id = _pending_source_id - _ability_idx = -1 - _ability_card_id = "" - _ability_target_conditions = [] - - 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 - _start_ability_targeting() - - -## PendingTilePick — player selects a tile satisfying given constraints. -func _on_tile_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _is_tile_pick = true - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - _tile_pick_max_range = int(req.get("maxRange", 0)) - _tile_pick_require_empty = bool(req.get("requireEmpty", false)) - _tile_pick_require_occupied = bool(req.get("requireOccupied", false)) - _ability_unit_id = _pending_source_id - - # Highlight valid tiles. - _set_mode(Mode.ABILITY_TARGET_FORCED) - _clear_highlights() - var bw := Game.board_width(); var bh := Game.board_height() - var src_pos : Dictionary = {} - if not _pending_source_id.is_empty(): - var src_unit := Game.get_unit_by_id(_pending_source_id) - if src_unit is Dictionary: src_pos = src_unit.get("position", {}) as Dictionary - var occupant_ownership : String = str(req.get("occupantOwnership", "Any")) - for tx in range(bw): - for ty in range(bh): - if _tile_pick_max_range > 0 and not src_pos.is_empty(): - var dist := _board_distance(tx, ty, int(src_pos.get("x", 0)), int(src_pos.get("y", 0))) - if dist > _tile_pick_max_range: continue - var tile := Game.get_tile(tx, ty) - if tile.is_empty(): continue - var occ_id : String = str(tile.get("occupantId", "")) - if _tile_pick_require_empty and not occ_id.is_empty(): continue - if _tile_pick_require_occupied and occ_id.is_empty(): continue - if _tile_pick_require_occupied and not occ_id.is_empty() and occupant_ownership != "Any": - var occ_owner : String = str(tile.get("occupantOwner", "")) - var my_id : String = Auth.user_id - if occupant_ownership == "Self" and occ_owner != my_id: continue - if occupant_ownership == "Enemy" and occ_owner == my_id: continue - _add_highlight(tx, ty, "ability") - - -## PendingPlayerPick — chooser selects a player from a specific valid-player list. -func _on_player_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - - var valid_ids_raw = req.get("validPlayerIds") - var valid_ids : Array = valid_ids_raw as Array if valid_ids_raw is Array else [] - - _hide_pending_prompt_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()) - - for pid_raw in valid_ids: - var pid : String = str(pid_raw) - var pname : String = Game.get_display_name(pid) - if pname.is_empty(): pname = pid.substr(0, 8) - var btn := Button.new(); btn.text = pname - btn.add_theme_font_size_override("font_size", 12) - var cap_pid : String = pid - btn.pressed.connect(func() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id; _pending_req_id = "" - Game.send_player_pick_response(rid, cap_pid)) - vbox.add_child(btn) - - panel.add_child(vbox) - _hud.add_child(panel) - _pending_prompt_panel = panel - - -## PendingRevealChoicePick — chooser orders revealed cards (e.g. StackDeck). -func _on_reveal_choice_pick_request(req: Dictionary) -> void: - if _mode != Mode.NONE: - _set_mode(Mode.NONE) - _pending_req_id = str(req.get("requestId", "")) - _pending_source_id = str(req.get("sourceInstanceId", "")) - _reveal_required_count = int(req.get("count", 1)) - _reveal_ordered_indices.clear() - - var cards_raw = JSON.parse_string(str(req.get("revealedCardsJson", "[]"))) - var cards : Array = _normalize_keys(cards_raw) as Array if cards_raw is Array else [] - _reveal_total_cards = cards.size() - - _hide_pending_prompt_panel() - var panel := PanelContainer.new() - panel.position = Vector2(8, 100) - var vbox := VBoxContainer.new() - vbox.add_theme_constant_override("separation", 6) - vbox.custom_minimum_size = Vector2(210, 0) - - var title := Label.new() - title.text = "Order top %d card(s):" % _reveal_required_count - title.add_theme_font_size_override("font_size", 13) - title.add_theme_color_override("font_color", Color(0.6, 1.0, 0.8)) - vbox.add_child(title) - vbox.add_child(HSeparator.new()) - - # Each card becomes a button; clicking adds its 0-based index to the ordering. - for i in cards.size(): - var card_d : Dictionary = cards[i] as Dictionary - var name_ : String = str(card_d.get("name", "Card %d" % (i + 1))) - var btn := Button.new(); btn.text = "%d. %s" % [i + 1, name_] - btn.add_theme_font_size_override("font_size", 11) - var cap_i : int = i - var cap_btn : Button = btn - btn.pressed.connect(func() -> void: - if cap_i in _reveal_ordered_indices: return - _reveal_ordered_indices.append(cap_i) - cap_btn.modulate = Color(0.4, 1.0, 0.5) - cap_btn.text = "#%d %s" % [_reveal_ordered_indices.size(), name_] - if _reveal_ordered_indices.size() >= _reveal_required_count: - _finish_reveal_pick()) - vbox.add_child(btn) - - # Confirm button for edge cases. - var confirm := Button.new() - confirm.text = "Confirm Order" - confirm.add_theme_font_size_override("font_size", 12) - confirm.pressed.connect(_finish_reveal_pick) - vbox.add_child(HSeparator.new()) - vbox.add_child(confirm) - - panel.add_child(vbox) - _hud.add_child(panel) - _pending_prompt_panel = panel - - -func _finish_reveal_pick() -> void: - _hide_pending_prompt_panel() - var rid := _pending_req_id; _pending_req_id = "" - Game.send_reveal_choice_pick_response(rid, _reveal_ordered_indices) - _reveal_ordered_indices.clear() - - -## 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 - - var card := _find_hand_card(iid) - #print(card.get("name", "name failed")) - if card.is_empty(): return - if not Game.is_my_turn() and card.get("cardType", "") != "Instinct": - 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 — preflight check then confirm before channeling. - if card.get("cardType", "") == "Ruin": - _channel_ruin(card) - 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 = _get_ability_actions(ab) - _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: - # Build new IID list. - var new_iids : Array[String] = [] - for card: Dictionary in hand: - var raw_iid : Variant = card.get("instanceId") - new_iids.append(str(raw_iid) if raw_iid != null else "") - if new_iids == _cached_hand_iids: - _refresh_hand_selection() - return - - _cached_hand_iids = new_iids - - # Spectators have no playable hand — just clear any stale widgets and stop. - if _is_spectating: - _apply_display_hand([]) - return - - # Detect brand-new cards (not in previous server hand, not already queued). - var pending_iids : Array[String] = [] - for c: Dictionary in _pending_popup_cards: - pending_iids.append(c.get("instanceId", "") as String) - - var brand_new : Array[Dictionary] = [] - if Settings.draw_card_popup: - for card: Dictionary in hand: - var iid : String = card.get("instanceId", "") - if iid not in _cached_hand_iids and iid not in pending_iids: - brand_new.append(card) - - # Drop pending popups for cards that left the hand (avoid typed-array filter). - var kept : Array[Dictionary] = [] - for c: Dictionary in _pending_popup_cards: - if c.get("instanceId", "") in new_iids: - kept.append(c) - _pending_popup_cards = kept - - # Queue brand-new cards for popup; exclude them from the live hand display. - for card: Dictionary in brand_new: - _pending_popup_cards.append(card) - - var popup_iids : Array[String] = [] - for c: Dictionary in _pending_popup_cards: - popup_iids.append(c.get("instanceId", "") as String) - - # Build the display hand (everything except cards waiting in popup queue). - var display_hand : Array[Dictionary] = [] - for card: Dictionary in hand: - if card.get("instanceId", "") not in popup_iids: - display_hand.append(card) - - _apply_display_hand(display_hand) - - # Kick off popup for the first pending card if nothing is showing yet. - if not _pending_popup_cards.is_empty() and (_popup_layer == null or not _popup_layer.visible): - _show_next_card_popup() - - -func _apply_display_hand(hand: Array) -> void: - if hand.is_empty(): - for c in _hand_cards.get_children(): - _hand_cards.remove_child(c) - c.queue_free() - _hand_focus_index = 0 - _hand_hover_iid = "" - _sync_hand_spin_buttons() - return - - # Map existing widgets by IID so we can reuse them. - var existing : Dictionary = {} - for child in _hand_cards.get_children(): - if child.has_meta("card_instance_id"): - existing[str(child.get_meta("card_instance_id"))] = child - - var hand_iids : Array[String] = [] - for card: Dictionary in hand: - hand_iids.append(card.get("instanceId", "") as String) - - # Remove widgets for cards no longer in the display hand. - for iid: String in existing.keys(): - if iid not in hand_iids: - var w : Node = existing[iid] - existing.erase(iid) - _hand_cards.remove_child(w) - w.queue_free() - - # Add widgets for new cards, update _fan_slot on all. - var slot := 0 - for card: Dictionary in hand: - var iid : String = card.get("instanceId", "") - if not existing.has(iid): - var widget := _make_hand_card(card) - widget.set_meta("_fan_slot", slot) - _hand_cards.add_child(widget) - else: - (existing[iid] as Control).set_meta("_fan_slot", slot) - slot += 1 - - _hand_focus_index = posmod(_hand_focus_index, hand.size()) - _queue_hand_layout() - _sync_hand_spin_buttons() - - -func _show_next_card_popup() -> void: - if _pending_popup_cards.is_empty(): - return - var card : Dictionary = _pending_popup_cards[0] - - # Create (or reuse) a dedicated CanvasLayer above the HUD. - if _popup_layer == null or not is_instance_valid(_popup_layer): - _popup_layer = CanvasLayer.new() - _popup_layer.layer = 20 - add_child(_popup_layer) - - # Clear any previous content. - for c in _popup_layer.get_children(): - c.queue_free() - _popup_layer.visible = true - - # Dim background — catches clicks that miss the card. - var bg := ColorRect.new() - bg.color = Color(0.0, 0.0, 0.0, 0.65) - bg.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) - bg.mouse_filter = Control.MOUSE_FILTER_STOP - _popup_layer.add_child(bg) - - # Centred column: label + card. - var vbox := VBoxContainer.new() - vbox.set_anchors_preset(Control.PRESET_CENTER) - vbox.grow_horizontal = Control.GROW_DIRECTION_BOTH - vbox.grow_vertical = Control.GROW_DIRECTION_BOTH - vbox.alignment = BoxContainer.ALIGNMENT_CENTER - _popup_layer.add_child(vbox) - vbox.add_theme_constant_override("separation", 16) - - var lbl := Label.new() - lbl.text = "Card Drawn — click to add to hand" - lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER - vbox.add_child(lbl) - lbl.add_theme_font_size_override("font_size", 16) - - var widget : PanelContainer = _CARD_WIDGET_SCENE.instantiate() - widget.custom_minimum_size = Vector2(200, 320) - widget.mouse_filter = Control.MOUSE_FILTER_STOP - var def_id : String = str(card.get("cardDefinitionId", "")) - var def : Dictionary = ContentCache.get_definition(def_id) - if def.is_empty(): - def = card.duplicate() - def["movementPoints"] = card.get("maxMp", def.get("movementPoints", null)) - widget.setup(card, def) - vbox.add_child(widget) - - # Either clicking the card or the background dismisses the popup. - bg.gui_input.connect(func(ev: InputEvent) -> void: - if ev is InputEventMouseButton and (ev as InputEventMouseButton).pressed: - _dismiss_card_popup()) - widget.card_pressed.connect(func(_id: String) -> void: _dismiss_card_popup()) - - -func _dismiss_card_popup() -> void: - if _pending_popup_cards.is_empty(): - return - var card : Dictionary = _pending_popup_cards.pop_front() - - # Hide the overlay. - if is_instance_valid(_popup_layer): - _popup_layer.visible = false - - # Build the updated display hand: currently shown widgets + this newly added card. - var display_iids : Array[String] = [] - for child in _hand_cards.get_children(): - if child.has_meta("card_instance_id"): - display_iids.append(str(child.get_meta("card_instance_id"))) - display_iids.append(card.get("instanceId", "") as String) - - # Reconstruct display hand in server order (from _cached_hand_iids). - var display_hand : Array = [] - for iid: String in _cached_hand_iids: - if iid in display_iids: - # Find the card dict; use the drawn card if it matches. - if iid == card.get("instanceId", ""): - display_hand.append(card) - else: - # Pull from live Game hand for existing cards. - for hc: Dictionary in Game.get_hand(): - if hc.get("instanceId", "") == iid: - display_hand.append(hc) - break - - _apply_display_hand(display_hand) - - # Show next queued popup if any. - if not _pending_popup_cards.is_empty(): - _show_next_card_popup() - - -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.top_level = false - widget.anchor_left = 0.0 - widget.anchor_top = 0.0 - widget.anchor_right = 0.0 - widget.anchor_bottom = 0.0 - widget.position = Vector2.ZERO - widget.size = widget.custom_minimum_size - widget.visible = true - 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. - # Note: _focus_hand_card is intentionally NOT called here — clicking a card - # brings it to front visually (via selection z_index boost) without shifting - # its position in the fan rotation. - widget.card_pressed.connect(func(_def_id: String) -> void: - _on_hand_card_clicked(iid, widget)) - - return widget - - -func _refresh_hand_selection() -> void: - var needs_layout := false - 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 - or (_mode == Mode.ABILITY_TARGET and not _ability_card_id.is_empty())) - and _sel_card_id == iid) - if widget.has_method("set_selected"): - widget.set_selected(sel) - # 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 != bool(widget.get_meta("_sel", false)): - widget.set_meta("_sel", sel) - needs_layout = true - if needs_layout: - _queue_hand_layout() - - -func _tween_hand_card(widget: Control, sel: bool) -> void: - if not is_instance_valid(widget): return - widget.set_meta("_sel", sel) - _queue_hand_layout() - - -func _find_hand_card(iid: String) -> Dictionary: - for card: Dictionary in Game.get_hand(): - if card.get("instanceId", "") == iid: - return card - return {} - - -func _configure_hand_spin_buttons() -> void: - _hand_spin_left.texture_normal = _HAND_ARROW_REGULAR - _hand_spin_left.texture_hover = _HAND_ARROW_HOVER - _hand_spin_left.texture_pressed = _HAND_ARROW_PRESSED - _hand_spin_left.modulate = Color(1, 1, 1, 0.92) - _hand_spin_left.focus_mode = Control.FOCUS_NONE - _hand_spin_left.rotation_degrees = 0.0 - - _hand_spin_right.texture_normal = _HAND_ARROW_REGULAR - _hand_spin_right.texture_hover = _HAND_ARROW_HOVER - _hand_spin_right.texture_pressed = _HAND_ARROW_PRESSED - _hand_spin_right.modulate = Color(1, 1, 1, 0.92) - _hand_spin_right.focus_mode = Control.FOCUS_NONE - _hand_spin_right.rotation_degrees = 0.0 - _layout_hand_spin_buttons() - - -func _layout_hand_spin_buttons() -> void: - _hand_spin_left.anchor_left = 0.0 - _hand_spin_left.anchor_top = 0.5 - _hand_spin_left.anchor_right = 0.0 - _hand_spin_left.anchor_bottom = 0.5 - _hand_spin_left.offset_left = 8.0 - _hand_spin_left.offset_top = -22.0 - _hand_spin_left.offset_right = 52.0 - _hand_spin_left.offset_bottom = 22.0 - _hand_spin_left.custom_minimum_size = Vector2(44, 44) - _hand_spin_left.size = Vector2(44, 44) - - _hand_spin_right.anchor_left = 1.0 - _hand_spin_right.anchor_top = 0.5 - _hand_spin_right.anchor_right = 1.0 - _hand_spin_right.anchor_bottom = 0.5 - _hand_spin_right.offset_left = -52.0 - _hand_spin_right.offset_top = -22.0 - _hand_spin_right.offset_right = -8.0 - _hand_spin_right.offset_bottom = 22.0 - _hand_spin_right.custom_minimum_size = Vector2(44, 44) - _hand_spin_right.size = Vector2(44, 44) - - -func _sync_hand_spin_buttons() -> void: - var enabled := _hand_cards.get_child_count() > 1 - _hand_spin_left.visible = enabled - _hand_spin_right.visible = enabled - _hand_spin_left.disabled = not enabled - _hand_spin_right.disabled = not enabled - - -func _spin_hand(direction: int) -> void: - var card_count := _hand_cards.get_child_count() - if card_count <= 1: - return - 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) - _hand_focus_index = posmod(_hand_focus_index + direction, card_count) - _layout_hand_cards() - - -func _focus_hand_card(iid: String) -> void: - var idx := 0 - for widget in _hand_cards.get_children(): - if str(widget.get_meta("card_instance_id", "")) == iid: - _hand_focus_index = idx - _layout_hand_cards() - return - idx += 1 - - -func _queue_hand_layout() -> void: - if not is_inside_tree(): - return - _layout_hand_cards.call_deferred() - - -func _layout_hand_cards() -> void: - var widgets := _hand_cards.get_children() - var widget_count := widgets.size() - if widget_count == 0: - return - - _hand_focus_index = posmod(_hand_focus_index, widget_count) - _hand_cards.position = Vector2.ZERO - _hand_cards.size = _hand_area.size - var viewport_size := _hand_area.size - if viewport_size.x <= 0.0 or viewport_size.y <= 0.0: - return - - var sample := widgets[0] as Control - sample.size = sample.custom_minimum_size - var sample_size := _hand_card_size(sample) - var side_margin : float = 40.0 - var usable_width : float = maxf(120.0, viewport_size.x - side_margin * 2.0) - var max_rel := 0 - var fan_half_width : float = minf(usable_width * 0.5 - sample_size.x * 0.5, 120.0 + widget_count * 18.0) - fan_half_width = maxf(fan_half_width, 0.0) - var fit_scale : float = minf(0.92, maxf(0.52, (viewport_size.y - 36.0) / sample_size.y)) - var scaled_height : float = sample_size.y * fit_scale - var base_y : float = maxf(0.0, viewport_size.y - scaled_height - 28.0) - var arc_height : float = minf(34.0, viewport_size.y * 0.14) - var max_angle_deg : float = clampf(14.0 + widget_count * 2.4, 18.0, 34.0) - - for i in range(widget_count): - var slot_i := int((widgets[i] as Control).get_meta("_fan_slot", i)) - max_rel = max(max_rel, abs(_wrapped_hand_delta(slot_i, widget_count))) - - for i in range(widget_count): - var widget := widgets[i] as Control - if widget == null: - continue - widget.size = widget.custom_minimum_size - - var slot := int(widget.get_meta("_fan_slot", i)) - var rel := _wrapped_hand_delta(slot, widget_count) - var t : float = 0.0 if max_rel == 0 else float(rel) / float(max_rel) - var angle_deg : float = t * max_angle_deg - var card_size := _hand_card_size(widget) - var edge_factor : float = absf(t) - var lift : float = 0.0 - var scale_amt : float = fit_scale * lerpf(1.0, 0.84, edge_factor) - var is_selected := bool(widget.get_meta("_sel", false)) - - if is_selected: - scale_amt += 0.08 - lift += 16.0 - - var pos := Vector2.ZERO - pos.x = viewport_size.x * 0.5 + t * fan_half_width - (card_size.x * scale_amt) * 0.5 - pos.y = base_y + float(pow(edge_factor, 1.35)) * arc_height - lift - pos.x = clampf(pos.x, side_margin, maxf(side_margin, viewport_size.x - side_margin - card_size.x * scale_amt)) - pos.y = clampf(pos.y, 0.0, maxf(0.0, viewport_size.y - card_size.y * scale_amt)) - var z := 20 + int((1.0 - edge_factor) * 100.0) - if is_selected: - z += 120 - widget.set_meta("_hand_stack", z) - - _apply_hand_card_transform(widget, pos, deg_to_rad(angle_deg * 0.35), scale_amt, z) - - # Reorder children by z so Godot routes GUI input to the visually topmost card. - # Positions are stable because we use _fan_slot metadata, not child index. - _restack_hand_cards() - - -func _restack_hand_cards() -> void: - var ordered : Array[Control] = [] - for child in _hand_cards.get_children(): - if child is Control: - ordered.append(child as Control) - ordered.sort_custom(func(a: Control, b: Control) -> bool: - return int(a.get_meta("_hand_stack", 0)) < int(b.get_meta("_hand_stack", 0)) - ) - for i in range(ordered.size()): - _hand_cards.move_child(ordered[i], i) - - -func _apply_hand_card_transform(widget: Control, pos: Vector2, rot: float, scale_amt: float, z: int) -> void: - widget.pivot_offset = _hand_card_size(widget) * 0.5 - widget.z_index = z - var existing : Variant = widget.get_meta("_hand_tween", null) - if existing is Tween and is_instance_valid(existing): - (existing as Tween).kill() - - # New widgets have never been positioned — snap them in place so they don't - # slide in from (0,0). All subsequent layout calls tween normally. - if not widget.has_meta("_hand_positioned"): - widget.set_meta("_hand_positioned", true) - widget.position = pos - widget.rotation = rot - widget.scale = Vector2.ONE * scale_amt - return - - var tw := create_tween().set_parallel(true) - tw.set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_OUT) - tw.tween_property(widget, "position", pos, 0.18) - tw.tween_property(widget, "rotation", rot, 0.18) - tw.tween_property(widget, "scale", Vector2.ONE * scale_amt, 0.18) - widget.set_meta("_hand_tween", tw) - - - -func _hand_card_size(widget: Control) -> Vector2: - var size_v := widget.size - if size_v.x <= 0.0 or size_v.y <= 0.0: - size_v = widget.custom_minimum_size - if size_v.x <= 0.0: - size_v.x = 160.0 - if size_v.y <= 0.0: - size_v.y = 257.0 - return size_v - - -func _wrapped_hand_delta(index: int, total: int) -> int: - var delta := index - _hand_focus_index - if total <= 1: - return 0 - if delta > total / 2: - delta -= total - elif delta < -int(ceil(total * 0.5)): - delta += total - return delta - -# ── HUD update ──────────────────────────────────────────────────────────────── - -func _update_hud(state: Dictionary) -> void: - var phase : String = state.get("phase", "") - var turn : int = state.get("turnNumber", 1) - _phase_lbl.text = "Phase: %s" % phase - - if _is_spectating: - _update_hud_spectator(state, turn) - return - - # ── Player path ─────────────────────────────────────────────────────────── - var is_mine : bool = Game.is_my_turn() - var my : Dictionary = Game.get_my_player() - var opp : Dictionary = Game.get_opponent() - - _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 = "%d" % int(my.get("currentSp", 0)) - _st_lbl.text = "%d" % int(my.get("currentSt", 0)) - _deck_lbl.text = "%d" % int(my.get("deckCount", 0)) - var discard : Array = my.get("discard", []) - _discard_lbl.text = "%d" % max(0, discard.size()) - - _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)) - - 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 - - _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) - - -func _update_hud_spectator(state: Dictionary, turn: int) -> void: - var active_id : String = str(state.get("activePlayerAccountId", "")) - var active_name : String = Game.get_display_name(active_id) - _turn_lbl.text = "Turn %d — %s is acting" % [turn, active_name] - _turn_lbl.modulate = Color(1.0, 0.76, 0.2) - - # Always hide the 2-player opponent panel; show turn strip for all player counts. - _opp_panel.visible = false - var all_players : Array = state.get("players", []) - _turn_order_strip.visible = all_players.size() > 1 - if _turn_order_strip.visible: - _rebuild_turn_order_strip(state) - - _draw_btn.visible = false - _end_turn_btn.visible = false - - _rebuild_spectator_panel(state) - - -## Rebuild the spectator player-summary list. One row per player sorted by seatIndex. -## Shows name (with active-turn highlight), SP, ST, deck count, and a Discard button. -func _rebuild_spectator_panel(state: Dictionary) -> void: - for c in _spectator_list.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", {}) - - 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_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 = Game.get_display_name(pid) - - var row := PanelContainer.new() - row.custom_minimum_size = Vector2(0, 40) - row.self_modulate = Color(1, 1, 1, 0.4 if eliminated else 1.0) - - var style := StyleBoxFlat.new() - style.bg_color = Color(0.18, 0.16, 0.08, 0.92) if is_active else Color(0.10, 0.10, 0.13, 0.85) - style.border_width_left = 4 - style.border_color = Color(1.0, 0.85, 0.2) if is_active \ - else (Color.html("#" + hex_str) if not hex_str.is_empty() else Color(0.4, 0.4, 0.4)) - row.add_theme_stylebox_override("panel", style) - - var margin := MarginContainer.new() - margin.add_theme_constant_override("margin_left", 8) - margin.add_theme_constant_override("margin_right", 8) - margin.add_theme_constant_override("margin_top", 4) - margin.add_theme_constant_override("margin_bottom", 4) - row.add_child(margin) - - var hbox := HBoxContainer.new() - hbox.add_theme_constant_override("separation", 12) - margin.add_child(hbox) - - var name_lbl := Label.new() - name_lbl.text = ("★ " if is_active else "") + display + (" [X]" if eliminated else "") - name_lbl.add_theme_font_size_override("font_size", 12) - name_lbl.custom_minimum_size = Vector2(120, 0) - name_lbl.size_flags_horizontal = Control.SIZE_EXPAND_FILL - name_lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER - if is_active: - name_lbl.add_theme_color_override("font_color", Color(1.0, 0.9, 0.3)) - elif eliminated: - name_lbl.add_theme_color_override("font_color", Color(0.4, 0.4, 0.4)) - hbox.add_child(name_lbl) - - var sp_lbl := Label.new() - sp_lbl.text = "SP: %d" % int(p.get("currentSp", 0)) - sp_lbl.add_theme_font_size_override("font_size", 11) - sp_lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER - sp_lbl.tooltip_text = "Spirit Points" - hbox.add_child(sp_lbl) - - var st_lbl := Label.new() - st_lbl.text = "ST: %d" % int(p.get("currentSt", 0)) - st_lbl.add_theme_font_size_override("font_size", 11) - st_lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER - st_lbl.tooltip_text = "Sacrifice Tokens" - hbox.add_child(st_lbl) - - var deck_lbl := Label.new() - deck_lbl.text = "Deck: %d" % int(p.get("deckCount", 0)) - deck_lbl.add_theme_font_size_override("font_size", 11) - deck_lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER - hbox.add_child(deck_lbl) - - var disc_cards : Array = p.get("discard", []) - var disc_count : int = disc_cards.size() if not disc_cards.is_empty() else int(p.get("discardCount", 0)) - var disc_btn := Button.new() - disc_btn.text = "Discard: %d" % disc_count - disc_btn.add_theme_font_size_override("font_size", 11) - disc_btn.custom_minimum_size = Vector2(80, 0) - if not disc_cards.is_empty(): - var cap_display := display - var cap_cards := disc_cards - disc_btn.pressed.connect(func() -> void: - _show_discard_for("%s Discard" % cap_display, cap_cards)) - else: - disc_btn.disabled = true - hbox.add_child(disc_btn) - - _spectator_list.add_child(row) - - -## 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: - # In N-player / team games, derive win from player_outcomes so a teammate - # winning also counts as a local victory. - var i_won : bool - if not player_outcomes.is_empty(): - var my_outcome : String = "" - for po: Dictionary in player_outcomes: - if str(po.get("accountId", "")) == Auth.user_id: - my_outcome = str(po.get("outcome", "")) - break - i_won = (my_outcome == "Winner") - else: - i_won = (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]\n" % win_condition + "\n".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 - - Mode.ABILITY_TARGET_FORCED: - _clear_highlights() - _start_ability_targeting() - - _: - # 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() diff --git a/Client/origin-client/scenes/game/game_screen_revamp_plan.md b/Client/origin-client/scenes/game/game_screen_revamp_plan.md new file mode 100644 index 0000000..17dcdba --- /dev/null +++ b/Client/origin-client/scenes/game/game_screen_revamp_plan.md @@ -0,0 +1,620 @@ +# Game Screen Revamp Plan + +## Problem + +`game_screen.gd` is a 6,463-line monolith managing every concern of the game screen: +3D board rendering, camera, input, animations, HUD, hand cards, ability targeting, tile +inspection, skybox, pathfinding, and game-over flows. Changes to any one domain risk +breaking unrelated ones; finding the relevant code requires scanning thousands of lines. + +The rest of the client (collection, bazaar, free_play, etc.) already follows the pattern: + +``` +scenes// + .gd ← thin orchestrator + components/ ← self-contained sub-panels / logic nodes + views/ ← full sub-screens swapped in/out +``` + +The game screen will adopt the same structure. + +--- + +## Target Directory Layout + +``` +scenes/game/ + game_screen.gd ← slim orchestrator (~300 lines) + game_screen.tscn + + components/ + board/ + board_controller.gd ← tile bodies, board build/teardown + board_controller.tscn + highlight_controller.gd ← all MeshInstance3D highlights, cursor quad + highlight_controller.tscn + pathfinder.gd ← bfs_path, bfs_reachable, board_distance, coord helpers + pathfinder.gd ← (no scene needed — pure logic Node) + tile_target_resolver.gd ← valid_play_tiles, valid_move_tiles, valid_attack_*, valid_placement_* + tile_target_resolver.gd ← (pure logic Node) + + camera/ + camera_controller.gd ← yaw/pitch/distance state, apply_camera, zoom + camera_controller.tscn ← owns CameraRig + Camera3D subtree + + environment/ + skybox_controller.gd ← procedural/live/CDN skybox, star system + skybox_controller.tscn ← owns WorldEnvironment + + input/ + board_input_handler.gd ← _unhandled_input, mouse & touch dispatch + board_input_handler.gd ← emits signals: tile_clicked(coord), unit_clicked(iid), + ← tile_held(coord), board_drag(delta), zoom(amount) + + units/ + unit_registry.gd ← _tile_bodies, _unit_meshes, _unit_bodies, _anim_players, + ← _enemy_unit_ids, _friendly_unit_ids; rebuild_ownership + unit_registry.gd ← (pure logic Node, no scene) + unit_mesh_builder.gd ← add_unit_mesh, model retry, tinting, facing, find_animation_player + unit_mesh_builder.tscn + unit_animator.gd ← play_unit_anim, play_damage_animations, play_move_animations, + ← counterattack chains, hitsplat layer + unit_animator.gd ← (pure logic Node) + + selection/ + selection_controller.gd ← Mode enum, _mode state, set_mode, select_unit, + ← handle_board_click dispatch per mode + selection_controller.gd ← emits: mode_changed(mode), unit_selected(iid), card_selected(id) + ability_targeting.gd ← start_ability_targeting, highlight_ability_targets, + ← _unit_passes_filters, _tile_passes_filters, LOS, confirm btn, + ← branch panel, send_ability + ability_targeting.gd ← (pure logic Node) + server_prompt_handler.gd ← all _on_*_pick_request handlers (cost, action_group, branch, + ← target, tile, player, reveal_choice) + server_prompt_handler.gd ← (pure logic Node) + + hud/ + hud_controller.gd ← update_hud, update_hud_spectator, turn_order_strip, + ← spectator_panel, discard viewer + hud_controller.tscn ← owns the CanvasLayer/HUD subtree + hand_manager.gd ← rebuild_hand, layout_hand_cards (fan arc), spin, popup queue, + ← hand card widget creation, on_hand_card_clicked dispatch + hand_manager.tscn ← owns HandArea + HandCards subtree + tile_drawer.gd ← create_tile_drawer, set_tile_drawer_content, open/close tween, + ← all _tile_drawer_* state + tile_drawer.tscn ← owns the slide-in PanelContainer + toggle button + + overlays/ + context_popup.gd ← hold-timer popup (tile/unit context info) + context_popup.tscn + game_over_overlay.gd ← _on_game_over, rank label, main menu btn + game_over_overlay.tscn + inactive_dialogs.gd ← opponent_inactive, inactive_warning, both_idle_warning dialogs + inactive_dialogs.gd ← (pure logic Node, reuses Godot dialogs) + + in_game_settings.gd ← already separate ✓ + in_game_settings.tscn +``` + +--- + +## Module Descriptions + +### `game_screen.gd` (orchestrator) + +Responsibilities after refactor: +- `_ready`: instantiate/add child components, wire cross-component signals +- Forward `Game.*` signals to the right component +- Coordinate state-update sequence: `_on_state_updated` calls each component in order +- Own nothing else — no 3D state, no UI state + +Target size: **~300 lines** + +--- + +### `board/board_controller.gd` + +Owns: `_tile_bodies`, `_tile_heights`, `_tile_y_bases`, `_tile_visual_tops`, tile scene root. + +Key methods extracted from `game_screen.gd`: +- `build_board(state)` +- `_add_tile(tile_data)` +- `_try_load_tile_model(...)`, `_try_load_tile_bottom(...)` +- `_apply_tile_texture(...)`, `_update_tile_affinity(...)` +- `_fit_model_to_tile(...)`, `_model_local_aabb(...)` + +Emits: `tile_model_loaded(coord)` — board is ready for unit placement. + +--- + +### `board/highlight_controller.gd` + +Owns: `_hi_root`, `_cursor_highlight`, `_hover_team_overlay`, `_hovered_coord`, `_hovered_unit_mesh`. + +Key methods: +- `clear_highlights()` +- `update_hover(coord, units_root)` +- `add_highlight(coord, color)` +- `highlight_tiles(coords, color)` +- `init_cursor_nodes()` +- `on_highlight_texture_loaded()` + +Constants moved here: `HI_GREEN`, `HI_RED`, `HI_BLUE`, `HI_YELLOW`, `HI_ORANGE`. + +--- + +### `board/pathfinder.gd` + +Pure GDScript `Node` (no scene). Stateless algorithms, receives board state as arguments. + +Key methods extracted: +- `bfs_path(from, to, state, blocked_fn) → Array[Vector2i]` +- `bfs_reachable(from, mp, state, blocked_fn) → Array[Vector2i]` +- `board_distance(a, b, grid_type) → int` +- `coord_to_world(coord, tile_heights) → Vector3` +- `mouse_to_tile_coord(camera, mouse_pos, tile_bodies) → Vector2i` +- `raycast_body(camera, mouse_pos, space) → PhysicsBody3D` + +No game-state dependency — pass in what it needs. + +--- + +### `board/tile_target_resolver.gd` + +Pure logic `Node`. Answers "which tiles are valid for X action?" using current game state. + +Key methods extracted: +- `valid_play_tiles(card, state) → Array[Vector2i]` +- `valid_move_tiles(unit_iid, state) → Array[Vector2i]` +- `valid_attack_target_coords(unit_iid, state) → Array[Vector2i]` +- `valid_attack_target_ids(unit_iid, state) → Array[String]` +- `valid_placement_tiles(state) → Array[Vector2i]` +- `valid_sacrifice_spirits(arch_coord, state) → Array[String]` +- `attack_range_tiles(unit_iid, state) → Array[Vector2i]` +- `tile_matches_channel_affinity(tile, card) → bool` +- `terra_count_for_card(card) → int` + +--- + +### `camera/camera_controller.gd` + +Owns: `CameraRig`, `Camera3D`, `CamCtrlPanel`, all `_cam_*` state variables. + +Key methods extracted: +- `apply_camera()` +- `zoom(delta)` +- `sync_cam_ctrl_panel()` +- `orbit(delta: Vector2)`, `pan(delta: Vector2)` +- `tween_to(pivot: Vector3)` — smooth camera pan to tile +- `_on_cam_orbit_btn_toggled(...)` etc. +- `deactivate_touch_cam_modes()` + +Emits nothing — purely reactive to input signals from `board_input_handler`. + +--- + +### `environment/skybox_controller.gd` + +Owns: `WorldEnvironment`, all `_skybox_*` and `_stars` state, ambient star timer. + +Key methods extracted: +- `_setup_environment()` +- `_setup_procedural_sky()`, `_setup_live_skybox()` +- `_on_skybox_setting_changed()` +- `_load_cubemap_skybox()`, `_load_static_skybox()`, `_load_animated_skybox()` +- `_apply_cubemap_material()`, `_apply_skybox_frame()` +- `_add_star()`, `_remove_star()`, `_start_ambient_star_cycle()` +- `_on_game_activity(event)` — star spawning on activity + +Receives: `process(delta)` call from game_screen for sky rotation, or uses its own `_process`. + +--- + +### `input/board_input_handler.gd` + +Owns: `HoldTimer`, `CamGestureTimer`, all touch state variables. + +Emits signals (game_screen routes these to camera/selection): +```gdscript +signal tile_clicked(coord: Vector2i) +signal unit_clicked(iid: String) +signal tile_held(coord: Vector2i) # long press +signal board_drag(delta: Vector2, type: String) # "orbit"|"pan" +signal board_zoom(amount: float) +signal board_double_clicked(coord: Vector2i) +``` + +All logic from `_unhandled_input()` and `_input()` moves here. +Camera controller and selection controller connect to these signals. + +--- + +### `units/unit_registry.gd` + +Pure logic `Node`. Central lookup table for all live units. + +Owns: +- `_tile_bodies`, `_unit_meshes`, `_unit_bodies`, `_anim_players`, `_unit_def_ids` +- `_enemy_unit_ids`, `_friendly_unit_ids` +- `_unit_team_idx`, `_model_base_angles`, `_needs_face_rot` + +Key methods: +- `rebuild_ownership(state, local_account_id)` +- `is_enemy_unit(iid) → bool` +- `is_friendly_unit(iid) → bool` +- `is_ruin_unit(iid) → bool` +- `all_board_units(state) → Array` +- `get_unit_def(iid) → Dictionary` + +--- + +### `units/unit_mesh_builder.gd` + +Owns: `_units_root` (Node3D). +Depends on: `unit_registry`, `board_controller` (for tile heights). + +Key methods extracted: +- `rebuild_units(state, prev_state)` — incremental diff +- `add_unit_mesh(unit_data)` — placeholder + async GLB load +- `schedule_model_retry(iid)` / `_do_model_retry(iid)` +- `apply_model_tint(mesh, color)` +- `find_animation_player(node) → AnimationPlayer` +- `resolve_anim_track(anim_player, action) → String` +- `facing_to_base_angle(dir) → float` +- `idle_rotation(iid, state)` + +Constants moved here: `ANIM_ALIASES`, `UNIT_SFX_KEYS`. + +--- + +### `units/unit_animator.gd` + +Pure logic `Node`. Coordinates animation sequencing. +Depends on: `unit_registry`, `unit_mesh_builder`. + +Key methods extracted: +- `play_unit_anim(iid, action, loop)` +- `play_damage_animations(state, prev_state)` — counterattack chains, death +- `play_move_animations(state, prev_state)` +- `play_counter_attack(...)`, `play_counter_chain(...)` +- `update_prev_state(state)` +- `sfx_for_unit(iid, sfx_key) → String` +- `prime_unit_sfx(iid)` +- `schedule_rebuild(state)` — deferred rebuild after animations + +Constants moved here: `MOVE_STEP_SECS`, `POST_ANIM_SECS`, `ANIM_TRANSITION_SECS`. + +--- + +### `selection/selection_controller.gd` + +Owns: `_mode`, `_sel_card_id`, `_sel_unit_id`, `_held_coord`, `_terra_targets`, +`_sac_arch_coord`, ability state. + +Key methods extracted: +- `set_mode(mode)` — clears stale state, emits `mode_changed` +- `select_unit(iid, state)` — sets mode, computes highlights +- `handle_board_click(coord, iid, state)` — match on `_mode` +- `show_arch_spirit_menu(arch_coord, state)` +- `start_sacrifice_mode(arch_coord, state)` +- `confirm_sacrifice(...)`, `confirm_ascend(...)`, `confirm_transition(...)` +- `channel_ruin(coord, state)`, `confirm_channel_ruin(...)` +- `show_card_picker(options, callback)` + +Emits: +```gdscript +signal mode_changed(mode: Mode) +signal highlights_requested(coords: Array, color: Color) +signal unit_selected(iid: String) +signal card_deselected() +``` + +--- + +### `selection/ability_targeting.gd` + +Pure logic `Node`. +Owns: all `_ability_*` state variables, `_ability_panel`, `_ability_confirm_btn`, +`_ability_branch_panel`. + +Key methods extracted: +- `show_ability_panel(unit_iid, state)` +- `hide_ability_panel()` +- `start_ability_targeting(ability_def, unit_iid, state)` +- `advance_ability_targeting()` +- `highlight_ability_targets(state) → Array[Vector2i]` +- `unit_passes_filters(iid, filters, state) → bool` +- `tile_passes_filters(coord, filters, state) → bool` +- `client_has_los(from, to, state) → bool` +- `show_ability_confirm_btn()`, `hide_ability_confirm_btn()` +- `show_branch_panel(branches)`, `hide_branch_panel()` +- `send_ability(state)` +- `normalize_keys(dict) → Dictionary` +- `get_ability_actions(ability) → Array` + +--- + +### `selection/server_prompt_handler.gd` + +Pure logic `Node`. Handles all server-driven pause prompts. +Owns: `_pending_req_id`, `_pending_source_id`, `_pending_prompt_panel`, cost/tile/reveal pick state. + +Key methods extracted: +- `_on_cost_pick_request(data)`, `_finish_cost_pick()` +- `_on_cost_group_pick_request(data)` +- `_on_action_group_pick_request(data)` +- `_on_branch_pick_request(data)` +- `_on_target_pick_request(data)` +- `_on_tile_pick_request(data)`, (reuses highlight + mode) +- `_on_player_pick_request(data)` +- `_on_reveal_choice_pick_request(data)`, `_finish_reveal_pick()` +- `show_triggered_banner(text)` +- `show_player_panel(players)`, `add_player_option(player)`, `hide_player_panel()` +- `hide_pending_prompt_panel()` + +--- + +### `hud/hud_controller.gd` + +Owns: All HUD labels, buttons, `_turn_order_strip`, `_spectator_*` nodes. + +Key methods extracted: +- `update_hud(state, is_my_turn, sp, st)` +- `update_hud_spectator(state)` +- `rebuild_turn_order_strip(state)` +- `rebuild_spectator_panel(state)` +- `show_discard_for(account_id, state)` → replaces `_show_own_discard` / `_show_opp_discard` +- `make_discard_row(card) → Control` + +--- + +### `hud/hand_manager.gd` + +Owns: `_hand_cards`, `_hand_area`, `_hand_spin_left`, `_hand_spin_right`, +`_cached_hand_iids`, `_hand_focus_index`, `_pending_popup_cards`, `_popup_layer`. + +Key methods extracted: +- `rebuild_hand(state)` +- `apply_display_hand(iids, state)` +- `show_next_card_popup(card_data)`, `dismiss_card_popup()` +- `make_hand_card(card_data) → Control` +- `layout_hand_cards()` +- `apply_hand_card_transform(widget, pos, rot, scale)` +- `refresh_hand_selection(sel_card_id)` +- `spin_hand(dir)` +- `focus_hand_card(iid)` +- `configure_hand_spin_buttons()`, `layout_hand_spin_buttons()`, `sync_hand_spin_buttons()` + +Emits: +```gdscript +signal hand_card_clicked(card_data: Dictionary) +``` + +--- + +### `hud/tile_drawer.gd` + +Owns: slide-in `PanelContainer`, toggle button, all `_tile_drawer_*` state. + +Key methods extracted: +- `create_tile_drawer()` — builds the panel +- `set_tile_drawer_content(tile_data, state)` — populates all sections +- `open()`, `close()`, `toggle()` +- `set_tile_drawer_button_state(enabled)` +- `layout_tile_drawer_toggle_button()` +- `build_unit_detail_lines(unit, state) → Array[String]` +- `append_active_effect_lines(unit, state) → Array[String]` +- `find_unit_owner_account_id(unit_iid, state) → String` + +--- + +### `overlays/context_popup.gd` + +Owns: `%ContextPopup` panel and its labels/buttons. + +Extracted from `_on_hold_timer_fired()` and context popup wiring in `_ready()`. + +- `show_for_tile(coord, state)` — populates and shows popup +- `hide()` + +--- + +### `overlays/game_over_overlay.gd` + +Owns: `%GameOverOverlay` panel. + +Extracted from `_on_game_over()`: +- `show_result(result, rank_delta)` — populates labels, shows overlay + +--- + +### `overlays/inactive_dialogs.gd` + +Owns no nodes — creates Godot `AcceptDialog`/`ConfirmationDialog` dynamically. + +Extracted from: +- `_on_opponent_inactive()` +- `_on_inactive_warning()` +- `_on_both_idle_warning()` + +--- + +## Cross-Cutting Concerns + +### Signal Bus (game_screen.gd as router) + +The slim orchestrator wires cross-component communication: + +```gdscript +# board_input_handler → camera_controller +board_input_handler.board_drag.connect(camera_controller.on_drag) +board_input_handler.board_zoom.connect(camera_controller.on_zoom) + +# board_input_handler → selection_controller +board_input_handler.tile_clicked.connect(selection_controller.handle_tile_click) +board_input_handler.unit_clicked.connect(selection_controller.handle_unit_click) +board_input_handler.tile_held.connect(context_popup.show_for_tile) + +# selection_controller → highlight_controller +selection_controller.highlights_requested.connect(highlight_controller.highlight_tiles) + +# hand_manager → selection_controller +hand_manager.hand_card_clicked.connect(selection_controller.handle_hand_card_click) + +# Game singletons → individual components +Game.state_updated.connect(_on_state_updated) # orchestrator fans out +Game.triggered_target_request → ability_targeting +Game.cost_pick_request → server_prompt_handler +# ...etc. +``` + +### Shared Constants + +Create `scenes/game/game_constants.gd` (autoload or static class): + +```gdscript +class_name GameConstants + +const AFFINITY_COLORS := { ... } # moved from game_screen.gd +const HI_GREEN := Color(...) +const HI_RED := Color(...) +const HI_BLUE := Color(...) +const HI_YELLOW := Color(...) +const HI_ORANGE := Color(...) +const HITSPLAT_LIFETIME := 0.75 +const HITSPLAT_RISE_PIXELS := 42.0 +const MOVE_STEP_SECS : float = 0.28 +const POST_ANIM_SECS : float = 1.2 +const ANIM_TRANSITION_SECS : float = 5.0 / 30.0 +const ANIM_ALIASES : Dictionary = { ... } +const UNIT_SFX_KEYS := [...] +``` + +--- + +## Implementation Phases + +### Phase 1 — Pure Logic Extractions (no scene changes) + +Extract nodes with **no scene or `@onready` dependencies** first. These can be moved as +plain `.gd` files added as child `Node`s in `game_screen.tscn`. + +| File | Extracted from | Risk | +|---|---|---| +| `pathfinder.gd` | bfs_*, board_distance, coord helpers | Low | +| `tile_target_resolver.gd` | valid_*_tiles, valid_*_target_* | Low | +| `unit_registry.gd` | ownership dicts, rebuild_ownership | Low | +| `game_constants.gd` | all top-level consts | Low | + +**Acceptance test**: gameplay is identical; game_screen.gd references the new nodes via +`@onready var _pathfinder : Pathfinder = $Pathfinder`. + +--- + +### Phase 2 — Animator Extraction + +Move animation orchestration out of game_screen.gd. + +| File | Extracted from | Risk | +|---|---|---| +| `unit_animator.gd` | play_damage_animations, play_move_animations, hitsplat, anim chains | Medium | + +Hitsplat layer creation stays in unit_animator; game_screen passes it the canvas layer root. + +**Acceptance test**: damage numbers, death animations, movement tweens all fire correctly. + +--- + +### Phase 3 — Input Handler + +Move all of `_unhandled_input()` and touch state. + +| File | Extracted from | Risk | +|---|---|---| +| `board_input_handler.gd` | _unhandled_input, _input, touch state | Medium | + +game_screen becomes a signal relay. Camera and selection connect to handler signals. + +**Acceptance test**: mouse orbit/pan/zoom, touch drag, pinch zoom, tap-to-select, tap-to-tile +all work on desktop and mobile. + +--- + +### Phase 4 — HUD Components + +Move HUD, hand, and tile drawer into dedicated nodes with their own `.tscn` subscenes. + +| File | Extracted from | Risk | +|---|---|---| +| `hud_controller.gd` | update_hud, turn strip, spectator panel, discard | Low-Medium | +| `hand_manager.gd` | rebuild_hand, layout_hand_cards, popup queue | Medium | +| `tile_drawer.gd` | _create_tile_drawer, all tile drawer vars | Medium | + +Hand layout math (fan arc with wrapping) is the riskiest part — unit test the geometry. + +--- + +### Phase 5 — Selection & Ability Targeting + +Break the board click state machine and ability targeting logic into their own nodes. + +| File | Extracted from | Risk | +|---|---|---| +| `selection_controller.gd` | _mode, handle_board_click match, select_unit | Medium-High | +| `ability_targeting.gd` | start_ability_targeting, LOS, filters, panels | High | +| `server_prompt_handler.gd` | all _on_*_pick_request | Medium | + +This is the highest-risk phase because the Mode enum and _ability_* state are deeply +intertwined. Extract selection_controller first, then peel off ability_targeting once +the mode boundary is stable. + +--- + +### Phase 6 — Board, Camera, Environment, Overlays + +Move the remaining structural nodes. + +| File | Extracted from | Risk | +|---|---|---| +| `board_controller.gd` | build_board, tile model loading | Low | +| `camera_controller.gd` | camera state, apply_camera, touch buttons | Low | +| `skybox_controller.gd` | skybox, stars, activity feed | Low | +| `context_popup.gd` | hold-timer popup | Low | +| `game_over_overlay.gd` | game over overlay | Low | +| `inactive_dialogs.gd` | inactive/abandoned dialogs | Low | + +--- + +### Phase 7 — Slim Orchestrator + +With all logic delegated, `game_screen.gd` becomes a ~300-line file that: +1. Holds `@onready` refs to all child components +2. Wires cross-component signals in `_ready()` +3. Fans out `Game.state_updated` to each component in the correct order +4. Handles scene transitions (`get_tree().change_scene_to_file(...)`) + +--- + +## What Does NOT Move + +- `InGameSettings` — already separate (`in_game_settings.gd`) ✓ +- `CardWidget` — already in `collection/components/` ✓ +- `Game`, `Auth`, `Settings`, `Chat`, `HighlightConfig` singletons — untouched + +--- + +## Non-Goals + +- **No behaviour changes** during the refactor. Each phase preserves exact gameplay. +- **No new features** introduced alongside structural changes. +- **No API redesign** of `Game.*` signals or server protocol. + +--- + +## Risk Mitigation + +- Refactor one phase at a time; commit and playtest after each. +- The `_on_state_updated` orchestration order is load-bearing — document it before Phase 5. +- Ability targeting interacts with every other domain; leave it for Phase 5 after boundaries + are stable. +- Touch input on mobile should be smoke-tested on device after Phase 3. diff --git a/Shared/legal/ccpa.md b/Shared/legal/ccpa.md new file mode 100644 index 0000000..03764f0 --- /dev/null +++ b/Shared/legal/ccpa.md @@ -0,0 +1,120 @@ +# CCPA Compliance Notes + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Internal compliance checklist. Not a published legal document.** +> Must be reviewed by a qualified attorney before California residents access the Services. + +--- + +## Overview + +The California Consumer Privacy Act (CCPA), as amended by the California Privacy Rights Act (CPRA), grants California residents specific rights regarding their personal information. This document tracks CCPA compliance requirements for AeternalisGames LLC. + +**Applicability threshold**: CCPA applies if the business: +- Has annual gross revenues exceeding $25 million, OR +- Buys, sells, or shares personal information of 100,000+ California consumers annually, OR +- Derives 50%+ of annual revenues from selling or sharing consumers' personal information. + +Even if below these thresholds, implementing CCPA-compliant practices is recommended as a baseline for user trust and future-proofing. + +--- + +## 1. Required Privacy Policy Disclosures + +The Privacy Policy must include CCPA-specific sections disclosing: + +- **Categories of personal information collected** (see Privacy Policy Section 2) +- **Purposes for which each category is used** +- **Categories of third parties with whom data is shared** +- **California consumers' rights** (see Section 2 below) +- **How to submit a request** to exercise rights +- **Right to non-discrimination**: Users who exercise their CCPA rights must not be denied services, charged different prices, or provided a different level of service + +**Action required**: Ensure Privacy Policy includes all required CCPA disclosures before any California users are permitted. + +--- + +## 2. California Consumer Rights + +California residents have the following rights under CCPA/CPRA: + +### Right to Know +- The right to request disclosure of: + - Specific pieces of personal information collected about them + - Categories of personal information collected + - Categories of sources from which information was collected + - Business purposes for collecting information + - Categories of third parties with whom information is shared + +### Right to Delete +- The right to request deletion of personal information collected from them. +- Exceptions apply (e.g., transaction records needed for legal compliance). +- Must extend to service providers where feasible. + +### Right to Correct +- The right to request correction of inaccurate personal information. + +### Right to Opt-Out of Sale or Sharing +- The right to opt out of the "sale" or "sharing" of their personal information. +- See Section 3 below regarding whether data sharing with Stripe constitutes a "sale." + +### Right to Limit Use of Sensitive Personal Information +- Sensitive personal information (e.g., precise geolocation, account login credentials) must be limited to necessary uses. + +### Right to Non-Discrimination +- Exercising CCPA rights must not result in denial or degraded quality of service. + +--- + +## 3. "Do Not Sell or Share My Personal Information" + +CCPA requires a **"Do Not Sell or Share My Personal Information"** link on the website if the business sells or shares personal information. + +**Key question**: Does data sharing with Stripe constitute a "sale" under CCPA? + +- **General analysis**: No. Stripe is a **service provider** — data shared with Stripe is shared for the purpose of processing payments on behalf of AeternalisGames LLC, not for Stripe's own commercial purposes. This is a service provider relationship, not a "sale" under CCPA. +- **Condition**: This analysis holds as long as Stripe is contractually restricted from using the data for its own commercial purposes. Stripe's Data Processing Agreement covers this. +- **Action required**: Confirm service provider status with legal counsel. If any data sharing constitutes a "sale," implement the opt-out mechanism. + +If no "sale" or "sharing" occurs, a "Do Not Sell" link may not be legally required, but it is a user-trust best practice to include one. + +--- + +## 4. Responding to CCPA Requests + +- Designate **two or more methods** for submitting requests (e.g., email + in-app form). +- Respond to verified requests within **45 days** (extendable by 45 days with notice). +- Verify the identity of the requestor before disclosing or deleting data. +- Free of charge for up to two requests per 12-month period per consumer. + +--- + +## 5. Data Sharing Inventory + +For CCPA purposes, document all categories of data shared with third parties: + +| Third Party | Data Shared | Purpose | Sale/Share? | +|---|---|---|---| +| Stripe, Inc. | Email, payment details, transaction records | Payment processing | No (service provider) | +| Hosting provider | All user data (stored on their infrastructure) | Infrastructure | No (service provider) | +| [Analytics — TBD] | [TBD] | [TBD] | [Review required] | + +**Action required**: Complete this inventory before launch; review any analytics integrations. + +--- + +## 6. Checklist + +- [ ] Add CCPA-specific disclosures to Privacy Policy +- [ ] Confirm whether "sale" of personal information occurs (service provider analysis) +- [ ] Add "Do Not Sell or Share My Personal Information" link to website if required +- [ ] Implement CCPA rights request mechanism (at minimum: email-based) +- [ ] Document response process for CCPA requests (45-day SLA) +- [ ] Complete third-party data sharing inventory +- [ ] Legal review by qualified attorney + +--- + +*This document is an internal compliance planning document and must be reviewed by a qualified attorney before California users access the Services.* diff --git a/Shared/legal/cookie-policy.md b/Shared/legal/cookie-policy.md new file mode 100644 index 0000000..a2bf97c --- /dev/null +++ b/Shared/legal/cookie-policy.md @@ -0,0 +1,124 @@ +# Cookie Policy + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Not yet reviewed by legal counsel. Do not publish.** + +--- + +## 1. Introduction + +AeternalisGames LLC ("Company," "we," "us," "our") uses cookies and similar tracking technologies on our website and web client (collectively, the "Website"). This Cookie Policy explains what cookies are, which cookies we use, and how you can control them. + +This policy should be read alongside our Privacy Policy. + +--- + +## 2. What Are Cookies? + +Cookies are small text files placed on your device by a website. They are widely used to: + +- Keep you signed in across page loads (session cookies) +- Remember your preferences +- Understand how visitors use a website (analytics) + +"Similar technologies" include local storage, session storage, and pixel tags, which function similarly to cookies. + +--- + +## 3. Cookies We Use + +We aim to keep our cookie footprint minimal. We do not use third-party advertising or tracking cookies. + +### 3.1 Strictly Necessary Cookies + +These cookies are essential for the Website to function. They cannot be disabled. + +| Cookie Name | Purpose | Duration | +|---|---|---| +| `session` / `auth_token` | Maintains your authenticated session | Session / [X days] | +| `csrf_token` | Prevents cross-site request forgery | Session | + +### 3.2 Functional Cookies + +These cookies remember your preferences to improve your experience. + +| Cookie Name | Purpose | Duration | +|---|---|---| +| `locale` | Remembers language/region preference | [X days] | +| `theme` | Remembers UI theme preference (if applicable) | [X days] | + +### 3.3 Analytics Cookies + +These cookies help us understand how visitors use our Website (page visits, navigation paths, errors). We use this data in aggregate to improve the Website. + +| Service | Purpose | Duration | +|---|---|---| +| [Analytics Provider — TBD] | Aggregate usage analytics | [X days] | + +**Note**: If we use a third-party analytics provider, this section must be completed with the specific provider's details. Prefer privacy-respecting analytics (e.g., Plausible, Fathom) that do not require consent banners over Google Analytics where possible. + +### 3.4 Cookies We Do NOT Use + +We do **not** use: +- Advertising or retargeting cookies +- Social media tracking cookies +- Third-party behavioral profiling cookies + +--- + +## 4. Cookie Consent + +### EU/EEA Visitors (GDPR) + +Under GDPR, we are required to obtain your consent before placing non-essential cookies (functional, analytics). When you first visit our Website from the EU/EEA, you will see a consent banner that allows you to: + +- Accept all cookies +- Accept only strictly necessary cookies +- Customize your preferences + +Your consent preferences are stored and respected on subsequent visits. You may change your preferences at any time via the cookie settings link in the website footer. + +### Other Visitors + +For visitors outside the EU/EEA, cookies are placed in accordance with this policy and our Privacy Policy. You may opt out of non-essential cookies via your browser settings or our cookie preferences tool. + +--- + +## 5. Managing Cookies + +You can control and delete cookies in several ways: + +### Browser Settings +Most browsers allow you to: +- View and delete existing cookies +- Block cookies from specific sites +- Block all third-party cookies + +Refer to your browser's help documentation for specific instructions. + +Note: Disabling strictly necessary cookies may prevent the Website from functioning correctly, including preventing login. + +### Cookie Preference Tool +[Link to cookie preference center — TBD when implemented on website] + +--- + +## 6. Updates to This Policy + +We may update this Cookie Policy as our use of cookies changes. The "Last Updated" date at the top of this page reflects the most recent revision. Material changes will be communicated via the Website. + +--- + +## 7. Contact + +For questions about this Cookie Policy: + +AeternalisGames LLC +**[ADDRESS]** +Email: **[PRIVACY CONTACT EMAIL]** + +--- + +*This Cookie Policy is a draft and must be reviewed by a qualified attorney before publication. The analytics section must be completed once the analytics provider is selected.* diff --git a/Shared/legal/coppa.md b/Shared/legal/coppa.md new file mode 100644 index 0000000..864aa52 --- /dev/null +++ b/Shared/legal/coppa.md @@ -0,0 +1,99 @@ +# COPPA Compliance Notes + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Internal compliance planning document. Not a published legal document.** +> Must be reviewed by a qualified attorney. A decision on minimum age policy is required before launch. + +--- + +## Overview + +The Children's Online Privacy Protection Act (COPPA) is a US federal law that imposes requirements on online services that collect personal information from children under 13. This document outlines the compliance options and recommended path for AeternalisGames LLC. + +--- + +## 1. Decision Required: Minimum Age Policy + +**A policy decision must be made before launch.** Two options: + +### Option A: Minimum Age 13 (Recommended) + +- Users under 13 are not permitted to use the Services. +- Enforced at registration with a date-of-birth field and age gate. +- If a user indicates they are under 13, registration is blocked with a message explaining the minimum age. +- If we become aware that a user is under 13, the account is immediately suspended and data deleted. +- COPPA compliance is achieved by **not collecting data from children under 13**. +- This is the standard approach for online gaming services (e.g., all major online games use minimum age 13 or higher). + +**Advantages**: +- Simplest compliance path. +- No parental consent infrastructure required. +- Aligns with GDPR (which uses 13–16 as the threshold for children's consent, varying by EU member state). + +### Option B: Allow Under-13 With Verifiable Parental Consent + +- Requires a robust **Verifiable Parental Consent (VPC)** mechanism. +- VPC methods approved by the FTC include: credit card verification, signed consent forms, video call verification, and others. +- Significant legal, UX, and operational overhead. +- Under-13 users must have limited data collection and cannot participate in features requiring broader data use. + +**Disadvantages**: +- Substantial compliance overhead. +- VPC systems are operationally complex and imperfect. +- Not recommended for a small team. + +--- + +## 2. Recommendation + +**Minimum age 13 (Option A).** + +This is the standard for online gaming and the lowest-overhead compliance path. Real-money features should additionally require users to be **18 years of age or older** (or the legal age of majority in their jurisdiction). + +--- + +## 3. Implementation Requirements (Option A) + +If Option A is adopted: + +- **Date of birth collection**: Collect date of birth at registration. Store it securely. +- **Age gate**: If the entered date of birth indicates the user is under 13, block registration and display a message: *"You must be at least 13 years old to use this service."* Do not collect or retain the entered date of birth for blocked registrations. +- **Neutral date of birth field**: Do not suggest a date or make it easy to lie. Do not prompt users to enter a date that would pass the check. +- **Account review**: If we receive a credible report that a user is under 13, investigate and suspend if confirmed; delete data within 5 business days. +- **Privacy Policy disclosure**: State that we do not knowingly collect data from children under 13 and the process for reporting under-age accounts. + +--- + +## 4. Age Gates for Real-Money Purchases + +Regardless of minimum age policy, real-money purchases are restricted to users 18 or older: + +- Date of birth must be verified before enabling purchase flow. +- Frontend must block the purchase UI for users under 18. +- Backend Bazaar service must enforce age check before processing any real-money transaction. + +--- + +## 5. International Considerations + +- **EU/EEA (GDPR)**: GDPR sets the age of digital consent at 13–16 depending on EU member state. Where state-level age of consent is above 13, we may need parental consent for users in that age bracket. **Legal review required per launch market.** +- **UK (UK GDPR / Age Appropriate Design Code)**: The UK has a specific Children's Code (AADC) that imposes additional requirements for services likely to be accessed by children. If we launch in the UK, this requires review. + +--- + +## 6. Checklist + +- [ ] **Decision**: Confirm minimum age policy (Option A — minimum age 13, recommended) +- [ ] Implement date-of-birth age gate at registration (block under-13) +- [ ] Implement age gate for real-money purchases (block under-18) +- [ ] Add Privacy Policy disclosure: no data collected from under-13 users +- [ ] Define process for handling reports of under-age users +- [ ] Legal review of age gate implementation +- [ ] EU member state age of consent review (if EU launch) +- [ ] UK Age Appropriate Design Code review (if UK launch) + +--- + +*This document is an internal compliance planning document and must be reviewed by a qualified attorney before the Services are made publicly available.* diff --git a/Shared/legal/eula.md b/Shared/legal/eula.md new file mode 100644 index 0000000..0651917 --- /dev/null +++ b/Shared/legal/eula.md @@ -0,0 +1,111 @@ +# End User License Agreement (EULA) + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Not yet reviewed by legal counsel. Do not publish.** + +--- + +## IMPORTANT — READ BEFORE INSTALLING OR USING THE SOFTWARE + +This End User License Agreement ("EULA") is a legal agreement between you ("User," "you") and AeternalisGames LLC ("Company," "we," "us") for the use of Shards of Rathe and any associated software, including game clients, patches, and updates (collectively, the "Software"). + +**By installing, downloading, or using the Software, you agree to be bound by this EULA. If you do not agree, do not install or use the Software.** + +--- + +## 1. License Grant + +Subject to your compliance with this EULA, AeternalisGames LLC grants you a **limited, personal, non-exclusive, non-transferable, revocable license** to: + +- Install and run the Software on devices you own or control. +- Use the Software solely for your personal, non-commercial entertainment purposes. + +This license does not include any right to sublicense, sell, rent, lease, transfer, assign, or otherwise dispose of the Software. + +--- + +## 2. Restrictions + +You agree that you will NOT: + +- **Reverse engineer, decompile, disassemble**, or attempt to derive the source code of the Software, except to the extent permitted by applicable law. +- **Modify or create derivative works** based on the Software. +- **Use or distribute cheat tools**, hacks, exploits, bots, automation software, or any third-party software that modifies the Software's behavior or provides an unfair advantage. +- **Redistribute, sell, rent, lease, or sublicense** the Software or any portion thereof. +- **Remove, alter, or obscure** any proprietary notices (copyright, trademark, etc.) in or on the Software. +- **Use the Software** for any commercial purpose, including streaming for commercial gain, without written consent from AeternalisGames LLC. +- **Extract, copy, or reuse** any game assets (art, audio, models, code) outside of the Software. + +--- + +## 3. Intellectual Property + +The Software and all content therein — including but not limited to game engine code, art, audio, characters, storyline, and user interface — are the exclusive property of AeternalisGames LLC and are protected by copyright, trademark, and other intellectual property laws. + +You acquire no ownership rights in the Software by virtue of this EULA. All rights not expressly granted herein are reserved by AeternalisGames LLC. + +--- + +## 4. Acceptance at Installation / First Launch + +This EULA must be presented to the user and require explicit acceptance: + +- **Installer**: A checkbox or "I Agree" button must be presented before installation proceeds. +- **First launch**: If not accepted at install, the EULA must be presented at first launch, requiring acceptance before the game loads. +- A record of acceptance (timestamp, version) should be stored locally and/or server-side. + +--- + +## 5. Updates and Patches + +AeternalisGames LLC may provide updates, patches, or new versions of the Software. This EULA applies to all updates unless a separate license accompanies the update, in which case the terms of that license govern. + +--- + +## 6. Termination + +This EULA is effective until terminated. Your license terminates automatically if: + +- You breach any term of this EULA. +- Your game account is suspended or terminated in accordance with the Terms of Service. +- You uninstall the Software. + +Upon termination, you must uninstall and destroy all copies of the Software in your possession. + +--- + +## 7. Disclaimer of Warranties + +THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. AETERNALISGAMES LLC DOES NOT WARRANT THAT THE SOFTWARE WILL BE UNINTERRUPTED, ERROR-FREE, OR FREE OF HARMFUL COMPONENTS. + +--- + +## 8. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, AETERNALISGAMES LLC SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES ARISING OUT OF OR RELATED TO YOUR USE OF OR INABILITY TO USE THE SOFTWARE. IN NO EVENT SHALL OUR TOTAL LIABILITY EXCEED THE AMOUNT YOU PAID FOR THE SOFTWARE IN THE TWELVE MONTHS PRECEDING THE CLAIM, OR $100 USD, WHICHEVER IS GREATER. + +--- + +## 9. Relationship to Terms of Service + +This EULA governs your use of the Software (client application). Your access to and use of online features of Shards of Rathe is also governed by the **Terms of Service**, which is incorporated herein by reference. In the event of a conflict between this EULA and the Terms of Service, the Terms of Service shall govern with respect to online services. + +--- + +## 10. Governing Law + +This EULA is governed by the laws of the **State of [STATE], United States**, without regard to conflict of law principles. + +--- + +## 11. Contact + +AeternalisGames LLC +**[ADDRESS]** +Email: **[LEGAL CONTACT EMAIL]** + +--- + +*This EULA is a draft and must be reviewed by a qualified attorney before publication or distribution.* diff --git a/Shared/legal/gdpr.md b/Shared/legal/gdpr.md new file mode 100644 index 0000000..544e1a4 --- /dev/null +++ b/Shared/legal/gdpr.md @@ -0,0 +1,148 @@ +# GDPR Compliance Notes + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Internal compliance checklist and design notes. Not a published legal document.** +> Must be reviewed by a qualified attorney before EU/EEA users are permitted to access the Services. + +--- + +## Overview + +The General Data Protection Regulation (GDPR) applies to any processing of personal data of individuals in the EU/EEA, regardless of where the data controller (AeternalisGames LLC) is based. This document tracks GDPR compliance requirements and implementation notes. + +--- + +## 1. Lawful Basis for Processing + +For each category of data, we must establish a lawful basis: + +| Data Category | Lawful Basis | +|---|---| +| Account data | Contract (necessary to provide the service) | +| Gameplay data | Contract / Legitimate Interest | +| Chat logs | Legitimate Interest (moderation/safety) | +| Payment data | Contract / Legal Obligation | +| Marketing emails | Consent (explicit opt-in required) | +| Analytics | Legitimate Interest (with opt-out) | + +**Action required**: Finalize lawful basis mapping with legal counsel before launch. + +--- + +## 2. Right to Erasure (Right to Be Forgotten) + +Users may request deletion of their personal data. Implementation requirements: + +- **Account data**: Must be fully deleted from all production databases within 30 days of a verified request. +- **Gameplay statistics**: Delete or anonymize (statistics may be retained in anonymized, non-identifiable form). +- **Chat logs**: Must propagate deletion to **both hot storage and cold archive** (remote MySQL). A deletion pipeline must be designed and tested before launch. +- **Transaction records**: May be retained for up to 7 years for financial/legal compliance. The user's PII within transaction records should be anonymized where possible (replace name/email with a pseudonymous ID). +- **Stripe data**: Deletion requests must also be forwarded to Stripe; document the Stripe data deletion process. + +**Design requirement**: The deletion pipeline must handle cold archive propagation. This must be architected before launch — do not launch with cold archive data that cannot be systematically deleted on request. + +--- + +## 3. Data Portability + +Users may request an export of their personal data in a machine-readable format (JSON or CSV). The export must include: + +- Account information (username, email, registration date) +- Gameplay history and statistics +- Virtual currency transaction history (in-game) +- Chat history (within hot storage retention window) + +**Action required**: Build a data export endpoint. This endpoint must be accessible via account settings or by contacting support. Authenticated requests only. + +--- + +## 4. Consent + +- **Data collection consent**: Must be obtained at registration. The registration flow must include a clear reference to the Privacy Policy with an explicit acknowledgment. +- **Marketing / email consent**: Must be a separate, explicit opt-in checkbox at registration. Pre-checked boxes are not valid consent under GDPR. +- **Cookie consent**: EU visitors must receive a cookie consent banner. See Cookie Policy. +- **Consent records**: Timestamp and version of consent must be stored per user. + +--- + +## 5. Data Retention Limits + +GDPR requires that data is not retained longer than necessary. Documented retention periods per category: + +| Data Category | Retention Period | Basis | +|---|---|---| +| Account data | Until deletion + 30-day grace period | Contract | +| Gameplay stats | Until account deletion | Contract | +| Chat logs (hot) | 30 days | Legitimate Interest | +| Chat logs (cold) | [TBD — define before launch] | Legitimate Interest | +| Transaction records | 7 years | Legal Obligation | +| IP / server logs | 90 days | Legitimate Interest | +| Support tickets | 2 years from resolution | Legitimate Interest | + +**Action required**: Document and enforce retention periods with automated cleanup jobs. + +--- + +## 6. Data Processing Agreements (DPA) + +A DPA must be in place with any third-party processor that handles EU user data: + +- **Stripe, Inc.**: Stripe's DPA is available at stripe.com/legal/dpa. We must execute or accept it before processing EU user payments. +- **Hosting / Infrastructure provider(s)**: [TBD — identify provider and execute DPA] +- **Any analytics service**: [TBD — if applicable] + +**Action required**: Execute DPAs with all processors before accepting EU/EEA users. + +--- + +## 7. Chat Archive: Cold Storage Deletion Pipeline + +The chat archive design creates a specific GDPR challenge: data in cold storage (remote MySQL) must be reachable by deletion requests. + +**Design requirements before launch**: +1. Cold archive must be queryable by user ID (not just time range). +2. Deletion pipeline must issue delete or anonymize commands to cold storage, not just hot storage. +3. Deletion must be logged in the audit log (with anonymized user reference — do not block deletion by logging a deleted user's ID). +4. The deletion pipeline must be tested end-to-end before any EU users are admitted. + +--- + +## 8. Data Protection Contact + +Under GDPR, we must designate a contact point for data protection inquiries. A formal Data Protection Officer (DPO) may not be required for a company of our size, but a designated contact is required. + +- **Designated contact**: **[NAME or ROLE — TBD]** +- **Contact email**: **[PRIVACY CONTACT EMAIL]** +- This contact information must appear in the Privacy Policy. + +--- + +## 9. Admin Service and Audit Logs + +GDPR deletion requests must not be blocked by audit log entries referencing the deleted user. + +**Design rule**: When a user is deleted, audit log entries referencing that user must have the user reference anonymized (replace with a pseudonymous token or "deleted_user"), not deleted. This preserves audit integrity while complying with deletion requests. + +This requirement must be incorporated into the Admin service audit log design. + +--- + +## 10. Checklist + +- [ ] Finalize lawful basis mapping +- [ ] Implement data export (portability) endpoint +- [ ] Design and implement cold-archive deletion pipeline +- [ ] Execute Stripe DPA +- [ ] Execute hosting provider DPA(s) +- [ ] Implement consent flow at registration (data collection + marketing, separately) +- [ ] Implement cookie consent banner (see Cookie Policy) +- [ ] Designate Data Protection contact and publish in Privacy Policy +- [ ] Implement automated data retention cleanup jobs +- [ ] Audit log anonymization on user deletion +- [ ] Legal review by qualified attorney + +--- + +*This document is an internal compliance planning document and must be reviewed by a qualified attorney before EU/EEA users access the Services.* diff --git a/Shared/legal/payment-compliance.md b/Shared/legal/payment-compliance.md new file mode 100644 index 0000000..9a642a1 --- /dev/null +++ b/Shared/legal/payment-compliance.md @@ -0,0 +1,118 @@ +# Payment Compliance Notes + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Internal compliance checklist. Not a published legal document.** +> Must be reviewed by a qualified attorney and Stripe account reviewed before real-money features are enabled. + +--- + +## Overview + +AeternalisGames LLC intends to offer real-money purchases of virtual currency ("hard currency") through the Bazaar service. Payment processing will be handled by **Stripe, Inc.** This document tracks payment compliance requirements. + +**Current status**: Stripe integration is implemented in the Bazaar service but is **DISABLED**. Real-money features must not be enabled until all items in this checklist are resolved. + +--- + +## 1. Stripe Account Setup + +- [ ] Create a Stripe account under the AeternalisGames LLC legal entity. +- [ ] Accept Stripe's Terms of Service. +- [ ] Determine account type: Standard Stripe account vs. Stripe Connect (Connected Accounts). Standard is appropriate if AeternalisGames LLC is the sole merchant. Stripe Connect is needed for marketplace/platform models. +- [ ] Complete Stripe identity verification (business entity, EIN, beneficial owner details as required by KYC/AML regulations). +- [ ] Configure Stripe webhook endpoints for payment confirmation and failure events. + +--- + +## 2. PCI DSS Compliance + +Stripe handles all payment card processing. AeternalisGames LLC must: + +- **Never transmit or store raw card numbers on our servers.** All card data must flow exclusively through Stripe's frontend (Stripe.js / Stripe Elements / Stripe Checkout). +- Our PCI DSS scope is **SAQ A** (Self-Assessment Questionnaire A), which is the minimum scope applicable to merchants who fully outsource card processing to a compliant third party like Stripe. +- **Confirm**: No card data (card number, CVV, expiry) ever touches AeternalisGames servers. If it does at any point, scope escalates significantly. +- Complete and retain the SAQ A annually once live. + +--- + +## 3. Refund Policy + +Defined refund rules: + +- **Hard currency purchases** (real money for virtual currency): Final sale. No refunds except: + - Technical failure that prevents delivery of purchased currency (e.g., server error during fulfillment). + - Cases required by applicable law (e.g., EU consumer rights, where applicable). +- **Chargeback handling**: A chargeback may result in account suspension pending investigation. +- **Voluntary refunds**: Issued at sole discretion of AeternalisGames LLC. Repeated refund requests may result in account restrictions. + +This policy must be clearly stated in the Terms of Service and at the point of purchase. + +--- + +## 4. Subscription vs. One-Time Purchases + +- At launch: **One-time purchases only** (no recurring subscriptions). +- This simplifies compliance (no recurring billing consent requirements, no subscription cancellation flows). +- Subscription billing should not be introduced without a dedicated compliance review. + +--- + +## 5. Age Gate for Real-Money Purchases + +- Real-money purchases must be restricted to users who are **18 years of age or older** (or the legal age of majority in their jurisdiction). +- Date of birth must be collected at registration and verified before purchase is permitted. +- A front-end age gate must be implemented in the Bazaar purchase flow. +- Server-side enforcement: The Bazaar service must validate the user's age against their stored date of birth before processing any real-money transaction. + +--- + +## 6. Regional Restrictions + +Certain jurisdictions restrict or prohibit virtual currency purchases or loot box mechanics: + +| Jurisdiction | Issue | Action Required | +|---|---|---| +| Belgium | Loot boxes classified as gambling; banned for minors, restricted for adults | Block real-money loot box purchases for Belgian users | +| Netherlands | Loot boxes with tradeable items banned | Review if applicable; block if items are tradeable | +| [Others TBD] | Various gambling/virtual currency laws | Review before global launch | + +**Action required**: Conduct a regional legal review before enabling real-money features globally. Implement geo-based purchase blocking where required. + +--- + +## 7. Currency Display and Transparency + +- The real-money cost of all hard currency packages must be clearly displayed before purchase. +- The value or purchasing power of virtual currency should be reasonably clear (e.g., what you can buy with X shards). +- Avoid manipulative pricing patterns (e.g., obscuring the real cost through currency conversion layers). + +--- + +## 8. Tax Considerations + +- **US sales tax**: Determine whether digital goods / virtual currency are taxable in jurisdictions where users are located. Stripe Tax may be used to automate tax calculation and collection. Consult with a tax professional. +- **VAT (EU/UK)**: Digital services sold to EU/UK consumers are subject to VAT. Stripe handles VAT collection for digital goods in many jurisdictions. + +**Action required**: Tax obligation review before enabling real-money features. + +--- + +## 9. Checklist + +- [ ] Create and verify Stripe account under AeternalisGames LLC +- [ ] Accept Stripe Terms of Service and execute DPA (if EU users) +- [ ] Confirm no card data touches AeternalisGames servers (PCI SAQ A scope) +- [ ] Complete SAQ A (once live) +- [ ] Implement age gate (18+) in Bazaar purchase flow — frontend and backend +- [ ] Finalize and publish refund policy in TOS +- [ ] Regional restriction review (Belgium, Netherlands, etc.) +- [ ] Tax obligation review (US sales tax, EU VAT) +- [ ] Configure Stripe webhooks for payment events +- [ ] End-to-end payment integration test in Stripe test mode before going live +- [ ] Enable Stripe integration in Bazaar service only after all above are complete + +--- + +*This document is an internal compliance planning document and must be reviewed by a qualified attorney before real-money features are enabled.* diff --git a/Shared/legal/privacy-policy.md b/Shared/legal/privacy-policy.md new file mode 100644 index 0000000..0a9b1d5 --- /dev/null +++ b/Shared/legal/privacy-policy.md @@ -0,0 +1,175 @@ +# Privacy Policy + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Not yet reviewed by legal counsel. Do not publish.** + +--- + +## 1. Introduction + +AeternalisGames LLC ("Company," "we," "us," "our") is committed to protecting your privacy. This Privacy Policy explains how we collect, use, store, and share your personal information when you use Shards of Rathe and our associated services, websites, and applications (collectively, the "Services"). + +By using the Services, you agree to the collection and use of information in accordance with this policy. + +--- + +## 2. Information We Collect + +We collect the following categories of data: + +### 2.1 Account Data +- Username and display name +- Email address +- Password (stored as a secure hash; we never store plaintext passwords) +- Date of birth (for age verification) +- Account creation date and last login + +### 2.2 Gameplay Data +- Match history, game results, rankings, and statistics +- In-game actions, decisions, and behavioral patterns +- Virtual currency balances and transaction history (in-game) +- Card collection and deck configurations + +### 2.3 Technical / Device Data +- IP address +- Device type, operating system, and version +- Game client version +- Connection timestamps and session duration +- Server logs and error reports + +### 2.4 Communications +- Chat messages sent through in-game chat systems +- Support tickets and correspondence with our team + +### 2.5 Payment Data +- Payment processing is handled by **Stripe, Inc.** We do **not** store raw payment card numbers on our servers. We receive and retain: + - Transaction identifiers + - Purchase amounts and timestamps + - Stripe customer ID + - Last 4 digits of card (as provided by Stripe for display purposes) + +--- + +## 3. How We Use Your Information + +We use collected data to: + +- Provide, operate, and improve the Services +- Authenticate users and maintain account security +- Process payments through Stripe +- Detect and prevent cheating, fraud, and abuse +- Enforce our Terms of Service and EULA +- Respond to support requests +- Send service-related notifications (account activity, policy updates) +- Analyze gameplay trends to balance and improve game design +- Comply with legal obligations + +We do **not** use your data for targeted advertising or sell it to third parties for marketing purposes. + +--- + +## 4. Chat Log Retention Policy + +- **Hot storage**: Chat logs are retained in active/queryable storage for **30 days** from the date of the message. This supports moderation, player reports, and abuse investigations. +- **Cold archive**: After 30 days, chat logs may be moved to long-term cold storage (remote MySQL archive) for a period of **[X months/years — TBD]** for legal, safety, and moderation audit purposes. +- **Access**: Cold-archived chat logs are accessed only by authorized personnel for abuse investigations or legal compliance purposes. +- **Deletion**: Upon a verified right-to-erasure request (see Section 8), chat logs in both hot and cold storage will be deleted or anonymized within **30 days** of the request. + +--- + +## 5. Data Retention + +| Data Category | Retention Period | +|---|---| +| Account data | Until account deletion + 30 days | +| Gameplay statistics | Until account deletion | +| Chat logs (hot) | 30 days from message date | +| Chat logs (cold archive) | [TBD — to be defined before launch] | +| Transaction records | 7 years (legal/financial requirement) | +| IP logs / server logs | 90 days | +| Support correspondence | 2 years from resolution | + +Note: Transaction records may be retained longer than account data for financial and legal compliance reasons even after an account deletion request. + +--- + +## 6. Data Sharing + +We share data only in the following circumstances: + +- **Stripe**: Payment processing. Stripe's privacy policy applies to data they process. +- **Infrastructure providers**: Hosting, database, and CDN providers operate under data processing agreements. +- **Legal compliance**: We may disclose data when required by law, court order, or to protect the safety of users or the public. +- **Business transfers**: In the event of a merger, acquisition, or asset sale, user data may be transferred. We will notify users before this occurs. + +We do **not** sell your personal information to third parties. + +--- + +## 7. Data Security + +We implement reasonable technical and organizational measures to protect your personal data, including: + +- Encrypted transmission (TLS/HTTPS) +- Hashed password storage +- Access controls limiting data access to authorized personnel +- Regular security reviews + +No system is perfectly secure. In the event of a data breach affecting your personal information, we will notify affected users as required by applicable law. + +--- + +## 8. Your Rights + +Depending on your location, you may have the following rights: + +- **Access**: Request a copy of the personal data we hold about you. +- **Correction**: Request correction of inaccurate data. +- **Deletion (Right to be Forgotten)**: Request deletion of your personal data. Note: Transaction records may be retained for legal/financial reasons even after deletion. +- **Portability**: Request your data in a structured, machine-readable format. +- **Opt-out of marketing**: Unsubscribe from any marketing communications at any time. + +To exercise any of these rights, contact us at: **[PRIVACY CONTACT EMAIL]** + +We will respond to verified requests within **30 days**. + +--- + +## 9. Children's Privacy + +The Services are not directed to children under the age of 13. We do not knowingly collect personal information from children under 13. If you believe we have inadvertently collected data from a child under 13, please contact us immediately at **[PRIVACY CONTACT EMAIL]** and we will delete that information. + +--- + +## 10. Cookies and Tracking + +See our separate **Cookie Policy** for details on how we use cookies and similar tracking technologies on our website. + +--- + +## 11. International Transfers + +Your data may be processed and stored in the **United States**. If you are located in the EU/EEA or another jurisdiction with data transfer restrictions, your data may be transferred to the US under appropriate safeguards (e.g., Standard Contractual Clauses where applicable). + +--- + +## 12. Changes to This Policy + +We may update this Privacy Policy from time to time. We will notify you of material changes by email or via an in-game notification. The updated policy will be effective from the "Last Updated" date at the top of this document. + +--- + +## 13. Contact + +For privacy-related requests or questions: + +AeternalisGames LLC +**[ADDRESS]** +Email: **[PRIVACY CONTACT EMAIL]** +Data Protection Contact: **[NAME or ROLE]** + +--- + +*This Privacy Policy is a draft and must be reviewed by a qualified attorney before publication.* diff --git a/Shared/legal/terms-of-service.md b/Shared/legal/terms-of-service.md new file mode 100644 index 0000000..56eb229 --- /dev/null +++ b/Shared/legal/terms-of-service.md @@ -0,0 +1,148 @@ +# Terms of Service + +**AeternalisGames LLC** +**Last Updated: [DATE]** + +> **DRAFT — Not yet reviewed by legal counsel. Do not publish.** + +--- + +## 1. Acceptance of Terms + +By accessing or using any game, service, website, or software provided by AeternalisGames LLC ("Company," "we," "us," or "our"), including Shards of Rathe and any associated services (collectively, the "Services"), you ("User," "you") agree to be bound by these Terms of Service ("TOS"). If you do not agree to these terms, do not use the Services. + +These Terms constitute a legally binding agreement between you and AeternalisGames LLC. + +--- + +## 2. Eligibility and Age Requirements + +- You must be at least **13 years of age** to use the Services. +- You must be at least **18 years of age** (or the age of majority in your jurisdiction, whichever is greater) to make real-money purchases. +- If you are between 13 and 18, you may only use the Services with verifiable parental or guardian consent. +- By using the Services, you represent that you meet these age requirements. + +--- + +## 3. Account Registration and Security + +- You must create an account to access most features of the Services. +- You are responsible for maintaining the confidentiality of your account credentials. +- You are responsible for all activity that occurs under your account. +- You must notify us immediately at **[CONTACT EMAIL]** if you suspect unauthorized access to your account. +- We reserve the right to terminate accounts that violate these Terms. + +--- + +## 4. Prohibited Conduct + +You agree not to: + +- Use cheats, exploits, automation software, bots, hacks, mods, or any unauthorized third-party software that modifies or interacts with the Services. +- Engage in harassment, abuse, hate speech, discrimination, or threats toward other users. +- Impersonate any person, entity, or AeternalisGames LLC staff. +- Attempt to reverse engineer, decompile, or disassemble any part of the Services. +- Sell, trade, or transfer your account to another person. +- Use the Services for any commercial purpose without our written consent. +- Exploit bugs or glitches rather than reporting them; repeated exploitation may result in termination. +- Engage in any activity that disrupts, damages, or impairs the Services or other users' experience. +- Violate any applicable local, national, or international law. + +--- + +## 5. Bannable Offenses + +The following conduct may result in permanent account suspension without prior warning: + +- Use of cheat software, aimbots, or any client-side modification that provides an unfair advantage. +- Real-money trading (RMT) of in-game items or currency outside of authorized systems. +- Severe or repeated harassment, hate speech, or threats. +- Chargebacks or payment fraud. +- Exploiting critical bugs after being warned. +- Account sharing in ranked or competitive modes (if applicable). + +Lesser violations may result in temporary suspensions at our discretion. We are not required to disclose the specific evidence behind enforcement decisions. + +--- + +## 6. Virtual Currency and In-Game Items + +- The Services may include virtual currency ("Shards" or other named currency) and virtual items. +- Virtual currency and items have **no real-world monetary value** and cannot be redeemed for cash. +- Virtual currency purchased with real money is **non-refundable** except as required by applicable law. +- Virtual currency earned through gameplay is not subject to any refund. +- We reserve the right to modify, adjust, or discontinue virtual currency and items at any time. +- Stripe purchase refund policy: Real-money purchases are final. Refunds may be issued at our sole discretion for technical failures preventing access to purchased content. See Section 10 for payment details. + +--- + +## 7. Content Ownership + +- AeternalisGames LLC retains all intellectual property rights in the Services, including all game content, art, audio, code, and design. +- You retain ownership of any original content you create and submit (e.g., forum posts, usernames), but you grant AeternalisGames LLC a worldwide, royalty-free, perpetual license to use, display, and distribute such content in connection with the Services. +- You may not reproduce, distribute, or create derivative works from our content without written permission. + +--- + +## 8. Service Availability + +- We do not guarantee uninterrupted or error-free access to the Services. +- We may modify, suspend, or discontinue the Services (or any portion thereof) at any time with or without notice. +- We are not liable for any loss or damage arising from service interruptions, maintenance, or discontinuation. + +--- + +## 9. Suspension and Termination + +- We may suspend or terminate your account at any time for violation of these Terms. +- You may terminate your account by contacting us at **[CONTACT EMAIL]**. +- Upon termination, your right to use the Services ceases immediately. Virtual currency and items are forfeited and not refundable. +- Sections that by their nature should survive termination will survive (including Sections 7, 11, 12, 13). + +--- + +## 10. Payments + +- Real-money purchases are processed by Stripe, Inc. By making a purchase, you also agree to Stripe's terms of service. +- All prices are in USD unless otherwise stated. +- We reserve the right to change prices at any time. +- Real-money purchases are final. Refunds are handled on a case-by-case basis. +- Age gate: Real-money purchases require users to be at least 18 years of age (or the legal age of majority in their jurisdiction). + +--- + +## 11. Disclaimer of Warranties + +THE SERVICES ARE PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WE DO NOT WARRANT THAT THE SERVICES WILL BE UNINTERRUPTED, SECURE, OR ERROR-FREE. + +--- + +## 12. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, AETERNALISGAMES LLC AND ITS OFFICERS, DIRECTORS, EMPLOYEES, AND AGENTS SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES ARISING FROM YOUR USE OF OR INABILITY TO USE THE SERVICES, EVEN IF WE HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. OUR TOTAL LIABILITY TO YOU FOR ANY CLAIM ARISING FROM THESE TERMS OR THE SERVICES SHALL NOT EXCEED THE GREATER OF (A) $100 USD OR (B) THE AMOUNT YOU PAID TO US IN THE SIX MONTHS PRECEDING THE CLAIM. + +--- + +## 13. Governing Law and Dispute Resolution + +- These Terms are governed by the laws of the **State of [STATE], United States**, without regard to conflict of law principles. +- Any dispute arising from these Terms or the Services shall be resolved by binding arbitration in **[CITY, STATE]** under the rules of the American Arbitration Association, except that either party may seek injunctive relief in court for intellectual property violations. +- **Class action waiver**: You agree to resolve disputes individually, not as part of a class or representative action. + +--- + +## 14. Changes to These Terms + +We may modify these Terms at any time. We will notify users of material changes via email or in-game notification. Continued use of the Services after changes take effect constitutes acceptance of the new Terms. + +--- + +## 15. Contact + +AeternalisGames LLC +**[ADDRESS]** +Email: **[LEGAL CONTACT EMAIL]** + +--- + +*These Terms of Service are a draft and must be reviewed by a qualified attorney before publication.*