46. agxRender: Real-Time Rendering and Visualization

agxRender is AGX Dynamics’ rendering module built on top of WickedEngine, a modern GPU-driven renderer supporting physically based materials, real-time shadows, ambient occlusion, ray traced reflections, path tracing and GPU-instanced particle/terrain rendering. It provides both a ready-to-use interactive viewer application (agxViewer) and a public C++/Python API (agxRender::) for building custom visualizations directly from a simulation script.

agxRender is the designated successor to agxOSG and agxOSGViewer (the OpenSceneGraph-based renderer). Both modules can currently be used side by side, but new projects are encouraged to start with agxRender; see Moving from agxOSG to agxRender for a function-by-function comparison and a porting checklist.

46.1. Overview

agxRender is organized as a set of small, focused headers, each covering one aspect of visualization:

Header

Covers

agxRender/agxRender.h

Session lifecycle: ViewerSessionOptions, runViewerSession(), the begin/step/end variant, window size/fullscreen/vsync, global renderer switches (wire mode, logo, corner axis gizmo, landscape terrain)

agxRender/Application.h

The Application class used by agxViewer – command-line parsing plus convenience setters for every option

agxRender/SceneAPI.h

Loading .agx/.aagx files (readFile()), creating visuals for an entire simulation, SceneLoader for custom file formats

agxRender/VisualAPI.h

createVisual() for geometries, rigid bodies, cables, wires, particle systems, deformables and terrain; visual-only meshes built in code (createMeshVisual()); attaching external 3D models; skeletal animation playback

agxRender/MaterialAPI.h

The Material class (PBR parameters, textures), free-function per-visual setters, preset materials (glass, car paint, chrome), and per-visual wireframe overlays

agxRender/LightingAPI.h

Point/directional/spot/rectangular lights, the default sun light, HDR/EXR environment maps (image-based lighting), background color/gradient

agxRender/EnvironmentEffectsAPI.h

Weather and atmosphere (fog, rain, wind, sky, volumetric clouds) and the ocean

agxRender/RenderSettingsAPI.h

Post-processing of the main view: exposure, eye adaption, bloom, depth of field, and the ray-traced global illumination switches

agxRender/ParticleVizAPI.h

Particle upsampling and particle materials for any agx::ParticleSystem

agxRender/EmitterAPI.h

Visual-only GPU particle emitters (dust, smoke, spray, sparks) that never interact with the simulation

agxRender/VegetationAPI.h

Grass and scattered model instances (trees, shrubs, rocks) grown on a visual’s mesh

agxRender/MeshLodAPI.h

Automatic level of detail: simplified copies of large meshes, generated in the background and cached on disk (see Automatic level of detail (LOD))

agxRender/CameraAPI.h

Reading/writing the interactive camera pose, camera-follow rigs, keyframed camera paths

agxRender/DebugAPI.h / agxRender/DebugDraw.h

Attaching AGX’s debug renderer, and drawing ad-hoc lines/spheres/boxes/arrows/frames

agxRender/AxesAPI.h

Coordinate-axes gizmos that track a frame, body, geometry or constraint

agxRender/HudAPI.h

On-screen text overlays and clickable buttons

agxRender/LabelAPI.h

3D labels: text tags anchored to a world position, frame, body or geometry

agxRender/TerrainVizAPI.h

The agxRender replacement for agxOSG::TerrainVoxelRenderer – height/compaction color gradients, wireframe overlays, voxel/velocity-field overlays, GPU particle upsampling

agxRender/TerrainPagerRenderer.h

Rendering the tiles of an agxTerrain::TerrainPager, with an optional backdrop of the whole pageable area

agxRender/TireDeformationAPI.h

Visual deformation of tire meshes where they touch the ground

agxRender/CameraSensorAPI.h / agxRender/LidarVisualizationAPI.h

On-screen previews of agxSensor::Camera color, depth and stereo-depth output, and point-cloud visualization of agxSensor::Lidar

agxRender/FisheyeCameraAPI.h

A reference implementation of a fisheye camera (not part of agxSensor), with previews and CPU read-back of its color and depth images

agxRender/PixelStreamingAPI.h

Streaming the rendered scene to a browser over WebSocket (remote/headless viewing). C++ only; from Python, pixel streaming is enabled through ViewerSessionOptions or Application

agxRender/Types.h

Shared types: VisualHandle, VisualOptions, MaterialDesc and the enums (BlendMode, VisualPrimitive, WireRenderMode, particle modes)

In Python, all of the above is exposed as a single flat module, agxRender, generated by SWIG – e.g. agxRender::createVisual() becomes agxRender.createVisual(), and a C++ enum class value such as BlendMode::ALPHA becomes the enum.IntEnum member agxRender.BlendMode.ALPHA. Default arguments carry over. Keyword arguments work for functions with a single signature, such as playAnimation(visual, "Walk", speed=2.0), but overloaded functions (createVisual(), createLabel(), createHudText(), createHudButton(), setTireDeformation(), …) take their arguments by position only.

The agxPythonModules.agxRender package adds a few pure-Python helpers on top of the SWIG module:

  • agxPythonModules.agxRender.environment.simulation() returns the simulation of the current script context, so a build_scene(sim=None) function can also be called without arguments when the script is loaded by agxViewer.

  • agxPythonModules.agxRender.openplx loads a .openplx file and visualizes it (load_openplx(sim, path)), including terrains and any sensor previews requested by the model, and runs a viewer session for it (run_session(sim, args)) – without the agxViewer executable.

  • agxPythonModules.agxRender.effects builds effects on the particle emitter API: WheelDust (dust kicked up by wheels, see Particle emitters (visual effects)), dust_settings() and puff_sprite().

46.1.1. API conventions

The functions follow the same conventions throughout the API:

  • Handles. Every object created through agxRender is identified by a handle of its own type – VisualHandle, LightHandle, LabelHandle, TerrainRendererHandle and so on – so handles of different kinds can’t be mixed up. A default-constructed handle is invalid (value() 0, isValid() false). In Python, a handle is false when invalid, compares equal to a handle of the same kind with the same value, and can be used as a dictionary key. A valid handle may refer to an object that has been destroyed since: functions taking a handle then do nothing and return false (setters and destroy*()) or a default value (getters).

  • Creating and destroying. What create*() makes, destroy*() destroys, and destroyAll*() destroys all of that kind, e.g. createPointLight()/destroyLight()/ destroyAllLights(). What add*() adds to an existing object (a camera preview, a lidar visualization), remove*() and removeAll*() remove.

  • Switches. On/off settings are setEnable*()/getEnable*(), as in the rest of AGX Dynamics, e.g. setEnableShadows(), setEnableDebugRendering() and Application.setEnableVideoCapture(). Running services are started and stopped: startPixelStreaming(), isPixelStreamingRunning(), startSimulationHost().

  • One property per setter. E.g. setLightColor() sets the color and setLightIntensity() the intensity.

46.2. Additional rendering resources

Many of the agxRender example scripts in data/python_agxrender (worksite, vehicle, terrain, weather and character scenes, among others) use large assets – HDR environment maps, terrain and ground textures, and 3D models – that live in data/resources of the AGX installation. This directory is more than 1 GB, so it is optional:

  • Windows installer: select Download and install additional rendering resources for agxRender on the Installation options page. This option is off by default. The resources (~900 MB) are downloaded and unpacked during installation. If the download fails, the installation continues without them.

  • Linux deb package: data/resources is not included. After installing the package, apt/dpkg prints a message on how to install the resources with the script described below. Graphical package installers usually do not show this message.

  • Linux rpm package: currently includes data/resources.

The resources can also be installed afterwards, or re-installed, using the fetch_agxrender_resources.py script in the root of the AGX installation directory. It works on all platforms and only uses the Python standard library:

# Windows (from an AGX Dynamics Command Line, where python is available)
cd <AGX install dir>
python fetch_agxrender_resources.py

# Linux (an installation in /opt requires root)
cd /opt/Algoryx/AGX-<version>
sudo python3 fetch_agxrender_resources.py

The script downloads the archive into the data directory, unpacks it into data/resources and removes the archive. Options:

Option

Description

--data-dir DIR

Install into DIR/resources instead of the data directory next to the script (falls back to AGX_DATA_DIR if that directory does not exist)

--archive ZIP

Unpack an already downloaded archive instead of downloading it, e.g. on a machine without internet access

--force

Download and unpack again even if data/resources already exists

--keep-archive

Keep the downloaded archive in the data directory

--url URL

Download from another location, e.g. an internal mirror

The Windows uninstaller and removing the deb package (sudo apt remove agx) remove data/resources also when it was installed with the script. Upgrading the deb package keeps it.

46.2.1. Cache directory

The files agxRender generates at runtime are not written into the AGX installation, which is often read-only (e.g. in /opt), but into a per-user cache directory:

  • AGXRENDER_CACHE_DIR, if this environment variable is set,

  • else Windows: %LOCALAPPDATA%\Algoryx\agxRender, macOS: ~/Library/Caches/Algoryx/agxRender, Linux: $XDG_CACHE_HOME/Algoryx/agxRender or ~/.cache/Algoryx/agxRender,

  • else agxRender in the temporary directory.

It contains:

Entry

Content

textures

Textures extracted from material ZIP archives (Material.fromFile())

nonrepeating

Textures synthesized by Material.makeNonRepeating()

MeshLodCache

Simplified mesh levels of detail

agxRender.log

The log of the latest run: warnings and errors, or all messages if the environment variable AGXRENDER_VERBOSE is set (and not 0)

Cached files are named after the source file’s path, size and modification time, so a changed or moved source is processed again. The directory can be deleted at any time; it is filled again when needed.

46.2.2. Driver shader cache and first-start time

Before the first frame, the GPU driver compiles agxRender’s shaders into code for the installed GPU. The driver stores the result in its own shader cache, so this happens only on the first start, and again after AGX or the GPU driver has been updated. The first start can then take 10-20 seconds longer, and agxRender prints:

agxRender: shader pipeline creation took 10.3 s (cold driver shader cache?)

Later starts reuse the cache and skip the delay.

The shader cache belongs to the GPU driver, not to agxRender. It is shared by all applications that use the GPU, and it is not part of the cache directory above. The driver limits its total size and removes the oldest entries when it is full. agxRender needs about 30 MB of it. Its location depends on the platform and GPU vendor (agxRender uses DirectX 12 on Windows unless started with -vulkan, and Vulkan on Linux):

GPU

Shader cache

NVIDIA, Windows

%LOCALAPPDATA%\NVIDIA\DXCache (DirectX 12), %LOCALAPPDATA%\NVIDIA\GLCache (Vulkan). Size limit: Shader Cache Size under Manage 3D Settings in the NVIDIA Control Panel.

NVIDIA, Linux

$XDG_CACHE_HOME/nvidia/GLCache or ~/.cache/nvidia/GLCache, or the directory in __GL_SHADER_DISK_CACHE_PATH. Size limit: __GL_SHADER_DISK_CACHE_SIZE in bytes (about 1 GB by default); __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 disables the limit.

AMD and Intel, Linux (Mesa)

~/.cache/mesa_shader_cache*. Size limit: MESA_SHADER_CACHE_MAX_SIZE (e.g. 4G; 1 GB by default).

AMD, Windows

%LOCALAPPDATA%\AMD\DxCache (DirectX 12), %LOCALAPPDATA%\AMD\VkCache (Vulkan).

If every start is slow, not just the first, the cache is too small for all the applications that share it, and agxRender’s shaders are removed before the next start. Raise the size limit as above. Deleting the shader cache is safe; it only makes the next start of each application slow. On Windows, Disk Cleanup empties it with the option DirectX Shader Cache.

46.3. Getting started

46.3.1. A minimal script

The simplest way to use agxRender is to write an .py script with a module-level build_scene(sim) function and open it with agxViewer – the viewer creates the agxSDK::Simulation, calls your function to populate it, and then owns the render loop, camera control and keyboard shortcuts. You can also also use the standard python application. It requires however the use of the Application class.

# hello_agxrender.py
import agx
import agxCollide
import agxRender


def build_scene(sim):
    ground = agxCollide.Geometry(agxCollide.Box(agx.Vec3(4.0, 4.0, 0.1)))
    ground.setPosition(agx.Vec3(0.0, 0.0, -0.1))
    sim.add(ground)
    agxRender.setBaseColor(agxRender.createVisual(ground), agx.Vec4f(0.8, 0.8, 0.8, 1.0))

    box = agx.RigidBody(agxCollide.Geometry(agxCollide.Box(agx.Vec3(0.3, 0.3, 0.3))))
    box.setPosition(agx.Vec3(0.0, 0.0, 2.0))
    sim.add(box)
    visual = agxRender.createVisual(box.getGeometries()[0])
    agxRender.setBaseColor(visual, agx.Vec4f(0.85, 0.15, 0.1, 1.0))
    agxRender.setRoughness(visual, 0.3)
agxViewer hello_agxrender.py

A few things are happening here, mirroring the familiar agxOSG/agxOSGViewer workflow but with a leaner contract:

  1. build_scene(sim) receives an already-constructed, empty agxSDK::Simulation – just add bodies/constraints/etc. to it as usual.

  2. Every geometry that should be visible needs an explicit agxRender.createVisual(geometry) call, which returns a VisualHandle. Nothing is rendered automatically – there is no implicit “create a visual for every geometry” step (see agxRender.createVisualsForSimulation() below if you want that behavior back).

  3. Material/color setters (setBaseColor, setRoughness, …) take a VisualHandle, not the geometry or body itself.

  4. The viewer keeps the returned simulation alive, drives stepForward(), renders each frame, and installs the mouse/keyboard bindings listed in Keyboard and mouse bindings.

If a single script needs more than one selectable scene, define build_scene1(sim), build_scene2(sim), … instead of one build_scene(sim); agxViewer detects them automatically and binds them to keys 1-9 (see Multi-scene scripts and custom SceneLoader).

46.3.2. Running headless, or driving your own loop

A script can also open its own viewer session instead of being loaded by agxViewer – useful for automated testing, batch rendering, or embedding the render loop inside a larger Python program (e.g. a reinforcement-learning environment). The blocking, all-in-one entry point is agxRender.runViewerSession():

import agxSDK
import agxRender

sim = agxSDK.Simulation()
# ... populate sim, create visuals ...

options = agxRender.ViewerSessionOptions()
options.simulation = sim
options.stepSimulationEachFrame = True
options.stopAfterSeconds = 10.0
options.width = 1920
options.height = 1080
options.headless = True          # no visible window; still renders off-screen
options.captureImage = True
options.captureImageName = "frame"
options.captureImageDirectory = "imageCapture"

if not agxRender.runViewerSession(options):
    raise RuntimeError("agxRender.runViewerSession failed")

For a caller that wants to drive the loop itself frame by frame (e.g. stepping the simulation under its own control between renders), use the begin/step/end triplet instead:

agxRender.setViewerSessionAutoStepping(False)  # we call sim.stepForward() ourselves
if not agxRender.beginViewerSession(options):
    raise RuntimeError("agxRender.beginViewerSession failed")

while agxRender.stepViewerSessionFrame():
    sim.stepForward()

agxRender.endViewerSession()

Note

The begin/step/end API is deliberately minimal: no interactive camera control, scene switching, keyboard shortcuts, or video/image capture. It exists for callers that need full control of the frame loop (e.g. a Python while loop driving a training environment); use runViewerSession() or the Application class (below) for everything else.

The Application class offers the same pattern as methods – beginSession(), stepFrame(), endSession(), with setAutoStepping(False) and stepSimulation() to step physics yourself – so a script can combine command-line parsing with its own loop (see data/python_agxrender/tutorial_explicit_stepping.py):

app = agxRender.Application()
app.parseArgumentList(sys.argv)
app.options().simulation = sim
app.setAutoStepping(False)
if app.beginSession():
    while True:
        app.stepSimulation()
        if not app.stepFrame():
            break
    app.endSession()

46.3.3. The Application class

agxRender::Application is the class agxViewer itself is built on – it adds command-line argument parsing, scene-file handling and the full interactive session (camera control, keyboard shortcuts, capture) on top of ViewerSessionOptions. Writing your own __main__ block around it, as most of the tutorial scripts in data/python_agxrender do, gives a script the exact same command-line interface as agxViewer while still allowing it to define custom scenes:

import sys
import agxRender


def build_scene(sim):
    ...  # as above


if __name__ == "__main__":
    app = agxRender.Application()
    if not app.parseArgumentList(sys.argv):
        raise RuntimeError("agxRender.Application.parseArgumentList failed")

    import agxSDK
    sim = agxSDK.Simulation()
    build_scene(sim)
    app.options().simulation = sim

    if not app.run():
        raise RuntimeError("agxRender.Application.run failed")

Running python hello_agxrender.py --startPaused --captureVideo 1 now works exactly like passing those flags to agxViewer, because both go through the same Application::parseArguments(). See Command-line arguments for the full flag reference.

data/python_agxrender/template_agxrender.py is a ready-made starting point for new scripts: it defines three scenes (build_scene1 … build_scene3) that load both through agxViewer and when the script is run directly with agxpython/python, using a SceneLoader (see Multi-scene scripts and custom SceneLoader) so that keys 1-3 switch between them in either case, and a reload picks up edits to the script.

46.3.4. Stopping a session

agxRender.requestViewerSessionStop() asks the running session (or an --agxOnly run) to exit exactly as if the window had been closed, so a video or image capture in progress is finalized normally. It is thread-safe, and a request made before the session has started (e.g. during a long scene load) is honored as soon as it starts.

agxViewer uses it for CTRL-C in the console: the first press stops the session gracefully, a second press force-quits immediately (exit code 130) without finalizing anything.

A script can follow the progress toward --stopAfter from a step callback:

stop_after = agxRender.getViewerSessionStopAfter()   # -1 if --stopAfter is not given
if stop_after > 0:
    progress = (sim.getTimeStamp() - agxRender.getViewerSessionStartTime()) / stop_after

getViewerSessionStartTime() is the simulation time the scene had when it was loaded (reset on a scene reload/switch). Neither value is valid yet inside build_scene(), which runs before the session starts.

46.3.5. Window, vsync and threads

The window can be configured from a script, before or during a session. Called before the session starts (e.g. from build_scene), a setter is applied at session start and takes precedence over the corresponding ViewerSessionOptions field/command-line flag; called while the session is running, it takes effect immediately:

agxRender.setWindowSize(1920, 1080)   # leaves fullscreen if it was active
agxRender.setWindowPosition(0, 0)     # its contents' top-left corner on the desktop (--position)
agxRender.setWindowBorderless(True)   # no border and title bar (--borderless)
agxRender.setFullscreen(False)        # same as pressing 'f'
agxRender.setVSync(True)              # same as the VSync check box in the F1 settings window

The corner axis gizmo is the exception: runViewerSession() sets it from ViewerSessionOptions.renderAxis (--renderAxis), so set that field before a session and use agxRender.setEnableAxis() only while the session is running.

agxRender.isViewerSessionHeadless() tells a script whether the session shows no window (--headless or --agxOnly), already in build_scene: e.g. to skip opening an external viewer window (wheelloader_quarry_cameras.py does not spawn the Rerun viewer then, nor with --unittest).

ViewerSessionOptions.numThreads (--numThreads) sets the number of AGX threads (agx.setNumThreads()). It is re-applied after every scene load, so it wins over a thread count set by the scene itself; 0 (default) leaves whatever the scene set. Alt+1-Alt+9 changes it at runtime, Alt+0 uses all CPUs.

46.3.6. Threaded simulation

By default (ViewerSessionOptions.threadedSimulation, --threadedSimulation 1, Application.setThreadedSimulation(True)) the simulation steps on its own thread, decoupled from rendering:

  • A slow simulation will not stall rendering. Camera control, the GUI and pixel streaming stay responsive while a step takes a long time; the view shows the latest completed step.

  • Rendering wont stall the simulation. With --realTime 1 the simulation thread paces itself to the wall clock at its own rate, independent of the frame rate, e.g. 1 kHz with a 1 ms time step for haptics while rendering at 60 Hz. --maxStepsPerFrame does not apply. With --realTime 0 it steps as fast as it can.

--threadedSimulation 0 (Application.setThreadedSimulation(False)) steps the simulation and renders on one thread, one after the other: a slow step freezes the window, and a slow frame holds back the simulation.

agxViewer haptics_scene.py --timeStep 0.001
agxViewer scene.py --threadedSimulation 0
app = agxRender.Application()
app.setThreadedSimulation(False)  # single-threaded
app.run()

How it works. Each rendered frame reads the simulation in a short sync window between two steps: input that acts on the simulation (picking, keyboard shortcuts, scene switching), the transform/particle/terrain sync, camera sensor poses, labels, statistics. The rest of the frame, including the camera sensor renders and the GPU work, runs while the simulation steps. A frame waits at most half a frame period for the step in progress; if the step takes longer, the frame shows the previous state and the next frame syncs.

Camera sensors stay deterministic. A step at which a camera sensor capture is due waits for the frame that renders it, so every capture shows the state of the step it was due at, exactly as in a single-threaded session. A synchronous camera sensor (see Synchronous camera sensors) also has the simulation wait until the images are in their outputs, so they are delivered (hasUnreadData()) before the next step, at the same steps as single-threaded, with or without render nodes. That costs the overlap of rendering and stepping at the steps with a capture; camera sensors are not synchronous by default and get their images two captures later. --captureSync video and image capture works the same way: each step waits for its frame while capture is on.

Step event listeners run on the simulation thread. They may call any agxRender function, e.g. update a visual’s color every step, and setters do not wait for the frame being rendered: emitter, HUD and label functions need no access to the render scene at all, and the other setters (materials, visibility, lights, render settings, debug drawing, …) called while a frame renders are queued and applied, in call order, before the next frame. A queued setter returns True; if it fails when applied (a destroyed handle, an invalid value) a warning is logged, once per function. A getter or a create waits for the frame being rendered and sees every earlier call of its thread applied. getCameraData() and applyCameraData() do not wait either: they read the camera of the last frame, and a camera applied meanwhile takes effect when the next frame starts. That frame draws the bodies as of the step it synchronized with, which need not be the step the camera was computed from, so a camera that follows a moving body this way jerks back and forth. To move the viewer camera every step, put it on a frame instead (attachCameraTo(), read in the same sync as the bodies): agxPythonModules.agxRender.camera_rig.CameraRig does that, rig.set(eye, center, ...) from the listener. The time a step waits for the frame is part of its StepForward time and is reported as the statistic agxRender wait time (threaded only); the F4 overlay shows it as Render wait, in the same graph as StepForward, Dynamics and Space. Python listeners work too: run() releases the GIL, and agxViewer switches its embedded interpreter to thread-safe mode for a threaded session.

