Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Hollow Knight: area titles
Mason Chen1edeb6932f7e
diff --git a/games/hollowknight/Makefile b/games/hollowknight/Makefileindex 04e82cce..1d82e1f1 100644--- a/games/hollowknight/Makefile+++ b/games/hollowknight/Makefile@@ -9,7 +9,7 @@ CC = arm-none-eabi-gccNWLINK ?= npx --yes -- [email protected]STRIP ?= arm-none-eabi-strip --strip-unneededBUILD_DIR = output-GAME = src/res.c src/tex.c src/room.c src/gfx.c src/phys.c src/anim.c src/hero.c src/camera.c src/game.c src/world.c src/obj.c src/enemy.c src/hud.c src/spell.c src/text.c src/npc.c src/save.c src/death.c src/lzma/LzmaDec.c+GAME = src/res.c src/tex.c src/room.c src/gfx.c src/phys.c src/anim.c src/hero.c src/camera.c src/game.c src/world.c src/obj.c src/enemy.c src/hud.c src/spell.c src/text.c src/npc.c src/title.c src/save.c src/death.c src/lzma/LzmaDec.cSRC = $(GAME) src/plat_eadk.c src/main.cHEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.hdiff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.binindex f4cb53ae..23b839d7 100644Binary files a/games/hollowknight/src/data.bin and b/games/hollowknight/src/data.bin differdiff --git a/games/hollowknight/src/data.h b/games/hollowknight/src/data.hindex bdfc48dd..822ed519 100644--- a/games/hollowknight/src/data.h+++ b/games/hollowknight/src/data.h@@ -394,9 +394,12 @@#define SPRITE_CORPSE_NAIL 1363#define SPRITE_FK_BARREL 1364#define SPRITE_FK_STAFF 1365-#define SPRITE_DIGIT0 1553+#define SPRITE_DIGIT0 1555#define STYLE_DIALOGUE 0#define STYLE_PROMPT 1+#define STYLE_TITLE_L 2+#define STYLE_TITLE_S 3+#define STYLE_TITLE_SUB 4#define TEXT_K 1.333333f#define FONT_PHASES 4#define EK_CRAWLER 1@@ -437,3 +440,31 @@#define TXT_PROMPT_CHALLENGE 13#define PROMPT_SORT 884737u#define DIGIT_ADV {0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f, 0.4182f}+#define TITLE_KINGSPASS 0+#define TITLE_DIRTMOUTH 1+#define TITLE_CROSSROADS 2+#define TITLE_EGGTEMPLE 3+#define TITLE_SHAMANTEMPLE 4+#define TITLE_GREENPATH 5+#define TITLE_BIGFLY 6+#define TITLE_FALSE_KNIGHT 7+#define TITLE_HORNET 8+#define TITLE_ELDERBUG 9+#define TITLE_SLY 10+#define TITLE_ISELDA 11+#define TITLE_CORNIFER 12+#define TITLE_QUIRREL 13+#define TITLE_SHAMAN 14+#define TITLE_STAG 15+#define TITLE_STAG2 16+#define TITLE_TISO_C 17+#define TITLE_TISO_NC 18+#define TITLE_CHARM_SLUG 19+#define NUM_TITLES 20+#define TITLE_TABLE {{15, 16, -1, -1}, {17, 18, 19, -1}, {20, 21, -1, 22}, {23, 24, -1, 25}, {26, 27, -1, 28}, {29, 30, -1, -1}, {31, 32, 33, -1}, {34, 35, -1, -1}, {36, 37, -1, -1}, {38, 39, -1, -1}, {40, 41, -1, -1}, {42, 43, -1, -1}, {44, 45, -1, -1}, {46, 47, -1, -1}, {48, 49, -1, 50}, {51, 52, -1, 53}, {51, 52, -1, 54}, {55, 56, 57, -1}, {55, 56, -1, -1}, {58, 59, -1, 60}}+#define SPRITE_FLEUR_TOP 1366+#define FLEUR_TOP_RECTS {{0.781f, -0.844f, 0.953f, -0.688f}, {-1.078f, -0.984f, 1.141f, -0.531f}, {-1.281f, -1.016f, 1.313f, -0.484f}, {-1.359f, -1.016f, 1.969f, -0.141f}, {-2.141f, -1.031f, 2.531f, 0.047f}, {-2.250f, -1.078f, 2.766f, 0.266f}, {-2.797f, -1.203f, 3.094f, 0.578f}, {-2.938f, -1.219f, 3.219f, 0.859f}, {-3.203f, -1.234f, 3.469f, 1.141f}, {-3.312f, -1.234f, 3.766f, 1.281f}, {-3.547f, -1.250f, 4.000f, 1.328f}, {-3.844f, -1.250f, 4.016f, 1.328f}, {-4.016f, -1.250f, 4.031f, 1.344f}, {-4.031f, -1.250f, 4.031f, 1.344f}, {-4.047f, -1.250f, 4.031f, 1.359f}, {-4.047f, -1.250f, 4.031f, 1.359f}, {-4.047f, -1.266f, 4.031f, 1.359f}, {-4.047f, -1.266f, 4.031f, 1.359f}, {-4.062f, -1.266f, 4.047f, 1.375f}, {-4.062f, -1.266f, 4.047f, 1.375f}, {-4.062f, -1.266f, 4.047f, 1.375f}, {-4.062f, -1.266f, 4.047f, 1.375f}}+#define FLEUR_FRAMES 22+#define FLEUR_FPS 15.0f+#define SPRITE_FLEUR_BOT 1367+#define FLEUR_BOT_RECTS {{0.000f, 0.000f, 0.016f, 0.016f}, {0.000f, 0.000f, 0.016f, 0.016f}, {0.391f, 0.406f, 0.828f, 0.844f}, {-1.063f, 0.281f, 1.516f, 1.016f}, {-1.594f, -0.047f, 2.109f, 1.031f}, {-1.984f, -0.156f, 2.375f, 1.047f}, {-2.531f, -0.438f, 2.719f, 1.172f}, {-2.688f, -0.594f, 2.766f, 1.188f}, {-2.797f, -0.797f, 3.156f, 1.219f}, {-3.078f, -0.938f, 3.219f, 1.219f}, {-3.250f, -1.156f, 3.438f, 1.219f}, {-3.250f, -1.172f, 3.828f, 1.219f}, {-3.781f, -1.188f, 4.203f, 1.234f}, {-3.984f, -1.188f, 4.344f, 1.234f}, {-4.281f, -1.203f, 4.562f, 1.234f}, {-4.406f, -1.203f, 4.641f, 1.234f}, {-4.578f, -1.219f, 4.719f, 1.234f}, {-4.656f, -1.219f, 4.719f, 1.234f}, {-4.734f, -1.219f, 4.734f, 1.234f}, {-4.750f, -1.234f, 4.734f, 1.234f}, {-4.766f, -1.234f, 4.734f, 1.250f}, {-4.766f, -1.234f, 4.734f, 1.250f}}diff --git a/games/hollowknight/src/enemy.c b/games/hollowknight/src/enemy.cindex 22ada7d1..307469f4 100644--- a/games/hollowknight/src/enemy.c+++ b/games/hollowknight/src/enemy.c@@ -2265,7 +2265,8 @@ static void fk_update(Enemy *e) {if (done) {if (fk.first_jump) fk_idle(e);else {- /* Music: (its title shown), First Idle */+ /* Music: its title (on the right), First Idle */+ title_show(TITLE_FALSE_KNIGHT, TF_VISITED | TF_RIGHT);e->body.gravity_scale = 0.39f;anim_play(&e->anim, CLIP_FK_IDLE);fk_hitter(e, -1);@@ -3611,7 +3612,8 @@ static void gfly_update(Enemy *e) {break;case GF_SLEEP:if (hit) {- /* Wake: the arena's fight starts */+ /* Wake: her title, the arena's fight starts */+ title_show(TITLE_BIGFLY, TF_VISITED);cam_shake(SHAKE_AVERAGE);arena_start();anim_play_from_frame(&e->anim, CLIP_GFLY_WAKE, 0);diff --git a/games/hollowknight/src/game.c b/games/hollowknight/src/game.cindex a9ef37ea..4019d2d8 100644--- a/games/hollowknight/src/game.c+++ b/games/hollowknight/src/game.c@@ -303,6 +303,7 @@ static void step(uint32_t keys) {death_tick();world_tick();benches_tick();+ titles_tick();prompts_tick();dialogue_tick();hazard_tick();@@ -326,6 +327,7 @@ void game_tick(uint32_t keys) {void game_draw(void) {hud_draw();+ titles_draw();dialogue_draw();prompts_draw();obj_draw();diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.hindex e19ab2c8..9c875e53 100644--- a/games/hollowknight/src/game.h+++ b/games/hollowknight/src/game.h@@ -9,7 +9,7 @@enum {PDF_AT_BENCH, PDF_HAS_MAP, PDF_HAS_QUILL, PDF_HAS_CHARM, PDF_CHARM_BENCH_MSG, PDF_MET_ELDERBUG, PDF_VISITED_CROSSROADS,PDF_FALSE_KNIGHT_DEFEATED, PDF_FK_FIRST_PLOP, PDF_MAPPER_SHOP, PDF_CORN_CROSSROADS_LEFT, PDF_HORNET1_DEFEATED,- PDF_VISITED_DIRTMOUTH, PDF_TISO_ENCOUNTERED_TOWN, PDF_HAS_DASH, PDF_SHAMAN_PILLAR,+ PDF_VISITED_DIRTMOUTH, PDF_TISO_ENCOUNTERED_TOWN, PDF_HAS_DASH, PDF_SHAMAN_PILLAR, PDF_VISITED_GREENPATH,PDF_COUNT};typedef struct {@@ -29,7 +29,8 @@ typedef struct {float play_time;uint8_t flags[32]; /* PDF_* */uint8_t shaman; /* (the Snail Shaman's state) */- uint8_t reserved[63];+ uint8_t current_area; /* (the area whose title showed last: AreaTitleController) */+ uint8_t reserved[62];/* (saved apart, by the objects' names: their states) */uint8_t persist[MAX_PERSIST / 8];/* (not saved) */@@ -54,7 +55,7 @@ void save_set_respawn(const char *marker, bool facing_right); /* (Bench Controenum { ENT_CAMLOCK = 1, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE,ENT_BOX, ENT_OBJ, ENT_PIECE, ENT_SHADE_MARKER }; /* (shape, box, piece: more of the record before) */enum { OK_BREAKABLE = 1, OK_ENEMY, OK_GREAT_DOOR, OK_GEO_ROCK, OK_CHEST, OK_BENCH, OK_BATTLE, OK_FK_FLOOR, OK_BGATE,- OK_ARENA, OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP, OK_COCOON }; /* objects (ENT_OBJ's flags) */+ OK_ARENA, OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP, OK_COCOON, OK_AREA }; /* objects (ENT_OBJ's flags) *//* an enemy record's s1: starts alert (or first); startles; one of an arena's Pre Battle Enemies; its death counts for its arena; gone once its arena's* fight is over; spawned by its mother's burster; there only once its arena's fight is over; its FSMs off till near* the camera (FSMActivator); then its death's effects@@ -248,6 +249,18 @@ void shade_spawn_check(void); /* (SceneManager: the shade where the Knight die/* benches (npc.c) */void benches_enter(void);void benches_tick(void);+/* the titles (title.c): an area's, a boss's or a character's (TITLE_*), as Area Title's FSM variables are set:+ * Visited (the small title), NPC Title (small, till NPC TITLE DOWN or NPC CONVO START), Display Right */+enum { TF_VISITED = 1, TF_NPC = 2, TF_RIGHT = 4 };+/* (AreaTitleController: OK_AREA's p3, tools/ents.py) */+enum { AF_TRIGGER = 1, AF_REVISIT = 2, AF_RIGHT = 4, AF_DOOR = 8, AF_SUB = 16, AF_AFTER_CROSSROADS = 32 };+void title_show(int title, int flags);+void title_npc_convo_start(void);+void title_npc_down(void);+void titles_enter(void);+void titles_hero_in_position(void);+void titles_tick(void);+void titles_draw(void);bool bench_respawn(const char *name); /* RESPAWN: the Knight asleep on the bench so named *//* the Spell Control FSM (spell.c): focus, spells */diff --git a/games/hollowknight/src/gfx.c b/games/hollowknight/src/gfx.cindex dffffdbf..2d573fba 100644--- a/games/hollowknight/src/gfx.c+++ b/games/hollowknight/src/gfx.c@@ -47,6 +47,8 @@ typedef struct {/* the HUD's clip circles */typedef struct {float cx, cy, r; /* screen pixels */+ float x0, y0, x1, y1;+ bool box; /* (else a circle) */} HudClip;#define MAX_HUD_CLIPS 4static HudClip hud_clips[MAX_HUD_CLIPS];@@ -93,7 +95,7 @@ static void make_luts(void) {}static bool grade_off; /* (the HUD's tints: the room's grading not for them) */-#define HUD_TINT 248 /* (dynamic tints from here on are the HUD's) */+#define HUD_TINT 240 /* (dynamic tints from slot 16 on are the HUD's) */static uint32_t grade(float r, float g, float b, float a) {/* r g b a: 0..1 straight */@@ -119,20 +121,20 @@ uint8_t g_group_alpha[MAX_GROUPS];uint8_t g_screen_fade; /* how black the screen is (the camera's fade) *//* tints: the room's, then colors the game sets (gfx_dyn_tint): a color, and a flash color and amount (SpriteFlash) */-#define DYN_TINT 240+#define DYN_TINT 224static uint8_t dyn_tints[256 - DYN_TINT][8];static inline const uint8_t *tint_rgba(int tint) { return tint >= DYN_TINT ? dyn_tints[tint - DYN_TINT] : g_room.tints + 4 * tint; }static void pals_forget_tint(int tint);uint8_t gfx_dyn_flash(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a, uint8_t fr, uint8_t fg, uint8_t fb, uint8_t amount) {- uint8_t *t = dyn_tints[slot & 15];+ uint8_t *t = dyn_tints[slot & 31];uint8_t v[8] = {r, g, b, a, fr, fg, fb, amount};if (memcmp(t, v, 8)) {/* (the colors made with its old values are stale) */memcpy(t, v, 8);- pals_forget_tint(DYN_TINT + (slot & 15));+ pals_forget_tint(DYN_TINT + (slot & 31));}- return (uint8_t)(DYN_TINT + (slot & 15));+ return (uint8_t)(DYN_TINT + (slot & 31));}uint8_t gfx_dyn_tint(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { return gfx_dyn_flash(slot, r, g, b, a, 0, 0, 0, 0); }@@ -828,12 +830,18 @@ __attribute__((noinline)) static void draw_item(int idx, Item *it, int sy0, int}int xe = it->x1;if (it->clip) {- /* (a circle: this row's span of it) */+ /* (a circle or a box: this row's span of it) */const HudClip *k = &hud_clips[it->clip - 1];- float dy = y + 0.5f - k->cy, w2 = k->r * k->r - dy * dy;- if (w2 <= 0) continue;- float w = sqrtf(w2);- int ca = (int)(k->cx - w + 0.5f), cb = (int)(k->cx + w + 0.5f);+ int ca, cb;+ if (k->box) {+ if (y + 0.5f < k->y0 || y + 0.5f >= k->y1) continue;+ ca = (int)(k->x0 + 0.5f), cb = (int)(k->x1 + 0.5f);+ } else {+ float dy = y + 0.5f - k->cy, w2 = k->r * k->r - dy * dy;+ if (w2 <= 0) continue;+ float w = sqrtf(w2);+ ca = (int)(k->cx - w + 0.5f), cb = (int)(k->cx + w + 0.5f);+ }if (cb < xe) xe = cb;if (ca > x) x = open_from(cv, ca, it->x1);}@@ -1092,7 +1100,12 @@ bool gfx_hud(const Inst *in, int clip) {void gfx_hud_clip(int clip, float x, float y, float r) {/* (HUD units, from the screen's center, to pixels) */float k = FOCAL / (HUD_Z - CAM_Z);- hud_clips[clip - 1] = (HudClip){VIEW_W / 2 + x * k, VIEW_H / 2 - y * k, r * k};+ hud_clips[clip - 1] = (HudClip){VIEW_W / 2 + x * k, VIEW_H / 2 - y * k, r * k, 0, 0, 0, 0, false};+}++void gfx_hud_rect(int clip, float x0, float y0, float x1, float y1) {+ float k = FOCAL / (HUD_Z - CAM_Z);+ hud_clips[clip - 1] = (HudClip){0, 0, 0, VIEW_W / 2 + x0 * k, VIEW_H / 2 - y1 * k, VIEW_W / 2 + x1 * k, VIEW_H / 2 - y0 * k, true};}/* text: lines of glyphs (4-bit alpha), drawn in front of what is behind them in their layer */diff --git a/games/hollowknight/src/hk.h b/games/hollowknight/src/hk.hindex 9027bc54..6e703d91 100644--- a/games/hollowknight/src/hk.h+++ b/games/hollowknight/src/hk.h@@ -203,6 +203,7 @@ bool gfx_actor(const Inst *in, uint32_t group);/* the HUD: a sprite in front of all, placed in HUD units from the screen's center (its camera's: 8.7107 units half* height), not graded nor faded with the room (tints from HUD_TINT); clip: 0, or 1 + a circle it is drawn in */bool gfx_hud(const Inst *in, int clip);+void gfx_hud_rect(int clip, float x0, float y0, float x1, float y1); /* (a clip that is a box, HUD units) */void gfx_hud_clip(int clip, float x, float y, float r);uint8_t gfx_dyn_tint(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a); /* a tint (for Inst.tint) of that color *//* the same, flashing: its colors towards (fr, fg, fb) by amount (SpriteFlash) */@@ -230,7 +231,9 @@ static inline float font_f(const uint8_t *st, int i) {#define font_desc(st) font_f(st, 3)/* a code's glyph, the pen phase (0 .. FONT_PHASES - 1) parts of a pixel right of a whole pixel */static inline const Glyph *font_glyph(const uint8_t *st, uint8_t c, int phase) {- uint16_t o = rd16(st + 16 + 2 * (c * FONT_PHASES + phase));+ /* (the codes it has: from st[16], st[17] of them) */+ if ((uint8_t)(c - st[16]) >= st[17]) return NULL;+ uint16_t o = rd16(st + 20 + 2 * ((c - st[16]) * FONT_PHASES + phase));return o ? (const Glyph *)(const void *)(st + o) : NULL;}extern uint32_t g_gfx_items, g_gfx_pixels;diff --git a/games/hollowknight/src/hud.c b/games/hollowknight/src/hud.cindex 3647665f..ac86ad40 100644--- a/games/hollowknight/src/hud.c+++ b/games/hollowknight/src/hud.c@@ -141,13 +141,13 @@ static void hud_sprite(int sprite, float x, float y, float sx, uint8_t tint, intvoid hud_draw(void) {if (!hd.started || hd.off) return;float k = hd.scale;- uint8_t white = gfx_dyn_tint(8, 255, 255, 255, 255);+ uint8_t white = gfx_dyn_tint(16, 255, 255, 255, 255);/* the soul orb: its liquid (in the orb's circle), the frame over it */if (g_pd.mp > 1 && !hd.out) { /* (the liquid's renderer off while the HUD is out) */float y = FILL_Y + LIQUID_BOTTOM_Y + g_pd.mp * LIQUID_Y_PER_MP;uint8_t g = (uint8_t)(255 - (255 - 110) * hd.liquid_grey);gfx_hud_clip(1, CANVAS_X + (FILL_X - 2.28f - CANVAS_X) * k, CANVAS_Y + (FILL_Y + 1.32f - CANVAS_Y) * k, 0.97f * k);- hud_sprite(hd.liquid.sprite, FILL_X - 2.23f, y, 1, gfx_dyn_tint(9, g, g, g, 255), 1);+ hud_sprite(hd.liquid.sprite, FILL_X - 2.23f, y, 1, gfx_dyn_tint(17, g, g, g, 255), 1);}hud_sprite(hd.frame.sprite, ORB_X + 0.12f, ORB_Y + 0.92f, 1, white, 0);if (hd.burst_on) hud_sprite(hd.burst.sprite, ORB_X - 0.715f, ORB_Y + 0.4318f, 1, white, 0);diff --git a/games/hollowknight/src/text.c b/games/hollowknight/src/text.cindex 701fc5a9..82c5f3f0 100644--- a/games/hollowknight/src/text.c+++ b/games/hollowknight/src/text.c@@ -256,14 +256,14 @@ void dialogue_draw(void) {if (dl.alpha > 0 || dl.fleurs_on) {/* the backboard (0.6 of its color's alpha), the fleurs */uint8_t a = (uint8_t)(dl.alpha * 0.6f * 0.616f * 255);- if (a) box_sprite(SPRITE_DIALOGUE_BACKBOARD, 0, 4.51f - 0.09f, 1, 1.2527f / 2.325f, gfx_dyn_tint(12, 255, 255, 255, a));- uint8_t white = gfx_dyn_tint(13, 255, 255, 255, 255);+ if (a) box_sprite(SPRITE_DIALOGUE_BACKBOARD, 0, 4.51f - 0.09f, 1, 1.2527f / 2.325f, gfx_dyn_tint(18, 255, 255, 255, a));+ uint8_t white = gfx_dyn_tint(19, 255, 255, 255, 255);if (dl.fleurs_on) {box_sprite(dl.fleur_top.sprite, 0, 4.51f + 2.85f, TEXT_K, TEXT_K, white);box_sprite(dl.fleur_bot.sprite, 0, 4.51f - 2.73f, TEXT_K, TEXT_K, white);}}- uint8_t white = gfx_dyn_tint(14, 255, 255, 255, 255);+ uint8_t white = gfx_dyn_tint(20, 255, 255, 255, 255);if (dl.arrow_on && dl.arrow.sprite >= 0) box_sprite(dl.arrow.sprite, 0.0069f, 1.695f, MARKER_K, MARKER_K, white);if (dl.stop_on && dl.stop.sprite >= 0) box_sprite(dl.stop.sprite, -0.0231f, 1.695f, MARKER_K, MARKER_K, white);if (!dl.text) return;diff --git a/games/hollowknight/src/title.c b/games/hollowknight/src/title.cnew file mode 100644index 00000000..8c95f134--- /dev/null+++ b/games/hollowknight/src/title.c@@ -0,0 +1,275 @@+/* The titles (Area Title: its Area Title Control FSM) and what shows them: a room's AreaTitleController, bosses and+ * characters (TITLE_*). On a first visit to an area its large title: the fleurs drawn in above and below, the lines faded+ * up; else the small one at the bottom left (or right). Places in HUD units from the screen's center. */+#include <math.h>+#include "game.h"++#define DT 0.02f+#define HUD_PX (FOCAL / (-1.342f - CAM_Z))+#define TITLE_Y 6.1f /* (Area Title's place; Fleur Top's, from it) */+#define FLEUR_TOP_Y 0.35f+#define SMALL_X (-13.68f) /* (Init: Small Title X Pos, Small Title X Pos R) */+#define SMALL_X_R 13.0f++/* the FSM's states (those that take time) */+enum { T_OFF, T_PAUSE, T_TITLES_UP, T_FLEURS_UP, T_TITLES_DOWN, T_SMALL_FRAME, T_VISITED_APPEAR, T_NPC_WAIT,+ T_VISITED_DISAPPEAR, T_QUICK_DISAPPEAR };++static const int16_t table[NUM_TITLES][4] = TITLE_TABLE; /* (main line large, main line small, below, above) */+static const float fleur_rects[2][FLEUR_FRAMES][4] = {FLEUR_TOP_RECTS, FLEUR_BOT_RECTS};++static struct {+ uint8_t st, flags;+ int8_t title;+ int8_t next, next_flags; /* (Area Event set again while it quickly disappears: -1 none) */+ bool large;+ float t; /* (the state's Wait) */+ /* FadeGroup: the shown folder's alpha, fading up (1) or down (-1) over its time */+ float alpha, fade_time;+ int8_t fade;+ /* the large title's folder and bottom fleur (kept where the last title put them), the small one's place */+ float folder_y, fleur_bot_y, small_x, small_y;+ /* the fleurs: their Appear clips' time (-1: Idle), their alpha (color_fader) */+ bool fleurs;+ float fleur_t, fleur_alpha, fleur_fade;+} at = {.folder_y = -3.03f, .fleur_bot_y = -5.92f};++/* AreaTitleController: a room's; its coroutine's pause, then the title */+#define MAX_AREAS 2+static struct {+ uint16_t ent;+ bool played, waiting, visited;+ float t;+} areas[MAX_AREAS];+static int nareas;++static void fade_group(int dir, float time) {+ /* (FadeUp from 0; FadeDown from full) */+ at.fade = (int8_t)dir, at.fade_time = time, at.alpha = dir > 0 ? 0 : 1;+}++static void start(void) {+ /* Pause: the folders off, then next frame Init, Other, the checks: Visited Check */+ at.st = T_PAUSE, at.t = 0, at.fleurs = false, at.alpha = 0, at.fade = 0;+}++void title_show(int title, int flags) {+ if (title < 0 || title >= NUM_TITLES) return;+ if (at.st == T_OFF || at.st == T_PAUSE) {+ at.title = (int8_t)title, at.flags = (uint8_t)flags;+ if (at.st == T_OFF) start();+ } else if (at.st == T_QUICK_DISAPPEAR)+ at.next = (int8_t)title, at.next_flags = (int8_t)flags; /* (Reappear?: CANCEL) */+}++static void quick_disappear(void) {+ at.next = -1;+ if (!at.large) fade_group(-1, 0.5f); /* (the small folder's FadeDownFast) */+ at.st = T_QUICK_DISAPPEAR, at.t = 0;+}++void title_npc_convo_start(void) {+ if (at.st == T_TITLES_UP) at.t = 1e9f; /* (straight to Fleurs Up) */+ else if (at.st == T_VISITED_APPEAR || at.st == T_NPC_WAIT) quick_disappear();+}++void title_npc_down(void) {+ if (at.st == T_NPC_WAIT) quick_disappear();+}++static float width_of(int text, int style) {+ if (text < 0) return 0;+ const uint8_t *s = text_get(text);+ return text_width(style, s, (int)strlen((const char *)s)) / HUD_PX;+}++static void titles_tick_fsm(void) {+ const int16_t *row = table[at.title];+ bool sub = row[2] >= 0, sup = row[3] >= 0;+ at.t += DT;+ if (at.fade) {+ float k = at.fade_time > 0 ? DT / at.fade_time : 1;+ at.alpha += at.fade * k;+ if (at.alpha >= 1) at.alpha = 1, at.fade = 0;+ if (at.alpha <= 0) at.alpha = 0, at.fade = 0;+ }+ if (at.fleurs) {+ if (at.fleur_t >= 0) at.fleur_t += DT;+ if (at.fleur_fade > 0) {+ at.fleur_alpha -= DT / at.fleur_fade;+ if (at.fleur_alpha <= 0) at.fleur_alpha = 0, at.fleur_fade = 0;+ }+ }+ switch (at.st) {+ case T_PAUSE:+ if (at.t < DT) break;+ if ((at.flags & (TF_NPC | TF_VISITED))) {+ /* Set Text Small: its place; a frame on, its lines' widths (Bounds, Set Margin) */+ at.large = false, at.small_y = TITLE_Y - 12.41f;+ at.st = T_SMALL_FRAME, at.t = 0;+ } else {+ /* Set Text Large: the fleurs on (Idle), then where the lines and the bottom fleur go */+ at.large = true, at.fleurs = true, at.fleur_t = -1, at.fleur_alpha = 1, at.fleur_fade = 0;+ if (sub && !sup) at.fleur_bot_y = -5.24f, at.folder_y = -2.24f;+ else if (!sub && sup) at.fleur_bot_y = -5.24f, at.folder_y = -3.03f;+ else if (!sub && !sup) at.fleur_bot_y = -4.38f, at.folder_y = -2.24f;+ at.st = T_TITLES_UP, at.t = 0;+ }+ break;+ case T_TITLES_UP:+ if (at.t >= 0.6f) {+ /* Fleurs Up: the lines fade up (4 s), the fleurs drawn in */+ fade_group(1, 4);+ at.fleur_t = 0;+ at.st = T_FLEURS_UP, at.t = 0;+ }+ break;+ case T_FLEURS_UP:+ if (at.t >= 4.75f) {+ fade_group(-1, 1.5f);+ at.fleur_fade = 1.5f; /* (color_fader's DOWN) */+ at.st = T_TITLES_DOWN, at.t = 0;+ }+ break;+ case T_TITLES_DOWN:+ if (at.t >= 2) at.st = T_OFF, at.fleurs = false; /* (Big Title End, Done) */+ break;+ case T_SMALL_FRAME: {+ float half = width_of(row[1], STYLE_TITLE_S) / 2, w = width_of(row[2], STYLE_TITLE_SUB) / 2,+ u = width_of(row[3], STYLE_TITLE_SUB) / 2;+ if (w > half) half = w;+ if (u > half) half = u;+ at.small_x = (at.flags & TF_RIGHT) ? SMALL_X_R - half : SMALL_X + half;+ if (!sub) at.small_y = TITLE_Y - 13.15f; /* (Super only 2: no line below) */+ fade_group(1, 1.5f);+ at.st = (at.flags & TF_NPC) ? T_NPC_WAIT : T_VISITED_APPEAR, at.t = 0;+ break;+ }+ case T_VISITED_APPEAR:+ if (at.t >= 6) fade_group(-1, 1.5f), at.st = T_VISITED_DISAPPEAR, at.t = 0;+ break;+ case T_VISITED_DISAPPEAR:+ if (at.t >= 1.5f) at.st = T_OFF;+ break;+ case T_QUICK_DISAPPEAR:+ if (at.t >= 0.5f) {+ if (at.next >= 0) {+ at.title = at.next, at.flags = (uint8_t)at.next_flags;+ start();+ } else+ at.st = T_OFF;+ }+ break;+ }+}++/* ---------------------------------------------------------------- AreaTitleController */+static const Ent *ent_at(int i) {+ int n;+ return &room_ents(&n)[i];+}++void titles_enter(void) {+ nareas = 0;+ int n;+ const Ent *es = room_ents(&n);+ for (int i = 0; i < n && nareas < MAX_AREAS; i++)+ if (es[i].type == ENT_OBJ && es[i].flags == OK_AREA) {+ memset(&areas[nareas], 0, sizeof areas[0]);+ areas[nareas++].ent = (uint16_t)i;+ }+}++/* Play: by its gate only (else off); CheckArea, Finish: a sub area's title is the small one; an area's large on a+ * first visit, small after, none while still in it */+static void area_play(int k) {+ const Ent *e = ent_at(areas[k].ent);+ int fl = (int)e->p3;+ areas[k].played = true;+ if (fl & AF_DOOR) {+ int n;+ const Ent *es = room_ents(&n);+ int g = g_hero.entry_gate;+ if (g < 0 || g >= n || strcmp(str_at(es[g].s0), str_at(e->s0))) return;+ }+ if ((fl & AF_AFTER_CROSSROADS) && !pd_flag(PDF_VISITED_CROSSROADS)) return;+ bool visited = true;+ if (!(fl & AF_SUB)) {+ visited = e->group != 255 && pd_flag(e->group);+ if ((!visited && (fl & AF_REVISIT)) || (int)e->p2 == g_pd.current_area) return;+ }+ areas[k].waiting = true, areas[k].visited = visited, areas[k].t = 0;+}++void titles_hero_in_position(void) {+ for (int k = 0; k < nareas; k++)+ if (!areas[k].played && !((int)ent_at(areas[k].ent)->p3 & AF_TRIGGER)) area_play(k);+}++void titles_tick(void) {+ const Body *b = &g_hero.body;+ float x0 = b->x + b->ox - b->hx, x1 = b->x + b->ox + b->hx, y0 = b->y + b->oy - b->hy, y1 = b->y + b->oy + b->hy;+ for (int k = 0; k < nareas; k++) {+ const Ent *e = ent_at(areas[k].ent);+ if (!areas[k].played && ((int)e->p3 & AF_TRIGGER) && x1 > e->x0 && x0 < e->x1 && y1 > e->y0 && y0 < e->y1)+ area_play(k);+ if (!areas[k].waiting) continue;+ /* VisitPause, UnvisitPause: the area is the current one; on a first visit, visited from now on */+ areas[k].t += DT;+ if (areas[k].t < (areas[k].visited ? e->p1 : e->p0)) continue;+ areas[k].waiting = false;+ g_pd.current_area = (uint8_t)e->p2;+ title_show(e->a, areas[k].visited ? TF_VISITED : 0);+ if (!areas[k].visited && e->group != 255) pd_set_flag(e->group, true);+ }+ if (at.st != T_OFF) titles_tick_fsm();+}++/* ---------------------------------------------------------------- drawing */+static void line(int text, int style, float x, float y, uint32_t a) {+ if (text < 0 || !a) return;+ const uint8_t *s = text_get(text), *st = font_style(style);+ int n = (int)strlen((const char *)s);+ /* (centered on its place: the baseline below it by half the font's ascender and descender) */+ float px = VIEW_W / 2 + x * HUD_PX - text_width(style, s, n) / 2;+ float py = VIEW_H / 2 - y * HUD_PX + (font_asc(st) - font_desc(st)) / 2;+ gfx_text(style, px, py, s, n, a << 24 | 0xFFFFFF, 0);+}++void titles_draw(void) {+ if (at.st == T_OFF) return;+ const int16_t *row = table[at.title];+ uint32_t a = (uint32_t)(at.alpha * 255 + 0.5f);+ bool shown = at.alpha > 0 || at.fade > 0;+ if (at.large && shown) {+ float y = TITLE_Y + at.folder_y;+ line(row[0], STYLE_TITLE_L, 0, y, a);+ line(row[2], STYLE_TITLE_SUB, 0, y - 1.11f, a);+ line(row[3], STYLE_TITLE_SUB, 0, y + 1.4f, a);+ } else if (!at.large && at.st != T_PAUSE && at.st != T_SMALL_FRAME && shown) {+ line(row[1], STYLE_TITLE_S, at.small_x, at.small_y, a);+ line(row[2], STYLE_TITLE_SUB, at.small_x, at.small_y - 0.84f, a);+ line(row[3], STYLE_TITLE_SUB, at.small_x, at.small_y + 1.09f, a);+ }+ if (at.fleurs && at.fleur_t >= 0 && at.fleur_alpha > 0) {+ /* (each frame of their Appear clips: the last one, as much of it as that frame shows) */+ int f = (int)(at.fleur_t * FLEUR_FPS);+ if (f >= FLEUR_FRAMES) f = FLEUR_FRAMES - 1;+ uint8_t tint = gfx_dyn_tint(21, 255, 255, 255, (uint8_t)(at.fleur_alpha * 255 + 0.5f));+ for (int i = 0; i < 2; i++) {+ float y = TITLE_Y + (i ? at.fleur_bot_y : FLEUR_TOP_Y);+ const float *r = fleur_rects[i][f];+ gfx_hud_rect(2 + i, r[0], y + r[1], r[2], y + r[3]);+ Inst in;+ sprite_inst(i ? SPRITE_FLEUR_BOT : SPRITE_FLEUR_TOP, 0, y, 0, 1, 1, tint, &in);+ gfx_hud(&in, 2 + i);+ }+ }+}++#ifdef HOST+#include <stdio.h>+void titles_debug(void) {+ if (at.st != T_OFF) fprintf(stderr, "title %d state %d large %d alpha %.2f fleur %.2f\n", at.title, at.st, at.large, at.alpha, at.fleur_t);+}+#endifdiff --git a/games/hollowknight/src/world.c b/games/hollowknight/src/world.cindex 00af0665..9424e330 100644--- a/games/hollowknight/src/world.c+++ b/games/hollowknight/src/world.c@@ -128,6 +128,7 @@ void world_enter(void) {if (e[i].group2) group_fade(e[i].group2, 0, 0); /* (Pause: the inverse mask hidden) */}obj_enter();+ titles_enter();}/* (Pause's WaitForHeroInPosition: the masks start as the Knight is placed; its Wait only counts when it was placed@@ -139,6 +140,7 @@ void world_hero_in_position(void) {const Ent *e = room_ents(&n);for (int i = 0; i < n && i < MAX_ENTS; i++)if (e[i].type == ENT_MASK && es[i].state == M_PAUSE) mask_idle(&e[i], &es[i]);+ titles_hero_in_position();}/* an object's FSM sent HIT to another (a breakable's hitEventReciever) */diff --git a/games/hollowknight/tools/actors.py b/games/hollowknight/tools/actors.pyindex d5c28a5a..34f70e61 100644--- a/games/hollowknight/tools/actors.py+++ b/games/hollowknight/tools/actors.py@@ -252,7 +252,7 @@ def unity_sprites(keys):c = tk2d.collection(path, col)sid = next(i for i, dd in enumerate(c["spriteDefinitions"]) if unity.S(dd["name"]) == name)img, lx, ty, upp, (wu, hu) = tk2d.sprite_image(path, c, sid)- w, h = max(1, round(img.width * upp * K0 * scale)), max(1, round(img.height * upp * K0 * scale))+ w, h = max(1, round(img.width * upp * K0 * scale * res)), max(1, round(img.height * upp * K0 * scale * res))arr = np.asarray(img.resize((w, h), Image.BOX)).copy()out.append({"key": (path, col, sid), "job": art.ImageJob(arr, "tk2d/%s" % name), "lx": lx * scale,"ty": ty * scale, "tu": wu * scale / w, "tv": hu * scale / h})@@ -265,3 +265,26 @@ def unity_sprites(keys):out.append({"key": (level, fid, pid), "job": art.ImageJob(arr, "piece/%s" % s.name),"lx": -s.px * wu, "ty": (1 - s.py) * hu, "tu": wu / w, "tv": hu / h})return out+++def title_fleurs(sprites):+ """The large area title's fleurs (Fleur Top, Fleur Bot: their Appear clips): their last frames as HUD sprites, and+ each frame's bounds (HUD units, from the fleur's place: what of the last frame it shows) -> {name: value}"""+ lib = tk2d.animation("resources.assets", 23444)+ byname = {unity.S(c["name"]): c for c in lib["clips"]}+ out = {}+ for name, clip in (("TOP", "Top Appear"), ("BOT", "Bottom Appear")):+ frames = byname[clip]["frames"]+ cpath, cpid = tk2d.ref_file("resources.assets", frames[-1]["spriteCollection"])+ col = tk2d.collection(cpath, cpid)+ last = frames[-1]["spriteId"]+ out["SPRITE_FLEUR_" + name] = sprites.tk2d(cpath, cpid, unity.S(col["spriteDefinitions"][last]["name"]), 1.0,+ HUD_K / K0)+ rects = []+ for f in frames:+ img, lx, ty, upp, (wu, hu) = tk2d.sprite_image(cpath, col, f["spriteId"])+ rects.append("{%.3ff, %.3ff, %.3ff, %.3ff}" % (lx, ty - hu, lx + wu, ty))+ out["FLEUR_%s_RECTS" % name] = "{%s}" % ", ".join(rects)+ out["FLEUR_FRAMES"] = len(frames)+ out["FLEUR_FPS"] = "%.1ff" % byname[clip]["fps"]+ return outdiff --git a/games/hollowknight/tools/ents.py b/games/hollowknight/tools/ents.pyindex da70ac69..64815f0d 100644--- a/games/hollowknight/tools/ents.py+++ b/games/hollowknight/tools/ents.py@@ -9,7 +9,15 @@ ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MENT_OBJ, ENT_PIECE, ENT_SHADE_MARKER = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12# objects (ENT_OBJ's flags: src/obj.c)OK_BREAKABLE, OK_ENEMY, OK_GREAT_DOOR, OK_GEO_ROCK, OK_CHEST, OK_BENCH, OK_BATTLE, OK_FK_FLOOR, OK_BGATE, OK_ARENA, \- OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP, OK_COCOON = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16+ OK_EVENT, OK_SUMMON, OK_COND, OK_PROP, OK_DRIP, OK_COCOON, OK_AREA = \+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17+# area titles (AreaTitleController: OK_AREA's p3): wait for its trigger, only on a revisit, shown on the right, only+# when the Knight came in by a gate (s0), a sub area (always the small title), only once the Crossroads were visited+AF_TRIGGER, AF_REVISIT, AF_RIGHT, AF_DOOR, AF_SUB, AF_AFTER_CROSSROADS = 1, 2, 4, 8, 16, 32+# (its area list: identifier -> area number, sub area, the PlayerData bool it sets on a first visit)+AREAS = {"KINGSPASS": (0, True, None), "DIRTMOUTH": (1, False, "visitedDirtmouth"),+ "CROSSROADS": (2, False, "visitedCrossroads"), "EGGTEMPLE": (0, True, None),+ "SHAMANTEMPLE": (0, True, None), "GREENPATH": (3, False, "visitedGreenpath")}# the battle gates' events (src/game.h: BG_*)BG_EVENTS = ["BG CLOSE", "BG QUICK CLOSE", "BG OPEN", "BG QUICK OPEN", "BG DESTROY"]# battle gates (BG Control: OK_BGATE's s0): closed at first, the bone ones' clips, gone once a PlayerData bool is set@@ -105,9 +113,9 @@ class Sprites:"""(res: its texture's resolution, as a part of the screen's: smooth sprites can be stretched)"""return self._add((d["level"], tuple(d["externals"]), ref[0], ref[1], round(scale, 3), res))- def tk2d(self, path, col, name, scale=1.0):+ def tk2d(self, path, col, name, scale=1.0, res=1.0):"""A 2D Toolkit sprite of a collection (file, path id), by name."""- return self._add(("tk2d", path, col, name, round(scale, 3), 1.0))+ return self._add(("tk2d", path, col, name, round(scale, 3), res))def _add(self, key):if key not in self.index:@@ -891,6 +899,21 @@ def room(d, rooms, strings, persist, name, sprites=None, owners=None, rec_base=0recs.append(rec(ENT_BOX, 0, (splat["lpos"][0] if splat else 0, splat["lpos"][1] if splat else 0,splat["pos"][2] if splat else 0, 0),(sprites.tk2d(*sp) if sp else -1, eclip, layer, order)))+ f = _fsm(o, ("Area Title Controller",))+ if f and any(c.get("class") == "AreaTitleController" for c in o["c"]):+ # an area's title: its trigger (if it waits for one), its pauses, its area, its flags; the title; the bool+ # its first visit sets+ import text+ v = {k: x[1] for k, x in f["vars"].items()}+ ident = v.get("Area Event", "")+ num, sub, vis = AREAS[ident]+ fl = (AF_TRIGGER if v.get("Wait for Trigger") else 0) | (AF_REVISIT if v.get("Only On Revisit") else 0) | \+ (AF_RIGHT if v.get("Display Right") else 0) | (AF_DOOR if v.get("Door Trigger") else 0) | \+ (AF_SUB if sub else 0) | (AF_AFTER_CROSSROADS if ident == "KINGSPASS" else 0)+ box = _trigger(o) if fl & AF_TRIGGER else None+ recs.append(rec(ENT_OBJ, OK_AREA, box or (0, 0, 0, 0), (v.get("Unvisited Pause", 2), v.get("Visited Pause", 2), num, fl),+ a=text.TITLES.index(ident), group=pdf[vis] if vis else 255,+ s0=strings.id(v["Door Trigger"]) if v.get("Door Trigger") else 0))dv = next((c.get("v") for c in o["c"] if c.get("class") == "WaterDrip" and c.get("v")), None)if dv is not None:# a water drip: its place, its idle times, fall speed and how far it sinks as it hitsdiff --git a/games/hollowknight/tools/pack.py b/games/hollowknight/tools/pack.pyindex 85b4c7af..85a90f1c 100644--- a/games/hollowknight/tools/pack.py+++ b/games/hollowknight/tools/pack.py@@ -250,6 +250,7 @@ def room_blobs(name, keep, st, tex_id, variant=0):table += struct.pack("<IIHHff", 0, 0, len(recs), 0, va, vb) # (offsets filled in by main)HDR = 84 + 192gw, gh, cells = coll.grid(segs, w, h)+ assert len(tints) <= 224, (name, len(tints)) # (src/gfx.c: DYN_TINT, the colors the game sets after)hdr = struct.pack("<4H4f4f4fff6HII", 6, len(order), len(tints), axis, w, h, bz, sat, *st["ambient"], 0.0,*st["hero_light"], lo, hi, len(keep), len(segs), len(cols), gw, gh, len(erecs), 0, 0) + lutassert len(hdr) == HDR, len(hdr)@@ -342,6 +343,15 @@ def main():named = actors.named_sprites(SPRITES)prompt_ids = {p: TEXTS.id("Prompts", p.upper(), "PROMPT") for p in PROMPTS}TEXTS.id("Elderbug", "ELDERBUG_INTRO_MAIN") # (until the NPCs: a conversation to try)+ # the titles (Area Title): each one's main line as the large and the small title show it, its lines below and above+ titles = []+ for t in text.TITLES:+ row = []+ for key, style in (("_MAIN", "TITLE_L"), ("_MAIN", "TITLE_S"), ("_SUB", "TITLE_SUB"), ("_SUPER", "TITLE_SUB")):+ line = text.clean(text.sheets()["Titles"].get(t + key) or "")+ row.append(TEXTS.add(line, style) if line else -1)+ titles.append("{%s}" % ", ".join(str(i) for i in row))+ fleurs = actors.title_fleurs(SPRITES)for r in ROOMS:room_data(r)if r in VARIANT_ROOMS:@@ -526,6 +536,11 @@ def main():f.write("#define TXT_PROMPT_%s %d\n" % (k.upper(), v))f.write("#define PROMPT_SORT %du\n" % ((scene.layer_index(-349214895) << 16) | (1 + 32768)))f.write("#define DIGIT_ADV {%s}\n" % ", ".join("%.4ff" % a for a in digit_adv))+ for i, t in enumerate(text.TITLES):+ f.write("#define TITLE_%s %d\n" % (t, i))+ f.write("#define NUM_TITLES %d\n#define TITLE_TABLE {%s}\n" % (len(titles), ", ".join(titles)))+ for k, v in fleurs.items():+ f.write("#define %s %s\n" % (k, v))if __name__ == "__main__":diff --git a/games/hollowknight/tools/pack.py.orig b/games/hollowknight/tools/pack.py.origdeleted file mode 100644index 1147b6fe..00000000--- a/games/hollowknight/tools/pack.py.orig+++ /dev/null@@ -1,519 +0,0 @@-"""Hollow Knight for the NumWorks calculator: makes src/data.bin (and src/data.h) from the game's files.-HOLLOWKNIGHT=<the game's Data folder> python3 pack.py"""-import os, sys, struct, math, lzma, time, multiprocessing as mp-import numpy as np-HERE = os.path.dirname(os.path.abspath(__file__))-sys.path.insert(0, HERE)-import unity, scene, visible, art, actors, coll, ents, font, text--SRC = os.path.join(HERE, "..", "src")-ALL_ROOMS = [l.strip() for l in open(os.path.join(HERE, "rooms.txt")) if l.strip() and not l.startswith("#")]-# (scenes loaded with others are part of those: two variants of the room, by a PlayerData bool)-ROOMS = [r for r in ALL_ROOMS if r not in scene.additive_scenes(ALL_ROOMS)]-VARIANT_ROOMS = [r for r in ROOMS if scene.additive(r)]-STRINGS = ents.Strings()-PERSIST = ents.Persist()-SPRITES = ents.Sprites()-TEXTS = text.Texts()-# the prompt markers' labels (Arrow Prompt New's)-PROMPTS = ["Listen", "Rest", "Inspect", "Enter", "Sit", "Shop", "Travel", "Ascend", "Descend", "Exit", "Accept", "Trade",- "Watch", "Challenge"]-ROOM_DATA = {} # name -> (coll.room's, ents.room's)---def room_data(name, variant=0):- """A room's ground and objects (once: the objects' sprites go into SPRITES) -> (coll.room's, (records, {(scene,- object id): group}), {which: its groups (first, last)}). With the scenes it loads with it: variant 0 has the first's- (which 1), variant 1 the alternative's (which 2); the groups of both numbered the same in either, after the room's;- (scene, None): the group of a scene's sprites with none of their own."""- if (name, variant) not in ROOM_DATA:- d = unity.scene(name)- st = scene.settings(d)- w, h = st["size"] if st["size"] else (40, 24)- solid, segs, cols, owners = coll.room(d, w, h)- recs, gr = ents.room(d, ROOMS, STRINGS, PERSIST, name, SPRITES, owners)- groups = {(name, k): g for k, g in gr.items()}- segs, cols, recs = list(segs), list(cols), list(recs)- gb = max(gr.values(), default=0)- spans = {}- for an, flag, val, which in scene.additive(name):- da = unity.scene(an)- _, asegs, acols, aown = coll.room(da, w, h)- ar, ag = ents.room(da, ROOMS, STRINGS, PERSIST, an, SPRITES, aown, rec_base=len(recs), col_base=len(cols),- group_base=gb)- cond = max(ag.values(), default=gb) + 1- groups.update({(an, k): g for k, g in ag.items()})- groups[(an, None)] = cond- spans[which] = (gb + 1, cond)- gb = cond- if (which == 1) == (variant == 0):- segs += [(x0, y0, x1, y1, ci + len(cols)) for x0, y0, x1, y1, ci in asegs]- cols += acols- recs += ar- assert gb < ents.MAX_GROUPS, (name, gb)- ROOM_DATA[(name, variant)] = ((solid, segs, cols, owners), (recs, groups), spans)- return ROOM_DATA[(name, variant)]--SECTIONS = ["TEX", "TMAP", "PAL", "BIDX", "BLK", "ROOMS", "RBLOB", "PRIOR", "SOFT", "SPR", "CLIP", "STR", "TEXT", "FONT", "PHASH",- "SCOL", "RVAR"]---def _pdf_flags():- return ents.pd_flags()-BLENDS = {"alpha": 0, "add": 1, "screen": 2, "linearlight": 3, "overlay": 4, "multiply": 5}-F_LIT, F_ROT, F_SOLID, F_DYN, F_GRASS = 8, 16, 32, 64, 128--TC_N0 = 1 # (src/tilecode.h)-LZ = [{"id": lzma.FILTER_LZMA1, "lc": 0, "lp": 0, "pb": 0, "dict_size": 1 << 16, "preset": 9 | lzma.PRESET_EXTREME}]---def lz(b):- return lzma.compress(b, format=lzma.FORMAT_RAW, filters=LZ)---def f16(x):- return int(np.array(x, np.float16).view(np.uint16))---def i16(x):- return max(-32768, min(32767, int(round(x))))---def f16s(x):- """A half float's bits as a signed 16-bit value (for struct 'h')."""- v = f16(x)- return v - 65536 if v >= 32768 else v---class Blob:- def __init__(self):- self.b = bytearray()-- def align(self, n=4):- while len(self.b) % n:- self.b.append(0)-- def add(self, data, align=4):- self.align(align)- o = len(self.b)- self.b += data- return o---SECTOR = 16.0 # sectors along the room's long camera axis (units)-GLOBAL_SPAN = 40.0 # instances seen over a longer stretch of camera positions are always kept-MARGIN = 2.0---def inst_record(it, tex_id, tints):- """An instance: where, its texture, how it is drawn."""- q = it.quad # bl, br, tr, tl (world)- tl, tr, bl = q[3], q[2], q[0]- flags = BLENDS.get(it.blend, 0)- if it.lit:- flags |= F_LIT- if it.group:- flags |= F_DYN # (in a render group: a byte more)- if it.grass:- flags |= F_GRASS- color = it.color- if it.solid and it.sprite.name == "black_solid":- color = (0, 0, 0, color[3])- col = tuple(int(round(min(1, max(0, c)) * 255)) for c in color)- if col not in tints:- tints.append(col)- tint = min(255, tints.index(col))- rot = 0- if it.solid:- flags |= F_SOLID- tex = 0xFFFF- ax, ay = min(p[0] for p in q), max(p[1] for p in q)- a, b = max(p[0] for p in q) - ax, -(ay - min(p[1] for p in q))- else:- t = tex_id[id(it.variant)]- tex, tw, th = t- eu = (tr - tl) / tw- ev = (bl - tl) / th- ax, ay = tl[0], tl[1]- a = math.hypot(eu[0], eu[1])- ang = math.atan2(eu[1], eu[0])- # flips: keep the angle small, put the sign in a- if abs(ang) > math.pi / 2:- ang = ang - math.pi if ang > 0 else ang + math.pi- a = -a- c, s_ = math.cos(ang), math.sin(ang)- b = ev[0] * -s_ + ev[1] * c # along (-sin, cos)- rot = int(round(ang / (2 * math.pi) * 65536))- if rot:- flags |= F_ROT- return (ax, ay, it.z, tex, tint, flags, a, b, rot, it.group)---def uvar(u):- out = bytearray()- while u >= 128:- out.append(u & 127 | 128)- u >>= 7- out.append(u)- return out---def svar(v):- return uvar(v << 1 if v >= 0 else ((-v) << 1) - 1)---def sector_stream(recs):- """A sector's instances in draw order, each relative to the one before (read in place by room.c):- flags, aux (1 tint, 2 same texture, 4 same z, 8|16 b: 0 its own, 1 = a, 2 = -a, 3 same as before, 32 same a,- 64 next rank, 128 another sorting layer or order), [rank step - 2], [layer, order], [texture step], [tint],- x step, y step, [z step], [a], [b], [angle], [render group (F_DYN)]."""- out = bytearray()- pr, pt, px, py, pz, pa, pb, pg = -1, 0, 0, 0, 0, 0, 0, None- for rank, (ax, ay, z, tex, tint, flags, a, b, rot, rgroup), group in recs:- X, Y, Z, A, B = i16(ax * 64), i16(ay * 64), i16(z * 128), f16s(a) & 0xFFFF, f16s(b) & 0xFFFF- aux = 0- if tint:- aux |= 1- if tex == pt:- aux |= 2- if Z == pz:- aux |= 4- bm = 1 if B == A else 2 if B == A ^ 0x8000 else 3 if B == pb else 0- aux |= bm << 3- if A == pa:- aux |= 32- if rank == pr + 1:- aux |= 64- if group != pg:- aux |= 128- out += bytes([flags, aux])- if not aux & 64:- out += uvar(rank - pr - 2)- if aux & 128:- out += bytes([group[0]]) + svar(group[1])- if not aux & 2:- out += svar(tex - pt)- if tint:- out.append(tint)- out += svar(X - px) + svar(Y - py)- if not aux & 4:- out += svar(Z - pz)- if not aux & 32:- out += struct.pack("<H", A)- if bm == 0:- out += struct.pack("<H", B)- if flags & F_ROT:- out += struct.pack("<h", rot)- if flags & F_DYN:- out.append(rgroup)- pr, pt, px, py, pz, pa, pb, pg = rank, tex, X, Y, Z, A, B, group- return bytes(out)---def room_blobs(name, keep, st, tex_id, variant=0):- """A room: its header (kept in RAM) and its instances in sectors (decoded when the camera is near)."""- w, h = st["size"] if st["size"] else (40, 24)- cx0, cx1, cy0, cy1 = scene.camera_range(st) if st["size"] else (20, 20, 12, 12)- axis = 0 if (cx1 - cx0) >= (cy1 - cy0) else 1- lo, hi = (cx0, cx1) if axis == 0 else (cy0, cy1)- HWU, HHU = scene.VIEW_W / 2 / scene.FOCAL, scene.VIEW_H / 2 / scene.FOCAL- (solid, segs, cols, _), (erecs, groups), _ = room_data(name, variant)- for it in keep:- it.group = groups.get((it.scene, it.obj["id"]), groups.get((it.scene, None), 0) if it.which else 0)- tints = [(255, 255, 255, 255)]- secs = {}- for rank, it in enumerate(keep):- rec = inst_record(it, tex_id, tints)- q = np.array(it.quad)- dist = max(0.5, it.z - scene.CAMZ)- half = (HWU if axis == 0 else HHU) * dist- p0, p1 = (q[:, 0].min(), q[:, 0].max()) if axis == 0 else (q[:, 1].min(), q[:, 1].max())- va, vb = max(lo, p0 - half - MARGIN), min(hi, p1 + half + MARGIN)- if it.dynamic or vb - va > GLOBAL_SPAN or vb < va:- sec = -1- else:- sec = int((va - lo) // SECTOR)- e = secs.setdefault(sec, [[], 1e9, -1e9])- e[0].append((rank, rec, (it.layer, it.order)))- e[1] = min(e[1], va)- e[2] = max(e[2], vb)- order = sorted(secs.keys())- luts, sat = scene.grading_luts(st, 64)- lut = bytes(int(round(luts[c][i] * 255)) for c in range(3) for i in range(64))- bz = st["blur_z"] if st["blur_z"] is not None else 1000.0- blobs = []- table = bytearray()- for k in order:- recs, va, vb = secs[k]- blobs.append((sector_stream(recs), len(recs)))- if k < 0:- va, vb = -1e9, 1e9- table += struct.pack("<IIHHff", 0, 0, len(recs), 0, va, vb) # (offsets filled in by main)- HDR = 84 + 192- gw, gh, cells = coll.grid(segs, w, h)- hdr = struct.pack("<4H4f4f4fff6HII", 6, len(order), len(tints), axis, w, h, bz, sat, *st["ambient"], 0.0,- *st["hero_light"], lo, hi, len(keep), len(segs), len(cols), gw, gh, len(erecs), 0, 0) + lut- assert len(hdr) == HDR, len(hdr)- body = bytearray(hdr)- body += b"".join(struct.pack("<4B", *t) for t in tints)- while len(body) % 4:- body.append(0)- o_sec = len(body)- body += table- # the ground (read in place): colliders' flags (0: the tilemap's), the tilemap's solid tiles (1 bit each, rows from- # the bottom), segments (1/128 unit), their colliders, cells' first entries, entries- cb = bytearray(bytes(cols))- if len(cb) % 2:- cb.append(0)- th, tw = solid.shape- cb += struct.pack("<HH", tw, th)- rowb = (tw + 7) // 8- for y in range(th):- row = bytearray(rowb)- for x in range(tw):- if solid[y, x]:- row[x >> 3] |= 1 << (x & 7)- cb += row- if len(cb) % 2:- cb.append(0)- for x0, y0, x1, y1, ci in segs:- cb += struct.pack("<4h", *(i16(c * coll.UNIT) for c in (x0, y0, x1, y1)))- cb += bytes(ci for x0, y0, x1, y1, ci in segs)- if len(cb) % 2:- cb.append(0)- first = 0- for c in cells:- cb += struct.pack("<H", first)- first += len(c)- cb += struct.pack("<H", first)- for c in cells:- cb += struct.pack("<%dH" % len(c), *c)- return body, o_sec, blobs, bytes(cb), b"".join(erecs)---def tilecode(blocks):- """Trains the tile coder's starting probabilities on every block and encodes them (tools/tilecode.c)."""- import subprocess, tempfile- tmp = tempfile.mkdtemp()- exe = os.path.join(tmp, "tilecode")- subprocess.check_call(["cc", "-O2", "-o", exe, os.path.join(HERE, "tilecode.c")])- job = bytearray(struct.pack("<I", len(blocks)))- for bits, tiles in blocks:- job += struct.pack("<BBH", bits, 0, len(tiles)) + b"".join(tiles)- open(os.path.join(tmp, "in.bin"), "wb").write(job)- subprocess.check_call([exe, "train", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin")])- subprocess.check_call([exe, "encode", os.path.join(tmp, "in.bin"), os.path.join(tmp, "prior.bin"), os.path.join(tmp, "out.bin")])- prior = open(os.path.join(tmp, "prior.bin"), "rb").read()- out = open(os.path.join(tmp, "out.bin"), "rb").read()- res, p = [], 0- for _ in blocks:- n = struct.unpack_from("<I", out, p)[0]- res.append(out[p + 4:p + 4 + n])- p += 4 + n- return prior, res---def main():- t0 = time.time()- fp = os.path.join(HERE, "fit.json")- if os.path.exists(fp):- import json- art.FIT.update(json.load(open(fp)))- variants, per_room = art.build_variants(ROOMS, visible.compute)- print("variants", len(variants), "%.0fs" % (time.time() - t0), flush=True)- jobs = [art.Job(v) for v in variants]- actors.add_props(ALL_ROOMS)- sprites, clips = actors.build()- ents.CLIP_INDEX.update({c["id"]: i for i, c in enumerate(clips)})- # the rooms' objects, and the sprites they show (after the actors')- SPRITES.base = len(sprites)- named = actors.named_sprites(SPRITES)- prompt_ids = {p: TEXTS.id("Prompts", p.upper(), "PROMPT") for p in PROMPTS}- TEXTS.id("Elderbug", "ELDERBUG_INTRO_MAIN") # (until the NPCs: a conversation to try)- for r in ROOMS:- room_data(r)- if r in VARIANT_ROOMS:- room_data(r, 1)- sprites += actors.unity_sprites(SPRITES.list)- # the HUD's geo count: TrajanPro-Bold digits (TextMesh: size 45, character size 1, scale 0.1527)- digit_base = len(sprites)- digits, digit_adv = font.glyphs("TrajanPro-Bold", "0123456789", 45 * 0.1 * 0.1527 * actors.HUD_K, 1 / actors.HUD_K)- sprites += digits- print("actor frames", len(sprites), "clips", len(clips), "%.0fs" % (time.time() - t0), flush=True)- jobs += [sp["job"] for sp in sprites]- with mp.get_context("spawn").Pool(min(4, os.cpu_count() or 1)) as pool:- texs = pool.map(art.encode_job, jobs, chunksize=4)- # (the actors' textures come after the scenery's)- variants = variants + [sp["job"] for sp in sprites]- print("textures %.0fs" % (time.time() - t0), flush=True)- blocks = []- for t in texs:- t.first_block = len(blocks)- for i in range(0, t.ntiles, art.BLOCK_TILES):- blocks.append((t.bits, t.tiles[i:i + art.BLOCK_TILES]))- prior, coded = tilecode(blocks)- print("tiles coded %.0fs" % (time.time() - t0), flush=True)- secs = {k: Blob() for k in SECTIONS}- # the starting probabilities as the game uses them: each with its count (tilecode.h: tc_pack)- secs["PRIOR"].b += b"".join(struct.pack("<H", v << 4 | TC_N0) for v in struct.unpack("<%dH" % (len(prior) // 2), prior))- tex_id = {}- pal_at = {} # (palettes shared: once each)- nblk = 0- texrec = bytearray()- for i, (v, t) in enumerate(zip(variants, texs)):- tex_id[id(v)] = (i, t.w, t.h)- pal_off = 0xFFFFFFFF- if t.pal is not None:- # (15 colors: RGB565, then alpha; read a byte at a time)- pb = b"".join(struct.pack("<HB", (int(r) * 31 + 127) // 255 << 11 | (int(g) * 63 + 127) // 255 << 5 |- (int(b) * 31 + 127) // 255, int(a)) for r, g, b, a in t.pal)- if pb not in pal_at:- pal_at[pb] = secs["PAL"].add(pb, 1)- pal_off = pal_at[pb]- if t.fmt == art.FMT_SOFTA: # (alpha only: read in place)- pal_off = secs["SOFT"].add(t.soft)- texrec += struct.pack("<HHBBBBIII", t.w, t.h, 0, 0, t.fmt, 0, pal_off, t.base, 0)- continue- if t.fmt == art.FMT_SOFT:- c = lz(t.soft)- pal_off = secs["SOFT"].add(struct.pack("<I", len(c)) + c)- texrec += struct.pack("<HHBBBBIII", t.w, t.h, 0, 0, t.fmt, 0, pal_off, t.base, 0)- continue- # tile map: per row, the rank of its first tile, then 2 bits a tile (0 empty, 1 tile, 3 opaque tile)- m = bytearray()- rank = 0- for ty in range(t.th):- m += struct.pack("<H", rank)- row = bytearray((t.tw + 3) // 4)- for tx in range(t.tw):- code = 0 if t.empty[ty, tx] else (3 if t.opaque[ty, tx] else 1)- row[tx >> 2] |= code << ((tx & 3) * 2)- rank += code != 0- m += row- map_off = secs["TMAP"].add(bytes(m))- bidx = secs["BIDX"].b- first = len(bidx) // 4- for bl in coded[t.first_block:t.first_block + (t.ntiles + art.BLOCK_TILES - 1) // art.BLOCK_TILES]:- bidx += struct.pack("<I", len(secs["BLK"].b))- secs["BLK"].b += bl- bidx += struct.pack("<I", len(secs["BLK"].b))- texrec += struct.pack("<HHBBBBIII", t.w, t.h, t.tw, t.th, t.fmt, 1 if v.blur else 0, pal_off, map_off, first)- if os.environ.get("ACTSTATS"):- import collections- tot = collections.Counter()- for j, sp in enumerate(sprites):- t = texs[len(variants) - len(sprites) + j]- nb = sum(len(b) for b in coded[t.first_block:t.first_block + (t.ntiles + art.BLOCK_TILES - 1) // art.BLOCK_TILES]) if t.fmt not in (art.FMT_SOFTA, art.FMT_SOFT) else len(t.soft or b"")- nb += (len(t.pal.tobytes()) if t.pal is not None else 0)- tot[str(sp.get("key", ("?",)))[:30].split(",")[0]] += nb- for k, v in tot.most_common(40):- print("ACT", v, k)- secs["TEX"].b += struct.pack("<I", len(variants)) + texrec- # actors: each sprite frame's texture and where its top-left corner is (local units), units a texel; the clips- first_actor = len(variants) - len(sprites)- # (their colliders, as frames set them: 0 none given, 1 none, 2 + an entry: a box or a shape)- col_ids, col_entries = {}, []- for i, sp in enumerate(sprites):- c, cid = sp.get("col"), 0- if c and c[0] == "none":- cid = 1- elif c:- b = struct.pack("<BBH4f", 2, 0, 0, *c[1:]) if c[0] == "box" else \- struct.pack("<BBH", 3, len(c[1]), 0) + b"".join(struct.pack("<2f", x, y) for x, y in c[1])- if b not in col_ids:- col_ids[b] = len(col_entries)- col_entries.append(b)- cid = 2 + col_ids[b]- secs["SPR"].b += struct.pack("<HHffff", first_actor + i, cid, sp["lx"], sp["ty"], sp["tu"], sp["tv"])- at = 4 + 4 * len(col_entries)- secs["SCOL"].b += struct.pack("<I", len(col_entries))- for b in col_entries:- secs["SCOL"].b += struct.pack("<I", at)- at += len(b)- for b in col_entries:- secs["SCOL"].b += b- secs["CLIP"].b += struct.pack("<I", len(clips))- frames = []- for c in clips:- secs["CLIP"].b += struct.pack("<HHfBBH", len(frames), len(c["frames"]), c["fps"], c["wrap"], c["loop"], 0)- frames += [sid | (0x8000 if trig else 0) for sid, trig in c["frames"]]- secs["CLIP"].b += struct.pack("<%dH" % len(frames), *frames)- with open(os.path.join(unity.CACHE, "texnames.txt"), "w") as f:- for i, (v, t) in enumerate(zip(variants, texs)):- name = v.name if isinstance(v, art.ImageJob) else v.sprite.name- f.write("%d %s %.3f %d %d %dx%d %d\n" % (i, name.replace(" ", "_"), getattr(v, "scale", 1.0), v.blur, v.alpha_only,- t.w, t.h, t.ntiles))- rooms = bytearray(struct.pack("<I", len(ROOMS) + len(VARIANT_ROOMS)))- sector_offs, rvar = {}, bytearray(struct.pack("<I", len(VARIANT_ROOMS)))- pdf = _pdf_flags()- for r in ROOMS + [r + "@1" for r in VARIANT_ROOMS]:- base, variant = (r[:-2], 1) if r.endswith("@1") else (r, 0)- keep, st = per_room[base]- body, o_sec, blobs, ground, recs = room_blobs(base, keep, st, tex_id, variant)- struct.pack_into("<I", body, 76, secs["RBLOB"].add(ground))- struct.pack_into("<I", body, 80, secs["RBLOB"].add(recs))- packed = 0- for i, (c, n) in enumerate(blobs):- # (a room's variant: the same sectors)- off = sector_offs[(base, i)] if variant else secs["RBLOB"].add(c)- sector_offs[(base, i)] = off- struct.pack_into("<II", body, o_sec + 20 * i, off, len(c))- packed += len(c)- if variant:- # its variants: which entry, by which PlayerData bool, and each one's groups to hide in the other- (flag, val), spans = next(((a[1], a[2]) for a in scene.additive(base)), ("", False)), room_data(base)[2]- s1, s2 = spans.get(1, (0, 0)), spans.get(2, (0, 0))- rvar += struct.pack("<HHHBB4H", ROOMS.index(base), len(ROOMS) + VARIANT_ROOMS.index(base), pdf[flag], val, 0,- *s1, *s2)- hc = lz(bytes(body))- off = secs["RBLOB"].add(hc)- assert len(r) < 32, r- rooms += struct.pack("<32sIII", base.encode(), off, len(hc), len(body))- print("room %-26s %5d instances in %2d sectors, %6d packed, ground %d, recs %d" % (r, len(keep), len(blobs), packed + len(hc), len(ground), len(recs)), flush=True)- secs["ROOMS"].b += rooms- secs["RVAR"].b += rvar- secs["STR"].b += STRINGS.blob()- secs["TEXT"].b += TEXTS.blob()- secs["FONT"].b += TEXTS.fonts()- secs["PHASH"].b += PERSIST.blob()- # the file: "HKNW", count, then (offset, size) per section- head = struct.pack("<4sI", b"HKNW", len(SECTIONS))- pos = len(head) + 8 * len(SECTIONS)- table = bytearray()- body = bytearray()- for k in SECTIONS:- while (pos + len(body)) % 4:- body.append(0)- table += struct.pack("<II", pos + len(body), len(secs[k].b))- body += secs[k].b- data = head + table + body- open(os.path.join(SRC, "data.bin"), "wb").write(data)- sizes = {k: len(secs[k].b) for k in SECTIONS}- print("data.bin", len(data), sizes, "%.0fs" % (time.time() - t0))- with open(os.path.join(SRC, "data.h"), "w") as f:- f.write("/* made by tools/pack.py */\n#pragma once\n")- for i, k in enumerate(SECTIONS):- f.write("#define SEC_%s %d\n" % (k, i))- f.write("#define NUM_ROOMS %d\n" % len(ROOMS))- for i, r in enumerate(ROOMS):- f.write("#define ROOM_%s %d\n" % (r.upper(), i))- for i, c in enumerate(clips):- f.write("#define %s %d\n" % (c["id"], i))- for k, v in named.items():- f.write("#define SPRITE_%s %d\n" % (k, v))- f.write("#define SPRITE_DIGIT0 %d\n" % digit_base)- for i, k in enumerate(text.STYLES):- f.write("#define STYLE_%s %d\n" % (k, i))- f.write("#define TEXT_K %.6ff\n#define FONT_PHASES %d\n" % (text.TEXT_K, text.PHASES))- for i, k in enumerate(actors.ENEMY_KINDS):- f.write("#define EK_%s %d\n" % (k[0].upper(), i + 1))- f.write("#define NUM_KINDS %d\n" % (len(actors.ENEMY_KINDS) + 1))- f.write("#define KIND_TABLE %s\n" % actors.kind_table({c["id"]: i for i, c in enumerate(clips)}))- for k, v in prompt_ids.items():- f.write("#define TXT_PROMPT_%s %d\n" % (k.upper(), v))- f.write("#define PROMPT_SORT %du\n" % ((scene.layer_index(-349214895) << 16) | (1 + 32768)))- f.write("#define DIGIT_ADV {%s}\n" % ", ".join("%.4ff" % a for a in digit_adv))---if __name__ == "__main__":- main()diff --git a/games/hollowknight/tools/text.py b/games/hollowknight/tools/text.pyindex 6118a835..72cef9ae 100644--- a/games/hollowknight/tools/text.py+++ b/games/hollowknight/tools/text.py@@ -65,22 +65,37 @@ TEXT_K = 4 / 3 # text a third bigger than the game's (its sizes at this screenBR, PAGE = 10, 12PHASES = 4 # glyphs drawn a quarter pixel apart-# the styles: (font, em in pixels, line advance in pixels, ascender, descender in pixels)-# TextMeshPro: an em is font size / 10 units; a line is (the font's line height + line spacing) / point size ems+# the styles: (font, em in pixels, line advance in pixels, ascender, descender in pixels, spacing after each glyph in+# pixels, phases kept: 1 for big text)+# TextMeshPro: an em is font size / 10 units; a line is (the font's line height + line spacing) / point size ems;+# character spacing is in hundredths of an emHUD_PX = 100 / 8.7107 # (the HUD camera's: pixels a unit)WORLD_PX = 421.94 / 38.1 # (the room's camera, at z = 0)-def _style(font, size, px, line_height, line_spacing, point, asc, desc):- em = size * 0.1 * px * TEXT_K- return (font, em, (line_height + line_spacing) / point * em, asc / point * em, -desc / point * em)+def _style(font, size, px, line_height, line_spacing, point, asc, desc, k=TEXT_K, spacing=0.0, phases=PHASES):+ em = size * 0.1 * px * k+ return (font, em, (line_height + line_spacing) / point * em, asc / point * em, -desc / point * em, spacing / 100 * em,+ phases)+# (Trajan Pro's metrics: trajan_bold_tmpro's point size, line height, ascender, descender)+TRAJAN = (84, 0, 70, 52.5, -17.5)STYLES = {"DIALOGUE": _style("Perpetua", 7.2, HUD_PX, 134.0625, 24.6, 117, 95.9375, -38.1875),- "PROMPT": _style("TrajanPro-Bold", 6.67, WORLD_PX, 84, 0, 70, 52.5, -17.5),+ "PROMPT": _style("TrajanPro-Bold", 6.67, WORLD_PX, *TRAJAN),+ # the area titles (Area Title: TextMeshPro, size 36): the large one's main line, the small one's, and the lines+ # above and below them (the large title's at their own size; the small one's, a third bigger, the same)+ "TITLE_L": _style("TrajanPro-Bold", 36 * 0.4902, HUD_PX, *TRAJAN, k=1, spacing=4.69, phases=1),+ "TITLE_S": _style("TrajanPro-Bold", 36 * 0.3493, HUD_PX, *TRAJAN, k=1, spacing=4.69, phases=1),+ "TITLE_SUB": _style("TrajanPro-Bold", 36 * 0.1942, HUD_PX, *TRAJAN, k=1, spacing=21.06),}+# the titles the game shows (the Titles sheet's X_MAIN, X_SUB, X_SUPER): the areas', bosses' and characters'+TITLES = ["KINGSPASS", "DIRTMOUTH", "CROSSROADS", "EGGTEMPLE", "SHAMANTEMPLE", "GREENPATH", "BIGFLY", "FALSE_KNIGHT",+ "HORNET", "ELDERBUG", "SLY", "ISELDA", "CORNIFER", "QUIRREL", "SHAMAN", "STAG", "STAG2", "TISO_C", "TISO_NC",+ "CHARM_SLUG"]+def clean(s):"""A sheet's entry as shown: its markup to breaks and pages."""@@ -123,25 +138,29 @@ class Texts:return struct.pack("<I", len(self.list)) + b"".join(struct.pack("<I", o) for o in offs) + bytes(body)def fonts(self):- """FONT: per style (as STYLES' order) its offset; a style: em, line advance, ascender, descender (floats),- 256 x PHASES glyph offsets (u16, from the style, 0 none: a code's glyph with the pen 0, 1/4... of a pixel right- of a whole pixel), then the glyphs: width, height, left, top (from the pen's pixel on the baseline, pixels),- advance (1/64 pixels, u16), then rows of 4-bit alpha (low nibble first)."""+ """FONT: per style (as STYLES' order) its offset; a style: em, line advance, ascender, descender (floats), the+ first code it has and how many (u8 each, then 2 bytes), PHASES glyph offsets for each of those codes (u16, from the+ style, 0 none: the code's glyph with the pen 0, 1/4... of a pixel right of a whole pixel), then the glyphs: width,+ height, left, top (from the pen's pixel on the baseline, pixels), advance (1/64 pixels, u16), then rows of 4-bit+ alpha (low nibble first)."""import fontcp = self.code_page()blocks = []- for name, (fname, em, line, asc, desc) in STYLES.items():+ for name, (fname, em, line, asc, desc, spacing, phases) in STYLES.items():chars = sorted({c for s, st in self.list if st == name for c in s if c not in "\n\f"} | {" ", "-"})- head = bytearray(struct.pack("<ffff", em, line, asc, desc))- offs = [0] * (256 * PHASES)+ lo = min(cp[c] for c in chars)+ ncodes = max(cp[c] for c in chars) - lo + 1+ head = bytearray(struct.pack("<ffffBBH", em, line, asc, desc, lo, ncodes, 0))+ offs = [0] * (ncodes * PHASES)body = bytearray()base = len(head) + 2 * len(offs)- for ph in range(PHASES):+ for ph in range(phases):for ch, g in zip(chars, font.bitmaps(fname, chars, em, ph / PHASES)):a, left, top, adv = gh, w = a.shape- offs[cp[ch] * PHASES + ph] = base + len(body)- body += struct.pack("<BBbbH", w, h, left, top, min(65535, round(adv * 64)))+ for q in range(ph, PHASES, phases): # (big text: one phase for all)+ offs[(cp[ch] - lo) * PHASES + q] = base + len(body)+ body += struct.pack("<BBbbH", w, h, left, top, min(65535, round((adv + spacing) * 64)))q = (a.astype(np.uint16) * 15 + 127) // 255for row in q:r = list(row) + [0] * (w & 1)