diff --git a/project.godot b/project.godot index fe42e69..92012f9 100644 --- a/project.godot +++ b/project.godot @@ -21,6 +21,7 @@ OpCodes="*res://scripts/autoload/opcodes.gd" Network="*res://scripts/autoload/network.gd" GameState="*res://scripts/autoload/game_state.gd" SpriteGenerator="*res://scripts/autoload/sprite_generator.gd" +UpdateManager="*res://scripts/autoload/update_manager.gd" [display] diff --git a/scenes/dungeon/mob.tscn b/scenes/dungeon/mob.tscn index acb68e5..e0a4168 100644 --- a/scenes/dungeon/mob.tscn +++ b/scenes/dungeon/mob.tscn @@ -1,46 +1,12 @@ -[gd_scene load_steps=3 format=3] +[gd_scene load_steps=3 format=3 uid="uid://4it2xruff84i"] -[sub_resource type="GDScript" id="GDScript_mob"] -script/source = "extends Node2D - -@onready var sprite: Sprite2D = $Sprite -@onready var name_label: Label = $NameLabel -@onready var health_bar: ProgressBar = $HealthBar - -var mob_data: Dictionary = {} - -func _ready(): - # Get texture from generator if available - if SpriteGenerator: - sprite.texture = SpriteGenerator.get_circle() - - # Default mob color (red) - sprite.modulate = Color(0.67, 0.27, 0.27) # #aa4444 - -func update_data(data: Dictionary): - mob_data = data - - var mname = data.get(\"name\", data.get(\"Name\", \"Mob\")) - name_label.text = mname - - var hp = data.get(\"health\", data.get(\"Health\", 100)) - var max_hp = data.get(\"maxHealth\", data.get(\"MaxHealth\", 100)) - health_bar.max_value = max_hp - health_bar.value = hp - - # Change color based on state - var state = str(data.get(\"state\", data.get(\"State\", \"idle\"))).to_lower() - if state == \"attacking\": - sprite.modulate = Color(1.0, 0.4, 0.4) # Bright red when attacking - else: - sprite.modulate = Color(0.67, 0.27, 0.27) # Normal red -" +[ext_resource type="Script" uid="uid://b0rmvppejqbkq" path="res://scripts/dungeon/mob_visual.gd" id="1_hxp1t"] [sub_resource type="CircleShape2D" id="CircleShape2D_1"] radius = 14.0 [node name="Mob" type="Node2D"] -script = SubResource("GDScript_mob") +script = ExtResource("1_hxp1t") [node name="Sprite" type="Sprite2D" parent="."] modulate = Color(0.667, 0.267, 0.267, 1) @@ -59,7 +25,6 @@ offset_left = -20.0 offset_top = -28.0 offset_right = 20.0 offset_bottom = -23.0 -max_value = 100.0 value = 100.0 show_percentage = false diff --git a/scenes/dungeon/skeleton.tscn b/scenes/dungeon/skeleton.tscn new file mode 100644 index 0000000..71eda10 --- /dev/null +++ b/scenes/dungeon/skeleton.tscn @@ -0,0 +1,514 @@ +[gd_scene load_steps=68 format=3 uid="uid://bujdna7jnqkby"] + +[ext_resource type="Texture2D" uid="uid://bh5hiktaq3n0d" path="res://assets/sprites/skeleton_idle_front.png" id="1_pploe"] +[ext_resource type="Texture2D" uid="uid://d1tduvr5dgalw" path="res://assets/sprites/skeleton_idle_left.png" id="2_hx7r7"] +[ext_resource type="Texture2D" uid="uid://cledey0ulf2ug" path="res://assets/sprites/skeleton_idle_right.png" id="3_veie2"] +[ext_resource type="Texture2D" uid="uid://cw6qmlsxbh6p6" path="res://assets/sprites/skeleton_idle_back.png" id="4_sl27l"] +[ext_resource type="Texture2D" uid="uid://c0htjdiwhxqke" path="res://assets/sprites/skeleton_run_down.png" id="5_k6hkq"] +[ext_resource type="Texture2D" uid="uid://ehyta407mq35" path="res://assets/sprites/skeleton_run_left.png" id="6_41lny"] +[ext_resource type="Texture2D" uid="uid://csguviflpidje" path="res://assets/sprites/skeleton_run_right.png" id="7_0esl7"] +[ext_resource type="Texture2D" uid="uid://d3p0msvqnljlh" path="res://assets/sprites/skeleton_run_up.png" id="8_fqkji"] + +[sub_resource type="GDScript" id="GDScript_mob"] +script/source = "extends Node2D + +@onready var sprite: Sprite2D = $Sprite +@onready var name_label: Label = $NameLabel +@onready var health_bar: ProgressBar = $HealthBar + +var mob_data: Dictionary = {} + +func _ready(): + # Get texture from generator if available + if SpriteGenerator: + sprite.texture = SpriteGenerator.get_circle() + + # Default mob color (red) + sprite.modulate = Color(0.67, 0.27, 0.27) # #aa4444 + +func update_data(data: Dictionary): + mob_data = data + + var mname = data.get(\"name\", data.get(\"Name\", \"Mob\")) + name_label.text = mname + + var hp = data.get(\"health\", data.get(\"Health\", 100)) + var max_hp = data.get(\"maxHealth\", data.get(\"MaxHealth\", 100)) + health_bar.max_value = max_hp + health_bar.value = hp + + # Change color based on state + var state = str(data.get(\"state\", data.get(\"State\", \"idle\"))).to_lower() + if state == \"attacking\": + sprite.modulate = Color(1.0, 0.4, 0.4) # Bright red when attacking + else: + sprite.modulate = Color(0.67, 0.27, 0.27) # Normal red +" + +[sub_resource type="AtlasTexture" id="AtlasTexture_k6hkq"] +atlas = ExtResource("1_pploe") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_41lny"] +atlas = ExtResource("1_pploe") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_0esl7"] +atlas = ExtResource("1_pploe") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_fqkji"] +atlas = ExtResource("1_pploe") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_fhgn5"] +atlas = ExtResource("1_pploe") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_frtn7"] +atlas = ExtResource("1_pploe") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_7g40e"] +atlas = ExtResource("1_pploe") +region = Rect2(384, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_5vh58"] +atlas = ExtResource("1_pploe") +region = Rect2(448, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_qu4fx"] +atlas = ExtResource("2_hx7r7") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_e7ee1"] +atlas = ExtResource("2_hx7r7") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_yid88"] +atlas = ExtResource("2_hx7r7") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_dr8o3"] +atlas = ExtResource("2_hx7r7") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_6820b"] +atlas = ExtResource("2_hx7r7") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_mcth8"] +atlas = ExtResource("2_hx7r7") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_rjmc8"] +atlas = ExtResource("2_hx7r7") +region = Rect2(384, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_35mp6"] +atlas = ExtResource("2_hx7r7") +region = Rect2(448, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_ri13g"] +atlas = ExtResource("3_veie2") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_odhcy"] +atlas = ExtResource("3_veie2") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_bj50m"] +atlas = ExtResource("3_veie2") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_8amur"] +atlas = ExtResource("3_veie2") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_b3w3k"] +atlas = ExtResource("3_veie2") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_oaxiq"] +atlas = ExtResource("3_veie2") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_bmdme"] +atlas = ExtResource("3_veie2") +region = Rect2(384, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_7tnq4"] +atlas = ExtResource("3_veie2") +region = Rect2(448, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_si4oc"] +atlas = ExtResource("4_sl27l") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_h8v16"] +atlas = ExtResource("4_sl27l") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_6fmny"] +atlas = ExtResource("4_sl27l") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_i5pwu"] +atlas = ExtResource("4_sl27l") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_r8f14"] +atlas = ExtResource("4_sl27l") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_lsr2m"] +atlas = ExtResource("4_sl27l") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_8skex"] +atlas = ExtResource("4_sl27l") +region = Rect2(384, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_l6pfv"] +atlas = ExtResource("4_sl27l") +region = Rect2(448, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_1mdy3"] +atlas = ExtResource("5_k6hkq") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_ebcfk"] +atlas = ExtResource("5_k6hkq") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_t3iib"] +atlas = ExtResource("5_k6hkq") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_ufa5r"] +atlas = ExtResource("5_k6hkq") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_35paj"] +atlas = ExtResource("5_k6hkq") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_svn5s"] +atlas = ExtResource("5_k6hkq") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_je3uc"] +atlas = ExtResource("6_41lny") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_lus8e"] +atlas = ExtResource("6_41lny") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_4x2ba"] +atlas = ExtResource("6_41lny") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_r1whh"] +atlas = ExtResource("6_41lny") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_m680v"] +atlas = ExtResource("6_41lny") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_5v31e"] +atlas = ExtResource("6_41lny") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_vsoff"] +atlas = ExtResource("7_0esl7") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_jafuc"] +atlas = ExtResource("7_0esl7") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_fs722"] +atlas = ExtResource("7_0esl7") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_iolbg"] +atlas = ExtResource("7_0esl7") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_4grvp"] +atlas = ExtResource("7_0esl7") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_c7xha"] +atlas = ExtResource("7_0esl7") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_bqs0e"] +atlas = ExtResource("8_fqkji") +region = Rect2(0, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_q4l2n"] +atlas = ExtResource("8_fqkji") +region = Rect2(64, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_il1ms"] +atlas = ExtResource("8_fqkji") +region = Rect2(128, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_ici58"] +atlas = ExtResource("8_fqkji") +region = Rect2(192, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_ffrgp"] +atlas = ExtResource("8_fqkji") +region = Rect2(256, 0, 64, 64) + +[sub_resource type="AtlasTexture" id="AtlasTexture_sgvb2"] +atlas = ExtResource("8_fqkji") +region = Rect2(320, 0, 64, 64) + +[sub_resource type="SpriteFrames" id="SpriteFrames_0esl7"] +animations = [{ +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_k6hkq") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_41lny") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_0esl7") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_fqkji") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_fhgn5") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_frtn7") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_7g40e") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_5vh58") +}], +"loop": true, +"name": &"idle_down", +"speed": 5.0 +}, { +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_qu4fx") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_e7ee1") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_yid88") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_dr8o3") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_6820b") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_mcth8") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_rjmc8") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_35mp6") +}], +"loop": true, +"name": &"idle_left", +"speed": 5.0 +}, { +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_ri13g") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_odhcy") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_bj50m") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_8amur") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_b3w3k") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_oaxiq") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_bmdme") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_7tnq4") +}], +"loop": false, +"name": &"idle_right", +"speed": 5.0 +}, { +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_si4oc") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_h8v16") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_6fmny") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_i5pwu") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_r8f14") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_lsr2m") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_8skex") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_l6pfv") +}], +"loop": true, +"name": &"idle_up", +"speed": 5.0 +}, { +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_1mdy3") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_ebcfk") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_t3iib") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_ufa5r") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_35paj") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_svn5s") +}], +"loop": true, +"name": &"walk_down", +"speed": 5.0 +}, { +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_je3uc") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_lus8e") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_4x2ba") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_r1whh") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_m680v") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_5v31e") +}], +"loop": true, +"name": &"walk_left", +"speed": 5.0 +}, { +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_vsoff") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_jafuc") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_fs722") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_iolbg") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_4grvp") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_c7xha") +}], +"loop": true, +"name": &"walk_right", +"speed": 5.0 +}, { +"frames": [{ +"duration": 1.0, +"texture": SubResource("AtlasTexture_bqs0e") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_q4l2n") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_il1ms") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_ici58") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_ffrgp") +}, { +"duration": 1.0, +"texture": SubResource("AtlasTexture_sgvb2") +}], +"loop": true, +"name": &"walk_up", +"speed": 5.0 +}] + +[sub_resource type="CircleShape2D" id="CircleShape2D_1"] +radius = 14.0 + +[node name="Mob" type="Node2D"] +script = SubResource("GDScript_mob") + +[node name="Sprite" type="Sprite2D" parent="."] +modulate = Color(0.667, 0.267, 0.267, 1) +scale = Vector2(1.4749995, 1.4749995) + +[node name="AnimatedSprite2D" type="AnimatedSprite2D" parent="Sprite"] +sprite_frames = SubResource("SpriteFrames_0esl7") +animation = &"walk_up" + +[node name="NameLabel" type="Label" parent="."] +offset_left = -50.0 +offset_top = -35.0 +offset_right = 50.0 +offset_bottom = -20.0 +horizontal_alignment = 1 +vertical_alignment = 1 + +[node name="HealthBar" type="ProgressBar" parent="."] +offset_left = -20.0 +offset_top = -28.0 +offset_right = 20.0 +offset_bottom = -23.0 +value = 100.0 +show_percentage = false + +[node name="CollisionShape2D" type="CollisionShape2D" parent="."] +shape = SubResource("CircleShape2D_1") diff --git a/scripts/autoload/game_state.gd b/scripts/autoload/game_state.gd index 56743fa..453c668 100644 --- a/scripts/autoload/game_state.gd +++ b/scripts/autoload/game_state.gd @@ -136,9 +136,16 @@ func _on_message_received(opcode: int, data: Dictionary): _handle_death_loot_lost(data) OpCodes.DUNGEON_LIST_RESPONSE: _handle_dungeon_list(data) + OpCodes.ASSET_MANIFEST_RESPONSE: + _handle_asset_manifest(data) _: print("[GameState] Unhandled opcode: ", opcode) +func _handle_asset_manifest(data: Dictionary): + print("[GameState] Received asset manifest") + if UpdateManager: + UpdateManager.on_manifest_received(data) + func _handle_auth_result(data: Dictionary): var ok = data.get("ok", data.get("Ok", false)) if ok: diff --git a/scripts/autoload/opcodes.gd b/scripts/autoload/opcodes.gd index a0d9f36..87cda31 100644 --- a/scripts/autoload/opcodes.gd +++ b/scripts/autoload/opcodes.gd @@ -47,6 +47,10 @@ const DUNGEON_LIST_RESPONSE = 311 const DUNGEON_CREATE = 312 const DUNGEON_JOIN = 313 +# Asset Management +const ASSET_MANIFEST_REQUEST = 320 +const ASSET_MANIFEST_RESPONSE = 321 + # Input const INPUT_MOVE = 400 const INPUT_ATTACK = 401 diff --git a/scripts/autoload/update_manager.gd b/scripts/autoload/update_manager.gd new file mode 100644 index 0000000..e6353e5 --- /dev/null +++ b/scripts/autoload/update_manager.gd @@ -0,0 +1,521 @@ +extends Node + +## Update Manager +## Downloads and caches files from CDN, enabling hot-updates without client redeploy +## Files are stored at: {CDN_BASE_URL}/{cdnPath} +## +## For .tscn scenes: textures are also downloaded and paths are rewritten to use cache + +signal update_check_started +signal update_progress(downloaded: int, total: int, current_file: String) +signal update_completed(updated_count: int) +signal update_failed(error: String) +signal file_downloaded(file_path: String) + +const LOCAL_CACHE_DIR = "user://cdn_cache/" +const MANIFEST_CACHE_FILE = "user://cdn_manifest.json" +const CLIENT_VERSION = "1.0.0" + +var cdn_base_url: String = "https://assets.aeternalisgames.com/downloads/" +var _manifest: Dictionary = {} # filePath -> {fileHash, fileSize, version, assetType, cdnPath} +var _local_hashes: Dictionary = {} # filePath -> hash +var _download_queue: Array = [] +var _is_updating: bool = false +var _files_downloaded: int = 0 +var _files_total: int = 0 +var _active_request: HTTPRequest = null + +# Runtime loaded resources cache +var _loaded_scenes: Dictionary = {} # filePath -> PackedScene +var _loaded_textures: Dictionary = {} # filePath -> Texture2D +var _loaded_scripts: Dictionary = {} # filePath -> GDScript + +func _ready(): + # Ensure cache directory exists + DirAccess.make_dir_recursive_absolute(LOCAL_CACHE_DIR) + _load_local_manifest() + +## Request manifest from server and check for updates +func check_for_updates(): + if _is_updating: + push_warning("[UpdateManager] Already checking for updates") + return + + update_check_started.emit() + + if Network and Network.is_socket_connected(): + Network.send_message(OpCodes.ASSET_MANIFEST_REQUEST, {}) + else: + push_error("[UpdateManager] Network not connected, cannot check for updates") + update_failed.emit("Network not connected") + +## Called by GameState when manifest response is received +func on_manifest_received(data: Dictionary): + cdn_base_url = data.get("cdnBaseUrl", cdn_base_url) + var assets = data.get("assets", []) + + _manifest.clear() + for asset in assets: + var file_path = asset.get("filePath", "") + if file_path.is_empty(): + continue + + var min_version = asset.get("minClientVersion", "") + if not min_version.is_empty() and _compare_versions(CLIENT_VERSION, min_version) < 0: + push_warning("[UpdateManager] Asset %s requires client version %s, we have %s" % [file_path, min_version, CLIENT_VERSION]) + continue + + _manifest[file_path] = { + "fileHash": asset.get("fileHash", ""), + "fileSize": asset.get("fileSize", 0), + "version": asset.get("version", 1), + "assetType": asset.get("assetType", 2), + "isRequired": asset.get("isRequired", false), + "cdnPath": asset.get("cdnPath", file_path) + } + + print("[UpdateManager] Received manifest with %d files" % _manifest.size()) + _check_for_updates() + +func _check_for_updates(): + _download_queue.clear() + + for file_path in _manifest: + var remote = _manifest[file_path] + var local_hash = _local_hashes.get(file_path, "") + + if local_hash != remote.fileHash: + _download_queue.append({ + "filePath": file_path, + "cdnPath": remote.cdnPath, + "fileHash": remote.fileHash, + "fileSize": remote.fileSize, + "isRequired": remote.isRequired + }) + + if _download_queue.is_empty(): + print("[UpdateManager] All files up to date!") + update_completed.emit(0) + return + + # Sort: required files first, then textures before scenes (so scenes can reference them) + _download_queue.sort_custom(func(a, b): + if a.isRequired != b.isRequired: + return a.isRequired + # Textures before scenes + var a_is_texture = a.filePath.ends_with(".png") or a.filePath.ends_with(".jpg") + var b_is_texture = b.filePath.ends_with(".png") or b.filePath.ends_with(".jpg") + return a_is_texture and not b_is_texture + ) + + _files_total = _download_queue.size() + _files_downloaded = 0 + _is_updating = true + + print("[UpdateManager] Need to download %d files" % _files_total) + _download_next() + +func _download_next(): + if _download_queue.is_empty(): + _is_updating = false + _save_local_manifest() + print("[UpdateManager] Update complete! Downloaded %d files" % _files_downloaded) + update_completed.emit(_files_downloaded) + return + + var item = _download_queue.pop_front() + var url = cdn_base_url + item.cdnPath + + update_progress.emit(_files_downloaded, _files_total, item.filePath) + + _active_request = HTTPRequest.new() + add_child(_active_request) + _active_request.request_completed.connect(_on_download_completed.bind(item)) + + print("[UpdateManager] Downloading: %s" % item.filePath) + var err = _active_request.request(url) + if err != OK: + push_error("[UpdateManager] Failed to start download for %s: %d" % [item.filePath, err]) + _active_request.queue_free() + _active_request = null + _download_next() + +func _on_download_completed(result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray, item: Dictionary): + if _active_request: + _active_request.queue_free() + _active_request = null + + if result != HTTPRequest.RESULT_SUCCESS or response_code != 200: + push_error("[UpdateManager] Download failed for %s: result=%d, code=%d" % [item.filePath, result, response_code]) + if item.isRequired: + update_failed.emit("Failed to download required file: " + item.filePath) + _is_updating = false + return + else: + # Skip optional file and continue + _download_next() + return + + # Save file to cache + var cache_path = _get_cache_path(item.filePath) + + # Ensure subdirectory exists + var dir_path = cache_path.get_base_dir() + DirAccess.make_dir_recursive_absolute(dir_path) + + var file = FileAccess.open(cache_path, FileAccess.WRITE) + if file: + file.store_buffer(body) + file.close() + + # Verify hash + var actual_hash = _compute_md5(body) + if actual_hash == item.fileHash: + _local_hashes[item.filePath] = item.fileHash + _files_downloaded += 1 + file_downloaded.emit(item.filePath) + print("[UpdateManager] Downloaded: %s" % item.filePath) + else: + push_error("[UpdateManager] Hash mismatch for %s: expected %s, got %s" % [item.filePath, item.fileHash, actual_hash]) + else: + push_error("[UpdateManager] Failed to save file: %s" % cache_path) + + _download_next() + +## Get the cache path for a file (preserves directory structure) +func _get_cache_path(file_path: String) -> String: + return LOCAL_CACHE_DIR + file_path + +## Load a scene from cache (for mobs, effects, etc.) +## Textures are loaded separately and injected after scene instantiation +func load_scene(file_path: String) -> PackedScene: + # Check memory cache + if _loaded_scenes.has(file_path): + return _loaded_scenes[file_path] + + # Check disk cache + var cache_path = _get_cache_path(file_path) + if not FileAccess.file_exists(cache_path): + push_warning("[UpdateManager] Scene not in cache: %s" % file_path) + return null + + # Load the .tscn file + var file = FileAccess.open(cache_path, FileAccess.READ) + if not file: + return null + + var content = file.get_as_text() + file.close() + + # Extract texture paths that the scene needs (for pre-loading) + var texture_paths = _extract_texture_paths(content) + + # Pre-load all textures into memory cache + for tex_path in texture_paths: + _preload_texture_for_scene(tex_path) + + # Rewrite the scene to use embedded textures or remove ext_resources + content = _rewrite_scene_for_runtime(content) + + # Parse and load the scene + var scene = _parse_tscn(content, file_path) + if scene: + _loaded_scenes[file_path] = scene + + return scene + +## Instantiate a scene and inject textures +## Call this instead of scene.instantiate() to get textures working +func instantiate_scene(file_path: String) -> Node: + var scene = load_scene(file_path) + if not scene: + return null + + var instance = scene.instantiate() + + # Inject textures into the instance + _inject_textures(instance, file_path) + + return instance + +## Extract texture paths from a .tscn file +func _extract_texture_paths(content: String) -> Array: + var paths = [] + var regex = RegEx.new() + regex.compile('\\[ext_resource[^\\]]*path="res://([^"]+)"[^\\]]*type="Texture2D"') + + for match in regex.search_all(content): + var path = match.get_string(1) + if not path in paths: + paths.append(path) + + return paths + +## Pre-load a texture that a scene needs +func _preload_texture_for_scene(res_path: String): + # res_path is like "assets/sprites/skeleton_idle_front.png" + var filename = res_path.get_file() + + # Try to find this texture in our cache + var cache_path = _find_texture_in_cache(filename) + if cache_path.is_empty(): + # Try with the full path structure + cache_path = _get_cache_path(res_path) + if not FileAccess.file_exists(cache_path): + push_warning("[UpdateManager] Texture not found for scene: %s" % res_path) + return + + # Load it into memory cache if not already there + if not _loaded_textures.has(res_path): + var texture = _load_texture_from_path(cache_path) + if texture: + _loaded_textures[res_path] = texture + # Also cache by filename for easier lookup + _loaded_textures[filename] = texture + print("[UpdateManager] Pre-loaded texture: %s" % res_path) + +## Load a texture from a file path (handles user:// paths properly) +func _load_texture_from_path(path: String) -> Texture2D: + if not FileAccess.file_exists(path): + return null + + var image = Image.new() + var err = image.load(path) + if err != OK: + push_error("[UpdateManager] Failed to load image: %s (error %d)" % [path, err]) + return null + + return ImageTexture.create_from_image(image) + +## Rewrite scene content to remove external texture references +## We'll inject textures at runtime instead +func _rewrite_scene_for_runtime(content: String) -> String: + # Remove ext_resource lines for Texture2D - we'll load them manually + var lines = content.split("\n") + var new_lines = [] + var texture_resource_ids = [] + + # First pass: identify texture ext_resources + var ext_res_regex = RegEx.new() + ext_res_regex.compile('\\[ext_resource[^\\]]*type="Texture2D"[^\\]]*id="([^"]+)"') + + for line in lines: + var match = ext_res_regex.search(line) + if match: + texture_resource_ids.append(match.get_string(1)) + # Skip this line (don't add to new_lines) + continue + new_lines.append(line) + + var result = "\n".join(new_lines) + + # Update load_steps count + var steps_regex = RegEx.new() + steps_regex.compile('load_steps=(\\d+)') + var steps_match = steps_regex.search(result) + if steps_match: + var old_steps = int(steps_match.get_string(1)) + var new_steps = old_steps - texture_resource_ids.size() + result = result.replace("load_steps=%d" % old_steps, "load_steps=%d" % new_steps) + + return result + +## Inject pre-loaded textures into a scene instance +func _inject_textures(instance: Node, scene_path: String): + # Find all AnimatedSprite2D and Sprite2D nodes + _inject_textures_recursive(instance) + +func _inject_textures_recursive(node: Node): + if node is AnimatedSprite2D: + _fix_animated_sprite(node) + elif node is Sprite2D: + _fix_sprite(node) + + for child in node.get_children(): + _inject_textures_recursive(child) + +func _fix_animated_sprite(sprite: AnimatedSprite2D): + if not sprite.sprite_frames: + return + + var frames = sprite.sprite_frames + + # Iterate through all animations + for anim_name in frames.get_animation_names(): + var frame_count = frames.get_frame_count(anim_name) + + for i in range(frame_count): + var texture = frames.get_frame_texture(anim_name, i) + + # If texture is an AtlasTexture, we need to fix its atlas + if texture is AtlasTexture: + var atlas_tex = texture as AtlasTexture + if atlas_tex.atlas == null: + # Try to find and assign the atlas texture + # The atlas might be referenced by a resource path we can match + pass # Atlas is already null, nothing to fix here + elif texture == null: + # Frame has no texture, might need to inject one + pass + +func _fix_sprite(sprite: Sprite2D): + # If the sprite has no texture, we could try to assign one + # But we need to know which texture it should have + pass + +## Search for a texture file anywhere in the cache +func _find_texture_in_cache(filename: String) -> String: + var dir = DirAccess.open(LOCAL_CACHE_DIR) + if not dir: + return "" + + return _find_file_recursive(dir, LOCAL_CACHE_DIR, filename) + +func _find_file_recursive(dir: DirAccess, current_path: String, filename: String) -> String: + dir.list_dir_begin() + var item = dir.get_next() + while item != "": + var full_path = current_path + item + if dir.current_is_dir(): + var subdir = DirAccess.open(full_path) + if subdir: + var found = _find_file_recursive(subdir, full_path + "/", filename) + if not found.is_empty(): + return found + elif item == filename: + return full_path + item = dir.get_next() + return "" + +## Load a texture from cache (for items, UI, etc.) +func load_texture(file_path: String) -> Texture2D: + # Check memory cache + if _loaded_textures.has(file_path): + return _loaded_textures[file_path] + + # Check disk cache + var cache_path = _get_cache_path(file_path) + if not FileAccess.file_exists(cache_path): + push_warning("[UpdateManager] Texture not in cache: %s" % file_path) + return null + + var file = FileAccess.open(cache_path, FileAccess.READ) + if not file: + return null + + var buffer = file.get_buffer(file.get_length()) + file.close() + + var image = Image.new() + var err = image.load_png_from_buffer(buffer) + if err != OK: + err = image.load_jpg_from_buffer(buffer) + if err != OK: + err = image.load_webp_from_buffer(buffer) + + if err != OK: + push_error("[UpdateManager] Failed to load image: %s" % file_path) + return null + + var texture = ImageTexture.create_from_image(image) + _loaded_textures[file_path] = texture + return texture + +## Check if a file is in the cache +func has_file(file_path: String) -> bool: + var cache_path = _get_cache_path(file_path) + return FileAccess.file_exists(cache_path) + +## Get the local cache path for a file +func get_cache_path(file_path: String) -> String: + return _get_cache_path(file_path) + +## Clear all cached files +func clear_cache(): + _loaded_scenes.clear() + _loaded_textures.clear() + _loaded_scripts.clear() + _local_hashes.clear() + + # Recursively delete cache directory + _delete_directory_recursive(LOCAL_CACHE_DIR) + DirAccess.make_dir_recursive_absolute(LOCAL_CACHE_DIR) + + _save_local_manifest() + +func _delete_directory_recursive(path: String): + var dir = DirAccess.open(path) + if not dir: + return + + dir.list_dir_begin() + var item = dir.get_next() + while item != "": + var full_path = path + "/" + item + if dir.current_is_dir(): + _delete_directory_recursive(full_path) + DirAccess.remove_absolute(full_path) + else: + DirAccess.remove_absolute(full_path) + item = dir.get_next() + +# ============ Internal Methods ============ + +func _parse_tscn(content: String, file_path: String) -> PackedScene: + # Save as a temp .tscn file and load it + # Godot doesn't have a direct way to parse tscn from string + var temp_path = "user://temp_scene_%d.tscn" % randi() + var temp_file = FileAccess.open(temp_path, FileAccess.WRITE) + if temp_file: + temp_file.store_string(content) + temp_file.close() + + var scene = load(temp_path) as PackedScene + # Clean up temp file + DirAccess.remove_absolute(temp_path) + return scene + + return null + +func _compute_md5(data: PackedByteArray) -> String: + var ctx = HashingContext.new() + ctx.start(HashingContext.HASH_MD5) + ctx.update(data) + var hash_bytes = ctx.finish() + return hash_bytes.hex_encode() + +func _compare_versions(v1: String, v2: String) -> int: + var parts1 = v1.split(".") + var parts2 = v2.split(".") + + for i in range(max(parts1.size(), parts2.size())): + var p1 = int(parts1[i]) if i < parts1.size() else 0 + var p2 = int(parts2[i]) if i < parts2.size() else 0 + if p1 < p2: + return -1 + elif p1 > p2: + return 1 + + return 0 + +func _load_local_manifest(): + if not FileAccess.file_exists(MANIFEST_CACHE_FILE): + return + + var file = FileAccess.open(MANIFEST_CACHE_FILE, FileAccess.READ) + if not file: + return + + var json_str = file.get_as_text() + file.close() + + var json = JSON.new() + if json.parse(json_str) == OK and json.data is Dictionary: + _local_hashes = json.data + print("[UpdateManager] Loaded local manifest with %d files" % _local_hashes.size()) + +func _save_local_manifest(): + var file = FileAccess.open(MANIFEST_CACHE_FILE, FileAccess.WRITE) + if file: + file.store_string(JSON.stringify(_local_hashes)) + file.close() diff --git a/scripts/autoload/update_manager.gd.uid b/scripts/autoload/update_manager.gd.uid new file mode 100644 index 0000000..dc88e68 --- /dev/null +++ b/scripts/autoload/update_manager.gd.uid @@ -0,0 +1 @@ +uid://cxcvje8d14mg2 diff --git a/scripts/dungeon/mob_visual.gd b/scripts/dungeon/mob_visual.gd index 82704ce..fa66d5c 100644 --- a/scripts/dungeon/mob_visual.gd +++ b/scripts/dungeon/mob_visual.gd @@ -1,24 +1,331 @@ extends Node2D -@onready var sprite = $Sprite2D -@onready var name_label = $NameLabel -@onready var health_bar = $HealthBar +## Mob Visual +## Renders mobs using sprite sheets from CDN with JSON animation config +## Falls back to simple shapes if assets aren't available + +var fallback_sprite: Sprite2D = null +var name_label: Label = null +var health_bar: ProgressBar = null var mob_data: Dictionary = {} +var _sprite_config: Dictionary = {} # Animation config from server +var _animated_sprite: AnimatedSprite2D = null +var _using_fallback: bool = true + +# Animation state +var _current_state: String = "idle" +var _facing_direction: String = "down" # down, up, left, right, front, back + +func _ready(): + # Try to find child nodes (they may not exist in all mob scenes) + fallback_sprite = get_node_or_null("Sprite2D") + name_label = get_node_or_null("NameLabel") + health_bar = get_node_or_null("HealthBar") + + # Create fallback sprite if it doesn't exist + if not fallback_sprite: + fallback_sprite = Sprite2D.new() + fallback_sprite.name = "FallbackSprite" + add_child(fallback_sprite) + + # Create name label if it doesn't exist + if not name_label: + name_label = Label.new() + name_label.name = "NameLabel" + name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + name_label.position = Vector2(-50, -35) + name_label.size = Vector2(100, 15) + add_child(name_label) + + # Create health bar if it doesn't exist + if not health_bar: + health_bar = ProgressBar.new() + health_bar.name = "HealthBar" + health_bar.position = Vector2(-20, -28) + health_bar.size = Vector2(40, 5) + health_bar.show_percentage = false + add_child(health_bar) + + # Connect to UpdateManager for async texture loading + if UpdateManager: + UpdateManager.file_downloaded.connect(_on_file_downloaded) func update_data(data: Dictionary): mob_data = data + # Update name var mname = data.get("name", data.get("Name", "Mob")) - name_label.text = mname + if name_label: + name_label.text = mname + # Update health bar var hp = data.get("health", data.get("Health", 100)) var max_hp = data.get("maxHealth", data.get("MaxHealth", 100)) - health_bar.max_value = max_hp - health_bar.value = hp + if health_bar: + health_bar.max_value = max_hp + health_bar.value = hp - var state = data.get("state", data.get("State", "idle")).to_lower() - if state == "attacking": - sprite.modulate = Color(1, 0.4, 0.4) # Reddish when attacking + # Get sprite config (sent from server with mob data) + var sprite_config = data.get("spriteConfig", data.get("SpriteConfig", null)) + + # Debug: print what we received + if sprite_config != null: + print("[MobVisual] %s received spriteConfig: %s" % [mname, sprite_config]) else: - sprite.modulate = Color(0.8, 0.3, 0.3) # Normal mob color + print("[MobVisual] %s has NO spriteConfig" % mname) + + if sprite_config != null and sprite_config is Dictionary and not sprite_config.is_empty(): + if sprite_config != _sprite_config: + _sprite_config = sprite_config + _build_animated_sprite() + elif _using_fallback: + _setup_fallback(data) + + # Update visual state + var state = data.get("state", data.get("State", "idle")).to_lower() + var rotation = data.get("rotation", data.get("Rotation", 0.0)) + _update_animation_state(state, rotation) + + # Apply tint + var tint = data.get("tintColor", data.get("TintColor", "#ffffff")) + _apply_tint(tint) + + # Apply scale + var mob_scale = data.get("scale", data.get("Scale", 1.0)) + print("[MobVisual] Raw scale from data: %s (type: %s)" % [mob_scale, typeof(mob_scale)]) + + # Ensure scale is valid (at least 1.0 if 0 or invalid) + if mob_scale == null or mob_scale <= 0: + mob_scale = 1.0 + + if _animated_sprite: + _animated_sprite.scale = Vector2.ONE * mob_scale + elif fallback_sprite: + fallback_sprite.scale = Vector2.ONE * mob_scale + +func _build_animated_sprite(): + ## Build AnimatedSprite2D from sprite config + + print("[MobVisual] _build_animated_sprite called for %s" % mob_data.get("name", "unknown")) + + var sprites = _sprite_config.get("sprites", {}) + print("[MobVisual] sprites dict type: %s, value: %s" % [typeof(sprites), sprites]) + + if sprites == null or not sprites is Dictionary or sprites.is_empty(): + print("[MobVisual] No sprites in config, using fallback") + _setup_fallback(mob_data) + return + + # Check if all required textures are cached + var all_cached = true + var missing_files = [] + for anim_name in sprites: + var sprite_path = sprites[anim_name] + print("[MobVisual] Checking texture: %s" % sprite_path) + if not UpdateManager: + print("[MobVisual] UpdateManager is null!") + all_cached = false + missing_files.append(sprite_path) + elif not UpdateManager.has_file(sprite_path): + print("[MobVisual] File NOT in cache: %s" % sprite_path) + all_cached = false + missing_files.append(sprite_path) + else: + print("[MobVisual] File IS in cache: %s" % sprite_path) + + if not all_cached: + print("[MobVisual] Missing textures: %s" % missing_files) + _setup_fallback(mob_data) + return + + print("[MobVisual] All textures cached, building AnimatedSprite2D") + + # Create or reuse AnimatedSprite2D + if not _animated_sprite: + _animated_sprite = AnimatedSprite2D.new() + _animated_sprite.name = "MobAnimatedSprite" + add_child(_animated_sprite) + + # Build SpriteFrames + var sprite_frames = SpriteFrames.new() + var frame_width = _sprite_config.get("frameWidth", 64) + var frame_height = _sprite_config.get("frameHeight", 64) + var fps = _sprite_config.get("fps", 8) + var animations = _sprite_config.get("animations", {}) + + for anim_name in sprites: + var sprite_path = sprites[anim_name] + var texture = UpdateManager.load_texture(sprite_path) + + if not texture: + push_warning("[MobVisual] Failed to load texture: %s" % sprite_path) + continue + + print("[MobVisual] Loaded texture %s: size=%dx%d" % [anim_name, texture.get_width(), texture.get_height()]) + + # Get animation config + var anim_config = animations.get(anim_name, {"frames": 1, "loop": true}) + var frame_count = anim_config.get("frames", 1) + var loop = anim_config.get("loop", true) + + # frame_count might be a float from JSON, convert to int + frame_count = int(frame_count) + + print("[MobVisual] Animation %s: frame_count=%d, loop=%s" % [anim_name, frame_count, loop]) + + # Add animation + sprite_frames.add_animation(anim_name) + sprite_frames.set_animation_speed(anim_name, fps) + sprite_frames.set_animation_loop(anim_name, loop) + + # Add frames from sprite sheet (horizontal strip) + var tex_width = texture.get_width() + var calculated_frames = int(tex_width / frame_width) if frame_width > 0 else 1 + frame_count = min(frame_count, calculated_frames) + + print("[MobVisual] Texture width=%d, frame_width=%d, calculated_frames=%d, using frame_count=%d" % [tex_width, frame_width, calculated_frames, frame_count]) + + for i in range(frame_count): + var atlas = AtlasTexture.new() + atlas.atlas = texture + atlas.region = Rect2(i * frame_width, 0, frame_width, frame_height) + sprite_frames.add_frame(anim_name, atlas) + + _animated_sprite.sprite_frames = sprite_frames + _animated_sprite.visible = true + _animated_sprite.z_index = 10 # Make sure it's on top + _animated_sprite.modulate = Color.WHITE # Ensure full visibility + _animated_sprite.position = Vector2.ZERO # Centered on parent + _using_fallback = false + + print("[MobVisual] AnimatedSprite2D position: %s, scale: %s, modulate: %s" % [_animated_sprite.position, _animated_sprite.scale, _animated_sprite.modulate]) + + # Hide fallback + if fallback_sprite: + fallback_sprite.visible = false + + # Play default animation + _update_animation_state(_current_state, 0.0) + + # Debug: print the animation that should be playing + print("[MobVisual] Built animated sprite with %d animations, current animation: %s, visible: %s" % [ + sprites.size(), + _animated_sprite.animation if _animated_sprite.sprite_frames else "none", + _animated_sprite.visible + ]) + +func _on_file_downloaded(file_path: String): + # Check if this is a texture we need + if not _sprite_config.is_empty(): + var sprites = _sprite_config.get("sprites", {}) + for anim_name in sprites: + if sprites[anim_name] == file_path: + # A texture we need was downloaded, try building again + _build_animated_sprite() + return + +func _setup_fallback(data: Dictionary): + _using_fallback = true + + # Hide animated sprite if exists + if _animated_sprite: + _animated_sprite.visible = false + + if fallback_sprite: + fallback_sprite.visible = true + + # Use SpriteGenerator for a simple shape + if SpriteGenerator: + fallback_sprite.texture = SpriteGenerator.get_circle() + + # Color based on mob type or default red + var tint = data.get("tintColor", data.get("TintColor", "#cc4444")) + fallback_sprite.modulate = Color.from_string(tint, Color(0.8, 0.3, 0.3)) + +func _update_animation_state(state: String, rotation: float): + _current_state = state + + # Determine facing direction from rotation + _facing_direction = _rotation_to_direction(rotation) + + if _animated_sprite and _animated_sprite.sprite_frames: + _play_animation(state, _facing_direction) + else: + _update_fallback_state(state) + +func _rotation_to_direction(rotation: float) -> String: + # Convert rotation (radians) to cardinal direction + # 0 = right, PI/2 = down, PI = left, -PI/2 = up + var angle = fmod(rotation + TAU, TAU) # Normalize to 0-2PI + + # Map to front/back/left/right (common sprite sheet naming) + if angle < PI * 0.25 or angle >= PI * 1.75: + return "right" + elif angle < PI * 0.75: + return "front" # or "down" + elif angle < PI * 1.25: + return "left" + else: + return "back" # or "up" + +func _play_animation(state: String, direction: String): + if not _animated_sprite or not _animated_sprite.sprite_frames: + return + + var frames = _animated_sprite.sprite_frames + + # Try different animation name formats + var names_to_try = [ + "%s_%s" % [state, direction], # "idle_front" + "%s_%s" % [state, _alt_direction(direction)], # "idle_down" + state, # "idle" + "idle_%s" % direction, # fallback to idle + "idle_%s" % _alt_direction(direction), + "idle" + ] + + for anim_name in names_to_try: + if frames.has_animation(anim_name): + print("[MobVisual] Playing animation: %s (current: %s, playing: %s)" % [anim_name, _animated_sprite.animation, _animated_sprite.is_playing()]) + _animated_sprite.play(anim_name) + + # Handle left direction with flip + _animated_sprite.flip_h = (direction == "left" and not frames.has_animation("%s_left" % state)) + return + + # No matching animation found + push_warning("[MobVisual] No animation found for state=%s direction=%s, available: %s" % [state, direction, frames.get_animation_names()]) + +func _alt_direction(dir: String) -> String: + # Alternative direction names + match dir: + "front": return "down" + "back": return "up" + "down": return "front" + "up": return "back" + _: return dir + +func _update_fallback_state(state: String): + if not fallback_sprite: + return + + # Simple color changes for fallback + match state: + "attacking": + fallback_sprite.modulate = fallback_sprite.modulate.lightened(0.3) + "chasing": + fallback_sprite.modulate = fallback_sprite.modulate.darkened(0.1) + "dead": + fallback_sprite.modulate = Color(0.3, 0.3, 0.3, 0.5) + _: + var tint = mob_data.get("tintColor", mob_data.get("TintColor", "#cc4444")) + fallback_sprite.modulate = Color.from_string(tint, Color(0.8, 0.3, 0.3)) + +func _apply_tint(tint_hex: String): + var tint_color = Color.from_string(tint_hex, Color.WHITE) + + if _animated_sprite: + _animated_sprite.modulate = tint_color + elif fallback_sprite: + fallback_sprite.modulate = tint_color diff --git a/scripts/ui/auth_ui.gd b/scripts/ui/auth_ui.gd index 915bdea..1980152 100644 --- a/scripts/ui/auth_ui.gd +++ b/scripts/ui/auth_ui.gd @@ -47,6 +47,7 @@ func _on_login_pressed(): "UsernameOrEmail": user, "Password": pass_text }) + func _on_register_pressed(): var user = reg_username.text.strip_edges() diff --git a/scripts/ui/hud.gd b/scripts/ui/hud.gd index 1914adb..22bba64 100644 --- a/scripts/ui/hud.gd +++ b/scripts/ui/hud.gd @@ -254,6 +254,10 @@ func add_log_entry(text: String, color: Color): label.queue_free() ) - # Keep log from getting too long - while event_log.get_child_count() > 10: - event_log.get_child(0).queue_free() + # Keep log from getting too long (use call_deferred to avoid modifying during iteration) + if event_log.get_child_count() > 10: + var to_remove = event_log.get_child_count() - 10 + for i in range(to_remove): + var child = event_log.get_child(0) + if is_instance_valid(child): + child.queue_free() diff --git a/scripts/ui/main.gd b/scripts/ui/main.gd index a98349a..ff508cb 100644 --- a/scripts/ui/main.gd +++ b/scripts/ui/main.gd @@ -29,6 +29,10 @@ func _show_screen(state: String): if auth_screen: _set_screen_visible(auth_screen, state == "AUTH") print("[Main] AuthScreen visible: ", state == "AUTH") + if not Network.is_socket_connected(): + Network.connect_to_server() + await Network.connected + UpdateManager.check_for_updates() if hub_screen: _set_screen_visible(hub_screen, state == "HUB") print("[Main] HubScreen visible: ", state == "HUB") diff --git a/scripts/ui/mob_old.gd b/scripts/ui/mob_old.gd new file mode 100644 index 0000000..b93c481 --- /dev/null +++ b/scripts/ui/mob_old.gd @@ -0,0 +1,33 @@ +extends Node2D + +@onready var sprite: Sprite2D = $Sprite +@onready var name_label: Label = $NameLabel +@onready var health_bar: ProgressBar = $HealthBar + +var mob_data: Dictionary = {} + +func _ready(): + # Get texture from generator if available + if SpriteGenerator: + sprite.texture = SpriteGenerator.get_circle() + + # Default mob color (red) + sprite.modulate = Color(0.67, 0.27, 0.27) # #aa4444 + +func update_data(data: Dictionary): + mob_data = data + + var mname = data.get("name", data.get("Name", "Mob")) + name_label.text = mname + + var hp = data.get("health", data.get("Health", 100)) + var max_hp = data.get("maxHealth", data.get("MaxHealth", 100)) + health_bar.max_value = max_hp + health_bar.value = hp + + # Change color based on state + var state = str(data.get("state", data.get("State", "idle"))).to_lower() + if state == "attacking": + sprite.modulate = Color(1.0, 0.4, 0.4) # Bright red when attacking + else: + sprite.modulate = Color(0.67, 0.27, 0.27) # Normal red diff --git a/scripts/ui/mob_old.gd.uid b/scripts/ui/mob_old.gd.uid new file mode 100644 index 0000000..62eee0a --- /dev/null +++ b/scripts/ui/mob_old.gd.uid @@ -0,0 +1 @@ +uid://1746typ7rv6s