AGXDynamics  2.31.1.0
SimulationController.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2021. 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 
137  void singleStep( bool asynchronous = true );
138 
142  void setRepeat( bool repeat );
143  bool getRepeat() const;
144 
149  void setRealTimeSync( bool realTime );
150  bool getRealTimeSync() const;
151 
155  void setFrameStride( agx::UInt stride );
156 
157 // /**
158 // * Space is updated when a new frame is loaded if update space is enabled.
159 // * It can be used to get updated contacts without saving them to the journal,
160 // * but it might be expensive.
161 // */
162 // void setUpdateSpace( bool updateSpace );
163 // bool getUpdateSpace() const;
164 
177  bool openJournal( const agx::String& journalPath="Journal.agxJournal", const agx::String& sessionName="", bool loadScene=true, bool attach=true );
178 
179  bool sanityCheck() const;
180 
181  void attach();
182 
183  void setDefaultSceneLoader(agx::Journal::SceneLoaderCallback callback);
184 
185  bool recordExtraData( const agx::String& key, const agx::String& value );
186  agx::String retrieveExtraData( const agx::String& key );
187 
188  bool truncate(agx::UInt firstFrameToRemove);
189 
199  void setSaveSceneToDisk( bool flag );
200 
204  bool getSaveSceneToDisk() const;
205 
206 
210  void signalSceneChanged();
211 
212  bool checkAndResetPlotSavedState();
213 
218  void setEnableSimulationStatisticsListener( bool flag );
219 
220  bool getEnableSimulationStatisticsListener( ) const;
221 
225  bool listSessions( agx::Vector<agx::Name>& sessionNames );
226 
227 
231  agx::String getCurrentSessionName();
232 
233 
234  bool deleteSessionFromDisk( const agx::String& sessionName );
235 
236  bool startRecording( const agx::String& journalConfiguration, const agx::String& journalPath="Journal.agxJournal", const agx::String& sessionName="" );
237  bool resumeRecording( const agx::Name& sessionName, const agx::String& journalConfiguration );
238  bool stopRecording(bool resetScene=true, bool blocking=false);
239  bool startTrack();
240  bool stopTrack();
241  bool isTrackRunning() const;
242  bool isRecording() const;
243  bool isRunning() const;
244 
249  bool renameRecording( const agx::String& sessionName );
250 
254  agx::Real setJournalFrequency( agx::Real freq );
255 
260  agx::Real getJournalFrequency() const;
261 
266  agx::UInt getJournalStride() const;
267 
268  agx::UInt getAccumulatedNumFrames() const;
269  agx::UInt getNumQueuedFrames() const;
270  agx::UInt getNumCachedFrames() const;
271 
280  bool copyRecording( const agx::String& sessionName, const agx::String& newJournalPath );
281 
290  bool transferRecording( const agx::String& sessionName, const agx::String& newJournalPath );
291 
292  bool jumpToFrame( agx::UInt frame );
293  bool jumpToTime( agx::Real time );
294 
295  agx::Real getTime() const;
296  agx::UInt getCurrentFrameIndex() const;
297  agx::Real getFirstFrameTimeStamp() const;
298  agx::Real getLastFrameTimeStamp() const;
299  agx::UInt getFirstFrameIndex() const;
300  agx::UInt getLastFrameIndex() const;
301  agx::UInt getNumFrames() const;
302  agx::UInt16 getPort() const;
303 
304 
312  bool endPlayback( bool resetScene = true);
313 
314  void registerStartPlaybackSignalCallback(CallbackWrapper_Real* callback);
315  void registerStartRecordingSignalCallback(CallbackWrapper_Real* callback);
316  void registerStopPlaybackSignalCallback(CallbackWrapper_Real* callback);
317  void registerStopRecordingSignalCallback(CallbackWrapper_Real* callback);
318 
319  void registerPreStepSignalCallback( CallbackWrapper_Real* callback );
320  void registerPostStepSignalCallback(CallbackWrapper_Real* callback);
321  void registerPlaySignalCallback( CallbackWrapper* callback );
322  void registerPauseSignalCallback( CallbackWrapper* callback );
323  void registerRealTimeSignalCallback( CallbackWrapper_Bool* callback );
324  void registerJumpSignalCallback( CallbackWrapper_Real* callback );
325  void registerErrorSignalCallback( CallbackWrapper_String* callback );
326 
327 
328  void unregisterPreStepSignalCallback( CallbackWrapper_Real* callback );
329  void unregisterPostStepSignalCallback(CallbackWrapper_Real* callback);
330 
331  void unregisterStartPlaybackSignalCallback(CallbackWrapper_Real* callback);
332  void unregisterStartRecordingSignalCallback(CallbackWrapper_Real* callback);
333  void unregisterStopPlaybackSignalCallback(CallbackWrapper_Real* callback);
334  void unregisterStopRecordingSignalCallback(CallbackWrapper_Real* callback);
335 
355  void requestExclusiveAccess();
356  void relinquishExclusiveAccess();
357 
358  void setupRemoteCommandServer( agx::UInt16 port = agx::InvalidIndex, bool scan = false );
359 
365  bool getContacts( std::vector<agx::Vec3>& contactPoints, std::vector<agx::Vec3>& normals, std::vector<agx::Real>& depths ) const;
366 
376  size_t calculateDirectSolvedContacts() const;
377 
378  protected:
379  virtual ~SimulationController();
380 
381 
382  private:
383 
384  // 'step', as it's written now with synchronous execution, doesn't fit well into the threading model used for the continuous stepping.
385  // Need a way to make the 'runLoop' thread we woken and take a single step. Do we need a public API 'step' method?
389  void step();
390 
391  /*
392  * HTTP callbacks used by the RemoteCommandServer.
393  */
394  // Basic simulation control.
395  bool httpPlaySimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
396  bool httpPauseSimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
397  bool httpEnableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
398  bool httpDisableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
399 
400  // Journal control.
401  bool httpEnableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
402  bool httpDisableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
403  bool httpListJournals(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
404  bool httpLoadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
405  bool httpUnloadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
406  bool httpSetPlaybackPosition(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
407 
408  // RemoteViewer control.
409  bool httpAttachRemoteViewer(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
410 
411 
412  // Websocket setup.
413  bool httpGetControlChannel(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
414  bool httpInitSynchronizationSocket(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
415 
416  void signalStartPlayback();
417  void signalStartRecording();
418  void signalStopPlayback();
419  void signalStopRecording();
420 
421  // Signaling methods. This will trigger the callbacks and write messages to the socket clients.
422  void signalPreStep();
423  void signalPostStep();
424  void signalPlay();
425  void signalPause();
426  void signalRealTime();
427  void signalJump();
428  void signalError(agx::String error);
429 
430 
431  private:
432  void init();
433  void webSocketClientConnected( agxNet::WebSocket* client );
434  void webSocketClientDisconnected( agxNet::WebSocket* client );
435  void webSocketMessageReceived( agxNet::WebSocket *socket, agx::UInt8* payload, size_t size );
436  void sendWebSocketMessage(const agxJson::Value& eMessage);
437 
438 
439  private:
440 
441  bool m_realTime;
442 
444  bool m_exitRunLoop;
445 
447  // bool m_singleStep;
448 
452  agx::AtomicValue m_singleStepsToTake;
453 
454 
455  agxSDK::SimulationRef m_simulation;
456  agx::JournalRef m_journal;
457 
458 
459 
460 // agx::RemoteCommandServer m_commandServer; ///\todo Make the RemoteCommandServer not a singleton.
461 
462  // These events are called from the simulation thread.
463  agx::Event1<agx::Real> m_startPlaybackEvent;
464  agx::Event1<agx::Real> m_startRecordingEvent;
465  agx::Event1<agx::Real> m_stopPlaybackEvent;
466  agx::Event1<agx::Real> m_stopRecordingEvent;
467 
468  // These events might be called for the main gui thread.
469  agx::Event1<agx::Real> m_preStepEvent;
470  agx::Event1<agx::Real> m_postStepEvent;
471  agx::Event m_playEvent;
472  agx::Event m_pauseEvent;
473  agx::Event1<bool> m_realTimeEvent;
474  agx::Event1<agx::Real> m_jumpEvent;
475  agx::Event1<agx::String> m_errorEvent;
476 
478 
479  agxNet::WebSocketRefVector m_webSocketClients;
480  agxNet::WebSocketServerRef m_webSocketServer;
481 
482  agx::Journal::SceneLoaderCallback m_defaultSceneLoader;
483 
484  agxSDK::RunLoopThread* m_runLoopThread;
485 
488  agx::ReentrantMutex m_frameMutex;
489 
490 
491 
498  agx::Block m_frameBlock;
499 
503  agx::Block m_pauseBlock;
504 
507  agx::Block m_stopBlock;
508 
510  bool m_autoStep;
511 
518  bool m_isRecording;
519 
527  enum PlaybackMode {FROM_SIMULATION, FROM_JOURNAL} m_playbackMode;
528 
529 
534  agxData::TrackRef m_remoteViewerTrack;
535 
539  agx::UInt16 m_remoteViewerPort;
540 
546  // bool m_updateSpace;
547 
548 
549  // This block of members are used for communication with the plotting tool.
550 
551  agxNet::WebSocket::ControlChannelRef m_controlChannel;
552  void controlChannelSocketConnectedCallback( agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket );
553  agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketConnectedCallback;
554  agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketDisconnectedCallback;
555 
556  void ccGetTreeStructure( agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message );
557  agxJson::Value& createArrayElement( agxJson::Value& eParent, const char* groupName );
558  void signalPlaybackStarting();
559  void signalPlaybackEnding();
560 
561  agx::JournalReaderRef m_journalReader;
562 
563  bool m_simulationStatisticsListenerEnabled;
564  bool m_saveSimulationToDisk;
565 
566  bool m_shouldSignalStartPlayback;
567  bool m_shouldSignalStartRecording;
568  bool m_shouldSignalStopPlayback;
569  bool m_shouldSignalStopRecording;
570  bool m_shouldJumpAfterStop;
571  agx::UInt m_jumpAfterStopFrame;
572  bool m_isTemporarilyPaused;
573 
574  };
575 
576 
580  class AGXPHYSICS_EXPORT ScopedStepLock
581  {
582  public:
583  ScopedStepLock( SimulationController* simulationController );
584  ~ScopedStepLock();
585  private:
586  ScopedStepLock( const ScopedStepLock& ) {};
587  void operator=( const ScopedStepLock& ) {};
588 
589  SimulationController* m_simulationController;
590  };
591 
592 
593 
594 
595 
597  AGX_FORCE_INLINE agxSDK::Simulation* SimulationController::getSimulation() { return m_simulation; }
598  AGX_FORCE_INLINE const agxSDK::Simulation* SimulationController::getSimulation() const { return m_simulation; }
599  AGX_FORCE_INLINE bool SimulationController::getRealTimeSync() const { return m_realTime; }
600  //AGX_FORCE_INLINE bool SimulationController::getUpdateSpace() const { return m_updateSpace; }
601  AGX_FORCE_INLINE bool SimulationController::isRecording() const { return m_isRecording; }
602  AGX_FORCE_INLINE bool SimulationController::isRunning() const { return m_autoStep; }
603 
604  AGX_FORCE_INLINE const agx::Journal* SimulationController::getJournal() const { return m_journal; }
605  AGX_FORCE_INLINE agx::Journal* SimulationController::getJournal() { return m_journal; }
606 }
607 
608 // use websockets?
609 #endif
610 
611 #endif
void AGXPHYSICS_EXPORT init()
Initialize agx.
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:248
Representation of a name string.
Definition: Name.h:32
#define AGX_FORCE_INLINE
Definition: Object.h:63
agx::ref_ptr< Journal > JournalRef
Definition: Journal.h:44
Block synchronization primitive.
Base class providing referencing counted objects.
Definition: Referenced.h:113
uint32_t UInt
Definition: Integer.h:34
Namespace agx 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:284
Contains classes for low level data storage for AGX.
Definition: Container.h:23
GLenum GLuint GLenum GLsizei const GLchar * message
Definition: gl.h:5539
#define CALLABLE
Definition: Object.h:77
std::recursive_mutex ReentrantMutex
Definition: Object.h:49
Simulation is a class that bridges the collision space agxCollide::Space and the dynamic simulation s...
Definition: Simulation.h:121
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