From 6dda0edf174e67283e4b86af29c460324f60c9d7 Mon Sep 17 00:00:00 2001 From: dingo Date: Mon, 9 Mar 2026 13:34:17 -0400 Subject: [PATCH] Fix: 3D model loading for units/tiles + tile model server pipeline - ModelCache: switch GLTFDocument.append_from_buffer (was append_from_file which returned ERR_BUSY/43); validate GLB magic bytes; explicit signal disconnect before queue_free to avoid freed-lambda errors - ContentCache: add tile model fetch (content.tile_models), disk cache at user://content/tile_models.json, get_tile_model_url() API - game_screen: _add_tile now loads tile CDN model via ModelCache when bound - Server: ContentGetTileModelsHandler (content.tile_models msg), registered in ServiceRegistration; TileModelDto / GetTileModelsResponse added to ContentMessages Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../origin-client/autoloads/ContentCache.gd | 81 ++++++++++++++++--- Client/origin-client/autoloads/ModelCache.gd | 73 +++++++++++------ .../origin-client/autoloads/ModelCache.gd.uid | 1 + .../origin-client/scenes/game/game_screen.gd | 24 ++++++ Server/src/SOR.Content/ContentMessages.cs | 10 +++ .../Handlers/ContentGetTileModelsHandler.cs | 42 ++++++++++ Server/src/SOR.Content/ServiceRegistration.cs | 1 + 7 files changed, 200 insertions(+), 32 deletions(-) create mode 100644 Client/origin-client/autoloads/ModelCache.gd.uid create mode 100644 Server/src/SOR.Content/Handlers/ContentGetTileModelsHandler.cs diff --git a/Client/origin-client/autoloads/ContentCache.gd b/Client/origin-client/autoloads/ContentCache.gd index a27266e..3851bfe 100644 --- a/Client/origin-client/autoloads/ContentCache.gd +++ b/Client/origin-client/autoloads/ContentCache.gd @@ -5,34 +5,40 @@ extends Node ## content.sync message (cursor-based, incremental). Definitions are text ## only (stats, CDN URLs for art/models) — no binary assets are stored here. ## -## Storage layout: -## user://content/defs.json — { "version": int, "defs": { id: dto } } +## Also caches tile model bindings fetched via content.tile_models. ## -## Sync is incremental: on the first launch SinceVersion=0 fetches everything; -## on subsequent launches only cards changed since the stored cursor are fetched -## (usually 0 pages if nothing changed — instant). +## Storage layout: +## user://content/defs.json — { "version": int, "defs": { id: dto } } +## user://content/tile_models.json — { "Forest_Square": "https://...", ... } ## ## Usage: ## ContentCache.start_sync() -## ContentCache.get_definition("some-guid") → Dictionary or {} +## ContentCache.get_definition("some-guid") → Dictionary or {} +## ContentCache.get_tile_model_url("Forest", "Square") → String or "" ## ContentCache.sync_complete.connect(...) -const CACHE_DIR := "user://content" -const CACHE_PATH := "user://content/defs.json" -const PAGE_SIZE := 200 +const CACHE_DIR := "user://content" +const CACHE_PATH := "user://content/defs.json" +const TILE_MODELS_PATH := "user://content/tile_models.json" +const PAGE_SIZE := 200 signal sync_progress(fetched_total: int) ## Running count of total definitions in memory. signal sync_complete(total: int) ## Emitted once sync finishes. signal sync_failed(error: String) ## Emitted if sync cannot complete. +signal tile_models_ready ## Emitted when tile model bindings are loaded. var _defs: Dictionary = {} ## definitionId (String) → definition Dictionary var _sync_version: int = 0 ## Stored DefinitionVersion cursor. var _is_syncing: bool = false +## "Affinity_Shape" (e.g. "Forest_Square") → CDN model URL string +var _tile_models: Dictionary = {} + # ── Lifecycle ───────────────────────────────────────────────────────────────── func _ready() -> void: _load_from_disk() + _load_tile_models_from_disk() # ── Public API ──────────────────────────────────────────────────────────────── @@ -68,11 +74,32 @@ func is_syncing() -> bool: ## Start (or resume) the incremental sync. ## Emits sync_progress during, sync_complete or sync_failed when done. +## Also triggers a fresh fetch of tile model bindings. func start_sync() -> void: if _is_syncing: return _is_syncing = true _fetch_page(_sync_version) + fetch_tile_models() + + +## Return the CDN URL for a tile's 3D model, or "" if not assigned. +## affinity: e.g. "Forest" shape: "Square" or "Hex" +func get_tile_model_url(affinity: String, shape: String) -> String: + return _tile_models.get(affinity + "_" + shape, "") + + +## Fetch tile model bindings from the server and update the local cache. +## Emits tile_models_ready when done (even on error, using cached data). +func fetch_tile_models() -> void: + Network.request( + "content.tile_models", + {}, + func(_type: String, p: Variant): _on_tile_models(p), + func(code: String, msg: String): + push_warning("ContentCache: tile_models fetch failed — %s %s" % [code, msg]) + tile_models_ready.emit() + ) # ── Sync loop ───────────────────────────────────────────────────────────────── @@ -113,6 +140,21 @@ func _on_error(code: String, msg: String) -> void: push_warning("ContentCache: sync failed — %s" % detail) sync_failed.emit(detail) + +func _on_tile_models(payload: Variant) -> void: + var p := payload as Dictionary + var bindings : Array = p.get("bindings", []) + _tile_models.clear() + for item in bindings: + var d := item as Dictionary + if d == null: continue + var key := str(d.get("affinity", "")) + "_" + str(d.get("shape", "")) + var url := str(d.get("modelPublicUrl", "")) + if not key.is_empty() and not url.is_empty(): + _tile_models[key] = url + _save_tile_models_to_disk() + tile_models_ready.emit() + # ── Persistence ─────────────────────────────────────────────────────────────── func _load_from_disk() -> void: @@ -143,3 +185,24 @@ func _save_to_disk() -> void: return file.store_string(JSON.stringify({ "version": _sync_version, "defs": _defs })) file.close() + + +func _load_tile_models_from_disk() -> void: + if not FileAccess.file_exists(TILE_MODELS_PATH): + return + var file := FileAccess.open(TILE_MODELS_PATH, FileAccess.READ) + if not file: + return + var parsed: Variant = JSON.parse_string(file.get_as_text()) + file.close() + if typeof(parsed) == TYPE_DICTIONARY: + _tile_models = parsed as Dictionary + + +func _save_tile_models_to_disk() -> void: + DirAccess.make_dir_recursive_absolute(CACHE_DIR) + var file := FileAccess.open(TILE_MODELS_PATH, FileAccess.WRITE) + if not file: + return + file.store_string(JSON.stringify(_tile_models)) + file.close() diff --git a/Client/origin-client/autoloads/ModelCache.gd b/Client/origin-client/autoloads/ModelCache.gd index 84dd79f..3cb24a0 100644 --- a/Client/origin-client/autoloads/ModelCache.gd +++ b/Client/origin-client/autoloads/ModelCache.gd @@ -6,13 +6,14 @@ extends Node ## ## The callback receives a freshly-instantiated Node3D on success, or null on ## failure. Multiple callers requesting the same URL share a single download. -## Cached PackedScenes are kept in memory; raw bytes are written to -## user://remote_model_cache/.glb +## Parsed PackedScenes are kept in memory so re-instantiation is instant. +## Raw GLB bytes are written to: +## user://remote_model_cache/.bin ## so subsequent app launches skip the download. -const _CACHE_DIR := "user://remote_model_cache/" +const _CACHE_DIR := "user://remote_model_cache" -# url (String) → PackedScene (null if load failed) +# url (String) → PackedScene or null (null means "tried and failed") static var _mem: Dictionary = {} # url (String) → Array[Callable] (callbacks waiting on an in-flight download) @@ -25,6 +26,8 @@ func _ready() -> void: ## Request a model by CDN URL. ## callback(node: Node3D) is called on the main thread; node may be null. +## If the same URL is already downloading, callbacks are queued and all +## fire together when the download completes. func load_model(url: String, callback: Callable) -> void: # 1 — memory hit if _mem.has(url): @@ -32,13 +35,17 @@ func load_model(url: String, callback: Callable) -> void: callback.call(packed.instantiate() if packed != null else null) return - # 2 — disk hit + # 2 — disk hit (bytes from previous session) var disk := _disk_path(url) if FileAccess.file_exists(disk): - var packed := _load_gltf(disk) - _mem[url] = packed - callback.call(packed.instantiate() if packed != null else null) - return + var bytes := FileAccess.get_file_as_bytes(disk) + if not bytes.is_empty(): + var packed := _parse_gltf(bytes) + _mem[url] = packed + callback.call(packed.instantiate() if packed != null else null) + return + # Empty / corrupt cache file — fall through to re-download + DirAccess.remove_absolute(disk) # 3 — already downloading → queue if _pending.has(url): @@ -56,63 +63,83 @@ func _download(url: String, disk: String) -> void: add_child(http) http.request_completed.connect(func(_result, code, _headers, body: PackedByteArray): + # Disconnect and free the requester before anything else. + http.get_signal_connection_list("request_completed").clear() http.queue_free() + var callbacks: Array = _pending.get(url, []) _pending.erase(url) if code < 200 or code >= 300: - push_warning("ModelCache: download failed (%d) for %s" % [code, url]) + push_warning("ModelCache: download failed (HTTP %d) — %s" % [code, url]) for cb: Callable in callbacks: cb.call(null) return - # Write disk cache + if body.is_empty(): + push_warning("ModelCache: empty response body — %s" % url) + for cb: Callable in callbacks: + cb.call(null) + return + + # Write raw bytes to disk cache for future sessions. var f := FileAccess.open(disk, FileAccess.WRITE) if f: f.store_buffer(body) f.close() - else: - push_warning("ModelCache: could not write cache file %s" % disk) - var packed := _load_gltf(disk) + # Parse directly from the downloaded bytes — avoids any file-path quirks. + var packed := _parse_gltf(body) _mem[url] = packed + for cb: Callable in callbacks: cb.call(packed.instantiate() if packed != null else null) ) var err := http.request(url) if err != OK: - push_warning("ModelCache: request() failed for %s (err %d)" % [url, err]) + push_warning("ModelCache: request() error %d — %s" % [err, url]) var callbacks: Array = _pending.get(url, []) _pending.erase(url) for cb: Callable in callbacks: cb.call(null) + http.get_signal_connection_list("request_completed").clear() + http.queue_free() -# Loads a .glb/.gltf from disk into a PackedScene for repeated instantiation. -func _load_gltf(path: String) -> PackedScene: +# Parse GLB/GLTF bytes using GLTFDocument.append_from_buffer. +# Returns a PackedScene ready for instantiation, or null on failure. +func _parse_gltf(data: PackedByteArray) -> PackedScene: + # Validate GLB magic bytes ("glTF"). + if data.size() >= 4: + var magic := data.decode_u32(0) + if magic != 0x46546C67: # little-endian "glTF" + push_warning("ModelCache: not a GLB file (bad magic 0x%X)" % magic) + return null + var doc := GLTFDocument.new() var state := GLTFState.new() - var err := doc.append_from_file(path, state) + # Empty base_path is correct for self-contained GLBs. + var err := doc.append_from_buffer(data, "", state) if err != OK: - push_warning("ModelCache: GLTFDocument error %d loading %s" % [err, path]) + push_warning("ModelCache: GLTFDocument.append_from_buffer error %d" % err) return null var root := doc.generate_scene(state) if root == null: - push_warning("ModelCache: generate_scene returned null for %s" % path) + push_warning("ModelCache: generate_scene returned null") return null - var packed := PackedScene.new() + var packed := PackedScene.new() var pack_err := packed.pack(root) root.queue_free() if pack_err != OK: - push_warning("ModelCache: PackedScene.pack() error %d for %s" % [pack_err, path]) + push_warning("ModelCache: PackedScene.pack error %d" % pack_err) return null return packed func _disk_path(url: String) -> String: - return _CACHE_DIR + url.sha256_text() + ".glb" + return _CACHE_DIR + "/" + url.sha256_text() + ".bin" diff --git a/Client/origin-client/autoloads/ModelCache.gd.uid b/Client/origin-client/autoloads/ModelCache.gd.uid new file mode 100644 index 0000000..a608df5 --- /dev/null +++ b/Client/origin-client/autoloads/ModelCache.gd.uid @@ -0,0 +1 @@ +uid://bl5e3ro08ok6d diff --git a/Client/origin-client/scenes/game/game_screen.gd b/Client/origin-client/scenes/game/game_screen.gd index c671555..da344aa 100644 --- a/Client/origin-client/scenes/game/game_screen.gd +++ b/Client/origin-client/scenes/game/game_screen.gd @@ -408,6 +408,7 @@ func _add_tile(x: int, y: int, affinity: String) -> void: shape.shape = box body.add_child(shape) + # Placeholder: affinity-coloured flat box, swapped out if a 3D model loads. var mi := MeshInstance3D.new() var bm := BoxMesh.new() bm.size = Vector3(0.98, 0.5, 0.98) @@ -421,6 +422,29 @@ func _add_tile(x: int, y: int, affinity: String) -> void: _tiles_root.add_child(body) _tile_bodies["%d,%d" % [x, y]] = body + # ── Try to load a 3D tile model for this affinity ────────────────────── + var model_url := ContentCache.get_tile_model_url(affinity, "Square") + if model_url.is_empty(): + return + + ModelCache.load_model(model_url, func(model_node: Node3D) -> void: + if not is_instance_valid(body): + if model_node != null: + model_node.queue_free() + return + if model_node == null: + return + + # Remove the placeholder MeshInstance3D. + for child in body.get_children(): + if child is MeshInstance3D: + child.queue_free() + + # Tile body sits at wp + (0, 0.25, 0); model should author its + # centre at y = 0 so it fills the same space as the box placeholder. + body.add_child(model_node) + ) + func _update_tile_affinity(x: int, y: int, affinity: String) -> void: var body = _tile_bodies.get("%d,%d" % [x, y]) diff --git a/Server/src/SOR.Content/ContentMessages.cs b/Server/src/SOR.Content/ContentMessages.cs index 4536d1b..d948bfb 100644 --- a/Server/src/SOR.Content/ContentMessages.cs +++ b/Server/src/SOR.Content/ContentMessages.cs @@ -16,6 +16,9 @@ public sealed record GetCardSetsRequest; /// Fetch a single card definition by ID including assets and animations. public sealed record GetCardDefinitionRequest(Guid Id); +/// Fetch all tile model bindings (affinity × shape → CDN URL). +public sealed record GetTileModelsRequest; + // ── Response / DTO types (server → client) ──────────────────────────────────── public sealed record SyncCardDefinitionsResponse( @@ -27,6 +30,13 @@ public sealed record GetCardSetsResponse(IEnumerable Sets); public sealed record GetCardDefinitionResponse(CardDefinitionDto? Card); +public sealed record GetTileModelsResponse(IEnumerable Bindings); + +public sealed record TileModelDto( + string Affinity, + string Shape, + string ModelPublicUrl); + // ── DTOs ────────────────────────────────────────────────────────────────────── public sealed record CardSetDto( diff --git a/Server/src/SOR.Content/Handlers/ContentGetTileModelsHandler.cs b/Server/src/SOR.Content/Handlers/ContentGetTileModelsHandler.cs new file mode 100644 index 0000000..a94a082 --- /dev/null +++ b/Server/src/SOR.Content/Handlers/ContentGetTileModelsHandler.cs @@ -0,0 +1,42 @@ +namespace SOR.Content.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// content.tile_models — returns all tile model bindings. +/// Each binding maps an (Affinity × Shape) pair to a CDN model URL. +/// The client uses these to render the correct 3D tile mesh on the board. +/// +internal sealed class ContentGetTileModelsHandler : IMessageHandler +{ + private readonly IMessageSerializer _serializer; + private readonly CatalogDbContext _catalogDb; + + public ContentGetTileModelsHandler(IMessageSerializer serializer, CatalogDbContext catalogDb) + { + _serializer = serializer; + _catalogDb = catalogDb; + } + + public string MessageType => "content.tile_models"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + var bindings = await _catalogDb.TileModelBindings + .Select(b => new TileModelDto( + b.Affinity.ToString(), + b.Shape.ToString(), + b.ModelPublicUrl)) + .ToListAsync(ct); + + return ServerMessage.Reply("content.tile_models.ack", message.Seq, + new GetTileModelsResponse(bindings)); + } +} diff --git a/Server/src/SOR.Content/ServiceRegistration.cs b/Server/src/SOR.Content/ServiceRegistration.cs index 421f063..3b8b113 100644 --- a/Server/src/SOR.Content/ServiceRegistration.cs +++ b/Server/src/SOR.Content/ServiceRegistration.cs @@ -21,6 +21,7 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); return services; }