C++ Module: vizInterface

Executive Summary

This module provides an interface to package up Basilisk messages and pass them onto the Vizard application. This allows for the Basilisk simulation data to be recorded to a file for play-back, or for live streaming of the simulation data. It is possible to record the simulation data of a single spacecraft or a multitude of spacecraft.

Module Assumptions and Limitations

The module is only able to read Basilisk simulation state messages that are accessable from the task group that is calling vizInterface.

Message Connection Descriptions

The following messages are set directly within vizInterface. Additional messages are set within the VizSpacecraftData data structures for each spacecraft.

vizInterface module input and output messages

Module I/O Messages

Msg Variable Name

Msg Type

Description

cameraConfInMsgs

CameraConfigMsgPayload

(optional) Camera configurations registered through vizInterface.addCamMsgToModule(msg).

opnavImageOutMsgs

CameraImageMsgPayload

One image output per registered camera, in the same order as cameraConfInMsgs.

epochInMsg

EpochMsgPayload

(optional) simulation epoch date/time input msg

spiceInMsgs

SpicePlanetStateMsgPayload

(optional) vector of input messages of planet Spice data

The VizSpacecraftData structure, defined in vizStructures, contains a range of input messages for each spacecraft added.

VizSpacecraftData input messages per spacecraft

Parameter

Default

Description

scStateInMsg

SCStatesMsgPayload

msg of incoming spacecraft state data

rwInMsgs

RWConfigLogMsgPayload

(optional) Vector of incoming RW state messages

thrInMsgs

THROutputMsgPayload

(optional) vector of thruster input messages

cssInMsgs

CSSConfigLogMsgPayload

(optional) Vector of CSS config log messages

Handshaking Protocol

vizInterface facilitates the port configuration and handshaking process between BSK and Vizard. The current implementation of this protocol is defined here for developers, for use if an alternate visualization destination is desired.

BSK instantiates the broadcast socket using zmq_bind, and the 2-way socket using zmq_connect. Vizard joins these sockets using reciprocal connect and bind structure where appropriate.

The two-way socket couples BSK and Vizard in lockstep. During Reset, vizInterface sends PING, waits for a response, and sends another PING to prepare the first simulation exchange. A simulation update consists of SIM_UPDATE, two empty frames, and the serialized simulation protobuf. The module then waits for Vizard’s OK response.

In liveStream mode, REQUEST_INPUT requests user input from Vizard. The reply begins with a status string, followed by the serialized user-input protobuf. VIZARD_INPUT indicates success, while ERROR indicates a failed request. Camera image requests use REQUEST_IMAGE_<cameraID>. Headless mode sends a keep-alive PING after each simulation exchange.

See Camera Image Cadence for image timing and startup behavior. For more specifics in message packaging and handling, see the source code for this module.

User Guide

The vizInterface module can be directly configured, or setup using the helper methods in vizSupport. More information can be found in BSK Scripting Settings page. The scenarioFormationBasic illustrates and discusses how to configure vizInterface for use with multiple satellites.

Camera Image Cadence

In liveStream and noDisplay modes, each registered camera’s CameraConfigMsgPayload controls image requests. Despite its name, renderRate is a time interval, not a frequency. The units depend on how you configure the camera:

  • The Python helper vizSupport.createCameraConfigMsg accepts renderRate in seconds and converts it to nanoseconds. Pass renderRate=3.0 for a three-second interval.

  • The message payload’s renderRate field stores nanoseconds. When editing a payload directly, use cameraConfig.renderRate = macros.sec2nano(3.0) for the same interval.

An image is requested when the camera is on (isOn == 1), its interval is positive, and the current simulation time is an exact multiple of that interval. The module must execute at that time; missed image times are not queued for later delivery. For example, a three-second interval with module updates every second produces requests at 3, 6, 9 seconds, and so on. No simulation updates or image requests are sent at simulation time zero.

A zero renderRate disables image requests for that camera, even when isOn == 1. No new message is written to its opnavImageOutMsgs entry while requests are disabled. An image already published remains in the output message, including its valid flag and timestamp. Consumers should check the message’s write time or the payload’s timeTag to distinguish a new image from a retained one. Before the first image, the output message is unwritten and its zero payload has valid = 0 and timeTag = 0.

Delayed Camera Configuration

