<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "state.h"
#include "lexers/streamfilters.h"

namespace embree
{
  /* error flag */
  tls_t State::g_error = nullptr; // FIXME: use thread local
  std::vector<RTCError*> State::g_errors; // FIXME: use thread local
  MutexSys State::g_errors_mutex;

  State State::state;

  State::State () {
    clear();
  }

  void State::clear()
  {
    tri_accel = "default";
    tri_builder = "default";
    tri_traverser = "default";
    tri_builder_replication_factor = 2.0f;

    tri_accel_mb = "default";
    tri_builder_mb = "default";
    tri_traverser_mb = "default";

    hair_accel = "default";
    hair_builder = "default";
    hair_traverser = "default";
    hair_builder_replication_factor = 3.0f;
    memory_preallocation_factor     = 1.0f;
    tessellation_cache_size         = 0;
    subdiv_accel = "default";

    scene_flags = -1;
    verbose = 0;
    g_numThreads = 0;
    benchmark = 0;
    regression_testing = 0;

    {
      Lock<MutexSys> lock(g_errors_mutex);
      if (g_error == nullptr)
        g_error = createTls();
    }
    g_error_function = nullptr;
    g_memory_monitor_function = nullptr;

    //Lock<MutexSys> lock(g_errors_mutex);
    //  for (size_t i=0; i<g_errors.size(); i++)
    //    delete g_errors[i];
    //  destroyTls(g_error);
    //  g_errors.clear();
  }

  static std::vector<std::string> symbols { "=", ",", "|" };

  bool State::parseFile(const FileName& fileName)
  {
    Ref<Stream<int> > file;
    try {
      file = new FileStream(fileName);
    } catch (const std::runtime_error&) {
      return false;
    }
    Ref<TokenStream> cin = new TokenStream(new LineCommentFilter(file,"#"),
                                           TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
                                           TokenStream::separators,symbols);
    parse(cin);
    return true;
  }

  void State::parseString(const char* cfg)
  {
    if (cfg == nullptr) return;

    Ref<TokenStream> cin = new TokenStream(new StrStream(cfg),
                                           TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
                                           TokenStream::separators,symbols);
    parse(cin);
  }

  void State::parse(Ref<TokenStream> cin)
  {
    /* parse until end of stream */
    while (cin->peek() != Token::Eof())
    {
      const Token tok = cin->get();

      if (tok == Token::Id("threads") && cin->trySymbol("="))
        g_numThreads = cin->get().Int();

      else if (tok == Token::Id("isa") && cin->trySymbol("="))
      {
        std::string isa = cin->get().Identifier();
        if      (isa == "sse" ) setCPUFeatures(SSE);
        else if (isa == "sse2") setCPUFeatures(SSE2);
        else if (isa == "sse3") setCPUFeatures(SSE3);
        else if (isa == "ssse3") setCPUFeatures(SSSE3);
        else if (isa == "sse41") setCPUFeatures(SSE41);
        else if (isa == "sse4.1") setCPUFeatures(SSE41);
        else if (isa == "sse42") setCPUFeatures(SSE42);
        else if (isa == "sse4.2") setCPUFeatures(SSE42);
        else if (isa == "avx") setCPUFeatures(AVX);
        else if (isa == "avxi") setCPUFeatures(AVXI);
        else if (isa == "avx2") setCPUFeatures(AVX2);
      }

      else if ((tok == Token::Id("tri_accel") || tok == Token::Id("accel")) && cin->trySymbol("="))
        tri_accel = cin->get().Identifier();
      else if ((tok == Token::Id("tri_builder") || tok == Token::Id("builder")) && cin->trySymbol("="))
        tri_builder = cin->get().Identifier();
      else if ((tok == Token::Id("tri_traverser") || tok == Token::Id("traverser")) && cin->trySymbol("="))
        tri_traverser = cin->get().Identifier();
      else if (tok == Token::Id("tri_builder_replication_factor") && cin->trySymbol("="))
        tri_builder_replication_factor = cin->get().Int();

      else if ((tok == Token::Id("tri_accel_mb") || tok == Token::Id("accel_mb")) && cin->trySymbol("="))
        tri_accel_mb = cin->get().Identifier();
      else if ((tok == Token::Id("tri_builder_mb") || tok == Token::Id("builder_mb")) && cin->trySymbol("="))
        tri_builder_mb = cin->get().Identifier();
      else if ((tok == Token::Id("tri_traverser_mb") || tok == Token::Id("traverser_mb")) && cin->trySymbol("="))
        tri_traverser_mb = cin->get().Identifier();

      else if (tok == Token::Id("hair_accel") && cin->trySymbol("="))
        hair_accel = cin->get().Identifier();
      else if (tok == Token::Id("hair_builder") && cin->trySymbol("="))
        hair_builder = cin->get().Identifier();
      else if (tok == Token::Id("hair_traverser") && cin->trySymbol("="))
        hair_traverser = cin->get().Identifier();
      else if (tok == Token::Id("hair_builder_replication_factor") && cin->trySymbol("="))
        hair_builder_replication_factor = cin->get().Int();

      else if (tok == Token::Id("subdiv_accel") && cin->trySymbol("="))
        subdiv_accel = cin->get().Identifier();

      else if (tok == Token::Id("verbose") && cin->trySymbol("="))
        verbose = cin->get().Int();
      else if (tok == Token::Id("benchmark") && cin->trySymbol("="))
        benchmark = cin->get().Int();

      else if (tok == Token::Id("flags")) {
        scene_flags = 0;
        if (cin->trySymbol("=")) {
          do {
            Token flag = cin->get();
            if      (flag == Token::Id("static") ) scene_flags |= RTC_SCENE_STATIC;
            else if (flag == Token::Id("dynamic")) scene_flags |= RTC_SCENE_DYNAMIC;
            else if (flag == Token::Id("compact")) scene_flags |= RTC_SCENE_COMPACT;
            else if (flag == Token::Id("coherent")) scene_flags |= RTC_SCENE_COHERENT;
            else if (flag == Token::Id("incoherent")) scene_flags |= RTC_SCENE_INCOHERENT;
            else if (flag == Token::Id("high_quality")) scene_flags |= RTC_SCENE_HIGH_QUALITY;
            else if (flag == Token::Id("robust")) scene_flags |= RTC_SCENE_ROBUST;
          } while (cin->trySymbol("|"));
        }
      }
      else if (tok == Token::Id("memory_preallocation_factor") && cin->trySymbol("="))
        memory_preallocation_factor = cin->get().Float();

      else if (tok == Token::Id("regression") && cin->trySymbol("="))
        regression_testing = cin->get().Int();

      else if (tok == Token::Id("tessellation_cache_size") && cin->trySymbol("="))
        tessellation_cache_size = cin->get().Float() * 1024 * 1024;

      cin->trySymbol(","); // optional , separator
    }
  }

  RTCError* State::error()
  {
    RTCError* stored_error = (RTCError*) getTls(g_error);
    if (stored_error == nullptr) {
      Lock<MutexSys> lock(g_errors_mutex);
      stored_error = new RTCError(RTC_NO_ERROR);
      g_errors.push_back(stored_error);
      setTls(g_error,stored_error);
    }
    return stored_error;
  }

  bool State::verbosity(int N) {
    return N <= verbose;
  }

  void State::print()
  {
    std::cout << "general:" << std::endl;
    std::cout << "  build threads = " << g_numThreads << std::endl;
    std::cout << "  verbosity     = " << verbose << std::endl;

    std::cout << "triangles:" << std::endl;
    std::cout << "  accel         = " << tri_accel << std::endl;
    std::cout << "  builder       = " << tri_builder << std::endl;
    std::cout << "  traverser     = " << tri_traverser << std::endl;
    std::cout << "  replications  = " << tri_builder_replication_factor << std::endl;

    std::cout << "motion blur triangles:" << std::endl;
    std::cout << "  accel         = " << tri_accel_mb << std::endl;
    std::cout << "  builder       = " << tri_builder_mb << std::endl;
    std::cout << "  traverser     = " << tri_traverser_mb << std::endl;

    std::cout << "hair:" << std::endl;
    std::cout << "  accel         = " << hair_accel << std::endl;
    std::cout << "  builder       = " << hair_builder << std::endl;
    std::cout << "  traverser     = " << hair_traverser << std::endl;
    std::cout << "  replications  = " << hair_builder_replication_factor << std::endl;

    std::cout << "subdivision surfaces:" << std::endl;
    std::cout << "  accel         = " << subdiv_accel << std::endl;

#if defined(__MIC__)
    std::cout << "memory allocation:" << std::endl;
    std::cout << "  preallocation_factor  = " << memory_preallocation_factor << std::endl;
#endif
  }
}
<commit_msg>VS2012 does not support initializer lists, implementing workaround<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "state.h"
#include "lexers/streamfilters.h"

namespace embree
{
  /* error flag */
  tls_t State::g_error = nullptr; // FIXME: use thread local
  std::vector<RTCError*> State::g_errors; // FIXME: use thread local
  MutexSys State::g_errors_mutex;

  State State::state;

  State::State () {
    clear();
  }

  void State::clear()
  {
    tri_accel = "default";
    tri_builder = "default";
    tri_traverser = "default";
    tri_builder_replication_factor = 2.0f;

    tri_accel_mb = "default";
    tri_builder_mb = "default";
    tri_traverser_mb = "default";

    hair_accel = "default";
    hair_builder = "default";
    hair_traverser = "default";
    hair_builder_replication_factor = 3.0f;
    memory_preallocation_factor     = 1.0f;
    tessellation_cache_size         = 0;
    subdiv_accel = "default";

    scene_flags = -1;
    verbose = 0;
    g_numThreads = 0;
    benchmark = 0;
    regression_testing = 0;

    {
      Lock<MutexSys> lock(g_errors_mutex);
      if (g_error == nullptr)
        g_error = createTls();
    }
    g_error_function = nullptr;
    g_memory_monitor_function = nullptr;

    //Lock<MutexSys> lock(g_errors_mutex);
    //  for (size_t i=0; i<g_errors.size(); i++)
    //    delete g_errors[i];
    //  destroyTls(g_error);
    //  g_errors.clear();
  }

  const char* symbols[3] = { "=", ",", "|" };

   bool State::parseFile(const FileName& fileName)
  {
    Ref<Stream<int> > file;
    try {
      file = new FileStream(fileName);
    } catch (const std::runtime_error&) {
      return false;
    }

    std::vector<std::string> syms;
	  for (size_t i=0; i<sizeof(symbols)/sizeof(void*); i++)
      syms.push_back(symbols[i]);

    Ref<TokenStream> cin = new TokenStream(new LineCommentFilter(file,"#"),
                                           TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
                                           TokenStream::separators,syms);
    parse(cin);
    return true;
  }

  void State::parseString(const char* cfg)
  {
    if (cfg == nullptr) return;

    std::vector<std::string> syms;
	  for (size_t i=0; i<sizeof(symbols)/sizeof(void*); i++)
	  	syms.push_back(symbols[i]);

	  Ref<TokenStream> cin = new TokenStream(new StrStream(cfg),
                                           TokenStream::alpha+TokenStream::ALPHA+TokenStream::numbers+"_.",
                                           TokenStream::separators,syms);
    parse(cin);
  }

