<commit_before>#include <itkMesh.h>
#include <itkTransformMeshFilter.h>
#include <itkLBFGSOptimizer.h>

#include "itkGMMPointSetToPointSetRegistrationMethod.h"
#include "itkPointSetPropertiesCalculator.h"
#include "itkInitializeTransform.h"
#include "itkInitializeMetric.h"
#include "itkPointSetToPointSetMetrics.h"

#include "itkIOutils.h"
#include "argsCustomParsers.h"

const unsigned int Dimension = 3;
typedef itk::Mesh<float, Dimension> MeshType;
typedef itk::PointSet<MeshType::PixelType, MeshType::PointDimension> PointSetType;
typedef itk::Transform <double, MeshType::PointDimension, MeshType::PointDimension> TransformType;

int main(int argc, char** argv) {

  // parse input arguments
  args::ArgumentParser parser("GMM-based point set to point set registration.", "");
  args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"});

  args::Group allRequired(parser, "Required arguments:", args::Group::Validators::All);

  args::ValueFlag<std::string> argFixedFileName(allRequired, "fixed", "The fixed mesh (point-set) filename", {'f', "fixed"});
  args::ValueFlag<std::string> argMovingFileName(allRequired, "moving", "The moving mesh (point-set) filename", {'m', "moving"});
  args::ValueFlag<std::string> argOutputFileName(parser, "output", "The output mesh (point-set) filename", {'o', "output"});

  args::ValueFlag<std::vector<double>, args::DoubleVectorReader> argScale(allRequired, "scale", "The scale levels", {"scale"});
  args::ValueFlag<size_t> argNumberOfIterations(parser, "iterations", "The number of iterations", {"iterations"}, 1000);
  args::Flag trace(parser, "trace", "Optimizer iterations tracing", {"trace"});

  const std::string transformDescription =
    "The type of transform (That is number):\n"
    "  0 : Translation\n"
    "  1 : Versor3D\n"
    "  2 : Similarity\n"
    "  3 : ScaleSkewVersor3D\n";

  args::ValueFlag<size_t> argTypeOfTransform(parser, "transform", transformDescription, {'t', "transform"}, 0);

  const std::string metricDescription =
    "The type of metric (That is number):\n"
    "  0 : L2Rigid\n"
    "  1 : L2\n"
    "  2 : KC\n";

  args::ValueFlag<size_t> argTypeOfMetric(parser, "metric", metricDescription, {'M', "metric"}, 0);

  try {
    parser.ParseCLI(argc, argv);
  }
  catch (args::Help) {
    std::cout << parser;
    return EXIT_SUCCESS;
  }
  catch (args::ParseError e) {
    std::cerr << e.what() << std::endl;
    std::cerr << parser;
    return EXIT_FAILURE;
  }
  catch (args::ValidationError e) {
    std::cerr << e.what() << std::endl;
    std::cerr << parser;
    return EXIT_FAILURE;
  }

  std::string fixedFileName = args::get(argFixedFileName);
  std::string movingFileName = args::get(argMovingFileName);
  size_t numberOfIterations = args::get(argNumberOfIterations);
  size_t typeOfTransform = args::get(argTypeOfTransform);
  size_t typeOfMetric = args::get(argTypeOfMetric);

  std::cout << "options" << std::endl;
  std::cout << "number of iterations " << numberOfIterations << std::endl;
  std::cout << std::endl;

  //--------------------------------------------------------------------
  // read meshes
  MeshType::Pointer fixedMesh = MeshType::New();
  if (!readMesh<MeshType>(fixedMesh, fixedFileName)) {
    return EXIT_FAILURE;
  }

  std::cout << fixedFileName << std::endl;
  std::cout << "number of points " << fixedMesh->GetNumberOfPoints() << std::endl;
  std::cout << std::endl;

  MeshType::Pointer movingMesh = MeshType::New();
  if (!readMesh<MeshType>(movingMesh, movingFileName)) {
    return EXIT_FAILURE;
  }

  std::cout << movingFileName << std::endl;
  std::cout << "number of points " << movingMesh->GetNumberOfPoints() << std::endl;
  std::cout << std::endl;

  PointSetType::Pointer fixedPointSet = PointSetType::New();
  fixedPointSet->SetPoints(fixedMesh->GetPoints());

  PointSetType::Pointer movingPointSet = PointSetType::New();
  movingPointSet->SetPoints(movingMesh->GetPoints());

  //--------------------------------------------------------------------
  // initialize scales
  typedef itk::PointSetPropertiesCalculator<PointSetType> PointSetPropertiesCalculatorType;
  PointSetPropertiesCalculatorType::Pointer fixedPointSetCalculator = PointSetPropertiesCalculatorType::New();
  fixedPointSetCalculator->SetPointSet(fixedPointSet);
  fixedPointSetCalculator->Compute();
  fixedPointSetCalculator->PrintReport(std::cout);

  PointSetPropertiesCalculatorType::Pointer movingPointSetCalculator = PointSetPropertiesCalculatorType::New();
  movingPointSetCalculator->SetPointSet(movingPointSet);
  movingPointSetCalculator->Compute();
  movingPointSetCalculator->PrintReport(std::cout);

  itk::Array<double> scale(args::get(argScale).size());
  for (size_t n = 0; n < scale.size(); ++n) {
    scale[n] = args::get(argScale)[n] * movingPointSetCalculator->GetScale();
  }

  // initialize transform
  typedef itk::VersorRigid3DTransform<double> InitialTransformType;
  InitialTransformType::Pointer fixedInitialTransform = InitialTransformType::New();
  fixedInitialTransform->SetCenter(fixedPointSetCalculator->GetCenter());
  fixedInitialTransform->SetIdentity();

  InitialTransformType::Pointer movingInitialTransform = InitialTransformType::New();
  movingInitialTransform->SetCenter(movingPointSetCalculator->GetCenter());
  movingInitialTransform->SetIdentity();

  typedef itk::InitializeTransform<double> TransformInitializerType;
  TransformInitializerType::Pointer transformInitializer = TransformInitializerType::New();
  transformInitializer->SetMovingLandmark(movingPointSetCalculator->GetCenter());
  transformInitializer->SetFixedLandmark(fixedPointSetCalculator->GetCenter());
  transformInitializer->SetTypeOfTransform(typeOfTransform);
  transformInitializer->Update();
  TransformType::Pointer transform = transformInitializer->GetTransform();

  //--------------------------------------------------------------------
  // initialize optimizer
  typedef itk::LBFGSOptimizer OptimizerType;
  OptimizerType::Pointer optimizer = OptimizerType::New();
  optimizer->SetMaximumNumberOfFunctionEvaluations(numberOfIterations);
  optimizer->SetScales(transformInitializer->GetScales());
  optimizer->SetTrace(trace);
  optimizer->MinimizeOn();

  //--------------------------------------------------------------------
  // metric
  typedef itk::InitializeMetric<PointSetType, PointSetType> InitializeMetricType;
  InitializeMetricType::Pointer metricInitializer = InitializeMetricType::New();
  metricInitializer->SetTypeOfMetric(typeOfMetric);
  try {
    metricInitializer->Initialize();
  }
  catch (itk::ExceptionObject& excep) {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
  }

  //--------------------------------------------------------------------
  // perform registration
  typedef itk::GMMPointSetToPointSetRegistrationMethod<PointSetType, PointSetType> GMMPointSetToPointSetRegistrationMethodType;
  GMMPointSetToPointSetRegistrationMethodType::Pointer registration = GMMPointSetToPointSetRegistrationMethodType::New();
  registration->SetFixedPointSet(fixedPointSet);
  registration->SetFixedInitialTransform(fixedInitialTransform);
  registration->SetMovingPointSet(movingPointSet);
  registration->SetMovingInitialTransform(movingInitialTransform);
  registration->SetScale(scale);
  registration->SetOptimizer(optimizer);
  registration->SetMetric(metricInitializer->GetMetric());
  registration->SetTransform(transform);
  try {
    registration->Update();
  }
  catch (itk::ExceptionObject& excep) {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << std::endl;
  std::cout << "optimizer " << registration->GetOptimizer()->GetNameOfClass() << std::endl;
  std::cout << "   scales " << registration->GetOptimizer()->GetScales() << std::endl;
  std::cout << std::endl;
  std::cout << "transform " << registration->GetTransform()->GetNameOfClass() << std::endl;
  std::cout << "Initial transform parameters " << registration->GetInitialTransformParameters() << std::endl;
  std::cout << "  Final transform parameters " << registration->GetFinalTransformParameters() << std::endl;
  std::cout << std::endl;
  std::cout << "metric " << registration->GetMetric()->GetNameOfClass() << std::endl;
  std::cout << "   Initial metric parameters " << registration->GetInitialMetricValues() << std::endl;
  std::cout << "     Final metric parameters " << registration->GetFinalMetricValues() << std::endl;
  std::cout << std::endl;

  // transform moving mesh
  typedef itk::TransformMeshFilter<MeshType, MeshType, TransformType> TransformMeshFilterType;
  TransformMeshFilterType::Pointer transformMesh = TransformMeshFilterType::New();
  transformMesh->SetInput(movingMesh);
  transformMesh->SetTransform(transform);
  try {
    transformMesh->Update();
  }
  catch (itk::ExceptionObject& excep) {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
  }

  if (argOutputFileName) {
    std::string fileName = args::get(argOutputFileName);
    std::cout << "write output mesh to the file " << fileName << std::endl;
    std::cout << std::endl;

    if (!writeMesh<MeshType>(transformMesh->GetOutput(), fileName)) {
      return EXIT_FAILURE;
    }
  }

  PointSetType::Pointer outputPointSet = transformMesh->GetOutput();

  // compute metrics
  typedef itk::PointSetToPointSetMetrics<PointSetType> PointSetToPointSetMetricsType;
  PointSetToPointSetMetricsType::Pointer metrics = PointSetToPointSetMetricsType::New();
  metrics->SetFixedPointSet(fixedPointSet);
  metrics->SetMovingPointSet(movingPointSet);
  metrics->Compute();
  metrics->PrintReport(std::cout);

  metrics->SetFixedPointSet(fixedPointSet);
  metrics->SetMovingPointSet(outputPointSet);
  metrics->Compute();
  metrics->PrintReport(std::cout);

  return EXIT_SUCCESS;
}
<commit_msg>refactoring<commit_after>#include <itkMesh.h>
#include <itkTransformMeshFilter.h>
#include <itkLBFGSOptimizer.h>

#include "itkGMMPointSetToPointSetRegistrationMethod.h"
#include "itkPointSetPropertiesCalculator.h"
#include "itkInitializeTransform.h"
#include "itkInitializeMetric.h"
#include "itkPointSetToPointSetMetrics.h"

#include "itkIOutils.h"
#include "argsCustomParsers.h"

const unsigned int Dimension = 3;
typedef itk::Mesh<float, Dimension> MeshType;
typedef itk::PointSet<MeshType::PixelType, MeshType::PointDimension> PointSetType;
typedef itk::Transform <double, MeshType::PointDimension, MeshType::PointDimension> TransformType;

int main(int argc, char** argv) {

  // parse input arguments
  args::ArgumentParser parser("GMM-based point set to point set registration.", "");
  args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"});

  args::Group allRequired(parser, "Required arguments:", args::Group::Validators::All);

  args::ValueFlag<std::string> argFixedFileName(allRequired, "fixed", "The fixed mesh (point-set) filename", {'f', "fixed"});
  args::ValueFlag<std::string> argMovingFileName(allRequired, "moving", "The moving mesh (point-set) filename", {'m', "moving"});
  args::ValueFlag<std::string> argOutputFileName(parser, "output", "The output mesh (point-set) filename", {'o', "output"});

  args::ValueFlag<std::vector<double>, args::DoubleVectorReader> argScale(allRequired, "scale", "The scale levels", {"scale"});
  args::ValueFlag<size_t> argNumberOfIterations(parser, "iterations", "The number of iterations", {"iterations"}, 1000);
  args::Flag trace(parser, "trace", "Optimizer iterations tracing", {"trace"});

  const std::string transformDescription =
    "The type of transform (That is number):\n"
    "  0 : Translation\n"
    "  1 : Versor3D\n"
    "  2 : Similarity\n"
    "  3 : ScaleSkewVersor3D\n";

  args::ValueFlag<size_t> argTypeOfTransform(parser, "transform", transformDescription, {'t', "transform"}, 0);

  const std::string metricDescription =
    "The type of metric (That is number):\n"
    "  0 : L2Rigid\n"
    "  1 : L2\n"
    "  2 : KC\n";

  args::ValueFlag<size_t> argTypeOfMetric(parser, "metric", metricDescription, {'M', "metric"}, 0);

  try {
    parser.ParseCLI(argc, argv);
  }
  catch (args::Help) {
    std::cout << parser;
    return EXIT_SUCCESS;
  }
  catch (args::ParseError e) {
    std::cerr << e.what() << std::endl;
    std::cerr << parser;
    return EXIT_FAILURE;
  }
  catch (args::ValidationError e) {
    std::cerr << e.what() << std::endl;
    std::cerr << parser;
    return EXIT_FAILURE;
  }

  std::string fixedFileName = args::get(argFixedFileName);
  std::string movingFileName = args::get(argMovingFileName);
  size_t numberOfIterations = args::get(argNumberOfIterations);
  size_t typeOfTransform = args::get(argTypeOfTransform);
  size_t typeOfMetric = args::get(argTypeOfMetric);

  std::cout << "options" << std::endl;
  std::cout << "number of iterations " << numberOfIterations << std::endl;
  std::cout << std::endl;

  //--------------------------------------------------------------------
  // read meshes
  MeshType::Pointer fixedMesh = MeshType::New();
  if (!readMesh<MeshType>(fixedMesh, fixedFileName)) {
    return EXIT_FAILURE;
  }

  std::cout << fixedFileName << std::endl;
  std::cout << "number of points " << fixedMesh->GetNumberOfPoints() << std::endl;
  std::cout << std::endl;

  MeshType::Pointer movingMesh = MeshType::New();
  if (!readMesh<MeshType>(movingMesh, movingFileName)) {
    return EXIT_FAILURE;
  }

  std::cout << movingFileName << std::endl;
  std::cout << "number of points " << movingMesh->GetNumberOfPoints() << std::endl;
  std::cout << std::endl;

  PointSetType::Pointer fixedPointSet = PointSetType::New();
  fixedPointSet->SetPoints(fixedMesh->GetPoints());

  PointSetType::Pointer movingPointSet = PointSetType::New();
  movingPointSet->SetPoints(movingMesh->GetPoints());

  //--------------------------------------------------------------------
  // initialize scales
  typedef itk::PointSetPropertiesCalculator<PointSetType> PointSetPropertiesCalculatorType;
  PointSetPropertiesCalculatorType::Pointer fixedPointSetCalculator = PointSetPropertiesCalculatorType::New();
  fixedPointSetCalculator->SetPointSet(fixedPointSet);
  fixedPointSetCalculator->Compute();
  fixedPointSetCalculator->PrintReport(std::cout);

  PointSetPropertiesCalculatorType::Pointer movingPointSetCalculator = PointSetPropertiesCalculatorType::New();
  movingPointSetCalculator->SetPointSet(movingPointSet);
  movingPointSetCalculator->Compute();
  movingPointSetCalculator->PrintReport(std::cout);

  itk::Array<double> scale(args::get(argScale).size());
  for (size_t n = 0; n < scale.size(); ++n) {
    scale[n] = args::get(argScale)[n] * movingPointSetCalculator->GetScale();
  }

  // initialize transform
  typedef itk::VersorRigid3DTransform<double> InitialTransformType;
  InitialTransformType::Pointer fixedInitialTransform = InitialTransformType::New();
  fixedInitialTransform->SetCenter(fixedPointSetCalculator->GetCenter());
  fixedInitialTransform->SetIdentity();

  InitialTransformType::Pointer movingInitialTransform = InitialTransformType::New();
  movingInitialTransform->SetCenter(movingPointSetCalculator->GetCenter());
  movingInitialTransform->SetIdentity();

  typedef itk::InitializeTransform<double> TransformInitializerType;
  TransformInitializerType::Pointer transformInitializer = TransformInitializerType::New();
  transformInitializer->SetMovingLandmark(movingPointSetCalculator->GetCenter());
  transformInitializer->SetFixedLandmark(fixedPointSetCalculator->GetCenter());
  transformInitializer->SetTypeOfTransform(typeOfTransform);
  transformInitializer->Update();
  TransformType::Pointer transform = transformInitializer->GetTransform();

  //--------------------------------------------------------------------
  // initialize optimizer
  typedef itk::LBFGSOptimizer OptimizerType;
  OptimizerType::Pointer optimizer = OptimizerType::New();
  optimizer->SetMaximumNumberOfFunctionEvaluations(numberOfIterations);
  optimizer->SetScales(transformInitializer->GetScales());
  optimizer->SetTrace(trace);
  optimizer->MinimizeOn();

  //--------------------------------------------------------------------
  // metric
  typedef itk::InitializeMetric<PointSetType, PointSetType> InitializeMetricType;
  InitializeMetricType::Pointer metricInitializer = InitializeMetricType::New();
  metricInitializer->SetTypeOfMetric(typeOfMetric);
  try {
    metricInitializer->Initialize();
  }
  catch (itk::ExceptionObject& excep) {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
  }

  //--------------------------------------------------------------------
  // perform registration
  typedef itk::GMMPointSetToPointSetRegistrationMethod<PointSetType, PointSetType> GMMPointSetToPointSetRegistrationMethodType;
  GMMPointSetToPointSetRegistrationMethodType::Pointer registration = GMMPointSetToPointSetRegistrationMethodType::New();
  registration->SetFixedPointSet(fixedPointSet);
  registration->SetFixedInitialTransform(fixedInitialTransform);
  registration->SetMovingPointSet(movingPointSet);
  registration->SetMovingInitialTransform(movingInitialTransform);
  registration->SetScale(scale);
  registration->SetOptimizer(optimizer);
  registration->SetMetric(metricInitializer->GetMetric());
  registration->SetTransform(transform);
  try {
    registration->Update();
  }
  catch (itk::ExceptionObject& excep) {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << std::endl;
  std::cout << "optimizer " << registration->GetOptimizer()->GetNameOfClass() << std::endl;
  std::cout << "   scales " << registration->GetOptimizer()->GetScales() << std::endl;
  std::cout << std::endl;
  std::cout << "transform " << registration->GetTransform()->GetNameOfClass() << std::endl;
  std::cout << "Initial transform parameters " << registration->GetInitialTransformParameters() << std::endl;
  std::cout << "  Final transform parameters " << registration->GetFinalTransformParameters() << std::endl;
  std::cout << std::endl;
  std::cout << "metric " << registration->GetMetric()->GetNameOfClass() << std::endl;
  std::cout << "   Initial metric values " << registration->GetInitialMetricValues() << std::endl;
  std::cout << "     Final metric values " << registration->GetFinalMetricValues() << std::endl;
  std::cout << std::endl;

  // transform moving mesh
  typedef itk::TransformMeshFilter<MeshType, MeshType, TransformType> TransformMeshFilterType;
  TransformMeshFilterType::Pointer transformMesh = TransformMeshFilterType::New();
  transformMesh->SetInput(movingMesh);
  transformMesh->SetTransform(transform);
  try {
    transformMesh->Update();
  }
  catch (itk::ExceptionObject& excep) {
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
  }

  if (argOutputFileName) {
    std::string fileName = args::get(argOutputFileName);
    std::cout << "write output mesh to the file " << fileName << std::endl;
    std::cout << std::endl;

    if (!writeMesh<MeshType>(transformMesh->GetOutput(), fileName)) {
      return EXIT_FAILURE;
    }
  }

  PointSetType::Pointer outputPointSet = transformMesh->GetOutput();

  // compute metrics
  typedef itk::PointSetToPointSetMetrics<PointSetType> PointSetToPointSetMetricsType;
  PointSetToPointSetMetricsType::Pointer metrics = PointSetToPointSetMetricsType::New();
  metrics->SetFixedPointSet(fixedPointSet);
  metrics->SetMovingPointSet(movingPointSet);
  metrics->Compute();
  metrics->PrintReport(std::cout);

  metrics->SetFixedPointSet(fixedPointSet);
  metrics->SetMovingPointSet(outputPointSet);
  metrics->Compute();
  metrics->PrintReport(std::cout);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "SphereMeshGenerator.h"
#include "CastUniquePointer.h"

// libMesh includes
#include "libmesh/mesh_generation.h"

registerMooseObject("MooseApp", SphereMeshGenerator);

InputParameters
SphereMeshGenerator::validParams()
{
  InputParameters params = MeshGenerator::validParams();
  params.addClassDescription("Generate a 3-D sphere mesh centered on the origin");
  params.addRequiredRangeCheckedParam<Real>("radius", "radius > 0.0", "Sphere radius");
  params.addRequiredRangeCheckedParam<unsigned int>("nr", "nr > 0", "Number of radial elements");

  MooseEnum types("HEX8 HEX27", "HEX8");
  params.addParam<MooseEnum>("elem_type", types, "The type of element to generate");
  params.addParam<unsigned int>("n_smooth", 0, "Number of smoothing operations");
  return params;
}

SphereMeshGenerator::SphereMeshGenerator(const InputParameters & parameters)
  : MeshGenerator(parameters),
    _radius(getParam<Real>("radius")),
    _nr(getParam<unsigned int>("nr")),
    _elem_type(getParam<MooseEnum>("elem_type")),
    _n_smooth(getParam<unsigned int>("n_smooth"))
{
}

std::unique_ptr<MeshBase>
SphereMeshGenerator::generate()
{
  auto mesh = buildMeshBaseObject();
  mesh->set_mesh_dimension(3);
  mesh->set_spatial_dimension(3);

  ElemType et = Utility::string_to_enum<ElemType>(_elem_type);

  MeshTools::Generation::build_sphere(static_cast<UnstructuredMesh &>(*mesh),
                                      _radius,
                                      _nr,
                                      et,
                                      _n_smooth,
                                      false /* dummy value; not used for 3-D meshes */);

  return dynamic_pointer_cast<MeshBase>(mesh);
}
<commit_msg>Add missing header file. Refs #22591<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "SphereMeshGenerator.h"
#include "CastUniquePointer.h"

#include "libmesh/mesh_generation.h"
#include "libmesh/string_to_enum.h"

registerMooseObject("MooseApp", SphereMeshGenerator);

InputParameters
SphereMeshGenerator::validParams()
{
  InputParameters params = MeshGenerator::validParams();
  params.addClassDescription("Generate a 3-D sphere mesh centered on the origin");
  params.addRequiredRangeCheckedParam<Real>("radius", "radius > 0.0", "Sphere radius");
  params.addRequiredRangeCheckedParam<unsigned int>("nr", "nr > 0", "Number of radial elements");

  MooseEnum types("HEX8 HEX27", "HEX8");
  params.addParam<MooseEnum>("elem_type", types, "The type of element to generate");
  params.addParam<unsigned int>("n_smooth", 0, "Number of smoothing operations");
  return params;
}

SphereMeshGenerator::SphereMeshGenerator(const InputParameters & parameters)
  : MeshGenerator(parameters),
    _radius(getParam<Real>("radius")),
    _nr(getParam<unsigned int>("nr")),
    _elem_type(getParam<MooseEnum>("elem_type")),
    _n_smooth(getParam<unsigned int>("n_smooth"))
{
}

std::unique_ptr<MeshBase>
SphereMeshGenerator::generate()
{
  auto mesh = buildMeshBaseObject();
  mesh->set_mesh_dimension(3);
  mesh->set_spatial_dimension(3);

  ElemType et = Utility::string_to_enum<ElemType>(_elem_type);

  MeshTools::Generation::build_sphere(static_cast<UnstructuredMesh &>(*mesh),
                                      _radius,
                                      _nr,
                                      et,
                                      _n_smooth,
                                      false /* dummy value; not used for 3-D meshes */);

  return dynamic_pointer_cast<MeshBase>(mesh);
}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include "../dbmanager.h"
#include "../iconmanager.h"
#include "tablewidget.h"

TableWidget::TableWidget(QWidget *parent)
  : AbstractTabWidget(parent)
{
  setupUi(this);

  setupWidgets();

  model = new QSqlTableModel(this);
}

TableWidget::TableWidget(QString table, QSqlDatabase *db, QWidget *parent)
  : AbstractTabWidget(parent)
{
  setupUi(this);
  setupWidgets();
  setTable(table, db);
}

QIcon TableWidget::icon()
{
  return IconManager::get("table");
}

QString TableWidget::id()
{
  return QString("t %1 on %2")
      .arg(m_table)
      .arg(m_db->databaseName());
}

void TableWidget::refresh()
{
  if(!m_db->isOpen())
    emit closeRequested();
}

void TableWidget::reload() {
  if(!m_db->isOpen())
    return;

  if(!m_db->tables(QSql::Tables).contains(m_table)
    && !m_db->tables(QSql::Views).contains(m_table)
    && !m_db->tables(QSql::SystemTables).contains(m_table))   {
    QMessageBox::critical(this,
                          tr("Error"),
                          tr("Unable to open the table %1. ").append(
                            tr("Check you have the necessary permissions."))
                          .arg(m_table));
    emit closeRequested();
    return;
  }

  if (!tableView->setTable(m_table, m_db)) {
    emit closeRequested();
  }
}

void TableWidget::setTable( QString table, QSqlDatabase *db )
{
  this->m_table = table;
  this->m_db = db;

//  reload();
}

void TableWidget::setupWidgets()
{
  connect(tableView, SIGNAL(reloadRequested()), this, SLOT(reload()));
}

QString TableWidget::table()
{
  return m_table;
}
<commit_msg>Gros bogue sur l'ouverture des tables<commit_after>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include "../dbmanager.h"
#include "../iconmanager.h"
#include "tablewidget.h"

TableWidget::TableWidget(QWidget *parent)
  : AbstractTabWidget(parent)
{
  setupUi(this);

  setupWidgets();

  model = new QSqlTableModel(this);
}

TableWidget::TableWidget(QString table, QSqlDatabase *db, QWidget *parent)
  : AbstractTabWidget(parent)
{
  setupUi(this);
  setupWidgets();
  setTable(table, db);
}

QIcon TableWidget::icon()
{
  return IconManager::get("table");
}

QString TableWidget::id()
{
  return QString("t %1 on %2")
      .arg(m_table)
      .arg(m_db->connectionName());
}

void TableWidget::refresh()
{
  if(!m_db->isOpen())
    emit closeRequested();
}

void TableWidget::reload() {
  if(!m_db->isOpen())
    return;

  if(!m_db->tables(QSql::Tables).contains(m_table)
    && !m_db->tables(QSql::Views).contains(m_table)
    && !m_db->tables(QSql::SystemTables).contains(m_table))   {
    QMessageBox::critical(this,
                          tr("Error"),
                          tr("Unable to open the table %1. ").append(
                            tr("Check you have the necessary permissions."))
                          .arg(m_table));
    emit closeRequested();
    return;
  }

  if (!tableView->setTable(m_table, m_db)) {
    emit closeRequested();
  }
}

void TableWidget::setTable( QString table, QSqlDatabase *db )
{
  this->m_table = table;
  this->m_db = db;

//  reload();
}

void TableWidget::setupWidgets()
{
  connect(tableView, SIGNAL(reloadRequested()), this, SLOT(reload()));
}

QString TableWidget::table()
{
  return m_table;
}
<|endoftext|>


<commit_before>#include "fplll.h"

FPLLL_BEGIN_NAMESPACE

//#define DEBUG_PRUNER_OPTIMIZE
#define NUM_OPTIMIZATION_TOURS 3

template <class FT> void Pruner<FT>::optimize_coefficients_cost_vary_prob(/*io*/ vector<double> &pr)
{

  FT old_c0, old_c1, new_c, min_c;
  vec b(n), best_b(n);

  // step 1 use half coefficients only
  optimize_coefficients_evec(pr);

  load_coefficients(b, pr);
  old_c0 = target_function(b);
  min_c  = old_c0;

#ifdef DEBUG_PRUNER_OPTIMIZE
  FT old_sc   = single_enum_cost(b);
  FT old_prob = measure_metric(b);
  cerr << "# [Stage ho] half-optimization done." << endl;
  cerr << "# [Stage ho]    all_enum_cost = " << old_c0 << endl;
  cerr << "# [Stage ho] single_enum_cost = " << old_sc << endl;
  cerr << "# [Stage ho] succ_probability = " << old_prob << endl;
#endif

  // step 2 use full coefficients if enabled
  if (!(flags & PRUNER_HALF))
  {
    int tours = 0;
    while (1)
    {
      tours++;

      // initial cost
      load_coefficients(b, pr);
      old_c0 = target_function(b);

      // step 2.1 full tuning
      optimize_coefficients_local_adjust_decr_single(pr);
      optimize_coefficients_local_adjust_incr_prob(pr);
      optimize_coefficients_local_adjust_smooth(pr);

      // update best after tuning
      load_coefficients(b, pr);
      old_c1 = target_function(b);
      if (old_c1 < min_c)
      {
        min_c  = old_c1;
        best_b = b;
      }

#ifdef DEBUG_PRUNER_OPTIMIZE
      old_sc   = single_enum_cost(b);
      old_prob = measure_metric(b);
      cerr << "# [Stage ft] full-tuning done." << endl;
      cerr << "# [Stage ft]    all_enum_cost = " << old_c1 << endl;
      cerr << "# [Stage ft] single_enum_cost = " << old_sc << endl;
      cerr << "# [Stage ft] succ_probability = " << old_prob << endl;
#endif

      // step 2.2 full optimization
      optimize_coefficients_full(pr);

      load_coefficients(b, pr);
      new_c = target_function(b);
      if (new_c < min_c)
      {
        min_c  = new_c;
        best_b = b;
      }

#ifdef DEBUG_PRUNER_OPTIMIZE
      old_sc   = single_enum_cost(b);
      old_prob = measure_metric(b);
      cerr << "# [Stage fo] full-optimization done." << endl;
      cerr << "# [Stage fo]    all_enum_cost = " << new_c << endl;
      cerr << "# [Stage fo] single_enum_cost = " << old_sc << endl;
      cerr << "# [Stage fo] succ_probability = " << old_prob << endl;
#endif

      // break if not improving
      if (new_c / old_c0 > 0.995 and tours > NUM_OPTIMIZATION_TOURS)
        break;
    }
    save_coefficients(pr, best_b);
  }
  else
  {
    save_coefficients(pr, b);
  }
}

template <class FT>
void Pruner<FT>::optimize_coefficients_cost_fixed_prob(/*io*/ vector<double> &pr)
{
  vec b(n), best_b(n);
  FT prob;

  // step 1 call global optimization (without fixing succ. prob)
  optimize_coefficients_evec(pr);
  optimize_coefficients_local_adjust_smooth(pr);
  optimize_coefficients_full(pr);

#ifdef DEBUG_PRUNER_OPTIMIZE
  load_coefficients(b, pr);
  cerr << "# [Stage ho] half-optimization done." << endl;
  cerr << "# [Stage ho]    all_enum_cost = " << repeated_enum_cost(b) << endl;
  cerr << "# [Stage fo] single_enum_cost = " << single_enum_cost(b) << endl;
  cerr << "# [Stage ho] succ_probability = " << measure_metric(b) << endl;
  cerr << b << endl;
#endif

  // step 2 achieve target succ. prob
  optimize_coefficients_local_adjust_smooth(pr);
  load_coefficients(b, pr);
  prob = measure_metric(b);
  if (prob <= target)
    optimize_coefficients_incr_prob(pr);
  else
  {
    optimize_coefficients_decr_prob(pr);
  }

  // step 3: some local tweaking
  optimize_coefficients_local_adjust_smooth(pr);
  optimize_coefficients_local_adjust_prob(pr);

#ifdef DEBUG_PRUNER_OPTIMIZE
  load_coefficients(b, pr);
  cerr << "# [Stage fo] full-optimization done." << endl;
  cerr << "# [Stage fo]    all_enum_cost = " << repeated_enum_cost(b) << endl;
  cerr << "# [Stage fo] single_enum_cost = " << single_enum_cost(b) << endl;
  cerr << "# [Stage fo] succ_probability = " << measure_metric(b) << endl;
  cerr << b << endl;
#endif
}

/**
 *  optimize either overall cost or cost by fixing probability
 */
template <class FT> void Pruner<FT>::optimize_coefficients(/*io*/ vector<double> &pr)
{
  if (opt_single)
  {
    optimize_coefficients_cost_fixed_prob(pr);
  }
  else
  {
    optimize_coefficients_cost_vary_prob(pr);
  }
}

FPLLL_END_NAMESPACE
<commit_msg>fixing bug in cost_vary_prob()<commit_after>#include "fplll.h"

FPLLL_BEGIN_NAMESPACE

#define DEBUG_PRUNER_OPTIMIZE
#define NUM_OPTIMIZATION_TOURS 3

template <class FT> void Pruner<FT>::optimize_coefficients_cost_vary_prob(/*io*/ vector<double> &pr)
{

  FT old_c0, old_c1, new_c, min_c;
  vec b(n), best_b(n);

  // step 1 use half coefficients only
  optimize_coefficients_evec(pr);

  load_coefficients(b, pr);
  best_b = b;
  old_c0 = target_function(b);
  min_c  = old_c0;

#ifdef DEBUG_PRUNER_OPTIMIZE
  FT old_sc   = single_enum_cost(b);
  FT old_prob = measure_metric(b);
  cerr << "# [Stage ho] half-optimization done." << endl;
  cerr << "# [Stage ho]    all_enum_cost = " << old_c0 << endl;
  cerr << "# [Stage ho] single_enum_cost = " << old_sc << endl;
  cerr << "# [Stage ho] succ_probability = " << old_prob << endl;
#endif

  // step 2 use full coefficients if enabled
  if (!(flags & PRUNER_HALF))
  {
    int tours = 0;
    while (1)
    {
      tours++;

      // initial cost
      load_coefficients(b, pr);
      old_c0 = target_function(b);

      // step 2.1 full tuning
      optimize_coefficients_local_adjust_decr_single(pr);
      optimize_coefficients_local_adjust_incr_prob(pr);
      optimize_coefficients_local_adjust_smooth(pr);

      // update best after tuning
      load_coefficients(b, pr);
      old_c1 = target_function(b);
      if (old_c1 < min_c)
      {
        min_c  = old_c1;
        best_b = b;
      }

#ifdef DEBUG_PRUNER_OPTIMIZE
      old_sc   = single_enum_cost(b);
      old_prob = measure_metric(b);
      cerr << "# [Stage ft] full-tuning done." << endl;
      cerr << "# [Stage ft]    all_enum_cost = " << old_c1 << endl;
      cerr << "# [Stage ft] single_enum_cost = " << old_sc << endl;
      cerr << "# [Stage ft] succ_probability = " << old_prob << endl;
#endif

      // step 2.2 full optimization
      optimize_coefficients_full(pr);

      load_coefficients(b, pr);
      new_c = target_function(b);
      if (new_c < min_c)
      {
        min_c  = new_c;
        best_b = b;
      }

#ifdef DEBUG_PRUNER_OPTIMIZE
      old_sc   = single_enum_cost(b);
      old_prob = measure_metric(b);
      cerr << "# [Stage fo] full-optimization done." << endl;
      cerr << "# [Stage fo]    all_enum_cost = " << new_c << endl;
      cerr << "# [Stage fo] single_enum_cost = " << old_sc << endl;
      cerr << "# [Stage fo] succ_probability = " << old_prob << endl;
#endif

      // break if not improving
      if (new_c / old_c0 > 0.995 and tours > NUM_OPTIMIZATION_TOURS)
        break;
    }
    save_coefficients(pr, best_b);
  }
  else
  {
    save_coefficients(pr, b);
  }
}

template <class FT>
void Pruner<FT>::optimize_coefficients_cost_fixed_prob(/*io*/ vector<double> &pr)
{
  vec b(n);
  FT prob;

  // step 1 call global optimization (without fixing succ. prob)
  optimize_coefficients_evec(pr);
  optimize_coefficients_local_adjust_smooth(pr);
  optimize_coefficients_full(pr);

#ifdef DEBUG_PRUNER_OPTIMIZE
  load_coefficients(b, pr);
  cerr << "# [Stage ho] half-optimization done." << endl;
  cerr << "# [Stage ho]    all_enum_cost = " << repeated_enum_cost(b) << endl;
  cerr << "# [Stage fo] single_enum_cost = " << single_enum_cost(b) << endl;
  cerr << "# [Stage ho] succ_probability = " << measure_metric(b) << endl;
  cerr << b << endl;
#endif

  // step 2 achieve target succ. prob
  optimize_coefficients_local_adjust_smooth(pr);
  load_coefficients(b, pr);
  prob = measure_metric(b);
  if (prob <= target)
    optimize_coefficients_incr_prob(pr);
  else
  {
    optimize_coefficients_decr_prob(pr);
  }

  // step 3: some local tweaking
  optimize_coefficients_local_adjust_smooth(pr);
  optimize_coefficients_local_adjust_prob(pr);

#ifdef DEBUG_PRUNER_OPTIMIZE
  load_coefficients(b, pr);
  cerr << "# [Stage fo] full-optimization done." << endl;
  cerr << "# [Stage fo]    all_enum_cost = " << repeated_enum_cost(b) << endl;
  cerr << "# [Stage fo] single_enum_cost = " << single_enum_cost(b) << endl;
  cerr << "# [Stage fo] succ_probability = " << measure_metric(b) << endl;
  cerr << b << endl;
#endif
}

/**
 *  optimize either overall cost or cost by fixing probability
 */
template <class FT> void Pruner<FT>::optimize_coefficients(/*io*/ vector<double> &pr)
{
  if (opt_single)
  {
    optimize_coefficients_cost_fixed_prob(pr);
  }
  else
  {
    optimize_coefficients_cost_vary_prob(pr);
  }
}

FPLLL_END_NAMESPACE
<|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_multiplier", &session_settings::optimistic_unchoke_multiplier)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("max_outstanding_disk_bytes_per_connection", &session_settings::max_outstanding_disk_bytes_per_connection)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings:coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::automanaged_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t("disk_cache_algo_t")
        .value("lru", session_settings::disk_cache_algo_t::lru)
        .value("largest_contiguous", session_settings::disk_cache_algo_t::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::io_buffer_mode_t::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::io_buffer_mode_t:disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::io_buffer_mode_t::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", dht_settings::max_peers_reply)
        .def_readwrite("search_branching", dht_settings::search_branching)
        .def_readwrite("service_port", dht_settings::service_port)
        .def_readwrite("max_fail_count", dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<commit_msg>Fix typo<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_multiplier", &session_settings::optimistic_unchoke_multiplier)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("max_outstanding_disk_bytes_per_connection", &session_settings::max_outstanding_disk_bytes_per_connection)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings:coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::automanaged_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t("disk_cache_algo_t")
        .value("lru", session_settings::disk_cache_algo_t::lru)
        .value("largest_contiguous", session_settings::disk_cache_algo_t::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::io_buffer_mode_t::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::io_buffer_mode_t:disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::io_buffer_mode_t::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", &dht_settings::max_peers_reply)
        .def_readwrite("search_branching", &dht_settings::search_branching)
        .def_readwrite("service_port", &dht_settings::service_port)
        .def_readwrite("max_fail_count", &dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;
    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<commit_msg>Update python bindings session_settings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_multiplier", &session_settings::optimistic_unchoke_multiplier)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("max_outstanding_disk_bytes_per_connection", &session_settings::max_outstanding_disk_bytes_per_connection)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings:coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::automanaged_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t("disk_cache_algo_t")
        .value("lru", session_settings::disk_cache_algo_t::lru)
        .value("largest_contiguous", session_settings::disk_cache_algo_t::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::io_buffer_mode_t::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::io_buffer_mode_t:disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::io_buffer_mode_t::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", dht_settings::max_peers_reply)
        .def_readwrite("search_branching", dht_settings::search_branching)
        .def_readwrite("service_port", dht_settings::service_port)
        .def_readwrite("max_fail_count", dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<|endoftext|>


<commit_before><commit_msg>Add session_settings::peer_tos to bindings<commit_after><|endoftext|>


<commit_before>#include <rw.h>
#include <skeleton.h>

#include "subrast.h"

rw::Camera *Camera;
rw::Camera *SubCameras[4];

void
CameraSetViewWindow(rw::Camera *camera, float width, float height, float vw)
{
	rw::V2d viewWindow;

	// TODO: aspect ratio when fullscreen
	if(width > height){
		viewWindow.x = vw;
		viewWindow.y = vw / (width/height);
	}else{
		viewWindow.x = vw / (height/width);
		viewWindow.y = vw;
	}

	camera->setViewWindow(&viewWindow);
}

void
UpdateSubRasters(rw::Camera *mainCamera, rw::int32 mainWidth, rw::int32 mainHeight)
{
	rw::Rect rect[4];
	float width, height, border;

	border = mainHeight*0.05f;

	width = (mainWidth - border*3.0f) / 2.0f;
	height = (mainHeight - border*3.0f) / 2.0f;

	// top left
	rect[0].x = border;
	rect[0].y = border;
	rect[0].w = width;
	rect[0].h = height;

	// top right
	rect[1].x = border*2 + width;
	rect[1].y = border;
	rect[1].w = width;
	rect[1].h = height;

	// bottom left
	rect[2].x = border;
	rect[2].y = border*2 + height;
	rect[2].w = width;
	rect[2].h = height;

	// bottom left
	rect[3].x = border*2 + width;
	rect[3].y = border*2 + height;
	rect[3].w = width;
	rect[3].h = height;

	CameraSetViewWindow(SubCameras[0], width, height, 0.5f);
	for(int i = 1; i < 4; i++)
		CameraSetViewWindow(SubCameras[i], width, height, 0.5f + 0.4f);

	for(int i = 0; i < 4; i++){
		SubCameras[i]->frameBuffer->subRaster(mainCamera->frameBuffer, &rect[i]);
		SubCameras[i]->zBuffer->subRaster(mainCamera->zBuffer, &rect[i]);
	}
}

void
PositionSubCameras(void)
{
	rw::Frame *frame;
	rw::V3d pos;
	const float dist = 2.5f;

	// perspective
	pos.x = pos.y = 0.0f;
	pos.z = -4.0f;
	frame = SubCameras[0]->getFrame();
	frame->translate(&pos, rw::COMBINEREPLACE);

	// look along z
	pos.x = pos.y = 0.0f;
	pos.z = -dist;
	frame = SubCameras[1]->getFrame();
	frame->translate(&pos, rw::COMBINEREPLACE);

	// look along x
	pos.x = -dist;
	pos.y = pos.z = 0.0f;
	frame = SubCameras[2]->getFrame();
	frame->rotate(&Yaxis, 90.0f, rw::COMBINEREPLACE);
	frame->translate(&pos, rw::COMBINEPOSTCONCAT);

	// look along y
	pos.x = pos.z = 0.0f;
	pos.y = -dist;
	frame = SubCameras[3]->getFrame();
	frame->rotate(&Xaxis, -90.0f, rw::COMBINEREPLACE);
	frame->translate(&pos, rw::COMBINEPOSTCONCAT);
}

void
CreateCameras(rw::World *world)
{
	Camera = sk::CameraCreate(sk::globals.width, sk::globals.height, 1);
	assert(Camera);

	for(int i = 0; i < 4; i++){
		SubCameras[i] = sk::CameraCreate(0, 0, 1);
		assert(SubCameras[i]);

		SubCameras[i]->setNearPlane(0.1f);
		SubCameras[i]->setFarPlane(30.0f);

		world->addCamera(SubCameras[i]);

		if(i > 0)
			SubCameras[i]->setProjection(rw::Camera::PARALLEL);
	}

	PositionSubCameras();
}

void
DestroyCameras(rw::World *world)
{
	if(Camera){
		world->removeCamera(Camera);
		sk::CameraDestroy(Camera);
		Camera = nil;
	}

	for(int i = 0; i < 4; i++)
		if(SubCameras[i]){
			world->removeCamera(SubCameras[i]);
			sk::CameraDestroy(SubCameras[i]);
			SubCameras[i] = nil;
		}
}
<commit_msg>subrast: fix assert error at exit<commit_after>#include <rw.h>
#include <skeleton.h>

#include "subrast.h"

rw::Camera *Camera;
rw::Camera *SubCameras[4];

void
CameraSetViewWindow(rw::Camera *camera, float width, float height, float vw)
{
	rw::V2d viewWindow;

	// TODO: aspect ratio when fullscreen
	if(width > height){
		viewWindow.x = vw;
		viewWindow.y = vw / (width/height);
	}else{
		viewWindow.x = vw / (height/width);
		viewWindow.y = vw;
	}

	camera->setViewWindow(&viewWindow);
}

void
UpdateSubRasters(rw::Camera *mainCamera, rw::int32 mainWidth, rw::int32 mainHeight)
{
	rw::Rect rect[4];
	float width, height, border;

	border = mainHeight*0.05f;

	width = (mainWidth - border*3.0f) / 2.0f;
	height = (mainHeight - border*3.0f) / 2.0f;

	// top left
	rect[0].x = border;
	rect[0].y = border;
	rect[0].w = width;
	rect[0].h = height;

	// top right
	rect[1].x = border*2 + width;
	rect[1].y = border;
	rect[1].w = width;
	rect[1].h = height;

	// bottom left
	rect[2].x = border;
	rect[2].y = border*2 + height;
	rect[2].w = width;
	rect[2].h = height;

	// bottom left
	rect[3].x = border*2 + width;
	rect[3].y = border*2 + height;
	rect[3].w = width;
	rect[3].h = height;

	CameraSetViewWindow(SubCameras[0], width, height, 0.5f);
	for(int i = 1; i < 4; i++)
		CameraSetViewWindow(SubCameras[i], width, height, 0.5f + 0.4f);

	for(int i = 0; i < 4; i++){
		SubCameras[i]->frameBuffer->subRaster(mainCamera->frameBuffer, &rect[i]);
		SubCameras[i]->zBuffer->subRaster(mainCamera->zBuffer, &rect[i]);
	}
}

void
PositionSubCameras(void)
{
	rw::Frame *frame;
	rw::V3d pos;
	const float dist = 2.5f;

	// perspective
	pos.x = pos.y = 0.0f;
	pos.z = -4.0f;
	frame = SubCameras[0]->getFrame();
	frame->translate(&pos, rw::COMBINEREPLACE);

	// look along z
	pos.x = pos.y = 0.0f;
	pos.z = -dist;
	frame = SubCameras[1]->getFrame();
	frame->translate(&pos, rw::COMBINEREPLACE);

	// look along x
	pos.x = -dist;
	pos.y = pos.z = 0.0f;
	frame = SubCameras[2]->getFrame();
	frame->rotate(&Yaxis, 90.0f, rw::COMBINEREPLACE);
	frame->translate(&pos, rw::COMBINEPOSTCONCAT);

	// look along y
	pos.x = pos.z = 0.0f;
	pos.y = -dist;
	frame = SubCameras[3]->getFrame();
	frame->rotate(&Xaxis, -90.0f, rw::COMBINEREPLACE);
	frame->translate(&pos, rw::COMBINEPOSTCONCAT);
}

void
CreateCameras(rw::World *world)
{
	Camera = sk::CameraCreate(sk::globals.width, sk::globals.height, 1);
	assert(Camera);

	for(int i = 0; i < 4; i++){
		SubCameras[i] = sk::CameraCreate(0, 0, 1);
		assert(SubCameras[i]);

		SubCameras[i]->setNearPlane(0.1f);
		SubCameras[i]->setFarPlane(30.0f);

		world->addCamera(SubCameras[i]);

		if(i > 0)
			SubCameras[i]->setProjection(rw::Camera::PARALLEL);
	}

	PositionSubCameras();
}

void
DestroyCameras(rw::World *world)
{
	if(Camera){
		sk::CameraDestroy(Camera);
		Camera = nil;
	}

	for(int i = 0; i < 4; i++)
		if(SubCameras[i]){
			world->removeCamera(SubCameras[i]);
			sk::CameraDestroy(SubCameras[i]);
			SubCameras[i] = nil;
		}
}
<|endoftext|>


<commit_before>#include "osg/Uniform"

#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"

using namespace osg;
using namespace osgDB;
using namespace std;

// forward declare functions to use later.
bool Uniform_readLocalData(Object& obj, Input& fr);
bool Uniform_writeLocalData(const Object& obj, Output& fw);

// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_UniformProxy
(
    new osg::Uniform,
    "Uniform",
    "Object Uniform",
    &Uniform_readLocalData,
    &Uniform_writeLocalData
);

bool Uniform_readLocalData(Object& obj, Input& fr)
{
    bool iteratorAdvanced = false;

    Uniform& uniform = static_cast<Uniform&>(obj);

    if (fr.matchSequence("type %w"))
    {
	uniform.setType( Uniform::getTypeId(fr[1].getStr()) );
	fr+=2;
	iteratorAdvanced = true;
    }

    if (fr.matchSequence("name %s"))
    {
        uniform.setName(fr[1].getStr());
        fr+=2;
        iteratorAdvanced = true;
    }

    // TODO read uniform value based on type

    return iteratorAdvanced;
}

bool Uniform_writeLocalData(const Object& obj,Output& fw)
{
    const Uniform& uniform = static_cast<const Uniform&>(obj);

    fw.indent() << "type " << Uniform::getTypename( uniform.getType() ) << std::endl;

    fw.indent() << "name "<< fw.wrapString(uniform.getName()) << std::endl;

    // TODO write uniform value based on type

    return true;
}
<commit_msg>Added more complete support for writing out data of Uniforms<commit_after>#include "osg/Uniform"
#include "osg/io_utils"
#include "osg/Notify"

#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"

using namespace osg;
using namespace osgDB;
using namespace std;

// forward declare functions to use later.
bool Uniform_readLocalData(Object& obj, Input& fr);
bool Uniform_writeLocalData(const Object& obj, Output& fw);

// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_UniformProxy
(
    new osg::Uniform,
    "Uniform",
    "Object Uniform",
    &Uniform_readLocalData,
    &Uniform_writeLocalData
);

bool Uniform_readLocalData(Object& obj, Input& fr)
{
    bool iteratorAdvanced = false;

    Uniform& uniform = static_cast<Uniform&>(obj);

    if (fr.matchSequence("name %s"))
    {
        uniform.setName(fr[1].getStr());
        fr+=2;
        iteratorAdvanced = true;
    }

    // TODO read uniform value based on type

    if (fr.matchSequence("type %w"))
    {
	uniform.setType( Uniform::getTypeId(fr[1].getStr()) );
	fr+=2;
	iteratorAdvanced = true;
    }

    switch(uniform.getType())
    {
        case(osg::Uniform::FLOAT):
        {
            float value;
            if (fr[0].getFloat(value))
            {
                uniform.set(value);
	        fr+=1;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC2):
        {
            osg::Vec2 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]))
            {
                uniform.set(value);
	        fr+=2;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC3):
        {
            osg::Vec3 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]))
            {
                uniform.set(value);
	        fr+=3;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC4):
        {
            osg::Vec4 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]) && fr[3].getFloat(value[3]))
            {
                uniform.set(value);
	        fr+=4;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT):
        {
            int value;
            if (fr[0].getInt(value))
            {
                uniform.set(value);
	        fr+=1;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC2):
        {
            int value[2];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]))
            {
                uniform.set(value[0],value[1]);
	        fr+=2;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC3):
        {
            int value[3];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]))
            {
                uniform.set(value[0],value[1],value[2]);
	        fr+=3;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC4):
        {
            int value[4];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]) && fr[3].getInt(value[3]))
            {
                uniform.set(value[0],value[1],value[2],value[3]);
	        fr+=4;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::BOOL):
        {
            int value;
            if (fr[0].getInt(value))
            {
                uniform.set(value!=0 ? true:false);
	        fr+=1;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::BOOL_VEC2):
        {
            int value[2];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]))
            {
                uniform.set(value[0]!=0 ? true:false, value[1]!=0 ? true:false);
	        fr+=2;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::BOOL_VEC3):
        {
            int value[3];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]))
            {
                uniform.set(value[0]!=0 ? true:false, value[1]!=0 ? true:false, value[2]!=0 ? true:false);
	        fr+=3;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::BOOL_VEC4):
        {
            int value[4];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]) && fr[3].getInt(value[3]))
            {
                uniform.set(value[0]!=0 ? true:false, value[1]!=0 ? true:false, value[2]!=0 ? true:false, value[3]!=0 ? true:false);
	        fr+=4;
	        iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_MAT2):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT3):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT4):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_1D):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_2D):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_3D):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_CUBE):
        {
             osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
           break;
        }
        case(osg::Uniform::SAMPLER_1D_SHADOW):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_2D_SHADOW):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for reading."<<std::endl;
            break;
        }
    }

    return iteratorAdvanced;
}

