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
Languages: NumPlay in French and Chinese, built from the same sources
Mason Chen17762a83a4bc
diff --git a/LICENSES/OFL-1.1-Fusion-Pixel.txt b/LICENSES/OFL-1.1-Fusion-Pixel.txtnew file mode 100644index 00000000..17ca3aed--- /dev/null+++ b/LICENSES/OFL-1.1-Fusion-Pixel.txt@@ -0,0 +1,124 @@+Fusion Pixel Font+https://github.com/TakWolf/fusion-pixel-font++Copyright (c) 2022, TakWolf (https://takwolf.com).++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.++----------------------------------------------------------------+Fusion Pixel Font includes glyphs from these fonts:++================ ark-pixel+Ark Pixel Font+https://github.com/TakWolf/ark-pixel-font++Copyright (c) 2021, TakWolf (https://takwolf.com).++This Font Software is licensed under the SIL Open Font License, Version 1.1.++================ cubic-11+[Cubic 11]+These fonts are free software.+Unlimited permission is granted to use, copy, and distribute them, with or without modification, either commercially or noncommercially.+THESE FONTS ARE PROVIDED "AS IS" WITHOUT WARRANTY.+此字型是免費的。+無論您是否進行對本字型進行商業或非商業性修改,均可無限制地使用,複製和分發它們。++================ galmuri+Copyright (c) 2019–2025 Lee Minseo ([email protected])++This font software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org++diff --git a/assets/fonts/fusion-pixel-12px.bin b/assets/fonts/fusion-pixel-12px.binnew file mode 100644index 00000000..036ed4b5Binary files /dev/null and b/assets/fonts/fusion-pixel-12px.bin differdiff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txtnew file mode 100644index 00000000..a88ce51f--- /dev/null+++ b/launcher/lang/fr.txt@@ -0,0 +1,101 @@+# NumPlay's launcher in French: the English text as in the source, a tab, the translation+# (see tools/lang.py). The games' names and taglines come from games/games.json.+# Based on the French of Gabriel (Mason363/NumPlay#31).+Settings Réglages+Reset, uninstall, more Effacer, supprimer, plus+Toolbox Boîte à outils+Examples Exemples+MATRICES MATRICES+Matrix Matrice+Results Résultats+Dimension Dimension+Determinant Déterminant+Trace Trace+Inverse Inverse+Not invertible Non inversible+Transpose Transposée+Identity matrix Matrice identité+Clear Effacer+Matrices Matrices+ KB Ko+x,n,t key touche x,n,t+var key touche var+Toolbox key touche Boîte à outils+Pi key touche Pi+Square root key touche racine carrée+Menu: Examples Menu : Exemples+INSTALLED GAMES JEUX INSTALLÉS+Made with Fait avec+ by Mason Chen par Mason Chen+Reset Effacer+Uninstall Supprimer+Reset all games Tout effacer+Deletes the progress of every game Efface la progression de tous les jeux+Start as Matrices Démarrer en Matrices+A math app first; NumPlay opens in secret D'abord une app de maths, NumPlay en secret+Show a hint Afficher un indice+Matrices names the secret, small and gray Matrices indique le secret, en petit et gris+Secret way in Accès secret+Opens NumPlay from Matrices Ouvre NumPlay depuis Matrices+Your calculator's software doesn't allow apps to uninstall parts of themselves. Update it to Epsilon 21 or newer at my.numworks.com, then try again. Le logiciel de ta calculatrice ne permet pas aux apps de supprimer une partie d'elles-mêmes. Mets-le à jour vers Epsilon 21 ou plus récent sur my.numworks.com, puis réessaie.+The battery is too low to safely erase flash memory. Plug in your calculator, then try again. La batterie est trop faible pour effacer la mémoire flash sans risque. Branche ta calculatrice, puis réessaie.+Something went wrong while erasing. To be safe, reinstall NumPlay from my.numworks.com/apps. Un problème est survenu pendant l'effacement. Par sécurité, réinstalle NumPlay depuis my.numworks.com/apps.+Hold OK Maintiens OK+every game tous les jeux+Every game Tous les jeux+ was reset : progression effacée+Its progress starts over. Tout repart de zéro.+OK OK+Reset Effacer+? ?+This deletes the saved progress of Cela efface la progression de+: best scores, unlocked levels and settings. You can't undo this. : meilleurs scores, niveaux débloqués et réglages. C'est définitif.+Games stay installed, and levels you made in an editor are kept. Les jeux restent installés, et les niveaux créés dans un éditeur sont gardés.+Cancel Annuler+ was uninstalled : supprimé+ of flash memory freed de mémoire flash libérés+Couldn't uninstall Suppression impossible+Uninstalling Suppression de+... ...+Don't turn off your calculator. N'éteins pas ta calculatrice.+Uninstall Supprimer+This deletes Cela supprime+ and all of its saved progress. You can't undo this. et toute sa progression. C'est définitif.+To play it again, reinstall NumPlay from my.numworks.com/apps. Your other games keep their progress. Pour y rejouer, réinstalle NumPlay depuis my.numworks.com/apps. Tes autres jeux gardent leur progression.+Crossy Road Crossy Road+Jump to the beat Saute en rythme+Hop, dodge, survive Saute, esquive, survis+Mine, craft, survive Mine, fabrique, survis+Drive, flip, finish Conduis, fais des saltos, arrive+Balatro Balatro+Poker hands, wild jokers Mains de poker, jokers fous+Buckshot Roulette Buckshot Roulette+You, the Dealer, one shotgun Toi, le croupier, un fusil+Portal Returns Portal Returns+Think with portals Pense avec les portails+Tetris Tetris+Stack and clear lines Empile et efface les lignes+Chess Échecs+Bots, puzzles, 2 players Bots, problèmes, 2 joueurs+Flappy Bird Flappy Bird+Flap through the pipes Vole entre les tuyaux+Pac-Man Pac-Man+Eat dots, dodge ghosts Mange les points, fuis les fantômes+Snake Snake+Eat apples, grow long Mange des pommes, grandis+Connect Four Puissance 4+Four in a row wins Quatre alignés pour gagner+Solitaire Solitaire+The classic card game Le jeu de cartes classique+Slide, merge, reach 2048 Glisse, fusionne, atteins 2048+Minesweeper Démineur+Clear the field, flag the mines Déblaie le terrain, pose les drapeaux+Block Breaker Casse-briques+Break every brick Casse toutes les briques+Backgrounds, clocks, timers Fonds, horloges, minuteurs+# (names that stay as they are)+NumDash NumDash+NumBlocks NumBlocks+NumDrive NumDrive+2048 2048+NumVisuals NumVisualsdiff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txtnew file mode 100644index 00000000..dc44b915--- /dev/null+++ b/launcher/lang/zh.txt@@ -0,0 +1,100 @@+# NumPlay's launcher in Chinese: the English text as in the source, a tab, the translation+# (see tools/lang.py). The games' names and taglines come from games/games.json.+Settings 设置+Reset, uninstall, more 重置、卸载及更多+Toolbox 工具箱+Examples 示例+MATRICES 矩阵+Matrix 矩阵+Results 结果+Dimension 维数+Determinant 行列式+Trace 迹+Inverse 逆矩阵+Not invertible 不可逆+Transpose 转置+Identity matrix 单位矩阵+Clear 清除+Matrices 矩阵+ KB KB+x,n,t key x,n,t 键+var key var 键+Toolbox key 工具箱键+Pi key π 键+Square root key 根号键+Menu: Examples 菜单:示例+INSTALLED GAMES 已安装的游戏+Made with 用+ by Mason Chen 打造 · Mason Chen+Reset 重置+Uninstall 卸载+Reset all games 重置所有游戏+Deletes the progress of every game 删除所有游戏的进度+Start as Matrices 以“矩阵”启动+A math app first; NumPlay opens in secret 先显示数学应用,再秘密打开 NumPlay+Show a hint 显示提示+Matrices names the secret, small and gray “矩阵”以灰色小字提示暗号+Secret way in 秘密入口+Opens NumPlay from Matrices 从“矩阵”打开 NumPlay+Your calculator's software doesn't allow apps to uninstall parts of themselves. Update it to Epsilon 21 or newer at my.numworks.com, then try again. 你的计算器系统不允许应用卸载自身的一部分。请在 my.numworks.com 将系统更新到 Epsilon 21 或更高版本,然后重试。+The battery is too low to safely erase flash memory. Plug in your calculator, then try again. 电量过低,无法安全擦除闪存。请给计算器充电,然后重试。+Something went wrong while erasing. To be safe, reinstall NumPlay from my.numworks.com/apps. 擦除时出错。为安全起见,请在 my.numworks.com/apps 重新安装 NumPlay。+Hold OK 按住 OK+every game 所有游戏+Every game 所有游戏+ was reset 已重置+Its progress starts over. 进度将从头开始。+OK 确定+Reset 重置+? ?+This deletes the saved progress of 这将删除+: best scores, unlocked levels and settings. You can't undo this. 的存档:最高分、已解锁的关卡和设置。此操作无法撤销。+Games stay installed, and levels you made in an editor are kept. 游戏仍会保留,你在编辑器中制作的关卡也会保留。+Cancel 取消+ was uninstalled 已卸载+ of flash memory freed 闪存已释放+Couldn't uninstall 无法卸载+Uninstalling 正在卸载+... ……+Don't turn off your calculator. 请勿关闭计算器。+Uninstall 卸载+This deletes 这将删除+ and all of its saved progress. You can't undo this. 及其所有存档。此操作无法撤销。+To play it again, reinstall NumPlay from my.numworks.com/apps. Your other games keep their progress. 如需再次游玩,请在 my.numworks.com/apps 重新安装 NumPlay。其他游戏的进度会保留。+Crossy Road 天天过马路+Jump to the beat 踩着节拍跳跃+Hop, dodge, survive 跳跃、闪避、活下去+Mine, craft, survive 挖矿、合成、生存+Drive, flip, finish 驾驶、翻转、冲线+Balatro 小丑牌+Poker hands, wild jokers 扑克牌型,狂野小丑+Buckshot Roulette 恶魔轮盘+You, the Dealer, one shotgun 你、庄家、一把霰弹枪+Portal Returns 传送门归来+Think with portals 用传送门思考+Tetris 俄罗斯方块+Stack and clear lines 堆叠并消除行+Chess 国际象棋+Bots, puzzles, 2 players 电脑对手、谜题、双人对战+Flappy Bird 笨鸟先飞+Flap through the pipes 拍着翅膀穿过水管+Pac-Man 吃豆人+Eat dots, dodge ghosts 吃豆子,躲幽灵+Snake 贪吃蛇+Eat apples, grow long 吃苹果,越长越长+Connect Four 四子棋+Four in a row wins 四子连线即获胜+Solitaire 纸牌接龙+The classic card game 经典纸牌游戏+Slide, merge, reach 2048 滑动、合并、达到 2048+Minesweeper 扫雷+Clear the field, flag the mines 清理雷区,标出地雷+Block Breaker 打砖块+Break every brick 打碎每一块砖+Backgrounds, clocks, timers 背景、时钟、计时器+# (names that stay as they are)+NumDash NumDash+NumBlocks NumBlocks+NumDrive NumDrive+2048 2048+NumVisuals NumVisualsdiff --git a/launcher/src/font.h b/launcher/src/font.hindex 1436d19c..3b7295e1 100644--- a/launcher/src/font.h+++ b/launcher/src/font.h@@ -16,4 +16,8 @@ typedef struct {} np_font_t;extern const np_font_t np_font_title, np_font_body, np_font_small;+/* Letters beyond ASCII in a language build (tools/lang.py runs tools/fontgen.py --extra): their code+ * points, in the order of their glyphs after the 95 ASCII ones; none in English. */+extern const uint16_t np_font_extra[];+extern const int np_font_extra_count;#endifdiff --git a/launcher/src/font_data.c b/launcher/src/font_data.cindex 85fcfc47..e9b28478 100644--- a/launcher/src/font_data.c+++ b/launcher/src/font_data.c@@ -1,6 +1,9 @@/* Generated by tools/fontgen.py from Nunito (SIL Open Font License 1.1). */#include "font.h"+const uint16_t np_font_extra[1] = {0};+const int np_font_extra_count = 0;+static const uint8_t np_font_title_data[7603] = {128,222,36,255,207,242,255,29,255,191,224,255,9,252,127,160,255,6,248,79,112,255,2,226,11,0,0,0,233,61,243,255,58,255,175,144,223,3,231,61,64,238,245,255,10,252,223,255,diff --git a/launcher/src/gfx.c b/launcher/src/gfx.cindex 9f82b4af..aabbfe2b 100644--- a/launcher/src/gfx.c+++ b/launcher/src/gfx.c@@ -1,5 +1,6 @@#include "gfx.h"#include <string.h>+#include "../../games/common/np_text.h"color_t *gfx_buf;int gfx_y0, gfx_y1;@@ -277,20 +278,58 @@ static const np_glyph_t *glyph(const np_font_t *f, char ch) {return i < f->count ? &f->glyphs[i] : &f->glyphs['?' - f->first];}+/* Language builds (games/common/np_text.h): the letter at *s, *s moved past it; its glyph, or NULL+ * for one of the 12-pixel font (Chinese) */+static const np_glyph_t *glyph_at(const np_font_t *f, const char **s, uint32_t *cp) {+ if (!NP_TEXT_EXTRA || (uint8_t)**s < 0x80) {+ *cp = (uint8_t)**s;+ return glyph(f, *(*s)++);+ }+ *cp = np_utf8(s);+ for (int k = 0; k < np_font_extra_count; k++)+ if (np_font_extra[k] == *cp) return &f->glyphs[95 + k];+ return np_xglyph(*cp) ? NULL : &f->glyphs['?' - f->first];+}+/* the 12-pixel font's pixels: twice as big for the title font */+static int xscale(const np_font_t *f) { return f->ascent >= 16 ? 2 : 1; }+typedef struct {+ color_t c;+ int a;+} xplot_t;+static void xplot(int x, int y, void *ctx) {+ const xplot_t *p = ctx;+ if (x < 0 || x >= SCREEN_W || y < gfx_y0 || y >= gfx_y1) return;+ color_t *q = px_at(x, y);+ *q = gfx_mix(*q, p->c, NP_MIN((p->a * 32 + 60) / 120, 32));+}+int gfx_text(const np_font_t *f, int x, int baseline, const char *s, color_t c, int a) {int top = baseline - f->ascent, bottom = baseline + f->descent;bool visible = bottom > gfx_y0 && top < gfx_y1;- for (; *s; s++) {- const np_glyph_t *g = glyph(f, *s);+ while (*s) {+ uint32_t cp;+ const np_glyph_t *g = glyph_at(f, &s, &cp);+ if (!g) { /* (NP_TEXT_EXTRA only) */+ xplot_t p = {c, a};+ int sc = xscale(f);+ x += visible ? np_xdraw(cp, x, baseline - 10 * sc, sc, xplot, &p) : np_xadvance(cp, sc);+ continue;+ }if (visible && g->w) gfx_mask(f->data + g->offset, g->w, g->h, x + g->x, baseline + g->y, c, a);x += g->advance;}return x;}+static int advance_at(const np_font_t *f, const char **s) {+ uint32_t cp;+ const np_glyph_t *g = glyph_at(f, s, &cp);+ return g ? g->advance : np_xadvance(cp, xscale(f));+}+int gfx_text_width(const np_font_t *f, const char *s) {int w = 0;- for (; *s; s++) w += glyph(f, *s)->advance;+ while (*s) w += advance_at(f, &s);return w;}@@ -305,16 +344,20 @@ void gfx_text_right(const np_font_t *f, int rx, int baseline, const char *s, colint gfx_paragraph(const np_font_t *f, int cx, int baseline, int width, int line, const char *s, color_t c, int a) {char buf[96];while (*s) {- /* take as many words as fit */+ /* take as many words as fit (in Chinese, as many letters: a line may end after any of them) */int n = 0, last_space = -1, wpx = 0;- while (s[n] && s[n] != '\n' && n < (int)sizeof(buf) - 1) {- wpx += glyph(f, s[n])->advance;- if (s[n] == ' ') last_space = n;+ while (s[n] && s[n] != '\n' && n < (int)sizeof(buf) - 4) {+ const char *p = s + n;+ uint32_t first = (uint8_t)*p;+ wpx += advance_at(f, &p);+ int len = (int)(p - (s + n));+ if (first == ' ') last_space = n;if (wpx > width && last_space > 0) {n = last_space;break;}- n++;+ if (NP_TEXT_EXTRA && first >= 0xE0 && wpx <= width) last_space = n + len; /* (after a Chinese letter) */+ n += len;}memcpy(buf, s, (size_t)n);buf[n] = 0;diff --git a/launcher/src/home.c b/launcher/src/home.cindex 8bd9ddc0..93a868f4 100644--- a/launcher/src/home.c+++ b/launcher/src/home.c@@ -2,6 +2,7 @@* its neighbours peek in from the sides, and the card cycles through the* game's screenshots. The last card opens the settings. */#include "ui.h"+#include "../../games/common/np_text.h"#define CARD_W 200#define CARD_H 152@@ -37,8 +38,8 @@ static uint32_t item_color(int game, int which) {return which == 0 ? g->top : which == 1 ? g->bottom : g->accent;}-static const char *item_title(int game) { return game < 0 ? "Settings" : np_games[game].title; }-static const char *item_tagline(int game) { return game < 0 ? "Reset, uninstall, more" : np_games[game].tagline; }+static const char *item_title(int game) { return game < 0 ? T("Settings") : np_games[game].title; }+static const char *item_tagline(int game) { return game < 0 ? T("Reset, uninstall, more") : np_games[game].tagline; }static float absf(float v) { return v < 0 ? -v : v; }diff --git a/launcher/src/settings.c b/launcher/src/settings.cindex 6306e04d..ef536e6d 100644--- a/launcher/src/settings.c+++ b/launcher/src/settings.c@@ -4,6 +4,7 @@#include <string.h>#include "sys.h"#include "ui.h"+#include "../../games/common/np_text.h"#define BG_TOP 0x3B4252#define BG_BOTTOM 0x171A21@@ -24,7 +25,7 @@ static char *fmt_kb(char *out, uint32_t bytes) {while (kb /= 10);char *o = out;while (n) *o++ = t[--n];- strcpy(o, " KB");+ strcpy(o, T(" KB"));return out;}@@ -38,8 +39,8 @@ typedef struct {float cursor; /* animated selection */} list_t;-static const char *const secret_names[NP_SECRET_COUNT] = {"x,n,t key", "var key", "Toolbox key", "Pi key",- "Square root key", "Menu: Examples"};+static const char *const secret_names[NP_SECRET_COUNT] = {T("x,n,t key"), T("var key"), T("Toolbox key"), T("Pi key"),+ T("Square root key"), T("Menu: Examples")};static void build_rows(list_t *l) {l->n = l->ngames = 0;@@ -88,12 +89,12 @@ static void list_scene(void *ctx) {gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, BG_TOP, BG_BOTTOM);if (gfx_y0 < 44) {gfx_icon(&np_icon_back, 14, 17, 0xFFFF, 200);- gfx_text(&np_font_title, 36, 30, "Settings", 0xFFFF, 256);+ gfx_text(&np_font_title, 36, 30, T("Settings"), 0xFFFF, 256);uint32_t total = 0;for (int i = 0; i < l->ngames; i++) total += np_game_size(l->game[i]);char kb[16];if (l->ngames) {- gfx_text_right(&np_font_small, SCREEN_W - 14, 20, "INSTALLED GAMES", 0xFFFF, 150);+ gfx_text_right(&np_font_small, SCREEN_W - 14, 20, T("INSTALLED GAMES"), 0xFFFF, 150);gfx_text_right(&np_font_body, SCREEN_W - 14, 34, fmt_kb(kb, total), 0xFFFF, 230);}}@@ -106,11 +107,11 @@ static void list_scene(void *ctx) {if (i >= l->n) {/* credits, under the last row */if (i != l->n) continue;- int w = gfx_text_width(&np_font_body, "Made with ") + 12 + gfx_text_width(&np_font_body, " by Mason Chen");+ int w = gfx_text_width(&np_font_body, T("Made with ")) + 12 + gfx_text_width(&np_font_body, T(" by Mason Chen"));int x = 160 - w / 2;- x = gfx_text(&np_font_body, x, y + 20, "Made with ", 0xFFFF, 230);+ x = gfx_text(&np_font_body, x, y + 20, T("Made with "), 0xFFFF, 230);gfx_icon(&np_icon_heart, x + 1, y + 12, gfx_rgb(DANGER), 256);- gfx_text(&np_font_body, x + 12, y + 20, " by Mason Chen", 0xFFFF, 230);+ gfx_text(&np_font_body, x + 12, y + 20, T(" by Mason Chen"), 0xFFFF, 230);gfx_text_center(&np_font_small, 160, y + 36, "github.com/Mason363/NumPlay", 0xFFFF, 170);gfx_text_center(&np_font_small, 160, y + 50, "NumPlay " NP_VERSION, 0xFFFF, 120);continue;@@ -124,30 +125,30 @@ static void list_scene(void *ctx) {gfx_text(&np_font_body, 60, y + 15, np_games[game].title, 0xFFFF, 256);gfx_text(&np_font_small, 60, y + 28, fmt_kb(kb, np_game_size(game)), 0xFFFF, 150);if (on) {- pill(SCREEN_W - 170, y + 7, 58, "Reset", l->action == 0, ACCENT);+ pill(SCREEN_W - 170, y + 7, 58, T("Reset"), l->action == 0, ACCENT);pill(SCREEN_W - 104, y + 7, 86, "", l->action == 1, DANGER);gfx_icon(&np_icon_trash, SCREEN_W - 96, y + 9, 0xFFFF, l->action == 1 ? 256 : 190);- gfx_text(&np_font_small, SCREEN_W - 78, y + 21, "Uninstall", 0xFFFF, l->action == 1 ? 256 : 190);+ gfx_text(&np_font_small, SCREEN_W - 78, y + 21, T("Uninstall"), 0xFFFF, l->action == 1 ? 256 : 190);}break;}case ROW_RESET_ALL:- row_text(y, "Reset all games", "Deletes the progress of every game", 256);- if (on) pill(SCREEN_W - 76, y + 7, 58, "Reset", true, ACCENT);+ row_text(y, T("Reset all games"), T("Deletes the progress of every game"), 256);+ if (on) pill(SCREEN_W - 76, y + 7, 58, T("Reset"), true, ACCENT);break;case ROW_DISGUISE:- row_text(y, "Start as Matrices", "A math app first; NumPlay opens in secret", 256);+ row_text(y, T("Start as Matrices"), T("A math app first; NumPlay opens in secret"), 256);toggle(y, l->cfg.disguise, 256);break;case ROW_HINT: {int a = l->cfg.disguise ? 256 : 130;- row_text(y, "Show a hint", "Matrices names the secret, small and gray", a);+ row_text(y, T("Show a hint"), T("Matrices names the secret, small and gray"), a);toggle(y, l->cfg.hint, a);break;}case ROW_SECRET: {int a = l->cfg.disguise ? 256 : 130;- row_text(y, "Secret way in", "Opens NumPlay from Matrices", a);+ row_text(y, T("Secret way in"), T("Opens NumPlay from Matrices"), a);const char *v = secret_names[l->cfg.secret];int w = gfx_text_width(&np_font_small, v);gfx_text_right(&np_font_small, SCREEN_W - 32, y + 21, v, 0xFFFF, a);@@ -178,12 +179,11 @@ typedef struct {static const char *error_text(int e) {switch (e) {case NP_UNINSTALL_UNSUPPORTED:- return "Your calculator's software doesn't allow apps to uninstall parts of themselves. Update it to Epsilon 21 or "- "newer at my.numworks.com, then try again.";+ return T("Your calculator's software doesn't allow apps to uninstall parts of themselves. Update it to Epsilon 21 or newer at my.numworks.com, then try again.");case NP_UNINSTALL_BATTERY:- return "The battery is too low to safely erase flash memory. Plug in your calculator, then try again.";+ return T("The battery is too low to safely erase flash memory. Plug in your calculator, then try again.");default:- return "Something went wrong while erasing. To be safe, reinstall NumPlay from my.numworks.com/apps.";+ return T("Something went wrong while erasing. To be safe, reinstall NumPlay from my.numworks.com/apps.");}}@@ -196,7 +196,7 @@ static void hold_button(const dialog_t *d, const char *label) {gfx_rrect(bx, by, bw, bh, bh / 2, gfx_rgb(DANGER), 256);int fill = (int)(bw * d->hold);if (fill > 0) gfx_rrect(bx, by, NP_MAX(fill, bh), bh, bh / 2, 0xFFFF, 110);- gfx_text_center(&np_font_body, bx + bw / 2, by + 18, d->hinted ? "Hold OK" : label, 0xFFFF, 256);+ gfx_text_center(&np_font_body, bx + bw / 2, by + 18, d->hinted ? T("Hold OK") : label, 0xFFFF, 256);} else {gfx_rrect(bx, by, bw, bh, bh / 2, 0xFFFF, 40);gfx_text_center(&np_font_body, bx + bw / 2, by + 18, label, 0xFFFF, 200);@@ -205,33 +205,33 @@ static void hold_button(const dialog_t *d, const char *label) {/* Reset and Reset all: a question (Cancel first, hold OK to reset), then done */static void reset_scene(dialog_t *d) {- const char *title = d->action == ACT_RESET_ALL ? "every game" : np_games[d->game].title;- char line[64], body[128];+ const char *title = d->action == ACT_RESET_ALL ? T("every game") : np_games[d->game].title;+ char line[128], body[384];if (d->stage == 2) {gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, 0x1F5A3C, 0x0B1A12);gfx_circle(160, 74, 34, gfx_rgb(OK_GREEN), 256);gfx_icon(&np_icon_check, 145, 59, 0xFFFF, 256);- strcpy(line, d->action == ACT_RESET_ALL ? "Every game" : title);- strcat(line, d->action == ACT_RESET_ALL ? " was reset" : " was reset");+ strcpy(line, d->action == ACT_RESET_ALL ? T("Every game") : title);+ strcat(line, T(" was reset"));gfx_text_center(&np_font_title, 160, 142, line, 0xFFFF, 256);- gfx_text_center(&np_font_body, 160, 166, "Its progress starts over.", 0xFFFF, 200);- ui_button(110, 192, 100, 28, "OK", true, OK_GREEN, 256);+ gfx_text_center(&np_font_body, 160, 166, T("Its progress starts over."), 0xFFFF, 200);+ ui_button(110, 192, 100, 28, T("OK"), true, OK_GREEN, 256);return;}gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, DANGER_TOP, DANGER_BOTTOM);gfx_icon(&np_icon_warning, 137, 14, 0xFFFF, 256);- strcpy(line, "Reset ");+ strcpy(line, T("Reset "));strcat(line, title);- strcat(line, "?");+ strcat(line, T("?"));gfx_text_center(&np_font_title, 160, 80, line, 0xFFFF, 256);- strcpy(body, "This deletes the saved progress of ");+ strcpy(body, T("This deletes the saved progress of "));strcat(body, title);- strcat(body, ": best scores, unlocked levels and settings. You can't undo this.");+ strcat(body, T(": best scores, unlocked levels and settings. You can't undo this."));int y = gfx_paragraph(&np_font_body, 160, 102, 280, 16, body, 0xFFFF, 240);- gfx_paragraph(&np_font_small, 160, y + 4, 290, 13, "Games stay installed, and levels you made in an editor are kept.",+ gfx_paragraph(&np_font_small, 160, y + 4, 290, 13, T("Games stay installed, and levels you made in an editor are kept."),0xFFFF, 170);- ui_button(38, 198, 110, 28, "Cancel", d->choice == 0, 0x555D70, 256);- hold_button(d, "Reset");+ ui_button(38, 198, 110, 28, T("Cancel"), d->choice == 0, 0x555D70, 256);+ hold_button(d, T("Reset"));}static void dialog_scene(void *ctx) {@@ -241,55 +241,54 @@ static void dialog_scene(void *ctx) {return;}const np_game_t *g = &np_games[d->game];- char line[64];+ char line[128];if (d->stage == 2) {gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, 0x1F5A3C, 0x0B1A12);gfx_circle(160, 74, 34, gfx_rgb(OK_GREEN), 256);gfx_icon(&np_icon_check, 145, 59, 0xFFFF, 256);strcpy(line, g->title);- strcat(line, " was uninstalled");+ strcat(line, T(" was uninstalled"));gfx_text_center(&np_font_title, 160, 142, line, 0xFFFF, 256);char kb[16];strcpy(line, fmt_kb(kb, d->freed));- strcat(line, " of flash memory freed");+ strcat(line, T(" of flash memory freed"));gfx_text_center(&np_font_body, 160, 166, line, 0xFFFF, 200);- ui_button(110, 192, 100, 28, "OK", true, OK_GREEN, 256);+ ui_button(110, 192, 100, 28, T("OK"), true, OK_GREEN, 256);return;}gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, DANGER_TOP, DANGER_BOTTOM);gfx_icon(&np_icon_warning, 137, 14, 0xFFFF, 256);if (d->stage == 3) {- gfx_text_center(&np_font_title, 160, 84, "Couldn't uninstall", 0xFFFF, 256);+ gfx_text_center(&np_font_title, 160, 84, T("Couldn't uninstall"), 0xFFFF, 256);gfx_paragraph(&np_font_body, 160, 112, 280, 17, error_text(d->error), 0xFFFF, 220);- ui_button(110, 196, 100, 28, "OK", true, DANGER, 256);+ ui_button(110, 196, 100, 28, T("OK"), true, DANGER, 256);return;}if (d->stage == 1) {- strcpy(line, "Uninstalling ");+ strcpy(line, T("Uninstalling "));strcat(line, g->title);- strcat(line, "...");+ strcat(line, T("..."));gfx_text_center(&np_font_title, 160, 96, line, 0xFFFF, 256);gfx_rrect(40, 118, 240, 10, 5, 0xFFFF, 60);int w = (int)(240 * d->progress);if (w >= 10) gfx_rrect(40, 118, w, 10, 5, 0xFFFF, 256);- gfx_text_center(&np_font_body, 160, 152, "Don't turn off your calculator.", 0xFFFF, 200);+ gfx_text_center(&np_font_body, 160, 152, T("Don't turn off your calculator."), 0xFFFF, 200);return;}- strcpy(line, "Uninstall ");+ strcpy(line, T("Uninstall "));strcat(line, g->title);- strcat(line, "?");+ strcat(line, T("?"));gfx_text_center(&np_font_title, 160, 80, line, 0xFFFF, 256);- char body[96];- strcpy(body, "This deletes ");+ char body[384];+ strcpy(body, T("This deletes "));strcat(body, g->title);- strcat(body, " and all of its saved progress. You can't undo this.");+ strcat(body, T(" and all of its saved progress. You can't undo this."));int y = gfx_paragraph(&np_font_body, 160, 102, 280, 16, body, 0xFFFF, 240);gfx_paragraph(&np_font_small, 160, y + 4, 290, 13,- "To play it again, reinstall NumPlay from my.numworks.com/apps. Your other games keep their "- "progress.",+ T("To play it again, reinstall NumPlay from my.numworks.com/apps. Your other games keep their progress."),0xFFFF, 170);- ui_button(38, 198, 110, 28, "Cancel", d->choice == 0, 0x555D70, 256);- hold_button(d, "Uninstall");+ ui_button(38, 198, 110, 28, T("Cancel"), d->choice == 0, 0x555D70, 256);+ hold_button(d, T("Uninstall"));}static dialog_t *active_dialog;diff --git a/tools/fontgen.py b/tools/fontgen.pyindex 7ac39c0c..cdd071a2 100644--- a/tools/fontgen.py+++ b/tools/fontgen.py@@ -6,7 +6,10 @@ supersampled with the baseline on a pixel boundary and stored as 4-bitcoverage. Run it again only to change sizes or weights; the output iscommitted.-Usage: fontgen.py out.c+With --extra, letters beyond ASCII follow (a language build's accents, from tools/lang.py): their+code points go in np_font_extra, in the order of their glyphs after the ASCII ones.++Usage: fontgen.py out.c [--extra 233,232,...]"""import hashlibimport sys@@ -81,24 +84,29 @@ def glyph(f, ch, spacing):return (q, ox, oy), round(adv)-def main(out):+def main(out, extra=()):lines = ["/* Generated by tools/fontgen.py from Nunito (SIL Open Font License 1.1). */",'#include "font.h"', ""]+ extra = sorted(set(extra))+ lines.append(f"const uint16_t np_font_extra[{max(1, len(extra))}] = {{" + (", ".join(str(c) for c in extra) or "0") + "};")+ lines.append(f"const int np_font_extra_count = {len(extra)};")+ lines.append("")total = 0for name, cap, weight, spacing in SPECS:f = load(cap, weight)data = bytearray()glyphs = []asc = desc = 0- for c in range(FIRST, LAST + 1):+ for c in list(range(FIRST, LAST + 1)) + extra:g, adv = glyph(f, chr(c), spacing * UP / 4)if g is None:glyphs.append((0, 0, 0, 0, adv, len(data)))continueq, ox, oy = gh, w = q.shape- asc = max(asc, -oy)- desc = max(desc, h + oy)+ if c <= LAST: # (the line's metrics from ASCII: accents don't move the layout)+ asc = max(asc, -oy)+ desc = max(desc, h + oy)flat = q.flatten().tolist()if len(flat) % 2:flat.append(0)@@ -115,7 +123,7 @@ def main(out):for w, h, ox, oy, adv, off in glyphs:lines.append(f" {{{w}, {h}, {ox}, {oy}, {adv}, {off}}},")lines.append("};")- lines.append(f"const np_font_t {name} = {{{FIRST}, {LAST - FIRST + 1}, {asc}, {desc}, {name}_glyphs, {name}_data}};")+ lines.append(f"const np_font_t {name} = {{{FIRST}, {LAST - FIRST + 1 + len(extra)}, {asc}, {desc}, {name}_glyphs, {name}_data}};")lines.append("")print(f"{name}: cap {cap}px, ascent {asc}, descent {desc}, {len(data)} bytes of glyphs")Path(out).write_text("\n".join(lines))@@ -123,4 +131,8 @@ def main(out):if __name__ == "__main__":- main(sys.argv[1])+ extra = []+ if "--extra" in sys.argv:+ v = sys.argv[sys.argv.index("--extra") + 1]+ extra = [int(c) for c in v.split(",") if c]+ main(sys.argv[1], extra)diff --git a/tools/lang.py b/tools/lang.pynew file mode 100644index 00000000..99354266--- /dev/null+++ b/tools/lang.py@@ -0,0 +1,201 @@+#!/usr/bin/env python3+"""NumPlay in other languages: NumPlay-French.nwa, NumPlay-Chinese.nwa.++Texts players read are marked in the sources: T("...") in C, T!("...") in Rust+(games/common/np_text.h). Each part has its translations, one per line, the+English text as it is written in the source, a tab, then the translation (the+same escapes: \\n, \\"; UTF-8):++ launcher/lang/<code>.txt the launcher, and the games' names and taglines (games/games.json)+ games/<game>/lang/<code>.txt a game++ lang.py strings [PART] every marked text of a part (or all), for translating+ lang.py check CODE the texts still missing a translation, part by part+ lang.py tree CODE OUT copies what builds NumPlay to OUT with the translations in place+ (a missing one stays English), NP_TEXT_EXTRA on, the launcher's+ accented letters (tools/fontgen.py) and the 12-pixel font's letters+ (tools/xfont.py) for the texts there+"""+import json+import os+import re+import shutil+import subprocess+import sys++ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))+LANGS = {"fr": "French", "zh": "Chinese"}+MARK = re.compile(r'\bT(!?)\(\s*"((?:[^"\\\n]|\\.)*)"\s*\)')+CODE_EXT = (".c", ".h", ".rs")+# not part of a build+SKIP = re.compile(r"\.(gif|mp4|mov)$")+++def parts():+ out = {"launcher": [os.path.join(ROOT, "launcher")]}+ for g in json.load(open(os.path.join(ROOT, "games", "games.json"))):+ out[g["id"]] = [os.path.join(ROOT, "games", g["id"])]+ return out+++def code_files(dirs):+ for d in dirs:+ for base, subdirs, files in os.walk(d):+ subdirs[:] = [s for s in subdirs if s not in ("node_modules", "target", "output", "build", "lang")]+ for f in files:+ if f.endswith(CODE_EXT):+ yield os.path.join(base, f)+++def marked(path):+ try:+ text = open(path, encoding="utf-8").read()+ except UnicodeDecodeError:+ return []+ return [m.group(2) for m in MARK.finditer(text)]+++def strings(part):+ found = []+ for f in code_files(parts()[part]):+ for s in marked(f):+ if s not in found:+ found.append(s)+ if part == "launcher":+ for g in json.load(open(os.path.join(ROOT, "games", "games.json"))):+ for k in ("title", "tagline"):+ v = json.dumps(g[k], ensure_ascii=False)[1:-1]+ if v not in found:+ found.append(v)+ return found+++def table_path(part, code):+ base = os.path.join(ROOT, "launcher") if part == "launcher" else os.path.join(ROOT, "games", part)+ return os.path.join(base, "lang", f"{code}.txt")+++def load_table(part, code):+ p = table_path(part, code)+ table = {}+ if not os.path.exists(p):+ return table+ for n, line in enumerate(open(p, encoding="utf-8"), 1):+ line = line.rstrip("\n")+ if not line or line.startswith("#"):+ continue+ if "\t" not in line:+ raise SystemExit(f"{p}:{n}: no tab between the English and the translation")+ en, tr = line.split("\t", 1)+ table[en] = tr+ return table+++def check(code):+ missing = 0+ for part in parts():+ t = load_table(part, code)+ todo = [s for s in strings(part) if s not in t]+ if todo:+ print(f"{part}: {len(todo)} missing")+ for s in todo:+ print(f" {s}")+ missing += len(todo)+ print(f"{LANGS.get(code, code)}: {missing} texts missing")+ return missing+++def tree(code, out):+ """A copy of what builds NumPlay, translated."""+ files = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard"], cwd=ROOT,+ capture_output=True, text=True, check=True).stdout.split("\n")+ keep = [f for f in files if f and (f in ("Makefile", "VERSION") or f.startswith(("launcher/", "games/", "tools/", "assets/fonts/")))+ and not SKIP.search(f) and not f.startswith("games/numdance/")]+ if os.path.exists(out):+ shutil.rmtree(out)+ tables = {part: load_table(part, code) for part in parts()}+ owner = {}+ for part, dirs in parts().items():+ for d in dirs:+ owner[os.path.relpath(d, ROOT)] = part+ used = [] # every translated text, for the fonts+ for f in keep:+ src, dst = os.path.join(ROOT, f), os.path.join(out, f)+ if not os.path.exists(src):+ continue+ os.makedirs(os.path.dirname(dst), exist_ok=True)+ part = next((p for d, p in owner.items() if f == d or f.startswith(d + "/")), None)+ if f.endswith(CODE_EXT) and part:+ t = tables[part]+ text = open(src, encoding="utf-8", errors="surrogateescape").read()++ def put(m):+ tr = t.get(m.group(2))+ if tr is None:+ return m.group(0)+ used.append(tr)+ return f'T{m.group(1)}("{tr}")'+ text = MARK.sub(put, text)+ if f == "games/common/np_text.h":+ text = text.replace("#define NP_TEXT_EXTRA 0", "#define NP_TEXT_EXTRA 1")+ open(dst, "w", encoding="utf-8", errors="surrogateescape").write(text)+ else:+ shutil.copy2(src, dst)+ # the common header (no part) still turns NP_TEXT_EXTRA on+ h = os.path.join(out, "games/common/np_text.h")+ text = open(h).read().replace("#define NP_TEXT_EXTRA 0", "#define NP_TEXT_EXTRA 1")+ open(h, "w").write(text)+ # the games' names and taglines+ gj = os.path.join(out, "games/games.json")+ games = json.load(open(gj))+ lt = tables["launcher"]+ for g in games:+ for k in ("title", "tagline"):+ key = json.dumps(g[k], ensure_ascii=False)[1:-1]+ if key in lt:+ g[k] = json.loads(f'"{lt[key]}"')+ used.append(lt[key])+ # (the screenshots in 32 colours, not 64: room for the translations and their letters)+ for g in games:+ g["colors"] = min(g.get("colors", 64), 32)+ json.dump(games, open(gj, "w"), indent=2, ensure_ascii=False)+ # node packages some games build with+ for nm in ("games/numdash/node_modules",):+ if os.path.isdir(os.path.join(ROOT, nm)):+ os.symlink(os.path.join(ROOT, nm), os.path.join(out, nm))+ # fonts: the launcher's accented letters, and the 12-pixel font for the rest+ text = "\n".join(used)+ latin = sorted({ord(c) for c in text if 0x80 <= ord(c) < 0x180})+ # the launcher's own texts get Nunito's letters; the games draw theirs with accents (np_latin)+ if os.path.isdir(os.path.join(ROOT, "tools/.fonts")):+ shutil.copytree(os.path.join(ROOT, "tools/.fonts"), os.path.join(out, "tools/.fonts"), dirs_exist_ok=True)+ subprocess.run([sys.executable, os.path.join(out, "tools/fontgen.py"), os.path.join(out, "launcher/src/font_data.c"),+ "--extra", ",".join(str(c) for c in latin)], check=True, cwd=ROOT)+ all_text = os.path.join(out, "build-lang-texts.txt")+ open(all_text, "w", encoding="utf-8").write(text)+ subprocess.run([sys.executable, os.path.join(ROOT, "tools/xfont.py"), "table",+ os.path.join(ROOT, "assets/fonts/fusion-pixel-12px.bin"),+ os.path.join(out, "launcher/src/np_xfont.h"), all_text], check=True)+ missing = sum(1 for part in parts() for s in strings(part) if s not in tables[part])+ print(f"{out}: {LANGS.get(code, code)}, {len(used)} texts translated, {missing} still English")+++def main():+ if len(sys.argv) < 2:+ raise SystemExit(__doc__)+ cmd = sys.argv[1]+ if cmd == "strings":+ for part in ([sys.argv[2]] if len(sys.argv) > 2 else parts()):+ print(f"== {part}")+ for s in strings(part):+ print(s)+ elif cmd == "check":+ sys.exit(1 if check(sys.argv[2]) else 0)+ elif cmd == "tree":+ tree(sys.argv[2], sys.argv[3])+ else:+ raise SystemExit(__doc__)+++if __name__ == "__main__":+ main()diff --git a/tools/pcf.py b/tools/pcf.pynew file mode 100644index 00000000..7e14bbe1--- /dev/null+++ b/tools/pcf.py@@ -0,0 +1,72 @@+"""Minimal PCF reader: {codepoint: (width_advance, xoff, yoff_from_baseline_top, w, h, rows)}"""+import struct+def read_pcf(path):+ d = open(path, 'rb').read()+ assert d[:4] == b'\x01fcp'+ n, = struct.unpack_from('<i', d, 4)+ tables = {}+ for i in range(n):+ t, fmt, size, off = struct.unpack_from('<iiii', d, 8 + 16 * i)+ tables[t] = (fmt, size, off)+ def hdr(t):+ fmt0, size, off = tables[t]+ fmt, = struct.unpack_from('<i', d, off)+ e = '>' if fmt & 4 else '<'+ return fmt, e, off + 4+ # metrics+ fmt, e, p = hdr(4)+ metrics = []+ if fmt & 0x100:+ cnt, = struct.unpack_from(e + 'H', d, p); p += 2+ for i in range(cnt):+ l, r, w, a, de = (x - 0x80 for x in d[p:p + 5]); p += 5+ metrics.append((l, r, w, a, de))+ else:+ cnt, = struct.unpack_from(e + 'i', d, p); p += 4+ for i in range(cnt):+ l, r, w, a, de, at = struct.unpack_from(e + 'hhhhhH', d, p); p += 12+ metrics.append((l, r, w, a, de))+ # bitmaps+ fmt, e, p = hdr(8)+ cnt, = struct.unpack_from(e + 'i', d, p); p += 4+ offs = struct.unpack_from(e + '%di' % cnt, d, p); p += 4 * cnt+ sizes = struct.unpack_from(e + '4i', d, p); p += 16+ pad = 1 << (fmt & 3)+ msbit = bool(fmt & 8)+ bits = d[p:p + sizes[fmt & 3]]+ # encodings+ fmt2, e2, q = hdr(32)+ min2, max2, min1, max1, dflt = struct.unpack_from(e2 + '5h', d, q); q += 10+ ncodes = (max2 - min2 + 1) * (max1 - min1 + 1)+ idx = struct.unpack_from(e2 + '%dH' % ncodes, d, q)+ out = {}+ k = 0+ for b1 in range(min1, max1 + 1):+ for b2 in range(min2, max2 + 1):+ gi = idx[k]; k += 1+ if gi == 0xFFFF: continue+ cp = b1 * 256 + b2+ l, r, w, a, de = metrics[gi]+ gw, gh = r - l, a + de+ stride = ((gw + 7) // 8 + pad - 1) // pad * pad if gw > 0 else 0+ rows = []+ o = offs[gi]+ for y in range(gh):+ row = 0+ for x in range(gw):+ byte = bits[o + y * stride + x // 8]+ bit = (byte >> (7 - x % 8)) & 1 if msbit else (byte >> (x % 8)) & 1+ row |= bit << x+ rows.append(row)+ out[cp] = (w, l, a, gw, gh, rows)+ return out+if __name__ == '__main__':+ import sys+ f = read_pcf(sys.argv[1])+ print(len(f))+ for ch in '你好游戏设置é':+ g = f.get(ord(ch))+ print(ch, g[:5] if g else None)+ if g:+ for r in g[5]:+ print(''.join('#' if r >> x & 1 else '.' for x in range(g[3])))diff --git a/tools/xfont.py b/tools/xfont.pynew file mode 100644index 00000000..d82fb2b6--- /dev/null+++ b/tools/xfont.py@@ -0,0 +1,105 @@+#!/usr/bin/env python3+"""The 12-pixel font for letters the games' own fonts don't have (Chinese).++ xfont.py extract font.pcf assets/fonts/fusion-pixel-12px.bin+ Keeps the letters of GB2312 (simplified Chinese), CJK and fullwidth+ punctuation from Fusion Pixel 12px (SIL Open Font License 1.1, see+ LICENSES/OFL-1.1-Fusion-Pixel.txt), in a small file committed with the+ sources: magic "NPXF", the count, then for each letter its code point+ (4 bytes), advance, x, y (from the top of a 12-pixel line), width, height+ and its rows ((width + 7) / 8 bytes each, the first pixel in bit 0).+ xfont.py table assets/fonts/fusion-pixel-12px.bin out.h TEXT_FILES...+ Writes games/common/np_xfont.h-style C: np_xfont with only the letters+ the text files use (see games/common/np_text.h).+"""+import struct+import sys++ASCENT = 10 # Fusion Pixel 12px: 10 above the baseline, 2 below+++def wanted():+ cps = set()+ for b1 in range(0xA1, 0xF8):+ for b2 in range(0xA1, 0xFF):+ try:+ cps.add(ord(bytes([b1, b2]).decode("gb2312")))+ except (UnicodeDecodeError, TypeError):+ pass+ cps |= set(range(0x3000, 0x3040)) | set(range(0xFF00, 0xFFF0)) | set(range(0x2010, 0x2070))+ return cps+++def extract(pcf, out):+ sys.path.insert(0, __file__.rsplit("/", 1)[0])+ from pcf import read_pcf+ font = read_pcf(pcf)+ keep = sorted(cp for cp in wanted() if cp in font and font[cp][4] > 0 or (cp in font and cp in (0x3000,)))+ data = bytearray(b"NPXF" + struct.pack("<I", len(keep)))+ for cp in keep:+ adv, l, a, w, h, rows = font[cp]+ data += struct.pack("<IBbbBB", cp, adv, l, ASCENT - a, w, h)+ stride = (w + 7) // 8+ for r in rows:+ data += r.to_bytes(stride, "little") if stride else b""+ open(out, "wb").write(data)+ print(f"{out}: {len(keep)} letters, {len(data)} bytes")+++def load(path):+ d = open(path, "rb").read()+ assert d[:4] == b"NPXF"+ n, = struct.unpack_from("<I", d, 4)+ p, out = 8, {}+ for _ in range(n):+ cp, adv, x, y, w, h = struct.unpack_from("<IBbbBB", d, p)+ p += 9+ size = h * ((w + 7) // 8)+ out[cp] = (adv, x, y, w, h, d[p:p + size])+ p += size+ return out+++def table(font_path, out, texts):+ font = load(font_path)+ used = set()+ for t in texts:+ used |= {ord(c) for c in open(t, encoding="utf-8").read() if ord(c) >= 0x80}+ # (Latin letters and the usual punctuation are drawn by the games' fonts: see np_latin)+ cps = sorted(c for c in used if c in font and c >= 0x2100)+ L = ["/* Made by tools/xfont.py from Fusion Pixel 12px (SIL Open Font License 1.1): the letters this",+ " build's texts use that the games' fonts don't have. See games/common/np_text.h. */"]+ rows = bytearray()+ glyphs = []+ for cp in cps:+ adv, x, y, w, h, r = font[cp]+ stride = (w + 7) // 8+ bits = [r[j * stride + i // 8] >> (i % 8) & 1 for j in range(h) for i in range(w)]+ packed = bytearray((len(bits) + 7) // 8)+ for k, b in enumerate(bits):+ packed[k // 8] |= b << (k % 8)+ if cp >= 0x10000 or len(rows) >= 0x10000:+ raise SystemExit("xfont: too many letters for 16-bit offsets")+ glyphs.append(f"{{{cp:#x}, {adv}, {w}, {h}, {x}, {y}, {len(rows)}}}")+ rows += packed # (each letter starts on a byte: its offset counts bytes)+ if cps:+ L.append("static const np_xglyph_t np_xfont_glyphs[] = {")+ L += [f" {g}," for g in glyphs]+ L.append("};")+ L.append(f"static const uint8_t np_xfont_rows[{len(rows)}] = {{")+ for i in range(0, len(rows), 24):+ L.append(" " + ", ".join(str(b) for b in rows[i:i + 24]) + ",")+ L.append("};")+ L.append(f"const np_xfont_t np_xfont = {{{len(cps)}, np_xfont_glyphs, np_xfont_rows}};")+ else:+ L.append("const np_xfont_t np_xfont = {0, 0, 0};")+ open(out, "w").write("\n".join(L) + "\n")+ return len(cps), len(rows) + 10 * len(cps)+++if __name__ == "__main__":+ if sys.argv[1] == "extract":+ extract(sys.argv[2], sys.argv[3])+ elif sys.argv[1] == "table":+ n, size = table(sys.argv[2], sys.argv[3], sys.argv[4:])+ print(f"{sys.argv[3]}: {n} letters, about {size} bytes")