AGX Dynamics  2.37.2.0
SimulationController.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2024. Algoryx Simulation AB.
3 
4 All AGX source code, intellectual property, documentation, sample code,
5 tutorials, scene files and technical white papers, are copyrighted, proprietary
6 and confidential material of Algoryx Simulation AB. You may not download, read,
7 store, distribute, publish, copy or otherwise disseminate, use or expose this
8 material unless having a written signed agreement with Algoryx Simulation AB, or
9 having been advised so by Algoryx Simulation AB for a time limited evaluation,
10 or having purchased a valid commercial license from Algoryx Simulation AB.
11 
12 Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13 from using this software, unless otherwise stated in written agreements with
14 Algoryx Simulation AB.
15 */
16 
17 
18 #ifndef AGX_SIMULATION_CONTROLLER_H
19 #define AGX_SIMULATION_CONTROLLER_H
20 
21 #include <agx/config/AGX_USE_WEBSOCKETS.h>
22 
23 #if AGX_USE_WEBSOCKETS()
24 
25 #include <agx/Referenced.h>
26 #include <agx/Callback.h>
27 #include <agx/Event.h>
28 #include <agx/macros.h>
29 #include <agx/Journal.h>
30 #include <agx/JournalReader.h>
31 
33 
34 #include <agxSDK/Simulation.h>
36 
37 #include <agxNet/WebSocket.h>
38 
39 namespace agx
40 {
41  class Journal;
43 }
44 
45 
46 namespace agxData
47 {
48  class Track;
50 }
51 
52 
53 
54 namespace agxSDK
55 {
56  class RunLoopThread;
57  class ScopedStepLock;
58 
59 
65  AGX_DECLARE_POINTER_TYPES(SimulationController);
66  class CALLABLE AGXPHYSICS_EXPORT SimulationController : public agx::Referenced
67  {
68  public:
69 
73  SimulationController();
74 
75 
81  SimulationController( bool enableRemoteCommandServer, agx::UInt16 port = agx::InvalidIndex, bool scan = false );
82 
83 
84  agxSDK::Simulation* getSimulation();
85  const agxSDK::Simulation* getSimulation() const;
86 
87  agx::Journal* getJournal();
88  const agx::Journal* getJournal() const;
89 
90 
95  void clearSimulation();
96 
97 
104  void runLoop();
105 
106 
110  void stopRunLoop();
111 
112 
116  void startRunLoopThread();
117 
118 
119 
123  void play(bool wasTemporarilyPaused = false);
124 
125 
130  void pause(bool isTemporarilyPaused = false);
131 
132 
136  void stepTo(agx::Real time, CallbackWrapper_String* errorCallback = nullptr, bool wasTemporarilyPaused = false);
137 
141  void stepToFrame(agx::UInt frameIndex, CallbackWrapper_String* errorCallback = nullptr, bool wasTemporarilyPaused = false);
142 
147  void singleStep( bool asynchronous = true );
148 
152  void setRepeat( bool repeat );
153  bool getRepeat() const;
154 
159  void setRealTimeSync( bool realTime );
160  bool getRealTimeSync() const;
161 
165  void setFrameStride( agx::UInt stride );
166 
167 // /**
168 // * Space is updated when a new frame is loaded if update space is enabled.
169 // * It can be used to get updated contacts without saving them to the journal,
170 // * but it might be expensive.
171 // */
172 // void setUpdateSpace( bool updateSpace );
173 // bool getUpdateSpace() const;
174 
187  bool openJournal( const agx::String& journalPath="Journal.agxJournal", const agx::String& sessionName="", bool loadScene=true, bool attach=true );
188 
189  void setJournalFormat(agx::Journal::ArchiveFormat format);
190  agx::Journal::ArchiveFormat getJournalFormat() const;
191 
192  bool sanityCheck() const;
193 
194  void attach();
195 
196  void setDefaultSceneLoader(agx::Journal::SceneLoaderCallback callback);
197 
198  bool recordExtraData( const agx::String& key, const agx::String& value );
199  agx::String retrieveExtraData( const agx::String& key );
200 
201  bool truncate(agx::UInt firstFrameToRemove);
202 
212  void setSaveSceneToDisk( bool flag );
213 
217  bool getSaveSceneToDisk() const;
218 
219 
223  void signalSceneChanged();
224 
225  bool checkAndResetPlotSavedState();
226 
231  void setEnableSimulationStatisticsListener( bool flag );
232 
233  bool getEnableSimulationStatisticsListener( ) const;
234 
238  bool listSessions( agx::Vector<agx::Name>& sessionNames );
239 
240 
244  agx::String getCurrentSessionName();
245 
246 
247  bool deleteSessionFromDisk( const agx::String& sessionName );
248 
249  bool startRecording( const agx::String& journalConfiguration, const agx::String& journalPath="Journal.agxJournal", const agx::String& sessionName="" );
250  bool resumeRecording( const agx::Name& sessionName, const agx::String& journalConfiguration );
251  bool stopRecording(bool resetScene=true, bool blocking=false);
252  bool startTrack();
253  bool stopTrack();
254  bool isTrackRunning() const;
255  bool isRecording() const;
256  bool isRunning() const;
257 
262  bool renameRecording( const agx::String& sessionName );
263 
267  agx::Real setJournalFrequency( agx::Real freq );
268 
273  agx::Real getJournalFrequency() const;
274 
279  agx::UInt getJournalStride() const;
280 
281  agx::UInt getAccumulatedNumFrames() const;
282  agx::UInt getNumQueuedFrames() const;
283  agx::UInt getNumCachedFrames() const;
284 
293  bool copyRecording( const agx::String& sessionName, const agx::String& newJournalPath );
294 
303  bool transferRecording( const agx::String& sessionName, const agx::String& newJournalPath );
304 
305  bool jumpToFrame( agx::UInt frame );
306  bool jumpToTime( agx::Real time );
307 
308  agx::Real getTime() const;
309  agx::UInt getCurrentFrameIndex() const;
310  agx::Real getFirstFrameTimeStamp() const;
311  agx::Real getLastFrameTimeStamp() const;
312  agx::UInt getFirstFrameIndex() const;
313  agx::UInt getLastFrameIndex() const;
314  agx::UInt getNumFrames() const;
315  agx::UInt16 getPort() const;
316 
317 
325  bool endPlayback( bool resetScene = true);
326 
327  void registerStartPlaybackSignalCallback(CallbackWrapper_Real* callback);
328  void registerStartRecordingSignalCallback(CallbackWrapper_Real* callback);
329  void registerStopPlaybackSignalCallback(CallbackWrapper_Real* callback);
330  void registerStopRecordingSignalCallback(CallbackWrapper_Real* callback);
331 
332  void registerPreStepSignalCallback( CallbackWrapper_Real* callback );
333  void registerPostStepSignalCallback(CallbackWrapper_Real* callback);
334  void registerPlaySignalCallback( CallbackWrapper* callback );
335  void registerPauseSignalCallback( CallbackWrapper* callback );
336  void registerRealTimeSignalCallback( CallbackWrapper_Bool* callback );
337  void registerJumpSignalCallback( CallbackWrapper_Real* callback );
338  void registerErrorSignalCallback( CallbackWrapper_String* callback );
339 
340 
341  void unregisterErrorSignalCallback( CallbackWrapper_String* callback );
342  void unregisterPreStepSignalCallback( CallbackWrapper_Real* callback );
343  void unregisterPostStepSignalCallback(CallbackWrapper_Real* callback);
344 
345  void unregisterStartPlaybackSignalCallback(CallbackWrapper_Real* callback);
346  void unregisterStartRecordingSignalCallback(CallbackWrapper_Real* callback);
347  void unregisterStopPlaybackSignalCallback(CallbackWrapper_Real* callback);
348  void unregisterStopRecordingSignalCallback(CallbackWrapper_Real* callback);
349 
369  void requestExclusiveAccess();
370  void relinquishExclusiveAccess();
371 
372  void setupRemoteCommandServer( agx::UInt16 port = agx::InvalidIndex, bool scan = false );
373 
379  bool getContacts( std::vector<agx::Vec3>& contactPoints, std::vector<agx::Vec3>& normals, std::vector<agx::Real>& depths ) const;
380 
390  size_t calculateDirectSolvedContacts() const;
391 
392  protected:
393  virtual ~SimulationController();
394 
395 
396  private:
397  void stepTo(std::function<bool(agx::Clock *)> stopPredicate, CallbackWrapper_String* errorCallback, bool wasTemporarilyPaused);
398 
399  // 'step', as it's written now with synchronous execution, doesn't fit well into the threading model used for the continuous stepping.
400  // Need a way to make the 'runLoop' thread we woken and take a single step. Do we need a public API 'step' method?
404  void step();
405 
406  /*
407  * HTTP callbacks used by the RemoteCommandServer.
408  */
409  // Basic simulation control.
410  bool httpPlaySimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
411  bool httpPauseSimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
412  bool httpEnableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
413  bool httpDisableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
414 
415  // Journal control.
416  bool httpEnableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
417  bool httpDisableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
418  bool httpListJournals(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
419  bool httpLoadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
420  bool httpUnloadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
421  bool httpSetPlaybackPosition(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
422 
423  // RemoteViewer control.
424  bool httpAttachRemoteViewer(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
425 
426 
427  // Websocket setup.
428  bool httpGetControlChannel(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
429  bool httpInitSynchronizationSocket(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
430 
431  void signalStartPlayback();
432  void signalStartRecording();
433  void signalStopPlayback();
434  void signalStopRecording();
435 
436  // Signaling methods. This will trigger the callbacks and write messages to the socket clients.
437  void signalPreStep();
438  void signalPostStep();
439  void signalPlay();
440  void signalPause();
441  void signalRealTime();
442  void signalJump();
443  void signalError(agx::String error);
444 
445 
446  private:
447  void init();
448  void webSocketClientConnected( agxNet::WebSocket* client );
449  void webSocketClientDisconnected( agxNet::WebSocket* client );
450  void webSocketMessageReceived( agxNet::WebSocket *socket, agx::UInt8* payload, size_t size );
451  void sendWebSocketMessage(const agxJson::Value& eMessage);
452 
453 
454  private:
455  agx::Journal::ArchiveFormat m_journalFormat;
456 
457  bool m_realTime;
458 
460  bool m_exitRunLoop;
461 
463  // bool m_singleStep;
464 
468  agx::AtomicValue m_singleStepsToTake;
469 
470 
471  agxSDK::SimulationRef m_simulation;
472  agx::JournalRef m_journal;
473 
474 
475 
476 // agx::RemoteCommandServer m_commandServer; ///\todo Make the RemoteCommandServer not a singleton.
477 
478  // These events are called from the simulation thread.
479  agx::Event1<agx::Real> m_startPlaybackEvent;
480  agx::Event1<agx::Real> m_startRecordingEvent;
481  agx::Event1<agx::Real> m_stopPlaybackEvent;
482  agx::Event1<agx::Real> m_stopRecordingEvent;
483 
484  // These events might be called for the main gui thread.
485  agx::Event1<agx::Real> m_preStepEvent;
486  agx::Event1<agx::Real> m_postStepEvent;
487  agx::Event m_playEvent;
488  agx::Event m_pauseEvent;
489  agx::Event1<bool> m_realTimeEvent;
490  agx::Event1<agx::Real> m_jumpEvent;
491  agx::Event1<agx::String> m_errorEvent;
492 
494 
495  agxNet::WebSocketRefVector m_webSocketClients;
496  agxNet::WebSocketServerRef m_webSocketServer;
497 
498  agx::Journal::SceneLoaderCallback m_defaultSceneLoader;
499 
500  agxSDK::RunLoopThread* m_runLoopThread;
501 
504  agx::ReentrantMutex m_frameMutex;
505 
506 
507 
514  agx::Block m_frameBlock;
515 
519  agx::Block m_pauseBlock;
520 
523  agx::Block m_stopBlock;
524 
526  bool m_autoStep;
527 
534  bool m_isRecording;
535 
543  enum PlaybackMode {FROM_SIMULATION, FROM_JOURNAL} m_playbackMode;
544 
545 
550  agxData::TrackRef m_remoteViewerTrack;
551 
555  agx::UInt16 m_remoteViewerPort;
556 
562  // bool m_updateSpace;
563 
564 
565  // This block of members are used for communication with the plotting tool.
566 
567  agxNet::WebSocket::ControlChannelRef m_controlChannel;
568  void controlChannelSocketConnectedCallback( agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket );
569  agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketConnectedCallback;
570  agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketDisconnectedCallback;
571 
572  void ccGetTreeStructure( agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message );
573  agxJson::Value& createArrayElement( agxJson::Value& eParent, const char* groupName );
574  void signalPlaybackStarting();
575  void signalPlaybackEnding();
576 
577  agx::JournalReaderRef m_journalReader;
578 
579  bool m_simulationStatisticsListenerEnabled;
580  bool m_saveSimulationToDisk;
581 
582  bool m_shouldSignalStartPlayback;
583  bool m_shouldSignalStartRecording;
584  bool m_shouldSignalStopPlayback;
585  bool m_shouldSignalStopRecording;
586  bool m_shouldJumpAfterStop;
587  agx::UInt m_jumpAfterStopFrame;
588  bool m_isTemporarilyPaused;
589 
590  };
591 
592 
596  class AGXPHYSICS_EXPORT ScopedStepLock
597  {
598  public:
599  ScopedStepLock( SimulationController* simulationController );
600  ~ScopedStepLock();
601  private:
602  ScopedStepLock( const ScopedStepLock& ) {};
603  void operator=( const ScopedStepLock& ) {};
604 
605  SimulationController* m_simulationController;
606  };
607 
608 
609 
610 
611 
613  AGX_FORCE_INLINE agxSDK::Simulation* SimulationController::getSimulation() { return m_simulation; }
614  AGX_FORCE_INLINE const agxSDK::Simulation* SimulationController::getSimulation() const { return m_simulation; }
615  AGX_FORCE_INLINE bool SimulationController::getRealTimeSync() const { return m_realTime; }
616  //AGX_FORCE_INLINE bool SimulationController::getUpdateSpace() const { return m_updateSpace; }
617  AGX_FORCE_INLINE bool SimulationController::isRecording() const { return m_isRecording; }
618  AGX_FORCE_INLINE bool SimulationController::isRunning() const { return m_autoStep; }
619 
620  AGX_FORCE_INLINE const agx::Journal* SimulationController::getJournal() const { return m_journal; }
621  AGX_FORCE_INLINE agx::Journal* SimulationController::getJournal() { return m_journal; }
622 }
623 
624 // use websockets?
625 #endif
626 
627 #endif
void AGXPHYSICS_EXPORT init()
Initialize AGX Dynamics API including thread resources and must be executed before using the AGX API...
agx::ref_ptr< Track > TrackRef
Definition: agxData/Track.h:34
uint8_t UInt8
Definition: Integer.h:38
#define AGXPHYSICS_EXPORT
AGXCORE_EXPORT const InvalidIndexStruct InvalidIndex
#define AGX_DECLARE_POINTER_TYPES(type)
Definition: Referenced.h:254
Representation of a name string.
Definition: Name.h:32
#define AGX_FORCE_INLINE
Definition: Object.h:59
agx::ref_ptr< Journal > JournalRef
Definition: Journal.h:45
Block synchronization primitive.
Base class providing referencing counted objects.
Definition: Referenced.h:119
uint32_t UInt
Definition: Integer.h:34
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
Callback1< const agx::String & > SceneLoaderCallback
A callback that will be called when starting playback from a recording.
Definition: Journal.h:290
Contains classes for low level data storage for AGX.
Definition: Container.h:23
#define CALLABLE
Definition: Object.h:73
std::recursive_mutex ReentrantMutex
Definition: Object.h:48
Simulation is a class that bridges the collision space agxCollide::Space and the dynamic simulation s...
Definition: Simulation.h:126
Clock class keeps representation of virtual/simulated time.
Definition: Clock.h:37
uint16_t UInt16
Definition: Integer.h:39
double Real
Definition: Real.h:42
The agxSDK namespace contain classes to bridge the collision detection system and the dynamical simul...
Definition: Constraint.h:30
An event with no arguments.
Definition: Event.h:89
An event with one argument.
Definition: Event.h:102