Limitations. Debug rendering (g, --renderDebug) and terrain debug overlays read the simulation while the frame renders: while either is in use, the simulation steps serialized with rendering, as in a single-threaded session. Turning debug rendering off detaches the debug renderer, so stepping is parallel again; turning it back on rebuilds the debug shapes. The Threaded simulation checkbox in the settings window (F1) switches between threaded and single-threaded stepping while the session runs. Do not touch the simulation from another thread of your own while a threaded session runs.

An explicit session (beginSession()/stepFrame(), e.g. a viewer embedded in a Qt window) is threaded too when it sets ViewerSessionOptions.threadedSimulationInExplicitSessions (then --threadedSimulation and the settings window switch it): the simulation steps in real time on its own thread while each frame renders, and is held between stepFrame() calls, so the application’s own code (its GUI callbacks) can change the simulation between frames. It does not step the simulation itself while Application.isSimulationThreadActive(); the motor grader (data/python_agxrender/motor_grader) shows the pattern. Without the option an explicit session steps on the caller’s thread: the caller steps the simulation, or stepFrame() steps it once per frame with auto-stepping.

app.options().threadedSimulationInExplicitSessions = True
app.beginSession()
while True:                        # e.g. from a Qt timer, one frame per call
    if not app.isSimulationThreadActive():
        app.stepSimulation()       # single-threaded (--threadedSimulation 0)
    if not app.stepFrame():        # steps while it renders, held after it returns
        break

46.4. Visuals: createVisual and VisualHandle

Every renderable object in agxRender is represented by an opaque, cheap-to-copy VisualHandle, returned by one of the createVisual() overloads and passed to every other API (materials, animation, visibility) that operates on that object:

Call

Creates a visual for…

createVisual(geometry) / createVisual(geometry, options)

A single agxCollide::Geometry – box, sphere, cylinder, mesh, etc. (its native AGX shape).

createVisual(geometry, modelPath, options, hideSourceVisual=True)

A geometry, with an external 3D model (.gltf, .fbx, .obj, .ply, USD .usd/.usda/.usdc/.usdz, .wiscene) attached and following it, instead of the native shape.

createVisual(rigidBody) / createVisual(rigidBody, modelPath, ...)

Convenience: creates visuals for every geometry attached to the body.

createVisual(deformableObject, color)

An agxModel::DeformableObject’s tetrahedral surface mesh (rebuilt whenever the mesh reports vertex changes).

createVisual(cable, color, radius=0)

An agxCable::Cable as a single GPU-skinned tube mesh (one bone per segment). See below for radius.

createVisual(wire, color, radius=0)

An agxWire::Wire as a tube, regenerated every frame (control-point count changes as the wire resamples/cuts/merges) – see setWireRenderMode() and radius below.

createVisual(particleSystem)

Registers an agx::ParticleSystem for GPU-instanced rendering. Must be called explicitly – particle systems are not picked up automatically.

createVisual(terrain, options) / createTerrainVisual(terrain, options)

An agxTerrain::Terrain’s heightfield surface, plus registration for sparse per-step height updates. Prefer agxRender.createTerrainRenderer() (see Terrain visualization) when you also want deformation visualization modes.

createVisual(assembly, options)

Recursively creates visuals for every rigid body, geometry, particle system, terrain instance and deformable object in an agxSDK::Assembly tree.

createMeshVisual(meshData, transform) / createMeshVisual(meshData, frame, localTransform)

A triangle mesh built in code, with no collision shape – see Visual meshes built in code.

createSignedDistanceFieldVisual(geometry, options)

The surface of a geometry’s signed distance field, colored by its error – see Signed distance fields.

geom = agxCollide.Geometry(agxCollide.Sphere(0.25))
body = agx.RigidBody(geom)
sim.add(body)

options = agxRender.VisualCreateOptions()
options.evenIfSensor = False  # skip sensor geometries (default True: they get visuals too)

visual = agxRender.createVisual(geom, options)
agxRender.setBaseColor(visual, agx.Vec4f(0.2, 0.6, 0.9, 1.0))
../_images/agxrender_cables.jpg

Fig. 46.1 GPU-skinned agxCable::Cable visuals (cables.py).

Once you have a handle, agxRender.findVisual(geometry) looks it up again later (e.g. from another part of the script), agxRender.hasVisual(handle)/destroyVisual(handle) manage its lifetime, and setVisualVisible(handle, False) hides it without destroying it. setVisualVisibleInCameraSensors(handle, False) leaves a visual out of agxSensor camera images (camera sensors, fisheye cameras and their previews) while the viewer still shows it, e.g. for paths, markers and other overlays meant for the user only (car_test_ground.py). getVisualPrimitive(handle) returns how the visual is rendered, as a VisualPrimitive (BOX, SPHERE, MESH, MULTI, DEFORMABLE, SKINNED_1D, WIRE, CUSTOM_MESH, … or UNSUPPORTED for an invalid handle). agxRender.syncVisualTransforms() pushes AGX’s current body transforms to the renderer; the viewer session (runViewerSession/Application::run) calls this automatically every frame, so you only need it if you are driving your own render loop outside of those.

Wire visuals have two render modes, selected globally with agxRender.setWireRenderMode() (existing wire visuals are rebuilt for the new mode):

  • WireRenderMode.GPU_COMPUTE_INDIRECT (default) generates the tube on the GPU. It is shaded with the visual’s full material, but casts no shadows and has no normal maps; the CPU cost per frame is the lowest.

  • WireRenderMode.CPU_MESH_REBUILD rebuilds the tube mesh on the CPU every frame, so it casts and receives shadows like any other mesh, at the cost of a full rebuild and GPU upload every frame.

Wire and cable tubes are rendered with the wire’s/cable’s physical radius by default. Pass a positive radius to createVisual() to render the tube thicker or thinner without changing the simulated radius, e.g. to make a thin wire visible from a distance. The radius is set when the visual is created: calling createVisual() again for the same wire or cable returns the existing visual and keeps its radius. OpenPLX Visuals.Geometries.Curve visuals on wires and cables use this to render with the curve’s radius.

wire = agxWire.Wire(0.01, 3.0)  # physical radius 1 cm
# ... route and add the wire ...
agxRender.createVisual(wire, agx.Vec4f(0.8, 0.2, 0.1, 1.0), 0.03)  # rendered with radius 3 cm

To load a serialized scene into an existing simulation, use agxRender.readFile(filename, sim) – the agxRender equivalent of agxOSG.readFile(). It reads the .agx/.aagx file and creates a visual for every loaded geometry that does not already have one:

if agxRender.readFile("models/wheel_loader.agx", sim) == 0:
    raise RuntimeError("Failed to read wheel_loader.agx")

46.4.1. Visual meshes built in code

createMeshVisual() renders a triangle mesh given as an agxRender.MeshData (in AGX axes, Z up, meters). No collision shape is involved, so it suits procedural decoration, markers, or analysis results that should be seen but not simulated. The returned handle works with all visual functions (materials, wireframe, visibility, destroyVisual()):

mesh = agxRender.MeshData()
for p in [(0, 0, 0), (1, 0, 0), (0, 1, 0)]:
    mesh.vertices.append(agx.Vec3(*p))
for i in [0, 1, 2]:                          # counter-clockwise seen from the front
    mesh.indices.append(i)
# mesh.normals / mesh.texCoords / mesh.colors are optional, but then one per vertex

# Fixed in the world:
marker = agxRender.createMeshVisual(mesh, agx.AffineMatrix4x4.translate(0.0, 0.0, 1.0))

# ... or following a body (removed when the frame is deleted):
fin = agxRender.createMeshVisual(mesh, body.getFrame())

agxRender.setBaseColor(fin, agx.Vec4f(1.0, 0.5, 0.0, 1.0))
../_images/agxrender_mesh_visuals.jpg

Fig. 46.2 A procedural surface rebuilt every step with updateMeshVisual(), drawn with a wireframe overlay (mesh_visuals.py, scene 1).

When normals are omitted, smooth normals are computed from the triangles (give each side of a hard edge its own vertices); when texture coordinates are omitted, box-projected coordinates are generated with one texture repeat per meter. For animated or procedural meshes, updateMeshVisual(handle, mesh) replaces the mesh while keeping material and transform, and setMeshVisualTransform(handle, transform) moves it (relative to its parent frame, if it has one). See data/python_agxrender/mesh_visuals.py for a complete example.

46.4.2. Signed distance fields

A geometry with an agxCollide.SignedDistanceField shape gets an ordinary visual from createVisual(): the source triangles of the field. createSignedDistanceFieldVisual() instead draws what the field represents, its zero surface, to check a field against its mesh:

options = agxRender.SignedDistanceFieldVisualOptions()
options.maxError = 0.002     # m; default a quarter voxel
agxRender.createSignedDistanceFieldVisual(geometry, options)

The surface is colored by the distance from it to the source mesh: white where they agree, red where the field is outside the mesh and blue where it is inside, saturated at maxError. Source triangles the field does not resolve (thinner than about a voxel, see SignedDistanceFieldGrid.findUnresolvedTriangles()) are drawn in magenta. The visual follows the geometry; it is built once, so create it again after changing the field.

In agxViewer, the Signed Distance Fields checkbox in the F1 settings window (AGX Viz section) shows these visuals for all fields in the scene in place of the visuals of their bodies. They are built when it is switched on (a fraction of a second to a few seconds per field) and destroyed when it is switched off. getVisualVisible() tells whether a visual is shown.

agxPythonModules.agxRender.signed_distance_field.replace_collision_with_field(sim, body) makes a body collide with a field of its triangle meshes (or, for bodies without meshes, of the triangles of their render data) instead of its collision geometries, which it disables. The voxel size is chosen from the mesh unless voxel_size is given. The mesh is welded and reduced to max_triangles (default 10,000) with agxUtil.reduceMesh() first. The new geometry takes their material and collision groups and does not collide with the bodies constrained to the body (actuator rods and links reach into the mesh at the pins). Grids are cached on disk, keyed by the mesh and the voxel size. The machine demos use it for their buckets and blades until OpenPLX creates the fields itself. tutorial_signed_distance_field.py is the agxRender port of the agxOSG tutorial, with the error visual in scene 8.

46.4.3. Attaching external 3D models

Any visual can have an external model file attached in place of its native AGX shape – useful for showing a detailed CAD/production asset while keeping a simple collision shape for physics:

options = agxRender.VisualCreateOptions()
options.modelScale = agx.Vec3f(1.0, 1.0, 1.0)
options.modelLocalTransform = agx.AffineMatrix4x4.rotate(agx.EulerAngles(0, 0, 0))

visual = agxRender.createVisual(geom, "models/wheel_loader_bucket.gltf", options)
# ... later, if needed:
agxRender.detachModel(visual)

getAttachedModelBounds() returns the model’s bounding box in the geometry’s own local frame – handy for auto-fitting a camera to a loaded asset regardless of file format. Models attached before the viewer window exists (e.g. in build_scene()) are loaded when the session starts, so until then it reports no bounds (in Python, ok, lo, hi = agxRender.getAttachedModelBounds(visual) gives ok == False); query it from a step or GUI event listener instead. To just look at a model file, open it directly in agxViewer (see Viewing 3D model files).

Models with named animation clips (baked walk cycles, door-open animations, etc.) can be played back with playAnimation(handle, name, loop=True, speed=1.0), stopAnimation(handle), isAnimationPlaying(handle) and getAnimationNames(handle). Playback advances in simulation time whenever the visual was created while a simulation is running (frozen while paused), matching physics rather than wall-clock time.

46.4.4. Driving a skeleton from code (character animation)

Baked clips only replay what is in the file. To make a character walk where the simulation steers it, plant its feet on deformable terrain or reach for a moving object, pose its bones from Python every step instead:

getBoneNames(handle)

The bones of the skinned model attached to the visual (every armature in the model).

getBoneRestPositions(handle)

The rest (bind pose) joint position of each bone, in the same order, in the geometry’s rigid local frame – the frame getAttachedModelBounds() uses.

setBonePose(handle, bone, rotation, position)

Rotates the bone by rotation relative to its rest pose and moves its joint to position, both in that same frame: a point bound to the bone at rest position v is drawn at position + rotation * (v - restPosition). Bones never posed keep their rest pose relative to their parent. A pose stays until set again and replaces what a playing clip does to that bone.

Because rotations are relative to the rest pose and expressed in one common frame, no bone roll conventions or parent-relative transforms are involved: forward kinematics is

# rest: {name: numpy rest joint position}, parents: {name: parent name or None},
# R: {name: 3x3 rotation from rest (common frame)}, hips: hip joint position.
P = {}
for name in bones:                      # parents before children
    parent = parents[name]
    P[name] = hips if parent is None else P[parent] + R[parent] @ (rest[name] - rest[parent])
for name in bones:
    agxRender.setBonePose(handle, name, to_quat(R[name]), agx.Vec3(*P[name]))

and two-bone IK only has to produce the joint positions and the rotations that take each rest bone direction to its new direction. Attach the model to a geometry at the world origin (collisions disabled) and the common frame is the world frame.

Like the bounds, the bones are only known once the model has loaded when the session starts, so getBoneNames() is empty in build_scene(); read the rest pose on the first step. Each createVisual(geometry, modelPath) loads its own instance of the model, so several characters share the file but are posed independently.

data/python_agxrender/lunar_base_operations.py uses this for its five astronauts (EVA suits around a cargo lander). The pipeline:

  1. Rig. tools/rig_astronaut.py (run with Blender, blender -b --python tools/rig_astronaut.py) turns a static scanned/generated suit mesh into a skinned glTF: it reduces the mesh to 90k triangles, fits a 20-bone humanoid skeleton (Mixamo bone names) from cross-sections of the mesh, weights it with Blender’s automatic weights and makes the hard parts (helmet, upper torso, backpack) rigid.

  2. Motion capture. tools/retarget_cmu.py retargets clips of the CMU Graphics Lab Motion Capture Database (BVH) to the rig as per-bone rotations from the rest pose – exactly what setBonePose() takes: each bone’s rotation from the clip’s T-pose, after a fixed correction from the rig’s A-pose to the T-pose. It cuts a walk to one looping gait cycle, records which feet are planted, stands the rig on the floor with its own leg lengths and paces the cycle by how fast the rig’s planted foot moves back under the hips. preview draws stick figures for choosing clip segments. The scene uses a slow walk, two idles and two hand-work clips.

  3. Motion. Every step each astronaut samples its clips (crossfading where a clip wraps around, blending idle and walk), turns them to its heading and applies forward kinematics, then grounds the result with IK:

    • The walk cycle advances with the distance walked, so feet the clip plants do not slide. A planted boot rolls over its heel from heel strike and over the ball of the foot once the heel lifts, the pivot held on the terrain height field; it lifts as soon as the clip’s toes leave the ground.

    • Stopping, the walk finishes its step until both feet are down and blends into the idle clip; standing, a footstep planner takes the closing and turning steps, and the body turns by stepping, never far ahead of its feet.

    • Leg IK holds each foot where it is planted. The knee bends the way the clip has it, but always forward over the toes: with a straight leg the clip’s bend direction is noise, and following it rolls the thigh against the shin, which the skinned mesh shows as a twisted, collapsed knee. Boots are kept from rolling onto their side and stand flat when planted.

    • Arm IK moves the hands to the work (the work clips’ hand motion re-centred on a crate or instrument; a pointing arm; a carried case kept hanging plumb), with the clip’s elbow and wrist motion; workers lean in or straighten up until the hands reach.

    • An activity object per astronaut sets the goals: a route to walk with a pause, a work surface, a target to watch and point at. The kneeling sampler is posed procedurally.

Things that matter for a believable result:

  • Check the motion with numbers, not only images: log hip height, knee angles and the twist between connected bones per step. A hip that sinks over a straight stance leg reads as sitting down; a twist of more than about 40° between thigh and shin shows as a pinched knee.

  • The skeleton of a motion capture actor and the rig differ inside the feet: give the foot no rest-to-T-pose correction, as both stand flat.

  • With a single low sun and no bounce light, the sides of a character facing away from the sun render black. lunar_base_operations.py raises the ambient term (AtmosphereSettings.ambientColor) to stand in for light bounced from the sunlit ground.

  • Posing costs about 0.7 ms per character per step in Python (20 bones, numpy).

46.4.5. Automatic level of detail (LOD)

Large meshes cost the same to draw whether they fill the screen or cover a few pixels. To avoid that, agxRender gives every static mesh with at least minTriangles triangles (8000 by default) up to five simplified copies – levels of detail. The geometric error of each LOD is measured when it is built, and the renderer draws an object at the coarsest LOD whose error on screen is at most maxScreenError pixels (1 by default), so switching between levels is not visible. This is on by default and needs no code. It applies to:

  • imported models (.gltf/.glb, .fbx, .obj, .ply, .usd*), including those attached with createVisual(geom, modelPath, ...) and those scattered with createModelScatter(),

  • meshes from shape RenderData, i.e. .agx files and OpenPLX visuals,

  • collision trimeshes without render data,

  • meshes from createMeshVisual() (again after each updateMeshVisual()).

Meshes that change every frame – terrain, wires, cables, deformables – get no LODs.

LOD 1 may differ from the mesh by maxError (0.5 % by default) of the mesh size, and each further LOD by twice the previous one, as it is drawn at about half the screen size. Within that error each LOD aims for reduction (0.4 by default) of the triangles of the one before it; meshes with much fine detail, such as tire treads, keep more. The LODs only add triangle lists that reuse the original vertices, so normals, texture coordinates and materials are unchanged. The simplification first preserves normal/texture seams, and gives up normal seams only for a level it cannot otherwise reach (flat shaded CAD meshes are seams everywhere); texture seams are always kept. It also removes small disconnected parts, such as bolts, that would be smaller than the allowed error. A level is skipped when it would not save at least 15 % of the triangles of the previous one, and the chain ends when the error a level needs grows faster than that. On a 1x1 km test scene with about 3600 trees, LODs cut the frame time by about a third.

What happens at load time. Loading itself is not slowed down: the mesh is drawn at full detail right away, while a background thread simplifies a copy of it, and the LODs are put in place before a later frame. On one CPU thread this takes about a second per million triangles (the 1.5 million triangles of wheel_loader_WA475.agx take 1-1.5 s). The results are cached:

  • in memory, so the same mesh loaded again in the session (for example many instances of a model) is simplified once,

  • on disk, in MeshLodCache in the agxRender cache directory, so the next run reads the LODs instead of computing them.

The cache is keyed by the mesh content (vertices, normals, triangles, material ranges) and the LOD settings, not by file name. The same mesh therefore hits the cache whether it comes from a glTF file, an .agx file, an OpenPLX model or a mesh built in a script, and a changed mesh simply gets a new entry. Cache files only hold the LOD triangle lists (about 11 MB for wheel_loader_WA475.agx). The cache is not cleaned up automatically; it is safe to delete the directory at any time.

The settings apply to meshes created after they are set, so set them before building the scene:

settings = agxRender.getMeshLodSettings()
settings.enabled = True          # False: no LODs for meshes created from now on
settings.minTriangles = 8000     # smaller meshes get no LODs
settings.maxLevels = 5           # LODs in addition to the original, 1-8
settings.reduction = 0.4         # triangle fraction each LOD aims for, relative to the previous one
settings.maxError = 0.005        # allowed error of LOD 1, relative to the mesh size; doubles per level
settings.maxScreenError = 1.0    # largest LOD error on screen, in pixels (applies immediately)
settings.useDiskCache = True
settings.cacheDirectory = ""     # "" = the per-user cache directory above
settings.sensorViewLod = False   # see below
assert agxRender.setMeshLodSettings(settings)   # False if a value is out of range

# Number of meshes still being simplified (e.g. to wait before measuring frame times):
agxRender.getPendingMeshLodCount()

Measuring the effect. getRenderStats() returns the main view’s visible mesh objects and their triangle count in the last rendered frame, both as drawn and at full detail; the stats window shows the same numbers (“Visible objects”, “Triangles: submitted / full detail”). Only objects passing frustum culling are counted, and shadow maps, camera sensors, grass, particles and GPU wires are not included:

stats = agxRender.getRenderStats()
print(f"{stats.visibleObjects} objects, {stats.trianglesSubmitted} of "
      f"{stats.trianglesFullDetail} triangles drawn")

For nine wheel_loader_WA475.agx machines (27.7 million triangles at full detail), LODs reduced the triangles drawn to 3.3 million, and the frame rate from 165 to 530 frames/s, with the camera 120 m away; at 30 m they drew 5.0 million triangles at 376 instead of 152 frames/s.

Camera sensors. The renderer picks each object’s LOD for the main camera. Camera sensors (agxSensor cameras rendered by agxRender, and the fisheye camera) instead draw every mesh at full detail by default, so their color and depth output does not depend on where the main camera happens to be. With sensorViewLod = True a sensor picks LODs from its own view, like the main camera does. That is faster, but depth is then only as exact as the LOD: thin parts may disappear at coarse levels. For a wheel loader 10 m from a depth camera the mean depth error was below a millimeter, but a few pixels were off by more than a meter where a thin part was dropped.

46.4.6. Tire deformation

Tire models with a compliant tread (agxVehicle.GTire, agxModel.TwoBodyTire) let the rigid tire shape sink into the ground by the tire deflection, and a rigid tire visual sinks with it. setTireDeformation() makes the visual flatten against the ground instead: every rendered frame, the geometries touched by the tire’s collision geometry are sampled with rays from the wheel center through the tread, and the tread is pulled in to where the rays hit them. Bumps, curbs and pot holes under the tire are followed, and the sidewalls bulge out where the tread is pushed in. Lower inflation pressure gives a larger deflection, and so a flatter tire.

settings = agxRender.TireDeformationSettings()   # tire dimensions are measured from the mesh
for tire in tires:                                 # agxVehicle.GTire
    visual = agxRender.findVisual(tire_visual_geometry(tire))
    agxRender.setTireDeformation(visual, tire.getTireBody().getGeometries()[0], settings)
...
agxRender.getTireDeflection(visual)               # largest deflection in the last frame, m

The visual can be on any body following the wheel (the OpenPLX VolvoEX90 has its tire visuals on the rims); only its frame is used. The mesh is skinned on the GPU with a ring of bones (one in the sidewall and one in the tread per sector, sectors = 72 by default), so the cost does not depend on the mesh size: for the four 15,000-vertex tires of gtire_deformation.py about 0.6 ms per frame. setEnableTireDeformation() switches it off and on, removeTireDeformation() restores the mesh, and calling setTireDeformation() again replaces the earlier deformation of that visual. Nothing deforms while the contact geometry has no contacts. setTireDeformation() returns False for an unknown visual, a null geometry or a setting out of range.

