|
VR-Engage
2.3
|
The Player Station Framework provides the core infrastructure for VR-Engage frontend development. It manages the application lifecycle, coordinates component interactions, and provides the foundation for customizing and extending the user experience.
This page describes how to implement frontend plugins and components for VR-Engage.
Unless otherwise noted, the types described here are defined in the makVre namespace and are part of the VR-Engage frontend libraries.
The Player Station Framework organizes frontend functionality into a hierarchy of cooperating classes. At the top, DtPlayerStationApp manages the overall application and global services. Below that, DtPlayerStation instances represent individual player stations (Gunner, Pilot, etc), encapsulating the components necessary for handling player input, communicating with the Simulation Engine, and managing the player's view and HUD and/or instrumentation. A player station is built from Component instances derived from DtPlayerComponent. These components implement specific functionality such as renering a HUD or handling steering input. The DtPlayerStation instance manages instantiating and initializing the necessary Components based on the given role configuration.
Key concepts
DtPlayerStationApp): Top-level application controlDtPlayerStation): Manager components that form a single player station/role.DtPlayerComponent): Base class for all components of a player station.This architecture promotes modularity through composition. For example: a Driver role might combine a DtDriverControlLogic component to handle throttle and steering input, a DtSavedViewUpdater component to manage switching between a forward view and a backup camera view, and a DtQtQuickOverlay component to render dashboard guages. This approach allows reusing components across different roles and variations of roles for different entity types.
Application lifecycle
DtPlayerStationApp initializes global services and loads plugins.DtPlayerStation is created (or updated) and the configured components are instantiated.DtLoadingPlayerState creates and initializes components, then waits for deferred initialization.tick() updates start only after the station and all its components are ready.DtPlayerStationApp serves as the top-level application controller and entry point for frontend customization. It manages global services, plugin loading, and the main update loop. Most developers interact with this class during plugin initialization to register component factories.
The registration excerpt below comes from examples/notification/plugin.cxx. Its plugin.h exports the entry points; the source includes notifyLogic.h, vrePlayerStation/playerStationApp.h, and vreUtil/logger.h. See Plugin Architecture for all three frontend hooks.
DtPlayerStation encapsulates all the I/O and logic components necessary to realize player interface for a given role.
Every component of a player station has access to the DtPlayerStation instance that owns it. Components can use this to retrieve information about the role configuration, share data between components, or lookup other components. The player() method of DtPlayerComponent returns a reference to the owning DtPlayerStation.
playerAttributeStore() accesses station-local values. ownshipState() accesses the reflected entity branch. Neither API publishes changes to the backend. The sections below describe ownership and command paths.
DtPlayerStationApp::stateManager() manages a stack of application states, not an entity-control state machine. The app registers DtPlayerStationState instances and transfers their ownership to the manager. The manager retains these objects until destruction; leaving a state does not delete its registered instance. Register replacements during startup, before the state enters the stack. Replacing an already registered name deletes its old instance; replacing an active state can invalidate stack pointers.
push(), transition(), pop(), and popUntil() enqueue operations, which tick() processes in FIFO order. push() calls onStacked() on the old top and onEnter(args) on the new top. transition() calls onExit() on the old top and onEnter(args) on its replacement. pop() calls onExit() on the removed top, then onExposed(args) on the newly exposed state. popUntil() exposes an existing state by popping intervening states. These operations require registered targets; a normal pop cannot empty the stack.
The manager ticks every stacked state, from top to bottom. A covered state must use its exposure state and stacking callbacks when it should suppress UI or runtime work. currentState() denotes the top; getState(name) searches the active stack, not all registered states.
The following diagram includes all twelve built-in states registered by DtPlayerStationApp. Arrows show common routes and their stack operations, not every event-specific transition or the stack's nesting. Plugin-defined states are not shown.
stateDiagram-v2
direction TB
[*] --> Initialization
Initialization --> SelectConnection: UI ready / transition
SelectConnection --> NetworkConnected: Connection ready / transition
NetworkConnected --> SessionMenu: Resources ready / push
NetworkConnected --> SelectConnection: Disconnected / transition
SessionMenu --> WaitingForHost: Join existing session / transition
SessionMenu --> JoinedSession: Start or host session / transition
WaitingForHost --> JoinedSession: Terrain available / transition
JoinedSession --> WaitingForHost: Session terrain changed / transition
JoinedSession --> Loading: Load session / push
JoinedSession --> EndingSession: Leave session or lose host / transition
EndingSession --> SessionMenu: Terrain cleared / transition
Loading --> ChooseRole: Session ready / transition
ChooseRole --> Engaged: Role selected / transition
Engaged --> LoadingPlayer: Load player / push
LoadingPlayer --> Engaged: Ready / pop
LoadingPlayer --> Engaged: Failure / popUntil
Engaged --> ChooseRole: Loading failure or role change / transition
Engaged --> Menu: Open menu / push
Menu --> Engaged: Close menu / pop
| Diagram state | Registered class | Responsibility |
|---|---|---|
| Initialization | DtInitializationState | Creates the application UI and waits for it to finish loading. |
| SelectConnection | DtSelectConnectionState | Presents connection selection and waits for a network connection. |
| NetworkConnected | DtNetworkConnectedState | Configures the backend, loads default model-set resources, and monitors the connection. |
| SessionMenu | DtSessionMenuState | Starts an unhosted session, hosts a scenario, or joins an existing session. |
| WaitingForHost | DtWaitingForHostState | Waits for session status to publish terrain that can be loaded. |
| JoinedSession | DtJoinedSessionState | Manages session and backend lifetime and pushes session loading. |
| EndingSession | DtEndingSessionState | Requests backend shutdown and waits for session status to report no terrain. |
| Loading | DtLoadingState | Coordinates simulation, GUI terrain, and model-set loading before role selection. |
| ChooseRole | DtChooseRoleState | Selects or creates an entity and selects its player role. |
| LoadingPlayer | DtLoadingPlayerState | Acquires ownership when needed, initializes the Player Station, and waits for component readiness. |
| Engaged | DtEngagedState | Manages engaged player stations and pushes player loading for role changes. |
| Menu | DtMenuState | Displays the application menu above another state and returns to that state when popped. |
NetworkConnected remains below the session states; JoinedSession remains below session loading and the subsequent role-selection and engaged states. DtLoadingState loads scenario/session resources; DtLoadingPlayerState loads the selected Player Station. They are distinct states. DtEngagedState enters first and pushes player loading. On loading failure, cleanup unwinds to Engaged, whose exposure callback routes back to role selection. Being in the Engaged stack does not imply that component ticks are already enabled.
Opening a menu can cover DtEngagedState without destroying its station. Menu can also be pushed above SessionMenu or ChooseRole; popping it returns to whichever state it covered. Station shutdown, suspension, and role-loading transitions govern component lifetime instead. See vrePlayerStation/playerStationStateManager.h, vrePlayerStation/playerStationState.h, vrePlayerStation/playerStationApp.h, and vrePlayerStation/loadingPlayerState.h. The examples/state/extendedEngagedState.cxx example implements state enter, exit, stacking, and exposure hooks.
Role definitions are discovered and loaded collaboratively by the Lua role loader script and the C++ player creation infrastructure. The loader script (appData/scripts/loadDefinition.lua) composes role templates from role files, component groups, and inheritance chains. The DtPlayerCreationPalette class catalogs available entities and roles from simulation model sets, uses the loader to build complete role configurations, and returns a merged DtInitTable when users select roles. For a detailed walkthrough of this composition pipeline, see the "How composition is implemented" section on the Role Configuration page.
Role definition files are Lua scripts that specify which component groups to instantiate and how to configure them. They live under vre-roles-dir, which by default is data/simulationModelSets/VR-Engage/roles:
Each component entry maps to a C++ class registered with the component factory (see Role Configuration for full details of the role system and file structure). Keys in the components table (such as configuration parameters) become fields in the DtInitTable passed to the component's initialize() method. For a catalog of configuration parameters supported by built-in toolkit components, see the Doxygen group Role Configuration Parameters.
DtPlayerComponent is the base class for all frontend components. Custom components inherit from this class and override lifecycle methods to implement their functionality.
Components follow a deterministic lifecycle managed by the framework. This lifecycle governs proper resource management and helps avoid common bugs.
stateDiagram-v2
[*] --> Constructed: Factory creates
Constructed --> Initialized: initialize() called
Initialized --> PostInitialized: postInitialize() called
PostInitialized --> Loading: Station finishInit()
Loading --> Loading: finalizeInitTick() returns Pending
Loading --> Ready: All components ready
Loading --> Failed: finalizeInitTick() returns Failed
Ready --> Destroyed: shutdown() called
Failed --> Destroyed: Loading cleanup
Destroyed --> [*]
note right of Initialized
Read configuration
Initialize members
Validate parameters
end note
note right of PostInitialized
Locate other components
Acquire shared resources
Subscribe to messages
end note
note right of Ready
tick() each frame
while station active
end note
note right of Destroyed
Unsubscribe messages
Release resources
Save state if needed
end note
initialize(DtPlayerStation*, DtInitTable&) when creating the component. Use the DtInitTable to read configuration parameters from the role definition and initialize member variables. Return false to indicate failure, which prevents the component from being used.postInitialize() on each component. Use this phase to locate other components, look up shared attributes in the player attribute store, and subscribe to messages.finishInit(). This installs configured connectors and queues PlayerCreatedMessage; it does not imply that deferred component setup has completed. Components needing asynchronous setup set myComponentReady = false in construction and override finalizeInitTick(double dt). DtLoadingPlayerState calls DtPlayerStation::tickUnreadyComponents() each frame. Ready marks that component ready; Pending requests another loading tick; Failed fails player loading. Normal component ticks remain gated until all components are ready.tick(double dt) every frame with the time delta since the last frame. Perform per-frame updates here, such as smoothing input values, updating animations, or refreshing UI state.shutdown() in reverse initialization order, then deletes the components. Call the base implementation to disconnect myMessageHandlers and myAttributeCallbacks. Suspension can retain the station and its attribute branch while destroying its components.See vrePlayerStation/playerStation.h, vrePlayerStation/loadingPlayerState.h ,vrePlayerStation/playerComponent.h.
A maintained component example is DtNotifyLogic in examples/notification/. It observes a player attribute and displays a temporary notification. The following excerpts retain its base post-initialization call, conditional subscription, and cleanup. The source includes notifyLogic.h, vrePlayerStation/playerStation.h, vrePlayerStation/playerStationApp.h, vrePlayerStation/playerStationTempNotification.h, and vreUtil/logger.h.
The complete header supplies type(), handleWeaponIndexChanged(int), and an empty tick(double). Its role inherits the human role, whose weapon logic publishes weaponIndex. See Notification Example for registration and deployment.
Component configuration originates from multiple sources, with later sources overriding earlier ones (the merge process is described in more detail on the Role Configuration page):
Fields in the Lua components tables become entries in the DtInitTable passed to the component's initialize() method. Read only parameters supported by that component. DtNotifyLogic needs no additional parameters.
Putting it together, the typical flow for a custom component is:
const char* type() const and returns a stable type string (for example, "DtNotifyLogic").Plugin registration: The plugin's initPlayerStationModule() function registers the component with the application-wide factory using the same type string:
The notification plugin registers DtNotifyLogic as shown above.
Role configuration: Role and component-group Lua files use that type string in the componentType field:
The notification role references "DtNotifyLogic" as shown above.
initialize(DtPlayerStation*, DtInitTable&) with a merged DtInitTable containing values from component defaults, component groups, role files, and entity overrides, and then calls postInitialize() before completing any deferred readiness work and beginning regular tick() updates.Design components with single, well-defined responsibilities. A component that combines unrelated functionality becomes difficult to test, configure, and reuse. If a component requires conditional behavior based on role, consider splitting it into separate components composed through configuration. For example, avoid a single component that implements both complex HUD rendering and weapon control; instead, separate these concerns into independent components.
Minimize dependencies between components. Components that directly reference other components create coupling that complicates testing and limits reusability. Use message passing and the player attribute store for component interaction instead of direct references.
The frontend process uses two primary threads that affect component implementation:
Main thread executes rendering, component updates, and UI event processing. Per-frame component tick() methods, input handlers, and most message callbacks run in the main thread. Components that block this thread cause frame rate drops and input latency. Long-running operations should execute asynchronously with results delivered via message callbacks.
Network thread handles communication with the backend process. Network message reception, serialization, and initial processing occur on this thread. The message manager automatically marshals messages to the main thread for component delivery, ensuring thread-safe callback execution. Components rarely interact directly with the network thread.
Component developers work primarily with the main thread. Attribute values can also be read or updated from other threads; callback delivery depends on thread registration and dispatch. Avoid blocking operations in message callbacks and tick() methods.
Components that create worker threads must synchronize their own shared state. Attribute value access uses internal locks, but operations spanning multiple attributes and the lifetimes of objects referenced by stored pointers need their own coordination. Use standard C++ synchronization primitives (such as mutexes and condition variables) for other shared data structures. Document thread-safety requirements in component interfaces.
Frontend components execute on the main rendering thread, so unnecessary work directly impacts frame rate and input latency. Keep tick() implementations lightweight and avoid per-frame allocations, complex container operations, or blocking I/O. Prefer incremental updates and caching over recomputing expensive results every frame. Minimize logging in hot paths and use debug-only logging guards for verbose output. Avoid long-running work in message callbacks or QML property notifications; offload heavy computation to worker threads and return results via messages or attributes.
Each DtPlayerStation has a branch of the process-local attribute tree at Root.App.Players.<entityId>.<stationName>. Its playerAttributeStore() returns a reference to a DtAttributeHandle; there is no separate DtPlayerAttributeStore class. Components use the same branch through DtPlayerComponent::playerAttributeStore(); other frontend code with a station can use station.playerAttributeStore(). The node at the branch root stores a DtPlayerStation* and is locked by the station. Publish values in children, not by replacing the root value.
Use this scope to share state among components and UI for one station. Use Frontend Attributes for the common handle, value, callback, persistence, and threading APIs. Use the application store for frontend state independent of a station, messages for discrete events and cross-process commands, and the reflected entity store for network-populated entity state. Ordinary player attributes do not synchronize with the backend.
Give each key a clear owner and a stable value type. The QML HUD example initializes two station-local damage flags in DtDriverQmlHudComponent::postInitialize(), after calling the base method:
Its handleSimState() filters SimulationStateMessage by ownship ID and updates those flags from appearance. myVehicleDamageState is a retained DtAttributeHandle declared in examples/qmlHud/driverQmlHudComponent.h. The configured overlay reads the values; these writes do not change simulation damage.
The dot separates path segments; chained brackets address the same hierarchy. A slash is a literal part of a name, not a separator. Looking up a path creates its nodes even if no value has been published. get<int>() on an unset node returns int(); use getOr<int>(fallback) for another default or isSet() to distinguish missing data from a valid zero. A wrong explicitly established value type asserts; string values created by setFromString() may instead convert on first typed access. Do not treat a default read as proof that a producer has run.
Resolve a frequently used path once in initialize(). DtPlayerComponent provides a member myAttributeCallbacks manager, and its base shutdown() disconnects the subscriptions. The notification component above demonstrates a real subscription to weaponIndex; Frontend Attributes describes the complete callback API.
invokeNowIfSet = true supplies an already-published, explicitly typed value when connecting; otherwise the callback runs on subsequent correctly typed value changes. A callback manager holds only one subscription per path. Reads through retained handles do not repeat the path lookup. Avoid a per-frame path lookup in tick(). Do not assume a callback always runs synchronously on the publishing thread: delivery depends on callback thread registration and dispatch. See Frontend Attributes for thread behavior and callback lifetime rules.
An ordinary player-attribute write changes only the frontend. To request a simulation state-property change, queue VrfSetStatePropertyMessage with the target entity ID, property type, name, and string representation. The helper below comes from drone task logic. Its source includes vreMessages/vrfSetStateProperty.h and vreMessageManager/vreMessageManager.h.
The frontend DtOwnshipControlConnector::handleSetStateProperties() converts the value to a Reader/Writer property and wraps it in DtSetStateProperties. Its VR-Forces remote controller sends the request to the simulation owner. Supported message types are String, Bool, Int, Real, and Vector3d. Use the representation consumed by the connector and a property supported by the target entity. The backend applies the request and publishes authoritative state; queuing is not an acknowledgement.
Read reflected results under ownshipState()["stateProperties"] after requesting the required fields. See Reflected Entity Attributes for subscription timing.
DtPlayerComponent::setExtendedData(const std::string& key, const std::string& value, DtEntityIdentifier entity) sends a scripted set-data request. The optional entity defaults to ownship. Pilot logic uses this inherited method:
The base implementation creates VrfScriptedEntitySetMessage, selects set_extended_data, and adds string key and value variables. DtOwnshipControlConnector::handleScriptedSet() packages the variables in a VR-Forces scripted set-data request and sends it through the remote controller. The receiving model set must supply the named scripted set-data operation. The maintained script is data/simulationModelSets/VR-Engage/scripts/set_extended_data.lua; its adjacent XML metadata identifies the operation and the string key/value inputs. The script sets tick-while-paused in init(), calls this:setExtendedData() during its tick, then calls vrf:endSet(). The VR-Forces Lua binding updates the entity's next-frame extended data. The simulation owner, not the Player Station store, publishes the result. Queuing the request does not acknowledge backend completion.
Use an entity-supported key and representation, not an arbitrary Player Station attribute name. Read requested reflected data under ownshipState()["extendedData"]; a local write does not invoke this command. See vrePlayerStation/playerComponent.h, vrePlayerStationConnector/ownshipControlConnector.h, and Inter-Process Communication.
DtPlayerComponent::initialize() calls the virtual initializeStateAttributes() hook. Derived components can override the hook to publish typed initial state; their initialize() overrides must call the base implementation. The base postInitialize() also reads an optional initAttributes table from the component's role configuration. For example, data/simulationModelSets/VR-Engage/roles/gunner.lua specifies:
Each entry is a player-store path and a string value. postInitialize() writes it with setFromString() only if that path has no value; an already-set path is left unchanged with a warning. Overrides of postInitialize() must call the base method for this feature to run. These strings begin with an implicit type and can be converted on first access through get<T>() on an untyped handle. Assigning a typed handle to a value still implicitly stored as a string checks its type first and asserts; read the configured value with get<T>() before assigning that typed handle. For typed or complex values, prefer an explicit component publisher with set<T>(); do not depend on configuration to overwrite a value a component already initialized.
Typed connect<T>() callbacks also check the stored type before reading it. A callback on an implicit string logs a type warning and skips the value, including with invokeNowIfSet = true. If the callback was connected in initialize(), it can miss the first initAttributes write in postInitialize(); converting the value later does not redeliver that change. To observe a configured value, connect an untyped callback that calls get<T>() on the supplied handle, or convert an already-set value through an untyped handle before connecting a typed callback.
The station creates an Ownship child that aliases its entity under Root.Entities. playerAttributeStore()["Ownship.position"] and ownshipState()["position"] resolve to the same reflected entity value; the entity connector owns that data. Do not write to it as if it were a player-owned key. Ownship is case-sensitive. The separate, lowercase ownship.* subtree is published by DtEntityControlLogic from SimulationStateMessage in roles that use that component. For example, ownship.position is player state populated by that logic, not the reflected-entity alias. Other components can consume these keys but should not overwrite the framework-owned values. See Reflected Entity Attributes for request timing, field types, and the ownship persistence exception.
During initialization, DtPlayerStation::preInit() publishes elementId (DtElementID), vrView, arCamera, and vr-enabled (the latter three are bool, initially false); finishInit() publishes displayLayout (std::string). VR logic can subsequently update vr-enabled. Other keys depend on the role's components: the action menu manager publishes ActiveActionMenu as a std::string when handling menu updates, including an empty string when no menu is active. Consult the producer for the value type and initialization behavior. Use Attribute Store Reference to discover candidate names and inferred scopes; it is not a type contract or a complete inventory of runtime attributes.
exampleEngine.rpm, and keep each key's value type stable. A path is a contract between its producer and consumers, not an automatically generated hierarchy of C++ member fields.first()/forEach() to inspect direct children when diagnosing state. The station's Player debug view displays its attribute branch. Do not use unsetRecursive() to broadcast a reset: unsetting values does not notify change callbacks.The station marks its branch persistent when constructed. On destruction, it unlocks the root, clears the stored station pointer, marks the branch non-persistent, and removes the Ownship alias. A role change can suspend a station without destroying it, so do not assume its values disappear on disengagement. Retained handles may keep non-persistent nodes alive after destruction, but they do not keep the station or its components alive. Disconnect callbacks and release handles during component shutdown, especially before a suspended station is initialized again. Do not override framework-managed persistence to keep player state beyond its station's lifetime.
Suspending a station destroys its components but retains its player branch. On resume, the station re-publishes its baseline keys and creates new components; other values can still be set from the previous engagement. A component's initAttributes entries therefore do not overwrite those existing values, and postInitialize() warns when a key is already set. Explicitly refresh component-owned state on reinitialization when a fresh value is required.
Attribute values use internal synchronization; this does not make a series of reads atomic or make pointers stored as values safe after their owners are destroyed. A callback connected on a registered thread belongs to that thread, not the writer; an unregistered connecting thread uses a registered fallback thread. Components normally connect during initialization on the main/render thread: same-thread writes can deliver immediately, whereas writes from another thread wait for that thread's callback dispatch tick. Keep frame-time and callback work bounded, and consult Frontend Attributes for detailed threading and ownership rules.
See also