SkeletalAnimationPlugin.cc 34.4 KB
Newer Older
1 2 3
/*===========================================================================*\
*                                                                            *
*                              OpenFlipper                                   *
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
39 40 41
*                                                                            *
\*===========================================================================*/

Jan Möbius's avatar
Jan Möbius committed
42

Dirk Wilden's avatar
Dirk Wilden committed
43
#include "SkeletalAnimationPlugin.hh"
44 45

#include <ObjectTypes/Skeleton/Skeleton.hh>
Dirk Wilden's avatar
Dirk Wilden committed
46 47 48
#include <ObjectTypes/Skeleton/SkeletonObjectData.hh>
#include <ObjectTypes/Skeleton/SkinT.hh>

Jan Möbius's avatar
Jan Möbius committed
49 50 51 52 53

#include <QInputDialog>
#include <QMessageBox>

#include "dialogs/AnimationToolbox.hh"
Jan Möbius's avatar
Jan Möbius committed
54
#include "dialogs/AddAnimationDialog.hh"
Dirk Wilden's avatar
Dirk Wilden committed
55 56 57 58 59

using namespace std;

//------------------------------------------------------------------------------

Jan Möbius's avatar
Jan Möbius committed
60 61 62 63 64 65 66 67 68 69 70 71 72
/** \brief Constructor
 *
 */
SkeletalAnimationPlugin::SkeletalAnimationPlugin() :
        pToolbox_(0),
        toolIcon_(0),
        bGuiUpdating_(false),
        animationOffset_(0)
{
}

//------------------------------------------------------------------------------

Dirk Wilden's avatar
Dirk Wilden 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 97 98 99 100 101 102 103
/** \brief returns the plugin name
 *
 */
QString SkeletalAnimationPlugin::name()
{
  return "SkeletalAnimation";
}

//------------------------------------------------------------------------------

/** \brief returns a plugin description
 *
 */
QString SkeletalAnimationPlugin::description()
{
  return "Plugin to control skeletal animations";
}

//------------------------------------------------------------------------------

/** \brief initialize the plugin
 *
 */
void SkeletalAnimationPlugin::initializePlugin()
{
  bGuiUpdating_ = false;

  pToolbox_ = new AnimationToolboxWidget();
  QSize size(300, 300);
  pToolbox_->resize(size);

Dirk Wilden's avatar
Dirk Wilden committed
104 105
  connect( pToolbox_->pbAttachSkin, SIGNAL(clicked()), this, SLOT(slotAttachSkin()) );
  connect( pToolbox_->pbClearSkins, SIGNAL(clicked()), this, SLOT(slotClearSkins()) );
Dirk Wilden's avatar
Dirk Wilden committed
106 107 108 109 110 111 112 113 114

  connect( pToolbox_->cbAnimation,                SIGNAL(currentIndexChanged(int)), this, SLOT(slotAnimationIndexChanged(int)) );
  connect( pToolbox_->hsFrame,                    SIGNAL(valueChanged(int)),        this, SLOT(slotFrameChanged(int)) );
  connect( pToolbox_->pbPlay,                     SIGNAL(clicked()),                this, SLOT( playAnimation() ) );
  connect( pToolbox_->pbStop,                     SIGNAL(clicked()),                this, SLOT( stopAnimation() ) );
  connect( pToolbox_->pbPrevFrame,                SIGNAL(clicked()),                this, SLOT( prevFrame() ) );
  connect( pToolbox_->pbNextFrame,                SIGNAL(clicked()),                this, SLOT( nextFrame() ) );
  connect( pToolbox_->sbFPS,                      SIGNAL(valueChanged ( int )),     this, SLOT( changeFPS(int) ) );
  connect( pToolbox_->cbSkipFrames,               SIGNAL(stateChanged(int)),        this, SLOT(slotSkipFramesChanged(int)) );
Dirk Wilden's avatar
Dirk Wilden committed
115
  connect( pToolbox_->pbAddAnimation,             SIGNAL(clicked()),                this, SLOT(slotAddAnimation()) );
116
  connect( pToolbox_->pbDeleteAnimation,          SIGNAL(clicked()),                this, SLOT(slotDeleteAnimation()) );
Dirk Wilden's avatar
Dirk Wilden committed
117
  
118 119
  connect( pToolbox_->pbEditAnimation, SIGNAL(clicked()), this, SLOT(slotAnimationNameChanged()));

Dirk Wilden's avatar
Dirk Wilden committed
120
  pToolbox_->pbAddAnimation->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"addAnimation.png") );
121
  pToolbox_->pbDeleteAnimation->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"deleteAnimation.png") );
122
  pToolbox_->pbEditAnimation->setIcon(QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"editAnimation.png") );
Dirk Wilden's avatar
Dirk Wilden committed
123
  
Dirk Wilden's avatar
Dirk Wilden committed
124 125 126 127 128
  pToolbox_->cbMethod->addItem("Linear Blend Skinning");
  pToolbox_->cbMethod->addItem("Dual Quaternion Blend Skinning");

  pToolbox_->cbMethod->setCurrentIndex(0);
  connect( pToolbox_->cbMethod, SIGNAL(currentIndexChanged(int)), this, SLOT(slotMethodChanged(int)) );
129
  method_ = Blending::M_LBS;
Dirk Wilden's avatar
Dirk Wilden committed
130

