VR-Engage  2.3
Loading...
Searching...
No Matches
Player Attribute Store Example

Overview

Purpose: This example demonstrates how to monitor and respond to changes in the VR-Engage player attribute store using the attribute callback system. It illustrates event-driven component design where components react to state changes rather than polling for updates.

Observable Behavior: The component polls Ownship.stateProperties.set-gear in the player attribute store each tick and logs changes delivered to its DtString callback as the vehicle's gear state is reflected.

Prerequisites:

  • Understanding of Player Attribute Store architecture and usage patterns
  • Familiarity with C++ member function callbacks and std::function semantics
  • Knowledge of VR-Engage component lifecycle methods (initialize(), postInitialize(), tick(), shutdown())
  • Basic understanding of the observer pattern and event-driven programming concepts

Related Examples:

Key Concepts Demonstrated

This example demonstrates:

  1. Player Attribute Store Access - Centralized state repository for player-specific data
    • See Player Attribute Store for architectural details
    • Unique aspect in this example: Demonstrates both read access patterns (polling vs. callbacks) for the same attribute
  2. Attribute Callback System - Event-driven programming using the observer pattern
    • Implementation pattern: DtAttributeCallbackManager owns the callback connection
    • Shows type-safe callback registration with automatic cleanup during component shutdown
  3. Component Lifecycle Management - Proper resource management across VR-Engage component states
    • Demonstrates critical timing differences between initialize() and postInitialize() for callback registration
    • Shows proper cleanup patterns in shutdown() to prevent dangling pointer issues
  4. Polling vs. Event-Driven Patterns - Comparison of continuous monitoring versus change notification
    • Illustrates performance trade-offs between tick() polling and attribute change callbacks
    • Demonstrates when each approach is appropriate for different types of state monitoring

Code Walkthrough

Component Registration

The plugin registers the component with VR-Engage's factory system:

// File: examples/playerStateAttribute/plugin.cxx
extern "C"
{
{
return true;
}
}
Example component demonstrating player attribute monitoring and callback patterns.
Definition sampleComponent.h:45
void addCreator(std::string name="")
Registers a creator for a specific type.
Definition factory.h:129
Top-level class representing the VR-Engage application.
Definition playerStationApp.h:155
virtual DtComponentFactory & componentFactory()
Gets the component factory.
VRECOMMONCOMPONENTS_DLL bool initPlayerStationModule(makVre::DtPlayerStationApp *app)
Module initialization function declarations using C linkage.
constexpr auto DtPlayerStateAttributeSampleComponentType
Type identifier string for DtNotifyLogic component registration.
Definition sampleComponent.h:25

The string DtPlayerStateAttributeSampleComponentType must match the component's type() method return value. This registration makes the component available for instantiation when specified in role configurations. The extern "C" linkage prevents C++ name mangling, which is required for dynamic loading of plugin entry points.

Component Initialization and Attribute Access

The component demonstrates proper attribute store access during initialization:

// File: examples/playerStateAttribute/sampleComponent.cxx
bool DtPlayerStateAttributeSampleComponent::initialize(DtPlayerStation* player, DtInitTable& config)
{
if (!DtPlayerComponent::initialize(player, config))
{
return false;
}
myGearAttributeHandle = playerAttributeStore()["Ownship.stateProperties.set-gear"];
return true;
}
virtual bool initialize(makVre::DtPlayerStation *player, makVre::DtInitTable &config) override
Initializes the component with player station and configuration.
makVre::DtAttributeHandle myGearAttributeHandle
Handle to the "Ownship.stateProperties.set-gear" player attribute.
Definition sampleComponent.h:155
virtual DtAttributeHandle & playerAttributeStore()
Gets the player attribute store.
virtual DtPlayerStation & player()
Gets the player station.

Call the base initialize() before accessing the player attribute store. The lookup creates a node if needed; retaining its handle does not establish a value. The bundled Driver role inherits driver.lua, whose dashboard reads this same path. Published DtRwString state properties are reflected as DtString, so both polling and the typed callback must use DtString, not std::string.

Callback Registration Timing

The component shows critical timing requirements for callback registration:

// File: examples/playerStateAttribute/sampleComponent.cxx
{
DtPlayerComponent::postInitialize();
return true;
}
virtual bool postInitialize() override
Performs post-initialization after all components are initialized.
virtual void onGearChanged(const DtString &newGear)
Callback invoked when "Ownship.stateProperties.set-gear" changes.
void connect(DtAttributeHandle attr, OBJECT_T *object, void(OBJECT_T::*method)(const DtAttributeHandle &), bool includeChildren=false, bool invokeNowIfSet=false)
Connects a member function callback for untyped attribute changes.
DtAttributeCallbackManager myAttributeCallbacks
Member-scope instance of Attribute callback manager.
Definition playerComponent.h:275

This example connects in postInitialize() after the other components have run initialize(), when this consumer is ready for callbacks. The lookup in initialize() already creates the node; postInitialize() does not guarantee that a producer has assigned a value. Connecting in initialize() is also possible when the consumer is ready, but the callback here observes subsequent changes only. Check isSet() before reading if an unset value differs from a valid empty string. The callback manager tracks the connection for cleanup.

Polling Pattern Implementation

The tick method demonstrates continuous attribute monitoring:

// File: examples/playerStateAttribute/sampleComponent.cxx
{
const auto currentGear = myGearAttributeHandle->get<DtString>();
LOG_VERBOSE("Player Attribute Sample", "Current Gear: %s\n", currentGear.c_str());
}
virtual void tick(double dt) override
Per-frame update callback.
const T get() const
Gets the value of the attribute.
#define LOG_VERBOSE(channel, format,...)
Macro to log a verbose message using printf-style formatting.
Definition logger.h:162

Polling retrieves attribute values every frame regardless of whether they have changed. The get<T>() template method provides type-safe access to attribute values. This approach is suitable for continuous monitoring but can be inefficient for attributes that change infrequently, incurring approximately 60 attribute accesses per second at typical frame rates.

Event-Driven Callback Implementation

The callback method demonstrates efficient change notification:

// File: examples/playerStateAttribute/sampleComponent.cxx
{
LOG_INFO("Player Attribute Sample", "Gear has changed! New Gear: %s\n", newGear.c_str());
}
#define LOG_INFO(channel, format,...)
Macro to log an informational message using printf-style formatting.
Definition logger.h:156

Callbacks execute when attribute values change. The new value is provided as a parameter, eliminating the need for another attribute query. The callback signature must match the stored type: DtString for Ownship.stateProperties.set-gear. The attribute system does not convert between DtString and std::string when dispatching typed callbacks.

Resource Cleanup

The shutdown method demonstrates proper callback lifecycle management:

// File: examples/playerStateAttribute/sampleComponent.cxx
{
DtPlayerComponent::shutdown();
}
virtual void shutdown() override
Shutdown callback for cleanup.
void disconnectAll()
Removes and destroys all registered callbacks.

All attribute callbacks must be disconnected before component destruction because the attribute store may outlive individual components. Without explicit cleanup, the store could attempt to invoke callbacks on destroyed objects, causing crashes. The connection manager's disconnectAll() method provides convenient bulk cleanup for all registered callbacks.

Deployment and Testing

Installation

Build the example (see Environment Setup & Build Guide):

cd examples\build
cmake --build . --config RelWithDebInfo --target playerStateAttribute

Install the plugin to the VR-Engage installation:

cmake --install . --config RelWithDebInfo

This copies the plugin to the appropriate location:

  • Frontend plugin: <VR-Engage-Install-Dir>\plugins64\vrEngage\release\examplePlayerStateAttribute.dll

Verify installation:

dir "<VR-Engage-Install-Dir>\plugins64\vrEngage\release\examplePlayerStateAttribute.dll"

The simulation model set is located at <VR-Engage-Install-Dir>\data\simulationModelSets\examples\playerStateAttribute.sms and should be available in the standard VR-Engage installation.

Launching with the Example Simulation Model Set

To run VR-Engage with the playerStateAttribute example simulation model set as the default, use the --setting command-line option to override playerStationApp.defaultSimulationModelSets:

vrEngage.exe -c -n 3 --setting "playerStationApp.defaultSimulationModelSets = {'<VR-Engage-Install-Dir>/data/simulationModelSets/examples/playerStateAttribute.sms'};"

This is equivalent to the Visual Studio debugger configuration for the playerStateAttribute example and ensures that the correct simulation model set and roles are loaded when testing this example.

Configuration

Option 1: Use Visual Studio debug configuration (easiest):

  1. Right-click the playerStateAttribute project in Visual Studio → Debug → Start New Instance
  2. This automatically loads the playerStateAttribute.sms simulation model set with pre-configured entities

Option 2: Manual scenario setup:

  1. Create a scenario that includes the playerStateAttribute.sms simulation model set
  2. Add a ground vehicle entity (e.g., LAV III APC) to the scenario

Testing Procedure

  1. Launch VR-Engage with the playerStateAttribute example (using Option 1 above)
  2. Select a driver role and connect to the ground vehicle entity
  3. Expected Behavior:
    • The component logs "Current Gear:" messages each tick
    • Changed values reflected at Ownship.stateProperties.set-gear produce "Gear has changed!" messages
  4. Test gear changes:
    • Use vehicle control inputs to shift gears (typically keyboard keys or joystick buttons)
    • Compare continuous polling output with change-only callback output

Verification:

  • Check the VR-Engage log (the most recent *.log file in the MAK log directory, typically C:/MAK/logs) for component registration:
    [Player State Attribute] Initializing front-end
  • Check polling output and callback messages when reflected gear values change

Troubleshooting

Plugin not loading:

  • Verify DLL is in correct plugins directory: <VR-Engage-Install-Dir>\plugins64\vrEngage\release\
  • Check VR-Engage framework dependencies are available (vrePlayerStation.dll, vreUtil.dll)
  • Review the VR-Engage log (most recent *.log file in the MAK log directory) for DLL load errors or missing symbols

No attribute messages appearing:

  • Symptom: Component loads but no gear messages appear in the log
  • Cause: The sample component may not have been instantiated in the engaged role
  • Solution: Engage the example LAV's Driver role, which includes driverInfo.lua

Only polling messages, no callback messages:

  • Symptom: Continuous "Current Gear:" messages but no "Gear has changed!" messages
  • Cause: The reflected gear value has not changed, or the component uses an incorrect path or callback type
  • Solution: Verify that polling and the callback use Ownship.stateProperties.set-gear with DtString, and confirm that gear changes publish new values

Crash on component destruction:

  • Symptom: VR-Engage crashes when exiting or changing roles
  • Cause: Callbacks not properly disconnected in shutdown()
  • Solution: Verify myAttributeCallbacks.disconnectAll() is called in shutdown method

Technical Reference

File Structure

examples/playerStateAttribute/
├── CMakeLists.txt # Build configuration with debug setup
├── README.md # This documentation
├── plugin.h/.cxx # Plugin entry point and factory registration
├── sampleComponent.h/.cxx # Component implementation demonstrating attribute monitoring
└── export.h # DLL export macros

Key Classes

Class Base Class Purpose Header
DtPlayerStateAttributeSampleComponent DtPlayerComponent Attribute monitoring component sampleComponent.h

API Methods Used

  • DtPlayerStation::playerAttributeStore() - Access centralized attribute repository
  • DtAttribute::get<T>() through DtAttributeHandle::operator->() - Read an attribute value
  • DtAttributeCallbackManager::connect() - Register attribute change callbacks
  • DtAttributeCallbackManager::disconnectAll() - Bulk callback cleanup
  • DtPlayerStationApp::componentFactory().addCreator<T>() - Component factory registration

Attribute Details

Attribute Name Type Description Updated By
Ownship.stateProperties.set-gear DtString Reflected gear value monitored by the component Reflected entity connector, from the published vehicle state property

Build Targets

  • Plugin: examplePlayerStateAttribute.dll (Windows)
  • Install Location: plugins64/vrEngage/release/
  • Debug Configuration: Automatically loads playerStateAttribute.sms simulation model set

Related Documentation: