Add MechPaint surface shader, 4x4 POM decal atlas & shader, vertex weathering baker, and live GL3 probe
This commit is contained in:
parent
0f36eed3a0
commit
81135e9a83
12 changed files with 2419 additions and 0 deletions
939
tools/decals/build_decal_atlas.py
Normal file
939
tools/decals/build_decal_atlas.py
Normal file
|
|
@ -0,0 +1,939 @@
|
|||
"""Procedural 4x4 hard-surface & combat POM decal trim-sheet atlas generator.
|
||||
|
||||
Outputs three 1024x1024 RGBA/RGB PNG textures under assets/decals/:
|
||||
- decal_atlas_albedo.png (RGBA: sRGB albedo + alpha mask, dilated into alpha=0)
|
||||
- decal_atlas_normal.png (RGB: tangent-space normal map, OpenGL/Godot +X right, +Y down)
|
||||
- decal_atlas_ormh.png (RGBA: R=AO, G=Roughness, B=Metallic, A=Height [1=surface, 0=deep recess])
|
||||
|
||||
4x4 tile layout (256x256 each, row 0 = top):
|
||||
Row 0: (0) louvered armor vent, (1) recessed bolted maintenance hatch,
|
||||
(2) 4-bolt recessed fastener strip, (3) slotted intake grille
|
||||
Row 1: (4) rivet panel seam, (5) welded armor repair patch,
|
||||
(6) recessed lift-lug pocket, (7) weathered hazard caution chevron strip
|
||||
Row 2: (8) tactical stencil "03", (9) tactical stencil "07",
|
||||
(10) radiation/heat warning stencil, (11) faction chevron emblem
|
||||
Row 3: (12) deep AP autocannon penetration hole, (13) diagonal shrapnel/flak armor gouge,
|
||||
(14) molten plasma burn crater, (15) radial blast scorch mark
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUT_DIR = REPO_ROOT / "assets" / "decals"
|
||||
|
||||
TILE_SIZE = 256
|
||||
GRID = 4
|
||||
ATLAS_SIZE = TILE_SIZE * GRID # 1024
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deterministic vectorized noise & SDF primitives (on normalized [-1, 1]^2 tile coords)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _hash2(ix: np.ndarray, iy: np.ndarray, seed: int) -> np.ndarray:
|
||||
n = (ix.astype(np.int64) * 374761393
|
||||
+ iy.astype(np.int64) * 668265263
|
||||
+ np.int64(seed) * 1442695041) & 0xFFFFFFFF
|
||||
n = ((n ^ (n >> 13)) * 1274126177) & 0xFFFFFFFF
|
||||
n = n ^ (n >> 16)
|
||||
return (n & 0xFFFFFF).astype(np.float32) / float(0x1000000)
|
||||
|
||||
|
||||
def value_noise(x: np.ndarray, y: np.ndarray, freq: float, seed: int = 1) -> np.ndarray:
|
||||
px = x * freq
|
||||
py = y * freq
|
||||
ix = np.floor(px).astype(np.int64)
|
||||
iy = np.floor(py).astype(np.int64)
|
||||
fx = px - ix
|
||||
fy = py - iy
|
||||
ux = fx * fx * (3.0 - 2.0 * fx)
|
||||
uy = fy * fy * (3.0 - 2.0 * fy)
|
||||
a = _hash2(ix, iy, seed)
|
||||
b = _hash2(ix + 1, iy, seed)
|
||||
c = _hash2(ix, iy + 1, seed)
|
||||
d = _hash2(ix + 1, iy + 1, seed)
|
||||
return (a * (1.0 - ux) + b * ux) * (1.0 - uy) + (c * (1.0 - ux) + d * ux) * uy
|
||||
|
||||
|
||||
def fbm(x: np.ndarray, y: np.ndarray, base_freq: float, octaves: int = 4, seed: int = 1) -> np.ndarray:
|
||||
acc = np.zeros_like(x, dtype=np.float32)
|
||||
amp = 0.5
|
||||
norm = 0.0
|
||||
f = base_freq
|
||||
for o in range(octaves):
|
||||
acc += amp * value_noise(x, y, f, seed + o * 37)
|
||||
norm += amp
|
||||
amp *= 0.5
|
||||
f *= 2.03
|
||||
return acc / norm
|
||||
|
||||
|
||||
def smoothstep(e0: float, e1: float, x: np.ndarray) -> np.ndarray:
|
||||
t = np.clip((x - e0) / (e1 - e0), 0.0, 1.0)
|
||||
return t * t * (3.0 - 2.0 * t)
|
||||
|
||||
|
||||
def sd_box(x: np.ndarray, y: np.ndarray, cx: float, cy: float, hx: float, hy: float, r: float = 0.0) -> np.ndarray:
|
||||
qx = np.abs(x - cx) - (hx - r)
|
||||
qy = np.abs(y - cy) - (hy - r)
|
||||
out = np.sqrt(np.maximum(qx, 0.0) ** 2 + np.maximum(qy, 0.0) ** 2)
|
||||
ins = np.minimum(np.maximum(qx, qy), 0.0)
|
||||
return out + ins - r
|
||||
|
||||
|
||||
def sd_circle(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray:
|
||||
return np.sqrt((x - cx) ** 2 + (y - cy) ** 2) - r
|
||||
|
||||
|
||||
def sd_segment(x: np.ndarray, y: np.ndarray, ax: float, ay: float, bx: float, by: float) -> np.ndarray:
|
||||
pax = x - ax
|
||||
pay = y - ay
|
||||
bax = bx - ax
|
||||
bay = by - ay
|
||||
denom = bax * bax + bay * bay + 1e-12
|
||||
h = np.clip((pax * bax + pay * bay) / denom, 0.0, 1.0)
|
||||
return np.sqrt((pax - bax * h) ** 2 + (pay - bay * h) ** 2)
|
||||
|
||||
|
||||
def sd_hexagon(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray:
|
||||
px = np.abs(x - cx)
|
||||
py = np.abs(y - cy)
|
||||
# Regular hexagon with flat top/bottom
|
||||
d = np.maximum(px * 0.8660254 + py * 0.5, py) - r
|
||||
return d
|
||||
|
||||
|
||||
def sd_triangle_eq(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray:
|
||||
# Pointing up (-y in image space)
|
||||
px = np.abs(x - cx)
|
||||
py = -(y - cy) + r * 0.25
|
||||
px_k = np.sqrt(3.0)
|
||||
# Standard IQ equilateral triangle SDF
|
||||
px2 = px - r
|
||||
py2 = py + r / px_k
|
||||
cond = (px + px_k * py) > 0.0
|
||||
nx = np.where(cond, (px - px_k * py) * 0.5, px)
|
||||
ny = np.where(cond, (-px_k * px - py) * 0.5, py)
|
||||
nx -= np.clip(nx, -2.0 * r, 0.0)
|
||||
return -np.sqrt(nx * nx + ny * ny) * np.sign(ny)
|
||||
|
||||
|
||||
def tile_coords() -> tuple[np.ndarray, np.ndarray]:
|
||||
lin = np.linspace(-1.0 + 1.0 / TILE_SIZE, 1.0 - 1.0 / TILE_SIZE, TILE_SIZE, dtype=np.float32)
|
||||
yy, xx = np.meshgrid(lin, lin, indexing="ij")
|
||||
return xx, yy
|
||||
|
||||
|
||||
def new_tile() -> dict[str, np.ndarray]:
|
||||
shape = (TILE_SIZE, TILE_SIZE)
|
||||
return {
|
||||
"rgb": np.full((*shape, 3), 0.18, dtype=np.float32),
|
||||
"alpha": np.zeros(shape, dtype=np.float32),
|
||||
"height": np.ones(shape, dtype=np.float32),
|
||||
"rough": np.full(shape, 0.56, dtype=np.float32),
|
||||
"metal": np.full(shape, 0.35, dtype=np.float32),
|
||||
}
|
||||
|
||||
|
||||
def add_hex_bolt(
|
||||
t: dict[str, np.ndarray],
|
||||
x: np.ndarray,
|
||||
y: np.ndarray,
|
||||
cx: float,
|
||||
cy: float,
|
||||
pocket_r: float = 0.095,
|
||||
head_r: float = 0.064,
|
||||
base_h: float = 0.85,
|
||||
) -> None:
|
||||
dp = sd_circle(x, y, cx, cy, pocket_r)
|
||||
dh = sd_circle(x, y, cx, cy, head_r)
|
||||
dhex = sd_hexagon(x, y, cx, cy, head_r * 0.48)
|
||||
|
||||
in_pocket = smoothstep(0.015, -0.015, dp)
|
||||
in_head = smoothstep(0.012, -0.012, dh)
|
||||
in_socket = smoothstep(0.010, -0.010, dhex)
|
||||
|
||||
# Countersunk floor
|
||||
pocket_h = base_h - 0.52 * in_pocket
|
||||
# Raised chamfered bolt head inside pocket
|
||||
head_profile = np.clip(1.0 - np.maximum(dh / head_r + 1.0, 0.0) ** 4 * 0.15, 0.0, 1.0)
|
||||
bolt_h = base_h - 0.06 + 0.04 * head_profile
|
||||
bolt_h = bolt_h - 0.36 * in_socket
|
||||
|
||||
t["height"] = np.where(in_head > 0.5, bolt_h, np.minimum(t["height"], pocket_h))
|
||||
# Colors & PBR
|
||||
pocket_col = np.array([0.055, 0.058, 0.056], dtype=np.float32)
|
||||
bolt_col = np.array([0.24, 0.25, 0.24], dtype=np.float32)
|
||||
sock_col = np.array([0.035, 0.036, 0.036], dtype=np.float32)
|
||||
|
||||
t["rgb"] = t["rgb"] * (1.0 - in_pocket[..., None]) + pocket_col * in_pocket[..., None]
|
||||
t["rgb"] = t["rgb"] * (1.0 - in_head[..., None]) + bolt_col * in_head[..., None]
|
||||
t["rgb"] = t["rgb"] * (1.0 - in_socket[..., None]) + sock_col * in_socket[..., None]
|
||||
t["metal"] = np.where(in_head > 0.5, 0.88, np.where(in_pocket > 0.5, 0.65, t["metal"]))
|
||||
t["rough"] = np.where(in_head > 0.5, 0.34, np.where(in_pocket > 0.5, 0.62, t["rough"]))
|
||||
|
||||
|
||||
def add_domed_rivet(
|
||||
t: dict[str, np.ndarray],
|
||||
x: np.ndarray,
|
||||
y: np.ndarray,
|
||||
cx: float,
|
||||
cy: float,
|
||||
r: float = 0.052,
|
||||
base_h: float = 0.88,
|
||||
) -> None:
|
||||
d = sd_circle(x, y, cx, cy, r)
|
||||
mask = smoothstep(0.012, -0.012, d)
|
||||
ring = smoothstep(0.018, 0.0, np.abs(d - 0.005))
|
||||
dist_norm = np.clip(np.sqrt((x - cx) ** 2 + (y - cy) ** 2) / r, 0.0, 1.0)
|
||||
dome = np.sqrt(np.maximum(1.0 - dist_norm ** 2, 0.0))
|
||||
rivet_h = base_h - 0.08 * ring + 0.11 * dome * mask
|
||||
t["height"] = t["height"] * (1.0 - mask) + np.clip(rivet_h, 0.0, 1.0) * mask
|
||||
col = np.array([0.28, 0.29, 0.27], dtype=np.float32)
|
||||
t["rgb"] = t["rgb"] * (1.0 - mask[..., None]) + col * mask[..., None]
|
||||
t["metal"] = t["metal"] * (1.0 - mask) + 0.85 * mask
|
||||
t["rough"] = t["rough"] * (1.0 - mask) + 0.32 * mask
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Individual tiles (0..15)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def tile_00_louvered_vent(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(0) Louvered armor vent."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 10.0, 4, seed=101)
|
||||
n2 = fbm(x, y, 36.0, 3, seed=102)
|
||||
|
||||
d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.72, r=0.06)
|
||||
d_inner = sd_box(x, y, 0.0, 0.0, 0.65, 0.56, r=0.03)
|
||||
d_seam = np.abs(d_outer)
|
||||
|
||||
outer_m = smoothstep(0.025, -0.025, d_outer)
|
||||
inner_m = smoothstep(0.02, -0.02, d_inner)
|
||||
|
||||
# Frame plate
|
||||
frame_h = 0.96 - 0.04 * smoothstep(0.0, 0.14, np.maximum(-d_outer, 0.0))
|
||||
frame_h -= 0.45 * smoothstep(0.03, 0.0, d_seam)
|
||||
# Recessed bay behind louvers
|
||||
h = np.where(inner_m > 0.5, 0.04, frame_h)
|
||||
|
||||
# 5 angled louvers inside d_inner
|
||||
slat_centers = np.linspace(-0.42, 0.42, 5)
|
||||
slat_mask_all = np.zeros_like(x)
|
||||
for sc in slat_centers:
|
||||
# Each louver spans x=[-0.62, 0.62], y=[sc-0.065, sc+0.065]
|
||||
ds = sd_box(x, y, 0.0, float(sc), 0.62, 0.068, r=0.015)
|
||||
sm = smoothstep(0.015, -0.015, ds)
|
||||
# Slope from top (high) down to bottom (low), exposing dark gap underneath
|
||||
local_t = np.clip((y - (sc - 0.068)) / 0.136, 0.0, 1.0)
|
||||
slat_h = 0.92 - 0.62 * local_t
|
||||
h = np.maximum(h, sm * slat_h)
|
||||
slat_mask_all = np.maximum(slat_mask_all, sm)
|
||||
|
||||
# Paint + worn steel + soot inside vent
|
||||
olive = np.array([0.16, 0.18, 0.14], dtype=np.float32) * (0.85 + 0.30 * n1[..., None])
|
||||
steel = np.array([0.26, 0.27, 0.26], dtype=np.float32) * (0.85 + 0.30 * n2[..., None])
|
||||
void = np.array([0.025, 0.025, 0.027], dtype=np.float32)
|
||||
|
||||
edge_wear = smoothstep(0.05, 0.0, np.abs(d_inner)) * smoothstep(0.35, 0.65, n2)
|
||||
slat_top_wear = slat_mask_all * smoothstep(0.70, 0.92, h) * smoothstep(0.35, 0.70, n2)
|
||||
wear = np.clip(np.maximum(edge_wear, slat_top_wear), 0.0, 1.0)
|
||||
|
||||
col = olive * (1.0 - wear[..., None]) + steel * wear[..., None]
|
||||
# Darken recessed gap
|
||||
in_void = inner_m * (1.0 - slat_mask_all)
|
||||
col = col * (1.0 - in_void[..., None]) + void * in_void[..., None]
|
||||
# Soot darkening on lower slope of slats
|
||||
col *= (1.0 - 0.45 * slat_mask_all[..., None] * smoothstep(0.85, 0.30, h)[..., None])
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = outer_m
|
||||
t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.35 + 0.55 * wear + 0.25 * slat_mask_all, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.58 - 0.26 * wear + 0.25 * in_void, 0.18, 0.95)
|
||||
|
||||
for bx, by in [(-0.71, -0.63), (0.71, -0.63), (-0.71, 0.63), (0.71, 0.63)]:
|
||||
add_hex_bolt(t, x, y, bx, by, pocket_r=0.055, head_r=0.036, base_h=0.95)
|
||||
return t
|
||||
|
||||
|
||||
def tile_01_bolted_hatch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(1) Recessed bolted maintenance hatch."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 8.0, 4, seed=201)
|
||||
n2 = fbm(x, y, 28.0, 3, seed=202)
|
||||
|
||||
d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.80, r=0.08)
|
||||
d_groove = np.abs(sd_box(x, y, 0.0, 0.0, 0.66, 0.66, r=0.06))
|
||||
d_door = sd_box(x, y, 0.0, 0.0, 0.63, 0.63, r=0.05)
|
||||
d_latch = sd_box(x, y, 0.32, 0.0, 0.13, 0.22, r=0.03)
|
||||
d_bar = sd_box(x, y, 0.32, 0.0, 0.045, 0.16, r=0.02)
|
||||
|
||||
outer_m = smoothstep(0.025, -0.025, d_outer)
|
||||
groove_m = smoothstep(0.032, 0.0, d_groove)
|
||||
latch_m = smoothstep(0.02, -0.02, d_latch)
|
||||
bar_m = smoothstep(0.015, -0.015, d_bar)
|
||||
|
||||
h = np.full_like(x, 0.96)
|
||||
# Bevel down into perimeter seam
|
||||
h = np.where(d_door < 0.0, 0.88, h)
|
||||
h -= 0.72 * groove_m
|
||||
# Recessed latch pocket with grab bar
|
||||
h = np.where(latch_m > 0.5, 0.22, h)
|
||||
h = np.where(bar_m > 0.5, 0.86, h)
|
||||
|
||||
base_col = np.array([0.19, 0.21, 0.16], dtype=np.float32) * (0.86 + 0.28 * n1[..., None])
|
||||
door_col = np.array([0.22, 0.24, 0.19], dtype=np.float32) * (0.86 + 0.28 * n1[..., None])
|
||||
seam_col = np.array([0.04, 0.04, 0.038], dtype=np.float32)
|
||||
bar_col = np.array([0.34, 0.34, 0.32], dtype=np.float32)
|
||||
|
||||
in_door = smoothstep(0.02, -0.02, d_door)
|
||||
col = base_col * (1.0 - in_door[..., None]) + door_col * in_door[..., None]
|
||||
# Paint chip around door edge
|
||||
chip = smoothstep(0.05, 0.0, np.abs(d_door)) * smoothstep(0.45, 0.68, n2)
|
||||
col = col * (1.0 - chip[..., None]) + np.array([0.32, 0.33, 0.32], dtype=np.float32) * chip[..., None]
|
||||
col = col * (1.0 - groove_m[..., None]) + seam_col * groove_m[..., None]
|
||||
col = col * (1.0 - latch_m[..., None]) + np.array([0.05, 0.05, 0.05], dtype=np.float32) * latch_m[..., None]
|
||||
col = col * (1.0 - bar_m[..., None]) + bar_col * bar_m[..., None]
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = outer_m
|
||||
t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.30 + 0.55 * chip + 0.60 * bar_m, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.56 - 0.24 * chip + 0.25 * groove_m, 0.2, 0.95)
|
||||
|
||||
for bx, by in [(-0.50, -0.50), (0.0, -0.52), (0.50, -0.50),
|
||||
(-0.50, 0.50), (0.0, 0.52), (0.50, 0.50),
|
||||
(-0.52, 0.0)]:
|
||||
add_hex_bolt(t, x, y, bx, by, pocket_r=0.068, head_r=0.044, base_h=0.88)
|
||||
return t
|
||||
|
||||
|
||||
def tile_02_fastener_strip(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(2) 4-bolt recessed fastener strip."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 12.0, 4, seed=301)
|
||||
n2 = fbm(x, y, 40.0, 3, seed=302)
|
||||
|
||||
d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.28, r=0.08)
|
||||
d_bevel = sd_box(x, y, 0.0, 0.0, 0.78, 0.22, r=0.05)
|
||||
mask = smoothstep(0.025, -0.025, d_strip)
|
||||
|
||||
# Raised beveled plate with seam around edge
|
||||
h = np.where(d_bevel < 0.0, 0.93, 0.82)
|
||||
h -= 0.45 * smoothstep(0.03, 0.0, np.abs(d_strip))
|
||||
|
||||
col = np.array([0.21, 0.22, 0.19], dtype=np.float32) * (0.86 + 0.28 * n1[..., None])
|
||||
edge_wear = smoothstep(0.05, 0.0, np.abs(d_bevel)) * smoothstep(0.35, 0.70, n2)
|
||||
col = col * (1.0 - edge_wear[..., None]) + np.array([0.36, 0.37, 0.36], dtype=np.float32) * edge_wear[..., None]
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = mask
|
||||
t["height"] = np.where(mask > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.45 + 0.45 * edge_wear, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.48 - 0.18 * edge_wear, 0.22, 0.9)
|
||||
|
||||
for bx in (-0.57, -0.19, 0.19, 0.57):
|
||||
add_hex_bolt(t, x, y, bx, 0.0, pocket_r=0.115, head_r=0.075, base_h=0.93)
|
||||
return t
|
||||
|
||||
|
||||
def tile_03_intake_grille(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(3) Slotted intake grille."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 10.0, 4, seed=401)
|
||||
n2 = fbm(x, y, 32.0, 3, seed=402)
|
||||
|
||||
d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.76, r=0.07)
|
||||
d_inner = sd_box(x, y, 0.0, 0.0, 0.66, 0.60, r=0.04)
|
||||
outer_m = smoothstep(0.025, -0.025, d_outer)
|
||||
inner_m = smoothstep(0.02, -0.02, d_inner)
|
||||
|
||||
h = np.where(inner_m > 0.5, 0.88, 0.96)
|
||||
h -= 0.38 * smoothstep(0.03, 0.0, np.abs(d_inner))
|
||||
|
||||
# 6 vertical intake slots (2 rows of 6 or 6 tall slots)
|
||||
slot_void = np.zeros_like(x)
|
||||
for sx in np.linspace(-0.48, 0.48, 6):
|
||||
for sy in (-0.27, 0.27):
|
||||
ds = sd_box(x, y, float(sx), float(sy), 0.046, 0.21, r=0.038)
|
||||
sm = smoothstep(0.015, -0.015, ds)
|
||||
# Chamfered rim then deep void
|
||||
rim = smoothstep(0.035, 0.0, np.abs(ds - 0.012))
|
||||
h = np.where(sm > 0.5, 0.02, h - 0.18 * rim)
|
||||
slot_void = np.maximum(slot_void, sm)
|
||||
|
||||
plate_col = np.array([0.16, 0.17, 0.16], dtype=np.float32) * (0.85 + 0.3 * n1[..., None])
|
||||
rib_wear = smoothstep(0.45, 0.75, n2) * inner_m * (1.0 - slot_void) * 0.45
|
||||
col = plate_col * (1.0 - rib_wear[..., None]) + np.array([0.30, 0.31, 0.30], dtype=np.float32) * rib_wear[..., None]
|
||||
col = col * (1.0 - slot_void[..., None]) + np.array([0.02, 0.02, 0.022], dtype=np.float32) * slot_void[..., None]
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = outer_m
|
||||
t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.55 + 0.35 * rib_wear - 0.5 * slot_void, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.46 - 0.15 * rib_wear + 0.4 * slot_void, 0.2, 0.95)
|
||||
|
||||
for rx, ry in [(-0.72, -0.68), (0.72, -0.68), (-0.72, 0.68), (0.72, 0.68)]:
|
||||
add_domed_rivet(t, x, y, rx, ry, r=0.042, base_h=0.95)
|
||||
return t
|
||||
|
||||
|
||||
def tile_04_rivet_seam(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(4) Rivet panel seam."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 10.0, 4, seed=501)
|
||||
n2 = fbm(x, y, 36.0, 3, seed=502)
|
||||
|
||||
d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.32, r=0.04)
|
||||
mask = smoothstep(0.025, -0.025, d_strip)
|
||||
# Central recessed panel seam groove along y=0, clipped inside strip
|
||||
groove = smoothstep(0.042, 0.0, np.abs(y)) * mask
|
||||
h = 0.90 - 0.72 * groove
|
||||
|
||||
col = np.array([0.20, 0.21, 0.17], dtype=np.float32) * (0.85 + 0.3 * n1[..., None])
|
||||
chip = smoothstep(0.08, 0.0, np.abs(y)) * smoothstep(0.48, 0.70, n2) * mask
|
||||
col = col * (1.0 - chip[..., None]) + np.array([0.34, 0.35, 0.34], dtype=np.float32) * chip[..., None]
|
||||
col = col * (1.0 - groove[..., None]) + np.array([0.04, 0.04, 0.036], dtype=np.float32) * groove[..., None]
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = mask
|
||||
t["height"] = np.where(mask > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.32 + 0.55 * chip, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.56 - 0.24 * chip + 0.30 * groove, 0.2, 0.95)
|
||||
|
||||
for rx in np.linspace(-0.70, 0.70, 6):
|
||||
add_domed_rivet(t, x, y, float(rx), -0.15, r=0.046, base_h=0.90)
|
||||
add_domed_rivet(t, x, y, float(rx), 0.15, r=0.046, base_h=0.90)
|
||||
return t
|
||||
|
||||
|
||||
def tile_05_welded_patch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(5) Welded armor repair patch."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 9.0, 4, seed=601)
|
||||
n2 = fbm(x, y, 42.0, 3, seed=602)
|
||||
|
||||
# Slightly rotated/chamfered patch shape
|
||||
ca, sa = np.cos(0.08), np.sin(0.08)
|
||||
xr = x * ca - y * sa
|
||||
yr = x * sa + y * ca
|
||||
d_patch = sd_box(xr, yr, 0.0, 0.0, 0.64, 0.50, r=0.05)
|
||||
# Irregular outer weld apron
|
||||
d_outer = d_patch - 0.12
|
||||
outer_m = smoothstep(0.025, -0.025, d_outer)
|
||||
patch_m = smoothstep(0.018, -0.018, d_patch)
|
||||
|
||||
# Weld bead ripple along perimeter d_patch ~= 0
|
||||
bead_band = smoothstep(0.085, 0.0, np.abs(d_patch - 0.01))
|
||||
# Ripple along perimeter coordinate
|
||||
ripple = 0.5 + 0.5 * np.sin((xr + yr) * 48.0 + n2 * 6.0)
|
||||
bead_h = 0.72 + 0.27 * bead_band * (0.65 + 0.35 * ripple)
|
||||
|
||||
h = np.where(patch_m > 0.5, 0.92 - 0.03 * n1, 0.68)
|
||||
h = np.maximum(h, bead_h * bead_band)
|
||||
|
||||
patch_col = np.array([0.23, 0.24, 0.21], dtype=np.float32) * (0.85 + 0.30 * n1[..., None])
|
||||
weld_col = np.array([0.38, 0.36, 0.33], dtype=np.float32) * (0.80 + 0.35 * ripple[..., None])
|
||||
# Heat-affected straw/blue oxide halo outside weld
|
||||
haz = smoothstep(0.14, 0.02, np.abs(d_patch - 0.03)) * (1.0 - bead_band)
|
||||
haz_col = np.array([0.14, 0.12, 0.14], dtype=np.float32)
|
||||
|
||||
col = haz_col * haz[..., None] + patch_col * patch_m[..., None]
|
||||
col = col * (1.0 - bead_band[..., None]) + weld_col * bead_band[..., None]
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = np.clip(np.maximum(patch_m, bead_band * 0.95 + haz * 0.75) * outer_m, 0.0, 1.0)
|
||||
t["height"] = np.where(t["alpha"] > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.35 + 0.58 * bead_band, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.55 - 0.28 * bead_band, 0.18, 0.92)
|
||||
return t
|
||||
|
||||
|
||||
def tile_06_lift_lug(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(6) Recessed lift-lug pocket."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 11.0, 4, seed=701)
|
||||
n2 = fbm(x, y, 34.0, 3, seed=702)
|
||||
|
||||
d_outer = sd_box(x, y, 0.0, 0.0, 0.74, 0.74, r=0.10)
|
||||
d_pocket = sd_box(x, y, 0.0, 0.0, 0.52, 0.52, r=0.09)
|
||||
outer_m = smoothstep(0.025, -0.025, d_outer)
|
||||
pocket_m = smoothstep(0.02, -0.02, d_pocket)
|
||||
|
||||
# Chamfered pit wall
|
||||
wall_t = np.clip(-d_pocket / 0.14, 0.0, 1.0)
|
||||
pit_h = 0.94 - 0.84 * smoothstep(0.0, 1.0, wall_t)
|
||||
h = np.where(pocket_m > 0.5, pit_h, 0.96)
|
||||
|
||||
# Cylindrical steel crossbar along X (spanning the recessed pocket)
|
||||
d_bar_y = np.abs(y) / 0.135
|
||||
d_bar_x = np.abs(x) - 0.50
|
||||
bar_m = smoothstep(1.06, 0.94, d_bar_y) * smoothstep(0.02, -0.02, d_bar_x)
|
||||
cyl_z = np.sqrt(np.maximum(1.0 - np.clip(d_bar_y, 0.0, 1.0) ** 2, 0.0))
|
||||
bar_h = 0.45 + 0.50 * cyl_z
|
||||
h = np.where(bar_m > 0.5, np.maximum(h, bar_h), h)
|
||||
|
||||
flange_col = np.array([0.18, 0.19, 0.16], dtype=np.float32) * (0.85 + 0.30 * n1[..., None])
|
||||
pit_col = np.array([0.055, 0.056, 0.055], dtype=np.float32) * (0.8 + 0.3 * n1[..., None])
|
||||
bar_col = np.array([0.36, 0.37, 0.36], dtype=np.float32) * (0.85 + 0.25 * n2[..., None])
|
||||
|
||||
col = flange_col * (1.0 - pocket_m[..., None]) + pit_col * pocket_m[..., None]
|
||||
col = col * (1.0 - bar_m[..., None]) + bar_col * bar_m[..., None]
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = outer_m
|
||||
t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.35 + 0.58 * bar_m, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.55 - 0.28 * bar_m + 0.20 * pocket_m * (1.0 - bar_m), 0.18, 0.95)
|
||||
return t
|
||||
|
||||
|
||||
def tile_07_hazard_chevron(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(7) Weathered hazard caution chevron strip."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 8.0, 4, seed=801)
|
||||
n2 = fbm(x, y, 34.0, 4, seed=802)
|
||||
|
||||
d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.26, r=0.025)
|
||||
d_inner = sd_box(x, y, 0.0, 0.0, 0.78, 0.20, r=0.015)
|
||||
strip_m = smoothstep(0.02, -0.02, d_strip)
|
||||
inner_m = smoothstep(0.015, -0.015, d_inner)
|
||||
|
||||
# Diagonal stripes
|
||||
stripe_wave = np.sin((x * 2.2 + y * 2.2) * np.pi * 2.4)
|
||||
is_yellow = smoothstep(-0.08, 0.08, stripe_wave)
|
||||
|
||||
yellow = np.array([0.68, 0.44, 0.06], dtype=np.float32)
|
||||
black = np.array([0.055, 0.055, 0.052], dtype=np.float32)
|
||||
steel = np.array([0.28, 0.29, 0.28], dtype=np.float32)
|
||||
|
||||
col = black * (1.0 - is_yellow[..., None]) + yellow * is_yellow[..., None]
|
||||
# Thin dark border frame
|
||||
col = black * (1.0 - inner_m[..., None]) + col * inner_m[..., None]
|
||||
# Grime + paint chips
|
||||
chip = smoothstep(0.62, 0.69, n2)
|
||||
col *= (0.78 + 0.35 * n1[..., None])
|
||||
col = col * (1.0 - chip[..., None] * 0.75) + steel * (chip[..., None] * 0.75)
|
||||
|
||||
# Subtle paint film thickness + border recess
|
||||
h = 0.98 - 0.08 * (1.0 - inner_m) - 0.04 * chip
|
||||
edge_wear = smoothstep(0.06, 0.0, np.abs(d_strip)) * smoothstep(0.55, 0.72, n2)
|
||||
alpha = np.clip(strip_m * (1.0 - 0.80 * edge_wear), 0.0, 1.0)
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = np.clip(alpha, 0.0, 1.0)
|
||||
t["height"] = np.where(strip_m > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.15 + 0.65 * chip, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.60 - 0.25 * chip, 0.25, 0.92)
|
||||
return t
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Row 2: Stencils & Emblems
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _sd_digit_0(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray:
|
||||
d_out = sd_box(x, y, cx, cy, 0.28, 0.46, r=0.14)
|
||||
d_in = sd_box(x, y, cx, cy, 0.11, 0.28, r=0.05)
|
||||
d = np.maximum(d_out, -d_in)
|
||||
# Stencil bridge gaps top/bottom
|
||||
gap = np.abs(x - cx) - 0.032
|
||||
d_bridge = np.maximum(gap, 0.25 - np.abs(y - cy))
|
||||
return np.maximum(d, -d_bridge)
|
||||
|
||||
|
||||
def _sd_digit_3(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray:
|
||||
d_out = sd_box(x, y, cx, cy, 0.28, 0.46, r=0.14)
|
||||
d_in_top = sd_box(x, y, cx - 0.04, cy - 0.20, 0.16, 0.11, r=0.03)
|
||||
d_in_bot = sd_box(x, y, cx - 0.04, cy + 0.20, 0.16, 0.11, r=0.03)
|
||||
d_open_l = sd_box(x, y, cx - 0.24, cy, 0.16, 0.15, r=0.0)
|
||||
d = np.maximum(d_out, -np.minimum(np.minimum(d_in_top, d_in_bot), d_open_l))
|
||||
# Stencil bridge on right spine
|
||||
gap = np.maximum(np.abs(y - cy) - 0.028, (cx - 0.05) - x)
|
||||
return np.maximum(d, -gap)
|
||||
|
||||
|
||||
def _sd_digit_7(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray:
|
||||
d_top = sd_box(x, y, cx, cy - 0.37, 0.28, 0.09, r=0.02)
|
||||
# Slanted leg from (cx+0.20, cy-0.36) to (cx-0.08, cy+0.39)
|
||||
d_leg = sd_segment(x, y, cx + 0.18, cy - 0.34, cx - 0.07, cy + 0.38) - 0.088
|
||||
d = np.minimum(d_top, d_leg)
|
||||
# Stencil gap between top bar & leg
|
||||
gap = sd_box(x, y, cx + 0.12, cy - 0.25, 0.20, 0.025, r=0.0)
|
||||
return np.maximum(d, -gap)
|
||||
|
||||
|
||||
def _finish_stencil(
|
||||
x: np.ndarray,
|
||||
y: np.ndarray,
|
||||
mask: np.ndarray,
|
||||
paint_col: np.ndarray,
|
||||
seed: int,
|
||||
) -> dict[str, np.ndarray]:
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 10.0, 4, seed=seed)
|
||||
n2 = fbm(x, y, 40.0, 4, seed=seed + 1)
|
||||
|
||||
# Flaking & scratching across stencil paint
|
||||
flake = smoothstep(0.58, 0.72, n2)
|
||||
scratches = smoothstep(0.68, 0.74, fbm(x * 0.4 + y * 1.8, y * 0.4, 24.0, 3, seed=seed + 2))
|
||||
wear = np.clip(flake * 0.85 + scratches * 0.7, 0.0, 1.0)
|
||||
|
||||
alpha = np.clip(mask * (1.0 - wear * 0.85), 0.0, 1.0)
|
||||
col = paint_col * (0.82 + 0.25 * n1[..., None])
|
||||
h = 1.0 - 0.02 * mask * (1.0 - wear) - 0.04 * (1.0 - mask)
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = alpha
|
||||
t["height"] = np.where(alpha > 0.02, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.full_like(x, 0.08)
|
||||
t["rough"] = np.clip(0.68 + 0.15 * n1, 0.4, 0.9)
|
||||
return t
|
||||
|
||||
|
||||
def tile_08_stencil_03(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(8) Tactical stencil '03'."""
|
||||
d = np.minimum(_sd_digit_0(x, y, -0.36, 0.0), _sd_digit_3(x, y, 0.36, 0.0))
|
||||
mask = smoothstep(0.02, -0.02, d)
|
||||
return _finish_stencil(x, y, mask, np.array([0.74, 0.71, 0.62], dtype=np.float32), seed=901)
|
||||
|
||||
|
||||
def tile_09_stencil_07(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(9) Tactical stencil '07'."""
|
||||
d = np.minimum(_sd_digit_0(x, y, -0.36, 0.0), _sd_digit_7(x, y, 0.36, 0.0))
|
||||
mask = smoothstep(0.02, -0.02, d)
|
||||
return _finish_stencil(x, y, mask, np.array([0.74, 0.71, 0.62], dtype=np.float32), seed=1001)
|
||||
|
||||
|
||||
def tile_10_radiation_warning(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(10) Radiation / thermal warning stencil."""
|
||||
r = np.sqrt(x * x + y * y)
|
||||
ang = np.arctan2(y, x)
|
||||
|
||||
# Outer dashed warning ring
|
||||
d_ring = np.abs(r - 0.66) - 0.065
|
||||
ring_seg = np.abs(((ang + np.pi) / (np.pi / 3.0)) % 1.0 - 0.5) - 0.34
|
||||
d_ring = np.maximum(d_ring, ring_seg * 0.5)
|
||||
|
||||
# Central dot + 3 trefoil blades
|
||||
d_core = r - 0.11
|
||||
blade_annulus = np.maximum(0.18 - r, r - 0.52)
|
||||
blade_ang = np.cos(3.0 * (ang + np.pi / 6.0))
|
||||
d_blades = np.maximum(blade_annulus, (0.45 - blade_ang) * 0.28)
|
||||
|
||||
d = np.minimum(np.minimum(d_ring, d_core), d_blades)
|
||||
mask = smoothstep(0.02, -0.02, d)
|
||||
return _finish_stencil(x, y, mask, np.array([0.78, 0.36, 0.09], dtype=np.float32), seed=1101)
|
||||
|
||||
|
||||
def tile_11_faction_emblem(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(11) Faction chevron emblem."""
|
||||
ax = np.abs(x)
|
||||
# Double military chevron + diamond center
|
||||
d1 = np.abs((y + 0.14) + ax * 0.85) - 0.085
|
||||
d1 = np.maximum(d1, ax - 0.68)
|
||||
d2 = np.abs((y - 0.22) + ax * 0.85) - 0.065
|
||||
d2 = np.maximum(d2, ax - 0.52)
|
||||
d_diamond = (ax * 0.9 + np.abs(y + 0.42)) - 0.18
|
||||
d_chev = np.minimum(d1, d2)
|
||||
|
||||
m_chev = smoothstep(0.02, -0.02, d_chev)
|
||||
m_dia = smoothstep(0.02, -0.02, d_diamond)
|
||||
mask = np.maximum(m_chev, m_dia)
|
||||
|
||||
t = _finish_stencil(x, y, mask, np.array([0.76, 0.72, 0.60], dtype=np.float32), seed=1201)
|
||||
# Signal orange center diamond
|
||||
orange = np.array([0.74, 0.27, 0.10], dtype=np.float32)
|
||||
t["rgb"] = t["rgb"] * (1.0 - m_dia[..., None]) + orange * m_dia[..., None]
|
||||
return t
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Row 3: Dynamic combat hits (12..15)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def tile_12_ap_penetration(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(12) Deep AP autocannon penetration hole (rolled metallic rim + black bore + hot rim)."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 7.0, 4, seed=1301)
|
||||
n2 = fbm(x, y, 24.0, 4, seed=1302)
|
||||
ang = np.arctan2(y, x)
|
||||
# Jagged petal modulation around bore
|
||||
jagged = 0.065 * np.sin(ang * 7.0 + 1.1) + 0.045 * np.cos(ang * 13.0 - 0.4) + 0.09 * (n2 - 0.5)
|
||||
r = np.sqrt(x * x + y * y) + jagged
|
||||
|
||||
bore_r = 0.28
|
||||
rim_r = 0.44
|
||||
scorch_r = 0.82
|
||||
|
||||
bore_m = smoothstep(bore_r + 0.03, bore_r - 0.02, r)
|
||||
rim_m = smoothstep(0.10, 0.0, np.abs(r - (bore_r + 0.05)))
|
||||
scorch_m = smoothstep(scorch_r, bore_r * 0.8, r) * (0.55 + 0.45 * n1)
|
||||
|
||||
# Height: flush 1.0 outside -> raised/rolled rim at 0.96 -> sharp drop into 0.0 pitch-black bore
|
||||
hole_wall = smoothstep(bore_r - 0.04, rim_r, r)
|
||||
h = np.clip(hole_wall * 0.96 + 0.04 * smoothstep(rim_r + 0.12, rim_r, r), 0.0, 1.0)
|
||||
h = np.where(r > rim_r + 0.12, 1.0, h)
|
||||
|
||||
soot_col = np.array([0.04, 0.035, 0.032], dtype=np.float32)
|
||||
steel_col = np.array([0.52, 0.54, 0.56], dtype=np.float32) * (0.75 + 0.45 * n2[..., None])
|
||||
bore_col = np.array([0.012, 0.010, 0.010], dtype=np.float32)
|
||||
|
||||
col = soot_col * (1.0 - rim_m[..., None]) + steel_col * rim_m[..., None]
|
||||
col = col * (1.0 - bore_m[..., None]) + bore_col * bore_m[..., None]
|
||||
|
||||
# Alpha: opaque in bore + metal rim, softly feathered soot halo
|
||||
alpha = np.clip(np.maximum(np.maximum(bore_m, rim_m), scorch_m * 0.88), 0.0, 1.0)
|
||||
# Keep zero bleed at outer margin
|
||||
border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y)))
|
||||
alpha *= border
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = alpha
|
||||
t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(rim_m * 0.94 + bore_m * 0.10, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.92 - rim_m * 0.66, 0.22, 0.96)
|
||||
return t
|
||||
|
||||
|
||||
def tile_13_shrapnel_gouge(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(13) Diagonal shrapnel/flak armor gouge."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 8.0, 4, seed=1401)
|
||||
n2 = fbm(x, y, 28.0, 4, seed=1402)
|
||||
|
||||
# Rotate -35 degrees for diagonal ricochet trench
|
||||
ca, sa = np.cos(-0.62), np.sin(-0.62)
|
||||
u = x * ca - y * sa
|
||||
v = x * sa + y * ca + 0.04 * (n2 - 0.5)
|
||||
|
||||
# Tapered V-trough from u=-0.62 to u=+0.62
|
||||
d_trench = sd_segment(u, v, -0.58, 0.0, 0.58, 0.0)
|
||||
width = 0.13 + 0.05 * np.clip((u + 0.58) / 1.16, 0.0, 1.0)
|
||||
trough_t = np.clip(1.0 - d_trench / width, 0.0, 1.0)
|
||||
burr_m = smoothstep(0.06, 0.0, np.abs(d_trench - width))
|
||||
|
||||
h = 1.0 - 0.88 * smoothstep(0.0, 1.0, trough_t)
|
||||
# Upturned burr ridge at edge
|
||||
h = np.clip(h + 0.04 * burr_m, 0.0, 1.0)
|
||||
|
||||
soot = np.array([0.045, 0.04, 0.036], dtype=np.float32)
|
||||
torn_steel = np.array([0.50, 0.52, 0.54], dtype=np.float32) * (0.75 + 0.45 * n2[..., None])
|
||||
furrow_dark = np.array([0.09, 0.09, 0.095], dtype=np.float32)
|
||||
|
||||
trench_m = smoothstep(0.05, 0.25, trough_t)
|
||||
col = soot * (1.0 - trench_m[..., None]) + torn_steel * trench_m[..., None]
|
||||
col = col * (1.0 - smoothstep(0.60, 0.95, trough_t)[..., None] * 0.7) + furrow_dark * (smoothstep(0.60, 0.95, trough_t)[..., None] * 0.7)
|
||||
col = col * (1.0 - burr_m[..., None] * 0.65) + torn_steel * (burr_m[..., None] * 0.65)
|
||||
|
||||
scorch_halo = smoothstep(0.42, 0.08, d_trench) * (0.5 + 0.5 * n1)
|
||||
alpha = np.clip(np.maximum(trench_m, np.maximum(burr_m, scorch_halo * 0.85)), 0.0, 1.0)
|
||||
border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y)))
|
||||
alpha *= border
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = alpha
|
||||
t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(np.maximum(trench_m, burr_m) * 0.90, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.90 - np.maximum(trench_m, burr_m) * 0.62, 0.24, 0.95)
|
||||
return t
|
||||
|
||||
|
||||
def tile_14_plasma_crater(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(14) Molten plasma burn crater."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 7.5, 4, seed=1501)
|
||||
n2 = fbm(x, y, 22.0, 4, seed=1502)
|
||||
r = np.sqrt(x * x + y * y) + 0.08 * (n2 - 0.5)
|
||||
|
||||
crater_r = 0.44
|
||||
bowl_m = smoothstep(crater_r + 0.04, crater_r - 0.08, r)
|
||||
rim_m = smoothstep(0.08, 0.0, np.abs(r - crater_r))
|
||||
scorch_m = smoothstep(0.84, 0.36, r) * (0.5 + 0.5 * n1)
|
||||
|
||||
# Slag ripples in bowl + crisp crater rim
|
||||
ripples = 0.5 + 0.5 * np.sin(r * 34.0 + n2 * 4.0)
|
||||
bowl_depth = smoothstep(crater_r, 0.04, r)
|
||||
h = 1.0 - 0.88 * bowl_depth + 0.08 * ripples * bowl_m + 0.06 * rim_m
|
||||
|
||||
carbon = np.array([0.035, 0.030, 0.028], dtype=np.float32)
|
||||
slag = np.array([0.22, 0.16, 0.14], dtype=np.float32) * (0.8 + 0.4 * ripples[..., None])
|
||||
molten_lip = np.array([0.46, 0.38, 0.32], dtype=np.float32)
|
||||
|
||||
col = carbon * (1.0 - bowl_m[..., None]) + slag * bowl_m[..., None]
|
||||
col = col * (1.0 - rim_m[..., None] * 0.7) + molten_lip * (rim_m[..., None] * 0.7)
|
||||
|
||||
alpha = np.clip(np.maximum(bowl_m, np.maximum(rim_m, scorch_m * 0.90)), 0.0, 1.0)
|
||||
border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y)))
|
||||
alpha *= border
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = alpha
|
||||
t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(bowl_m * 0.78 + rim_m * 0.85, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.92 - bowl_m * 0.50 - rim_m * 0.45, 0.28, 0.96)
|
||||
return t
|
||||
|
||||
|
||||
def tile_15_blast_scorch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]:
|
||||
"""(15) Radial blast scorch mark."""
|
||||
t = new_tile()
|
||||
n1 = fbm(x, y, 6.0, 4, seed=1601)
|
||||
n2 = fbm(x, y, 20.0, 4, seed=1602)
|
||||
ang = np.arctan2(y, x)
|
||||
r = np.sqrt(x * x + y * y)
|
||||
|
||||
# Radial blast rays
|
||||
rays = 0.55 + 0.45 * value_noise(np.cos(ang) * 3.0, np.sin(ang) * 3.0, 3.5, seed=1603)
|
||||
rays *= (0.7 + 0.3 * np.sin(ang * 11.0 + n2 * 3.0))
|
||||
r_eff = r / np.maximum(rays, 0.35)
|
||||
|
||||
scorch = smoothstep(0.95, 0.08, r_eff) * (0.65 + 0.35 * n1)
|
||||
pock = smoothstep(0.24, 0.05, r + 0.05 * (n2 - 0.5))
|
||||
h = 1.0 - 0.45 * pock - 0.04 * scorch
|
||||
|
||||
soot = np.array([0.032, 0.028, 0.025], dtype=np.float32)
|
||||
ash = np.array([0.11, 0.095, 0.082], dtype=np.float32)
|
||||
col = soot * (1.0 - pock[..., None] * 0.35) + ash * (pock[..., None] * 0.35)
|
||||
|
||||
border = smoothstep(0.93, 0.78, np.maximum(np.abs(x), np.abs(y)))
|
||||
alpha = np.clip(scorch * 0.92 * border, 0.0, 1.0)
|
||||
|
||||
t["rgb"] = np.clip(col, 0.0, 1.0)
|
||||
t["alpha"] = alpha
|
||||
t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0)
|
||||
t["metal"] = np.clip(0.05 + 0.25 * pock, 0.0, 1.0)
|
||||
t["rough"] = np.clip(0.94 - 0.20 * pock, 0.65, 0.98)
|
||||
return t
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Normal map, AO, color dilation, and atlas assembly
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def compute_normal_map(height: np.ndarray, strength: float = 5.5) -> np.ndarray:
|
||||
"""Sobel tangent-space normal map matching OpenGL/Godot (+X right, +Y down, +Z out)."""
|
||||
h = np.pad(height, 1, mode="edge")
|
||||
# Sobel X (+right) and Y (+down)
|
||||
dx = ((h[:-2, 2:] + 2.0 * h[1:-1, 2:] + h[2:, 2:])
|
||||
- (h[:-2, :-2] + 2.0 * h[1:-1, :-2] + h[2:, :-2])) * 0.125
|
||||
dy = ((h[2:, :-2] + 2.0 * h[2:, 1:-1] + h[2:, 2:])
|
||||
- (h[:-2, :-2] + 2.0 * h[:-2, 1:-1] + h[:-2, 2:])) * 0.125
|
||||
nx = -dx * strength
|
||||
ny = -dy * strength
|
||||
nz = np.ones_like(nx)
|
||||
inv_len = 1.0 / np.sqrt(nx * nx + ny * ny + nz * nz + 1e-12)
|
||||
return np.stack([nx * inv_len * 0.5 + 0.5,
|
||||
ny * inv_len * 0.5 + 0.5,
|
||||
nz * inv_len * 0.5 + 0.5], axis=-1)
|
||||
|
||||
|
||||
def compute_height_ao(height: np.ndarray) -> np.ndarray:
|
||||
"""Fast multi-radius horizon/cavity AO from the heightfield."""
|
||||
ao = np.ones_like(height, dtype=np.float32)
|
||||
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)]
|
||||
radii = (2, 5, 10)
|
||||
occ_sum = np.zeros_like(height, dtype=np.float32)
|
||||
count = 0
|
||||
h_pad = np.pad(height, 12, mode="edge")
|
||||
H, W = height.shape
|
||||
for r in radii:
|
||||
for dx, dy in dirs:
|
||||
ox = 12 + dx * r
|
||||
oy = 12 + dy * r
|
||||
sample_h = h_pad[oy : oy + H, ox : ox + W]
|
||||
diff = np.maximum(sample_h - height, 0.0)
|
||||
occ_sum += np.clip(diff * 2.8, 0.0, 1.0)
|
||||
count += 1
|
||||
cavity = occ_sum / float(count)
|
||||
# Also darken deep recesses naturally
|
||||
ao = np.clip((1.0 - cavity * 1.35) * (0.30 + 0.70 * height), 0.08, 1.0)
|
||||
return ao
|
||||
|
||||
|
||||
def dilate_albedo(rgb: np.ndarray, alpha: np.ndarray, steps: int = 8) -> np.ndarray:
|
||||
"""Propagate opaque RGB into transparent pixels to eliminate bilinear dark fringes."""
|
||||
out = rgb.copy()
|
||||
mask = alpha > 0.04
|
||||
for _ in range(steps):
|
||||
if np.all(mask):
|
||||
break
|
||||
acc = np.zeros_like(out)
|
||||
wsum = np.zeros(mask.shape, dtype=np.float32)
|
||||
p_rgb = np.pad(out, ((1, 1), (1, 1), (0, 0)), mode="edge")
|
||||
p_m = np.pad(mask.astype(np.float32), ((1, 1), (1, 1)), mode="edge")
|
||||
H, W = mask.shape
|
||||
for dy in (-1, 0, 1):
|
||||
for dx in (-1, 0, 1):
|
||||
if dx == 0 and dy == 0:
|
||||
continue
|
||||
m_nb = p_m[1 + dy : 1 + dy + H, 1 + dx : 1 + dx + W]
|
||||
acc += p_rgb[1 + dy : 1 + dy + H, 1 + dx : 1 + dx + W] * m_nb[..., None]
|
||||
wsum += m_nb
|
||||
fill = (~mask) & (wsum > 0.0)
|
||||
out[fill] = acc[fill] / wsum[fill, None]
|
||||
mask = mask | fill
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
x, y = tile_coords()
|
||||
|
||||
builders = [
|
||||
tile_00_louvered_vent,
|
||||
tile_01_bolted_hatch,
|
||||
tile_02_fastener_strip,
|
||||
tile_03_intake_grille,
|
||||
tile_04_rivet_seam,
|
||||
tile_05_welded_patch,
|
||||
tile_06_lift_lug,
|
||||
tile_07_hazard_chevron,
|
||||
tile_08_stencil_03,
|
||||
tile_09_stencil_07,
|
||||
tile_10_radiation_warning,
|
||||
tile_11_faction_emblem,
|
||||
tile_12_ap_penetration,
|
||||
tile_13_shrapnel_gouge,
|
||||
tile_14_plasma_crater,
|
||||
tile_15_blast_scorch,
|
||||
]
|
||||
|
||||
atlas_albedo = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 4), dtype=np.uint8)
|
||||
atlas_normal = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 3), dtype=np.uint8)
|
||||
atlas_ormh = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 4), dtype=np.uint8)
|
||||
|
||||
for idx, fn in enumerate(builders):
|
||||
row = idx // GRID
|
||||
col = idx % GRID
|
||||
t = fn(x, y)
|
||||
|
||||
rgb_dilated = dilate_albedo(t["rgb"], t["alpha"], steps=12)
|
||||
nrm = compute_normal_map(t["height"], strength=6.0)
|
||||
ao = compute_height_ao(t["height"])
|
||||
|
||||
y0, y1 = row * TILE_SIZE, (row + 1) * TILE_SIZE
|
||||
x0, x1 = col * TILE_SIZE, (col + 1) * TILE_SIZE
|
||||
|
||||
albedo_rgba = np.dstack([rgb_dilated, t["alpha"]])
|
||||
ormh_rgba = np.dstack([ao, t["rough"], t["metal"], t["height"]])
|
||||
|
||||
atlas_albedo[y0:y1, x0:x1] = np.clip(np.round(albedo_rgba * 255.0), 0, 255).astype(np.uint8)
|
||||
atlas_normal[y0:y1, x0:x1] = np.clip(np.round(nrm * 255.0), 0, 255).astype(np.uint8)
|
||||
atlas_ormh[y0:y1, x0:x1] = np.clip(np.round(ormh_rgba * 255.0), 0, 255).astype(np.uint8)
|
||||
|
||||
Image.fromarray(atlas_albedo, mode="RGBA").save(OUT_DIR / "decal_atlas_albedo.png")
|
||||
Image.fromarray(atlas_normal, mode="RGB").save(OUT_DIR / "decal_atlas_normal.png")
|
||||
Image.fromarray(atlas_ormh, mode="RGBA").save(OUT_DIR / "decal_atlas_ormh.png")
|
||||
|
||||
print(f"Wrote 1024x1024 decal atlas textures to {OUT_DIR}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
BIN
tools/decals/previews/visual_substrate_preview.png
Normal file
BIN
tools/decals/previews/visual_substrate_preview.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 749 KiB |
556
tools/vehicles/bake_vertex_weathering.py
Normal file
556
tools/vehicles/bake_vertex_weathering.py
Normal file
|
|
@ -0,0 +1,556 @@
|
|||
"""Bake geometric weathering vertex attributes (COLOR_0) into Brokkr vehicle GLBs.
|
||||
|
||||
Writes COLOR_0 (VEC4 normalized UNSIGNED_BYTE) onto every mesh primitive:
|
||||
R = geometric cavity AO (0 = deep crevice, 1 = open exposed face)
|
||||
G = convex dihedral edge curvature (0 = flat, 1 = sharp exposed edge)
|
||||
B = connected-component per-island hash (0..1)
|
||||
A = normalized rest-pose height above minY (meters / 6.0, clamped 0..1)
|
||||
|
||||
Pure numpy + struct; runs in < 1s per vehicle and is idempotent on re-run.
|
||||
Preserves all glTF nodes, transforms, materials, hardpoint anchors, joints, and bounds.
|
||||
|
||||
Usage:
|
||||
python tools/vehicles/bake_vertex_weathering.py paladin jackal
|
||||
python tools/vehicles/bake_vertex_weathering.py --all
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import struct
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles"
|
||||
|
||||
ALL_VEHICLES = (
|
||||
"jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor",
|
||||
"breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# glTF / GLB helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _node_local_matrix(node: dict[str, Any]) -> np.ndarray:
|
||||
if "matrix" in node:
|
||||
return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T
|
||||
m = np.eye(4, dtype=np.float64)
|
||||
if "scale" in node:
|
||||
sx, sy, sz = node["scale"]
|
||||
m = m @ np.diag([sx, sy, sz, 1.0])
|
||||
if "rotation" in node:
|
||||
qx, qy, qz, qw = node["rotation"]
|
||||
xx, yy, zz = qx * qx, qy * qy, qz * qz
|
||||
xy, xz, yz = qx * qy, qx * qz, qy * qz
|
||||
wx, wy, wz = qw * qx, qw * qy, qw * qz
|
||||
r = np.array([
|
||||
[1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0.0],
|
||||
[2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0.0],
|
||||
[2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
], dtype=np.float64)
|
||||
m = r @ m
|
||||
if "translation" in node:
|
||||
tx, ty, tz = node["translation"]
|
||||
m[:3, 3] = [tx, ty, tz]
|
||||
return m
|
||||
|
||||
|
||||
def _read_accessor(
|
||||
accessors: list[dict[str, Any]],
|
||||
buffer_views: list[dict[str, Any]],
|
||||
bin_blob: bytes,
|
||||
acc_idx: int,
|
||||
) -> np.ndarray:
|
||||
acc = accessors[acc_idx]
|
||||
bv = buffer_views[acc["bufferView"]]
|
||||
off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0)
|
||||
count = acc["count"]
|
||||
ct = acc["componentType"]
|
||||
typ = acc["type"]
|
||||
if typ == "VEC3" and ct == 5126:
|
||||
stride = bv.get("byteStride", 12)
|
||||
if stride == 12:
|
||||
return np.frombuffer(bin_blob, dtype="<f4", count=count * 3, offset=off).reshape(count, 3).astype(np.float64)
|
||||
raw = np.frombuffer(bin_blob, dtype=np.uint8, count=count * stride, offset=off).reshape(count, stride)
|
||||
return raw[:, :12].view("<f4").reshape(count, 3).astype(np.float64)
|
||||
if typ == "SCALAR":
|
||||
dtype = {5121: np.uint8, 5123: "<u2", 5125: "<u4"}[ct]
|
||||
stride = bv.get("byteStride", np.dtype(dtype).itemsize)
|
||||
if stride == np.dtype(dtype).itemsize:
|
||||
return np.frombuffer(bin_blob, dtype=dtype, count=count, offset=off).astype(np.int64)
|
||||
item = np.dtype(dtype).itemsize
|
||||
raw = np.frombuffer(bin_blob, dtype=np.uint8, count=count * stride, offset=off).reshape(count, stride)
|
||||
return raw[:, :item].view(dtype).reshape(count).astype(np.int64)
|
||||
raise ValueError(f"Unsupported accessor type={typ} componentType={ct}")
|
||||
|
||||
|
||||
def _splitmix64_hash(a: int, b: int, c: int) -> float:
|
||||
x = (a * 0x9E3779B97F4A7C15 + b * 0xBF58476D1CE4E5B9 + c * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF
|
||||
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & 0xFFFFFFFFFFFFFFFF
|
||||
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF
|
||||
x = x ^ (x >> 31)
|
||||
return float((x >> 40) & 0xFFFFFF) / float(0x1000000)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fast geometric operators (pure numpy)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _weld_positions(pos: np.ndarray) -> tuple[np.ndarray, int]:
|
||||
"""Quantize positions to 0.1 mm and return (weld_id_per_vert, unique_count)."""
|
||||
q = np.round(pos * 10000.0).astype(np.int64)
|
||||
# View rows as structured void for fast single-pass np.unique
|
||||
q_contig = np.ascontiguousarray(q)
|
||||
view = q_contig.view([("x", np.int64), ("y", np.int64), ("z", np.int64)]).ravel()
|
||||
_, inv = np.unique(view, return_inverse=True)
|
||||
return inv.astype(np.int64), int(inv.max()) + 1 if len(inv) else 0
|
||||
|
||||
|
||||
def _connected_components(n_weld: int, tris_weld: np.ndarray) -> np.ndarray:
|
||||
"""Fast union-find connected components on welded vertex indices."""
|
||||
parent = list(range(n_weld))
|
||||
|
||||
def find(x: int) -> int:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
for a, b, c in tris_weld.tolist():
|
||||
ra, rb, rc = find(a), find(b), find(c)
|
||||
if ra != rb:
|
||||
parent[rb] = ra
|
||||
if ra != rc:
|
||||
parent[rc] = ra
|
||||
|
||||
roots = np.empty(n_weld, dtype=np.int64)
|
||||
root_map: dict[int, int] = {}
|
||||
nxt = 0
|
||||
for i in range(n_weld):
|
||||
r = find(i)
|
||||
cid = root_map.get(r)
|
||||
if cid is None:
|
||||
cid = nxt
|
||||
root_map[r] = cid
|
||||
nxt += 1
|
||||
roots[i] = cid
|
||||
return roots
|
||||
|
||||
|
||||
def _dihedral_edge_and_crevice(
|
||||
pos: np.ndarray,
|
||||
nrm: np.ndarray,
|
||||
tris: np.ndarray,
|
||||
weld_id: np.ndarray,
|
||||
n_weld: int,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Compute (convex_edge_curvature, local_concave_ao) per vertex."""
|
||||
edge_out = np.zeros(len(pos), dtype=np.float32)
|
||||
conc_ao = np.ones(len(pos), dtype=np.float32)
|
||||
if len(tris) == 0 or n_weld == 0:
|
||||
return edge_out, conc_ao
|
||||
|
||||
v0 = pos[tris[:, 0]]
|
||||
v1 = pos[tris[:, 1]]
|
||||
v2 = pos[tris[:, 2]]
|
||||
fn_raw = np.cross(v1 - v0, v2 - v0)
|
||||
fn_len = np.linalg.norm(fn_raw, axis=1, keepdims=True)
|
||||
valid_tri = (fn_len[:, 0] > 1e-12)
|
||||
fn = np.divide(fn_raw, np.maximum(fn_len, 1e-12))
|
||||
fc = (v0 + v1 + v2) / 3.0
|
||||
|
||||
wt = weld_id[tris] # (T, 3)
|
||||
t_idx = np.arange(len(tris), dtype=np.int64)
|
||||
|
||||
e0 = np.stack([np.minimum(wt[:, 0], wt[:, 1]), np.maximum(wt[:, 0], wt[:, 1]), t_idx], axis=1)
|
||||
e1 = np.stack([np.minimum(wt[:, 1], wt[:, 2]), np.maximum(wt[:, 1], wt[:, 2]), t_idx], axis=1)
|
||||
e2 = np.stack([np.minimum(wt[:, 2], wt[:, 0]), np.maximum(wt[:, 2], wt[:, 0]), t_idx], axis=1)
|
||||
edges = np.concatenate([e0, e1, e2], axis=0)
|
||||
# Remove degenerate edges
|
||||
edges = edges[edges[:, 0] != edges[:, 1]]
|
||||
if len(edges) == 0:
|
||||
return edge_out, conc_ao
|
||||
|
||||
order = np.lexsort((edges[:, 1], edges[:, 0]))
|
||||
edges = edges[order]
|
||||
|
||||
same = (edges[:-1, 0] == edges[1:, 0]) & (edges[:-1, 1] == edges[1:, 1])
|
||||
idx_a = edges[:-1, 2][same]
|
||||
idx_b = edges[1:, 2][same]
|
||||
eu = edges[:-1, 0][same]
|
||||
ev = edges[:-1, 1][same]
|
||||
|
||||
both_valid = valid_tri[idx_a] & valid_tri[idx_b]
|
||||
idx_a, idx_b, eu, ev = idx_a[both_valid], idx_b[both_valid], eu[both_valid], ev[both_valid]
|
||||
|
||||
weld_convex_sum = np.zeros(n_weld, dtype=np.float32)
|
||||
weld_convex_cnt = np.zeros(n_weld, dtype=np.float32)
|
||||
weld_convex_max = np.zeros(n_weld, dtype=np.float32)
|
||||
weld_concave = np.zeros(n_weld, dtype=np.float32)
|
||||
|
||||
if len(idx_a) > 0:
|
||||
na = fn[idx_a]
|
||||
nb = fn[idx_b]
|
||||
dots = np.clip(np.sum(na * nb, axis=1), -1.0, 1.0)
|
||||
angles = np.arccos(dots) # radians [0, pi]
|
||||
delta_c = fc[idx_b] - fc[idx_a]
|
||||
# Convex if triangle B center lies behind triangle A's front plane
|
||||
proj_a = np.sum(na * delta_c, axis=1)
|
||||
proj_b = np.sum(nb * (-delta_c), axis=1)
|
||||
sign_val = 0.5 * (proj_a + proj_b)
|
||||
|
||||
is_convex = (sign_val < -1e-5) & (angles > 0.55)
|
||||
is_concave = (sign_val > 1e-5) & (angles > 0.28)
|
||||
|
||||
convex_val = np.where(is_convex, np.clip((angles - 0.55) / 0.95, 0.0, 1.0), 0.0).astype(np.float32)
|
||||
concave_val = np.where(is_concave, np.clip((angles - 0.28) / 1.20, 0.0, 1.0), 0.0).astype(np.float32)
|
||||
|
||||
np.add.at(weld_convex_sum, eu, convex_val)
|
||||
np.add.at(weld_convex_sum, ev, convex_val)
|
||||
np.add.at(weld_convex_cnt, eu, 1.0)
|
||||
np.add.at(weld_convex_cnt, ev, 1.0)
|
||||
np.maximum.at(weld_convex_max, eu, convex_val)
|
||||
np.maximum.at(weld_convex_max, ev, convex_val)
|
||||
np.maximum.at(weld_concave, eu, concave_val)
|
||||
np.maximum.at(weld_concave, ev, concave_val)
|
||||
|
||||
weld_convex_mean = np.divide(weld_convex_sum, np.maximum(weld_convex_cnt, 1.0))
|
||||
weld_convex = 0.55 * weld_convex_mean + 0.45 * weld_convex_max
|
||||
edge_out = weld_convex[weld_id]
|
||||
conc_ao = np.clip(1.0 - 0.55 * weld_concave[weld_id], 0.35, 1.0).astype(np.float32)
|
||||
return edge_out, conc_ao
|
||||
|
||||
|
||||
def _compute_voxel_ao(
|
||||
all_wpos: np.ndarray,
|
||||
all_wnrm: np.ndarray,
|
||||
sample_pts: np.ndarray,
|
||||
) -> np.ndarray:
|
||||
"""Fast 3D spatial occupancy ray-marched AO across the whole rest-pose vehicle."""
|
||||
if len(all_wpos) == 0 or len(sample_pts) == 0:
|
||||
return np.ones(len(all_wpos), dtype=np.float32)
|
||||
|
||||
bmin = sample_pts.min(axis=0)
|
||||
bmax = sample_pts.max(axis=0)
|
||||
extent = np.maximum(bmax - bmin, 0.2)
|
||||
max_ext = float(extent.max())
|
||||
voxel = max(0.075, max_ext / 84.0)
|
||||
pad = voxel * 8.0
|
||||
origin = bmin - pad
|
||||
dims = np.ceil((extent + 2.0 * pad) / voxel).astype(np.int64)
|
||||
nx, ny, nz = int(dims[0]), int(dims[1]), int(dims[2])
|
||||
|
||||
grid = np.zeros((nx, ny, nz), dtype=np.uint8)
|
||||
idx = np.floor((sample_pts - origin) / voxel).astype(np.int64)
|
||||
idx[:, 0] = np.clip(idx[:, 0], 0, nx - 1)
|
||||
idx[:, 1] = np.clip(idx[:, 1], 0, ny - 1)
|
||||
idx[:, 2] = np.clip(idx[:, 2], 0, nz - 1)
|
||||
grid[idx[:, 0], idx[:, 1], idx[:, 2]] = 1
|
||||
grid_flat = grid.ravel()
|
||||
sy = nz
|
||||
sx = ny * nz
|
||||
|
||||
# 18 well-distributed unit ray directions (6 axial + 12 diagonal)
|
||||
raw_dirs = [
|
||||
(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1),
|
||||
(1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0),
|
||||
(1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1),
|
||||
(0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1),
|
||||
]
|
||||
dirs = np.array(raw_dirs, dtype=np.float32)
|
||||
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
|
||||
|
||||
# Start rays slightly outside the vertex surface to prevent self-hit
|
||||
p0 = all_wpos.astype(np.float32) + all_wnrm.astype(np.float32) * (1.35 * voxel)
|
||||
steps = np.array([0.14, 0.25, 0.38, 0.54, 0.72], dtype=np.float32)
|
||||
step_weights = np.array([1.0, 0.85, 0.65, 0.45, 0.28], dtype=np.float32)
|
||||
|
||||
nrm_f = all_wnrm.astype(np.float32)
|
||||
inv_vox = np.float32(1.0 / voxel)
|
||||
orig_f = origin.astype(np.float32)
|
||||
|
||||
occ_acc = np.zeros(len(all_wpos), dtype=np.float32)
|
||||
weight_acc = np.zeros(len(all_wpos), dtype=np.float32)
|
||||
|
||||
for d in dirs:
|
||||
cos_w = np.maximum(nrm_f @ d, 0.0)
|
||||
active = cos_w > 0.08
|
||||
if not np.any(active):
|
||||
continue
|
||||
w_act = cos_w[active]
|
||||
p_act = p0[active]
|
||||
hit_max = np.zeros(len(p_act), dtype=np.float32)
|
||||
|
||||
for st, sw in zip(steps, step_weights):
|
||||
q = p_act + d * st
|
||||
gx = np.floor((q[:, 0] - orig_f[0]) * inv_vox).astype(np.int64)
|
||||
gy = np.floor((q[:, 1] - orig_f[1]) * inv_vox).astype(np.int64)
|
||||
gz = np.floor((q[:, 2] - orig_f[2]) * inv_vox).astype(np.int64)
|
||||
inside = (gx >= 0) & (gx < nx) & (gy >= 0) & (gy < ny) & (gz >= 0) & (gz < nz)
|
||||
if not np.any(inside):
|
||||
continue
|
||||
flat_i = np.where(inside, gx * sx + gy * sy + gz, 0)
|
||||
occ = grid_flat[flat_i] & inside
|
||||
hit_max = np.maximum(hit_max, occ.astype(np.float32) * sw)
|
||||
|
||||
occ_acc[active] += hit_max * w_act
|
||||
weight_acc[active] += w_act
|
||||
|
||||
raw_occ = np.divide(occ_acc, np.maximum(weight_acc, 1e-4))
|
||||
return np.clip(1.0 - raw_occ * 0.92, 0.06, 1.0).astype(np.float32)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GLB baker
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def bake_glb(glb_path: Path) -> dict[str, Any]:
|
||||
t0 = time.perf_counter()
|
||||
data = glb_path.read_bytes()
|
||||
magic, version, total_len = struct.unpack_from("<III", data, 0)
|
||||
if magic != 0x46546C67 or version != 2 or total_len != len(data):
|
||||
raise ValueError(f"Invalid GLB header in {glb_path}")
|
||||
json_len, json_type = struct.unpack_from("<II", data, 12)
|
||||
if json_type != 0x4E4F534A:
|
||||
raise ValueError(f"Expected JSON chunk in {glb_path}")
|
||||
gltf = json.loads(data[20 : 20 + json_len].decode("utf-8"))
|
||||
|
||||
bin_off = 20 + json_len
|
||||
b_len, b_type = struct.unpack_from("<II", data, bin_off)
|
||||
if b_type != 0x004E4942:
|
||||
raise ValueError(f"Expected BIN chunk in {glb_path}")
|
||||
bin_blob = data[bin_off + 8 : bin_off + 8 + b_len]
|
||||
|
||||
# Idempotency: if we previously baked COLOR_0 into this GLB, trim back to the base BIN/views/accessors
|
||||
extras = gltf.get("extras") or {}
|
||||
if "rtd.color0_base_bin_len" in extras:
|
||||
base_bin_len = int(extras["rtd.color0_base_bin_len"])
|
||||
base_bv_count = int(extras["rtd.color0_base_bv_count"])
|
||||
base_acc_count = int(extras["rtd.color0_base_acc_count"])
|
||||
bin_blob = bin_blob[:base_bin_len]
|
||||
gltf["bufferViews"] = gltf["bufferViews"][:base_bv_count]
|
||||
gltf["accessors"] = gltf["accessors"][:base_acc_count]
|
||||
for mesh in gltf.get("meshes", []):
|
||||
for prim in mesh.get("primitives", []):
|
||||
prim.get("attributes", {}).pop("COLOR_0", None)
|
||||
else:
|
||||
base_bin_len = len(bin_blob)
|
||||
base_bv_count = len(gltf.get("bufferViews", []))
|
||||
base_acc_count = len(gltf.get("accessors", []))
|
||||
|
||||
nodes = gltf.get("nodes", [])
|
||||
meshes = gltf.get("meshes", [])
|
||||
accessors = gltf.get("accessors", [])
|
||||
buffer_views = gltf.get("bufferViews", [])
|
||||
scenes = gltf.get("scenes", [])
|
||||
root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes)))
|
||||
|
||||
# Map each mesh index to its first scene node's world matrix
|
||||
mesh_world: dict[int, np.ndarray] = {}
|
||||
|
||||
def walk(node_idx: int, parent_mat: np.ndarray) -> None:
|
||||
node = nodes[node_idx]
|
||||
world = parent_mat @ _node_local_matrix(node)
|
||||
if "mesh" in node and node["mesh"] not in mesh_world:
|
||||
mesh_world[node["mesh"]] = world
|
||||
for c in node.get("children", []):
|
||||
walk(c, world)
|
||||
|
||||
ident = np.eye(4, dtype=np.float64)
|
||||
for r_idx in root_indices:
|
||||
walk(r_idx, ident)
|
||||
|
||||
# Pass 1: Read all primitives, compute rest-pose world positions/normals, edges, islands, and surface samples
|
||||
prim_records: list[dict[str, Any]] = []
|
||||
wpos_chunks: list[np.ndarray] = []
|
||||
wnrm_chunks: list[np.ndarray] = []
|
||||
sample_chunks: list[np.ndarray] = []
|
||||
global_min_y = math.inf
|
||||
vert_cursor = 0
|
||||
|
||||
for m_idx, mesh in enumerate(meshes):
|
||||
wmat = mesh_world.get(m_idx, ident)
|
||||
rot_lin = wmat[:3, :3]
|
||||
det = float(np.linalg.det(rot_lin))
|
||||
nrm_mat = np.linalg.inv(rot_lin).T if abs(det) > 1e-12 else rot_lin
|
||||
|
||||
for p_idx, prim in enumerate(mesh.get("primitives", [])):
|
||||
attrs = prim.get("attributes", {})
|
||||
if "POSITION" not in attrs:
|
||||
continue
|
||||
pos = _read_accessor(accessors, buffer_views, bin_blob, attrs["POSITION"])
|
||||
vcount = len(pos)
|
||||
if vcount == 0:
|
||||
continue
|
||||
if "NORMAL" in attrs:
|
||||
nrm = _read_accessor(accessors, buffer_views, bin_blob, attrs["NORMAL"])
|
||||
else:
|
||||
nrm = np.tile(np.array([0.0, 1.0, 0.0]), (vcount, 1))
|
||||
|
||||
if prim.get("mode", 4) == 4:
|
||||
if "indices" in prim:
|
||||
tris = _read_accessor(accessors, buffer_views, bin_blob, prim["indices"]).reshape(-1, 3)
|
||||
else:
|
||||
tris = np.arange((vcount // 3) * 3, dtype=np.int64).reshape(-1, 3)
|
||||
else:
|
||||
tris = np.empty((0, 3), dtype=np.int64)
|
||||
|
||||
wpos = pos @ rot_lin.T + wmat[:3, 3]
|
||||
wnrm = nrm @ nrm_mat.T
|
||||
wnrm_len = np.linalg.norm(wnrm, axis=1, keepdims=True)
|
||||
wnrm = np.divide(wnrm, np.maximum(wnrm_len, 1e-12))
|
||||
|
||||
global_min_y = min(global_min_y, float(wpos[:, 1].min()))
|
||||
|
||||
weld_id, n_weld = _weld_positions(pos)
|
||||
if len(tris) > 0 and n_weld > 0:
|
||||
comp_weld = _connected_components(n_weld, weld_id[tris])
|
||||
max_c = int(comp_weld.max()) + 1
|
||||
comp_hashes = np.array([_splitmix64_hash(m_idx, p_idx, c) for c in range(max_c)], dtype=np.float32)
|
||||
island_hash = comp_hashes[comp_weld[weld_id]]
|
||||
else:
|
||||
island_hash = np.full(vcount, _splitmix64_hash(m_idx, p_idx, 0), dtype=np.float32)
|
||||
|
||||
edge_curv, local_conc_ao = _dihedral_edge_and_crevice(pos, nrm, tris, weld_id, n_weld)
|
||||
|
||||
# Surface samples for voxel AO (vertices + face centroids + edge midpoints)
|
||||
sample_chunks.append(wpos)
|
||||
if len(tris) > 0:
|
||||
tv0, tv1, tv2 = wpos[tris[:, 0]], wpos[tris[:, 1]], wpos[tris[:, 2]]
|
||||
sample_chunks.append((tv0 + tv1 + tv2) / 3.0)
|
||||
sample_chunks.append((tv0 + tv1) * 0.5)
|
||||
sample_chunks.append((tv1 + tv2) * 0.5)
|
||||
sample_chunks.append((tv2 + tv0) * 0.5)
|
||||
|
||||
wpos_chunks.append(wpos)
|
||||
wnrm_chunks.append(wnrm)
|
||||
prim_records.append({
|
||||
"prim": prim,
|
||||
"vcount": vcount,
|
||||
"vstart": vert_cursor,
|
||||
"edge": edge_curv,
|
||||
"local_ao": local_conc_ao,
|
||||
"island": island_hash,
|
||||
})
|
||||
vert_cursor += vcount
|
||||
|
||||
if not prim_records:
|
||||
raise RuntimeError(f"No mesh primitives found in {glb_path}")
|
||||
|
||||
all_wpos = np.concatenate(wpos_chunks, axis=0)
|
||||
all_wnrm = np.concatenate(wnrm_chunks, axis=0)
|
||||
all_samples = np.concatenate(sample_chunks, axis=0)
|
||||
|
||||
# Pass 2: Global 3D voxel ambient occlusion
|
||||
voxel_ao = _compute_voxel_ao(all_wpos, all_wnrm, all_samples)
|
||||
rest_height = np.clip((all_wpos[:, 1] - global_min_y) / 6.0, 0.0, 1.0).astype(np.float32)
|
||||
|
||||
# Pass 3: Append COLOR_0 bufferViews & accessors cleanly
|
||||
new_bin = bytearray(bin_blob)
|
||||
if len(new_bin) % 4 != 0:
|
||||
new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4)))
|
||||
|
||||
ao_vals = []
|
||||
edge_vals = []
|
||||
for rec in prim_records:
|
||||
s, n = rec["vstart"], rec["vcount"]
|
||||
ao = np.clip(voxel_ao[s : s + n] * rec["local_ao"], 0.0, 1.0)
|
||||
edge = rec["edge"]
|
||||
island = rec["island"]
|
||||
h = rest_height[s : s + n]
|
||||
ao_vals.append(ao)
|
||||
edge_vals.append(edge)
|
||||
|
||||
rgba = np.stack([ao, edge, island, h], axis=1)
|
||||
rgba_u8 = np.clip(np.round(rgba * 255.0), 0, 255).astype(np.uint8)
|
||||
raw_bytes = rgba_u8.tobytes()
|
||||
|
||||
byte_off = len(new_bin)
|
||||
new_bin.extend(raw_bytes)
|
||||
if len(new_bin) % 4 != 0:
|
||||
new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4)))
|
||||
|
||||
bv_idx = len(buffer_views)
|
||||
buffer_views.append({
|
||||
"buffer": 0,
|
||||
"byteOffset": byte_off,
|
||||
"byteLength": len(raw_bytes),
|
||||
"target": 34962, # ARRAY_BUFFER
|
||||
})
|
||||
acc_idx = len(accessors)
|
||||
accessors.append({
|
||||
"bufferView": bv_idx,
|
||||
"byteOffset": 0,
|
||||
"componentType": 5121, # UNSIGNED_BYTE
|
||||
"normalized": True,
|
||||
"count": n,
|
||||
"type": "VEC4",
|
||||
})
|
||||
rec["prim"]["attributes"]["COLOR_0"] = acc_idx
|
||||
|
||||
gltf["buffers"][0]["byteLength"] = len(new_bin)
|
||||
gltf.setdefault("extras", {})
|
||||
gltf["extras"]["rtd.color0_base_bin_len"] = base_bin_len
|
||||
gltf["extras"]["rtd.color0_base_bv_count"] = base_bv_count
|
||||
gltf["extras"]["rtd.color0_base_acc_count"] = base_acc_count
|
||||
|
||||
json_bytes = json.dumps(gltf, separators=(",", ":")).encode("utf-8")
|
||||
if len(json_bytes) % 4 != 0:
|
||||
json_bytes += b" " * (4 - (len(json_bytes) % 4))
|
||||
if len(new_bin) % 4 != 0:
|
||||
new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4)))
|
||||
|
||||
total_out = 12 + 8 + len(json_bytes) + 8 + len(new_bin)
|
||||
out = bytearray()
|
||||
out.extend(struct.pack("<III", 0x46546C67, 2, total_out))
|
||||
out.extend(struct.pack("<II", len(json_bytes), 0x4E4F534A))
|
||||
out.extend(json_bytes)
|
||||
out.extend(struct.pack("<II", len(new_bin), 0x004E4942))
|
||||
out.extend(new_bin)
|
||||
|
||||
glb_path.write_bytes(bytes(out))
|
||||
elapsed = time.perf_counter() - t0
|
||||
all_ao = np.concatenate(ao_vals)
|
||||
all_edge = np.concatenate(edge_vals)
|
||||
return {
|
||||
"verts": vert_cursor,
|
||||
"prims": len(prim_records),
|
||||
"elapsed_s": elapsed,
|
||||
"ao_min": float(all_ao.min()),
|
||||
"ao_mean": float(all_ao.mean()),
|
||||
"edge_mean": float(all_edge.mean()),
|
||||
"edge_gt_03": float((all_edge > 0.3).mean()),
|
||||
"size_kib": len(out) / 1024.0,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Bake COLOR_0 weathering attributes onto vehicle GLBs.")
|
||||
parser.add_argument("vehicles", nargs="*", help="Vehicle IDs to bake (e.g. paladin jackal).")
|
||||
parser.add_argument("--all", action="store_true", help="Bake all 15 vehicles.")
|
||||
args = parser.parse_args()
|
||||
|
||||
targets = ALL_VEHICLES if args.all else (tuple(args.vehicles) if args.vehicles else ("paladin", "jackal"))
|
||||
for vid in targets:
|
||||
glb_path = VEHICLES_DIR / vid / f"{vid}.glb"
|
||||
if not glb_path.is_file():
|
||||
raise FileNotFoundError(f"Missing vehicle GLB: {glb_path}")
|
||||
stats = bake_glb(glb_path)
|
||||
print(
|
||||
f"Baked {vid:10s} | verts={stats['verts']:6d} | prims={stats['prims']:3d} "
|
||||
f"| {stats['elapsed_s']:.3f}s | ao=[{stats['ao_min']:.2f}, mean={stats['ao_mean']:.2f}] "
|
||||
f"| edge>0.3={stats['edge_gt_03']*100:.1f}% | {stats['size_kib']:.1f} KiB"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Loading…
Reference in a new issue