openrave.org

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
orexample.h
Go to the documentation of this file.
1 
6 #include <openrave-core.h>
7 #include <string>
8 
9 #include <boost/thread/thread.hpp>
10 #include <boost/bind.hpp>
11 
12 #include <signal.h>
13 
14 namespace cppexamples {
15 
32 {
33 public:
34  OpenRAVEExample(const std::string& viewername="qtcoin") : _viewername(viewername), _bDestroyThread(false) {
35  OPENRAVE_ASSERT_FORMAT0(GetSingleton()==NULL,"expecting only once instance of OpenRAVEExample",OpenRAVE::ORE_Assert);
36  GetSingleton() = this;
37  signal(SIGINT,sigint_handler); // for control C
38  }
39  virtual ~OpenRAVEExample()
40  {
41  GetSingleton() = NULL;
42  this->Exit();
43  if( _thopenrave.joinable() ) {
44  _thopenrave.join(); // wait for the thread to exit
45  }
46  }
47 
48  virtual int main(int argc, char ** argv)
49  {
52  penv->SetDebugLevel(OpenRAVE::Level_Debug);
53 
54  // create a viewer
55  _viewer.reset();
56  if( _viewername.size() > 0 ) {
57  _viewer = OpenRAVE::RaveCreateViewer(penv,_viewername);
58  }
59  if( !!_viewer ) {
60  penv->Add(_viewer);
61 
62  // create the main openrave thread
63  _bDestroyThread = false;
64  _thopenrave = boost::thread(boost::bind(&OpenRAVEExample::_demothreadwrapper,this,argc,argv));
65 
66  // start the viewer main loop
67  _viewer->main(true);
68  }
69  else {
70  // just execute
71  demothread(argc,argv);
72  }
73  return 0;
74  }
75 
76  virtual bool IsOk() {
77  return !_bDestroyThread;
78  }
79 
80  virtual void Exit() {
81  _bDestroyThread = true;
83  }
84 
85  virtual void demothread(int argc, char ** argv) = 0;
86 
87 protected:
89 
90 private:
92  std::string _viewername;
93  bool _bDestroyThread;
94  boost::thread _thopenrave;
95 
96  void quitviewer(void *) {
97  if( !!_viewer ) {
98  _viewer->quitmainloop();
99  }
100  }
101 
102  void _demothreadwrapper(int argc, char ** argv) {
103  boost::shared_ptr<void> quitviewer((void*)NULL, boost::bind(&OpenRAVEExample::quitviewer, this,_1));
104  demothread(argc,argv);
105  }
106 
107  static void sigint_handler(int sig)
108  {
109  if( !!OpenRAVEExample::GetSingleton() ) {
110  OpenRAVEExample::GetSingleton()->Exit();
111  }
112  }
113 
114  static OpenRAVEExample*& GetSingleton() {
115  static OpenRAVEExample* psingleton = NULL;
116  return psingleton;
117  }
118 };
119 
120 } // end namespace cppexamples