cosmo/terminal/tools/gen_assets.py

368 lines
15 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""生成 COSMO 终端的内置美术:霓虹线稿天体图标 + 16x16 中文字库。
/usr/bin/python3 terminal/tools/gen_assets.py
输出(提交进仓库,编译时不需要 PIL):
terminal/firmware/cosmo_terminal/src/icons.{h,cpp}
terminal/firmware/cosmo_terminal/src/font_cjk.{h,cpp}
图标约定:源图必须是自己发光的霓虹线稿 + 纯黑底(资源文件/*小.jpeg)。
存成不带 alpha 的 RGB565,固件按"叠加混合"贴到帧缓冲上——黑色加上去等于没画,
霓虹线条自动发光,省掉一半 flash 和一次 alpha 乘法。
"""
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parents[2]
ART_DIR = ROOT / "资源文件"
OUT = ROOT / "terminal/firmware/cosmo_terminal/src"
FONT_PATH = "/System/Library/Fonts/STHeiti Medium.ttc"
FONT_PT = 160 # 大字号渲染再降到 16x16;64pt 时字身只有 9px,缩下去必然糊死
FONT_CANVAS = 320
FONT_CROP = 158 # 截取 em 见方:满宽字(木/行)字身 149px -> 15px
FONT_DY = 4 # STHeiti 的字身比 anchor="mm" 的中心低几个像素,往下找齐
FONT_THR = 130 # 主阈值:再低笔画就粘在一起;过密往上试,没墨往下试
LIST_SIZE = 40
DETAIL_SIZE = 64
MODE_SIZE = 96 # 入口页"天体 / 火箭"两张大图标
# 生成式图标:火箭立绘不吃源图,直接用后端那套 rocket_art 按参数画,所以终端兜底图和 Web 端 3D 模型是同一台火箭
ROCKET_CFG = {
"color": "#cfe6ff",
"height_m": 57.0,
"diameter_m": 5.0,
"stage_1": {"length_ratio": 0.62, "engine_count": 2, "recoverable": False},
"stage_2": {"length_ratio": 0.38, "engine_count": 2},
"boosters": {"count": 4, "diameter_ratio": 0.67, "length_ratio": 0.57},
"appearance": {},
}
# 图标素材:key -> 源文件名(都是 320x320 纯黑底霓虹线稿)
ART = {
"planet": "行星小.jpeg",
"jupiter": "木星小.jpeg",
"saturn": "土星小.jpeg",
"mars": "火星小.jpeg",
"earth": "地球-2小.jpeg",
"earth_icon": "地球-图标小.jpeg",
"venus": "金星(图标)小.jpeg",
"neptune": "海王星小.jpeg",
"sun": "太阳小.jpeg",
"star": "恒星小.jpeg",
"comet": "彗星小.jpeg",
"halley": "哈雷彗星小.jpeg",
"galaxy": "星系小.jpeg",
"satellite": "卫星小.jpeg",
"probe": "通信卫星小.jpeg",
"shuttle": "航天飞机小.jpeg",
"rover": "火星车小.jpeg",
}
# 按 name / name_zh 小写子串命中(从上到下优先)
NAMES = [
# 先匹配更具体的名字:火星车/探测器里的"火星""太阳"不能抢先命中行星图标
("curiosity", "rover"), ("perseverance", "rover"), ("zhurong", "rover"),
("yutu", "rover"), ("毅力", "rover"), ("好奇号", "rover"), ("祝融", "rover"),
("月球车", "rover"), ("火星车", "rover"), ("巡视器", "rover"),
("shuttle", "shuttle"), ("航天飞机", "shuttle"),
("voyager", "probe"), ("pioneer", "probe"), ("new horizons", "probe"),
("parker", "probe"), ("cassini", "probe"), ("juno", "probe"),
("messenger", "probe"), ("bepicolombo", "probe"), ("juice", "probe"),
("旅行者", "probe"), ("新视野", "probe"), ("帕克", "probe"), ("卡西尼", "probe"),
("朱诺", "probe"), ("信使号", "probe"), ("欧空", "probe"),
("telescope", "satellite"), ("webb", "satellite"), ("hubble", "satellite"),
("望远镜", "satellite"), ("卫星", "satellite"),
("halley", "halley"), ("哈雷", "halley"),
("moon", "earth_icon"), ("luna", "earth_icon"), ("月球", "earth_icon"),
("jupiter", "jupiter"), ("木星", "jupiter"),
("saturn", "saturn"), ("土星", "saturn"),
("mars", "mars"), ("火星", "mars"),
("earth", "earth"), ("地球", "earth"),
("venus", "venus"), ("金星", "venus"),
("neptune", "neptune"), ("海王星", "neptune"),
("uranus", "planet"), ("天王星", "planet"),
("mercury", "planet"), ("水星", "planet"),
("pluto", "planet"), ("冥王", "planet"),
("sun", "sun"), ("太阳", "sun"),
]
# 类型兜底:后端 type 见 backend/app/models/celestial.py
TYPES = {
"planet": "planet",
"dwarf_planet": "planet",
"star": "star",
"comet": "comet",
"satellite": "satellite",
"probe": "probe",
}
FALLBACK = "planet"
def rgb565(r, g, b):
return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)
def pack(im, size):
"""RGB 图 -> size x size 的 RGB565 列表(黑底门限,叠加混合时不落地)"""
sq = im.resize((size, size), Image.LANCZOS)
out = []
for r, g, b in sq.getdata():
if (r * 299 + g * 587 + b * 114) // 1000 <= 10:
out.append(0) # 黑底 -> 叠加混合时不落地
else:
out.append(rgb565(r, g, b))
return out
def rocket_pixels(cfg, size):
"""按参数画一枚火箭:直接 import 后端的绘图模块,保证两端长得一样"""
import sys
sys.path.insert(0, str(ROOT / "backend"))
from app.services.rocket_art import art_params, render
return pack(render(art_params(cfg), size), size)
def icon_pixels(path, size):
"""亮度 bbox 裁切 -> 补方 -> 缩放 -> 黑底门限 -> RGB565 列表"""
im = Image.open(path).convert("RGB")
bbox = Image.open(path).convert("L").point(lambda v: 255 if v > 40 else 0).getbbox()
if bbox:
im = im.crop(bbox)
w, h = im.size
side = max(w, h)
sq = Image.new("RGB", (side, side), (0, 0, 0))
sq.paste(im, ((side - w) // 2, (side - h) // 2))
return pack(sq, size)
def emit_icons():
keys = list(ART)
data = {k: {s: icon_pixels(ART_DIR / ART[k], s) for s in (LIST_SIZE, DETAIL_SIZE)}
for k in keys}
gen = {
"mode_planet_96": icon_pixels(ART_DIR / ART["planet"], MODE_SIZE),
"mode_rocket_96": rocket_pixels(ROCKET_CFG, MODE_SIZE),
"rocket_list": rocket_pixels(ROCKET_CFG, LIST_SIZE),
"rocket_detail": rocket_pixels(ROCKET_CFG, DETAIL_SIZE),
}
GEN_SIZES = [("mode_planet_96", MODE_SIZE), ("mode_rocket_96", MODE_SIZE),
("rocket_list", LIST_SIZE), ("rocket_detail", DETAIL_SIZE)]
h = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"/* 天体霓虹线稿图标:无 alpha 的 RGB565,固件用叠加混合绘制(黑色不落地)。 */",
"#pragma once",
"#include <stdint.h>",
"",
f"#define ICON_LIST_W {LIST_SIZE}",
f"#define ICON_LIST_H {LIST_SIZE}",
f"#define ICON_DETAIL_W {DETAIL_SIZE}",
f"#define ICON_DETAIL_H {DETAIL_SIZE}",
"",
"typedef struct { const uint16_t *px; uint8_t w, h; } IconArt;",
""]
for k in keys:
h.append(f"extern const IconArt ic_{k}_list; /* {ART[k]} */")
for k in keys:
h.append(f"extern const IconArt ic_{k}_detail;")
for name, side in GEN_SIZES:
h.append(f"extern const IconArt ic_{name}; /* {side}x{side} */")
h += ["",
"/** name/name_zh 小写子串命中优先,其次按 type 兜底;detail!=0 取大图 */",
"const IconArt *icon_for(const char *name, const char *name_zh, const char *type, int detail);",
""]
c = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"#include <string.h>",
"#include <ctype.h>",
'#include "icons.h"',
""]
for k in keys:
for s, tag in ((LIST_SIZE, "list"), (DETAIL_SIZE, "detail")):
px = data[k][s]
c.append(f"static const uint16_t px_{k}_{tag}[{len(px)}] = {{")
for i in range(0, len(px), 16):
c.append(",".join("0x%04X" % v for v in px[i:i + 16]) + ",")
c.append("};")
for name, side in GEN_SIZES:
px = gen[name]
c.append(f"static const uint16_t px_{name}[{len(px)}] = {{")
for j in range(0, len(px), 16):
c.append(",".join("0x%04X" % v for v in px[j:j + 16]) + ",")
c.append("};")
c.append("")
for k in keys:
c.append(f"const IconArt ic_{k}_list = {{ px_{k}_list, {LIST_SIZE}, {LIST_SIZE} }};")
for k in keys:
c.append(f"const IconArt ic_{k}_detail = {{ px_{k}_detail, {DETAIL_SIZE}, {DETAIL_SIZE} }};")
for name, side in GEN_SIZES:
c.append(f"const IconArt ic_{name} = {{ px_{name}, {side}, {side} }};")
c += ["", "struct NameRule { const char *needle; const IconArt *list, *detail; };",
"struct TypeRule { const char *type; const IconArt *list, *detail; };", "",
"static const NameRule s_names[] = {"]
for needle, key in NAMES:
c.append(f' {{ "{needle}", &ic_{key}_list, &ic_{key}_detail }},')
c += ["};", "", "static const TypeRule s_types[] = {"]
for t, key in TYPES.items():
c.append(f' {{ "{t}", &ic_{key}_list, &ic_{key}_detail }},')
c += ["};", "",
"static void lower_utf8(const char *s, char *buf, size_t cap)",
"{",
" size_t i = 0;",
" for (; *s && i + 1 < cap; s++)",
" buf[i++] = ((unsigned char)*s < 0x80) ? (char)tolower((unsigned char)*s) : *s;",
" buf[i] = 0;",
"}",
"",
"static const IconArt *match(const char *hay, int detail)",
"{",
" char low[48];",
" if (!hay || !hay[0]) return NULL;",
" lower_utf8(hay, low, sizeof(low));",
" for (unsigned i = 0; i < sizeof(s_names) / sizeof(s_names[0]); i++)",
" if (strstr(low, s_names[i].needle))",
" return detail ? s_names[i].detail : s_names[i].list;",
" return NULL;",
"}",
"",
"const IconArt *icon_for(const char *name, const char *name_zh, const char *type, int detail)",
"{",
" const IconArt *a = match(name, detail);",
" if (!a) a = match(name_zh, detail);",
" if (a) return a;",
" if (type) {",
" for (unsigned i = 0; i < sizeof(s_types) / sizeof(s_types[0]); i++)",
" if (!strcmp(type, s_types[i].type))",
" return detail ? s_types[i].detail : s_types[i].list;",
" }",
" return detail ? &ic_planet_detail : &ic_planet_list;",
"}",
""]
(OUT / "icons.h").write_text("\n".join(h) + "\n", encoding="utf-8")
(OUT / "icons.cpp").write_text("\n".join(c) + "\n", encoding="utf-8")
total = sum(len(v) * 2 for v in list(data.values()) )
total += sum(len(v) * 2 for v in gen.values())
print(f"icons: {len(keys)} 张天体 x2 尺寸 + {len(gen)} 张生成图,{total // 1024} KB flash")
def cjk_codepoints():
"""GB2312 一级字库(0xB0A1-0xD7F9)+ 常用中文标点/单位"""
cps = set()
for hi in range(0xB0, 0xD8):
for lo in range(0xA1, 0xFF):
try:
u = bytes([hi, lo]).decode("gb2312")
except UnicodeDecodeError:
continue
if len(u) == 1:
cps.add(ord(u))
cps |= {ord(c) for c in ",。:;、!?()—…·%℃°××ⅠⅡⅢⅣ"}
return sorted(cps)
BLANK_BOX = [0x00, 0x00] + [0x81, 0x00] * 7 + [0x81, 0x00] * 6 + [0x00, 0x00]
def _threshold(small, thr):
"""16x16 灰度 -> 点阵行(2 字节/行,MSB 为最左像素)"""
rows = []
for y in range(16):
hi = lo = 0
for x in range(8):
hi = hi << 1 | (1 if small.getpixel((x, y)) >= thr else 0)
lo = lo << 1 | (1 if small.getpixel((x + 8, y)) >= thr else 0)
rows += [hi, lo]
return rows
def _pick_threshold(small):
"""主阈值优先;点阵超过 55% 有墨(笔画糊成一团)就加严,一点墨都没有就放宽"""
rows = _threshold(small, FONT_THR)
ink = sum(bin(v).count("1") for v in rows) / 256.0
if ink > 0.55:
for thr in (FONT_THR + 40, FONT_THR + 70):
dense = _threshold(small, thr)
if sum(bin(v).count("1") for v in dense) / 256.0 <= 0.55:
return dense
return dense if sum(dense) else rows
if ink == 0:
for thr in (FONT_THR - 30, FONT_THR - 50, FONT_THR - 70):
light = _threshold(small, thr)
if sum(light):
return light
return BLANK_BOX # 字体里根本没有这个字
return rows
def cjk_rows(ch, font):
"""em 见方等比降到 16x16:满宽字字身 ~15px,标点自然只占几像素。缺字返回空心方框"""
big = Image.new("L", (FONT_CANVAS, FONT_CANVAS), 0)
ImageDraw.Draw(big).text((FONT_CANVAS // 2, FONT_CANVAS // 2 + FONT_DY), ch,
fill=255, font=font, anchor="mm")
c, r = FONT_CANVAS // 2, FONT_CROP // 2
small = big.crop((c - r, c + FONT_DY - r, c + r, c + FONT_DY + r)).resize((16, 16), Image.BILINEAR)
return _pick_threshold(small)
def emit_font():
cps = cjk_codepoints()
font = ImageFont.truetype(FONT_PATH, FONT_PT, index=0)
glyphs, missing = [], []
for cp in cps:
rows = cjk_rows(chr(cp), font)
if rows == BLANK_BOX:
missing.append(chr(cp))
glyphs.append(rows)
h = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"/* 16x16 点阵中文字库:GB2312 一级字 + 常用标点,行式 2 字节/行,MSB 为最左像素。 */",
"#pragma once",
"#include <stdint.h>",
"#include <stdbool.h>",
"",
"#define CJK_CELL 16",
f"#define CJK_COUNT {len(cps)}",
"",
"/** 按码位二分;缺字返回 NULL(调用字画空心方框) */",
"const uint8_t *cjk_glyph(uint32_t cp);",
""]
c = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"#include <stddef.h>",
'#include "font_cjk.h"', "",
"static const uint16_t s_codepoints[] = {"]
for i in range(0, len(cps), 16):
c.append(",".join("0x%04X" % v for v in cps[i:i + 16]) + ",")
c += ["};", "", "static const uint8_t s_glyphs[][32] = {"]
for g in glyphs:
c.append(" " + ",".join("0x%02X" % v for v in g) + ",")
c += ["};", "",
"const uint8_t *cjk_glyph(uint32_t cp)",
"{",
" unsigned lo = 0, hi = sizeof(s_codepoints) / sizeof(s_codepoints[0]);",
" while (lo < hi) {",
" unsigned mid = (lo + hi) / 2;",
" if (s_codepoints[mid] == cp) return s_glyphs[mid];",
" if (s_codepoints[mid] < cp) lo = mid + 1; else hi = mid;",
" }",
" return NULL;",
"}",
""]
(OUT / "font_cjk.h").write_text("\n".join(h) + "\n", encoding="utf-8")
(OUT / "font_cjk.cpp").write_text("\n".join(c) + "\n", encoding="utf-8")
print(f"font_cjk: {len(cps)} 字 @16x16,{len(cps) * 34 // 1024} KB flash,"
f"缺字 {len(missing)} {missing[:8]}")
def main():
OUT.mkdir(parents=True, exist_ok=True)
emit_icons()
emit_font()
if __name__ == "__main__":
main()