820 lines
26 KiB
Markdown
820 lines
26 KiB
Markdown
extends CanvasLayer
|
|
|
|
const WORLD_RUNTIME_FLAG := "application/config/world_runtime_enabled"
|
|
const WORLD_DEBUG_PAYWALL_FLAG := "application/config/world_debug_show_paywalls"
|
|
const MOVE_SEND_INTERVAL_MS := 100
|
|
const LOCAL_MOVE_SPEED := 160.0
|
|
const VISUAL_RECONCILE_RATE := 4.0
|
|
const VISUAL_SNAP_DISTANCE := 256.0
|
|
|
|
@onready var return_to_hub_btn = $Control/Panel/VBoxContainer/ReturnToHubBtn
|
|
@onready var status_label = $Control/Panel/VBoxContainer/StatusLabel
|
|
@onready var mode_label = $Control/Panel/VBoxContainer/ModeLabel
|
|
@onready var connect_btn = $Control/Panel/VBoxContainer/ConnectBtn
|
|
@onready var world_bg = $ColorRect
|
|
@onready var menu_control = $Control
|
|
@onready var menu_panel = $Control/Panel
|
|
|
|
var runtime = null
|
|
var world_root: Node2D = null
|
|
var visual_renderer: VisualTileMapRenderer = null
|
|
var paywall_overlay: Node2D = null
|
|
var tile_fallback_overlay: Node2D = null
|
|
var object_container: Node2D = null
|
|
var npc_container: Node2D = null
|
|
var players_container: Node2D = null
|
|
var player_marker: Node2D = null
|
|
var world_camera: Camera2D = null
|
|
var npc_scene: PackedScene = null
|
|
var player_scene: PackedScene = null
|
|
var other_player_scene: PackedScene = null
|
|
var self_player_node: Node2D = null
|
|
var other_player_nodes: Dictionary = {} # id -> Node2D
|
|
var _show_paywall_debug: bool = false
|
|
var _last_move_send_ms: int = 0
|
|
var _object_texture_cache: Dictionary = {}
|
|
var _last_move_vec: Vector2 = Vector2.ZERO
|
|
var _last_world_input_log_ms: int = 0
|
|
var _was_visible: bool = true
|
|
var _last_sent_move_vec: Vector2 = Vector2.ZERO
|
|
var _last_sent_facing: String = ""
|
|
var _render_self_position: Vector2 = Vector2.ZERO
|
|
var _has_render_self_position: bool = false
|
|
|
|
func _ready():
|
|
if return_to_hub_btn:
|
|
return_to_hub_btn.pressed.connect(_on_return_to_hub_pressed)
|
|
if connect_btn:
|
|
connect_btn.pressed.connect(_on_connect_pressed)
|
|
if GameState:
|
|
GameState.state_changed.connect(_on_game_state_changed)
|
|
|
|
_init_world_nodes()
|
|
_setup_runtime()
|
|
_was_visible = visible
|
|
|
|
func _input(event: InputEvent):
|
|
if runtime == null:
|
|
return
|
|
if runtime.mode != runtime.MODE_ACTIVE_WORLD:
|
|
return
|
|
if event.is_action_pressed("escape_menu"):
|
|
if menu_panel:
|
|
menu_panel.visible = not menu_panel.visible
|
|
if world_bg:
|
|
world_bg.visible = menu_panel.visible
|
|
get_viewport().set_input_as_handled()
|
|
|
|
func _on_return_to_hub_pressed():
|
|
if GameState and GameState.has_method("return_to_hub_from_world"):
|
|
GameState.return_to_hub_from_world()
|
|
|
|
func _process(delta: float):
|
|
var is_now_visible = visible
|
|
if _was_visible != is_now_visible:
|
|
_was_visible = is_now_visible
|
|
if not is_now_visible:
|
|
# When this screen is hidden (state switched away), clear all world runtime/UI state.
|
|
_reset_world_session()
|
|
|
|
if runtime == null:
|
|
return
|
|
if runtime.mode != runtime.MODE_ACTIVE_WORLD:
|
|
return
|
|
_handle_world_input(delta)
|
|
_update_render_self_position(delta)
|
|
_sync_player_marker()
|
|
|
|
func _setup_runtime():
|
|
var enabled = ProjectSettings.get_setting(WORLD_RUNTIME_FLAG, true)
|
|
if not enabled:
|
|
if status_label:
|
|
status_label.text = "World runtime disabled by feature flag."
|
|
if mode_label:
|
|
mode_label.text = "Mode: disabled"
|
|
if connect_btn:
|
|
connect_btn.disabled = true
|
|
return
|
|
|
|
var runtime_script = load("res://scripts/world/world_runtime_client.gd")
|
|
runtime = runtime_script.new()
|
|
add_child(runtime)
|
|
runtime.mode_changed.connect(_on_mode_changed)
|
|
runtime.chunk_refresh_required.connect(_on_chunk_refresh_required)
|
|
runtime.chunk_updated.connect(_on_chunk_updated)
|
|
runtime.chunk_unloaded.connect(_on_chunk_unloaded)
|
|
runtime.set_mode(runtime.MODE_CONNECTING)
|
|
if GameState:
|
|
GameState.world_spawn_received.connect(_on_world_spawn_received)
|
|
GameState.world_state_received.connect(_on_world_state_received)
|
|
GameState.world_despawn_received.connect(_on_world_despawn_received)
|
|
if status_label:
|
|
status_label.text = "World runtime ready. Connect to request spawn."
|
|
|
|
func _on_connect_pressed():
|
|
if runtime == null:
|
|
return
|
|
if runtime.mode == runtime.MODE_AWAITING_SPAWN or runtime.mode == runtime.MODE_ACTIVE_WORLD:
|
|
return
|
|
runtime.set_mode(runtime.MODE_AWAITING_SPAWN)
|
|
if status_label:
|
|
status_label.text = "Awaiting world spawn from server..."
|
|
if GameState and GameState.has_method("request_world_spawn"):
|
|
GameState.request_world_spawn()
|
|
|
|
func _on_mode_changed(mode: String):
|
|
if mode_label:
|
|
mode_label.text = "Mode: %s" % mode
|
|
if connect_btn:
|
|
connect_btn.disabled = (mode == runtime.MODE_AWAITING_SPAWN or mode == runtime.MODE_ACTIVE_WORLD)
|
|
connect_btn.text = "Connected" if mode == runtime.MODE_ACTIVE_WORLD else "Connect World"
|
|
if menu_panel:
|
|
menu_panel.visible = mode != runtime.MODE_ACTIVE_WORLD
|
|
if world_bg:
|
|
world_bg.visible = mode != runtime.MODE_ACTIVE_WORLD
|
|
|
|
func _on_chunk_refresh_required(chunk_key: String):
|
|
if status_label:
|
|
status_label.text = "Chunk refresh required: %s" % chunk_key
|
|
|
|
func _on_world_spawn_received(data: Dictionary):
|
|
if runtime == null:
|
|
return
|
|
runtime.apply_spawn(data)
|
|
_render_self_position = Vector2(
|
|
float(runtime.self_player.get("x", 0.0)),
|
|
float(runtime.self_player.get("y", 0.0))
|
|
)
|
|
_has_render_self_position = true
|
|
_rebuild_world_visuals()
|
|
_rebuild_world_entities()
|
|
_ensure_self_player_node()
|
|
_update_player_entities()
|
|
_sync_player_marker()
|
|
# Spawn means world is active; force-hide menu in case stale UI toggles survived.
|
|
if menu_panel:
|
|
menu_panel.visible = false
|
|
if world_bg:
|
|
world_bg.visible = false
|
|
if status_label:
|
|
if runtime.chunk_cache.is_empty():
|
|
status_label.text = "World spawn received (no chunks in payload)."
|
|
else:
|
|
status_label.text = "World spawn received."
|
|
|
|
func _on_world_state_received(data: Dictionary):
|
|
if runtime == null:
|
|
return
|
|
runtime.apply_world_state(data)
|
|
_update_player_entities()
|
|
_sync_player_marker()
|
|
#_rebuild_world_entities()
|
|
|
|
func _on_world_despawn_received(data: Dictionary):
|
|
if runtime == null:
|
|
return
|
|
runtime.set_mode(runtime.MODE_RECOVERING)
|
|
if status_label:
|
|
status_label.text = "World despawned: %s" % str(data.get("reason", "unknown"))
|
|
if connect_btn:
|
|
connect_btn.disabled = false
|
|
connect_btn.text = "Connect World"
|
|
_clear_player_entities()
|
|
|
|
func _on_game_state_changed(state: String):
|
|
if state == "WORLD":
|
|
# Always start world scene from a clean baseline before new connect/spawn.
|
|
_reset_world_session()
|
|
_prepare_world_entry_ui()
|
|
return
|
|
# Any non-world state should fully reset world session/UI to prevent stale re-entry.
|
|
_reset_world_session()
|
|
|
|
func _on_chunk_updated(_chunk_key: String):
|
|
_rebuild_world_visuals()
|
|
_rebuild_world_entities()
|
|
|
|
func _on_chunk_unloaded(_chunk_key: String):
|
|
_rebuild_world_visuals()
|
|
_rebuild_world_entities()
|
|
|
|
func _init_world_nodes():
|
|
_show_paywall_debug = bool(ProjectSettings.get_setting(WORLD_DEBUG_PAYWALL_FLAG, false))
|
|
|
|
world_root = Node2D.new()
|
|
world_root.name = "WorldRoot"
|
|
add_child(world_root)
|
|
# Keep world above background but below menu/control.
|
|
var target_index = 1 if world_bg != null else 0
|
|
move_child(world_root, target_index)
|
|
|
|
visual_renderer = VisualTileMapRenderer.new()
|
|
visual_renderer.name = "WorldVisualRenderer"
|
|
world_root.add_child(visual_renderer)
|
|
|
|
paywall_overlay = Node2D.new()
|
|
paywall_overlay.name = "PaywallOverlay"
|
|
paywall_overlay.z_index = 5
|
|
world_root.add_child(paywall_overlay)
|
|
|
|
tile_fallback_overlay = Node2D.new()
|
|
tile_fallback_overlay.name = "TileFallbackOverlay"
|
|
tile_fallback_overlay.z_index = 2
|
|
world_root.add_child(tile_fallback_overlay)
|
|
|
|
object_container = Node2D.new()
|
|
object_container.name = "WorldObjects"
|
|
object_container.z_index = 20
|
|
world_root.add_child(object_container)
|
|
|
|
npc_container = Node2D.new()
|
|
npc_container.name = "WorldNpcs"
|
|
npc_container.z_index = 30
|
|
world_root.add_child(npc_container)
|
|
|
|
players_container = Node2D.new()
|
|
players_container.name = "WorldPlayers"
|
|
players_container.z_index = 35
|
|
world_root.add_child(players_container)
|
|
|
|
player_marker = Node2D.new()
|
|
player_marker.name = "SelfPlayer"
|
|
player_marker.z_index = 40
|
|
world_root.add_child(player_marker)
|
|
_create_player_marker_visual()
|
|
|
|
world_camera = Camera2D.new()
|
|
world_camera.name = "WorldCamera"
|
|
world_camera.enabled = true
|
|
world_camera.zoom = Vector2(1.3, 1.3)
|
|
world_root.add_child(world_camera)
|
|
|
|
if ResourceLoader.exists("res://scenes/dungeon/mob.tscn"):
|
|
npc_scene = load("res://scenes/dungeon/mob.tscn")
|
|
if ResourceLoader.exists("res://scenes/dungeon/player.tscn"):
|
|
player_scene = load("res://scenes/dungeon/player.tscn")
|
|
if ResourceLoader.exists("res://scenes/dungeon/other_player.tscn"):
|
|
other_player_scene = load("res://scenes/dungeon/other_player.tscn")
|
|
|
|
func _create_player_marker_visual():
|
|
for child in player_marker.get_children():
|
|
child.queue_free()
|
|
var sprite = Sprite2D.new()
|
|
if SpriteGenerator:
|
|
sprite.texture = SpriteGenerator.get_circle()
|
|
sprite.modulate = Color(0.35, 0.9, 1.0, 1.0)
|
|
sprite.scale = Vector2(0.8, 0.8)
|
|
else:
|
|
var poly = Polygon2D.new()
|
|
poly.polygon = PackedVector2Array([
|
|
Vector2(-12, -12),
|
|
Vector2(12, -12),
|
|
Vector2(12, 12),
|
|
Vector2(-12, 12)
|
|
])
|
|
poly.color = Color(0.35, 0.9, 1.0, 1.0)
|
|
player_marker.add_child(poly)
|
|
return
|
|
player_marker.add_child(sprite)
|
|
|
|
func _sync_player_marker():
|
|
if runtime == null:
|
|
return
|
|
if not _has_render_self_position:
|
|
_render_self_position = Vector2(
|
|
float(runtime.self_player.get("x", 0.0)),
|
|
float(runtime.self_player.get("y", 0.0))
|
|
)
|
|
_has_render_self_position = true
|
|
var x = _render_self_position.x
|
|
var y = _render_self_position.y
|
|
if world_root:
|
|
var viewport_center = get_viewport().get_visible_rect().size * 0.5
|
|
world_root.position = viewport_center - Vector2(x, y)
|
|
if world_camera:
|
|
world_camera.position = Vector2(x, y)
|
|
if self_player_node and is_instance_valid(self_player_node):
|
|
if player_marker:
|
|
player_marker.visible = false
|
|
self_player_node.position = Vector2(x, y)
|
|
if self_player_node.has_method("set_player_name"):
|
|
self_player_node.set_player_name(str(runtime.self_player.get("name", "You")))
|
|
if self_player_node.has_method("update_health"):
|
|
var hp = int(runtime.self_player.get("health", 100))
|
|
var max_hp = int(runtime.self_player.get("maxHealth", runtime.self_player.get("max_health", 100)))
|
|
self_player_node.update_health(hp, max_hp)
|
|
if self_player_node.has_method("set_movement"):
|
|
self_player_node.set_movement(_last_move_vec)
|
|
return
|
|
if player_marker:
|
|
player_marker.visible = true
|
|
player_marker.position = Vector2(x, y)
|
|
|
|
func _update_render_self_position(delta: float):
|
|
if runtime == null:
|
|
return
|
|
var auth_pos = Vector2(
|
|
float(runtime.self_player.get("x", 0.0)),
|
|
float(runtime.self_player.get("y", 0.0))
|
|
)
|
|
if not _has_render_self_position:
|
|
_render_self_position = auth_pos
|
|
_has_render_self_position = true
|
|
return
|
|
|
|
# Dungeon-like local render prediction while keeping server authoritative position as truth.
|
|
var predicted = _render_self_position + (_last_move_vec * LOCAL_MOVE_SPEED * delta)
|
|
var error = auth_pos - predicted
|
|
if error.length() > VISUAL_SNAP_DISTANCE:
|
|
_render_self_position = auth_pos
|
|
return
|
|
var alpha = min(1.0, delta * VISUAL_RECONCILE_RATE)
|
|
_render_self_position = predicted + (error * alpha)
|
|
|
|
func _handle_world_input(delta: float):
|
|
var move_x = Input.get_axis("move_left", "move_right")
|
|
var move_y = Input.get_axis("move_up", "move_down")
|
|
var movement = Vector2(move_x, move_y)
|
|
if movement.length() > 1.0:
|
|
movement = movement.normalized()
|
|
|
|
var is_vip = bool(runtime.self_player.get("isVip", false))
|
|
var current_pos = Vector2(
|
|
float(runtime.self_player.get("x", 0.0)),
|
|
float(runtime.self_player.get("y", 0.0))
|
|
)
|
|
var target_pos = current_pos + movement * LOCAL_MOVE_SPEED * delta
|
|
|
|
# Keep world movement server-authoritative to avoid rubber-banding.
|
|
# We still evaluate local blocking to avoid sending obviously invalid movement spam.
|
|
if movement.length() > 0.0:
|
|
var target_tile_x = int(floor(target_pos.x / float(runtime.TILE_SIZE)))
|
|
var target_tile_y = int(floor(target_pos.y / float(runtime.TILE_SIZE)))
|
|
var blocked = runtime.is_target_tile_blocked(target_tile_x, target_tile_y, is_vip)
|
|
if blocked:
|
|
movement = Vector2.ZERO
|
|
_last_move_vec = movement
|
|
|
|
var now_ms = Time.get_ticks_msec()
|
|
var facing = _movement_to_facing(movement)
|
|
var is_running = Input.is_key_pressed(KEY_SHIFT)
|
|
var time_since_last = now_ms - _last_move_send_ms
|
|
var moved_changed = movement != _last_sent_move_vec
|
|
var facing_changed = facing != _last_sent_facing
|
|
var should_send = moved_changed \
|
|
or (movement.length() > 0.0 and time_since_last >= MOVE_SEND_INTERVAL_MS) \
|
|
or (facing_changed and movement.length() > 0.0)
|
|
|
|
if not should_send:
|
|
return
|
|
|
|
var seq = runtime.next_input_seq()
|
|
GameState.send_world_input(
|
|
seq,
|
|
movement.x,
|
|
movement.y,
|
|
is_running,
|
|
facing
|
|
)
|
|
_last_move_send_ms = now_ms
|
|
_last_sent_move_vec = movement
|
|
_last_sent_facing = facing
|
|
if movement.length() > 0.0 and now_ms - _last_world_input_log_ms > 500:
|
|
_last_world_input_log_ms = now_ms
|
|
print("[World] INPUT seq=%d move=(%.2f,%.2f) pos=(%.1f,%.1f) run=%s" % [
|
|
seq,
|
|
movement.x,
|
|
movement.y,
|
|
float(runtime.self_player.get("x", 0.0)),
|
|
float(runtime.self_player.get("y", 0.0)),
|
|
str(is_running)
|
|
])
|
|
|
|
func _movement_to_facing(movement: Vector2) -> String:
|
|
if movement.length() < 0.001:
|
|
return ""
|
|
if absf(movement.x) >= absf(movement.y):
|
|
return "right" if movement.x > 0.0 else "left"
|
|
return "down" if movement.y > 0.0 else "up"
|
|
|
|
func _rebuild_world_visuals():
|
|
if runtime == null or visual_renderer == null:
|
|
return
|
|
|
|
if paywall_overlay:
|
|
_clear_children(paywall_overlay)
|
|
if tile_fallback_overlay:
|
|
_clear_children(tile_fallback_overlay)
|
|
|
|
var sheets = runtime.tile_sheets.duplicate(true)
|
|
var available_sheet_ids: Dictionary = {}
|
|
for s in sheets:
|
|
available_sheet_ids[int(s.get("id", 0))] = true
|
|
var visual_tiles: Array = []
|
|
|
|
for key in runtime.chunk_cache:
|
|
var chunk_data = runtime.chunk_cache[key]
|
|
var zone_x = int(chunk_data.get("zoneX", 0))
|
|
var zone_y = int(chunk_data.get("zoneY", 0))
|
|
var chunk_x = int(chunk_data.get("chunkX", 0))
|
|
var chunk_y = int(chunk_data.get("chunkY", 0))
|
|
|
|
for tile in chunk_data.get("tiles", []):
|
|
var local_tile_x = int(tile.get("x", tile.get("tileX", 0)))
|
|
var local_tile_y = int(tile.get("y", tile.get("tileY", 0)))
|
|
var world_tile_x = runtime.world_tile_x(zone_x, chunk_x, local_tile_x)
|
|
var world_tile_y = runtime.world_tile_y(zone_y, chunk_y, local_tile_y)
|
|
var sheet_id = int(tile.get("sid", tile.get("sheetId", 0)))
|
|
var frame_index = int(tile.get("frame", tile.get("frameIndex", 0)))
|
|
|
|
visual_tiles.append({
|
|
"x": world_tile_x,
|
|
"y": world_tile_y,
|
|
"l": int(tile.get("l", 0)),
|
|
"sid": sheet_id,
|
|
"frame": frame_index,
|
|
"fx": bool(tile.get("fx", false)),
|
|
"fy": bool(tile.get("fy", false)),
|
|
"r": int(tile.get("r", 0))
|
|
})
|
|
|
|
if _show_paywall_debug and bool(tile.get("isInvisiblePaywall", false)):
|
|
_add_paywall_debug_overlay(world_tile_x, world_tile_y)
|
|
if not available_sheet_ids.has(sheet_id) and _fallback_sheet_path(sheet_id).is_empty():
|
|
_add_fallback_tile_overlay(world_tile_x, world_tile_y, sheet_id)
|
|
|
|
# Render textured tiles when sheet metadata exists.
|
|
if sheets.is_empty():
|
|
sheets = _build_fallback_world_sheets(visual_tiles)
|
|
if sheets.size() > 0:
|
|
visual_renderer.render_visual_tiles({
|
|
"sheets": sheets,
|
|
"tiles": visual_tiles
|
|
})
|
|
else:
|
|
visual_renderer.clear_tiles()
|
|
|
|
func _build_fallback_world_sheets(visual_tiles: Array) -> Array:
|
|
# WORLD_SPAWN payload currently sends sheetId/frameIndex but not sheet metadata.
|
|
# Build a local fallback catalog so VisualTileMapRenderer can render.
|
|
var used_sheet_ids: Dictionary = {}
|
|
for t in visual_tiles:
|
|
used_sheet_ids[int(t.get("sid", 0))] = true
|
|
|
|
var fallback_defs: Array = []
|
|
for sid in used_sheet_ids.keys():
|
|
var sheet_id = int(sid)
|
|
var path = _fallback_sheet_path(sheet_id)
|
|
if path.is_empty():
|
|
continue
|
|
var cols = 16
|
|
var sheet_w = 256
|
|
var sheet_h = 256
|
|
if ResourceLoader.exists(path):
|
|
var tex = load(path)
|
|
if tex and tex is Texture2D:
|
|
var w = tex.get_width()
|
|
var h = tex.get_height()
|
|
if w > 0:
|
|
cols = max(1, int(w / 16))
|
|
sheet_w = w
|
|
if h > 0:
|
|
sheet_h = h
|
|
fallback_defs.append({
|
|
"id": sheet_id,
|
|
"path": path,
|
|
"tileW": 16,
|
|
"tileH": 16,
|
|
"sheetW": sheet_w,
|
|
"sheetH": sheet_h,
|
|
"cols": cols
|
|
})
|
|
return fallback_defs
|
|
|
|
func _fallback_sheet_path(sheet_id: int) -> String:
|
|
# Known runtime/default mapping.
|
|
match sheet_id:
|
|
3:
|
|
return "res://assets/sprites/Dungeon_Tileset.png"
|
|
_:
|
|
return ""
|
|
|
|
func _fallback_tile_color(sheet_id: int) -> Color:
|
|
# Deterministic fallback color per sheet id when no sheet path is known.
|
|
var hue = float(abs(sheet_id * 53) % 360) / 360.0
|
|
return Color.from_hsv(hue, 0.35, 0.8, 0.9)
|
|
|
|
func _add_paywall_debug_overlay(world_tile_x: int, world_tile_y: int):
|
|
if paywall_overlay == null:
|
|
return
|
|
var tile_size = float(runtime.TILE_SIZE)
|
|
var poly = Polygon2D.new()
|
|
poly.color = Color(1.0, 0.2, 0.2, 0.35)
|
|
poly.polygon = PackedVector2Array([
|
|
Vector2(0, 0),
|
|
Vector2(tile_size, 0),
|
|
Vector2(tile_size, tile_size),
|
|
Vector2(0, tile_size)
|
|
])
|
|
poly.position = Vector2(world_tile_x * tile_size, world_tile_y * tile_size)
|
|
poly.z_index = 1
|
|
paywall_overlay.add_child(poly)
|
|
|
|
func _add_fallback_tile_overlay(world_tile_x: int, world_tile_y: int, sheet_id: int):
|
|
if tile_fallback_overlay == null:
|
|
return
|
|
var tile_size = float(runtime.TILE_SIZE)
|
|
var poly = Polygon2D.new()
|
|
poly.color = _fallback_tile_color(sheet_id)
|
|
poly.polygon = PackedVector2Array([
|
|
Vector2(0, 0),
|
|
Vector2(tile_size, 0),
|
|
Vector2(tile_size, tile_size),
|
|
Vector2(0, tile_size)
|
|
])
|
|
poly.position = Vector2(world_tile_x * tile_size, world_tile_y * tile_size)
|
|
tile_fallback_overlay.add_child(poly)
|
|
|
|
func _clear_children(node: Node):
|
|
for child in node.get_children():
|
|
child.queue_free()
|
|
|
|
func _ensure_self_player_node():
|
|
if players_container == null:
|
|
return
|
|
if self_player_node and is_instance_valid(self_player_node):
|
|
return
|
|
if player_scene:
|
|
self_player_node = player_scene.instantiate()
|
|
self_player_node.name = "SelfPlayerNode"
|
|
players_container.add_child(self_player_node)
|
|
if self_player_node.has_method("set_player_name"):
|
|
self_player_node.set_player_name(str(runtime.self_player.get("name", "You")))
|
|
else:
|
|
self_player_node = null
|
|
|
|
func _update_player_entities():
|
|
if runtime == null:
|
|
return
|
|
_ensure_self_player_node()
|
|
|
|
var seen_ids: Array = []
|
|
for pid in runtime.nearby_players.keys():
|
|
seen_ids.append(pid)
|
|
var player_data = runtime.nearby_players[pid]
|
|
var node = other_player_nodes.get(pid, null)
|
|
if node == null or not is_instance_valid(node):
|
|
if other_player_scene:
|
|
node = other_player_scene.instantiate()
|
|
node.name = "OtherPlayer_%s" % str(pid)
|
|
if players_container:
|
|
players_container.add_child(node)
|
|
other_player_nodes[pid] = node
|
|
else:
|
|
continue
|
|
|
|
node.position = Vector2(
|
|
float(player_data.get("x", 0.0)),
|
|
float(player_data.get("y", 0.0))
|
|
)
|
|
if node.has_method("update_data"):
|
|
var merged = player_data.duplicate(true)
|
|
if not merged.has("id"):
|
|
merged["id"] = pid
|
|
if not merged.has("name"):
|
|
merged["name"] = merged.get("playerName", "Player")
|
|
node.update_data(merged)
|
|
|
|
var to_remove: Array = []
|
|
for pid in other_player_nodes.keys():
|
|
if pid not in seen_ids:
|
|
to_remove.append(pid)
|
|
for pid in to_remove:
|
|
var node = other_player_nodes[pid]
|
|
if node and is_instance_valid(node):
|
|
node.queue_free()
|
|
other_player_nodes.erase(pid)
|
|
|
|
func _clear_player_entities():
|
|
if self_player_node and is_instance_valid(self_player_node):
|
|
self_player_node.queue_free()
|
|
self_player_node = null
|
|
for pid in other_player_nodes.keys():
|
|
var node = other_player_nodes[pid]
|
|
if node and is_instance_valid(node):
|
|
node.queue_free()
|
|
other_player_nodes.clear()
|
|
|
|
func _prepare_world_entry_ui():
|
|
if menu_panel:
|
|
menu_panel.visible = true
|
|
if world_bg:
|
|
world_bg.visible = true
|
|
if connect_btn:
|
|
connect_btn.disabled = false
|
|
connect_btn.text = "Connect World"
|
|
if status_label:
|
|
status_label.text = "World runtime ready. Connect to request spawn."
|
|
if runtime:
|
|
runtime.set_mode(runtime.MODE_CONNECTING)
|
|
|
|
func _reset_world_session():
|
|
_last_move_send_ms = 0
|
|
_last_world_input_log_ms = 0
|
|
_last_move_vec = Vector2.ZERO
|
|
_last_sent_move_vec = Vector2.ZERO
|
|
_last_sent_facing = ""
|
|
_render_self_position = Vector2.ZERO
|
|
_has_render_self_position = false
|
|
_clear_player_entities()
|
|
if object_container:
|
|
_clear_children(object_container)
|
|
if npc_container:
|
|
_clear_children(npc_container)
|
|
if paywall_overlay:
|
|
_clear_children(paywall_overlay)
|
|
if tile_fallback_overlay:
|
|
_clear_children(tile_fallback_overlay)
|
|
if visual_renderer:
|
|
visual_renderer.clear_tiles()
|
|
if runtime:
|
|
runtime.reset_runtime()
|
|
if world_root:
|
|
world_root.position = Vector2.ZERO
|
|
if world_camera:
|
|
world_camera.position = Vector2.ZERO
|
|
if player_marker:
|
|
player_marker.position = Vector2.ZERO
|
|
player_marker.visible = true
|
|
if menu_panel:
|
|
menu_panel.visible = true
|
|
if world_bg:
|
|
world_bg.visible = true
|
|
if connect_btn:
|
|
connect_btn.disabled = false
|
|
connect_btn.text = "Connect World"
|
|
if mode_label:
|
|
mode_label.text = "Mode: connecting"
|
|
if status_label:
|
|
status_label.text = "World runtime ready. Connect to request spawn."
|
|
|
|
func _rebuild_world_entities():
|
|
if runtime == null:
|
|
return
|
|
if object_container:
|
|
_clear_children(object_container)
|
|
if npc_container:
|
|
_clear_children(npc_container)
|
|
|
|
for key in runtime.chunk_cache:
|
|
var chunk_data = runtime.chunk_cache[key]
|
|
|
|
for obj in chunk_data.get("objects", []):
|
|
var object_pos = _resolve_entity_position(chunk_data, obj)
|
|
_add_world_object_instance(object_pos, obj)
|
|
|
|
for npc in chunk_data.get("npcs", []):
|
|
var npc_pos = _resolve_entity_position(chunk_data, npc)
|
|
_add_world_npc_instance(npc_pos, npc)
|
|
for mob in chunk_data.get("mobs", []):
|
|
var mob_pos = _resolve_entity_position(chunk_data, mob)
|
|
_add_world_npc_instance(mob_pos, mob)
|
|
|
|
func _resolve_entity_position(chunk_data: Dictionary, entity: Dictionary) -> Vector2:
|
|
# Runtime can emit either world pixel coords or chunk-local tile coords.
|
|
if entity.has("worldX") and entity.has("worldY"):
|
|
return Vector2(float(entity.get("worldX", 0.0)), float(entity.get("worldY", 0.0)))
|
|
|
|
var x = float(entity.get("x", 0.0))
|
|
var y = float(entity.get("y", 0.0))
|
|
|
|
var chunk_width_tiles = int(runtime.region.get("chunkWidthTiles", 0))
|
|
var chunk_height_tiles = int(runtime.region.get("chunkHeightTiles", 0))
|
|
if chunk_width_tiles > 0 and chunk_height_tiles > 0 and x >= 0.0 and y >= 0.0 and x < chunk_width_tiles and y < chunk_height_tiles:
|
|
var zone_x = int(chunk_data.get("zoneX", 0))
|
|
var zone_y = int(chunk_data.get("zoneY", 0))
|
|
var chunk_x = int(chunk_data.get("chunkX", 0))
|
|
var chunk_y = int(chunk_data.get("chunkY", 0))
|
|
var tx = runtime.world_tile_x(zone_x, chunk_x, int(x))
|
|
var ty = runtime.world_tile_y(zone_y, chunk_y, int(y))
|
|
return Vector2((tx + 0.5) * runtime.TILE_SIZE, (ty + 0.5) * runtime.TILE_SIZE)
|
|
|
|
return Vector2(x, y)
|
|
|
|
func _add_world_object_marker(position: Vector2, label_text: String):
|
|
if object_container == null:
|
|
return
|
|
var node = Node2D.new()
|
|
node.position = position
|
|
|
|
var marker = Polygon2D.new()
|
|
marker.color = Color(0.95, 0.75, 0.25, 0.9)
|
|
marker.polygon = PackedVector2Array([
|
|
Vector2(-8, -8),
|
|
Vector2(8, -8),
|
|
Vector2(8, 8),
|
|
Vector2(-8, 8)
|
|
])
|
|
node.add_child(marker)
|
|
|
|
var label = Label.new()
|
|
label.text = label_text.left(16)
|
|
label.position = Vector2(-28, -26)
|
|
node.add_child(label)
|
|
object_container.add_child(node)
|
|
|
|
func _add_world_object_instance(position: Vector2, object_data: Dictionary):
|
|
if object_container == null:
|
|
return
|
|
|
|
var sprite_path = _resolve_object_sprite_path(object_data)
|
|
if sprite_path.is_empty():
|
|
_add_world_object_marker(position, str(object_data.get("objectName", "Object")))
|
|
return
|
|
|
|
var texture = _load_world_texture(sprite_path)
|
|
if texture == null:
|
|
_add_world_object_marker(position, str(object_data.get("objectName", "Object")))
|
|
return
|
|
|
|
var node = Node2D.new()
|
|
node.position = position
|
|
|
|
var sprite = Sprite2D.new()
|
|
sprite.texture = texture
|
|
sprite.centered = true
|
|
sprite.texture_filter = CanvasItem.TEXTURE_FILTER_NEAREST
|
|
var scale_value = float(object_data.get("scale", object_data.get("Scale", 1.0)))
|
|
if scale_value <= 0.0:
|
|
scale_value = 1.0
|
|
sprite.scale = Vector2.ONE * scale_value
|
|
var tint = str(object_data.get("tintColor", object_data.get("TintColor", "")))
|
|
if not tint.is_empty():
|
|
sprite.modulate = Color.from_string(tint, Color.WHITE)
|
|
node.add_child(sprite)
|
|
|
|
object_container.add_child(node)
|
|
|
|
func _resolve_object_sprite_path(object_data: Dictionary) -> String:
|
|
var direct_keys = ["spritePath", "SpritePath", "path", "Path", "sprite", "Sprite"]
|
|
for key in direct_keys:
|
|
var value = str(object_data.get(key, ""))
|
|
if not value.is_empty():
|
|
return value
|
|
|
|
var sprite_config = object_data.get("spriteConfig", object_data.get("SpriteConfig", null))
|
|
if sprite_config is Dictionary:
|
|
if sprite_config.has("sheets"):
|
|
var sheets = sprite_config.get("sheets", {})
|
|
for sheet_key in sheets.keys():
|
|
var info = sheets[sheet_key]
|
|
if info is Dictionary:
|
|
var path = str(info.get("path", ""))
|
|
if not path.is_empty():
|
|
return path
|
|
if sprite_config.has("sprites"):
|
|
var sprites = sprite_config.get("sprites", {})
|
|
for anim in sprites.keys():
|
|
var path = str(sprites[anim])
|
|
if not path.is_empty():
|
|
return path
|
|
|
|
var definition_id = int(object_data.get("objectDefinitionId", object_data.get("definitionId", -1)))
|
|
if definition_id >= 0:
|
|
var local_path = "res://textures/objects/%d.png" % definition_id
|
|
if ResourceLoader.exists(local_path):
|
|
return local_path
|
|
|
|
return ""
|
|
|
|
func _load_world_texture(path: String) -> Texture2D:
|
|
if _object_texture_cache.has(path):
|
|
return _object_texture_cache[path]
|
|
|
|
var texture: Texture2D = null
|
|
if path.begins_with("res://"):
|
|
if ResourceLoader.exists(path):
|
|
texture = load(path)
|
|
elif UpdateManager:
|
|
texture = UpdateManager.load_texture(path)
|
|
|
|
if texture != null:
|
|
_object_texture_cache[path] = texture
|
|
return texture
|
|
|
|
func _add_world_npc_instance(position: Vector2, npc_data: Dictionary):
|
|
if npc_container == null:
|
|
return
|
|
if npc_scene == null:
|
|
_add_world_object_marker(position, str(npc_data.get("npcName", npc_data.get("name", "NPC"))))
|
|
return
|
|
|
|
var npc_node = npc_scene.instantiate()
|
|
npc_node.position = position
|
|
if npc_node.has_method("update_data"):
|
|
var merged = npc_data.duplicate(true)
|
|
if not merged.has("name") and merged.has("npcName"):
|
|
merged["name"] = merged["npcName"]
|
|
npc_node.update_data(merged)
|
|
npc_container.add_child(npc_node)
|