bool Uniform_writeLocalData(const Object& obj,Output& fw)
{
    const Uniform& uniform = static_cast<const Uniform&>(obj);

    fw.indent() << "name "<< fw.wrapString(uniform.getName()) << std::endl;

    fw.indent() << "type " << Uniform::getTypename( uniform.getType() ) << " ";

    switch(uniform.getType())
    {
        case(osg::Uniform::FLOAT):
        {
            float value = 0.0f;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC2):
        {
            Vec2 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC3):
        {
            Vec3 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC4):
        {
            Vec4 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::INT):
        {
            int value = 0;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::INT_VEC2):
        {
            int value[2];
            uniform.get(value[0],value[1]);
            fw << value[0]<<" "<<value[1];
            break;
        }
        case(osg::Uniform::INT_VEC3):
        {
            int value[3];
            uniform.get(value[0],value[1],value[2]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2];
            break;
        }
        case(osg::Uniform::INT_VEC4):
        {
            int value[4];
            uniform.get(value[0],value[1],value[2],value[3]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2]<<" "<<value[3];
            break;
        }
        case(osg::Uniform::BOOL):
        {
            bool value = 0;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::BOOL_VEC2):
        {
            bool value[2];
            uniform.get(value[0],value[1]);
            fw << value[0]<<" "<<value[1];
            break;
        }
        case(osg::Uniform::BOOL_VEC3):
        {
            bool value[3];
            uniform.get(value[0],value[1],value[2]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2];
            break;
        }
        case(osg::Uniform::BOOL_VEC4):
        {
            bool value[4];
            uniform.get(value[0],value[1],value[2],value[3]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2]<<" "<<value[3];
            break;
        }
        case(osg::Uniform::FLOAT_MAT2):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT3):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT4):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_1D):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_2D):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_3D):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_CUBE):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_1D_SHADOW):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::SAMPLER_2D_SHADOW):
        {
            osg::notify(osg::WARN)<<"Warning : type not supported for writing."<<std::endl;
            break;
        }
    }

    fw << std::endl;

    return true;
}
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, 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.

