Files
NODEDC_MISSION_CORE/simulation/ai-polygon/rover_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

132 lines
5.5 KiB
Python

"""Visual track kinematics, shared contract with the local PlayCanvas adapter.
Each side advances by measured travel. Never changes physics or AI observations.
The CAD belt path is Blender X/Z; returned poses are glTF Y-up coordinates.
"""
import math
import time
def belt_pose(motion, distance, side, index):
s = (distance + motion["phase_m"] + index * motion["pitch_m"]) % motion["length_m"]
kind, start, _, d = next(seg for seg in motion["segments"] if s <= seg[1] + seg[2] + 1e-10)
t = s - start
if kind == "arc":
cx, cz, r, a = d
q = a - t / r
x, z, angle = cx + r * math.cos(q), cz + r * math.sin(q), q - math.pi / 2
else:
x, z, angle = d[0] + d[2] * t, d[1] + d[3] * t, math.atan2(d[3], d[2])
shift = motion["shift_m"]
return [x + shift[0], z + shift[2], -motion["track_centres_m"][side] - shift[1]], angle
class TrackPhase:
def __init__(self, motion):
self.motion = motion
self.distances = {"L": 0.0, "R": 0.0}
self.wheel_angles = {w["node"]: 0.0 for w in motion["wheels"]}
def step(self, dt, left, right):
dt = min(0.1, max(0.0, dt))
speeds = {"L": left, "R": right}
for side, speed in speeds.items():
self.distances[side] = (self.distances[side] + speed * dt) % self.motion["length_m"]
for wheel in self.motion["wheels"]:
name = wheel["node"]
self.wheel_angles[name] = (
self.wheel_angles[name] - speeds[name[0]] * dt / wheel["radius_m"]
) % (2 * math.pi)
class UsdTrackMotion:
def __init__(self, stage, root, motion):
from pxr import Usd, UsdGeom, Vt
self.motion = motion
self.phase = TrackPhase(motion)
self.links, self.wheels = [], []
self.updates = 0
self.total_seconds = self.max_seconds = 0.0
self.travel = {"L": 0.0, "R": 0.0}
self.dirty = True
prims = {p.GetName(): p for p in Usd.PrimRange(stage.GetPrimAtPath(root))}
def ops(name):
if name not in prims:
raise ValueError(f"Converted rover is missing animated node: {name}")
xform = UsdGeom.Xformable(prims[name])
# Store the static translation before replacing the converter's
# transform stack. Source nodes have unit scale and no parent spin.
translation = xform.GetLocalTransformation().ExtractTranslation()
xform.ClearXformOpOrder()
position = xform.AddTranslateOp()
position.Set(translation)
rotation = xform.AddRotateZOp()
rotation.Set(0)
return position, rotation
first = prims["L_BELT_00"]
instancer = UsdGeom.PointInstancer.Define(
stage, first.GetParent().GetPath().AppendChild("AnimatedBelts")
)
prototype = stage.DefinePrim(instancer.GetPath().AppendChild("Pitch"))
prototype.GetReferences().AddInternalReference(first.GetPath())
UsdGeom.Xformable(prototype).ClearXformOpOrder()
UsdGeom.Imageable(prototype).CreateVisibilityAttr(UsdGeom.Tokens.inherited)
instancer.CreatePrototypesRel().SetTargets([prototype.GetPath()])
instancer.CreateProtoIndicesAttr(Vt.IntArray([0] * (2 * motion["link_count"])))
self.positions = instancer.CreatePositionsAttr()
self.orientations = instancer.CreateOrientationsAttr()
for side in ("L", "R"):
for index in range(motion["link_count"]):
prim = prims[f"{side}_BELT_{index:02d}"]
if prim.GetParent() != first.GetParent():
raise ValueError("Belt nodes must share the glTF model frame")
UsdGeom.Imageable(prim).CreateVisibilityAttr(UsdGeom.Tokens.invisible)
self.links.append((side, index))
for wheel in motion["wheels"]:
self.wheels.append((wheel["node"], ops(wheel["node"])[1]))
self.publish()
def advance(self, dt, left, right):
self.phase.step(dt, left, right)
self.travel["L"] += left * dt
self.travel["R"] += right * dt
self.dirty |= abs(left) + abs(right) > 1e-6
def publish(self):
if not self.dirty:
return
from pxr import Gf, Sdf, Vt
started = time.perf_counter()
# USD notices are expensive. Batch all visual nodes once per render,
# outside PhysX callbacks, instead of resyncing the stage per attribute.
positions, orientations = [], []
for side, index in self.links:
point, angle = belt_pose(self.motion, self.phase.distances[side], side, index)
positions.append(Gf.Vec3f(*point))
orientations.append(Gf.Quath(math.cos(angle / 2), Gf.Vec3h(0, 0, math.sin(angle / 2))))
with Sdf.ChangeBlock():
self.positions.Set(Vt.Vec3fArray(positions))
self.orientations.Set(Vt.QuathArray(orientations))
for name, rotation in self.wheels:
rotation.Set(math.degrees(self.phase.wheel_angles[name]))
elapsed = time.perf_counter() - started
self.updates += 1
self.total_seconds += elapsed
self.max_seconds = max(self.max_seconds, elapsed)
self.dirty = False
def metrics(self):
return dict(
updates=self.updates,
mean_ms=1000 * self.total_seconds / max(1, self.updates),
max_ms=1000 * self.max_seconds,
side_travel_m=self.travel,
belt_phase_m=self.phase.distances,
wheel_angles_rad=self.phase.wheel_angles,
)