  void State::parse(Ref<TokenStream> cin)
  {
    /* parse until end of stream */
    while (cin->peek() != Token::Eof())
    {
      const Token tok = cin->get();

      if (tok == Token::Id("threads") && cin->trySymbol("="))
        g_numThreads = cin->get().Int();

      else if (tok == Token::Id("isa") && cin->trySymbol("="))
      {
        std::string isa = cin->get().Identifier();
        if      (isa == "sse" ) setCPUFeatures(SSE);
        else if (isa == "sse2") setCPUFeatures(SSE2);
        else if (isa == "sse3") setCPUFeatures(SSE3);
        else if (isa == "ssse3") setCPUFeatures(SSSE3);
        else if (isa == "sse41") setCPUFeatures(SSE41);
        else if (isa == "sse4.1") setCPUFeatures(SSE41);
        else if (isa == "sse42") setCPUFeatures(SSE42);
        else if (isa == "sse4.2") setCPUFeatures(SSE42);
        else if (isa == "avx") setCPUFeatures(AVX);
        else if (isa == "avxi") setCPUFeatures(AVXI);
        else if (isa == "avx2") setCPUFeatures(AVX2);
      }

      else if ((tok == Token::Id("tri_accel") || tok == Token::Id("accel")) && cin->trySymbol("="))
        tri_accel = cin->get().Identifier();
      else if ((tok == Token::Id("tri_builder") || tok == Token::Id("builder")) && cin->trySymbol("="))
        tri_builder = cin->get().Identifier();
      else if ((tok == Token::Id("tri_traverser") || tok == Token::Id("traverser")) && cin->trySymbol("="))
        tri_traverser = cin->get().Identifier();
      else if (tok == Token::Id("tri_builder_replication_factor") && cin->trySymbol("="))
        tri_builder_replication_factor = cin->get().Int();

      else if ((tok == Token::Id("tri_accel_mb") || tok == Token::Id("accel_mb")) && cin->trySymbol("="))
        tri_accel_mb = cin->get().Identifier();
      else if ((tok == Token::Id("tri_builder_mb") || tok == Token::Id("builder_mb")) && cin->trySymbol("="))
        tri_builder_mb = cin->get().Identifier();
      else if ((tok == Token::Id("tri_traverser_mb") || tok == Token::Id("traverser_mb")) && cin->trySymbol("="))
        tri_traverser_mb = cin->get().Identifier();

      else if (tok == Token::Id("hair_accel") && cin->trySymbol("="))
        hair_accel = cin->get().Identifier();
      else if (tok == Token::Id("hair_builder") && cin->trySymbol("="))
        hair_builder = cin->get().Identifier();
      else if (tok == Token::Id("hair_traverser") && cin->trySymbol("="))
        hair_traverser = cin->get().Identifier();
      else if (tok == Token::Id("hair_builder_replication_factor") && cin->trySymbol("="))
        hair_builder_replication_factor = cin->get().Int();

      else if (tok == Token::Id("subdiv_accel") && cin->trySymbol("="))
        subdiv_accel = cin->get().Identifier();

      else if (tok == Token::Id("verbose") && cin->trySymbol("="))
        verbose = cin->get().Int();
      else if (tok == Token::Id("benchmark") && cin->trySymbol("="))
        benchmark = cin->get().Int();

      else if (tok == Token::Id("flags")) {
        scene_flags = 0;
        if (cin->trySymbol("=")) {
          do {
            Token flag = cin->get();
            if      (flag == Token::Id("static") ) scene_flags |= RTC_SCENE_STATIC;
            else if (flag == Token::Id("dynamic")) scene_flags |= RTC_SCENE_DYNAMIC;
            else if (flag == Token::Id("compact")) scene_flags |= RTC_SCENE_COMPACT;
            else if (flag == Token::Id("coherent")) scene_flags |= RTC_SCENE_COHERENT;
            else if (flag == Token::Id("incoherent")) scene_flags |= RTC_SCENE_INCOHERENT;
            else if (flag == Token::Id("high_quality")) scene_flags |= RTC_SCENE_HIGH_QUALITY;
            else if (flag == Token::Id("robust")) scene_flags |= RTC_SCENE_ROBUST;
          } while (cin->trySymbol("|"));
        }
      }
      else if (tok == Token::Id("memory_preallocation_factor") && cin->trySymbol("="))
        memory_preallocation_factor = cin->get().Float();

      else if (tok == Token::Id("regression") && cin->trySymbol("="))
        regression_testing = cin->get().Int();

      else if (tok == Token::Id("tessellation_cache_size") && cin->trySymbol("="))
        tessellation_cache_size = cin->get().Float() * 1024 * 1024;

      cin->trySymbol(","); // optional , separator
    }
  }

  RTCError* State::error()
  {
    RTCError* stored_error = (RTCError*) getTls(g_error);
    if (stored_error == nullptr) {
      Lock<MutexSys> lock(g_errors_mutex);
      stored_error = new RTCError(RTC_NO_ERROR);
      g_errors.push_back(stored_error);
      setTls(g_error,stored_error);
    }
    return stored_error;
  }

  bool State::verbosity(int N) {
    return N <= verbose;
  }

  void State::print()
  {
    std::cout << "general:" << std::endl;
    std::cout << "  build threads = " << g_numThreads << std::endl;
    std::cout << "  verbosity     = " << verbose << std::endl;

    std::cout << "triangles:" << std::endl;
    std::cout << "  accel         = " << tri_accel << std::endl;
    std::cout << "  builder       = " << tri_builder << std::endl;
    std::cout << "  traverser     = " << tri_traverser << std::endl;
    std::cout << "  replications  = " << tri_builder_replication_factor << std::endl;

    std::cout << "motion blur triangles:" << std::endl;
    std::cout << "  accel         = " << tri_accel_mb << std::endl;
    std::cout << "  builder       = " << tri_builder_mb << std::endl;
    std::cout << "  traverser     = " << tri_traverser_mb << std::endl;

    std::cout << "hair:" << std::endl;
    std::cout << "  accel         = " << hair_accel << std::endl;
    std::cout << "  builder       = " << hair_builder << std::endl;
    std::cout << "  traverser     = " << hair_traverser << std::endl;
    std::cout << "  replications  = " << hair_builder_replication_factor << std::endl;

    std::cout << "subdivision surfaces:" << std::endl;
    std::cout << "  accel         = " << subdiv_accel << std::endl;

#if defined(__MIC__)
    std::cout << "memory allocation:" << std::endl;
    std::cout << "  preallocation_factor  = " << memory_preallocation_factor << std::endl;
#endif
  }
}
<|endoftext|>


<commit_before>/*  -*- c++ -*-
    identitydialog.cpp

    KMail, the KDE mail client.
    Copyright (c) 2002 the KMail authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2.0, as published by the Free Software Foundation.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US
*/

#include "identitydialog.h"

// other KMail headers:
#include "kmidentity.h"
#include "signatureconfigurator.h"
#include "kmfoldercombobox.h"
#include "kmkernel.h"
#include "kmfoldermgr.h"

// other kdenetwork headers:
#include <kpgpui.h>

// other KDE headers:
#include <klocale.h>
#include <kmessagebox.h>
#include <kconfig.h>
#include <kapplication.h>

// Qt headers:
#include <qtabwidget.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qcheckbox.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qwhatsthis.h>

// other headers: (none)

namespace KMail {

  IdentityDialog::IdentityDialog( QWidget * parent, const char * name )
    : KDialogBase( Plain, i18n("Edit Identity"), Ok|Cancel|Help, Ok,
		   parent, name )
  {
    // tmp. vars:
    QWidget * tab;
    QLabel  * label;
    int row;
    QGridLayout * glay;
    QString msg;

    //
    // Tab Widget: General
    //
    row = -1;
    QVBoxLayout * vlay = new QVBoxLayout( plainPage(), 0, spacingHint() );
    QTabWidget *tabWidget = new QTabWidget( plainPage(), "config-identity-tab" );
    vlay->addWidget( tabWidget );

    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("&General") );
    glay = new QGridLayout( tab, 4, 2, marginHint(), spacingHint() );
    glay->setRowStretch( 3, 1 );
    glay->setColStretch( 1, 1 );

    // "Name" line edit and label:
    ++row;
    mNameEdit = new QLineEdit( tab );
    glay->addWidget( mNameEdit, row, 1 );
    glay->addWidget( new QLabel( mNameEdit, i18n("&Your name:"), tab ), row, 0 );

    // "Organization" line edit and label:
    ++row;
    mOrganizationEdit = new QLineEdit( tab );
    glay->addWidget( mOrganizationEdit, row, 1 );
    glay->addWidget( new QLabel( mOrganizationEdit,
				 i18n("Organi&zation:"), tab ), row, 0 );

    // "Email Address" line edit and label:
    // (row 3: spacer)
    ++row;
    mEmailEdit = new QLineEdit( tab );
    glay->addWidget( mEmailEdit, row, 1 );
    glay->addWidget( new QLabel( mEmailEdit, i18n("&Email address:"), tab ),
		     row, 0 );