Table 46.1 TireDeformationSettings

Field

Default

Explanation

axis

(0, 0, 0)

Wheel rotation axis in the visual’s local frame. Zero: the axis along which the mesh is thinnest. The wheel center is the center of the mesh bounds

outerRadius

0

Tread radius. 0: the largest distance of a mesh vertex from the axis

rimRadius

0

Bead seat radius; the tire does not deform inside it. 0: the smallest distance of a mesh vertex from the axis

sectors

72

Number of sectors (bone pairs) around the tire, in [8, 255]. More follow narrow obstacles more closely

lateralSamples

3

Rays across the tread width per sector, in [1, 8]

sidewallBulge

0.35

Lateral bulge of each sidewall per meter of deflection (>= 0)

transitionAngle

0.25

Angle (radians) over which the deflection fades out beyond the contact patch (>= 0)

maxDeflection

0

Largest deflection in meters. 0: 75% of the sidewall height (outerRadius - rimRadius)

The visual’s own mesh is deformed (shape RenderData, i.e. OpenPLX visuals and .agx files, or the collision shape); models attached with attachModel() are not. The visual gets its own copy of the mesh, so other visuals sharing the same RenderData are not affected. A sector deflects as much as its most deflected ray across the tread, so an obstacle under one edge of the tread pushes in the whole width.

../_images/agxrender_tire_deformation.jpg

Fig. 46.3 The front left GTire of the VolvoEX90 at 2.9 bar: the tread is flat on the ground instead of sinking into it (gtire_deformation.py).

46.5. Materials and lighting

46.5.1. The Material object

For anything beyond a flat color, create an agxRender.Material and apply it to one or more visuals. Materials are shared by reference: calling a setter on the Material updates every visual it has been applied to via propagate()-linked assignment.

chrome = agxRender.Material("Chrome")
chrome.setBaseColor(agx.Vec4f(0.9, 0.9, 0.95, 1.0))
chrome.setRoughness(0.02)
chrome.setMetalness(1.0)

agxRender.applyMaterial(visual_a, chrome)
agxRender.applyMaterial(visual_b, chrome)

chrome.setRoughness(0.3)   # both visual_a and visual_b pick up the change
chrome.propagate()         # (implicit on every setter; explicit call rarely needed)

Important

Calling a free-function setter directly on a VisualHandle (e.g. agxRender.setBaseColor(visual_a, ...)) detaches that visual from its shared material – further changes to the Material object no longer affect it. Use the free functions for one-off per-visual tweaks, and the Material object when several visuals should track the same look.

Textures are set by file path; a packed occlusion/roughness/metalness map (Polyhaven’s _arm convention) can be assigned in one call:

rusty_metal = agxRender.Material("RustyMetal")
rusty_metal.setBaseColorTexture("materials/rusty_metal_diff.jpg")
rusty_metal.setNormalTexture("materials/rusty_metal_nor_gl.jpg")
rusty_metal.setSurfaceTexture("materials/rusty_metal_arm.jpg")
rusty_metal.setTextureScale(4.0, 4.0)   # tile the texture 4x across the surface

A Material can also be loaded wholesale from a file: a Polyhaven-style .zip archive (diffuse/normal/ARM textures extracted automatically) or a single image (applied as the base-color texture):

gravel = agxRender.Material.fromFile("materials/rocky_terrain_02_1k.zip", "Gravel")
agxRender.applyMaterial(terrain_surface_visual, gravel)

setMaterial(handle, path) loads the same files (and .usda) into one visual, without a shared Material. It returns False and logs a warning for files it cannot load. Use Material.fromFile() when several visuals share a texture pack or you want to edit it later.

A small tiling texture repeated over a large surface shows a visible grid. Two tools hide it:

# Up close: rebuild all maps into a larger, non-repeating tile (1k -> 4k by default).
gravel.makeNonRepeating()      # or pass agxRender.TextureSynthesisOptions()

# From a distance: darker/warmer world-space patches, baked into the vertex colors.
variation = agxRender.ColorVariationSettings()
variation.amplitude = 0.3      # how much darker the darkest patches are, 0..1
variation.featureSize = 25.0   # typical patch size, meters
agxRender.setColorVariation(terrain_surface_visual, variation)

Material.makeNonRepeating() assembles every map (base color, normal, surface, roughness, metalness, emissive) from randomly shifted and mirrored patches of the original, with the same layout for all maps, and divides the texture scale by the same factor so texels keep their world size. The sources must tile seamlessly. TextureSynthesisOptions sets the output size (tiles = 4 source textures wide, at most maxSize = 8192 pixels), patchSize (0.5 of the source), seamWidth (0.07), seamWobble (0.35), mirror (True; disable it for textures with writing or a clear direction) and seed. The results are cached as PNG files in nonrepeating in the agxRender cache directory, so only the first call per texture takes time – about a second for a 1k texture set. It returns False if the material has no readable texture.

setColorVariation() multiplies a visual’s color by a pattern of the world position, taken at the vertex positions when the mesh is built, so the detail follows the mesh resolution. tint (0.4) shifts the patches toward a warmer, drier color, and visuals with the same seed get a continuous pattern across their borders (e.g. a terrain and the ground mesh around it). amplitude = 0 removes the variation. See cat_d3_worksite_scenario.py.

Three ready-made presets cover common “hero” materials without hand-tuning PBR parameters:

agxRender.applyGlassMaterial(window_visual)
agxRender.applyCarPaintMaterial(body_visual, agx.Vec4f(0.8, 0.0, 0.0, 1.0), 0.1)  # clear-coat roughness
agxRender.applyChromeMaterial(bumper_visual)
../_images/agxrender_material_gallery.jpg

Fig. 46.4 Metals, clear coat paints, glass and gems, roughness sweeps, emissive, animated and textured materials, tagged with 3D labels (material_color_demo.py).

46.5.2. Wireframe overlays

Any visual can get a wireframe drawn on top of its surface – or instead of it. The overlay follows the visual as it moves, as an attached model animates, and as a terrain/height field deforms:

agxRender.setWireframe(visual, True, agx.Vec4f(0.0, 1.0, 0.4, 1.0))

settings = agxRender.WireframeSettings()
settings.enabled = True
settings.color = agx.Vec4f(0.2, 0.8, 1.0, 1.0)
settings.intensity = 4.0        # above the bloom threshold, the lines glow
settings.lineWidth = 1.5        # pixels
settings.hideDiagonals = True   # draw a quad grid as a grid, not as triangles (default)
settings.fadeDistance = 50.0    # fade the lines out towards 50 m from the camera
settings.hideSurface = False    # True: draw only the wireframe (no surface, no shadow)
agxRender.setWireframe(visual, settings)
../_images/agxrender_wireframe_overlay.jpg

Fig. 46.5 Wireframe overlays on the tires of a clay-style wheel loader (clay_studio_wheel_loader.py).

The overlay is not shown in path tracing mode or in camera sensor images. This is independent of the w key, which switches the whole view to WickedEngine’s wireframe mode.

46.5.3. Lighting

agxRender creates a default sun (directional light) automatically. Adjust it, replace it, or build a fully custom lighting rig:

sun = agxRender.getDefaultSunLight()
agxRender.setLightColor(sun, agx.Vec4f(1.0, 0.95, 0.85, 1.0))
agxRender.setLightIntensity(sun, 3.0)
agxRender.setLightDirection(sun, agx.Vec3f(-0.3, -0.5, -1.0))

# Or start from a clean slate:
agxRender.removeDefaultLighting()
key_light = agxRender.createSpotLight(
    agx.Vec3f(2.0, -2.0, 3.0),       # position
    agx.Vec3f(-1.0, 1.0, -1.0),      # direction
    agx.Vec4f(1.0, 1.0, 1.0, 1.0),   # color
    8.0,                             # intensity
    15.0,                            # range
)

createPointLight(), createDirectionalLight() and createRectangularLight() work the same way. Every light can be changed after creation (setLightPosition, setLightDirection, setLightColor, setLightIntensity, setLightRange, and the matching getters) and removed with destroyLight(handle) or destroyAllLights(). While a session is running, Shift+L prints the current sun direction as a ready-to-paste setLightDirection() snippet – handy after rotating the sun interactively with Ctrl+L + left-drag. See data/python_agxrender/light_show.py for a scene using many lights.

../_images/agxrender_lights.jpg

Fig. 46.6 36 moving point lights (light_show.py, scene 1).

For image-based lighting (reflections and ambient light sourced from a photograph rather than analytic lights), set an equirectangular HDR/EXR environment map:

agxRender.setEnvironmentMap("hdri/studio_small_08_4k.hdr")
agxRender.setEnvironmentMapIntensity(0.6)
../_images/agxrender_environment_map.jpg

Fig. 46.7 An HDR environment map providing lighting, reflections and background (environmentmapping.py).

Model and environment-map paths are resolved through the AGX environment’s file paths, so files shipped with AGX are found regardless of the current working directory.

46.5.4. Background color

setBackgroundColor() replaces the visible sky with a uniform color, a vertical gradient, or a four-corner gradient. Only pixels where no geometry is rendered are affected – lighting and reflections from the environment map or sky are unchanged – and the color is written after tone mapping, so it appears on screen and in captured images exactly as specified:

agxRender.setBackgroundColor(agx.Vec4f(0.1, 0.1, 0.12, 1.0))                 # uniform
agxRender.setBackgroundColor(agx.Vec4f(0.05, 0.07, 0.15, 1.0),               # top
                          agx.Vec4f(0.35, 0.30, 0.30, 1.0))               # bottom
agxRender.resetBackground()   # show the sky/environment map again

Camera sensor images are not affected. See data/python_agxrender/background_color.py.

46.5.5. Weather and atmosphere

Fog, rain, wind, a physically based sky, and volumetric clouds are each configured with a settings struct. The setters validate their input and return False (leaving the effect unchanged) for invalid values:

fog = agxRender.FogSettings()
fog.enabled = True
fog.startDistance = 20.0     # meters from the camera
fog.density = 0.02           # 1/m
fog.heightEnabled = True     # denser near the ground (world Z)
fog.heightStart = 0.5
fog.heightEnd = 4.0
agxRender.setFogSettings(fog)

rain = agxRender.RainSettings()
rain.enabled = True
rain.amount = 0.3            # 0..1
agxRender.setRainSettings(rain)

wind = agxRender.WindSettings()
wind.enabled = True
wind.direction = agx.Vec3f(1.0, 0.3, 0.0)   # also drifts the rain
wind.speed = 0.5
agxRender.setWindSettings(wind)

atmosphere = agxRender.AtmosphereSettings()
atmosphere.realisticSky = True
atmosphere.aerialPerspective = True
agxRender.setAtmosphereSettings(atmosphere)

clouds = agxRender.VolumetricCloudSettings()
clouds.enabled = True
clouds.coverage = 0.6
clouds.castShadow = True
agxRender.setVolumetricCloudSettings(clouds)
../_images/agxrender_weather.jpg

Fig. 46.8 Rain, wind, realistic sky and volumetric clouds (weather_effects.py).

With realisticSky = False (the default), the sky is a gradient from skyHorizonColor to skyZenithColor (linear RGB). It is seen behind the scene and also lights it, like an environment map. ambientColor adds ambient light to all surfaces. For the realistic sky, highQuality enables its high-quality mode and aerialPerspectiveScale scales the distance haze.

setEnableFog()/setEnableRain() toggle fog and rain while keeping their parameters. All of these can be called before the session starts or while it is running. Wind, atmosphere and cloud settings are reset to their defaults on a scene switch/reload, so set them from the scene’s build function. See data/python_agxrender/fog.py and data/python_agxrender/weather_effects.py.

The same effects, plus the sun direction/intensity and the environment-map intensity, can be adjusted interactively in the Render Effects window (F6), grouped in sections that fold and unfold when their header is clicked (Environment starts unfolded). Its Save Effects button writes them to render_effects.json, which is loaded at startup (from the AGX resource path, or from the file given with --renderEffects).

46.5.6. Ocean

setOceanSettings() turns on an animated FFT ocean: one infinite water surface at the height waterHeight (world Z), with reflections, refraction and underwater fog. It is visual only; to float objects on its waves with AGX hydrodynamics, see Floating on the ocean.

ocean = agxRender.OceanSettings()
ocean.enabled = True
ocean.waterHeight = 0.0
ocean.waveAmplitude = 120.0                         # calm: crests up to ~1.2 m
ocean.windDirection = agx.Vec2f(0.6, 0.8)
ocean.waterColor = agx.Vec4f(0.02, 0.07, 0.08, 0.1) # alpha: water fog density per meter
ocean.extinctionColor = agx.Vec4f(0.9, 0.3, 0.2, 1.0)
agxRender.setOceanSettings(ocean)

surface = agxRender.getOceanSurfacePosition(agx.Vec3(x, y, 0.0))   # the moving wave surface
agxRender.addWaterRipple(agx.Vec3(x, y, 0.0))

Things to know when tuning it:

  • Wave heights grow with the square root of waveAmplitude. The default, 1000, is a rough sea (crests up to ~3.5 m); 120 is calm (crests up to ~1.2 m).

  • The water surface continues under the land, so wave crests poke through low, flat ground near the water line. Keep the shores a bit higher than the crests, or lower waveAmplitude.

  • Seen from below the surface, the fog grows with the water depth above each surface seen, with waterColor’s alpha as the density per meter: 0.25 hides a 15 m deep seabed completely, and ~0.1 reads as clear water. extinctionColor behaves as the absorption per color channel (sea water absorbs red most, e.g. (0.9, 0.3, 0.2)).

  • planarReflections (default on) lets the water reflect the terrain and vehicles, not only the sky, at the cost of one extra scene render per frame.

  • getOceanSurfacePosition() is read back from the GPU, so it lags the rendered waves by a few frames.

  • Surfel GI only covers a radius around the camera, and through clear water it shows up as a lighter disc on the seabed; turn it off (setEnableSurfelGI(False)) in underwater scenes.

The ocean settings are reset to their defaults on a scene switch/reload. See data/python_agxrender/submarine_ocean.py and dune_buggy_scenario.py.

46.5.7. Floating on the ocean

agxRender.OceanWaterPatch brings the rendered waves into the simulation. It is a step event listener that owns (or is given) an agxCollide.HeightField, and before every collision detection it moves the height field and gives each vertex the height of the ocean surface above it. Used as the water of an agxModel.WindAndWaterController, objects get buoyancy and drag from the waves that are drawn:

water_material = agx.Material("sea_water")
water_material.getBulkMaterial().setDensity(1025.0)
controller = agxModel.WindAndWaterController()
sim.add(controller)

patch = agxRender.OceanWaterPatch(ship_body, 0.5, 2.0)   # cell size, margin (meters)
water = patch.getWaterGeometry()
water.setMaterial(water_material)
sim.add(water)
sim.add(patch)
controller.addWater(water)
  • Give the patch a rigid body, a geometry or an assembly to follow. It is made large enough to cover the target’s bounding sphere plus the margin, so the target stays covered in any orientation, and it is moved with the target every step. The patch size is fixed at creation: for an assembly whose parts move apart, add that to the margin.

  • Or give it a height field you place yourself (OceanWaterPatch(heightField)), e.g. from your own PRE_COLLIDE listener added to the simulation before the patch. Its geometry may only be rotated about the world Z axis.

  • The vertices sit on a world grid of the cell size, so the water does not shimmer as the patch moves. A smaller cell resolves shorter waves, at the cost of more vertices ((2 * (radius + margin) / cellSize)^2).

  • The heights come from the wave data the renderer already copies to the CPU for getOceanSurfacePosition(): a few bilinear lookups per vertex, no extra GPU work. They are corrected for the sideways motion of choppy waves, so a vertex gets the height drawn above it. They lag the rendered waves by one or two frames and update once per rendered frame. Without a viewer, or with the ocean disabled, the water is flat at waterHeight.

  • Hydrodynamics uses every water a geometry overlaps, so overlapping patches would double the buoyancy. Patches that follow a target keep each floater in its own patch: when added to a simulation, a patch disables its water for the geometries of the other patches’ targets (and theirs for its target), and enables it again when removed. Objects without a patch of their own get water from any patch they are in.

  • The ocean’s animation speed is an artistic parameter, not physical wave dispersion. Keep timeScale low enough that the wave periods look (and act) like the sea state you want; fast waves near a light hull’s heave period make it bounce. ship_in_ocean.py uses waveAmplitude = 1660, patchLength = 60 and timeScale = 0.1 (a rough sea, crests of a few meters).

  • Show the patches with the debug rendering (g).

See data/python_agxrender/ship_in_ocean.py.

46.5.8. Exposure, bloom and depth of field

agxRender/RenderSettingsAPI.h exposes the most commonly scripted post-processing settings of the main view – the same settings as in the F1 settings window and graphics_settings.json:

agxRender.setEnableEyeAdaption(False)  # fixed exposure, e.g. for an intentionally dark scene
agxRender.setExposure(1.0)
agxRender.setEnableBloom(True)
agxRender.setBloomThreshold(1.2)        # lower = more of the image glows

dof = agxRender.DepthOfFieldSettings()
dof.enabled = True
dof.autoFocus = True                 # keep the orbit/follow target in focus
dof.aperture = 1.0
dof.strength = 10.0
agxRender.setDepthOfField(dof)

With autoFocus = False, focusDistance (meters) sets the focal plane instead. A setter called while a session is running takes effect immediately; called before the session starts, the value is applied after graphics_settings.json has been loaded, so it overrides the file. The values stay in effect across scene switches.

Ray-traced global illumination is switched with setEnableRaytracedDiffuse(), setEnableSurfelGI() and setEnableDDGI() (each with a matching getter). All three need a GPU with hardware ray tracing and are ignored otherwise; isRayTracingSupported() tells whether it is available, but only once the viewer has started (it returns False in a build_scene function). Surfel GI resolves at one sample per pixel, so enabling it also turns off MSAA for the main view.

DDGI places a grid of 32 x 8 x 32 light probes over the bounds of the whole scene. In a scene with a large backdrop or a long road the probes end up tens or hundreds of meters apart and give no visible indirect light around the machines. setDDGIBounds(min, max) puts the grid in a world-space box around the area that matters instead; clearDDGIBounds() goes back to the scene bounds, and ok, lo, hi = getDDGIBounds() reads the box back. The box is cleared on a scene switch/reload.

agxRender.setEnableDDGI(True)
agxRender.setDDGIBounds(agx.Vec3(-30, -30, -3), agx.Vec3(30, 30, 12))  # probes ~2 m apart

Shadows are switched with setEnableShadows(). setShadowMethod() selects ShadowMethod.SHADOW_MAPS (default) or ShadowMethod.RAY_TRACED; ray traced shadows need a GPU with hardware ray tracing, and shadow maps are used otherwise. setShadowMapResolution() sets the maximum shadow map size of directional and spot lights (0, 128, 256, 512, 1024 (default), 2048 or 4096) and setShadowCubeMapResolution() the one of point lights (0, 128, 256 (default), 512, 1024 or 2048); both return False for any other value. Lights far away or covering little of the view get a smaller map. 0 turns those shadow maps off.

agxRender.setShadowMethod(agxRender.ShadowMethod.SHADOW_MAPS)
agxRender.setShadowMapResolution(4096)  # sharper sun shadows over a large site

The realistic sky (AtmosphereSettings.realisticSky) does not light the scene: without an environment map, surfaces in shadow get only AtmosphereSettings.ambientColor and what GI adds. Raise ambientColor for sky fill light.

Time-based effects – rain, wind, ocean waves, particle emitters, texture animation – run on simulation time: each rendered frame advances them by the simulated time elapsed since the previous one. A simulation that cannot keep up with real time shows them in the same slow motion, and they stand still while the simulation is paused or not stepped. Without a simulation they run on the wall clock. setEffectsAnimateWhilePaused(True) keeps them animating on the wall clock while the simulation is paused (e, setViewerSessionPaused()).

All other renderer settings (anti-aliasing, shadows, ambient occlusion, GI, tone mapping, …) are available in the F1 settings window, grouped in sections that fold and unfold when their header is clicked (Simulation and AGX Viz start unfolded). Its Save Settings button writes them back to the graphics_settings.json loaded at startup – found on the AGX resource path or in the current directory, or given explicitly with --graphicsSettings.

46.6. Camera control

46.6.1. Reading and setting the camera pose

CameraData round-trips the full interactive camera state (eye, look-at center, up vector, and clip planes) – the agxRender analog of agxOSG::ExampleApplication::CameraData:

data = agxRender.getCameraData()
data.eye = agx.Vec3(6.0, -6.0, 4.0)
data.center = agx.Vec3(0.0, 0.0, 0.5)
data.up = agx.Vec3(0.0, 0.0, 1.0)
agxRender.applyCameraData(data)

While a viewer session is running, press c to print the current camera pose as a ready-to-paste CameraData snippet in exactly this shape – the fastest way to capture a good framing interactively and bake it into a script.

46.6.2. Following a moving object

attachCameraTo() mounts the camera at a fixed offset relative to a moving agx::Frame/RigidBody/Geometry, overriding manual mouse/keyboard control until detachCamera() is called:

follow = agxRender.CameraFollowOptions()
follow.relativePosition = agx.Vec3(-3.0, 0.0, 1.5)       # behind and above, in vehicle space
follow.relativeLookDirection = agx.Vec3(1.0, 0.0, -0.15) # forward, slightly down
follow.smooth = True
follow.positionSmoothTime = 0.3
follow.rotationSmoothTime = 0.3
agxRender.attachCameraTo(vehicle_body, follow)

# later:
agxRender.detachCamera()

With smooth = False (default) the camera is a rigid mount – exactly matching the target’s transform every frame, like a dashboard camera. With smooth = True it eases toward the target pose, like a chase camera in a game. Both positionSmoothTime and rotationSmoothTime are expressed in simulation seconds, so the follow motion’s feel is independent of how fast the simulation runs relative to real time.

allowUserControl = True keeps orbit, zoom, pan and fly input active while following; the camera then keeps chasing the target from the viewpoint the user chose. Picking (Shift + left-click) works with or without it.

In the viewer, Ctrl+M + left-click follows the clicked geometry of a kinematic or dynamic body this way (smooth, allowUserControl, starting from the current view), replacing any attached camera. A click on anything else – a static or body-less geometry, or nothing – detaches the camera.

46.6.3. Keyframed camera paths

