Merge nibu/rtd-visuals: Brokkr mech_paint shader, POM decal atlas/shader, and vertex weathering baker

This commit is contained in:
Meta Vens 2026-12-04 23:33:12 +01:00
commit 0fa1de2dce
12 changed files with 2419 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 787 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 491 KiB

Binary file not shown.

Binary file not shown.

140
client/decal_pom.gdshader Normal file
View file

@ -0,0 +1,140 @@
shader_type spatial;
render_mode blend_mix, depth_draw_never, cull_back;
// OpenGL 3.3 (gl_compatibility) Parallax Occlusion Mapping (POM) decal shader for MultiMeshInstance3D.
// Renders hundreds of hard-surface vents, hatches, stencils, and live combat hits in 1 draw call.
//
// INSTANCE_CUSTOM layout:
// x = tile_index (0..15 in 4x4 trim-sheet atlas)
// y = heat_glow (0..1, incandescent glow on rolled rim & core of fresh combat hits)
// z = opacity (0..1)
// w = depth_scale (default ~0.06 when 0)
//
// Atlas textures (assets/decals/):
// albedo_tex : RGBA albedo + alpha mask
// normal_tex : tangent-space normal map (+X right, +Y down, +Z out)
// ormh_tex : R=AO, G=Roughness, B=Metallic, A=Height (1.0=flush surface, 0.0=deep recess)
uniform sampler2D albedo_tex : source_color, filter_linear_mipmap, repeat_disable;
uniform sampler2D normal_tex : hint_normal, filter_linear_mipmap, repeat_disable;
uniform sampler2D ormh_tex : filter_linear_mipmap, repeat_disable;
uniform bool use_instance_custom = true;
uniform float fallback_tile_index : hint_range(0.0, 15.0) = 0.0;
uniform float fallback_heat_glow : hint_range(0.0, 1.0) = 0.0;
uniform float fallback_opacity : hint_range(0.0, 1.0) = 1.0;
uniform float default_depth_scale : hint_range(0.0, 0.25) = 0.06;
uniform float normal_offset : hint_range(0.0, 0.02) = 0.004;
uniform float normal_depth : hint_range(0.0, 3.0) = 1.15;
uniform float heat_emission_energy : hint_range(0.0, 10.0) = 2.6;
varying vec4 v_custom;
void vertex() {
VERTEX += NORMAL * normal_offset;
if (use_instance_custom) {
v_custom = INSTANCE_CUSTOM;
} else {
v_custom = vec4(fallback_tile_index, fallback_heat_glow, fallback_opacity, default_depth_scale);
}
}
void fragment() {
const int POM_STEPS = 10;
const float CELL_SIZE = 0.25;
float tile_idx = floor(clamp(v_custom.x + 0.5, 0.0, 15.0));
float heat_glow = clamp(v_custom.y, 0.0, 1.0);
float opacity = clamp(v_custom.z, 0.0, 1.0);
float depth_scale = v_custom.w > 0.0001 ? v_custom.w : default_depth_scale;
float col_idx = mod(tile_idx, 4.0);
float row_idx = floor(tile_idx * 0.25);
vec2 cell_origin = vec2(col_idx, row_idx) * CELL_SIZE;
// Hoist screen-space derivatives above any non-uniform control flow / discard (GLSL 330 safety)
vec2 d_uv_dx = dFdx(UV * CELL_SIZE);
vec2 d_uv_dy = dFdy(UV * CELL_SIZE);
// Soft outer edge fade on local quad UV
float edge_fade = smoothstep(0.0, 0.04, UV.x)
* smoothstep(1.0, 0.96, UV.x)
* smoothstep(0.0, 0.04, UV.y)
* smoothstep(1.0, 0.96, UV.y);
// Tangent-space view ray (Godot fragment VIEW, TANGENT, BINORMAL, NORMAL are all in view space)
vec3 t_dir = normalize(TANGENT);
vec3 b_dir = normalize(BINORMAL);
vec3 n_dir = normalize(NORMAL);
vec3 view_ts = normalize(vec3(dot(VIEW, t_dir), dot(VIEW, b_dir), dot(VIEW, n_dir)));
// Clamp grazing Z so oblique rays stay well-behaved without sliding out of the tile
float vz = max(view_ts.z, 0.22);
vec2 p_dir = -(view_ts.xy / vz) * depth_scale;
// 10 linear POM steps from surface (layer_depth=0, height=1) into recess (layer_depth=1, height=0)
float step_size = 1.0 / float(POM_STEPS);
vec2 delta_uv = p_dir * step_size;
vec2 cur_uv = UV;
float cur_layer_depth = 0.0;
float cur_tex_depth = 1.0 - textureLod(ormh_tex, cell_origin + clamp(cur_uv, 0.002, 0.998) * CELL_SIZE, 0.0).a;
vec2 prev_uv = cur_uv;
float prev_layer_depth = cur_layer_depth;
float prev_tex_depth = cur_tex_depth;
for (int i = 0; i < POM_STEPS; i++) {
if (cur_layer_depth >= cur_tex_depth) {
break;
}
prev_uv = cur_uv;
prev_layer_depth = cur_layer_depth;
prev_tex_depth = cur_tex_depth;
cur_uv += delta_uv;
cur_layer_depth += step_size;
cur_tex_depth = 1.0 - textureLod(ormh_tex, cell_origin + clamp(cur_uv, 0.002, 0.998) * CELL_SIZE, 0.0).a;
}
// 1 secant interpolation step
float after_d = cur_tex_depth - cur_layer_depth;
float before_d = prev_tex_depth - prev_layer_depth;
float denom = after_d - before_d;
float weight = abs(denom) > 1e-5 ? clamp(after_d / denom, 0.0, 1.0) : 0.0;
vec2 final_uv = mix(cur_uv, prev_uv, weight);
// Discard cleanly outside tile bounds so adjacent atlas cells never bleed
if (final_uv.x < 0.002 || final_uv.x > 0.998 || final_uv.y < 0.002 || final_uv.y > 0.998) {
discard;
}
vec2 atlas_uv = cell_origin + final_uv * CELL_SIZE;
vec4 alb = textureGrad(albedo_tex, atlas_uv, d_uv_dx, d_uv_dy);
vec3 nrm_sample = textureGrad(normal_tex, atlas_uv, d_uv_dx, d_uv_dy).rgb;
vec4 ormh = textureGrad(ormh_tex, atlas_uv, d_uv_dx, d_uv_dy);
float out_alpha = alb.a * edge_fade * opacity;
if (out_alpha < 0.015) {
discard;
}
// Emissive rim & molten crater mask for combat hits (Row 3: tiles 12..15)
float is_combat = step(11.5, tile_idx);
// Rolled metallic lip & crater wall glow hot while keeping pitch-black bore contrast
float rim_band = smoothstep(0.94, 0.50, ormh.a) * smoothstep(0.08, 0.55, ormh.b);
float bore_inner_ring = smoothstep(0.35, 0.10, ormh.a) * smoothstep(0.01, 0.16, ormh.a);
float hot_mask = clamp((rim_band * 1.15 + bore_inner_ring * 0.45) * is_combat, 0.0, 1.0);
float hot_intensity = heat_glow * hot_mask;
vec3 hot_col = mix(vec3(0.95, 0.18, 0.02), vec3(1.0, 0.58, 0.14), smoothstep(0.25, 0.90, hot_intensity));
ALBEDO = alb.rgb;
ALPHA = out_alpha;
NORMAL_MAP = nrm_sample;
NORMAL_MAP_DEPTH = normal_depth;
AO = ormh.r;
AO_LIGHT_AFFECT = 0.85;
ROUGHNESS = clamp(ormh.g, 0.12, 0.98);
METALLIC = clamp(ormh.b, 0.0, 1.0);
EMISSION = hot_col * (hot_intensity * heat_emission_energy);
}