    //
    // Tab Widget: Advanced
    //
    row = -1;
    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("&Advanced") );
    glay = new QGridLayout( tab, 7, 2, marginHint(), spacingHint() );
    // the last (empty) row takes all the remaining space
    glay->setRowStretch( 7-1, 1 );
    glay->setColStretch( 1, 1 );

    // "Reply-To Address" line edit and label:
    ++row;
    mReplyToEdit = new QLineEdit( tab );
    glay->addWidget( mReplyToEdit, row, 1 );
    glay->addWidget( new QLabel( mReplyToEdit,
				 i18n("&Reply-To address:"), tab ), row, 0 );

    // "BCC addresses" line edit and label:
    ++row;
    mBccEdit = new QLineEdit( tab );
    glay->addWidget( mBccEdit, row, 1 );
    label = new QLabel( mBccEdit, i18n("&BCC addresses:"), tab );
    glay->addWidget( label, row, 0 );
    msg = i18n("<qt>
BCC (Blind Carbon Copy) addresses
"
	       "
The addresses that you enter here will be added to each"
	       "   outgoing mail that is sent with this identity. They will not"
	       "   be visible to other recipients.
"
	       "
This is commonly used to send a copy of each sent message to"
	       "   another account of yours.
"
	       "
If in doubt, leave this field blank.
</qt>");
    QWhatsThis::add( label, msg );
    QWhatsThis::add( mBccEdit, msg );

    // "OpenPGP Key" requester and label:
    ++row;
    mPgpKeyRequester = new Kpgp::SecretKeyRequester( tab );
    mPgpKeyRequester->dialogButton()->setText( i18n("Chang&e...") );
    mPgpKeyRequester->setDialogCaption( i18n("Your OpenPGP Key") );
    mPgpKeyRequester->setDialogMessage( i18n("Select the OpenPGP key which "
					     "should be used to sign your "
					     "messages and when encrypting to "
					     "yourself.") );
    msg = i18n("<qt>
The OpenPGP key you choose here will be used "
	       "to sign messages and to encrypt messages to "
	       "yourself.
</qt>");

    label = new QLabel( mPgpKeyRequester, i18n("OpenPGP key:"), tab );
    QWhatsThis::add( mPgpKeyRequester, msg );
    QWhatsThis::add( label, msg );

    glay->addWidget( label, row, 0 );
    glay->addWidget( mPgpKeyRequester, row, 1 );

    // "Sent-mail Folder" combo box and label:
    ++row;
    mFccCombo = new KMFolderComboBox( tab );
    mFccCombo->showOutboxFolder( false );
    glay->addWidget( mFccCombo, row, 1 );
    glay->addWidget( new QLabel( mFccCombo, i18n("Sent-mail &folder:"), tab ),
		     row, 0 );

    // "Drafts Folder" combo box and label:
    ++row;
    mDraftsCombo = new KMFolderComboBox( tab );
    mDraftsCombo->showOutboxFolder( false );
    glay->addWidget( mDraftsCombo, row, 1 );
    glay->addWidget( new QLabel( mDraftsCombo, i18n("&Drafts folder:"), tab ),
		     row, 0 );

    // "Special transport" combobox and label:
    ++row;
    mTransportCheck = new QCheckBox( i18n("Special &transport:"), tab );
    glay->addWidget( mTransportCheck, row, 0 );
    mTransportCombo = new QComboBox( true, tab );
    mTransportCombo->setEnabled( false ); // since !mTransportCheck->isChecked()
    glay->addWidget( mTransportCombo, row, 1 );
    connect( mTransportCheck, SIGNAL(toggled(bool)),
	     mTransportCombo, SLOT(setEnabled(bool)) );

    // the last row is a spacer

    //
    // Tab Widget: Signature
    //
    mSignatureConfigurator = new SignatureConfigurator( tabWidget );
    mSignatureConfigurator->layout()->setMargin( KDialog::marginHint() );
    tabWidget->addTab( mSignatureConfigurator, i18n("&Signature") );

    KConfigGroup geometry( kapp->config(), "Geometry" );
    if ( geometry.hasKey( "Identity Dialog size" ) )
      resize( geometry.readSizeEntry( "Identity Dialog size" ) );
  }

  IdentityDialog::~IdentityDialog() {
    KConfigGroup geometry( kapp->config(), "Geometry" );
    geometry.writeEntry( "Identity Dialog size", size() );
  }

  bool IdentityDialog::checkFolderExists( const QString & folderID,
					  const QString & msg ) {
    KMFolder * folder = kernel->folderMgr()->findIdString( folderID );
    if ( !folder )
      folder = kernel->imapFolderMgr()->findIdString( folderID );
    if ( !folder ) {
      KMessageBox::sorry( this, msg );
      return false;
    }
    return true;
  }

  void IdentityDialog::setIdentity( KMIdentity & ident ) {
    // "General" tab:
    mNameEdit->setText( ident.fullName() );
    mOrganizationEdit->setText( ident.organization() );
    mEmailEdit->setText( ident.emailAddr() );

    // "Advanced" tab:
    mPgpKeyRequester->setKeyIDs( Kpgp::KeyIDList() << ident.pgpIdentity() );
    mReplyToEdit->setText( ident.replyToAddr() );
    mBccEdit->setText( ident.bcc() );
    mTransportCheck->setChecked( !ident.transport().isEmpty() );
    mTransportCombo->setEditText( ident.transport() );
    mTransportCombo->setEnabled( !ident.transport().isEmpty() );

    if ( ident.fcc().isEmpty() ||
	 !checkFolderExists( ident.fcc(),
			     i18n("The custom sent-mail folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default sent-mail folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mFccCombo->setFolder( kernel->sentFolder() );
    else
      mFccCombo->setFolder( ident.fcc() );

    if ( ident.drafts().isEmpty() ||
	 !checkFolderExists( ident.drafts(),
			     i18n("The custom drafts folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default drafts folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mDraftsCombo->setFolder( kernel->draftsFolder() );
    else
      mDraftsCombo->setFolder( ident.drafts() );

    // "Signature" tab:
    mSignatureConfigurator->setSignature( ident.signature() );
  }

  void IdentityDialog::updateIdentity( KMIdentity & ident ) {
    // "General" tab:
    ident.setFullName( mNameEdit->text() );
    ident.setOrganization( mOrganizationEdit->text() );
    ident.setEmailAddr( mEmailEdit->text() );
    // "Advanced" tab:
    ident.setPgpIdentity( mPgpKeyRequester->keyIDs().first() );
    ident.setReplyToAddr( mReplyToEdit->text() );
    ident.setBcc( mBccEdit->text() );
    ident.setTransport( ( mTransportCheck->isChecked() ) ?
			mTransportCombo->currentText() : QString::null );
    ident.setFcc( mFccCombo->getFolder() ?
		  mFccCombo->getFolder()->idString() : QString::null );
    ident.setDrafts( mDraftsCombo->getFolder() ?
		     mDraftsCombo->getFolder()->idString() : QString::null );
    // "Signature" tab:
    ident.setSignature( mSignatureConfigurator->signature() );
  }

  void IdentityDialog::slotUpdateTransportCombo( const QStringList & sl ) {
    // save old setting:
    QString content = mTransportCombo->currentText();
    // update combo box:
    mTransportCombo->clear();
    mTransportCombo->insertStringList( sl );
    // restore saved setting:
    mTransportCombo->setEditText( content );
  };

};

#include "identitydialog.moc"
<commit_msg>show identity name in caption<commit_after>/*  -*- c++ -*-
    identitydialog.cpp

    KMail, the KDE mail client.
    Copyright (c) 2002 the KMail authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2.0, as published by the Free Software Foundation.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US
*/

#include "identitydialog.h"

// other KMail headers:
#include "kmidentity.h"
#include "signatureconfigurator.h"
#include "kmfoldercombobox.h"
#include "kmkernel.h"
#include "kmfoldermgr.h"

// other kdenetwork headers:
#include <kpgpui.h>

// other KDE headers:
#include <klocale.h>
#include <kmessagebox.h>
#include <kconfig.h>
#include <kapplication.h>

// Qt headers:
#include <qtabwidget.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qcheckbox.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qwhatsthis.h>

// other headers: (none)

namespace KMail {

  IdentityDialog::IdentityDialog( QWidget * parent, const char * name )
    : KDialogBase( Plain, i18n("Edit Identity"), Ok|Cancel|Help, Ok,
		   parent, name )
  {
    // tmp. vars:
    QWidget * tab;
    QLabel  * label;
    int row;
    QGridLayout * glay;
    QString msg;

    //
    // Tab Widget: General
    //
    row = -1;
    QVBoxLayout * vlay = new QVBoxLayout( plainPage(), 0, spacingHint() );
    QTabWidget *tabWidget = new QTabWidget( plainPage(), "config-identity-tab" );
    vlay->addWidget( tabWidget );

    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("&General") );
    glay = new QGridLayout( tab, 4, 2, marginHint(), spacingHint() );
    glay->setRowStretch( 3, 1 );
    glay->setColStretch( 1, 1 );

    // "Name" line edit and label:
    ++row;
    mNameEdit = new QLineEdit( tab );
    glay->addWidget( mNameEdit, row, 1 );
    glay->addWidget( new QLabel( mNameEdit, i18n("&Your name:"), tab ), row, 0 );

    // "Organization" line edit and label:
    ++row;
    mOrganizationEdit = new QLineEdit( tab );
    glay->addWidget( mOrganizationEdit, row, 1 );
    glay->addWidget( new QLabel( mOrganizationEdit,
				 i18n("Organi&zation:"), tab ), row, 0 );

    // "Email Address" line edit and label:
    // (row 3: spacer)
    ++row;
    mEmailEdit = new QLineEdit( tab );
    glay->addWidget( mEmailEdit, row, 1 );
    glay->addWidget( new QLabel( mEmailEdit, i18n("&Email address:"), tab ),
		     row, 0 );

    //
    // Tab Widget: Advanced
    //
    row = -1;
    tab = new QWidget( tabWidget );
    tabWidget->addTab( tab, i18n("&Advanced") );
    glay = new QGridLayout( tab, 7, 2, marginHint(), spacingHint() );
    // the last (empty) row takes all the remaining space
    glay->setRowStretch( 7-1, 1 );
    glay->setColStretch( 1, 1 );

    // "Reply-To Address" line edit and label:
    ++row;
    mReplyToEdit = new QLineEdit( tab );
    glay->addWidget( mReplyToEdit, row, 1 );
    glay->addWidget( new QLabel( mReplyToEdit,
				 i18n("&Reply-To address:"), tab ), row, 0 );

    // "BCC addresses" line edit and label:
    ++row;
    mBccEdit = new QLineEdit( tab );
    glay->addWidget( mBccEdit, row, 1 );
    label = new QLabel( mBccEdit, i18n("&BCC addresses:"), tab );
    glay->addWidget( label, row, 0 );
    msg = i18n("<qt>
BCC (Blind Carbon Copy) addresses
"
	       "
The addresses that you enter here will be added to each"
	       "   outgoing mail that is sent with this identity. They will not"
	       "   be visible to other recipients.
"
	       "
This is commonly used to send a copy of each sent message to"
	       "   another account of yours.
"
	       "
If in doubt, leave this field blank.
</qt>");
    QWhatsThis::add( label, msg );
    QWhatsThis::add( mBccEdit, msg );

    // "OpenPGP Key" requester and label:
    ++row;
    mPgpKeyRequester = new Kpgp::SecretKeyRequester( tab );
    mPgpKeyRequester->dialogButton()->setText( i18n("Chang&e...") );
    mPgpKeyRequester->setDialogCaption( i18n("Your OpenPGP Key") );
    mPgpKeyRequester->setDialogMessage( i18n("Select the OpenPGP key which "
					     "should be used to sign your "
					     "messages and when encrypting to "
					     "yourself.") );
    msg = i18n("<qt>
The OpenPGP key you choose here will be used "
	       "to sign messages and to encrypt messages to "
	       "yourself.
</qt>");

    label = new QLabel( mPgpKeyRequester, i18n("OpenPGP key:"), tab );
    QWhatsThis::add( mPgpKeyRequester, msg );
    QWhatsThis::add( label, msg );

    glay->addWidget( label, row, 0 );
    glay->addWidget( mPgpKeyRequester, row, 1 );

    // "Sent-mail Folder" combo box and label:
    ++row;
    mFccCombo = new KMFolderComboBox( tab );
    mFccCombo->showOutboxFolder( false );
    glay->addWidget( mFccCombo, row, 1 );
    glay->addWidget( new QLabel( mFccCombo, i18n("Sent-mail &folder:"), tab ),
		     row, 0 );

    // "Drafts Folder" combo box and label:
    ++row;
    mDraftsCombo = new KMFolderComboBox( tab );
    mDraftsCombo->showOutboxFolder( false );
    glay->addWidget( mDraftsCombo, row, 1 );
    glay->addWidget( new QLabel( mDraftsCombo, i18n("&Drafts folder:"), tab ),
		     row, 0 );

    // "Special transport" combobox and label:
    ++row;
    mTransportCheck = new QCheckBox( i18n("Special &transport:"), tab );
    glay->addWidget( mTransportCheck, row, 0 );
    mTransportCombo = new QComboBox( true, tab );
    mTransportCombo->setEnabled( false ); // since !mTransportCheck->isChecked()
    glay->addWidget( mTransportCombo, row, 1 );
    connect( mTransportCheck, SIGNAL(toggled(bool)),
	     mTransportCombo, SLOT(setEnabled(bool)) );

    // the last row is a spacer

    //
    // Tab Widget: Signature
    //
    mSignatureConfigurator = new SignatureConfigurator( tabWidget );
    mSignatureConfigurator->layout()->setMargin( KDialog::marginHint() );
    tabWidget->addTab( mSignatureConfigurator, i18n("&Signature") );

    KConfigGroup geometry( kapp->config(), "Geometry" );
    if ( geometry.hasKey( "Identity Dialog size" ) )
      resize( geometry.readSizeEntry( "Identity Dialog size" ) );
  }

  IdentityDialog::~IdentityDialog() {
    KConfigGroup geometry( kapp->config(), "Geometry" );
    geometry.writeEntry( "Identity Dialog size", size() );
  }

  bool IdentityDialog::checkFolderExists( const QString & folderID,
					  const QString & msg ) {
    KMFolder * folder = kernel->folderMgr()->findIdString( folderID );
    if ( !folder )
      folder = kernel->imapFolderMgr()->findIdString( folderID );
    if ( !folder ) {
      KMessageBox::sorry( this, msg );
      return false;
    }
    return true;
  }

  void IdentityDialog::setIdentity( KMIdentity & ident ) {

    setCaption( i18n("Edit Identity \"%1\"").arg( ident.identityName() ) );

    // "General" tab:
    mNameEdit->setText( ident.fullName() );
    mOrganizationEdit->setText( ident.organization() );
    mEmailEdit->setText( ident.emailAddr() );

    // "Advanced" tab:
    mPgpKeyRequester->setKeyIDs( Kpgp::KeyIDList() << ident.pgpIdentity() );
    mReplyToEdit->setText( ident.replyToAddr() );
    mBccEdit->setText( ident.bcc() );
    mTransportCheck->setChecked( !ident.transport().isEmpty() );
    mTransportCombo->setEditText( ident.transport() );
    mTransportCombo->setEnabled( !ident.transport().isEmpty() );

    if ( ident.fcc().isEmpty() ||
	 !checkFolderExists( ident.fcc(),
			     i18n("The custom sent-mail folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default sent-mail folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mFccCombo->setFolder( kernel->sentFolder() );
    else
      mFccCombo->setFolder( ident.fcc() );

    if ( ident.drafts().isEmpty() ||
	 !checkFolderExists( ident.drafts(),
			     i18n("The custom drafts folder for identity "
				  "\"%1\" doesn't exist (anymore). "
				  "Therefore the default drafts folder "
				  "will be used.")
			     .arg( ident.identityName() ) ) )
      mDraftsCombo->setFolder( kernel->draftsFolder() );
    else
      mDraftsCombo->setFolder( ident.drafts() );

    // "Signature" tab:
    mSignatureConfigurator->setSignature( ident.signature() );
  }

  void IdentityDialog::updateIdentity( KMIdentity & ident ) {
    // "General" tab:
    ident.setFullName( mNameEdit->text() );
    ident.setOrganization( mOrganizationEdit->text() );
    ident.setEmailAddr( mEmailEdit->text() );
    // "Advanced" tab:
    ident.setPgpIdentity( mPgpKeyRequester->keyIDs().first() );
    ident.setReplyToAddr( mReplyToEdit->text() );
    ident.setBcc( mBccEdit->text() );
    ident.setTransport( ( mTransportCheck->isChecked() ) ?
			mTransportCombo->currentText() : QString::null );
    ident.setFcc( mFccCombo->getFolder() ?
		  mFccCombo->getFolder()->idString() : QString::null );
    ident.setDrafts( mDraftsCombo->getFolder() ?
		     mDraftsCombo->getFolder()->idString() : QString::null );
    // "Signature" tab:
    ident.setSignature( mSignatureConfigurator->signature() );
  }

  void IdentityDialog::slotUpdateTransportCombo( const QStringList & sl ) {
    // save old setting:
    QString content = mTransportCombo->currentText();
    // update combo box:
    mTransportCombo->clear();
    mTransportCombo->insertStringList( sl );
    // restore saved setting:
    mTransportCombo->setEditText( content );
  };

};

#include "identitydialog.moc"
<|endoftext|>


<commit_before>/*
 * RBDL - Rigid Body Dynamics Library
 * Copyright (c) 2011-2012 Martin Felis <martin.felis@iwr.uni-heidelberg.de>
 *
 * Licensed under the zlib license. See LICENSE for more details.
 */

#include <iostream>
#include <limits>
#include <assert.h>

#include "rbdl_mathutils.h"

#include "Logging.h"

#include "Model.h"
#include "Body.h"
#include "Joint.h"

using namespace RigidBodyDynamics;
using namespace RigidBodyDynamics::Math;

void Model::Init() {
	Body root_body;
	Joint root_joint;

	Vector3d zero_position (0., 0., 0.);
	SpatialVector zero_spatial (0., 0., 0., 0., 0., 0.);

	// structural information
	lambda.push_back(0.);
	mu.push_back(std::vector<unsigned int>());
	dof_count = 0;
	previously_added_body_id = 0;

	gravity = Vector3d (0., -9.81, 0.);

	// state information
	v.push_back(zero_spatial);
	a.push_back(zero_spatial);

	// Joints
	mJoints.push_back(root_joint);
	S.push_back (zero_spatial);
	X_T.push_back(SpatialTransform());

	// Dynamic variables
	c.push_back(zero_spatial);
	IA.push_back(SpatialMatrixIdentity);
	pA.push_back(zero_spatial);
	U.push_back(zero_spatial);

	u = VectorNd::Zero(1);
	d = VectorNd::Zero(1);

	f.push_back (zero_spatial);
	Ic.push_back (
			SpatialRigidBodyInertia(
				0.,
				Vector3d (0., 0., 0.),
				Matrix3d::Zero(3,3)
				)
			);

	// Bodies
	X_lambda.push_back(SpatialTransform());
	X_base.push_back(SpatialTransform());

	mBodies.push_back(root_body);
	mBodyNameMap["ROOT"] = 0;

	fixed_body_discriminator = std::numeric_limits<unsigned int>::max() / 2;
}

unsigned int AddBodyFixedJoint (
		Model &model,
		const unsigned int parent_id,
		const SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name) {
	FixedBody fbody = FixedBody::CreateFromBody (body);
	fbody.mMovableParent = parent_id;
	fbody.mParentTransform = joint_frame;

	if (model.IsFixedBodyId(parent_id)) {
		FixedBody fixed_parent = model.mFixedBodies[parent_id - model.fixed_body_discriminator];

		fbody.mMovableParent = fixed_parent.mMovableParent;
		fbody.mParentTransform = joint_frame * fixed_parent.mParentTransform;
	}

	// merge the two bodies
	Body parent_body = model.mBodies[fbody.mMovableParent];
	parent_body.Join (fbody.mParentTransform, body);
	model.mBodies[fbody.mMovableParent] = parent_body;

	model.mFixedBodies.push_back (fbody);

	if (model.mFixedBodies.size() > std::numeric_limits<unsigned int>::max() - model.fixed_body_discriminator) {
		std::cerr << "Error: cannot add more than " << std::numeric_limits<unsigned int>::max() - model.mFixedBodies.size() << " fixed bodies. You need to modify Model::fixed_body_discriminator for this." << std::endl;
		assert (0);
		abort();
	}

	if (body_name.size() != 0) {
		if (model.mBodyNameMap.find(body_name) != model.mBodyNameMap.end()) {
			std::cerr << "Error: Body with name '" << body_name << "' already exists!" << std::endl;
			assert (0);
			abort();
		}
		model.mBodyNameMap[body_name] = model.mFixedBodies.size() + model.fixed_body_discriminator - 1;
	}

	return model.mFixedBodies.size() + model.fixed_body_discriminator - 1;
}

unsigned int AddBodyMultiDofJoint (
		Model &model,
		const unsigned int parent_id,
		const SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name) {
	// Here we emulate multi DoF joints by simply adding nullbodies. This
	// allows us to use fixed size elements for S,v,a, etc. which is very
	// fast in Eigen.
	unsigned int joint_count;
	if (joint.mJointType == JointType1DoF)
		joint_count = 1;
	else if (joint.mJointType == JointType2DoF)
		joint_count = 2;
	else if (joint.mJointType == JointType3DoF)
		joint_count = 3;
	else if (joint.mJointType == JointType4DoF)
		joint_count = 4;
	else if (joint.mJointType == JointType5DoF)
		joint_count = 5;
	else if (joint.mJointType == JointType6DoF)
		joint_count = 6;
	else {
		std::cerr << "Error: Invalid joint type: " << joint.mJointType << std::endl;
		assert (0 && !"Invalid joint type!");
	}

	Body null_body (0., Vector3d (0., 0., 0.), Vector3d (0., 0., 0.));
	unsigned int null_parent = parent_id;
	SpatialTransform joint_frame_transform;

	Joint single_dof_joint;
	unsigned int j;

	// Here we add multiple virtual bodies that have no mass or inertia for
	// which each is attached to the model with a single degree of freedom
	// joint.
	for (j = 0; j < joint_count; j++) {
		Vector3d rotation (
				joint.mJointAxes[j][0],
				joint.mJointAxes[j][1],
				joint.mJointAxes[j][2]);
		Vector3d translation (
				joint.mJointAxes[j][3],
				joint.mJointAxes[j][4],
				joint.mJointAxes[j][5]);

		if (rotation == Vector3d (0., 0., 0.)) {
			single_dof_joint = Joint (JointTypePrismatic, translation);
		} else if (translation == Vector3d (0., 0., 0.)) {
			single_dof_joint = Joint (JointTypeRevolute, rotation);
		}

		// the first joint has to be transformed by joint_frame, all the
		// others must have a null transformation
		if (j == 0)
			joint_frame_transform = joint_frame;
		else
			joint_frame_transform = SpatialTransform();

		if (j == joint_count - 1)
			// if we are at the last we must add the real body
			break;
		else
			// otherwise we just add an intermediate body
			null_parent = model.AddBody (null_parent, joint_frame_transform, single_dof_joint, null_body);
	}

	return model.AddBody (null_parent, joint_frame_transform, single_dof_joint, body, body_name);
}

unsigned int Model::AddBody (const unsigned int parent_id,
		const SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name) {
	if (joint.mJointType == JointTypeFixed) {
		previously_added_body_id = AddBodyFixedJoint (*this, parent_id, joint_frame, joint, body, body_name);
		return previously_added_body_id;
	}
	else if (joint.mJointType != JointTypePrismatic
			&& joint.mJointType != JointTypeRevolute) {
		previously_added_body_id = AddBodyMultiDofJoint (*this, parent_id, joint_frame, joint, body, body_name);
		return previously_added_body_id;
	}

	assert (lambda.size() > 0);
	assert (joint.mJointType != JointTypeUndefined);

	// If we add the body to a fixed body we have to make sure that we
	// actually add it to its movable parent.
	unsigned int movable_parent_id = parent_id;
	SpatialTransform movable_parent_transform;

	if (IsFixedBodyId(parent_id)) {
		unsigned int fbody_id = parent_id - fixed_body_discriminator;
		movable_parent_id = mFixedBodies[fbody_id].mMovableParent;
		movable_parent_transform = mFixedBodies[fbody_id].mParentTransform;
	}

	// structural information
	lambda.push_back(movable_parent_id);
	mu.push_back(std::vector<unsigned int>());
	mu.at(movable_parent_id).push_back(mBodies.size());

	// Bodies
	X_lambda.push_back(SpatialTransform());
	X_base.push_back(SpatialTransform());
	mBodies.push_back(body);

	if (body_name.size() != 0) {
		if (mBodyNameMap.find(body_name) != mBodyNameMap.end()) {
			std::cerr << "Error: Body with name '" << body_name << "' already exists!" << std::endl;
			assert (0);
			abort();
		}
		mBodyNameMap[body_name] = mBodies.size() - 1;
	}

	dof_count++;

	// state information
	v.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
	a.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));

	// Joints
	mJoints.push_back(joint);
	S.push_back (joint.mJointAxes[0]);

	// we have to invert the transformation as it is later always used from the
	// child bodies perspective.
	X_T.push_back(joint_frame * movable_parent_transform);

	// Dynamic variables
	c.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
	IA.push_back(body.mSpatialInertia);
	pA.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
	U.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));

	d = VectorNd::Zero (mBodies.size());
	u = VectorNd::Zero (mBodies.size());

	f.push_back (SpatialVector (0., 0., 0., 0., 0., 0.));
	Ic.push_back (
			SpatialRigidBodyInertia(
				body.mMass,
				body.mCenterOfMass,
				body.mInertia
				)
			);

	if (mBodies.size() == fixed_body_discriminator) {
		std::cerr << "Error: cannot add more than " << fixed_body_discriminator << " movable bodies. You need to modify Model::fixed_body_discriminator for this." << std::endl;
		assert (0);
		abort();
	}

	previously_added_body_id = mBodies.size() - 1;

	return previously_added_body_id;
}

unsigned int Model::AppendBody (
		const Math::SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name
		) {
	return Model::AddBody (previously_added_body_id, joint_frame,
			joint, body, body_name);
}

unsigned int Model::SetFloatingBaseBody (const Body &body) {
	assert (lambda.size() >= 0);

	// Add five zero weight bodies and append the given body last. Order of
	// the degrees of freedom is:
	// 		tx ty tz rz ry rx
	//

	Joint floating_base_joint (
			SpatialVector (0., 0., 0., 1., 0., 0.),
			SpatialVector (0., 0., 0., 0., 1., 0.),
			SpatialVector (0., 0., 0., 0., 0., 1.),
			SpatialVector (0., 0., 1., 0., 0., 0.),
			SpatialVector (0., 1., 0., 0., 0., 0.),
			SpatialVector (1., 0., 0., 0., 0., 0.)
			);

	unsigned int body_id = this->AddBody (0, Xtrans (Vector3d (0., 0., 0.)), floating_base_joint, body);

	return body_id;
}
<commit_msg>get rid of warning<commit_after>/*
 * RBDL - Rigid Body Dynamics Library
 * Copyright (c) 2011-2012 Martin Felis <martin.felis@iwr.uni-heidelberg.de>
 *
 * Licensed under the zlib license. See LICENSE for more details.
 */

#include <iostream>
#include <limits>
#include <assert.h>

#include "rbdl_mathutils.h"

#include "Logging.h"

#include "Model.h"
#include "Body.h"
#include "Joint.h"

using namespace RigidBodyDynamics;
using namespace RigidBodyDynamics::Math;

void Model::Init() {
	Body root_body;
	Joint root_joint;

	Vector3d zero_position (0., 0., 0.);
	SpatialVector zero_spatial (0., 0., 0., 0., 0., 0.);

	// structural information
	lambda.push_back(0.);
	mu.push_back(std::vector<unsigned int>());
	dof_count = 0;
	previously_added_body_id = 0;

	gravity = Vector3d (0., -9.81, 0.);

	// state information
	v.push_back(zero_spatial);
	a.push_back(zero_spatial);

	// Joints
	mJoints.push_back(root_joint);
	S.push_back (zero_spatial);
	X_T.push_back(SpatialTransform());

	// Dynamic variables
	c.push_back(zero_spatial);
	IA.push_back(SpatialMatrixIdentity);
	pA.push_back(zero_spatial);
	U.push_back(zero_spatial);

	u = VectorNd::Zero(1);
	d = VectorNd::Zero(1);

	f.push_back (zero_spatial);
	Ic.push_back (
			SpatialRigidBodyInertia(
				0.,
				Vector3d (0., 0., 0.),
				Matrix3d::Zero(3,3)
				)
			);

	// Bodies
	X_lambda.push_back(SpatialTransform());
	X_base.push_back(SpatialTransform());

	mBodies.push_back(root_body);
	mBodyNameMap["ROOT"] = 0;

	fixed_body_discriminator = std::numeric_limits<unsigned int>::max() / 2;
}

unsigned int AddBodyFixedJoint (
		Model &model,
		const unsigned int parent_id,
		const SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name) {
	FixedBody fbody = FixedBody::CreateFromBody (body);
	fbody.mMovableParent = parent_id;
	fbody.mParentTransform = joint_frame;

	if (model.IsFixedBodyId(parent_id)) {
		FixedBody fixed_parent = model.mFixedBodies[parent_id - model.fixed_body_discriminator];

		fbody.mMovableParent = fixed_parent.mMovableParent;
		fbody.mParentTransform = joint_frame * fixed_parent.mParentTransform;
	}

	// merge the two bodies
	Body parent_body = model.mBodies[fbody.mMovableParent];
	parent_body.Join (fbody.mParentTransform, body);
	model.mBodies[fbody.mMovableParent] = parent_body;

	model.mFixedBodies.push_back (fbody);

	if (model.mFixedBodies.size() > std::numeric_limits<unsigned int>::max() - model.fixed_body_discriminator) {
		std::cerr << "Error: cannot add more than " << std::numeric_limits<unsigned int>::max() - model.mFixedBodies.size() << " fixed bodies. You need to modify Model::fixed_body_discriminator for this." << std::endl;
		assert (0);
		abort();
	}

	if (body_name.size() != 0) {
		if (model.mBodyNameMap.find(body_name) != model.mBodyNameMap.end()) {
			std::cerr << "Error: Body with name '" << body_name << "' already exists!" << std::endl;
			assert (0);
			abort();
		}
		model.mBodyNameMap[body_name] = model.mFixedBodies.size() + model.fixed_body_discriminator - 1;
	}

	return model.mFixedBodies.size() + model.fixed_body_discriminator - 1;
}

unsigned int AddBodyMultiDofJoint (
		Model &model,
		const unsigned int parent_id,
		const SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name) {
	// Here we emulate multi DoF joints by simply adding nullbodies. This
	// allows us to use fixed size elements for S,v,a, etc. which is very
	// fast in Eigen.
	unsigned int joint_count=0;
	if (joint.mJointType == JointType1DoF)
		joint_count = 1;
	else if (joint.mJointType == JointType2DoF)
		joint_count = 2;
	else if (joint.mJointType == JointType3DoF)
		joint_count = 3;
	else if (joint.mJointType == JointType4DoF)
		joint_count = 4;
	else if (joint.mJointType == JointType5DoF)
		joint_count = 5;
	else if (joint.mJointType == JointType6DoF)
		joint_count = 6;
	else {
		std::cerr << "Error: Invalid joint type: " << joint.mJointType << std::endl;
		assert (0 && !"Invalid joint type!");
	}

	Body null_body (0., Vector3d (0., 0., 0.), Vector3d (0., 0., 0.));
	unsigned int null_parent = parent_id;
	SpatialTransform joint_frame_transform;

	Joint single_dof_joint;
	unsigned int j;

	// Here we add multiple virtual bodies that have no mass or inertia for
	// which each is attached to the model with a single degree of freedom
	// joint.
	for (j = 0; j < joint_count; j++) {
		Vector3d rotation (
				joint.mJointAxes[j][0],
				joint.mJointAxes[j][1],
				joint.mJointAxes[j][2]);
		Vector3d translation (
				joint.mJointAxes[j][3],
				joint.mJointAxes[j][4],
				joint.mJointAxes[j][5]);

		if (rotation == Vector3d (0., 0., 0.)) {
			single_dof_joint = Joint (JointTypePrismatic, translation);
		} else if (translation == Vector3d (0., 0., 0.)) {
			single_dof_joint = Joint (JointTypeRevolute, rotation);
		}

		// the first joint has to be transformed by joint_frame, all the
		// others must have a null transformation
		if (j == 0)
			joint_frame_transform = joint_frame;
		else
			joint_frame_transform = SpatialTransform();

		if (j == joint_count - 1)
			// if we are at the last we must add the real body
			break;
		else
			// otherwise we just add an intermediate body
			null_parent = model.AddBody (null_parent, joint_frame_transform, single_dof_joint, null_body);
	}

	return model.AddBody (null_parent, joint_frame_transform, single_dof_joint, body, body_name);
}

unsigned int Model::AddBody (const unsigned int parent_id,
		const SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name) {
	if (joint.mJointType == JointTypeFixed) {
		previously_added_body_id = AddBodyFixedJoint (*this, parent_id, joint_frame, joint, body, body_name);
		return previously_added_body_id;
	}
	else if (joint.mJointType != JointTypePrismatic
			&& joint.mJointType != JointTypeRevolute) {
		previously_added_body_id = AddBodyMultiDofJoint (*this, parent_id, joint_frame, joint, body, body_name);
		return previously_added_body_id;
	}

	assert (lambda.size() > 0);
	assert (joint.mJointType != JointTypeUndefined);

	// If we add the body to a fixed body we have to make sure that we
	// actually add it to its movable parent.
	unsigned int movable_parent_id = parent_id;
	SpatialTransform movable_parent_transform;

	if (IsFixedBodyId(parent_id)) {
		unsigned int fbody_id = parent_id - fixed_body_discriminator;
		movable_parent_id = mFixedBodies[fbody_id].mMovableParent;
		movable_parent_transform = mFixedBodies[fbody_id].mParentTransform;
	}

	// structural information
	lambda.push_back(movable_parent_id);
	mu.push_back(std::vector<unsigned int>());
	mu.at(movable_parent_id).push_back(mBodies.size());

	// Bodies
	X_lambda.push_back(SpatialTransform());
	X_base.push_back(SpatialTransform());
	mBodies.push_back(body);

	if (body_name.size() != 0) {
		if (mBodyNameMap.find(body_name) != mBodyNameMap.end()) {
			std::cerr << "Error: Body with name '" << body_name << "' already exists!" << std::endl;
			assert (0);
			abort();
		}
		mBodyNameMap[body_name] = mBodies.size() - 1;
	}

	dof_count++;

	// state information
	v.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
	a.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));

	// Joints
	mJoints.push_back(joint);
	S.push_back (joint.mJointAxes[0]);

	// we have to invert the transformation as it is later always used from the
	// child bodies perspective.
	X_T.push_back(joint_frame * movable_parent_transform);

	// Dynamic variables
	c.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
	IA.push_back(body.mSpatialInertia);
	pA.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));
	U.push_back(SpatialVector(0., 0., 0., 0., 0., 0.));

	d = VectorNd::Zero (mBodies.size());
	u = VectorNd::Zero (mBodies.size());

	f.push_back (SpatialVector (0., 0., 0., 0., 0., 0.));
	Ic.push_back (
			SpatialRigidBodyInertia(
				body.mMass,
				body.mCenterOfMass,
				body.mInertia
				)
			);

	if (mBodies.size() == fixed_body_discriminator) {
		std::cerr << "Error: cannot add more than " << fixed_body_discriminator << " movable bodies. You need to modify Model::fixed_body_discriminator for this." << std::endl;
		assert (0);
		abort();
	}

	previously_added_body_id = mBodies.size() - 1;

	return previously_added_body_id;
}

unsigned int Model::AppendBody (
		const Math::SpatialTransform &joint_frame,
		const Joint &joint,
		const Body &body,
		std::string body_name
		) {
	return Model::AddBody (previously_added_body_id, joint_frame,
			joint, body, body_name);
}

unsigned int Model::SetFloatingBaseBody (const Body &body) {
	assert (lambda.size() >= 0);

	// Add five zero weight bodies and append the given body last. Order of
	// the degrees of freedom is:
	// 		tx ty tz rz ry rx
	//

	Joint floating_base_joint (
			SpatialVector (0., 0., 0., 1., 0., 0.),
			SpatialVector (0., 0., 0., 0., 1., 0.),
			SpatialVector (0., 0., 0., 0., 0., 1.),
			SpatialVector (0., 0., 1., 0., 0., 0.),
			SpatialVector (0., 1., 0., 0., 0., 0.),
			SpatialVector (1., 0., 0., 0., 0., 0.)
			);

	unsigned int body_id = this->AddBody (0, Xtrans (Vector3d (0., 0., 0.)), floating_base_joint, body);

	return body_id;
}
<|endoftext|>


<commit_before>
#include "shapefile.hpp"
#include "shape_object.hpp"

namespace shp {

VALUE shapefile::_klass = Qnil;

VALUE shapefile::klass() {
  return shapefile::_klass;
}

shapefile::shapefile(SHPHandle handle)
  : _handle(handle)
{
}

shapefile::~shapefile() {
  if (_handle) {
    SHPClose(_handle);
    _handle = NULL;
  }
}

VALUE shapefile::open(VALUE klass, VALUE filename, VALUE accessType)
{
  CHECK_ARGUMENT_STRING(filename);
  CHECK_ARGUMENT_STRING(accessType);

  SHPHandle handle = SHPOpen(RSTRING_PTR(filename), RSTRING_PTR(accessType));

  if (handle == NULL) {
    SHP_FATAL("Failed to open shapefile.");
    return Qnil;
  }

  shapefile *shp = new shapefile(handle);

  return shp->wrapped();
}

VALUE shapefile::create(VALUE klass, VALUE filename, VALUE shapeType)
{
  CHECK_ARGUMENT_STRING(filename);
  CHECK_ARGUMENT_FIXNUM(shapeType);

  SHPHandle handle = SHPCreate(RSTRING_PTR(filename), FIX2INT(shapeType));

  if (handle == NULL) {
    SHP_FATAL("Failed to create shapefile.");
    return Qnil;
  }

  shapefile *shp = new shapefile(handle);

  return shp->wrapped();
}

VALUE shapefile::create_simple_object(VALUE klass, VALUE shapeType, VALUE numberOfVertices, VALUE arrayOfX, VALUE arrayOfY, VALUE arrayOfZ)
{
  CHECK_ARGUMENT_FIXNUM(shapeType);
  CHECK_ARGUMENT_FIXNUM(numberOfVertices);
  CHECK_ARGUMENT_ARRAY(arrayOfX);
  CHECK_ARGUMENT_ARRAY(arrayOfY);

  double *xVertices = new double[FIX2INT(numberOfVertices)];
  double *yVertices = new double[FIX2INT(numberOfVertices)];
  double *zVertices = NULL;

  if (!NIL_P(arrayOfZ)) {
    CHECK_ARGUMENT_ARRAY(arrayOfZ);
    zVertices = new double[FIX2INT(numberOfVertices)];
  }

  for (int i = 0; i < FIX2INT(numberOfVertices); ++i) {
    xVertices[i] = NUM2DBL(rb_ary_entry(arrayOfX, i));
    yVertices[i] = NUM2DBL(rb_ary_entry(arrayOfY, i));

    if (zVertices) {
      zVertices[i] = NUM2DBL(rb_ary_entry(arrayOfZ, i));
    }
  }

  SHPObject *object = SHPCreateSimpleObject(FIX2INT(shapeType),
                                            FIX2INT(numberOfVertices),
                                            xVertices,
                                            yVertices,
                                            zVertices);

  delete [] xVertices;
  delete [] yVertices;

  if (zVertices) {
    delete [] zVertices;
  }

  if (object == NULL) {
    SHP_FATAL("Failed to create shape object.");
    return Qnil;
  }

  shape_object *shape = new shape_object(object);

  return shape->wrapped();
}

VALUE shapefile::create_object(VALUE klass, VALUE shapeType, VALUE shapeIndex, VALUE numberOfParts,
                               VALUE arrayOfPartStarts, VALUE arrayOfPartTypes, VALUE numberOfVertices,
                               VALUE arrayOfX, VALUE arrayOfY, VALUE arrayOfZ, VALUE arrayOfM)
{
  CHECK_ARGUMENT_FIXNUM(shapeType);
  CHECK_ARGUMENT_FIXNUM(shapeIndex);
  CHECK_ARGUMENT_FIXNUM(numberOfParts);
  CHECK_ARGUMENT_FIXNUM(numberOfVertices);
  CHECK_ARGUMENT_ARRAY(arrayOfX);
  CHECK_ARGUMENT_ARRAY(arrayOfY);

  double *xVertices = new double[FIX2INT(numberOfVertices)];
  double *yVertices = new double[FIX2INT(numberOfVertices)];
  double *zVertices = NULL;
  double *mVertices = NULL;

  int *nativeArrayOfPartStarts = NULL;
  int *nativeArrayOfPartTypes  = NULL;

  if (!NIL_P(arrayOfZ)) {
    CHECK_ARGUMENT_ARRAY(arrayOfZ);
    zVertices = new double[FIX2INT(numberOfVertices)];
  }

  if (!NIL_P(arrayOfM)) {
    CHECK_ARGUMENT_ARRAY(arrayOfM);
    mVertices = new double[FIX2INT(numberOfVertices)];
  }

  if (!NIL_P(arrayOfPartStarts)) {
    CHECK_ARGUMENT_ARRAY(arrayOfPartStarts);
    nativeArrayOfPartStarts = new int[FIX2INT(numberOfParts)];

    for (int i = 0; i < FIX2INT(numberOfParts); ++i) {
      nativeArrayOfPartStarts[i] = FIX2INT(rb_ary_entry(arrayOfPartStarts, i));
    }
  }

  if (!NIL_P(arrayOfPartTypes)) {
    CHECK_ARGUMENT_ARRAY(arrayOfPartTypes);
    nativeArrayOfPartTypes = new int[FIX2INT(numberOfParts)];

    for (int i = 0; i < FIX2INT(numberOfParts); ++i) {
      nativeArrayOfPartTypes[i] = FIX2INT(rb_ary_entry(arrayOfPartTypes, i));
    }
  }

  SHPObject *object = SHPCreateObject(FIX2INT(shapeType),
                                      FIX2INT(shapeIndex),
                                      FIX2INT(numberOfParts),
                                      nativeArrayOfPartStarts,
                                      nativeArrayOfPartTypes,
                                      FIX2INT(numberOfVertices),
                                      xVertices,
                                      yVertices,
                                      zVertices,
                                      mVertices);

  delete [] xVertices;
  delete [] yVertices;

  if (zVertices) {
    delete [] zVertices;
  }

  if (mVertices) {
    delete [] mVertices;
  }

  if (nativeArrayOfPartStarts) {
    delete [] nativeArrayOfPartStarts;
  }

  if (nativeArrayOfPartTypes) {
    delete [] nativeArrayOfPartTypes;
  }

  if (object == NULL) {
    SHP_FATAL("Failed to create shape object.");
    return Qnil;
  }

  shape_object *shape = new shape_object(object);

  return shape->wrapped();
}

VALUE shapefile::rewind_object(VALUE self, VALUE shapeObject) {
  shapefile *file = unwrap(self);
  shape_object *shape = shape_object::unwrap(shapeObject);

  CHECK_VALID_HANDLE(file->value());
  CHECK_VALID_HANDLE(shape->value());

  if (shape == NULL) {
    SHP_FATAL("You must specify a valid shape.");
    return Qnil;
  }

  int result = SHPRewindObject(file->value(), shape->value());

  return INT2FIX(result);
}

VALUE shapefile::get_info(VALUE self)
{
  shapefile *file = unwrap(self);

  CHECK_VALID_HANDLE(file->value());

  int numberOfEntities = 0;
  int shapeType = 0;
  double minBounds[4];
  double maxBounds[4];

  SHPGetInfo(file->value(),
             &numberOfEntities,
             &shapeType,
             minBounds,
             maxBounds);

  VALUE hash = rb_hash_new();

  VALUE minBoundsAry = rb_ary_new();
  VALUE maxBoundsAry = rb_ary_new();

  rb_ary_push(minBoundsAry, rb_float_new(minBounds[0]));
  rb_ary_push(minBoundsAry, rb_float_new(minBounds[1]));
  rb_ary_push(minBoundsAry, rb_float_new(minBounds[2]));
  rb_ary_push(minBoundsAry, rb_float_new(minBounds[3]));

  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[0]));
  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[1]));
  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[2]));
  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[3]));

  rb_hash_aset(hash, ID2SYM(rb_intern("number_of_entities")), INT2FIX(numberOfEntities));
  rb_hash_aset(hash, ID2SYM(rb_intern("shape_type")), INT2FIX(shapeType));
  rb_hash_aset(hash, ID2SYM(rb_intern("min_bounds")), minBoundsAry);
  rb_hash_aset(hash, ID2SYM(rb_intern("max_bounds")), maxBoundsAry);

  return hash;
}