// Internal Includes
#include <osvr/Common/ParseAlias.h>
#include <osvr/Util/Verbosity.h>

// Library/third-party includes
#include <json/reader.h>
#include <json/writer.h>

// Standard includes
#include <sstream>

namespace osvr {
namespace common {

    /// @brief Helper, converts old-style tracker source into normal. For a
    /// little backward-compatibility.
    ///
    /// @todo remove this method in the future.
    inline std::string getPathFromOldRouteSource(Json::Value obj) {
        std::ostringstream ret;
        if (obj.isObject() && obj.isMember("tracker")) {
            auto tracker = obj["tracker"].asString();
            if (tracker.front() != '/') {
                ret << "/";
            }
            ret << tracker;
            ret << "/tracker";
            if (obj.isMember("sensor")) {
                ret << "/";
                ret << obj["sensor"].asInt();
            }
        }
        return ret.str();
    }

    ParsedAlias::ParsedAlias(std::string const &src) : m_simple(true) {
        m_parse(src);
    }

    ParsedAlias::ParsedAlias(Json::Value src) : m_simple(true) { m_parse(src); }

    bool ParsedAlias::isValid() const { return !m_value.isNull(); }

    bool ParsedAlias::isSimple() const { return m_simple; }
    std::string ParsedAlias::getLeaf() const { return m_leaf().asString(); }
    void ParsedAlias::setLeaf(std::string const &leaf) { m_leaf() = leaf; }

