#!/usr/bin/env python3 """화면 UI 미리보기 그리기: 로블록스 서버에서 만든 ScreenGui를 JSON으로 덤프한 것(tests/cloud/dump_gui.luau)을 cairo로 그립니다. 서버에서는 실제 화면을 볼 수 없어서 배치·색·글자 크기를 눈으로 확인하는 용도입니다. 로블록스 렌더러와 똑같지는 않습니다(글꼴 대체, 글자 크기 맞춤, 3D 배경 없음). 지원: Frame/TextLabel/TextButton/ImageLabel/ImageButton/ScrollingFrame, UDim2·AnchorPoint·Rotation·ZIndex, UICorner, UIStroke(테두리·글자), UIGradient(색·투명도·회전·오프셋), UIPadding, UIListLayout, UIScale, UITextSizeConstraint, SizeConstraint, TextScaled/TextWrapped/정렬, ImageRectOffset/Size, ClipsDescendants. python3 tools/gui_render.py dump.json out_dir [--bg scene.png] """ import json import math import os import sys import ctypes import cairo ROOT_UNUSED = None class _Rect(ctypes.Structure): _fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int)] class PangoLib: """python3-gi-cairo가 없어서 libpangocairo를 ctypes로 직접 부릅니다(쓰는 함수만).""" SCALE = 1024 def __init__(self): self.pc = ctypes.CDLL("libpangocairo-1.0.so.0") self.p = ctypes.CDLL("libpango-1.0.so.0") self.g = ctypes.CDLL("libgobject-2.0.so.0") vp, ci, cs = ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p for lib, name, res, args in ( (self.pc, "pango_cairo_create_layout", vp, [vp]), (self.pc, "pango_cairo_show_layout", None, [vp, vp]), (self.pc, "pango_cairo_layout_path", None, [vp, vp]), (self.p, "pango_layout_set_text", None, [vp, cs, ci]), (self.p, "pango_layout_set_width", None, [vp, ci]), (self.p, "pango_layout_set_wrap", None, [vp, ci]), (self.p, "pango_layout_set_alignment", None, [vp, ci]), (self.p, "pango_layout_set_font_description", None, [vp, vp]), (self.p, "pango_layout_get_pixel_extents", None, [vp, ctypes.POINTER(_Rect), ctypes.POINTER(_Rect)]), (self.p, "pango_layout_get_line_count", ci, [vp]), (self.p, "pango_font_description_from_string", vp, [cs]), (self.p, "pango_font_description_set_weight", None, [vp, ci]), (self.p, "pango_font_description_set_absolute_size", None, [vp, ctypes.c_double]), (self.p, "pango_font_description_free", None, [vp]), (self.g, "g_object_unref", None, [vp]), ): f = getattr(lib, name) f.restype = res f.argtypes = args @staticmethod def cr(ctx): # pycairo Context 객체 안의 cairo_t 포인터(PyObject 머리 16바이트 다음) return ctypes.c_void_p.from_address(id(ctx) + 16).value PANGO = PangoLib() ALIGN = {"Left": 0, "Center": 1, "Right": 2} WEIGHT = {"SemiBold": 600, "Bold": 700, "Heavy": 900, "Black": 900} class Layout: def __init__(self, ctx, family, weight, size, text, width, wrap, align): P = PANGO self.ctx = ctx self.ptr = P.pc.pango_cairo_create_layout(P.cr(ctx)) desc = P.p.pango_font_description_from_string(f"{family}, {FALLBACK}".encode()) P.p.pango_font_description_set_weight(desc, weight) P.p.pango_font_description_set_absolute_size(desc, max(1.0, size) * P.SCALE) P.p.pango_layout_set_font_description(self.ptr, desc) P.p.pango_font_description_free(desc) P.p.pango_layout_set_text(self.ptr, text.encode(), -1) if wrap: P.p.pango_layout_set_width(self.ptr, int(max(1, width) * P.SCALE)) P.p.pango_layout_set_wrap(self.ptr, 2) # WORD_CHAR P.p.pango_layout_set_alignment(self.ptr, ALIGN.get(align, 1)) def extents(self): ink, logical = _Rect(), _Rect() PANGO.p.pango_layout_get_pixel_extents(self.ptr, ctypes.byref(ink), ctypes.byref(logical)) return ink, logical def lines(self): return PANGO.p.pango_layout_get_line_count(self.ptr) def path(self, ctx): PANGO.pc.pango_cairo_layout_path(PANGO.cr(ctx), self.ptr) def show(self, ctx): PANGO.pc.pango_cairo_show_layout(PANGO.cr(ctx), self.ptr) def __del__(self): PANGO.g.g_object_unref(self.ptr) ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) IMAGES = {} # rbxassetid 숫자 -> 로컬 png 경로 (Icons.luau의 ID와 art/ui_icons.png) FONT_FAMILY = { "FredokaOne": "Fredoka SemiBold", "LuckiestGuy": "Luckiest Guy", "Bangers": "Luckiest Guy", "GothamBlack": "Noto Sans Black", "BuilderSans": "Noto Sans", "Montserrat": "Noto Sans", } # 한글·한자·이모지는 로블록스도 대체 글꼴로 그립니다. FALLBACK = "Noto Sans CJK KR, Noto Color Emoji" def surface_png(path): return cairo.ImageSurface.create_from_png(path) _img_cache = {} def image_surface(asset): num = "".join(ch for ch in str(asset) if ch.isdigit()) path = IMAGES.get(num) if not path: return None if path not in _img_cache: _img_cache[path] = surface_png(path) return _img_cache[path] def udim(u, size, k): return u[0] * size + u[1] * k def round_rect(c, x, y, w, h, r): r = max(0, min(r, w / 2, h / 2)) if r <= 0.01: c.rectangle(x, y, w, h) return c.new_sub_path() c.arc(x + w - r, y + r, r, -math.pi / 2, 0) c.arc(x + w - r, y + h - r, r, 0, math.pi / 2) c.arc(x + r, y + h - r, r, math.pi / 2, math.pi) c.arc(x + r, y + r, r, math.pi, 3 * math.pi / 2) c.close_path() def gradient_pattern(g, x, y, w, h, base, alpha): """UIGradient를 cairo 패턴으로. base(색)·alpha(불투명도)에 곱합니다.""" rot = math.radians(g.get("Rotation", 0)) ox, oy = g.get("Offset", [0, 0]) cx, cy = x + w / 2 + ox * w, y + h / 2 + oy * h dx, dy = math.cos(rot), math.sin(rot) # 회전된 방향으로 상자를 덮는 길이 half = (abs(dx) * w + abs(dy) * h) / 2 pat = cairo.LinearGradient(cx - dx * half, cy - dy * half, cx + dx * half, cy + dy * half) colors = g.get("Color") or [[0, [1, 1, 1]], [1, [1, 1, 1]]] trans = g.get("Transparency") or [[0, 0], [1, 0]] times = sorted(set([t for t, _ in colors] + [t for t, _ in trans])) def at(seq, t): for i in range(len(seq) - 1): t0, v0 = seq[i] t1, v1 = seq[i + 1] if t0 <= t <= t1: f = 0 if t1 == t0 else (t - t0) / (t1 - t0) if isinstance(v0, list): return [v0[j] + (v1[j] - v0[j]) * f for j in range(3)] return v0 + (v1 - v0) * f return seq[-1][1] if t >= seq[-1][0] else seq[0][1] for t in times: col = at(colors, t) tr = at(trans, t) pat.add_color_stop_rgba(t, base[0] * col[0], base[1] * col[1], base[2] * col[2], alpha * (1 - tr)) return pat class Renderer: def __init__(self, c): self.c = c # ---------------------------------------------------------------- 배치 def children_rects(self, node, rect, k): """자식 GuiObject의 (자식, x, y, w, h, k) 목록. UIListLayout·UIPadding·UIScale 반영.""" x, y, w, h = rect pad = node.get("UIPadding") if pad: pl = udim(pad["Left"], w, k) pr = udim(pad["Right"], w, k) pt = udim(pad["Top"], h, k) pb = udim(pad["Bottom"], h, k) x, y, w, h = x + pl, y + pt, w - pl - pr, h - pt - pb out = [] kids = [ch for ch in node.get("children", []) if ch.get("Visible", True)] for ch in kids: s = ch.get("UIScale", 1) sc = ch.get("SizeConstraint", "RelativeXY") cw = udim(ch["Size"][0], h if sc == "RelativeYY" else w, k) * s chh = udim(ch["Size"][1], w if sc == "RelativeXX" else h, k) * s ar = ch.get("UIAspectRatio") if ar: if cw / max(chh, 1e-6) > ar: cw = chh * ar else: chh = cw / ar out.append([ch, cw, chh, k * s]) lay = node.get("UIListLayout") if lay: horiz = lay.get("FillDirection") == "Horizontal" gap = udim(lay.get("Padding", [0, 0]), w if horiz else h, k) items = sorted(out, key=lambda o: (o[0].get("LayoutOrder", 0), o[0].get("_i", 0))) \ if lay.get("SortOrder") == "LayoutOrder" else sorted(out, key=lambda o: o[0].get("Name", "")) total = sum((o[1] if horiz else o[2]) for o in items) + gap * max(0, len(items) - 1) ha = lay.get("HorizontalAlignment", "Left") va = lay.get("VerticalAlignment", "Top") if horiz: cur = x + {"Left": 0, "Center": (w - total) / 2, "Right": w - total}[ha] else: cur = y + {"Top": 0, "Center": (h - total) / 2, "Bottom": h - total}[va] res = [] for ch, cw, chh, kk in items: if horiz: cy = y + {"Top": 0, "Center": (h - chh) / 2, "Bottom": h - chh}[va] res.append((ch, cur, cy, cw, chh, kk)) cur += cw + gap else: cx = x + {"Left": 0, "Center": (w - cw) / 2, "Right": w - cw}[ha] res.append((ch, cx, cur, cw, chh, kk)) cur += chh + gap return res res = [] for ch, cw, chh, kk in out: s = ch.get("UIScale", 1) # UIScale은 AnchorPoint를 기준으로 크기를 바꿉니다. bw, bh = cw / s, chh / s ax, ay = ch.get("AnchorPoint", [0, 0]) px = x + udim(ch["Position"][0], w, k) - ax * bw py = y + udim(ch["Position"][1], h, k) - ay * bh px -= (cw - bw) * ax py -= (chh - bh) * ay res.append((ch, px, py, cw, chh, kk)) return res # ---------------------------------------------------------------- 그리기 def draw_node(self, node, x, y, w, h, k): c = self.c c.save() rot = node.get("Rotation", 0) if rot: c.translate(x + w / 2, y + h / 2) c.rotate(math.radians(rot)) c.translate(-(x + w / 2), -(y + h / 2)) corner = node.get("UICorner") r = udim(corner, min(w, h), k) if corner else 0 grad = node.get("UIGradient") bt = node.get("BackgroundTransparency", 1) if bt < 1 and node["ClassName"] not in ("ScreenGui",): base = node.get("BackgroundColor3", [1, 1, 1]) round_rect(c, x, y, w, h, r) if grad: c.set_source(gradient_pattern(grad, x, y, w, h, base, 1 - bt)) else: c.set_source_rgba(*base, 1 - bt) c.fill() img = node.get("Image") if img: self.draw_image(node, x, y, w, h, r, grad) if "Text" in node and node.get("Text"): self.draw_text(node, x, y, w, h, k, grad) for st in node.get("UIStrokes", []): if st.get("ApplyStrokeMode") == "Border" and st.get("Enabled", True): t = st["Thickness"] * k round_rect(c, x - t / 2, y - t / 2, w + t, h + t, r + t / 2 if r > 0 else 0) c.set_line_width(t) c.set_line_join(cairo.LINE_JOIN_ROUND) sg = st.get("UIGradient") if sg: c.set_source(gradient_pattern(sg, x, y, w, h, st["Color"], 1 - st.get("Transparency", 0))) else: c.set_source_rgba(*st["Color"], 1 - st.get("Transparency", 0)) c.stroke() if node.get("ClipsDescendants") or node["ClassName"] == "ScrollingFrame": round_rect(c, x, y, w, h, r) c.clip() cpx, cpy = node.get("CanvasPosition", [0, 0]) kids = self.children_rects(node, (x - cpx * k, y - cpy * k, w, h), k) kids.sort(key=lambda t: (t[0].get("ZIndex", 1), t[0].get("_i", 0))) for ch, cx, cy, cw, chh, kk in kids: self.draw_node(ch, cx, cy, cw, chh, kk) c.restore() def draw_image(self, node, x, y, w, h, r, grad): surf = image_surface(node["Image"]) c = self.c if surf is None: c.rectangle(x, y, w, h) c.set_source_rgba(1, 0, 1, 0.5) c.fill() return ox, oy = node.get("ImageRectOffset", [0, 0]) sw, sh = node.get("ImageRectSize", [0, 0]) if sw == 0 or sh == 0: sw, sh = surf.get_width(), surf.get_height() dw, dh = w, h if node.get("ScaleType") == "Fit": s = min(w / sw, h / sh) dw, dh = sw * s, sh * s dx, dy = x + (w - dw) / 2, y + (h - dh) / 2 c.save() round_rect(c, x, y, w, h, r) c.clip() c.translate(dx, dy) c.scale(dw / sw, dh / sh) c.translate(-ox, -oy) alpha = 1 - node.get("ImageTransparency", 0) col = node.get("ImageColor3", [1, 1, 1]) c.rectangle(ox, oy, sw, sh) c.clip() if col != [1, 1, 1] or grad: # 색 곱하기: 그림을 마스크로 쓰고 색을 곱한 그림을 그립니다. tmp = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(sw), int(sh)) tc = cairo.Context(tmp) tc.set_source_surface(surf, -ox, -oy) tc.paint() tc.set_operator(cairo.OPERATOR_MULTIPLY) if grad: tc.set_source(gradient_pattern(grad, 0, 0, sw, sh, col, 1)) else: tc.set_source_rgb(*col) tc.paint() tc.set_operator(cairo.OPERATOR_DEST_IN) tc.set_source_surface(surf, -ox, -oy) tc.paint() c.set_source_surface(tmp, ox, oy) else: c.set_source_surface(surf, 0, 0) c.get_source().set_filter(cairo.FILTER_GOOD) c.paint_with_alpha(alpha) c.restore() def layout_text(self, node, size, width, wrap): fam = FONT_FAMILY.get(node.get("Font", "FredokaOne"), "Noto Sans") weight = WEIGHT.get(node.get("Weight", ""), 400) if fam.startswith("Fredoka"): weight = 600 elif "Black" in fam: weight = 900 align = node.get("TextXAlignment", "Center") return Layout(self.c, fam.replace(" SemiBold", "").replace(" Black", ""), weight, size, node["Text"], width, wrap, align) def draw_text(self, node, x, y, w, h, k, grad): c = self.c pad = node.get("UIPadding") if pad: pl, pr = udim(pad["Left"], w, k), udim(pad["Right"], w, k) pt, pb = udim(pad["Top"], h, k), udim(pad["Bottom"], h, k) x, y, w, h = x + pl, y + pt, w - pl - pr, h - pt - pb wrap = node.get("TextWrapped", False) or node.get("TextScaled", False) maxsize = node.get("MaxTextSize", 100) if node.get("TextScaled"): lo, hi = 1, min(maxsize, 100) * k best = lo while hi - lo > 0.5: mid = (lo + hi) / 2 lay = self.layout_text(node, mid, w, wrap) ink, logical = lay.extents() # 단어 중간에서 줄이 끊기면 안 맞는 것으로 봅니다(로블록스 TextScaled와 비슷하게). words_ok = lay.lines() <= max(1, len(node["Text"].split())) + node["Text"].count("\n") if logical.width <= w + 0.5 and logical.height <= h + 0.5 and words_ok: best = mid lo = mid else: hi = mid size = best else: size = node.get("TextSize", 14) * k lay = self.layout_text(node, size, w, wrap) ink, logical = lay.extents() ya = node.get("TextYAlignment", "Center") ty = y + {"Top": 0, "Center": (h - logical.height) / 2, "Bottom": h - logical.height}[ya] tx = x if not wrap: xa = node.get("TextXAlignment", "Center") tx = x + {"Left": 0, "Center": (w - logical.width) / 2, "Right": w - logical.width}[xa] c.save() c.move_to(tx, ty) lay.path(c) alpha = 1 - node.get("TextTransparency", 0) for st in node.get("UIStrokes", []): if st.get("ApplyStrokeMode", "Contextual") == "Contextual" and st.get("Enabled", True): c.set_line_width(st["Thickness"] * k * 2) c.set_line_join(cairo.LINE_JOIN_ROUND) c.set_source_rgba(*st["Color"], alpha * (1 - st.get("Transparency", 0))) c.stroke_preserve() if node.get("TextStrokeTransparency", 1) < 1: c.set_line_width(2 * k) c.set_source_rgba(*node.get("TextStrokeColor3", [0, 0, 0]), alpha * (1 - node["TextStrokeTransparency"])) c.stroke_preserve() c.new_path() c.restore() # 글자 채우기(이모지 색을 살리려고 path 대신 show_layout) c.save() col = node.get("TextColor3", [0, 0, 0]) if grad and node.get("TextGradient", True): c.push_group() c.move_to(tx, ty) c.set_source_rgba(1, 1, 1, alpha) lay.show(c) mask = c.pop_group() c.set_source(gradient_pattern(grad, x, y, w, h, col, 1)) c.mask(mask) else: c.move_to(tx, ty) c.set_source_rgba(*col, alpha) lay.show(c) c.restore() def render(dump, out, bg=None): W, H, inset = dump["width"], dump["height"], dump.get("inset", 0) surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(W), int(H + inset)) c = cairo.Context(surf) if bg and os.path.exists(bg): b = surface_png(bg) c.save() c.scale(W / b.get_width(), (H + inset) / b.get_height()) c.set_source_surface(b, 0, 0) c.paint() c.restore() else: g = cairo.LinearGradient(0, 0, 0, H + inset) g.add_color_stop_rgb(0, 0.55, 0.78, 0.95) g.add_color_stop_rgb(0.55, 0.75, 0.88, 0.98) g.add_color_stop_rgb(0.56, 0.42, 0.66, 0.36) g.add_color_stop_rgb(1, 0.33, 0.55, 0.28) c.set_source(g) c.paint() # 로블록스 상단 바(대략) if inset: c.set_source_rgba(0, 0, 0, 0.25) for i, x in enumerate((12, 60)): round_rect(c, x, 10, 40, 40, 10) c.fill() touch = dump.get("touch") if touch and dump.get("zones"): for z in dump["zones"].values(): c.set_source_rgba(1, 1, 1, 0.12) c.rectangle(z["x"], z["y"] + inset, z["w"], z["h"]) c.fill() # 조이스틱·점프 버튼 모양(대략) st = dump["zones"]["stick"] c.arc(st["x"] + 110, inset + H - 110, 60, 0, 2 * math.pi) c.set_source_rgba(0, 0, 0, 0.3) c.fill() jp = dump["zones"]["jump"] jr = min(jp["w"], jp["h"]) * 0.3 c.arc(jp["x"] + jp["w"] * 0.55, inset + jp["y"] + jp["h"] * 0.55, jr, 0, 2 * math.pi) c.fill() r = Renderer(c) gui = dump["gui"] c.translate(0, inset) for ch, x, y, w, h, k in r.children_rects(gui, (0, 0, W, H), 1): r.draw_node(ch, x, y, w, h, k) surf.write_to_png(out) def main(argv): src, outdir = argv[0], argv[1] bg = argv[argv.index("--bg") + 1] if "--bg" in argv else None with open(src) as f: data = json.load(f) for num, path in data.get("images", {}).items(): IMAGES[str(num)] = os.path.join(ROOT, path) os.makedirs(outdir, exist_ok=True) for shot in data["shots"]: out = os.path.join(outdir, shot["name"] + ".png") render(shot, out, bg) print(out) if __name__ == "__main__": main(sys.argv[1:])