Dirk Wilden's avatar
Dirk Wilden committed
131 132
  toolIcon_ = new QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"skeletalAnimation.png");
  emit addToolbox( tr("Skeletal Animation") , pToolbox_, toolIcon_ );
Dirk Wilden's avatar
Dirk Wilden committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
}

//------------------------------------------------------------------------------

/** \brief final initializations
 *
 */
void SkeletalAnimationPlugin::pluginsInitialized()
{
  emit setDescriptions();
}

//------------------------------------------------------------------------------

/** \brief Plugin gets closed
 *
 */
void SkeletalAnimationPlugin::exit()
{
}

//------------------------------------------------------------------------------

/** \brief clear all occurred
 *
 */
void SkeletalAnimationPlugin::slotAllCleared()
{
  activeSkeletons_.clear();

  slotAnimationIndexChanged(0);
}

//------------------------------------------------------------------------------

/** \brief Update ui when the object selection changes
 *
 */
171
void SkeletalAnimationPlugin::slotObjectSelectionChanged(int _id)
Dirk Wilden's avatar
Dirk Wilden committed
172
{
173
  checkObjectSelection(_id);
Dirk Wilden's avatar
Dirk Wilden committed
174 175 176 177 178 179 180
}

//------------------------------------------------------------------------------

/** \brief Update ui when the object is loaded
 *
 */
181 182
void SkeletalAnimationPlugin::fileOpened( int _id) {
  checkObjectSelection(_id);
Dirk Wilden's avatar
Dirk Wilden committed
183 184 185 186 187 188 189
}

//------------------------------------------------------------------------------

/** \brief Update ui when the object is added
 *
 */
190 191 192
void SkeletalAnimationPlugin::addedEmptyObject(int _id) {

  checkObjectSelection(_id);
Dirk Wilden's avatar
Dirk Wilden committed
193 194 195 196 197 198 199
}

//------------------------------------------------------------------------------

/** \brief Update ui when the object is deleted
 *
 */
200 201
void SkeletalAnimationPlugin::objectDeleted(int _id) {

202
    checkObjectSelection(_id);
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

    // Check for skin that is to be cleared
    BaseObjectData* bod = 0;
    if (!PluginFunctions::getObject(_id, bod)) {
        return;
    }

    if (bod->hasObjectData(OBJECTDATA_SKIN)) {

        BaseSkin* baseSkin = 0;

        if (bod->dataType(DATA_TRIANGLE_MESH))
            baseSkin = dynamic_cast<BaseSkin*> (bod->objectData(OBJECTDATA_SKIN));
        else if (bod->dataType(DATA_POLY_MESH))
            baseSkin = dynamic_cast<BaseSkin*> (bod->objectData(OBJECTDATA_SKIN));

        if (baseSkin) {
            BaseObjectData* skeletonObj = PluginFunctions::skeletonObject(baseSkin->skeletonId());

            if(skeletonObj) {
                // Detach skin  from skeleton
                detachSkin(bod, skeletonObj);
            }
        }
    }
Dirk Wilden's avatar
Dirk Wilden committed
228 229 230 231 232 233 234
}

//------------------------------------------------------------------------------

/** \brief Check source/target selection of objects
 *
 */
235
void SkeletalAnimationPlugin::checkObjectSelection(const int _objectId){
Dirk Wilden's avatar
Dirk Wilden committed
236

237 238
  BaseObject* object;
  PluginFunctions::getObject(_objectId,object);
Dirk Wilden's avatar
Dirk Wilden committed
239

240 241 242
  if ( !object ) {
    std::cerr << "SkeletalAnimationPlugin::checkObjectSelection : unable to get object! " << std::endl;
    return;
Dirk Wilden's avatar
Dirk Wilden committed
243 244
  }

245 246
  if ( object->dataType() == DataType(DATA_SKELETON) ) {
    activeSkeletons_.clear();
Dirk Wilden's avatar
Dirk Wilden committed
247

248 249 250 251 252 253 254 255 256 257 258 259
    // get target skeletons
    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::TARGET_OBJECTS, DataType(DATA_SKELETON)) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
      activeSkeletons_.push_back( o_it->id() );

    // if no target skeleton there check if there is only one skeleton
    if ( activeSkeletons_.empty() ){
      for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::ALL_OBJECTS, DataType(DATA_SKELETON)) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
        activeSkeletons_.push_back( o_it->id() );

      if (activeSkeletons_.size() != 1)
        activeSkeletons_.clear();
    }
Dirk Wilden's avatar
Dirk Wilden committed
260 261 262 263 264 265 266 267

  }

  UpdateUI();
}

//------------------------------------------------------------------------------

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
void SkeletalAnimationPlugin::slotAnimationNameChanged() {

    if(pToolbox_->cbAnimation->currentText() == "Reference Pose") {

        QMessageBox::warning(0, "Not editable!", "You cannot change the reference pose's name!");
        return;
    }

    QString newName = QInputDialog::getText(0, tr("Change Animation's Name"), tr("New Name:"),
            QLineEdit::Normal, pToolbox_->cbAnimation->currentText());

    // Set animation's name
    for (unsigned int i=0; i < activeSkeletons_.size(); i++){

        // Get active skeleton
        BaseObjectData* baseObject = 0;
        PluginFunctions::getObject(activeSkeletons_[i], baseObject);

        if ( baseObject == 0 )
          continue;

        SkeletonObject* skeletonObject = dynamic_cast<SkeletonObject*>(baseObject);
        if(!skeletonObject) continue;
        Skeleton*             skeleton = PluginFunctions::skeleton(skeletonObject);
292
        if(!skeleton) continue;
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

        AnimationHandle h = skeleton->animationHandle(pToolbox_->cbAnimation->currentText().toStdString());
        if(skeleton != 0 && h.isValid()) {
            skeleton->animation(h)->setName(newName.toStdString());
            skeleton->replaceAnimationName(pToolbox_->cbAnimation->currentText().toStdString(), newName.toStdString());
        } else {
            return;
        }
    }

    pToolbox_->cbAnimation->setItemText(pToolbox_->cbAnimation->currentIndex(), newName);
}

