Spatial packets

This commit is contained in:
dingo
2026-02-09 08:58:44 -05:00
parent a0ee3deeca
commit 1c8dafabd1
9 changed files with 358 additions and 73 deletions
+77 -15
View File
@@ -56,6 +56,9 @@ var _last_aim_sent: float = 0.0
var _prefetched_mob_paths: Dictionary = {}
var _mob_prefetch_in_progress: bool = false
# Spatial visibility: how long (ms) to keep an out-of-range mob entity before removing it
const MOB_OUT_OF_RANGE_TIMEOUT_MS: int = 5000
func _ready():
# Add to group for HUD to access
add_to_group("dungeon_manager")
@@ -477,7 +480,7 @@ func _on_state_updated():
_update_entities(players_container, GameState.players, player_scene)
if mob_scene and mobs_container:
await _prefetch_mob_textures_if_needed()
_update_entities(mobs_container, GameState.mobs, mob_scene)
_update_mob_entities()
if chest_scene and chests_container:
_update_entities(chests_container, GameState.chests, chest_scene)
if item_scene and items_container:
@@ -543,6 +546,8 @@ func _prefetch_mob_textures_if_needed() -> void:
_mob_prefetch_in_progress = false
func _update_entities(container: Node2D, data: Dictionary, scene: PackedScene):
## Generic entity updater for players, chests, items, portals.
## Mobs use _update_mob_entities() instead for visibility-scoped lifecycle.
if scene == null or container == null:
return
@@ -562,17 +567,6 @@ func _update_entities(container: Node2D, data: Dictionary, scene: PackedScene):
var y = entity_data.get("y", entity_data.get("Y", 0))
entity_node.position = Vector2(x, y)
# Check if this is a mob that just died
if container == mobs_container:
var hp = entity_data.get("health", entity_data.get("Health", 100))
var was_alive = not entity_node.get_meta("is_dead", false)
if hp <= 0 and was_alive:
# Mark as dead and play death animation
entity_node.set_meta("is_dead", true)
if entity_node.has_method("play_death_animation"):
entity_node.play_death_animation()
if entity_node.has_method("update_data"):
entity_node.update_data(entity_data)
@@ -580,12 +574,80 @@ func _update_entities(container: Node2D, data: Dictionary, scene: PackedScene):
if child.has_meta("entity_id"):
var id = child.get_meta("entity_id")
if id not in seen_ids:
# For mobs, keep dead bodies for looting
if container == mobs_container and child.get_meta("is_dead", false):
# Don't remove dead mob bodies
child.queue_free()
func _update_mob_entities():
## Visibility-scoped mob entity lifecycle.
## Mobs present in the packet are created/updated normally.
## Mobs absent from the packet (out of range) are kept for a timeout before removal.
if mob_scene == null or mobs_container == null:
return
var now_ms = Time.get_ticks_msec()
var seen_ids = []
for id in GameState.mobs:
var mob = GameState.mobs[id]
var is_visible = mob.get("_visible", true)
if not is_visible:
# Out-of-range mob — check timeout
var last_seen = mob.get("_last_seen", now_ms)
if now_ms - last_seen > MOB_OUT_OF_RANGE_TIMEOUT_MS:
# Timed out — remove entity node and data
var entity_node = _find_entity_by_id(mobs_container, id)
if entity_node and not entity_node.get_meta("is_dead", false):
entity_node.queue_free()
else:
# Still within grace period — keep the node but don't update position
seen_ids.append(id)
continue
seen_ids.append(id)
var entity_node = _find_entity_by_id(mobs_container, id)
if entity_node == null:
entity_node = mob_scene.instantiate()
entity_node.set_meta("entity_id", id)
mobs_container.add_child(entity_node)
var x = mob.get("x", mob.get("X", 0))
var y = mob.get("y", mob.get("Y", 0))
entity_node.position = Vector2(x, y)
# Check if this mob just died
var hp = mob.get("health", mob.get("Health", 100))
var was_alive = not entity_node.get_meta("is_dead", false)
if hp <= 0 and was_alive:
entity_node.set_meta("is_dead", true)
if entity_node.has_method("play_death_animation"):
entity_node.play_death_animation()
if entity_node.has_method("update_data"):
entity_node.update_data(mob)
# Remove entity nodes that are no longer tracked at all
for child in mobs_container.get_children():
if child.has_meta("entity_id"):
var id = child.get_meta("entity_id")
if id not in seen_ids:
# Keep dead mob bodies for looting
if child.get_meta("is_dead", false):
continue
child.queue_free()
# Clean up timed-out mobs from GameState dict
var to_remove: Array = []
for id in GameState.mobs:
var mob = GameState.mobs[id]
if not mob.get("_visible", true):
var last_seen = mob.get("_last_seen", now_ms)
if now_ms - last_seen > MOB_OUT_OF_RANGE_TIMEOUT_MS:
to_remove.append(id)
for id in to_remove:
GameState.mobs.erase(id)
func _find_entity_by_id(container: Node2D, id) -> Node2D:
for child in container.get_children():
if child.has_meta("entity_id") and child.get_meta("entity_id") == id:
+63 -12
View File
@@ -16,6 +16,11 @@ var _animated_sprite: AnimatedSprite2D = null
var _using_fallback: bool = true
var _initialized: bool = false # Track if we've already set up this mob
var _last_animation: String = "" # Track animation to avoid spam
var _sprite_config_key: String = ""
var _definition_id = null # Server definitionId for fallback art resolution
# Shared cache to reuse sprite frames across mobs with identical configs
static var _sprite_frames_cache: Dictionary = {} # key -> SpriteFrames
# Animation state
var _current_state: String = "idle"
@@ -81,8 +86,14 @@ func _state_to_animation(state: String) -> String:
func update_data(data: Dictionary):
mob_data = data
var mob_id = data.get("id", data.get("Id", "unknown"))
var sprite_config = data.get("spriteConfig", data.get("SpriteConfig", null))
# Track definitionId for fallback art resolution
var def_id = data.get("definitionId", data.get("DefinitionId", null))
if def_id != null:
_definition_id = def_id
# Update name
var mname = data.get("name", data.get("Name", "Mob"))
@@ -96,25 +107,43 @@ func update_data(data: Dictionary):
health_bar.max_value = max_hp
health_bar.value = hp
# Only process sprite config on first update or if it changed
if not _initialized:
print("[MobVisual] First init for mob %s (%s)" % [mname, mob_id])
var sprite_config = data.get("spriteConfig", data.get("SpriteConfig", null))
if sprite_config != null and sprite_config is Dictionary and not sprite_config.is_empty():
# Process sprite config on first update or if it changed.
# Server may send null for invalid configs — treat as missing.
if sprite_config != null and sprite_config is Dictionary and not sprite_config.is_empty():
# Validate that config has at minimum sheets or sprites
var has_sheets = sprite_config.has("sheets") and sprite_config["sheets"] is Dictionary and not sprite_config["sheets"].is_empty()
var has_sprites = sprite_config.has("sprites") and sprite_config["sprites"] is Dictionary and not sprite_config["sprites"].is_empty()
if has_sheets or has_sprites:
_sprite_config_key = _get_sprite_config_key(sprite_config)
if sprite_config != _sprite_config:
_sprite_config = sprite_config
_using_fallback = true
if _animated_sprite:
_animated_sprite.visible = false
if UpdateManager and UpdateManager.has_method("queue_build"):
UpdateManager.queue_build(Callable(self, "_build_animated_sprite"))
else:
_build_animated_sprite()
else:
# Config present but missing actual sprite data — use fallback
if not _sprite_config.is_empty():
_sprite_config = {}
_sprite_config_key = ""
_setup_fallback(data)
# Apply tint on first setup
else:
# Null or missing sprite config — use fallback with safe defaults
if not _sprite_config.is_empty():
_sprite_config = {}
_sprite_config_key = ""
_setup_fallback(data)
if not _initialized:
print("[MobVisual] First init for mob %s (%s)" % [mname, mob_id])
# Apply tint on first setup (null-safe: server may send null for invalid tint)
var tint = data.get("tintColor", data.get("TintColor", "#ffffff"))
if tint == null or not (tint is String) or tint.is_empty():
tint = "#ffffff"
_apply_tint(tint)
_initialized = true
# Update visual state (skip for dead mobs to preserve death animation)
@@ -139,6 +168,12 @@ func update_data(data: Dictionary):
func _build_animated_sprite():
## Build AnimatedSprite2D from sprite config
## Detects format and uses appropriate builder
if _sprite_config_key != "" and _sprite_frames_cache.has(_sprite_config_key):
_use_cached_frames(_sprite_frames_cache[_sprite_config_key])
_using_fallback = false
if fallback_sprite:
fallback_sprite.visible = false
return
# Check for new format (has "sheets" key)
if _sprite_config.has("sheets"):
@@ -244,7 +279,7 @@ func _build_from_new_format():
sprite_frames.add_frame(anim_name, atlas)
_animated_sprite.sprite_frames = sprite_frames
_cache_and_apply_frames(sprite_frames)
_animated_sprite.visible = true
_animated_sprite.z_index = 10
_animated_sprite.modulate = Color.WHITE
@@ -328,7 +363,7 @@ func _build_from_legacy_format():
atlas.region = Rect2(i * frame_width, 0, frame_width, frame_height)
sprite_frames.add_frame(anim_name, atlas)
_animated_sprite.sprite_frames = sprite_frames
_cache_and_apply_frames(sprite_frames)
_animated_sprite.visible = true
_animated_sprite.z_index = 10
_animated_sprite.modulate = Color.WHITE
@@ -369,6 +404,22 @@ func _on_file_downloaded(file_path: String):
_build_animated_sprite()
return
func _get_sprite_config_key(config: Dictionary) -> String:
# Use JSON as a stable-ish cache key (server sends consistent key order)
return JSON.stringify(config)
func _cache_and_apply_frames(sprite_frames: SpriteFrames) -> void:
if _sprite_config_key != "":
_sprite_frames_cache[_sprite_config_key] = sprite_frames
_use_cached_frames(sprite_frames)
func _use_cached_frames(sprite_frames: SpriteFrames) -> void:
if not _animated_sprite:
_animated_sprite = AnimatedSprite2D.new()
_animated_sprite.name = "MobAnimatedSprite"
add_child(_animated_sprite)
_animated_sprite.sprite_frames = sprite_frames
func _setup_fallback(data: Dictionary):
_using_fallback = true
+142
View File
@@ -0,0 +1,142 @@
extends Node2D
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite
@onready var fallback_sprite: Sprite2D = $FallbackSprite
@onready var name_label: Label = $NameLabel
@onready var health_bar: ProgressBar = $HealthBar
var player_data: Dictionary = {}
var player_id: int = 0
var _tint_color: Color = Color(0.27, 0.67, 1.0)
func _ready():
# Start with fallback circle until the sprite sheet is ready
if fallback_sprite and SpriteGenerator:
fallback_sprite.texture = SpriteGenerator.get_circle()
fallback_sprite.visible = true
if animated_sprite:
animated_sprite.visible = false
# Try to load sprite sheet immediately
if UpdateManager:
var texture = UpdateManager.load_texture("textures/player/Warrior-Blue.png")
if texture:
_setup_sprite_frames(texture)
else:
if not UpdateManager.file_downloaded.is_connected(_on_file_downloaded):
UpdateManager.file_downloaded.connect(_on_file_downloaded)
func update_data(data: Dictionary):
player_data = data
player_id = int(data.get("id", data.get("Id", 0)))
var pname = data.get("name", data.get("Name", "Player"))
if name_label:
name_label.text = pname
var hp = data.get("health", data.get("Health", 100))
var max_hp = data.get("maxHealth", data.get("MaxHealth", 100))
if health_bar:
health_bar.max_value = max_hp
health_bar.value = hp
var is_alive = data.get("isAlive", data.get("IsAlive", true))
if is_alive:
_tint_color = _color_from_id(player_id)
else:
_tint_color = Color(0.3, 0.3, 0.3)
_apply_tint(_tint_color)
# Ensure idle animation is playing when available
if animated_sprite and animated_sprite.sprite_frames:
if animated_sprite.animation != "walk_down":
animated_sprite.play("walk_down")
func _on_file_downloaded(file_path: String):
if file_path != "textures/player/Warrior-Blue.png":
return
if UpdateManager:
var texture = UpdateManager.load_texture("textures/player/Warrior-Blue.png")
if texture:
_setup_sprite_frames(texture)
func _apply_tint(tint: Color):
if animated_sprite:
animated_sprite.modulate = tint
if fallback_sprite:
fallback_sprite.modulate = tint
func _setup_sprite_frames(texture: Texture2D):
if not animated_sprite:
return
var frames = SpriteFrames.new()
var frame_width = 32
var frame_height = 32
var create_anim = func(anim_name: String, row_y: int, start_col: int, frame_count: int, loop: bool = true):
frames.add_animation(anim_name)
frames.set_animation_loop(anim_name, loop)
frames.set_animation_speed(anim_name, 8.0)
for i in range(frame_count):
var atlas = AtlasTexture.new()
atlas.atlas = texture
atlas.region = Rect2(
(start_col + i) * frame_width,
row_y,
frame_width,
frame_height
)
frames.add_frame(anim_name, atlas)
create_anim.call("walk_down", 0, 0, 4)
create_anim.call("walk_right", 64, 0, 4)
create_anim.call("walk_up", 128, 0, 4)
create_anim.call("walk_left", 192, 0, 4)
create_anim.call("attack_sword_down", 0, 4, 4, false)
create_anim.call("attack_sword_right", 64, 4, 4, false)
create_anim.call("attack_sword_up", 128, 4, 4, false)
create_anim.call("attack_sword_left", 192, 4, 4, false)
create_anim.call("attack_bow_down", 0, 8, 4, false)
create_anim.call("attack_bow_right", 64, 8, 4, false)
create_anim.call("attack_bow_up", 128, 8, 4, false)
create_anim.call("attack_bow_left", 192, 8, 4, false)
create_anim.call("attack_spell_down", 0, 12, 4, false)
create_anim.call("attack_spell_right", 64, 12, 4, false)
create_anim.call("attack_spell_up", 128, 12, 4, false)
create_anim.call("attack_spell_left", 192, 12, 4, false)
create_anim.call("attack_fist_down", 0, 16, 4, false)
create_anim.call("attack_fist_right", 64, 16, 4, false)
create_anim.call("attack_fist_up", 128, 16, 4, false)
create_anim.call("attack_fist_left", 192, 16, 4, false)
create_anim.call("hurt_down", 0, 20, 1, false)
create_anim.call("hurt_right", 64, 20, 1, false)
create_anim.call("hurt_up", 128, 20, 1, false)
create_anim.call("hurt_left", 192, 20, 1, false)
create_anim.call("dead_down", 0, 21, 4, false)
create_anim.call("dead_right", 64, 21, 4, false)
create_anim.call("dead_up", 128, 21, 4, false)
create_anim.call("dead_left", 192, 21, 4, false)
animated_sprite.sprite_frames = frames
animated_sprite.visible = true
animated_sprite.play("walk_down")
if fallback_sprite:
fallback_sprite.visible = false
_apply_tint(_tint_color)
func _color_from_id(id_value: int) -> Color:
# Stable, distinct tint per player ID
var hue = float(abs(id_value) % 360) / 360.0
return Color.from_hsv(hue, 0.6, 1.0)
+1
View File
@@ -0,0 +1 @@
uid://tmg1icw1h5ac