rbprmbuilder.impl.cc 131 KB
Newer Older
Steve Tonneau's avatar
Steve Tonneau committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Copyright (c) 2012 CNRS
// Author: Florent Lamiraux, Joseph Mirabel
//
// This file is part of hpp-manipulation-corba.
// hpp-manipulation-corba is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-manipulation-corba is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-manipulation-corba.  If not, see
// <http://www.gnu.org/licenses/>.

//#include <hpp/fcl/math/transform.h>
#include <hpp/util/debug.hh>
20
#include <hpp/corbaserver/rbprm/rbprmbuilder.hh>
Steve Tonneau's avatar
Steve Tonneau committed
21
22
#include "rbprmbuilder.impl.hh"
#include "hpp/rbprm/rbprm-device.hh"
Steve Tonneau's avatar
Steve Tonneau committed
23
#include "hpp/rbprm/rbprm-validation.hh"
24
#include "hpp/rbprm/interpolation/rbprm-path-interpolation.hh"
Steve Tonneau's avatar
Steve Tonneau committed
25
26
#include "hpp/rbprm/interpolation/limb-rrt.hh"
#include "hpp/rbprm/interpolation/com-rrt.hh"
27
#include "hpp/rbprm/interpolation/com-trajectory.hh"
28
#include "hpp/rbprm/interpolation/spline/effector-rrt.hh"
Steve Tonneau's avatar
Steve Tonneau committed
29
30
#include "hpp/rbprm/projection/projection.hh"
#include "hpp/rbprm/contact_generation/contact_generation.hh"
t steve's avatar
t steve committed
31
#include "hpp/rbprm/contact_generation/algorithm.hh"
Steve Tonneau's avatar
Steve Tonneau committed
32
#include "hpp/rbprm/stability/stability.hh"
Steve Tonneau's avatar
Steve Tonneau committed
33
#include "hpp/rbprm/sampling/sample-db.hh"
Steve Tonneau's avatar
Steve Tonneau committed
34
#include "hpp/model/urdf/util.hh"
35
#include "hpp/core/straight-path.hh"
36
#include "hpp/model/joint.hh"
37
38
39
#include "hpp/core/config-validations.hh"
#include "hpp/core/collision-validation-report.hh"
#include <hpp/core/subchain-path.hh>
40
41
#include <hpp/core/basic-configuration-shooter.hh>
#include <hpp/core/collision-validation.hh>
Steve Tonneau's avatar
Steve Tonneau committed
42
#include <fstream>
43
#include <hpp/rbprm/planner/dynamic-planner.hh>
44
#include <hpp/rbprm/planner/rbprm-steering-kinodynamic.hh>
45
#include <hpp/model/configuration.hh>
Steve Tonneau's avatar
Steve Tonneau committed
46
#include <algorithm>    // std::random_shuffle
47
#include <hpp/rbprm/interpolation/time-constraint-helper.hh>
t steve's avatar
t steve committed
48
49
#include "spline/bezier_curve.h"
#include "hpp/rbprm/interpolation/polynom-trajectory.hh"
50
#include <hpp/rbprm/planner/random-shortcut-dynamic.hh>
51
#include <hpp/rbprm/planner/oriented-path-optimizer.hh>
52
#include <hpp/rbprm/sampling/heuristic-tools.hh>
53
#include <hpp/rbprm/contact_generation/kinematics_constraints.hh>
54
55
56
57
#ifdef PROFILE
    #include "hpp/rbprm/rbprm-profiler.hh"
#endif

Steve Tonneau's avatar
Steve Tonneau committed
58
59


Steve Tonneau's avatar
Steve Tonneau committed
60
61
namespace hpp {
  namespace rbprm {
t steve's avatar
t steve committed
62
63

  typedef spline::bezier_curve<> bezier;
Steve Tonneau's avatar
Steve Tonneau committed
64
65
    namespace impl {

Steve Tonneau's avatar
Steve Tonneau committed
66
67
68
    RbprmBuilder::RbprmBuilder ()
    : POA_hpp::corbaserver::rbprm::RbprmBuilder()
    , romLoaded_(false)
Steve Tonneau's avatar
Steve Tonneau committed
69
    , fullBodyLoaded_(false)
Steve Tonneau's avatar
Steve Tonneau committed
70
    , bindShooter_()
Steve Tonneau's avatar
Steve Tonneau committed
71
    , analysisFactory_(0)
Steve Tonneau's avatar
Steve Tonneau committed
72
73
74
75
    {
        // NOTHING
    }

76
77
78
79
80
81
82
83
84
85
86
87

    hpp::floatSeq vectorToFloatseq (const hpp::core::vector_t& input)
    {
      CORBA::ULong size = (CORBA::ULong) input.size ();
      double* dofArray = hpp::floatSeq::allocbuf(size);
      hpp::floatSeq floats (size, size, dofArray, true);
      for (std::size_t i=0; i<size; ++i) {
        dofArray [i] = input [i];
      }
      return floats;
    }

Steve Tonneau's avatar
Steve Tonneau committed
88
89
90
91
92
93
94
95
96
    void RbprmBuilder::loadRobotRomModel(const char* robotName,
         const char* rootJointType,
         const char* packageName,
         const char* modelName,
         const char* urdfSuffix,
         const char* srdfSuffix) throw (hpp::Error)
    {
        try
        {
Steve Tonneau's avatar
Steve Tonneau committed
97
98
99
            hpp::model::DevicePtr_t romDevice = model::Device::create (robotName);
            romDevices_.insert(std::make_pair(robotName, romDevice));
            hpp::model::urdf::loadRobotModel (romDevice,
Steve Tonneau's avatar
Steve Tonneau committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
                    std::string (rootJointType),
                    std::string (packageName),
                    std::string (modelName),
                    std::string (urdfSuffix),
                    std::string (srdfSuffix));
        }
        catch (const std::exception& exc)
        {
            hppDout (error, exc.what ());
            throw hpp::Error (exc.what ());
        }
        romLoaded_ = true;
    }