//------------------------------------------------------------------------------

Dirk Wilden's avatar
Dirk Wilden committed
308 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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
/**
 * @brief Returns the number of frames in the currently active animation
 */
int SkeletalAnimationPlugin::getNumberOfFrames()
{

  for (unsigned int i=0; i < activeSkeletons_.size(); i++){

    //get active skeleton
    BaseObjectData* baseObject = 0;
    PluginFunctions::getObject(activeSkeletons_[i], baseObject);

    if ( baseObject == 0 )
      continue;

    SkeletonObject* skeletonObject = dynamic_cast<SkeletonObject*>(baseObject);
    Skeleton*             skeleton = PluginFunctions::skeleton(skeletonObject);

    if(skeleton != 0 && skeleton->animation( currentAnimationHandle() ) != 0)
      return skeleton->animation( currentAnimationHandle() )->frameCount();
  }

  return 0;
}

//------------------------------------------------------------------------------

/**
 * @brief Displays the given frame from the current animation and updates the view
 */
void SkeletalAnimationPlugin::setFrame(int _iFrame)
{
  pToolbox_->hsFrame->setValue(_iFrame);
}

//------------------------------------------------------------------------------

/**
 * @brief Gets the current frame number
 */
int SkeletalAnimationPlugin::getFrame() {
  return pToolbox_->hsFrame->value();
}

//------------------------------------------------------------------------------

/**
 * @brief Change the frames per second (FPS)
 */
void SkeletalAnimationPlugin::changeFPS(int _fps) {
  pToolbox_->sbFPS->blockSignals(true);
  pToolbox_->sbFPS->setValue(_fps);
  pToolbox_->sbFPS->blockSignals(false);

  animationTimer_.setInterval(1000/_fps);
}

//------------------------------------------------------------------------------

/**
 * @brief Changes the mesh's pose to represent the frame given by the animation handle
 *
370 371
 * @param _skeletonObject The object holding the skeleton, it is holding the pointer to the skin object
 * @param _hAni           A handle of the new animation/pose
Dirk Wilden's avatar
Dirk Wilden committed
372
 */
Dirk Wilden's avatar
Dirk Wilden committed
373
void SkeletalAnimationPlugin::UpdateSkins(BaseObjectData *_skeletonObject, AnimationHandle &_hAni)
Dirk Wilden's avatar
Dirk Wilden committed
374
{
Dirk Wilden's avatar
Dirk Wilden committed
375 376 377 378 379 380 381
  
  if( !_skeletonObject->hasObjectData(OBJECTDATA_SKELETON) )
    return;

  SkeletonObjectData* skeletonData = dynamic_cast< SkeletonObjectData* >( _skeletonObject->objectData(OBJECTDATA_SKELETON) );
  
  for (unsigned int i=0; i < skeletonData->skinCount(); i++){
382 383

    // deform all attached skin meshes
Dirk Wilden's avatar
Dirk Wilden committed
384 385 386 387 388 389 390 391 392 393 394
    int meshId = skeletonData->skin(i);

    BaseObjectData* object = 0;
    PluginFunctions::getObject(meshId, object);
    
    if (object == 0)
      continue;

    if ( !object->hasObjectData(OBJECTDATA_SKIN) ){
      emit log(LOGERR, tr("Error: Attached skin mesh has no skin-object-data."));
      continue;
Dirk Wilden's avatar
Dirk Wilden committed
395
    }
Dirk Wilden's avatar
Dirk Wilden committed
396 397 398 399 400
    
    BaseSkin* skin = dynamic_cast< BaseSkin* > ( object->objectData(OBJECTDATA_SKIN) );
    skin->deformSkin(_hAni, method_ );

    emit updatedObject(object->id(), UPDATE_GEOMETRY);
Dirk Wilden's avatar
Dirk Wilden committed
401 402 403 404 405 406 407 408
  }
}

//------------------------------------------------------------------------------

/**
 * @brief Check activePose if a skeleton was updated
 */
409
void SkeletalAnimationPlugin::slotObjectUpdated( int _id, const UpdateType& /*_type*/ )
Dirk Wilden's avatar
Dirk Wilden committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
{
  // do nothing during animation
  if ( animationTimer_.isActive() )
    return;
  
  BaseObjectData* obj = 0;
  
  PluginFunctions::getObject(_id, obj);
  
  if ( (obj != 0)  && (obj->dataType(DATA_SKELETON)) ){

    SkeletonObject* sObj = PluginFunctions::skeletonObject(obj);
    
    //check if pose changed
    if ( sObj->activePose() != currentAnimationHandle() ){

      AnimationHandle newHandle = sObj->activePose();

      if ( !newHandle.isValid() ) //refPose
        pToolbox_->cbAnimation->setCurrentIndex( 0 ); 
      else
431
        setComboBoxPosition(newHandle.animationIndex());
Dirk Wilden's avatar
Dirk Wilden committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
    }

    //check if animationCount changed
    if ( (int)PluginFunctions::skeleton(sObj)->animationCount() != pToolbox_->cbAnimation->count()-1 )
      UpdateUI();
  }
}

