pathplayer.cc 13.5 KB
Newer Older
Joseph Mirabel's avatar
Joseph Mirabel committed
1
#include "hppwidgetsplugin/pathplayer.hh"
Joseph Mirabel's avatar
Joseph Mirabel committed
2

3
4
5
6
7
8
9
#include <QDoubleSpinBox>
#include <QFileDialog>
#include <QTextBrowser>
#include <QProgressDialog>
#include <QPushButton>
#include <QSpinBox>
#include <QSlider>
Joseph Mirabel's avatar
Joseph Mirabel committed
10
11
12
13
14
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
# include <QtCore>
#else
# include <QtConcurrent>
#endif
15

Joseph Mirabel's avatar
Joseph Mirabel committed
16
17
18
#include <hpp/corbaserver/common.hh>
#include <hpp/corbaserver/client.hh>

19
20
21
#include "gepetto/gui/mainwindow.hh"
#include <gepetto/gui/windows-manager.hh>
#include <gepetto/gui/osgwidget.hh>
Joseph Mirabel's avatar
Joseph Mirabel committed
22
#include <gepetto/gui/action-search-bar.hh>
Joseph Mirabel's avatar
Joseph Mirabel committed
23

24
#include "hppwidgetsplugin/conversions.hh"
25
#include "hppwidgetsplugin/ui_pathplayerwidget.h"
Joseph Mirabel's avatar
Joseph Mirabel committed
26
#include "hppwidgetsplugin/joint-action.hh"
27
#include <hppwidgetsplugin/hppwidgetsplugin.hh>
28

