UnboundRun-data / code /pk /render.py
teawhite's picture
Update dataset card, summaries, previews, thumbnails and code
2258c8d verified
Raw History Blame Contribute Delete
11.2 kB
"""Lightweight whitebox renderer (OpenGL 3.3 via moderngl): instanced boxes / cylinders + capsule body.
Fixed world-space lighting independent of the RGB appearance; black sky; logarithmic depth so 1 cm..10 km
needs no tuning. Same camera model as the UE capture (horizontal FOV, UE rotator, cm).
mode='shade' -> grey whitebox (HxWx3 uint8); mode='ids' -> semantic class per pixel (HxW uint8, 0 = sky).
"""
import math
import numpy as np
from .motion import rot_matrix
VS = """
#version 330
in vec3 in_pos; in vec3 in_nrm;
in vec3 i_a0; in vec3 i_a1; in vec3 i_a2; in vec3 i_t;
in vec3 i_n0; in vec3 i_n1; in vec3 i_n2; in vec2 i_ac;
uniform mat4 u_vp; uniform vec3 u_eye;
out vec3 v_n; out float v_w; out float v_d; flat out vec2 v_ac;
void main(){
vec3 w = mat3(i_a0, i_a1, i_a2) * in_pos + i_t;
v_n = normalize(mat3(i_n0, i_n1, i_n2) * in_nrm);
vec4 c = u_vp * vec4(w, 1.0);
v_w = c.w; v_d = length(w - u_eye); v_ac = i_ac;
gl_Position = c;
}
"""
FS = """
#version 330
in vec3 v_n; in float v_w; in float v_d; flat in vec2 v_ac;
uniform float u_logfar; uniform int u_mode;
layout(location = 0) out vec4 f_color;
layout(location = 1) out vec4 f_geo;
void main(){
gl_FragDepth = log2(max(1e-6, 1.0 + v_w)) / u_logfar;
vec3 n = normalize(v_n);
f_geo = vec4(n, v_w);
if(u_mode == 1){ f_color = vec4(v_ac.y / 255.0, 0.0, 0.0, 1.0); return; }
vec3 l1 = normalize(vec3(0.55, 0.35, 0.75));
vec3 l2 = normalize(vec3(-0.70, 0.50, 0.20));
float s = 0.18 + 0.22 * (0.6 + 0.4 * n.z) + 0.45 * max(dot(n, l1), 0.0) + 0.25 * max(dot(n, l2), 0.0);
s *= v_ac.x;
s *= 1.0 - 0.45 * smoothstep(3000.0, 80000.0, v_d);
vec3 col = vec3(s);
if(abs(v_ac.y - 7.0) < 0.5) col = s * vec3(1.15, 0.92, 0.36); // coins: gold tint in every scene
else if(abs(v_ac.y - 8.0) < 0.5) col = s * vec3(0.80, 0.76, 0.72); // falling rocks / debris
f_color = vec4(clamp(col, 0.0, 1.0), 1.0);
}
"""
# screen-space contour lines: depth or normal discontinuities darken the pixel (fading with distance), so faces with the
# same orientation at different depths (an obstacle top in front of the roof, window frames) stay separable.
QVS = """
#version 330
out vec2 v_uv;
void main(){ vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); v_uv = p; gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }
"""
QFS = """
#version 330
in vec2 v_uv; uniform sampler2D u_col; uniform sampler2D u_geo; uniform vec2 u_px; uniform float u_strength;
out vec4 f_color;
void main(){
vec3 c = texture(u_col, v_uv).rgb;
vec4 g = texture(u_geo, v_uv);
float w = g.w;
float e = 0.0;
vec2 offs[4] = vec2[](vec2(u_px.x, 0.0), vec2(-u_px.x, 0.0), vec2(0.0, u_px.y), vec2(0.0, -u_px.y));
for(int i = 0; i < 4; i++){
vec4 q = texture(u_geo, v_uv + offs[i]);
float wa = (w <= 0.0) ? 1e9 : w, wb = (q.w <= 0.0) ? 1e9 : q.w;
float dz = abs(wa - wb) / min(wa, wb);
float en = (w > 0.0 && q.w > 0.0) ? 1.0 - clamp(dot(g.xyz, q.xyz), 0.0, 1.0) : 0.0;
e = max(e, max(smoothstep(0.015, 0.06, dz), smoothstep(0.15, 0.5, en)));
}
float near = min(w <= 0.0 ? 1e9 : w, 1e9);
float fade = 1.0 - smoothstep(4000.0, 25000.0, near);
c *= 1.0 - u_strength * e * fade;
f_color = vec4(c, 1.0);
}
"""
SCENE_ALBEDO, BODY_ALBEDO = 0.85, 1.0
def _cube():
v = []
for ax in range(3):
for sg in (-1, 1):
n = [0, 0, 0]; n[ax] = sg
u, w = [a for a in range(3) if a != ax]
quad = []
for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
p = [0.0, 0.0, 0.0]; p[ax] = .5 * sg; p[u] = .5 * a; p[w] = .5 * b
quad.append(p)
for i in (0, 1, 2, 0, 2, 3):
v.append(quad[i] + n)
return np.array(v, 'f4')
def _cylinder(seg=32):
v = []
for i in range(seg):
a0, a1 = 2 * math.pi * i / seg, 2 * math.pi * (i + 1) / seg
c0, s0, c1, s1 = math.cos(a0), math.sin(a0), math.cos(a1), math.sin(a1)
p = lambda c, s, z: [.5 * c, .5 * s, z]
for q in ((c0, s0, -.5), (c1, s1, -.5), (c1, s1, .5), (c0, s0, -.5), (c1, s1, .5), (c0, s0, .5)):
v.append(p(*q) + [q[0], q[1], 0.0])
for z, sg in ((.5, 1), (-.5, -1)):
for q in ((0, 0), (c0, s0), (c1, s1)):
v.append([.5 * q[0], .5 * q[1], z, 0.0, 0.0, float(sg)])
return np.array(v, 'f4')
def _sphere(nu=12, nv=20):
v = []
for i in range(nu):
t0, t1 = math.pi * i / nu, math.pi * (i + 1) / nu
for j in range(nv):
p0, p1 = 2 * math.pi * j / nv, 2 * math.pi * (j + 1) / nv
pts = [(t0, p0), (t1, p0), (t1, p1), (t0, p0), (t1, p1), (t0, p1)]
for t, p in pts:
n = [math.sin(t) * math.cos(p), math.sin(t) * math.sin(p), math.cos(t)]
v.append([.5 * n[0], .5 * n[1], .5 * n[2]] + n)
return np.array(v, 'f4')
def _instances(A, T, albedo, cls):
"""A: (n,3,3) linear maps (columns = images of the unit axes), T: (n,3) translations."""
A = np.asarray(A, 'f8').reshape(-1, 3, 3)
N = np.transpose(np.linalg.inv(A), (0, 2, 1))
n = len(A)
out = np.zeros((n, 26), 'f4')
out[:, 0:3], out[:, 3:6], out[:, 6:9] = A[:, :, 0], A[:, :, 1], A[:, :, 2]
out[:, 9:12] = T
out[:, 12:15], out[:, 15:18], out[:, 18:21] = N[:, :, 0], N[:, :, 1], N[:, :, 2]
out[:, 21] = albedo; out[:, 22] = cls
return out[:, :23]
def prim_instances(prims):
"""prims: iterable of (shape, c, s, rot, cls, mat) -> dict shape -> instance array."""
groups = {0: ([], [], []), 1: ([], [], []), 2: ([], [], [])}
for shape, c, s, r, cls, _ in prims:
M = rot_matrix(*r) # rows = rotated axes
A = (M.T * np.asarray(s, float)[None, :]) # column j = axis_j * size_j
g = groups[int(shape)]
g[0].append(A); g[1].append(c); g[2].append(cls)
out = {}
for k, (A, T, C) in groups.items():
if A:
inst = _instances(np.array(A), np.array(T, float), SCENE_ALBEDO, 0)
inst[:, 22] = np.array(C, 'f4')
out[k] = inst
return out
def capsule_instances(caps, cls=10):
cyl_A, cyl_T, sph_A, sph_T = [], [], [], []
for a, b, r in caps:
a, b = np.asarray(a, float), np.asarray(b, float)
ax = b - a; ln = np.linalg.norm(ax)
if ln < 1e-3:
continue
z = ax / ln
x = np.cross(z, [0, 0, 1.0]) if abs(z[2]) < .9 else np.cross(z, [1.0, 0, 0])
x /= np.linalg.norm(x); y = np.cross(z, x)
cyl_A.append(np.stack([x * 2 * r, y * 2 * r, ax], 1)); cyl_T.append((a + b) / 2)
for p in (a, b):
sph_A.append(np.eye(3) * 2 * r); sph_T.append(p)
out = {}
if cyl_A:
out[1] = _instances(np.array(cyl_A), np.array(cyl_T), BODY_ALBEDO, cls)
out[2] = _instances(np.array(sph_A), np.array(sph_T), BODY_ALBEDO, cls)
return out
def view_proj(cam, width, height, near=2.0, far=2.0e6):
x, y, z, pitch, yaw, roll, fov = cam
M = rot_matrix(pitch, yaw, roll)
fwd, right, up = M[0], M[1], M[2]
eye = np.array([x, y, z])
V = np.eye(4)
V[0, :3], V[1, :3], V[2, :3] = right, up, -fwd
V[:3, 3] = -V[:3, :3] @ eye
th = math.tan(math.radians(fov) * .5)
tv = th / (width / height)
P = np.zeros((4, 4))
P[0, 0], P[1, 1] = 1 / th, 1 / tv
P[2, 2], P[2, 3] = -(far + near) / (far - near), -2 * far * near / (far - near)
P[3, 2] = -1
return P @ V, eye
class WhiteboxRenderer:
def __init__(self, width=1280, height=704, ctx=None, backend=None):
import moderngl
self.mgl = moderngl
if ctx is None:
ctx = moderngl.create_standalone_context(backend=backend) if backend else moderngl.create_standalone_context()
self.ctx, self.w, self.h = ctx, width, height
self.prog = ctx.program(vertex_shader=VS, fragment_shader=FS)
self.col_tex = ctx.texture((width, height), 4)
self.geo_tex = ctx.texture((width, height), 4, dtype='f4')
for t in (self.col_tex, self.geo_tex):
t.filter = (moderngl.NEAREST, moderngl.NEAREST); t.repeat_x = False; t.repeat_y = False
self.fbo = ctx.framebuffer(color_attachments=[self.col_tex, self.geo_tex], depth_attachment=ctx.depth_renderbuffer((width, height)))
self.out_fbo = ctx.framebuffer(color_attachments=[ctx.renderbuffer((width, height), 4)])
self.qprog = ctx.program(vertex_shader=QVS, fragment_shader=QFS)
self.qvao = ctx.vertex_array(self.qprog, [])
self.edge_strength = 0.55
self.meshes = {0: ctx.buffer(_cube().tobytes()), 1: ctx.buffer(_cylinder().tobytes()), 2: ctx.buffer(_sphere().tobytes())}
self.counts = {0: 36, 1: len(_cylinder()), 2: len(_sphere())}
self.scene = {}
def _vao(self, shape, inst):
ib = self.ctx.buffer(np.ascontiguousarray(inst, 'f4').tobytes())
vao = self.ctx.vertex_array(self.prog, [(self.meshes[shape], '3f 3f', 'in_pos', 'in_nrm'),
(ib, '3f 3f 3f 3f 3f 3f 3f 2f/i', 'i_a0', 'i_a1', 'i_a2', 'i_t', 'i_n0', 'i_n1', 'i_n2', 'i_ac')])
return vao, ib, len(inst)
def set_scene(self, prims, dynamic=()):
"""Static primitives (indices in `dynamic` are skipped: they are drawn per frame via render(dyn=...))."""
for vao, ib, _ in self.scene.values():
vao.release(); ib.release()
skip = set(dynamic)
self.scene = {k: self._vao(k, v) for k, v in prim_instances([p for i, p in enumerate(prims) if i not in skip]).items()}
def render(self, cam, capsules=(), mode='shade', dyn=()):
ctx = self.ctx
self.fbo.use(); ctx.viewport = (0, 0, self.w, self.h)
ctx.enable(self.mgl.DEPTH_TEST); ctx.disable(self.mgl.CULL_FACE)
self.fbo.clear(0, 0, 0, 0, depth=1.0)
VP, eye = view_proj(cam, self.w, self.h)
self.prog['u_vp'].write(VP.T.astype('f4').tobytes())
self.prog['u_eye'].value = tuple(eye)
self.prog['u_logfar'].value = math.log2(1 + 2.0e6)
self.prog['u_mode'].value = 1 if mode == 'ids' else 0
for vao, _, n in self.scene.values():
vao.render(instances=n)
tmp = []
if dyn:
for k, inst in prim_instances(dyn).items():
vao, ib, n = self._vao(k, inst); vao.render(instances=n); tmp.append((vao, ib))
for k, inst in capsule_instances(capsules).items():
vao, ib, n = self._vao(k, inst); vao.render(instances=n); tmp.append((vao, ib))
for vao, ib in tmp:
vao.release(); ib.release()
if mode == 'ids':
data = np.frombuffer(self.fbo.read(components=3, attachment=0), np.uint8).reshape(self.h, self.w, 3)[::-1]
return data[:, :, 0].copy()
self.out_fbo.use(); ctx.disable(self.mgl.DEPTH_TEST)
self.col_tex.use(0); self.geo_tex.use(1)
self.qprog['u_col'].value = 0; self.qprog['u_geo'].value = 1
self.qprog['u_px'].value = (1.0 / self.w, 1.0 / self.h); self.qprog['u_strength'].value = self.edge_strength
self.qvao.render(mode=self.mgl.TRIANGLES, vertices=3)
data = np.frombuffer(self.out_fbo.read(components=3), np.uint8).reshape(self.h, self.w, 3)[::-1]
return data.copy()