//------------------------------------------------------------------------------

/**
 * @brief Called by the framework when the animation index changed
 */
void SkeletalAnimationPlugin::slotAnimationIndexChanged(int /*_index*/)
{
  if(bGuiUpdating_)	// do not update while the gui is updating
    return;

450
  if ( activeSkeletons_.empty() ){
Dirk Wilden's avatar
Dirk Wilden committed
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
    pToolbox_->hsFrame->setRange( 0, 0 );
    pToolbox_->hsFrame->setTickInterval(1);
    pToolbox_->hsFrame->setValue(0);

    pToolbox_->cbAnimation->clear();

  } else {

    //get first active skeleton
    BaseObjectData* skelObject = 0;
    PluginFunctions::getObject(activeSkeletons_[0], skelObject);
    
    if ( skelObject == 0 )
      return;
    
    Skeleton* skeleton = PluginFunctions::skeleton(skelObject);
    
    // equip the frame slider with the new range
    AnimationT<ACG::Vec3d> *pAnimation = skeleton->animation(currentAnimationHandle());
    if(pAnimation != 0){
      pToolbox_->hsFrame->setRange( 0, pAnimation->frameCount() - 1 );
      changeFPS( pAnimation->fps() );
    }else
      pToolbox_->hsFrame->setRange( 0, 0 );

    pToolbox_->hsFrame->setTickInterval(1);
    pToolbox_->hsFrame->setValue(0);

    // pass the current frame
    AnimationHandle hAni = currentAnimationHandle();
    dynamic_cast<SkeletonObject*>(skelObject)->setActivePose(hAni);

    emit updatedObject(skelObject->id(), UPDATE_GEOMETRY);

Dirk Wilden's avatar
Dirk Wilden committed
485 486
    // update skins if available
    UpdateSkins(skelObject, hAni);
Dirk Wilden's avatar
Dirk Wilden committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

    slotFrameChanged(0);
  }
}

//------------------------------------------------------------------------------

/**
 * @brief Called by the framework when a different frame was selected
 */
void SkeletalAnimationPlugin::slotFrameChanged(int /*_index*/)
{
  // do not update while the gui is updating
  if(bGuiUpdating_)
    return;

  for (unsigned int i=0; i < activeSkeletons_.size(); i++){
    
      //get active skeleton
      BaseObjectData* skelObject = 0;
      PluginFunctions::getObject(activeSkeletons_[i], skelObject);
    
      if ( skelObject == 0 )
        return;
      
      // pass the current frame
      AnimationHandle hAni = currentAnimationHandle();
Dirk Wilden's avatar
Dirk Wilden committed
514
      PluginFunctions::skeletonObject(skelObject)->setActivePose(hAni);
Dirk Wilden's avatar
Dirk Wilden committed
515 516

      // and update the skin if available
Dirk Wilden's avatar
Dirk Wilden committed
517
      UpdateSkins(skelObject, hAni);
Dirk Wilden's avatar
Dirk Wilden committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

      emit updatedObject(skelObject->id(), UPDATE_GEOMETRY);
  }
}

//------------------------------------------------------------------------------

/**
 * @brief Called by the ui and starts an automatic animation
 */
void SkeletalAnimationPlugin::playAnimation() {
  disconnect(&animationTimer_, 0, 0, 0);
  animationTimer_.stop();
  animationTimer_.setSingleShot(false);
  animationTimer_.setInterval(1000 / pToolbox_->sbFPS->value());
  connect(&animationTimer_,SIGNAL(timeout()),this,SLOT(animate()));
  animationTimer_.start();
  animationTime_.start();
  animationOffset_ = pToolbox_->hsFrame->value();
  
  //The Play button will just toggle between play and pause mode
  connect( pToolbox_->pbPlay, SIGNAL(clicked()), this, SLOT( pauseAnimation() ) );
}

//------------------------------------------------------------------------------

/**
 * @brief Called by the ui and stops the current animation
 */
void SkeletalAnimationPlugin::pauseAnimation() {
  animationTimer_.stop();
  disconnect(&animationTimer_, 0, 0, 0);
  
  connect( pToolbox_->pbPlay, SIGNAL(clicked()), this, SLOT( playAnimation() ) );
}

//------------------------------------------------------------------------------

/**
 * @brief Called by the ui and stops the current animation
 */
void SkeletalAnimationPlugin::stopAnimation() {
  pauseAnimation();
  pToolbox_->hsFrame->setSliderPosition(0);     //Reset the playback
}

//------------------------------------------------------------------------------

/**
 * @brief Called by the ui and goes to previous frame of the current animation
 */
void SkeletalAnimationPlugin::prevFrame() {
  pauseAnimation();
  pToolbox_->hsFrame->setSliderPosition(pToolbox_->hsFrame->sliderPosition() - 1);
}

//------------------------------------------------------------------------------

/**
 * @brief Called by the ui and goes to next frame of the current animation
 */
