AGX Dynamics  2.37.2.0
ScriptManager.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 having been
9 advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10 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 #pragma once
18 
19 #include <agx/config/AGX_USE_PYTHON.h>
20 #include <agx/config/AGX_USE_WEBSOCKETS.h>
21 #include <agx/config.h>
22 
23 #if AGX_USE_PYTHON()
24 
25 #include <agx/ref_ptr.h>
26 #include <agxPython/export.h>
27 
28 #include <agx/Referenced.h>
29 #include <agx/Logger.h>
30 #include <agx/Timer.h>
31 #include <agx/agx_vector_types.h>
32 #include <agx/Uuid.h>
33 
34 #if AGX_USE_WEBSOCKETS()
36 #endif // AGX_USE_WEBSOCKETS
37 
40 
41 
42 #ifdef _MSC_VER
43 # pragma warning( push )
44 # pragma warning( disable: 4512 ) // Disable warning about assignment operator could not be generated due to reference members.
45 # pragma warning( disable: 4275 ) // Disable non dll-interface class std::exception used as base for dll-interface class agxPython::ScriptError
46 # endif // _MSC_VER
47 
48 #include <agxPython/ScriptIDE.h>
49 
50 #include <string>
51 #include <map>
52 #include <set>
53 #include <exception>
54 
55 #if AGX_USE_WEBSOCKETS()
56 namespace agxSDK
57 {
58  class SimulationController;
59 }
60 #endif // AGX_USE_WEBSOCKETS
61 
62 namespace osg
63 {
64  class Group;
65 }
66 
67 namespace agxPython {
68 
69  enum ScriptContextType
70  {
71  SCRIPTCONTEXT_INVALID = 0,
72  SCRIPTCONTEXT_PYTHON,
73  SCRIPTCONTEXT_AGXVIEWER,
74  SCRIPTCONTEXT_FMI,
75  SCRIPTCONTEXT_QTVIEWER
76  };
77 
88  class AGXPYTHON_EXPORT ScriptError : public std::exception
89  {
90 
91  public:
92 
93  ScriptError();
94  ScriptError(const ScriptError& other);
95  ScriptError(std::string scriptError, std::string scriptFile);
96 
97  virtual ~ScriptError();
98 
99  virtual const char* what() const AGX_NOEXCEPT override; //=0;
100 
101  private:
102 
103  std::string m_msg;
104 
105  };
106 
107 
108 #if AGX_USE_WEBSOCKETS()
109  AGX_DECLARE_POINTER_TYPES(StartPlaybackSignalCallback);
110  class AGXPYTHON_EXPORT StartPlaybackSignalCallback : public agxSDK::CallbackWrapper_Real
111  {
112  public:
113  StartPlaybackSignalCallback() : agxSDK::CallbackWrapper_Real() {}
114 
115  protected:
116 
117  virtual ~StartPlaybackSignalCallback() {}
118 
119  private:
120  void callback(agxSDK::SimulationController*, agx::Real value) override;
121  };
122 
123  AGX_DECLARE_POINTER_TYPES(StartRecordingSignalCallback);
124  class AGXPYTHON_EXPORT StartRecordingSignalCallback : public agxSDK::CallbackWrapper_Real
125  {
126  public:
127  StartRecordingSignalCallback() : agxSDK::CallbackWrapper_Real() {}
128 
129  protected:
130 
131  virtual ~StartRecordingSignalCallback() {}
132 
133  private:
134  void callback(agxSDK::SimulationController*, agx::Real value) override;
135  };
136 
137  AGX_DECLARE_POINTER_TYPES(StopPlaybackSignalCallback);
138  class AGXPYTHON_EXPORT StopPlaybackSignalCallback : public agxSDK::CallbackWrapper_Real
139  {
140  public:
141  StopPlaybackSignalCallback() : agxSDK::CallbackWrapper_Real() {}
142 
143  protected:
144 
145  virtual ~StopPlaybackSignalCallback() {}
146 
147  private:
148  void callback(agxSDK::SimulationController*, agx::Real value) override;
149  };
150 
151  AGX_DECLARE_POINTER_TYPES(StopRecordingSignalCallback);
152  class AGXPYTHON_EXPORT StopRecordingSignalCallback : public agxSDK::CallbackWrapper_Real
153  {
154  public:
155  StopRecordingSignalCallback() : agxSDK::CallbackWrapper_Real() {}
156 
157  protected:
158 
159  virtual ~StopRecordingSignalCallback() {}
160 
161  private:
162  void callback(agxSDK::SimulationController*, agx::Real value) override;
163  };
164 #endif // AGX_USE_WEBSOCKETS
165 
166  class ReactiveScript;
167  class ScriptContext;
168 
173  class AGXPYTHON_EXPORT ScriptManager : public agx::Singleton
174  {
175 
176  public:
177 
178  friend class ReactiveInitializer;
179 
183  static ScriptContext* getContext();
184 
185  static bool hasInstance();
186  static bool isStartedFromExternalPython();
187 
192  static ScriptManager* instance(const std::string& requestor = "", const std::string& pythonPaths="", const std::string& pythonHome="", bool ignoreEnvironment = false);
193 
195  void shutdown() override;
196 
201  void registerError(const std::string& prefix = "");
202 
206  bool breakFlag();
207 
211  void reportError(const std::string& errorReport) const;
212 
219  bool addSearchPath(const agx::String& path);
220 
234  bool registerReactiveScript(ReactiveScript* script);
235  bool unregisterReactiveScript(const agx::Uuid& uuid);
236  bool isRegisteredReactiveScript(const agx::Uuid& uuid) const;
237  void clearReactiveScripts();
238  void acquireReactiveScriptContext(const agx::Uuid& scriptId, const char* func);
239  void releaseReactiveScriptContext(const agx::Uuid& scriptId, bool unlock = true);
240  void addScriptToSimulation(const agx::Uuid& scriptId, agxSDK::Simulation* simulation);
241 
242 #if AGX_USE_WEBSOCKETS()
243  void updateReactiveScripts(agxSDK::SimulationController* simulationController);
244 #endif // AGX_USE_WEBSOCKETS
245  void updateReactiveScripts();
246 
247  void onStartPlaybackReactiveScripts(agx::Real value);
248  void onStartRecordingReactiveScripts(agx::Real value);
249  void onStopPlaybackReactiveScripts(agx::Real value);
250  void onStopRecordingReactiveScripts(agx::Real value);
251 
252 
257  std::string getLastErrorMessage() const;
258 
263  int getLastErrorLine() const;
264 
269  bool receivedErrorMessage() const;
270 
274  void resetError();
275 
279  void setLastErrorMessage(const std::string& errorMessage);
280  void setLastErrorLine(int line);
281 
289  ScriptIDERef requestVirtualIDE(const agx::Name& identifyingName);
290 
295  void setCurrentScriptSimulationOverride(agxSDK::Simulation* simulation);
296 
297 #if AGX_USE_WEBSOCKETS()
298  void registerSimulationControllerCallbacks(agxSDK::SimulationController* simulationController);
299  void unregisterSimulationControllerCallbacks(agxSDK::SimulationController* simulationController);
300 #endif // AGX_USE_WEBSOCKETS
301 
302  // Destroy the main module for the given script.
303  void destroyMainModule(const agx::Uuid& scriptId);
304 
305 #if !defined(SWIGJAVA)
306 
307  void enableEmbeddedMode(const std::string& programName);
308 
310  void init(const std::string& pythonPaths="");
311 
313  void reset();
314 
317  agxPython::ScriptContextInterface *initScriptContext(agxPython::ScriptContextType contextType);
318 
321  agxPython::ScriptContextInterface* getScriptContext();
322 
323  // Create a separate main module for the given script.
324  void createMainModule(const agx::Uuid& scriptId);
325 
326  // Swap to the main module for the given script.
327  void swapMainModule(const agx::Uuid& scriptId);
328 
329  // Swap to the global main module.
330  void restoreGlobalMainModule(bool unlock = true);
331 
332  bool hasMainModule(const agx::Uuid& uuid) const;
333 
334  void* getMainModule();
335 
341  bool hasReactiveScriptErrors( bool printWarnings = true );
342 
349  bool doFile(const std::string& path, bool resolvePath = true);
350 
356  bool doString(const std::string& code, const std::string& origin);
357 
358 
365  bool doCompiledScript(void* compiled);
366  void* doCompiledFunction(void* funcObject, void **args, int numArgs);
367 
374  bool doFunction(const std::string& function, void* args = nullptr);
375 
376 
377 
378  agxSDK::Simulation* getCurrentScriptSimulation();
379 
380 #if AGX_USE_WEBSOCKETS()
381  agxSDK::SimulationController* getCurrentScriptSimulationController();
382 #endif // AGX_USE_WEBSOCKETS
383 
384 
390  bool hasFunction(const std::string& function);
391 
392  bool getTreatInvalidAsErrors() const;
393  void setTreatInvalidAsErrors(const bool treatInvalidAsErrors);
394 
395 
413  void* getGlobals();
414 
418  std::string getProgramName();
419 
420 
421  protected:
422 
423  typedef std::map<std::string, std::string> PythonDefMap;
424 
425  PythonDefMap dumpGlobals(void* globals, std::ostream* logStream = nullptr);
426 
427 #endif // !defined(SWIGJAVA)
428 
429  public:
430 
432  static void startProfiling(void* obj, const char* decl);
434  static void endProfiling(void* obj, const char* decl);
436  static void abortProfiling(void* obj, const char* decl);
437 
438 
439  private:
440 
441  SINGLETON_CLASSNAME_METHOD();
442 
444  virtual ~ScriptManager();
445 
447  ScriptManager(const std::string& program, const std::string& pythonPaths, const std::string& pythonHome, bool ignoreEnvironment);
448 
449  agx::ref_ptr<ScriptContext> m_scriptContext;
450 
451  std::map<agx::Uuid, agx::ref_ptr<ReactiveScript> > m_reactiveScripts;
452  std::map<agx::Uuid, void*> m_reactiveScriptMainModules;
453 
454  void* m_globalMainModule;
455  void* m_currentMainModule;
456  ReactiveScript* m_currentReactiveScriptContext;
457 
458  agxSDK::Simulation* m_currentScriptSimulationOverride;
459 
460  bool m_initialized;
461  bool m_breakFlag;
462  std::string m_programName;
463  std::set<std::string> m_pythonPath;
464  wchar_t* m_pythonHome;
465  bool m_shutdownInProgress;
466  bool m_treatInvalidAsErrors;
467  std::string m_lastErrorMessage;
468  int m_lastErrorLine;
469  std::string m_scriptPath;
470  bool m_ignoreEnvironment;
471 
472  agx::Vector<ScriptIDERef> m_ideInstances;
473 
474 
475 #if AGX_USE_WEBSOCKETS()
476  StartPlaybackSignalCallbackRef m_startPlaybackSignalCallback;
477  StartRecordingSignalCallbackRef m_startRecordingSignalCallback;
478  StopPlaybackSignalCallbackRef m_stopPlaybackSignalCallback;
479  StopRecordingSignalCallbackRef m_stopRecordingSignalCallback;
480 
481 
482  agxSDK::SimulationController* m_simulationController;
483 #endif // AGX_USE_WEBSOCKETS
484 
485  agx::ReentrantMutex m_mutex;
486 
487  static ScriptManager* s_instance;
488 
492  const char* const MOMENTUM_PROGRAM_NAME = "AlgoryxMomentum";
493 
494  friend class ScriptIDEAutocompleteCollection;
495 
496  static std::shared_ptr<agx::AutoInit> m_autoInit;
497 
498  };
499 
500  AGXPYTHON_EXPORT ScriptContext* getContext();
501 
502  AGXPYTHON_EXPORT bool scriptIsAttached();
503 
504  AGXPYTHON_EXPORT bool doFile(const std::string& path);
505 
506 } // namespace agxPython
507 
508 
509 #define g_pythonScriptManager agxPython::ScriptManager::instance("")
510 #define g_pythonScriptManagerForProgram(PROGRAM) agxPython::ScriptManager::instance(PROGRAM)
511 #define AGXPYTHON_REPORT_ERROR(errorMessage) \
512  if (g_pythonScriptManager->getTreatInvalidAsErrors() || agxUnit::isUnittestingEnabled()) \
513  { \
514  LOGGER_ERROR() << (errorMessage) << std::endl << LOGGER_END(); \
515  } \
516  else \
517  { \
518  LOGGER_WARNING() << (errorMessage) << std::endl << LOGGER_END(); \
519  }
520 
521 
522 #ifdef _MSC_VER
523 # pragma warning(pop)
524 #endif
525 
526 #endif // AGX_USE_PYTHON
void AGXPHYSICS_EXPORT init()
Initialize AGX Dynamics API including thread resources and must be executed before using the AGX API...
void AGXPHYSICS_EXPORT shutdown()
Shutdown of the AGX Dynamics API will be done when the number of shutdown matches the number of calls...
STL namespace.
#define AGX_NOEXCEPT
Definition: Object.h:47
#define AGX_DECLARE_POINTER_TYPES(type)
Definition: Referenced.h:254
Representation of a name string.
Definition: Name.h:32
Templated vector class.
Definition: Vector.h:52
Smart pointer for handling referenced counted objects.
Definition: ref_ptr.h:29
A UUID, or Universally unique identifier, is intended to uniquely identify information in a distribut...
Definition: Uuid.h:41
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
double Real
Definition: Real.h:42
#define AGXPYTHON_EXPORT
The agxSDK namespace contain classes to bridge the collision detection system and the dynamical simul...
Definition: Constraint.h:30
Base class for Singletons that should have its shutdown called explicitly before exit of the applicat...
Definition: Singleton.h:30