For cinematic fly-throughs, build a path from keyframes and play it back – the same feature the in-viewer F5 “Camera Path” window edits interactively:

def keyframe(eye, center, hold=0.5, travel=3.0):
    kf = agxRender.CameraPathKeyframe()
    kf.eye, kf.center, kf.hold, kf.travel = eye, center, hold, travel
    kf.easing = agxRender.CameraPathEasing.EASE_IN_OUT
    return kf

agxRender.clearCameraPath()
agxRender.addCameraPathKeyframe(keyframe(agx.Vec3(-6, -6, 3), agx.Vec3(-2.5, 0, 1)))
agxRender.addCameraPathKeyframe(keyframe(agx.Vec3(0, -6, 4), agx.Vec3(0, 0, 1)))
agxRender.addCameraPathKeyframe(keyframe(agx.Vec3(6, -6, 3), agx.Vec3(2.5, 0, 1)))

agxRender.setCameraPathLooping(True)
agxRender.playCameraPath()

# Persist/restore the same JSON the F5 window's Save/Load buttons write:
agxRender.saveCameraPath("camera_path.json")
agxRender.loadCameraPath("camera_path.json")

Positions are interpolated with a Catmull-Rom spline through the keyframes, so a path with three or more points has a smooth flight direction through the middle ones. Any mouse button press stops playback; resume it with the Play button in the F5 window or with playCameraPath(). stopCameraPath(), isCameraPathPlaying() and getCameraPathKeyframeCount() complete the scripting API.

46.7. Debug visualization

46.7.1. Debug rendering of physics internals

AGX’s built-in debug renderer (constraints, contacts, bounding volumes, etc.) is available exactly as in agxOSG, driven by the same agxSDK::RenderFlags bitmask described in Debug rendering:

import agxSDK

agxRender.attachDebugRenderer(sim)
agxRender.setEnableDebugRendering(True)
agxRender.setDebugRenderFlags(
    agxSDK.RENDER_DEFAULT | agxSDK.RENDER_CONTACTS | agxSDK.RENDER_CONSTRAINTS
)

In the viewer, g toggles debug rendering on/off at runtime (Shift+``G`` toggles the ordinary scene visuals instead, letting you isolate the debug view).

setDebugWireframeOnly(True) draws all debug shapes as wireframe only, with no solid fill; set it before attachDebugRenderer(), since the fill of already created shapes only updates when their material is next reapplied. Heightfield and trimesh debug shapes are always drawn as wireframe. detachDebugRenderer() removes the debug renderer again.

46.7.2. Ad-hoc debug shapes

agxRender/DebugDraw.h draws simple primitives directly, independent of the AGX debug renderer above – useful for visualizing an algorithm’s internal state (a sensor’s field of view, a planned path, a contact normal) from a step listener:

class ShowContactNormals(agxSDK.StepEventListener):
    def __init__(self):
        super().__init__(agxSDK.StepEventListener.POST_STEP)

    def post(self, t):
        for contact in sim.getSpace().getGeometryContacts():
            for point in contact.points():
                agxRender.drawArrow(
                    point.point(),
                    point.point() + point.normal() * 0.3,
                    agx.Vec4f(1.0, 1.0, 0.0, 1.0),
                )

Per-frame shapes (drawLine, drawSphere, drawBox, drawArrow, drawPoint, drawFrame) are cleared automatically after each render – call them again every step to keep them visible. Persistent variants (drawStaticLine, drawStaticSphere, …) stay until explicitly removed with clearDrawStatics() – useful for a fixed marker or reference grid that shouldn’t need to be redrawn every frame.

46.7.3. Coordinate-axes gizmos

createAxes() drops a small X (red) / Y (green) / Z (blue) gizmo that continuously tracks a frame, body, geometry or constraint – handy for confirming a sensor’s mounting orientation at a glance:

agxRender.createAxes(lidar.getFrame(), 0.5)   # second argument: scale
axes = agxRender.createAxes(camera_body, 0.3)

setAxesVisible(handle, visible) hides a gizmo, and destroyAxes(handle) / destroyAllAxes() remove one or all of them.

46.8. On-screen HUD

HudAPI places text overlays and clickable buttons in normalized screen space (0..1, origin top-left) – useful for live telemetry (speed, forces, sensor readings) and simple controls without a full GUI:

fps_label = agxRender.createHudText("", agx.Vec2f(0.02, 0.02), 18.0, agx.Vec4f(1, 1, 1, 1))

class UpdateHud(agxSDK.StepEventListener):
    def post(self, t):
        agxRender.setHudText(fps_label, f"t = {t:6.2f} s")

The size is the font size in pixels at a 720 px tall window and scales with the window height, so text keeps its layout relative to the normalized positions at any window size. A label can be restyled or moved later with setHudTextColor(), setHudTextSize() and setHudTextPosition(), and removed with destroyHudText(). destroyAllHudElements() removes all HUD text and all HUD buttons. The HUD is also cleared on every scene switch or reload, like labels. HUD text and buttons are included in image/video capture.

46.8.1. HUD buttons

createHudButton(label, normalizedPos, normalizedSize, size=18, textColor=white, backgroundColor=(0.08, 0.08, 0.08, 0.7)) creates a filled rectangle with a centered label. normalizedPos is its top-left corner and normalizedSize its width and height, both in normalized screen coordinates; size is the font size, as for HUD text. The button is drawn brighter while the mouse hovers it.

There are no callbacks: a left click (counted on press) increments the button’s click count, and the script polls getHudButtonClickCount(), typically from a StepEventListener, and reacts when the count changes. A click on a button never moves the camera. Polling from a step listener is thread safe; note that a POST_STEP listener does not run while the simulation is paused, but clicks keep accumulating and are seen on the next step.

class Buttons(agxSDK.StepEventListener):
    ACTIVE = agx.Vec4f(0.78, 0.52, 0.03, 0.9)
    DIM = agx.Vec4f(0.08, 0.08, 0.08, 0.62)

    def __init__(self):
        super().__init__(agxSDK.StepEventListener.POST_STEP)
        self.button = agxRender.createHudButton(
            "LIGHTS: OFF", agx.Vec2f(0.83, 0.03), agx.Vec2f(0.15, 0.05), 15.0)
        self.clicks = 0
        self.on = False

    def post(self, t):
        count = agxRender.getHudButtonClickCount(self.button)
        if count != self.clicks:
            self.clicks = count
            self.on = not self.on
            agxRender.setHudButtonLabel(self.button, "LIGHTS: ON" if self.on else "LIGHTS: OFF")
            agxRender.setHudButtonColors(self.button, agx.Vec4f(1, 1, 1, 1),
                                         self.ACTIVE if self.on else self.DIM)

setHudButtonLabel() and setHudButtonColors() change a button after creation (e.g. to highlight the selected button of a group), and destroyHudButton() removes it. Position, size and font size are fixed at creation; to move a button, remove it and create a new one. Buttons are drawn below HUD text, so a button with an empty label works as a translucent backdrop panel behind a block of text. createHudButton() is overloaded in Python, so its arguments are passed by position. See wheelloader_quarry_scenario.py for a complete example with a group of mode buttons.

setHudVisible(False) hides the whole HUD, all text and all buttons (hidden buttons take no clicks), and setHudVisible(True) shows it again; getHudVisible() returns the current state. The elements keep their state and can be updated while hidden. Camera previews are not part of the HUD and stay visible. Loading another scene shows the HUD again.

46.9. 3D labels

LabelAPI tags points in the world with text. A label is anchored at a world position or follows an agx::Frame, agx::RigidBody or agxCollide::Geometry (the anchor is then given in its local coordinates). The text is drawn on top of the scene at a constant screen size, optionally on a panel and connected to the anchor by a lead line:

opts = agxRender.LabelOptions()
opts.font = "resources/fonts/Inter-600.ttf"    # relative to the resource path, "" = default
opts.size = 16.0                               # pixels at a 720 px tall window
opts.color = agx.Vec4f(1.0, 0.85, 0.3, 1.0)
opts.screenOffset = agx.Vec2f(40.0, -50.0)     # text placement relative to the anchor
label = agxRender.createLabel("Bucket", bucket_body, agx.Vec3(0, 0, 0.5), opts)

# Later, e.g. from a StepEventListener:
agxRender.setLabelText(label, f"load {mass:.0f} kg")
agxRender.setLabelColor(label, agx.Vec4f(1, 0, 0, 1))

screenOffset places the text relative to the projected anchor: to the right for x > 0, to the left for x < 0, centered above or below for x == 0, and centered on the anchor (without lead line) for (0, 0). backgroundColor with alpha 0 removes the panel (the text then gets a drop shadow). The lead line, with a dot at the anchor, is controlled with leadLine, leadLineColor and leadLineWidth. createLabel() returns an invalid handle if the font cannot be found, and setLabelFont() / setLabelOptions() then return False and keep the old font; getLabelText() and getLabelOptions() read a label back. Labels are changed with setLabelText(), setLabelColor(), setLabelSize(), setLabelFont(), setLabelVisible() and setLabelOptions(), moved with setLabelPosition() / attachLabelTo(), and removed with destroyLabel() / destroyAllLabels(). A label whose frame is destroyed is hidden. Labels are cleared on scene switches and are included in image/video capture. See material_color_demo.py.

46.10. Terrain visualization

agxRender.createTerrainRenderer() is the agxRender replacement for agxOSG::TerrainVoxelRenderer: it creates the heightfield surface mesh and returns a TerrainRendererHandle used to enable any combination of diagnostic overlays on top of it – height/compaction color gradients, a wireframe grid, voxel mass/bounding-box overlays, a velocity field, and material-zone coloring.

terrain_viz = agxRender.createTerrainRenderer(terrain)

height_opts = agxRender.TerrainHeightVizOptions()
height_opts.enabled = True
height_opts.heightRange = agx.RangeReal(-1.2, 1.2)
agxRender.setTerrainHeightVisualization(terrain_viz, height_opts)

wireframe_opts = agxRender.TerrainWireframeOverlayOptions()
wireframe_opts.enabled = True
wireframe_opts.gridStride = 2
wireframe_opts.colorFromActiveMode = True   # tint the grid using the height gradient above
agxRender.setTerrainWireframeOverlay(terrain_viz, wireframe_opts)
../_images/agxrender_terrain_height_gradient.jpg

Fig. 46.9 Height color gradient (terrain_visualization_gallery.py, scene 1).

../_images/agxrender_terrain_wireframe.jpg

Fig. 46.10 Wireframe grid overlay on a deforming terrain (terrain_visualization_gallery.py, scene 4).

Applying a material (e.g. one loaded from a texture ZIP, see above) colors the surface mesh with real PBR textures instead of a flat gradient:

gravel = agxRender.Material.fromFile("materials/rocky_terrain_02_1k.zip", "Gravel")
agxRender.applyMaterial(agxRender.getTerrainSurfaceMesh(terrain_viz), gravel)

(setTerrainVisualMaterial() is a different function: it takes an agxCollide::RenderMaterial, e.g. OpenPLX’s Terrain.visual_material.)

The remaining overlays follow the same pattern: setTerrainCompactionVisualization() (compaction color gradient), setEnableTerrainVoxelSolidMassVisualization() / setEnableTerrainVoxelFluidMassVisualization() / setEnableTerrainVoxelBoundingBoxVisualization() (voxel overlays), setTerrainVelocityFieldVisualization(), setEnableTerrainMaterialZoneVisualization() (color cells by terrain material) and setTerrainSoilParticleMeshVisualization() (draw soil particles as mesh instances, optionally with a custom model). setTerrainHeightFieldVisible(terrain_viz, False) hides the surface mesh while keeping the overlays, getTerrainSurfaceMesh() returns the surface’s VisualHandle (e.g. for setWireframe()), and findTerrainRenderer(terrain) / destroyTerrainRenderer() look up and remove a renderer.

For terrains that generate a lot of granular material (digging, bulldozing), particle upsampling renders several visually smaller particles for each simulated one, so the pile looks dense even though physics only tracks a coarse particle count. The terrain functions are thin wrappers around the general particle API (see Particle visualization) applied to the terrain’s soil particle system:

upsampling = agxRender.TerrainParticleUpsamplingOptions()   # alias of ParticleUpsamplingOptions
upsampling.enabled = True
upsampling.factor = 6
upsampling.tier = agxRender.ParticleUpsamplingTier.GPU
agxRender.setTerrainParticleUpsampling(terrain_viz, upsampling)

# Texture the soil particles with the terrain surface's own material:
agxRender.setTerrainParticleMaterialMode(terrain_viz, agxRender.ParticleMaterialMode.INHERIT_TERRAIN)

Instead of particles, the soil can be drawn as one continuous surface shaded with the terrain’s own material, setTerrainParticleSurface(terrain_viz, options) – see Particle surface.

46.10.1. Terrain pagers

For an agxTerrain::TerrainPager, the simplest option is agxRender.TerrainPagerRenderer, a StepEventListener that renders all of the pager’s tiles. With a backdrop it also draws the whole area the pager can page in, from a height field (typically the source geometry of the pager’s TerrainRasterizer), so the world is visible although only a few tiles are live. A tile gets its own full-resolution mesh once its heights change, e.g. under a wheel; that mesh follows the deformation while the tile is live and stays after it is unloaded, so tracks remain visible:

options = agxRender.TerrainPagerRendererOptions()
options.textureRepeat = 1.6        # meters per texture repeat (world-space UVs, no seams)
options.backdropTilesPerChunk = 3  # backdrop chunk size, in tiles
options.backdropSpacing = 1.2      # meters between backdrop vertices
renderer = agxRender.TerrainPagerRenderer(pager, options)
renderer.setMaterial(sand_material)
renderer.setBackdrop(rasterizer_source_geometry, agx.Vec2i(-33, -33), agx.Vec2i(33, 33))
sim.add(renderer)

The other options are updateInterval (simulation seconds between re-uploads of a deforming tile, default 0.25), maxUploadsPerStep (default 2), and textureWarp / textureWarpScale (a noise warp of the texture coordinates that breaks up the repeat pattern; 0 disables it). setBackdrop() covers tiles [tileMin, tileMax), can be called once, and needs the pager’s reference rotation to be identity (the default). setActiveTileMaterial() together with setShowActiveTiles(True) highlights the tiles that are currently loaded, and getNumActiveTiles(), getNumVisitedTiles() and getNumTileMeshes() report statistics. See dune_buggy_scenario.py, submarine_ocean.py and tutorial_vehicle_terrain_pager_wheel.py.

To use the terrain overlays and particle upsampling on paged tiles instead, create one terrain renderer per tile with createTerrainRenderer(terrain, keepAlive=False, tileMarginCells=0):

  • tileMarginCells (set it to TerrainPager.getTileSpecification().getTileMarginSize()) avoids rendering the overlap region shared between adjacent tiles twice.

  • With keepAlive=True the surface mesh stays visible, frozen, when the pager evicts the tile; eviction is detected automatically. Call reconnectTerrainRenderer() when the tile is loaded again (e.g. from the pager’s tile load callback) to resume live updates. detachTerrainRenderer() detaches a renderer explicitly, e.g. from the tile unload callback.

46.11. Vegetation: grass and scattered models

agxRender/VegetationAPI.h grows vegetation on the triangles of a visual’s mesh – typically the visual of a static height field, but any visual with a mesh works, including one built with createMeshVisual():

  • createGrass(surface, settings) grows GPU-simulated, camera-facing grass blades. Their look (texture atlas, material, blade shape) comes from a template .wiscene (resources/landscape/grass.wiscene by default), or from a single image with alpha (texturePath).

  • createModelScatter(surface, settings) scatters instances of a model file (.gltf, .glb, .obj, .fbx, .ply, .wiscene). All instances share the model’s GPU mesh and materials.

VegetationPlacement (settings.placement) decides where things grow: a world-height band (minHeight/maxHeight), the steepest slope (maxSlopeDeg, faded out over the last 5 degrees) and patchy coverage from a noise pattern (coverage, noiseScale). The same seed always gives the same result.

surface = agxRender.createVisual(height_field_geometry)

grass = agxRender.GrassSettings()
grass.density = 4.0          # blades per m^2 where the placement allows full growth
grass.lengthScale = 0.5      # the template blades are ~1.5 m tall
grass.viewDistance = 190.0   # only drawn within this distance of the camera
grass.placement.coverage = 0.85
agxRender.createGrass(surface, grass)

trees = agxRender.ModelScatterSettings()
trees.modelPath = "resources/tree1/Tree.fbx"
trees.density = 0.01         # instances per m^2
trees.minScale = 210.0       # Tree.fbx is in centimeters: 210-320 gives 8-12 m trees
trees.maxScale = 320.0
trees.sinkDepth = 0.2        # lowered into the ground to hide the base on slopes
trees.placement.minHeight = 4.0
trees.placement.maxSlopeDeg = 30.0
trees.impostorDistance = 150.0  # billboards beyond 150 m (0 = always the full model)
agxRender.createModelScatter(surface, trees)
../_images/agxrender_vegetation.jpg

Fig. 46.11 Grass and scattered Tree.fbx instances on a height field (vegetation_tree_hill.py).

Paths are located with agxIO::Environment (AGX_FILE_PATH), so scripts pass paths relative to the resource directories. Both functions return an invalid handle for invalid settings or a file that cannot be found. The vegetation is built on a later rendered frame, once the surface mesh exists, and is rebuilt if the surface visual is rebuilt; getVegetationCount(handle) returns the number of blades or instances once it is built. Remove vegetation with destroyVegetation(handle) or destroyAllVegetation(), which clearScene() also does. At most 4 million blades per grass and 50 000 instances per scatter are created.

Beyond impostorDistance, scattered instances are drawn as impostors: billboards of the model rendered from several directions, which makes large forests cheap. All scatters of a model share its impostors (and the distance last set), and at most 8 meshes in a scene can have impostors; further ones are drawn as models.

onePerTriangle = True places exactly one instance at the center of each surface triangle, without random rotation, and ignores density. A surface of small triangles at chosen points gives an exact layout, e.g. a grid.

Cluster LOD: setEnableScatterClusterLod(True, maxScreenError) gives the meshes of all scattered models a hierarchy of simplified clusters, and the GPU draws, per cluster, the coarsest version whose error stays below maxScreenError pixels (default 0.25; 0.25 keeps alpha tested foliage intact, 1 is faster). Distant instances then cost a few hundred triangles instead of the full model. It needs mesh shader support and turns mesh shaders on for the whole scene while enabled; without support it logs a warning and stays off. The first enable builds the hierarchies, which can take a second per detailed model. getEnableScatterClusterLod() and getScatterClusterLodError() return the current state. The viewer’s settings window (F1, Rendering) has a checkbox and a pixel error slider for it, and tutorial_forest_hill.py toggles it with l.

Other visuals get cluster LOD with VisualCreateOptions.clusterLod = True in createVisual(): the shape mesh and an attached model are drawn the same way, with the same pixel error. It only pays off for dense static meshes seen at a distance (scanned rocks, detailed CAD, many copies of a model). Terrain, deformable, cable, wire and createMeshVisual() visuals ignore it.

Some tips:

  • The placement rules only look at height, slope and noise. To keep vegetation off roads, paths or buildings, grow it on a separate mesh that only covers the allowed area, placed a few centimeters under the visible ground so it is never seen. Hiding that mesh with setVisualVisible(surface, False) does not work: it hides the vegetation on it too. car_test_ground.py does this for its grass verges and woods.

  • Check a model’s size before scattering it (agxViewer model.fbx prints it, see Viewing 3D model files). FBX files are often in centimeters, which minScale and maxScale have to compensate for.

  • Vegetation is meant for static surfaces; deformable terrain and TerrainPager are not supported yet.

See data/python_agxrender/vegetation_tree_hill.py, vegetation_meadow.py, car_test_ground.py and cluster_lod_helmets.py.

46.12. Particle visualization

Particle systems are rendered as GPU-instanced impostors once registered with agxRender.createVisual(particleSystem) (terrain soil particles are registered by the terrain visual). setEnableParticleGpuRendering(False) switches to one sphere entity per particle instead – slower, but fully PBR-shaded; the upsampling and material functions below only apply to the default GPU path.

agxRender/ParticleVizAPI.h configures any agx::ParticleSystem – a terrain’s soil particles or the output of an agx::ParticleEmitter alike. Each function registers the system for rendering if needed, so they can be called in any order.

46.12.1. Particle upsampling

Upsampling draws factor visually smaller, volume-conserving fine particles per simulated particle. Fine particles persist across frames and fade in/out (easeStepSize) instead of popping:

options = agxRender.ParticleUpsamplingOptions()
options.enabled = True
options.factor = 8
options.method = agxRender.ParticleUpsamplingMethod.PARTICLE_BOUND   # default
options.tier = agxRender.ParticleUpsamplingTier.GPU
agxRender.setParticleUpsampling(emitter_particle_system, options)
../_images/agxrender_particle_upsampling.jpg

Fig. 46.12 GPU particle upsampling (factor 100) with a custom particle material on terrain soil particles (clay_studio_wheel_loader.py, scene 2).

Two placement methods are available:

method

Behavior

PARTICLE_BOUND (default)

Each real particle owns factor fine particles, which follow the weighted motion of their owner and a few neighbors. Material at rest stays at rest and material moving rigidly (e.g. in a bucket) moves rigidly; fine particles are only created/removed together with their real particle.

VOXEL_GRID

The AGXUnreal/AGXUnity reference scheme: fine particles are counted into a world-aligned voxel mass grid rebuilt every step and advected by its averaged velocity, spawning and despawning as material crosses voxel boundaries. For a non-terrain particle system, the voxel size comes from nominalParticleRadius (0 = mean particle radius – set it explicitly for a size distribution).

Both methods run on either tier: CPU (unbounded, costs CPU time every step) or GPU (compute shaders, near-zero CPU cost, fixed capacity). The tier can be switched at runtime by calling setParticleUpsampling() again. getParticleUpsamplingStats(system) reports the update cost and the real/fine particle counts, which helps decide which tier suits a scene; for the GPU tier, droppedVoxelInserts/droppedSpawns greater than zero mean its fixed capacity is the limit.

46.12.2. Particle surface

setParticleSurface() (setTerrainParticleSurface() for a terrain’s soil) draws the particles as one continuous surface instead of separate particles. The surface is rebuilt on the GPU every physics step: every particle gets an anisotropic kernel from the distribution of its neighbours (flat soil reconstructs flat), the kernels are summed into a sparse field and marching cubes extracts the surface. It is drawn as an ordinary scene mesh, so it casts and receives shadows and takes part in ambient occlusion, TAA and reflections.