void SkeletalAnimationPlugin::nextFrame() {
  pauseAnimation();
  pToolbox_->hsFrame->setSliderPosition(pToolbox_->hsFrame->sliderPosition() + 1);
}

//------------------------------------------------------------------------------

/**
 * @brief Iterates the animation
 *
 * If frame skipping is disabled, the next frame will be drawn. Otherwise, the next frame is determined by the
 * time that passed since the last call.
 */
void SkeletalAnimationPlugin::animate()
{
  unsigned long frameCount = getNumberOfFrames();
  if(frameCount <= 1)	// 0: invalid animation, 1: just a pose
  {
    setFrame(0);
    stopAnimation();
    return;
  }
  --frameCount;

  if(pToolbox_->cbSkipFrames->isChecked())
  {
    int fps = pToolbox_->sbFPS->value();
    unsigned long currentFrame = animationOffset_ + (unsigned long)floor(double(animationTime_.elapsed()) / 1000.0 * fps);
    setFrame(currentFrame % frameCount);
  }else{
    setFrame((getFrame() + 1) % frameCount);
  }
}

//------------------------------------------------------------------------------

/**
 * @brief Called as the skip frames check box changes state
 *
 * To prevent the animation playback from jumping, the animation timer is restarted here.
 */
void SkeletalAnimationPlugin::slotSkipFramesChanged(int _state)
{
  if(_state == Qt::Checked)
  {
    // changing to skip frames as necessary
    animationTime_.start();
    animationOffset_ = pToolbox_->hsFrame->value();
  }else{
    // changing to display all frames
  }
}

//------------------------------------------------------------------------------

/**
 * @brief Called as the skin deformation method changed
 *
 * The spherical skin blending appears to be buggy, so it is recommended not to use it.
 */
void SkeletalAnimationPlugin::slotMethodChanged(int _index)
{
  // change the method
  switch(_index)
  {
  case 0:
645
    method_ = Blending::M_LBS;
Dirk Wilden's avatar
Dirk Wilden committed
646 647 648
    break;
  default:
  case 1:
649
    method_ = Blending::M_DBS;
Dirk Wilden's avatar
Dirk Wilden committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    break;
  }

  // deform the skin(s) using the new method
  for (unsigned int i=0; i < activeSkeletons_.size(); i++){

    //get active skeleton
    BaseObjectData* baseObject = 0;
    PluginFunctions::getObject(activeSkeletons_[i], baseObject);

    if ( baseObject == 0 )
      return;

    SkeletonObject* skeletonObject = dynamic_cast<SkeletonObject*>(baseObject);
    AnimationHandle hAni = skeletonObject->skeletonNode()->activePose();

    // and update the skin
Dirk Wilden's avatar
Dirk Wilden committed
667
    UpdateSkins(skeletonObject, hAni);
Dirk Wilden's avatar
Dirk Wilden committed
668 669 670 671 672 673 674
  }

  emit updateView();
}

//------------------------------------------------------------------------------

Matthias Möller's avatar
Matthias Möller committed
675 676 677 678 679 680 681 682
/**
 * @brief Helper Class for UpdateUI. assigns a bool value and set it to "true". after leaving the scope, set it to false
 *
 */
class GuiUpdatingScopeGuard
{
  bool& v_;
public:
Jan Möbius's avatar
Jan Möbius committed
683
  explicit GuiUpdatingScopeGuard(bool &_in):v_(_in){v_ = true;}
Matthias Möller's avatar
Matthias Möller committed
684 685 686
  ~GuiUpdatingScopeGuard(){v_ = false;}
};

Dirk Wilden's avatar
Dirk Wilden committed
687 688 689 690 691 692 693 694
/**
 * @brief Called when the active object changes and the interface needs to be updated
 */