To start taking images later, publish valid camera settings with a zero interval before initializing the simulation. When images are needed, set a positive interval and isOn = 1, then write the updated payload to the same message. Changing the Python payload alone does not update the message.

The following example extends an existing simulation scSim with a spacecraft scObject already added to the task named simTaskName. The task runs every second, starting at simulation time zero. Run this setup before InitializeSimulation and keep cameraMsg alive throughout the simulation. Vizard must be running to answer the headless connection request.

from Basilisk.utilities import macros, vizSupport

viz = vizSupport.enableUnityVisualization(
    scSim, simTaskName, scObject, noDisplay=True
)
cameraConfig, cameraMsg = vizSupport.createCameraConfigMsg(
    viz,
    cameraID=1,
    parentName=scObject.ModelTag,
    fieldOfView=40.0 * macros.D2R,  # [rad]
    resolution=[640, 480],  # [pixel]
    cameraPos_B=[0.0, 0.0, 1.0],  # [m]
    sigma_CB=[0.0, 0.0, 0.0],  # [-]
    renderRate=0.0,  # [s] Helper argument: start without image requests.
)
cameraConfig.isOn = 1
cameraMsg.write(cameraConfig)

scSim.InitializeSimulation()
scSim.ConfigureStopTime(macros.sec2nano(14.0))  # [ns]
scSim.ExecuteSimulation()

# The simulation is now paused at 14 seconds; enable image requests.
cameraConfig.renderRate = macros.sec2nano(3.0)  # [ns] Payload field.
cameraMsg.write(cameraConfig, scSim.TotalSim.CurrentNanos)
scSim.ConfigureStopTime(macros.sec2nano(21.0))  # [ns]
scSim.ExecuteSimulation()

The helper creates, writes, and registers the camera input message; do not also call addCamMsgToModule for that message. If creating a message directly, register it with addCamMsgToModule(msg) before simulation initialization.

This example requests images at 15, 18, and 21 seconds. The module reads the new settings at its next update, and the interval remains aligned to simulation time zero. No reset is needed. Setting the payload’s interval back to zero and writing it again pauses requests; a later positive interval resumes them at multiples of that interval.

A registered input that has never been written also supplies a zero interval. It produces no image requests and does not prevent other configured cameras from requesting images, regardless of registration order. However, its default camera fields can still be sent to Vizard during simulation updates. Initializing the settings as shown above avoids sending an uninitialized camera configuration.

Headless Startup Exchange

Headless mode (noDisplay = True) still requires Vizard. A zero interval stops image requests, but startup communication still occurs. Simulation initialization waits for Vizard to respond, even when every camera has a zero interval.

For a newly constructed interface with at least one registered camera, startup sends simulation data to Vizard on the first 11 module updates after time zero. These exchanges let Vizard initialize its scene; they do not require cameras to request images. An enabled camera can still request images during startup when its positive interval is due.

After startup, headless mode sends simulation data only when at least one camera is due for an image. With all cameras paused or off, the module keeps reading configuration messages at its task rate so that image requests can resume later. Updating a camera does not restart the startup sequence. In the example above, startup exchanges occur at 1 through 11 seconds, followed by exchanges and image requests at 15, 18, and 21 seconds.

Each headless exchange waits for Vizard’s acknowledgement and sends a keep-alive message, as described under Handshaking Protocol. In liveStream mode, simulation data continues to be sent at every module update after time zero, regardless of camera intervals.


Defines

VIZ_MAX_SIZE
class VizInterface : public SysModel
#include <vizInterface.h>

Defines a data structure for the spacecraft state messages and ID’s.

Public Functions

VizInterface()

VizInterface Constructor

~VizInterface()

VizInterface Destructor

void Reset(uint64_t CurrentSimNanos)

A Reset method to put the module back into a clean state

Parameters:

CurrentSimNanos – The current sim time in nanoseconds

void UpdateState(uint64_t CurrentSimNanos)

Update this module at the task rate

Parameters:

CurrentSimNanos – The current sim time

void ReadBSKMessages()

A method in which the module reads the content of all available bsk messages

void WriteProtobuffer(uint64_t CurrentSimNanos)

The method in which the vizInterface writes a protobuffer with the information from the simulation.

Parameters:

CurrentSimNanos – The current sim time in nanoseconds