    void RbprmBuilder::loadRobotCompleteModel(const char* robotName,
         const char* rootJointType,
         const char* packageName,
         const char* modelName,
         const char* urdfSuffix,
         const char* srdfSuffix) throw (hpp::Error)
    {
        if(!romLoaded_)
        {
            std::string err("Rom must be loaded before loading complete model") ;
Pierre Fernbach's avatar
Pierre Fernbach committed
124
            hppDout (error, err );
Steve Tonneau's avatar
Steve Tonneau committed
125
126
127
128
            throw hpp::Error(err.c_str());
        }
        try
        {
Steve Tonneau's avatar
Steve Tonneau committed
129
            hpp::model::RbPrmDevicePtr_t device = hpp::model::RbPrmDevice::create (robotName, romDevices_);
Steve Tonneau's avatar
Steve Tonneau committed
130
131
132
133
134
135
136
            hpp::model::urdf::loadRobotModel (device,
                    std::string (rootJointType),
                    std::string (packageName),
                    std::string (modelName),
                    std::string (urdfSuffix),
                    std::string (srdfSuffix));
            // Add device to the planner
137
138
            problemSolver()->robot (device);
            problemSolver()->robot ()->controlComputation
Steve Tonneau's avatar
Steve Tonneau committed
139
140
141
142
143
144
145
146
147
            (model::Device::JOINT_POSITION);
        }
        catch (const std::exception& exc)
        {
            hppDout (error, exc.what ());
            throw hpp::Error (exc.what ());
        }
    }

Steve Tonneau's avatar
Steve Tonneau committed
148
149
150
151
152
    void RbprmBuilder::loadFullBodyRobot(const char* robotName,
         const char* rootJointType,
         const char* packageName,
         const char* modelName,
         const char* urdfSuffix,
Steve Tonneau's avatar
Steve Tonneau committed
153
154
         const char* srdfSuffix,
         const char* selectedProblem) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
155
156
157
158
    {
        try
        {
            model::DevicePtr_t device = model::Device::create (robotName);
159
            hpp::model::urdf::loadRobotModel (device,
Steve Tonneau's avatar
Steve Tonneau committed
160
161
162
163
164
                    std::string (rootJointType),
                    std::string (packageName),
                    std::string (modelName),
                    std::string (urdfSuffix),
                    std::string (srdfSuffix));
Steve Tonneau's avatar
Steve Tonneau committed
165
            std::string name(selectedProblem);
Steve Tonneau's avatar
Steve Tonneau committed
166
167
168
            fullBodyLoaded_ = true;
            fullBodyMap_.map_[name] = rbprm::RbPrmFullBody::create(device);
            fullBodyMap_.selected_ = name;
169
170
171
172
173
174
175
176
177
178
179
180
181
182
            if(problemSolver()){
                if(problemSolver()->problem()){
                    try {
                      boost::any value = problemSolver()->problem()->get<boost::any> (std::string("friction"));
                      fullBody()->setFriction(boost::any_cast<double>(value));
                      hppDout(notice,"fullbody : mu define in python : "<<fullBody()->getFriction());
                    } catch (const std::exception& e) {
                      hppDout(notice,"fullbody : mu not defined, take : "<<fullBody()->getFriction()<<" as default.");
                    }
                }else{
                    hppDout(warning,"No instance of problem while initializing fullBody");
                }
            }else{
                hppDout(warning,"No instance of problemSolver while initializing fullBody");
183
            }
184
            problemSolver()->pathValidationType ("Discretized",0.05); // reset to avoid conflict with rbprm path
Steve Tonneau's avatar
Steve Tonneau committed
185
            problemSolver()->robot (fullBody()->device_);
186
187
            problemSolver()->resetProblem();
            problemSolver()->robot ()->controlComputation
188
            (model::Device::JOINT_POSITION);
Pierre Fernbach's avatar
Pierre Fernbach committed
189
            refPose_ = fullBody()->device_->currentConfiguration();
Steve Tonneau's avatar
Steve Tonneau committed
190
191
192
        }
        catch (const std::exception& exc)
        {
Steve Tonneau's avatar
Steve Tonneau committed
193
            fullBodyLoaded_ = false;
Steve Tonneau's avatar
Steve Tonneau committed
194
195
196
            hppDout (error, exc.what ());
            throw hpp::Error (exc.what ());
        }
Steve Tonneau's avatar
Steve Tonneau committed
197
        analysisFactory_ = new sampling::AnalysisFactory(fullBody());
Steve Tonneau's avatar
Steve Tonneau committed
198
199
    }

200
201
202
203
    void RbprmBuilder::loadFullBodyRobotFromExistingRobot() throw (hpp::Error)
    {
        try
        {
Steve Tonneau's avatar
Steve Tonneau committed
204
            fullBody() = rbprm::RbPrmFullBody::create(problemSolver()->problem()->robot());
205
            problemSolver()->pathValidationType ("Discretized",0.05); // reset to avoid conflict with rbprm path
Steve Tonneau's avatar
Steve Tonneau committed
206
            problemSolver()->robot (fullBody()->device_);
207
208
            problemSolver()->resetProblem();
            problemSolver()->robot ()->controlComputation
209
210
211
212
213
214
215
216
            (model::Device::JOINT_POSITION);
        }
        catch (const std::exception& exc)
        {
            hppDout (error, exc.what ());
            throw hpp::Error (exc.what ());
        }
        fullBodyLoaded_ = true;
Steve Tonneau's avatar
Steve Tonneau committed
217
        analysisFactory_ = new sampling::AnalysisFactory(fullBody());
218
219
    }

Steve Tonneau's avatar
Steve Tonneau committed
220
221
222
223
    hpp::floatSeq* RbprmBuilder::getSampleConfig(const char* limb, unsigned short sampleId) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
Steve Tonneau's avatar
Steve Tonneau committed
224
        const T_Limb& limbs = fullBody()->GetLimbs();
Steve Tonneau's avatar
Steve Tonneau committed
225
226
227
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
Steve Tonneau's avatar
Steve Tonneau committed
228
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody()->device_->name());
Steve Tonneau's avatar
Steve Tonneau committed
229
230
231
232
            throw Error (err.c_str());
        }
        const RbPrmLimbPtr_t& limbPtr = lit->second;
        hpp::floatSeq *dofArray;
Steve Tonneau's avatar
Steve Tonneau committed
233
        Eigen::VectorXd config = fullBody()->device_->currentConfiguration ();
Steve Tonneau's avatar
Steve Tonneau committed
234
235
236
237
238
239
        if(sampleId > limbPtr->sampleContainer_.samples_.size())
        {
            std::string err("Limb " + std::string(limb) + "does not have samples.");
            throw Error (err.c_str());
        }
        const sampling::Sample& sample = limbPtr->sampleContainer_.samples_[sampleId];
Steve Tonneau's avatar
Steve Tonneau committed
240
        config.segment(sample.startRank_, sample.length_) = sample.configuration_;
Steve Tonneau's avatar
Steve Tonneau committed
241
242
243
244
245
246
247
        dofArray = new hpp::floatSeq();
        dofArray->length(_CORBA_ULong(config.rows()));
        for(std::size_t i=0; i< _CORBA_ULong(config.rows()); i++)
          (*dofArray)[(_CORBA_ULong)i] = config [i];
        return dofArray;
    }

Steve Tonneau's avatar
Steve Tonneau committed
248
249
250
251
252

    hpp::floatSeq* RbprmBuilder::getSamplePosition(const char* limb, unsigned short sampleId) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
Steve Tonneau's avatar
Steve Tonneau committed
253
        const T_Limb& limbs = fullBody()->GetLimbs();
Steve Tonneau's avatar
Steve Tonneau committed
254
255
256
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
Steve Tonneau's avatar
Steve Tonneau committed
257
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody()->device_->name());
Steve Tonneau's avatar
Steve Tonneau committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
            throw Error (err.c_str());
        }
        const RbPrmLimbPtr_t& limbPtr = lit->second;
        hpp::floatSeq *dofArray;
        if(sampleId > limbPtr->sampleContainer_.samples_.size())
        {
            std::string err("Limb " + std::string(limb) + "does not have samples.");
            throw Error (err.c_str());
        }
        const sampling::Sample& sample = limbPtr->sampleContainer_.samples_[sampleId];
        const fcl::Vec3f& position = sample.effectorPosition_;
        dofArray = new hpp::floatSeq();
        dofArray->length(_CORBA_ULong(3));
        for(std::size_t i=0; i< 3; i++)
          (*dofArray)[(_CORBA_ULong)i] = position [i];
        return dofArray;
    }

Steve Tonneau's avatar
Steve Tonneau committed
276

277
278
279
280
281
    typedef Eigen::Matrix <value_type, 4, 3, Eigen::RowMajor> Matrix43;
    typedef Eigen::Matrix <value_type, 4, 3, Eigen::RowMajor> Rotation;
    typedef Eigen::Ref<Matrix43> Ref_matrix43;

    std::vector<fcl::Vec3f> computeRectangleContact(const rbprm::RbPrmFullBodyPtr_t device,
282
                                                    const rbprm::State& state, const std::vector<std::string> limbSelected = std::vector<std::string>())