For a terrain, the surface is shaded with the terrain surface’s own material and texture placement, sampled triplanar so steep cut faces are not stretched. With textureFollowsSoil (default) the texture is carried by the particles: soil in a bucket keeps the pattern of the ground it was dug from instead of sliding through a fixed texture. A procedural clod relief (relief, reliefSize) and a cavity term (cavity) give it a granular look, and adhesion makes it meet the ground in a fillet instead of lying on it as a blob. Particles with fewer than minNeighbors neighbours (flying grains) are drawn as particles.

surface = agxRender.ParticleSurfaceOptions()
surface.enabled = True
agxRender.setTerrainParticleSurface(terrain_viz, surface)

stats = agxRender.getTerrainParticleSurfaceStats(terrain_viz)
print(stats.triangleCount, stats.avgGpuStepMs)
../_images/agxrender_particle_surface.jpg

Fig. 46.13 The same bucket of soil drawn as particles, upsampled particles and as a surface (round kernels without relief, and the defaults) – particle_surface_digging.py.

Lengths in the options are in particle radii: voxelSize (field sample spacing, 0.5) sets the resolution, kernelRadius (2.5), smoothing and anisotropy the shape. The GPU cost is a fraction of a millisecond per step for a few thousand particles (gpuStepMs and the per-pass fields of ParticleSurfaceStats). Buffers grow on demand; droppedBricks, droppedCells and outOfRange stay zero once they have. Combined with particle upsampling, the fine particles are drawn as well (grain detail where they reach through the surface). Particles far from the bulk (e.g. fallen off the terrain’s edge) are drawn as particles. The surface is not drawn into the voxel GI, and render nodes of distributed rendering draw the particles instead. See doc/agxRender_particle_surface_paper.md for the method.

46.12.3. Ground material

setTerrainGroundMaterial() draws a terrain, its particle surface and its soil particles with one ground material, evaluated in the soil’s material coordinates: the terrain’s own position, and on the particle surface the particles’ reference positions (where the soil was in the ground). Dug soil therefore continues the pattern of the ground it came from, and cut faces are not stretched. Two looks share all of it:

  • Procedural (GroundMaterial with a preset, getGroundMaterialPreset(): SOIL, DRY_SAND, CLAY, GRAVEL): colour patches and a band-limited relief whose octaves are weighted by the frequency they appear with on the surface and on the screen (after Kalinov et al. 2026), so the grain size stays the same where dug soil stretches, and nothing aliases.

  • The terrain’s own textures (useTerrainTextures = True): its colour, normal and roughness maps sampled triplanar in the material coordinates, with the large-scale patches over them against visible tiling.

The ground material also keeps history:

  • Subsoil. Each terrain stores its surface heights on its first frame. Below subsoilDepth under that original surface the ground shows subsoilColor, or, with setTerrainGroundSubsoilMaterial(), a textured material of its own, sampled the same way. Cut faces show the layer, and so does soil dug from below it (particle surface and particles).

  • Deposits. Where the terrain rises, the particle surface records the depth the soil that merged into it was dug from, so a dumped heap keeps the layer it came from (e.g. subsoil); thin spills fade into the ground. Soil dug out of a deposit takes that depth again. Deposits need the particle surface (setTerrainParticleSurface()).

from agxPythonModules.agxRender.soil import show_soil_as_surface, terrain_textures_ground

# The terrain's textures with a subsoil layer (show_soil_as_surface()'s default)...
show_soil_as_surface(terrain_viz, ground=terrain_textures_ground())

# ...or procedural soil, with a textured subsoil:
options = agxRender.TerrainGroundMaterialOptions()
options.enabled = True
options.material = agxRender.getGroundMaterialPreset(agxRender.GroundMaterialPreset.SOIL)
agxRender.setTerrainGroundMaterial(terrain_viz, options)
agxRender.setTerrainGroundSubsoilMaterial(
    terrain_viz, agxRender.Material.fromFile("data/resources/gravel_ground_01_1k.zip", "Subsoil"))
../_images/agxrender_ground_material.jpg

Fig. 46.14 One dig and dump cycle each: the terrain’s textures (default rendering, top left), the same textures in the soil’s material coordinates with a subsoil tint (top right) and with a gravel subsoil material (bottom left), and procedural soil (bottom right). The cut at the pile’s foot and the dumped heap show the subsoil – particle_surface_digging.py --groundMaterial cycle.

A paged terrain gets it with TerrainPagerRenderer.setGroundMaterial() and setGroundSubsoilMaterial(), on its tiles and backdrop alike. Each tile’s original surface is its heights when the pager first loads it (set the material before tiles are dug), kept per tile for the renderer’s lifetime, so a tile paged out and in again keeps its subsoil. It costs 4 bytes per vertex of each tile that has been deformed; deposit records (16 bytes per vertex) are only allocated for terrains a particle surface writes to. Render nodes get each tile’s original surface from the host (GROUND_MATERIAL). The pager’s soil particles, once rendered (agxRender.createVisual(pager.getGranularBodySystem()), setParticleSurface()), lie on the deformed tile most of them are over: they take its material and their surface adheres to and deposits into it (scene 4 of particle_surface_digging.py). Render nodes get the deposits from the host (GROUND_DEPOSITS), also the ones made before they joined. The history is not saved with the pager’s tile cache.

Lengths are in metres and colours are linear albedo. particle_surface_digging.py compares all looks (key t, or --groundMaterial cycle for a video). Limitations: the original surface is the terrain’s heights when its renderer first syncs; depth is measured along world up, so tilted terrains are not supported; the landscape terrain renderer and the voxel GI are not covered, and environment probes and ray-traced effects see the terrain’s ordinary material. The method and its background are in doc/agxRender_ground_material_plan.md.

46.12.4. Particle materials

setParticleMaterialMode() chooses how GPU particles are shaded: DEFAULT (procedural, untextured, cheapest), INHERIT_TERRAIN (the terrain surface’s material – terrain particles only) or CUSTOM. setParticleRenderMaterial() assigns a material and switches to CUSTOM:

sand = agxRender.Material.fromFile("materials/sand_1k.zip", "Sand")
agxRender.setParticleRenderMaterial(particle_system, sand)
agxRender.setParticleTextureScale(particle_system, 2.0)   # tile the texture more per particle

Only the base color (scalar and texture), roughness and metalness are used per particle; normal/roughness/metalness maps are not sampled, since their detail would be smaller than a pixel at particle scale. The terrain equivalents are setTerrainParticleMaterialMode(), setTerrainParticleRenderMaterial() and setTerrainParticleTextureScale().

46.12.5. Particle emitters (visual effects)

agxRender/EmitterAPI.h creates GPU particle emitters for effects such as dust, smoke, spray, exhaust and sparks. Their particles are simulated on the GPU and never interact with the AGX simulation (for simulated particles, use an agx::ParticleEmitter and the functions above). An emitter can follow a frame, such as a rigid body’s; emitted particles live in world space, so a moving emitter leaves a trail:

from agxPythonModules.agxRender.effects import puff_sprite

smoke = agxRender.EmitterSettings()
smoke.texturePath = puff_sprite()     # a generated soft puff; empty draws soft squares
smoke.shading = agxRender.EmitterShading.UNLIT
smoke.blending = agxRender.EmitterBlending.ALPHA   # dark smoke covers what is behind it
smoke.maxParticles = 400
smoke.rate = 20.0                     # particles per second
smoke.life = 3.0                      # seconds
smoke.size = 0.3                      # meters at birth ...
smoke.endSizeScale = 4.0              # ... and 4x that at the end of the life
smoke.velocity = agx.Vec3(0.0, 0.0, 1.0)
smoke.gravity = agx.Vec3(0.0, 0.0, 0.3)   # world axes; positive z makes smoke rise
smoke.color = agx.Vec4f(0.1, 0.1, 0.1, 0.45)

exhaust = agxRender.createEmitter(smoke, body.getFrame(), agx.AffineMatrix4x4.translate(0.5, 0.0, 2.0))
agxRender.setEmitterRate(exhaust, 60.0 * throttle)   # cheap enough to call every step
agxRender.emitParticles(exhaust, 50)                  # a burst on the next rendered frame

setEmitterRate(), setEmitterVelocity() and setEmitterColor() are cheap enough to call every step; setEmitterSettings() replaces all parameters, and setEmitterTransform() moves the emitter or attaches it to another frame. emitParticlesAt(handle, count, worldPosition) emits a burst at any point with the emitter’s look. destroyEmitter()/destroyAllEmitters() remove emitters, which clearScene() also does.

The shading modes are UNLIT (color used as is), LIT (lit by the scene lights) and DISTORTION (heat haze). LIT shades every sprite like a small sphere, which gives dust clouds hard, bubble-like rims; UNLIT usually looks better for dust and haze. Particles blend ADDITIVE by default: they add their color like light, which suits light dust, spray and sparks but cannot darken. blending = EmitterBlending.ALPHA lets them cover what is behind them by their opacity, for dark smoke such as diesel exhaust. depthCollision lets particles bounce off the visible scene.

agxPythonModules.agxRender.effects.WheelDust puts one emitter at the ground contact of each wheel and emits more the faster the wheel rolls and the more it slips:

from agxPythonModules.agxRender.effects import WheelDust, dust_settings

# agxTerrain.TerrainWheel instances (dust only while touching terrain), or (body, radius)
dust = WheelDust([(tire_body, 0.45) for tire_body in tire_bodies],
                 settings=dust_settings(color=(0.82, 0.82, 0.84, 0.22), max_particles=500))
sim.add(dust)

See data/python_agxrender/dune_buggy_scenario.py, cat_d3_worksite_scenario.py and submarine_ocean.py.

46.13. Sensor visualization

46.13.1. Camera sensor previews

registerCameraSensorBackend() routes agxSensor::Camera rendering through agxRender (instead of the default headless renderer). It must be called before constructing any agxSensor::Camera you want rendered this way, since the backend is captured at construction time:

agxRender.registerCameraSensorBackend()   # before any agxSensor.Camera is created
environment = agxSensor.Environment.getOrCreate(sim)
camera = agxSensor.Camera(camera_body.getFrame(), agxSensor.CameraModel(lens, sensor))
environment.add(camera)

color_output = agxSensor.CameraColorOutput()
camera.getOutputHandler().add(1, color_output)

agxRender.addColorCameraPreview(color_output, agx.Vec2f(0.0, 0.7), agx.Vec2f(0.3, 0.3))
../_images/agxrender_camera_sensor_previews.jpg

Fig. 46.15 Five camera sensors with on-screen previews: color with depth of field, depth, telephoto, barrel distortion and active illumination (camera_sensor_showcase.py).

addDepthCameraPreview() works the same way for a CameraDepthOutput, and addStereoDepthCameraPreview() for a CameraStereoDepthOutput; both take an optional false-color flag (colorMode) and the depth in meters mapped to the far end of the gradient (maximumDepth):

agxRender.addDepthCameraPreview(depth_output, agx.Vec2f(0.7, 0.7), agx.Vec2f(0.3, 0.3), True, 20.0)

The agxRender camera backend renders the lens model’s optical effects: a color camera’s depth of field follows its agxSensor.CameraLensSingleElement focal length and f-stop (independent of the main view’s agxRender::setDepthOfField()) – see data/python_agxrender/depth_of_field.py. It also simulates the sensor effects of agxOSG’s NeoCamera from the same agxSensor parameters: CameraCMOSSensor noise (on by default), depth noise, time-of-flight multipath confidence (CameraDepthOutput), and stereo matching with occlusion, texture/edge confidence, structured light and disparity noise (CameraStereoDepthOutput). Stereo depth is computed in rectified space, so lens distortion does not apply to it. Both previews update automatically whenever their output captures a new frame; remove one with removeCameraPreview(handle), or all of them with removeAllCameraPreviews().

A preview has no visibility switch of its own; to toggle it, remove it and add it again. The sensor keeps capturing while its preview is removed. For example, a forward-looking time-of-flight depth camera on the roof of the VolvoEX90, with a key that shows/hides its preview (from car_test_ground.py, key D):

# agxSensor cameras look along their frame's local +X with +Z up. The chassis here has +Y
# forward, so rotate +X onto +Y, tilted 6 degrees down, and place it on the roof above the
# windshield.
c, s = math.cos(math.radians(6.0)), math.sin(math.radians(6.0))
rotation = agx.AffineMatrix4x4(0, c, -s, 0,  -1, 0, 0, 0,  0, s, c, 0,  0, 0, 0, 1)
mount = agx.Frame()
mount.setLocalMatrix(rotation * agx.AffineMatrix4x4.translate(0.0, 0.45, 1.8))
mount.setParent(chassis.getFrame())

sensor = agxSensor.CameraCMOSSensor(agx.Vec2(0.0064, 0.0048), agx.Vec2i(320, 240))
lens = agxSensor.CameraLensSingleElement(0.005, 2.0)   # ~65 deg horizontal field of view
camera = agxSensor.Camera(mount, agxSensor.CameraModel(lens, sensor))
agxSensor.Environment.getOrCreate(sim).add(camera)

depth = agxSensor.CameraDepthOutput()
depth.setResolution(agx.Vec2i(320, 240))
depth.setChannelType(agxSensor.CameraDepthOutput.U16)
depth.setDepthUnit(1.0e-3)                       # millimeters: up to 65 m
depth.setDepthNoiseStandardDeviation(0.01)
depth.setDepthNoiseStandardDeviationSlope(0.002) # noise grows with distance
depth.setConstantCapture(20.0)
camera.getOutputHandler().add(1, depth)

preview = None

def toggle_preview():
    global preview
    if preview is None:
        preview = agxRender.addDepthCameraPreview(depth, agx.Vec2f(0.745, 0.25), agx.Vec2f(0.24, 0.32), True, 40.0)
    else:
        agxRender.removeCameraPreview(preview)
        preview = None
../_images/agxrender_gtire_tof_preview.jpg

Fig. 46.16 A time-of-flight depth camera on the roof of the VolvoEX90 and its time-of-depth camera preview, 0-40 m (car_test_ground.py).

Camera sensors render meshes at full detail, regardless of the level of detail the main view uses for them; see Automatic level of detail (LOD).

46.13.2. Synchronous camera sensors

By default, an image arrives a few steps after its capture: it is read back from the GPU without waiting (two captures later), or rendered on a render node. The simulation and the rendering then overlap, which is what a camera that only feeds a preview, a display or a recording needs. A controller or a reinforcement learning policy that acts on the images needs them before the next step, so that what a step reads is the state it starts from: a synchronous camera sensor has the simulation wait for its images at every step with a capture – in step callbacks, with a threaded simulation and with render nodes alike. Waiting costs the overlap of the CPU and the GPU, and can slow down the whole scene noticeably, e.g. in car_test_ground.py with its depth camera on (D).

# All camera sensors without a setting of their own (default False)
agxRender.setCameraSensorSynchronousDefault(True)

# This camera only, whatever the default
agxRender.setCameraSensorSynchronous(camera, True)
agxRender.getCameraSensorSynchronous(camera)   # the setting in effect

In agxViewer, --cameraSensorSync 1 sets the default, and the Synchronous camera sensors checkbox in the Simulation section of the F1 settings window switches it while the simulation runs; cameras with their own setCameraSensorSynchronous() keep it.

agxRender.getCameraSensorCaptureTime(output) returns the simulation time of the capture of the output’s latest image, the time to stamp it with when recording it with other data:

if color_output.hasUnreadData(True):
    captured_at = agxRender.getCameraSensorCaptureTime(color_output)

46.13.3. Lidar point clouds

agxRender.addLidarVisualization(lidar)
../_images/agxrender_lidar_pointcloud.jpg

Fig. 46.17 Lidar point cloud. (tutorial_lidar.py).

The point cloud (GPU-instanced, intensity-colored sprites) refreshes automatically on every step that produces new lidar data and is hidden while the lidar is disabled. Remove it with removeLidarVisualization(), or all of them with removeAllLidarVisualizations().

An optional agxRender.LidarVisualizationSettings controls how the points are drawn (the counterpart of the agxOSG::LidarOutputRenderer setters). By default only the latest lidar output is shown, which for a sweeping lidar is just the slice scanned in the last step; set hitPointLifetime to at least one scan period to see the full sweep:

settings = agxRender.LidarVisualizationSettings()
settings.hitPointLifetime = 1.0 / lidar_frequency  # simulation seconds a point stays visible
settings.fadeOut = True                            # fade out over the lifetime
settings.pointRadius = 0.02                        # meters
settings.pointRadiusPerMeter = 0.002               # grow with distance so far points stay visible
visual = agxRender.addLidarVisualization(lidar, settings)
Table 46.2 LidarVisualizationSettings

Field

Default

Explanation

hitPointLifetime

0

Seconds of simulation time a hit point stays visible; 0 shows only the latest output. Points stay where they were hit when the lidar moves

fadeOut

False

Fade a point’s opacity linearly to zero over hitPointLifetime

pointRadius

0.03

Constant point radius in meters

pointRadiusPerMeter

0

Radius added per meter of distance from the lidar

intensityScale

120

Scale mapping the lidar intensity to [0, 1] before coloring

colorMode

RED_GREEN

RED_GREEN (red low, green high), ALPHA (constant purple, intensity as opacity) or LEGEND

colorLegend

empty

Intensity/color points interpolated for LEGEND mode (must not be empty in that mode, need not be sorted)

colorLegendExponent

1

Exponent applied to the scaled intensity before the legend lookup

alwaysOnTop

False

Draw the points over all other geometry (no depth test)

A custom color legend:

settings.colorMode = agxRender.LidarColorMode.LEGEND
settings.colorLegend = agxRender.LidarColorLegend([
    agxRender.LidarColorLegendPoint(0.0, agx.Vec4f(0.1, 0.1, 0.8, 1.0)),
    agxRender.LidarColorLegendPoint(1.0, agx.Vec4f(1.0, 0.9, 0.2, 1.0))])

setLidarVisualizationSettings(visual, settings) replaces the settings of an existing visualization and getLidarVisualizationSettings(visual) returns them. Invalid settings (negative values, an empty legend in LEGEND mode) are rejected: addLidarVisualization() then returns an invalid handle and setLidarVisualizationSettings() returns False. Color changes apply to points received after the change.

data/python_agxrender/camera_sensor_showcase.py and sensor_carousel.py show several camera and lidar sensors with previews in one scene.

46.13.4. Fisheye camera (reference implementation)

agxRender/FisheyeCameraAPI.h is a prototype of what a fisheye camera sensor could look like. It is not part of agxSensor or OpenPLX and is not connected to the agxSensor API. Each capture renders up to five perspective views from the same eye (the front of a cube around the lens and the needed strips of its four sides) and maps every fisheye pixel through the exact inverse lens model, for fields of view up to 250 degrees:

p = agxRender.FisheyeCameraParameters()
p.width, p.height = 1024, 1024
p.fieldOfView = math.radians(185.0)
p.projection = agxRender.FisheyeProjection.EQUIDISTANT   # EQUISOLID, STEREOGRAPHIC, ORTHOGRAPHIC, RECTILINEAR
p.distortion = agx.Vec4f(0.02, -0.01, 0.0, 0.0)     # Kannala-Brandt k1..k4
p.framerate = 30.0                                  # captures per second of simulation time

fisheye = agxRender.createFisheyeCamera(p)
agxRender.attachFisheyeCamera(fisheye, body.getFrame())  # looks along local +X, +Z up
agxRender.addFisheyeColorPreview(fisheye, agx.Vec2f(0.7, 0.02), agx.Vec2f(0.28, 0.5))
agxRender.addFisheyeDepthPreview(fisheye, agx.Vec2f(0.7, 0.53), agx.Vec2f(0.28, 0.45), True, 20.0)

The parameters also cover the image-circle size (imageCircleScale: circular or full-frame fisheye), the principal point offset, vignetting and lateral chromatic aberration. setFisheyeCameraTransform() places a camera at a fixed world transform instead of a frame. The latest images are read back with getFisheyeColorImageBytes(handle) (RGBA8 rows from the top) and getFisheyeDepthImageBytes(handle) (float32 distance along each pixel’s ray in meters, -1 for no hit); both return None until the first image arrives, which is two captures after it is rendered. getFisheyePixelRay(handle, pixel) returns the ray direction of a pixel, for turning a depth image into a point cloud. See data/python_agxrender/fisheye_camera_showcase.py.

46.14. Video and image capture

These mirror the equivalent agxOSG/agxOSGViewer features (see VideoCapture / Headless video capture), configured either via ViewerSessionOptions/Application setters or the matching command-line flags:

options.captureVideo = True
options.videoName = "demo.webm"       # VP9/WebM (not .mp4 -- no FFmpeg dependency)
options.captureFPS = 30.0
options.captureSync = True            # frames keyed to simulation time, not wall clock
options.videoQuality = 12             # 0..63, lower = better and larger (constant quality)
options.videoBitrateKbps = 0          # > 0: fixed target bitrate instead of videoQuality
options.videoSpeed = 6                # encoder speed 0..9, higher = faster
options.videoThreads = 0              # encoder threads, 0 = half of the CPU cores

options.captureImage = True
options.captureImageName = "frame"
options.captureImageFiletype = "jpg"  # "jpg" (default), "png", or "bmp"
options.captureImageDirectory = "imageCapture"

At runtime, F10/F12 toggle video/image capture on and off. Both work with --headless 1 for automated/CI screenshot and video generation with no visible window (see Generating the screenshots used in this document for a worked example).

Video is encoded at constant quality by default, so the bitrate follows the resolution and the content. videoQuality 12 is close to lossless; 20-30 gives considerably smaller files, and from about 40 compression artifacts show. Set videoBitrateKbps for a predictable file size instead. Encoding runs on its own threads and does not slow down rendering unless it falls behind; when it does, rendering waits for it, so no frame is dropped. A higher videoSpeed or a lower captureFPS helps then.

For remote viewing in a web browser, see Pixel streaming: remote viewing in a browser below.

46.15. Recording sensor data with Rerun

Rerun records and replays multimodal data (images, video, scalars, text) on timelines, for inspecting and training on simulation runs. RerunRecorder (agxPythonModules.agxRender.rerun_recorder) records camera sensors and values from a script, on a timeline sim_time of the simulation time:

from agxPythonModules.agxRender.rerun_recorder import RerunRecorder

recorder = RerunRecorder("wheel_loader")             # opens the Rerun viewer and streams to it
recorder = RerunRecorder("wheel_loader", "run.rrd")  # or records to a file
recorder.add_camera("cameras/front", color_output)   # CameraColorOutput, 3 channels, U8
recorder.add_scalar("loader/speed", loader.speed)    # called after every step
recorder.add_text("loader/autopilot", pilot.describe)  # logged when it changes
sim.add(recorder)
...
recorder.close()                                     # encodes what is queued, flushes the file

