277 lines
9.0 KiB
GDScript
277 lines
9.0 KiB
GDScript
extends Node
|
|
## HighlightConfig autoload — fetches and caches tile highlight texture configuration.
|
|
##
|
|
## Usage:
|
|
## HighlightConfig.get_texture("movement") → Texture2D or null
|
|
## HighlightConfig.get_color("movement") → Color (parsed from fallbackHex)
|
|
## HighlightConfig.is_ready → bool
|
|
##
|
|
## Cosmetic overrides (via Settings.highlight_overrides or equipped HighlightPack):
|
|
## HighlightConfig.set_override("movement", { cdnPath=…, isAnimated=false, … })
|
|
## HighlightConfig.clear_override("movement")
|
|
## HighlightConfig.clear_all_overrides()
|
|
##
|
|
## Texture loading is async. Callers should handle null gracefully and fall back to
|
|
## get_color() when get_texture() returns null.
|
|
|
|
signal loaded
|
|
signal texture_loaded(type: String)
|
|
|
|
const CACHE_PATH := "user://highlight_config.json"
|
|
const REQUEST_TYPE := "content.get_highlight_config"
|
|
|
|
## Default fallback colours used when no server config exists.
|
|
const DEFAULT_HEX : Dictionary = {
|
|
"movement": "#33FF3366",
|
|
"attack": "#FF404080",
|
|
"ability": "#3380FF66",
|
|
"terramorpha": "#FF990073",
|
|
"selector": "#FFFFFF40",
|
|
}
|
|
|
|
## Whether the server config has been loaded (or the cache has been used).
|
|
var is_ready : bool = false
|
|
var _fetch_in_flight : bool = false
|
|
|
|
# ── Internal state ─────────────────────────────────────────────────────────────
|
|
|
|
# Server-provided configs keyed by lowercase type name.
|
|
# Each entry: { cdnPath, isAnimated, frameCount, fps, fallbackHex }
|
|
var _server_configs : Dictionary = {}
|
|
|
|
# Admin/cosmetic overrides — same structure, keyed by lowercase type name.
|
|
var _overrides : Dictionary = {}
|
|
|
|
# Loaded textures: type → Texture2D (null while loading or if failed).
|
|
var _textures : Dictionary = {}
|
|
|
|
# HTTP fetch nodes keyed by type (to avoid duplicate requests).
|
|
var _pending_fetches : Dictionary = {}
|
|
|
|
# ── Lifecycle ──────────────────────────────────────────────────────────────────
|
|
|
|
func _ready() -> void:
|
|
_load_cache()
|
|
_prefetch_known_textures()
|
|
Auth.auth_success.connect(_on_auth_success)
|
|
Network.connected.connect(_on_network_connected)
|
|
if not Auth.user_id.is_empty():
|
|
_fetch_from_server()
|
|
|
|
|
|
# ── Public API ─────────────────────────────────────────────────────────────────
|
|
|
|
## Returns the loaded Texture2D for this highlight type, or null if not yet loaded.
|
|
## Starts loading the texture on first call if not already in progress.
|
|
func get_texture(type: String) -> Texture2D:
|
|
if not is_ready:
|
|
_fetch_from_server()
|
|
var key := type.to_lower()
|
|
if _textures.has(key):
|
|
return _textures[key]
|
|
# Start loading if we have a config for this type.
|
|
var cfg := _effective_config(key)
|
|
if not cfg.is_empty() and not cfg.get("cdnPath", "").is_empty():
|
|
_start_texture_load(key, cfg)
|
|
return null
|
|
|
|
|
|
## Returns the fallback Color for this highlight type.
|
|
func get_color(type: String) -> Color:
|
|
if not is_ready:
|
|
_fetch_from_server()
|
|
var key := type.to_lower()
|
|
var cfg := _effective_config(key)
|
|
var hex : String = cfg.get("fallbackHex", DEFAULT_HEX.get(key, "#FFFFFF66"))
|
|
return _parse_hex(hex)
|
|
|
|
|
|
## Override a highlight type with a custom config dict.
|
|
## Config keys: cdnPath (String), isAnimated (bool), frameCount (int), fps (float), fallbackHex (String).
|
|
func set_override(type: String, config: Dictionary) -> void:
|
|
var key := type.to_lower()
|
|
_overrides[key] = config
|
|
_textures.erase(key) # Invalidate cached texture so next get_texture() reloads.
|
|
_pending_fetches.erase(key)
|
|
|
|
|
|
## Remove override for one type.
|
|
func clear_override(type: String) -> void:
|
|
var key := type.to_lower()
|
|
_overrides.erase(key)
|
|
_textures.erase(key)
|
|
_pending_fetches.erase(key)
|
|
|
|
|
|
## Remove all cosmetic/settings overrides.
|
|
func clear_all_overrides() -> void:
|
|
_overrides.clear()
|
|
_textures.clear()
|
|
_pending_fetches.clear()
|
|
|
|
|
|
## Apply an equipped HighlightPack cosmetic (parsed from AssetCdnUrl JSON).
|
|
## pack_data: Dictionary keyed by lowercase type name, each value is a config dict.
|
|
func apply_cosmetic_pack(pack_data: Dictionary) -> void:
|
|
for key in pack_data:
|
|
set_override(str(key).to_lower(), pack_data[key] as Dictionary)
|
|
|
|
|
|
# ── Internal ───────────────────────────────────────────────────────────────────
|
|
|
|
func _effective_config(key: String) -> Dictionary:
|
|
if _overrides.has(key):
|
|
return _overrides[key] as Dictionary
|
|
if _server_configs.has(key):
|
|
return _server_configs[key] as Dictionary
|
|
return {}
|
|
|
|
|
|
func _fetch_from_server() -> void:
|
|
if _fetch_in_flight:
|
|
return
|
|
if not Network.is_online():
|
|
return
|
|
if Auth.user_id.is_empty():
|
|
return
|
|
_fetch_in_flight = true
|
|
Network.request(
|
|
REQUEST_TYPE,
|
|
{},
|
|
func(_type: String, resp: Variant) -> void:
|
|
_fetch_in_flight = false
|
|
_on_server_response(resp),
|
|
func(code: String, msg: String) -> void:
|
|
_fetch_in_flight = false
|
|
if code not in ["DISCONNECTED", "AUTH_REQUIRED"]:
|
|
push_warning("HighlightConfig: config fetch failed - %s %s" % [code, msg])
|
|
)
|
|
|
|
|
|
func _on_server_response(resp: Variant) -> void:
|
|
var configs : Array = (resp as Dictionary).get("configs", [])
|
|
_server_configs.clear()
|
|
for entry : Dictionary in configs:
|
|
var key : String = str(entry.get("highlightType", "")).to_lower()
|
|
if key.is_empty():
|
|
continue
|
|
_server_configs[key] = {
|
|
"cdnPath": str(entry.get("cdnPath", "")),
|
|
"isAnimated": bool(entry.get("isAnimated", false)),
|
|
"frameCount": int(entry.get("frameCount", 1)),
|
|
"fps": float(entry.get("fps", 12.0)),
|
|
"fallbackHex": str(entry.get("fallbackHex", DEFAULT_HEX.get(key, "#FFFFFF66"))),
|
|
}
|
|
_save_cache()
|
|
_prefetch_known_textures()
|
|
is_ready = true
|
|
loaded.emit()
|
|
|
|
|
|
func _on_auth_success(_user_id: String, _display_name: String) -> void:
|
|
_fetch_from_server()
|
|
|
|
|
|
func _on_network_connected() -> void:
|
|
if not Auth.user_id.is_empty():
|
|
_fetch_from_server()
|
|
|
|
|
|
func _start_texture_load(key: String, cfg: Dictionary) -> void:
|
|
if _pending_fetches.has(key):
|
|
return
|
|
var url := _normalize_url(str(cfg.get("cdnPath", "")))
|
|
if url.is_empty():
|
|
return
|
|
_pending_fetches[key] = true
|
|
|
|
var http := HTTPRequest.new()
|
|
add_child(http)
|
|
http.request_completed.connect(
|
|
func(result: int, code: int, _headers: PackedStringArray, body: PackedByteArray) -> void:
|
|
http.queue_free()
|
|
_pending_fetches.erase(key)
|
|
if result != HTTPRequest.RESULT_SUCCESS or code != 200 or body.is_empty():
|
|
push_warning("HighlightConfig: failed to download %s (result=%d http=%d url=%s)" % [key, result, code, url])
|
|
return
|
|
var img := Image.new()
|
|
var err := _load_image_from_body(img, url, body)
|
|
if err != OK:
|
|
push_warning("HighlightConfig: failed to decode %s from %s" % [key, url])
|
|
return
|
|
var tex := ImageTexture.create_from_image(img)
|
|
_textures[key] = tex
|
|
texture_loaded.emit(key)
|
|
)
|
|
var err := http.request(url)
|
|
if err != OK:
|
|
_pending_fetches.erase(key)
|
|
http.queue_free()
|
|
push_warning("HighlightConfig: request start failed for %s (err=%d url=%s)" % [key, err, url])
|
|
|
|
|
|
func _parse_hex(hex: String) -> Color:
|
|
var s := hex.strip_edges()
|
|
if s.begins_with("#"):
|
|
s = s.substr(1)
|
|
match s.length():
|
|
6: return Color(s.hex_to_int() << 8 | 0xFF) / float(0xFFFFFFFF)
|
|
8:
|
|
var v := s.hex_to_int()
|
|
var r := ((v >> 24) & 0xFF) / 255.0
|
|
var g := ((v >> 16) & 0xFF) / 255.0
|
|
var b := ((v >> 8) & 0xFF) / 255.0
|
|
var a := ( v & 0xFF) / 255.0
|
|
return Color(r, g, b, a)
|
|
return Color.WHITE
|
|
|
|
|
|
func _load_cache() -> void:
|
|
var f := FileAccess.open(CACHE_PATH, FileAccess.READ)
|
|
if f == null:
|
|
return
|
|
var text := f.get_as_text()
|
|
f.close()
|
|
var parsed : Dictionary = JSON.parse_string(text)
|
|
if parsed is Dictionary:
|
|
_server_configs = parsed as Dictionary
|
|
|
|
|
|
func _save_cache() -> void:
|
|
DirAccess.make_dir_recursive_absolute("user://")
|
|
var f := FileAccess.open(CACHE_PATH, FileAccess.WRITE)
|
|
if f == null:
|
|
return
|
|
f.store_string(JSON.stringify(_server_configs))
|
|
f.close()
|
|
|
|
|
|
func _prefetch_known_textures() -> void:
|
|
for key in _server_configs.keys():
|
|
var cfg := _effective_config(str(key))
|
|
if not cfg.is_empty():
|
|
_start_texture_load(str(key), cfg)
|
|
for key in _overrides.keys():
|
|
var cfg := _effective_config(str(key))
|
|
if not cfg.is_empty():
|
|
_start_texture_load(str(key), cfg)
|
|
|
|
|
|
func _normalize_url(url: String) -> String:
|
|
return url.strip_edges().replace(" ", "%20")
|
|
|
|
|
|
func _load_image_from_body(img: Image, url: String, body: PackedByteArray) -> Error:
|
|
var ext := url.split("?")[0].get_extension().to_lower()
|
|
if ext in ["jpg", "jpeg"]:
|
|
return img.load_jpg_from_buffer(body)
|
|
if ext == "webp":
|
|
return img.load_webp_from_buffer(body)
|
|
var png_err := img.load_png_from_buffer(body)
|
|
if png_err == OK:
|
|
return OK
|
|
var webp_err := img.load_webp_from_buffer(body)
|
|
if webp_err == OK:
|
|
return OK
|
|
return img.load_jpg_from_buffer(body)
|