AGX Dynamics 2.38.0.2
Loading...
Searching...
No Matches
SimulationController.h
Go to the documentation of this file.
1/*
2Copyright 2007-2024. Algoryx Simulation AB.
3
4All AGX source code, intellectual property, documentation, sample code,
5tutorials, scene files and technical white papers, are copyrighted, proprietary
6and confidential material of Algoryx Simulation AB. You may not download, read,
7store, distribute, publish, copy or otherwise disseminate, use or expose this
8material unless having a written signed agreement with Algoryx Simulation AB, or
9having been advised so by Algoryx Simulation AB for a time limited evaluation,
10or having purchased a valid commercial license from Algoryx Simulation AB.
11
12Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13from using this software, unless otherwise stated in written agreements with
14Algoryx Simulation AB.
15*/
16
17
18#pragma once
19
20#include <agx/config/AGX_USE_WEBSOCKETS.h>
21
22#if AGX_USE_WEBSOCKETS()
23
24#include <agx/Referenced.h>
25#include <agx/Callback.h>
26#include <agx/Event.h>
27#include <agx/macros.h>
28#include <agx/Journal.h>
29#include <agx/JournalReader.h>
30
32
33#include <agxSDK/Simulation.h>
35
36#include <agxNet/WebSocket.h>
37
38namespace agx
39{
40 class Journal;
42}
43
44
45namespace agxData
46{
47 class Track;
49}
50
51
52
53namespace agxSDK
54{
55 class RunLoopThread;
56 class ScopedStepLock;
57
58
64 AGX_DECLARE_POINTER_TYPES(SimulationController);
65 class CALLABLE AGXPHYSICS_EXPORT SimulationController : public agx::Referenced
66 {
67 public:
68
72 SimulationController();
73
74
80 SimulationController( bool enableRemoteCommandServer, agx::UInt16 port = agx::InvalidIndex, bool scan = false );
81
82
83 agxSDK::Simulation* getSimulation();
84 const agxSDK::Simulation* getSimulation() const;
85
86 agx::Journal* getJournal();
87 const agx::Journal* getJournal() const;
88
89
94 void clearSimulation();
95
100 void clear();
101
102
109 void runLoop();
110
111
115 void stopRunLoop();
116
117
121 void startRunLoopThread();
122
123
124
128 void play(bool wasTemporarilyPaused = false);
129
130
135 void pause(bool isTemporarilyPaused = false);
136
137
141 void stepTo(agx::Real time, CallbackWrapper_String* errorCallback = nullptr, bool wasTemporarilyPaused = false);
142
146 void stepToFrame(agx::UInt frameIndex, CallbackWrapper_String* errorCallback = nullptr, bool wasTemporarilyPaused = false);
147
152 void singleStep( bool asynchronous = true );
153
157 void setRepeat( bool repeat );
158 bool getRepeat() const;
159
164 void setRealTimeSync( bool realTime );
165 bool getRealTimeSync() const;
166
170 void setFrameStride( agx::UInt stride );
171
172// /**
173// * Space is updated when a new frame is loaded if update space is enabled.
174// * It can be used to get updated contacts without saving them to the journal,
175// * but it might be expensive.
176// */
177// void setUpdateSpace( bool updateSpace );
178// bool getUpdateSpace() const;
179
192 bool openJournal( const agx::String& journalPath="Journal.agxJournal", const agx::String& sessionName="", bool loadScene=true, bool attach=true );
193
194 void setJournalFormat(agx::Journal::ArchiveFormat format);
195 agx::Journal::ArchiveFormat getJournalFormat() const;
196
197 bool sanityCheck() const;
198
199 void attach();
200
201 void setDefaultSceneLoader(agx::Journal::SceneLoaderCallback callback);
202
203 bool recordExtraData( const agx::String& key, const agx::String& value );
204 agx::String retrieveExtraData( const agx::String& key );
205
206 bool truncate(agx::UInt firstFrameToRemove);
207
217 void setSaveSceneToDisk( bool flag );
218
222 bool getSaveSceneToDisk() const;
223
224
228 void signalSceneChanged();
229
230 bool checkAndResetPlotSavedState();
231
236 void setEnableSimulationStatisticsListener( bool flag );
237
238 bool getEnableSimulationStatisticsListener( ) const;
239
243 bool listSessions( agx::Vector<agx::Name>& sessionNames );
244
245
249 agx::String getCurrentSessionName();
250
251
252 bool deleteSessionFromDisk( const agx::String& sessionName );
253
254 bool startRecording( const agx::String& journalConfiguration, const agx::String& journalPath="Journal.agxJournal", const agx::String& sessionName="" );
255 bool resumeRecording( const agx::Name& sessionName, const agx::String& journalConfiguration );
256 bool stopRecording(bool resetScene=true, bool blocking=false);
257 bool startTrack();
258 bool stopTrack();
259 bool isTrackRunning() const;
260 bool isRecording() const;
261 bool isRunning() const;
262
267 bool renameRecording( const agx::String& sessionName );
268
272 agx::Real setJournalFrequency( agx::Real freq );
273
278 agx::Real getJournalFrequency() const;
279
284 agx::UInt getJournalStride() const;
285
286 agx::UInt getAccumulatedNumFrames() const;
287 agx::UInt getNumQueuedFrames() const;
288 agx::UInt getNumCachedFrames() const;
289
298 bool copyRecording( const agx::String& sessionName, const agx::String& newJournalPath );
299
308 bool transferRecording( const agx::String& sessionName, const agx::String& newJournalPath );
309
310 bool jumpToFrame( agx::UInt frame );
311 bool jumpToTime( agx::Real time );
312
313 agx::Real getTime() const;
314 agx::UInt getCurrentFrameIndex() const;
315 agx::Real getFirstFrameTimeStamp() const;
316 agx::Real getLastFrameTimeStamp() const;
317 agx::UInt getFirstFrameIndex() const;
318 agx::UInt getLastFrameIndex() const;
319 agx::UInt getNumFrames() const;
320 agx::UInt16 getPort() const;
321
322
330 bool endPlayback( bool resetScene = true);
331
332 void registerStartPlaybackSignalCallback(CallbackWrapper_Real* callback);
333 void registerStartRecordingSignalCallback(CallbackWrapper_Real* callback);
334 void registerStopPlaybackSignalCallback(CallbackWrapper_Real* callback);
335 void registerStopRecordingSignalCallback(CallbackWrapper_Real* callback);
336
337 void registerPreStepSignalCallback( CallbackWrapper_Real* callback );
338 void registerPostStepSignalCallback(CallbackWrapper_Real* callback);
339 void registerPlaySignalCallback( CallbackWrapper* callback );
340 void registerPauseSignalCallback( CallbackWrapper* callback );
341 void registerRealTimeSignalCallback( CallbackWrapper_Bool* callback );
342 void registerJumpSignalCallback( CallbackWrapper_Real* callback );
343 void registerErrorSignalCallback( CallbackWrapper_String* callback );
344
345
346 void unregisterErrorSignalCallback( CallbackWrapper_String* callback );
347 void unregisterPreStepSignalCallback( CallbackWrapper_Real* callback );
348 void unregisterPostStepSignalCallback(CallbackWrapper_Real* callback);
349
350 void unregisterStartPlaybackSignalCallback(CallbackWrapper_Real* callback);
351 void unregisterStartRecordingSignalCallback(CallbackWrapper_Real* callback);
352 void unregisterStopPlaybackSignalCallback(CallbackWrapper_Real* callback);
353 void unregisterStopRecordingSignalCallback(CallbackWrapper_Real* callback);
354
374 void requestExclusiveAccess();
375 void relinquishExclusiveAccess();
376
377 void setupRemoteCommandServer( agx::UInt16 port = agx::InvalidIndex, bool scan = false );
378
384 bool getContacts( std::vector<agx::Vec3>& contactPoints, std::vector<agx::Vec3>& normals, std::vector<agx::Real>& depths ) const;
385
395 size_t calculateDirectSolvedContacts() const;
396
397 protected:
398 virtual ~SimulationController();
399
400
401 private:
402 void stepTo(std::function<bool(agx::Clock *)> stopPredicate, CallbackWrapper_String* errorCallback, bool wasTemporarilyPaused);
403
404 // 'step', as it's written now with synchronous execution, doesn't fit well into the threading model used for the continuous stepping.
405 // Need a way to make the 'runLoop' thread we woken and take a single step. Do we need a public API 'step' method?
409 void step();
410
411 /*
412 * HTTP callbacks used by the RemoteCommandServer.
413 */
414 // Basic simulation control.
415 bool httpPlaySimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
416 bool httpPauseSimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
417 bool httpEnableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
418 bool httpDisableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
419
420 // Journal control.
421 bool httpEnableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
422 bool httpDisableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
423 bool httpListJournals(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
424 bool httpLoadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
425 bool httpUnloadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
426 bool httpSetPlaybackPosition(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
427
428 // RemoteViewer control.
429 bool httpAttachRemoteViewer(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
430
431
432 // Websocket setup.
433 bool httpGetControlChannel(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
434 bool httpInitSynchronizationSocket(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
435
436 void signalStartPlayback();
437 void signalStartRecording();
438 void signalStopPlayback();
439 void signalStopRecording();
440
441 // Signaling methods. This will trigger the callbacks and write messages to the socket clients.
442 void signalPreStep();
443 void signalPostStep();
444 void signalPlay();
445 void signalPause();
446 void signalRealTime();
447 void signalJump();
448 void signalError(agx::String error);
449
450
451 private:
452 void init();
453 void webSocketClientConnected( agxNet::WebSocket* client );
454 void webSocketClientDisconnected( agxNet::WebSocket* client );
455 void webSocketMessageReceived( agxNet::WebSocket *socket, agx::UInt8* payload, size_t size );
456 void sendWebSocketMessage(const agxJson::Value& eMessage);
457
458
459 private:
460 agx::Journal::ArchiveFormat m_journalFormat;
461
462 bool m_realTime;
463
465 bool m_exitRunLoop;
466
468 // bool m_singleStep;
469
473 agx::AtomicValue m_singleStepsToTake;
474
475
476 agxSDK::SimulationRef m_simulation;
477 agx::JournalRef m_journal;
478
479
480
481// agx::RemoteCommandServer m_commandServer; ///\todo Make the RemoteCommandServer not a singleton.
482
483 // These events are called from the simulation thread.
484 agx::Event1<agx::Real> m_startPlaybackEvent;
485 agx::Event1<agx::Real> m_startRecordingEvent;
486 agx::Event1<agx::Real> m_stopPlaybackEvent;
487 agx::Event1<agx::Real> m_stopRecordingEvent;
488
489 // These events might be called for the main gui thread.
490 agx::Event1<agx::Real> m_preStepEvent;
491 agx::Event1<agx::Real> m_postStepEvent;
492 agx::Event m_playEvent;
493 agx::Event m_pauseEvent;
494 agx::Event1<bool> m_realTimeEvent;
495 agx::Event1<agx::Real> m_jumpEvent;
496 agx::Event1<agx::String> m_errorEvent;
497
499
500 agxNet::WebSocketRefVector m_webSocketClients;
501 agxNet::WebSocketServerRef m_webSocketServer;
502
503 agx::Journal::SceneLoaderCallback m_defaultSceneLoader;
504
505 agxSDK::RunLoopThread* m_runLoopThread;
506
509 agx::ReentrantMutex m_frameMutex;
510
511
512
519 agx::Block m_frameBlock;
520
524 agx::Block m_pauseBlock;
525
528 agx::Block m_stopBlock;
529
531 bool m_autoStep;
532
539 bool m_isRecording;
540
548 enum PlaybackMode {FROM_SIMULATION, FROM_JOURNAL} m_playbackMode;
549
550
555 agxData::TrackRef m_remoteViewerTrack;
556
560 agx::UInt16 m_remoteViewerPort;
561
567 // bool m_updateSpace;
568
569
570 // This block of members are used for communication with the plotting tool.
571
572 agxNet::WebSocket::ControlChannelRef m_controlChannel;
573 void controlChannelSocketConnectedCallback( agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket );
574 agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketConnectedCallback;
575 agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketDisconnectedCallback;
576
577 void ccGetTreeStructure( agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message );
578 agxJson::Value& createArrayElement( agxJson::Value& eParent, const char* groupName );
579 void signalPlaybackStarting();
580 void signalPlaybackEnding();
581
582 agx::JournalReaderRef m_journalReader;
583
584 bool m_simulationStatisticsListenerEnabled;
585 bool m_saveSimulationToDisk;
586
587 bool m_shouldSignalStartPlayback;
588 bool m_shouldSignalStartRecording;
589 bool m_shouldSignalStopPlayback;
590 bool m_shouldSignalStopRecording;
591 bool m_shouldJumpAfterStop;
592 agx::UInt m_jumpAfterStopFrame;
593 bool m_isTemporarilyPaused;
594
595 };
596
597
601 class AGXPHYSICS_EXPORT ScopedStepLock
602 {
603 public:
604 ScopedStepLock( SimulationController* simulationController );
605 ~ScopedStepLock();
606 private:
607 ScopedStepLock( const ScopedStepLock& ) {};
608 void operator=( const ScopedStepLock& ) {};
609
610 SimulationController* m_simulationController;
611 };
612
613
614
615
616
618 AGX_FORCE_INLINE agxSDK::Simulation* SimulationController::getSimulation() { return m_simulation; }
619 AGX_FORCE_INLINE const agxSDK::Simulation* SimulationController::getSimulation() const { return m_simulation; }
620 AGX_FORCE_INLINE bool SimulationController::getRealTimeSync() const { return m_realTime; }
621 //AGX_FORCE_INLINE bool SimulationController::getUpdateSpace() const { return m_updateSpace; }
622 AGX_FORCE_INLINE bool SimulationController::isRecording() const { return m_isRecording; }
623 AGX_FORCE_INLINE bool SimulationController::isRunning() const { return m_autoStep; }
624
625 AGX_FORCE_INLINE const agx::Journal* SimulationController::getJournal() const { return m_journal; }
626 AGX_FORCE_INLINE agx::Journal* SimulationController::getJournal() { return m_journal; }
627}
628
629// use websockets?
630#endif
631
#define AGX_DECLARE_POINTER_TYPES(type)
Definition Referenced.h:254
#define AGXPHYSICS_EXPORT
Simulation is a class that bridges the collision space agxCollide::Space and the dynamic simulation s...
Definition Simulation.h:126
Block synchronization primitive.
Clock class keeps representation of virtual/simulated time.
Definition Clock.h:38
An event with one argument.
Definition Event.h:103
An event with no arguments.
Definition Event.h:90
Representation of a name string.
Definition Name.h:33
Base class providing referencing counted objects.
Definition Referenced.h:120
Templated vector class.
Definition agx/Vector.h:53
Smart pointer for handling referenced counted objects.
Definition ref_ptr.h:30
#define CALLABLE
Definition macros.h:72
#define AGX_FORCE_INLINE
Definition macros.h:58
Contains classes for low level data storage for AGX.
Definition Container.h:23
agx::ref_ptr< Track > TrackRef
The agxSDK namespace contain classes to bridge the collision detection system and the dynamical simul...
Definition Constraint.h:31
AGXTERRAIN_EXPORT void clear()
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
uint16_t UInt16
Definition Integer.h:31
agx::ref_ptr< Journal > JournalRef
Definition Journal.h:45
uint64_t UInt
Definition Integer.h:27
double Real
Definition Real.h:42
uint8_t UInt8
Definition Integer.h:30
AGXCORE_EXPORT const InvalidIndexStruct InvalidIndex
std::recursive_mutex ReentrantMutex
Definition Object.h:48
void AGXPHYSICS_EXPORT init()
Initialize AGX Dynamics API including thread resources and must be executed before using the AGX API.