283
    {
284
285
        device->device_->currentConfiguration(state.configuration_);
        device->device_->computeForwardKinematics();
286
287
288
289
290
291
292
293
        std::vector<fcl::Vec3f> res;
        const rbprm::T_Limb& limbs = device->GetLimbs();
        rbprm::RbPrmLimbPtr_t limb;
        Matrix43 p; Eigen::Matrix3d R;
        for(std::map<std::string, fcl::Vec3f>::const_iterator cit = state.contactPositions_.begin();
            cit != state.contactPositions_.end(); ++cit)
        {
            const std::string& name = cit->first;
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
            if(limbSelected.empty() || std::find(limbSelected.begin(), limbSelected.end(), name) != limbSelected.end())
            {
                const fcl::Vec3f& position = cit->second;
                limb = limbs.at(name);
                const fcl::Vec3f& normal = state.contactNormals_.at(name);
                const fcl::Vec3f z = limb->effector_->currentTransformation().getRotation() * limb->normal_;
                const fcl::Matrix3f alignRotation = tools::GetRotationMatrix(z,normal);
                const fcl::Matrix3f rotation = alignRotation * limb->effector_->currentTransformation().getRotation();
                const fcl::Vec3f offset = rotation * limb->offset_;
                const double& lx = limb->x_, ly = limb->y_;
                p << lx,  ly, 0,
                     lx, -ly, 0,
                    -lx, -ly, 0,
                    -lx,  ly, 0;
                if(limb->contactType_ == _3_DOF)
309
                {
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
                    //create rotation matrix from normal
                    fcl::Vec3f z_fcl = state.contactNormals_.at(name);
                    Eigen::Vector3d z,x,y;
                    for(int i =0; i<3; ++i) z[i] = z_fcl[i];
                    x = z.cross(Eigen::Vector3d(0,-1,0));
                    if(x.norm() < 10e-6)
                    {
                        y = z.cross(fcl::Vec3f(1,0,0));
                        y.normalize();
                        x = y.cross(z);
                    }
                    else
                    {
                        x.normalize();
                        y = z.cross(x);
                    }
                    R.block<3,1>(0,0) = x;
                    R.block<3,1>(0,1) = y;
                    R.block<3,1>(0,2) = z;
                    /*for(std::size_t i =0; i<4; ++i)
                    {
                        res.push_back(position + (R*(p.row(i).transpose())) + offset);
                        res.push_back(state.contactNormals_.at(name));
                    }*/
                    res.push_back(position + (R*(offset)));
                    res.push_back(state.contactNormals_.at(name));
336
337
338
                }
                else
                {
339
340
341
342
343
344
345
346
347
348
349
                    const fcl::Matrix3f& fclRotation = state.contactRotation_.at(name);
                    for(int i =0; i< 3; ++i)
                        for(int j =0; j<3;++j)
                            R(i,j) = fclRotation(i,j);
                    fcl::Vec3f z_axis(0,0,1);
                    fcl::Matrix3f rotationLocal = tools::GetRotationMatrix(z_axis, limb->normal_);
                    for(std::size_t i =0; i<4; ++i)
                    {
                        res.push_back(position + (R*(rotationLocal*(p.row(i).transpose() + limb->offset_))));
                        res.push_back(state.contactNormals_.at(name));
                    }
350
                }
351
352
353
354
355
            }
        }
        return res;
    }

356
    std::vector<fcl::Vec3f> computeRectangleContactLocalTr(const rbprm::RbPrmFullBodyPtr_t device,
357
                                                    const rbprm::State& state,
Steve Tonneau's avatar
Steve Tonneau committed
358
                                                    const std::string& limbName)
359
    {
360
361
        device->device_->currentConfiguration(state.configuration_);
        device->device_->computeForwardKinematics();
362
363
364
        std::vector<fcl::Vec3f> res;
        const rbprm::T_Limb& limbs = device->GetLimbs();
        rbprm::RbPrmLimbPtr_t limb;
Steve Tonneau's avatar
Steve Tonneau committed
365
        Matrix43 p; Eigen::Matrix3d R = Eigen::Matrix3d::Identity(); Eigen::Matrix3d cFrame = Eigen::Matrix3d::Identity();
366
367
368
369
370
371
372
373
        for(std::map<std::string, fcl::Vec3f>::const_iterator cit = state.contactPositions_.begin();
            cit != state.contactPositions_.end(); ++cit)
        {
            const std::string& name = cit->first;
            if(limbName == name)
            {
                const fcl::Vec3f& position = cit->second;
                limb = limbs.at(name);
374
375
376
377
378
                const fcl::Vec3f& normal = state.contactNormals_.at(name);
                const fcl::Vec3f z = limb->effector_->currentTransformation().getRotation() * limb->normal_;
                const fcl::Matrix3f alignRotation = tools::GetRotationMatrix(z,normal);
                const fcl::Matrix3f rotation = alignRotation * limb->effector_->currentTransformation().getRotation();
                const fcl::Vec3f offset = rotation * limb->offset_;
379
380
381
382
383
384
385
386
387
                const double& lx = limb->x_, ly = limb->y_;
                p << lx,  ly, 0,
                     lx, -ly, 0,
                    -lx, -ly, 0,
                    -lx,  ly, 0;
                if(limb->contactType_ == _3_DOF)
                {
                    //create rotation matrix from normal
                    Eigen::Vector3d z,x,y;
388
                    for(int i =0; i<3; ++i) z[i] = normal[i];
389
390
391
392
393
394
395
396
397
398
399
400
                    x = z.cross(Eigen::Vector3d(0,-1,0));
                    if(x.norm() < 10e-6)
                    {
                        y = z.cross(fcl::Vec3f(1,0,0));
                        y.normalize();
                        x = y.cross(z);
                    }
                    else
                    {
                        x.normalize();
                        y = z.cross(x);
                    }
Steve Tonneau's avatar
Steve Tonneau committed
401
402
403
                    cFrame.block<3,1>(0,0) = x;
                    cFrame.block<3,1>(0,1) = y;
                    cFrame.block<3,1>(0,2) = z;
404
                }
405
406
407
408
                fcl::Transform3f roWorld, roEffector;
                roWorld.setRotation(state.contactRotation_.at(name));
                roWorld.setTranslation(position);
                roEffector = roWorld; roEffector.inverse();
409
410
                fcl::Vec3f z_axis(0,0,1);
                fcl::Matrix3f rotationLocal = tools::GetRotationMatrix(z_axis, limb->normal_);
Steve Tonneau's avatar
Steve Tonneau committed
411
                if(limb->contactType_ == _3_DOF)
412
                {
Steve Tonneau's avatar
Steve Tonneau committed
413
414
415
416
417
418
419
                    fcl::Vec3f pworld = position +  offset;
                    res.push_back((roEffector * pworld).getTranslation());
                    res.push_back(roEffector.getRotation() * state.contactNormals_.at(name));
                }
                else
                {
                    for(std::size_t i =0; i<4; ++i)
420
                    {
Steve Tonneau's avatar
Steve Tonneau committed
421
422
423
424
425
426
427
428
429
                        /*if(limb->contactType_ == _3_DOF)
                        {
                            fcl::Vec3f pworld = position + (cFrame*(p.row(i).transpose())) + offset;
                            res.push_back((roEffector * pworld).getTranslation());
                            res.push_back(roEffector.getRotation() * state.contactNormals_.at(name));
                        }
                        else*/
                        {
                            res.push_back(rotationLocal*(p.row(i).transpose()) + limb->offset_);
t steve's avatar
t steve committed
430
431
                            //res.push_back(roEffector.getRotation() * state.contactNormals_.at(name));
                           res.push_back( limb->normal_);
Steve Tonneau's avatar
Steve Tonneau committed
432
                        }
433
434
435
436
437
438
439
440
                    }
                }
                return res;
            }
        }
        return res;
    }

