feat(iggy-shim): M-C — interactivity, text, focus/nav, scene controllers

- text_renderer: renders labels using the game's OWN captured bitmap-font
  provider (Mojangles) as R8 alpha glyph textures — no external font dep
- generic control semantics for Init/SetLabel/SetFocus/SetSafeZone/Show*/
  Hide*/EnableButton/checkbox in sceneCallMethod
- focus model: collectFocusables by id, handlePress/handleFocusChange/
  handleInitFocus emitted back to game via ExternalInterface protocol
- keyboard nav: authored m_objNav links (extracted from AS3) + geometric
  fallback; Enter/Space fire handlePress
- gen-scene-bundles: resolves class-linked art (Button:FJ_MenuButton_Normal
  -> skin symbol PNG) and emits nav-link (V) records
- animation-end auto-signal so Intro/Credits don't block boot
Verified: dialogs dismiss via synthesized button press, intro completes,
boot reaches menu flow, focus init fires per scene
This commit is contained in:
2026-07-07 04:20:00 -05:00
parent 2e1e752e0a
commit 39c8678bc5
8 changed files with 503 additions and 29 deletions

2
.gitignore vendored
View File

@@ -24,3 +24,5 @@ ui-png-test/
ffdec.zip
ffdec/
tools/*.class
as3/
iggy-shim/build/

View File

@@ -21,9 +21,16 @@ import sys
HOME = os.path.expanduser("~")
LAYOUT = os.environ.get("LAYOUT_DIR", f"{HOME}/neoLegacy-mac/ui-layout")
UIPNG = os.environ.get("UIPNG_DIR", f"{HOME}/neoLegacy-mac/ui-png")
AS3 = os.environ.get("AS3_DIR", f"{HOME}/neoLegacy-mac/as3")
GAME = os.environ.get("GAME_DIR", f"{HOME}/neoLegacy/build/windows64-clang-mac/Minecraft.Client")
OUT = os.path.join(GAME, "uiassets", "scenes")
# skins searched for class-linked symbols, resolution-appropriate first
SKINS_SD = ["skin", "skinInGame", "skinHud", "skinGraphics", "skinGraphicsInGame",
"skinGraphicsHud", "skinLabels", "skinTooltips", "skinWin"]
SKINS_HD = ["skinHD", "skinHDInGame", "skinHDHud", "skinHDGraphics", "skinHDGraphicsInGame",
"skinHDGraphicsHud", "skinHDLabels", "skinHDTooltips", "skinHDWin"]
manifests = {}
for fn in os.listdir(LAYOUT):
if fn.endswith(".json"):
@@ -42,10 +49,15 @@ def index_swf(swf):
idx = {}
base = os.path.join(UIPNG, swf)
if os.path.isdir(base):
for fn in os.listdir(base):
m = re.match(r"^(\d+)_?(.*)\.png$", fn)
if m:
idx[int(m.group(1))] = (f"uiassets/png/{swf}/{fn}", 1)
for sub in ("", "images"):
d = os.path.join(base, sub) if sub else base
if not os.path.isdir(d):
continue
rel = f"{swf}/{sub}" if sub else swf
for fn in os.listdir(d):
m = re.match(r"^(\d+)_?(.*)\.png$", fn)
if m:
idx[int(m.group(1))] = (f"uiassets/png/{rel}/{fn}", 1)
spr = os.path.join(base, "sprites")
if os.path.isdir(spr):
for d in os.listdir(spr):
@@ -66,6 +78,47 @@ def index_swf(swf):
return idx
# ---- AS3 document-class metadata: instance var classes + nav links ----
_docmeta_cache = {}
def scene_family(scene_name):
return re.sub(r"(Split)?(1080|720|480|Vita)$", "", scene_name)
def doc_meta(scene_name):
fam = scene_family(scene_name)
if fam in _docmeta_cache:
return _docmeta_cache[fam]
meta = {"vars": {}, "nav": {}}
# find any decompiled variant of this family
for variant in (scene_name, fam + "720", fam + "1080", fam + "480"):
docdir = os.path.join(AS3, variant, "scripts", "fourj", "documents")
if os.path.isdir(docdir):
for fn in os.listdir(docdir):
src = open(os.path.join(docdir, fn), errors="replace").read()
for m in re.finditer(r"public var (\w+):([\w.]+);", src):
meta["vars"][m.group(1)] = m.group(2)
for m in re.finditer(r"(\w+)\.m_objNav(Up|Down|Left|Right) = \"(\w*)\"", src):
meta["nav"].setdefault(m.group(1), {})[m.group(2)] = m.group(3)
break
_docmeta_cache[fam] = meta
return meta
def resolve_class_symbol(cls, hd):
"""AS3 class name -> (pngpath, frames) via skin exports"""
short = cls.split(".")[-1]
for skin in (SKINS_HD + SKINS_SD if hd else SKINS_SD + SKINS_HD):
exports = skin_export_index(skin)
cid = exports.get(cls) or exports.get(short) or exports.get("fourj.Buttons." + short)
if cid is not None:
hit = index_swf(skin).get(cid)
if hit:
return hit
return (None, 1)
def skin_export_index(skin):
"""name -> charId in the skin swf"""
m = manifests.get(skin)
@@ -96,7 +149,7 @@ def resolve_char(scene_m, scene_name, cid):
return hit if hit else (None, 1)
def emit_node(out, scene_m, scene_name, place, treedepth, visited):
def emit_node(out, scene_m, scene_name, place, treedepth, visited, meta, hd):
cid = place.get("charId", -1)
mat = place.get("matrix") or {}
tx, ty = mat.get("tx", 0.0), mat.get("ty", 0.0)
@@ -109,13 +162,20 @@ def emit_node(out, scene_m, scene_name, place, treedepth, visited):
sprite = scene_m.get("sprites", {}).get(str(cid))
if sprite and cid not in visited:
children = sprite
# class-linked art (Button1:FJ_MenuButton_Normal etc.)
if not png and treedepth == 0 and name in meta["vars"]:
png, frames = resolve_class_symbol(meta["vars"][name], hd)
out.append("N\t%d\t%d\t%d\t%s\t%s\t%d\t%.2f\t%.2f\t%.4f\t%.4f"
% (treedepth, place.get("depth", 0), place.get("frame", 0),
name, png or "-", frames, tx, ty, sx, sy))
if treedepth == 0 and name in meta["nav"]:
nv = meta["nav"][name]
out.append("V\t%s\t%s\t%s\t%s\t%s" % (name, nv.get("Up", ""), nv.get("Down", ""),
nv.get("Left", ""), nv.get("Right", "")))
if children:
visited = visited | {cid}
for sub in children.get("places", []):
emit_node(out, scene_m, scene_name, sub, treedepth + 1, visited)
emit_node(out, scene_m, scene_name, sub, treedepth + 1, visited, meta, hd)
os.makedirs(OUT, exist_ok=True)
@@ -123,8 +183,10 @@ count = 0
for scene_name, m in manifests.items():
out = ["S\t%d\t%d\t%.1f" % (int(m.get("width", 1280)), int(m.get("height", 720)),
float(m.get("fps", 30.0)))]
meta = doc_meta(scene_name)
hd = "1080" in scene_name
for place in m.get("timeline", []):
emit_node(out, m, scene_name, place, 0, set())
emit_node(out, m, scene_name, place, 0, set(), meta, hd)
with open(os.path.join(OUT, scene_name + ".scene"), "w") as f:
f.write("\n".join(out) + "\n")
count += 1

View File

@@ -4,6 +4,7 @@
#include "iggy_object.hpp"
#include "iggy_player.hpp"
#include "scene_registry.hpp"
#include "text_renderer.hpp"
#include "iggy.h"
#include "iggyexpruntime.h"
@@ -197,7 +198,9 @@ RADEXPFUNC void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF8(const ch
RADEXPFUNC void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF16(const U16 *, S32, U32, S32) {}
RADEXPFUNC void RADEXPLINK IggyFontInstallVectorUTF8(const IggyVectorFontProvider *, const char *, S32, U32) {}
RADEXPFUNC void RADEXPLINK IggyFontInstallVectorUTF16(const IggyVectorFontProvider *, const U16 *, S32, U32) {}
RADEXPFUNC void RADEXPLINK IggyFontInstallBitmapUTF8(const IggyBitmapFontProvider *, const char *, S32, U32) {}
RADEXPFUNC void RADEXPLINK IggyFontInstallBitmapUTF8(const IggyBitmapFontProvider *bmf, const char *fontname, S32, U32) {
if (bmf) textCaptureProvider(fontname ? fontname : "", bmf);
}
RADEXPFUNC void RADEXPLINK IggyFontInstallBitmapUTF16(const IggyBitmapFontProvider *, const U16 *, S32, U32) {}
RADEXPFUNC void RADEXPLINK IggyFontInstallBitmapOverrideUTF8(const IggyBitmapFontOverride *, const char *, S32, U32) {}
RADEXPFUNC void RADEXPLINK IggyFontInstallBitmapOverrideUTF16(const IggyBitmapFontOverride *, const U16 *, S32, U32) {}

View File

@@ -77,5 +77,9 @@ struct Iggy {
shim::Value callbackResult; // written via CallbackResultPath
// interactivity state (M-C)
shim::IggyObjectNode *focusNode = nullptr;
int safeTop = 0, safeBottom = 0, safeLeft = 0, safeRight = 0;
~Iggy();
};

View File

@@ -13,6 +13,8 @@
namespace shim {
static void emitExternal(Iggy *player, const char16_t *fn, int nargs, double a = 0, double b = 0);
// ---------------- crc32 (standard polynomial, table-based) ----------------
static uint32_t crc32buf(const uint8_t *data, size_t len) {
static uint32_t table[256];
@@ -297,6 +299,13 @@ void scenePlayerTick(Iggy *player, bool isInit) {
if (player->nextTickDue < now - step * 2) player->nextTickDue = now;
player->nextTickDue += step;
// Scenes whose AS3 signalled animation completion need the same signal
// from us; the intro otherwise blocks the whole boot flow forever.
if (player->framesPassed == 90 &&
(player->sceneName.rfind("Intro", 0) == 0 || player->sceneName.rfind("Credits", 0) == 0)) {
emitExternal(player, u"handleAnimationEnd", 0);
}
if (isInit) debugLog("init tick: %s", player->sceneName.c_str());
}
@@ -304,6 +313,73 @@ void scenePlayerDraw(Iggy *player) {
rendererDrawPlayer(player);
}
// ---------------- M-C: generic control semantics ----------------
static Value dataValueToValue(const IggyDataValue &dv) {
switch (dv.type) {
case IGGY_DATATYPE_number: return Value::number(dv.number);
case IGGY_DATATYPE_boolean: return Value::boolean(dv.boolval != 0);
case IGGY_DATATYPE_string_UTF16: {
std::u16string s;
for (S32 i = 0; i < dv.string16.length && dv.string16.string; i++)
s.push_back((char16_t)dv.string16.string[i]);
return Value::string(std::move(s));
}
case IGGY_DATATYPE_string_UTF8:
return Value::string(NameTable::fromUtf8(dv.string8.string ? dv.string8.string : ""));
default: return Value::undefined();
}
}
// game -> scene callback (ExternalInterface.call equivalent)
static void emitExternal(Iggy *player, const char16_t *fn, int nargs, double a, double b) {
auto &g = globals();
if (!g.externalFn16) return;
struct {
IggyExternalFunctionCallUTF16 call;
IggyDataValue extra; // arguments[1]
} buf{};
static std::u16string fnName;
fnName = fn;
buf.call.function_name.string = (IggyUTF16 *)fnName.c_str();
buf.call.function_name.length = (S32)fnName.size();
buf.call.num_arguments = nargs;
buf.call.arguments[0].type = IGGY_DATATYPE_number;
buf.call.arguments[0].number = a;
buf.extra.type = IGGY_DATATYPE_number;
buf.extra.number = b;
g.externalFn16(g.externalFnUser16, player, &buf.call);
debugLog("emit %s(%d) -> game [%s]", NameTable::toUtf8(fnName).c_str(), nargs,
player->sceneName.c_str());
}
static IggyObjectNode *findById(IggyObjectNode *n, double id) {
Value v = n->props.count(u"id") ? n->props[u"id"] : Value::undefined();
if (v.type == Value::Type::Number && v.num == id) return n;
for (auto &c : n->children)
if (c)
if (IggyObjectNode *r = findById(c.get(), id)) return r;
return nullptr;
}
static void applyFocusVisual(IggyObjectNode *n, bool focused) {
if (!n) return;
// FJ buttons: frame 1 = idle, frame 2 = focused/over
if (n->totalFrames >= 2) n->currentFrame = focused ? 2 : 1;
n->props[u"__focused"] = Value::boolean(focused);
}
static void setFocusNode(Iggy *player, IggyObjectNode *n, bool init) {
if (player->focusNode == n) return;
applyFocusVisual(player->focusNode, false);
player->focusNode = n;
applyFocusVisual(n, true);
if (n) {
Value idv = n->getProp(u"id");
emitExternal(player, init ? u"handleInitFocus" : u"handleFocusChange", 2, idv.asNumber(), 0);
}
}
int32_t sceneCallMethod(Iggy *player, const ObjectPtr &target, uintptr_t methodName,
int32_t numArgs, IggyDataValue *args, IggyDataValue *result) {
if (result) {
@@ -311,37 +387,161 @@ int32_t sceneCallMethod(Iggy *player, const ObjectPtr &target, uintptr_t methodN
result->type = IGGY_DATATYPE_undefined;
}
if (!player) return IGGY_RESULT_Error_InvalidIggy;
const std::u16string *m = names().lookup(methodName);
static int logBudget = 500;
if (m && logBudget > 0) {
logBudget--;
debugLog("call %s.%s(%d args)", player->sceneName.c_str(), NameTable::toUtf8(*m).c_str(), numArgs);
const std::u16string *mp = names().lookup(methodName);
if (!mp || !target) return IGGY_RESULT_SUCCESS;
const std::u16string &m = *mp;
auto argN = [&](int i) { return (i < numArgs) ? dataValueToValue(args[i]).asNumber() : 0.0; };
auto argS = [&](int i) { return (i < numArgs) ? dataValueToValue(args[i]).asString() : std::u16string(); };
auto argB = [&](int i) { return (i < numArgs) ? dataValueToValue(args[i]).asBool() : false; };
if (m == u"Init") { // Init(label, id) on controls; checkbox: Init(label, id, checked)
target->props[u"label"] = Value::string(argS(0));
target->props[u"id"] = Value::number(argN(1));
if (numArgs >= 3) target->props[u"checked"] = Value::boolean(argB(2));
return IGGY_RESULT_SUCCESS;
}
if (m == u"SetLabel" || m == u"SetText") {
target->props[u"label"] = Value::string(argS(0));
return IGGY_RESULT_SUCCESS;
}
if (m == u"SetFocus") { // on the document
IggyObjectNode *n = numArgs >= 1 ? findById(player->root.get(), argN(0)) : nullptr;
setFocusNode(player, n, true);
return IGGY_RESULT_SUCCESS;
}
if (m == u"SetSafeZone") {
player->safeTop = (int)argN(0);
player->safeBottom = (int)argN(1);
player->safeLeft = (int)argN(2);
player->safeRight = (int)argN(3);
return IGGY_RESULT_SUCCESS;
}
if (m == u"EnableButton") { target->props[u"enabled"] = Value::boolean(argB(0)); return IGGY_RESULT_SUCCESS; }
if (m == u"SetControlAlpha") { target->alpha = argN(0); return IGGY_RESULT_SUCCESS; }
if (m == u"SetChecked" || m == u"SetCheckBox") { target->props[u"checked"] = Value::boolean(argB(0)); return IGGY_RESULT_SUCCESS; }
// Show*/Hide* conventions map to visibility of the target
if (m.rfind(u"Show", 0) == 0 && numArgs <= 1) {
target->visible = numArgs == 0 ? true : argB(0);
return IGGY_RESULT_SUCCESS;
}
if (m.rfind(u"Hide", 0) == 0 && numArgs == 0) { target->visible = false; return IGGY_RESULT_SUCCESS; }
static int logBudget = 400;
if (logBudget > 0) {
logBudget--;
debugLog("call %s.%s(%d args) [unhandled]", player->sceneName.c_str(),
NameTable::toUtf8(m).c_str(), numArgs);
}
(void)target;
(void)args;
return IGGY_RESULT_SUCCESS;
}
int32_t sceneDispatchEvent(Iggy *player, IggyEvent *event, IggyEventResult *result) {
(void)player;
(void)event;
(void)result;
return 0;
// bbox helper for focusables: accumulate transforms to root
static void nodeScreenRect(Iggy *player, IggyObjectNode *n, float *x0, float *y0, float *x1, float *y1) {
float x = 0, y = 0, sx = 1, sy = 1;
for (IggyObjectNode *p = n; p; ) {
x = (float)p->x + x * (float)p->scaleX;
y = (float)p->y + y * (float)p->scaleY;
sx *= (float)p->scaleX;
sy *= (float)p->scaleY;
auto parent = p->parent.lock();
p = parent ? parent.get() : nullptr;
}
float w = 200 * sx, h = 40 * sy; // fallback size; refined by texture at draw
Value wv = n->getProp(u"width"), hv = n->getProp(u"height");
if (wv.type == Value::Type::Number && wv.num > 0) w = (float)wv.num * sx;
if (hv.type == Value::Type::Number && hv.num > 0) h = (float)hv.num * sy;
*x0 = x; *y0 = y; *x1 = x + w; *y1 = y + h;
}
int32_t sceneGetFocusableObjects(Iggy *player, void **currentFocus, void *objs,
static void collectFocusables(Iggy *player, IggyObjectNode *n, std::vector<IggyObjectNode *> &out) {
if (!n->visible) return;
auto it = n->props.find(u"id");
if (it != n->props.end() && it->second.type == Value::Type::Number && it->second.num >= 0) {
auto en = n->props.find(u"enabled");
bool enabled = en == n->props.end() || en->second.asBool();
if (enabled) out.push_back(n);
}
for (auto &c : n->children)
if (c) collectFocusables(player, c.get(), out);
}
int32_t sceneGetFocusableObjects(Iggy *player, void **currentFocus, void *objsRaw,
int32_t maxObj, int32_t *numObj) {
(void)player;
(void)objs;
(void)maxObj;
if (currentFocus) *currentFocus = nullptr;
if (numObj) *numObj = 0;
if (currentFocus) *currentFocus = player ? (void *)player->focusNode : nullptr;
if (!player || !player->root) { if (numObj) *numObj = 0; return 1; }
std::vector<IggyObjectNode *> nodes;
collectFocusables(player, player->root.get(), nodes);
IggyFocusableObject *objs = (IggyFocusableObject *)objsRaw;
int32_t n = 0;
for (auto *node : nodes) {
if (n >= maxObj) break;
objs[n].object = (IggyFocusHandle)node;
nodeScreenRect(player, node, &objs[n].x0, &objs[n].y0, &objs[n].x1, &objs[n].y1);
n++;
}
if (numObj) *numObj = n;
return 1;
}
void sceneSetFocus(Iggy *player, void *object, int) {
(void)player;
(void)object;
if (!player) return;
setFocusNode(player, (IggyObjectNode *)object, false);
}
int32_t sceneDispatchEvent(Iggy *player, IggyEvent *event, IggyEventResult *result) {
(void)result;
if (!player || !event) return 0;
if (event->type == IGGY_EVENTTYPE_KeyDown) {
int key = event->keycode;
if (key == IGGY_KEYCODE_ENTER || key == IGGY_KEYCODE_SPACE) {
if (player->focusNode) {
Value idv = player->focusNode->getProp(u"id");
emitExternal(player, u"handlePress", 2, idv.asNumber(), 0);
return 1;
}
}
// arrow-key focus navigation: authored nav links first, geometry fallback
if (key == IGGY_KEYCODE_UP || key == IGGY_KEYCODE_DOWN ||
key == IGGY_KEYCODE_LEFT || key == IGGY_KEYCODE_RIGHT) {
std::vector<IggyObjectNode *> nodes;
collectFocusables(player, player->root.get(), nodes);
if (nodes.empty()) return 0;
if (!player->focusNode) { setFocusNode(player, nodes[0], false); return 1; }
const char16_t *navProp = key == IGGY_KEYCODE_UP ? u"navUp"
: key == IGGY_KEYCODE_DOWN ? u"navDown"
: key == IGGY_KEYCODE_LEFT ? u"navLeft" : u"navRight";
auto nit = player->focusNode->props.find(navProp);
if (nit != player->focusNode->props.end() && !nit->second.str.empty()) {
if (auto target = player->root->childByName(nit->second.str)) {
setFocusNode(player, target.get(), false);
return 1;
}
}
float cx0, cy0, cx1, cy1;
nodeScreenRect(player, player->focusNode, &cx0, &cy0, &cx1, &cy1);
float cx = (cx0 + cx1) / 2, cy = (cy0 + cy1) / 2;
IggyObjectNode *best = nullptr;
float bestDist = 1e30f;
for (auto *n : nodes) {
if (n == player->focusNode) continue;
float x0, y0, x1, y1;
nodeScreenRect(player, n, &x0, &y0, &x1, &y1);
float nx = (x0 + x1) / 2, ny = (y0 + y1) / 2;
float dx = nx - cx, dy = ny - cy;
bool dirOk = (key == IGGY_KEYCODE_UP && dy < -1) || (key == IGGY_KEYCODE_DOWN && dy > 1) ||
(key == IGGY_KEYCODE_LEFT && dx < -1) || (key == IGGY_KEYCODE_RIGHT && dx > 1);
if (!dirOk) continue;
float primary = (key == IGGY_KEYCODE_UP || key == IGGY_KEYCODE_DOWN) ? fabsf(dy) : fabsf(dx);
float secondary = (key == IGGY_KEYCODE_UP || key == IGGY_KEYCODE_DOWN) ? fabsf(dx) : fabsf(dy);
float dist = primary + secondary * 3.0f;
if (dist < bestDist) { bestDist = dist; best = n; }
}
if (best) { setFocusNode(player, best, false); return 1; }
}
}
return 0;
}
int32_t sceneHasEditableFocus(Iggy *) { return 0; }

View File

@@ -0,0 +1,143 @@
#include "text_renderer.hpp"
#include "iggy_player.hpp"
#include "scene_registry.hpp"
#include "gdraw.h"
#include "iggy.h"
#include <cstring>
#include <unordered_map>
namespace shim {
struct Glyph {
GDrawTexture *tex = nullptr;
int w = 0, h = 0; // bitmap dims
int ox = 0, oy = 0; // top-left offset from origin
float advance = 0;
bool present = false;
};
struct BitmapFontCapture {
IggyBitmapFontProvider provider{};
IggyFontMetrics metrics{};
bool haveMetrics = false;
std::unordered_map<uint32_t, Glyph> glyphs; // codepoint -> glyph
};
static BitmapFontCapture s_font; // primary UI font (Mojangles)
static bool s_haveFont = false;
void textCaptureProvider(const std::string &family, const void *providerStruct) {
// Prefer the first registered (Mojangles_7); keep _11 if it comes first.
if (s_haveFont) return;
memcpy(&s_font.provider, providerStruct, sizeof(IggyBitmapFontProvider));
s_haveFont = true;
debugLog("text: captured bitmap font provider '%s' (%d glyphs)", family.c_str(),
s_font.provider.num_glyphs);
}
bool textHaveFont() { return s_haveFont; }
static Glyph *glyphGet(GDrawFunctions *gd, uint32_t cp) {
auto it = s_font.glyphs.find(cp);
if (it != s_font.glyphs.end()) return &it->second;
Glyph &g = s_font.glyphs[cp];
auto &p = s_font.provider;
if (!p.get_glyph_for_codepoint || !p.get_glyph_metrics || !p.get_bitmap) return &g;
S32 gi = p.get_glyph_for_codepoint(p.userdata, cp);
if (gi == IGGY_GLYPH_INVALID) return &g;
IggyGlyphMetrics gm{};
if (IggyGlyphMetrics *r = p.get_glyph_metrics(p.userdata, gi, &gm)) gm = *r;
g.advance = gm.advance;
if (p.is_empty && p.is_empty(p.userdata, gi)) { g.present = true; return &g; }
IggyBitmapCharacter bc{};
if (!p.get_bitmap(p.userdata, gi, 1.0f, &bc) || !bc.pixels_one_per_byte) {
g.present = true; // metrics-only (e.g. space)
return &g;
}
// upload as R8 "font" texture
GDrawStats stats{};
GDraw_MakeTexture_ProcessingInfo info{};
if (gd->MakeTextureBegin(&g, bc.width_in_pixels, bc.height_in_pixels,
GDRAW_TEXTURE_FORMAT_font, 0, &info, &stats)) {
for (int row = 0; row < bc.height_in_pixels; row++)
memcpy(info.texture_data + (size_t)row * info.stride_in_bytes,
bc.pixels_one_per_byte + (size_t)row * bc.stride_in_bytes,
bc.width_in_pixels);
gd->MakeTextureMore(&info);
g.tex = gd->MakeTextureEnd(&info, &stats);
}
g.w = bc.width_in_pixels;
g.h = bc.height_in_pixels;
g.ox = bc.top_left_x;
g.oy = bc.top_left_y;
g.present = true;
if (p.free_bitmap) p.free_bitmap(p.userdata, gi, 1.0f, &bc);
return &g;
}
static float s_zeros4[4] = {0, 0, 0, 0};
static void glyphQuad(GDrawFunctions *gd, Glyph *g, float x, float y, float scale, const float rgba[4]) {
if (!g->tex) return;
GDrawRenderState rs{};
rs.use_world_space = 1;
rs.tex0_mode = GDRAW_TEXTURE_alpha;
rs.wrap0 = GDRAW_WRAP_clamp;
rs.blend_mode = GDRAW_BLEND_alpha;
rs.tex[0] = g->tex;
rs.edge_matrix = s_zeros4;
for (int i = 0; i < 4; i++) rs.color[i] = rgba[i] * rgba[3];
rs.color[3] = rgba[3];
float gx = x + g->ox * scale, gy = y + g->oy * scale;
float gw = g->w * scale, gh = g->h * scale;
gswf_vertex_xyst v[4] = {
{gx, gy, 0, 0}, {gx + gw, gy, 1, 0}, {gx + gw, gy + gh, 1, 1}, {gx, gy + gh, 0, 1}};
GDrawPrimitive prim{};
prim.vertices = (F32 *)v;
prim.num_vertices = 4;
prim.num_indices = 6;
prim.vertex_format = GDRAW_vformat_v2tc2;
GDrawStats stats{};
gd->DrawIndexedTriangles(&rs, &prim, nullptr, &stats);
}
float textDraw(GDrawFunctions *gd, const std::u16string &s, float x, float y,
float scale, const float rgba[4]) {
if (!s_haveFont || !gd) return 0;
float pen = 0;
for (char16_t c : s) {
Glyph *g = glyphGet(gd, (uint32_t)c);
if (!g->present) continue;
glyphQuad(gd, g, x + pen, y, scale, rgba);
pen += g->advance * scale;
}
return pen;
}
float textMeasure(const std::u16string &s, float scale) {
if (!s_haveFont) return 0;
float pen = 0;
for (char16_t c : s) {
// measuring may create glyphs lazily without a gdraw; only metrics used
auto it = s_font.glyphs.find((uint32_t)c);
if (it != s_font.glyphs.end()) { pen += it->second.advance * scale; continue; }
auto &p = s_font.provider;
if (!p.get_glyph_for_codepoint || !p.get_glyph_metrics) continue;
S32 gi = p.get_glyph_for_codepoint(p.userdata, (uint32_t)c);
if (gi == IGGY_GLYPH_INVALID) continue;
IggyGlyphMetrics gm{};
if (IggyGlyphMetrics *r = p.get_glyph_metrics(p.userdata, gi, &gm)) gm = *r;
pen += gm.advance * scale;
}
return pen;
}
} // namespace shim

View File

@@ -0,0 +1,24 @@
// Text rendering using the game's OWN bitmap-font providers (captured from
// IggyFontInstallBitmapUTF8). Glyph alpha bitmaps are uploaded as R8 textures
// and drawn with GDraw's alpha-texture mode — no external font library.
#pragma once
#include <cstdint>
#include <string>
struct GDrawFunctions;
namespace shim {
struct BitmapFontCapture; // holds the provider vtable the game registered
void textCaptureProvider(const std::string &familyUtf8, const void *providerStruct);
bool textHaveFont();
// Draw a UTF-16 string at (x, y) top-left, `scalePx` = target pixel height
// multiplier relative to the font's native size. Returns drawn width.
float textDraw(GDrawFunctions *gd, const std::u16string &s, float x, float y,
float scale, const float rgba[4]);
float textMeasure(const std::u16string &s, float scale);
} // namespace shim

View File

@@ -1,6 +1,7 @@
#include "ui_renderer.hpp"
#include "iggy_player.hpp"
#include "scene_registry.hpp"
#include "text_renderer.hpp"
#include "gdraw.h"
#include "iggy.h"
@@ -75,6 +76,21 @@ bool bundleLoadInto(Iggy *player) {
std::string tag;
std::getline(ss, tag, '\t');
if (tag == "S") continue; // dims already known from scenes.tsv
if (tag == "V") { // nav links: name up down left right
std::string name, up, down, left, right;
std::getline(ss, name, '\t');
std::getline(ss, up, '\t');
std::getline(ss, down, '\t');
std::getline(ss, left, '\t');
std::getline(ss, right, '\t');
if (auto n = player->root->childByName(NameTable::fromUtf8(name))) {
n->props[u"navUp"] = Value::string(NameTable::fromUtf8(up));
n->props[u"navDown"] = Value::string(NameTable::fromUtf8(down));
n->props[u"navLeft"] = Value::string(NameTable::fromUtf8(left));
n->props[u"navRight"] = Value::string(NameTable::fromUtf8(right));
}
continue;
}
if (tag != "N") continue;
std::string td, zd, fr, name, png, frames, tx, ty, sx, sy;
std::getline(ss, td, '\t');
@@ -178,11 +194,31 @@ static void drawNode(GDrawFunctions *gd, IggyObjectNode &n, float ox, float oy,
float na = alpha * (float)n.alpha;
std::string file = frameFile(n);
Texture *tex = nullptr;
if (!file.empty()) {
Texture *tex = textureGet(file);
tex = textureGet(file);
if (tex->handle)
drawQuad(gd, tex, nx, ny, tex->w * nsx, tex->h * nsy, na);
}
// focus highlight for buttons without distinct frame art
auto focusedIt = n.props.find(u"__focused");
bool focused = focusedIt != n.props.end() && focusedIt->second.asBool();
// label text (set by the game via Init/SetLabel)
auto labelIt = n.props.find(u"label");
if (labelIt != n.props.end() && labelIt->second.type == shim::Value::Type::String &&
!labelIt->second.str.empty() && textHaveFont()) {
float scale = 2.0f * nsx;
float tw = textMeasure(labelIt->second.str, scale);
float boxW = tex && tex->w ? tex->w * nsx : 0.f;
float tx = nx + (boxW > tw ? (boxW - tw) / 2 : 0);
float ty = ny + (tex && tex->h ? (tex->h * nsy) * 0.5f - 8.f * scale * 0.5f : 0);
float white[4] = {1, 1, 1, na};
float yellow[4] = {1, 1, 0.35f, na};
textDraw(gd, labelIt->second.str, tx, ty, scale, focused ? yellow : white);
}
for (auto &c : n.children)
if (c) drawNode(gd, *c, nx, ny, nsx, nsy, na);
}