Shows the first 20 printable bytes and explains that only binary .glb is supported at runtime, with a Blender re-export hint. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
178 lines
5.5 KiB
GDScript
178 lines
5.5 KiB
GDScript
extends Node
|
|
## ModelCache — downloads and caches .glb / .gltf 3D models from CDN.
|
|
##
|
|
## Usage:
|
|
## ModelCache.load_model(url, func(node: Node3D): ...)
|
|
##
|
|
## The callback receives a freshly-instantiated Node3D on success, or null on
|
|
## failure. Multiple callers requesting the same URL share a single download.
|
|
## Parsed PackedScenes are kept in memory so re-instantiation is instant.
|
|
## Raw GLB bytes are written to:
|
|
## user://remote_model_cache/<sha256>.bin
|
|
## so subsequent app launches skip the download.
|
|
|
|
const _CACHE_DIR := "user://remote_model_cache"
|
|
|
|
# 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)
|
|
static var _pending: Dictionary = {}
|
|
|
|
|
|
func _ready() -> void:
|
|
DirAccess.make_dir_recursive_absolute(_CACHE_DIR)
|
|
|
|
|
|
## 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):
|
|
var packed: PackedScene = _mem[url]
|
|
callback.call(packed.instantiate() if packed != null else null)
|
|
return
|
|
|
|
# 2 — disk hit (bytes from previous session)
|
|
var disk := _disk_path(url)
|
|
if FileAccess.file_exists(disk):
|
|
var bytes := FileAccess.get_file_as_bytes(disk)
|
|
if not bytes.is_empty():
|
|
var packed := _parse_gltf(bytes)
|
|
if packed != null:
|
|
_mem[url] = packed
|
|
callback.call(packed.instantiate())
|
|
return
|
|
# Corrupted cache file — delete and re-download.
|
|
push_warning("ModelCache: deleting corrupt disk cache for %s" % url)
|
|
DirAccess.remove_absolute(disk)
|
|
|
|
# 3 — already downloading → queue
|
|
if _pending.has(url):
|
|
_pending[url].append(callback)
|
|
return
|
|
|
|
# 4 — start download
|
|
_pending[url] = [callback]
|
|
_download(url, disk)
|
|
|
|
|
|
func _download(url: String, disk: String) -> void:
|
|
print("ModelCache: downloading — %s" % url)
|
|
var http := HTTPRequest.new()
|
|
http.body_size_limit = -1 # unlimited
|
|
add_child(http)
|
|
|
|
http.request_completed.connect(
|
|
func(res: int, code: int, headers: PackedStringArray, 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)
|
|
|
|
# Log details to help diagnose content-type / truncation issues.
|
|
var ct := ""
|
|
for h: String in headers:
|
|
if h.to_lower().begins_with("content-type"):
|
|
ct = h
|
|
break
|
|
var first_hex := ""
|
|
for i in mini(16, body.size()):
|
|
first_hex += "%02X " % body[i]
|
|
print("ModelCache: result=%d http=%d size=%d [%s] first=[%s]" \
|
|
% [res, code, body.size(), ct, first_hex.strip_edges()])
|
|
|
|
# res is the HTTPRequest.Result enum; anything != 0 means a network error.
|
|
if res != HTTPRequest.RESULT_SUCCESS:
|
|
push_warning("ModelCache: network error result=%d http=%d — %s" % [res, code, url])
|
|
for cb: Callable in callbacks:
|
|
cb.call(null)
|
|
return
|
|
|
|
if code < 200 or code >= 300:
|
|
push_warning("ModelCache: HTTP %d — %s" % [code, url])
|
|
for cb: Callable in callbacks:
|
|
cb.call(null)
|
|
return
|
|
|
|
if body.is_empty():
|
|
push_warning("ModelCache: empty response — %s" % url)
|
|
for cb: Callable in callbacks:
|
|
cb.call(null)
|
|
return
|
|
|
|
# Parse directly from the downloaded bytes — avoids any file-path quirks.
|
|
var packed := _parse_gltf(body)
|
|
_mem[url] = packed
|
|
|
|
if packed != null:
|
|
# Only write a good file to the disk cache.
|
|
var f := FileAccess.open(disk, FileAccess.WRITE)
|
|
if f:
|
|
f.store_buffer(body)
|
|
f.close()
|
|
|
|
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() 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()
|
|
|
|
|
|
# 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" = 0x46546C67 little-endian).
|
|
if data.size() >= 4:
|
|
var magic := data.decode_u32(0)
|
|
if magic != 0x46546C67:
|
|
# Try to give a human-readable diagnosis.
|
|
var preview := ""
|
|
for i in mini(20, data.size()):
|
|
var b := data[i]
|
|
preview += char(b) if b >= 0x20 and b < 0x7F else "."
|
|
push_warning(
|
|
"ModelCache: not a GLB file — expected 'glTF' magic, got 0x%X ('%s'). " \
|
|
+ "Only binary .glb format is supported at runtime. " \
|
|
+ "Re-export from Blender as glTF 2.0 Binary (.glb)." % [magic, preview])
|
|
return null
|
|
|
|
var doc := GLTFDocument.new()
|
|
var state := GLTFState.new()
|
|
# Empty base_path is correct for self-contained GLBs.
|
|
var err := doc.append_from_buffer(data, "", state)
|
|
if err != OK:
|
|
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")
|
|
return null
|
|
|
|
var packed := PackedScene.new()
|
|
var pack_err := packed.pack(root)
|
|
root.queue_free()
|
|
|
|
if pack_err != OK:
|
|
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() + ".bin"
|