441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
    model::Configuration_t dofArrayToConfig (const std::size_t& deviceDim,
      const hpp::floatSeq& dofArray)
    {
        std::size_t configDim = (std::size_t)dofArray.length();
        // Fill dof vector with dof array.
        model::Configuration_t config; config.resize (configDim);
        for (std::size_t iDof = 0; iDof < configDim; iDof++) {
            config [iDof] = (double)dofArray[(_CORBA_ULong)iDof];
        }
        // fill the vector by zero
        hppDout (info, "config dimension: " <<configDim
           <<",  deviceDim "<<deviceDim);
        if(configDim != deviceDim){
            throw hpp::Error ("dofVector Does not match");
        }
        return config;
    }

    model::Configuration_t dofArrayToConfig (const model::DevicePtr_t& robot,
      const hpp::floatSeq& dofArray)
    {
        return dofArrayToConfig(robot->configSize(), dofArray);
    }

    T_Configuration doubleDofArrayToConfig (const std::size_t& deviceDim,
      const hpp::floatSeqSeq& doubleDofArray)
    {
        std::size_t configsDim = (std::size_t)doubleDofArray.length();
        T_Configuration res;
        for (_CORBA_ULong iConfig = 0; iConfig < configsDim; iConfig++)
        {
            res.push_back(dofArrayToConfig(deviceDim, doubleDofArray[iConfig]));
        }
        return res;
    }

    T_Configuration doubleDofArrayToConfig (const model::DevicePtr_t& robot,
      const hpp::floatSeqSeq& doubleDofArray)
    {
        return doubleDofArrayToConfig(robot->configSize(), doubleDofArray);
    }

    hpp::floatSeqSeq* RbprmBuilder::getEffectorPosition(const char* lb, const hpp::floatSeq& configuration) throw (hpp::Error)
    {
        try
        {
            const std::string limbName(lb);
Steve Tonneau's avatar
Steve Tonneau committed
488
489
490
491
            const RbPrmLimbPtr_t limb = fullBody()->GetLimbs().at(limbName);
            model::Configuration_t config = dofArrayToConfig (fullBody()->device_, configuration);
            fullBody()->device_->currentConfiguration(config);
            fullBody()->device_->computeForwardKinematics();
492
493
494
495
            State state;
            state.configuration_ = config;
            state.contacts_[limbName] = true;
            const fcl::Vec3f position = limb->effector_->currentTransformation().getTranslation();
496
            state.contactPositions_[limbName] = position;
497
498
            state.contactNormals_[limbName] = fcl::Vec3f(0,0,1);
            state.contactRotation_[limbName] = limb->effector_->currentTransformation().getRotation();
Pierre Fernbach's avatar
Pierre Fernbach committed
499
            std::vector<fcl::Vec3f> poss = (computeRectangleContact(fullBody(), state));
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524

            hpp::floatSeqSeq *res;
            res = new hpp::floatSeqSeq ();
            res->length ((_CORBA_ULong)poss.size ());
            for(std::size_t i = 0; i < poss.size(); ++i)
            {
                _CORBA_ULong size = (_CORBA_ULong) (3);
                double* dofArray = hpp::floatSeq::allocbuf(size);
                hpp::floatSeq floats (size, size, dofArray, true);
                //convert the config in dofseq
                for(std::size_t j=0; j<3; j++)
                {
                    dofArray[j] = poss[i][j];
                }
                (*res) [(_CORBA_ULong)i] = floats;
            }
            return res;
        }
        catch (const std::exception& exc)
        {
            throw hpp::Error (exc.what ());
        }
    }


Steve Tonneau's avatar
Steve Tonneau committed
525
526
    CORBA::UShort RbprmBuilder::getNumSamples(const char* limb) throw (hpp::Error)
    {
Steve Tonneau's avatar
Steve Tonneau committed
527
        const T_Limb& limbs = fullBody()->GetLimbs();
Steve Tonneau's avatar
Steve Tonneau committed
528
529
530
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
Steve Tonneau's avatar
Steve Tonneau committed
531
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody()->device_->name());
Steve Tonneau's avatar
Steve Tonneau committed
532
533
            throw Error (err.c_str());
        }
534
        return (CORBA::UShort)(lit->second->sampleContainer_.samples_.size());
Steve Tonneau's avatar
Steve Tonneau committed
535
536
    }

537
538
    floatSeq *RbprmBuilder::getOctreeNodeIds(const char* limb) throw (hpp::Error)
    {
Steve Tonneau's avatar
Steve Tonneau committed
539
        const T_Limb& limbs = fullBody()->GetLimbs();
540
541
542
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
Steve Tonneau's avatar
Steve Tonneau committed
543
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody()->device_->name());
544
545
546
547
            throw Error (err.c_str());
        }
        const sampling::T_VoxelSampleId& ids =  lit->second->sampleContainer_.samplesInVoxels_;
        hpp::floatSeq* dofArray = new hpp::floatSeq();
548
        dofArray->length((_CORBA_ULong)ids.size());
549
550
551
        sampling::T_VoxelSampleId::const_iterator it = ids.begin();
        for(std::size_t i=0; i< _CORBA_ULong(ids.size()); ++i, ++it)
        {
552
          (*dofArray)[(_CORBA_ULong)i] = (double)it->first;
553
554
555
556
        }
        return dofArray;
    }

Steve Tonneau's avatar
Steve Tonneau committed
557
558
    double RbprmBuilder::getSampleValue(const char* limb, const char* valueName, unsigned short sampleId) throw (hpp::Error)
    {
Steve Tonneau's avatar
Steve Tonneau committed
559
        const T_Limb& limbs = fullBody()->GetLimbs();
Steve Tonneau's avatar
Steve Tonneau committed
560
561
562
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
Steve Tonneau's avatar
Steve Tonneau committed
563
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody()->device_->name());
Steve Tonneau's avatar
Steve Tonneau committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
            throw Error (err.c_str());
        }
        const sampling::SampleDB& database = lit->second->sampleContainer_;
        if (database.samples_.size() <= sampleId)
        {
            std::string err("unexisting sample id " + sampleId);
            throw Error (err.c_str());
        }
        sampling::T_Values::const_iterator cit = database.values_.find(std::string(valueName));
        if(cit == database.values_.end())
        {
            std::string err("value not existing in database " + std::string(valueName));
            throw Error (err.c_str());
        }
        return cit->second[sampleId];
    }