    std::string ParsedAlias::getAlias() const {
        if (m_value.isString()) {
            return m_value.asString();
        }
        Json::FastWriter writer;
        writer.omitEndingLineFeed();
        return writer.write(m_value);
    }

    Json::Value ParsedAlias::getAliasValue() const { return m_value; }

    void ParsedAlias::m_parse(std::string const &src) {
        Json::Value val;
        Json::Reader reader;
        if (!reader.parse(src, val)) {
            // If it didn't parse as JSON, just assume it's a string.
            m_value = src;
            return;
        }
        m_parse(val);
    }

    static const char CHILD_KEY[] = "child";
    static const char SOURCE_KEY[] = "source";
    void ParsedAlias::m_parse(Json::Value &val) {
        if (val.isString()) {
            // Assume a string is just a string.
            m_value = val;
            return;
        }
        if (val.isObject()) {
            if (val.isMember(SOURCE_KEY)) {
                // Strip any initial "source" level
                m_parse(val[SOURCE_KEY]);
                return;
            }

            // Assume an object means a transform.
            m_simple = false;
            m_value = val;

            auto &leaf = m_leaf();
            if (leaf.isString()) {
                return;
            }

            auto trackerEquiv = getPathFromOldRouteSource(leaf);
            if (!trackerEquiv.empty()) {
                leaf = trackerEquiv;
                return;
            }

            OSVR_DEV_VERBOSE(
                "Couldn't handle transform leaf: " << leaf.toStyledString());
        }
        m_value = Json::nullValue;
        /// @todo finish by throwing?
    }
    Json::Value &ParsedAlias::m_leaf() {
        Json::Value *current = &m_value;
        while (current->isObject() && current->isMember(CHILD_KEY)) {
            current = &(*current)[CHILD_KEY];
        }
        return *current;
    }
    Json::Value const &ParsedAlias::m_leaf() const {
        Json::Value const *current = &m_value;
        while (current->isObject() && current->isMember(CHILD_KEY)) {
            current = &(*current)[CHILD_KEY];
        }
        return *current;
    }

} // namespace common
} // namespace osvr<commit_msg>Make compatible with newer 0.y.z versions of jsoncpp.<commit_after>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, 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.

