rbprmbuilder.impl.cc 85.8 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>
Steve Tonneau's avatar
Steve Tonneau committed
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
#include "hpp/rbprm/stability/stability.hh"
Steve Tonneau's avatar
Steve Tonneau committed
30
#include "hpp/rbprm/sampling/sample-db.hh"
Steve Tonneau's avatar
Steve Tonneau committed
31
#include "hpp/model/urdf/util.hh"
32
#include "hpp/core/straight-path.hh"
33
#include "hpp/model/joint.hh"
34
35
36
#include "hpp/core/config-validations.hh"
#include "hpp/core/collision-validation-report.hh"
#include <hpp/core/subchain-path.hh>
37
38
#include <hpp/core/basic-configuration-shooter.hh>
#include <hpp/core/collision-validation.hh>
Steve Tonneau's avatar
Steve Tonneau committed
39
#include <fstream>
Steve Tonneau's avatar
Steve Tonneau committed
40

41
42
43
44
#ifdef PROFILE
    #include "hpp/rbprm/rbprm-profiler.hh"
#endif

Steve Tonneau's avatar
Steve Tonneau committed
45
46


Steve Tonneau's avatar
Steve Tonneau committed
47
48
49
50
namespace hpp {
  namespace rbprm {
    namespace impl {

Steve Tonneau's avatar
Steve Tonneau committed
51
52
53
    RbprmBuilder::RbprmBuilder ()
    : POA_hpp::corbaserver::rbprm::RbprmBuilder()
    , romLoaded_(false)
Steve Tonneau's avatar
Steve Tonneau committed
54
    , fullBodyLoaded_(false)
Steve Tonneau's avatar
Steve Tonneau committed
55
    , bindShooter_()
Steve Tonneau's avatar
Steve Tonneau committed
56
    , analysisFactory_(0)
Steve Tonneau's avatar
Steve Tonneau committed
57
58
59
60
    {
        // NOTHING
    }

Steve Tonneau's avatar
Steve Tonneau committed
61
62
63
64
65
66
67
68
69
    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
70
71
72
            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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
                    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
97
            hppDout (error, err );
Steve Tonneau's avatar
Steve Tonneau committed
98
99
100
101
            throw hpp::Error(err.c_str());
        }
        try
        {
Steve Tonneau's avatar
Steve Tonneau committed
102
            hpp::model::RbPrmDevicePtr_t device = hpp::model::RbPrmDevice::create (robotName, romDevices_);
Steve Tonneau's avatar
Steve Tonneau committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
            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
            problemSolver_->robot (device);
            problemSolver_->robot ()->controlComputation
            (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
121
122
123
124
125
126
127
128
129
130
    void RbprmBuilder::loadFullBodyRobot(const char* robotName,
         const char* rootJointType,
         const char* packageName,
         const char* modelName,
         const char* urdfSuffix,
         const char* srdfSuffix) throw (hpp::Error)
    {
        try
        {
            model::DevicePtr_t device = model::Device::create (robotName);
131
            hpp::model::urdf::loadRobotModel (device,
Steve Tonneau's avatar
Steve Tonneau committed
132
133
134
135
136
137
                    std::string (rootJointType),
                    std::string (packageName),
                    std::string (modelName),
                    std::string (urdfSuffix),
                    std::string (srdfSuffix));
            fullBody_ = rbprm::RbPrmFullBody::create(device);
Steve Tonneau's avatar
Steve Tonneau committed
138
            problemSolver_->pathValidationType ("Discretized",0.05); // reset to avoid conflict with rbprm path
139
            problemSolver_->robot (fullBody_->device_);
Steve Tonneau's avatar
Steve Tonneau committed
140
            problemSolver_->resetProblem();
141
142
            problemSolver_->robot ()->controlComputation
            (model::Device::JOINT_POSITION);
Steve Tonneau's avatar
Steve Tonneau committed
143
144
145
146
147
148
149
        }
        catch (const std::exception& exc)
        {
            hppDout (error, exc.what ());
            throw hpp::Error (exc.what ());
        }
        fullBodyLoaded_ = true;
150
        analysisFactory_ = new sampling::AnalysisFactory(fullBody_);
Steve Tonneau's avatar
Steve Tonneau committed
151
152
    }

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    void RbprmBuilder::loadFullBodyRobotFromExistingRobot() throw (hpp::Error)
    {
        try
        {
            fullBody_ = rbprm::RbPrmFullBody::create(problemSolver_->problem()->robot());
            problemSolver_->pathValidationType ("Discretized",0.05); // reset to avoid conflict with rbprm path
            problemSolver_->robot (fullBody_->device_);
            problemSolver_->resetProblem();
            problemSolver_->robot ()->controlComputation
            (model::Device::JOINT_POSITION);
        }
        catch (const std::exception& exc)
        {
            hppDout (error, exc.what ());
            throw hpp::Error (exc.what ());
        }
        fullBodyLoaded_ = true;
        analysisFactory_ = new sampling::AnalysisFactory(fullBody_);
    }

Steve Tonneau's avatar
Steve Tonneau committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    hpp::floatSeq* RbprmBuilder::getSampleConfig(const char* limb, unsigned short sampleId) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        const T_Limb& limbs = fullBody_->GetLimbs();
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody_->device_->name());
            throw Error (err.c_str());
        }
        const RbPrmLimbPtr_t& limbPtr = lit->second;
        hpp::floatSeq *dofArray;
        Eigen::VectorXd config = fullBody_->device_->currentConfiguration ();
        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
193
        config.segment(sample.startRank_, sample.length_) = sample.configuration_;
Steve Tonneau's avatar
Steve Tonneau committed
194
195
196
197
198
199
200
        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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

