cosmo/backend/app/services/rocket_art.py

315 lines
12 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.

"""按火箭登记参数绘制终端用的霓虹线稿立面图。
和天体图标同一条流水线(纯黑底、无 alpha、终端叠加混合),区别是这张图不用人
维护:形状全部来自 rocket_configs 里的身高/直径/级长比/助推器/可回收标记,
所以参数一改图形就跟着改,参数没改图形哈希就不变。
比例沿用 frontend/src/features/rocket-simulator/sceneMath.ts 的 stageGeometry(),
这样终端图标和网页端 3D 模型是同一台火箭,不会长成两个样子。
"""
from __future__ import annotations
import hashlib
import json
import math
from array import array
from typing import List, Tuple
from PIL import Image, ImageChops, ImageDraw, ImageFilter
from app.services.terminal_icon import BLACK_FLOOR
#: 画布四周留白(比例),给栅格翼和喷管留出位置
MARGIN = 0.06
#: 长细比压缩:drawn_aspect = GIRTH_K * 真实长细比 ** GIRTH_POW。
#: 真实的猎鹰 9 是 19:1,照画到 40px 上只剩一根针;开方压缩后既认得出是火箭,
#: 又保留"电子号细、长征五号粗"的相对关系
GIRTH_K = 1.72
GIRTH_POW = 0.45
#: 一台箭体最多画几个喷管,40px 上再多就糊成一条线
MAX_BELLS = 5
#: 超采样倍数:1px 的线在 40px 画布上直接画会发灰,先放大画再 LANCZOS 缩回来
SS = 4
DEFAULT_BOOSTER_DIAMETER_RATIO = 0.45
DEFAULT_BOOSTER_LENGTH_RATIO = 0.86
def _num(value, default: float = 0.0) -> float:
try:
return float(value)
except (TypeError, ValueError):
return default
def _clamp(value: float, lo: float, hi: float) -> float:
return max(lo, min(hi, value))
def _ink(color: str) -> Tuple[int, int, int]:
"""#rrggbb -> 最亮通道归一化到 255 的 RGB。
电子号登记的是 #242a30 这种接近纯黑的涂装,直接当线条画到黑底上等于没画,
叠加混合看不见;这里按线稿的习惯只保留色调,亮度由线稿自己决定。
"""
raw = (color or "").strip().lstrip("#")
if len(raw) != 6:
return (235, 245, 255)
try:
rgb = tuple(int(raw[i : i + 2], 16) for i in (0, 2, 4))
except ValueError:
return (235, 245, 255)
peak = max(rgb)
if peak < 1:
return (235, 245, 255)
return tuple(min(255, round(c * 255 / peak)) for c in rgb)
def art_params(cfg: dict) -> dict:
"""rocket_configs 的外观字段 -> 可直接绘制的米制几何(可序列化、可哈希)。
只收"画面上看得见"的键:改介绍、厂商不会让终端重新下载点阵。
数值统一 round,避免 0.45 和 0.45000000001 产生两个版本。
"""
height = max(1.0, _num(cfg.get("height_m"), 1.0))
diameter = max(0.5, _num(cfg.get("diameter_m"), 1.0))
stage_1 = cfg.get("stage_1") or {}
stage_2 = cfg.get("stage_2") or {}
boosters = cfg.get("boosters") or {}
appearance = cfg.get("appearance") or {}
# appearance.fairing 缺省 = 有整流罩;false 表示二级自己带头锥(星舰、电子号)
has_fairing = appearance.get("fairing") is not False
fairing_d = diameter * 1.4 if has_fairing else diameter * 0.97
fairing_d = min(fairing_d, 5.4) if has_fairing else fairing_d
fairing_h = _clamp(fairing_d * 2.5, height * 0.13, height * 0.27) if has_fairing else height * 0.11
fairing_cone_h = fairing_h * (0.62 if has_fairing else 1.0)
interstage_h = _clamp(4.6, height * 0.035, height * 0.085)
stack_h = height - fairing_h - interstage_h
ratio1 = _clamp(_num(stage_1.get("length_ratio"), 0.65), 0.2, 0.9)
ratio2 = _clamp(_num(stage_2.get("length_ratio"), 0.35), 0.1, 0.8)
stage1_h = stack_h * ratio1 / (ratio1 + ratio2)
stage2_h = stack_h * ratio2 / (ratio1 + ratio2)
booster_count = max(0, int(round(_num(boosters.get("count")))))
b_diam = _clamp(_num(boosters.get("diameter_ratio"), DEFAULT_BOOSTER_DIAMETER_RATIO), 0.2, 1.0)
b_len = _clamp(_num(boosters.get("length_ratio"), DEFAULT_BOOSTER_LENGTH_RATIO), 0.2, 1.0)
params = {
"color": "#%02x%02x%02x" % _ink(cfg.get("color")),
"height": round(height, 3),
"diameter": round(diameter, 3),
"fairing": has_fairing,
"fairing_d": round(fairing_d, 3),
"fairing_h": round(fairing_h, 3),
"fairing_cone_h": round(fairing_cone_h, 3),
"interstage_h": round(interstage_h, 3),
"stage1_h": round(stage1_h, 3),
"stage2_h": round(stage2_h, 3),
"booster_count": booster_count,
"booster_d": round(diameter * b_diam, 3) if booster_count else 0.0,
"booster_len": round(stage1_h * b_len, 3) if booster_count else 0.0,
"booster_engines": max(1, int(round(_num(boosters.get("engine_count"), 1)))) if booster_count else 0,
"core_engines": max(0, int(round(_num(stage_1.get("engine_count"))))),
"stage2_engines": max(1, int(round(_num(stage_2.get("engine_count"), 1)))),
"core_recoverable": bool(stage_1.get("recoverable")),
"booster_recoverable": bool(boosters.get("recoverable")) if booster_count else False,
}
return params
def params_version(params: dict) -> int:
"""图形参数的稳定版本号(同一个参数在任何进程/机器上算出同一个数)"""
blob = json.dumps(params, sort_keys=True, separators=(",", ":")).encode("utf-8")
return int(hashlib.sha1(blob).hexdigest()[:8], 16)
# ----------------------------------------------------------------------
# 绘制
# ----------------------------------------------------------------------
def _bell(draw: ImageDraw.ImageDraw, cx: float, top: float, out: float, height: float, width: int, color) -> None:
"""一个喷管:上窄下宽的梯形(立面图里就是喉部到扩张段)"""
throat = out * 0.55
draw.polygon(
[(cx - throat, top), (cx + throat, top), (cx + out, top + height), (cx - out, top + height)],
outline=color,
width=width,
)
def _bells(
draw: ImageDraw.ImageDraw,
cx: float,
top: float,
half_w: float,
count: int,
bell_h: float,
lw: int,
color,
) -> None:
if count <= 0:
return
shown = min(count, MAX_BELLS)
bell_out = max(1.0 * SS, half_w / math.ceil(shown / 2.0) * 0.62)
span = max(0.0, half_w - bell_out)
if shown == 1:
xs = [cx]
else:
step = 2 * span / (shown - 1)
xs = [cx - span + step * i for i in range(shown)]
for x in xs:
_bell(draw, x, top, bell_out, bell_h, lw, color)
def _nose(
draw: ImageDraw.ImageDraw,
cx: float,
base: float,
half_w: float,
height: float,
lw: int,
color,
ogive: float = 0.75,
) -> None:
"""头锥/鼻锥:底边到顶点的一条尖拱曲线(两侧对称折线)"""
steps = 10
left: List[Tuple[float, float]] = []
right: List[Tuple[float, float]] = []
for i in range(steps + 1):
t = i / steps
dx = half_w * (1.0 - t) ** ogive
y = base - height * t
left.append((cx - dx, y))
right.append((cx + dx, y))
draw.line(left, fill=color, width=lw, joint="curve")
draw.line(right, fill=color, width=lw, joint="curve")
def _tube(
draw: ImageDraw.ImageDraw,
cx: float,
bottom: float,
top: float,
half_w: float,
lw: int,
color,
) -> None:
draw.line([(cx - half_w, bottom), (cx - half_w, top)], fill=color, width=lw)
draw.line([(cx + half_w, bottom), (cx + half_w, top)], fill=color, width=lw)
draw.line([(cx - half_w, top), (cx + half_w, top)], fill=color, width=lw)
def render(params: dict, size: int) -> Image.Image:
"""参数 -> size x size 的黑底霓虹线稿(RGB,无 alpha)
画布是方的、火箭是细长条:按真实长细比画到 40px 上就只剩一根针,所以把长细比
做一次开方压缩(drawn_aspect = GIRTH_K * a ** GIRTH_POW)。压缩之后仍然保持
"电子号比猎鹰 9 细、猎鹰 9 比长征五号细"的相对关系,只是没那么极端。
"""
size = max(16, int(size))
canvas = size * SS
height = params["height"]
diameter = params["diameter"]
core_r = diameter / 2
booster_count = params["booster_count"]
booster_r = params["booster_d"] / 2
fairing_r = params["fairing_d"] / 2
widest = max(params["fairing_d"], diameter + (2 * params["booster_d"] if booster_count else 0.0))
aspect = _clamp(GIRTH_K * (height / widest) ** GIRTH_POW, 3.0, 8.5)
avail = canvas * (1 - 2 * MARGIN)
sy = avail / height
sx = avail / aspect / widest
ink = _ink(params["color"])
body = ink
dim = tuple(round(c * 0.6) for c in ink)
core_px = diameter * sx / SS # 芯级在目标画布上的像素宽,线宽按它取
lw = max(SS, int(round(_clamp(core_px * 0.17, 1.0, core_px * 0.35))) * SS)
lw_fine = max(SS, lw - SS if lw <= 2 * SS else int(round(lw * 0.6 / SS)) * SS)
img = Image.new("RGB", (canvas, canvas), (0, 0, 0))
d = ImageDraw.Draw(img)
cx = canvas / 2.0
base = canvas * (1 - MARGIN) # 一级尾端所在的像素行
def X(m: float) -> float:
return cx + m * sx
def Y(m: float) -> float:
return base - m * sy
s1_top = params["stage1_h"]
ist_top = s1_top + params["interstage_h"]
s2_top = ist_top + params["stage2_h"]
core_r_px = core_r * sx
bell_h = max(1.2 * SS, params["stage1_h"] * 0.08 * sy)
# --- 一级 / 级间段 / 二级 ---
_tube(d, cx, base, Y(s1_top), core_r_px, lw, body)
_tube(d, cx, Y(s1_top), Y(ist_top), core_r_px * 0.84, lw_fine, dim)
_tube(d, cx, Y(ist_top), Y(s2_top), core_r_px * (1.0 if not params["fairing"] else 0.9), lw, body)
# --- 头锥:有罩是"粗罩体 + 尖拱",没罩就是二级自带的等径短头锥(星舰、电子号)---
if params["fairing"]:
cone_base = s2_top + params["fairing_h"] - params["fairing_cone_h"]
_tube(d, cx, Y(s2_top), Y(cone_base), fairing_r * sx, lw, body)
_nose(d, cx, Y(cone_base), fairing_r * sx, params["fairing_cone_h"] * sy, lw, body)
else:
_nose(d, cx, Y(s2_top), core_r_px * 0.97, params["fairing_h"] * sy, lw, body, ogive=0.95)
flap_x = core_r_px * 1.3
flap_y = Y(s2_top - params["stage2_h"] * 0.16)
for side in (-1, 1):
d.line([(cx + side * core_r_px * 0.97, flap_y), (cx + side * flap_x, flap_y - core_r_px * 0.5)],
fill=dim, width=lw_fine)
d.line([(cx + side * flap_x, flap_y - core_r_px * 0.5), (cx + side * flap_x, flap_y + core_r_px * 0.35)],
fill=dim, width=lw_fine)
# --- 一级喷管 ---
_bells(d, cx, base, core_r_px, params["core_engines"], bell_h, lw_fine, dim)
# --- 捆绑助推器 / 侧芯级:立面图上左右对称的一对,粗细长短全部来自登记值 ---
if booster_count:
b_r_px = booster_r * sx
b_top = base - params["booster_len"] * sy
b_fin = max(1.5 * SS, params["booster_len"] * 0.1 * sy)
for side in (-1, 1):
bx = X(side * (core_r + booster_r))
_tube(d, bx, base, b_top, b_r_px, lw, body)
_nose(d, bx, b_top, b_r_px, b_fin, lw, body, ogive=0.9)
_bells(d, bx, base, b_r_px, params["booster_engines"], bell_h, lw_fine, body)
if params["booster_recoverable"]:
fy = b_top + b_fin * 0.9
d.line([(bx + side * b_r_px, fy), (bx + side * (b_r_px + b_r_px * 0.8), fy)], fill=body, width=lw)
# --- 栅格翼:可回收一级顶部外侧的两块小板子 ---
if params["core_recoverable"]:
# 栅格翼按箭体粗细封顶,否则 9m 级直径的星舰会长出一对机翼
fin = max(1.5 * SS, core_r_px * 0.5)
fy = Y(s1_top) + max(1.5 * SS, fin * 0.4)
for side in (-1, 1):
x0 = X(side * core_r)
d.line([(x0, fy), (x0 + side * fin, fy)], fill=body, width=lw)
d.line([(x0 + side * fin, fy), (x0 + side * fin, fy + fin * 0.8)], fill=body, width=lw)
im = img.resize((size, size), Image.LANCZOS)
# 辉光:叠一层自己的模糊,叠加混合到深底上才有设计稿那种霓虹感
return ImageChops.add(im, im.filter(ImageFilter.GaussianBlur(1.0)).point(lambda v: v // 2))
def render_rgb565(params: dict, size: int) -> bytes:
"""参数 -> size*size*2 字节的大端 RGB565 裸点阵(黑像素归零,交给终端叠加混合)"""
im = render(params, size)
out = array("H")
for r, g, b in im.getdata():
if (r * 299 + g * 587 + b * 114) // 1000 <= BLACK_FLOOR:
out.append(0)
else:
out.append(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3))
out.byteswap()
return out.tobytes()