tools(bunsik): 장면 덤프와 간이 3D 미리보기 렌더러(배치 확인용)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-12 01:36:17 +09:00
parent 802ba10e1a
commit ebfe23c509
3 changed files with 281 additions and 4 deletions

View File

@@ -0,0 +1,97 @@
-- 미리보기용 장면 덤프: 맵과 가게 두 곳(1단계 중간, 2단계 전부 산 상태)을 짓고 모든 파트를 JSON으로 돌려줍니다.
-- python3 tools/cloud.py run tests/cloud/dump_scene.luau --version N --out .cache/scene.json
-- python3 tools/render.py .cache/scene.json
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local ServerScriptService = game:GetService("ServerScriptService")
local Server = ServerScriptService.Server
local World = require(Server.World)
local Npc = require(Server.Npc)
local PlotController = require(Server.PlotController)
local PlotBuilder = require(Server.PlotBuilder)
local PlotLayout = require(Server.PlotLayout)
local Data = require(Server.Data)
local slots = World.build()
Npc.preload()
local function shop(slot, bought: number, withChar: boolean)
local data = table.clone(Data.TEMPLATE)
data.PurchaseIdCache = {}
data.Bought = bought
data.TutorialDone = true
local char: Model? = nil
if withChar then
char = Players:CreateHumanoidModelFromDescription(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15)
local c = char :: Model
c.Parent = workspace
local root = c:FindFirstChild("HumanoidRootPart") :: BasePart
root.Anchored = true
local pos = PlotBuilder.world(slot.cf, PlotLayout.STOVE + Vector3.new(0, 0, 4.5))
c:PivotTo(CFrame.lookAt(pos + Vector3.new(0, 3, 0), pos + Vector3.new(0, 3, 10)))
end
local owner = Instance.new("Folder")
owner.Parent = ServerScriptService
local c = PlotController.new(slot, owner, {
userId = slot.index,
displayName = "Player" .. slot.index,
data = data,
now = 0,
getCharacter = function()
return char
end,
})
-- 손님을 채우고 몇 명은 먹는 중으로
local t = 0
for _ = 1, 400 do
t += 0.1
c:update(t)
end
local n = 0
for id, cust in c.shop.customers do
if cust.state == "waiting" and n < 2 then
c.shop.hand = { cust.menu }
c:serve(id)
n += 1
end
end
if withChar then
c:cook()
end
return c
end
shop(slots[2], #require(game:GetService("ReplicatedStorage").Shared.Economy).PURCHASES, true)
shop(slots[1], 6, false)
shop(slots[3], 0, false)
task.wait(0.5)
local parts = {}
for _, d in workspace:GetDescendants() do
if d:IsA("BasePart") and d.Transparency < 0.95 then
local shape = "Block"
if d:IsA("Part") then
shape = d.Shape.Name
elseif d:IsA("WedgePart") then
shape = "Wedge"
end
local cf = d.CFrame
local x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 = cf:GetComponents()
local col = d.Color
table.insert(parts, {
s = shape,
c = { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 },
z = { d.Size.X, d.Size.Y, d.Size.Z },
k = { math.floor(col.R * 255), math.floor(col.G * 255), math.floor(col.B * 255) },
t = d.Transparency,
m = d.Material.Name,
})
end
end
print("parts", #parts)
local json = HttpService:JSONEncode(parts)
return {
BinaryOutput = buffer.fromstring(json),
ReturnValues = { #parts },
}

View File

@@ -2,7 +2,7 @@
"""Open Cloud 도구: 게임 파일 업로드, 로블록스 서버에서 Luau 실행.
python3 tools/cloud.py publish build/BunsikTycoon.rbxl [--published]
python3 tools/cloud.py run script.luau [--version N] # 기본: 가장 최근 저장 버전
python3 tools/cloud.py run script.luau [--version N] [--out file] # 기본: 가장 최근 저장 버전
python3 tools/cloud.py products # 게임패스·개발자 상품 만들기(이미 있으면 건너뜀)
python3 tools/cloud.py place # 서버 인원 6명, 설명 설정
@@ -55,15 +55,21 @@ def publish(path, published=False):
return res["versionNumber"]
def run(script, version=None, timeout_s=300):
def run(script, version=None, timeout_s=300, binary_out=None):
base = f"https://apis.roblox.com/cloud/v2/universes/{UNIVERSE}/places/{PLACE}"
if version:
base += f"/versions/{version}"
task = request("POST", base + "/luau-execution-session-tasks", {"script": script, "timeout": f"{timeout_s}s"})
body = {"script": script, "timeout": f"{timeout_s}s"}
if binary_out:
body["enableBinaryOutput"] = True
task = request("POST", base + "/luau-execution-session-tasks", body)
path = task["path"]
while task.get("state") not in ("COMPLETE", "FAILED", "CANCELLED"):
time.sleep(3)
task = request("GET", f"https://apis.roblox.com/cloud/v2/{path}")
if binary_out and task.get("binaryOutputUri"):
with urllib.request.urlopen(task["binaryOutputUri"], timeout=120) as r, open(binary_out, "wb") as f:
f.write(r.read())
logs = request("GET", f"https://apis.roblox.com/cloud/v2/{path}/logs?maxPageSize=10000")
lines = []
for page in logs.get("luauExecutionSessionTaskLogs", []):
@@ -154,7 +160,8 @@ def main(argv):
version = int(argv[argv.index("--version") + 1])
with open(argv[1]) as f:
script = f.read()
task, lines = run(script, version)
out = argv[argv.index("--out") + 1] if "--out" in argv else None
task, lines = run(script, version, binary_out=out)
for line in lines:
print(line)
print(f"state: {task['state']}")

View File

@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""장면 덤프(JSON)를 간단한 3D 그림으로 그립니다. 서버에서 화면을 볼 수 없어 배치 확인용으로 씁니다.
로블록스 렌더링과 다르고(조명·질감·애니메이션 없음), 파트 위치·크기·색만 맞습니다.
python3 tools/render.py .cache/scene.json out.png --eye x,y,z --at x,y,z [--size 1280x720]
"""
import argparse
import json
import math
import numpy as np
from PIL import Image
def box_mesh():
v = np.array([[x, y, z] for x in (-0.5, 0.5) for y in (-0.5, 0.5) for z in (-0.5, 0.5)])
f = [(0, 1, 3), (0, 3, 2), (4, 6, 7), (4, 7, 5), (0, 4, 5), (0, 5, 1),
(2, 3, 7), (2, 7, 6), (0, 2, 6), (0, 6, 4), (1, 5, 7), (1, 7, 3)]
return v, f
def wedge_mesh():
# 로블록스 WedgePart: 아래 면 전체, 뒤(-Z) 면 전체, 경사면은 위-뒤에서 아래-앞으로
v = np.array([[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, -0.5, 0.5], [0.5, -0.5, 0.5],
[-0.5, 0.5, -0.5], [0.5, 0.5, -0.5]])
f = [(0, 1, 3), (0, 3, 2), (0, 4, 5), (0, 5, 1), (2, 3, 5), (2, 5, 4), (0, 2, 4), (1, 5, 3)]
return v, f
def cyl_mesh(n=14):
# 축은 X
v = []
for x in (-0.5, 0.5):
for i in range(n):
a = 2 * math.pi * i / n
v.append([x, 0.5 * math.cos(a), 0.5 * math.sin(a)])
v.append([-0.5, 0, 0])
v.append([0.5, 0, 0])
f = []
for i in range(n):
j = (i + 1) % n
f += [(i, j, n + j), (i, n + j, n + i), (2 * n, j, i), (2 * n + 1, n + i, n + j)]
return np.array(v), f
def ball_mesh(lat=7, lon=12):
v = []
for i in range(lat + 1):
th = math.pi * i / lat
for j in range(lon):
ph = 2 * math.pi * j / lon
v.append([0.5 * math.sin(th) * math.cos(ph), 0.5 * math.cos(th), 0.5 * math.sin(th) * math.sin(ph)])
f = []
for i in range(lat):
for j in range(lon):
a = i * lon + j
b = i * lon + (j + 1) % lon
c = (i + 1) * lon + j
d = (i + 1) * lon + (j + 1) % lon
f += [(a, c, d), (a, d, b)]
return np.array(v), f
MESHES = {"Block": box_mesh(), "Wedge": wedge_mesh(), "Cylinder": cyl_mesh(), "Ball": ball_mesh()}
def triangles(parts):
tris, cols = [], []
for p in parts:
v, f = MESHES.get(p["s"], MESHES["Block"])
c = p["c"]
pos = np.array(c[:3])
rot = np.array(c[3:]).reshape(3, 3)
size = np.array(p["z"])
w = (v * size) @ rot.T + pos
col = np.array(p["k"], dtype=float)
if p["m"] == "Neon":
col = np.minimum(col * 1.25 + 30, 255)
for a, b, d in f:
tris.append(w[[a, b, d]])
cols.append((col, p["t"], p["m"] == "Neon"))
return np.array(tris), cols
def render(parts, eye, at, w, h, fov=55):
tris, cols = triangles(parts)
eye, at = np.array(eye, float), np.array(at, float)
fwd = at - eye
fwd /= np.linalg.norm(fwd)
right = np.cross(fwd, [0, 1, 0])
right /= np.linalg.norm(right)
up = np.cross(right, fwd)
rel = tris - eye
cx = rel @ right
cy = rel @ up
cz = rel @ fwd
f = 0.5 * h / math.tan(math.radians(fov) / 2)
img = np.zeros((h, w, 3))
# 하늘
for y in range(h):
t = y / h
img[y] = np.array([150, 200, 250]) * (1 - t) + np.array([210, 230, 250]) * t
zbuf = np.full((h, w), np.inf)
light = np.array([0.4, 0.85, 0.35])
light /= np.linalg.norm(light)
order = np.argsort([1 if c[1] > 0.3 else 0 for c in cols], kind="stable") # 투명은 나중에
for i in order:
z = cz[i]
if np.any(z < 0.5):
continue
sx = w / 2 + f * cx[i] / z
sy = h / 2 - f * cy[i] / z
x0, x1 = int(max(0, math.floor(sx.min()))), int(min(w - 1, math.ceil(sx.max())))
y0, y1 = int(max(0, math.floor(sy.min()))), int(min(h - 1, math.ceil(sy.max())))
if x0 > x1 or y0 > y1:
continue
t = tris[i]
n = np.cross(t[1] - t[0], t[2] - t[0])
nn = np.linalg.norm(n)
if nn == 0:
continue
n /= nn
if np.dot(n, eye - t[0]) < 0:
n = -n
col, tr, neon = cols[i]
shade = 1.0 if neon else 0.55 + 0.45 * max(0.0, float(np.dot(n, light)))
rgb = np.clip(col * shade, 0, 255)
xs, ys = np.meshgrid(np.arange(x0, x1 + 1) + 0.5, np.arange(y0, y1 + 1) + 0.5)
(ax, bx, cx_), (ay, by, cy_) = sx, sy
den = (by - cy_) * (ax - cx_) + (cx_ - bx) * (ay - cy_)
if abs(den) < 1e-9:
continue
l1 = ((by - cy_) * (xs - cx_) + (cx_ - bx) * (ys - cy_)) / den
l2 = ((cy_ - ay) * (xs - cx_) + (ax - cx_) * (ys - cy_)) / den
l3 = 1 - l1 - l2
inside = (l1 >= -1e-6) & (l2 >= -1e-6) & (l3 >= -1e-6)
if not inside.any():
continue
iz = l1 / z[0] + l2 / z[1] + l3 / z[2]
depth = 1 / np.where(iz > 0, iz, 1e-9)
sub = zbuf[y0:y1 + 1, x0:x1 + 1]
m = inside & (depth < sub)
if tr > 0.3:
a = 1 - tr
region = img[y0:y1 + 1, x0:x1 + 1]
region[m] = region[m] * (1 - a) + rgb * a
else:
sub[m] = depth[m]
img[y0:y1 + 1, x0:x1 + 1][m] = rgb
return Image.fromarray(img.astype(np.uint8))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("scene")
ap.add_argument("out")
ap.add_argument("--eye", default="0,120,160")
ap.add_argument("--at", default="0,0,0")
ap.add_argument("--size", default="1280x720")
ap.add_argument("--fov", type=float, default=55)
a = ap.parse_args()
with open(a.scene) as f:
parts = json.load(f)
w, h = map(int, a.size.split("x"))
eye = [float(x) for x in a.eye.split(",")]
at = [float(x) for x in a.at.split(",")]
# 큰 것(바닥)부터 그려도 z-버퍼가 있으니 순서는 상관없음
render(parts, eye, at, w, h, a.fov).save(a.out)
print(a.out)
if __name__ == "__main__":
main()