581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598

    double RbprmBuilder::getEffectorDistance(unsigned short state1, unsigned short state2) throw (hpp::Error)
    {
        try
        {
            std::size_t s1((std::size_t)state1), s2((std::size_t)state2);
            if(lastStatesComputed_.size () < s1 || lastStatesComputed_.size () < s2 )
            {
                throw std::runtime_error ("did not find a states at indicated indices: " + std::string(""+s1) + ", " + std::string(""+s2));
            }
            return rbprm::effectorDistance(lastStatesComputed_[s1], lastStatesComputed_[s2]);
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }

Steve Tonneau's avatar
Steve Tonneau committed
599
600
601
602
    std::vector<std::string> stringConversion(const hpp::Names_t& dofArray)
    {
        std::vector<std::string> res;
        std::size_t dim = (std::size_t)dofArray.length();
603
        for (_CORBA_ULong iDof = 0; iDof < dim; iDof++)
Steve Tonneau's avatar
Steve Tonneau committed
604
605
606
607
608
        {
            res.push_back(std::string(dofArray[iDof]));
        }
        return res;
    }
Steve Tonneau's avatar
Steve Tonneau committed
609

Steve Tonneau's avatar
Steve Tonneau committed
610
611
612
613
    std::vector<double> doubleConversion(const hpp::floatSeq& dofArray)
    {
        std::vector<double> res;
        std::size_t dim = (std::size_t)dofArray.length();
614
        for (_CORBA_ULong iDof = 0; iDof < dim; iDof++)
Steve Tonneau's avatar
Steve Tonneau committed
615
616
617
618
619
620
        {
            res.push_back(dofArray[iDof]);
        }
        return res;
    }

621
    void RbprmBuilder::setStaticStability(const bool staticStability) throw (hpp::Error){
622
623
      if(!fullBodyLoaded_)
        throw Error ("No full body robot was loaded");
Pierre Fernbach's avatar
Pierre Fernbach committed
624
      fullBody()->staticStability(staticStability);
625
626
    }

627
628
629
    void RbprmBuilder::setReferenceConfig(const hpp::floatSeq& referenceConfig) throw (hpp::Error){
      if(!fullBodyLoaded_)
        throw Error ("No full body robot was loaded");
630
631
      Configuration_t config(dofArrayToConfig (fullBody()->device_, referenceConfig));
      refPose_ = config;
Pierre Fernbach's avatar
Pierre Fernbach committed
632
      fullBody()->referenceConfig(config);
633
634
635
    }


Steve Tonneau's avatar
Steve Tonneau committed
636
637
638
639
640
641

    void RbprmBuilder::setFilter(const hpp::Names_t& roms) throw (hpp::Error)
    {
        bindShooter_.romFilter_ = stringConversion(roms);
    }

642

643
    void RbprmBuilder::setAffordanceFilter(const char* romName, const hpp::Names_t& affordances) throw (hpp::Error)
644
    {
645
646
647
648
        std::string name (romName);
				std::vector<std::string> affNames = stringConversion(affordances);
        bindShooter_.affFilter_.erase(name);
        bindShooter_.affFilter_.insert(std::make_pair(name,affNames));
649
650
    }

Steve Tonneau's avatar
Steve Tonneau committed
651
652
653
654
655
656
657
658
659
660
661
    void RbprmBuilder::boundSO3(const hpp::floatSeq& limitszyx) throw (hpp::Error)
    {
        std::vector<double> limits = doubleConversion(limitszyx);
        if(limits.size() !=6)
        {
            throw Error ("Can not bound SO3, array of 6 double required");
        }
        bindShooter_.so3Bounds_ = limits;

    }

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
    rbprm::T_Limb GetFreeLimbs(const RbPrmFullBodyPtr_t fullBody, const hpp::rbprm::State &from, const hpp::rbprm::State &to)
    {
        rbprm::T_Limb res;
        std::vector<std::string> fixedContacts = to.fixedContacts(from);
        std::vector<std::string> variations = to.contactVariations(from);
        for(rbprm::CIT_Limb cit = fullBody->GetLimbs().begin();
            cit != fullBody->GetLimbs().end(); ++cit)
        {
            if(std::find(fixedContacts.begin(), fixedContacts.end(), cit->first) == fixedContacts.end())
            {
                if(std::find(variations.begin(), variations.end(), cit->first) != variations.end())
                {
                    res.insert(*cit);
                }
            }
        }
        return res;
    }

t steve's avatar
t steve committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
    rbprm::T_Limb GetFreeLimbs(const RbPrmFullBodyPtr_t fullBody, const hpp::rbprm::State &state)
    {
        rbprm::T_Limb res;
        std::vector<std::string> fixedContacts = state.fixedContacts(state);
        for(rbprm::CIT_Limb cit = fullBody->GetLimbs().begin();
            cit != fullBody->GetLimbs().end(); ++cit)
        {
            if(std::find(fixedContacts.begin(), fixedContacts.end(), cit->first) == fixedContacts.end())
            {
                    res.insert(*cit);
            }
        }
        return res;
    }

696
    double RbprmBuilder::projectStateToCOMEigen(unsigned short stateId, const model::Configuration_t& com_target, unsigned short maxNumeSamples) throw (hpp::Error)
697
698
699
700
701
702
703
    {
        try
        {
            if(lastStatesComputed_.size() <= stateId)
            {
                throw std::runtime_error ("Unexisting state " + std::string(""+(stateId)));
            }
704
            State s = lastStatesComputed_[stateId];
Steve Tonneau's avatar
Steve Tonneau committed
705
706
//            /hpp::model::Configuration_t c = rbprm::interpolation::projectOnCom(fullBody(), problemSolver()->problem(),s,com_target,succes);
            rbprm::projection::ProjectionReport rep = rbprm::projection::projectToComPosition(fullBody(),com_target,s);
707
708
            hpp::model::Configuration_t& c = rep.result_.configuration_;
            ValidationReportPtr_t rport (ValidationReportPtr_t(new CollisionValidationReport));
Steve Tonneau's avatar
Steve Tonneau committed
709
            CollisionValidationPtr_t val = fullBody()->GetCollisionValidation();
710
711
712
713
714
715
716
717
718
719
720
            if(!rep.success_){
                hppDout(notice,"Projection failed for state "<<stateId<<" , config = "<<model::displayConfig(c));
            }
            if(rep.success_){
                hppDout(notice,"Projection successfull for state "<<stateId<<" without collision check.");
                rep.success_ =  rep.success_ &&  val->validate(rep.result_.configuration_,rport);
                if(!rep.success_){
                    hppDout(notice,"Projection failed after collision check for state "<<stateId<<" , config = "<<model::displayConfig(c));
                    hppDout(notice,"report : "<<*rport);
                }
            }
721
722
            if (! rep.success_ && maxNumeSamples>0)
            {
723
                hppDout(notice,"Projection for state "<<stateId<<" failed, try to randomly sample other initial point : ");
724
                Configuration_t head = s.configuration_.head<7>();
Steve Tonneau's avatar
Steve Tonneau committed
725
                BasicConfigurationShooterPtr_t shooter = BasicConfigurationShooter::create(fullBody()->device_);
726
727
728
729
                for(std::size_t i =0; !rep.success_ && i< maxNumeSamples; ++i)
                {
                    s.configuration_ = *shooter->shoot();
                    s.configuration_.head<7>() = head;
Steve Tonneau's avatar
Steve Tonneau committed
730
731
                    //c = rbprm::interpolation::projectOnCom(fullBody(), problemSolver()->problem(),s,com_target,succes);
                    rep = rbprm::projection::projectToComPosition(fullBody(),com_target,s);
732
733
734
735
736
737
738
739
740
741
742
                    if(!rep.success_){
                        hppDout(notice,"Projection failed on iter "<<i<<" for state "<<stateId<<" , config = "<<model::displayConfig(c));
                    }
                    if(rep.success_){
                        hppDout(notice,"Projection successfull on iter "<<i<<" for state "<<stateId<<" without collision check.");
                        rep.success_ =  rep.success_ &&  val->validate(rep.result_.configuration_,rport);
                        if(!rep.success_){
                            hppDout(notice,"Projection failed on iter "<<i<<" after collision check for state "<<stateId<<" , config = "<<model::displayConfig(c));
                            hppDout(notice,"report : "<<*rport);
                        }
                    }
743
744
745
746
                    c = rep.result_.configuration_;
                }
            }
            if(rep.success_)
747
            {
t steve's avatar
t steve committed
748
                hpp::model::Configuration_t trySave = c;
749
                rbprm::T_Limb fLimbs = GetFreeLimbs(fullBody(), s);
t steve's avatar
t steve committed
750
751
752
753
754
                for(rbprm::CIT_Limb cit = fLimbs.begin(); cit != fLimbs.end() && rep.success_; ++cit)
                {
                    // get part of reference configuration that concerns the limb.
                    RbPrmLimbPtr_t limb = cit->second;
                    const sampling::Sample& sample = limb->sampleContainer_.samples_[0];
Pierre Fernbach's avatar
Pierre Fernbach committed
755
                    s.configuration_.segment(sample.startRank_, sample.length_) = refPose_.segment(sample.startRank_, sample.length_) ;
t steve's avatar
t steve committed
756
757
                    rep = rbprm::projection::projectToComPosition(fullBody(),com_target,s);
                    rep.success_ = rep.success_ && val->validate(rep.result_.configuration_,rport);
758
759
760
761
762
763
764
765
766
                    if(rep.success_)
                    {
                        std::cout << "yay " << std::endl;
                        trySave = rep.result_.configuration_;
                    }
                    else
                    {
                        std::cout << "ow" << std::endl;
                    }
t steve's avatar
t steve committed
767
                }
768
769
                lastStatesComputed_[stateId].configuration_ = trySave;
                lastStatesComputedTime_[stateId].second.configuration_ = trySave;
770
771
772
773
774
775
                return 1.;
            }
            return 0;
        }
        catch(std::runtime_error& e)
        {
776
            std::cout << "ERREUR " << std::endl;
777
778
779
780
            throw Error(e.what());
        }
    }

Steve Tonneau's avatar
Steve Tonneau committed
781
782
    CORBA::Short RbprmBuilder::createState(const hpp::floatSeq& configuration, const hpp::Names_t& contactLimbs) throw (hpp::Error)
    {
Steve Tonneau's avatar
Steve Tonneau committed
783
784
785
        model::Configuration_t config = dofArrayToConfig (fullBody()->device_, configuration);
        fullBody()->device_->currentConfiguration(config);
        fullBody()->device_->computeForwardKinematics();
Steve Tonneau's avatar
Steve Tonneau committed
786
787
788
789
790
        State state;
        state.configuration_ = config;
        std::vector<std::string> names = stringConversion(contactLimbs);
        for(std::vector<std::string>::const_iterator cit = names.begin(); cit != names.end(); ++cit)
        {
Steve Tonneau's avatar
Steve Tonneau committed
791
            rbprm::RbPrmLimbPtr_t limb = fullBody()->GetLimbs().at(*cit);
Steve Tonneau's avatar
Steve Tonneau committed
792
793
794
795
796
797
798
799
800
            const std::string& limbName = *cit;
            state.contacts_[limbName] = true;
            const fcl::Vec3f position = limb->effector_->currentTransformation().getTranslation();
            state.contactPositions_[limbName] = position;
            state.contactNormals_[limbName] = limb->effector_->currentTransformation().getRotation() * limb->normal_;
            state.contactRotation_[limbName] = limb->effector_->currentTransformation().getRotation();

        }
        lastStatesComputed_.push_back(state);
Steve Tonneau's avatar
Steve Tonneau committed
801
        lastStatesComputedTime_.push_back(std::make_pair(-1., state));
Steve Tonneau's avatar
Steve Tonneau committed
802
803
804
        return lastStatesComputed_.size()-1;
    }

805
    double RbprmBuilder::projectStateToCOM(unsigned short stateId, const hpp::floatSeq& com, unsigned short max_num_sample) throw (hpp::Error)
806
807
    {        
        model::Configuration_t com_target = dofArrayToConfig (3, com);
808
        return projectStateToCOMEigen(stateId, com_target, max_num_sample);
809
810
    }

811
    hpp::floatSeq* RbprmBuilder::generateContacts(const hpp::floatSeq& configuration,
812
      const hpp::floatSeq& direction,const hpp::floatSeq& acceleration, const double robustnessThreshold ) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
813
814
815
816
817
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
818
            fcl::Vec3f dir,acc;
Steve Tonneau's avatar
Steve Tonneau committed
819
820
            for(std::size_t i =0; i <3; ++i)
            {
821
                dir[i] = direction[(_CORBA_ULong)i];
822
                acc[i] = acceleration[(_CORBA_ULong)i];
Steve Tonneau's avatar
Steve Tonneau committed
823
            }
824
825
826
            dir = dir.normalize();

            const affMap_t &affMap = problemSolver()->map<std::vector<boost::shared_ptr<model::CollisionObject> > > ();
827
		        if (affMap.empty ()) {
828
829
    	        throw hpp::Error ("No affordances found. Unable to generate Contacts.");
      		  }
Steve Tonneau's avatar
Steve Tonneau committed
830
831
            model::Configuration_t config = dofArrayToConfig (fullBody()->device_, configuration);
            rbprm::State state = rbprm::contact::ComputeContacts(fullBody(),config,
Pierre Fernbach's avatar
Pierre Fernbach committed
832
              affMap, bindShooter_.affFilter_, dir,robustnessThreshold,acc);
Steve Tonneau's avatar
Steve Tonneau committed
833
            hpp::floatSeq* dofArray = new hpp::floatSeq();
Steve Tonneau's avatar
stair    
Steve Tonneau committed
834
            dofArray->length(_CORBA_ULong(state.configuration_.rows()));
Steve Tonneau's avatar
Steve Tonneau committed
835
836
837
838
839
840
841
842
            for(std::size_t i=0; i< _CORBA_ULong(config.rows()); i++)
              (*dofArray)[(_CORBA_ULong)i] = state.configuration_ [i];
            return dofArray;
        } catch (const std::exception& exc) {
        throw hpp::Error (exc.what ());
        }
    }