VALUE shapefile::read_object(VALUE self, VALUE shapeIndex)
{
  CHECK_ARGUMENT_FIXNUM(shapeIndex);

  shapefile *file = unwrap(self);

  CHECK_VALID_HANDLE(file->value());

  SHPObject *object = SHPReadObject(file->value(), FIX2INT(shapeIndex));

  if (object == NULL) {
    SHP_FATAL("Unable to read shape object.");
    return Qnil;
  }

  shape_object *shape = new shape_object(object);

  return shape->wrapped();
}

VALUE shapefile::write_object(VALUE self, VALUE shapeIndex, VALUE shapeObject)
{
  CHECK_ARGUMENT_FIXNUM(shapeIndex);

  shapefile *file = unwrap(self);
  shape_object *object = shape_object::unwrap(shapeObject);

  CHECK_VALID_HANDLE(file->value());
  CHECK_VALID_HANDLE(object->value());

  int result = SHPWriteObject(file->value(), FIX2INT(shapeIndex), object->value());

  return INT2FIX(result);
}

VALUE shapefile::close(VALUE self)
{
  shapefile *file = unwrap(self);

  CHECK_VALID_HANDLE(file->value());

  SHPClose(file->value());

  file->_handle = 0;

  return Qnil;
}

void shapefile::define(VALUE module)
{
  shapefile::_klass = rb_define_class_under(module, "Shapefile", rb_cObject);
  base::define(shapefile::_klass, false);
  rb_define_singleton_method(shapefile::_klass, "open", SHP_METHOD(shapefile::open), 2);
  rb_define_singleton_method(shapefile::_klass, "create", SHP_METHOD(shapefile::create), 2);
  rb_define_singleton_method(shapefile::_klass, "create_simple_object", SHP_METHOD(shapefile::create_simple_object), 5);
  rb_define_singleton_method(shapefile::_klass, "create_object", SHP_METHOD(shapefile::create_simple_object), 10);
  rb_define_method(shapefile::_klass, "write_object", SHP_METHOD(shapefile::write_object), 2);
  rb_define_method(shapefile::_klass, "close", SHP_METHOD(shapefile::close), 0);
  rb_define_method(shapefile::_klass, "get_info", SHP_METHOD(shapefile::get_info), 0);
  rb_define_method(shapefile::_klass, "read_object", SHP_METHOD(shapefile::read_object), 1);
  rb_define_method(shapefile::_klass, "rewind_object", SHP_METHOD(shapefile::rewind_object), 1);
}

}