225
client/mech_paint.gdshader Normal file
View file

@ -0,0 +1,225 @@
shader_type spatial;
render_mode cull_back, depth_draw_opaque;
// Real-time GLSL 330 (gl_compatibility) port of Brokkr's 6-layer MechPaint.
// Samples 3D procedural noise in rest-pose object space (v_local_pos, v_local_nrm)
// so weathering never swims during skeletal/joint animation or chassis motion.
//
// Expects baked vertex COLOR_0:
// R = geometric cavity AO (0 = deep crevice, 1 = open exposed face)
// G = convex dihedral edge curvature (0 = flat, 1 = sharp exposed edge)
// B = per-island connected-component hash (0..1)
// A = rest-pose height above ground (meters / 6.0, clamped 0..1)
//
// Live combat channels (via INSTANCE_CUSTOM or uniform fallback for non-MultiMesh):
// INSTANCE_CUSTOM.x / scorch (0..1) -> char/soot darkening + matte roughness
// INSTANCE_CUSTOM.y / heat_glow (0..1) -> incandescent orange-red emission without cloning materials
uniform vec4 base_color : source_color = vec4(0.306, 0.341, 0.251, 1.0);
uniform float roughness : hint_range(0.0, 1.0) = 0.58;
uniform float metallic : hint_range(0.0, 1.0) = 0.28;
uniform float tone_variation : hint_range(0.0, 1.0) = 0.30;
uniform float mottle : hint_range(0.0, 2.0) = 1.0;
uniform float noise_scale : hint_range(0.1, 10.0) = 1.0;
uniform float grime : hint_range(0.0, 2.0) = 0.90;
uniform vec4 grime_color : source_color = vec4(0.145, 0.133, 0.114, 1.0);
uniform float streaks : hint_range(0.0, 2.0) = 0.95;
uniform float dust : hint_range(0.0, 2.0) = 0.55;
uniform vec4 dust_color : source_color = vec4(0.451, 0.431, 0.388, 1.0);
uniform float wear : hint_range(0.0, 2.5) = 0.95;
uniform vec4 chip_color : source_color = vec4(0.460, 0.470, 0.465, 1.0);
uniform float chip_metallic : hint_range(0.0, 1.0) = 0.85;
uniform float chip_roughness : hint_range(0.0, 1.0) = 0.28;
uniform vec4 primer_color : source_color = vec4(0.345, 0.325, 0.286, 1.0);
uniform float mud : hint_range(0.0, 2.0) = 1.0;
uniform float mud_top : hint_range(0.1, 5.0) = 1.45;
uniform vec4 mud_color : source_color = vec4(0.180, 0.148, 0.118, 1.0);
uniform float wet : hint_range(0.0, 2.0) = 0.60;
uniform float wet_top : hint_range(0.1, 6.0) = 2.80;
uniform float scorch : hint_range(0.0, 1.0) = 0.0;
uniform float heat_glow : hint_range(0.0, 1.0) = 0.0;
uniform float heat_emission_energy : hint_range(0.0, 8.0) = 2.6;
varying vec3 v_local_pos;
varying vec3 v_local_nrm;
varying vec4 v_color;
varying float v_scorch;
varying float v_heat;
// Safe remapping helper supporting inverted bounds (lo > hi) without GLSL smoothstep UB.
float map_range(float v, float lo, float hi, float out_lo, float out_hi) {
float denom = hi - lo;
float t = abs(denom) > 1e-6 ? clamp((v - lo) / denom, 0.0, 1.0) : 0.0;
t = t * t * (3.0 - 2.0 * t);
return mix(out_lo, out_hi, t);
}
float hash31(vec3 p) {
p = fract(p * vec3(0.1031, 0.1030, 0.0973));
p += dot(p, p.yxz + 33.33);
return fract((p.x + p.y) * p.z);
}
float noise3d(vec3 p) {
vec3 i = floor(p);
vec3 f = fract(p);
vec3 u = f * f * (3.0 - 2.0 * f);
float n000 = hash31(i + vec3(0.0, 0.0, 0.0));
float n100 = hash31(i + vec3(1.0, 0.0, 0.0));
float n010 = hash31(i + vec3(0.0, 1.0, 0.0));
float n110 = hash31(i + vec3(1.0, 1.0, 0.0));
float n001 = hash31(i + vec3(0.0, 0.0, 1.0));
float n101 = hash31(i + vec3(1.0, 0.0, 1.0));
float n011 = hash31(i + vec3(0.0, 1.0, 1.0));
float n111 = hash31(i + vec3(1.0, 1.0, 1.0));
float nx00 = mix(n000, n100, u.x);
float nx10 = mix(n010, n110, u.x);
float nx01 = mix(n001, n101, u.x);
float nx11 = mix(n011, n111, u.x);
float nxy0 = mix(nx00, nx10, u.y);
float nxy1 = mix(nx01, nx11, u.y);
return mix(nxy0, nxy1, u.z);
}
float fbm2(vec3 p) {
// Rotate second octave to eliminate cubic lattice grid alignment
const mat3 rot = mat3(
vec3(0.80, -0.48, 0.36),
vec3(0.60, 0.64, -0.48),
vec3(0.00, 0.60, 0.80)
);
float a = noise3d(p);
float b = noise3d((rot * p) * 2.17 + vec3(17.3, 9.1, 23.7));
float c = noise3d((rot * p) * 4.61 + vec3(5.7, 31.4, 11.2));
return a * 0.55 + b * 0.30 + c * 0.15;
}
vec3 rgb_to_hsv(vec3 c) {
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-6;
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
vec3 hsv_to_rgb(vec3 c) {
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
void vertex() {
v_local_pos = VERTEX;
v_local_nrm = NORMAL;
v_color = COLOR;
v_scorch = clamp(max(INSTANCE_CUSTOM.x, scorch), 0.0, 1.0);
v_heat = clamp(max(INSTANCE_CUSTOM.y, heat_glow), 0.0, 1.0);
}
void fragment() {
vec3 pos = v_local_pos * noise_scale;
vec3 nrm = normalize(v_local_nrm);
float up = nrm.y;
float occ = clamp(v_color.r, 0.0, 1.0);
float edge = clamp(v_color.g, 0.0, 1.0);
float island_rand = clamp(v_color.b, 0.0, 1.0);
float height_m = clamp(v_color.a, 0.0, 1.0) * 6.0;
// Layer 1: Base paint + per-island tone variation + 2-octave 3D object-space mottle
float rand2 = fract(island_rand * 7.31 + 0.37);
vec3 hsv = rgb_to_hsv(base_color.rgb);
hsv.x = fract(hsv.x + (rand2 - 0.5) * tone_variation * 0.14);
hsv.y = clamp(hsv.y * (1.0 + (rand2 - 0.5) * tone_variation * 0.75), 0.0, 1.0);
hsv.z = clamp(hsv.z * (1.0 + (island_rand * 2.0 - 1.0) * tone_variation * 0.65), 0.01, 2.0);
vec3 col = hsv_to_rgb(hsv);
float blotch = fbm2(pos * 0.75);
float speck = fbm2(pos * 26.0);
float mid_n = fbm2(pos * 4.5);
float shade = map_range(blotch, 0.25, 0.75, -0.14, 0.14)
+ map_range(speck, 0.25, 0.75, -0.07, 0.07)
+ map_range(mid_n, 0.25, 0.75, -0.09, 0.09);
col *= clamp(1.0 + shade * mottle, 0.55, 1.35);
// Layer 2: Cavity grime darkening + roughness boost from (1 - AO)
float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(fbm2(pos * 5.0), 0.30, 0.65, 0.45, 1.0) * grime, 0.0, 1.0);
float film = clamp(map_range(fbm2(pos * 2.1), 0.54, 0.72, 0.0, 1.0) * 0.30 * grime, 0.0, 1.0);
float grime_amt = max(cavity, film);
col = mix(col, grime_color.rgb, min(grime_amt, 0.85));
// Layer 3: Vertical rain/oil streaks on upright surfaces boosted by cavity
vec3 stretch = pos * vec3(13.0, 0.5, 13.0);
float upright = map_range(abs(up), 0.80, 0.35, 0.0, 1.0);
float under = map_range(occ, 0.96, 0.65, 0.40, 1.0);
float broken = map_range(noise3d(pos * 1.4), 0.35, 0.55, 0.15, 1.0);
float dark_run = clamp(map_range(fbm2(stretch), 0.52, 0.68, 0.0, 1.0) * upright * under * broken * streaks, 0.0, 1.0);
float pale_run = clamp(map_range(fbm2(stretch + vec3(31.0, 5.0, 17.0)), 0.62, 0.76, 0.0, 1.0) * upright * 0.28 * streaks, 0.0, 1.0);
col = mix(col, dust_color.rgb, pale_run);
col = mix(col, grime_color.rgb, dark_run * 0.85);
// Layer 4: Pale dust on upward-facing normals (v_local_nrm.y)
float dust_amt = clamp(map_range(up, 0.45, 0.95, 0.0, 1.0) * map_range(fbm2(pos * 3.0), 0.25, 0.70, 0.25, 1.0) * dust * 0.55, 0.0, 1.0);
col = mix(col, dust_color.rgb, dust_amt);
// Layer 5: Metallic edge chipping + thin primer_color halo from edge_curvature * noise
float exposed = map_range(occ, 0.42, 0.88, 0.0, 1.0);
float edge_sharp = pow(edge, 1.85);
float chip_n = map_range(fbm2(pos * 6.5), 0.30, 0.72, 0.0, 0.44)
+ map_range(noise3d(pos * 46.0), 0.30, 0.70, -0.06, 0.06);
float wear_level = chip_n + edge_sharp * exposed * wear * 0.56;
float scuff = map_range(fbm2(pos * 4.5), 0.68, 0.72, 0.0, 1.0) * clamp(wear / 1.8, 0.0, 1.0) * 0.55;
float chip_metal_mask = clamp(max(map_range(wear_level, 0.76, 0.80, 0.0, 1.0), scuff * 0.85), 0.0, 1.0);
float primer_mask = clamp(max(map_range(wear_level, 0.71, 0.75, 0.0, 1.0), scuff), 0.0, 1.0);
col = mix(col, primer_color.rgb, primer_mask * 0.75);
col = mix(col, chip_color.rgb, chip_metal_mask);
// Layer 6: Lower-hull/foot mud & wet gloss driven by rest_height (COLOR.a)
float wet_amt = clamp(map_range(height_m, wet_top, 0.0, 0.0, 1.0) * wet, 0.0, 1.0);
col *= (1.0 - 0.50 * wet_amt);
float mud_n = fbm2(pos * 3.2);
float thick = map_range(height_m, mud_top, 0.0, 0.0, 1.0)
* map_range(mud_n, 0.35, 0.62, 0.1, 1.5)
* map_range(occ, 0.95, 0.50, 0.7, 1.6) * mud;
float splash = map_range(fbm2(pos * 11.0), 0.62, 0.66, 0.0, 1.0)
* map_range(height_m, mud_top * 2.2, mud_top * 0.4, 0.0, 1.0) * mud * 0.85;
float mud_amt = clamp(max(map_range(thick, 0.20, 0.50, 0.0, 1.0), splash), 0.0, 1.0);
col = mix(col, mud_color.rgb * map_range(mud_n, 0.30, 0.70, 0.70, 1.30), mud_amt);
// PBR metallic & roughness synthesis
float out_metallic = mix(metallic, chip_metallic, chip_metal_mask);
out_metallic *= (1.0 - mud_amt) * (1.0 - grime_amt * 0.70);
float out_rough = roughness + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(grime, 0.0, 1.0);
out_rough = mix(out_rough, chip_roughness, chip_metal_mask);
out_rough -= wet_amt * 0.18;
out_rough += mud_amt * 0.18;
out_rough = clamp(out_rough, 0.12, 0.98);
// Live combat channel 1: scorch (char/soot darkening + matte roughness)
float soot_pat = mix(0.65, 1.0, fbm2(pos * 4.5));
float scorch_mask = clamp(v_scorch * soot_pat, 0.0, 1.0);
col = mix(col, vec3(0.022, 0.018, 0.016), scorch_mask * 0.88);
out_metallic *= (1.0 - scorch_mask * 0.75);
out_rough = mix(out_rough, 0.94, scorch_mask);
// Live combat channel 2: heat_glow (incandescent orange-red emission without cloning material)
float heat_mod = mix(0.25, 1.15, pow(edge, 1.4) * 0.6 + fbm2(pos * 3.8) * 0.4);
float h_val = clamp(v_heat * heat_mod, 0.0, 1.0);
vec3 heat_col = mix(vec3(0.85, 0.12, 0.01), vec3(1.0, 0.52, 0.10), smoothstep(0.25, 0.95, h_val));
ALBEDO = col;
METALLIC = clamp(out_metallic, 0.0, 1.0);
ROUGHNESS = out_rough;
AO = mix(1.0, occ, 0.65);
AO_LIGHT_AFFECT = 0.65;
EMISSION = heat_col * (pow(v_heat, 1.35) * heat_mod * heat_emission_energy);
}

553
client/tests/VisualProbe.cs Normal file
View file

@ -0,0 +1,553 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Godot;
namespace RustToDust.Client.Tests;
/// <summary>
/// Live OpenGL 3.3 (gl_compatibility) visual verification probe for:
/// - Baked COLOR_0 vertex weathering (AO, edge curvature, per-island hash, rest height)
/// - Brokkr 6-layer MechPaint spatial shader (mech_paint.gdshader) + INSTANCE_CUSTOM scorch/heat
/// - 4x4 POM MultiMesh decal atlas + decal_pom.gdshader in 1 draw call
/// Captures a 1280x720 preview PNG to tools/decals/previews/visual_substrate_preview.png and %TEMP%.
/// </summary>
public partial class VisualProbe : Node3D
{
private readonly List<string> _failures = new();
private readonly List<IDisposable> _disposables = new();
public override void _Ready() => _ = RunAsync();
public override void _ExitTree()
{
foreach (var d in _disposables)
{
d.Dispose();
}
_disposables.Clear();
}
private void Check(bool cond, string msg)
{
if (!cond)
{
_failures.Add(msg);
GD.PushError("VISUAL_PROBE FAIL: " + msg);
}
}
private async Task RunAsync()
{
int exitCode = 0;
try
{
string repoRoot = Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), ".."));
string decalsDir = Path.Combine(repoRoot, "assets", "decals");
string previewRepoPath = Path.Combine(repoRoot, "tools", "decals", "previews", "visual_substrate_preview.png");
string previewTempPath = Path.Combine(Path.GetTempPath(), "visual_substrate_preview.png");
SetupEnvironment();
var mechShader = GD.Load<Shader>("res://mech_paint.gdshader");
var decalShader = GD.Load<Shader>("res://decal_pom.gdshader");
Check(mechShader is not null, "Failed to load res://mech_paint.gdshader");
Check(decalShader is not null, "Failed to load res://decal_pom.gdshader");
if (mechShader is null || decalShader is null)
{
Finish(1);
return;
}
ImageTexture albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png"));
ImageTexture normalTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_normal.png"));
ImageTexture ormhTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_ormh.png"));
var cache = new VehicleAssetCache();
_disposables.Add(cache);
var paladinTpl = cache.GetOrLoadVehicle("paladin");
var jackalTpl = cache.GetOrLoadVehicle("jackal");
VerifyBakedVertexColors("paladin", paladinTpl.BakedStaticMesh);
VerifyBakedVertexColors("jackal", jackalTpl.BakedStaticMesh);
// Ground desert pad
var groundMesh = new PlaneMesh { Size = new Vector2(48f, 48f) };
var groundMat = new StandardMaterial3D
{
AlbedoColor = new Color(0.42f, 0.34f, 0.24f),
Roughness = 0.94f,
Metallic = 0.02f
};
AddChild(new MeshInstance3D { Name = "DesertPad", Mesh = groundMesh, MaterialOverride = groundMat });
// Shared MechPaint ShaderMaterial variants (zero per-hit cloning)
var paladinArmorMat = MakeMechPaintMat(mechShader, new Color(0.306f, 0.341f, 0.251f), metallic: 0.22f, roughness: 0.58f, wear: 1.05f, grime: 0.95f, mud: 1.15f);
var jackalArmorMat = MakeMechPaintMat(mechShader, new Color(0.388f, 0.345f, 0.255f), metallic: 0.20f, roughness: 0.56f, wear: 1.15f, grime: 0.95f, mud: 1.25f, mudTop: 0.95f);
var gunmetalMat = MakeMechPaintMat(mechShader, new Color(0.173f, 0.188f, 0.180f), metallic: 0.78f, roughness: 0.42f, wear: 0.80f, grime: 1.10f, mud: 1.05f);
var copperMat = MakeMechPaintMat(mechShader, new Color(0.612f, 0.353f, 0.204f), metallic: 0.86f, roughness: 0.34f, wear: 0.65f, grime: 0.90f, mud: 0.80f);
var orangeMat = MakeMechPaintMat(mechShader, new Color(0.851f, 0.424f, 0.153f), metallic: 0.18f, roughness: 0.44f, wear: 1.10f, grime: 0.85f, mud: 0.90f);
var markMat = MakeMechPaintMat(mechShader, new Color(0.760f, 0.730f, 0.640f), metallic: 0.10f, roughness: 0.62f, wear: 0.95f, grime: 0.80f, mud: 0.80f);
// Spawn Paladin (left-center, 3/4 view toward camera)
var paladinMesh = (ArrayMesh)paladinTpl.BakedStaticMesh.Duplicate();
ApplyMechPaintSurfaces(paladinMesh, paladinArmorMat, gunmetalMat, copperMat, orangeMat, markMat);
var paladinXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(24f)), new Vector3(-2.8f, 0f, -2.4f));
var paladinMi = new MeshInstance3D
{
Name = "PaladinWeathered",
Mesh = paladinMesh,
Transform = paladinXf
};
AddChild(paladinMi);
// Spawn Jackal (right-midground, angled 3/4 toward camera)
var jackalMesh = (ArrayMesh)jackalTpl.BakedStaticMesh.Duplicate();
ApplyMechPaintSurfaces(jackalMesh, jackalArmorMat, gunmetalMat, copperMat, orangeMat, markMat);
var jackalXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-38f)), new Vector3(3.4f, 0f, 1.2f));
var jackalMi = new MeshInstance3D
{
Name = "JackalWeathered",
Mesh = jackalMesh,
Transform = jackalXf
};
AddChild(jackalMi);
// Foreground angled Armor Showcase Slab (MechPaint via MultiMesh showing clean vs INSTANCE_CUSTOM scorch+heat)
var slabMesh = BuildBeveledShowcaseSlab(3.2f, 1.26f, 0.14f);
var slabMm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseCustomData = true,
Mesh = slabMesh,
InstanceCount = 2
};
var slabXf0 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(14f)) * new Basis(Vector3.Right, Mathf.DegToRad(-22f)), new Vector3(1.15f, 1.85f, 6.2f));
var slabXf1 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-18f)) * new Basis(Vector3.Right, Mathf.DegToRad(-18f)) * Basis.FromScale(new Vector3(0.45f, 0.55f, 1.0f)), new Vector3(5.35f, 0.85f, 3.8f));
slabMm.SetInstanceTransform(0, slabXf0);
slabMm.SetInstanceCustomData(0, new Color(0.0f, 0.0f, 0f, 0f)); // clean weathered chest-height plate
slabMm.SetInstanceTransform(1, slabXf1);
slabMm.SetInstanceCustomData(1, new Color(0.90f, 0.48f, 0f, 0f)); // live combat scorch + heat_glow without cloning!
var slabMmi = new MultiMeshInstance3D
{
Name = "ShowcaseArmorPlates",
Multimesh = slabMm,
MaterialOverride = paladinArmorMat
};
AddChild(slabMmi);
// Build 1 single MultiMeshInstance3D batch of POM decals across Paladin, Jackal, and the Showcase Slab
var decalMat = new ShaderMaterial { Shader = decalShader };
decalMat.SetShaderParameter("albedo_tex", albedoTex);
decalMat.SetShaderParameter("normal_tex", normalTex);
decalMat.SetShaderParameter("ormh_tex", ormhTex);
decalMat.SetShaderParameter("use_instance_custom", true);
decalMat.SetShaderParameter("default_depth_scale", 0.06f);
decalMat.SetShaderParameter("normal_offset", 0.004f);
var decalPlacements = new List<(Transform3D Xform, Color Custom)>();
// Showcase slab POM decals (close 3/4 grazing angle so 3D depth & hot rims are unmistakable)
AddSlabDecal(decalPlacements, slabXf0, -1.16f, 0.30f, 0.07f, 0.48f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // louvered vent
AddSlabDecal(decalPlacements, slabXf0, -0.58f, 0.30f, 0.07f, 0.48f, tile: 1, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // bolted hatch
AddSlabDecal(decalPlacements, slabXf0, 0.00f, 0.30f, 0.07f, 0.48f, tile: 3, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // slotted intake grille
AddSlabDecal(decalPlacements, slabXf0, 0.58f, 0.30f, 0.07f, 0.48f, tile: 5, heat: 0.0f, opacity: 1.0f, depth: 0.070f); // welded patch
AddSlabDecal(decalPlacements, slabXf0, 1.16f, 0.30f, 0.07f, 0.46f, tile: 8, heat: 0.0f, opacity: 0.96f, depth: 0.03f); // stencil "03"
AddSlabDecal(decalPlacements, slabXf0, -1.16f, -0.30f, 0.07f, 0.48f, tile: 6, heat: 0.0f, opacity: 1.0f, depth: 0.085f); // lift-lug pocket
AddSlabDecal(decalPlacements, slabXf0, -0.58f, -0.30f, 0.07f, 0.48f, tile: 7, heat: 0.0f, opacity: 0.96f, depth: 0.04f); // hazard chevron
AddSlabDecal(decalPlacements, slabXf0, 0.00f, -0.30f, 0.07f, 0.50f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.095f); // glowing AP hole
AddSlabDecal(decalPlacements, slabXf0, 0.58f, -0.30f, 0.07f, 0.50f, tile: 13, heat: 0.75f, opacity: 1.0f, depth: 0.085f); // shrapnel gouge
AddSlabDecal(decalPlacements, slabXf0, 1.16f, -0.30f, 0.07f, 0.50f, tile: 14, heat: 0.92f, opacity: 1.0f, depth: 0.090f); // molten plasma crater
// Raycast flush decals directly onto Paladin armor surfaces
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.6f, 8.2f, 3.0f), new Vector3(0f, -0.05f, -1f), 0.72f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.07f);
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-1.5f, 8.8f, 3.0f), new Vector3(-0.2f, -0.05f, -1f), 0.65f, tile: 8, heat: 0.0f, opacity: 0.95f, depth: 0.03f);
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.8f, 7.1f, 3.0f), new Vector3(0.05f, 0f, -1f), 0.72f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.09f);
TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-3.6f, 7.8f, 3.0f), new Vector3(0.25f, 0f, -1f), 0.65f, tile: 10, heat: 0.0f, opacity: 0.95f, depth: 0.03f);
// Raycast flush decals onto Jackal armor surfaces
TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.4f, 3.0f, 1.5f), new Vector3(0f, -1f, 0.1f), 0.55f, tile: 9, heat: 0.0f, opacity: 0.95f, depth: 0.03f);
TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.1f, 2.5f, 2.1f), new Vector3(0.2f, -0.8f, -0.5f), 0.50f, tile: 14, heat: 0.85f, opacity: 1.0f, depth: 0.08f);
var decalQuad = new QuadMesh { Size = Vector2.One };
var decalMm = new MultiMesh
{
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
UseCustomData = true,
Mesh = decalQuad,
InstanceCount = decalPlacements.Count
};
for (int i = 0; i < decalPlacements.Count; i++)
{
decalMm.SetInstanceTransform(i, decalPlacements[i].Xform);
decalMm.SetInstanceCustomData(i, decalPlacements[i].Custom);
}
var decalMmi = new MultiMeshInstance3D
{
Name = "PomDecalsBatch",
Multimesh = decalMm,
MaterialOverride = decalMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
AddChild(decalMmi);
// Camera framing full Paladin (head to feet) + Jackal + close grazing showcase slab
var cam = new Camera3D
{
Name = "ProbeCamera",
Current = true,
Fov = 48f,
Near = 0.08f,
Far = 200f
};
AddChild(cam);
cam.GlobalPosition = new Vector3(2.8f, 4.3f, 13.4f);
cam.LookAt(new Vector3(0.0f, 4.4f, 0.2f), Vector3.Up);
// Wait several rendered frames so OpenGL 3.3 compiles all shaders and finishes drawing
for (int f = 0; f < 6; f++)
{
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
if (DisplayServer.GetName() != "headless")
{
Image? cap = GetViewport().GetTexture()?.GetImage();
Check(cap is not null && cap.GetWidth() == 1280 && cap.GetHeight() == 720,
$"Expected 1280x720 viewport capture, got {cap?.GetWidth()}x{cap?.GetHeight()}");
if (cap is not null)
{
Directory.CreateDirectory(Path.GetDirectoryName(previewRepoPath)!);
cap.SavePng(previewRepoPath);
cap.SavePng(previewTempPath);
GD.Print($"VISUAL_PROBE SAVED: {previewRepoPath}");
GD.Print($"VISUAL_PROBE SAVED: {previewTempPath}");
}
}
double drawCalls = RenderingServer.GetRenderingInfo(RenderingServer.RenderingInfo.TotalDrawCallsInFrame);
GD.Print($"VISUAL_PROBE INFO: renderer={RenderingServer.GetVideoAdapterName()} drawCalls={drawCalls} pomDecals={decalPlacements.Count}");
Check(_failures.Count == 0, $"Encountered {_failures.Count} failures");
}
catch (Exception ex)
{
Check(false, ex.ToString());
}
exitCode = _failures.Count == 0 ? 0 : 1;
GD.Print(exitCode == 0 ? "VISUAL_PROBE RESULT: PASS" : $"VISUAL_PROBE RESULT: FAIL ({_failures.Count})");
Finish(exitCode);
}
private void Finish(int code)
{
GetTree().Quit(code);
}
private void SetupEnvironment()
{
var sun = new DirectionalLight3D
{
Name = "DesertSun",
LightColor = new Color(1.0f, 0.93f, 0.82f),
LightEnergy = 1.85f,
ShadowEnabled = true,
DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits,
RotationDegrees = new Vector3(-38f, 36f, 0f)
};
AddChild(sun);
// Cool oblique fill light so POM recesses & metal rims catch clear specular highlights
var fill = new DirectionalLight3D
{
Name = "SkyFill",
LightColor = new Color(0.68f, 0.80f, 0.98f),
LightEnergy = 0.55f,
ShadowEnabled = false,
RotationDegrees = new Vector3(-25f, -125f, 0f)
};
AddChild(fill);
var skyMat = new ProceduralSkyMaterial
{
SkyTopColor = new Color(0.24f, 0.34f, 0.44f),
SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f),
GroundBottomColor = new Color(0.28f, 0.20f, 0.14f),
GroundHorizonColor = new Color(0.68f, 0.48f, 0.32f)
};
var env = new Godot.Environment
{
BackgroundMode = Godot.Environment.BGMode.Sky,
Sky = new Sky { SkyMaterial = skyMat },
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.65f
};
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env });
}
private void VerifyBakedVertexColors(string name, ArrayMesh mesh)
{
int surfCount = mesh.GetSurfaceCount();
bool foundColor = false;
float minR = 1f, maxR = 0f, minG = 1f, maxG = 0f, minB = 1f, maxB = 0f, minA = 1f, maxA = 0f;
int totalVerts = 0;
for (int s = 0; s < surfCount; s++)
{
var arrays = mesh.SurfaceGetArrays(s);
if (arrays.Count > (int)Mesh.ArrayType.Color &&
arrays[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray)
{
Color[] cols = arrays[(int)Mesh.ArrayType.Color].AsColorArray();
foundColor = true;
totalVerts += cols.Length;
foreach (Color c in cols)
{
if (c.R < minR) minR = c.R; if (c.R > maxR) maxR = c.R;
if (c.G < minG) minG = c.G; if (c.G > maxG) maxG = c.G;
if (c.B < minB) minB = c.B; if (c.B > maxB) maxB = c.B;
if (c.A < minA) minA = c.A; if (c.A > maxA) maxA = c.A;
}
}
}
GD.Print($"COLOR_0 [{name}]: verts={totalVerts} AO=[{minR:F2},{maxR:F2}] Edge=[{minG:F2},{maxG:F2}] Island=[{minB:F2},{maxB:F2}] Height=[{minA:F2},{maxA:F2}]");
Check(foundColor && totalVerts > 0, $"{name} missing baked COLOR_0 array");
Check(minR < 0.35f && maxR > 0.85f, $"{name} AO range too narrow [{minR:F2},{maxR:F2}]");
Check(maxG > 0.65f, $"{name} Edge curvature max too low ({maxG:F2})");
Check(maxA - minA > 0.15f, $"{name} Rest height span too small [{minA:F2},{maxA:F2}]");
}
private static ImageTexture LoadTextureWithMips(string path)
{
var img = Image.LoadFromFile(path);
if (img is null)
{
throw new FileNotFoundException($"Could not load texture '{path}'", path);
}
img.GenerateMipmaps();
return ImageTexture.CreateFromImage(img);
}
private static ShaderMaterial MakeMechPaintMat(
Shader shader,
Color baseColor,
float metallic,
float roughness,
float wear,
float grime,
float mud,
float mudTop = 1.45f)
{
var mat = new ShaderMaterial { Shader = shader };
mat.SetShaderParameter("base_color", baseColor);
mat.SetShaderParameter("metallic", metallic);
mat.SetShaderParameter("roughness", roughness);
mat.SetShaderParameter("wear", wear);
mat.SetShaderParameter("grime", grime);
mat.SetShaderParameter("mud", mud);
mat.SetShaderParameter("mud_top", mudTop);
return mat;
}
private static void ApplyMechPaintSurfaces(
ArrayMesh mesh,
ShaderMaterial armorMat,
ShaderMaterial gunmetalMat,
ShaderMaterial copperMat,
ShaderMaterial orangeMat,
ShaderMaterial markMat)
{
int n = mesh.GetSurfaceCount();
for (int s = 0; s < n; s++)
{
Material? orig = mesh.SurfaceGetMaterial(s);
string mName = (orig?.ResourceName ?? string.Empty).ToLowerInvariant();
if (mName.Contains("glass") || mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan"))
{
continue;
}
if (mName.Contains("copper"))
{
mesh.SurfaceSetMaterial(s, copperMat);
}
else if (mName.Contains("signal") || mName.Contains("orange"))
{
mesh.SurfaceSetMaterial(s, orangeMat);
}
else if (mName.Contains("mark") || mName.Contains("stencil"))
{
mesh.SurfaceSetMaterial(s, markMat);
}
else if (mName.Contains("gunmetal") || mName.Contains("metal") || mName.Contains("steel") || mName.Contains("socket") || mName.Contains("pit") || mName.Contains("rubber"))
{
mesh.SurfaceSetMaterial(s, gunmetalMat);
}
else
{
mesh.SurfaceSetMaterial(s, armorMat);
}
}
}
private static ArrayMesh BuildBeveledShowcaseSlab(float w, float h, float d)
{
// Build a subdivided box with baked COLOR_0 (flat faces G=0, sharp edges G=1, AO=0.9, island=0.42)
float hw = w * 0.5f, hh = h * 0.5f, hd = d * 0.5f;
var st = new SurfaceTool();
st.Begin(Mesh.PrimitiveType.Triangles);
void AddQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 dPt, Vector3 nrm, float edgeA, float edgeB, float edgeC, float edgeD)
{
void V(Vector3 p, Vector2 uv, float edge)
{
float restH = Math.Clamp((p.Y + 4.2f) / 6.0f, 0f, 1f);
st.SetColor(new Color(0.92f, edge, 0.42f, restH));
st.SetNormal(nrm);
st.SetUV(uv);
st.AddVertex(p);
}
// Clockwise front-face winding for Godot Spatial cull_back
V(a, new Vector2(0, 1), edgeA);
V(c, new Vector2(1, 0), edgeC);
V(b, new Vector2(1, 1), edgeB);
V(a, new Vector2(0, 1), edgeA);
V(dPt, new Vector2(0, 0), edgeD);
V(c, new Vector2(1, 0), edgeC);
}
// Front (+Z) subdivided 3x1 so center interior vertices have edge=0 and outer corners have edge=0.95
float x0 = -hw, x1 = -hw * 0.72f, x2 = hw * 0.72f, x3 = hw;
float y0 = -hh, y1 = -hh * 0.65f, y2 = hh * 0.65f, y3 = hh;
float[] xs = { x0, x1, x2, x3 };
float[] ys = { y0, y1, y2, y3 };
float[,] edges = {
{ 0.95f, 0.85f, 0.85f, 0.95f },
{ 0.85f, 0.00f, 0.00f, 0.85f },
{ 0.85f, 0.00f, 0.00f, 0.85f },
{ 0.95f, 0.85f, 0.85f, 0.95f },
};
for (int iy = 0; iy < 3; iy++)
{
for (int ix = 0; ix < 3; ix++)
{
AddQuad(
new Vector3(xs[ix], ys[iy], hd),
new Vector3(xs[ix + 1], ys[iy], hd),
new Vector3(xs[ix + 1], ys[iy + 1], hd),
new Vector3(xs[ix], ys[iy + 1], hd),
Vector3.Back,
edges[iy, ix], edges[iy, ix + 1], edges[iy + 1, ix + 1], edges[iy + 1, ix]);
}
}
// Back & sides
AddQuad(new Vector3(hw, -hh, -hd), new Vector3(-hw, -hh, -hd), new Vector3(-hw, hh, -hd), new Vector3(hw, hh, -hd), Vector3.Forward, 0.9f, 0.9f, 0.9f, 0.9f);
AddQuad(new Vector3(-hw, hh, hd), new Vector3(hw, hh, hd), new Vector3(hw, hh, -hd), new Vector3(-hw, hh, -hd), Vector3.Up, 0.95f, 0.95f, 0.95f, 0.95f);
AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(hw, -hh, -hd), new Vector3(hw, -hh, hd), new Vector3(-hw, -hh, hd), Vector3.Down, 0.95f, 0.95f, 0.95f, 0.95f);
AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(-hw, -hh, hd), new Vector3(-hw, hh, hd), new Vector3(-hw, hh, -hd), Vector3.Left, 0.95f, 0.95f, 0.95f, 0.95f);
AddQuad(new Vector3(hw, -hh, hd), new Vector3(hw, -hh, -hd), new Vector3(hw, hh, -hd), new Vector3(hw, hh, hd), Vector3.Right, 0.95f, 0.95f, 0.95f, 0.95f);
st.GenerateTangents();
return st.Commit();
}
private static void AddSlabDecal(
List<(Transform3D, Color)> list,
Transform3D slabXf,
float lx,
float ly,
float lz,
float size,
int tile,
float heat,
float opacity,
float depth)
{
var localXf = new Transform3D(Basis.FromScale(new Vector3(size, size, 1f)), new Vector3(lx, ly, lz));
list.Add((slabXf * localXf, new Color(tile, heat, opacity, depth)));
}
private static void TryAddRayDecal(
List<(Transform3D, Color)> list,
ArrayMesh mesh,
Transform3D meshXf,
Vector3 worldOrigin,
Vector3 worldDir,
float size,
int tile,
float heat,
float opacity,
float depth)
{
Transform3D inv = meshXf.AffineInverse();
Vector3 localOrigin = inv * worldOrigin;
Vector3 localDir = (inv.Basis * worldDir).Normalized();
float bestT = float.PositiveInfinity;
Vector3 bestN = Vector3.Back;
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
{
var arr = mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex) continue;
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
: null;
int triCount = (indices is not null ? indices.Length : verts.Length) / 3;
for (int t = 0; t < triCount; t++)
{
int i0 = indices is not null ? indices[t * 3] : t * 3;
int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1;
int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2;
Vector3 v0 = verts[i0], v1 = verts[i1], v2 = verts[i2];
if (RayTriangle(localOrigin, localDir, v0, v1, v2, out float hitT))
{
if (hitT < bestT)
{
Vector3 fn = (v1 - v0).Cross(v2 - v0);
if (fn.LengthSquared() > 1e-10f)
{
fn = fn.Normalized();
if (fn.Dot(-localDir) < 0f) fn = -fn;
bestT = hitT;
bestN = fn;
}
}
}
}
}
if (!float.IsFinite(bestT))
{
return;
}
Vector3 worldHit = meshXf * (localOrigin + localDir * bestT);
Vector3 worldN = (meshXf.Basis.Inverse().Transposed() * bestN).Normalized();
Vector3 upRef = MathF.Abs(worldN.Y) > 0.92f ? Vector3.Forward : Vector3.Up;
Vector3 right = upRef.Cross(worldN).Normalized();
Vector3 up = worldN.Cross(right).Normalized();
var basis = new Basis(right * size, up * size, worldN);
list.Add((new Transform3D(basis, worldHit), new Color(tile, heat, opacity, depth)));
}
private static bool RayTriangle(Vector3 orig, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = 0f;
Vector3 e1 = v1 - v0;
Vector3 e2 = v2 - v0;
Vector3 pvec = dir.Cross(e2);
float det = e1.Dot(pvec);
if (MathF.Abs(det) < 1e-7f) return false;
float invDet = 1f / det;
Vector3 tvec = orig - v0;
float u = tvec.Dot(pvec) * invDet;
if (u < 0f || u > 1f) return false;
Vector3 qvec = tvec.Cross(e1);
float v = dir.Dot(qvec) * invDet;
if (v < 0f || u + v > 1f) return false;
t = e2.Dot(qvec) * invDet;
return t > 0.01f;
}
}

View file

@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://tests/VisualProbe.cs" id="1"]
[node name="VisualProbe" type="Node3D"]
script = ExtResource("1")

View 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())

Binary file not shown.

After

Width:  |  Height:  |  Size: 749 KiB

View 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())