Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,315 @@
|
||||
"""Isaac implementation of the portable Rover 006 observation rig.
|
||||
|
||||
Two separated RTX fisheyes produce panorama and a calibrated digital view.
|
||||
D455 RGB and ideal first-hit depth remain separate observations. All geometry
|
||||
queries retain first-hit self occlusion; unknown depth never clears space.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from k1link.simulation.ai_polygon.camera_optics import (
|
||||
DualFisheye,
|
||||
axes,
|
||||
fisheye_intrinsics,
|
||||
pinhole_rays,
|
||||
view_toward,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.run_inputs import MOUNTED_SENSOR_SCHEMA, CONTINUOUS_SENSOR_SCHEMA
|
||||
from k1link.simulation.ai_polygon.sensor_mounts import validate_mounts
|
||||
|
||||
|
||||
class MountedSensors:
|
||||
def __init__(self, stage, rig, contact_height):
|
||||
import omni.replicator.core as rep
|
||||
from pxr import Gf, UsdGeom, UsdPhysics
|
||||
|
||||
self.rig, self.contact_height = rig, contact_height
|
||||
self.mounts = validate_mounts(rig["mounts"])
|
||||
self.optics = DualFisheye(self.mounts["insta360"])
|
||||
self.cameras, self.products, self.rgb, self.depth = [], [], [], []
|
||||
self.focal = 800 * rig["focal_length_mm"] / rig["horizontal_aperture_mm"]
|
||||
self.intrinsics = [self.focal, self.focal, 400, 300]
|
||||
rs = self.mounts["realsense"]
|
||||
self.rs_axes = axes(0, rs["pitch_degrees"])
|
||||
|
||||
def camera(name, size, spec=None):
|
||||
value = UsdGeom.Camera.Define(stage, "/World/Sensors/" + name)
|
||||
value.CreateClippingRangeAttr(Gf.Vec2f(0.001, 1000))
|
||||
value.CreateFocalLengthAttr(14)
|
||||
value.CreateHorizontalApertureAttr(36)
|
||||
value.CreateVerticalApertureAttr(36 * size[1] / size[0])
|
||||
if spec is not None:
|
||||
prim = value.GetPrim()
|
||||
if not prim.ApplyAPI("OmniLensDistortionOpenCvFisheyeAPI"):
|
||||
raise RuntimeError("Native RTX fisheye schema unavailable")
|
||||
prim.GetAttribute("omni:lensdistortion:model").Set("opencvFisheye")
|
||||
fx, fy, cx, cy = fisheye_intrinsics(spec)
|
||||
for key, number in dict(
|
||||
fx=fx,
|
||||
fy=fy,
|
||||
cx=cx,
|
||||
cy=cy,
|
||||
k1=0.0,
|
||||
k2=0.0,
|
||||
k3=0.0,
|
||||
k4=0.0,
|
||||
imageSize=Gf.Vec2i(*size),
|
||||
).items():
|
||||
if not prim.GetAttribute("omni:lensdistortion:opencvFisheye:" + key).Set(
|
||||
number
|
||||
):
|
||||
raise RuntimeError("Cannot configure fisheye parameter " + key)
|
||||
else:
|
||||
value.CreateFocalLengthAttr(1.0)
|
||||
value.CreateHorizontalApertureAttr(
|
||||
2 * math.tan(math.radians(rs["fov_degrees"][0] / 2))
|
||||
)
|
||||
value.CreateVerticalApertureAttr(
|
||||
2 * math.tan(math.radians(rs["fov_degrees"][1] / 2))
|
||||
)
|
||||
self.cameras.append((value.AddTranslateOp(), value.AddOrientOp()))
|
||||
product = rep.create.render_product(str(value.GetPath()), tuple(size))
|
||||
rgb = rep.AnnotatorRegistry.get_annotator("rgb")
|
||||
rgb.attach(product)
|
||||
self.products.append(product)
|
||||
self.rgb.append(rgb)
|
||||
if spec is not None:
|
||||
depth = rep.AnnotatorRegistry.get_annotator("distance_to_camera")
|
||||
depth.attach(product)
|
||||
self.depth.append(depth)
|
||||
|
||||
x4 = self.mounts["insta360"]
|
||||
camera("InstaLeft", x4["image_size"], x4)
|
||||
camera("InstaRight", x4["image_size"], x4)
|
||||
camera("RealSense", rs["image_size"])
|
||||
# Shapes are explicitly approximate sensor envelopes, attached to the
|
||||
# chassis. They occlude other sensors rather than being hidden from them.
|
||||
for name, center, size, pitch in (
|
||||
("Insta360", x4["body_center_m"], x4["body_size_m"], 0),
|
||||
(
|
||||
"RealSense",
|
||||
(np.asarray(rs["origin_m"]) - self.rs_axes[:, 0] * 0.014).tolist(),
|
||||
rs["body_size_m"],
|
||||
rs["pitch_degrees"],
|
||||
),
|
||||
(
|
||||
"K1",
|
||||
(np.asarray(self.mounts["k1"]["origin_m"]) - axes(0, -15)[:, 2] * 0.12).tolist(),
|
||||
self.mounts["k1"]["body_size_m"],
|
||||
-15,
|
||||
),
|
||||
):
|
||||
shape = UsdGeom.Cube.Define(stage, "/World/Rover/chassis/Sensor" + name)
|
||||
shape.CreateSizeAttr(1)
|
||||
shape.AddTranslateOp().Set(Gf.Vec3d(center[0], center[1], center[2] - contact_height))
|
||||
shape.AddRotateYOp().Set(-pitch)
|
||||
shape.AddScaleOp().Set(Gf.Vec3f(*size))
|
||||
shape.CreateDisplayColorAttr([Gf.Vec3f(0.07, 0.08, 0.09)])
|
||||
UsdPhysics.CollisionAPI.Apply(shape.GetPrim())
|
||||
|
||||
def update(self, transform):
|
||||
from pxr import Gf
|
||||
|
||||
self.body_axes = np.asarray(transform, dtype=float)[:3, :3].T
|
||||
self.position = np.array(transform.ExtractTranslation())
|
||||
x4 = self.mounts["insta360"]
|
||||
locations = [*x4["lens_centres_m"], self.mounts["realsense"]["origin_m"]]
|
||||
self.origins, self.rotations = [], []
|
||||
for (pos, rotation), local, local_axes in zip(
|
||||
self.cameras, locations, [*self.optics.lens_axes, self.rs_axes], strict=True
|
||||
):
|
||||
origin = transform.Transform(
|
||||
Gf.Vec3d(local[0], local[1], local[2] - self.contact_height)
|
||||
)
|
||||
world_axes = self.body_axes @ local_axes
|
||||
pos.Set(origin)
|
||||
rotation.Set(
|
||||
Gf.Quatf(
|
||||
Gf.Matrix4d()
|
||||
.SetLookAt(
|
||||
origin, origin + Gf.Vec3d(*world_axes[:, 0]), Gf.Vec3d(*world_axes[:, 2])
|
||||
)
|
||||
.GetInverse()
|
||||
.ExtractRotationQuat()
|
||||
)
|
||||
)
|
||||
self.origins.append(list(origin))
|
||||
self.rotations.append(world_axes)
|
||||
|
||||
def capture(self, target):
|
||||
images = [np.array(a.get_data()[..., :3], copy=True) for a in self.rgb]
|
||||
depths = [np.array(a.get_data(), copy=True) for a in self.depth]
|
||||
if any(image.shape != (640, 640, 3) for image in images[:2]) or images[2].shape != (
|
||||
480,
|
||||
640,
|
||||
3,
|
||||
):
|
||||
return None
|
||||
view = view_toward(
|
||||
self.position[:2],
|
||||
self.body_axes,
|
||||
target["xy"] if target else None,
|
||||
self.rig["camera_height_m"],
|
||||
single_lens=self.rig["schema_version"] == MOUNTED_SENSOR_SCHEMA,
|
||||
)
|
||||
if self.rig["schema_version"] == CONTINUOUS_SENSOR_SCHEMA:
|
||||
view = axes(0, -20)
|
||||
calibration = {
|
||||
"projection": "dual-origin-rectilinear/v1",
|
||||
"origin": np.mean(self.origins[:2], axis=0).tolist(),
|
||||
"rotation": (self.body_axes @ view).reshape(-1).tolist(),
|
||||
"intrinsics": self.intrinsics,
|
||||
"lens_origins": self.origins[:2],
|
||||
"lens_axes": np.stack(self.rotations[:2]).tolist(),
|
||||
"body_contact_height_m": self.contact_height,
|
||||
}
|
||||
return images[0], {
|
||||
"calibration": calibration,
|
||||
"lens_depths": depths,
|
||||
"rectified_body_axes": view,
|
||||
"camera_sources": {
|
||||
"insta360_left": images[0],
|
||||
"insta360_right": images[1],
|
||||
"realsense_rgb": images[2],
|
||||
},
|
||||
}
|
||||
|
||||
def close(self):
|
||||
for annotator, product in zip(self.rgb, self.products, strict=True):
|
||||
annotator.detach(product)
|
||||
for annotator, product in zip(self.depth, self.products[:2], strict=True):
|
||||
annotator.detach(product)
|
||||
for product in self.products:
|
||||
product.destroy()
|
||||
|
||||
|
||||
class MountedRange:
|
||||
def __init__(self, rig, contact_height):
|
||||
from terrain import RangeSensor
|
||||
|
||||
legacy = RangeSensor()
|
||||
self.query = legacy.query
|
||||
self.mounts, self.contact_height = rig["mounts"], contact_height
|
||||
k1 = self.mounts["k1"]
|
||||
elevation, azimuth = np.meshgrid(
|
||||
np.radians(np.linspace(*k1["elevation_degrees"], 21)),
|
||||
np.radians(np.arange(-180, 180, 3)),
|
||||
indexing="ij",
|
||||
)
|
||||
fan = np.stack(
|
||||
(
|
||||
np.cos(elevation) * np.cos(azimuth),
|
||||
np.cos(elevation) * np.sin(azimuth),
|
||||
np.sin(elevation),
|
||||
),
|
||||
axis=-1,
|
||||
).reshape(-1, 3)
|
||||
self.k1_directions = fan @ axes(0, -k1["tilt_forward_degrees"]).T
|
||||
rs = self.mounts["realsense"]
|
||||
w, h = rs["depth_sample_size"]
|
||||
intrinsic = [
|
||||
w / (2 * math.tan(math.radians(rs["fov_degrees"][0] / 2))),
|
||||
h / (2 * math.tan(math.radians(rs["fov_degrees"][1] / 2))),
|
||||
w / 2,
|
||||
h / 2,
|
||||
]
|
||||
self.rs_rays = pinhole_rays([w, h], intrinsic).reshape(-1, 3)
|
||||
self.rs_directions = self.rs_rays @ axes(0, rs["pitch_degrees"]).T
|
||||
self.rs_size = (h, w)
|
||||
self.view_parameters = np.asarray([
|
||||
[-180, 3, k1["elevation_degrees"][0],
|
||||
(k1["elevation_degrees"][1]-k1["elevation_degrees"][0])/20],
|
||||
intrinsic,
|
||||
], dtype=float)
|
||||
self.view_axes = np.stack((axes(0, -k1["tilt_forward_degrees"]),
|
||||
axes(0, rs["pitch_degrees"])))
|
||||
|
||||
def capture(self, transform):
|
||||
from pxr import Gf
|
||||
|
||||
points, ends, indices, view_ranges = [], [], [], []
|
||||
self.hit_paths, origins = {}, []
|
||||
self.depth = np.full(len(self.rs_rays), np.nan, np.float32)
|
||||
self.source_counts = {"k1": 0, "realsense": 0}
|
||||
rotation = np.asarray(transform, dtype=float)[:3, :3]
|
||||
for index, (key, rays) in enumerate(
|
||||
(("k1", self.k1_directions), ("realsense", self.rs_directions))
|
||||
):
|
||||
local = self.mounts[key]["origin_m"]
|
||||
origin = np.array(
|
||||
transform.Transform(Gf.Vec3d(local[0], local[1], local[2] - self.contact_height))
|
||||
)
|
||||
origins.append(origin)
|
||||
observed, clear, depth, paths = mounted_range_returns(
|
||||
self.query, origin, rays @ rotation, key, self.mounts[key], self.rs_rays[:, 0],
|
||||
organized_ranges=view_ranges,
|
||||
)
|
||||
points.extend(observed)
|
||||
ends.extend(clear)
|
||||
indices.extend([index] * len(clear))
|
||||
self.source_counts[key] = len(observed)
|
||||
for path in paths:
|
||||
self.hit_paths[path] = self.hit_paths.get(path, 0) + 1
|
||||
if key == "realsense":
|
||||
self.depth = depth
|
||||
self.depth = self.depth.reshape(self.rs_size)
|
||||
self.rays = {
|
||||
"origins": np.asarray(origins, np.float32),
|
||||
"origin_indices": np.asarray(indices, np.int32),
|
||||
"ends": np.asarray(ends, np.float32).reshape(-1, 3),
|
||||
"view_models": np.asarray([0, 1], np.int32),
|
||||
"view_sizes": np.asarray([[120, 21], list(reversed(self.rs_size))], np.int32),
|
||||
"view_axes": rotation.T @ self.view_axes,
|
||||
"view_parameters": self.view_parameters,
|
||||
"view_ranges": np.concatenate(view_ranges),
|
||||
}
|
||||
return np.asarray(points, np.float32).reshape(-1, 3)
|
||||
|
||||
|
||||
def mounted_range_returns(query, origin, directions, key, spec, forward, *, organized_ranges=None):
|
||||
"""Same first-hit rays, with range filtering outside the Python query loop.
|
||||
|
||||
Keep per-beam ownership and order. A self hit never becomes a no-return
|
||||
clearing ray; an invalid D455 depth remains unknown. Only the native query
|
||||
itself is scalar, avoiding thousands of tiny NumPy allocations per frame.
|
||||
"""
|
||||
count = len(directions)
|
||||
maximum = np.full(count, 8.0) if key == "k1" else np.minimum(8.0, 6.0 / forward)
|
||||
mount = tuple(origin)
|
||||
positions = np.full((count, 3), np.nan)
|
||||
no_hit = np.zeros(count, dtype=bool)
|
||||
paths = [None] * count
|
||||
for row, (direction, limit) in enumerate(
|
||||
zip(directions.tolist(), maximum.tolist(), strict=True)
|
||||
):
|
||||
hit = query.raycast_closest(mount, tuple(direction), limit, bothSides=True)
|
||||
if not hit["hit"]:
|
||||
no_hit[row] = True
|
||||
elif not (
|
||||
str(hit.get("rigidBody", "")).startswith("/World/Rover")
|
||||
or str(hit.get("collision", "")).startswith("/World/Rover")
|
||||
):
|
||||
positions[row] = hit["position"]
|
||||
paths[row] = str(hit.get("collision", ""))
|
||||
distances = np.linalg.norm(positions - origin, axis=1)
|
||||
depth = np.full(count, np.nan, np.float32)
|
||||
if key == "k1":
|
||||
valid = np.isfinite(distances) & (distances >= spec["range_m"][0])
|
||||
positions[no_hit] = origin + directions[no_hit] * maximum[no_hit, None]
|
||||
clear = valid | no_hit
|
||||
else:
|
||||
z = distances * forward
|
||||
low, high = spec["depth_z_range_m"]
|
||||
valid = np.isfinite(z) & (z >= low) & (z <= high)
|
||||
depth[valid] = z[valid]
|
||||
clear = valid
|
||||
if organized_ranges is not None:
|
||||
# Zero is unknown, including every self hit and invalid stereo depth.
|
||||
# Only the lidar's declared no-hit range is a free-space observation.
|
||||
ranges = np.where(valid, distances, 0.0)
|
||||
if key == "k1":
|
||||
ranges[no_hit] = maximum[no_hit]
|
||||
organized_ranges.append(ranges.astype(np.float32))
|
||||
return positions[valid], positions[clear], depth, [paths[i] for i in np.flatnonzero(valid)]
|
||||
Reference in New Issue
Block a user