<commit_msg>Make it possible to call create_object<commit_after>
#include "shapefile.hpp"
#include "shape_object.hpp"

namespace shp {

VALUE shapefile::_klass = Qnil;

VALUE shapefile::klass() {
  return shapefile::_klass;
}

shapefile::shapefile(SHPHandle handle)
  : _handle(handle)
{
}

shapefile::~shapefile() {
  if (_handle) {
    SHPClose(_handle);
    _handle = NULL;
  }
}

VALUE shapefile::open(VALUE klass, VALUE filename, VALUE accessType)
{
  CHECK_ARGUMENT_STRING(filename);
  CHECK_ARGUMENT_STRING(accessType);

  SHPHandle handle = SHPOpen(RSTRING_PTR(filename), RSTRING_PTR(accessType));

  if (handle == NULL) {
    SHP_FATAL("Failed to open shapefile.");
    return Qnil;
  }

  shapefile *shp = new shapefile(handle);

  return shp->wrapped();
}

VALUE shapefile::create(VALUE klass, VALUE filename, VALUE shapeType)
{
  CHECK_ARGUMENT_STRING(filename);
  CHECK_ARGUMENT_FIXNUM(shapeType);

  SHPHandle handle = SHPCreate(RSTRING_PTR(filename), FIX2INT(shapeType));

  if (handle == NULL) {
    SHP_FATAL("Failed to create shapefile.");
    return Qnil;
  }

  shapefile *shp = new shapefile(handle);

  return shp->wrapped();
}

VALUE shapefile::create_simple_object(VALUE klass, VALUE shapeType, VALUE numberOfVertices, VALUE arrayOfX, VALUE arrayOfY, VALUE arrayOfZ)
{
  CHECK_ARGUMENT_FIXNUM(shapeType);
  CHECK_ARGUMENT_FIXNUM(numberOfVertices);
  CHECK_ARGUMENT_ARRAY(arrayOfX);
  CHECK_ARGUMENT_ARRAY(arrayOfY);

  double *xVertices = new double[FIX2INT(numberOfVertices)];
  double *yVertices = new double[FIX2INT(numberOfVertices)];
  double *zVertices = NULL;

  if (!NIL_P(arrayOfZ)) {
    CHECK_ARGUMENT_ARRAY(arrayOfZ);
    zVertices = new double[FIX2INT(numberOfVertices)];
  }

  for (int i = 0; i < FIX2INT(numberOfVertices); ++i) {
    xVertices[i] = NUM2DBL(rb_ary_entry(arrayOfX, i));
    yVertices[i] = NUM2DBL(rb_ary_entry(arrayOfY, i));

    if (zVertices) {
      zVertices[i] = NUM2DBL(rb_ary_entry(arrayOfZ, i));
    }
  }

  SHPObject *object = SHPCreateSimpleObject(FIX2INT(shapeType),
                                            FIX2INT(numberOfVertices),
                                            xVertices,
                                            yVertices,
                                            zVertices);

  delete [] xVertices;
  delete [] yVertices;

  if (zVertices) {
    delete [] zVertices;
  }

  if (object == NULL) {
    SHP_FATAL("Failed to create shape object.");
    return Qnil;
  }

  shape_object *shape = new shape_object(object);

  return shape->wrapped();
}

VALUE shapefile::create_object(VALUE klass, VALUE shapeType, VALUE shapeIndex, VALUE numberOfParts,
                               VALUE arrayOfPartStarts, VALUE arrayOfPartTypes, VALUE numberOfVertices,
                               VALUE arrayOfX, VALUE arrayOfY, VALUE arrayOfZ, VALUE arrayOfM)
{
  CHECK_ARGUMENT_FIXNUM(shapeType);
  CHECK_ARGUMENT_FIXNUM(shapeIndex);
  CHECK_ARGUMENT_FIXNUM(numberOfParts);
  CHECK_ARGUMENT_FIXNUM(numberOfVertices);
  CHECK_ARGUMENT_ARRAY(arrayOfX);
  CHECK_ARGUMENT_ARRAY(arrayOfY);

  double *xVertices = new double[FIX2INT(numberOfVertices)];
  double *yVertices = new double[FIX2INT(numberOfVertices)];
  double *zVertices = NULL;
  double *mVertices = NULL;

  if (!NIL_P(arrayOfZ)) {
    CHECK_ARGUMENT_ARRAY(arrayOfZ);
    zVertices = new double[FIX2INT(numberOfVertices)];
  }

  if (!NIL_P(arrayOfM)) {
    CHECK_ARGUMENT_ARRAY(arrayOfM);
    mVertices = new double[FIX2INT(numberOfVertices)];
  }

  for (int i = 0; i < FIX2INT(numberOfVertices); ++i) {
    xVertices[i] = NUM2DBL(rb_ary_entry(arrayOfX, i));
    yVertices[i] = NUM2DBL(rb_ary_entry(arrayOfY, i));

    if (zVertices) {
      zVertices[i] = NUM2DBL(rb_ary_entry(arrayOfZ, i));
    }

    if (mVertices) {
      mVertices[i] = NUM2DBL(rb_ary_entry(arrayOfM, i));
    }
  }

  int *nativeArrayOfPartStarts = NULL;
  int *nativeArrayOfPartTypes  = NULL;

  if (!NIL_P(arrayOfPartStarts)) {
    CHECK_ARGUMENT_ARRAY(arrayOfPartStarts);
    nativeArrayOfPartStarts = new int[FIX2INT(numberOfParts)];

    for (int i = 0; i < FIX2INT(numberOfParts); ++i) {
      nativeArrayOfPartStarts[i] = FIX2INT(rb_ary_entry(arrayOfPartStarts, i));
    }
  }

  if (!NIL_P(arrayOfPartTypes)) {
    CHECK_ARGUMENT_ARRAY(arrayOfPartTypes);
    nativeArrayOfPartTypes = new int[FIX2INT(numberOfParts)];

    for (int i = 0; i < FIX2INT(numberOfParts); ++i) {
      nativeArrayOfPartTypes[i] = FIX2INT(rb_ary_entry(arrayOfPartTypes, i));
    }
  }

  SHPObject *object = SHPCreateObject(FIX2INT(shapeType),
                                      FIX2INT(shapeIndex),
                                      FIX2INT(numberOfParts),
                                      nativeArrayOfPartStarts,
                                      nativeArrayOfPartTypes,
                                      FIX2INT(numberOfVertices),
                                      xVertices,
                                      yVertices,
                                      zVertices,
                                      mVertices);

  delete [] xVertices;
  delete [] yVertices;

  if (zVertices) {
    delete [] zVertices;
  }

  if (mVertices) {
    delete [] mVertices;
  }

  if (nativeArrayOfPartStarts) {
    delete [] nativeArrayOfPartStarts;
  }

  if (nativeArrayOfPartTypes) {
    delete [] nativeArrayOfPartTypes;
  }

  if (object == NULL) {
    SHP_FATAL("Failed to create shape object.");
    return Qnil;
  }

  shape_object *shape = new shape_object(object);

  return shape->wrapped();
}

VALUE shapefile::rewind_object(VALUE self, VALUE shapeObject) {
  shapefile *file = unwrap(self);
  shape_object *shape = shape_object::unwrap(shapeObject);

  CHECK_VALID_HANDLE(file->value());
  CHECK_VALID_HANDLE(shape->value());

  if (shape == NULL) {
    SHP_FATAL("You must specify a valid shape.");
    return Qnil;
  }

  int result = SHPRewindObject(file->value(), shape->value());

  return INT2FIX(result);
}

VALUE shapefile::get_info(VALUE self)
{
  shapefile *file = unwrap(self);

  CHECK_VALID_HANDLE(file->value());

  int numberOfEntities = 0;
  int shapeType = 0;
  double minBounds[4];
  double maxBounds[4];

  SHPGetInfo(file->value(),
             &numberOfEntities,
             &shapeType,
             minBounds,
             maxBounds);

  VALUE hash = rb_hash_new();

  VALUE minBoundsAry = rb_ary_new();
  VALUE maxBoundsAry = rb_ary_new();

  rb_ary_push(minBoundsAry, rb_float_new(minBounds[0]));
  rb_ary_push(minBoundsAry, rb_float_new(minBounds[1]));
  rb_ary_push(minBoundsAry, rb_float_new(minBounds[2]));
  rb_ary_push(minBoundsAry, rb_float_new(minBounds[3]));

  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[0]));
  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[1]));
  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[2]));
  rb_ary_push(maxBoundsAry, rb_float_new(maxBounds[3]));

  rb_hash_aset(hash, ID2SYM(rb_intern("number_of_entities")), INT2FIX(numberOfEntities));
  rb_hash_aset(hash, ID2SYM(rb_intern("shape_type")), INT2FIX(shapeType));
  rb_hash_aset(hash, ID2SYM(rb_intern("min_bounds")), minBoundsAry);
  rb_hash_aset(hash, ID2SYM(rb_intern("max_bounds")), maxBoundsAry);

  return hash;
}

