<commit_before>#include <QtCore/QString>
#include <QtCore>
#include <QApplication>
#include <QtGui/qevent.h>
#include <QtGui/QtGui>
#include "controlpanel.h"
#include "ui_controlpanel.h"
#include <QLCDNumber>
#include <QtGui/QStyleOption>

ControlPanel::ControlPanel(QWidget *parent) : QMainWindow(parent), ui(new Ui::ControlPanel) {
    ui->setupUi(this);
    paletteOrg.setColor(paletteOrg.WindowText, Qt::black);
    paletteRed.setColor(paletteRed.WindowText, Qt::red);
    ui->lcdNumber_Right->setPalette(paletteOrg);
    ui->lcdNumber_Left->setPalette(paletteOrg);
    ui->lcdNumber_Position->setPalette(paletteOrg);
    ui->lcdNumber_Right->display("00");
    ui->lcdNumber_Left->display("00:00");
    ui->lcdNumber_Position->display("000:000:000");
    timer = new QTimer(this);
    timerPos = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updatePanel()));
    connect(timerPos, SIGNAL(timeout()), this, SLOT(updatePosition()));
    timer->start(1000);
    timerPos->start(50);
}

ControlPanel::~ControlPanel(void){
    delete(ui);
    delete(timer);
    delete(timerPos);
}

void ControlPanel::setValues(Nav *nav, FlightController *newController, ros::NodeHandle *n, int countdownSeconds){
    node = n;
    navData = nav;
    secondsLeft = secondsleftConst = countdownSeconds;
    controller = newController;
    sub_navdata = n->subscribe<ardrone_autonomy::Navdata>("ardrone/navdata", 10, &ControlPanel::callback, this);
}

void ControlPanel::callback(const ardrone_autonomy::NavdataConstPtr &msg) {
    battery =  msg->batteryPercent;
}

void ControlPanel::on_pushButton_Start_clicked(void)
{
    controller->startProgram();
    started = true;
}

void ControlPanel::on_pushButton_Reset_clicked(void)
{
    started = false;
    secondsLeft = secondsleftConst;
    controller->resetProgram();
}

void ControlPanel::on_pushButton_Stop_clicked(void)
{
    started = false;
    secondsLeft = secondsleftConst;
    controller->abortProgram();
}

void ControlPanel::updatePanel(void) {

    if (started && --secondsLeft > -600) {
        string timeStr;

        int mins = secondsLeft / 60;
        int secs = secondsLeft % 60;

        if (mins != 0) {
            timeStr = to_string(mins);
            timeStr.append(":");
        }

        if (secondsLeft < 0 && mins != 0)
            secs = -secs;

        timeStr.append(to_string(secs));

        if (secondsLeft < 30)
            ui->lcdNumber_Left->setPalette(paletteRed);
        else
            ui->lcdNumber_Left->setPalette(paletteOrg);

        ui->lcdNumber_Left->display(QString::fromStdString(timeStr));
    }
    if (battery < 30.00)
        ui->lcdNumber_Right->setPalette(paletteRed);
    else
        ui->lcdNumber_Right->setPalette(paletteOrg);

    ui->lcdNumber_Right->display(battery);
}

void ControlPanel::updatePosition(void) {
    string posStr;
    posStr.append(to_string((int)navData->position.x));
    posStr.append(":");
    posStr.append(to_string((int)navData->position.y));
    posStr.append(":");
    posStr.append(to_string(navData->position.z));

    ui->lcdNumber_Position->display(QString::fromStdString(posStr));
}

void ControlPanel::on_pushButton_shutdown_clicked(void)
{
    const char* command = "kill $(ps aux | grep ros | grep -v grep | awk '{print $2}')";
    controller->resetProgram();
    system(command);
    exit (EXIT_SUCCESS);
}

<commit_msg>Added yaw<commit_after>#include <QtCore/QString>
#include <QtCore>
#include <QApplication>
#include <QtGui/qevent.h>
#include <QtGui/QtGui>
#include "controlpanel.h"
#include "ui_controlpanel.h"
#include <QLCDNumber>
#include <QtGui/QStyleOption>

ControlPanel::ControlPanel(QWidget *parent) : QMainWindow(parent), ui(new Ui::ControlPanel) {
    ui->setupUi(this);
    paletteOrg.setColor(paletteOrg.WindowText, Qt::black);
    paletteRed.setColor(paletteRed.WindowText, Qt::red);
    ui->lcdNumber_Right->setPalette(paletteOrg);
    ui->lcdNumber_Left->setPalette(paletteOrg);
    ui->lcdNumber_Position->setPalette(paletteOrg);
    ui->lcdNumber_Right->display("00");
    ui->lcdNumber_Left->display("00:00");
    ui->lcdNumber_Position->display("000:000:000");
    timer = new QTimer(this);
    timerPos = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updatePanel()));
    connect(timerPos, SIGNAL(timeout()), this, SLOT(updatePosition()));
    timer->start(1000);
    timerPos->start(50);
}

ControlPanel::~ControlPanel(void){
    delete(ui);
    delete(timer);
    delete(timerPos);
}

void ControlPanel::setValues(Nav *nav, FlightController *newController, ros::NodeHandle *n, int countdownSeconds){
    node = n;
    navData = nav;
    secondsLeft = secondsleftConst = countdownSeconds;
    controller = newController;
    sub_navdata = n->subscribe<ardrone_autonomy::Navdata>("ardrone/navdata", 10, &ControlPanel::callback, this);
}

void ControlPanel::callback(const ardrone_autonomy::NavdataConstPtr &msg) {
    battery =  msg->batteryPercent;
}

void ControlPanel::on_pushButton_Start_clicked(void)
{
    controller->startProgram();
    started = true;
}

void ControlPanel::on_pushButton_Reset_clicked(void)
{
    started = false;
    secondsLeft = secondsleftConst;
    controller->resetProgram();
}

void ControlPanel::on_pushButton_Stop_clicked(void)
{
    started = false;
    secondsLeft = secondsleftConst;
    controller->abortProgram();
}

void ControlPanel::updatePanel(void) {

    if (started && --secondsLeft > -600) {
        string timeStr;

        int mins = secondsLeft / 60;
        int secs = secondsLeft % 60;

        if (mins != 0) {
            timeStr = to_string(mins);
            timeStr.append(":");
        }

        if (secondsLeft < 0 && mins != 0)
            secs = -secs;

        timeStr.append(to_string(secs));

        if (secondsLeft < 30)
            ui->lcdNumber_Left->setPalette(paletteRed);
        else
            ui->lcdNumber_Left->setPalette(paletteOrg);

        ui->lcdNumber_Left->display(QString::fromStdString(timeStr));
    }
    if (battery < 30.00)
        ui->lcdNumber_Right->setPalette(paletteRed);
    else
        ui->lcdNumber_Right->setPalette(paletteOrg);

    ui->lcdNumber_Right->display(battery);
}

void ControlPanel::updatePosition(void) {
    string posStr;
    posStr.append(to_string((int)navData->position.x));
    posStr.append(":");
    posStr.append(to_string((int)navData->position.y));
    posStr.append(":");
    posStr.append(to_string(navData->position.z));
    posStr.append(":");
    posStr.append(to_string((int)navData->rotation));
    ui->lcdNumber_Position->display(QString::fromStdString(posStr));
}