    hpp::floatSeq* RbprmBuilder::getSamplePosition(const char* limb, unsigned short sampleId) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        const T_Limb& limbs = fullBody_->GetLimbs();
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody_->device_->name());
            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
229

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    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,
                                                    const rbprm::State& state)
    {
        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;
            const fcl::Vec3f& position = cit->second;
            limb = limbs.at(name);
            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
                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;
            }
            else
            {
                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);
            }
            for(std::size_t i =0; i<4; ++i)
            {
283
                res.push_back(position + (R*(p.row(i).transpose() + limb->offset_)));
284
285
286
287
288
289
                res.push_back(state.contactNormals_.at(name));
            }
        }
        return res;
    }

290
291
    std::vector<fcl::Vec3f> computeRectangleContact(const rbprm::RbPrmFullBodyPtr_t device,
                                                    const rbprm::State& state,
Steve Tonneau's avatar
Steve Tonneau committed
292
                                                    const std::string& limbName)
293
    {
294
295
        device->device_->currentConfiguration(state.configuration_);
        device->device_->computeForwardKinematics();
296
297
298
        std::vector<fcl::Vec3f> res;
        const rbprm::T_Limb& limbs = device->GetLimbs();
        rbprm::RbPrmLimbPtr_t limb;
Steve Tonneau's avatar
Steve Tonneau committed
299
        Matrix43 p; Eigen::Matrix3d R = Eigen::Matrix3d::Identity(); Eigen::Matrix3d cFrame = Eigen::Matrix3d::Identity();
300
301
302
303
304
305
306
307
        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);
308
309
310
311
312
                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_;
313
314
315
316
317
318
319
320
321
                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;
322
                    for(int i =0; i<3; ++i) z[i] = normal[i];
323
324
325
326
327
328
329
330
331
332
333
334
                    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
335
336
337
                    cFrame.block<3,1>(0,0) = x;
                    cFrame.block<3,1>(0,1) = y;
                    cFrame.block<3,1>(0,2) = z;
338
                }
339
340
341
342
                fcl::Transform3f roWorld, roEffector;
                roWorld.setRotation(state.contactRotation_.at(name));
                roWorld.setTranslation(position);
                roEffector = roWorld; roEffector.inverse();
343
344
                fcl::Vec3f z_axis(0,0,1);
                fcl::Matrix3f rotationLocal = tools::GetRotationMatrix(z_axis, limb->normal_);
345
346
                for(std::size_t i =0; i<4; ++i)
                {
Steve Tonneau's avatar
Steve Tonneau committed
347
                    if(limb->contactType_ == _3_DOF)
348
                    {
349
                        fcl::Vec3f pworld = position + (cFrame*(p.row(i).transpose())) + offset;
350
351
                        res.push_back((roEffector * pworld).getTranslation());
                        res.push_back(roEffector.getRotation() * state.contactNormals_.at(name));
352
353
354
                    }
                    else
                    {
355
356
                        // TODO if limb is 6D and offset is not in the good direction
                        // this probably won't work
357
                        res.push_back(rotationLocal*(p.row(i).transpose()) + limb->offset_);
358
                        res.push_back(roEffector.getRotation() * state.contactNormals_.at(name));
359
360
361
362
363
364
365
366
                    }
                }
                return res;
            }
        }
        return res;
    }

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
    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);
            const RbPrmLimbPtr_t limb = fullBody_->GetLimbs().at(limbName);
            model::Configuration_t config = dofArrayToConfig (fullBody_->device_, configuration);
            fullBody_->device_->currentConfiguration(config);
            fullBody_->device_->computeForwardKinematics();
            State state;
            state.configuration_ = config;
            state.contacts_[limbName] = true;
            const fcl::Vec3f position = limb->effector_->currentTransformation().getTranslation();
422
            state.contactPositions_[limbName] = position;
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
            state.contactNormals_[limbName] = fcl::Vec3f(0,0,1);
            state.contactRotation_[limbName] = limb->effector_->currentTransformation().getRotation();
            std::vector<fcl::Vec3f> poss = (computeRectangleContact(fullBody_, state));

            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
451
452
453
454
455
456
457
458
459
    CORBA::UShort RbprmBuilder::getNumSamples(const char* limb) throw (hpp::Error)
    {
        const T_Limb& limbs = fullBody_->GetLimbs();
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody_->device_->name());
            throw Error (err.c_str());
        }
460
        return (CORBA::UShort)(lit->second->sampleContainer_.samples_.size());
Steve Tonneau's avatar
Steve Tonneau committed
461
462
    }

463
464
465
466
467
468
469
470
471
472
473
    floatSeq *RbprmBuilder::getOctreeNodeIds(const char* limb) throw (hpp::Error)
    {
        const T_Limb& limbs = fullBody_->GetLimbs();
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody_->device_->name());
            throw Error (err.c_str());
        }
        const sampling::T_VoxelSampleId& ids =  lit->second->sampleContainer_.samplesInVoxels_;
        hpp::floatSeq* dofArray = new hpp::floatSeq();
474
        dofArray->length((_CORBA_ULong)ids.size());
475
476
477
        sampling::T_VoxelSampleId::const_iterator it = ids.begin();
        for(std::size_t i=0; i< _CORBA_ULong(ids.size()); ++i, ++it)
        {
478
          (*dofArray)[(_CORBA_ULong)i] = (double)it->first;
479
480
481
482
        }
        return dofArray;
    }

Steve Tonneau's avatar
Steve Tonneau committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    double RbprmBuilder::getSampleValue(const char* limb, const char* valueName, unsigned short sampleId) throw (hpp::Error)
    {
        const T_Limb& limbs = fullBody_->GetLimbs();
        T_Limb::const_iterator lit = limbs.find(std::string(limb));
        if(lit == limbs.end())
        {
            std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody_->device_->name());
            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];
    }

507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524

    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