VALUE shapefile::read_object(VALUE self, VALUE shapeIndex)
{
  CHECK_ARGUMENT_FIXNUM(shapeIndex);

  shapefile *file = unwrap(self);

  CHECK_VALID_HANDLE(file->value());

  SHPObject *object = SHPReadObject(file->value(), FIX2INT(shapeIndex));

  if (object == NULL) {
    SHP_FATAL("Unable to read shape object.");
    return Qnil;
  }

  shape_object *shape = new shape_object(object);

  return shape->wrapped();
}

VALUE shapefile::write_object(VALUE self, VALUE shapeIndex, VALUE shapeObject)
{
  CHECK_ARGUMENT_FIXNUM(shapeIndex);

  shapefile *file = unwrap(self);
  shape_object *object = shape_object::unwrap(shapeObject);

  CHECK_VALID_HANDLE(file->value());
  CHECK_VALID_HANDLE(object->value());

  int result = SHPWriteObject(file->value(), FIX2INT(shapeIndex), object->value());

  return INT2FIX(result);
}

VALUE shapefile::close(VALUE self)
{
  shapefile *file = unwrap(self);

  CHECK_VALID_HANDLE(file->value());

  SHPClose(file->value());

  file->_handle = 0;

  return Qnil;
}

void shapefile::define(VALUE module)
{
  shapefile::_klass = rb_define_class_under(module, "Shapefile", rb_cObject);
  base::define(shapefile::_klass, false);
  rb_define_singleton_method(shapefile::_klass, "open", SHP_METHOD(shapefile::open), 2);
  rb_define_singleton_method(shapefile::_klass, "create", SHP_METHOD(shapefile::create), 2);
  rb_define_singleton_method(shapefile::_klass, "create_simple_object", SHP_METHOD(shapefile::create_simple_object), 5);
  rb_define_singleton_method(shapefile::_klass, "create_object", SHP_METHOD(shapefile::create_object), 10);
  rb_define_method(shapefile::_klass, "write_object", SHP_METHOD(shapefile::write_object), 2);
  rb_define_method(shapefile::_klass, "close", SHP_METHOD(shapefile::close), 0);
  rb_define_method(shapefile::_klass, "get_info", SHP_METHOD(shapefile::get_info), 0);
  rb_define_method(shapefile::_klass, "read_object", SHP_METHOD(shapefile::read_object), 1);
  rb_define_method(shapefile::_klass, "rewind_object", SHP_METHOD(shapefile::rewind_object), 1);
}

}