void SkeletalAnimationPlugin::UpdateUI()
{
  if(bGuiUpdating_)	// gui updates object -> object is updated so gui gets updated -> loop forever
    return;

Matthias Möller's avatar
Matthias Möller committed
695
  GuiUpdatingScopeGuard guard(bGuiUpdating_);
Dirk Wilden's avatar
Dirk Wilden committed
696

Jan Möbius's avatar
Jan Möbius committed
697
  if( ! activeSkeletons_.empty() )
Dirk Wilden's avatar
Dirk Wilden committed
698 699 700 701 702 703 704 705 706 707
  {
    //get first active skeleton
    BaseObjectData* baseObject = 0;
    PluginFunctions::getObject(activeSkeletons_[0], baseObject);

    if ( baseObject == 0 )
      return;

    SkeletonObject* skeletonObj = PluginFunctions::skeletonObject(baseObject);
    Skeleton*          skeleton = PluginFunctions::skeleton(baseObject);
Dirk Wilden's avatar
Dirk Wilden committed
708
    
Dirk Wilden's avatar
Dirk Wilden committed
709 710 711 712
    // update the rigging and skinning group
    // enable UI
    if(skeletonObj->objectData(OBJECTDATA_SKELETON) == 0)
    {
Dirk Wilden's avatar
Dirk Wilden committed
713 714 715
      pToolbox_->pbAttachSkin->setEnabled(true);
      pToolbox_->pbClearSkins->setEnabled(false);
      pToolbox_->skinningBox->setTitle(tr("Attached Skins"));
Dirk Wilden's avatar
Dirk Wilden committed
716
    }else{
Dirk Wilden's avatar
Dirk Wilden committed
717 718 719 720 721
      pToolbox_->pbAttachSkin->setEnabled(true);
      pToolbox_->pbClearSkins->setEnabled(true);

      SkeletonObjectData* skelData = dynamic_cast<SkeletonObjectData*>( skeletonObj->objectData(OBJECTDATA_SKELETON) );
      pToolbox_->skinningBox->setTitle(tr("Attached Skins (Currently: %1)").arg(skelData->skinCount())  );
Dirk Wilden's avatar
Dirk Wilden committed
722 723 724 725 726
    }

    // update the Skeleton group
    AnimationHandle hAni = skeletonObj->skeletonNode()->activePose();

Dirk Wilden's avatar
Dirk Wilden committed
727
    pToolbox_->pbAddAnimation->setEnabled(true);
Dirk Wilden's avatar
Dirk Wilden committed
728 729 730 731 732 733
    pToolbox_->cbAnimation->setEnabled(true);
    pToolbox_->cbAnimation->clear();

    // create the reference pose
    pToolbox_->cbAnimation->addItem("Reference Pose");

734 735 736 737
    Skeleton::AnimationIterator animations = skeleton->animationsBegin();

    while ( animations ) {
      AnimationHandle anim = *animations;
Jan Möbius's avatar
Jan Möbius committed
738
      pToolbox_->cbAnimation->addItem(skeleton->animationName(anim.animationIndex()).c_str(),QVariant::fromValue(anim.animationIndex()));
739 740 741 742
      ++animations;
    }

    setComboBoxPosition(hAni.animationIndex());
Dirk Wilden's avatar
Dirk Wilden committed
743 744 745 746 747 748 749 750 751 752

    // get the number of frames in the animation
    pToolbox_->hsFrame->setEnabled(true);
    if(skeleton->animation(hAni) != 0)
      pToolbox_->hsFrame->setRange( 0, skeleton->animation(hAni)->frameCount() - 1 );
    pToolbox_->hsFrame->setTickInterval(1);
    pToolbox_->hsFrame->setValue(hAni.frame());

  }else{
    // disable UI
Dirk Wilden's avatar
Dirk Wilden committed
753
    pToolbox_->pbAddAnimation->setEnabled(false);
Dirk Wilden's avatar
Dirk Wilden committed
754 755 756 757 758 759
    pToolbox_->cbAnimation->setEnabled(false);
    pToolbox_->cbAnimation->clear();
    pToolbox_->hsFrame->setEnabled(false);
    pToolbox_->hsFrame->setRange(0, 0);
    pToolbox_->hsFrame->setTickInterval(1);

Dirk Wilden's avatar
Dirk Wilden committed
760 761 762
    pToolbox_->pbAttachSkin->setEnabled(false);
    pToolbox_->pbClearSkins->setEnabled(false);
    pToolbox_->skinningBox->setTitle(tr("Attached Skins"));
Dirk Wilden's avatar
Dirk Wilden committed
763 764 765 766 767 768 769 770
  }
}

//------------------------------------------------------------------------------

/**
 * @brief Called by Qt as the user is trying to connect a mesh to a skeleton
 */
Dirk Wilden's avatar
Dirk Wilden committed
771
void SkeletalAnimationPlugin::slotAttachSkin()
Dirk Wilden's avatar
Dirk Wilden committed
772
{
Dirk Wilden's avatar
Dirk Wilden committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
  
  if( activeSkeletons_.size() != 1 ){
    emit log(LOGERR, tr("Cannot bind mesh. Please select only one skeleton."));
    return;
  }

  int meshCount = 0;

  for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::TARGET_OBJECTS, DataType(DATA_TRIANGLE_MESH|DATA_POLY_MESH)) ; o_it != PluginFunctions::objectsEnd(); ++o_it)
  {
    attachSkin(activeSkeletons_[0], o_it->id());
    meshCount++;
  }
  
  if (meshCount == 0){
    emit log(LOGERR, tr("Cannot bind mesh. Please select at least one mesh as target."));
    return;
  }
Dirk Wilden's avatar
Dirk Wilden committed
791 792 793 794
}

//------------------------------------------------------------------------------