// Internal Includes
#include <osvr/Common/ParseAlias.h>
#include <osvr/Util/Verbosity.h>

// Library/third-party includes
#include <json/reader.h>
#include <json/writer.h>

// Standard includes
#include <sstream>

namespace osvr {
namespace common {

    /// @brief Helper, converts old-style tracker source into normal. For a
    /// little backward-compatibility.
    ///
    /// @todo remove this method in the future.
    inline std::string getPathFromOldRouteSource(Json::Value obj) {
        std::ostringstream ret;
        if (obj.isObject() && obj.isMember("tracker")) {
            auto tracker = obj["tracker"].asString();
            if (tracker.front() != '/') {
                ret << "/";
            }
            ret << tracker;
            ret << "/tracker";
            if (obj.isMember("sensor")) {
                ret << "/";
                ret << obj["sensor"].asInt();
            }
        }
        return ret.str();
    }

    ParsedAlias::ParsedAlias(std::string const &src) : m_simple(true) {
        m_parse(src);
    }

    ParsedAlias::ParsedAlias(Json::Value src) : m_simple(true) { m_parse(src); }

    bool ParsedAlias::isValid() const { return !m_value.isNull(); }

    bool ParsedAlias::isSimple() const { return m_simple; }
    std::string ParsedAlias::getLeaf() const { return m_leaf().asString(); }
    void ParsedAlias::setLeaf(std::string const &leaf) { m_leaf() = leaf; }