Each camera is encoded to H.264 on its own thread, with NVENC on NVIDIA GPUs and libx264 otherwise (also when the GPU has no NVENC session left), and logged as a Rerun video stream at its capture time (getCameraSensorCaptureTime()). A 1080p camera at 15 Hz takes about 3 Mbit/s. Ten 1080p cameras encode at about 27 frames per second each; a recording keeps every frame, so encoding that falls behind holds back the simulation instead of dropping frames. Install the packages with pip install rerun-sdk av. The Rerun viewer decodes the video with the first ffmpeg on PATH, which must be version 5.1 or newer (some applications, e.g. ImageMagick, put an older one there). Otherwise the viewer reports “FFmpeg version … supported is only >= 5.1”; set a newer one in the viewer’s Settings under Video, “FFmpeg path”.

wheelloader_quarry_cameras.py records the quarry of wheelloader_quarry_scenario.py with ten 1920x1080 cameras on the wheel loader (cab roof, bucket, mirrors, surround, rear, wheels and a chase camera), the loader’s speed and bucket load and the autopilots’ phases:

# Live, in a Rerun viewer the script opens:
agxViewer wheelloader_quarry_cameras.py

# To a file, then open it:
python wheelloader_quarry_cameras.py --rerunSave quarry.rrd --stopAfter 60
rerun quarry.rrd

# With the cameras rendered on render nodes (on this or other machines):
agxViewer wheelloader_quarry_cameras.py --simulationHost 9003
agxRenderNode --host simhost --view sensors

Each image is logged at its capture time, also when it arrives some steps later, and is the state of that step. The simulation does not wait for the images (setCameraSensorSynchronous()), so with render nodes a capture that is due while the camera’s previous one is still on its way is skipped; --cameraSensorSync 1 makes it wait and record every capture, the same with and without render nodes. Use python ... --rerunSave for a complete file: agxViewer ends its process without closing the recorder, so the last frames still being encoded may be lost.

To check a recording:

  1. rerun quarry.rrd opens it. The left panel lists cameras/<name> for every camera, and loader/ and truck/.

  2. Every camera view plays as video when you drag the time cursor on the sim_time timeline; the images and the plots of loader/speed and loader/bucket_load move together.

  3. loader/autopilot shows the phase changes (“Entering the pile”, …) at the times they happened.

  4. From Python, rerun.dataframe.load_recording("quarry.rrd") reads the samples back, e.g. for a training data loader; tests/pytest/agxRender/test_rerun_recorder.py decodes them with PyAV.

46.16. Pixel streaming: remote viewing in a browser

Pixel streaming sends the rendered main view as realtime VP9 video over a WebSocket to any number of connected web browsers, and sends each browser’s mouse and keyboard input back to the session. A browser is therefore a fully interactive remote viewer, not a one-way feed: it can orbit/fly the camera, pick bodies and use the keyboard shortcuts, alongside (or, with --headless 1, instead of) the local window. Typical uses are running a simulation on a GPU workstation or a cluster node and viewing it from a laptop, or showing a running simulation to several people at once. The images of the session’s camera sensors are streams too: one page shows any of them, from one or more sessions, see Camera sensor streams.

Pixel streaming consists of two parts:

  • The server: any agxRender session (agxViewer, runViewerSession(), or an Application) with pixel streaming enabled. It listens on a TCP port (default 9002) on all network interfaces.

  • The client: PixelStreamingViewer, a single self-contained HTML page (no build step, no dependencies) that connects to the server, decodes the video in the browser and forwards the input. It is located in tools/PixelStreamingViewer/index.html in the AGX source tree.

46.16.1. Step 1: Start a session with pixel streaming

From the command line, on the machine that runs the simulation:

configuration\setup_env.bat
agxViewer data\python_agxrender\cat_d3_worksite_scenario.py --pixelStreaming 1

For a machine without a display, or when nobody needs the local window, add --headless 1. The stream has the resolution of the (possibly off-screen) window, so set it with --window as well:

agxViewer scene.py --headless 1 --window 1920 1080 --pixelStreaming 1 --pixelStreamingPort 9002

Pixel streaming can also be enabled from a script, before or during a session:

# Before the session, via the session options (same as the command-line flags):
options.pixelStreaming = True
options.pixelStreamingPort = 9002
options.pixelStreamingBitrateKbps = 4000
options.pixelStreamingKeyframeInterval = 60

# ...or on an Application:
app.setEnablePixelStreaming(True)
app.setPixelStreamingPort(9002)

From C++, agxRender::startPixelStreaming(port, bitrateKbps, keyframeInterval) also starts it at any time, including while the session is running (see the function table below).

In an interactive session that was started without it, pixel streaming can be switched on and off with the Pixel Streaming checkbox in the F1 settings window.