Dirk Wilden's avatar
Dirk Wilden committed
795
void SkeletalAnimationPlugin::attachSkin(BaseObjectData* _skin, BaseObjectData* _skeletonObj) {
Dirk Wilden's avatar
Dirk Wilden committed
796
  
Dirk Wilden's avatar
Dirk Wilden committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
  // get the skeleton and make it prepare the mesh
  Skeleton* skeleton = dynamic_cast<SkeletonObject*>(_skeletonObj)->skeleton();

  //check if mesh is already a skin
  if (_skin->hasObjectData(OBJECTDATA_SKIN) ){
    emit log(LOGERR, tr("Cannot bind mesh as skin. Mesh is already a skin."));
    return;
  }

  // prepare the skin template class used to deform the skin
  SkeletonObjectData* skelData = 0;

  if ( _skeletonObj->hasObjectData(OBJECTDATA_SKELETON) )
    skelData = dynamic_cast< SkeletonObjectData* >(_skeletonObj->objectData(OBJECTDATA_SKELETON));
  else {
    skelData = new SkeletonObjectData();
    _skeletonObj->setObjectData(OBJECTDATA_SKELETON, skelData);
  }

  skelData->addSkin( _skin->id() );

  BaseSkin* baseSkin = 0;

  OpenMesh::VPropHandleT<BaseSkin::SkinWeights> propWeights;
  bool hasSkinWeights = true;

  if(_skin->dataType(DATA_TRIANGLE_MESH)){
    hasSkinWeights = PluginFunctions::triMesh(_skin)->get_property_handle(propWeights, SKIN_WEIGHTS_PROP);
825
    baseSkin       = dynamic_cast<BaseSkin*>( new TriMeshSkin(skeleton, PluginFunctions::triMesh(_skin),_skeletonObj->id()) );
Dirk Wilden's avatar
Dirk Wilden committed
826 827
  }else if(_skin->dataType(DATA_POLY_MESH)){
    hasSkinWeights = PluginFunctions::polyMesh(_skin)->get_property_handle(propWeights, SKIN_WEIGHTS_PROP);
828
    baseSkin       = dynamic_cast<BaseSkin*>( new PolyMeshSkin(skeleton, PluginFunctions::polyMesh(_skin) ,_skeletonObj->id() ));
Dirk Wilden's avatar
Dirk Wilden committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
  }

  baseSkin->attachSkin();

  if (hasSkinWeights)
    baseSkin->deformSkin(currentAnimationHandle(), method_);

  emit updatedObject(_skin->id(), UPDATE_GEOMETRY);
  _skin->setObjectData(OBJECTDATA_SKIN, baseSkin);

  _skeletonObj->target(true);
  _skeletonObj->source(false);

  if( !hasSkinWeights ){
    //ask if they should be computed automatically
    bool canCompute;
    emit pluginExists("skinningplugin", canCompute);
    
    if (canCompute){
      QMessageBox msgBox;
      msgBox.setText("The mesh is not equipped with skin weights.");
      msgBox.setInformativeText("Do you want to compute them automatically?");
      msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
      msgBox.setDefaultButton(QMessageBox::Yes);
      int ret = msgBox.exec();

      if (ret == QMessageBox::Yes)
        RPC::callFunction("skinningplugin", "computeSkinWeights");
    }
  }
  
  UpdateUI();
Dirk Wilden's avatar
Dirk Wilden committed
861 862 863 864 865 866 867
}

//------------------------------------------------------------------------------

/**
 * @brief Called by Qt as the user is trying to unbind a mesh from as a skeleton
 */
Dirk Wilden's avatar
Dirk Wilden committed
868
void SkeletalAnimationPlugin::slotClearSkins()
Dirk Wilden's avatar
Dirk Wilden committed
869
{
Dirk Wilden's avatar
Dirk Wilden committed
870 871
  for (unsigned int i=0; i < activeSkeletons_.size(); i++)
    clearSkins( activeSkeletons_[i] );
Dirk Wilden's avatar
Dirk Wilden committed
872 873 874 875
}

//------------------------------------------------------------------------------

Dirk Wilden's avatar
Dirk Wilden committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
void SkeletalAnimationPlugin::clearSkins(BaseObjectData* _skeletonObj) {

  // prepare the skin template class used to deform the skin
  SkeletonObjectData* skelData = 0;

  if ( !_skeletonObj->hasObjectData(OBJECTDATA_SKELETON) )
    return;

  skelData = dynamic_cast< SkeletonObjectData* >(_skeletonObj->objectData(OBJECTDATA_SKELETON));

  for (int i=skelData->skinCount()-1; i >= 0; i--){
    //deform all attached skin meshes
    int meshId = skelData->skin(i);

    BaseObjectData* object = 0;
    PluginFunctions::getObject(meshId, object);
    
    if (object == 0)
      continue;

    detachSkin(object, _skeletonObj);
  }
}

//------------------------------------------------------------------------------

void SkeletalAnimationPlugin::detachSkin(BaseObjectData* _skin, BaseObjectData* _skeletonObj) {

  // get the skeleton and make it prepare the mesh
  Skeleton* skeleton = dynamic_cast<SkeletonObject*>(_skeletonObj)->skeleton();

  if ( !_skeletonObj->hasObjectData(OBJECTDATA_SKELETON) ){
    emit log(LOGERR, tr("Cannot detach skin. Skeleton has no object data."));
    return;
  }

  //first try to remove the skin from the mesh
  if (_skin->hasObjectData(OBJECTDATA_SKIN) ){

    BaseSkin* baseSkin = 0;

    if(_skin->dataType(DATA_TRIANGLE_MESH))
918
      baseSkin = dynamic_cast<BaseSkin*>( new TriMeshSkin(skeleton, PluginFunctions::triMesh(_skin) ,_skeletonObj->id()));
Dirk Wilden's avatar
Dirk Wilden committed
919
    else if(_skin->dataType(DATA_POLY_MESH))
920
      baseSkin = dynamic_cast<BaseSkin*>( new PolyMeshSkin(skeleton, PluginFunctions::polyMesh(_skin) ,_skeletonObj->id()));
Dirk Wilden's avatar
Dirk Wilden committed
921 922 923 924 925 926 927 928 929 930 931 932

    baseSkin->releaseSkin();
    _skin->clearObjectData(OBJECTDATA_SKIN);
    delete baseSkin;

    emit updatedObject(_skin->id(), UPDATE_GEOMETRY);
  }

  // then remove the skin from the skeleton data
  SkeletonObjectData* skelData = dynamic_cast< SkeletonObjectData* >(_skeletonObj->objectData(OBJECTDATA_SKELETON));

  skelData->removeSkin( _skin->id() );
Dirk Wilden's avatar
Dirk Wilden committed
933
  
Dirk Wilden's avatar
Dirk Wilden committed
934 935 936 937 938 939 940
  //remove the objectData if all skins are removed
  if ( skelData->skinCount() == 0 ){
    _skeletonObj->clearObjectData(OBJECTDATA_SKELETON);
    delete skelData;
  }

  UpdateUI();
Dirk Wilden's avatar
Dirk Wilden committed
941 942 943 944
}