843
844
845
846
847
848
849
850
    hpp::floatSeq* RbprmBuilder::generateGroundContact(const hpp::Names_t& contactLimbs) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
            fcl::Vec3f z(0,0,1);
            ValidationReportPtr_t report = ValidationReportPtr_t(new CollisionValidationReport);
Steve Tonneau's avatar
Steve Tonneau committed
851
            core::BasicConfigurationShooterPtr_t  shooter = core::BasicConfigurationShooter::create(fullBody()->device_);
852
853
            for(int i =0; i< 1000; ++i)
            {
Steve Tonneau's avatar
Steve Tonneau committed
854
                core::DevicePtr_t device = fullBody()->device_->clone();
855
                std::vector<std::string> names = stringConversion(contactLimbs);
Steve Tonneau's avatar
Steve Tonneau committed
856
                core::ConfigProjectorPtr_t proj = core::ConfigProjector::create(device,"proj", 1e-4, 40);
857
858
859
                //hpp::tools::LockJointRec(limb->limb_->name(), body->device_->rootJoint(), proj);
                for(std::vector<std::string>::const_iterator cit = names.begin(); cit !=names.end(); ++cit)
                {
Steve Tonneau's avatar
Steve Tonneau committed
860
                    rbprm::RbPrmLimbPtr_t limb = fullBody()->GetLimbs().at(*cit);
861
                    fcl::Transform3f localFrame, globalFrame;
862
                    localFrame.setTranslation(-limb->offset_);
863
864
865
866
                    std::vector<bool> posConstraints;
                    std::vector<bool> rotConstraints;
                    posConstraints.push_back(false);posConstraints.push_back(false);posConstraints.push_back(true);
                    rotConstraints.push_back(true);rotConstraints.push_back(true);rotConstraints.push_back(true);
Steve Tonneau's avatar
Steve Tonneau committed
867
                    proj->add(core::NumericalConstraint::create (constraints::Position::create("",fullBody()->device_,
868
869
870
871
872
873
874
875
876
877
                                                                                               limb->effector_,
                                                                                               globalFrame,
                                                                                               localFrame,
                                                                                               posConstraints)));
                    if(limb->contactType_ == hpp::rbprm::_6_DOF)
                    {
                        // rotation matrix around z
                        value_type theta = 2*(value_type(rand()) / value_type(RAND_MAX) - 0.5) * M_PI;
                        fcl::Matrix3f r = tools::GetZRotMatrix(theta);
                        fcl::Matrix3f rotation = r * limb->effector_->initialPosition ().getRotation();
Steve Tonneau's avatar
Steve Tonneau committed
878
                        proj->add(core::NumericalConstraint::create (constraints::Orientation::create("",fullBody()->device_,
879
880
881
882
883
884
885
886
887
                                                                                                      limb->effector_,
                                                                                                      fcl::Transform3f(rotation),
                                                                                                      rotConstraints)));
                    }
                }
                ConfigurationPtr_t configptr = shooter->shoot();
                Configuration_t config = *configptr;
                if(proj->apply(config) && config[2]> 0.3)
                {
888
                    if(problemSolver()->problem()->configValidations()->validate(config,report))
889
890
891
892
893
                    {
                        State tmp;
                        for(std::vector<std::string>::const_iterator cit = names.begin(); cit !=names.end(); ++cit)
                        {
                            std::string limbId = *cit;
Steve Tonneau's avatar
Steve Tonneau committed
894
                            rbprm::RbPrmLimbPtr_t limb = fullBody()->GetLimbs().at(*cit);
895
896
897
898
899
900
901
                            tmp.contacts_[limbId] = true;
                            tmp.contactPositions_[limbId] = limb->effector_->currentTransformation().getTranslation();
                            tmp.contactRotation_[limbId] = limb->effector_->currentTransformation().getRotation();
                            tmp.contactNormals_[limbId] = z;
                            tmp.configuration_ = config;
                            ++tmp.nbContacts;
                        }
Steve Tonneau's avatar
Steve Tonneau committed
902
                        if(stability::IsStable(fullBody(),tmp)>=0)
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
                        {
                            config[0]=0;
                            config[1]=0;
                            hpp::floatSeq* dofArray = new hpp::floatSeq();
                            dofArray->length(_CORBA_ULong(config.rows()));
                            for(std::size_t j=0; j< config.rows(); j++)
                            {
                              (*dofArray)[(_CORBA_ULong)j] = config [j];
                            }
                            return dofArray;
                        }
                    }
                }
            }
            throw (std::runtime_error("could not generate contact configuration after 1000 trials"));
        } catch (const std::exception& exc) {
        throw hpp::Error (exc.what ());
        }
    }