<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <stdint.h>
#include <sys/stat.h>
#include <fstream>
#include <numeric>

#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/data_type_transform.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/selected_rows.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/platform/device_context.h"

namespace paddle {
namespace operators {

// TODO(yuyang18): If the functions below are needed by other files, move them
// to paddle::filesystem namespace.
constexpr char kSEP = '/';
static bool FileExists(const std::string &filepath) {
  struct stat buffer;
  return (stat(filepath.c_str(), &buffer) == 0);
}

static std::string DirName(const std::string &filepath) {
  auto pos = filepath.rfind(kSEP);
  if (pos == std::string::npos) {
    return "";
  }
  return filepath.substr(0, pos);
}

static void MkDir(const char *path) {
  if (mkdir(path, 0755)) {
    PADDLE_ENFORCE_EQ(errno, EEXIST, "%s mkdir failed!", path);
  }
}

static void MkDirRecursively(const char *fullpath) {
  if (*fullpath == '\0') return;  // empty string
  if (FileExists(fullpath)) return;

  MkDirRecursively(DirName(fullpath).c_str());
  MkDir(fullpath);
}

class SaveOp : public framework::OperatorBase {
 public:
  SaveOp(const std::string &type, const framework::VariableNameMap &inputs,
         const framework::VariableNameMap &outputs,
         const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {

    auto iname = Input("X");
    auto *var = scope.FindVar(iname);
    PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s for save_op",
                   iname);

    if (var->IsType<framework::LoDTensor>()) {
      SaveLodTensor(place, var);
    } else if (var->IsType<framework::SelectedRows>()) {
      SaveSelectedRows(scope, place, var);
    } else {
      PADDLE_ENFORCE(
          false,
          "SaveOp only support LoDTensor and SelectedRows, %s has wrong type",
          iname);
    }
  }