Joseph Mirabel's avatar
Joseph Mirabel committed
29
30
namespace hpp {
  namespace gui {
Joseph Mirabel's avatar
Joseph Mirabel committed
31
32
33
    using gepetto::gui::MainWindow;
    using gepetto::gui::ActionSearchBar;

Joseph Mirabel's avatar
Joseph Mirabel committed
34
35
36
    PathPlayer::PathPlayer (HppWidgetsPlugin *plugin, QWidget *parent) :
      QWidget (parent)
      , ui_ (new ::Ui::PathPlayerWidget)
37
      , timerId_ (0)
Joseph Mirabel's avatar
Joseph Mirabel committed
38
      , velocity_ (false)
Joseph Mirabel's avatar
Joseph Mirabel committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
      , process_ (new QProcess (this))
      , showPOutput_ (new QDialog (this, Qt::Dialog | Qt::WindowCloseButtonHint | Qt::WindowMinMaxButtonsHint))
      , pOutput_ (new QTextBrowser())
      , plugin_ (plugin)
    {
      ui_->setupUi (this);
      pathIndex()->setMaximum(0);
      connect (pathSlider(), SIGNAL (sliderMoved (int)), this, SLOT (pathSliderChanged(int)));
      connect (pathIndex(), SIGNAL (valueChanged(int)), this, SLOT (pathIndexChanged(int)));
      connect (playPause(), SIGNAL (toggled (bool)), this, SLOT (playPauseToggled(bool)));
      connect (stop(), SIGNAL (clicked()), this, SLOT (stopClicked()));
      connect (record(), SIGNAL (toggled(bool)), this, SLOT (recordToggled(bool)));
      connect (ui_->refreshButton_path, SIGNAL (clicked()), this, SLOT (update()));

      process_->setProcessChannelMode(QProcess::MergedChannels);
      connect (process_, SIGNAL (readyReadStandardOutput ()), SLOT (readyReadProcessOutput()));

      showPOutput_->setModal(false);
      showPOutput_->setLayout(new QHBoxLayout ());
      showPOutput_->layout()->addWidget(pOutput_);
Joseph Mirabel's avatar
Joseph Mirabel committed
59
60

      initSearchActions();
Joseph Mirabel's avatar
Joseph Mirabel committed
61
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
62
63
64
65
66
67
68
69
70

    PathPlayer::~PathPlayer()
    {
      if (process_ != NULL) {
        if (process_->state() == QProcess::Running)
          process_->kill();
        delete process_;
      }
      delete ui_;
Joseph Mirabel's avatar
Joseph Mirabel committed
71
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
72

Joseph Mirabel's avatar
Joseph Mirabel committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    void PathPlayer::initSearchActions()
    {
      ActionSearchBar* asb = MainWindow::instance()->actionSearchBar();
      JointAction* a;

      a = new JointAction (tr("Display &waypoints of selected path"), plugin_->jointTreeWidget(), this);
      connect (a, SIGNAL (triggered(std::string)), SLOT (displayWaypointsOfPath(std::string)));
      asb->addAction(a);

      a = new JointAction (tr("Display selected &path"), plugin_->jointTreeWidget(), this);
      connect (a, SIGNAL (triggered(std::string)), SLOT (displayPath(std::string)));
      asb->addAction(a);
    }

Joseph Mirabel's avatar
Joseph Mirabel committed
87
88
    void PathPlayer::displayWaypointsOfPath(const std::string jointName)
    {
89
      gepetto::gui::MainWindow* main = gepetto::gui::MainWindow::instance();
Joseph Mirabel's avatar
Joseph Mirabel committed
90
91
92
93
94
95
96
      if (!pathIndex()->isEnabled()) {
        main->logError("There is no path. Did you solve a problem ?");
        return;
      }
      int pid = pathIndex()->value();
      std::stringstream ss; ss << "path" << pid << "_" << jointName;
      std::string pn = ss.str();
97
98
      const osgVector4 colorN (0.f, 0.f, 1.f, 1.f),
                       colorE (1.f, 0.f, 0.f, 1.f);
99
      gepetto::gui::WindowsManagerPtr_t wsm = main->osg();
Joseph Mirabel's avatar
Joseph Mirabel committed
100
      HppWidgetsPlugin::HppClient* hpp = plugin_->client();
101
      hpp::floatSeq_var times;
102
      hpp::floatSeqSeq_var waypoints = hpp->problem()->getWaypoints((CORBA::ULong)pid, times.out());
Joseph Mirabel's avatar
Joseph Mirabel committed
103
104
105
106
      if (!wsm->getGroup(pn, false)) {
        wsm->createGroup (pn);
        wsm->addToGroup(pn, "hpp-gui");
      }
Joseph Mirabel's avatar
Joseph Mirabel committed
107
      hpp::floatSeq_var curCfg = hpp->robot()->getCurrentConfig();
108
109
      graphics::Configuration pos;
      osgVector3 pos1, pos2;
Joseph Mirabel's avatar
Joseph Mirabel committed
110
      for (unsigned int i = 0; i < waypoints->length(); ++i) {
111
112
113
114
        // Make name
        ss.clear(); ss.str(std::string()); ss << pn << "/node" << i;
        std::string xyzName = ss.str();
        // Get positions
Joseph Mirabel's avatar
Joseph Mirabel committed
115
        hpp->robot()->setCurrentConfig(waypoints[i]);
Joseph Mirabel's avatar
Joseph Mirabel committed
116
        hpp::Transform__var t = hpp->robot()->getJointPosition(jointName.c_str());
117
        fromHPP(t, pos);
118
119
        pos1 = pos2; pos2 = pos.position;
        // Create the nodes
Joseph Mirabel's avatar
Joseph Mirabel committed
120
121
        if (wsm->nodeExists(xyzName)) wsm->deleteNode(xyzName, false);
        wsm->addXYZaxis(xyzName, colorN, 0.01f, 0.05f);
122
        wsm->applyConfiguration(xyzName, pos);
Joseph Mirabel's avatar
Joseph Mirabel committed
123
        if  (i > 0) {
124
125
          xyzName.replace(pn.length() + 1, 4, "edge");
          qDebug () << xyzName.c_str();
Joseph Mirabel's avatar
Joseph Mirabel committed
126
          if (wsm->nodeExists(xyzName)) wsm->deleteNode(xyzName, false);
127
          wsm->addLine(xyzName, pos1, pos2, colorE);
128
        }
Joseph Mirabel's avatar
Joseph Mirabel committed
129
130
131
      }
      hpp->robot()->setCurrentConfig(curCfg.in());
      wsm->refresh();
132
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
133
134
135
136
137
138
139
140
141
142
143
144

    void PathPlayer::displayPath(const std::string jointName)
    {
      QFutureWatcher <void>* fw = new QFutureWatcher<void>(this);
      QProgressDialog* pd = new QProgressDialog ("Computing curved path. Please wait...", "Cancel", 0, 100, this);
      connect(this, SIGNAL(displayPath_status(int)), pd, SLOT (setValue(int)));
      pd->setCancelButton(0);
      pd->setRange(0, 100);
      pd->show();
      fw->setFuture(QtConcurrent::run (this, &PathPlayer::displayPath_impl, jointName));
      connect (fw, SIGNAL (finished()), pd, SLOT (deleteLater()));
      connect (fw, SIGNAL (finished()), fw, SLOT (deleteLater()));
Joseph Mirabel's avatar
Joseph Mirabel committed
145
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
146
147
148

    void PathPlayer::displayPath_impl(const std::string jointName)
    {
149
      gepetto::gui::MainWindow* main = gepetto::gui::MainWindow::instance();
Joseph Mirabel's avatar
Joseph Mirabel committed
150
151
152
153
154
      if (!pathIndex()->isEnabled()) {
        main->logError("There is no path. Did you solve a problem ?");
        emit displayPath_status(100);
        return;
      }
155
      CORBA::ULong pid = (CORBA::ULong) pathIndex()->value();
Joseph Mirabel's avatar
Joseph Mirabel committed
156
157
      std::stringstream ss; ss << "curvedpath_" << pid << "_" << jointName;
      std::string pn = ss.str();
158
      graphics::WindowsManager::Color_t colorE (1.f, 0.f, 0.f, 1.f);
159
      gepetto::gui::WindowsManagerPtr_t wsm = main->osg();
Joseph Mirabel's avatar
Joseph Mirabel committed
160
161
162
163
      HppWidgetsPlugin::HppClient* hpp = plugin_->client();
      hpp::floatSeq_var curCfg = hpp->robot()->getCurrentConfig();
      CORBA::Double length = hpp->problem()->pathLength(pid);
      double dt = lengthBetweenRefresh();
164
165
      CORBA::ULong nbPos = (CORBA::ULong)(length / dt) + 1;
      ::osg::Vec3ArrayRefPtr posSeq = new ::osg::Vec3Array;
Joseph Mirabel's avatar
Joseph Mirabel committed
166
167
      float statusStep = 100.f / (float) nbPos;
      emit displayPath_status(0);
168
      for (CORBA::ULong i = 0; i < nbPos; ++i) {
Joseph Mirabel's avatar
Joseph Mirabel committed
169
170
171
        double t = std::min (i * dt, length);
        hpp::floatSeq_var q = hpp->problem()->configAtParam(pid, t);
        hpp->robot()->setCurrentConfig(q);
172
        hpp::Transform__var transform = hpp->robot()->getJointPosition(jointName.c_str());
173
174
        const hpp::Transform__slice* tt = transform.in();
        posSeq->push_back(::osg::Vec3 ((float)tt[0],(float)tt[1],(float)tt[2]));
Joseph Mirabel's avatar
Joseph Mirabel committed
175
176
        emit displayPath_status(qFloor ((float)i * statusStep));
      }
177
      if (wsm->nodeExists(pn)) wsm->deleteNode (pn, true);
178
      wsm->addCurve(pn, posSeq, colorE);
Joseph Mirabel's avatar
Joseph Mirabel committed
179
180
181
182
      hpp->robot()->setCurrentConfig(curCfg.in());
      wsm->addToGroup(pn.c_str(), "hpp-gui");
      wsm->refresh();
      emit displayPath_status (100);
Joseph Mirabel's avatar
Joseph Mirabel committed
183
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
184
185

    void PathPlayer::update ()
Joseph Mirabel's avatar
Joseph Mirabel committed
186
    {
187
      CORBA::Long nbPath = plugin_->client()->problem ()->numberPaths ();
Joseph Mirabel's avatar
Joseph Mirabel committed
188
189
190
191
192
193
194
      if (nbPath > 0)
      {
        pathIndex()->setEnabled(true);
        pathSlider()->setEnabled(true);
        playPause()->setEnabled(true);
        stop()->setEnabled(true);
        if (pathIndex()->maximum() == 0) {
Joseph Mirabel's avatar
Joseph Mirabel committed
195
196
197
          // If path index value is 0, no signal valueChanged will
          // be emitted. Force a value changed.
          if (pathIndex()->value() == 0)
198
            pathIndexChanged(0);
Joseph Mirabel's avatar
Joseph Mirabel committed
199
        }
Joseph Mirabel's avatar
Joseph Mirabel committed
200
        pathIndex()->setMaximum(nbPath - 1);
201
	pathIndex()->setValue(nbPath - 1);
Joseph Mirabel's avatar
Joseph Mirabel committed
202
203
204
205
206
207
208
209
210
      }
      else {
        pathIndex()->setEnabled(false);
        pathSlider()->setEnabled(false);
        playPause()->setEnabled(false);
        stop()->setEnabled(false);
      }
    }

Joseph Mirabel's avatar
Joseph Mirabel committed
211
212
213
214
215
    void PathPlayer::setRobotVelocity (bool set)
    {
      velocity_ = set;
    }

Joseph Mirabel's avatar
Joseph Mirabel committed
216
217
218
219
220
221
222
223
224
225
226
227
    void PathPlayer::pathIndexChanged(int i)
    {
      assert (i >= 0);
      pathLength_ = plugin_->client()->problem()->pathLength ((short unsigned int)i);
      currentParam_= 0;
    }

    void PathPlayer::pathSliderChanged(int value)
    {
      // The user moved the slider manually.
      currentParam_ = sliderToLength(value);
      updateConfiguration();
Joseph Mirabel's avatar
Joseph Mirabel committed
228
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
229
230
231

    void PathPlayer::playPauseToggled(bool toggled)
    {
232
233
234
235
236
237
      if (toggled) {
        if (timerId_ == 0) timerId_ = startTimer(timeBetweenRefresh());
      } else {
        killTimer(timerId_);
        timerId_ = 0;
      }
238
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
239
240
241
242
243
244
245
246
247
248
249
250
251

    void PathPlayer::stopClicked()
    {
      // Pause
      playPause()->setChecked(false);
      // Reset current position.
      currentParam_ = 0;
      pathSlider()->setSliderPosition(0);
      updateConfiguration();
    }

    void PathPlayer::recordToggled(bool toggled)
    {
252
      gepetto::gui::MainWindow* main = gepetto::gui::MainWindow::instance();
Joseph Mirabel's avatar
Joseph Mirabel committed
253
254
255
256
      if (toggled) {
        QDir tmp ("/tmp");
        tmp.mkpath ("hpp-gui/record"); tmp.cd("hpp-gui/record");
        foreach (QString f, tmp.entryList(QStringList() << "img_0_*.jpeg", QDir::Files))
Joseph Mirabel's avatar
Joseph Mirabel committed
257
          tmp.remove(f);
Joseph Mirabel's avatar
Joseph Mirabel committed
258
259
260
        QString path = tmp.absoluteFilePath("img");
        QString ext = "jpeg";
        main->osg ()->startCapture(
Joseph Mirabel's avatar
Joseph Mirabel committed
261
262
263
            main->centralWidget()->windowID(),
            path.toLocal8Bit().data(),
            ext.toLocal8Bit().data());
Joseph Mirabel's avatar
Joseph Mirabel committed
264
265
266
267
268
        main->log("Saving images to " + path + "_*." + ext);
      } else {
        main->osg()->stopCapture(main->centralWidget()->windowID());
        QString outputFile = QFileDialog::getSaveFileName(this, tr("Save video to"), "untitled.mp4");
        if (!outputFile.isNull()) {
Joseph Mirabel's avatar
Joseph Mirabel committed
269
          if (QFile::exists(outputFile))
Joseph Mirabel's avatar
Joseph Mirabel committed
270
            QFile::remove(outputFile);
Joseph Mirabel's avatar
Joseph Mirabel committed
271
272
273
274
275
          QString avconv = "avconv";

          QStringList args;
          QString input = "/tmp/hpp-gui/record/img_0_%d.jpeg";
          args << "-r" << "50"
Joseph Mirabel's avatar
Joseph Mirabel committed
276
277
278
279
280
            << "-i" << input
            << "-vf" << "scale=trunc(iw/2)*2:trunc(ih/2)*2"
            << "-r" << "25"
            << "-vcodec" << "libx264"
            << outputFile;
Joseph Mirabel's avatar
Joseph Mirabel committed
281
282
283
284
285
286
287
288
          qDebug () << args;

          showPOutput_->setWindowTitle(avconv + " " + args.join(" "));
          pOutput_->clear();
          showPOutput_->resize(main->size() / 2);
          showPOutput_->show();
          process_->start(avconv, args);
        }
Joseph Mirabel's avatar
Joseph Mirabel committed
289
      }
Joseph Mirabel's avatar
Joseph Mirabel committed
290
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
291
292
293
294
295
296
297

    void PathPlayer::pathPulse()
    {
      if (playPause()->isChecked()) {
        // Stil playing
        currentParam_ += lengthBetweenRefresh();
        if (currentParam_ > pathLength_) {
Joseph Mirabel's avatar
Joseph Mirabel committed
298
          currentParam_ = pathLength_;
Joseph Mirabel's avatar
Joseph Mirabel committed
299
300
          playPause()->setChecked(false);
        }
Joseph Mirabel's avatar
Joseph Mirabel committed
301
302
303
304
305
        pathSlider()->setSliderPosition(lengthToSlider(currentParam_));
        updateConfiguration();
      }
    }

Joseph Mirabel's avatar
Joseph Mirabel committed
306
307
308
309
310
311
312
313
314
315
316
317
    void PathPlayer::setCurrentTime (const double& param)
    {
      if (!pathIndex()->isEnabled()) return;
      if (currentParam_ > pathLength_)
        currentParam_ = pathLength_;
      if (0 < currentParam_)
        currentParam_ = 0;
      currentParam_ = param;
      pathSlider()->setSliderPosition(lengthToSlider(currentParam_));
      updateConfiguration();
    }

Joseph Mirabel's avatar
Joseph Mirabel committed
318
319
320
321
322
323
324
325
326
327
    void PathPlayer::timerEvent(QTimerEvent *event)
    {
      if (timerId_ == event->timerId()) {
        pathPulse();
      }
    }

    void PathPlayer::readyReadProcessOutput()
    {
      pOutput_->append(process_->readAll());
Joseph Mirabel's avatar
Joseph Mirabel committed
328
329
    }

Joseph Mirabel's avatar
Joseph Mirabel committed
330
331
332
    void PathPlayer::updateConfiguration ()
    {
      hpp::floatSeq_var config =
333
        plugin_->client()->problem()->configAtParam ((CORBA::ULong)pathIndex()->value(),currentParam_);
Joseph Mirabel's avatar
Joseph Mirabel committed
334
      plugin_->client()->robot()->setCurrentConfig (config.in());
Joseph Mirabel's avatar
Joseph Mirabel committed
335
336
      if (velocity_) {
        config =
337
          plugin_->client()->problem()->velocityAtParam ((CORBA::ULong)pathIndex()->value(),currentParam_);
Joseph Mirabel's avatar
Joseph Mirabel committed
338
339
        plugin_->client()->robot()->setCurrentVelocity (config.in());
      }
340
      gepetto::gui::MainWindow::instance()->requestApplyCurrentConfiguration();
341
      emit appliedConfigAtParam (getCurrentPath(), currentParam_);
Joseph Mirabel's avatar
Joseph Mirabel committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
    }

    inline double PathPlayer::sliderToLength(int v) const
    {
      return ((double)v / (double)pathSlider()->maximum()) * pathLength_;
    }

    int PathPlayer::lengthToSlider(double l) const
    {
      return (int) (pathSlider()->maximum() * l / pathLength_);
    }

    inline double PathPlayer::timeToLength(double time) const
    {
      return time * pathLength_ / timeSpinBox()->value();
    }

    inline int PathPlayer::timeBetweenRefresh() const
    {
Joseph Mirabel's avatar
Joseph Mirabel committed
361
362
      gepetto::gui::MainWindow* main = gepetto::gui::MainWindow::instance();
      return main->settings_->refreshRate;
Joseph Mirabel's avatar
Joseph Mirabel committed
363
364
365
366
    }

    double PathPlayer::lengthBetweenRefresh() const
    {
Joseph Mirabel's avatar
Joseph Mirabel committed
367
      return pathLength_ * timeBetweenRefresh() / (1000 * timeSpinBox()->value());
Joseph Mirabel's avatar
Joseph Mirabel committed
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
    }

    QDoubleSpinBox *PathPlayer::timeSpinBox() const
    {
      return ui_->timeSpinBox;
    }

    QSpinBox *PathPlayer::pathIndex() const
    {
      return ui_->pathIndexSpin;
    }

    QSlider *PathPlayer::pathSlider() const
    {
      return ui_->pathSlider;
    }

    QPushButton *PathPlayer::playPause() const
    {
      return ui_->playPauseButton;
    }

    QPushButton *PathPlayer::stop() const
    {
      return ui_->stopButton;
    }

    QPushButton *PathPlayer::record() const
    {
      return ui_->recordButton;
Joseph Mirabel's avatar
Joseph Mirabel committed
398
    }
399
400
401

    int	PathPlayer::getCurrentPath() const
    {
Joseph Mirabel's avatar
Joseph Mirabel committed
402
      if (!pathIndex()->isEnabled()) return -1;
403
404
      return pathIndex()->value();
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
405
406
  } // namespace gui
} // namespace hpp