//------------------------------------------------------------------------------

Dirk Wilden's avatar
Dirk Wilden committed
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
void SkeletalAnimationPlugin::slotAddAnimation()
{
  
  if( activeSkeletons_.size() != 1 ){
    emit log(LOGERR, tr("Cannot add animation. Please select only one skeleton."));
    return;
  }

  AddAnimationDialog dialog;
  dialog.animationName->selectAll();
  dialog.animationName->setFocus();
  
  if ( dialog.exec() == QDialog::Accepted ){
    if ( dialog.animationName->text() == "" ){
      emit log(LOGERR, tr("Cannot add animation with empty name"));
      return;
    }

    BaseObjectData* obj = 0;

    PluginFunctions::getObject(activeSkeletons_[0], obj);

    if (obj == 0){
      emit log(LOGERR, tr("Unable to get object"));
      return;
    }

    SkeletonObject* skeletonObj = PluginFunctions::skeletonObject(obj);

    if (skeletonObj == 0){
      emit log(LOGERR, tr("Unable to get skeletonObject"));
      return;
    }

    Skeleton* skeleton = PluginFunctions::skeleton(obj);

    std::string stdName = dialog.animationName->text().toStdString();

    if ( skeleton->animation(stdName) != 0 ){
      emit log(LOGERR, tr("Animation with this name already exists"));
      return;
    }

    FrameAnimationT<ACG::Vec3d>* animation = new FrameAnimationT<ACG::Vec3d>(skeleton, dialog.frames->value());
    AnimationHandle handle = skeleton->addAnimation(stdName, animation);

    //init pose to refPose
    for (unsigned int i=0; i < skeleton->animation(handle)->frameCount(); i++){
      handle.setFrame(i);
      Skeleton::Pose* pose = skeleton->pose(handle);

      for (unsigned int j=0; j < skeleton->jointCount(); j++)
        pose->setGlobalMatrix(j, skeleton->referencePose()->globalMatrix(j) );
    }

    emit updatedObject(activeSkeletons_[0], UPDATE_ALL);

    //select the new animation
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    setComboBoxPosition(handle.animationIndex());
  }
}

//------------------------------------------------------------------------------

void SkeletalAnimationPlugin::slotDeleteAnimation()
{
  int iAnimation = pToolbox_->cbAnimation->currentIndex();
  unsigned int animationIndex = pToolbox_->cbAnimation->itemData(iAnimation).toUInt();

  if ( iAnimation == 0 ) {
    emit log(LOGERR,"Reference pose could never be removed!");
  } else {
    pToolbox_->cbAnimation->removeItem(iAnimation);

    for ( PluginFunctions::ObjectIterator o_it(PluginFunctions::TARGET_OBJECTS, DataType(DATA_SKELETON)) ; o_it != PluginFunctions::objectsEnd(); ++o_it) {

      SkeletonObject* skeletonObject = dynamic_cast<SkeletonObject*>(*o_it);
      Skeleton*             skeleton = PluginFunctions::skeleton(skeletonObject);

      skeleton->removeAnimation(AnimationHandle(animationIndex));

    }

    UpdateUI();
Dirk Wilden's avatar
Dirk Wilden committed
1029 1030 1031 1032
  }
}

//------------------------------------------------------------------------------
Dirk Wilden's avatar
Dirk Wilden committed
1033 1034 1035 1036

/**
 * @brief Returns a handle describing the current frame in the active animation
 *
1037
 * This information is derived from the corresponding combo box and slider.
Dirk Wilden's avatar
Dirk Wilden committed
1038 1039 1040 1041
 */
AnimationHandle SkeletalAnimationPlugin::currentAnimationHandle()
{
  int iAnimation = pToolbox_->cbAnimation->currentIndex();
1042
  unsigned int animationId = pToolbox_->cbAnimation->itemData(iAnimation).toUInt();
Dirk Wilden's avatar
Dirk Wilden committed
1043
  
Dirk Wilden's avatar
Dirk Wilden committed
1044 1045 1046
  if(iAnimation == 0)
    return AnimationHandle(); //This will be the reference pose, i.e. an empty animation
  else if(iAnimation > 0)
1047
    return AnimationHandle(animationId, pToolbox_->hsFrame->value());
Dirk Wilden's avatar
Dirk Wilden committed
1048 1049 1050 1051 1052
  return AnimationHandle(); // should not happen
}

//------------------------------------------------------------------------------

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
/**
 * @brief Sets the animations combo box to the right entry
 *
 */
void SkeletalAnimationPlugin::setComboBoxPosition(unsigned int _animationIndex)
{
  for ( int i = 0 ; i <  pToolbox_->cbAnimation->count(); ++i ) {
    unsigned int animationId = pToolbox_->cbAnimation->itemData(i).toUInt();

    if ( animationId == _animationIndex ) {
      pToolbox_->cbAnimation->setCurrentIndex(i);
      return;
    }

  }

}

//------------------------------------------------------------------------------

1073 1074