46.16.2. Step 2: Open PixelStreamingViewer in a browser

  1. Copy tools/PixelStreamingViewer/index.html to the computer you want to view the simulation on (or use it in place, if that is the same computer).

  2. Open it in Chrome or Edge – double-clicking the file (file://) is enough. The page uses the browser’s WebCodecs API to decode the video; if the browser lacks it, the page says “WebCodecs API not available in this browser” and the Connect button is disabled. Firefox and Safari support varies.

  3. Enter the server address, <host>:<port> (or ws://<host>:<port>/), in the address field – for example localhost:9002 on the same computer, or 192.168.1.20:9002 for a simulation running on another computer on the network. Several servers are separated by commas.

  4. Click Connect. The main view of each server appears; its label shows the resolution, frame rate and bandwidth of the stream. Disconnect closes the connections; the simulations keep running. The page address then names the servers (index.html?servers=localhost:9002): a bookmark of it connects at once.

The video starts at the next keyframe, which the server sends immediately when a browser connects.

Note

WebCodecs is only available on pages loaded from a secure context: file://, http://localhost or https://. Opening the page from the local disk always works. If you instead serve the page from the simulation computer (for example with python -m http.server in tools/PixelStreamingViewer) and open http://<remote-host>:8000/ in the browser, WebCodecs is disabled by the browser. Copy the file to the viewing computer instead, or forward the port over SSH (below) and use localhost.

Also note that the stream is plain, unencrypted ws://. A page served over https:// cannot connect to it (mixed content), and the stream should not be exposed on an untrusted network – see Network, firewall and remote access.

46.16.3. Step 3: Control the simulation

Click the video to give it keyboard focus and lock the mouse pointer to it; press Esc to release the pointer again. While the pointer is locked, the mouse and keyboard work as in a local agxViewer window (see Keyboard and mouse bindings):

  • Left-drag: orbit, Middle-drag: pan, Scroll: zoom

  • Right-drag, with W/A/S/D/Q/E: look around and fly

  • Ctrl+Left-click(-drag): pick and drag a physics body

  • keyboard shortcuts such as e (play/pause), Space (fit the camera) and F1 (settings window, rendered into the stream)

Input from the browser is combined with input from the local window, and all connected browsers share one camera: everyone sees the same view, and anyone can move it.

Warning

Esc quits the session, also when it is pressed in the browser, which ends the stream for every viewer. The browser uses Esc to release the pointer lock; an Esc pressed while the pointer is already released but the video still has keyboard focus is sent to the session. Click outside the video before pressing Esc if you only want to leave the page.

Only the keys used by agxRender’s own camera control and keyboard shortcuts are forwarded: letters, digits, arrows, Space, Shift/Ctrl/Alt, Esc, Enter, Tab and F1-F12. +/- (scene cycling) are not forwarded; use 1-9 to switch scenes from the browser.

46.16.4. Camera sensor streams

Every output of an agxSensor camera that agxRender renders (see Camera sensor previews) is a stream of its own, named after its camera (agxSensor.Camera.setName()). The panel on the left of the page lists the streams of each server, also cameras that are added later; tick the ones to watch, or All/None. The watched streams fill the page in a grid; double-click one to show it alone, and again to return to the grid. Only the main view takes mouse and keyboard input.

Images of cameras rendered on render nodes (Distributed rendering: render nodes) are streamed by the simulation host, like those rendered by the host itself. To watch the cameras of several simulations, start each with pixel streaming on its own port or machine and connect the page to all of them:

agxViewer wheelloader_quarry_cameras.py --headless 1 --pixelStreaming 1
# in the browser: index.html?servers=localhost:9002,simhost2:9002

A camera stream shows each image when it is delivered, at the camera’s capture rate (in simulation time). A stream is encoded only while a browser watches it, on a thread of its own, at the bitrate of the main view; a depth output is shown as its preview, gray or colored by depth. A stream drops images rather than fall behind when its encoding cannot keep up, so many high-resolution cameras at high rates need as many CPU cores; watch fewer streams on a smaller computer.

46.16.5. Network, firewall and remote access

  • The server listens on all network interfaces of the simulation computer. Allow incoming TCP connections on the pixel-streaming port in its firewall (on Windows, the firewall typically asks the first time agxViewer listens on the port).

  • The connection is unencrypted and unauthenticated: anyone who can reach the port can watch the simulation and control it. Use it on a trusted network, or tunnel it over SSH:

    ssh -L 9002:localhost:9002 user@simulation-host
    

    and connect the browser to ws://localhost:9002/.

  • If the port is already in use, the server does not report an error; the browser simply cannot connect. Choose another port with --pixelStreamingPort.

  • The transport is TCP, which is well suited for a wired LAN. On a lossy WiFi link, a lost packet makes the stream stall briefly rather than degrade. A shorter keyframe interval (--pixelStreamingKeyframeInterval) makes the stream recover faster after a corrupted frame, at the cost of bandwidth.

46.16.6. Bitrate and quality

The stream is encoded at a fixed target bitrate, 4000 kbit/s by default, which is suitable for 720p at 30-60 fps on a LAN. It is not adapted to the network automatically. Raise it for a larger window or better image quality, lower it for a slow link:

agxViewer scene.py --window 1920 1080 --pixelStreaming 1 --pixelStreamingBitrate 12000

or, from C++, change it while streaming with agxRender::setPixelStreamingBitrate(12000).

Table 46.3 Pixel streaming settings

Command line

ViewerSessionOptions / Application

Default

Explanation

--pixelStreaming <0|1>

pixelStreaming / setEnablePixelStreaming()

0

Enable pixel streaming

--pixelStreamingPort <port>

pixelStreamingPort / setPixelStreamingPort()

9002

TCP port of the WebSocket server

--pixelStreamingBitrate <kbps>

pixelStreamingBitrateKbps / setPixelStreamingBitrate()

4000

Target VP9 bitrate in kbit/s

--pixelStreamingKeyframeInterval <n>

pixelStreamingKeyframeInterval / setPixelStreamingKeyframeInterval()

60

Maximum number of frames between keyframes

The runtime API in PixelStreamingAPI.h is C++ only; it is not wrapped for Python, where pixel streaming is configured through ViewerSessionOptions or Application (above):

Table 46.4 Pixel streaming functions

Function

Explanation

startPixelStreaming(port, bitrateKbps, keyframeInterval)

Start the server; can be called before or during a session. Calling it again changes the settings (and restarts the server if the port changed)

stopPixelStreaming()

Stop the server and disconnect all browsers

isPixelStreamingRunning()

Whether the server is running

getPixelStreamingPort()

The port the server listens on

getPixelStreamingClientCount()

Number of connected browsers

setPixelStreamingBitrate(bitrateKbps)

Change the bitrate of a running stream

Pixel streaming is independent of video capture (--captureVideo); both can run at the same time.

46.16.7. Writing your own client

PixelStreamingViewer is a reference client in one file; the protocol is simple enough to embed the streams in another web page or application. When a client connects, and whenever cameras are added or removed, the server sends the list of its streams as a JSON text message; stream 0 is the main view:

{"t":"streams","streams":[{"id":0,"name":"Main view","kind":"view"},
                          {"id":1,"name":"bucket","kind":"color","w":1920,"h":1080}, ...]}

kind is view, color, depth or stereo depth. A new client watches the main view; it watches and stops watching streams with {"t":"sub","id":1} and {"t":"unsub","id":1}, and the server then sends a keyframe of the stream first. Each binary WebSocket message from the server is one VP9 frame (no container) preceded by a 20-byte little-endian header:

Table 46.5 Frame header

Offset

Type

Field

0

uint32

Magic number 0x5A565841

4

uint8

Flags, bit 0 set for a keyframe

5

uint8

Codec, 0 = VP9

6

uint16

Width in pixels

8

uint16

Height in pixels

10

uint16

Stream id, 0 for the main view

12

uint64

Timestamp in microseconds: since streaming started for the main view, the simulation time of the capture for a camera

20

bytes

The VP9 frame

A browser client decodes the frames of each stream with a WebCodecs VideoDecoder of its own, configured with codec vp09.00.10.08, recreating the decoder when the width or height in the header changes. A decoder must be started with a keyframe. A client that ignores the stream list gets only the main view, as before camera streams existed.

Input to the main view is sent to the server as single-line JSON text messages:

{"t":"m","dx":1.2,"dy":-0.4}      mouse move, relative, in stream pixels
{"t":"b","b":0,"d":true}          mouse button 0/1/2 (left/middle/right), down (true) or up
{"t":"w","d":-1}                  mouse wheel, one step per message, sign only
{"t":"k","c":"KeyW","d":true}     key down/up, c is the JavaScript KeyboardEvent.code

The mouse position used for picking is accumulated from the relative moves, so scale movementX/movementY from displayed to stream pixels if the video is shown scaled, as index.html does.

46.17. Distributed rendering: render nodes

A simulation host sends its render scene to render nodes: other processes, on the same machine or on other machines, that rebuild the scene and render it with their own GPU. The host keeps stepping the simulation; each node renders its own views, for example camera sensors, so the rendering of many cameras is spread over several GPUs.

# The simulation host: any agxViewer session, with --simulationHost [port] (default 9003)
agxViewer wheel_loader.py --simulationHost 9003

# A render node, here on another machine
agxRenderNode --host simhost.example.com --port 9003

Nodes and host can be started in any order. agxRenderNode waits for the host (the window says so) and reconnects when the connection is lost; the last received scene stays visible meanwhile. A node that joins a running host first gets the whole scene. agxRenderNode takes the window, capture and pixel streaming options of agxViewer (--headless, --width, --captureVideo, --pixelStreaming, …), see agxRenderNode --help. Scene files and the simulation options (--stopAfter, --numThreads, --startPaused, …) belong to the host, and a node refuses them. Capture runs on the wall clock. --name names the node in its window title and in the host’s log.

--view sets what the node renders in its window:

  • follow (default): what the host’s viewer camera shows.

  • free: its own camera, controlled in its window.

  • sensors: no 3D view. The node renders only camera sensors, which leaves its GPU to them.

  • Any other name: that view of the host’s camera group, see Camera groups.

--showSensors 1 shows the images of the camera sensors the node renders, labeled with the camera’s name and the output type: over the whole window in the sensors view (the default there), else in a column on the right. F7 opens the Render Node window, which shows the connection and changes both. What is chosen there is kept when the node (re)connects, so a node can be set up before the host starts. From a script: setRenderNodeView() and setRenderNodeShowSensors(), or the view and showSensors fields of RenderNodeOptions.

--frameLock 1 shows each frame together with the host’s other frame locked nodes, so the screens of a camera group never show different frames side by side (RenderNodeOptions.frameLock). The host sends these nodes a new frame only when all have rendered the last one, so the slowest node sets their frame rate; a node that takes more than a second is not waited for. The nodes submit their frames together; with the same GPUs and vsync they also show them together.

From a script, the host and the node are a few calls:

# Simulation host: before or during the session
agxRender.startSimulationHost(9003)
print(agxRender.getRenderNodeCount())

# Render node: a session without a simulation of its own
node = agxRender.RenderNodeOptions()
node.host = "simhost.example.com"
node.port = 9003
if not agxRender.connectRenderNode(node):
    print(agxRender.getRenderNodeError())
agxRender.runViewerSession(options)

The host costs nothing while no node is connected. With nodes, it reads the scene once per rendered frame (in the sync window of a threaded session) and sends each node only what changed since what that node last got: a node that cannot keep up skips frames instead of falling behind.

46.17.1. Assets

The host sends what it renders, not simulation objects: triangle meshes, PBR materials and the image files of their textures, each identified by a hash of its content, and objects that place a mesh in the world. Models (.glb, .gltf, .fbx, .obj, …) arrive as the meshes, materials and images the host imported from them. A node keeps meshes and images in its asset cache (--assetCache <directory>, default agxRenderNodeCache in the temporary directory); a node that connects again, or to a host showing the same scene, gets only the assets it does not have. Objects with the same mesh and materials are drawn instanced on the node.

46.17.2. What is replicated

Replicated

Not yet replicated

Everything drawn as a mesh: visuals of geometries and rigid bodies, attached models, mesh visuals (createMeshVisual()), deformables, cables, terrain (as it deforms, only the changed parts are sent). Particles (with their upsampling and material). Wires (their render nodes; the node builds the tube). Materials, textures, visibility (also in camera sensors). Lights, background color, environment map, sky, fog, clouds, rain, wind, exposure and bloom. The ocean, emitters and grass (createGrass()). The viewer camera.

Landscape terrain (setEnableLandscapeTerrain()). HUD, labels, wireframe and terrain debug overlays.

Time-based effects (ocean waves, wind, emitters, grass) follow the host’s scene time on the nodes, so the waves are where the host has them. Emitter particles are simulated on each node from the host’s emitter settings and bursts: the clouds look alike, the individual particles differ. A node that skips frames to keep up misses the bursts of those frames. The grass template (GrassSettings::templatePath) is looked up in the node’s own resource path, as with the same AGX installation; a grass image is sent like other textures.

46.17.3. Camera sensors

While a node is connected, the host’s camera sensors (agxSensor::Camera with the agxRender backend) are rendered by the nodes instead of the host’s GPU. Each camera goes to the node with the fewest pixels per second to render, and stays there. A capture renders the scene as it was at the step that took it; for a synchronous camera, the step after it waits for the images: a script reading the outputs in POST_STEP gets the same images as without nodes, at the same steps. The previews show the returned images, labeled with the node that renders them (“rendered here” once it is gone). A camera whose node disconnects goes to another node, or back to the host, at its next capture.

Two settings per camera, which can be made before startSimulationHost():

# Always render this camera on the node started with --name left; here while it is not connected
agxRender.setCameraSensorRenderNode(camera, "left")

# Wait for this camera's images before the next step (a camera a controller acts on)
agxRender.setCameraSensorSynchronous(camera, True)

A camera that is not synchronous (the default, see Synchronous camera sensors) gets its images a few steps after the capture, and a capture that is due while the previous one is still on its way is skipped, so a slow node lowers the camera’s frame rate instead of holding back the simulation. A host or node built without agxSensor ignores camera sensors.

46.17.4. Camera groups

Several windows or screens, each driven by its own render node, show one viewer camera together: a camera group gives each node a view of the host’s viewer camera, and all views follow it. The group is one JSON file on the host. data/cfg/camera_group.json makes one wide image of three windows side by side across the display, the host’s in the middle:

{ "borderless": true,
  "window": [0.3333, 0.25, 0.6667, 0.75],
  "views": { "left":  { "tile": [-1, 0], "window": [0, 0.25, 0.3333, 0.75] },
             "right": { "tile": [1, 0],  "window": [0.6667, 0.25, 1, 0.75] } } }
agxViewer driving_simulator.py --simulationHost 9003 --cameraGroup camera_group.json
agxRenderNode --name left --view left --frameLock 1
agxRenderNode --name right --view right --frameLock 1

A file that is not found as given is looked for in the resource path, which data/cfg is part of. The host’s own window shows the viewer camera itself, here the middle of the image.

tile is the part of the wide image a node shows, in whole images right and up of the host’s: the node continues the host camera’s image plane with the host’s pixel size, so the images join without a seam whatever the windows’ sizes. window places a window as [left, top, right, bottom], fractions of its display, so the layout fits any resolution; give a shared edge the same value in both windows. The top-level window is the host’s. borderless removes the border and title bar of the windows the group places. A node places its window once when it shows the view; it can be moved afterwards. The image is flat: wider tiles look more stretched toward the sides, and a flat image cannot reach 180 degrees.

For screens that stand at an angle to each other, a view is instead turned from the viewer camera:

{ "views": { "left":   { "yaw": 50, "fov": 45 },
             "center": { "yaw": 0,  "fov": 45 },
             "right":  { "yaw": -50, "fov": 45 } } }

yaw turns a view about the camera’s up axis (positive to the left), pitch about its right axis (positive up) and roll about its view direction (positive turns the image clockwise), in degrees; fov is the vertical field of view in degrees, the viewer camera’s when left out. Each node uses the aspect ratio of its own window. A node shows a view by its name (--view <name>, setRenderNodeView()); a view the host does not have shows the viewer camera, with a warning in the node’s log. From a script: agxRender.setCameraGroup("camera_group.json"), also before startSimulationHost(), and agxRender.clearCameraGroup(). Neighboring views meet at their edges only when the yaw between them is the horizontal field of view of the windows, which follows from fov and the window’s aspect ratio; flat windows side by side need tiles instead.

For a power wall or a CAVE, a view is instead a physical screen, seen from the viewer’s eye:

{ "views": { "front": { "screen": { "lowerLeft":  [2, 1.5, -1],
                                    "lowerRight": [2, -1.5, -1],
                                    "upperLeft":  [2, 1.5, 1] } },
             "left":  { "screen": { "lowerLeft":  [-1, 1.5, -1],
                                    "lowerRight": [2, 1.5, -1],
                                    "upperLeft":  [-1, 1.5, 1],
                                    "eye":        [0, 0, 0] } } } }

The corners and eye are in meters relative to the viewer camera: x forward, y left, z up. The eye defaults to the camera; a head tracker can move it. The node renders what the eye sees through the screen (an off-axis frustum), so the screens join without seams when their corners are measured where they stand. Give the node’s window the screen’s aspect ratio. A screen must be a rectangle facing the eye, and a view is either a screen, a tile or angles. Any view can have a window. Run the nodes with --frameLock 1.

46.17.5. Network and firewall

The host listens on all network interfaces, IPv4 and IPv6, on the given TCP port (default 9003); open that port in the host’s firewall for nodes on other machines. The stream is not encrypted or authenticated: use it on a trusted network, or tunnel it (for example ssh -L 9003:localhost:9003 simhost). Updates are zstd-compressed.

46.17.6. The wire format

The format carries only renderable data and no renderer types, so a render node can be written for any engine. All values are little-endian; string is a u32 byte count and UTF-8 bytes. Coordinates are AGX’s: right-handed, Z up, meters. Matrix is 16 f32, row major, for row vectors (translation in the last row).

A connection is a sequence of messages: a 16-byte header (u32 magic 0x4E525841, u16 protocol version 11, u16 type, u32 payload size, u32 uncompressed size: 0 when the payload is not compressed, otherwise the payload is zstd-compressed). The node sends HELLO (type 1: u16 version, string name, u32 count, u64 ids of the assets it has, and optionally u8 flags: 1 frame lock), the host answers WELCOME (type 2: u16 version) and then sends FRAME messages (type 3). A node rendering camera sensors answers each SENSOR_CAPTURE with an IMAGE message (type 4) per output: u64 camera, u64 output, f64 the capture’s time (from SENSOR_CAPTURE), u32 size and the output’s data, laid out as in its agxSensor output buffer. A node renders a capture at the state of the frames up to it, after rendering that state once (so that new lights and shadows are in effect), and applies no later frame before; it answers every capture. A frame locked node sends READY (type 5, no payload) after it applied frames and shows them when the host answers PRESENT (type 6, no payload), which the host sends to all locked nodes once each is ready, and at once for frames outside a lock round (e.g. only captures). A frame is a sequence of records, each an 8-byte header (u16 type, u16 reserved, u32 size) and its data. Skip records of unknown types.

Table 46.6 Records

Record

Data

1 ASSET

u64 id, u8 kind (1 mesh, 2 image, 3 material, see below), u8 flags (1: transient, e.g. a mesh rebuilt every step: do not cache it, it is sent again whenever used; 2: patch, see below), the kind’s data. Sent before the first record that uses it; other assets only once per node, and not at all if the node’s HELLO listed it.

A patch (a deforming terrain or body: a transient mesh of the same size) has as data u64 base asset, u32 count, and per range u32 offset, u32 size and the bytes: the base asset’s data with these ranges replaced. The base is a transient asset the node got at most 600 FRAME messages before and has not used as a base yet; a node keeps each transient asset that long for this.

2 OBJECT

u64 object, u64 mesh, u32 count, u64 material per mesh subset, u8 flags (1 visible in the viewer, 2 visible in camera sensors, 4 casts shadows, 8 skinned: the mesh is deformed by the object’s SKIN; 0: hidden), f32[4] color and f32[4] emissive color multipliers (linear RGBA). Creates the object or replaces its data.

3 OBJECT_REMOVE

u64 object

4 TRANSFORMS

u32 count, per object u64 object and Matrix world transform

5 CAMERA

f64[3] eye, center and up, f64 near, far and vertical field of view in degrees, u32 width and height of the camera’s image in pixels

6 LIGHTS

All lights, sent when any changed: u32 count, per light u64 light, u8 type (0 directional, 1 point, 2 spot, 3 rectangle), u8 flags (1 casts shadows, 2 volumetric), f32[3] color (linear RGB), f32 intensity (lux for directional lights, candela for the others, as in glTF KHR_lights_punctual), range, outer and inner cone angle (radians), width and height (rectangle), Matrix world. Directional and spot lights shine along -Z of their frame, a rectangle light along -Y with its width along X.

7 ENVIRONMENT

Sent when changed: u32 flags (1 background color, 2 physically based sky, 4 aerial perspective, 8 high quality sky, 16 fog, 32 height fog, 64 clouds, 128 clouds cast shadows, 256 clouds receive shadows, 512 rain, 1024 wind, 2048 eye adaption, 4096 bloom); f32[4] background color of the upper left, upper right, lower left and lower right corner (sRGB after tone mapping, shown where no geometry is); u64 environment map image (0 none) and f32 its intensity; f32 aerial perspective scale, f32[3] sky horizon, zenith and ambient color; f32 fog start distance, density, height start, height end; f32 cloud start height, thickness, coverage, type amount, rain amount, wind speed; f32 rain amount, length, speed, scale, splash scale, f32[4] rain color; f32[3] wind direction, f32 wind speed, randomness, wave size; f32 exposure and bloom threshold. The fields follow agxRender’s AtmosphereSettings, FogSettings, VolumetricCloudSettings, RainSettings and WindSettings.

8 SKIN

u64 object, u32 count, Matrix per bone: the skinning matrix taking a vertex of the mesh’s bind pose to the object’s frame (the object’s world transform applies on top). A skinned vertex is the weighted sum of its bones’ skinning matrices applied to it.

9 PARTICLES

The particles of one particle system, sent when the simulation time or a setting changed: u64 particle system, f64 simulation time, u64 material (0: shaded with the particle colors), f32 texture scale and texture scale per radius (the texture scale is their sum with the second times the radius of the drawn particles), upsampling (u8 enabled, tier, method, u32 factor, f32 ease step size, nominal particle radius, voxel size, particle density; see agxRender::ParticleUpsamplingOptions), u32 count, and per particle f32[3] position, f32 radius, f32[4] color (linear RGBA), f32[4] rotation (quaternion x, y, z, w), u32 id (stable while the particle lives), f32 mass, f32[3] velocity. Spheres of that radius render the particles; a node that upsamples advances its fine particles by the time between two records.

10 PARTICLES_REMOVE

u64 particle system

11 SENSOR_CAMERA

A camera sensor this node renders, sent before its first capture and when it changed: u64 camera, u8 flags (1 lens, 2 sensor, 4 lens distortion), the parameters the flags say are present (CameraLensSingleElementParameters, CameraCMOSSensorParameters, LensDistortionBrownConradyCoefficients), u32 count, and per output u64 output, u8 type (0 color, 1 depth, 2 stereo depth), u32 size and its Camera*OutputParameters; then the camera’s name (string). The parameters are the packed structs of agxSensor/CameraBackend.h, byte for byte.

12 SENSOR_CAMERA_REMOVE

u64 camera

13 SENSOR_CAPTURE

u64 camera, u32 capture index (seeds the sensor noise), f64 simulation time of the capture (returned with its images), f64[16] world pose (row major, translation in the last row; the camera looks along X with Z up), u32 count and u64 outputs to render. Render them at the state of the records before it in the frame and answer with an IMAGE message each.

14 WIRE

A wire, sent when it changed: u64 wire, u64 material, f32 radius, u32 count, and per render node f32[3] world position and f32 length scaler (stretches the texture along the wire). Draw a tube of that radius along a smooth curve through the nodes (agxRender: Catmull-Rom).

15 WIRE_REMOVE

u64 wire

16 PARTICLE_SURFACE

How a particle system is drawn as a surface (agxRender::setTerrainParticleSurface()), sent before its PARTICLES when it changed: u64 particle system, u64 terrain object (0: none; the surface takes its material and meets its ground), then agxRender::ParticleSurfaceOptions: u8 enabled, f32 voxel size, kernel radius, smoothing, anisotropy, max stretch, u32 min neighbors, u8 texture follows soil, f32 texture relaxation, cavity, iso scale, relief, relief size, adhesion, adhesion distance, and the particle radius its lengths are relative to.

17 GROUND_MATERIAL

A terrain object’s ground material (see Ground material), sent after the object when it changed: u64 terrain object, u8 enabled, then agxRender::GroundMaterial: f32[3] color, f32[3] color variation, f32 macro scale, clod size, clod strength, grain size, grain contrast, roughness, normal strength, u8 use terrain textures, f32 subsoil depth, f32[3] subsoil color; u64 subsoil material asset (0: none), u32 resX, u32 resY and resX × resY f32 heights, row by row: the terrain’s original surface, which the subsoil depth is measured from (0 × 0 until the host has it). A node that joins after the terrain was dug still shows the subsoil where the host does.

18 GROUND_DEPOSITS

A terrain object’s deposits, after its GROUND_MATERIAL: u64 terrain object, u32 resX, u32 resY, u32 count, and per record u32 grid vertex (row by row) and f32 depth below the original surface the soil deposited there was dug from. Sent about four times a second while they change, and to a node that joins, which replaces its own with them.

19 CAMERA_GROUP

The camera group, sent when it changed: u32 count, and per view string name and u8 kind. Kind 0 (angles): f64 yaw, f64 pitch, f64 roll (degrees, relative to the CAMERA record’s camera) and f64 vertical field of view (degrees, 0 for the camera’s). Kind 1 (screen): f64[3] lower left, lower right and upper left corner and eye, in the camera’s frame (x forward, y left, z up). Kind 2 (tile): f64 x, f64 y, whole images right and up of the camera’s image, continuing its image plane at its pixel size. Then u8 window flags (1 place the window, 2 borderless) and with flag 1 f64 left, top, right, bottom: the window’s area as fractions of the node’s display. Count 0: no group.

20 SCENE_TIME

f64 seconds: the clock of time-based effects (ocean waves, wind, emitters, grass). A node without a simulation of its own runs its effects on it.

21 OCEAN

OceanSettings, sent when they changed: u8 flags (1 enabled, 2 planar reflections), f32 water height, f32[4] water color, f32[4] extinction color, f32 wave amplitude, f32 patch length, f32[2] wind direction (xy), f32 wind speed, f32 wind dependency, f32 choppy scale, f32 time scale, u32 surface detail.

22 EMITTER

EmitterSettings of an emitter, sent when it changed or emitted a burst: u64 emitter, u64 sprite image asset (0 none), u32 frames x, u32 frames y, f32 frame rate, u8 shading (0 unlit, 1 lit, 2 soft), u8 blending (0 additive, 1 alpha), u8 flags (1 depth collision, 2 sorting), u32 max particles, f32 rate, life, life randomness, size, end size scale, randomness, spin, f32[3] velocity, f32 velocity spread, f32[3] gravity, f32 drag, f32[4] color, f32 color randomness, fade in end, fade out start, f32[3] emit half extents, Matrix world, u32 count, and per burst u32 particles, u8 at a position, f32[3] world position.

23 EMITTER_REMOVE

u64 emitter

24 GRASS

GrassSettings of grass, sent when they changed: u64 grass, u64 object it grows on, string template (a path in the node’s resource path, empty for none), u64 blade image asset (0 none), f32 density, length scale, width scale, view distance, f32[4] color, f32 min height, max height, max slope (degrees), coverage, noise scale, u32 seed.

25 GRASS_REMOVE

u64 grass

Table 46.7 Assets

Kind

Data

1 mesh

u8 flags (1 double sided, 2 full precision: keep float positions on the GPU, for ground a particle surface adheres to), u32 vertex count n, f32[3] positions; four optional vertex arrays, each u32 count (0 or n) and values: f32[3] normals, f32[4] tangents (w: bitangent sign), f32[2] uv set 0, f32[2] uv set 1; u32 count (0 or n) and u8[4] RGBA vertex colors; u32 count (0 or n), u32[4] bone indices and f32[4] bone weights per vertex (skinned meshes, see SKIN); u32 index count and u32 indices (triangle list, counter-clockwise seen from the front); u32 subset count and per subset u32 first index and u32 index count.

2 image

string file extension (.png, .jpg, .dds, …), u32 size, the image file

3 material

Metallic-roughness PBR as in glTF: u8 shading (0 PBR, 1 unlit), u8 blend (0 opaque, 1 alpha, 2 premultiplied, 3 additive, 4 multiply), u8 flags (1 double sided, 2 casts shadows, 4 receives shadows, 8 multiply base color by vertex colors, 16 the surface texture’s R is occlusion, 32 use the occlusion texture), f32[4] base color (linear RGBA), f32[4] specular color, f32[3] emissive color and f32 emissive strength, f32 roughness, metalness, reflectance, alpha cutoff (1: no alpha test), normal map strength, transmission, refraction, clearcoat, clearcoat roughness, f32[4] uv scale (xy) and offset (zw), then five textures, each u64 image (0 none) and u8 uv set: base color (sRGB), normal (tangent space), surface (occlusion R, roughness G, metalness B), emissive (sRGB), occlusion (R).

46.18. Example scripts

data/python_agxrender contains runnable examples for each feature on this page. A scene that needs more than one file has its own directory with the entry script run.py and its scene-specific modules beside it (track_runner_forest_trail/run.py). modules/ holds only building blocks that several scenes share: path_following, panda, drone, procedural (noise and grid meshes for generated landscapes) and rock_canyon. A selection:

Script

Shows

template_agxrender.py

Starting point for new scripts: multiple scenes, runnable with agxViewer or directly

material_color_demo.py, clay_studio_wheel_loader.py

Materials (metals, clear coat, transmission, emissive, textures, presets) and 3D labels

light_show.py, environmentmapping.py, background_color.py

Lights, environment maps, background colors, exposure and bloom

fog.py, weather_effects.py, worksite_wheel_loader.py

Fog, rain, wind, realistic sky and volumetric clouds

mesh_visuals.py

Visual-only meshes built in code (createMeshVisual())

tutorial_signed_distance_field.py

Signed distance field collision shapes and their error visual (createSignedDistanceFieldVisual())

cables.py, wire_renderer.py, tutorial_wire*.py

Cable and wire rendering

usd_import.py

USD models (.usda, .usdc, .usdz): materials, instancing, skinning, animation (USD models)

character_walk.py, gaussian_splat_viewer.py

Attached models with skeletal animation, Gaussian splats

lunar_base_operations.py (tools/rig_astronaut.py, tools/retarget_cmu.py)

Skeletons driven from code (setBonePose()): motion-captured astronauts walking, working and kneeling with IK foot planting on the terrain and steering, around a cargo lander unloading a payload with a 4-joint robotic arm; see Driving a skeleton from code (character animation)

cameraControl.py

Camera poses, camera follow and keyframed camera paths

terrain_visualization_gallery.py, bulldozer_terrain.py, excavator_336_terrain.py

Terrain visualization modes, particle upsampling

tutorial_camera.py, tutorial_lidar.py, camera_sensor_showcase.py, sensor_carousel.py, depth_of_field.py

Camera and lidar sensor visualization

fisheye_camera_showcase.py

The fisheye camera reference implementation: lens projections, distortion, vignetting, chromatic aberration, depth read-back

cat_d3_worksite_scenario.py

A dozer grading terrain with lidar-based blade control, lidar point cloud with LidarVisualizationSettings, and GPU particle emitters for dust and exhaust

winter_road_clearing_scenario.py

A wheel loader on agxTerrain.TerrainWheel tires plowing 50 cm of deformable snow off an asphalt road: terrain minimum heights over a static road bed, upsampled snow particles, falling snow, snow poles and procedural snowy spruces

vegetation_tree_hill.py, vegetation_meadow.py

Grass and scattered models (trees, shrubs, rocks) on a height field

cluster_lod_helmets.py

10 000 instances of one model in a grid (onePerTriangle), cluster LOD on/off and its screen space error

tutorial_forest_hill.py

A forest on a hill, step by step: two grass layers, Poly Haven firs and pines with impostors, forest floor and meadow flowers, all grown on a mesh limited to the hill

car_test_ground.py

A 1 km vehicle test area with a 3 km closed track: the OpenPLX VolvoEX90 with its tires replaced by agxVehicle.GTire, tire deformation, selectable paint colors, grass and woods kept off the track, wheel dust, a lake, and a roof-mounted time-of-flight depth camera with a toggleable preview

gtire_deformation.py

Tire visuals that flatten against the ground and wrap over obstacles (setTireDeformation()), on the GTires of the OpenPLX VolvoEX90; inflation pressure and deformation toggled with keys

drone_scenario.py (classes in modules/drone)

A reusable quadcopter on one rigid body: simulated rotors, agxModel aerodynamics and gusty wind, cascaded flight control, missions (paths, go-to, follow an object, land), a stabilized gimbal camera sensor, keyboard/gamepad piloting

quadtrack_excavator_canyon.py (modules/rock_canyon.py)

The OpenPLX QuadTrackExcavator, modelled in Blender, walking over layered rock on four levelling track-pod legs and digging scree on its own, a ducted-fan drone (modules/drone with a glTF airframe) overhead, in a canyon with a stratified cliff, hazy mountains and a cloudy sky

wheelloader_algoryx_canyon.py

The OpenPLX AlgoryxWheelLoader in the same canyon, driven through its signal interface: a Y-cycle autopilot digs loose limestone out of the scree with an agxTerrain shovel (colliding with a signed distance field of the bucket mesh) and builds a spoil heap, on TerrainWheel tires; glowing red trim, a day / moonlit night switch with headlights, arrow-key driving, wheel dust and a HUD

track_runner_forest_trail/run.py (landscape in forest_trail.py beside it)

The OpenPLX AlgoryxTrackRunner, a high-speed tracked vehicle modelled in Blender (in-arm suspension, sprung idler, rubber band tracks, glazed cabin), on a 1.1 km forest trail with whoops, a crest, logs, a creek and a rock garden; ~1900 trees with static colliders (one shared model, placed by single-instance scatters), a power-limited traction controller, autopilot and arrow-key driving, track dust, exhaust smoke and a camera director

wheelloader_quarry_scenario.py

A wheel loader loading a dump truck on deformable gravel: HUD buttons for switching between autopilot and manual driving, a paged quarry floor drawn by TerrainPagerRenderer, soil drawn as a particle surface with grains and tire deformation

wheelloader_quarry_cameras.py

The quarry with ten HD camera sensors on the wheel loader recorded to Rerun, also with the cameras on render nodes; see Recording sensor data with Rerun

submarine_ocean.py, dune_buggy_scenario.py

The ocean (above and below the surface), particle emitters, and TerrainPagerRenderer

ship_in_ocean.py

A ship hull (models/shipHull.obj) and barrels floating on the rendered ocean: OceanWaterPatch water for agxModel.WindAndWaterController

deformable_finger.py, deformable_muscle.py, soft_pad_gripper.py

agxModel.DeformableObject surface meshes updated every step

particle_bucket.py, granularBodies_gpu.py

Particle upsampling and rendering of agx::ParticleSystem without terrain

particle_surface_digging.py

Soil particles drawn as a continuous surface (setTerrainParticleSurface()) while OpenPLX wheel loader / excavator buckets and a bulldozer blade dig; key m compares it with upsampled and plain particles

randomization_dual_robot.py

Domain randomization of materials, lights and environment maps (synthetic training data)

tutorial_explicit_stepping.py

Driving the frame loop from Python (begin/step/end session)

lunar_cruiser_moonscape.py

An OpenPLX model loaded and visualized with agxRender

showcase/run.py

A PySide6 desktop application with an embedded agxRender view

46.19. The agxViewer application

agxViewer is the ready-to-run interactive viewer application built on agxRender::Application. It opens .agx, .aagx,``.py`` (calling build_scene(sim)), (when built with OpenPLX support) .openplx files, and 3D model files (.fbx, .gltf, .glb, .obj, .usd, .usda, .usdc, .usdz, .wiscene – see Viewing 3D model files):

agxViewer scene.py --startPaused --stopAfter 10 --captureVideo 1 --videoName demo.webm

Any other file type is rejected with an error that lists the supported formats, and the viewer exits with exit code 1:

> agxViewer something.webm
[agxViewer] Unsupported file format: something.webm
  Supported: .agx .aagx .openplx .py .py, and 3D models .fbx .gltf .glb .obj .usd .usda .usdc .usdz .wiscene

As with agxOSGViewer, make sure to run the installed setup_env script first so the executable can find its dependent libraries:

configuration\setup_env.bat
agxViewer scene.py

Press CTRL-C in the console to stop the viewer gracefully (a video capture in progress is finalized); press it a second time to force it to quit.

Full help, including every flag and keybinding below, is always available at:

agxViewer --help

46.19.1. Command-line arguments

Table 46.8 Arguments to agxViewer

Argument

Explanation

-h, --help

Print help and exit

--agxFile <file>

Scene file to load (equivalent to a positional scene-file argument)

--agxOnly, -a

Only step the simulation – no window, no graphics context, no rendering at all (default: 0). Implies --realTime 0 unless --realTime 1 is given explicitly

--captureDirectory <dir>

Directory for captured images (default: imageCapture), created automatically if missing

--captureFiletype <type>

Image format: jpg, png, or bmp (default: jpg)

--captureFPS <fps>

Video/image capture frame rate (alias: --videoFPS)

--captureImage <0|1>

Enable image sequence capture (default: 0)

--captureImageName <name>

Image base filename: <name>_000001.<ext> (default: image)

--captureVideo <0|1>

Enable video capture (default: 0)

--borderless <0|1>

Window without border and title bar (default: 0)

--fullscreen <0|1>

Start in borderless fullscreen, no window decoration (default: 0). Press ‘f’ at runtime to toggle

--graphicsSettings <file>

Load graphics_settings.json from this path at startup, taking precedence over the default lookup (AGX resource path, then the current directory)

--headless <0|1>

Run without a visible window (default: 0). A graphics context is still created off-screen, so camera sensors and video/image capture of the main view still work

--height <pixels>

Window height (default: 720)

--landscape

Use the WickedEngine landscape terrain renderer instead of the default heightfield mesh renderer

--maxStepsPerFrame <n>

With --realTime 1, max simulation steps taken back-to-back before a render if the simulation is slower than real time (default: 1)

--noLogo

Hide the Algoryx logo overlay (default: shown)

--numThreads <n>

Number of AGX threads (agx::setNumThreads), applied after each scene load; Alt+1-9 changes it at runtime, Alt+0 uses all CPUs

--pixelStreaming <0|1>

Stream the rendered scene to a browser over WebSocket (default: 0); combine with --headless for a fully remote session

--pixelStreamingBitrate <kbps>

Pixel-streaming VP9 target bitrate, kbit/s (default: 4000)

--pixelStreamingKeyframeInterval <n>

Pixel-streaming max frames between keyframes (default: 60)

--pixelStreamingPort <port>

Pixel-streaming WebSocket port (default: 9002)

--realTime <0|1>

Throttle simulation to wall clock (default: 1; default: 0 when --agxOnly is given)

--renderAxis <0|1>

Show the corner axis orientation gizmo (default: 1)

--renderDebug <0|1>

Enable debug rendering (default: 0)

--renderEffects <file>

Load render_effects.json (fog, rain, sun, environment-map intensity – see the F6 Render Effects window) from this path at startup, taking precedence over the default lookup

--renderStats <0|1>

Show the render statistics overlay (default: 0)

--renderVis <0|1>

Enable/disable visual rendering (default: 1). Aliases: --renderViz, --renderOsg, --render

--saveScene <file>

File Shift+O saves the simulation to: .agx (binary) or .aagx (ASCII) (default: saved_scene.agx)

--scene <n>

Load the n-th registered scene (1…n) at startup; press 1-9 or +/- to switch at runtime

--simulationHost [port]

Send the rendered scene to render nodes (agxRenderNode) that connect to this port (default 9003), see Distributed rendering: render nodes

--cameraGroup <file>

Views of the viewer camera that render nodes show by name, for several screens side by side (JSON), see Distributed rendering: render nodes

--startPaused, -p

Start the simulation paused

--stopAfter <s>, -s <s>

Stop the simulation after N seconds of simulation time

--stopAfterStep <n>

Stop once N simulation steps have been taken (alias: --stopAfterFrame)

--stopAt <s>

Stop once simulation time reaches N seconds

--synchronize <0|1>

Sync video/image capture to simulation time; 0 = capture on wall clock (default: 1)

--targetFPS <fps>

Target render frame rate (default: 60)

--threadedSimulation <0|1>

Step the simulation on its own thread, decoupled from rendering (default: 1), see Threaded simulation

--cameraSensorSync <0|1>

Wait for camera sensor images before the next step, for controllers that act on them (default: 0), see Synchronous camera sensors

--timeStep <s>, -t <s>

Simulation time step (dt); overrides the scene’s own

-v, --version

Print version information and exit

--videoBitrate <kbps>

Video target bitrate in kbit/s; 0 = constant quality, see --videoQuality (default: 0)

--videoName <file>

Video output filename (.webm)

--videoQuality <0-63>

Video quality, lower is better and larger: 12 near-lossless, 20-30 smaller files, 40+ artifacts (default: 12)

--videoSpeed <0-9>

Video encoder speed, higher is faster (default: 6)

--videoThreads <n>

Video encoder threads; 0 = half of the logical processors (default: 0)

--vsync <0|1>

Synchronize to the display refresh rate; overrides graphics_settings.json (default: its vsync entry, else 0)

--position <x> <y>

Window position: its contents’ top-left corner on the desktop, in screen coordinates

--webDebugger <port>

Enable the web debugger on the given port

--width <pixels>

Window width (default: 1280)

--window <width> <height>

Set both window dimensions at once (default: 1280 720)

Any other flag-shaped argument (starting with - or --) not listed above is a hard parse error rather than being silently ignored (the only exceptions are WickedEngine’s own graphics-debugging flags --debugdevice, --gpuvalidation and --gpu_verbose, which are passed on to the renderer) – unlike agxOSG, agxViewer does not pass unrecognized flags through to a script’s sys.argv (see Moving from agxOSG to agxRender for how to adapt a script that relied on this). Positional arguments are treated as scene files (.agx, .py, .fbx, etc.).

When AGX is built with unit tests (AGX_BUILD_UNIT_TESTS), agxViewer – and any C++ or Python program that parses its command line with agxRender::Application – also accepts the unit testing arguments of agxOSG::ExampleApplication. In a build without unit tests these arguments are an error.

Table 46.9 Unit testing arguments

Argument

Explanation

--cycleThroughScenes

Run every registered scene in turn, each until --stopAfter, --stopAt or --stopAfterStep is reached, starting at --scene and wrapping around, then exit. Works with and without --agxOnly. A scene that fails to load makes the run fail. Also available as Application::setCycleThroughScenes()

--unittest, -u

Enable unit testing: a failed agxUnit assertion or an exception while loading or running a scene is reported and makes the run fail (non-zero exit code)

--onlyFastUnittests

Only run fast unit tests

--unittestPassOnExceptions

Let exceptions propagate instead of reporting them

--disableUnittest

Disable unit testing again

--determinism

Run as a determinism test

--isFileSanityUnitTest

Mark the run as a file sanity test

For example, the C++ tutorials are tested with tutorial_x --agxOnly --stopAfterFrame 5 --cycleThroughScenes --unittest.

46.19.2. Keyboard and mouse bindings

These bindings apply both to a local window and to a connected PixelStreamingViewer browser session (see Pixel streaming: remote viewing in a browser). Letter keys are case-sensitive: a plain letter means the lowercase key only (for example f toggles fullscreen, F/Shift+F does not). Press h in the viewer to show this list on screen.

Table 46.10 Keyboard/mouse bindings

Key

Description

Esc

Quit

Space

Reset/fit camera view to the scene

h

Show/hide the list of keybindings

c

Print the current camera pose as a Python snippet (mirrors agxOSG’s ‘c’)

e

Toggle play/pause

r

Step the simulation forward one time step (works whether running or paused); hold to keep stepping

f

Toggle fullscreen

w

Toggle wireframe rendering

g

Toggle debug rendering

Shift+G

Toggle scene visuals

Up/Down

Scale the debug rendering glyphs by 10 % (unless a script’s keyboard listener handles the key); also the Debug Glyph Scale slider in F1, saved as debug_render_scale

Shift+Q

Toggle real-time pacing

Shift+L

Print the sun direction as a Python snippet

Shift+O

Save the scene to the --saveScene file (default saved_scene.agx)

Shift+P

Store the rendered meshes and materials in the shapes’ RenderData, so a following Shift+O saves them (see Saving the rendered visuals in a .agx file)

Shift+Z

Save WickedEngine scene to saved.wiscene

F1

Toggle the settings window

F2

Toggle the profiler overlay

F3

Toggle the render stats window

F4

Toggle the AGX stats overlay

F5

Toggle the camera path window

F6

Toggle the Render Effects window (fog, rain, wind, sky, clouds, sun)

F7

Toggle the Render Node window (render nodes only: connection, view, camera sensor images)

F10

Toggle video capture on/off

F12

Toggle image capture on/off

Shift+F12

Save a single screenshot

1-9, +/-

Switch/cycle scenes registered via –scene

Alt+1-9, Alt+0

Set the number of AGX threads, Alt+0: all CPUs

Left-drag

Orbit camera around the current target

Right-drag

Look around (first-person); with W/A/S/D/Q/E, fly; hold Shift to move faster; the wheel changes the fly speed (by default the scene crosses in ~20 s, at most 10 m/s)

Middle-drag

Pan camera

Scroll

Zoom

Ctrl+Left-click(-drag)

Pick and drag a physics body (left Ctrl, as in agxOSGViewer)

Ctrl+Right-click(-drag)

Pick and drag a physics body (agxOSG-style alternate gesture)

Ctrl+L+Left-drag

Rotate the sun direction

Ctrl+M+Left-click

Follow the clicked kinematic/dynamic body, with orbit control; any other click detaches the camera

46.19.3. Viewing 3D model files

agxViewer shows a .fbx, .gltf, .glb, .obj, USD (.usd, .usda, .usdc, .usdz) or .wiscene (WickedEngine scene, e.g. one saved with Shift+Z) file on its own, without a script – handy for checking an asset before using it in a scene:

> agxViewer resources\tree1\Tree.fbx
[agxViewer] resources\tree1\Tree.fbx: model size 0.0363381 0.0354523 0.0382196 m

The model is placed at the origin (attached to a hidden, non-colliding geometry, so nothing is simulated), and once it has loaded the camera is aimed at it from the front right and slightly above, with clipping planes scaled to its size. The printed size (x, y, z in meters, in AGX’s Z-up axes) shows at a glance whether a file uses other units – the tree above is modelled in centimeters and needs a scale of about 250 to become a 9 m tree (see Vegetation: grass and scattered models). A missing file, or a file that fails to load, is reported:

> agxViewer nope.fbx
[agxViewer] File not found: nope.fbx

All the viewer’s usual options apply, e.g. --captureImage 1 for a screenshot. Note that Space (fit view to the scene) fits the view to the scene’s collision geometries, not to the model, so here it zooms in on the hidden geometry at the origin; scroll out, or restart the viewer to get the initial view back.

46.19.4. USD models

USD files (.usd, .usda, .usdc and .usdz packages) load wherever a glTF or FBX model does: createVisual(geometry, modelPath), attachModel(), createModelScatter() and agxViewer. agxRender reads them with OpenUSD (the same package the OpenPLX USD plugin uses); a build without OpenUSD reports the file as unsupported. data/python_agxrender/usd_import.py shows the supported features on generated test assets.

  • Axes and units: the stage’s upAxis (Y or Z) and metersPerUnit are applied, so a Z-up model in centimeters comes in upright and in meters.

  • Scene graph: the xform hierarchy (resetXformStack included), visibility and purpose (guide and proxy prims are skipped), payloads and variants (default selections), native instancing (instances share one mesh) and PointInstancer.

  • Geometry: Mesh with any polygon size, holes and leftHanded orientation; indexed primvars of every interpolation; normals (computed when missing: smooth for subdivision surfaces, faceted for subdivisionScheme = "none"); two texture coordinate sets; displayColor/displayOpacity as vertex colors or material color; GeomSubset material binding. Cube, Sphere, Cylinder, Cone, Capsule and Plane are tessellated. Subdivision surfaces render as their control mesh.

  • Materials: UsdPreviewSurface with UsdUVTexture, UsdPrimvarReader_float2 and UsdTransform2d (scale and translation; rotation is ignored): diffuse color, opacity (blend, or cutout with opacityThreshold), roughness, metallic and occlusion (packed into one texture when they come from separate files), normal map, emission, ior, clearcoat. The specular workflow is approximated by a dielectric. OmniPBR (MDL) materials, as in Isaac Sim assets, are read from their constant and texture inputs. Textures inside a .usdz package are read directly from it. MaterialX networks are not supported.

  • Skinning: UsdSkel skeletons become armatures, with up to 8 joint influences per point, blend shapes and their weights, and joint animation.

  • Animation: joint, blend shape and xform time samples form one clip named after the file; play it with getAnimationNames()/playAnimation(). Animated points and visibility are not imported.

  • Lights and cameras: DistantLight, SphereLight (spot with ShapingAPI), DiskLight and RectLight become lights, their intensity converted from luminance; DomeLight is ignored (the environment is set through agxRender). Perspective cameras are imported.

46.19.5. Saving the rendered visuals in a .agx file

Shift+O writes the simulation to saved_scene.agx (or the --saveScene file), but a shape’s visual only ends up in the file if the shape carries it in its agxCollide::RenderData. Visuals that exist only in agxRender – primitives given a color or material from Python, attached models (attachModel()/createVisual(..., modelPath)), textures set with setBaseColorTexturePath() etc. – are lost. Press Shift+P before Shift+O to store them: for every shape agxRender renders, its RenderData is replaced with what the shape is rendered with:

  • Mesh: vertices, normals, tangents, texture coordinates and vertex colors of the rendered mesh (LOD 0), in the shape’s local frame. Primitives (box, sphere, cylinder, …) are stored as the rendered, scaled mesh. An attached model is merged into one mesh together with the shape’s own mesh if that is shown too (hideSourceVisual=False). A texture scale/offset/rotation (setTextureScale() etc.) is baked into the texture coordinates.

  • Material: an agxCollide::RenderMaterial with base color, opacity, roughness, metalness, specular, ambient and emissive color, and the base color, normal, roughness/metalness and emissive textures. A texture loaded from a file is stored as its path; an embedded texture (OpenPLX, or an image embedded in a glTF/FBX model) as pixel data in the file. A surface (occlusion/roughness/metalness) texture is stored as both the roughness and the metallic texture. A merged model gets the material of its first mesh; its other materials are lost.

Shapes rendered alike (same mesh, scale and material, e.g. OpenPLX track shoes) share one RenderData, so the file doesn’t grow with the number of instances. Terrain, wires, cables, deformables and meshes created with createMeshVisual() are not stored.

Press Shift+P again after changing visuals to store their current state. During the session agxRender keeps rendering each shape from the RenderData it had before Shift+P, so storing the visuals doesn’t change what is shown; a loaded saved_scene.agx is rendered from the stored RenderData. Properties a RenderMaterial has no field for – transmission, index of refraction, blend mode and shadow flags – are not stored.

46.19.6. Multi-scene scripts and custom SceneLoader

A single .py file can define several selectable scenes by naming its build functions build_scene1(sim), build_scene2(sim), etc. (1-based, matching the 1-9 keys and --scene N). agxViewer’s default scene loader detects the highest build_sceneN defined and automatically registers that many scene slots – no extra configuration needed:

def build_scene1(sim):
    """RGB camera demo."""
    ...

def build_scene2(sim):
    """Depth camera demo."""
    ...
agxViewer tutorial_camera.py --scene 2

For file formats agxViewer does not open (or when scene switching should rebuild a fresh agxSDK::Simulation from scratch each time rather than reusing state), implement agxRender.SceneLoader and register it with Application.setSceneLoader():

class MySceneLoader(agxRender.SceneLoader):
    def loadFile(self, filename, scene_index):
        sim = agxSDK.Simulation()
        # ... build a Simulation for sceneo_index, or from `filename` ...
        return sim

app = agxRender.Application()
app.setSceneLoader(MySceneLoader())
app.setSceneFiles(["1", "2", "3"])   # placeholders; loadFile() decides what they mean

A script that runs its own session (python script.py) can use agxPythonModules.agxRender.scene_loader.ScriptSceneLoader instead: like agxViewer, it executes the script file again on every load and calls build_sceneN(sim) or build_scene(sim), so edits to the script take effect when a scene is reloaded (1-9). Modules the script imports are not reloaded. If the edited script fails, the error is printed and the scene stays empty until it is fixed and reloaded:

from agxPythonModules.agxRender.scene_loader import ScriptSceneLoader

if __name__ == "__main__":
    app = agxRender.Application()
    app.setSceneLoader(ScriptSceneLoader())
    if not app.parseArgumentList(sys.argv):
        raise RuntimeError("agxRender.Application.parseArgumentList failed")
    app.setSceneFiles(["1"])   # after parseArgumentList(), which clears the list
    if not app.run():
        raise RuntimeError("agxRender.Application.run failed")

46.20. Moving from agxOSG to agxRender

agxRender is designed so that porting a scene-building script is mostly a mechanical substitution, not a rewrite. The concepts map one-to-one, but a few defaults and contracts differ deliberately – summarized below.

46.20.1. Conceptual mapping

agxOSG

agxRender

agxOSG::ExampleApplication

agxRender::Application (see The agxViewer application)

agxOSGViewer

agxViewer

agxOSG::createVisual(geometry, root, detailRatio, createAxes, evenIfSensor)

agxRender.createVisual(geometry, options) – returns a VisualHandle instead of an osg::Group*; no scene-graph root parameter to manage

agxOSG::setDiffuseColor(node, color) / material node setters

agxRender.setBaseColor(handle, color), setRoughness, setMetalness, … on a VisualHandle, or an agxRender.Material object for a full PBR material shared across visuals

agxOSG::readFile(filename, sim, root)

agxRender.readFile(filename, sim)

agxOSG::TerrainVoxelRenderer

agxRender.createTerrainRenderer() + TerrainRendererHandle (see Terrain visualization)

agxOSG::NeoCameraSensorBackend::configure()

agxRender.registerCameraSensorBackend()

agxOSG::LidarOutputRenderer

agxRender.addLidarVisualization(lidar)

ExampleApplication::CameraData / --cameraSettingsFile

agxRender.CameraData / agxRender.getCameraData() / applyCameraData()

agxOSG::createAxes(...)

agxRender.createAxes(...) (same idea: tracks a frame/body/geometry/constraint)

simulation->getRenderManager()->setFlags(...)

agxRender.setDebugRenderFlags(...) (same agxSDK::RenderFlags bitmask)

OpenSceneGraph 3D rendering, GLX/EGL contexts

WickedEngine (DirectX 12 / Vulkan) rendering

46.20.2. Key behavioral differences

  • No implicit visuals. agxOSG’s ExampleApplication can be configured to create visuals for an entire simulation automatically; a plain agxRender script must call agxRender.createVisual() per object. To keep the “just show me everything” workflow when porting a script that relied on this, call agxRender.createVisualsForSimulation(sim) once after populating the simulation.

  • No scene-graph handle to manage. Because agxRender doesn’t expose an osg::Group scene graph, there’s no equivalent of manually re-parenting or removing OSG nodes – destroyVisual(handle) and clearScene() cover the lifetime management agxOSG scripts did through the scene graph directly.

  • Unrecognized command-line flags are a hard error. agxOSG’s init_app() forwarded any flag it didn’t recognize into a script’s own sys.argv/argparse handling. agxRender::Application::parseArguments() instead rejects any unrecognized -/-- flag outright. A script that defines its own custom flags must parse sys.argv itself with argparse before handing off to agxRender, removing its own flags from the list passed to parseArgumentList(), rather than relying on the viewer to pass an unknown flag through.

  • Materials are richer, and shareable by reference. agxOSG’s node-level diffuse/specular setters are still available as free functions (setBaseColor, setRoughness, …), but agxRender.Material adds real PBR (metalness/roughness/transmission/IOR), texture maps, and reference-shared propagation to every visual it’s applied to – there’s no equivalent object in agxOSG.

  • Video capture is VP9/WebM, not FFmpeg/MP4. --videoName must end in .webm; there’s no external FFmpeg process to manage or fail to find on PATH.

  • The renderer is DirectX12/Vulkan (WickedEngine), not OpenGL. The Linux/EGL headless rendering notes for agxOSGViewer are specific to agxOSG’s OpenGL/GLX path and do not apply to agxRender; use --headless 1 for off-screen rendering with agxRender instead.

  • The keyboard scheme is different. agxOSG/agxOSGViewer’s bindings (Key bindings) and agxViewer’s (Keyboard and mouse bindings) share a few mnemonics (e play/pause, r single-step, C/c print camera) but are otherwise independent – review both tables rather than assuming a 1:1 match.

46.20.3. Porting checklist

  1. Replace agxOSG::createVisual(geometry, root, ...) calls with agxRender.createVisual(geometry, options), dropping the root scene-graph argument and keeping the returned handle instead of the osg::Group*.

  2. Replace direct OSG material/color node manipulation with agxRender material free functions or an agxRender.Material object.

  3. If the script defines a custom command-line flag, parse it with argparse against sys.argv yourself, then pass only recognized agxRender flags on to Application.parseArgumentList().

  4. Rename any .mp4/FFmpeg-based video capture configuration to .webm.

  5. Swap agxOSG::TerrainVoxelRenderer setup for agxRender.createTerrainRenderer() plus the relevant TerrainVizAPI options structs.

  6. If the script used agxOSG::NeoCameraSensorBackend::configure() or agxOSG::LidarOutputRenderer, switch to agxRender.registerCameraSensorBackend() / agxRender.addLidarVisualization() – remembering that the camera backend must be registered before constructing any agxSensor::Camera.

  7. Re-review keyboard shortcuts your users rely on against Keyboard and mouse bindings – do not assume agxOSG muscle memory carries over exactly.

  8. Both modules can run side by side during migration: keep the agxOSG entry point behind its own if __name__ == "__main__": guard and add a separate build_scene(sim) for agxViewer, or vice versa, until the port is validated.

46.20.4. Old agxRender debug rendering classes, now in agxSDK

Before

After

#include <agxRender/RenderManager.h> (also RenderProxy.h, RenderProxyFactory.h, RenderSingleton.h, Renderable.h, Graph.h)

#include <agxSDK/RenderManager.h> (and so on, same file names)

agxRender::RenderManager, agxRender::RenderProxy, agxRender::RenderProxyFactory, agxRender::RenderSingleton, agxRender::Renderable, agxRender::Graph, agxRender::GraphRenderer

agxSDK::RenderManager, agxSDK::RenderProxy, agxSDK::RenderProxyFactory, agxSDK::RenderSingleton, agxSDK::Renderable, agxSDK::Graph, agxSDK::GraphRenderer

Shape proxies agxRender::SphereProxy, BoxProxy, CylinderProxy, LineProxy, TextProxy, … and the RENDER_* flags, e.g. agxRender::RENDER_DEFAULT

agxSDK::SphereProxy, … and agxSDK::RENDER_DEFAULT

agxRender::debugRenderConstraintFrames()

agxSDK::debugRenderConstraintFrames()

Remote debugger proxies in agxSDK/RemoteDebugRenderProxy.h: agxSDK::SphereProxy, agxSDK::BoxProxy, …

agxSDK::RemoteSphereProxy, agxSDK::RemoteBoxProxy, … (renamed so that they do not clash with the debug rendering base classes)

Python: import agxRender, agxRender.RenderManager, agxRender.RENDER_CONTACTS

import agxSDK, agxSDK.RenderManager, agxSDK.RENDER_CONTACTS

Java package agxRender / C# namespace agxRender

Java package agxSDK / C# namespace agxSDK

46.21. Generating the screenshots used in this document

Every screenshot on this page was captured headlessly from an unmodified script in data/python_agxrender, using agxViewer’s image capture. After running setup_env, from data/python_agxrender:

agxViewer <script> [--scene N] --headless 1 --window 1280 720 --realTime 0 ^
    --captureImage 1 --captureFiletype png --captureFPS 2 ^
    --captureImageName <name> --captureDirectory <dir> --stopAfter <seconds>

Image capture writes a numbered sequence (<name>_000001.png, …) keyed to simulation time; the last frame is the one at --stopAfter. HUD text and camera-sensor previews are included in the captured images. The frames were converted to JPEG for the documentation.

Table 46.11 Screenshots

File (images/)

Script

Options

Frame

agxrender_cables.jpg

cables.py

--stopAfter 3

last

agxrender_material_gallery.jpg

material_color_demo.py

--stopAfter 8

last

agxrender_wireframe_overlay.jpg

clay_studio_wheel_loader.py

--scene 1 --stopAfter 4

last

agxrender_lights.jpg

light_show.py

--scene 1 --stopAfter 5

last

agxrender_environment_map.jpg

environmentmapping.py

--stopAfter 3

last

agxrender_weather.jpg

weather_effects.py

--stopAfter 4

last

agxrender_mesh_visuals.jpg

mesh_visuals.py

--scene 1 --stopAfter 3

last

agxrender_terrain_height_gradient.jpg

terrain_visualization_gallery.py

--scene 1 --stopAfter 5

last

agxrender_terrain_wireframe.jpg

terrain_visualization_gallery.py

--scene 4 --stopAfter 6

last

agxrender_particle_upsampling.jpg

clay_studio_wheel_loader.py

--scene 2 --stopAfter 24

22 (t ≈ 10.5 s)

agxrender_camera_sensor_previews.jpg

camera_sensor_showcase.py

--stopAfter 5

last

agxrender_lidar_pointcloud.jpg

tutorial_lidar.py

--stopAfter 3

last

agxrender_vegetation.jpg

vegetation_tree_hill.py

--stopAfter 3

last

agxrender_gtire_tof_preview.jpg

car_test_ground.py

--stopAfter 10

last

agxrender_tire_deformation.jpg

gtire_deformation.py

--stopAfter 3

last