VR-Engage  2.3
Loading...
Searching...
No Matches
vreMessageManager.h
Go to the documentation of this file.
1/******************************************************************************
2** Copyright (c) 2025 MAK Technologies
3** All rights reserved.
4******************************************************************************/
5
6//! \file vreMessageManager.h
7//! \brief Defines the central message manager for the VREngage messaging system
8//!
9//! This file contains the DtVreMessageManager abstract base class which serves as the
10//! central hub for message routing and dispatching in the VREngage system. It provides
11//! a thread-safe mechanism for registering message handlers, queuing messages, and
12//! dispatching messages to appropriate handlers across multiple threads.
13
14#pragma once
15
18
19#include "vreUtil/assert.h"
20
21#include <map>
22#include <memory>
23#include <set>
24#include <string>
25#include <vector>
26
27namespace makVre
28{
30
31//! \brief Delegate type for message handler callbacks
32//!
33//! This type defines a delegate that takes a DtVreMessage pointer and
34//! returns a DtVreMessageResult value. It is used to register message
35//! handlers with the message manager.
37
38//! \brief Central manager for the VREngage messaging system
39//!
40//! This abstract base class defines the interface for the message manager, which
41//! serves as the central hub for message routing and dispatching in the VREngage
42//! system. It provides thread-safe mechanisms for registering message handlers,
43//! queuing messages, and dispatching messages to appropriate handlers.
44//!
45//! The message manager uses a hierarchical message listener tree to efficiently
46//! route messages to the appropriate handlers based on their message types, and
47//! supports both immediate message dispatch and delayed message queuing.
48//!
49//! The system is implemented as a singleton, with a concrete implementation
50//! (DtTbbVreMessageManager) that uses Intel TBB concurrent containers for
51//! thread-safe message queuing across multiple threads.
53{
54public:
55 //! \brief Statistics for message dispatching
56 //!
57 //! This structure stores statistics about message dispatching activity,
58 //! including the number of messages dispatched in the current frame and
59 //! the types of messages that were dispatched.
61 {
62 //! \brief Number of messages dispatched in the current frame
64
65 //! \brief List of message types that were dispatched
66 std::vector<std::string> messageTypesDispatched;
67 };
68
69 //! \brief Position for adding a message handler in the handler list
70 //!
71 //! This enumeration defines the possible positions for adding a message
72 //! handler in the handler list for a specific message type. The position
73 //! affects the order in which handlers are called when a message is dispatched.
74 enum class HandlerPosition
75 {
76 FRONT = 0, //!< Add the handler at the front of the list (called first)
77 BACK //!< Add the handler at the back of the list (called last)
78 };
79
80 //! \brief Gets the singleton instance of the message manager
81 //! \return Reference to the singleton message manager instance
82 //!
83 //! This static method returns a reference to the singleton instance of the
84 //! message manager. If the instance doesn't exist yet, it creates a new one.
86
87 //! \brief Initialize the current thread as a tickable dispatch thread
88 //! \param isMainThread Indicates if the current thread is the main thread
89 //!
90 //! This method registers the current thread as a tickable dispatch thread,
91 //! allowing it to process messages. All registered threads are expected to call
92 //! dispatchTick() in their thread loop to process and dispatch messages for that
93 //! thread.
94 //!
95 //! The main app thread should init with isMainThread = true. The main thread
96 //! serves as the default fallback for handlers added from unregistered threads.
97 //!
98 //! Message handlers are assigned to the thread from which addHandler is called,
99 //! as long as that thread is a registed dispatch thread. Any handlers added from
100 //! an unregistered thread will be assigned to the main thread instead.
101 //!
102 //! Dispatch threads should call shutdownDispatchThread() before exiting.
103 virtual void initDispatchThread(bool isMainThread = false) = 0;
104
105 virtual void shutdownDispatchThread() = 0;
106
107 //! \brief Registers a message handler for a specific message type
108 //! \param messageType Type of messages to handle (can include wildcards)
109 //! \param handler Delegate to the handler function
110 //! \param handlerPos Position to add the handler (FRONT or BACK)
111 //!
112 //! This method registers a handler function for a specific message type.
113 //! When a message of the specified type is dispatched, the handler function
114 //! will be called with the message as its parameter. The position parameter
115 //! determines whether the handler is added to the front or back of the
116 //! handler list, affecting its execution order relative to other handlers
117 //! for the same message type.
118 //!
119 //! The message type can include wildcards ("*") to match multiple message
120 //! types. For example, "entity.*" would match all message types that start
121 //! with "entity.".
122 //!
123 //! Handlers are assigned to the dispatch thread from which this method is called,
124 //! provided that thread is registered as a dispatch thread. If this method is called
125 //! from an unregisted thread, the handler will be assigned to the main thread for
126 //! dispatch instead.
127 virtual void addHandler(const std::string& messageType, const DtVreMessageDelegate& handler,
128 HandlerPosition handlerPos = HandlerPosition::BACK) = 0;
129
130 //! \brief Unregisters a message handler for a specific message type
131 //! \param messageType Type of messages the handler was registered for
132 //! \param handler Delegate to the handler function to remove
133 //!
134 //! This method removes a previously registered handler function for a
135 //! specific message type. After removal, the handler will no longer be
136 //! called when messages of the specified type are dispatched.
137 virtual void removeHandler(const std::string& messageType, const DtVreMessageDelegate& handler) = 0;
138
139 //! \brief Processes queued messages for the current thread
140 //! \param dt Delta time in seconds since the last tick
141 //!
142 //! This method processes all queued messages for the current thread,
143 //! dispatching them to registered handlers. It also updates the timers
144 //! for delayed messages, making them available for dispatch when their
145 //! delay time has elapsed.
146 //!
147 //! \note Each thread that participates in the messaging system must call
148 //! this method in its thread loop to process messages targeted for
149 //! that thread.
150 virtual void dispatchTick(double dt) = 0;
151
152 //! \brief Queues a message for later dispatch
153 //! \param msg Pointer to the message to queue
154 //! \param delay Delay in seconds before the message is dispatched
155 //!
156 //! This method queues a message for later dispatch. If a delay is specified,
157 //! the message will not be dispatched until the delay time has elapsed.
158 //! The message will be dispatched the next time tick() is called after the
159 //! delay has elapsed.
160 //!
161 //! \note The message manager takes ownership of the message and will delete
162 //! it when it is no longer needed.
163 virtual void queueMessage(DtVreMessage* msg, double delay = 0.0) = 0;
164
165 //! \brief Like queueMessage, but immediately dispatches message to handlers
166 //! on the current thread, if possible.
167 //!
168 //! \param msg Pointer to the message to dispatch
169 //!
170 //! Message will be dispatchd immediately for handlers on the current thread,
171 //! if the current thread is registered as a dispatch thread. In all other
172 //! cases and for all other threads the message will be queued for dispatch
173 //! on the next thread tick, as if queueMessage were called.
174 virtual void sendMessageAsap(DtVreMessage* msg) = 0;
175
176 //! \brief Gets the message factory associated with this message manager
177 //! \return Reference to the message factory
178 //!
179 //! This method returns a reference to the message factory associated with
180 //! this message manager. The factory is used to create messages from
181 //! serialized data and to register message types.
183
184 //! \brief Gets the event statistics for the current thread
185 //! \return Reference to the event statistics structure
186 //!
187 //! This method returns a reference to the event statistics structure for
188 //! the current thread. The statistics include the number of messages
189 //! dispatched in the current frame and the types of messages that were
190 //! dispatched.
191 virtual const EventStats& stats() = 0;
192
193protected:
194 //! \brief Protected constructor
195 //!
196 //! This constructor is protected to enforce the singleton pattern.
197 //! It creates a new message factory and initializes member variables.
199
200 //! \brief Virtual destructor
201 //!
202 //! Ensures proper cleanup of derived classes.
204
205 //! \brief Singleton instance of the message manager
206 //!
207 //! This static pointer holds the singleton instance of the message manager.
208 //! It is initialized by the constructor and accessed through the instance() method.
210
211 //! \brief Message factory for creating messages
212 //!
213 //! This static pointer holds the message factory associated with the message
214 //! manager. It is initialized by the constructor and accessed through the
215 //! factory() method.
217};
218
219//! \brief Message handler class for VREngage messages
220//!
221//! This class provides a convenient interface for defining message handlers that can be
222//! connected to specific message types. It inherits from DtVreMessageDelegate and adds
223//! functionality for managing connections to message types, including tracking which
224//! message types the handler is connected to.
225//!
226//! Most importantly, this class automatically disconnects all handler connections when
227//! it is destroyed, allowing for scope-managed handler cleanup, avoiding the need for
228//! explicit removeHandler calls. Define instances of this class as members of the
229//! delegate object to avoid accidental invokation of member handler methods for objects
230//! which have been destroyed.
232{
233public:
234 // \brief Constructor for member function handlers
235 // \tparam OBJECT_T The type of the object that will handle messages
236 // \param object Pointer to the object that will handle messages
237 // \param method Pointer to the member function that will handle messages
238 template <class OBJECT_T>
239 DtVreMessageHandler(OBJECT_T* object, DtVreMessageResult (OBJECT_T::*method)(DtVreMessage*))
240 : DtVreMessageDelegate(object, method)
241 {
242 }
243
244 // \brief Constructor for free functions or static member functions
245 // \param function Pointer to the function that will handle messages
250
251 //! \brief Constructor for callable handlers
252 //! \tparam Callable The type of the callable that will handle messages
253 //! \param callable The callable that will handle messages
254 template <typename Callable,
255 typename = std::enable_if_t<!std::is_same<std::decay_t<Callable>, DtVreMessageHandler>::value>>
256 DtVreMessageHandler(Callable&& callable)
257 : DtVreMessageDelegate(std::forward<Callable>(callable))
258 {
259 }
260
261 //! \brief Virtual destructor
262 //!
263 //! Disconnects all handler connections to ensure proper cleanup when the handler object is destroyed.
265
266 //! \brief Connects this handler to a specific message type
267 //! \param messageType The type of message to connect to
268 //! \param position The position in the handler list (front or back). Optional, defaults to back
269 virtual void connect(const std::string& messageType,
271
272 //! \brief Disconnects this handler from a specific message type
273 virtual void disconnect(const std::string& messageType);
274
275 //! \brief Disconnects this handler from all message types it is connected to
276 virtual void disconnectAll();
277
278 //! \brief Checks if this handler is currently connected to a specific message type
279 virtual bool isConnected(const std::string& messageType) const;
280
281protected:
282 using ConnectedList = std::set<std::string>;
283
284 //! \brief List of message types this handler is currently connected to
286};
287
288//! \brief Manager class for connecting message handlers to message types
289//!
290//! Allows for managing the lifetime of multiple handler connections using a single manager instance.
292{
293public:
295
297
298 //! \brief Connects a handler method to a specific message type
299 //!
300 //! Creates a new Connector instance to manage the lifetime of the connection. The Connector
301 //! is added to the manager's map and will automatically disconnect when the manager instance
302 //! is destroyed, so there is no need for explicit disconnect calls, unless it is necessary
303 //! to disconnect the handler before the manager is destroyed.
304 //!
305 //! \tparam OBJECT_T The type of the object that will handle messages
306 //! \param messageType The type of message to connect to
307 //! \param object Pointer to the object that will handle messages
308 //! \param method Pointer to the member function that will handle messages
309 //! \param position The position in the handler list (front or back). Optional, defaults to back
310 template <class OBJECT_T>
311 void connect(const std::string& messageType,
312 OBJECT_T* object,
313 DtVreMessageResult (OBJECT_T::*method)(DtVreMessage*),
315 {
316 myConnectors[messageType] = std::make_shared<DtVreMessageHandler>(object, method);
317 myConnectors[messageType]->connect(messageType, position);
318 }
319
320 //! \brief Connects a free function or static member function to a specific message type
321 //!
322 //! Creates a new Connector instance to manage the lifetime of the connection. The Connector
323 //! is added to the manager's map and will automatically disconnect when the manager instance
324 //! is destroyed, so there is no need for explicit disconnect calls, unless it is necessary
325 //! to disconnect the handler before the manager is destroyed.
326 //!
327 //! \param messageType The type of message to connect to
328 //! \param function Pointer to the function that will handle messages
329 //! \param position The position in the handler list (front or back). Optional, defaults to back
330 void connect(const std::string& messageType,
331 DtVreMessageResult (*function)(DtVreMessage*),
333 {
334 myConnectors[messageType] = std::make_shared<DtVreMessageHandler>(function);
335 myConnectors[messageType]->connect(messageType, position);
336 }
337
338 //! \brief Connects a callable handler to a specific message type
339 //! \tparam Callable The type of the callable that will handle messages
340 //! \param messageType The type of message to connect to
341 //! \param callable The callable that will handle messages
342 //! \param position The position in the handler list (front or back). Optional, defaults to back
343 template <typename Callable>
344 void connect(const std::string& messageType,
345 Callable&& callable,
347 {
348 myConnectors[messageType] = std::make_shared<DtVreMessageHandler>(std::forward<Callable>(callable));
349 myConnectors[messageType]->connect(messageType, position);
350 }
351
352 //! \brief Checks if a handler is currently connected for a specific message type
353 //!
354 //! \param messageType The type of message to check
355 //! \return True if a handler is currently connected to the specified message type, false otherwise
356 bool isConnected(const std::string& messageType) const
357 {
358 auto findIt = myConnectors.find(messageType);
359 return findIt != myConnectors.end() && findIt->second->isConnected(messageType);
360 }
361
362 //! \brief Disconnects a handler from a specific message type
363 //!
364 //! \param messageType The type of message to disconnect from
365 void disconnect(const std::string& messageType) { myConnectors.erase(messageType); }
366
367 //! \brief Disconnects all handlers for all message types
368 void disconnectAll() { myConnectors.clear(); }
369
370protected:
371 std::map<std::string, std::shared_ptr<DtVreMessageHandler>> myConnectors;
372};
373
374} // namespace makVre
375
376//! \name Message Type Assertion Macros
377//! @{
378
379//! \brief Asserts that a message is of the expected type and casts it
380//! \param msg Pointer to the message to check and cast
381//! \param MsgType Expected message type (class name)
382//! \param msgCast Variable name for the cast message pointer
383//!
384//! This macro checks that a message is of the expected type using dynamic_cast,
385//! and then creates a properly typed pointer to the message using static_cast.
386//! It should be used when handling messages for which you have registered a
387//! handler with the exact message type (no wildcards).
388#define ASSERT_TYPE(msg, MsgType, msgCast)\
389 DtASSERT(dynamic_cast<MsgType*>(msg), "Message is incorrect type");\
390 MsgType* msgCast = static_cast<MsgType*>(msg);
391
392//! \brief Asserts that a message is of the expected type without casting it
393//! \param msg Pointer to the message to check
394//! \param MsgType Expected message type (class name)
395//!
396//! This macro checks that a message is of the expected type using dynamic_cast,
397//! but does not create a cast pointer. It should be used when handling messages
398//! for which you have registered a handler with the exact message type (no wildcards)
399//! and you don't need to access type-specific members of the message.
400#define ASSERT_TYPE_NO_CAST(msg, MsgType) DtASSERT(dynamic_cast<MsgType*>(msg), "Message is incorrect type");
401
402//! @}
Provides assertion macros and functions for error detection and handling.
Modern delegate class that can bind and invoke callables with any number of parameters.
Definition delegate.h:31
Factory for creating VREngage messages from serialized data.
Definition vreMessageFactory.h:48
std::map< std::string, std::shared_ptr< DtVreMessageHandler > > myConnectors
Definition vreMessageManager.h:371
void connect(const std::string &messageType, DtVreMessageResult(*function)(DtVreMessage *), DtVreMessageManager::HandlerPosition position=DtVreMessageManager::HandlerPosition::BACK)
Connects a free function or static member function to a specific message type.
Definition vreMessageManager.h:330
DtVreMessageHandlerGroup()
Definition vreMessageManager.h:294
bool isConnected(const std::string &messageType) const
Checks if a handler is currently connected for a specific message type.
Definition vreMessageManager.h:356
void disconnect(const std::string &messageType)
Disconnects a handler from a specific message type.
Definition vreMessageManager.h:365
void connect(const std::string &messageType, Callable &&callable, DtVreMessageManager::HandlerPosition position=DtVreMessageManager::HandlerPosition::BACK)
Connects a callable handler to a specific message type.
Definition vreMessageManager.h:344
virtual ~DtVreMessageHandlerGroup()
Definition vreMessageManager.h:296
void connect(const std::string &messageType, OBJECT_T *object, DtVreMessageResult(OBJECT_T::*method)(DtVreMessage *), DtVreMessageManager::HandlerPosition position=DtVreMessageManager::HandlerPosition::BACK)
Connects a handler method to a specific message type.
Definition vreMessageManager.h:311
void disconnectAll()
Disconnects all handlers for all message types.
Definition vreMessageManager.h:368
Message handler class for VREngage messages.
Definition vreMessageManager.h:232
virtual void disconnect(const std::string &messageType)
Disconnects this handler from a specific message type.
virtual void disconnectAll()
Disconnects this handler from all message types it is connected to.
ConnectedList myConnectedList
List of message types this handler is currently connected to.
Definition vreMessageManager.h:285
virtual bool isConnected(const std::string &messageType) const
Checks if this handler is currently connected to a specific message type.
virtual void connect(const std::string &messageType, DtVreMessageManager::HandlerPosition position=DtVreMessageManager::HandlerPosition::BACK)
Connects this handler to a specific message type.
virtual ~DtVreMessageHandler()
Virtual destructor.
std::set< std::string > ConnectedList
Definition vreMessageManager.h:282
DtVreMessageHandler(OBJECT_T *object, DtVreMessageResult(OBJECT_T::*method)(DtVreMessage *))
Definition vreMessageManager.h:239
DtVreMessageHandler(DtVreMessageResult(*function)(DtVreMessage *))
Definition vreMessageManager.h:246
DtVreMessageHandler(Callable &&callable)
Constructor for callable handlers.
Definition vreMessageManager.h:256
Abstract base class for all VREngage messages.
Definition vreMessage.h:50
static DtVreMessageManager * theVreMessageManager
Singleton instance of the message manager.
Definition vreMessageManager.h:209
virtual void queueMessage(DtVreMessage *msg, double delay=0.0)=0
Queues a message for later dispatch.
virtual const EventStats & stats()=0
Gets the event statistics for the current thread.
virtual void shutdownDispatchThread()=0
static DtVreMessageManager & instance()
Gets the singleton instance of the message manager.
DtVreMessageManager()
Protected constructor.
virtual void dispatchTick(double dt)=0
Processes queued messages for the current thread.
virtual DtVreMessageFactory & factory()=0
Gets the message factory associated with this message manager.
virtual ~DtVreMessageManager()
Virtual destructor.
static DtVreMessageFactory * theMessageFactory
Message factory for creating messages.
Definition vreMessageManager.h:216
virtual void addHandler(const std::string &messageType, const DtVreMessageDelegate &handler, HandlerPosition handlerPos=HandlerPosition::BACK)=0
Registers a message handler for a specific message type.
HandlerPosition
Position for adding a message handler in the handler list.
Definition vreMessageManager.h:75
@ BACK
Add the handler at the back of the list (called last)
Definition vreMessageManager.h:77
@ FRONT
Add the handler at the front of the list (called first)
Definition vreMessageManager.h:76
virtual void initDispatchThread(bool isMainThread=false)=0
Initialize the current thread as a tickable dispatch thread.
virtual void sendMessageAsap(DtVreMessage *msg)=0
Like queueMessage, but immediately dispatches message to handlers on the current thread,...
virtual void removeHandler(const std::string &messageType, const DtVreMessageDelegate &handler)=0
Unregisters a message handler for a specific message type.
Defines export macros for the VREngage Message Manager library.
#define MESSAGEMANAGER_DLL
Export/import macro for non-Windows platforms.
Definition export.h:39
!
Definition glsVreMessageUtil.h:50
DtDelegate< DtVreMessageResult, DtVreMessage * > DtVreMessageDelegate
Delegate type for message handler callbacks.
Definition vreMessageManager.h:36
DtVreMessageResult
Enumeration of possible message handling results.
Definition vreMessage.h:33
Statistics for message dispatching.
Definition vreMessageManager.h:61
std::vector< std::string > messageTypesDispatched
List of message types that were dispatched.
Definition vreMessageManager.h:66
int messagesDispatchedThisFrame
Number of messages dispatched in the current frame.
Definition vreMessageManager.h:63
Defines the base class for all VREngage messages.