PySimulator.cpp
Go to the documentation of this file.
1 #include <fstream>
2 #include <boost/bind.hpp>
3 #include <boost/function.hpp>
4 #include <boost/python.hpp>
5 #include <boost/foreach.hpp>
6 #include <boost/range/value_type.hpp>
7 #include <rtm/Manager.h>
8 #include <rtm/CorbaNaming.h>
9 #include <hrpModel/ModelLoaderUtil.h>
10 #ifdef __APPLE__
11 #include <GLUT/glut.h>
12 #else
13 #include <GL/glut.h>
14 #endif
15 #include <SDL_thread.h>
16 #include "hrpsys/util/GLbody.h"
17 #include "hrpsys/util/GLlink.h"
18 #include "hrpsys/util/GLutil.h"
19 #include "hrpsys/util/Project.h"
20 #include "hrpsys/util/OpenRTMUtil.h"
21 #include "hrpsys/util/BVutil.h"
22 #include "PyBody.h"
23 #include "PyLink.h"
24 #include "PyShape.h"
25 #include "PySimulator.h"
26 
27 using namespace std;
28 using namespace hrp;
29 using namespace OpenHRP;
30 
31 static hrp::Link *createLink() { return new PyLink(); }
32 hrp::BodyPtr createBody(const std::string& name, const ModelItem& mitem,
33  ModelLoader_ptr modelloader, GLscene *scene,
34  bool usebbox)
35 {
36  std::cout << "createBody(" << name << "," << mitem.url << ")" << std::endl;
38  std::string args = "PyBody?instance_name="+name;
39  PyBody *pybody = (PyBody *)manager.createComponent(args.c_str());
40  hrp::BodyPtr body = hrp::BodyPtr(pybody);
41  BodyInfo_var binfo;
42  try{
43  OpenHRP::ModelLoader::ModelLoadOption opt;
44  opt.readImage = true;
45  opt.AABBdata.length(0);
46  opt.AABBtype = OpenHRP::ModelLoader::AABB_NUM;
47  binfo = modelloader->getBodyInfoEx(mitem.url.c_str(), opt);
48  }catch(OpenHRP::ModelLoader::ModelLoaderException ex){
49  std::cerr << ex.description << std::endl;
50  return hrp::BodyPtr();
51  }
52  if (!loadBodyFromBodyInfo(body, binfo, true, GLlinkFactory)){
53  std::cerr << "failed to load model[" << mitem.url << "]" << std::endl;
54  manager.deleteComponent(pybody);
55  return hrp::BodyPtr();
56  }else{
57  if (usebbox) convertToAABB(body);
58  for (std::map<std::string, JointItem>::const_iterator it2=mitem.joint.begin();
59  it2 != mitem.joint.end(); it2++){
60  hrp::Link *link = body->link(it2->first);
61  if (!link) continue;
62  link->isHighGainMode = it2->second.isHighGain;
63  if (it2->second.collisionShape == ""){
64  // do nothing
65  }else if (it2->second.collisionShape == "convex hull"){
66  convertToConvexHull(link);
67  }else if (it2->second.collisionShape == "AABB"){
68  convertToAABB(link);
69  }else{
70  std::cerr << "unknown value of collisionShape property:"
71  << it2->second.collisionShape << std::endl;
72  }
73  }
74  for (size_t i=0; i<mitem.inports.size(); i++){
75  pybody->createInPort(mitem.inports[i]);
76  }
77  for (size_t i=0; i<mitem.outports.size(); i++){
78  pybody->createOutPort(mitem.outports[i]);
79  }
80  loadShapeFromBodyInfo(pybody, binfo, createPyShape);
81  body->setName(name);
82  scene->addBody(body);
83  return body;
84  }
85 }
86 
88  Simulator(&log), scene(&log), window(&scene, &log, this), manager(NULL),
89  useBBox(false), maxLogLen(60)
90 {
92 }
93 
94 PySimulator::PySimulator(PyObject *pyo) :
95  Simulator(&log), scene(&log), window(&scene, &log, this), manager(NULL),
96  useBBox(false)
97 {
98  initRTCmanager(pyo);
99 }
100 
102  stop();
103  window.stop();
104  clear();
105  if (manager) manager->shutdown();
106 }
107 
109 {
110  window.start();
111 }
112 
114 {
115  int argc=1;
116  char *argv[] = {(char *)"dummy"};
117  initRTCmanager(argc, argv);
118 }
119 
120 void PySimulator::initRTCmanager(int argc, char **argv)
121 {
122  manager = RTC::Manager::init(argc, argv);
123  manager->init(argc, argv);
126  manager->runManager(true);
127 }
128 
129 void PySimulator::initRTCmanager(PyObject *pyo)
130 {
131  std::vector<char *> args(PySequence_Size(pyo)+1);
132  args[0] = (char *)"dummy";
133  for (int i=0; i<PySequence_Size(pyo); i++) {
134  args[i+1] = boost::python::extract<char *>(PySequence_GetItem(pyo, i));
135  }
136  initRTCmanager(args.size(), &args[0]);
137 }
138 
139 PyBody* PySimulator::loadBody(std::string name, std::string url){
141  std::string nameServer = manager->getConfig()["corba.nameservers"];
142  int comPos = nameServer.find(",");
143  if (comPos < 0){
144  comPos = nameServer.length();
145  }
146  nameServer = nameServer.substr(0, comPos);
147  RTC::CorbaNaming naming(manager->getORB(), nameServer.c_str());
148 
149  ModelLoader_var modelloader = getModelLoader(CosNaming::NamingContext::_duplicate(naming.getRootContext()));
150  OpenHRP::BodyInfo_var binfo;
151  try{
152  binfo = modelloader->loadBodyInfo(url.c_str());
153  }catch(OpenHRP::ModelLoader::ModelLoaderException ex){
154  std::cerr << ex.description << std::endl;
155  return NULL;
156  }
157  std::string args = "PyBody?instance_name="+name;
158  PyBody *pybody = (PyBody *)manager->createComponent(args.c_str());
159  pybody->setListener(this);
160  hrp::BodyPtr body = hrp::BodyPtr(pybody);
161  if (!loadBodyFromBodyInfo(body, binfo, true, createLink)){
162  std::cerr << "failed to load model[" << url << "]" << std::endl;
163  manager->deleteComponent(pybody);
164  return NULL;
165  }else{
166  if (useBBox) convertToAABB(body);
167  body->setName(name);
168  addBody(body);
169  loadShapeFromBodyInfo(pybody, binfo, createPyShape);
170  scene.addBody(body);
171  return pybody;
172  }
173 }
174 
175 bool PySimulator::loadProject(std::string fname){
176  clear();
177 
178  Project prj;
179  if (!prj.parse(fname)){
180  std::cerr << "failed to parse " << fname << std::endl;
181  return false;
182  }
183 
185  std::string nameServer = manager->getConfig()["corba.nameservers"];
186  int comPos = nameServer.find(",");
187  if (comPos < 0){
188  comPos = nameServer.length();
189  }
190  nameServer = nameServer.substr(0, comPos);
191  RTC::CorbaNaming naming(manager->getORB(), nameServer.c_str());
192 
193  ModelLoader_var modelloader = getModelLoader(CosNaming::NamingContext::_duplicate(naming.getRootContext()));
194  //================= setup Simulator ======================
195  BodyFactory factory = boost::bind(::createBody, _1, _2, modelloader,
196  &scene, useBBox);
197  init(prj, factory);
198  for (unsigned int i=0; i<numBodies(); i++){
199  PyBody *pybody = dynamic_cast<PyBody *>(body(i).get());
200  pybody->setListener(this);
201  }
202  window.setView(prj.view().T);
203 
204  std::cout << "timestep = " << prj.timeStep() << ", total time = "
205  << prj.totalTime() << std::endl;
206  return true;
207 }
208 
210 {
211  while(oneStep());
212 }
213 
214 void PySimulator::simulate(double time)
215 {
216  setTotalTime(currentTime()+time);
217  simulate();
218 }
219 
220 void PySimulator::start(double time)
221 {
222  setTotalTime(currentTime()+time);
224 }
225 
226 void PySimulator::endless(bool flag)
227 {
228  if (flag){
229  setTotalTime(0);
231  }
232 }
233 
235 {
237  log.clear();
238  if (window.isRunning()) scene.requestClear();
239 }
240 
242 {
243  log.play();
244 }
245 
247 {
248  log.play();
249 }
250 
252 {
253  appendLog();
254 }
255 
256 PyBody *PySimulator::createBody(std::string name)
257 {
259  std::string args = "PyBody?instance_name="+name;
260  PyBody *pybody = (PyBody *)manager->createComponent(args.c_str());
261  pybody->setListener(this);
262  pybody->setName(name);
263  PyLink *root = new PyLink();
264  root->name = "root";
265  pybody->setRootLink(root);
266 
267  hrp::BodyPtr body = hrp::BodyPtr(pybody);
268  addBody(body);
269  scene.addBody(body);
270 
271  return pybody;
272 }
273 
275 {
276  boost::python::list retval;
277  for (unsigned int i=0; i<numBodies(); i++){
278  PyBody *b = dynamic_cast<PyBody *>(body(i).get());
279  retval.append(boost::python::ptr(b));
280  }
281  return boost::python::incref(retval.ptr());
282 }
283 
285 {
287 }
288 
289 void PySimulator::capture(std::string fname)
290 {
291  scene.requestCapture(fname.c_str());
292 }
293 
295 {
296  return log.length();
297 }
298 
299 PyBody *PySimulator::getBody(std::string name)
300 {
301  return dynamic_cast<PyBody *>(body(name).get());
302 }
303 
305 {
306  return scene.showSensors();
307 }
308 
310 {
311  scene.showSensors(flag);
312 }
313 
315 {
316  maxLogLen = len;
317 }
318 
320 {
321  return maxLogLen;
322 }
323 
325 {
326  log.clear();
327  setCurrentTime(0.0);
328  for (unsigned int i=0; i<numBodies(); i++){
329  body(i)->initializeConfiguration();
330  }
331  checkCollision();
332  appendLog();
333 }
334 
335 void PySimulator::setUseBBox(bool flag)
336 {
337  useBBox = flag;
338 }
339 
341 {
342  window.setSize(s,s);
343 }
344 
346 {
347  using namespace boost::python;
348 
349  class_<PySimulator, boost::noncopyable>("Simulator")
350  .def(init<PyObject *>())
351  .def("initViewer", &PySimulator::initViewer)
352  .def("loadBody", &PySimulator::loadBody, return_internal_reference<>())
353  .def("createBody", &PySimulator::createBody, return_internal_reference<>())
354  .def("addCollisionCheckPair", &PySimulator::addCollisionCheckPair)
355  .def("loadProject", &PySimulator::loadProject)
356  .def("oneStep", &PySimulator::oneStep)
357  .def("simulate", (void(PySimulator::*)())&PySimulator::simulate)
358  .def("simulate", (void(PySimulator::*)(double))&PySimulator::simulate)
359  .def("realTime", &PySimulator::realTime)
360  .def("useBBox", &PySimulator::setUseBBox)
361  .def("windowSize", &PySimulator::setWindowSize)
362  .def("endless", &PySimulator::endless)
363  .def("start", &PySimulator::start)
364  .def("stop", &PySimulator::stop)
365  .def("wait", &PySimulator::wait)
366  .def("clear", &PySimulator::clear)
367  .def("reset", &PySimulator::reset)
368  .def("play", &PySimulator::play)
369  .def("pause", &PySimulator::pause)
370  .def("capture", &PySimulator::capture)
371  .def("logLength", &PySimulator::logLength)
372  .def("body", &PySimulator::getBody, return_internal_reference<>())
373  .def("bodies", &PySimulator::bodies)
374  .def("initialize", &PySimulator::initialize)
375  .add_property("timeStep",
377  .add_property("time", &PySimulator::currentTime)
378  .add_property("totalTime",
380  .add_property("showSensors",
382  .add_property("maxLogLength",
384  ;
385 
386  class_<PyBody, boost::noncopyable>("Body", no_init)
387  .def("calcForwardKinematics", &PyBody::calcForwardKinematics)
388  .def("rootLink", &PyBody::rootLink, return_internal_reference<>())
389  .def("link", &PyBody::link, return_internal_reference<>())
390  .def("links", &PyBody::links)
391  .def("joint", &PyBody::joint, return_internal_reference<>())
392  .def("joints", &PyBody::joints)
393  .def("calcTotalMass", &PyBody::calcTotalMass)
394  .def("calcCM", &PyBody::calcCM)
395  .def("totalMass", &PyBody::totalMass)
396  .def("numJoints", &PyBody::numJoints)
397  .def("numLinks", &PyBody::numLinks)
398  .def("creteInPort", &PyBody::createInPort)
399  .def("creteOutPort", &PyBody::createOutPort)
400  .add_property("name", &PyBody::getName, &PyBody::setName)
401  .add_property("p", &PyBody::getPosition, &PyBody::setPosition)
402  .add_property("R", &PyBody::getRotation, &PyBody::setRotation)
403  .add_property("q", &PyBody::getPosture, &PyBody::setPosture)
404  ;
405 
406  class_<PyLink, boost::noncopyable>("Link", no_init)
407  .def("addChildLink", &PyLink::addChildLink, return_internal_reference<>())
408  .def("addShapeFromFile", &PyLink::addShapeFromFile)
409  .def("addCube", &PyLink::addCube, return_internal_reference<>())
410  .def("parent", &PyLink::getParent, return_internal_reference<>())
411  .def("children", &PyLink::getChildren)
412  .def("showAxes", &PyLink::showAxes)
413  .def("shapes", &PyLink::shapes)
414  .def("highlight", &PyLink::highlight)
415  .def_readwrite("name", &PyLink::name)
416  .def_readwrite("m", &PyLink::m)
417  .def_readwrite("u", &PyLink::u)
418  .def_readwrite("Ir", &PyLink::Ir)
419  .def_readwrite("gearRatio", &PyLink::gearRatio)
420  .def_readwrite("dq", &PyLink::dq)
421  .def_readwrite("ddq", &PyLink::ddq)
422  .def_readwrite("isHighGainMode", &PyLink::isHighGainMode)
423  .add_property("jointId", &PyLink::getJointId, &PyLink::setJointId)
424  .add_property("q", &PyLink::getPosture, &PyLink::setPosture)
425  .add_property("p", &PyLink::getPosition, &PyLink::setPosition)
426  .add_property("R", &PyLink::getRotation, &PyLink::setRotation)
427  .add_property("b", &PyLink::getRelPosition, &PyLink::setRelPosition)
428  .add_property("Rs", &PyLink::getRelRotation, &PyLink::setRelRotation)
429  .add_property("a", &PyLink::getRotationAxis, &PyLink::setRotationAxis)
431  .add_property("c", &PyLink::getCoM, &PyLink::setCoM)
432  .add_property("I", &PyLink::getInertia, &PyLink::setInertia)
433  .add_property("v", &PyLink::getLinVel, &PyLink::setLinVel)
434  .add_property("w", &PyLink::getAngVel, &PyLink::setAngVel)
435  .add_property("jointType", &PyLink::getJointType, &PyLink::setJointType)
436  ;
437 
438  class_<PyShape, boost::noncopyable>("Shape", no_init)
439  .add_property("b", &PyShape::getRelPosition, &PyShape::setRelPosition)
440  .add_property("Rs", &PyShape::getRelRotation, &PyShape::setRelRotation)
441  .add_property("diffuse", &PyShape::getDiffuseColor, &PyShape::setDiffuseColor)
442  ;
443 }
void convertToAABB(hrp::BodyPtr i_body)
Definition: BVutil.cpp:14
void createInPort(const std::string &config)
Definition: BodyRTC.cpp:140
void enableRingBuffer(int len)
Definition: LogManager.h:157
void setRelPosition(PyObject *v)
Definition: PyShape.cpp:11
RTObject_impl * createComponent(const char *comp_args)
void setSize(int w, int h)
Definition: SDLUtil.cpp:369
void deleteComponent(RTObject_impl *comp)
void setWindowSize(int s)
double maxLogLength()
static hrp::Link * createLink()
Definition: PySimulator.cpp:31
double maxLogLen
Definition: PySimulator.h:49
double calcTotalMass()
void setRelRotation(PyObject *v)
Definition: PyShape.cpp:27
double timeStep(void) const
void setListener(PySimulator *i_sim)
Definition: PyBody.cpp:143
HRPMODEL_API OpenHRP::ModelLoader_var getModelLoader(CosNaming::NamingContext_var cxt)
void initViewer()
PyLink * rootLink()
Definition: PyBody.cpp:81
bool parse(const std::string &filename)
Definition: Project.cpp:32
int addBody(BodyPtr body)
void setName(const std::string &name)
void addBody(GLbody *i_body)
Definition: GLmodel.cpp:293
void runManager(bool no_block=false)
RTC::Manager * manager
Definition: PySimulator.h:47
PyObject * joints()
Definition: PyBody.cpp:105
PyLink * joint(int i)
Definition: PyBody.cpp:101
void setShowSensors(bool flag)
void shutdown()
void setCurrentTime(double tm)
void addCollisionCheckPair(PyBody *b1, PyBody *b2)
void setRootLink(Link *link)
hrp::BodyPtr createBody(const std::string &name, const ModelItem &mitem, ModelLoader_ptr modelloader, GLscene *scene, bool usebbox)
Definition: PySimulator.cpp:32
void initRTCmanager()
manager
sample RT component which has one data input port and one data output port
GLshape * createPyShape()
Definition: PyShape.cpp:67
CORBA::ORB_ptr getORB()
void loadShapeFromBodyInfo(GLbody *body, BodyInfo_var i_binfo, GLshape *(*shapeFactory)())
Definition: GLutil.cpp:181
png_uint_32 i
std::vector< std::string > outports
Definition: Project.h:66
void notifyChanged()
static Manager & instance()
std::string getName()
Definition: PyBody.cpp:115
boost::shared_ptr< Body > BodyPtr
void setView(double T[16])
Definition: SDLUtil.cpp:359
double totalMass() const
PyBody * getBody(std::string name)
BodyPtr body(int index)
PyBody * createBody(std::string name)
LogManager< SceneState > log
Definition: PySimulator.h:44
PyObject * getRelRotation()
Definition: PyShape.cpp:19
void endless(bool flag)
PyObject * bodies()
std::string url
Definition: Project.h:62
coil::Properties & getConfig()
PyObject * getPosition()
Definition: PyBody.cpp:55
PyObject * calcCM()
Definition: PyBody.cpp:120
PyObject * links()
Definition: PyBody.cpp:91
void setUseBBox(bool flag)
void convertToConvexHull(hrp::BodyPtr i_body)
Definition: BVutil.cpp:79
void capture(std::string)
BOOST_PYTHON_MODULE(hrpsysext)
static Manager * init(int argc, char **argv)
double totalTime()
Definition: Project.h:106
PyObject * getRelPosition()
Definition: PyShape.cpp:4
SDLwindow window
Definition: PySimulator.h:46
bool loadProject(std::string fname)
ThreeDView & view()
Definition: Project.h:119
Definition: PyBody.h:8
unsigned int logLength()
unsigned int length()
Definition: LogManager.h:158
void setTotalTime(double time)
bool activateManager()
void realTime(bool flag)
void setPosture(PyObject *v)
Definition: PyBody.cpp:45
std::vector< std::string > inports
Definition: Project.h:65
naming
void setMaxLogLength(double len)
void addCollisionCheckPair(BodyRTC *b1, BodyRTC *b2)
void setRotation(PyObject *v)
Definition: PyBody.cpp:40
unsigned int numJoints() const
PyLink * link(std::string name)
Definition: PyBody.cpp:86
std::map< std::string, JointItem > joint
Definition: Project.h:63
double T[16]
Definition: Project.h:98
bool useBBox
Definition: PySimulator.h:48
void setTimeStep(double dt)
void simulate()
void setPosition(PyObject *v)
Definition: PyBody.cpp:35
void setDiffuseColor(PyObject *v)
Definition: PyShape.cpp:57
int loadBodyFromBodyInfo(::World *world, const char *_name, BodyInfo_ptr bodyInfo)
void play()
Definition: LogManager.h:95
void calcForwardKinematics()
Definition: PyBody.cpp:76
double currentTime(void) const
unsigned int numLinks() const
double timeStep()
Definition: Project.h:105
void clear()
Definition: LogManager.h:27
PyObject * getDiffuseColor()
Definition: PyShape.cpp:50
unsigned int numBodies()
static void moduleInit(RTC::Manager *)
Definition: PyBody.cpp:153
PyObject * getRotation()
Definition: PyBody.cpp:60
boost::function2< hrp::BodyPtr, const std::string &, const ModelItem & > BodyFactory
Definition: ProjectUtil.h:9
bool showSensors()
PyObject * getPosture()
Definition: PyBody.cpp:65
PyBody * loadBody(std::string name, std::string url)
void createOutPort(const std::string &config)
Definition: BodyRTC.cpp:219


hrpsys
Author(s): AIST, Fumio Kanehiro
autogenerated on Thu May 6 2021 02:41:50