icub-basic-demos
world.cpp
1 /******************************************************************************
2  * *
3  * Copyright (C) 2020 Fondazione Istituto Italiano di Tecnologia (IIT) *
4  * All Rights Reserved. *
5  * *
6  ******************************************************************************/
7 
8 #include <cmath>
9 
10 #include <gazebo/common/Plugin.hh>
11 #include <gazebo/physics/Model.hh>
12 #include <gazebo/physics/Link.hh>
13 #include <gazebo/physics/Joint.hh>
14 #include <gazebo/common/Events.hh>
15 #include <ignition/math/Pose3.hh>
16 
17 #include <boost/bind.hpp>
18 
19 #include <yarp/os/Bottle.h>
20 #include <yarp/os/BufferedPort.h>
21 #include <yarp/os/LogStream.h>
22 
23 namespace gazebo {
24 
25 /******************************************************************************/
26 class ModelMover : public gazebo::ModelPlugin
27 {
28  gazebo::physics::ModelPtr model;
29  gazebo::event::ConnectionPtr renderer_connection;
30  yarp::os::BufferedPort<yarp::os::Bottle> port;
31  ignition::math::Vector3d starting_pos;
32 
33  /**************************************************************************/
34  void onWorldFrame()
35  {
36  if (auto* b = port.read(false))
37  {
38  if (b->size() >= 3)
39  {
40  if (model->GetJoint("fixed_to_ground"))
41  {
42  if (model->RemoveJoint("fixed_to_ground"))
43  {
44  yInfo() << "Removed fixed_to_ground joint";
45  }
46  }
47 
48  const auto x = starting_pos.X() + b->get(0).asFloat64();
49  const auto y = starting_pos.Y() + b->get(1).asFloat64();
50  const auto z = starting_pos.Z() + b->get(2).asFloat64();
51  ignition::math::Pose3d new_pose(x, y, z, 0.0, 0.0, 0.0);
52  yInfo() << "New pose:" << x << y << z;
53  model->SetWorldPose(new_pose);
54 
55  physics::LinkPtr child = model->GetLink("red-ball::root_link");
56  physics::LinkPtr parent = model->GetLink("world");
57  if (child || parent)
58  {
59  if (model->CreateJoint("fixed_to_ground", "fixed", parent, child))
60  {
61  yInfo() << "Added fixed_to_ground joint";
62  }
63  }
64  }
65  }
66  }
67 
68 public:
69  /**************************************************************************/
70  void Load(gazebo::physics::ModelPtr model, sdf::ElementPtr)
71  {
72  this->model = model;
73  auto model_sdf = model->GetSDF();
74  if( model_sdf->HasElement("pose") )
75  {
76  starting_pos = model_sdf->Get<ignition::math::Vector3d>("pose");
77  }
78  else
79  {
80  starting_pos = ignition::math::Vector3d(0.0, 0.0, 0.0);
81  }
82 
83  port.open("/" + model->GetName() + "/mover:i");
84  auto bind = boost::bind(&ModelMover::onWorldFrame, this);
85  renderer_connection = gazebo::event::Events::ConnectWorldUpdateBegin(bind);
86  }
87 
88  /**************************************************************************/
89  virtual ~ModelMover()
90  {
91  if (!port.isClosed())
92  {
93  port.close();
94  }
95  }
96 };
97 
98 }
99 
100 GZ_REGISTER_MODEL_PLUGIN(gazebo::ModelMover)