Checkpoint scripts
Run from the Isaac Sim root folder. The lesson checkpoint scripts support --headless --test and print PASS/FAIL. Run snippets through m4_run_snippet.py or Window > Script Editor. Capture helpers have their own usage instructions below.
cd ~/isaacsim # your Isaac Sim installation folder
./python.sh learning_resource/scripts/<script>.py --headless --test
capture_first_robot.py
Capture real Isaac Sim frames from the lesson 1.1 checkpoint scene.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | """Capture real Isaac Sim frames from the lesson 1.1 checkpoint scene. First save the checkpoint, then run this helper from the Isaac Sim installation: ./python.sh learning_resource/scripts/m1_build_simple_robot.py --headless --test --save learning_resource/output/simple_robot.usd ./python.sh learning_resource/scripts/capture_first_robot.py --stage learning_resource/output/simple_robot.usd --output-dir learning_resource/screenshots/first_robot The camera, lighting, and display colours are for readability. Geometry, joints, and drives are loaded unchanged. This records simulated motion, not GUI actions. """ import argparse import json from pathlib import Path parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--stage", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) args, _ = parser.parse_known_args() if not args.stage.is_file(): parser.error(f"Stage does not exist: {args.stage}") args.output_dir.mkdir(parents=True, exist_ok=True) from isaacsim import SimulationApp app = SimulationApp({"headless": True, "width": 1440, "height": 900, "renderer": "RealTimePathTracing", "multi_gpu": False}) try: import carb import numpy as np import omni.replicator.core as rep import omni.timeline import omni.usd from PIL import Image from pxr import Gf, UsdGeom, UsdLux if not omni.usd.get_context().open_stage(str(args.stage.resolve())): raise RuntimeError("Could not open checkpoint stage") for _ in range(20): app.update() stage = omni.usd.get_context().get_stage() body = stage.GetPrimAtPath("/World/SimpleRobot/Cube") if not body.IsValid(): raise RuntimeError("Expected the lesson 1.1 SimpleRobot checkpoint") xf = UsdGeom.Xformable(body) UsdGeom.Gprim(body).GetDisplayColorAttr().Set([Gf.Vec3f(0.12, 0.38, 0.65)]) for prim in stage.Traverse(): if prim.GetName().endswith("_Wheel"): UsdGeom.Gprim(prim).GetDisplayColorAttr().Set([Gf.Vec3f(0.16, 0.18, 0.22)]) dome = UsdLux.DomeLight.Define(stage, "/World/CaptureDome") dome.GetIntensityAttr().Set(300.0) sun = UsdLux.DistantLight.Define(stage, "/World/defaultLight/DistantLight") sun.GetIntensityAttr().Set(1200.0) sun.GetAngleAttr().Set(2.0) UsdGeom.Xformable(sun).ClearXformOpOrder() UsdGeom.Xformable(sun).AddRotateXYZOp().Set(Gf.Vec3f(-45, 25, 0)) settings = carb.settings.get_settings() settings.set("/rtx/post/tonemap/op", 4) settings.set("/rtx/post/tonemap/filmIso", 200.0) settings.set("/rtx/post/tonemap/enabled", True) camera = UsdGeom.Camera.Define(stage, "/World/CourseCamera") camera.CreateFocalLengthAttr(32.0) camera.CreateClippingRangeAttr(Gf.Vec2f(0.1, 100.0)) camera_op = UsdGeom.Xformable(camera).AddTransformOp() def aim(eye, target, up=(0, 0, 1)): camera_op.Set(Gf.Matrix4d().SetLookAt(Gf.Vec3d(*eye), Gf.Vec3d(*target), Gf.Vec3d(*up)).GetInverse()) aim((5.5, -7.0, 4.5), (0.5, 0, 0.3)) rep.orchestrator.set_capture_on_play(False) product = rep.create.render_product(str(camera.GetPath()), (1440, 900)) rgb = rep.AnnotatorRegistry.get_annotator("rgb") rgb.attach([product]) for _ in range(60): app.update() frames = [] def capture(name): rep.orchestrator.step(rt_subframes=16, delta_time=0.0, pause_timeline=True) pixels = np.asarray(rgb.get_data())[:, :, :3] if pixels.shape != (900, 1440, 3) or pixels.std() < 5 or not 10 < pixels.mean() < 220: raise RuntimeError(f"Invalid capture: shape={pixels.shape}, mean={pixels.mean()}, std={pixels.std()}") Image.fromarray(pixels).save(args.output_dir / name) frames.append({"file": name, "mean_rgb": round(float(pixels.mean()), 2), "std_rgb": round(float(pixels.std()), 2), "body_position": list(xf.ComputeLocalToWorldTransform(0).ExtractTranslation())}) timeline = omni.timeline.get_timeline_interface() capture("assembled.png") timeline.play() for _ in range(180): app.update() timeline.pause() end_time = timeline.get_current_time() capture("driving.png") x = xf.ComputeLocalToWorldTransform(0).ExtractTranslation()[0] if not 0.5 < x < 1.5: raise RuntimeError(f"Unexpected driven displacement: {x}") aim((x, 0, 7), (x, 0, 0), (1, 0, 0)) capture("wheel-layout.png") record = {"stage": str(args.stage), "frames": frames, "updates": 180, "timeline_seconds": end_time, "displacement_x_m": x, "presentation_changes": "Camera, lights, chassis/wheel display colours only; physics unchanged."} (args.output_dir / "capture.json").write_text(json.dumps(record, indent=2) + "\n") print(f"[capture] PASS: {len(frames)} frames, displacement={x:.3f} m, timeline={end_time:.3f} s") rgb.detach([product]) product.destroy() timeline.stop() finally: app.close() |
m1_build_simple_robot.py
Module 1 checkpoint: build the course's 4-wheeled "SimpleRobot" in Isaac Sim 6.1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | """Module 1 checkpoint: build the course's 4-wheeled "SimpleRobot" in Isaac Sim 6.1. This reproduces lessons 1.1 and 1.2 of "Building Your First Robot in Isaac Sim" using the same Kit commands the GUI menus call, so the result matches what you build by hand: - Physics Scene + Ground Plane - SimpleRobot (Xform) > Cube chassis (2 x 1 x 0.5 m) + 4 cylinder wheels (diameter 0.75 m) - Rigid Body with Colliders Preset on chassis and wheels - 4 revolute joints (axis Y, Local Rotation 1 = -90, 0, 0) - Angular drives on the rear joints (damping 10000, target velocity 50 deg/s) - Articulation Root on SimpleRobot (needed by the Differential Controller in lesson 1.2) Usage (from the Isaac Sim root folder): ./python.sh learning_resource/scripts/m1_build_simple_robot.py # GUI, keeps running ./python.sh learning_resource/scripts/m1_build_simple_robot.py --headless --test ./python.sh learning_resource/scripts/m1_build_simple_robot.py --save learning_resource/output/simple_robot.usd """ import argparse import os parser = argparse.ArgumentParser() parser.add_argument("--headless", action="store_true", help="Run without a window") parser.add_argument("--test", action="store_true", help="Simulate ~3 s, check the robot drove forward, then exit") parser.add_argument("--save", default=None, help="Save the built stage to this .usd path") args, _ = parser.parse_known_args() from isaacsim import SimulationApp simulation_app = SimulationApp({"headless": args.headless}) import omni.kit.commands import omni.timeline import omni.usd from omni.physx.scripts import utils as physx_utils from pxr import Gf, PhysxSchema, UsdGeom, UsdPhysics omni.usd.get_context().new_stage() simulation_app.update() stage = omni.usd.get_context().get_stage() UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) UsdGeom.SetStageMetersPerUnit(stage, 1.0) def set_xform(path, translate=(0, 0, 0), rotate_xyz=(0, 0, 0), scale=(1, 1, 1)): """Set Translate / Orient / Scale, the same ops the Property > Transform panel edits. Rotation is given in XYZ euler degrees (what the panel shows) and stored as a quaternion. """ prim = stage.GetPrimAtPath(path) xf = UsdGeom.Xformable(prim) xf.ClearXformOpOrder() rot = ( Gf.Rotation(Gf.Vec3d(1, 0, 0), rotate_xyz[0]) * Gf.Rotation(Gf.Vec3d(0, 1, 0), rotate_xyz[1]) * Gf.Rotation(Gf.Vec3d(0, 0, 1), rotate_xyz[2]) ) xf.AddTranslateOp(UsdGeom.XformOp.PrecisionDouble).Set(Gf.Vec3d(*translate)) xf.AddOrientOp(UsdGeom.XformOp.PrecisionDouble).Set(Gf.Quatd(rot.GetQuat())) xf.AddScaleOp(UsdGeom.XformOp.PrecisionDouble).Set(Gf.Vec3d(*scale)) def create_mesh(prim_type, path): """Same as Create > Mesh > <prim_type>.""" omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type=prim_type, prim_path=path) return stage.GetPrimAtPath(path) # --- Lesson 1.1 Part 2: physics scene + ground plane -------------------------------------------- UsdPhysics.Scene.Define(stage, "/World/PhysicsScene") # Create > Physics > Physics Scene omni.kit.commands.execute( # Create > Physics > Ground Plane "AddGroundPlaneCommand", stage=stage, planePath="/World/GroundPlane", axis="Z", size=25.0, position=Gf.Vec3f(0.0), color=Gf.Vec3f(0.5), ) UsdGeom.Xform.Define(stage, "/World/defaultLight") omni.kit.commands.execute("CreatePrim", prim_type="DistantLight", prim_path="/World/defaultLight/DistantLight") # --- Lesson 1.1 Part 3: chassis + hierarchy ----------------------------------------------------- WHEEL_RADIUS = 0.375 # cylinder mesh is 1 m tall / 1 m diameter -> scale 0.75 gives 0.75 m diameter UsdGeom.Xform.Define(stage, "/World/SimpleRobot") set_xform("/World/SimpleRobot", translate=(0, 0, WHEEL_RADIUS)) # wheels rest on the ground chassis = create_mesh("Cube", "/World/SimpleRobot/Cube") set_xform(chassis.GetPath(), scale=(2, 1, 0.5)) # --- Lesson 1.1 Part 4: wheels ------------------------------------------------------------------ wheels = { "Front_Left_Wheel": (0.5, 0.75, 0), "Front_Right_Wheel": (0.5, -0.75, 0), "Rear_Left_Wheel": (-0.5, 0.75, 0), "Rear_Right_Wheel": (-0.5, -0.75, 0), } for name, pos in wheels.items(): create_mesh("Cylinder", f"/World/SimpleRobot/{name}") set_xform(f"/World/SimpleRobot/{name}", translate=pos, rotate_xyz=(90, 0, 0), scale=(0.75, 0.75, 0.25)) # Right-click > Add > Physics > Rigid Body with Colliders Preset for path in ["/World/SimpleRobot/Cube"] + [f"/World/SimpleRobot/{n}" for n in wheels]: physx_utils.setRigidBody(stage.GetPrimAtPath(path), "convexHull", False) # --- Lesson 1.1 Part 5: revolute joints (select Cube first, then the wheel) --------------------- local_rot1 = Gf.Rotation(Gf.Vec3d(1, 0, 0), -90).GetQuat() # Local Rotation 1 = (-90, 0, 0) joints = {} for name in wheels: joint_name = name.replace("_Wheel", "_Joint") joint = physx_utils.createJoint(stage, "Revolute", chassis, stage.GetPrimAtPath(f"/World/SimpleRobot/{name}")) new_path = f"/World/SimpleRobot/{joint_name}" omni.kit.commands.execute("MovePrim", path_from=str(joint.GetPath()), path_to=new_path) joint = UsdPhysics.RevoluteJoint.Get(stage, new_path) joint.GetAxisAttr().Set("Y") joint.GetLocalRot0Attr().Set(Gf.Quatf(1, 0, 0, 0)) joint.GetLocalRot1Attr().Set(Gf.Quatf(local_rot1)) joints[joint_name] = joint.GetPrim() # --- Lesson 1.1 Part 6: angular drive on the rear wheels ---------------------------------------- for joint_name in ["Rear_Left_Joint", "Rear_Right_Joint"]: drive = UsdPhysics.DriveAPI.Apply(joints[joint_name], "angular") # Add > Physics > Angular Drive drive.CreateDampingAttr(10000.0) drive.CreateStiffnessAttr(0.0) drive.CreateTargetVelocityAttr(50.0) # deg/s # --- Lesson 1.2 Part 1: articulation root (required by the Differential Controller) ------------- robot_prim = stage.GetPrimAtPath("/World/SimpleRobot") UsdPhysics.ArticulationRootAPI.Apply(robot_prim) PhysxSchema.PhysxArticulationAPI.Apply(robot_prim) if args.save: os.makedirs(os.path.dirname(os.path.abspath(args.save)), exist_ok=True) omni.usd.get_context().save_as_stage(os.path.abspath(args.save)) print(f"[m1] saved stage to {os.path.abspath(args.save)}") # --- Run ---------------------------------------------------------------------------------------- timeline = omni.timeline.get_timeline_interface() timeline.play() stage = omni.usd.get_context().get_stage() # re-fetch: save_as_stage can swap the stage handle chassis_xf = UsdGeom.Xformable(stage.GetPrimAtPath("/World/SimpleRobot/Cube")) if args.test: for _ in range(180): # ~3 s at 60 Hz simulation_app.update() x = chassis_xf.ComputeLocalToWorldTransform(0).ExtractTranslation()[0] print(f"[m1] chassis x after 3 s = {x:.3f} m") timeline.stop() print("[m1] PASS: robot drove forward" if x > 0.1 else "[m1] FAIL: robot did not drive forward") simulation_app.close() else: while simulation_app.is_running(): simulation_app.update() simulation_app.close() |
m1_ros2_lidar.py
Module 1.3/1.4 checkpoint: 2D lidar on SimpleRobot -> ROS 2 LaserScan -> RViz (Isaac Sim 6.1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | """Module 1.3/1.4 checkpoint: 2D lidar on SimpleRobot -> ROS 2 LaserScan -> RViz (Isaac Sim 6.1). The course adds a *PhysX* rotating lidar and wires "Isaac Read Lidar Beams -> ROS2 Publish Laser Scan". In 6.1 the PhysX lidar is deprecated (extsDeprecated/isaacsim.sensors.physx), so this uses the replacement: an *RTX* lidar with the 2D config "Example_Rotary_2D", published through the same graph that Tools > Robotics > ROS 2 OmniGraphs > RTX Lidar builds. Expected: ~10 LaserScan msgs/s on /scan_lidar, frame sim_lidar, 3600 beams, and a forward beam of 2.50 m to an obstacle placed 2.50 m ahead. Prerequisite: learning_resource/output/simple_robot.usd (run m1_build_simple_robot.py --save ... first, or save your own robot there). Usage (from the Isaac Sim root folder): ./python.sh learning_resource/scripts/m1_ros2_lidar.py then: ros2 topic echo /scan_lidar --once / rviz2 (Fixed Frame = sim_lidar, Add > By topic > /scan_lidar) ./python.sh learning_resource/scripts/m1_ros2_lidar.py --headless --test """ import argparse import os HERE = os.path.dirname(os.path.abspath(__file__)) parser = argparse.ArgumentParser() parser.add_argument("--headless", action="store_true") parser.add_argument("--test", action="store_true", help="Subscribe to /scan_lidar and check the obstacle is seen") parser.add_argument("--usd", default=os.path.join(os.path.dirname(HERE), "output", "simple_robot.usd")) args, _ = parser.parse_known_args() from isaacsim import SimulationApp simulation_app = SimulationApp({"headless": args.headless, "enable_motion_bvh": True}) # RTX lidar needs motion BVH import omni.kit.app omni.kit.app.get_app().get_extension_manager().set_extension_enabled_immediate("isaacsim.ros2.bridge", True) simulation_app.update() # let the ROS 2 bridge finish starting before touching the stage import omni.kit.commands import omni.timeline import omni.usd from isaacsim.ros2.nodes import Ros2RtxLidarGraphConfig, create_ros2_rtx_lidar_graph from isaacsim.sensors.experimental.rtx import Lidar from omni.physx.scripts import utils as physx_utils from pxr import Gf, UsdGeom, UsdPhysics omni.usd.get_context().open_stage(args.usd) simulation_app.update() stage = omni.usd.get_context().get_stage() # Stop the rear-wheel drives from lesson 1.1 so the robot stands still for the scan check for joint in ["Rear_Left_Joint", "Rear_Right_Joint"]: UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath(f"/World/SimpleRobot/{joint}"), "angular").GetTargetVelocityAttr().Set(0.0) # --- Lesson 1.3 (6.1 version): lidar on the chassis body ----------------------------------------- # The course mounts the lidar on Front_Sensor, its own rigid body fixed to the chassis with a Fixed Joint. # On this 6.1 build an RTX lidar under such a fixed-jointed link published NOTHING (also under a # scale-compensating Xform), while a lidar directly under the chassis body works - which is also how # Nova Carter mounts its sensors. So: select Cube > Create > Sensors > RTX Lidar > NVIDIA > Example Rotary 2D. # Its Translate is in Cube-local units (Cube is scaled 2 x 1 x 0.5): (0.45, 0, 1.0) = 0.9 m forward and # 0.5 m above the chassis centre, i.e. above the wheel tops so the scan doesn't hit the robot itself. lidar = Lidar.create( path="/World/SimpleRobot/Cube/Lidar", config="Example_Rotary_2D", tick_rate=10.0, translations=[[0.45, 0.0, 1.0]] ) lidar_path = lidar.paths[0] # An obstacle whose front face is 2.5 m in front of the lidar (lesson: add cubes/cones, Rigid Body with Colliders Preset) omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type="Cube", prim_path="/World/Obstacle") # Create > Mesh prims carry translate/orient/scale ops; set the translate op directly (XformCommonAPI # silently refuses prims that have an orient op). stage.GetPrimAtPath("/World/Obstacle").GetAttribute("xformOp:translate").Set(Gf.Vec3d(3.9, 0.0, 0.5)) physx_utils.setRigidBody(stage.GetPrimAtPath("/World/Obstacle"), "convexHull", False) # --- Lesson 1.4: Tools > Robotics > ROS 2 OmniGraphs > RTX Lidar (Laser Scan ticked) ------------ graph_path = create_ros2_rtx_lidar_graph( Ros2RtxLidarGraphConfig( graph_path="/World/ROS2_LidarStream", lidar_prim=lidar_path, frame_id="sim_lidar", publish_laser_scan=True, laser_scan_topic="scan_lidar", ) ) print(f"[m1] ROS 2 lidar graph: {graph_path} lidar: {lidar_path}") timeline = omni.timeline.get_timeline_interface() timeline.play() if args.test: import rclpy from rclpy.qos import qos_profile_sensor_data from sensor_msgs.msg import LaserScan rclpy.init() node = rclpy.create_node("m1_scan_check") scans = [] node.create_subscription(LaserScan, "scan_lidar", lambda m: scans.append(m), qos_profile_sensor_data) import time t0, frames = time.time(), 0 while (len(scans) < 3 or frames < 180) and frames < 1500: # RTX sensors can take a while to warm up on the first run simulation_app.update() rclpy.spin_once(node, timeout_sec=0.0) frames += 1 print(f"[m1] waited {frames} frames / {time.time() - t0:.1f} s") from isaacsim.core.experimental.prims import RigidPrim pos, _ = RigidPrim("/World/SimpleRobot/Cube").get_world_poses() print(f"[m1] chassis world position: {pos.numpy()[0].round(3)}") if scans: m = scans[-1] valid = [r for r in m.ranges if m.range_min < r < m.range_max] closest = min(valid) if valid else float("nan") import math def beam(angle_deg): i = int(round((math.radians(angle_deg) - m.angle_min) / m.angle_increment)) % len(m.ranges) return m.ranges[i] i_min = min(range(len(m.ranges)), key=lambda i: m.ranges[i] if m.range_min < m.ranges[i] < m.range_max else 1e9) print(f"[m1] forward beam = {beam(0):.2f} m (obstacle face expected at 2.50 m), " f"closest return at {math.degrees(m.angle_min + i_min * m.angle_increment):.0f} deg") print(f"[m1] got {len(scans)} LaserScan msgs, frame={m.header.frame_id}, {len(m.ranges)} beams, closest={closest:.2f} m") ok = m.header.frame_id == "sim_lidar" and abs(beam(0) - 2.5) < 0.1 and closest > 2.0 print("[m1] PASS: /scan_lidar sees the obstacle" if ok else "[m1] FAIL: unexpected scan") else: print(f"[m1] FAIL: no LaserScan received on /scan_lidar; topics seen: {node.get_topic_names_and_types()}") node.destroy_node() rclpy.shutdown() timeline.stop() simulation_app.close() else: print("[m1] Playing. Try: ros2 topic echo /scan_lidar --once or rviz2 (Fixed Frame: sim_lidar)") while simulation_app.is_running(): simulation_app.update() simulation_app.close() |
m2_import_carter.py
Module 2 checkpoint: import the Carter URDF and drive it with a Differential Controller (Isaac Sim 6.1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | """Module 2 checkpoint: import the Carter URDF and drive it with a Differential Controller (Isaac Sim 6.1). Reproduces lessons 2.1 + 2.2 of "Ingesting Robot Assets and Simulating Your Robot in Isaac Sim" with the 6.1 URDF importer: 1. Convert learning_resource/assets/carter/urdf/carter.urdf -> learning_resource/output/carter/carter.usda (Base Type = Mobile, like the course's "moveable base"). 2. New stage + Flat Grid environment (falls back to a plain ground plane if the asset server is offline). 3. Reference the robot at /World/carter, select the "physx" Physics variant (new in 6.x). 4. Configure drives (the 6.1 importer dialog no longer has a "Joints and Drives" section): left_wheel / right_wheel -> velocity drive (stiffness 0, damping 10000) rear_pivot / rear_axle -> passive (stiffness 0, damping 0) 5. Build the same Action Graph that Tools > Robotics > OmniGraph Controllers > Differential Controller makes (without keyboard nodes): OnPlaybackTick -> DifferentialController -> ArticulationController. Usage (from the Isaac Sim root folder): ./python.sh learning_resource/scripts/m2_import_carter.py ./python.sh learning_resource/scripts/m2_import_carter.py --headless --test """ import argparse import os HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) parser = argparse.ArgumentParser() parser.add_argument("--headless", action="store_true") parser.add_argument("--test", action="store_true", help="Drive forward ~3 s, check motion, then exit") parser.add_argument("--linear", type=float, default=0.2, help="Desired linear velocity (m/s)") parser.add_argument("--angular", type=float, default=0.0, help="Desired angular velocity (rad/s)") args, _ = parser.parse_known_args() from isaacsim import SimulationApp simulation_app = SimulationApp({"headless": args.headless}) import omni.kit.app ext_manager = omni.kit.app.get_app().get_extension_manager() for ext in ["omni.scene.optimizer.core", "isaacsim.robot.schema", "isaacsim.robot.wheeled_robots.nodes"]: ext_manager.set_extension_enabled_immediate(ext, True) import omni.graph.core as og import omni.kit.commands import omni.timeline import omni.usd from isaacsim.asset.importer.urdf.impl import URDFImporter, URDFImporterConfig from isaacsim.storage.native import get_assets_root_path from pxr import Gf, UsdGeom, UsdPhysics # --- 1. URDF -> USD -------------------------------------------------------------------------- # The Carter URDF ships with Isaac Sim; copy it next to the course files on first use (lesson 2.1). carter_dir = os.path.join(ROOT, "assets", "carter") if not os.path.isfile(os.path.join(carter_dir, "urdf", "carter.urdf")): import shutil src = os.path.join(os.path.dirname(ROOT), "exts", "isaacsim.asset.importer.urdf", "data", "urdf", "robots", "carter") shutil.copytree(src, carter_dir, dirs_exist_ok=True) print(f"[m2] copied Carter URDF from {src}") config = URDFImporterConfig( urdf_path=os.path.join(carter_dir, "urdf", "carter.urdf"), usd_path=os.path.join(ROOT, "output"), fix_base=False, # GUI: Options > Base Type = Mobile ) carter_usd = URDFImporter(config).import_urdf() print(f"[m2] converted URDF -> {carter_usd}") # --- 2. Scene ---------------------------------------------------------------------------------- omni.usd.get_context().new_stage() simulation_app.update() stage = omni.usd.get_context().get_stage() UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) UsdGeom.SetStageMetersPerUnit(stage, 1.0) UsdPhysics.Scene.Define(stage, "/World/PhysicsScene") assets_root = get_assets_root_path() if assets_root: # Create > Environments > Flat Grid grid = stage.DefinePrim("/World/FlatGrid", "Xform") grid.GetReferences().AddReference(assets_root + "/Isaac/Environments/Grid/default_environment.usd") print(f"[m2] Flat Grid from {assets_root}") else: omni.kit.commands.execute( "AddGroundPlaneCommand", stage=stage, planePath="/World/GroundPlane", axis="Z", size=25.0, position=Gf.Vec3f(0.0), color=Gf.Vec3f(0.5), ) print("[m2] asset server unreachable -> plain ground plane") # --- 3. Reference the robot + pick the physics variant ---------------------------------------- robot = stage.DefinePrim("/World/carter", "Xform") robot.GetReferences().AddReference(carter_usd) robot.GetVariantSet("Physics").SetVariantSelection("physx") # Property > Variants > Physics robot_xf = UsdGeom.Xformable(robot) # lift slightly off the floor (the asset root may already carry xform ops) translate_op = next((op for op in robot_xf.GetOrderedXformOps() if op.GetOpType() == UsdGeom.XformOp.TypeTranslate), None) (translate_op or robot_xf.AddTranslateOp(UsdGeom.XformOp.PrecisionDouble)).Set(Gf.Vec3d(0, 0, 0.05)) simulation_app.update() # --- 4. Drives --------------------------------------------------------------------------------- for name, damping in [("left_wheel", 10000.0), ("right_wheel", 10000.0), ("rear_pivot", 0.0), ("rear_axle", 0.0)]: drive = UsdPhysics.DriveAPI.Apply(stage.GetPrimAtPath(f"/World/carter/Physics/{name}"), "angular") drive.CreateStiffnessAttr().Set(0.0) drive.CreateDampingAttr().Set(damping) # --- 5. Differential controller graph --------------------------------------------------------- # Wheel radius 0.24 m (collision cylinder), wheel distance 2 x 0.3142 m (joint localPos0 Y offset). og.Controller.edit( {"graph_path": "/World/Graphs/differential_controller", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("DifferentialController", "isaacsim.robot.wheeled_robots.DifferentialController"), ("ArticulationController", "isaacsim.core.nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("DifferentialController.inputs:wheelRadius", 0.24), ("DifferentialController.inputs:wheelDistance", 0.6284), ("DifferentialController.inputs:maxLinearSpeed", 0.5), ("DifferentialController.inputs:maxAngularSpeed", 1.0), ("DifferentialController.inputs:linearVelocity", args.linear), ("DifferentialController.inputs:angularVelocity", args.angular), ("ArticulationController.inputs:robotPath", "/World/carter"), ("ArticulationController.inputs:jointNames", ["left_wheel", "right_wheel"]), ], og.Controller.Keys.CONNECT: [ ("OnPlaybackTick.outputs:tick", "DifferentialController.inputs:execIn"), ("OnPlaybackTick.outputs:deltaSeconds", "DifferentialController.inputs:dt"), ("OnPlaybackTick.outputs:tick", "ArticulationController.inputs:execIn"), ("DifferentialController.outputs:velocityCommand", "ArticulationController.inputs:velocityCommand"), ], }, ) # --- Run --------------------------------------------------------------------------------------- timeline = omni.timeline.get_timeline_interface() timeline.play() chassis = UsdGeom.Xformable(stage.GetPrimAtPath("/World/carter/Geometry/chassis_link")) if args.test: for _ in range(180): simulation_app.update() pos = chassis.ComputeLocalToWorldTransform(0).ExtractTranslation() print(f"[m2] chassis position after 3 s = ({pos[0]:.3f}, {pos[1]:.3f}, {pos[2]:.3f})") timeline.stop() print("[m2] PASS: Carter drove forward" if pos[0] > 0.2 else "[m2] FAIL: Carter did not drive forward") simulation_app.close() else: while simulation_app.is_running(): simulation_app.update() simulation_app.close() |
m3_palletjack_sdg.py
Ported from NVIDIA-AI-IOT/synthetic_data_generation_training_workflow (palletjack_sdg/standalone_palletjack_sdg.py)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | # Ported from NVIDIA-AI-IOT/synthetic_data_generation_training_workflow (palletjack_sdg/standalone_palletjack_sdg.py) # SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: MIT # Modifications for Isaac Sim 6.1 (functional Replicator API, label handling) are described below. """Module 3: pallet-jack synthetic dataset with Replicator, ported to Isaac Sim 6.1. Port of the course's `standalone_palletjack_sdg.py` (github.com/NVIDIA-AI-IOT/synthetic_data_generation_training_workflow). Same scene, same randomizations, same KITTI output. What changed for 6.1: omni.isaac.kit.SimulationApp -> isaacsim.SimulationApp omni.isaac.core.utils.nucleus -> isaacsim.storage.native renderer "RayTracedLighting" -> "RealTimePathTracing" (6.x default) graph randomizers inside rep.trigger.on_frame() -> rep.functional.* calls in a Python loop, followed by + rep.orchestrator.run() rep.orchestrator.step() (the 6.1 SDG examples' pattern) pxr.Semantics "update_semantics()" -> block the referenced semantic attributes (RemoveProperty can't delete them), then keep only "palletjack" rows in the KITTI files Why not keep the graph randomizers? On this 6.1 build, (a) `rep.create.material_omnipbr` + `rep.randomizer.materials` inside the trigger hung for >10 min, and (b) graph randomizers fired only on the first `rep.orchestrator.step()`. The functional API has neither problem and is what the 6.1 examples use (standalone_examples/replicator/sdg_ur10_palletizing.py, .../isaacsim.replicator.examples/randomizing_textures.py). Usage (from the Isaac Sim root folder): ./python.sh learning_resource/scripts/m3_palletjack_sdg.py --num_frames 20 ./python.sh learning_resource/scripts/m3_palletjack_sdg.py --headless --num_frames 2000 --distractors warehouse ./python.sh learning_resource/scripts/m3_palletjack_sdg.py --headless --test # 5 frames + output check Output: learning_resource/output/palletjack_data/<distractors>/Camera/{rgb,object_detection,...} """ import argparse import os HERE = os.path.dirname(os.path.abspath(__file__)) parser = argparse.ArgumentParser("Dataset generator") parser.add_argument("--headless", action="store_true") parser.add_argument("--height", type=int, default=544) parser.add_argument("--width", type=int, default=960) parser.add_argument("--num_frames", type=int, default=20) parser.add_argument("--distractors", default="warehouse", choices=["warehouse", "None"]) parser.add_argument("--data_dir", default=None) parser.add_argument("--rt_subframes", type=int, default=4, help="Increase if moving objects leave ghosts") parser.add_argument("--seed", type=int, default=None) parser.add_argument("--test", action="store_true") args, _ = parser.parse_known_args() if args.test: args.num_frames = 5 # Replicator resolves relative paths under its own output root, while the checks # below use the process working directory. Give both the same absolute path. data_dir = os.path.abspath(args.data_dir or os.path.join(os.path.dirname(HERE), "output", "palletjack_data", args.distractors)) from isaacsim import SimulationApp simulation_app = SimulationApp( {"headless": args.headless, "renderer": "RealTimePathTracing", "width": args.width, "height": args.height} ) import numpy as np import omni.replicator.core as rep import omni.usd from isaacsim.core.experimental.utils import semantics as semantics_utils from isaacsim.storage.native import get_assets_root_path from pxr import UsdGeom, UsdLux ENV_URL = "/Isaac/Environments/Simple_Warehouse/warehouse.usd" SIMREADY = "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Equipment" PALLETJACKS = [ f"{SIMREADY}/Pallet_Trucks/Scale_A/PalletTruckScale_A01_PR_NVD_01.usd", f"{SIMREADY}/Pallet_Trucks/Heavy_Duty_A/HeavyDutyPalletTruck_A01_PR_NVD_01.usd", f"{SIMREADY}/Pallet_Trucks/Low_Profile_A/LowProfilePalletTruck_A01_PR_NVD_01.usd", ] DISTRACTORS_WAREHOUSE = [ "/Isaac/Environments/Simple_Warehouse/Props/" + name for name in [ "S_TrafficCone.usd", "S_WetFloorSign.usd", "SM_BarelPlastic_A_01.usd", "SM_BarelPlastic_B_01.usd", "SM_BottlePlasticA_02.usd", "SM_BucketPlastic_B.usd", "SM_CardBoxB_01_1262.usd", "SM_CardBoxD_01_1454.usd", "SM_CratePlastic_A_04.usd", "SM_CratePlastic_B_03.usd", "SM_PushcartA_02.usd", "SM_RackPile_04.usd", ] ] TEXTURES = [ "/Isaac/Materials/Textures/Patterns/" + name for name in [ "nv_asphalt_yellow_weathered.jpg", "nv_tile_hexagonal_green_white.jpg", "nv_rubber_woven_charcoal.jpg", "nv_granite_tile.jpg", "nv_marble.jpg", "nv_brick_reclaimed.jpg", "nv_concrete_aged_with_lines.jpg", "nv_wooden_wall.jpg", "nv_stone_painted_grey.jpg", "nv_carpet_abstract_pattern.jpg", ] ] assets_root = get_assets_root_path() if not assets_root: raise SystemExit("Isaac Sim asset server not reachable; check your network / asset root setting") gen = np.random.default_rng(args.seed) # --- Scene ------------------------------------------------------------------------------------- print(f"[m3] loading {assets_root + ENV_URL}") omni.usd.get_context().open_stage(assets_root + ENV_URL) for _ in range(100): # let the stage finish loading simulation_app.update() while omni.usd.get_context().get_stage_loading_status()[2] > 0: simulation_app.update() stage = omni.usd.get_context().get_stage() rep.orchestrator.set_capture_on_play(False) # Pallet jacks (2 of each) and distractors, under one scope rep.functional.create.scope(name="SDG") palletjacks = [ rep.functional.create.reference( usd_path=url, parent="/SDG", name=f"palletjack_{i}_{k}" ) for i, url in enumerate(PALLETJACKS) for k in range(2) ] distractors = [] if args.distractors == "warehouse": distractors = [ rep.functional.create.reference(usd_path=assets_root + d, parent="/SDG", name=f"distractor_{i}") for i, d in enumerate(DISTRACTORS_WAREHOUSE) ] cam = rep.functional.create.camera(parent="/SDG", name="Camera", clipping_range=(0.1, 1000000)) textures = [assets_root + t for t in TEXTURES] for _ in range(10): simulation_app.update() while omni.usd.get_context().get_stage_loading_status()[2] > 0: simulation_app.update() # The course's update_semantics(): only pallet jacks may carry labels. # The warehouse and props use legacy "SemanticsAPI:*" labels that come from *referenced* layers, and # prim.RemoveProperty() cannot delete those. So we block their values (USD's way to "delete" a referenced # opinion), drop the schema, remove any new-style UsdSemantics labels, and only then label the pallet jacks. n_stripped = 0 for prim in stage.Traverse(): semantics_utils.remove_all_labels(prim) legacy = [sch for sch in prim.GetAppliedSchemas() if sch.startswith("SemanticsAPI:")] for sch in legacy: prim.RemoveAppliedSchema(sch) for attr in prim.GetAttributes(): if attr.GetName().startswith("semantic:"): attr.Block() n_stripped += bool(legacy) for prim in palletjacks: rep.functional.modify.semantics(prim, {"class": "palletjack"}, mode="add") print(f"[m3] stripped labels from {n_stripped} prims, labelled {len(palletjacks)} pallet jacks") # Materials we randomize: one OmniPBR for the floor meshes, one for the walls, one per pallet-jack steer axle surfaces = {"SM_Floor": [], "SM_Wall": []} steer_axles = [] for prim in stage.Traverse(): name = prim.GetName() for key in surfaces: if key in name and prim.IsA(UsdGeom.Mesh): surfaces[key].append(prim) if "SteerAxles" in name and str(prim.GetPath()).startswith("/SDG/"): steer_axles.append(prim) rect_lights = [p for p in stage.Traverse() if p.IsA(UsdLux.RectLight)] surface_mats = dict(zip(surfaces, rep.functional.create_batch.material(mdl="OmniPBR.mdl", count=2, parent="/SDG"))) for key, prims in surfaces.items(): for prim in prims: rep.functional.modify.material(prim, surface_mats[key]) axle_mats = [] if steer_axles: axle_mats = rep.functional.create_batch.material(mdl="OmniPBR.mdl", count=len(steer_axles), parent="/SDG") for prim, mat in zip(steer_axles, axle_mats): rep.functional.modify.material(prim, mat) print( f"[m3] floor meshes: {len(surfaces['SM_Floor'])}, wall meshes: {len(surfaces['SM_Wall'])}, " f"steer axles: {len(steer_axles)}, rect lights: {len(rect_lights)}" ) def randomize(): """One frame of the course's domain randomization.""" # Camera somewhere in the warehouse, looking at its centre rep.functional.modify.pose( cam, position_value=tuple(gen.uniform((-9.2, -11.8, 0.4), (7.2, 15.8, 4))), look_at_value=(0, 0, 0) ) # Pallet jack body colour for mat in axle_mats: rep.functional.modify.attribute(mat, "inputs:diffuse_color_constant", tuple(gen.uniform(0, 1, 3))) # Pallet jack poses (the SimReady assets are authored in cm -> scale 0.01) for prim in palletjacks: rep.functional.modify.pose( prim, position_value=tuple(gen.uniform((-6, -6, 0), (6, 12, 0))), rotation_value=(0, 0, float(gen.uniform(0, 360))), scale_value=0.01, ) for prim in distractors: rep.functional.modify.pose( prim, position_value=tuple(gen.uniform((-6, -6, 0), (6, 12, 0))), rotation_value=(0, 0, float(gen.uniform(0, 360))), scale_value=float(gen.uniform(1, 1.5)), ) # Lights: random colour, intensity ~ N(1e5, 6e5) clipped at 0, on 1 time in 7 for light in rect_lights: rep.functional.modify.attribute(light, "inputs:color", tuple(gen.uniform(0, 1, 3))) rep.functional.modify.attribute(light, "inputs:intensity", max(0.0, float(gen.normal(100000.0, 600000.0)))) rep.functional.modify.visibility(light, bool(gen.integers(0, 7) == 0)) # Floor / wall textures for mat in surface_mats.values(): rep.functional.modify.attribute(mat, "inputs:diffuse_texture", str(gen.choice(textures))) rep.functional.modify.attribute(mat, "inputs:reflection_roughness_constant", float(gen.uniform(0, 1))) rep.functional.modify.attribute(mat, "inputs:metallic_constant", float(gen.choice([0, 1]))) rep.functional.modify.attribute(mat, "inputs:enable_emission", True) rep.functional.modify.attribute(mat, "inputs:emissive_color_texture", str(gen.choice(textures))) rep.functional.modify.attribute(mat, "inputs:emissive_intensity", float(gen.uniform(0, 1000))) # --- Writer -------------------------------------------------------------------------------------- writer = rep.WriterRegistry.get("KittiWriter") writer.initialize(output_dir=data_dir, omit_semantic_type=True, semantic_filter_predicate="class:palletjack") render_product = rep.create.render_product(cam.GetPath(), (args.width, args.height)) writer.attach(render_product) print(f"[m3] writing {args.num_frames} frames to {data_dir}") for i in range(args.num_frames): randomize() rep.orchestrator.step(rt_subframes=args.rt_subframes) if i % 10 == 0: print(f"[m3] frame {i}/{args.num_frames}") rep.orchestrator.wait_until_complete() writer.detach() render_product.destroy() # KittiWriter's semantic_filter_predicate is not applied to its *_fast bbox annotators in this build, so # unlabelled warehouse geometry still gets "Unlabelled" rows. Keep only the class we train on. det_dir = os.path.join(data_dir, "Camera", "object_detection") for f in os.listdir(det_dir): path = os.path.join(det_dir, f) with open(path) as fh: rows = [line for line in fh if line.split(" ", 1)[0] == "palletjack"] with open(path, "w") as fh: fh.writelines(rows) if args.test: cam_dir = os.path.join(data_dir, "Camera") labels = sorted(os.listdir(os.path.join(cam_dir, "object_detection"))) classes, boxes = set(), set() for f in labels: with open(os.path.join(cam_dir, "object_detection", f)) as fh: rows = [line.split() for line in fh if line.strip()] classes.update(r[0] for r in rows) boxes.add(tuple(tuple(r[4:8]) for r in rows)) n_rgb = len(os.listdir(os.path.join(cam_dir, "rgb"))) print(f"[m3] rgb images: {n_rgb}, label files: {len(labels)}, classes: {sorted(classes)}, distinct label sets: {len(boxes)}") ok = n_rgb >= args.num_frames and classes <= {"palletjack"} and len(boxes) > 1 print("[m3] PASS: randomized, palletjack-only KITTI data" if ok else "[m3] FAIL") simulation_app.close() |
m4_nova_carter_cmd_vel.py
Module 4.3 checkpoint: drive Nova Carter from ROS 2 /cmd_vel with an Action Graph (Isaac Sim 6.1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """Module 4.3 checkpoint: drive Nova Carter from ROS 2 /cmd_vel with an Action Graph (Isaac Sim 6.1). Builds the same graph as the lesson "Using OmniGraph to Drive a Robot in Isaac Sim": On Playback Tick ─┬─> ROS2 Subscribe Twist ──linear──> Break 3-Vector ─x─> Differential Controller ──> Articulation Controller ROS2 Context ─────┘ └─angular─> Break 3-Vector ─z─┘ (wheel radius 0.14, wheel distance 0.413, max 2.0 m/s / 3.0 rad/s) Differences from the 4.5 lesson: none in the graph itself. The ROS 2 bridge auto-loads with bundled Jazzy libraries (Ubuntu 24.04), so you do not have to source /opt/ros before launching. Usage (from the Isaac Sim root folder): ./python.sh learning_resource/scripts/m4_nova_carter_cmd_vel.py then, in another terminal: ros2 run teleop_twist_keyboard teleop_twist_keyboard ./python.sh learning_resource/scripts/m4_nova_carter_cmd_vel.py --headless --test (publishes /cmd_vel itself with rclpy for 3 s and checks that the robot moved) """ import argparse parser = argparse.ArgumentParser() parser.add_argument("--headless", action="store_true") parser.add_argument("--test", action="store_true") args, _ = parser.parse_known_args() from isaacsim import SimulationApp simulation_app = SimulationApp({"headless": args.headless}) import omni.kit.app ext_manager = omni.kit.app.get_app().get_extension_manager() for ext in ["isaacsim.ros2.bridge", "isaacsim.robot.wheeled_robots.nodes", "isaacsim.core.nodes"]: ext_manager.set_extension_enabled_immediate(ext, True) simulation_app.update() # let the ROS 2 bridge finish starting before touching the stage import omni.graph.core as og import omni.timeline import omni.usd from isaacsim.storage.native import get_assets_root_path from pxr import Gf, UsdGeom, UsdPhysics assets_root = get_assets_root_path() omni.usd.get_context().new_stage() simulation_app.update() stage = omni.usd.get_context().get_stage() UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) # Environment + robot (GUI: Window > Browsers > Isaac Sim Assets, or Create > Environments / Create > Robots) room = stage.DefinePrim("/World/SimpleRoom", "Xform") room.GetReferences().AddReference(assets_root + "/Isaac/Environments/Simple_Room/simple_room.usd") robot = stage.DefinePrim("/World/nova_carter", "Xform") robot.GetReferences().AddReference(assets_root + "/Isaac/Robots/NVIDIA/NovaCarter/nova_carter.usd") robot_xf = UsdGeom.Xformable(robot) # lift slightly off the floor (the asset root may already carry xform ops) translate_op = next((op for op in robot_xf.GetOrderedXformOps() if op.GetOpType() == UsdGeom.XformOp.TypeTranslate), None) (translate_op or robot_xf.AddTranslateOp(UsdGeom.XformOp.PrecisionDouble)).Set(Gf.Vec3d(0, 0, 0.05)) while omni.usd.get_context().get_stage_loading_status()[2] > 0: simulation_app.update() simulation_app.update() art_root = None # the lesson's "Add Target > nova_carter > chassis_link" for prim in stage.Traverse(): if prim.HasAPI(UsdPhysics.ArticulationRootAPI) and str(prim.GetPath()).startswith("/World/nova_carter"): art_root = str(prim.GetPath()) break wheel_joints = [str(p.GetName()) for p in stage.Traverse() if p.IsA(UsdPhysics.RevoluteJoint) and "wheel" in p.GetName()] print(f"[m4] articulation root: {art_root}") print(f"[m4] wheel joints found: {wheel_joints}") og.Controller.edit( {"graph_path": "/World/nova_carter_cmd_vel", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("ROS2Context", "isaacsim.ros2.bridge.ROS2Context"), ("SubscribeTwist", "isaacsim.ros2.bridge.ROS2SubscribeTwist"), ("BreakLinear", "omni.graph.nodes.BreakVector3"), ("BreakAngular", "omni.graph.nodes.BreakVector3"), ("DifferentialController", "isaacsim.robot.wheeled_robots.DifferentialController"), ("ArticulationController", "isaacsim.core.nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("SubscribeTwist.inputs:topicName", "cmd_vel"), ("DifferentialController.inputs:wheelRadius", 0.14), ("DifferentialController.inputs:wheelDistance", 0.413), ("DifferentialController.inputs:maxLinearSpeed", 2.0), ("DifferentialController.inputs:maxAngularSpeed", 3.0), ("ArticulationController.inputs:robotPath", art_root), ("ArticulationController.inputs:jointNames", ["joint_wheel_left", "joint_wheel_right"]), ], og.Controller.Keys.CONNECT: [ ("OnPlaybackTick.outputs:tick", "SubscribeTwist.inputs:execIn"), ("ROS2Context.outputs:context", "SubscribeTwist.inputs:context"), ("SubscribeTwist.outputs:linearVelocity", "BreakLinear.inputs:tuple"), ("SubscribeTwist.outputs:angularVelocity", "BreakAngular.inputs:tuple"), ("SubscribeTwist.outputs:execOut", "DifferentialController.inputs:execIn"), ("BreakLinear.outputs:x", "DifferentialController.inputs:linearVelocity"), ("BreakAngular.outputs:z", "DifferentialController.inputs:angularVelocity"), ("OnPlaybackTick.outputs:tick", "ArticulationController.inputs:execIn"), ("DifferentialController.outputs:velocityCommand", "ArticulationController.inputs:velocityCommand"), ], }, ) timeline = omni.timeline.get_timeline_interface() timeline.play() if args.test: import rclpy from geometry_msgs.msg import Twist rclpy.init() node = rclpy.create_node("m4_test_publisher") pub = node.create_publisher(Twist, "cmd_vel", 10) msg = Twist() msg.linear.x = 0.5 chassis = UsdGeom.Xformable(stage.GetPrimAtPath(art_root)) p0 = chassis.ComputeLocalToWorldTransform(0).ExtractTranslation() for i in range(240): # ~4 s if i > 30: pub.publish(msg) simulation_app.update() p1 = chassis.ComputeLocalToWorldTransform(0).ExtractTranslation() dist = (p1 - p0).GetLength() print(f"[m4] robot moved {dist:.3f} m while /cmd_vel linear.x = 0.5") print("[m4] PASS: Nova Carter follows /cmd_vel" if dist > 0.5 else "[m4] FAIL: robot did not follow /cmd_vel") node.destroy_node() rclpy.shutdown() timeline.stop() simulation_app.close() else: print("[m4] Playing. Publish geometry_msgs/Twist on /cmd_vel (e.g. teleop_twist_keyboard).") while simulation_app.is_running(): simulation_app.update() simulation_app.close() |
m4_run_snippet.py
Run a Script Editor snippet as a standalone app (and optionally self-check it).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | """Run a Script Editor snippet as a standalone app (and optionally self-check it). The snippets m4_snippet_*.py are meant for Window > Script Editor. This runner lets you run the same code from a terminal, which is the "standalone Python" workflow the course does not cover: ./python.sh learning_resource/scripts/m4_run_snippet.py learning_resource/scripts/m4_snippet_core_api.py ./python.sh learning_resource/scripts/m4_run_snippet.py learning_resource/scripts/m4_snippet_usd_api.py --headless --test """ import argparse parser = argparse.ArgumentParser() parser.add_argument("snippet") parser.add_argument("--headless", action="store_true") parser.add_argument("--test", action="store_true", help="Play 2 s and check that a cube fell onto the ground") args, _ = parser.parse_known_args() from isaacsim import SimulationApp simulation_app = SimulationApp({"headless": args.headless}) import omni.timeline import omni.usd from pxr import UsdGeom, UsdPhysics omni.usd.get_context().new_stage() simulation_app.update() with open(args.snippet) as f: exec(compile(f.read(), args.snippet, "exec"), {"__name__": "__snippet__"}) simulation_app.update() stage = omni.usd.get_context().get_stage() cube = next(p for p in stage.Traverse() if p.HasAPI(UsdPhysics.RigidBodyAPI)) z0 = UsdGeom.Xformable(cube).ComputeLocalToWorldTransform(0).ExtractTranslation()[2] timeline = omni.timeline.get_timeline_interface() timeline.play() if args.test: for _ in range(120): simulation_app.update() z1 = UsdGeom.Xformable(cube).ComputeLocalToWorldTransform(0).ExtractTranslation()[2] print(f"[m4] {cube.GetPath()} z: {z0:.3f} -> {z1:.3f}") print("[m4] PASS: cube fell and rests on the ground" if 0.1 < z1 < z0 - 0.3 else "[m4] FAIL") timeline.stop() simulation_app.close() else: while simulation_app.is_running(): simulation_app.update() simulation_app.close() |
m4_snippet_core_api.py
Module 4.4 - "Isaac Sim Core API Workflow" snippet, rewritten for Isaac Sim 6.1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # Module 4.4 - "Isaac Sim Core API Workflow" snippet, rewritten for Isaac Sim 6.1. # Paste into Window > Script Editor on an EMPTY stage (File > New From Stage Template > Empty), Ctrl+Enter, then Play. # # The course used omni.isaac.core (4.2): # from omni.isaac.core.objects import DynamicCuboid # from omni.isaac.core.objects.ground_plane import GroundPlane # from omni.isaac.core.physics_context import PhysicsContext # In 6.1 `omni.isaac.core` is gone and `isaacsim.core.api` is deprecated. The current API is # isaacsim.core.experimental.*: shapes are plain geometry, and you add physics by wrapping # them in RigidPrim (rigid body) + GeomPrim (collider). from isaacsim.core.experimental.materials import PreviewSurfaceMaterial from isaacsim.core.experimental.objects import Cube, GroundPlane from isaacsim.core.experimental.prims import GeomPrim, RigidPrim from pxr import UsdPhysics import omni.usd stage = omni.usd.get_context().get_stage() if not any(p.IsA(UsdPhysics.Scene) for p in stage.Traverse()): # = PhysicsContext() UsdPhysics.Scene.Define(stage, "/World/PhysicsScene") GroundPlane("/World/groundPlane", sizes=10) cube = Cube("/World/cube", sizes=1.0, positions=[-0.5, -0.2, 1.0], scales=[0.5, 0.5, 0.5]) material = PreviewSurfaceMaterial("/World/Looks/cube_color") material.set_input_values("diffuseColor", [0.2, 0.3, 0.0]) cube.apply_visual_materials(material) RigidPrim(cube.paths) # = "Dynamic": adds a rigid body GeomPrim(cube.paths, apply_collision_apis=True) # adds a collider |
m4_snippet_usd_api.py
Module 4.4 - "USD API Workflow" snippet. Paste into Window > Script Editor on an EMPTY stage, Ctrl+Enter, then Play.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | # Module 4.4 - "USD API Workflow" snippet. Paste into Window > Script Editor on an EMPTY stage, Ctrl+Enter, then Play. # This is the course code unchanged: raw USD / PhysX schema APIs are stable, so it still works in Isaac Sim 6.1. from pxr import UsdPhysics, PhysxSchema, Gf, PhysicsSchemaTools, UsdGeom import omni stage = omni.usd.get_context().get_stage() # Setting up Physics Scene gravity = 9.8 scene = UsdPhysics.Scene.Define(stage, "/World/physics") scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(gravity) PhysxSchema.PhysxSceneAPI.Apply(stage.GetPrimAtPath("/World/physics")) physxSceneAPI = PhysxSchema.PhysxSceneAPI.Get(stage, "/World/physics") physxSceneAPI.CreateEnableCCDAttr(True) physxSceneAPI.CreateEnableStabilizationAttr(True) physxSceneAPI.CreateEnableGPUDynamicsAttr(False) physxSceneAPI.CreateBroadphaseTypeAttr("MBP") physxSceneAPI.CreateSolverTypeAttr("TGS") # Setting up Ground Plane PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 15, Gf.Vec3f(0, 0, 0), Gf.Vec3f(0.7)) # Adding a Cube path = "/World/Cube" cubeGeom = UsdGeom.Cube.Define(stage, path) cubePrim = stage.GetPrimAtPath(path) size = 0.5 offset = Gf.Vec3f(0.5, 0.2, 1.0) cubeGeom.CreateSizeAttr(size) cubeGeom.AddTranslateOp().Set(offset) # Attach Rigid Body and Collision Preset rigid_api = UsdPhysics.RigidBodyAPI.Apply(cubePrim) rigid_api.CreateRigidBodyEnabledAttr(True) UsdPhysics.CollisionAPI.Apply(cubePrim) |