525
526
527
528
    std::vector<std::string> stringConversion(const hpp::Names_t& dofArray)
    {
        std::vector<std::string> res;
        std::size_t dim = (std::size_t)dofArray.length();
529
        for (_CORBA_ULong iDof = 0; iDof < dim; iDof++)
Steve Tonneau's avatar
Steve Tonneau committed
530
531
532
533
534
        {
            res.push_back(std::string(dofArray[iDof]));
        }
        return res;
    }
Steve Tonneau's avatar
Steve Tonneau committed
535

Steve Tonneau's avatar
Steve Tonneau committed
536
537
538
539
    std::vector<double> doubleConversion(const hpp::floatSeq& dofArray)
    {
        std::vector<double> res;
        std::size_t dim = (std::size_t)dofArray.length();
540
        for (_CORBA_ULong iDof = 0; iDof < dim; iDof++)
Steve Tonneau's avatar
Steve Tonneau committed
541
542
543
544
545
546
        {
            res.push_back(dofArray[iDof]);
        }
        return res;
    }

Steve Tonneau's avatar
Steve Tonneau committed
547
548
549
550
551
552

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

553

554
    void RbprmBuilder::setAffordanceFilter(const char* romName, const hpp::Names_t& affordances) throw (hpp::Error)
555
    {
556
557
558
559
        std::string name (romName);
				std::vector<std::string> affNames = stringConversion(affordances);
        bindShooter_.affFilter_.erase(name);
        bindShooter_.affFilter_.insert(std::make_pair(name,affNames));
560
561
    }

Steve Tonneau's avatar
Steve Tonneau committed
562
563
564
565
566
567
568
569
570
571
572
    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;

    }

573
    double RbprmBuilder::projectStateToCOMEigen(unsigned short stateId, const model::Configuration_t& com_target) throw (hpp::Error)
574
575
576
577
578
579
580
    {
        try
        {
            if(lastStatesComputed_.size() <= stateId)
            {
                throw std::runtime_error ("Unexisting state " + std::string(""+(stateId)));
            }
581
            State s = lastStatesComputed_[stateId];
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
            bool succes (false);
            hpp::model::Configuration_t c = rbprm::interpolation::projectOnCom(fullBody_, problemSolver_->problem(),s,com_target,succes);
            if(succes)
            {
                lastStatesComputed_[stateId].configuration_ = c;
                lastStatesComputedTime_[stateId].second.configuration_ = c;
                return 1.;
            }
            return 0;
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }

598
599
600
601
602
603
    double RbprmBuilder::projectStateToCOM(unsigned short stateId, const hpp::floatSeq& com) throw (hpp::Error)
    {        
        model::Configuration_t com_target = dofArrayToConfig (3, com);
        return projectStateToCOMEigen(stateId, com_target);
    }

604
605
    hpp::floatSeq* RbprmBuilder::generateContacts(const hpp::floatSeq& configuration,
			const hpp::floatSeq& direction) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
606
607
608
609
610
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
611
            fcl::Vec3f dir;
Steve Tonneau's avatar
Steve Tonneau committed
612
613
            for(std::size_t i =0; i <3; ++i)
            {
614
                dir[i] = direction[(_CORBA_ULong)i];
Steve Tonneau's avatar
Steve Tonneau committed
615
            }
616
617
618
						const affMap_t &affMap = problemSolver_->map
							<std::vector<boost::shared_ptr<model::CollisionObject> > > ();
		        if (affMap.empty ()) {
619
620
    	        throw hpp::Error ("No affordances found. Unable to generate Contacts.");
      		  }
Steve Tonneau's avatar
Steve Tonneau committed
621
            model::Configuration_t config = dofArrayToConfig (fullBody_->device_, configuration);
622
623
            rbprm::State state = rbprm::ComputeContacts(fullBody_,config,
							affMap, bindShooter_.affFilter_, dir);
Steve Tonneau's avatar
Steve Tonneau committed
624
            hpp::floatSeq* dofArray = new hpp::floatSeq();
Steve Tonneau's avatar
stair    
Steve Tonneau committed
625
            dofArray->length(_CORBA_ULong(state.configuration_.rows()));
Steve Tonneau's avatar
Steve Tonneau committed
626
627
628
629
630
631
632
633
            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 ());
        }
    }

