diff --git a/core/board_images.gd b/core/board_images.gd new file mode 100644 index 0000000..35eed5b --- /dev/null +++ b/core/board_images.gd @@ -0,0 +1,57 @@ +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 diff --git a/core/board_images.gd.uid b/core/board_images.gd.uid new file mode 100644 index 0000000..e745113 --- /dev/null +++ b/core/board_images.gd.uid @@ -0,0 +1 @@ +uid://dsjbrc5jrldag diff --git a/core/book_page.gd b/core/book_page.gd index 610da3d..4d2222e 100644 --- a/core/book_page.gd +++ b/core/book_page.gd @@ -11,6 +11,8 @@ var name: String = "" var text: String = "" var details: String = "" var tags: Array[String] = [] +## A picture (BoardImages id). "" = none. +var image: String = "" func label() -> String: @@ -25,6 +27,8 @@ func to_dict() -> Dictionary: d["details"] = details if not tags.is_empty(): d["tags"] = tags.duplicate() + if image != "": + d["image"] = image return d @@ -34,6 +38,7 @@ static func from_dict(d: Dictionary) -> BookPage: p.name = str(d.get("name", "")) p.text = str(d.get("text", "")) p.details = str(d.get("details", "")) + p.image = str(d.get("image", "")) for t: Variant in d.get("tags", []): p.tags.append(str(t)) return p diff --git a/core/table_entry.gd b/core/table_entry.gd index 839d253..b4bbaad 100644 --- a/core/table_entry.gd +++ b/core/table_entry.gd @@ -49,6 +49,8 @@ var pipe_pause: Dictionary = {} ## amount (an expression). "" = free. var cost_value: String = "" var cost_amount: String = "" +## A picture (BoardImages id, kept in the spread file). "" = none. +var image: String = "" ## Router cards: this case's condition. "" is the Otherwise case (always ## matches). Ignored on other kinds. var when: String = "" @@ -278,6 +280,8 @@ func to_dict() -> Dictionary: d["range"] = [range_lo, range_hi] if page != "": d["page"] = page + if image != "": + d["image"] = image if cost_value.strip_edges() != "": d["cost"] = {"value": cost_value.strip_edges(), "amount": cost_amount.strip_edges()} return d @@ -289,6 +293,7 @@ static func from_dict(d: Dictionary) -> TableEntry: e.weight = maxi(0, int(d.get("weight", 1))) e.effects = str(d.get("effects", "")) e.page = str(d.get("page", "")) + e.image = str(d.get("image", "")) var cost: Variant = d.get("cost") if cost is Dictionary: e.cost_value = str(cost.get("value", "")) diff --git a/core/tower_board.gd b/core/tower_board.gd index 22b5ffc..65c28ba 100644 --- a/core/tower_board.gd +++ b/core/tower_board.gd @@ -19,6 +19,8 @@ var tables: Array[RollTable] = [] var groups: Array[TableGroup] = [] ## The Book: reusable results (Pages) for this spread. var book: Array[BookPage] = [] +## Pictures: id -> base64 data (BoardImages). Only used ones are saved. +var images: Dictionary = {} static func new_id(prefix: String) -> String: @@ -102,6 +104,11 @@ func get_page(pid: String) -> BookPage: return null +## The texture of a stored picture, or null. +func picture(id: String) -> Texture2D: + return BoardImages.texture(id, str(images.get(id, ""))) + + func add_page(text: String, details: String = "") -> BookPage: var p := BookPage.new() p.id = new_id("p") @@ -127,6 +134,7 @@ func link_page(e: TableEntry, pid: String) -> void: e.page = pid e.text = p.text e.details = p.details + e.image = p.image ## Copies a page onto every result linked to it. Returns the tables touched. @@ -140,6 +148,7 @@ func sync_page(pid: String) -> Array[String]: if e.page == pid: e.text = p.text e.details = p.details + e.image = p.image if not touched.has(t.id): touched.append(t.id) return touched @@ -367,6 +376,9 @@ func to_dict() -> Dictionary: d["groups"] = gl if not book.is_empty(): d["book"] = book_list() + var pics := BoardImages.used(self) + if not pics.is_empty(): + d["images"] = pics return d @@ -402,6 +414,9 @@ func load_dict(src: Dictionary) -> bool: groups = loaded_groups clean_groups() load_book(d.get("book", [])) + # Undo snapshots carry no pictures: keep the ones already loaded. + if d.get("images") is Dictionary: + images.merge(d["images"], true) if str(d.get("id", "")) != "": id = str(d["id"]) if str(d.get("name", "")) != "": diff --git a/io/json_io.gd b/io/json_io.gd index a25d915..c04fb70 100644 --- a/io/json_io.gd +++ b/io/json_io.gd @@ -264,9 +264,27 @@ static func canonical(src: Dictionary) -> Dictionary: groups.append(_canon_group(g)) if not groups.is_empty(): out["groups"] = groups + # The Book and pictures (2026-11-10): taken as they are; TowerBoard checks them. + if src.get("book") is Array: + out["book"] = (src["book"] as Array).filter(func(v: Variant) -> bool: return v is Dictionary) + if src.get("images") is Dictionary: + var pics := {} + for k: Variant in src["images"]: + if src["images"][k] is String: + pics[str(k)] = src["images"][k] + out["images"] = pics return out +## Copies the keys that are present and not empty (newer optional keys that +## need no conversion). +static func _keep(src: Dictionary, dst: Dictionary, keys: Array) -> void: + for k: String in keys: + var v: Variant = src.get(k) + if v != null and not (v is String and (v as String).strip_edges() == "") and not (v is bool and not v): + dst[k] = v + + static func _canon_group(gd: Dictionary) -> Dictionary: var g := { "id": str(gd.get("id", "")), @@ -288,6 +306,7 @@ static func _canon_group(gd: Dictionary) -> Dictionary: if str(m) != "" and not members.has(str(m)): members.append(str(m)) g["members"] = members + _keep(gd, g, ["parent"]) return g @@ -351,6 +370,7 @@ static func _canon_table(td: Dictionary) -> Dictionary: for e in src_entries: entries.append(_canon_entry(e)) t["entries"] = entries + _keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text"]) return t @@ -401,9 +421,13 @@ static func _canon_entry(ev: Variant) -> Dictionary: var wv := _canon_with(p.get("with")) if not wv.is_empty(): np["with"] = wv + _keep(p, np, ["color", "combine", "pause"]) pipes.append(np) if not pipes.is_empty(): e["pipes"] = pipes + _keep(ed, e, ["page", "image"]) + if ed.get("cost") is Dictionary: + e["cost"] = ed["cost"] return e diff --git a/tests/test_book.gd b/tests/test_book.gd index 7838518..d298944 100644 --- a/tests/test_book.gd +++ b/tests/test_book.gd @@ -18,6 +18,7 @@ func _init() -> void: main.set_mode(Main.Mode.BUILD) await _frames() await _test_book() + _test_pictures() print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) quit(1 if _failures else 0) @@ -71,6 +72,52 @@ func _test_book() -> void: _check(main.data.book.size() == 1, "undo brings the page back") +func _test_pictures() -> void: + var img := Image.create(900, 600, false, Image.FORMAT_RGBA8) + img.fill(Color.MEDIUM_PURPLE) + var r := BoardImages.from_image(img) + _check(r.has("id") and not r.has("error"), "a picture is stored") + main.data.images[r["id"]] = r["data"] + var tex := main.data.picture(r["id"]) + _check(tex != null and maxi(tex.get_width(), tex.get_height()) == BoardImages.MAX_SIDE, "and shrunk to %d px" % BoardImages.MAX_SIDE) + main.data.images["img_unused"] = r["data"] + var e := main.data.get_table("weapons").entries[0] + e.image = r["id"] + var d := main.data.to_dict() + _check((d.get("images", {}) as Dictionary).has(r["id"]) and not (d["images"] as Dictionary).has("img_unused"), "only used pictures are saved") + var back := TowerBoard.new() + back.load_dict(d) + _check(back.picture(back.get_table("weapons").entries[0].image) != null, "pictures load with the spread") + var p := main.data.add_page("Pic page") + p.image = r["id"] + var e2 := main.data.get_table("weapons").entries[2] + main.data.link_page(e2, p.id) + _check(e2.image == r["id"], "a page's picture comes with it") + # Everything new survives an export and import of the spread file. + var t := main.data.get_table("weapons") + t.color = "#2f8a4f" + t.width = 300 + t.roll_floor = "2" + e2.cost_value = "@gold" + e2.cost_amount = "3" + e2.add_pipe("loot") + e2.pipe_combine["loot"] = "max" + e2.pipe_pause["loot"] = true + e2.pipe_color["loot"] = "#c04a86" + var g := main.data.add_group("Outer", []) + var g2 := main.data.add_group("Inner", []) + g2.parent = g.id + var canon := JsonIO.canonical(JSON.parse_string(JSON.stringify(main.data.to_dict()))) + var b2 := TowerBoard.new() + b2.load_dict(canon) + var t2 := b2.get_table("weapons") + var e3 := t2.entries[2] + _check(t2.color == "#2f8a4f" and t2.width == 300.0 and t2.roll_floor == "2", "card colour, size and limits import") + _check(e3.page == p.id and e3.image == r["id"] and e3.cost_amount == "3", "page links, pictures and costs import") + _check(e3.combine_for("loot") == "max" and e3.pipe_pause.has("loot") and e3.pipe_color.get("loot") == "#c04a86", "thread options import") + _check(b2.get_group(g2.id).parent == g.id and b2.book.size() == main.data.book.size() and b2.images.has(r["id"]), "nesting, the Book and pictures import") + + func _frames(n: int = 2) -> void: for i in n: await process_frame diff --git a/ui/book_panel.gd b/ui/book_panel.gd index e826e5e..061ba81 100644 --- a/ui/book_panel.gd +++ b/ui/book_panel.gd @@ -123,6 +123,7 @@ func new_page() -> BookPage: func save_result(t: RollTable, e: TableEntry) -> BookPage: m.undo_redo._begin_edit() var p := m.data.add_page(e.text, e.details) + p.image = e.image e.page = p.id m.inspector_edited(t.id) m.mark_dirty() diff --git a/ui/details_popup.gd b/ui/details_popup.gd index 9e26d85..6011646 100644 --- a/ui/details_popup.gd +++ b/ui/details_popup.gd @@ -19,6 +19,7 @@ var main: Main var _owner_ctrl: Control var _title: Label var _sub: Label +var _pic: TextureRect var _body: RichTextLabel var _wait := 0.0 var _pending := false @@ -45,6 +46,12 @@ func setup(p_main: Main) -> void: _title.custom_minimum_size = Vector2(WIDTH, 0) _title.mouse_filter = MOUSE_FILTER_IGNORE v.add_child(_title) + _pic = TextureRect.new() + _pic.custom_minimum_size = Vector2(WIDTH, 160) + _pic.expand_mode = TextureRect.EXPAND_IGNORE_SIZE + _pic.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED + _pic.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(_pic) _sub = Style.make_label("", Style.body(), 12, Style.MUTED) _sub.mouse_filter = MOUSE_FILTER_IGNORE v.add_child(_sub) @@ -56,9 +63,11 @@ func setup(p_main: Main) -> void: ## Shows the pop-up for `owner` after a short delay. Empty parts are hidden. -func show_for(owner: Control, title: String, body: String, sub: String = "") -> void: +func show_for(owner: Control, title: String, body: String, sub: String = "", pic: Texture2D = null) -> void: if owner == null: return + _pic.texture = pic + _pic.visible = pic != null if not owner.has_meta("_details_hooked"): owner.set_meta("_details_hooked", true) owner.mouse_exited.connect(_on_owner_exited.bind(owner)) @@ -153,12 +162,13 @@ func show_entry(owner: Control, tid: String, eid: String) -> void: var why := why_bbcode(found["steps"], int(found["index"]), main.data, plain) if why != "": parts.append(why) - if parts.is_empty(): + var pic := main.data.picture(e.image) + if parts.is_empty() and pic == null: return var shown := main.lit_text(tid, eid) if shown == "": shown = RichText.preview(e.text, main.data) - show_for(owner, _short(Formatter.strip_tags(shown)), "\n\n".join(parts), Formatter.strip_tags(t.name)) + show_for(owner, _short(Formatter.strip_tags(shown)), "\n\n".join(parts), Formatter.strip_tags(t.name), pic) ## An entry's rules as short BBCode lines: "only if …", "Changes: Luck −1 · diff --git a/ui/image_field.gd b/ui/image_field.gd new file mode 100644 index 0000000..0d9579f --- /dev/null +++ b/ui/image_field.gd @@ -0,0 +1,50 @@ +class_name ImageField +extends HBoxContainer +## Picks a picture for a result or a Book page: a thumbnail, "Choose…" (a +## file, shrunk and kept in the spread: BoardImages) and "Remove". Calls +## on_change with the picture's id ("" for none). + +var m: Main +var _on_change: Callable +var _thumb: TextureRect +var _remove: Button + + +func _init(p_main: Main, id: String, on_change: Callable) -> void: + m = p_main + _on_change = on_change + add_theme_constant_override("separation", 8) + _thumb = TextureRect.new() + _thumb.custom_minimum_size = Vector2(48, 48) + _thumb.expand_mode = TextureRect.EXPAND_IGNORE_SIZE + _thumb.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED + add_child(_thumb) + var choose := ModalCard.make_button("Choose…") + choose.tooltip_text = "A picture file; it's shrunk and kept inside the spread, so exports carry it" + choose.pressed.connect(_choose) + add_child(choose) + _remove = ModalCard.make_button("Remove") + _remove.pressed.connect(func() -> void: _pick("")) + add_child(_remove) + _show(id) + + +func _show(id: String) -> void: + _thumb.texture = m.data.picture(id) + _thumb.visible = _thumb.texture != null + _remove.visible = id != "" + + +func _choose() -> void: + m.file_dialog("Choose a picture", ["*.png, *.jpg, *.jpeg, *.webp, *.svg ; Pictures"], FileDialog.FILE_MODE_OPEN_FILE, func(path: String) -> void: + var r := BoardImages.from_file(path) + if r.has("error"): + m.toast(str(r["error"])) + return + m.data.images[r["id"]] = r["data"] + _pick(str(r["id"]))) + + +func _pick(id: String) -> void: + _show(id) + _on_change.call(id) diff --git a/ui/image_field.gd.uid b/ui/image_field.gd.uid new file mode 100644 index 0000000..92cb21f --- /dev/null +++ b/ui/image_field.gd.uid @@ -0,0 +1 @@ +uid://cudlyrqrahr2q diff --git a/ui/inspector.gd b/ui/inspector.gd index c9f9933..65c27a8 100644 --- a/ui/inspector.gd +++ b/ui/inspector.gd @@ -566,6 +566,10 @@ func _result_section(t: RollTable, e: TableEntry) -> void: det.text_changed.connect(func() -> void: set_entry_details(det.text)) fields["details"] = det _content.add_child(InspectorKit.field("Details", det)) + _content.add_child(InspectorKit.field("Picture", ImageField.new(main, e.image, func(id: String) -> void: + e.image = id + e.page = "" + wrote(t)))) _content.add_child(_book_line(t, e)) if t.kind == RollTable.KIND_CHOICE and t.choice == "pick" and not (t.is_dynamic() and t.entries.find(e) == 0): diff --git a/ui/page_editor.gd b/ui/page_editor.gd index aded1d0..0c3ce64 100644 --- a/ui/page_editor.gd +++ b/ui/page_editor.gd @@ -50,6 +50,9 @@ func show_page(p: BookPage) -> void: p.details = det.text _changed()) add_child(_field("Details", det)) + add_child(_field("Picture", ImageField.new(m, p.image, func(id: String) -> void: + p.image = id + _changed()))) var tags := _line(", ".join(p.tags), "e.g. weapon, holy", func(s: String) -> void: var list: Array[String] = [] for t in s.split(","): diff --git a/ui/table_card_rows.gd b/ui/table_card_rows.gd index 743108f..ce5c42f 100644 --- a/ui/table_card_rows.gd +++ b/ui/table_card_rows.gd @@ -157,6 +157,15 @@ func make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float) num.tooltip_text = "Only a modifier reaches this: the dice alone roll %s–%s" % [table.fmt(nat.x), table.fmt(nat.y)] num.mouse_filter = Control.MOUSE_FILTER_PASS + if e.image != "": + var pic := TextureRect.new() + pic.texture = main.data.picture(e.image) + pic.custom_minimum_size = Vector2(30, 30) + pic.expand_mode = TextureRect.EXPAND_IGNORE_SIZE + pic.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED + pic.size_flags_vertical = Control.SIZE_SHRINK_CENTER + pic.mouse_filter = Control.MOUSE_FILTER_PASS + h.add_child(pic) if e.page != "": # A small § says the result follows a Book page. var pg := main.data.get_page(e.page)