void addCamMsgToModule(Message<CameraConfigMsgPayload> *tmpMsg)

Method to add a Vizard instrument camera module to vizInterface

Parameters:

tmpMsg – Camera configuration msg

Public Members

std::vector<VizSpacecraftData> scData

vector of spacecraft data containers

std::vector<ReadFunctor<SpicePlanetStateMsgPayload>> spiceInMsgs

vector of input messages of planet Spice data

std::vector<LocationPbMsg> locations

vector of ground or spacecraft locations

std::vector<QuadMap*> quadMaps

vector of QuadMap regions

std::vector<GravBodyInfo> gravBodyInformation

vector of gravitational body info

std::vector<Message<CameraImageMsgPayload>*> opnavImageOutMsgs

vector of vizard instrument camera output messages

bool saveFile

[Bool] Set True if Vizard should save a file of the data.

bool liveStream

[Bool] Set True if Vizard should receive a live stream of BSK data.

bool broadcastStream

[Bool] Set True if messages should be broadcast for listener Vizards to pick up.

bool noDisplay

[Bool] Set True if Vizard should run performance opNav (no Vizard display)

std::vector<void*> bskImagePtrs

[RUN] vector of permanent pointers for the images to be used in BSK without relying on ZMQ because ZMQ will free it (whenever, who knows)

std::vector<ReadFunctor<CameraConfigMsgPayload>> cameraConfInMsgs

vector of incoming camera data messages

std::vector<MsgCurrStatus> cameraConfMsgStatus

vector of msg status of incoming camera data

std::vector<CameraConfigMsgPayload> cameraConfigBuffers

vector of Camera config buffers

int64_t FrameNumber

Number of frames that have been updated for TimeStamp message.

std::string protoFilename

Filename for where to save the protobuff message.

VizSettings settings

container for the Viz settings that can be specified from BSK

LiveVizSettings liveSettings

container for Viz settings that are updated on each time step

std::vector<VizEventDialog*> vizEventDialogs = {}

vector of dialog boxes to show

std::string reqComProtocol

Communication protocol to use when connecting to 2-way Vizard.

std::string reqComAddress

Communication address to use when connecting to 2-way Vizard.

std::string reqPortNumber

Communication port number to use when connecting to 2-way Vizard.

std::string pubComProtocol

Communication protocol to use when connecting to broadcast Vizard.

std::string pubComAddress

Communication address to use when connecting to broadcast Vizard.

std::string pubPortNumber

Communication port number to use when connecting to broadcast Vizard.

double broadcastSettingsSendDelay

Real-time delay between sending Viz settings to broadcast socket.

ReadFunctor<EpochMsgPayload> epochInMsg

simulation epoch date/time input msg

MsgCurrStatus epochMsgStatus

ID of the epoch msg.

EpochMsgPayload epochMsgBuffer

epoch msg data

Message<VizUserInputMsgPayload> userInputMsg

User input from Vizard.

BSKLogger bskLogger

BSK Logging object.

Private Functions

void receiveUserInput(uint64_t CurrentSimNanos)

request user input from Vizard, save as

During liveStream mode, ask Vizard for any user inputs recorded since the last timestep. Parse and package into VizUserInputMsgPayload for handling in Python.

Parameters:

CurrentSimNanos – The current sim time

void requestImage(size_t camCounter, uint64_t CurrentSimNanos)

request image from Vizard and store it in output img msg

Requests an image from Vizard and stores it in the image output message

Private Members

void *requester_context

2-way context pointer (container for socket management)

void *requester_socket

2-way socket pointer (ZMQ_REQ)

void *publisher_context

Broadcast context pointer (container for socket management).

void *publisher_socket

Broadcast socket pointer (ZMQ_PUB).

int firstPass

Flag to intialize the viz at first timestep.

std::vector<MsgCurrStatus> spiceInMsgStatus

status of the incoming planets’ spice data messages

std::vector<SpicePlanetStateMsgPayload> spiceMessage

Spice message copies.

std::ofstream outputStream

Output file stream owned by this module.

int64_t now

Current system time stamp.

int64_t lastSettingsSendTime

System time stamp when settings message was last sent to broadcast socket.

std::vector<std::unique_ptr<Message<CameraImageMsgPayload>>> ownedOpnavImageOutMsgs

Storage for opnavImageOutMsgs.