634
635
636
637
638
639
640
641
642
643
644
    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);
            core::BasicConfigurationShooterPtr_t  shooter = core::BasicConfigurationShooter::create(fullBody_->device_);
            for(int i =0; i< 1000; ++i)
            {
Steve Tonneau's avatar
Steve Tonneau committed
645
                core::DevicePtr_t device = fullBody_->device_->clone();
646
                std::vector<std::string> names = stringConversion(contactLimbs);
Steve Tonneau's avatar
Steve Tonneau committed
647
                core::ConfigProjectorPtr_t proj = core::ConfigProjector::create(device,"proj", 1e-4, 40);
648
649
650
651
652
                //hpp::tools::LockJointRec(limb->limb_->name(), body->device_->rootJoint(), proj);
                for(std::vector<std::string>::const_iterator cit = names.begin(); cit !=names.end(); ++cit)
                {
                    rbprm::RbPrmLimbPtr_t limb = fullBody_->GetLimbs().at(*cit);
                    fcl::Transform3f localFrame, globalFrame;
653
                    localFrame.setTranslation(-limb->offset_);
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
                    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);
                    proj->add(core::NumericalConstraint::create (constraints::Position::create("",fullBody_->device_,
                                                                                               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();
                        proj->add(core::NumericalConstraint::create (constraints::Orientation::create("",fullBody_->device_,
                                                                                                      limb->effector_,
                                                                                                      fcl::Transform3f(rotation),
                                                                                                      rotConstraints)));
                    }
                }
                ConfigurationPtr_t configptr = shooter->shoot();
                Configuration_t config = *configptr;
                if(proj->apply(config) && config[2]> 0.3)
                {
                    if(problemSolver_->problem()->configValidations()->validate(config,report))
                    {
                        State tmp;
                        for(std::vector<std::string>::const_iterator cit = names.begin(); cit !=names.end(); ++cit)
                        {
                            std::string limbId = *cit;
                            rbprm::RbPrmLimbPtr_t limb = fullBody_->GetLimbs().at(*cit);
                            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;
                        }
                        if(stability::IsStable(fullBody_,tmp)>=0)
                        {
                            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 ());
        }
    }

714
715
716
717
718
719
720
721
    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
        {
722
            fcl::Vec3f dir;
723
724
            for(std::size_t i =0; i <3; ++i)
            {
725
                dir[i] = direction[(_CORBA_ULong)i];
726
727
            }
            model::Configuration_t config = dofArrayToConfig (fullBody_->device_, configuration);
Steve Tonneau's avatar
Steve Tonneau committed
728
729
            model::Configuration_t save = fullBody_->device_->currentConfiguration();
            fullBody_->device_->currentConfiguration(config);
730
731
732
733
734
735

            sampling::T_OctreeReport finalSet;
            rbprm::T_Limb::const_iterator lit = fullBody_->GetLimbs().find(std::string(limbname));
            if(lit == fullBody_->GetLimbs().end())
            {
                throw std::runtime_error ("Impossible to find limb for joint "
Steve Tonneau's avatar
Steve Tonneau committed
736
                                          + std::string(limbname) + " to robot; limb not defined.");
737
738
            }
            const RbPrmLimbPtr_t& limb = lit->second;
Steve Tonneau's avatar
Steve Tonneau committed
739
            fcl::Transform3f transform = limb->limb_->robot()->rootJoint()->childJoint(0)->currentTransformation (); // get root transform from configuration
740
                        // TODO fix as in rbprm-fullbody.cc!!
741
742
743
744
745
746
            std::vector<sampling::T_OctreeReport> reports(problemSolver_->collisionObstacles().size());
            std::size_t i (0);
            //#pragma omp parallel for
            for(model::ObjectVector_t::const_iterator oit = problemSolver_->collisionObstacles().begin();
                oit != problemSolver_->collisionObstacles().end(); ++oit, ++i)
            {
Steve Tonneau's avatar
Steve Tonneau committed
747
                sampling::GetCandidates(limb->sampleContainer_, transform, *oit, dir, reports[i]);
748
749
750
751
752
753
754
            }
            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();
755
            dofArray->length((_CORBA_ULong)finalSet.size());
756
757
758
            sampling::T_OctreeReport::const_iterator candCit = finalSet.begin();
            for(std::size_t i=0; i< _CORBA_ULong(finalSet.size()); ++i, ++candCit)
            {
759
              (*dofArray)[(_CORBA_ULong)i] = (double)candCit->sample_->id_;
760
            }
Steve Tonneau's avatar
Steve Tonneau committed
761
            fullBody_->device_->currentConfiguration(save);
762
763
764
765
766
767
            return dofArray;
        } catch (const std::exception& exc) {
        throw hpp::Error (exc.what ());
        }
    }

768
769
770
771
772
773
774
    hpp::floatSeq* RbprmBuilder::getSamplesIdsInOctreeNode(const char* limb,
                                                           double octreeNodeId) throw (hpp::Error)
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
775
            long ocId ((long)octreeNodeId);
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
            const T_Limb& limbs = fullBody_->GetLimbs();
            T_Limb::const_iterator lit = limbs.find(std::string(limb));
            if(lit == limbs.end())
            {
                std::string err("No limb " + std::string(limb) + "was defined for robot" + fullBody_->device_->name());
                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;
                std::string err("No octree node with id " + ss.str() + "was defined for robot" + fullBody_->device_->name());
                throw Error (err.c_str());
            }
            const sampling::VoxelSampleId& ids = cit->second;
            hpp::floatSeq* dofArray = new hpp::floatSeq();
793
            dofArray->length((_CORBA_ULong)ids.second);
794
795
796
            std::size_t sampleId = ids.first;
            for(std::size_t i=0; i< _CORBA_ULong(ids.second); ++i, ++sampleId)
            {
797
              (*dofArray)[(_CORBA_ULong)i] = (double)sampleId;
798
799
800
801
802
803
804
            }
            return dofArray;
        } catch (const std::exception& exc) {
        throw hpp::Error (exc.what ());
        }
    }

805
    void RbprmBuilder::addLimb(const char* id, const char* limb, const char* effector, const hpp::floatSeq& offset, const hpp::floatSeq& normal, double x, double y,
806
                               unsigned short samples, const char* heuristicName, double resolution, const char *contactType, double disableEffectorCollision) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
807
808
809
810
811
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
Steve Tonneau's avatar
Steve Tonneau committed
812
            fcl::Vec3f off, norm;
813
814
            for(std::size_t i =0; i <3; ++i)
            {
815
816
                off[i] = offset[(_CORBA_ULong)i];
                norm[i] = normal[(_CORBA_ULong)i];
817
            }
818
819
820
821
822
            ContactType cType = hpp::rbprm::_6_DOF;
            if(std::string(contactType) == "_3_DOF")
            {
                cType = hpp::rbprm::_3_DOF;
            }
823
824
            fullBody_->AddLimb(std::string(id), std::string(limb), std::string(effector), off, norm, x, y,
                               problemSolver_->collisionObstacles(), samples,heuristicName,resolution,cType,disableEffectorCollision > 0.5);
Steve Tonneau's avatar
Steve Tonneau committed
825
826
827
828
829
830
831
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }

Steve Tonneau's avatar
Steve Tonneau committed
832

833
    void RbprmBuilder::addLimbDatabase(const char* databasePath, const char* id, const char* heuristicName, double loadValues, double disableEffectorCollision) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