923
924
925
926
927
928
929
930
    hpp::floatSeq* RbprmBuilder::getContactSamplesIds(const char* limbname,
                                        const hpp::floatSeq& configuration,
                                        const hpp::floatSeq& direction) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
931
            fcl::Vec3f dir;
932
933
            for(std::size_t i =0; i <3; ++i)
            {
934
                dir[i] = direction[(_CORBA_ULong)i];
935
            }
Steve Tonneau's avatar
Steve Tonneau committed
936
937
938
            model::Configuration_t config = dofArrayToConfig (fullBody()->device_, configuration);
            model::Configuration_t save = fullBody()->device_->currentConfiguration();
            fullBody()->device_->currentConfiguration(config);
939
940

            sampling::T_OctreeReport finalSet;
Steve Tonneau's avatar
Steve Tonneau committed
941
942
            rbprm::T_Limb::const_iterator lit = fullBody()->GetLimbs().find(std::string(limbname));
            if(lit == fullBody()->GetLimbs().end())
943
944
            {
                throw std::runtime_error ("Impossible to find limb for joint "
Steve Tonneau's avatar
Steve Tonneau committed
945
                                          + std::string(limbname) + " to robot; limb not defined.");
946
947
            }
            const RbPrmLimbPtr_t& limb = lit->second;
Steve Tonneau's avatar
Steve Tonneau committed
948
            fcl::Transform3f transform = limb->limb_->robot()->rootJoint()->childJoint(0)->currentTransformation (); // get root transform from configuration
949
                        // TODO fix as in rbprm-fullbody.cc!!
950
            std::vector<sampling::T_OctreeReport> reports(problemSolver()->collisionObstacles().size());
951
952
            std::size_t i (0);
            //#pragma omp parallel for
953
954
            for(model::ObjectVector_t::const_iterator oit = problemSolver()->collisionObstacles().begin();
                oit != problemSolver()->collisionObstacles().end(); ++oit, ++i)
955
            {
Raphael Lefevre's avatar
Raphael Lefevre committed
956
                sampling::GetCandidates(limb->sampleContainer_, transform, *oit, dir, reports[i], sampling::HeuristicParam());
957
958
959
960
961
962
963
            }
            for(std::vector<sampling::T_OctreeReport>::const_iterator cit = reports.begin();
                cit != reports.end(); ++cit)
            {
                finalSet.insert(cit->begin(), cit->end());
            }
            hpp::floatSeq* dofArray = new hpp::floatSeq();
964
            dofArray->length((_CORBA_ULong)finalSet.size());
965
966
967
            sampling::T_OctreeReport::const_iterator candCit = finalSet.begin();
            for(std::size_t i=0; i< _CORBA_ULong(finalSet.size()); ++i, ++candCit)
            {
968
              (*dofArray)[(_CORBA_ULong)i] = (double)candCit->sample_->id_;
969
            }
Steve Tonneau's avatar
Steve Tonneau committed
970
            fullBody()->device_->currentConfiguration(save);
971
972
973
974
975
976
            return dofArray;
        } catch (const std::exception& exc) {
        throw hpp::Error (exc.what ());
        }
    }

Steve Tonneau's avatar
Steve Tonneau committed
977
    hpp::floatSeqSeq* RbprmBuilder::getContactSamplesProjected(const char* limbname,
Steve Tonneau's avatar
Steve Tonneau committed
978
979
980
981
982
983
984
985
986
987
988
989
990
                                        const hpp::floatSeq& configuration,
                                        const hpp::floatSeq& direction,
                                        unsigned short numSamples) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
            fcl::Vec3f dir;
            for(std::size_t i =0; i <3; ++i)
            {
                dir[i] = direction[(_CORBA_ULong)i];
            }
Steve Tonneau's avatar
Steve Tonneau committed
991
992
            model::Configuration_t config = dofArrayToConfig (fullBody()->device_, configuration);
            fullBody()->device_->currentConfiguration(config);
Steve Tonneau's avatar
Steve Tonneau committed
993
994

            sampling::T_OctreeReport finalSet;
Steve Tonneau's avatar
Steve Tonneau committed
995
996
            rbprm::T_Limb::const_iterator lit = fullBody()->GetLimbs().find(std::string(limbname));
            if(lit == fullBody()->GetLimbs().end())
Steve Tonneau's avatar
Steve Tonneau committed
997
998
999
1000
1001
            {
                throw std::runtime_error ("Impossible to find limb for joint "
                                          + std::string(limbname) + " to robot; limb not defined.");
            }
            const RbPrmLimbPtr_t& limb = lit->second;
