Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -9,7 +9,7 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
|
||||
def load_glb(path):
|
||||
def load_glb(path, rotation=None):
|
||||
data = Path(path).read_bytes()
|
||||
magic, version, size = struct.unpack_from("<III", data)
|
||||
if (magic, version, size) != (0x46546C67, 2, len(data)):
|
||||
@@ -43,6 +43,13 @@ def load_glb(path):
|
||||
strides=(view.get("byteStride", width * item), item),
|
||||
).copy()
|
||||
|
||||
transform = np.eye(3)
|
||||
if rotation:
|
||||
x, y, z = np.radians(rotation)
|
||||
rx = np.array([[1, 0, 0], [0, np.cos(x), -np.sin(x)], [0, np.sin(x), np.cos(x)]])
|
||||
ry = np.array([[np.cos(y), 0, np.sin(y)], [0, 1, 0], [-np.sin(y), 0, np.cos(y)]])
|
||||
rz = np.array([[np.cos(z), -np.sin(z), 0], [np.sin(z), np.cos(z), 0], [0, 0, 1]])
|
||||
transform = rz @ ry @ rx
|
||||
vertices, faces, base = [], [], 0
|
||||
# SplatTransform collision exports bake coordinates; reject transforms so
|
||||
# we never silently misregister contact geometry against the Gaussian view.
|
||||
@@ -57,6 +64,7 @@ def load_glb(path):
|
||||
triangles = accessor(primitive["indices"]).reshape(-1, 3).astype(np.int32)
|
||||
if not np.isfinite(points).all() or triangles.max() >= len(points):
|
||||
raise ValueError("Invalid collision vertices")
|
||||
points = points @ transform.T
|
||||
vertices.append(points[:, [0, 2, 1]] * np.array([1, -1, 1], np.float32))
|
||||
faces.append(triangles + base)
|
||||
base += len(points)
|
||||
@@ -82,7 +90,105 @@ def ground_intersections(vertices, faces, x, y):
|
||||
return (u * a[:, 2] + v * b[:, 2] + (1 - u - v) * c[:, 2])[inside]
|
||||
|
||||
|
||||
def install_terrain(stage, manifest_path, world):
|
||||
def terrain_contact_policy(physics_profile):
|
||||
"""Metric contact generation distance, independent of a map's full extent."""
|
||||
offset = physics_profile["contact_offset_m"]
|
||||
if type(offset) not in (float, int) or not math.isfinite(offset) or offset <= 0:
|
||||
raise ValueError("Terrain contact offset requires a positive finite metric profile value")
|
||||
return dict(contact_offset_m=float(offset), rest_offset_m=0.,
|
||||
source="robot.physics.contact_offset_m", derived_from_map_extent=False)
|
||||
|
||||
|
||||
CONTACT_READBACK_TOLERANCE_M = 1e-7 # Fixed USD float32 readback tolerance, not a contact margin.
|
||||
|
||||
|
||||
def _contact_policy_readback(prim, policy):
|
||||
from pxr import PhysxSchema, UsdPhysics
|
||||
|
||||
if not prim or not prim.IsValid() or not prim.HasAPI(UsdPhysics.CollisionAPI):
|
||||
raise ValueError("Environment contact policy requires an existing collision prim")
|
||||
if not prim.HasAPI(PhysxSchema.PhysxCollisionAPI):
|
||||
raise ValueError("Environment contact policy must be explicitly authored")
|
||||
api = PhysxSchema.PhysxCollisionAPI(prim)
|
||||
values = {}
|
||||
for key, attribute in (
|
||||
("contact_offset_m", api.GetContactOffsetAttr()),
|
||||
("rest_offset_m", api.GetRestOffsetAttr()),
|
||||
):
|
||||
if not attribute or not attribute.HasAuthoredValueOpinion():
|
||||
raise ValueError("Environment contact offset cannot use an automatic default")
|
||||
value = attribute.Get()
|
||||
if (
|
||||
type(value) not in (float, int)
|
||||
or not math.isfinite(value)
|
||||
or (key == "contact_offset_m" and value <= 0)
|
||||
or (key == "rest_offset_m" and value != 0.0)
|
||||
or not math.isclose(
|
||||
value, policy[key], rel_tol=0.0, abs_tol=CONTACT_READBACK_TOLERANCE_M
|
||||
)
|
||||
):
|
||||
raise ValueError("Authored environment contact policy differs from effective robot")
|
||||
values[key] = float(value)
|
||||
return dict(
|
||||
collider=str(prim.GetPath()),
|
||||
**values,
|
||||
contact_offset_authored=True,
|
||||
rest_offset_authored=True,
|
||||
)
|
||||
|
||||
|
||||
def apply_environment_contact_policy(prim, physics_profile):
|
||||
"""Author the same metric policy for terrain, native pads and obstacles."""
|
||||
from pxr import PhysxSchema
|
||||
|
||||
policy = terrain_contact_policy(physics_profile)
|
||||
api = PhysxSchema.PhysxCollisionAPI.Apply(prim)
|
||||
api.CreateContactOffsetAttr(policy["contact_offset_m"])
|
||||
api.CreateRestOffsetAttr(policy["rest_offset_m"])
|
||||
return _contact_policy_readback(prim, policy)
|
||||
|
||||
|
||||
def validate_environment_contact_policy(stage, collider_paths, physics_profile):
|
||||
"""Read-only USD preflight. It does not claim a cooked-native readback."""
|
||||
from pxr import Sdf, UsdGeom
|
||||
|
||||
if (
|
||||
not isinstance(collider_paths, (list, tuple))
|
||||
or not collider_paths
|
||||
or any(not isinstance(path, str) for path in collider_paths)
|
||||
or len(set(collider_paths)) != len(collider_paths)
|
||||
):
|
||||
raise ValueError("Exact unique environment collider paths are required")
|
||||
if stage is None:
|
||||
raise ValueError("Native scene stage is missing")
|
||||
units = UsdGeom.GetStageMetersPerUnit(stage)
|
||||
if type(units) not in (float, int) or not math.isfinite(units) or units != 1.0:
|
||||
raise ValueError("Metric environment contact policy requires metre stage units")
|
||||
policy = terrain_contact_policy(physics_profile)
|
||||
colliders = []
|
||||
for name in collider_paths:
|
||||
path = Sdf.Path(name)
|
||||
if not path.IsAbsolutePath() or not path.IsPrimPath() or str(path) != name:
|
||||
raise ValueError("Environment contact policy needs exact absolute prim paths")
|
||||
prim = stage.GetPrimAtPath(path)
|
||||
if not prim or not prim.IsValid() or str(prim.GetPath()) != name:
|
||||
raise ValueError("Environment contact policy prim is missing or mismatched")
|
||||
colliders.append(_contact_policy_readback(prim, policy))
|
||||
policy_sha256 = hashlib.sha256(
|
||||
json.dumps(policy, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
).hexdigest()
|
||||
return dict(
|
||||
schema_version="missioncore.environment-contact-policy/v1",
|
||||
policy=policy,
|
||||
policy_sha256=policy_sha256,
|
||||
meters_per_unit=float(units),
|
||||
readback_tolerance_m=CONTACT_READBACK_TOLERANCE_M,
|
||||
colliders=colliders,
|
||||
scope="authored-usd-readback; native-cooked-not-verified",
|
||||
)
|
||||
|
||||
|
||||
def install_terrain(stage, manifest_path, world, *, physics_profile=None):
|
||||
from pxr import UsdGeom, UsdPhysics, UsdShade
|
||||
from rover_profile import PROFILE
|
||||
|
||||
@@ -94,7 +200,7 @@ def install_terrain(stage, manifest_path, world):
|
||||
path = Path(manifest["collider"])
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != manifest["collider_sha256"]:
|
||||
raise ValueError("Collision mesh identity changed")
|
||||
points, triangles = load_glb(path)
|
||||
points, triangles = load_glb(path, manifest.get("collision_rotation"))
|
||||
settings = world["settings"]
|
||||
heights = ground_intersections(points, triangles, *settings["spawn_xy"])
|
||||
candidates = heights[np.abs(heights - settings["ground_z"]) < 0.8]
|
||||
@@ -104,8 +210,8 @@ def install_terrain(stage, manifest_path, world):
|
||||
# in a stone beside the centre ray. This is setup, never a planner input.
|
||||
angle = math.radians(settings["heading_degrees"])
|
||||
support, offsets = [], []
|
||||
for dx in (-0.5, 0, 0.5):
|
||||
for dy in (-0.5, 0, 0.5):
|
||||
for dx in (-PROFILE["length_m"] / 2, 0, PROFILE["length_m"] / 2):
|
||||
for dy in (-PROFILE["width_m"] / 2, 0, PROFILE["width_m"] / 2):
|
||||
x = settings["spawn_xy"][0] + dx * math.cos(angle) - dy * math.sin(angle)
|
||||
y = settings["spawn_xy"][1] + dx * math.sin(angle) + dy * math.cos(angle)
|
||||
intersections = ground_intersections(points, triangles, x, y)
|
||||
@@ -129,6 +235,8 @@ def install_terrain(stage, manifest_path, world):
|
||||
settings["heading_degrees"],
|
||||
plane,
|
||||
step=PROFILE["max_step_m"],
|
||||
length=PROFILE["length_m"],
|
||||
width=PROFILE["width_m"],
|
||||
):
|
||||
raise ValueError("Configured spawn contains an obstacle inside the rover footprint")
|
||||
# Align to the local support plane before gravity settles the suspensionless
|
||||
@@ -145,6 +253,9 @@ def install_terrain(stage, manifest_path, world):
|
||||
mesh.CreateVisibilityAttr(UsdGeom.Tokens.invisible)
|
||||
UsdPhysics.CollisionAPI.Apply(mesh.GetPrim())
|
||||
UsdPhysics.MeshCollisionAPI.Apply(mesh.GetPrim()).CreateApproximationAttr("none")
|
||||
effective_physics = PROFILE if physics_profile is None else physics_profile
|
||||
apply_environment_contact_policy(mesh.GetPrim(), effective_physics)
|
||||
contact_policy = terrain_contact_policy(effective_physics)
|
||||
material = UsdShade.Material.Define(stage, "/World/Materials/Terrain")
|
||||
surface = UsdPhysics.MaterialAPI.Apply(material.GetPrim())
|
||||
surface.CreateStaticFrictionAttr(0.9)
|
||||
@@ -160,6 +271,7 @@ def install_terrain(stage, manifest_path, world):
|
||||
initial_contact_z=float(plane[2]),
|
||||
initial_ground_normal=normal.tolist(),
|
||||
support_residual_m=float(np.max(np.abs(residual))),
|
||||
contact_policy=contact_policy,
|
||||
)
|
||||
|
||||
|
||||
@@ -175,28 +287,54 @@ class RangeSensor:
|
||||
|
||||
self.query = omni.physx.get_physx_scene_query_interface()
|
||||
elevations = (-80, -75, -70, -60, -45, -35, -28, -22, -18, -14, -10, -5, 0, 5, 15)
|
||||
self.directions = [
|
||||
(math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e))
|
||||
for e in np.radians(elevations)
|
||||
for a in np.radians(np.arange(-180, 180, 2.5))
|
||||
]
|
||||
self.rear_directions = [
|
||||
(math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e))
|
||||
for e in np.radians(np.arange(-80, 16, 5))
|
||||
for a in np.radians(np.arange(100, 261, 5))
|
||||
]
|
||||
self.directions = np.array(
|
||||
[
|
||||
(math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e))
|
||||
for e in np.radians(elevations)
|
||||
for a in np.radians(np.arange(-180, 180, 2.5))
|
||||
]
|
||||
)
|
||||
self.rear_directions = np.array(
|
||||
[
|
||||
(math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e))
|
||||
for e in np.radians(np.arange(-80, 16, 5))
|
||||
for a in np.radians(np.arange(100, 261, 5))
|
||||
]
|
||||
)
|
||||
|
||||
def capture(self, origin, rotation, rear_origin=None):
|
||||
from pxr import Gf
|
||||
|
||||
points = []
|
||||
# Qualification evidence only. Collider identities never enter the
|
||||
# observation packet consumed by navigation or semantic inference.
|
||||
self.hit_paths = {}
|
||||
ray_origin_indices, ray_ends = [], []
|
||||
# Gf uses row vectors. Transform the whole fan once, preserving all
|
||||
# rays and the closest-hit/self-occlusion policy of the sensor.
|
||||
axes = np.asarray(rotation, dtype=float)[:3, :3]
|
||||
mounts = [(origin, self.directions)]
|
||||
if rear_origin is not None:
|
||||
mounts.append((rear_origin, self.rear_directions))
|
||||
for mount, directions in mounts:
|
||||
for direction in directions:
|
||||
ray = rotation.TransformDir(Gf.Vec3d(*direction)).GetNormalized()
|
||||
hit = self.query.raycast_closest(tuple(mount), tuple(ray), 8.0, bothSides=True)
|
||||
for mount_index, (mount, directions) in enumerate(mounts):
|
||||
rays = np.asarray(directions) @ axes
|
||||
rays /= np.linalg.norm(rays, axis=1, keepdims=True)
|
||||
mount = tuple(mount)
|
||||
for ray in rays.tolist():
|
||||
hit = self.query.raycast_closest(mount, tuple(ray), 8.0, bothSides=True)
|
||||
# A valid no-echo beam observes free space to its maximum range.
|
||||
# Self-occluded rays grant no clearing evidence behind the body.
|
||||
if not hit["hit"]:
|
||||
ray_origin_indices.append(mount_index)
|
||||
ray_ends.append(np.asarray(mount) + np.asarray(ray) * 8.0)
|
||||
if hit["hit"] and not str(hit.get("rigidBody", "")).startswith("/World/Rover"):
|
||||
points.append(hit["position"])
|
||||
ray_origin_indices.append(mount_index)
|
||||
ray_ends.append(hit["position"])
|
||||
path = str(hit.get("collision", ""))
|
||||
if path:
|
||||
self.hit_paths[path] = self.hit_paths.get(path, 0) + 1
|
||||
self.rays = {
|
||||
"origins": np.asarray([m for m, _ in mounts], dtype=np.float32).reshape(-1, 3),
|
||||
"origin_indices": np.asarray(ray_origin_indices, dtype=np.int32),
|
||||
"ends": np.asarray(ray_ends, dtype=np.float32).reshape(-1, 3),
|
||||
}
|
||||
return np.asarray(points, dtype=np.float32).reshape(-1, 3)
|
||||
|
||||
Reference in New Issue
Block a user