feat(sim): integrate Gazebo Classic with Point-LIO and SCAN navigation

Import the complete field and a simplified omnidirectional robot in sim_ws.
Reuse original Point-LIO, SCAN and controller implementations with isolated
simulation profiles, timed MID360/IMU data, readiness and command guards.
Support known-corridor terrain paths, optional sensor stress profiles and
separate physics/algorithm launch processes.

Remove retired Fortress resources and operating instructions; add build,
usage, scope and durable validation documentation.

Validation: full build script; 8 adapter tests and 4 SCAN CTest targets;
8 continuous mild-noise routes; red/blue terrain 4 cases each; noise 9/9;
visibility characterization 9/9; default sensors 16/16; loss-stop and
post-build straight navigation. Real wheels/network remain unverified.
This commit is contained in:
2026-11-08 19:04:32 +08:00
parent b6f84ac118
commit 664eaa81e5
83 changed files with 16948 additions and 12 deletions
+306
View File
@@ -0,0 +1,306 @@
#!/usr/bin/python3
"""Run existing SCAN/controller against Gazebo truth, never publish drive commands.
PASS requires a new goal to be acknowledged, ACTIVE and SUCCEEDED, physical
arrival, and a full second stopped at the goal. Save every independent truth
sample and observed command. A static test obstacle does not modify the map.
"""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import signal
import sys
import time
import numpy as np
import rclpy
from gazebo_msgs.srv import SpawnEntity
from geometry_msgs.msg import PoseStamped, Twist
from rclpy.qos import QoSProfile, DurabilityPolicy, qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2
from scan_planner_msgs.msg import TrajectoryStatus
from std_msgs.msg import Bool
from check_omni_robot import Probe, Sim, sim_env
from check_sim_lidar import points
class NavProbe(Probe):
def __init__(self, map_diagnostics=True):
super().__init__()
self.goal_pub = self.create_publisher(PoseStamped, '/move_base_simple/goal', 10)
self.status = []
self.commands = []
self.ready = False
self.clouds = {}
topics = ['/cloud_registered_for_scan']
if map_diagnostics:
topics.extend(('/grid_map/occupancy', '/grid_map/occupancy_inflate'))
for topic in topics:
self.create_subscription(PointCloud2, topic,
lambda m, topic=topic: self.clouds.update({topic: m}), qos_profile_sensor_data)
self.create_subscription(TrajectoryStatus, '/planning/trajectory_status',
self.status.append,
QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(Twist, '/cmd_vel', self.on_cmd, 100)
self.create_subscription(Bool, '/planning/perception_ready',
lambda m: setattr(self, 'ready', m.data),
QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.spawn = self.create_client(SpawnEntity, '/spawn_entity')
def on_cmd(self, m):
self.commands.append(dict(t=self.now(), vx=m.linear.x, vy=m.linear.y, wz=m.angular.z))
def add_obstacle(self):
req = SpawnEntity.Request()
req.name = 'p4_test_box'
req.reference_frame = 'world'
req.initial_pose.position.x = -4.6
req.initial_pose.position.y = 3.0
req.initial_pose.position.z = .3
req.initial_pose.orientation.w = 1.
req.xml = '''<sdf version="1.6"><model name="p4_test_box"><static>true</static>
<link name="box"><collision name="collision"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></collision>
<visual name="visual"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></visual></link></model></sdf>'''
res = self._call(self.spawn, req, timeout=15)
if not res or not res.success:
raise RuntimeError('test obstacle spawn failed: %s' % res)
return req.xml
def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settle_timeout=0., sample_hook=None):
first = p.get_state()
old_id = p.status[-1].goal_id if p.status else 0
start_cmd = len(p.commands)
start_status = len(p.status)
m = PoseStamped()
m.header.frame_id = 'world'
m.header.stamp = p.get_clock().now().to_msg()
m.pose.position.x, m.pose.position.y, m.pose.position.z = x, y, first['pos'][2] if goal_z is None else goal_z
m.pose.orientation.z, m.pose.orientation.w = math.sin(yaw/2), math.cos(yaw/2)
p.goal_pub.publish(m)
t0, wall_end = p.now(), time.monotonic()+300
samples = []
while p.now()-t0 < timeout and time.monotonic() < wall_end:
p.pump(.1)
truth = p.get_state()
if truth is None:
raise RuntimeError('missing independent Gazebo truth')
samples.append(truth)
if sample_hook is not None:
sample_hook(truth)
s = p.status[-1] if p.status else None
if s is not None and s.goal_id > old_id and s.state in (s.SUCCEEDED, s.FAILED):
break
# The optional force-drive protocol measures braking explicitly, then starts
# the full stopped window. Legacy instantaneous-drive protocol is unchanged.
braking=[];settle_latency=None;terminal_observed_time=p.now()
terminal_status=p.status[-1] if p.status else None
terminal_time=terminal_observed_time
if terminal_status is not None and terminal_status.goal_id>old_id and terminal_status.state in (terminal_status.SUCCEEDED,terminal_status.FAILED):
terminal_time=terminal_status.header.stamp.sec+terminal_status.header.stamp.nanosec*1e-9
if settle_timeout>0:
while p.now()-terminal_time<settle_timeout:
p.pump(.005);state=p.get_state()
if state is None:raise RuntimeError('truth missing during braking')
braking.append(state)
if math.hypot(*state['twist_world'][:2])<.01 and abs(state['wz'])<.02:
settle_latency=state['stamp']-terminal_time;break
# Observe the post-arrival behavior; do not inject a stop to make this pass.
stop_start = p.now()
stopped_samples = []
while p.now()-stop_start < 1.1:
p.pump(.1)
stopped_samples.append(p.get_state())
final = stopped_samples[-1]
statuses = p.status[start_status:]
cmds = p.commands[start_cmd:]
err = math.hypot(final['pos'][0]-x, final['pos'][1]-y)
yaw_err = abs(math.atan2(math.sin(final['yaw']-yaw), math.cos(final['yaw']-yaw)))
speed = max(math.hypot(*s['twist_world'][:2]) for s in stopped_samples)
drift = max(math.hypot(s['pos'][0]-final['pos'][0], s['pos'][1]-final['pos'][1])
for s in stopped_samples)
checks = dict(acknowledged=any(s.goal_id > old_id for s in statuses),
active=any(s.goal_id > old_id and s.state == s.ACTIVE for s in statuses),
succeeded=bool(statuses and statuses[-1].goal_id > old_id and
statuses[-1].state == statuses[-1].SUCCEEDED),
arrival=err < .10, yaw=yaw_err < .10,
stopped=speed < .01 and drift < .02,
commands_observed=len(cmds) > 10,
moved=math.hypot(final['pos'][0]-first['pos'][0],
final['pos'][1]-first['pos'][1]) > .3)
if name == 'lateral':
checks['lateral_command'] = any(abs(c['vy']) > .05 for c in cmds)
if settle_timeout>0:
checks['bounded_braking']=settle_latency is not None and 0<=settle_latency<=settle_timeout
checks['stopped_rotation']=all(abs(s['wz'])<.02 for s in stopped_samples)
if obstacle:
# Square footprint at heading pi/2; use its enclosing AABB, including yaw drift.
clearances = []
for s in samples:
extent = .4*(abs(math.cos(s['yaw']))+abs(math.sin(s['yaw'])))
clearances.append(max(abs(s['pos'][0]+4.6)-.125-extent,
abs(s['pos'][1]-3.)-.125-extent))
checks['physical_clearance'] = min(clearances) > .015
checks['detoured'] = max(s['pos'][0] for s in samples) > -3.95
else:
clearances = []
cloud_diagnostics = {}
for topic, msg in p.clouds.items():
pc = points(msg)
pc = pc[np.isfinite(pc).all(axis=1)]
near = pc[(np.abs(pc[:, 0]-x) < .6) & (np.abs(pc[:, 1]-y) < .6) & (pc[:, 2] < .4)]
cloud_diagnostics[topic] = dict(total=len(pc), near_goal=near.tolist())
return dict(name=name, goal=[x, y, yaw], checks=checks, ok=all(checks.values()),
cloud_diagnostics=cloud_diagnostics,
position_error_m=err, yaw_error_rad=yaw_err, stopped_max_speed_m_s=speed,
stopped_drift_m=drift, duration_sim_s=p.now()-t0,
settle_latency_sim_s=settle_latency,braking_samples=braking,
terminal_source_stamp=terminal_time,terminal_observed_stamp=terminal_observed_time,
min_obstacle_clearance_m=min(clearances) if clearances else None,
samples=samples, stop_samples=stopped_samples, commands=cmds,
statuses=[dict(t=s.header.stamp.sec+s.header.stamp.nanosec*1e-9,
goal_id=s.goal_id, state=s.state, reason=s.reason,
traj_id=s.traj_id, is_final=s.is_final,
goal=[s.goal.x, s.goal.y, s.goal.z]) for s in statuses])
def run_data_loss(p, sim):
"""Suspend only our adapter while the real controller is moving; no injected stop."""
m = PoseStamped()
m.header.frame_id = 'world'
m.header.stamp = p.get_clock().now().to_msg()
m.pose.position.x, m.pose.position.y = -3.6, 4.5
m.pose.orientation.w = 1.
p.goal_pub.publish(m)
deadline = time.monotonic()+60
while time.monotonic() < deadline:
p.pump(.05)
truth = p.get_state()
if truth and math.hypot(*truth['twist_world'][:2]) > .1:
break
else:
raise RuntimeError('data-loss test never reached moving state')
owned = []
for pid in sim.known:
try:
if b'/sim_data_adapter.py' in Path('/proc/%d/cmdline' % pid).read_bytes():
owned.append(pid)
except FileNotFoundError:
pass
if len(owned) != 1:
raise RuntimeError('cannot identify exactly one owned adapter: %r' % owned)
pid = owned[0]
samples, ready = [], []
t0 = p.now()
try:
os.kill(pid, signal.SIGSTOP)
while p.now()-t0 < 1.3:
p.pump(.05)
state = p.get_state()
if state is None:
raise RuntimeError('independent truth missing during data loss')
samples.append(state)
ready.append(dict(t=p.now(), ready=p.ready))
finally:
os.kill(pid, signal.SIGCONT)
stop = next((s['stamp']-t0 for s in samples
if math.hypot(*s['twist_world'][:2]) < .01 and abs(s['wz']) < .02), None)
late = [s for s in samples if s['stamp']-t0 >= .7]
drift = max(math.hypot(s['pos'][0]-late[0]['pos'][0], s['pos'][1]-late[0]['pos'][1])
for s in late) if late else None
checks = dict(initially_moving=True, readiness_revoked=any(not s['ready'] for s in ready),
stopped_in_time=stop is not None and 0 <= stop <= .5,
stayed_stopped=bool(late) and all(math.hypot(*s['twist_world'][:2]) < .01
for s in late) and drift < .02)
return dict(name='data_loss_stop', checks=checks, ok=all(checks.values()),
owned_adapter_pid=pid, stop_latency_sim_s=stop, drift_m=drift,
samples=samples, readiness=ready)
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--out', required=True)
ap.add_argument('--no-map-diagnostics', action='store_true',
help='Skip dense visualization maps; keep physical arrival/stop criteria unchanged')
ap.add_argument('--settle-timeout', type=float, default=0.,
help='Explicit bounded braking window before the full stopped interval (0 preserves legacy protocol)')
group = ap.add_mutually_exclusive_group()
group.add_argument('--straight-only', action='store_true')
group.add_argument('--fault-only', action='store_true')
args = ap.parse_args()
if not math.isfinite(args.settle_timeout) or not 0<=args.settle_timeout<=.2:
ap.error('--settle-timeout must be between 0 and 0.20 simulation seconds')
out = Path(args.out).resolve()
out.mkdir(parents=True, exist_ok=True)
os.environ.update(sim_env())
sim, p = Sim(str(out/'sim')), None
source = Path(__file__).read_bytes()
(out/'collector_snapshot.py').write_bytes(source)
report = dict(status='INVALID', cases=[],
collector_sha256_at_start=hashlib.sha256(source).hexdigest(),
braking_window_sim_s=args.settle_timeout, map_diagnostics=not args.no_map_diagnostics)
try:
ok, why = sim.start(navigation=True)
report['sim_start'] = why
if not ok:
raise RuntimeError(why)
rclpy.init()
p = NavProbe(map_diagnostics=not args.no_map_diagnostics)
if not p.wait_clock():
raise RuntimeError('no simulation clock')
end = time.monotonic()+90
while time.monotonic() < end:
rclpy.spin_once(p, timeout_sec=.02)
if p.ready and p.status and p.goal_pub.get_subscription_count() >= 2:
break
else:
raise RuntimeError('navigation not ready')
p.pump(1.)
if args.fault_only:
result = run_data_loss(p, sim)
report['cases'].append(result)
print(result['name'], result['checks'], flush=True)
# Keep the 0.8 m footprint plus margin away from the stair edge at y=4.
goals = [('straight', -3.6, 4.5, 0.), ('lateral', -3.6, 3.5, 0.),
('return_and_turn', -4.5, 4.5, math.pi/2)]
if args.straight_only:
goals = goals[:1]
if args.fault_only:
goals = []
for name, x, y, yaw in goals:
result = run_goal(p, name, x, y, yaw, settle_timeout=args.settle_timeout)
report['cases'].append(result)
(out/(name+'.json')).write_text(json.dumps(result, indent=2)+'\n')
print(name, result['checks'], 'error', result['position_error_m'], flush=True)
if not result['ok']:
break
if not args.straight_only and not args.fault_only and all(c['ok'] for c in report['cases']) and len(report['cases']) == 3:
(out/'test_obstacle.sdf').write_text(p.add_obstacle())
p.pump(2.)
result = run_goal(p, 'detour', -4.5, 1.5, math.pi/2, obstacle=True, settle_timeout=args.settle_timeout)
report['cases'].append(result)
(out/'detour.json').write_text(json.dumps(result, indent=2)+'\n')
print('detour', result['checks'], 'error', result['position_error_m'], flush=True)
expected = 1 if args.straight_only or args.fault_only else 4
report['status'] = 'PASS' if len(report['cases']) == expected and all(
c['ok'] for c in report['cases']) else 'FAIL'
except Exception as exc:
report['error'] = repr(exc)
print(report['error'], flush=True)
finally:
if p is not None:
p.send(0., 0., 0.) # Teardown only, after all measurements have been saved.
p.destroy_node()
if rclpy.ok():
rclpy.shutdown()
report['teardown'] = sim.stop()
(out/'result.json').write_text(json.dumps(report, indent=2)+'\n')
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']]
if __name__ == '__main__':
sys.exit(main())