  void SaveLodTensor( const platform::Place &place,
                     framework::Variable *var) const {
    auto filename = Attr<std::string>("file_path");
    auto overwrite = Attr<bool>("overwrite");

    if (FileExists(filename) && !overwrite) {
      PADDLE_THROW("%s is existed, cannot save to it when overwrite=false",
                   filename, overwrite);
    }

    MkDirRecursively(DirName(filename).c_str());

    auto &tensor = var->Get<framework::LoDTensor>();

    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    // FIXME(yuyang18): We save variable to local file now, but we should change
    // it to save an output stream.
    std::ofstream fout(filename);
    PADDLE_ENFORCE(static_cast<bool>(fout), "Cannot open %s to write",
                   filename);

    auto save_as_fp16 = Attr<bool>("save_as_fp16");
    auto in_dtype = framework::ToDataType(tensor.type());
    auto out_dtype = save_as_fp16 ? framework::proto::VarType::FP16 : in_dtype;

    if (in_dtype != out_dtype) {
      auto in_kernel_type = framework::OpKernelType(in_dtype, place);
      auto out_kernel_type = framework::OpKernelType(out_dtype, place);
      framework::LoDTensor out;
      framework::TransDataType(in_kernel_type, out_kernel_type, tensor, &out);
      // copy LoD info to the new tensor
      out.set_lod(tensor.lod());
      framework::SerializeToStream(fout, out, dev_ctx);
    } else {
      framework::SerializeToStream(fout, tensor, dev_ctx);
    }
    fout.close();
  }

  void SaveSelectedRows(const framework::Scope &scope,
                        const platform::Place &place,
                        framework::Variable *var) const {
    auto *lt_var = scope.FindVar("loopup_table_path")->GetMutable<std::string>();
    PADDLE_ENFORCE(lt_var != nullptr, "Cannot find variable loopup_table_path for SaveSelectedRows");
    std::string filename = lt_var->data();
    VLOG(4) << "SaveSelectedRows get File name: " << filename;

    auto &selectedRows = var->Get<framework::SelectedRows>();

    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    // FIXME(yuyang18): We save variable to local file now, but we should change
    // it to save an output stream.
    std::ofstream fout(filename);
    PADDLE_ENFORCE(static_cast<bool>(fout), "Cannot open %s to write",
                   filename);
    framework::SerializeToStream(fout, selectedRows, dev_ctx);
    fout.close();
  }
};

class SaveOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor ) Input LoDTensor and SelectedRows to be saved");
    AddComment(R"DOC(
Save operator

This operator will serialize and write a tensor/selected rows variable to file on disk.
)DOC");
    AddAttr<bool>("overwrite",
                  "(boolean, default true)"
                  "Overwrite the output file if exist")
        .SetDefault(true);
    AddAttr<bool>("save_as_fp16",
                  "(boolean, default false)"
                  "If true, the tensor will be converted to float16 data "
                  "type and then saved. Otherwise, the tensor will be "
                  "directly saved without data type conversion.")
        .SetDefault(false);
    AddAttr<std::string>("file_path",
                         "(string)"
                         "The \"file_path\" where the variable will be saved.")
        .AddCustomChecker(
            [](const std::string &path) { return !path.empty(); });
  }
};

class SaveOpVarTypeInference : public framework::VarTypeInference {
 public:
  void operator()(const framework::OpDesc &op_desc,
                  framework::BlockDesc *block) const override {
    auto out_var_name = op_desc.Output("loopup_table_path").front();
    auto &out_var = block->FindRecursiveOrCreateVar(out_var_name);
    auto var_type = framework::proto::VarType::RAW;
    out_var.SetType(var_type);
  }
};

class SaveOpShapeInference : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *ctx) const override {}
};
}
}

// namespace operators
// namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(save, ops::SaveOp,
                  paddle::framework::EmptyGradOpMaker,
                  ops::SaveOpProtoMaker,
                  ops::SaveOpVarTypeInference,
                  ops::SaveOpShapeInference);

<commit_msg>code style<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <stdint.h>
#include <sys/stat.h>
#include <fstream>
#include <numeric>

#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/data_type_transform.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/selected_rows.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/platform/device_context.h"

namespace paddle {
namespace operators {

// TODO(yuyang18): If the functions below are needed by other files, move them
// to paddle::filesystem namespace.
constexpr char kSEP = '/';
static bool FileExists(const std::string &filepath) {
  struct stat buffer;
  return (stat(filepath.c_str(), &buffer) == 0);
}

static std::string DirName(const std::string &filepath) {
  auto pos = filepath.rfind(kSEP);
  if (pos == std::string::npos) {
    return "";
  }
  return filepath.substr(0, pos);
}

static void MkDir(const char *path) {
  if (mkdir(path, 0755)) {
    PADDLE_ENFORCE_EQ(errno, EEXIST, "%s mkdir failed!", path);
  }
}

static void MkDirRecursively(const char *fullpath) {
  if (*fullpath == '\0') return;  // empty string
  if (FileExists(fullpath)) return;

  MkDirRecursively(DirName(fullpath).c_str());
  MkDir(fullpath);
}

class SaveOp : public framework::OperatorBase {
 public:
  SaveOp(const std::string &type, const framework::VariableNameMap &inputs,
         const framework::VariableNameMap &outputs,
         const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    auto iname = Input("X");
    auto *var = scope.FindVar(iname);
    PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s for save_op",
                   iname);

    if (var->IsType<framework::LoDTensor>()) {
      SaveLodTensor(place, var);
    } else if (var->IsType<framework::SelectedRows>()) {
      SaveSelectedRows(scope, place, var);
    } else {
      PADDLE_ENFORCE(
          false,
          "SaveOp only support LoDTensor and SelectedRows, %s has wrong type",
          iname);
    }
  }

  void SaveLodTensor(const platform::Place &place,
                     framework::Variable *var) const {
    auto filename = Attr<std::string>("file_path");
    auto overwrite = Attr<bool>("overwrite");

    if (FileExists(filename) && !overwrite) {
      PADDLE_THROW("%s is existed, cannot save to it when overwrite=false",
                   filename, overwrite);
    }

    MkDirRecursively(DirName(filename).c_str());

    auto &tensor = var->Get<framework::LoDTensor>();

    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    // FIXME(yuyang18): We save variable to local file now, but we should change
    // it to save an output stream.
    std::ofstream fout(filename);
    PADDLE_ENFORCE(static_cast<bool>(fout), "Cannot open %s to write",
                   filename);

    auto save_as_fp16 = Attr<bool>("save_as_fp16");
    auto in_dtype = framework::ToDataType(tensor.type());
    auto out_dtype = save_as_fp16 ? framework::proto::VarType::FP16 : in_dtype;

    if (in_dtype != out_dtype) {
      auto in_kernel_type = framework::OpKernelType(in_dtype, place);
      auto out_kernel_type = framework::OpKernelType(out_dtype, place);
      framework::LoDTensor out;
      framework::TransDataType(in_kernel_type, out_kernel_type, tensor, &out);
      // copy LoD info to the new tensor
      out.set_lod(tensor.lod());
      framework::SerializeToStream(fout, out, dev_ctx);
    } else {
      framework::SerializeToStream(fout, tensor, dev_ctx);
    }
    fout.close();
  }

  void SaveSelectedRows(const framework::Scope &scope,
                        const platform::Place &place,
                        framework::Variable *var) const {
    auto *lt_var =
        scope.FindVar("loopup_table_path")->GetMutable<std::string>();
    PADDLE_ENFORCE(
        lt_var != nullptr,
        "Can not find variable loopup_table_path for SaveSelectedRows");
    std::string filename = lt_var->data();
    VLOG(4) << "SaveSelectedRows get File name: " << filename;

    auto &selectedRows = var->Get<framework::SelectedRows>();

    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    // FIXME(yuyang18): We save variable to local file now, but we should change
    // it to save an output stream.
    std::ofstream fout(filename);
    PADDLE_ENFORCE(static_cast<bool>(fout), "Cannot open %s to write",
                   filename);
    framework::SerializeToStream(fout, selectedRows, dev_ctx);
    fout.close();
  }
};

class SaveOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor ) Input LoDTensor and SelectedRows to be saved");
    AddComment(R"DOC(
Save operator

This operator will serialize and write a tensor/selected rows variable to file on disk.
)DOC");
    AddAttr<bool>("overwrite",
                  "(boolean, default true)"
                  "Overwrite the output file if exist")
        .SetDefault(true);
    AddAttr<bool>("save_as_fp16",
                  "(boolean, default false)"
                  "If true, the tensor will be converted to float16 data "
                  "type and then saved. Otherwise, the tensor will be "
                  "directly saved without data type conversion.")
        .SetDefault(false);
    AddAttr<std::string>("file_path",
                         "(string)"
                         "The \"file_path\" where the variable will be saved.")
        .AddCustomChecker(
            [](const std::string &path) { return !path.empty(); });
  }
};

class SaveOpVarTypeInference : public framework::VarTypeInference {
 public:
  void operator()(const framework::OpDesc &op_desc,
                  framework::BlockDesc *block) const override {
    auto out_var_name = op_desc.Output("loopup_table_path").front();
    auto &out_var = block->FindRecursiveOrCreateVar(out_var_name);
    auto var_type = framework::proto::VarType::RAW;
    out_var.SetType(var_type);
  }
};

class SaveOpShapeInference : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *ctx) const override {}
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(save, ops::SaveOp, paddle::framework::EmptyGradOpMaker,
                  ops::SaveOpProtoMaker, ops::SaveOpVarTypeInference,
                  ops::SaveOpShapeInference);
<|endoftext|>