Files
NODEDC_MISSION_CORE/tools/rover-scene/export_motion.py
T
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00

281 lines
10 KiB
Python

"""Export v020 CAD as a shared, articulated visual rig; source .blend is never saved.
Run Blender -b <v020.blend> --python tools/rover-scene/export_motion.py from repo root.
The original reconstructed tread recipe and taut belt path live in source/.
The 44 repeated rubber pitches are rigid visual links, not contact simulation.
"""
import hashlib
import json
import math
import sys
from collections import defaultdict
from pathlib import Path
import bpy
from mathutils import Matrix, Vector
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE), str(HERE / "source")]
from materials import classify, materials # noqa: E402
from track_detail import add_track # noqa: E402
from track_path import PITCH, RW, solve # noqa: E402
root = Path.cwd()
source = Path(bpy.data.filepath)
source_hash = hashlib.sha256(source.read_bytes()).hexdigest()
bpy.context.scene.frame_set(1)
dg = bpy.context.evaluated_depsgraph_get()
shift = Vector((-0.0535, 0, 0))
groups = defaultdict(list)
pivots = {}
for o in bpy.context.scene.objects:
if o.name.startswith(("L_SPIN_", "R_SPIN_")):
pivots[o.name] = o.matrix_world.translation.copy() + shift
for inst in dg.object_instances:
o = inst.object
src = o.original
if o.type not in {"MESH", "CURVE"} or src.hide_render:
continue
if "MURAVEY" in src.name:
if "carcass" not in src.name:
continue
# The continuous side bands have no longitudinal pattern and do not
# change shape as rubber circulates. Keep their exact curved CAD surface.
original = src.data
mesh = bpy.data.meshes.new("Continuous side bands")
mesh.from_pydata(
[v.co[:] for v in original.vertices],
[],
[p.vertices[:] for p in original.polygons if all(i % 240 < 192 for i in p.vertices)],
)
mesh.materials.append(materials["rubber"])
mesh.transform(Matrix.Translation(shift) @ inst.matrix_world)
groups["STATIC"].append(mesh)
continue
if any(
c.hide_render or any(t in c.name for t in ["STUDIO", "BOOLEAN", "DATUM"])
for c in src.users_collection
):
continue
if not inst.is_instance and not src.visible_get():
continue
parent, group = src.parent, "STATIC"
while parent:
if parent.name in pivots:
group = parent.name
break
parent = parent.parent
mesh = bpy.data.meshes.new_from_object(o, preserve_all_data_layers=True, depsgraph=dg)
for i, mat in enumerate(mesh.materials):
mesh.materials[i] = materials[classify(mat.name if mat else "", src.name)]
if not mesh.materials:
mesh.materials.append(materials["body"])
matrix = Matrix.Translation(shift) @ inst.matrix_world
if group != "STATIC":
matrix = Matrix.Translation(-pivots[group]) @ matrix
mesh.transform(matrix)
groups[group].append(mesh)
# Blender object names are global across scenes; reserve the portable rig names.
for name in pivots:
bpy.data.objects[name].name = "SOURCE_" + name
scene = bpy.data.scenes.new("DCD-006 simulation motion")
bpy.context.window.scene = scene
for group, meshes in groups.items():
objects = []
for mesh in meshes:
o = bpy.data.objects.new(group, mesh)
scene.collection.objects.link(o)
objects.append(o)
bpy.ops.object.select_all(action="DESELECT")
for o in objects:
o.select_set(True)
bpy.context.view_layer.objects.active = objects[0]
bpy.ops.object.join()
o = bpy.context.object
o.name = group
if group != "STATIC":
o.location = pivots[group]
# Nine static material batches, while rotating assemblies keep their identity.
if group == "STATIC":
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.mesh.separate(type="MATERIAL")
bpy.ops.object.mode_set(mode="OBJECT")
# Reuse one mould pitch on every link. At ground contact the chevron points
# toward +X (front drive sprocket), hence direction=-1 along the bottom run.
scratch = bpy.data.collections.new("Pitch source")
scene.collection.children.link(scratch)
length = 2.222
def flat_sample(s):
if s > length / 2:
s -= length
return Vector((s, 0, 0)), Vector((1, 0, 0)), Vector((0, 0, 1))
full = add_track(
dict(
collection=scratch,
materials={"rubber": materials["rubber"], "metal": materials["track-steel"]},
sample=flat_sample,
length=length,
pitch=PITCH,
direction=-1,
side_label="Template",
)
)
templates = []
for o in full:
# Generator emits each of its five components in 44 contiguous equal blocks.
count = len(o.data.vertices) // 44
mesh = bpy.data.meshes.new("pitch")
offset = 192 if "carcass" in o.name else 0
mesh.from_pydata(
[v.co[:] for v in o.data.vertices[offset:count]],
[],
[
tuple(i - offset for i in p.vertices)
for p in o.data.polygons
if min(p.vertices) >= offset and max(p.vertices) < count
],
)
# Re-centre each disconnected mould detail into the nearest repeated pitch.
# This avoids a long rigid overhang when a link goes around a small roller.
neighbours = defaultdict(set)
for face in mesh.polygons:
for i in face.vertices:
neighbours[i].update(face.vertices)
remaining = set(range(len(mesh.vertices)))
while remaining:
cluster, todo = set(), [next(iter(remaining))]
while todo:
i = todo.pop()
if i in cluster:
continue
cluster.add(i)
todo.extend(neighbours[i] - cluster)
remaining -= cluster
centre = sum(mesh.vertices[i].co.x for i in cluster) / len(cluster)
correction = math.floor(centre / PITCH + 0.5) * PITCH
for i in cluster:
mesh.vertices[i].co.x -= correction
mesh.materials.append(o.data.materials[0])
part = bpy.data.objects.new("pitch", mesh)
scene.collection.objects.link(part)
for m in o.modifiers:
modifier = part.modifiers.new(m.name, m.type)
modifier.width = m.width
modifier.segments = m.segments
templates.append(part)
bpy.data.objects.remove(o, do_unlink=True)
bpy.context.view_layer.update()
for o in templates:
for mod in list(o.modifiers):
bpy.context.view_layer.objects.active = o
bpy.ops.object.modifier_apply(modifier=mod.name)
bpy.ops.object.select_all(action="DESELECT")
for o in templates:
o.select_set(True)
bpy.context.view_layer.objects.active = templates[0]
bpy.ops.object.join()
template = bpy.context.object
path = solve()
nodes = []
for side, transverse in [("L", 0.3425), ("R", -0.3425)]:
for i in range(44):
o = bpy.data.objects.new(f"{side}_BELT_{i:02d}", template.data)
scene.collection.objects.link(o)
p, t, n = path["sample"](path["track_phase"] + i * PITCH, transverse)
o.location = p + shift
o.rotation_euler.y = math.atan2(-t.z, t.x)
nodes.append(o)
bpy.data.objects.remove(template, do_unlink=True)
bpy.data.collections.remove(scratch)
bpy.context.view_layer.update()
objects = list(scene.objects)
lo = Vector(
min((o.matrix_world @ Vector(v))[i] for o in objects for v in o.bound_box) for i in range(3)
)
hi = Vector(
max((o.matrix_world @ Vector(v))[i] for o in objects for v in o.bound_box) for i in range(3)
)
if (
max(abs(a - b) for a, b in zip(hi - lo, (1.163, 0.905, 0.734), strict=True)) > 0.006
or abs(lo.z) > 0.006
):
raise ValueError(f"Articulated model envelope changed: {lo}, {hi}")
out = root / "apps/control-station/public/rover-scene/dcd006-v020-motion.glb"
bpy.ops.object.select_all(action="SELECT")
bpy.ops.export_scene.gltf(
filepath=str(out),
export_format="GLB",
use_selection=True,
use_active_scene=True,
export_animations=False,
export_cameras=False,
export_lights=False,
export_extras=False,
export_yup=True,
export_apply=False,
export_attributes=False,
export_vertex_color="NONE",
)
manifest = dict(
schema_version="missioncore.rover-motion/v1",
source_scene=source.name,
source_sha256=source_hash,
source_saved=False,
visual_sha256=hashlib.sha256(out.read_bytes()).hexdigest(),
forward_axis="+X",
up_axis="Y",
track_centres_m={"L": 0.3425, "R": -0.3425},
track_width_m=0.685,
shift_m=list(shift),
length_m=path["length"],
pitch_m=PITCH,
phase_m=path["track_phase"],
segments=path["segments"],
link_count=44,
wheels=[
dict(node=name, radius_m=PITCH * 9 / (2 * math.pi) if name.endswith("DRIVE") else RW)
for name in pivots
],
dimensions_m=list(hi - lo),
minimum_m=list(lo),
method=(
"44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; "
"no track contact dynamics"
),
)
out.with_suffix(".json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
# A portable Blender preview: 1 metre of forward travel over 4 seconds, baked
# to the exported nodes. Runtime drives these same nodes from each side's speed.
scene.render.fps = 30
scene.frame_start, scene.frame_end = 1, 121
for frame in range(1, 122):
distance = (frame - 1) / 120
for o in nodes:
side, _, index = o.name.split("_")
p, t, n = path["sample"](
manifest["phase_m"] + int(index) * PITCH + distance, 0.3425 if side == "L" else -0.3425
)
o.location = p + shift
o.rotation_euler.y = math.atan2(-t.z, t.x)
o.keyframe_insert("location", frame=frame)
o.keyframe_insert("rotation_euler", frame=frame)
for spec in manifest["wheels"]:
o = scene.objects[spec["node"]]
o.rotation_euler.y = distance / spec["radius_m"]
o.keyframe_insert("rotation_euler", frame=frame)
scene.frame_set(1)
preview = root / "outputs/rover-motion/DCD-006_v020_motion.blend"
preview.parent.mkdir(parents=True, exist_ok=True)
bpy.ops.wm.save_as_mainfile(filepath=str(preview))
print("MOTION_EXPORT", out.stat().st_size, "bytes", len(objects), "nodes", flush=True)