Files
commander-ai-lab/unity-client/Assets/Scripts/Services/ImageCache.cs
T
KoalaTrapLord 3f5d6d12e8 feat: 4-player Commander Battleground UI (issues #138–#151)
* chore: add battleground UI task tracker (2026-03-28)

* feat(#142): add [NonSerialized] battleground runtime state to CardModel

* feat(#143): add LoadArtCrop and LoadCardRaw (RawImage) to ImageCache

* feat(#148): add GameStateManager singleton and GameState/SeatState POCOs

* feat(#138): add BattlegroundController scene orchestrator

* feat(#139): add LifeTrackerWidget, CommanderDamageRow, PoisonCounter

* feat(#140): add PhaseTrackerWidget and PhaseStepButton

* feat(#141): add TurnOrderBar and TurnOrderPill

* feat(#142): add CardZone and CardView battlefield zone components

* feat(#143): add CommanderZoneWidget with art crop, cast counter, and tax display

* feat(#144): add TokenModel POCO, TokenPanelController, and TokenRowView

* chore: mark issues 1-8 as complete in task tracker

* feat(#146): add StackZoneController, StackItemView, and ManaPoolDisplay

* feat(#147 #150 #151): add LobbySetupModal, ZoneViewerModal, EliminationHandler; add Play Live button to SimulationController

* feat(#151): add Play Live button to SimulationController

* feat(#149): add GameWebSocketClient with reconnect, ping, and main-thread dispatch

* fix: add PostGameAction to ApiClient + update TODO.md all issues complete

- ApiClient.cs: add PostGameAction() wrapper → POST /api/game/action
  (fixes compile error in HumanActionBar.cs)
- TODO.md: mark issues #145, #146, #147, #149, #150, #151 as ✅
  all 14 battleground issues now committed

* feat(game): add routes/game.py + wire lab_api + fix GameWebSocketClient game_id URL

- routes/game.py: POST /api/game/start, POST /api/game/action (new)
- lab_api.py: import + register game_router
- GameWebSocketClient.cs: read game_id from PlayerPrefs, build
  ws://{host}/ws/game/{game_id} — fixes URL mismatch with ws_game.py

* fix(lobby): wire OnConfirm to POST /api/game/start, save game_id to PlayerPrefs

- OnConfirm() now calls ApiClient.PostGameStart() with 4-seat config
- On success: saves BattleSeats + GameId + WsUrl to PlayerPrefs,
  loads Battleground scene
- On failure: shows inline error label (red), re-enables Confirm button
- Added StartGameRequest/Response POCOs matching routes/game.py schema
- Added _errorLabel [SerializeField] for user-facing error feedback
2026-03-29 05:35:29 -04:00

93 lines
3.9 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
namespace CommanderAILab.Services
{
/// <summary>
/// Singleton texture cache for card images.
/// Downloads and caches Scryfall card art as Sprite or Texture2D.
/// </summary>
public class ImageCache : MonoBehaviour
{
public static ImageCache Instance { get; private set; }
private readonly Dictionary<string, Sprite> _spriteCache = new();
private readonly Dictionary<string, Texture2D> _textureCache = new();
[SerializeField] private int maxCacheSize = 500;
private void Awake()
{
if (Instance != null && Instance != this) { Destroy(gameObject); return; }
Instance = this;
DontDestroyOnLoad(gameObject);
}
// ── Sprite (existing usage) ───────────────────────────────────────────
public void GetSprite(string url, Action<Sprite> callback)
{
if (string.IsNullOrEmpty(url)) { callback?.Invoke(null); return; }
if (_spriteCache.TryGetValue(url, out var cached)) { callback?.Invoke(cached); return; }
StartCoroutine(DownloadSprite(url, callback));
}
private IEnumerator DownloadSprite(string url, Action<Sprite> callback)
{
using var req = UnityWebRequestTexture.GetTexture(url);
yield return req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"[ImageCache] Sprite failed {url}: {req.error}");
callback?.Invoke(null);
yield break;
}
var tex = DownloadHandlerTexture.GetContent(req);
var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.one * 0.5f);
if (_spriteCache.Count >= maxCacheSize) _spriteCache.Clear();
_spriteCache[url] = sprite;
callback?.Invoke(sprite);
}
// ── RawImage / Texture2D (battleground CardView + CommanderZoneWidget) ───
/// <summary>Load a card image URL directly into a RawImage component.</summary>
public IEnumerator LoadCard(string url, RawImage target)
{
if (target == null || string.IsNullOrEmpty(url)) yield break;
if (_textureCache.TryGetValue(url, out var cached)) { target.texture = cached; yield break; }
yield return DownloadTexture(url, tex => { if (target != null) target.texture = tex; });
}
/// <summary>
/// Load Scryfall art_crop into a RawImage by card name.
/// URL: https://api.scryfall.com/cards/named?exact={name}&format=image&version=art_crop
/// </summary>
public IEnumerator LoadArtCrop(string cardName, RawImage target)
{
if (target == null || string.IsNullOrEmpty(cardName)) yield break;
string url = $"https://api.scryfall.com/cards/named?exact={Uri.EscapeDataString(cardName)}&format=image&version=art_crop";
yield return LoadCard(url, target);
}
private IEnumerator DownloadTexture(string url, Action<Texture2D> callback)
{
using var req = UnityWebRequestTexture.GetTexture(url);
yield return req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning($"[ImageCache] Texture failed {url}: {req.error}");
callback?.Invoke(null);
yield break;
}
var tex = DownloadHandlerTexture.GetContent(req);
if (_textureCache.Count >= maxCacheSize) _textureCache.Clear();
_textureCache[url] = tex;
callback?.Invoke(tex);
}
public void ClearCache() { _spriteCache.Clear(); _textureCache.Clear(); }
}
}