class_name BoardImages extends RefCounted ## Pictures kept inside a spread file, so exports and imports carry them: ## shrunk to at most MAX_SIDE pixels, stored as base64 WebP under an id ## (TowerBoard.images). Results and Book pages point at them by id ## (TableEntry.image, BookPage.image). Only pictures something uses are saved. const MAX_SIDE := 512 ## Pictures bigger than this after shrinking are refused (keeps files sane). const MAX_BYTES := 400_000 static var _textures: Dictionary = {} ## Loads a picture file, shrinks it and returns {id, data} or {error}. static func from_file(path: String) -> Dictionary: var img := Image.load_from_file(path) if img == null or img.is_empty(): return {"error": "Couldn't read %s as a picture" % path.get_file()} return from_image(img) static func from_image(img: Image) -> Dictionary: var side := maxi(img.get_width(), img.get_height()) if side > MAX_SIDE: var k := float(MAX_SIDE) / float(side) img.resize(maxi(1, roundi(img.get_width() * k)), maxi(1, roundi(img.get_height() * k)), Image.INTERPOLATE_LANCZOS) var bytes := img.save_webp_to_buffer(true, 0.85) if bytes.size() > MAX_BYTES: return {"error": "That picture is too big even after shrinking"} var data := Marshalls.raw_to_base64(bytes) return {"id": "img_" + data.md5_text().left(12), "data": data} ## The texture for stored data (cached by id). static func texture(id: String, data: String) -> Texture2D: if id == "" or data == "": return null if not _textures.has(id): var img := Image.new() if img.load_webp_from_buffer(Marshalls.base64_to_raw(data)) != OK: return null _textures[id] = ImageTexture.create_from_image(img) return _textures[id] ## Only the pictures that results or pages use. static func used(board: TowerBoard) -> Dictionary: var out := {} for t in board.tables: for e in t.entries: if e.image != "" and board.images.has(e.image): out[e.image] = board.images[e.image] for p in board.book: if p.image != "" and board.images.has(p.image): out[p.image] = board.images[p.image] return out