Retrofit 4 Brokkr mechs with hardpoints, LOD GLBs, and mechanisms

This commit is contained in:
Meta Vens 2026-12-04 16:15:48 +01:00
commit 916bac2904
15 changed files with 2493 additions and 21 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View file

@ -0,0 +1,820 @@
"""Retrofit Brokkr kit-built mechs for Rust to Dust:
- Strip built-in weapon loadouts and studio backdrop/rig helpers (read-only on source .blend/.json).
- Normalize procedural Brokkr shaders to clean glTF 2.0 Principled BSDF PBR materials.
- Apply skinning-preserving / silhouette-preserving LOD decimation (target ~26k-32k tris).
- Reorient from Brokkr (+Y forward, -X left) to RTD (+Z forward glTF / -Y Blender, +X left), grounded at minY = 0.
- Attach visible exterior hardpoint collars/bays (`add_hardpoint_slot`) and joint tags (`tag_joint`).
- Emit `<mech>.glb`, `manifest.json` (including `mechanisms` when model JSON has rams/scissors/struts), and 4-panel preview PNG.
Adding a future Brokkr mech (e.g. `bastion`, `seraph`): add a `MechRetrofitSpec` entry in `SPECS`.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import bmesh
import bpy
from mathutils import Euler, Matrix, Vector
sys.path.insert(0, str(Path(__file__).resolve().parent))
import vehicle_common as vc # noqa: E402
@dataclass(frozen=True)
class HardpointMount:
hp_id: str
kind: str
x: int
y: int
w: int
h: int
parent_name: str
parent_bone: str | None
world_pos: tuple[float, float, float]
world_normal: tuple[float, float, float]
size: tuple[float, float, float]
@dataclass(frozen=True)
class JointTagSpec:
joint_id: str
target_name: str
parent_bone: str | None
axis_gltf: tuple[float, float, float]
min_val: float
max_val: float
@dataclass(frozen=True)
class MechRetrofitSpec:
mech_id: str
name: str
vehicle_class: str
plane: str
grid_width: int
grid_height: int
mask: tuple[str, ...]
blend_path: Path
model_json_path: Path | None
target_mech_tris: int
drop_collections: tuple[str, ...] = ()
strip_prefixes: tuple[str, ...] = ()
strip_vertex_groups: tuple[str, ...] = ()
armature_name: str | None = None
hardpoints: tuple[HardpointMount, ...] = ()
joints: tuple[JointTagSpec, ...] = ()
extra_notes: str = ""
SPECS: dict[str, MechRetrofitSpec] = {
"breaker": MechRetrofitSpec(
mech_id="breaker",
name="Breaker",
vehicle_class="Heavy Assault Biped",
plane="Coronal",
grid_width=5,
grid_height=6,
mask=(
".###.",
"#####",
"#####",
"#####",
".#.#.",
".#.#.",
),
blend_path=Path(r"F:\aeth-wt\fable-walk4\out\breaker_rigged.blend"),
model_json_path=Path(r"F:\aeth-wt\fable-walk4\out\breaker_model.json"),
target_mech_tris=28000,
drop_collections=("breaker.build",),
strip_prefixes=("Mark.",),
strip_vertex_groups=("CannonL", "CannonR"),
armature_name="breaker.rig",
hardpoints=(
HardpointMount("hp.weapon.arm_l", "weapon", 0, 1, 1, 2, "breaker.rig", "ForearmL", (-2.22, 0.56, 3.58), (-1.0, 0.0, 0.0), (0.58, 0.58, 0.11)),
HardpointMount("hp.weapon.arm_r", "weapon", 4, 1, 1, 2, "breaker.rig", "ForearmR", (2.22, 0.36, 3.58), (1.0, 0.0, 0.0), (0.58, 0.58, 0.11)),
HardpointMount("hp.weapon.shoulder_l", "weapon", 1, 0, 1, 1, "breaker.rig", "ShoulderYokeL", (-1.68, 0.15, 6.02), (0.0, 0.0, 1.0), (0.72, 0.72, 0.12)),
HardpointMount("hp.armor.torso", "armor", 2, 1, 1, 1, "breaker.rig", "Core", (0.0, 1.24, 5.42), (0.0, 0.82, 0.57), (1.05, 0.42, 0.11)),
HardpointMount("hp.engine.chest", "engine", 2, 2, 1, 2, "breaker.rig", "Core", (0.0, 1.46, 4.35), (0.0, 1.0, 0.0), (0.86, 0.78, 0.13)),
HardpointMount("hp.radiator.back_l", "radiator", 1, 1, 1, 1, "breaker.rig", "Core", (-1.30, -1.34, 5.30), (0.0, -1.0, 0.0), (0.68, 0.92, 0.12)),
HardpointMount("hp.radiator.back_r", "radiator", 3, 1, 1, 1, "breaker.rig", "Core", (1.08, -1.50, 5.30), (0.0, -1.0, 0.0), (0.68, 0.92, 0.12)),
),
joints=(
JointTagSpec("joint.torso_yaw", "breaker.rig", "Core", (0.0, 1.0, 0.0), -90.0, 90.0),
JointTagSpec("joint.arm_l_pitch", "breaker.rig", "ShoulderYokeL", (1.0, 0.0, 0.0), -45.0, 60.0),
JointTagSpec("joint.arm_r_pitch", "breaker.rig", "ShoulderYokeR", (1.0, 0.0, 0.0), -45.0, 60.0),
),
),
"paladin": MechRetrofitSpec(
mech_id="paladin",
name="Paladin",
vehicle_class="Heavy Assault Biped",
plane="Coronal",
grid_width=6,
grid_height=7,
mask=(
"..##..",
".####.",
"######",
"######",
".####.",
".#..#.",
".#..#.",
),
blend_path=Path(r"F:\aeth-wt\fable-paladin-3\out\paladin\paladin.blend"),
model_json_path=None,
target_mech_tris=29000,
strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Battery.", "EW.", "EWLow.", "Gatling.", "Emitter."),
hardpoints=(
HardpointMount("hp.weapon.sh_l", "weapon", 1, 1, 1, 1, "Trunk", None, (-2.88, 0.35, 9.94), (0.0, 0.0, 1.0), (0.98, 0.98, 0.15)),
HardpointMount("hp.armor.torso", "armor", 2, 1, 2, 1, "Trunk", None, (0.0, 2.02, 8.85), (0.0, 0.88, 0.47), (1.35, 0.44, 0.12)),
HardpointMount("hp.weapon.sh_r", "weapon", 4, 1, 1, 1, "Trunk", None, (2.88, 0.35, 9.94), (0.0, 0.0, 1.0), (0.98, 0.98, 0.15)),
HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ArmL.Lower", None, (-3.44, 0.85, 5.75), (-1.0, 0.0, 0.0), (0.78, 0.78, 0.13)),
HardpointMount("hp.engine.chest", "engine", 2, 2, 2, 2, "Trunk", None, (0.0, 2.18, 7.82), (0.0, 1.0, 0.0), (1.12, 0.94, 0.14)),
HardpointMount("hp.weapon.arm_r", "weapon", 5, 2, 1, 2, "ArmR.Lower", None, (3.56, 1.15, 6.20), (1.0, 0.0, 0.0), (0.78, 0.78, 0.13)),
HardpointMount("hp.radiator.back_l", "radiator", 1, 4, 1, 1, "Trunk", None, (-0.92, -1.44, 8.65), (0.0, -1.0, 0.0), (0.82, 1.35, 0.14)),
HardpointMount("hp.armor.legs", "armor", 2, 4, 2, 1, "Pelvis", None, (0.0, 1.18, 5.55), (0.0, 1.0, 0.0), (0.95, 0.38, 0.11)),
HardpointMount("hp.radiator.back_r", "radiator", 4, 4, 1, 1, "Trunk", None, (0.92, -1.44, 8.65), (0.0, -1.0, 0.0), (0.82, 1.35, 0.14)),
),
joints=(
JointTagSpec("joint.torso_yaw", "Trunk", None, (0.0, 1.0, 0.0), -90.0, 90.0),
JointTagSpec("joint.arm_l_pitch", "ArmL.Upper", None, (1.0, 0.0, 0.0), -40.0, 70.0),
JointTagSpec("joint.arm_r_pitch", "ArmR.Upper", None, (1.0, 0.0, 0.0), -40.0, 70.0),
),
),
"raptor": MechRetrofitSpec(
mech_id="raptor",
name="Raptor",
vehicle_class="Medium Theropod Biped",
plane="Coronal",
grid_width=5,
grid_height=6,
mask=(
"..#..",
".###.",
"#####",
"#.#.#",
".#.#.",
".#.#.",
),
blend_path=Path(r"F:\aeth-wt\fable-raptor-4\out\raptor\raptor.blend"),
model_json_path=None,
target_mech_tris=28000,
strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Bank0.", "Bank1.", "LaserL.", "LaserR."),
hardpoints=(
HardpointMount("hp.radiator.sh_l", "radiator", 1, 1, 1, 1, "_ROOT_", None, (-0.56, 0.05, 6.26), (-0.25, 0.0, 0.97), (0.66, 1.05, 0.12)),
HardpointMount("hp.radiator.sh_r", "radiator", 3, 1, 1, 1, "_ROOT_", None, (0.56, 0.05, 6.26), (0.25, 0.0, 0.97), (0.66, 1.05, 0.12)),
HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ArmL.Fore", None, (-1.40, 2.22, 3.90), (-1.0, 0.0, 0.0), (0.56, 0.56, 0.11)),
HardpointMount("hp.engine.chest", "engine", 2, 2, 1, 2, "_ROOT_", None, (0.0, -2.02, 6.78), (0.0, 0.0, 1.0), (0.86, 1.12, 0.14)),
HardpointMount("hp.weapon.arm_r", "weapon", 4, 2, 1, 2, "ArmR.Fore", None, (1.40, 2.22, 3.90), (1.0, 0.0, 0.0), (0.56, 0.56, 0.11)),
),
joints=(
JointTagSpec("joint.arm_l_pitch", "ArmL.Upper", None, (1.0, 0.0, 0.0), -45.0, 45.0),
JointTagSpec("joint.arm_r_pitch", "ArmR.Upper", None, (1.0, 0.0, 0.0), -45.0, 45.0),
),
),
"manticore": MechRetrofitSpec(
mech_id="manticore",
name="Manticore",
vehicle_class="Heavy Quadruped Scorpion",
plane="Dorsal",
grid_width=5,
grid_height=5,
mask=(
"#####",
".###.",
"#####",
".###.",
"#.#.#",
),
blend_path=Path(r"F:\aeth-wt\fable-manticore-3\out\manticore\manticore.blend"),
model_json_path=None,
target_mech_tris=28000,
strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Laser.light", "Launcher.", "ArmGunL.", "ArmGunR."),
hardpoints=(
HardpointMount("hp.weapon.chin", "weapon", 2, 0, 1, 1, "Hull", None, (0.0, 3.34, 1.38), (0.0, 0.94, -0.34), (0.64, 0.64, 0.12)),
HardpointMount("hp.radiator.flank_l", "radiator", 1, 1, 1, 1, "Hull", None, (-1.18, -0.35, 2.76), (-0.22, 0.0, 0.97), (0.56, 0.98, 0.12)),
HardpointMount("hp.engine.core", "engine", 2, 1, 1, 2, "Hull", None, (0.0, -0.25, 2.94), (0.0, 0.14, 0.99), (0.86, 1.20, 0.14)),
HardpointMount("hp.radiator.flank_r", "radiator", 3, 1, 1, 1, "Hull", None, (1.18, -0.35, 2.76), (0.22, 0.0, 0.97), (0.56, 0.98, 0.12)),
HardpointMount("hp.weapon.l", "weapon", 0, 2, 1, 1, "ArmL.Upper", None, (-0.96, 2.75, 0.72), (-0.65, 0.76, 0.0), (0.56, 0.56, 0.11)),
HardpointMount("hp.weapon.r", "weapon", 4, 2, 1, 1, "ArmR.Upper", None, (0.96, 2.75, 0.72), (0.65, 0.76, 0.0), (0.56, 0.56, 0.11)),
HardpointMount("hp.armor.prow", "armor", 2, 3, 1, 1, "Hull", None, (0.0, 3.14, 1.94), (0.0, 0.85, 0.53), (0.88, 0.34, 0.11)),
),
joints=(
JointTagSpec("joint.tail_yaw", "Tail.Coxa", None, (0.0, 1.0, 0.0), -75.0, 75.0),
JointTagSpec("joint.tail_s1", "Tail.S1", None, (1.0, 0.0, 0.0), -60.0, 60.0),
JointTagSpec("joint.tail_s2", "Tail.S2", None, (1.0, 0.0, 0.0), -75.0, 15.0),
JointTagSpec("joint.tail_s3", "Tail.S3", None, (1.0, 0.0, 0.0), -80.0, 10.0),
JointTagSpec("joint.tail_elev", "Tail.Elev", None, (1.0, 0.0, 0.0), -40.0, 30.0),
),
),
}
def _should_strip(name: str, prefixes: tuple[str, ...]) -> bool:
return any(name == p or name.startswith(p) or name.startswith(p.rstrip(".")) and name == p.rstrip(".") for p in prefixes)
def _remove_object_recursive(obj: bpy.types.Object) -> None:
for ch in list(obj.children):
_remove_object_recursive(ch)
if obj.name in bpy.data.objects:
bpy.data.objects.remove(obj, do_unlink=True)
def _strip_scene_objects(spec: MechRetrofitSpec) -> list[str]:
stripped: list[str] = []
# 1. Drop excluded build collections (e.g. breaker.build)
for col_name in spec.drop_collections:
col = bpy.data.collections.get(col_name)
if col is not None:
for obj_name in [o.name for o in col.objects]:
stripped.append(obj_name)
obj = bpy.data.objects.get(obj_name)
if obj is not None:
bpy.data.objects.remove(obj, do_unlink=True)
bpy.data.collections.remove(col)
# 2. Strip matching prefixes, studio lights/cameras/fonts, and hidden boolean cutters
for obj_name in [o.name for o in bpy.data.objects]:
obj = bpy.data.objects.get(obj_name)
if obj is None:
continue
if obj.type in ("LIGHT", "CAMERA", "FONT"):
stripped.append(obj_name)
bpy.data.objects.remove(obj, do_unlink=True)
continue
if obj.hide_viewport or obj.hide_render or obj.display_type in ("WIRE", "BOUNDS"):
stripped.append(obj_name)
bpy.data.objects.remove(obj, do_unlink=True)
continue
if _should_strip(obj_name, spec.strip_prefixes):
stripped.append(obj_name)
_remove_object_recursive(obj)
continue
if not spec.armature_name and ".bolts" in obj_name:
stripped.append(obj_name)
bpy.data.objects.remove(obj, do_unlink=True)
return sorted(set(stripped))
def _strip_vertex_groups_from_mesh(obj: bpy.types.Object, vg_names: tuple[str, ...]) -> int:
if not vg_names or obj.type != "MESH":
return 0
target_indices = {
obj.vertex_groups[name].index
for name in vg_names
if name in obj.vertex_groups
}
if not target_indices:
return 0
bm = bmesh.new()
bm.from_mesh(obj.data)
dlayer = bm.verts.layers.deform.active
removed_verts = 0
if dlayer is not None:
to_delete = []
for v in bm.verts:
dw = v[dlayer]
if any(dw.get(idx, 0.0) > 0.5 for idx in target_indices):
to_delete.append(v)
removed_verts = len(to_delete)
if to_delete:
bmesh.ops.delete(bm, geom=to_delete, context="VERTS")
bm.to_mesh(obj.data)
bm.free()
obj.data.validate(verbose=False)
obj.data.update()
return removed_verts
def _apply_existing_modifiers() -> None:
"""Drop BEVEL (which causes decimate spikes) and bake SOLIDIFY/BOOLEAN before stripping cutters."""
for obj_name in [o.name for o in bpy.data.objects]:
obj = bpy.data.objects.get(obj_name)
if obj is None or obj.type != "MESH" or not obj.modifiers:
continue
for mod in list(obj.modifiers):
if mod.type == "BEVEL":
obj.modifiers.remove(mod)
depsgraph = bpy.context.evaluated_depsgraph_get()
for obj_name in [o.name for o in bpy.data.objects]:
obj = bpy.data.objects.get(obj_name)
if obj is None or obj.type != "MESH" or not obj.modifiers:
continue
if any(m.type == "ARMATURE" for m in obj.modifiers):
continue
ev = obj.evaluated_get(depsgraph)
new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph)
new_mesh.name = f"{obj.name}_baked"
obj.modifiers.clear()
obj.data = new_mesh
def _convert_surviving_curves() -> None:
"""Convert surviving CURVE hydraulic hoses to MESH."""
view_layer = bpy.context.view_layer
curves = [o for o in bpy.data.objects if o.type == "CURVE"]
if curves:
bpy.ops.object.select_all(action="DESELECT")
for c in curves:
c.select_set(True)
view_layer.objects.active = curves[0]
bpy.ops.object.convert(target="MESH")
def _normalize_materials_for_gltf() -> None:
"""Replace linked procedural shader trees with clean flat Principled BSDF PBR values."""
vc.ensure_materials()
pal_map = {
"armour": "olive_armor",
"armor": "olive_armor",
"olive": "olive_armor",
"khaki": "olive_armor",
"metal": "gunmetal",
"gunmetal": "gunmetal",
"machine": "gunmetal",
"rubber": "rubber_dark",
"hazard": "signal_orange",
"brass": "copper_rad",
"copper": "copper_rad",
"glass": "smoked_glass",
"optic": "smoked_glass",
"pit": "socket_bay",
}
for mat in list(bpy.data.materials):
if mat.name in vc.PALETTE or not mat.use_nodes or not mat.node_tree:
continue
nt = mat.node_tree
bsdf = next((n for n in nt.nodes if n.type == "BSDF_PRINCIPLED"), None)
if bsdf is None:
continue
lname = mat.name.lower()
# Extract Group node overrides if authored by Brokkr paint_pinned
grp = next((n for n in nt.nodes if n.type == "GROUP"), None)
base_col = None
metallic = None
roughness = None
if grp is not None:
if "Base Color" in grp.inputs and hasattr(grp.inputs["Base Color"], "default_value"):
base_col = tuple(grp.inputs["Base Color"].default_value)
if "Metallic" in grp.inputs and hasattr(grp.inputs["Metallic"], "default_value"):
metallic = float(grp.inputs["Metallic"].default_value)
if "Roughness" in grp.inputs and hasattr(grp.inputs["Roughness"], "default_value"):
roughness = float(grp.inputs["Roughness"].default_value)
# Fallback to matching shared RTD palette entry for linked/procedural mats
matched_pal = None
for key, pal_name in pal_map.items():
if key in lname:
matched_pal = vc.PALETTE[pal_name]
break
# Clear links on Principled BSDF and reset overrides (e.g. Emission/Transmission)
for inp in bsdf.inputs:
for lk in list(inp.links):
nt.links.remove(lk)
if "Emission Strength" in bsdf.inputs:
bsdf.inputs["Emission Strength"].default_value = 0.0
if "Emission Color" in bsdf.inputs:
bsdf.inputs["Emission Color"].default_value = (0.0, 0.0, 0.0, 1.0)
if "Transmission Weight" in bsdf.inputs:
bsdf.inputs["Transmission Weight"].default_value = 0.0
if "Coat Weight" in bsdf.inputs:
bsdf.inputs["Coat Weight"].default_value = 0.0
if "glow_blue" in lname:
bsdf.inputs["Base Color"].default_value = vc.srgb_hex_to_linear("#38c9d8")
bsdf.inputs["Roughness"].default_value = 0.20
bsdf.inputs["Emission Color"].default_value = vc.srgb_hex_to_linear("#38c9d8")
bsdf.inputs["Emission Strength"].default_value = 2.4
elif any(k in lname for k in ("lamp", "glow", "amber")):
col = vc.srgb_hex_to_linear("#ff9f2e")
bsdf.inputs["Base Color"].default_value = col
bsdf.inputs["Roughness"].default_value = 0.20
bsdf.inputs["Emission Color"].default_value = col
bsdf.inputs["Emission Strength"].default_value = 2.2
elif "steel" in lname:
bsdf.inputs["Base Color"].default_value = (0.58, 0.60, 0.62, 1.0)
bsdf.inputs["Metallic"].default_value = 0.94
bsdf.inputs["Roughness"].default_value = 0.22
elif "warhead" in lname:
bsdf.inputs["Base Color"].default_value = (0.28, 0.10, 0.06, 1.0)
bsdf.inputs["Metallic"].default_value = 0.35
bsdf.inputs["Roughness"].default_value = 0.45
elif matched_pal is not None:
bsdf.inputs["Base Color"].default_value = vc.srgb_hex_to_linear(matched_pal["hex"])
bsdf.inputs["Metallic"].default_value = float(matched_pal["metallic"])
bsdf.inputs["Roughness"].default_value = float(matched_pal["roughness"])
if "alpha" in matched_pal:
bsdf.inputs["Alpha"].default_value = float(matched_pal["alpha"])
if hasattr(mat, "blend_method"):
mat.blend_method = "BLEND"
elif base_col is not None:
bsdf.inputs["Base Color"].default_value = base_col
if metallic is not None:
bsdf.inputs["Metallic"].default_value = metallic
if roughness is not None:
bsdf.inputs["Roughness"].default_value = roughness
def _mesh_tri_count(obj: bpy.types.Object) -> int:
obj.data.calc_loop_triangles()
return len(obj.data.loop_triangles)
def _apply_crisp_normals_and_decimate(obj: bpy.types.Object, ratio: float) -> int:
view_layer = bpy.context.view_layer
if obj.data.users > 1:
obj.data = obj.data.copy()
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
view_layer.objects.active = obj
if ratio < 0.99:
mod = obj.modifiers.new("LOD_Decimate", "DECIMATE")
mod.decimate_type = "COLLAPSE"
mod.ratio = ratio
mod.use_collapse_triangulate = True
if len(obj.modifiers) > 1:
bpy.ops.object.modifier_move_to_index(modifier=mod.name, index=0)
bpy.ops.object.modifier_apply(modifier=mod.name)
# Split sharp armor edges (>36 deg) so decimated bevel corners never look pillowed
es = obj.modifiers.new("LOD_EdgeSplit", "EDGE_SPLIT")
es.use_edge_angle = True
es.split_angle = math.radians(36.0)
es.use_edge_sharp = True
if len(obj.modifiers) > 1:
bpy.ops.object.modifier_move_to_index(modifier=es.name, index=0)
bpy.ops.object.modifier_apply(modifier=es.name)
obj.data.validate(verbose=False)
obj.data.update()
return _mesh_tri_count(obj)
def _decimate_mech_meshes(meshes: list[bpy.types.Object], target_tris: int, min_keep_tris: int = 48) -> tuple[int, int]:
"""Decimate mech meshes adaptively to target_tris while keeping armor plates crisp and spike-free."""
tri_counts = [_mesh_tri_count(o) for o in meshes]
raw_total = sum(tri_counts)
if raw_total == 0:
return 0, 0
# Single-mesh rigged path (e.g. breaker.mesh) -> modifier_apply preserves armature + skinning
if len(meshes) == 1:
obj = meshes[0]
ratio = max(0.02, min(1.0, target_tris / raw_total))
after = _apply_crisp_normals_and_decimate(obj, ratio)
return raw_total, after
def _target_for(obj: bpy.types.Object, t: int, k_val: float) -> int:
if t <= min_keep_tris:
return t
is_detail = (
obj.name.startswith("Foot")
or ".Foot" in obj.name
or ".fit." in obj.name
or ".ferrules" in obj.name
or ".panels" in obj.name
)
if is_detail:
return max(24, int(round(t * max(k_val * 0.50, 0.08))))
if t <= 220:
return max(min(t, 44), int(round(t * max(k_val, 0.28))))
return max(84, int(round(t * max(k_val, 0.20))))
if raw_total <= target_tris:
k = 1.0
else:
lo, hi = 0.10, 1.0
for _ in range(28):
mid = 0.5 * (lo + hi)
est = sum(_target_for(obj, t, mid) for obj, t in zip(meshes, tri_counts))
if est > target_tris:
hi = mid
else:
lo = mid
k = 0.5 * (lo + hi)
# Queue DECIMATE + EDGE_SPLIT on all objects, then evaluate in one depsgraph pass
for obj, t in zip(meshes, tri_counts):
tgt = _target_for(obj, t, k)
if tgt < t:
ratio = max(0.08, min(1.0, tgt / t))
if ratio < 0.99:
mod = obj.modifiers.new("LOD_Decimate", "DECIMATE")
mod.decimate_type = "COLLAPSE"
mod.ratio = ratio
mod.use_collapse_triangulate = True
es = obj.modifiers.new("LOD_EdgeSplit", "EDGE_SPLIT")
es.use_edge_angle = True
es.split_angle = math.radians(36.0)
es.use_edge_sharp = True
depsgraph = bpy.context.evaluated_depsgraph_get()
after_total = 0
for obj in meshes:
ev = obj.evaluated_get(depsgraph)
new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph)
new_mesh.name = f"{obj.name}_lod"
new_mesh.validate(verbose=False)
obj.modifiers.clear()
obj.data = new_mesh
after_total += _mesh_tri_count(obj)
return raw_total, after_total
def _attach_hardpoint_world(
hp: HardpointMount,
root_obj: bpy.types.Object,
) -> None:
parent_obj = root_obj if hp.parent_name == "_ROOT_" else bpy.data.objects[hp.parent_name]
anchor = vc.add_hardpoint_slot(
hp.hp_id,
hp.kind,
parent=parent_obj,
location=(0.0, 0.0, 0.0),
rotation_deg=(0.0, 0.0, 0.0),
size=hp.size,
)
bay_root = anchor.parent
if hp.parent_bone is not None:
bay_root.parent_type = "BONE"
bay_root.parent_bone = hp.parent_bone
bpy.context.view_layer.update()
n = Vector(hp.world_normal).normalized()
q = Vector((0.0, 0.0, 1.0)).rotation_difference(n)
m_world = Matrix.Translation(Vector(hp.world_pos)) @ q.to_matrix().to_4x4()
if hp.parent_bone is not None and parent_obj.type == "ARMATURE":
pb = parent_obj.pose.bones[hp.parent_bone]
# Blender bone parenting attaches at the pose bone tail with bone axes
bone_tail_mat = parent_obj.matrix_world @ pb.matrix @ Matrix.Translation((0.0, pb.length, 0.0))
m_local = bone_tail_mat.inverted() @ m_world
else:
m_local = parent_obj.matrix_world.inverted() @ m_world
loc, rot, _ = m_local.decompose()
bay_root.location = loc
bay_root.rotation_mode = "XYZ"
bay_root.rotation_euler = rot.to_euler("XYZ")
def _apply_joint_tags(spec: MechRetrofitSpec) -> list[dict[str, Any]]:
joints_manifest: list[dict[str, Any]] = []
for j in spec.joints:
target = bpy.data.objects[j.target_name]
if j.parent_bone is not None and target.type == "ARMATURE":
node = vc.make_empty(j.joint_id, parent=target, display_size=0.16)
node.parent_type = "BONE"
node.parent_bone = j.parent_bone
bpy.context.view_layer.update()
pb = target.pose.bones[j.parent_bone]
bone_head_w = target.matrix_world @ pb.head
bone_tail_mat = target.matrix_world @ pb.matrix @ Matrix.Translation((0.0, pb.length, 0.0))
m_local = bone_tail_mat.inverted() @ Matrix.Translation(bone_head_w)
node.location = m_local.to_translation()
else:
node = target
vc.tag_joint(node, j.joint_id, j.axis_gltf, j.min_val, j.max_val)
joints_manifest.append({
"id": j.joint_id,
"axis": [float(v) for v in j.axis_gltf],
"min": float(j.min_val),
"max": float(j.max_val),
})
return joints_manifest
def _brokkr_vec_to_gltf(v: list[float], ground_z_shift: float = 0.0) -> list[float]:
"""Convert raw Brokkr Blender (+Y fwd, -X left, +Z up) after 180 deg Z rot to glTF (+Z fwd, +X left, +Y up)."""
return [round(-float(v[0]), 6), round(float(v[2]) + ground_z_shift, 6), round(float(v[1]), 6)]
def _brokkr_dir_to_gltf(v: list[float]) -> list[float]:
return [round(-float(v[0]), 6), round(float(v[2]), 6), round(float(v[1]), 6)]
def _extract_mechanisms(model_json_path: Path, ground_z_shift: float = 0.0) -> dict[str, Any]:
raw = json.loads(model_json_path.read_text(encoding="utf-8"))
dofs_out = []
for d in raw.get("dofs", []):
entry = {
"name": d["name"],
"parent": d["parent"],
"kind": d["kind"],
"mechanism": d.get("mechanism"),
"side": d.get("side"),
"origin": _brokkr_vec_to_gltf(d["origin"], ground_z_shift),
"axis": _brokkr_dir_to_gltf(d["axis"]),
"lo": d["lo"],
"hi": d["hi"],
"depth": d["depth"],
}
if "compliance" in d:
entry["compliance"] = d["compliance"]
if "stopped_by" in d:
entry["stopped_by"] = d["stopped_by"]
dofs_out.append(entry)
points_raw = raw.get("points", {})
dirs_raw = raw.get("dirs", {})
rams_out = []
for r in raw.get("rams", []):
pt_a = points_raw.get(r["a"])
pt_b = points_raw.get(r["b"])
dir_pin = dirs_raw.get(r["pin"])
rams_out.append({
"name": r["name"],
"barrel_bone": r["barrel_bone"],
"rod_bone": r["rod_bone"],
"spans": r.get("spans", []),
"bore": r.get("bore"),
"body": r.get("body"),
"inner": r.get("inner"),
"extension": r.get("extension"),
"rest": r.get("rest"),
"stroke": r.get("stroke"),
"a_parent_dof": pt_a[0] if pt_a else None,
"a_pos": _brokkr_vec_to_gltf(pt_a[1], ground_z_shift) if pt_a else None,
"b_parent_dof": pt_b[0] if pt_b else None,
"b_pos": _brokkr_vec_to_gltf(pt_b[1], ground_z_shift) if pt_b else None,
"pin_dir": _brokkr_dir_to_gltf(dir_pin[1]) if dir_pin else None,
})
scissors_out = []
for s in raw.get("scissors", []):
pt_a = points_raw.get(s["a"])
pt_b = points_raw.get(s["b"])
dir_out = dirs_raw.get(s["out"])
scissors_out.append({
"name": s["name"],
"upper_bone": s["upper_bone"],
"lower_bone": s["lower_bone"],
"arm": s.get("arm"),
"a_parent_dof": pt_a[0] if pt_a else None,
"a_pos": _brokkr_vec_to_gltf(pt_a[1], ground_z_shift) if pt_a else None,
"b_parent_dof": pt_b[0] if pt_b else None,
"b_pos": _brokkr_vec_to_gltf(pt_b[1], ground_z_shift) if pt_b else None,
"out_dir": _brokkr_dir_to_gltf(dir_out[1]) if dir_out else None,
})
struts_out = [
{
"name": st["name"],
"side": st.get("side"),
"dof": st["dof"],
"travel": st["travel"],
"hertz": st["hertz"],
"damping_ratio": st["damping_ratio"],
}
for st in raw.get("struts", [])
]
return {
"frame": "gltf (+Y up, +Z forward, +X left, meters)",
"rootOrigin": _brokkr_vec_to_gltf(raw.get("root", [0.0, 0.0, 0.0]), ground_z_shift),
"dofs": dofs_out,
"rams": rams_out,
"scissors": scissors_out,
"struts": struts_out,
}
def retrofit_mech(spec: MechRetrofitSpec) -> dict[str, Any]:
bpy.ops.wm.open_mainfile(filepath=str(spec.blend_path))
scene = bpy.context.scene
scene.unit_settings.system = "METRIC"
scene.unit_settings.scale_length = 1.0
# 1. Apply SOLIDIFY/BOOLEAN/BEVEL BEFORE stripping hidden boolean cutters
if not spec.armature_name:
_apply_existing_modifiers()
# 2. Strip studio rig/backdrop & built-in weapons
stripped = _strip_scene_objects(spec)
if not spec.armature_name:
_convert_surviving_curves()
# 3. For rigged meshes, strip weapon vertex groups cleanly
stripped_vgs: dict[str, int] = {}
if spec.strip_vertex_groups:
for obj in bpy.data.objects:
if obj.type == "MESH":
cnt = _strip_vertex_groups_from_mesh(obj, spec.strip_vertex_groups)
if cnt > 0:
stripped_vgs[obj.name] = cnt
# 4. Normalize procedural materials -> clean glTF PBR
_normalize_materials_for_gltf()
# 5. Collect surviving mech meshes & decimate to game-ready LOD budget
mech_meshes = [o for o in bpy.data.objects if o.type == "MESH"]
raw_tris, lod_tris = _decimate_mech_meshes(mech_meshes, spec.target_mech_tris)
# 6. Parent everything cleanly under a root Empty (in raw Brokkr orientation first)
chassis_root = vc.make_empty(spec.mech_id, parent=None, location=(0.0, 0.0, 0.0))
for obj in list(bpy.data.objects):
if obj == chassis_root or obj.parent is not None:
continue
mw = obj.matrix_world.copy()
obj.parent = chassis_root
obj.matrix_parent_inverse = Matrix.Identity(4)
obj.matrix_local = mw
# 7. Attach standardized visible exterior hardpoint bays & tag joints
for hp in spec.hardpoints:
_attach_hardpoint_world(hp, chassis_root)
joints_manifest = _apply_joint_tags(spec)
# 8. Rotate chassis_root 180 deg around Z so Brokkr +Y forward -> RTD -Y forward (+Z glTF), -X left -> +X left
chassis_root.rotation_mode = "XYZ"
chassis_root.rotation_euler = Euler((0.0, 0.0, math.pi), "XYZ")
bpy.context.view_layer.update()
# 9. Export GLB (grounding minZ=0.0), write manifest.json, render 4-panel preview
glb_path = vc.ASSETS_VEHICLES_DIR / spec.mech_id / f"{spec.mech_id}.glb"
manifest_path = vc.ASSETS_VEHICLES_DIR / spec.mech_id / "manifest.json"
preview_path = vc.PREVIEWS_DIR / f"{spec.mech_id}_preview.png"
z_shift_before = chassis_root.location.z
tri_count, bounds = vc.export_vehicle_glb(glb_path, root=chassis_root)
ground_z_shift = chassis_root.location.z - z_shift_before
mechanisms = (
_extract_mechanisms(spec.model_json_path, ground_z_shift=ground_z_shift)
if spec.model_json_path is not None
else None
)
hp_manifest = [
{
"id": hp.hp_id,
"kind": hp.kind,
"x": hp.x,
"y": hp.y,
"w": hp.w,
"h": hp.h,
"modelNodeId": hp.hp_id,
}
for hp in spec.hardpoints
]
vc.write_manifest(
manifest_path,
vehicle_id=spec.mech_id,
name=spec.name,
vehicle_class=spec.vehicle_class,
plane=spec.plane,
grid_width=spec.grid_width,
grid_height=spec.grid_height,
mask=spec.mask,
hardpoints=hp_manifest,
joints=joints_manifest,
bounds=bounds,
tri_count=tri_count,
mechanisms=mechanisms,
)
vc.render_four_panel_preview(preview_path)
glb_bytes = glb_path.stat().st_size
summary = {
"id": spec.mech_id,
"raw_tris_after_strip": raw_tris,
"lod_mech_tris": lod_tris,
"exported_total_tris": tri_count,
"glb_bytes": glb_bytes,
"bounds": bounds,
"stripped_count": len(stripped),
"stripped_vgs": stripped_vgs,
}
print(f"[{spec.mech_id}] {json.dumps(summary)}")
return summary
def main() -> int:
argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
parser = argparse.ArgumentParser(description="Retrofit Brokkr mechs for Rust to Dust.")
parser.add_argument("--mech", choices=sorted(SPECS.keys()), help="Single mech ID to retrofit.")
parser.add_argument("--all", action="store_true", help="Retrofit all configured mechs sequentially.")
args = parser.parse_args(argv)
targets = list(SPECS.keys()) if (args.all or not args.mech) else [args.mech]
for mid in targets:
retrofit_mech(SPECS[mid])
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -956,6 +956,7 @@ def write_manifest(
bounds: dict[str, list[float]],
tri_count: int,
plane: str = "Dorsal",
mechanisms: dict[str, Any] | None = None,
) -> None:
if len(mask) == grid_height and isinstance(mask[0], str):
mask_bools = [ch == "#" for row in mask for ch in row]
@ -975,6 +976,8 @@ def write_manifest(
"bounds": bounds,
"triCount": int(tri_count),
}
if mechanisms is not None:
doc["mechanisms"] = mechanisms
manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest_path.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8")

View file

@ -14,11 +14,15 @@ REPO_ROOT = Path(__file__).resolve().parents[2]
VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles"
GEAR_DIR = REPO_ROOT / "assets" / "gear"
EXPECTED_VEHICLES = ("jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor")
EXPECTED_VEHICLES = (
"jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor",
"breaker", "paladin", "raptor", "manticore",
)
RETROFIT_MECHS = frozenset({"breaker", "paladin", "raptor", "manticore"})
EXPECTED_GEAR = ("mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator")
def parse_glb_json(glb_path: Path) -> dict[str, Any]:
def parse_glb(glb_path: Path) -> tuple[dict[str, Any], bytes]:
data = glb_path.read_bytes()
if len(data) < 20:
raise AssertionError(f"{glb_path}: file too small ({len(data)} bytes)")
@ -30,7 +34,18 @@ def parse_glb_json(glb_path: Path) -> dict[str, Any]:
chunk_len, chunk_type = struct.unpack_from("<II", data, 12)
if chunk_type != 0x4E4F534A:
raise AssertionError(f"{glb_path}: first chunk is not JSON ({hex(chunk_type)})")
return json.loads(data[20 : 20 + chunk_len].decode("utf-8"))
gltf = json.loads(data[20 : 20 + chunk_len].decode("utf-8"))
bin_off = 20 + chunk_len
bin_blob = b""
if bin_off + 8 <= len(data):
b_len, b_type = struct.unpack_from("<II", data, bin_off)
if b_type == 0x004E4942:
bin_blob = data[bin_off + 8 : bin_off + 8 + b_len]
return gltf, bin_blob
def parse_glb_json(glb_path: Path) -> dict[str, Any]:
return parse_glb(glb_path)[0]
def _node_local_matrix(node: dict[str, Any]) -> np.ndarray:
@ -58,10 +73,11 @@ def _node_local_matrix(node: dict[str, Any]) -> np.ndarray:
return m
def compute_glb_stats(gltf: dict[str, Any]) -> tuple[int, np.ndarray, np.ndarray]:
def compute_glb_stats(gltf: dict[str, Any], bin_blob: bytes = b"") -> tuple[int, np.ndarray, np.ndarray]:
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)))
@ -85,15 +101,27 @@ def compute_glb_stats(gltf: dict[str, Any]) -> tuple[int, np.ndarray, np.ndarray
pos_acc_idx = prim.get("attributes", {}).get("POSITION")
if pos_acc_idx is not None:
acc = accessors[pos_acc_idx]
pmin = np.array(acc["min"], dtype=np.float64)
pmax = np.array(acc["max"], dtype=np.float64)
corners = np.array([
[x, y, z, 1.0]
for x in (pmin[0], pmax[0])
for y in (pmin[1], pmax[1])
for z in (pmin[2], pmax[2])
], dtype=np.float64)
wc = (world @ corners.T).T[:, :3]
if bin_blob and "bufferView" in acc and acc.get("componentType") == 5126 and acc.get("type") == "VEC3":
bv = buffer_views[acc["bufferView"]]
off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0)
stride = bv.get("byteStride", 12)
count = acc["count"]
if stride == 12:
pts = np.frombuffer(bin_blob, dtype="<f4", count=count * 3, offset=off).reshape(count, 3)
else:
raw = np.frombuffer(bin_blob, dtype=np.uint8, count=count * stride, offset=off).reshape(count, stride)
pts = raw[:, :12].view("<f4").reshape(count, 3)
wc = pts @ world[:3, :3].T + world[:3, 3]
else:
pmin = np.array(acc["min"], dtype=np.float64)
pmax = np.array(acc["max"], dtype=np.float64)
corners = np.array([
[x, y, z, 1.0]
for x in (pmin[0], pmax[0])
for y in (pmin[1], pmax[1])
for z in (pmin[2], pmax[2])
], dtype=np.float64)
wc = (world @ corners.T).T[:, :3]
g_min = np.minimum(g_min, wc.min(axis=0))
g_max = np.maximum(g_max, wc.max(axis=0))
for child_idx in node.get("children", []):
@ -116,7 +144,7 @@ def validate_vehicle(vid: str) -> dict[str, Any]:
raise AssertionError(f"Missing manifest: {manifest_path}")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
gltf = parse_glb_json(glb_path)
gltf, bin_blob = parse_glb(glb_path)
nodes = gltf.get("nodes", [])
# 1. Check hardpoint grid bounds, mask activity, and zero overlaps
@ -171,24 +199,35 @@ def validate_vehicle(vid: str) -> dict[str, Any]:
if key not in extras:
raise AssertionError(f"{vid}: joint {jid!r} missing {key} in GLB extras")
plane = manifest.get("plane")
if plane not in ("Dorsal", "Coronal"):
raise AssertionError(f"{vid}: invalid plane {plane!r}")
# 4. Check GLB triangle count & grounded +Y-up / +Z-forward bounds
tri_total, g_min, g_max = compute_glb_stats(gltf)
if not (1500 <= tri_total <= 35000):
raise AssertionError(f"{vid}: tri count {tri_total} outside [1500, 35000]")
tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob)
max_tris = 50000 if vid in RETROFIT_MECHS else 35000
min_tris = 15000 if vid in RETROFIT_MECHS else 1500
if not (min_tris <= tri_total <= max_tris):
raise AssertionError(f"{vid}: tri count {tri_total} outside [{min_tris}, {max_tris}]")
if abs(tri_total - manifest["triCount"]) > 0:
raise AssertionError(f"{vid}: GLB tri count {tri_total} != manifest triCount {manifest['triCount']}")
if abs(float(g_min[1])) > 0.02:
raise AssertionError(f"{vid}: GLB not grounded at minY=0 (got minY={g_min[1]:.4f})")
size = g_max - g_min
if not (1.2 <= size[0] <= 5.0 and 1.0 <= size[1] <= 3.5 and 2.5 <= size[2] <= 6.5):
if vid in RETROFIT_MECHS:
if not (2.5 <= size[0] <= 10.0 and 5.0 <= size[1] <= 12.5 and 2.5 <= size[2] <= 10.0):
raise AssertionError(f"{vid}: implausible mech bounds size {size.tolist()}")
elif not (1.2 <= size[0] <= 5.0 and 1.0 <= size[1] <= 3.5 and 2.5 <= size[2] <= 6.5):
raise AssertionError(f"{vid}: implausible bounds size {size.tolist()}")
return {
"id": vid,
"plane": plane,
"tris": tri_total,
"bytes": glb_path.stat().st_size,
"hardpoints": len(manifest["hardpoints"]),
"joints": len(manifest["joints"]),
"mechanisms": len((manifest.get("mechanisms") or {}).get("dofs", [])),
"minY": round(float(g_min[1]), 4),
"size": [round(float(v), 3) for v in size],
}
@ -198,8 +237,8 @@ def validate_gear(gid: str) -> dict[str, Any]:
glb_path = GEAR_DIR / f"{gid}.glb"
if not glb_path.is_file():
raise AssertionError(f"Missing gear GLB: {glb_path}")
gltf = parse_glb_json(glb_path)
tri_total, g_min, g_max = compute_glb_stats(gltf)
gltf, bin_blob = parse_glb(glb_path)
tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob)
if tri_total <= 0 or tri_total > 10000:
raise AssertionError(f"gear/{gid}: unexpected tri count {tri_total}")
if abs(float(g_min[1])) > 0.02:
@ -217,7 +256,8 @@ def main() -> int:
g_reports = [validate_gear(g) for g in EXPECTED_GEAR]
print("=== VEHICLE GLB VALIDATION PASSED ===")
for r in v_reports:
print(f" {r['id']:8s} | tris={r['tris']:5d} | size={r['size']} | minY={r['minY']} | hps={r['hardpoints']} | joints={r['joints']} | {r['bytes']/1024:.1f} KiB")
mech_tag = f" | dofs={r['mechanisms']}" if r["mechanisms"] else ""
print(f" {r['id']:10s} | {r['plane']:7s} | tris={r['tris']:5d} | size={r['size']} | minY={r['minY']} | hps={r['hardpoints']} | joints={r['joints']}{mech_tag} | {r['bytes']/1024:.1f} KiB")
print("=== GEAR GLB VALIDATION PASSED ===")
for r in g_reports:
print(f" {r['id']:14s} | tris={r['tris']:4d} | size={r['size']} | {r['bytes']/1024:.1f} KiB")