834
835
836
837
838
839
    {
        if(!fullBodyLoaded_)
            throw Error ("No full body robot was loaded");
        try
        {
            std::string fileName(databasePath);
840
841
            fullBody_->AddLimb(fileName, std::string(id), problemSolver_->collisionObstacles(), heuristicName, loadValues > 0.5,
                               disableEffectorCollision > 0.5);
Steve Tonneau's avatar
Steve Tonneau committed
842
843
844
845
846
847
848
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }

849
850
    void SetPositionAndNormal(rbprm::State& state,
			hpp::rbprm::RbPrmFullBodyPtr_t fullBody, const hpp::floatSeq& configuration,
851
            std::vector<std::string>& names)
Steve Tonneau's avatar
Steve Tonneau committed
852
853
854
855
    {
        core::Configuration_t old = fullBody->device_->currentConfiguration();
        model::Configuration_t config = dofArrayToConfig (fullBody->device_, configuration);
        fullBody->device_->currentConfiguration(config);
Steve Tonneau's avatar
Steve Tonneau committed
856
        fullBody->device_->computeForwardKinematics();
Steve Tonneau's avatar
Steve Tonneau committed
857
858
859
860
861
862
        for(std::vector<std::string>::const_iterator cit = names.begin(); cit != names.end();++cit)
        {
            rbprm::T_Limb::const_iterator lit = fullBody->GetLimbs().find(*cit);
            if(lit == fullBody->GetLimbs().end())
            {
                throw std::runtime_error ("Impossible to find limb for joint "
Steve Tonneau's avatar
Steve Tonneau committed
863
                                          + (*cit) + " to robot; limb not defined");
Steve Tonneau's avatar
Steve Tonneau committed
864
865
866
867
868
            }
            const core::JointPtr_t joint = fullBody->device_->getJointByName(lit->second->effector_->name());
            const fcl::Transform3f& transform =  joint->currentTransformation ();
            const fcl::Matrix3f& rot = transform.getRotation();
            state.contactPositions_[*cit] = transform.getTranslation();
Steve Tonneau's avatar
Steve Tonneau committed
869
            state.contactRotation_[*cit] = rot;
870
871
            const fcl::Vec3f z = transform.getRotation() * lit->second->normal_;
            state.contactNormals_[*cit] = z;
Steve Tonneau's avatar
Steve Tonneau committed
872
            state.contacts_[*cit] = true;
Steve Tonneau's avatar
Steve Tonneau committed
873
            state.contactOrder_.push(*cit);
Steve Tonneau's avatar
Steve Tonneau committed
874
875
        }        
        state.nbContacts = state.contactNormals_.size() ;
Steve Tonneau's avatar
Steve Tonneau committed
876
        state.configuration_ = config;
877
878
        state.robustness =  stability::IsStable(fullBody,state);
        state.stable = state.robustness >= 0;
Steve Tonneau's avatar
Steve Tonneau committed
879
880
881
882
883
884
885
        fullBody->device_->currentConfiguration(old);
    }

    void RbprmBuilder::setStartState(const hpp::floatSeq& configuration, const hpp::Names_t& contactLimbs) throw (hpp::Error)
    {
        try
        {
886
887
            std::vector<std::string> names = stringConversion(contactLimbs);
            SetPositionAndNormal(startState_,fullBody_, configuration, names);
Steve Tonneau's avatar
Steve Tonneau committed
888
889
890
891
892
893
894
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }

895
896
897
898
899
900
901
902
903
904
905

    hpp::floatSeq* RbprmBuilder::computeContactForConfig(const hpp::floatSeq& configuration, const char *limbNam) throw (hpp::Error)
    {
        State state;
        std::string limb(limbNam);
        try
        {
            std::vector<std::string> limbs; limbs.push_back(limbNam);
            SetPositionAndNormal(state,fullBody_, configuration, limbs);

            const std::vector<fcl::Vec3f>& positions = computeRectangleContact(fullBody_,state,limb);
Steve Tonneau's avatar
Steve Tonneau committed
906
            _CORBA_ULong size = (_CORBA_ULong) (positions.size () * 3);
907
908
909
910
911
912
913
            hpp::floatSeq* dofArray = new hpp::floatSeq();
            dofArray->length(size);
            for(std::size_t h = 0; h<positions.size(); ++h)
            {
                for(std::size_t k =0; k<3; ++k)
                {
                    model::size_type j (h*3 + k);
Steve Tonneau's avatar
Steve Tonneau committed
914
                    (*dofArray)[(_CORBA_ULong)j] = positions[h][k];
915
916
917
918
919
920
921
922
923
924
925
                }
            }
            return dofArray;
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }

    }

Steve Tonneau's avatar
Steve Tonneau committed
926
927
928
929
    void RbprmBuilder::setEndState(const hpp::floatSeq& configuration, const hpp::Names_t& contactLimbs) throw (hpp::Error)
    {
        try
        {
930
931
            std::vector<std::string> names = stringConversion(contactLimbs);
            SetPositionAndNormal(endState_,fullBody_, configuration, names);
Steve Tonneau's avatar
Steve Tonneau committed
932
933
934
935
936
937
938
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }

939
940
941
942
943
944
945
946
947
948
    std::vector<State> TimeStatesToStates(const T_StateFrame& ref)
    {
        std::vector<State> res;
        for(CIT_StateFrame cit = ref.begin(); cit != ref.end(); ++cit)
        {
            res.push_back(cit->second);
        }
        return res;
    }

949
    floatSeqSeq* RbprmBuilder::interpolateConfigs(const hpp::floatSeqSeq& configs, double robustnessTreshold, unsigned short filterStates) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
950
951
952
953
954
955
956
957
958
959
960
    {
        try
        {
            if(startState_.configuration_.rows() == 0)
            {
                throw std::runtime_error ("Start state not initialized, can not interpolate ");
            }
            if(endState_.configuration_.rows() == 0)
            {
                throw std::runtime_error ("End state not initialized, can not interpolate ");
            }
961
            T_Configuration configurations = doubleDofArrayToConfig(fullBody_->device_, configs);
962
963
964
965
966
967
968
            const affMap_t &affMap = problemSolver_->map
                        <std::vector<boost::shared_ptr<model::CollisionObject> > > ();
            if (affMap.empty ())
            {
                throw hpp::Error ("No affordances found. Unable to interpolate.");
            }
            hpp::rbprm::interpolation::RbPrmInterpolationPtr_t interpolator = rbprm::interpolation::RbPrmInterpolation::create(fullBody_,startState_,endState_);
969
            lastStatesComputedTime_ = interpolator->Interpolate(affMap, bindShooter_.affFilter_,configurations,robustnessTreshold, filterStates != 0);
970
            lastStatesComputed_ = TimeStatesToStates(lastStatesComputedTime_);
Steve Tonneau's avatar
Steve Tonneau committed
971
972
973
            hpp::floatSeqSeq *res;
            res = new hpp::floatSeqSeq ();

974
            res->length ((_CORBA_ULong)lastStatesComputed_.size ());
Steve Tonneau's avatar
Steve Tonneau committed
975
976
            std::size_t i=0;
            std::size_t id = 0;
977
            for(std::vector<State>::const_iterator cit = lastStatesComputed_.begin(); cit != lastStatesComputed_.end(); ++cit, ++id)
Steve Tonneau's avatar
Steve Tonneau committed
978
979
980
981
982
983
984
985
986
987
988
            {
                std::cout << "ID " << id;
                cit->print();
                const core::Configuration_t config = cit->configuration_;
                _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];
                }
989
                (*res) [(_CORBA_ULong)i] = floats;
Steve Tonneau's avatar
Steve Tonneau committed
990
991
992
993
994
995
996
997
998
                ++i;
            }
            return res;
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }
Steve Tonneau's avatar
Steve Tonneau committed
999

1000
    hpp::floatSeqSeq* contactCone(RbPrmFullBodyPtr_t& fullBody, State& state, const double friction)
1001
1002
1003
1004
    {
        hpp::floatSeqSeq *res;
        res = new hpp::floatSeqSeq ();

1005
        std::pair<stability::MatrixXX, stability::VectorX> cone = stability::ComputeCentroidalCone(fullBody, state, friction);
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
        res->length ((_CORBA_ULong)cone.first.rows());
        _CORBA_ULong size = (_CORBA_ULong) cone.first.cols()+1;
        for(int i=0; i < cone.first.rows(); ++i)
        {
            double* dofArray = hpp::floatSeq::allocbuf(size);
            hpp::floatSeq floats (size, size, dofArray, true);
            //convert the row in dofseq
            for (int j=0 ; j < cone.first.cols() ; ++j)
            {
                dofArray[j] = cone.first(i,j);
            }
            dofArray[size-1] =cone.second[i];
            (*res) [(_CORBA_ULong)i] = floats;
        }
        return res;
    }

1023
    hpp::floatSeqSeq* RbprmBuilder::getContactCone(unsigned short stateId, double friction) throw (hpp::Error)
1024
1025
1026
1027
1028
1029
1030
    {
        try
        {
            if(lastStatesComputed_.size() <= stateId)
            {
                throw std::runtime_error ("Unexisting state " + std::string(""+(stateId)));
            }
1031
            return contactCone(fullBody_, lastStatesComputed_[stateId],friction);
1032
1033
1034
        }
        catch(std::runtime_error& e)
        {
1035
            std::cout << "ERROR " << e.what() << std::endl;
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
            throw Error(e.what());
        }
    }

    State intermediary(const State& firstState, const State& thirdState, unsigned short& cId, bool& success)
    {
        success = false;
        std::vector<std::string> breaks;
        thirdState.contactBreaks(firstState, breaks);
        if(breaks.size() > 1)
        {
1047
            throw std::runtime_error ("too many contact breaks between states" + std::string(""+cId) + "and " + std::string(""+(cId + 1)));
1048
1049
1050
1051
1052
1053
        }
        if(breaks.size() == 1)
        {
            State intermediary(firstState);
            intermediary.RemoveContact(*breaks.begin());
            success = true;
1054
            return intermediary;
1055
1056
1057
1058
        }
        return firstState;
    }

1059
    hpp::floatSeqSeq* RbprmBuilder::getContactIntermediateCone(unsigned short stateId, double friction) throw (hpp::Error)
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
    {
        try
        {
            if(lastStatesComputed_.size() <= stateId+1)
            {
                throw std::runtime_error ("Unexisting state " + std::string(""+(stateId+1)));
            }
            bool success;
            State intermediaryState = intermediary(lastStatesComputed_[stateId], lastStatesComputed_[stateId+1],stateId,success);
            if(!success)
            {
                throw std::runtime_error ("No contact breaks, hence no intermediate state from state " + std::string(""+(stateId)));
            }
1073
            return contactCone(fullBody_,intermediaryState, friction);
1074
1075
1076
        }
        catch(std::runtime_error& e)
        {
1077
            std::cout << "ERROR " << e.what() << std::endl;
1078
1079
1080
1081
1082
1083
1084
1085
1086
            throw Error(e.what());
        }
    }

    core::PathPtr_t makePath(DevicePtr_t device,
                             const ProblemPtr_t& problem,
                             model::ConfigurationIn_t q1,
                             model::ConfigurationIn_t q2)
    {
Steve Tonneau's avatar
Steve Tonneau committed
1087
        // TODO DT
1088
        return problem->steeringMethod()->operator ()(q1,q2);
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
    }

    model::Configuration_t addRotation(CIT_Configuration& pit, const model::value_type& u,
                              model::ConfigurationIn_t q1, model::ConfigurationIn_t q2,
                              model::ConfigurationIn_t ref)
    {
        model::Configuration_t res = ref;
        res.head(3) = *pit;
        res.segment<4>(3) = tools::interpolate(q1, q2, u);
        return res;
    }

    core::PathVectorPtr_t addRotations(const T_Configuration& positions,
                                       model::ConfigurationIn_t q1, model::ConfigurationIn_t q2,
                                       model::ConfigurationIn_t ref, DevicePtr_t device,
                                       const ProblemPtr_t& problem)
    {
        core::PathVectorPtr_t res = core::PathVector::create(device->configSize(), device->numberDof());
        model::value_type size_step = 1 /(model::value_type)(positions.size());
        model::value_type u = 0.;
        CIT_Configuration pit = positions.begin();
        model::Configuration_t previous = addRotation(pit, 0., q1, q2, ref), current;
        ++pit;
        for(;pit != positions.end()-1; ++pit, u+=size_step)
        {
            current = addRotation(pit, u, q1, q2, ref);
            res->appendPath(makePath(device,problem, previous, current));
            previous = current;
        }
        // last configuration is exactly q2
        current = addRotation(pit, 1., q1, q2, ref);
        res->appendPath(makePath(device,problem, previous, current));
        return res;
    }

1124
   core::PathVectorPtr_t generateTrunkPath(RbPrmFullBodyPtr_t& fullBody, core::ProblemSolverPtr_t problemSolver, const hpp::floatSeqSeq& rootPositions,
Steve Tonneau's avatar
Steve Tonneau committed
1125
1126
1127
1128
1129
                          const model::Configuration_t q1, const model::Configuration_t q2) throw (hpp::Error)
    {
        try
        {
            T_Configuration positions = doubleDofArrayToConfig(3, rootPositions);
1130
1131
            if(positions.size() <2)
            {
1132
                throw std::runtime_error("generateTrunkPath requires at least 2 configurations to generate path");
1133
            }
Steve Tonneau's avatar
Steve Tonneau committed
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
            return addRotations(positions,q1,q2,fullBody->device_->currentConfiguration(),
                                                 fullBody->device_,problemSolver->problem());
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }


1144
    CORBA::Short RbprmBuilder::generateRootPath(const hpp::floatSeqSeq& rootPositions,
1145
1146
1147
1148
1149
                          const hpp::floatSeq& q1Seq, const hpp::floatSeq& q2Seq) throw (hpp::Error)
    {
        try
        {
            model::Configuration_t q1 = dofArrayToConfig(4, q1Seq), q2 = dofArrayToConfig(4, q2Seq);
1150
            return problemSolver_->addPath(generateTrunkPath(fullBody_, problemSolver_, rootPositions, q1, q2));
1151
1152
1153
1154
1155
1156
        }
        catch(std::runtime_error& e)
        {
            throw Error(e.what());
        }
    }
1157

1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
    CORBA::Short RbprmBuilder::generateComTraj(const hpp::floatSeqSeq& positions, const hpp::floatSeqSeq& velocities,
                                          const hpp::floatSeqSeq& accelerations,
                                          const double dt) throw (hpp::Error)
     {
         try
         {
             T_Configuration c = doubleDofArrayToConfig(3, positions);
             T_Configuration cd = doubleDofArrayToConfig(3, velocities);
             T_Configuration cdd = doubleDofArrayToConfig(3, accelerations);
             if(c.size() <2)
             {
                 throw std::runtime_error("generateComTraj requires at least 2 configurations to generate path");
             }
             core::PathVectorPtr_t res = core::PathVector::create(3, 3);
1172
             if(cdd.size() != c.size()-1 || cdd.size() != cd.size())
1173
1174
1175
1176
1177
1178
1179
             {
                 std::cout << c.size() << " " << cd.size() << " " << cdd.size() << std::endl;
                 throw std::runtime_error("in generateComTraj, positions and accelerations vector should have the same size");
             }
             CIT_Configuration cit = c.begin(); ++cit;
             CIT_Configuration cdit = cd.begin();
             CIT_Configuration cddit = cdd.begin();
1180
1181
             int i = 0;
             for(;cit != c.end(); ++cit, ++cdit, ++cddit, ++i)
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
             {
                 res->appendPath(interpolation::ComTrajectory::create(*(cit-1),*cit,*cdit,*cddit,dt));
             }
             return problemSolver_->addPath(res);
         }
         catch(std::runtime_error& e)
         {
             throw Error(e.what());
         }
     }

1193
1194
1195
1196
1197
1198
1199
1200
1201
1202

    floatSeqSeq* RbprmBuilder::computeContactPoints(unsigned short cId) throw (hpp::Error)
    {
        if(lastStatesComputed_.size() <= cId + 1)
        {
            throw std::runtime_error ("Unexisting state " + std::string(""+(cId+1)));
        }
        const State& firstState = lastStatesComputed_[cId], thirdState = lastStatesComputed_[cId+1];
        std::vector<std::vector<fcl::Vec3f> > allStates;
        allStates.push_back(computeRectangleContact(fullBody_, firstState));
1203
1204
1205
1206
        std::vector<std::string> creations;
        bool success(false);
        State intermediaryState = intermediary(firstState, thirdState, cId, success);
        if(success)
1207
        {
1208
            allStates.push_back(computeRectangleContact(fullBody_, intermediaryState));
1209
        }
Steve Tonneau's avatar
rebase    
Steve Tonneau committed
1210
1211
1212
1213
1214
1215
1216
        thirdState.contactCreations(firstState, creations);
        if(creations.size() == 1)
        {
            allStates.push_back(computeRectangleContact(fullBody_, thirdState));
        }
        if(creations.size() > 1)
        {
1217
            throw std::runtime_error ("too many contact creations between states" + std::string(""+cId) + "and " + std::string(""+(cId + 1)));
Steve Tonneau's avatar
rebase    
Steve Tonneau committed
1218
        }
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247

        hpp::floatSeqSeq *res;
        res = new hpp::floatSeqSeq ();

        // compute array of contact positions

        res->length ((_CORBA_ULong)allStates.size());
        std::size_t i=0;
        for(std::vector<std::vector<fcl::Vec3f> >::const_iterator cit = allStates.begin();
                    cit != allStates.end(); ++cit, ++i)
        {
            const std::vector<fcl::Vec3f>& positions = *cit;
            _CORBA_ULong size = (_CORBA_ULong) positions.size () * 3;
            double* dofArray = hpp::floatSeq::allocbuf(size);
            hpp::floatSeq floats (size, size, dofArray, true);
            //convert the config in dofseq
            for(std::size_t h = 0; h<positions.size(); ++h)
            {
                for(std::size_t k =0; k<3; ++k)
                {
                    model::size_type j (h*3 + k);
                    dofArray[j] = positions[h][k];
                }
            }
            (*res) [(_CORBA_ULong)i] = floats;
        }
        return res;
    }

1248
1249
1250
1251
1252
1253
1254
1255
1256
    floatSeqSeq* RbprmBuilder::computeContactPointsForLimb(unsigned short cId, const char *limbName) throw (hpp::Error)
    {
        if(lastStatesComputed_.size() <= cId + 1)
        {
            throw std::runtime_error ("Unexisting state " + std::string(""+(cId+1)));
        }
        std::string limb(limbName);
        const State& firstState = lastStatesComputed_[cId], thirdState = lastStatesComputed_[cId+1];
        std::vector<std::vector<fcl::Vec3f> > allStates;
Steve Tonneau's avatar
Steve Tonneau committed
1257
        allStates.push_back(computeRectangleContact(fullBody_, firstState, limb));
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
        std::vector<std::string> creations;
        bool success(false);
        State intermediaryState = intermediary(firstState, thirdState, cId, success);
        if(success)
        {
            allStates.push_back(computeRectangleContact(fullBody_, intermediaryState, limb));
        }
        thirdState.contactCreations(firstState, creations);
        if(creations.size() == 1)
        {
            allStates.push_back(computeRectangleContact(fullBody_, thirdState, limb));
        }
        if(creations.size() > 1)
        {
1272
            throw std::runtime_error ("too many contact creations between states" + std::string(""+cId) + "and " + std::string(""+(cId + 1)));
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
        }

        hpp::floatSeqSeq *res;
        res = new hpp::floatSeqSeq ();

        // compute array of contact positions

        res->length ((_CORBA_ULong)allStates.size());
        std::size_t i=0;
        for(std::vector<std::vector<fcl::Vec3f> >::const_iterator cit = allStates.begin();
                    cit != allStates.end(); ++cit, ++i)
        {
            const std::vector<fcl::Vec3f>& positions = *cit;
            _CORBA_ULong size = (_CORBA_ULong) positions.size () * 3;
            double* dofArray = hpp::floatSeq::allocbuf(size);
            hpp::floatSeq floats (size, size, dofArray, true);
            //convert the config in dofseq
            for(std::size_t h = 0; h<positions.size(); ++h)
            {
                for(std::size_t k =0; k<3; ++k)
                {
                    model::size_type j (h*3 + k);
                    dofArray[j] = positions[h][k];
                }
            }
            (*res) [(_CORBA_ULong)i] = floats;
        }
        return res;
    }

1303
    floatSeqSeq* RbprmBuilder::interpolate(double timestep, double path, double robustnessTreshold, unsigned short filterStates) throw (hpp::Error)
Steve Tonneau's avatar
Steve Tonneau committed
1304
1305
1306
    {
        try
        {
1307
        unsigned int pathId = int(path);
Steve Tonneau's avatar
Steve Tonneau committed
1308
1309
        if(startState_.configuration_.rows() == 0)
        {
1310
            throw std::runtime_error ("Start state not initialized, cannot interpolate ");
Steve Tonneau's avatar
Steve Tonneau committed
1311
1312
1313
        }
        if(endState_.configuration_.rows() == 0)
        {
1314
            throw std::runtime_error ("End state not initialized, cannot interpolate ");
Steve Tonneau's avatar
Steve Tonneau committed
1315
        }
1316

1317
        if(problemSolver_->paths().size() <= pathId)
Steve Tonneau's avatar
Steve Tonneau committed
1318
1319
1320
        {
            throw std::runtime_error ("No path computed, cannot interpolate ");
        }
1321
        const affMap_t &affMap = problemSolver_->map
1322
					<std::vector<boost::shared_ptr<model::CollisionObject> > > ();
1323
1324
1325
1326
        if (affMap.empty ())
        {
            throw hpp::Error ("No affordances found. Unable to interpolate.");
        }
Steve Tonneau's avatar
Steve Tonneau committed
1327

Akseppal's avatar
Akseppal committed
1328
1329
        hpp::rbprm::interpolation::RbPrmInterpolationPtr_t interpolator = 
					rbprm::interpolation::RbPrmInterpolation::create(fullBody_,startState_,endState_,problemSolver_->paths()[pathId]);
1330
        lastStatesComputedTime_ = interpolator->Interpolate(affMap, bindShooter_.affFilter_,
1331
                    timestep,robustnessTreshold, filterStates != 0);
1332
		lastStatesComputed_ = TimeStatesToStates(lastStatesComputedTime_);
Steve Tonneau's avatar
Steve Tonneau committed
1333
1334
1335
1336

        hpp::floatSeqSeq *res;
        res = new hpp::floatSeqSeq ();

1337
        res->length ((_CORBA_ULong)lastStatesComputed_.size ());
Steve Tonneau's avatar
Steve Tonneau committed
1338
        std::size_t i=0;