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