1002
            fcl::Transform3f transform = limb->octreeRoot(); // get root transform from configuration
1003
                        // TODO fix as in rbprm-fullbody.cc!!
1004
            const affMap_t &affMap = problemSolver()->map
1005
1006
1007
1008
1009
                        <std::vector<boost::shared_ptr<model::CollisionObject> > > ();
            if (affMap.empty ())
            {
                throw hpp::Error ("No affordances found. Unable to interpolate.");
            }
Steve Tonneau's avatar
Steve Tonneau committed
1010
            const model::ObjectVector_t objects = contact::getAffObjectsForLimb(std::string(limbname), affMap,
1011
1012
1013
                                                                       bindShooter_.affFilter_);

            std::vector<sampling::T_OctreeReport> reports(objects.size());
1014
1015
            std::size_t i (0);
            //#pragma omp parallel for
1016
1017
            for(model::ObjectVector_t::const_iterator oit = objects.begin();
                oit != objects.end(); ++oit, ++i)
1018
            {
Raphael Lefevre's avatar
Raphael Lefevre committed
1019
                sampling::GetCandidates(limb->sampleContainer_, transform, *oit, dir, reports[i], sampling::HeuristicParam());
1020
1021
1022
1023
1024
1025
            }
            for(std::vector<sampling::T_OctreeReport>::const_iterator cit = reports.begin();
                cit != reports.end(); ++cit)
            {
                finalSet.insert(cit->begin(), cit->end());
            }
Steve Tonneau's avatar
Steve Tonneau committed
1026
1027
1028
1029
1030
1031
            // randomize samples
            std::random_shuffle(reports.begin(), reports.end());
            unsigned short num_samples_ok (0);
            bool success(false);
            model::Configuration_t sampleConfig = config;
            std::vector<model::Configuration_t> results;
1032
            sampling::T_OctreeReport::const_iterator candCit = finalSet.begin();
Steve Tonneau's avatar
Steve Tonneau committed
1033
            for(std::size_t i=0; i< _CORBA_ULong(finalSet.size()) && num_samples_ok < numSamples; ++i, ++candCit)
1034
            {
Steve Tonneau's avatar
Steve Tonneau committed
1035
1036
1037
1038
                const sampling::OctreeReport& report = *candCit;
                success = false;
                State state;
                state.configuration_ = config;
Steve Tonneau's avatar
Steve Tonneau committed
1039
                hpp::rbprm::projection::ProjectionReport rep =
Steve Tonneau's avatar
Steve Tonneau committed
1040
                hpp::rbprm::projection::projectSampleToObstacle(fullBody(),std::string(limbname), limb, report, fullBody()->GetCollisionValidation(), sampleConfig, state);
Steve Tonneau's avatar
Steve Tonneau committed
1041
                if(rep.success_)
Steve Tonneau's avatar
Steve Tonneau committed
1042
1043
1044
1045
                {
                    results.push_back(sampleConfig);
                    ++num_samples_ok;
                }
1046
            }
Steve Tonneau's avatar
Steve Tonneau committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
            hpp::floatSeqSeq *res;
            res = new hpp::floatSeqSeq ();

            res->length ((_CORBA_ULong)results.size ());
            i=0;
            std::size_t id = 0;
            for(std::vector<model::Configuration_t>::const_iterator cit = results.begin();
                        cit != results.end(); ++cit, ++id)
            {
                /*std::cout << "ID " << id;
                cit->print();*/
                const core::Configuration_t& config = *cit;
                _CORBA_ULong size = (_CORBA_ULong) config.size ();
                double* dofArray = hpp::floatSeq::allocbuf(size);
                hpp::floatSeq floats (size, size, dofArray, true);
                //convert the config in dofseq
                for (model::size_type j=0 ; j < config.size() ; ++j) {
                  dofArray[j] = config [j];
                }
                (*res) [(_CORBA_ULong)i] = floats;
                ++i;
            }
            return res;
1070
1071
1072
1073
1074
        } catch (const std::exception& exc) {
        throw hpp::Error (exc.what ());
        }
    }

1075
1076
1077
1078
1079
1080
1081
    hpp::floatSeq* RbprmBuilder::getSamplesIdsInOctreeNode(const char* limb,
                                                           double octreeNodeId) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
1082
            long ocId ((long)octreeNodeId);
Steve Tonneau's avatar
Steve Tonneau committed
1083
            const T_Limb& limbs = fullBody()->GetLimbs();
1084
1085
1086
            T_Limb::const_iterator lit = limbs.find(std::string(limb));
            if(lit == limbs.end())
            {
Steve Tonneau's avatar
Steve Tonneau committed
1087
                std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody()->device_->name());
1088
1089
1090
1091
1092
1093
1094
                throw Error (err.c_str());
            }
            const sampling::T_VoxelSampleId& sampleIds =  lit->second->sampleContainer_.samplesInVoxels_;
            sampling::T_VoxelSampleId::const_iterator cit = sampleIds.find(ocId);
            if(cit == sampleIds.end())
            {
                std::stringstream ss; ss << ocId;
Steve Tonneau's avatar
Steve Tonneau committed
1095
                std::string err("No octree node with id " + ss.str() + "was defined for robot" + fullBody()->device_->name());
1096
1097
1098
1099
                throw Error (err.c_str());
            }
            const sampling::VoxelSampleId& ids = cit->second;
            hpp::floatSeq* dofArray = new hpp::floatSeq();
1100
            dofArray->length((_CORBA_ULong)ids.second);
1101
1102
1103
            std::size_t sampleId = ids.first;
            for(std::size_t i=0; i< _CORBA_ULong(ids.second); ++i, ++sampleId)
            {
1104
              (*dofArray)[(_CORBA_ULong)i] = (double)sampleId;
1105
1106
1107
1108
1109
1110
1111
            }
            return dofArray;
        } catch (const std::exception& exc) {
        throw hpp::Error (exc.what ());
        }
    }

1112
    void RbprmBuilder::addLimb(const char* id, const char* limb, const char* effector, const hpp::floatSeq& offset, const hpp::floatSeq& normal, double x, double y,
1113
                               unsigned int samples, const char* heuristicName, double resolution, const char *contactType, double disableEffectorCollision, double grasp, const hpp::floatSeq &limbOffset) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
1114
1115
1116
1117
1118
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
1119
            fcl::Vec3f off, norm,limbOff;
1120
1121
            for(std::size_t i =0; i <3; ++i)
            {
1122
1123
                off[i] = offset[(_CORBA_ULong)i];
                norm[i] = normal[(_CORBA_ULong)i];
1124
1125
                limbOff[i] = limbOffset[(_CORBA_ULong)i];

1126
            }
1127
1128
1129
1130
1131
            ContactType cType = hpp::rbprm::_6_DOF;
            if(std::string(contactType) == "_3_DOF")
            {
                cType = hpp::rbprm::_3_DOF;
            }
1132
            fullBody()->AddLimb(std::string(id), std::string(limb), std::string(effector), off,limbOff, norm, x, y,
1133
                               problemSolver()->collisionObstacles(), samples,heuristicName,resolution,cType,disableEffectorCollision > 0.5, grasp > 0.5);
Steve Tonneau's avatar
Steve Tonneau committed
1134
1135
1136
1137
1138
1139
1140
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }

1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
    void RbprmBuilder::addNonContactingLimb(const char* id, const char* limb, const char* effector, unsigned int samples) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {

            fullBody()->AddNonContactingLimb(std::string(id), std::string(limb), std::string(effector), problemSolver()->collisionOb