    std::string ParsedAlias::getAlias() const {
        if (m_value.isString()) {
            return m_value.asString();
        }
        Json::FastWriter writer;
        std::string ret = writer.write(m_value);
        // Remove trailing line feed, if any.
        while (ret.back() == '\n' || ret.back() == '\r') {
            ret.pop_back();
        }
        return ret;
    }

    Json::Value ParsedAlias::getAliasValue() const { return m_value; }

    void ParsedAlias::m_parse(std::string const &src) {
        Json::Value val;
        Json::Reader reader;
        if (!reader.parse(src, val)) {
            // If it didn't parse as JSON, just assume it's a string.
            m_value = src;
            return;
        }
        m_parse(val);
    }

    static const char CHILD_KEY[] = "child";
    static const char SOURCE_KEY[] = "source";
    void ParsedAlias::m_parse(Json::Value &val) {
        if (val.isString()) {
            // Assume a string is just a string.
            m_value = val;
            return;
        }
        if (val.isObject()) {
            if (val.isMember(SOURCE_KEY)) {
                // Strip any initial "source" level
                m_parse(val[SOURCE_KEY]);
                return;
            }

            // Assume an object means a transform.
            m_simple = false;
            m_value = val;

            auto &leaf = m_leaf();
            if (leaf.isString()) {
                return;
            }

            auto trackerEquiv = getPathFromOldRouteSource(leaf);
            if (!trackerEquiv.empty()) {
                leaf = trackerEquiv;
                return;
            }

            OSVR_DEV_VERBOSE(
                "Couldn't handle transform leaf: " << leaf.toStyledString());
        }
        m_value = Json::nullValue;
        /// @todo finish by throwing?
    }
    Json::Value &ParsedAlias::m_leaf() {
        Json::Value *current = &m_value;
        while (current->isObject() && current->isMember(CHILD_KEY)) {
            current = &(*current)[CHILD_KEY];
        }
        return *current;
    }
    Json::Value const &ParsedAlias::m_leaf() const {
        Json::Value const *current = &m_value;
        while (current->isObject() && current->isMember(CHILD_KEY)) {
            current = &(*current)[CHILD_KEY];
        }
        return *current;
    }

} // namespace common
} // namespace osvr<|endoftext|>