void ControlPanel::on_pushButton_shutdown_clicked(void)
{
    const char* command = "kill $(ps aux | grep ros | grep -v grep | awk '{print $2}')";
    controller->resetProgram();
    system(command);
    exit (EXIT_SUCCESS);
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkKdTreeTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkVector.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkListSample.h"
#include "itkKdTree.h"
#include "itkKdTreeGenerator.h"
#include "itkEuclideanDistance.h"

int itkKdTreeTest1(int , char * [] )
{
  // Random number generator
  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator NumberGeneratorType;

  NumberGeneratorType::Pointer randomNumberGenerator = NumberGeneratorType::New();
  randomNumberGenerator->Initialize();

  typedef itk::Array< double > MeasurementVectorType ;
  typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;

  const SampleType::MeasurementVectorSizeType measurementVectorSize = 2;

  SampleType::Pointer sample = SampleType::New() ;
  sample->SetMeasurementVectorSize( measurementVectorSize );

  //
  // Generate a sample of random points
  //
  MeasurementVectorType mv( measurementVectorSize ) ;
  for (unsigned int i = 0 ; i < 1000 ; ++i )
    {
    mv[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
    mv[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
    sample->PushBack( mv ) ;
    }

  typedef itk::Statistics::KdTreeGenerator< SampleType > TreeGeneratorType ;
  TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New() ;

  treeGenerator->SetSample( sample ) ;
  treeGenerator->SetBucketSize( 16 ) ;
  treeGenerator->Update() ;

  typedef TreeGeneratorType::KdTreeType TreeType ;
  typedef TreeType::NearestNeighbors NeighborsType ;
  typedef TreeType::KdTreeNodeType NodeType ;

  TreeType::Pointer tree = treeGenerator->GetOutput() ;

  MeasurementVectorType queryPoint( measurementVectorSize ) ;

  unsigned int numberOfNeighbors = 1 ;
  TreeType::InstanceIdentifierVectorType neighbors ;

  MeasurementVectorType result( measurementVectorSize ) ;
  MeasurementVectorType test_point( measurementVectorSize ) ;
  MeasurementVectorType min_point( measurementVectorSize ) ;

  //
  // Generate a second sample of random points
  // and use them to query the tree
  //
  for (unsigned int i = 0 ; i < 1000 ; ++i )
    {

    double min_dist = itk::NumericTraits< double >::max();

    queryPoint[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
    queryPoint[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );

    tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;

    //
    // The first neighbor should be the closest point.
    //
    result = tree->GetMeasurementVector( neighbors[0] );

    //
    // Compute the distance to the "presumed" nearest neighbor
    //
    double result_dist = sqrt(
          (result[0] - queryPoint[0]) *
          (result[0] - queryPoint[0]) +
          (result[1] - queryPoint[1]) *
          (result[1] - queryPoint[1])
          );

    //
    // Compute the distance to all other points, to verify
    // whether the first neighbor was the closest one or not.
    //
    for( unsigned int i = 0 ; i < 1000 ; ++i )
      {
      test_point = tree->GetMeasurementVector( i );

      const double dist = sqrt(
          (test_point[0] - queryPoint[0]) *
          (test_point[0] - queryPoint[0]) +
          (test_point[1] - queryPoint[1]) *
          (test_point[1] - queryPoint[1])
          );

      if( dist < min_dist )
        {
        min_dist = dist;
        min_point = test_point;
        }
      }

    if( min_dist < result_dist )
      {
      std::cerr << "Problem found " << std::endl;
      std::cerr << "Query point " << queryPoint << std::endl;
      std::cerr << "Reported closest point " << result
                << " distance " << result_dist << std::endl;
      std::cerr << "Actual   closest point " << min_point
                << " distance " << min_dist << std::endl;
      std::cerr << std::endl;
      std::cerr << "Test FAILED." << std::endl;
      return EXIT_FAILURE;
      }

    }

  std::cout << "Test PASSED." << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>ENH: Continue even if a point fails. In this we we have the total list of      the points that failed.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkKdTreeTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkVector.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkListSample.h"
#include "itkKdTree.h"
#include "itkKdTreeGenerator.h"
#include "itkEuclideanDistance.h"

int itkKdTreeTest1(int , char * [] )
{
  // Random number generator
  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator NumberGeneratorType;

  NumberGeneratorType::Pointer randomNumberGenerator = NumberGeneratorType::New();
  randomNumberGenerator->Initialize();

  typedef itk::Array< double > MeasurementVectorType ;
  typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;

  const SampleType::MeasurementVectorSizeType measurementVectorSize = 2;

  SampleType::Pointer sample = SampleType::New() ;
  sample->SetMeasurementVectorSize( measurementVectorSize );

  //
  // Generate a sample of random points
  //
  MeasurementVectorType mv( measurementVectorSize ) ;
  for (unsigned int i = 0 ; i < 1000 ; ++i )
    {
    mv[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
    mv[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
    sample->PushBack( mv ) ;
    }

  typedef itk::Statistics::KdTreeGenerator< SampleType > TreeGeneratorType ;
  TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New() ;

  treeGenerator->SetSample( sample ) ;
  treeGenerator->SetBucketSize( 16 ) ;
  treeGenerator->Update() ;

  typedef TreeGeneratorType::KdTreeType TreeType ;
  typedef TreeType::NearestNeighbors NeighborsType ;
  typedef TreeType::KdTreeNodeType NodeType ;

  TreeType::Pointer tree = treeGenerator->GetOutput() ;

  MeasurementVectorType queryPoint( measurementVectorSize ) ;

  unsigned int numberOfNeighbors = 1 ;
  TreeType::InstanceIdentifierVectorType neighbors ;

  MeasurementVectorType result( measurementVectorSize ) ;
  MeasurementVectorType test_point( measurementVectorSize ) ;
  MeasurementVectorType min_point( measurementVectorSize ) ;

  unsigned int numberOfFailedPoints = 0;

  const unsigned int numberOfTestPoints = 1000;

  //
  // Generate a second sample of random points
  // and use them to query the tree
  //
  for (unsigned int i = 0 ; i < numberOfTestPoints ; ++i )
    {

    double min_dist = itk::NumericTraits< double >::max();

    queryPoint[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
    queryPoint[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );

    tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;

    //
    // The first neighbor should be the closest point.
    //
    result = tree->GetMeasurementVector( neighbors[0] );

    //
    // Compute the distance to the "presumed" nearest neighbor
    //
    double result_dist = sqrt(
          (result[0] - queryPoint[0]) *
          (result[0] - queryPoint[0]) +
          (result[1] - queryPoint[1]) *
          (result[1] - queryPoint[1])
          );

    //
    // Compute the distance to all other points, to verify
    // whether the first neighbor was the closest one or not.
    //
    for( unsigned int i = 0 ; i < 1000 ; ++i )
      {
      test_point = tree->GetMeasurementVector( i );

      const double dist = sqrt(
          (test_point[0] - queryPoint[0]) *
          (test_point[0] - queryPoint[0]) +
          (test_point[1] - queryPoint[1]) *
          (test_point[1] - queryPoint[1])
          );

      if( dist < min_dist )
        {
        min_dist = dist;
        min_point = test_point;
        }
      }

    if( min_dist < result_dist )
      {
      std::cerr << "Problem found " << std::endl;
      std::cerr << "Query point " << queryPoint << std::endl;
      std::cerr << "Reported closest point " << result
                << " distance " << result_dist << std::endl;
      std::cerr << "Actual   closest point " << min_point
                << " distance " << min_dist << std::endl;
      std::cerr << std::endl;
      std::cerr << "Test FAILED." << std::endl;
      numberOfFailedPoints++;
      }

    }

  if( numberOfFailedPoints )
    {
    std::cerr << numberOfFailedPoints << " failed out of "
              << numberOfTestPoints << " points " << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test PASSED." << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2018 Google Inc.
 *
 * 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 "utils.hpp"

#include "fs.hpp"
#include "manager.hpp"

#include <dlfcn.h>

#include <memory>
#include <phosphor-logging/log.hpp>
#include <regex>
#include <string>
#include <vector>

namespace blobs
{

using namespace phosphor::logging;

bool matchBlobHandler(const std::string& filename)
{
    return std::regex_match(filename, std::regex(".+\\.so\\.\\d+$"));
}

void loadLibraries(ManagerInterface* manager, const std::string& path,
                   const internal::DlSysInterface* sys)
{
    void* libHandle = NULL;
    HandlerFactory factory;

    std::vector<std::string> libs = getLibraryList(path, matchBlobHandler);

    for (const auto& p : libs)
    {
        libHandle = sys->dlopen(p.c_str(), RTLD_NOW | RTLD_GLOBAL);
        if (!libHandle)
        {
            log<level::ERR>("ERROR opening", entry("HANDLER=%s", p.c_str()),
                            entry("ERROR=%s", sys->dlerror()));
            continue;
        }

        sys->dlerror(); /* Clear any previous error. */

        factory = reinterpret_cast<HandlerFactory>(
            sys->dlsym(libHandle, "createHandler"));

        const char* error = sys->dlerror();
        if (error)
        {
            log<level::ERR>("ERROR loading symbol",
                            entry("HANDLER=%s", p.c_str()),
                            entry("ERROR=%s", error));
            continue;
        }

        std::unique_ptr<GenericBlobInterface> result = factory();
        if (!result)
        {
            log<level::ERR>("Unable to create handler",
                            entry("HANDLER=%s", p.c_str()));
            continue;
        }

        manager->registerHandler(std::move(result));
    }
}

} // namespace blobs
<commit_msg>continue loading libraries if factory excepts<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * 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 "utils.hpp"

#include "fs.hpp"
#include "manager.hpp"

#include <dlfcn.h>

#include <memory>
#include <phosphor-logging/log.hpp>
#include <regex>
#include <string>
#include <vector>

namespace blobs
{

using namespace phosphor::logging;

bool matchBlobHandler(const std::string& filename)
{
    return std::regex_match(filename, std::regex(".+\\.so\\.\\d+$"));
}

void loadLibraries(ManagerInterface* manager, const std::string& path,
                   const internal::DlSysInterface* sys)
{
    void* libHandle = NULL;
    HandlerFactory factory;

    std::vector<std::string> libs = getLibraryList(path, matchBlobHandler);

    for (const auto& p : libs)
    {
        libHandle = sys->dlopen(p.c_str(), RTLD_NOW | RTLD_GLOBAL);
        if (!libHandle)
        {
            log<level::ERR>("ERROR opening", entry("HANDLER=%s", p.c_str()),
                            entry("ERROR=%s", sys->dlerror()));
            continue;
        }

        sys->dlerror(); /* Clear any previous error. */

        factory = reinterpret_cast<HandlerFactory>(
            sys->dlsym(libHandle, "createHandler"));

        const char* error = sys->dlerror();
        if (error)
        {
            log<level::ERR>("ERROR loading symbol",
                            entry("HANDLER=%s", p.c_str()),
                            entry("ERROR=%s", error));
            continue;
        }

        try
        {
            std::unique_ptr<GenericBlobInterface> result = factory();
            if (!result)
            {
                log<level::ERR>("Unable to create handler",
                                entry("HANDLER=%s", p.c_str()));
                continue;
            }

            manager->registerHandler(std::move(result));
        }
        catch (const std::exception& e)
        {
            log<level::ERR>("Received exception loading handler",
                            entry("HANDLER=%s", p.c_str()),
                            entry("EXCEPTION=%s", e.what()));
        }
    }
}

} // namespace blobs
<|endoftext|>


<commit_before>#include <config.h>

#include "coarse_scale_operator.hh"

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/msfem/localproblems/localgridlist.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/msfem/coarse_rhs_functional.hh>
#include <sstream>

namespace Dune {
namespace Multiscale {

Stuff::LA::SparsityPatternDefault CoarseScaleOperator::pattern(const CoarseScaleOperator::RangeSpaceType& range_space,
                                                               const CoarseScaleOperator::SourceSpaceType& source_space,
                                                               const CoarseScaleOperator::GridViewType& grid_view) {
  return range_space.compute_volume_pattern(grid_view, source_space);
}

CoarseScaleOperator::CoarseScaleOperator(const CoarseScaleOperator::SourceSpaceType& source_space_in,
                                         LocalGridList& localGridList)
  : OperatorBaseType(global_matrix_, source_space_in)
  , AssemblerBaseType(source_space_in, source_space_in.grid_view().grid().template leafGridView<InteriorBorder_Partition>())
  , global_matrix_(coarse_space().mapper().size(), coarse_space().mapper().size(),
                   EllipticOperatorType::pattern(coarse_space()))
  , local_assembler_(local_operator_, localGridList)
  , msfem_rhs_(coarse_space(), "MsFEM right hand side")
  , dirichlet_projection_(coarse_space()) {
  DSC::Profiler::ScopedTiming st("msfem.coarse.assemble");
  msfem_rhs_.vector() *= 0;
  auto interior = coarse_space().grid_view().grid().template leafGridView<InteriorBorder_Partition>();
  CoarseRhsFunctional force_functional(msfem_rhs_.vector(), coarse_space(), localGridList, interior);

  const auto& dirichlet = DMP::getDirichletData();
  const auto& boundary_info = Problem::getModelData()->boundaryInfo();
  const auto& neumann = Problem::getNeumannData();

  typedef CommonTraits::InteriorGridViewType InteriorView;
  GDT::Operators::DirichletProjectionLocalizable<InteriorView, Problem::DirichletDataBase,
                                                 CommonTraits::DiscreteFunctionType>
  dirichlet_projection_operator(interior, boundary_info, *dirichlet, dirichlet_projection_);
  GDT::Functionals::L2Face<Problem::NeumannDataBase, CommonTraits::GdtVectorType, CommonTraits::SpaceType, InteriorView>
  neumann_functional(*neumann, msfem_rhs_.vector(), coarse_space(), interior);

  this->add_codim0_assembler(local_assembler_, this->matrix());
  this->add(force_functional);
  this->add(dirichlet_projection_operator, new DSG::ApplyOn::BoundaryEntities<CommonTraits::InteriorGridViewType>());
  this->add(neumann_functional, new DSG::ApplyOn::NeumannIntersections<CommonTraits::InteriorGridViewType>(boundary_info));
  AssemblerBaseType::assemble(true);
  // substract the operators action on the dirichlet values, since we assemble in H^1 but solve in H^1_0
  CommonTraits::GdtVectorType tmp(coarse_space().mapper().size());
  global_matrix_.mv(dirichlet_projection_.vector(), tmp);
  force_functional.vector() -= tmp;
  // apply the dirichlet zero constraints to restrict the system to H^1_0
  GDT::Spaces::Constraints::Dirichlet<typename CommonTraits::GridViewType::Intersection, CommonTraits::RangeFieldType>
  dirichlet_constraints(boundary_info, coarse_space().mapper().maxNumDofs(), coarse_space().mapper().maxNumDofs());
  this->add(dirichlet_constraints, global_matrix_ /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  this->add(dirichlet_constraints,
            force_functional.vector() /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  AssemblerBaseType::assemble(DSC_CONFIG_GET("global.smp_constraints", false));

}

void CoarseScaleOperator::assemble() { DUNE_THROW(Dune::InvalidStateException, "nobody should be calling this"); }

void CoarseScaleOperator::apply_inverse(CoarseScaleOperator::CoarseDiscreteFunction& solution) {

  DSC::Profiler::ScopedTiming st("msfem.coarse.solve");

  BOOST_ASSERT_MSG(msfem_rhs_.dofs_valid(), "Coarse scale RHS DOFs need to be valid!");
  DSC_PROFILER.startTiming("msfem.coarse.linearSolver");
  typedef typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType Inverse;
  const  Inverse inverse(
      global_matrix_, msfem_rhs_.space().communicator());

  auto options = Inverse::options("bicgstab.amg.ilu0");
  constexpr bool overwrite = true;
  options.set("preconditioner.anisotropy_dim", CommonTraits::world_dim, overwrite);
  options.set("preconditioner.isotropy_dim", CommonTraits::world_dim, overwrite);
  options.set("verbose", "2", overwrite);
  options.set("preconditioner.verbose", "2", overwrite);
  options.set("smoother.verbose", "2", overwrite);
  options.set("post_check_solves_system", "0", overwrite);
  inverse.apply(msfem_rhs_.vector(), solution.vector(), options);

  if (!solution.dofs_valid())
    DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");

  solution.vector() += dirichlet_projection_.vector();

  DSC_PROFILER.stopTiming("msfem.coarse.linearSolver");
  DSC_LOG_INFO << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.coarse.linearSolver") << "ms."
               << std::endl;
}

const CoarseScaleOperator::SourceSpaceType& CoarseScaleOperator::coarse_space() const { return test_space(); }

} // namespace Multiscale {
} // namespace Dune {
<commit_msg>use custom partitioning for coarse scale op too<commit_after>#include <config.h>

#include "coarse_scale_operator.hh"

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/functionals/l2.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/msfem/localproblems/localgridlist.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/problems/base.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/msfem/coarse_rhs_functional.hh>
#include <dune/stuff/common/parallel/partitioner.hh>
#include <dune/grid/utility/partitioning/seedlist.hh>
#include <sstream>

namespace Dune {
namespace Multiscale {

Stuff::LA::SparsityPatternDefault CoarseScaleOperator::pattern(const CoarseScaleOperator::RangeSpaceType& range_space,
                                                               const CoarseScaleOperator::SourceSpaceType& source_space,
                                                               const CoarseScaleOperator::GridViewType& grid_view) {
  return range_space.compute_volume_pattern(grid_view, source_space);
}

CoarseScaleOperator::CoarseScaleOperator(const CoarseScaleOperator::SourceSpaceType& source_space_in,
                                         LocalGridList& localGridList)
  : OperatorBaseType(global_matrix_, source_space_in)
  , AssemblerBaseType(source_space_in, source_space_in.grid_view().grid().template leafGridView<InteriorBorder_Partition>())
  , global_matrix_(coarse_space().mapper().size(), coarse_space().mapper().size(),
                   EllipticOperatorType::pattern(coarse_space()))
  , local_assembler_(local_operator_, localGridList)
  , msfem_rhs_(coarse_space(), "MsFEM right hand side")
  , dirichlet_projection_(coarse_space()) {
  DSC::Profiler::ScopedTiming st("msfem.coarse.assemble");
  msfem_rhs_.vector() *= 0;
  const auto interior = coarse_space().grid_view().grid().template leafGridView<InteriorBorder_Partition>();
  typedef std::remove_const<decltype(interior)>::type InteriorType;
  Stuff::IndexSetPartitioner<InteriorType> ip(interior.indexSet());
  SeedListPartitioning<typename InteriorType::Grid, 0> partitioning(interior, ip);
  CoarseRhsFunctional force_functional(msfem_rhs_.vector(), coarse_space(), localGridList, interior);

  const auto& dirichlet = DMP::getDirichletData();
  const auto& boundary_info = Problem::getModelData()->boundaryInfo();
  const auto& neumann = Problem::getNeumannData();

  typedef CommonTraits::InteriorGridViewType InteriorView;
  GDT::Operators::DirichletProjectionLocalizable<InteriorView, Problem::DirichletDataBase,
                                                 CommonTraits::DiscreteFunctionType>
  dirichlet_projection_operator(interior, boundary_info, *dirichlet, dirichlet_projection_);
  GDT::Functionals::L2Face<Problem::NeumannDataBase, CommonTraits::GdtVectorType, CommonTraits::SpaceType, InteriorView>
  neumann_functional(*neumann, msfem_rhs_.vector(), coarse_space(), interior);

  this->add_codim0_assembler(local_assembler_, this->matrix());
  this->add(force_functional);
  this->add(dirichlet_projection_operator, new DSG::ApplyOn::BoundaryEntities<CommonTraits::InteriorGridViewType>());
  this->add(neumann_functional, new DSG::ApplyOn::NeumannIntersections<CommonTraits::InteriorGridViewType>(boundary_info));
  AssemblerBaseType::assemble(partitioning);
  // substract the operators action on the dirichlet values, since we assemble in H^1 but solve in H^1_0
  CommonTraits::GdtVectorType tmp(coarse_space().mapper().size());
  global_matrix_.mv(dirichlet_projection_.vector(), tmp);
  force_functional.vector() -= tmp;
  // apply the dirichlet zero constraints to restrict the system to H^1_0
  GDT::Spaces::Constraints::Dirichlet<typename CommonTraits::GridViewType::Intersection, CommonTraits::RangeFieldType>
  dirichlet_constraints(boundary_info, coarse_space().mapper().maxNumDofs(), coarse_space().mapper().maxNumDofs());
  this->add(dirichlet_constraints, global_matrix_ /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  this->add(dirichlet_constraints,
            force_functional.vector() /*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  if(DSC_CONFIG_GET("global.smp_constraints", false))
    AssemblerBaseType::assemble(false);
  else
    AssemblerBaseType::assemble(partitioning);
}

void CoarseScaleOperator::assemble() { DUNE_THROW(Dune::InvalidStateException, "nobody should be calling this"); }

void CoarseScaleOperator::apply_inverse(CoarseScaleOperator::CoarseDiscreteFunction& solution) {

  DSC::Profiler::ScopedTiming st("msfem.coarse.solve");

  BOOST_ASSERT_MSG(msfem_rhs_.dofs_valid(), "Coarse scale RHS DOFs need to be valid!");
  DSC_PROFILER.startTiming("msfem.coarse.linearSolver");
  typedef typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType Inverse;
  const  Inverse inverse(
      global_matrix_, msfem_rhs_.space().communicator());

  auto options = Inverse::options("bicgstab.amg.ilu0");
  constexpr bool overwrite = true;
  options.set("preconditioner.anisotropy_dim", CommonTraits::world_dim, overwrite);
  options.set("preconditioner.isotropy_dim", CommonTraits::world_dim, overwrite);
  options.set("verbose", "2", overwrite);
  options.set("preconditioner.verbose", "2", overwrite);
  options.set("smoother.verbose", "2", overwrite);
  options.set("post_check_solves_system", "0", overwrite);
  inverse.apply(msfem_rhs_.vector(), solution.vector(), options);

  if (!solution.dofs_valid())
    DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");

  solution.vector() += dirichlet_projection_.vector();

  DSC_PROFILER.stopTiming("msfem.coarse.linearSolver");
  DSC_LOG_INFO << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.coarse.linearSolver") << "ms."
               << std::endl;
}

const CoarseScaleOperator::SourceSpaceType& CoarseScaleOperator::coarse_space() const { return test_space(); }

} // namespace Multiscale {
} // namespace Dune {
<|endoftext|>


<commit_before>/*
    Copyright (C) 2009, 2011 Ferruccio Barletta (ferruccio.barletta@gmail.com)

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/

#include "dynamic.h"

namespace dynamic {

    ///
    /// cast to bool
    ///
    var::operator bool() const {
        try {
            return boost::get<bool_t>(_var);
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to int");
        }
    }

    ///
    /// cast to int
    ///
    var::operator int() const {
        try {
            return boost::get<int_t>(_var);
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to int");
        }
    }

    ///
    /// cast to double
    ///
    var::operator double() const {
        try {
            return boost::get<double_t>(_var);
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to double");
        }
    }

    ///
    /// cast to string
    ///
    var::operator std::string() const {
        try {
            return *boost::get<string_t>(_var).ps;
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to string");
        }
    }

    ///
    /// cast to wide string
    ///
    var::operator std::wstring() const {
        try {
            return *boost::get<wstring_t>(_var).ps;
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to wstring");
        }
    }

    ///
    /// @return type name
    ///
    struct var::type_string_visitor : public boost::static_visitor<std::string>
    {
        result_type operator () (null_t) const { return "none"; }
        result_type operator () (bool_t) const { return "bool"; }
        result_type operator () (int_t) const { return "int"; }
        result_type operator () (double_t) const { return "double"; }
        result_type operator () (const string_t& value) const { return "string"; }
        result_type operator () (const wstring_t& value) const { return "wstring"; }
        result_type operator () (const list_ptr& ptr) const { return "list"; }
        result_type operator () (const vector_ptr& ptr) const { return "vector"; }
        result_type operator () (const set_ptr& ptr) const { return "set"; }
        result_type operator () (const map_ptr& ptr) const { return "map"; }
    };
    std::string var::type() const {
        return boost::apply_visitor(type_string_visitor(), _var);
    }

    ///
    /// @return type identifier
    ///
    var::type_t var::get_type() const {
        return boost::apply_visitor(type_visitor(), _var);
    }

}
<commit_msg>Fixed name of null type<commit_after>/*
    Copyright (C) 2009, 2011 Ferruccio Barletta (ferruccio.barletta@gmail.com)

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/

#include "dynamic.h"

namespace dynamic {

    ///
    /// cast to bool
    ///
    var::operator bool() const {
        try {
            return boost::get<bool_t>(_var);
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to int");
        }
    }

    ///
    /// cast to int
    ///
    var::operator int() const {
        try {
            return boost::get<int_t>(_var);
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to int");
        }
    }

    ///
    /// cast to double
    ///
    var::operator double() const {
        try {
            return boost::get<double_t>(_var);
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to double");
        }
    }

    ///
    /// cast to string
    ///
    var::operator std::string() const {
        try {
            return *boost::get<string_t>(_var).ps;
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to string");
        }
    }

    ///
    /// cast to wide string
    ///
    var::operator std::wstring() const {
        try {
            return *boost::get<wstring_t>(_var).ps;
        } catch (const boost::bad_get&) {
            throw exception("cannot convert to wstring");
        }
    }

    ///
    /// @return type name
    ///
    struct var::type_string_visitor : public boost::static_visitor<std::string>
    {
        result_type operator () (null_t) const { return "null"; }
        result_type operator () (bool_t) const { return "bool"; }
        result_type operator () (int_t) const { return "int"; }
        result_type operator () (double_t) const { return "double"; }
        result_type operator () (const string_t& value) const { return "string"; }
        result_type operator () (const wstring_t& value) const { return "wstring"; }
        result_type operator () (const list_ptr& ptr) const { return "list"; }
        result_type operator () (const vector_ptr& ptr) const { return "vector"; }
        result_type operator () (const set_ptr& ptr) const { return "set"; }
        result_type operator () (const map_ptr& ptr) const { return "map"; }
    };
    std::string var::type() const {
        return boost::apply_visitor(type_string_visitor(), _var);
    }

    ///
    /// @return type identifier
    ///
    var::type_t var::get_type() const {
        return boost::apply_visitor(type_visitor(), _var);
    }

}
<|endoftext|>


<commit_before>// Copyright **********************************************************
//
// File ecmdDllCapi.H
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 2003
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright ******************************************************

//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <inttypes.h>
#include <stdio.h>

#include <ecmdDllCapi.H>
#include <ecmdStructs.H>
#include <ecmdReturnCodes.H>
#include <ecmdDataBuffer.H>

//--------------------------------------------------------------------
//  Forward References
//--------------------------------------------------------------------

// Change Log *********************************************************
//
//  Flag Reason   Vers Date     Coder  Description
//  ---- -------- ---- -------- -----  -------------------------------
//                              willsj Initial Creation
//
// End Change Log *****************************************************

//--------------------------------------------------------------------
//  Function Definitions
//--------------------------------------------------------------------
//
//   These are just stubs, used for testing the out the DLL

int dllInitDll() {
  /* This is where we would init any local variables to the dll */
  printf("Stub dll has been initialized\n");
  return ECMD_SUCCESS;
}

int dllCommandArgs(int argc, char* argv[]) {
  return ECMD_SUCCESS;
}

int dllGetRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllRingRead (ecmdChipTarget & target, const char * ringName, const char * fileName) { return ECMD_SUCCESS; }

int dllRingWrite (ecmdChipTarget & target, const char * ringName, const char * fileName) { return ECMD_SUCCESS; }

int dllGetScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllGetSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllGetSpyEnum(ecmdChipTarget & target, const char * spyName, std::string enumValue){ return ECMD_SUCCESS; }

int dllPutSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutSpyEnum(ecmdChipTarget & target, const char * spyName, const std::string enumValue){ return ECMD_SUCCESS; }

int dllGetArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllQueryConfig(ecmdChipTarget & target, std::vector<ecmdCageData> & queryData){ return ECMD_SUCCESS; }

int dllQueryRing(ecmdChipTarget & target, std::vector<ecmdRingData> & queryData, const char * ringName ){ return ECMD_SUCCESS; }

int dllQueryArray(ecmdChipTarget & target, std::vector<ecmdArrayData> & queryData, const char * arrayName){ return ECMD_SUCCESS; }

int dllQuerySpy(ecmdChipTarget & target, std::vector<ecmdSpyData> & queryData, const char * spyName){ return ECMD_SUCCESS; }

int dllQueryFileLocation(ecmdChipTarget & target, ecmdFileType_t fileType, std::string fileLocation){ return ECMD_SUCCESS; }

int dllFlushSys () { return ECMD_SUCCESS; }

int dllIplSys () { return ECMD_SUCCESS; }

void dllOutputError(const char* message) {
  printf("DLLSTUBERROR : %s\n",message);
}

void dllOutputWarning(const char* message) {
  printf("DLLSTUBWARNING : %s\n",message);
}

void dllOutput(const char* message) {
  printf(message);
}
<commit_msg>Added new functions<commit_after>// Copyright **********************************************************
//
// File ecmdDllCapi.H
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 2003
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright ******************************************************

//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <inttypes.h>
#include <stdio.h>

#include <ecmdDllCapi.H>
#include <ecmdStructs.H>
#include <ecmdReturnCodes.H>
#include <ecmdDataBuffer.H>

//--------------------------------------------------------------------
//  Forward References
//--------------------------------------------------------------------

// Change Log *********************************************************
//
//  Flag Reason   Vers Date     Coder  Description
//  ---- -------- ---- -------- -----  -------------------------------
//                              willsj Initial Creation
//
// End Change Log *****************************************************

//--------------------------------------------------------------------
//  Function Definitions
//--------------------------------------------------------------------
//
//   These are just stubs, used for testing the out the DLL

int dllInitDll() {
  /* This is where we would init any local variables to the dll */
  printf("Stub dll has been initialized\n");
  return ECMD_SUCCESS;
}

int dllFreeDll() {
  return ECMD_SUCCESS;
}

int dllSpecificCommandArgs(int* argc, char** argv[]) {
  return ECMD_SUCCESS;
}

int dllGetRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllRingRead (ecmdChipTarget & target, const char * ringName, const char * fileName) { return ECMD_SUCCESS; }

int dllRingWrite (ecmdChipTarget & target, const char * ringName, const char * fileName) { return ECMD_SUCCESS; }

int dllGetScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllGetSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllGetSpyEnum(ecmdChipTarget & target, const char * spyName, std::string enumValue){ return ECMD_SUCCESS; }

int dllPutSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutSpyEnum(ecmdChipTarget & target, const char * spyName, const std::string enumValue){ return ECMD_SUCCESS; }

int dllGetArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllPutArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data) { return ECMD_SUCCESS; }

int dllQueryConfig(ecmdChipTarget & target, std::vector<ecmdCageData> & queryData){ return ECMD_SUCCESS; }

int dllQueryRing(ecmdChipTarget & target, std::vector<ecmdRingData> & queryData, const char * ringName ){ return ECMD_SUCCESS; }

int dllQueryArray(ecmdChipTarget & target, std::vector<ecmdArrayData> & queryData, const char * arrayName){ return ECMD_SUCCESS; }

int dllQuerySpy(ecmdChipTarget & target, std::vector<ecmdSpyData> & queryData, const char * spyName){ return ECMD_SUCCESS; }

int dllQueryFileLocation(ecmdChipTarget & target, ecmdFileType_t fileType, std::string fileLocation){ return ECMD_SUCCESS; }

int dllFlushSys () { return ECMD_SUCCESS; }

int dllIplSys () { return ECMD_SUCCESS; }

void dllOutputError(const char* message) {
  printf("DLLSTUBERROR : %s\n",message);
}

void dllOutputWarning(const char* message) {
  printf("DLLSTUBWARNING : %s\n",message);
}

void dllOutput(const char* message) {
  printf(message);
}
<|endoftext|>


<commit_before>//https://code.google.com/p/nya-engine/

#include "ui/ui.h"

#include <string>

namespace
{
    nya_log::log *ui_log=0;
}

namespace nya_ui
{

uint clamp(int v,uint from,uint to)
{
    if(v>(int)to) v=to;
    if(v<(int)from) v=from;
    return v;
}

float clamp(float v,float from,float to)
{
    if(v>(int)to) v=to;
    if(v<(int)from) v=from;
    return v;
}

const rect &widget::get_rect()
{
    if(m_cached_rect)
        return m_rect;

    int x,y,w,h;
    if(m_align_left)
    {
        x=m_pos_left+m_parent_pos_x;
        if(m_align_right)
            w=m_parent_width-m_pos_right-m_pos_left;
        else
            w=m_width;
    }
    else if(m_align_right)
    {
        x=m_parent_pos_x+m_parent_width-m_width-m_pos_right;
        w=m_width;
    }
    else
    {
        x=m_parent_pos_x+m_parent_width/2-m_center_x-m_width/2;
        w=m_width;
    }

    if(m_align_bottom)
    {
        y=m_pos_bottom+m_parent_pos_y;
        if(m_align_top)
            h=m_parent_height-m_pos_top-m_pos_bottom;
        else
            h=m_height;
    }
    else if(m_align_top)
    {
        y=m_parent_pos_y+m_parent_height-m_height-m_pos_top;
        h=m_height;
    }
    else
    {
        y=m_parent_pos_y+m_parent_height/2-m_center_y-m_height/2;
        h=m_height;
    }

    if(m_keep_aspect==from_width)
    {
        h=w*m_height/m_width;
    }
    else if(m_keep_aspect==from_height)
    {
        w=h*m_width/m_height;
    }

    if(x<m_parent_pos_x)
        x=m_parent_pos_x;
    if(y<m_parent_pos_y)
        y=m_parent_pos_y;

    const int cw=m_parent_pos_x-x+m_parent_width;
    if(w>cw)
        w=cw;

    const int ch=m_parent_pos_y-y+m_parent_height;
    if(h>ch)
        h=ch;

    m_rect=rect();

    if(x>0) m_rect.x=x;
    if(y>0) m_rect.y=y;
    if(w>0) m_rect.w=w;
    if(h>0) m_rect.h=h;

    m_cached_rect=true;

    return m_rect;
}

void layer::draw()
{
    draw_widgets(*this);
}

void layer::resize(uint width, uint height)
{
    m_width=width;
    m_height=height;

    layout::resize(m_width,m_height);
}

void layer::process()
{
    for(events_deque::iterator it=m_events.begin();
        it!=m_events.end();++it)
    {
        //get_log()<<"event: "<<it->sender.c_str()<<" "<<it->type.c_str()<<"\n";
        process_events(*it);

        //layout::process_events(*it);
        it->free_data();
    }

    m_events.clear();
}

void layout::process_events(layout::event &e)
{
    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        w->process_events(e);
    }
}

void layout::add_widget(widget &w)
{
    w.parent_moved(m_x,m_y);
    w.parent_resized(m_width,m_height);
    w.calc_pos_markers();

    w.m_parent=this;

    m_widgets.push_back(&w);
}

void layout::draw_widgets(layer &l)
{
    if(!m_width || !m_height)
        return;

    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        if(w->m_visible)
            w->draw(l);
    }
}

void layout::resize(uint width,uint height)
{
    m_width=width;
    m_height=height;

    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
        (*it)->parent_resized(m_width,m_height);
}

void layout::move(int x,int y)
{
    m_x=x;
    m_y=y;

    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
        (*it)->parent_moved(m_x,m_y);
}

bool layout::mouse_button(layout::mbutton button,bool pressed)
{
    bool processed=false;

    for(widgets_list::reverse_iterator it=m_widgets.rbegin();
          it!=m_widgets.rend();++it)
    {
        widget *w=*it;
        if(!w->is_visible())
            continue;

        if(((w->m_mouse_over && !processed) || !pressed)
            && w->m_mouse_pressed!=pressed)
        {
            w->on_mouse_button(button,pressed);
            w->m_mouse_pressed=pressed;
            if(pressed)
                processed=true;
        }
    }
    //get_log()<<"mbutton"<<(int)button<<" "<<(int)pressed<<"\n";

    return processed;
}

bool layout::mouse_move(uint x,uint y)
{
    m_mouse_x=x;
    m_mouse_y=y;

    bool processed=false;

    for(widgets_list::reverse_iterator it=m_widgets.rbegin();
          it!=m_widgets.rend();++it)
    {
        widget *w=*it;
        if(!w->is_visible())
            continue;

        w->update_mouse_over();

        if(!processed && w->on_mouse_move(x,y,w->is_mouse_over()))
            processed=true;
    }
    //get_log()<<"mmove "<<(int)x<<" "<<(int)y<<"\n";

    return processed;
}

void layout::mouse_left()
{
    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        if(w->m_mouse_over)
        {
            w->on_mouse_left();
            w->m_mouse_over=false;
        }
    }
}

bool layout::mouse_scroll(uint dx,uint dy)
{
    bool processed=false;
    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        if(!w->is_visible())
            continue;

        if(w->m_mouse_over)
        {
            if(w->on_mouse_scroll(dx,dy))
                processed=true;
        }
    }

    return processed;
}

void layer::send_event(event &e)
{
    m_events.push_back(e);

    const uint msg_limit=1024;

    if(m_events.size()>msg_limit)
        m_events.pop_front();
}

void set_log(nya_log::log *l)
{
    ui_log = l;
}

nya_log::log &get_log()
{
    static const char *ui_log_tag="ui";
    if(!ui_log)
    {
        return nya_log::get_log(ui_log_tag);
    }

    ui_log->set_tag(ui_log_tag);
    return *ui_log;
}

}
<commit_msg>ui events fix<commit_after>//https://code.google.com/p/nya-engine/

#include "ui/ui.h"

#include <string>

namespace
{
    nya_log::log *ui_log=0;
}

namespace nya_ui
{

uint clamp(int v,uint from,uint to)
{
    if(v>(int)to) v=to;
    if(v<(int)from) v=from;
    return v;
}

float clamp(float v,float from,float to)
{
    if(v>(int)to) v=to;
    if(v<(int)from) v=from;
    return v;
}

const rect &widget::get_rect()
{
    if(m_cached_rect)
        return m_rect;

    int x,y,w,h;
    if(m_align_left)
    {
        x=m_pos_left+m_parent_pos_x;
        if(m_align_right)
            w=m_parent_width-m_pos_right-m_pos_left;
        else
            w=m_width;
    }
    else if(m_align_right)
    {
        x=m_parent_pos_x+m_parent_width-m_width-m_pos_right;
        w=m_width;
    }
    else
    {
        x=m_parent_pos_x+m_parent_width/2-m_center_x-m_width/2;
        w=m_width;
    }

    if(m_align_bottom)
    {
        y=m_pos_bottom+m_parent_pos_y;
        if(m_align_top)
            h=m_parent_height-m_pos_top-m_pos_bottom;
        else
            h=m_height;
    }
    else if(m_align_top)
    {
        y=m_parent_pos_y+m_parent_height-m_height-m_pos_top;
        h=m_height;
    }
    else
    {
        y=m_parent_pos_y+m_parent_height/2-m_center_y-m_height/2;
        h=m_height;
    }

    if(m_keep_aspect==from_width)
    {
        h=w*m_height/m_width;
    }
    else if(m_keep_aspect==from_height)
    {
        w=h*m_width/m_height;
    }

    if(x<m_parent_pos_x)
        x=m_parent_pos_x;
    if(y<m_parent_pos_y)
        y=m_parent_pos_y;

    const int cw=m_parent_pos_x-x+m_parent_width;
    if(w>cw)
        w=cw;

    const int ch=m_parent_pos_y-y+m_parent_height;
    if(h>ch)
        h=ch;

    m_rect=rect();

    if(x>0) m_rect.x=x;
    if(y>0) m_rect.y=y;
    if(w>0) m_rect.w=w;
    if(h>0) m_rect.h=h;

    m_cached_rect=true;

    return m_rect;
}

void layer::draw()
{
    draw_widgets(*this);
}

void layer::resize(uint width, uint height)
{
    m_width=width;
    m_height=height;

    layout::resize(m_width,m_height);
}

void layer::process()
{
    events_deque events=m_events;
    m_events.clear();

    for(events_deque::iterator it=events.begin();
        it!=events.end();++it)
    {
        //get_log()<<"event: "<<it->sender.c_str()<<" "<<it->type.c_str()<<"\n";
        process_events(*it);

        //layout::process_events(*it);
        it->free_data();
    }
}

void layout::process_events(layout::event &e)
{
    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        w->process_events(e);
    }
}

void layout::add_widget(widget &w)
{
    w.parent_moved(m_x,m_y);
    w.parent_resized(m_width,m_height);
    w.calc_pos_markers();

    w.m_parent=this;

    m_widgets.push_back(&w);
}

void layout::draw_widgets(layer &l)
{
    if(!m_width || !m_height)
        return;

    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        if(w->m_visible)
            w->draw(l);
    }
}

void layout::resize(uint width,uint height)
{
    m_width=width;
    m_height=height;

    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
        (*it)->parent_resized(m_width,m_height);
}

void layout::move(int x,int y)
{
    m_x=x;
    m_y=y;

    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
        (*it)->parent_moved(m_x,m_y);
}

bool layout::mouse_button(layout::mbutton button,bool pressed)
{
    bool processed=false;

    for(widgets_list::reverse_iterator it=m_widgets.rbegin();
          it!=m_widgets.rend();++it)
    {
        widget *w=*it;
        if(!w->is_visible())
            continue;

        if(((w->m_mouse_over && !processed) || !pressed)
            && w->m_mouse_pressed!=pressed)
        {
            w->on_mouse_button(button,pressed);
            w->m_mouse_pressed=pressed;
            if(pressed)
                processed=true;
        }
    }
    //get_log()<<"mbutton"<<(int)button<<" "<<(int)pressed<<"\n";

    return processed;
}

bool layout::mouse_move(uint x,uint y)
{
    m_mouse_x=x;
    m_mouse_y=y;

    bool processed=false;

    for(widgets_list::reverse_iterator it=m_widgets.rbegin();
          it!=m_widgets.rend();++it)
    {
        widget *w=*it;
        if(!w->is_visible())
            continue;

        w->update_mouse_over();

        if(!processed && w->on_mouse_move(x,y,w->is_mouse_over()))
            processed=true;
    }
    //get_log()<<"mmove "<<(int)x<<" "<<(int)y<<"\n";

    return processed;
}

void layout::mouse_left()
{
    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        if(w->m_mouse_over)
        {
            w->on_mouse_left();
            w->m_mouse_over=false;
        }
    }
}

bool layout::mouse_scroll(uint dx,uint dy)
{
    bool processed=false;
    for(widgets_list::iterator it=m_widgets.begin();
        it!=m_widgets.end();++it)
    {
        widget *w=*it;
        if(!w->is_visible())
            continue;

        if(w->m_mouse_over)
        {
            if(w->on_mouse_scroll(dx,dy))
                processed=true;
        }
    }

    return processed;
}

void layer::send_event(event &e)
{
    m_events.push_back(e);

    const uint msg_limit=1024;

    if(m_events.size()>msg_limit)
        m_events.pop_front();
}

void set_log(nya_log::log *l)
{
    ui_log = l;
}

nya_log::log &get_log()
{
    static const char *ui_log_tag="ui";
    if(!ui_log)
    {
        return nya_log::get_log(ui_log_tag);
    }

    ui_log->set_tag(ui_log_tag);
    return *ui_log;
}

}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkRenderWindow.h"
#include "mitkVtkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include "mitkRenderingManager.h"
#include "mitkSliceNavigationController.h"
#include "mitkCameraRotationController.h"
#include "mitkVtkLayerController.h"

#include <itkSmartPointerForwardReference.txx>

#include <assert.h>

std::set<mitk::RenderWindow*> mitk::RenderWindow::instances;

mitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer)
  : m_MitkVtkRenderWindow(NULL), m_Renderer(renderer)
{
  if(name == NULL)
    m_Name = "renderwindow";
  else
    m_Name = name;
  instances.insert(this);

  RenderingManager::GetInstance()->AddRenderWindow( this );

  m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();

  m_CameraRotationController = mitk::CameraRotationController::New();
  m_CameraRotationController->SetRenderWindow( this );
  m_CameraRotationController->AcquireCamera();

  // Initialize Layer Controller
  m_VtkLayerController = new mitk::VtkLayerController(m_MitkVtkRenderWindow);
}

mitk::RenderWindow::~RenderWindow()
{
  instances.erase(this);

  RenderingManager::GetInstance()->RemoveRenderWindow( this );

  // maybe the following block should be after the next one
  if(m_Renderer.IsNotNull())
  {
    m_Renderer->InitRenderer(NULL);
    m_Renderer = NULL;
  }

  if(m_MitkVtkRenderWindow != NULL)
  {
    m_MitkVtkRenderWindow->Delete();
    m_MitkVtkRenderWindow = NULL;
  }
}

void mitk::RenderWindow::MakeCurrent()
{
  m_MitkVtkRenderWindow->MakeCurrent();
};

void mitk::RenderWindow::SwapBuffers()
{
  m_MitkVtkRenderWindow->Frame();
};

bool mitk::RenderWindow::IsSharing () const
{
  return false;
}

void mitk::RenderWindow::RequestUpdate()
{
  mitk::RenderingManager::GetInstance()->RequestUpdate( this );
}

void mitk::RenderWindow::ForceImmediateUpdate()
{
  mitk::RenderingManager::GetInstance()->ForceImmediateUpdate( this );
}

void mitk::RenderWindow::SetSize(int w, int h)
{
  m_MitkVtkRenderWindow->SetSize(w,h);
}

void mitk::RenderWindow::InitRenderer()
{

  if(m_Renderer.IsNull())
  {
    std::string rendererName("Renderer::");
    rendererName += m_Name;
    m_Renderer = new OpenGLRenderer( rendererName.c_str() );
  }
  mitk::OpenGLRenderer* o = dynamic_cast<mitk::OpenGLRenderer*>( m_Renderer.GetPointer());
  vtkRenderer* r = o->GetVtkRenderer();
  if(o->GetVtkRenderer() == NULL)
  {
    std::string rendererName("Renderer::");
    rendererName += m_Name;
    m_Renderer = new OpenGLRenderer( rendererName.c_str() );
  }

  m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);
  m_Renderer->InitRenderer(this);

  int * size = m_MitkVtkRenderWindow->GetSize();
  if((size[0]>10) && (size[1]>10))
    m_Renderer->InitSize(size[0], size[1]);

  m_SliceNavigationController = mitk::SliceNavigationController::New( "navigation" );
  m_SliceNavigationController->ConnectGeometrySliceEvent( m_Renderer.GetPointer());
  m_SliceNavigationController->ConnectGeometryUpdateEvent( m_Renderer.GetPointer() );
  m_SliceNavigationController->ConnectGeometryTimeEvent( m_Renderer.GetPointer(), false );

  // VTK Layer Controller
  m_VtkLayerController->InsertSceneRenderer(r);

}

void mitk::RenderWindow::SetWindowId(void * id)
{
  m_MitkVtkRenderWindow->SetWindowId( id );
}

void mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)
{
  if (renWin != NULL)
  {
    m_MitkVtkRenderWindow = renWin;
    m_VtkLayerController->SetRenderWindow(renWin);
    InitRenderer();
  }
}

mitk::SliceNavigationController*
mitk::RenderWindow
::GetSliceNavigationController() const
{
  return m_SliceNavigationController;
}

mitk::CameraRotationController*
mitk::RenderWindow
::GetCameraRotationController() const
{
  return m_CameraRotationController;
}

mitk::BaseController*
mitk::RenderWindow
::GetController() const
{
  switch ( m_Renderer->GetMapperID() )
  {
    case BaseRenderer::Standard2D:
      return m_SliceNavigationController;

    case BaseRenderer::Standard3D:
      return m_CameraRotationController;

    default:
      return m_SliceNavigationController;
  }
}

mitk::VtkLayerController*
mitk::RenderWindow
::GetVtkLayerController() const
{
  return m_VtkLayerController;
}
<commit_msg>ENH (#1020): Provide reference to Renderer for SliceNavigationController (used for compensating DisplayGeometry positioning error during rotation)<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkRenderWindow.h"
#include "mitkVtkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include "mitkRenderingManager.h"
#include "mitkSliceNavigationController.h"
#include "mitkCameraRotationController.h"
#include "mitkVtkLayerController.h"

#include <itkSmartPointerForwardReference.txx>

#include <assert.h>

std::set<mitk::RenderWindow*> mitk::RenderWindow::instances;

mitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer)
  : m_MitkVtkRenderWindow(NULL), m_Renderer(renderer)
{
  if(name == NULL)
    m_Name = "renderwindow";
  else
    m_Name = name;
  instances.insert(this);

  RenderingManager::GetInstance()->AddRenderWindow( this );

  m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();

  m_CameraRotationController = mitk::CameraRotationController::New();
  m_CameraRotationController->SetRenderWindow( this );
  m_CameraRotationController->AcquireCamera();

  // Initialize Layer Controller
  m_VtkLayerController = new mitk::VtkLayerController(m_MitkVtkRenderWindow);
}

mitk::RenderWindow::~RenderWindow()
{
  instances.erase(this);

  RenderingManager::GetInstance()->RemoveRenderWindow( this );

  // maybe the following block should be after the next one
  if(m_Renderer.IsNotNull())
  {
    m_Renderer->InitRenderer(NULL);
    m_Renderer = NULL;
  }

  if(m_MitkVtkRenderWindow != NULL)
  {
    m_MitkVtkRenderWindow->Delete();
    m_MitkVtkRenderWindow = NULL;
  }
}

void mitk::RenderWindow::MakeCurrent()
{
  m_MitkVtkRenderWindow->MakeCurrent();
};

void mitk::RenderWindow::SwapBuffers()
{
  m_MitkVtkRenderWindow->Frame();
};

bool mitk::RenderWindow::IsSharing () const
{
  return false;
}

void mitk::RenderWindow::RequestUpdate()
{
  mitk::RenderingManager::GetInstance()->RequestUpdate( this );
}

void mitk::RenderWindow::ForceImmediateUpdate()
{
  mitk::RenderingManager::GetInstance()->ForceImmediateUpdate( this );
}

void mitk::RenderWindow::SetSize(int w, int h)
{
  m_MitkVtkRenderWindow->SetSize(w,h);
}

void mitk::RenderWindow::InitRenderer()
{

  if(m_Renderer.IsNull())
  {
    std::string rendererName("Renderer::");
    rendererName += m_Name;
    m_Renderer = new OpenGLRenderer( rendererName.c_str() );
  }
  mitk::OpenGLRenderer* o = dynamic_cast<mitk::OpenGLRenderer*>( m_Renderer.GetPointer());
  vtkRenderer* r = o->GetVtkRenderer();
  if(o->GetVtkRenderer() == NULL)
  {
    std::string rendererName("Renderer::");
    rendererName += m_Name;
    m_Renderer = new OpenGLRenderer( rendererName.c_str() );
  }

  m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);
  m_Renderer->InitRenderer(this);

  int * size = m_MitkVtkRenderWindow->GetSize();
  if((size[0]>10) && (size[1]>10))
    m_Renderer->InitSize(size[0], size[1]);

  m_SliceNavigationController = mitk::SliceNavigationController::New( "navigation" );
  m_SliceNavigationController->SetRenderer( m_Renderer.GetPointer() );
  m_SliceNavigationController->ConnectGeometrySliceEvent( m_Renderer.GetPointer());
  m_SliceNavigationController->ConnectGeometryUpdateEvent( m_Renderer.GetPointer() );
  m_SliceNavigationController->ConnectGeometryTimeEvent( m_Renderer.GetPointer(), false );

  // VTK Layer Controller
  m_VtkLayerController->InsertSceneRenderer(r);

}

void mitk::RenderWindow::SetWindowId(void * id)
{
  m_MitkVtkRenderWindow->SetWindowId( id );
}

void mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)
{
  if (renWin != NULL)
  {
    m_MitkVtkRenderWindow = renWin;
    m_VtkLayerController->SetRenderWindow(renWin);
    InitRenderer();
  }
}

mitk::SliceNavigationController*
mitk::RenderWindow
::GetSliceNavigationController() const
{
  return m_SliceNavigationController;
}

mitk::CameraRotationController*
mitk::RenderWindow
::GetCameraRotationController() const
{
  return m_CameraRotationController;
}

mitk::BaseController*
mitk::RenderWindow
::GetController() const
{
  switch ( m_Renderer->GetMapperID() )
  {
    case BaseRenderer::Standard2D:
      return m_SliceNavigationController;

    case BaseRenderer::Standard3D:
      return m_CameraRotationController;

    default:
      return m_SliceNavigationController;
  }
}

mitk::VtkLayerController*
mitk::RenderWindow
::GetVtkLayerController() const
{
  return m_VtkLayerController;
}
<|endoftext|>


<commit_before>/*
* FUEL(isp) is a fast usable embeddable lisp interpreter.
*
* Copyright (c) 2016 Michael Neuroth
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* */

//using System;
//using System.IO;
//using System.Linq;
//using System.Reflection;

#include "fuel.h"

#ifdef _WIN32
#include <windows.h>
#define FUEL_DEBUGGER_NAME "FuelDebugger.dll"
#endif

#if defined( __linux__ ) || defined( __APPLE__ )
#include <dlfcn.h>			// fuer:
#endif

#if defined( __linux__ )
#define FUEL_DEBUGGER_NAME "libFuelDebugger.so"
#endif

#if defined( __APPLE__ )
#define FUEL_DEBUGGER_NAME "libFuelDebugger.dylib"
#endif

void * SimpleLoadLibrary(const char * sDllName)
{
#ifdef _WIN32
#ifdef UNICODE
	std::string s(sDllName);
	std::wstring stemp = std::wstring(s.begin(), s.end());
    return (void *)LoadLibrary( (LPCWSTR)stemp.c_str() );
#else
    return (void *)LoadLibrary( (LPCSTR)sDllName );
#endif
#endif
#if defined( __linux__ ) || defined( __APPLE__ )
    return (void *)dlopen( sDllName, RTLD_LAZY );
#endif
}

bool SimpleFreeLibrary(void * hDllModule)
{
#ifdef _WIN32
	return FreeLibrary((HMODULE)hDllModule) == TRUE;
#endif
#if defined( __linux__ ) || defined( __APPLE__ )
    return dlclose( (void *)hDllModule );
#endif
}

void * SimpleGetProcAddress(void * hDllModule, const char * sProcName)
{
#ifdef _WIN32
	return (void *)GetProcAddress((HMODULE)hDllModule, sProcName);
#endif
#if defined( __linux__ ) || defined( __APPLE__ )
	return (void *)dlsym( (void *)hDllModule, sProcName );
#endif
}

static void * g_hDebuggerDLL = 0;

#ifdef UNIT_TEST
extern "C" CppLisp::ILispDebugger * create_debugger();
#endif

static void DisconnectDebugger()
{
	if (g_hDebuggerDLL != 0)
	{
		SimpleFreeLibrary(g_hDebuggerDLL);
	}
}

namespace CppLisp
{
	extern string LispUtils_LibraryPath;

	uint64_t Environment_GetTickCount(void);

	bool Contains(const std::vector<string> & container, const string & search)
	{
		return std::find(container.begin(), container.end(), search) != container.end();
	}

	std::vector<string> GetScriptFilesFromProgramArgs(const std::vector<string> & args)
	{
		std::vector<string> result;
		std::copy_if(args.begin(), args.end(), back_inserter(result), [](const string & s) -> bool { return !s.StartsWith("-");  });
		return result;
	}

	void Fuel::Main(std::vector<string> args)
	{
		std::shared_ptr<TextWriter> writer = std::make_shared<TextWriter>();
		std::shared_ptr<TextReader> reader = std::make_shared<TextReader>();
		MainExtended(args, /*Console.Out, Console.In*/writer, reader);
	}

	void Fuel::MainExtended(std::vector<string> args, std::shared_ptr<TextWriter> output, std::shared_ptr<TextReader> input)
	{
		if (args.size() == 0)
		{
			Usage(output);
			return;
		}

		string script = /*null*/string::Empty;
		var loadFiles = true;
		var trace = false;
		var macroExpand = false;
		//var compile = false;
		var wasDebugging = false;
		//var showCompileOutput = false;
		var measureTime = false;
		var lengthyErrorOutput = false;
		var result = std::make_shared<LispVariant>();
		var startTickCount = /*Environment.TickCount*/Environment_GetTickCount();
		var debugger = TryGetDebugger();

		if (Contains(args, "-m"))
		{
			measureTime = true;
		}
		if (Contains(args, "-v"))
		{
			output->WriteLine(Lisp::ProgramName + " " + Lisp::Version + " from " + Lisp::Date);
			return;
		}
		if (Contains(args, "-h"))
		{
			Usage(output);
			return;
		}
		if (Contains(args, "--doc"))
		{
			script = "(println (doc))";
			loadFiles = false;
		}
		if (Contains(args, "--html"))
		{
			script = "(println (htmldoc))";
			loadFiles = false;
		}
		if (Contains(args, "--macro-expand"))
		{
			macroExpand = true;
		}
		if (Contains(args, "-x"))
		{
			lengthyErrorOutput = true;
		}
		if (Contains(args, "-t"))
		{
			trace = true;
		}
		if (Contains(args, "-e"))
		{
			script = /*LispUtils.*/GetScriptFilesFromProgramArgs(args)[0]/*.FirstOrDefault()*/;
			loadFiles = false;
		}
		//org: var libPath = args.Where(v = > v.StartsWith("-l=")).Select(v = > v).ToArray();
		var libPath = std::vector<string>(std::find_if(args.begin(), args.end(), [](const string & v) -> bool { return v.StartsWith("-l="); }), args.end());
		if (libPath.size() > 0)
		{
			string libraryPath = libPath.front().Substring(3);
			LispUtils_LibraryPath = libraryPath;
		}

		// handle options for compiler
		//if (Contains(args, "-c"))
		//{
		//	compile = true;
		//}
		//if (Contains(args, "-s"))
		//{
		//	showCompileOutput = true;
		//}

		// handle options for debugger
		if (debugger != null)
		{
			debugger->SetInputOutputStreams(output, input);
			if (Contains(args, "-i"))
			{
				InteractiveLoopHeader(output);
				debugger->InteractiveLoop(null, null, /*startedFromMain:*/ true, /*tracing :*/ trace, output, input);
				loadFiles = false;
				wasDebugging = true;
			}
			if (Contains(args, "-d"))
			{
				//var fileName = /*LispUtils.*/GetScriptFilesFromProgramArgs(args)./*FirstOrDefault()*/front();
				var scriptFiles = GetScriptFilesFromProgramArgs(args);
				var fileName = scriptFiles.size() > 0 ? scriptFiles.front() : string::Empty;
				// process -e option if script is given via command line
				if (string::IsNullOrEmpty(script))
				{
					script = /*LispUtils.*/ReadFileOrEmptyString(fileName);
				}
				else
				{
					fileName = "command-line";
				}

				InteractiveLoopHeader(output);
				result = debugger->DebuggerLoop(script, fileName, /*tracing:*/ trace);
				loadFiles = false;
				wasDebugging = true;
			}
		}

		if (loadFiles)
		{
			var scriptFiles = /*LispUtils.*/GetScriptFilesFromProgramArgs(args);

			for (var fileName : scriptFiles)
			{
				script = /*LispUtils.*/ReadFileOrEmptyString(fileName);
				//ILispCompiler compiler = TryGetCompiler();
				//if (compile && compiler != null)
				//{
				//	result = compiler.CompileToExe(script, fileName + ".exe");
				//}
				//else if (showCompileOutput && compiler != null)
				//{
				//	result = compiler.CompileToCsCode(script);
				//	output->WriteLine(result.StringValue);
				//}
				//else
				{
					result = Lisp::SaveEval(script, /*moduleName:*/ fileName, /*verboseErrorOutput:*/ lengthyErrorOutput, /*tracing:*/ trace, output, input, macroExpand);
				}
			}
		}
		else if (!string::IsNullOrEmpty(script) && !wasDebugging)
		{
			// process -e option
			result = Lisp::SaveEval(script, /*moduleName:*/ "cmdline", /*verboseErrorOutput:*/ false, /*tracing:*/ false, output, input, macroExpand);
		}

		if (macroExpand)
		{
			output->WriteLine(string("Macro expand: ") + result->ToString());
		}
		if (trace)
		{
			output->WriteLine(string("Result=") + result->ToString());
		}
		if (measureTime)
		{
			output->WriteLine("Execution time = {0} s", std::to_string((/*Environment.TickCount*/Environment_GetTickCount() - startTickCount) * 0.001));
		}

		DisconnectDebugger();
	}

	void Fuel::Usage(std::shared_ptr<TextWriter> output)
	{
		/*LispUtils.*/ShowAbout(output);
		output->WriteLine("usage:");
		output->WriteLine(">" + Lisp::ProgramName + " [options] [script_file_name]");
		output->WriteLine();
		output->WriteLine("options:");
		output->WriteLine("  -v          : show version");
		output->WriteLine("  -h          : show help");
		output->WriteLine("  -e \"script\" : execute given script");
		output->WriteLine("  -l=\"path\"   : path to library");
		output->WriteLine("  --doc       : show language documentation");
		output->WriteLine("  --html      : show language documentation in html");
		output->WriteLine("  --macro-expand : expand all macros and show resulting code");
		output->WriteLine("  -m          : measure execution time");
		output->WriteLine("  -t          : enable tracing");
		output->WriteLine("  -x          : exhaustive error output");
		if (TryGetDebugger() != null)
		{
			output->WriteLine("  -i          : interactive shell");
			output->WriteLine("  -d          : start debugger");
		}
		else
		{
			output->WriteLine();
			output->WriteLine("Info: no debugger support installed !");
		}
		//if (TryGetCompiler() != null)
		//{
		//	output->WriteLine("  -c          : compile program");
		//	output->WriteLine("  -s          : show C# compiler output");
		//}
		//else
		//{
		//	output->WriteLine();
		//	output->WriteLine("Info: no compiler support installed !");
		//}
		output->WriteLine();
	}

	void Fuel::InteractiveLoopHeader(std::shared_ptr<TextWriter> output)
	{
		/*LispUtils.*/ShowVersion(output);
		output->WriteLine("Type \"help\" for informations.");
		output->WriteLine();
	}

	std::shared_ptr<ILispDebugger> Fuel::TryGetDebugger()
	{
		std::shared_ptr<ILispDebugger> dbg = 0;

#if !defined(UNIT_TEST) && !defined(WITH_STATIC_DEBUGGER)
		typedef ILispDebugger * (*fcnGetDebugger)();

		if (g_hDebuggerDLL == 0)
		{
			g_hDebuggerDLL = SimpleLoadLibrary(FUEL_DEBUGGER_NAME);
		}
		if (g_hDebuggerDLL)
		{
			fcnGetDebugger pGetDebugger = (fcnGetDebugger)SimpleGetProcAddress(g_hDebuggerDLL, "create_debugger");
			if (pGetDebugger)
			{
				dbg = std::shared_ptr<ILispDebugger>((*pGetDebugger)());
			}
		}
#else
		dbg = std::shared_ptr<ILispDebugger>(create_debugger());
#endif

		return dbg;
	}
};

extern "C" int fuel_main(int argc, char *argv[])
{
	std::vector<CppLisp::string> args;
	for (int i = 1; i < argc; i++)
	{
		args.push_back(argv[i]);
	}
	CppLisp::Fuel::Main(args);

	return 0;
}
<commit_msg>Fixed for fuel application without shared libraries<commit_after>/*
* FUEL(isp) is a fast usable embeddable lisp interpreter.
*
* Copyright (c) 2016 Michael Neuroth
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* */

//using System;
//using System.IO;
//using System.Linq;
//using System.Reflection;

#include "fuel.h"

#ifdef _WIN32
#include <windows.h>
#define FUEL_DEBUGGER_NAME "FuelDebugger.dll"
#endif

#if defined( __linux__ ) || defined( __APPLE__ )
#include <dlfcn.h>			// fuer:
#endif

#if defined( __linux__ )
#define FUEL_DEBUGGER_NAME "libFuelDebugger.so"
#endif

#if defined( __APPLE__ )
#define FUEL_DEBUGGER_NAME "libFuelDebugger.dylib"
#endif

void * SimpleLoadLibrary(const char * sDllName)
{
#ifdef _WIN32
#ifdef UNICODE
	std::string s(sDllName);
	std::wstring stemp = std::wstring(s.begin(), s.end());
    return (void *)LoadLibrary( (LPCWSTR)stemp.c_str() );
#else
    return (void *)LoadLibrary( (LPCSTR)sDllName );
#endif
#endif
#if defined( __linux__ ) || defined( __APPLE__ )
    return (void *)dlopen( sDllName, RTLD_LAZY );
#endif
}

bool SimpleFreeLibrary(void * hDllModule)
{
#ifdef _WIN32
	return FreeLibrary((HMODULE)hDllModule) == TRUE;
#endif
#if defined( __linux__ ) || defined( __APPLE__ )
    return dlclose( (void *)hDllModule );
#endif
}

void * SimpleGetProcAddress(void * hDllModule, const char * sProcName)
{
#ifdef _WIN32
	return (void *)GetProcAddress((HMODULE)hDllModule, sProcName);
#endif
#if defined( __linux__ ) || defined( __APPLE__ )
	return (void *)dlsym( (void *)hDllModule, sProcName );
#endif
}

static void * g_hDebuggerDLL = 0;

#if !defined(UNIT_TEST) && !defined(WITH_STATIC_DEBUGGER)
extern "C" CppLisp::ILispDebugger * create_debugger();
#endif

static void DisconnectDebugger()
{
	if (g_hDebuggerDLL != 0)
	{
		SimpleFreeLibrary(g_hDebuggerDLL);
	}
}

namespace CppLisp
{
	extern string LispUtils_LibraryPath;

	uint64_t Environment_GetTickCount(void);

	bool Contains(const std::vector<string> & container, const string & search)
	{
		return std::find(container.begin(), container.end(), search) != container.end();
	}

	std::vector<string> GetScriptFilesFromProgramArgs(const std::vector<string> & args)
	{
		std::vector<string> result;
		std::copy_if(args.begin(), args.end(), back_inserter(result), [](const string & s) -> bool { return !s.StartsWith("-");  });
		return result;
	}

	void Fuel::Main(std::vector<string> args)
	{
		std::shared_ptr<TextWriter> writer = std::make_shared<TextWriter>();
		std::shared_ptr<TextReader> reader = std::make_shared<TextReader>();
		MainExtended(args, /*Console.Out, Console.In*/writer, reader);
	}

	void Fuel::MainExtended(std::vector<string> args, std::shared_ptr<TextWriter> output, std::shared_ptr<TextReader> input)
	{
		if (args.size() == 0)
		{
			Usage(output);
			return;
		}

		string script = /*null*/string::Empty;
		var loadFiles = true;
		var trace = false;
		var macroExpand = false;
		//var compile = false;
		var wasDebugging = false;
		//var showCompileOutput = false;
		var measureTime = false;
		var lengthyErrorOutput = false;
		var result = std::make_shared<LispVariant>();
		var startTickCount = /*Environment.TickCount*/Environment_GetTickCount();
		var debugger = TryGetDebugger();

		if (Contains(args, "-m"))
		{
			measureTime = true;
		}
		if (Contains(args, "-v"))
		{
			output->WriteLine(Lisp::ProgramName + " " + Lisp::Version + " from " + Lisp::Date);
			return;
		}
		if (Contains(args, "-h"))
		{
			Usage(output);
			return;
		}
		if (Contains(args, "--doc"))
		{
			script = "(println (doc))";
			loadFiles = false;
		}
		if (Contains(args, "--html"))
		{
			script = "(println (htmldoc))";
			loadFiles = false;
		}
		if (Contains(args, "--macro-expand"))
		{
			macroExpand = true;
		}
		if (Contains(args, "-x"))
		{
			lengthyErrorOutput = true;
		}
		if (Contains(args, "-t"))
		{
			trace = true;
		}
		if (Contains(args, "-e"))
		{
			script = /*LispUtils.*/GetScriptFilesFromProgramArgs(args)[0]/*.FirstOrDefault()*/;
			loadFiles = false;
		}
		//org: var libPath = args.Where(v = > v.StartsWith("-l=")).Select(v = > v).ToArray();
		var libPath = std::vector<string>(std::find_if(args.begin(), args.end(), [](const string & v) -> bool { return v.StartsWith("-l="); }), args.end());
		if (libPath.size() > 0)
		{
			string libraryPath = libPath.front().Substring(3);
			LispUtils_LibraryPath = libraryPath;
		}

		// handle options for compiler
		//if (Contains(args, "-c"))
		//{
		//	compile = true;
		//}
		//if (Contains(args, "-s"))
		//{
		//	showCompileOutput = true;
		//}

		// handle options for debugger
		if (debugger != null)
		{
			debugger->SetInputOutputStreams(output, input);
			if (Contains(args, "-i"))
			{
				InteractiveLoopHeader(output);
				debugger->InteractiveLoop(null, null, /*startedFromMain:*/ true, /*tracing :*/ trace, output, input);
				loadFiles = false;
				wasDebugging = true;
			}
			if (Contains(args, "-d"))
			{
				//var fileName = /*LispUtils.*/GetScriptFilesFromProgramArgs(args)./*FirstOrDefault()*/front();
				var scriptFiles = GetScriptFilesFromProgramArgs(args);
				var fileName = scriptFiles.size() > 0 ? scriptFiles.front() : string::Empty;
				// process -e option if script is given via command line
				if (string::IsNullOrEmpty(script))
				{
					script = /*LispUtils.*/ReadFileOrEmptyString(fileName);
				}
				else
				{
					fileName = "command-line";
				}

				InteractiveLoopHeader(output);
				result = debugger->DebuggerLoop(script, fileName, /*tracing:*/ trace);
				loadFiles = false;
				wasDebugging = true;
			}
		}

		if (loadFiles)
		{
			var scriptFiles = /*LispUtils.*/GetScriptFilesFromProgramArgs(args);

			for (var fileName : scriptFiles)
			{
				script = /*LispUtils.*/ReadFileOrEmptyString(fileName);
				//ILispCompiler compiler = TryGetCompiler();
				//if (compile && compiler != null)
				//{
				//	result = compiler.CompileToExe(script, fileName + ".exe");
				//}
				//else if (showCompileOutput && compiler != null)
				//{
				//	result = compiler.CompileToCsCode(script);
				//	output->WriteLine(result.StringValue);
				//}
				//else
				{
					result = Lisp::SaveEval(script, /*moduleName:*/ fileName, /*verboseErrorOutput:*/ lengthyErrorOutput, /*tracing:*/ trace, output, input, macroExpand);
				}
			}
		}
		else if (!string::IsNullOrEmpty(script) && !wasDebugging)
		{
			// process -e option
			result = Lisp::SaveEval(script, /*moduleName:*/ "cmdline", /*verboseErrorOutput:*/ false, /*tracing:*/ false, output, input, macroExpand);
		}

		if (macroExpand)
		{
			output->WriteLine(string("Macro expand: ") + result->ToString());
		}
		if (trace)
		{
			output->WriteLine(string("Result=") + result->ToString());
		}
		if (measureTime)
		{
			output->WriteLine("Execution time = {0} s", std::to_string((/*Environment.TickCount*/Environment_GetTickCount() - startTickCount) * 0.001));
		}

		DisconnectDebugger();
	}

	void Fuel::Usage(std::shared_ptr<TextWriter> output)
	{
		/*LispUtils.*/ShowAbout(output);
		output->WriteLine("usage:");
		output->WriteLine(">" + Lisp::ProgramName + " [options] [script_file_name]");
		output->WriteLine();
		output->WriteLine("options:");
		output->WriteLine("  -v          : show version");
		output->WriteLine("  -h          : show help");
		output->WriteLine("  -e \"script\" : execute given script");
		output->WriteLine("  -l=\"path\"   : path to library");
		output->WriteLine("  --doc       : show language documentation");
		output->WriteLine("  --html      : show language documentation in html");
		output->WriteLine("  --macro-expand : expand all macros and show resulting code");
		output->WriteLine("  -m          : measure execution time");
		output->WriteLine("  -t          : enable tracing");
		output->WriteLine("  -x          : exhaustive error output");
		if (TryGetDebugger() != null)
		{
			output->WriteLine("  -i          : interactive shell");
			output->WriteLine("  -d          : start debugger");
		}
		else
		{
			output->WriteLine();
			output->WriteLine("Info: no debugger support installed !");
		}
		//if (TryGetCompiler() != null)
		//{
		//	output->WriteLine("  -c          : compile program");
		//	output->WriteLine("  -s          : show C# compiler output");
		//}
		//else
		//{
		//	output->WriteLine();
		//	output->WriteLine("Info: no compiler support installed !");
		//}
		output->WriteLine();
	}

	void Fuel::InteractiveLoopHeader(std::shared_ptr<TextWriter> output)
	{
		/*LispUtils.*/ShowVersion(output);
		output->WriteLine("Type \"help\" for informations.");
		output->WriteLine();
	}

	std::shared_ptr<ILispDebugger> Fuel::TryGetDebugger()
	{
		std::shared_ptr<ILispDebugger> dbg = 0;

#if !defined(UNIT_TEST) && !defined(WITH_STATIC_DEBUGGER)
		typedef ILispDebugger * (*fcnGetDebugger)();

		if (g_hDebuggerDLL == 0)
		{
			g_hDebuggerDLL = SimpleLoadLibrary(FUEL_DEBUGGER_NAME);
		}
		if (g_hDebuggerDLL)
		{
			fcnGetDebugger pGetDebugger = (fcnGetDebugger)SimpleGetProcAddress(g_hDebuggerDLL, "create_debugger");
			if (pGetDebugger)
			{
				dbg = std::shared_ptr<ILispDebugger>((*pGetDebugger)());
			}
		}
#else
		dbg = std::shared_ptr<ILispDebugger>(create_debugger());
#endif

		return dbg;
	}
};

extern "C" int fuel_main(int argc, char *argv[])
{
	std::vector<CppLisp::string> args;
	for (int i = 1; i < argc; i++)
	{
		args.push_back(argv[i]);
	}
	CppLisp::Fuel::Main(args);

	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "thread.h"
#include <atomic>
#include <thread>
#include <unistd.h>

namespace {
#ifdef __linux__
   std::atomic_size_t _G_nextCpuId(0);
#endif
   volatile size_t _G_maxNumCpus=0;  // Non zero means use cpu pinning.
}

bool FastOS_UNIX_Thread::InitializeClass ()
{
    if (getenv("VESPA_PIN_THREAD_TO_CORE") != nullptr) {
        _G_maxNumCpus = std::thread::hardware_concurrency();
        fprintf(stderr, "Will pin threads to CPU. Using %ld cores\n", _G_maxNumCpus);
        if (getenv("VESPA_MAX_CORES") != nullptr) {
            size_t maxCores = strtoul(getenv("VESPA_MAX_CORES"), nullptr, 0);
            fprintf(stderr, "Will limit to %ld", maxCores);
            if (maxCores < _G_maxNumCpus) {
                _G_maxNumCpus = maxCores;
            }
        }
    }
    return true;
}

bool FastOS_UNIX_Thread::CleanupClass ()
{
    return true;
}

bool FastOS_UNIX_Thread::Initialize (int stackSize, int stackGuardSize)
{
    bool rc=false;

    pthread_attr_t attr;
    pthread_attr_init(&attr);

    pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

    pthread_attr_setstacksize(&attr, stackSize);
#ifdef __linux__
    if (_G_maxNumCpus > 0) {
        int cpuid = _G_nextCpuId.fetch_add(1)%_G_maxNumCpus;
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);
        CPU_SET(cpuid, &cpuset);
        int retval = pthread_attr_setaffinity_np(&attr, sizeof(cpuset), &cpuset);
        if (retval != 0) {
            fprintf(stderr, "Pinning FAILURE retval = %d, errno=%d sizeof(cpuset_t)=%ld cpuid(%d)\n", retval, errno, sizeof(cpuset), cpuid);
        }
    }
#endif

    if (stackGuardSize != 0) {
        pthread_attr_setguardsize(&attr, stackGuardSize);
    }

    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    rc = (0 == pthread_create(&_handle, &attr, FastOS_ThreadHook, this));
    if (rc)
        _handleValid = true;

    pthread_attr_destroy(&attr);

    return rc;
}

void FastOS_UNIX_Thread::PreEntry ()
{
}

FastOS_UNIX_Thread::~FastOS_UNIX_Thread()
{
    void *value;

    // Wait for thread library cleanup to complete.
    if (_handleValid) {
        value = nullptr;
        pthread_join(_handle, &value);
    }
}

FastOS_ThreadId FastOS_UNIX_Thread::GetThreadId ()
{
    return _handle;
}

FastOS_ThreadId FastOS_UNIX_Thread::GetCurrentThreadId ()
{
    return pthread_self();
}

bool FastOS_UNIX_Thread::CompareThreadIds (FastOS_ThreadId a, FastOS_ThreadId b)
{
    return (pthread_equal(a, b) != 0);
}
<commit_msg>adjust stack size by adding system minimum size<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "thread.h"
#include <atomic>
#include <thread>
#include <unistd.h>

#ifdef __linux__
extern "C" { size_t __pthread_get_minstack(const pthread_attr_t *); }
#endif

namespace {
#ifdef __linux__
   std::atomic_size_t _G_nextCpuId(0);
#endif
   volatile size_t _G_maxNumCpus=0;  // Non zero means use cpu pinning.
}

bool FastOS_UNIX_Thread::InitializeClass ()
{
    if (getenv("VESPA_PIN_THREAD_TO_CORE") != nullptr) {
        _G_maxNumCpus = std::thread::hardware_concurrency();
        fprintf(stderr, "Will pin threads to CPU. Using %ld cores\n", _G_maxNumCpus);
        if (getenv("VESPA_MAX_CORES") != nullptr) {
            size_t maxCores = strtoul(getenv("VESPA_MAX_CORES"), nullptr, 0);
            fprintf(stderr, "Will limit to %ld", maxCores);
            if (maxCores < _G_maxNumCpus) {
                _G_maxNumCpus = maxCores;
            }
        }
    }
    return true;
}

bool FastOS_UNIX_Thread::CleanupClass ()
{
    return true;
}

bool FastOS_UNIX_Thread::Initialize (int stackSize, int stackGuardSize)
{
    bool rc=false;

    pthread_attr_t attr;
    pthread_attr_init(&attr);

    pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
#ifdef __linux__
    if (_G_maxNumCpus > 0) {
        int cpuid = _G_nextCpuId.fetch_add(1)%_G_maxNumCpus;
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);
        CPU_SET(cpuid, &cpuset);
        int retval = pthread_attr_setaffinity_np(&attr, sizeof(cpuset), &cpuset);
        if (retval != 0) {
            fprintf(stderr, "Pinning FAILURE retval = %d, errno=%d sizeof(cpuset_t)=%ld cpuid(%d)\n", retval, errno, sizeof(cpuset), cpuid);
        }
    }
#endif

    if (stackGuardSize != 0) {
        pthread_attr_setguardsize(&attr, stackGuardSize);
    }

    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    size_t adjusted_stack_size = stackSize;
#ifdef __linux__
    ssize_t stack_needed_by_system = __pthread_get_minstack(&attr);
    adjusted_stack_size += stack_needed_by_system;
#endif
    pthread_attr_setstacksize(&attr, adjusted_stack_size);

    rc = (0 == pthread_create(&_handle, &attr, FastOS_ThreadHook, this));
    if (rc)
        _handleValid = true;

    pthread_attr_destroy(&attr);

    return rc;
}

void FastOS_UNIX_Thread::PreEntry ()
{
}

FastOS_UNIX_Thread::~FastOS_UNIX_Thread()
{
    void *value;

    // Wait for thread library cleanup to complete.
    if (_handleValid) {
        value = nullptr;
        pthread_join(_handle, &value);
    }
}

FastOS_ThreadId FastOS_UNIX_Thread::GetThreadId ()
{
    return _handle;
}

FastOS_ThreadId FastOS_UNIX_Thread::GetCurrentThreadId ()
{
    return pthread_self();
}

bool FastOS_UNIX_Thread::CompareThreadIds (FastOS_ThreadId a, FastOS_ThreadId b)
{
    return (pthread_equal(a, b) != 0);
}
<|endoftext|>