text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "TranslateSpriteState.h"
#include "history/TranslateSpriteAOP.h"
namespace d2d
{
TranslateSpriteState::TranslateSpriteState(SpriteSelection* selection,
const Vector& first_pos)
{
m_selection = selection;
m_selection->Retain();
m_first_pos = m_last_pos = first_pos;
}
TranslateSpriteState::~TranslateSpriteState()
{
m_selection->Release();
}
void TranslateSpriteState::OnMousePress(const Vector& pos)
{
m_last_pos = pos;
}
AbstractAtomicOP* TranslateSpriteState::OnMouseRelease(const Vector& pos)
{
m_last_pos.setInvalid();
return new TranslateSpriteAOP(*m_selection, pos - m_first_pos);
}
bool TranslateSpriteState::OnMouseDrag(const Vector& pos)
{
if (m_selection->IsEmpty() || !m_last_pos.isValid()) {
return false;
}
Translate(pos - m_last_pos);
m_last_pos = pos;
return true;
}
bool TranslateSpriteState::OnDirectionKeyDown(DirectionType type)
{
if (m_selection->IsEmpty()) return false;
switch (type)
{
case e_left:
Translate(Vector(-1, 0));
break;
case e_right:
Translate(Vector(1, 0));
break;
case e_down:
Translate(Vector(0, -1));
break;
case e_up:
Translate(Vector(0, 1));
break;
}
return true;
}
void TranslateSpriteState::Translate(const Vector& offset)
{
m_selection->Traverse(Visitor(offset));
}
//////////////////////////////////////////////////////////////////////////
// class TranslateSpriteState::Visitor
//////////////////////////////////////////////////////////////////////////
void TranslateSpriteState::Visitor::
Visit(Object* object, bool& bFetchNext)
{
ISprite* sprite = static_cast<ISprite*>(object);
sprite->translate(m_offset);
bFetchNext = true;
}
}<commit_msg>[FIXED] translate sprite<commit_after>#include "TranslateSpriteState.h"
#include "history/TranslateSpriteAOP.h"
namespace d2d
{
TranslateSpriteState::TranslateSpriteState(SpriteSelection* selection,
const Vector& first_pos)
{
m_selection = selection;
m_selection->Retain();
m_first_pos = m_last_pos = first_pos;
}
TranslateSpriteState::~TranslateSpriteState()
{
m_selection->Release();
}
void TranslateSpriteState::OnMousePress(const Vector& pos)
{
m_first_pos = m_last_pos = pos;
}
AbstractAtomicOP* TranslateSpriteState::OnMouseRelease(const Vector& pos)
{
m_last_pos.setInvalid();
return new TranslateSpriteAOP(*m_selection, pos - m_first_pos);
}
bool TranslateSpriteState::OnMouseDrag(const Vector& pos)
{
if (m_selection->IsEmpty() || !m_last_pos.isValid()) {
return false;
}
Translate(pos - m_last_pos);
m_last_pos = pos;
return true;
}
bool TranslateSpriteState::OnDirectionKeyDown(DirectionType type)
{
if (m_selection->IsEmpty()) return false;
switch (type)
{
case e_left:
Translate(Vector(-1, 0));
break;
case e_right:
Translate(Vector(1, 0));
break;
case e_down:
Translate(Vector(0, -1));
break;
case e_up:
Translate(Vector(0, 1));
break;
}
return true;
}
void TranslateSpriteState::Translate(const Vector& offset)
{
m_selection->Traverse(Visitor(offset));
}
//////////////////////////////////////////////////////////////////////////
// class TranslateSpriteState::Visitor
//////////////////////////////////////////////////////////////////////////
void TranslateSpriteState::Visitor::
Visit(Object* object, bool& bFetchNext)
{
ISprite* sprite = static_cast<ISprite*>(object);
sprite->translate(m_offset);
bFetchNext = true;
}
}<|endoftext|>
|
<commit_before>/**
@file IO/Prop.hpp
@brief Prop structures.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_IO_PROP_HPP_
#define HORD_IO_PROP_HPP_
#include <Hord/config.hpp>
#include <Hord/IO/Defs.hpp>
#include <Hord/Object/Defs.hpp>
namespace Hord {
namespace IO {
// Forward declarations
struct PropInfo;
/**
@addtogroup io
@{
*/
/**
@addtogroup prop
@{
*/
/**
Prop info.
*/
struct PropInfo final {
public:
/** @name Properties */ /// @{
/** Object ID. */
Object::ID object_id;
/** Object type. */
Object::Type object_type;
/** Prop type. */
IO::PropType prop_type;
/// @}
/** @name Special member functions */ /// @{
/** Destructor. */
~PropInfo() noexcept = default;
/** Copy constructor. */
PropInfo(PropInfo const&) noexcept = default;
/** Move constructor. */
PropInfo(PropInfo&&) noexcept = default;
/** Copy assignment operator. */
PropInfo& operator=(PropInfo const&) noexcept = default;
/** Move assignment operator. */
PropInfo& operator=(PropInfo&&) noexcept = default;
/**
Constructor with object id, object type, and prop type.
@param object_id Object ID.
@param object_type Object Type.
@param prop_type Prop type.
*/
constexpr
PropInfo(
Object::ID const object_id,
Object::Type const object_type,
IO::PropType const prop_type
) noexcept
: object_id(object_id)
, object_type(object_type)
, prop_type(prop_type)
{}
/**
Constructor with object.
@post @code
this->object_id == object.get_id() &&
this->object_type == object.get_type()
@endcode
@param object Object.
@param prop_type Prop type.
*/
PropInfo(
Object::Unit const& object,
IO::PropType const prop_type
) noexcept;
/// @}
};
/** @} */ // end of doc-group prop
/** @} */ // end of doc-group io
} // namespace IO
} // namespace Hord
#endif // HORD_IO_PROP_HPP_
<commit_msg>IO::Prop: doc tidy.<commit_after>/**
@file IO/Prop.hpp
@brief Prop structures.
@author Timothy Howard
@copyright 2013-2014 Timothy Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_IO_PROP_HPP_
#define HORD_IO_PROP_HPP_
#include <Hord/config.hpp>
#include <Hord/IO/Defs.hpp>
#include <Hord/Object/Defs.hpp>
namespace Hord {
namespace IO {
// Forward declarations
struct PropInfo;
/**
@addtogroup io
@{
*/
/**
@addtogroup prop
@{
*/
/**
Prop info.
@sa IO::PropStream
*/
struct PropInfo final {
public:
/** @name Properties */ /// @{
/** Object ID. */
Object::ID object_id;
/** Object type. */
Object::Type object_type;
/** Prop type. */
IO::PropType prop_type;
/// @}
/** @name Special member functions */ /// @{
/** Destructor. */
~PropInfo() noexcept = default;
/** Copy constructor. */
PropInfo(PropInfo const&) noexcept = default;
/** Move constructor. */
PropInfo(PropInfo&&) noexcept = default;
/** Copy assignment operator. */
PropInfo& operator=(PropInfo const&) noexcept = default;
/** Move assignment operator. */
PropInfo& operator=(PropInfo&&) noexcept = default;
/**
Constructor with object id, object type, and prop type.
@param object_id Object ID.
@param object_type Object Type.
@param prop_type Prop type.
*/
constexpr
PropInfo(
Object::ID const object_id,
Object::Type const object_type,
IO::PropType const prop_type
) noexcept
: object_id(object_id)
, object_type(object_type)
, prop_type(prop_type)
{}
/**
Constructor with object.
@post @code
this->object_id == object.get_id() &&
this->object_type == object.get_type()
@endcode
@param object Object.
@param prop_type Prop type.
*/
PropInfo(
Object::Unit const& object,
IO::PropType const prop_type
) noexcept;
/// @}
};
/** @} */ // end of doc-group prop
/** @} */ // end of doc-group io
} // namespace IO
} // namespace Hord
#endif // HORD_IO_PROP_HPP_
<|endoftext|>
|
<commit_before>
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/pipelines/localization/SfM_Localizer.hpp"
#include "openMVG/sfm/sfm_data_BA_ceres.hpp"
#include "openMVG/multiview/solver_resection_kernel.hpp"
#include "openMVG/multiview/solver_resection_p3p.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp"
namespace openMVG {
namespace sfm {
struct ResectionSquaredResidualError {
// Compute the residual of the projection distance(pt2D, Project(P,pt3D))
// Return the squared error
static double Error(const Mat34 & P, const Vec2 & pt2D, const Vec3 & pt3D){
const Vec2 x = Project(P, pt3D);
return (x - pt2D).squaredNorm();
}
};
bool SfM_Localizer::Localize
(
const Pair & image_size,
const cameras::IntrinsicBase * optional_intrinsics,
Image_Localizer_Match_Data & resection_data,
geometry::Pose3 & pose
)
{
// --
// Compute the camera pose (resectioning)
// --
Mat34 P;
resection_data.vec_inliers.clear();
// Setup the admissible upper bound residual error
const double dPrecision =
resection_data.error_max == std::numeric_limits<double>::infinity() ?
std::numeric_limits<double>::infinity() :
Square(resection_data.error_max);
size_t MINIMUM_SAMPLES = 0;
const cameras::Pinhole_Intrinsic * pinhole_cam = dynamic_cast<const cameras::Pinhole_Intrinsic *>(optional_intrinsics);
if (pinhole_cam == nullptr)
{
//--
// Classic resection (try to compute the entire P matrix)
typedef openMVG::resection::kernel::SixPointResectionSolver SolverType;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
typedef openMVG::robust::ACKernelAdaptorResection<
SolverType, ResectionSquaredResidualError, openMVG::robust::UnnormalizerResection, Mat34>
KernelType;
KernelType kernel(resection_data.pt2D, image_size.first, image_size.second,
resection_data.pt3D);
// Robust estimation of the Projection matrix and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
else
{
//--
// Since K calibration matrix is known, compute only [R|t]
typedef openMVG::euclidean_resection::P3PSolver SolverType;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
typedef openMVG::robust::ACKernelAdaptorResection_K<
SolverType, ResectionSquaredResidualError,
openMVG::robust::UnnormalizerResection, Mat34> KernelType;
// since the intrinsics are known undistort the input 2d points
//@fixe there is a lot of code redundancy in this solution; find better solution to
// avoid code duplication when calling ACRansacOut
if(pinhole_cam->have_disto())
{
const std::size_t numPts = resection_data.pt2D.cols();
Mat pt2Dundistorted = Mat2X(2, numPts);
for(std::size_t iPoint = 0; iPoint < numPts; ++iPoint)
{
pt2Dundistorted.col(iPoint) = pinhole_cam->get_ud_pixel(resection_data.pt2D.col(iPoint));
}
KernelType kernel = KernelType(pt2Dundistorted, resection_data.pt3D, pinhole_cam->K());
// Robust estimation of the Projection matrix and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
else
{
// otherwise we just pass the input points
KernelType kernel = KernelType(resection_data.pt2D, resection_data.pt3D, pinhole_cam->K());
// Robust estimation of the Projection matrix and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
}
// Test if the mode support some points (more than those required for estimation)
#ifdef HAVE_CCTAG
const bool bResection = (resection_data.vec_inliers.size() > MINIMUM_SAMPLES);
#else
const bool bResection = (resection_data.vec_inliers.size() > 2.5 * MINIMUM_SAMPLES);
#endif
if (bResection)
{
resection_data.projection_matrix = P;
Mat3 K, R;
Vec3 t;
KRt_From_P(P, &K, &R, &t);
pose = geometry::Pose3(R, -R.transpose() * t);
}
std::cout << "\n"
<< "-------------------------------" << "\n"
<< "-- Robust Resection " << "\n"
<< "-- Resection status: " << bResection << "\n"
<< "-- #Points used for Resection: " << resection_data.pt2D.cols() << "\n"
<< "-- #Points validated by robust Resection: " << resection_data.vec_inliers.size() << "\n"
<< "-- Threshold: " << resection_data.error_max << "\n"
<< "-------------------------------" << std::endl;
return bResection;
}
bool SfM_Localizer::RefinePose
(
cameras::IntrinsicBase * intrinsics,
geometry::Pose3 & pose,
const Image_Localizer_Match_Data & matching_data,
bool b_refine_pose,
bool b_refine_intrinsic
)
{
// Setup a tiny SfM scene with the corresponding 2D-3D data
SfM_Data sfm_data;
// view
sfm_data.views.insert( std::make_pair(0, std::make_shared<View>("",0, 0, 0)));
// pose
sfm_data.poses[0] = pose;
// intrinsic (the shared_ptr does not take the ownership, will not release the input pointer)
sfm_data.intrinsics[0] = std::shared_ptr<cameras::IntrinsicBase>(intrinsics, [](cameras::IntrinsicBase*){});
// structure data (2D-3D correspondences)
for (size_t i = 0; i < matching_data.vec_inliers.size(); ++i)
{
const size_t idx = matching_data.vec_inliers[i];
Landmark landmark;
landmark.X = matching_data.pt3D.col(idx);
landmark.obs[0] = Observation(matching_data.pt2D.col(idx), UndefinedIndexT);
sfm_data.structure[i] = std::move(landmark);
}
Bundle_Adjustment_Ceres bundle_adjustment_obj;
const bool b_BA_Status = bundle_adjustment_obj.Adjust(sfm_data, b_refine_pose, b_refine_pose, b_refine_intrinsic, false);
if (b_BA_Status)
{
pose = sfm_data.poses[0];
}
return b_BA_Status;
}
} // namespace sfm
} // namespace openMVG
<commit_msg>[sfm] just formatting<commit_after>
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/pipelines/localization/SfM_Localizer.hpp"
#include "openMVG/sfm/sfm_data_BA_ceres.hpp"
#include "openMVG/multiview/solver_resection_kernel.hpp"
#include "openMVG/multiview/solver_resection_p3p.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp"
#include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp"
namespace openMVG {
namespace sfm {
struct ResectionSquaredResidualError {
// Compute the residual of the projection distance(pt2D, Project(P,pt3D))
// Return the squared error
static double Error(const Mat34 & P, const Vec2 & pt2D, const Vec3 & pt3D){
const Vec2 x = Project(P, pt3D);
return (x - pt2D).squaredNorm();
}
};
bool SfM_Localizer::Localize
(
const Pair & image_size,
const cameras::IntrinsicBase * optional_intrinsics,
Image_Localizer_Match_Data & resection_data,
geometry::Pose3 & pose
)
{
// --
// Compute the camera pose (resectioning)
// --
Mat34 P;
resection_data.vec_inliers.clear();
// Setup the admissible upper bound residual error
const double dPrecision =
resection_data.error_max == std::numeric_limits<double>::infinity() ?
std::numeric_limits<double>::infinity() :
Square(resection_data.error_max);
size_t MINIMUM_SAMPLES = 0;
const cameras::Pinhole_Intrinsic * pinhole_cam = dynamic_cast<const cameras::Pinhole_Intrinsic *>(optional_intrinsics);
if (pinhole_cam == nullptr)
{
//--
// Classic resection (try to compute the entire P matrix)
typedef openMVG::resection::kernel::SixPointResectionSolver SolverType;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
typedef openMVG::robust::ACKernelAdaptorResection<
SolverType, ResectionSquaredResidualError, openMVG::robust::UnnormalizerResection, Mat34>
KernelType;
KernelType kernel(resection_data.pt2D, image_size.first, image_size.second,
resection_data.pt3D);
// Robust estimation of the Projection matrix and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
else
{
//--
// Since K calibration matrix is known, compute only [R|t]
typedef openMVG::euclidean_resection::P3PSolver SolverType;
MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;
typedef openMVG::robust::ACKernelAdaptorResection_K<
SolverType, ResectionSquaredResidualError,
openMVG::robust::UnnormalizerResection, Mat34> KernelType;
// since the intrinsics are known undistort the input 2d points
//@fixe there is a lot of code redundancy in this solution; find better solution to
// avoid code duplication when calling ACRansacOut
if(pinhole_cam->have_disto())
{
const std::size_t numPts = resection_data.pt2D.cols();
Mat pt2Dundistorted = Mat2X(2, numPts);
for(std::size_t iPoint = 0; iPoint < numPts; ++iPoint)
{
pt2Dundistorted.col(iPoint) = pinhole_cam->get_ud_pixel(resection_data.pt2D.col(iPoint));
}
KernelType kernel = KernelType(pt2Dundistorted, resection_data.pt3D, pinhole_cam->K());
// Robust estimation of the Projection matrix and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
else
{
// otherwise we just pass the input points
KernelType kernel = KernelType(resection_data.pt2D, resection_data.pt3D, pinhole_cam->K());
// Robust estimation of the Projection matrix and its precision
const std::pair<double,double> ACRansacOut =
openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);
// Update the upper bound precision of the model found by AC-RANSAC
resection_data.error_max = ACRansacOut.first;
}
}
// Test if the mode support some points (more than those required for estimation)
#ifdef HAVE_CCTAG
const bool bResection = (resection_data.vec_inliers.size() > MINIMUM_SAMPLES);
#else
const bool bResection = (resection_data.vec_inliers.size() > 2.5 * MINIMUM_SAMPLES);
#endif
if (bResection)
{
resection_data.projection_matrix = P;
Mat3 K, R;
Vec3 t;
KRt_From_P(P, &K, &R, &t);
pose = geometry::Pose3(R, -R.transpose() * t);
}
std::cout << "\n"
<< "-------------------------------" << "\n"
<< "-- Robust Resection " << "\n"
<< "-- Resection status: " << bResection << "\n"
<< "-- #Points used for Resection: " << resection_data.pt2D.cols() << "\n"
<< "-- #Points validated by robust Resection: " << resection_data.vec_inliers.size() << "\n"
<< "-- Threshold: " << resection_data.error_max << "\n"
<< "-------------------------------" << std::endl;
return bResection;
}
bool SfM_Localizer::RefinePose
(
cameras::IntrinsicBase * intrinsics,
geometry::Pose3 & pose,
const Image_Localizer_Match_Data & matching_data,
bool b_refine_pose,
bool b_refine_intrinsic
)
{
// Setup a tiny SfM scene with the corresponding 2D-3D data
SfM_Data sfm_data;
// view
sfm_data.views.insert( std::make_pair(0, std::make_shared<View>("",0, 0, 0)));
// pose
sfm_data.poses[0] = pose;
// intrinsic (the shared_ptr does not take the ownership, will not release the input pointer)
sfm_data.intrinsics[0] = std::shared_ptr<cameras::IntrinsicBase>(intrinsics, [](cameras::IntrinsicBase*){});
// structure data (2D-3D correspondences)
for (size_t i = 0; i < matching_data.vec_inliers.size(); ++i)
{
const size_t idx = matching_data.vec_inliers[i];
Landmark landmark;
landmark.X = matching_data.pt3D.col(idx);
landmark.obs[0] = Observation(matching_data.pt2D.col(idx), UndefinedIndexT);
sfm_data.structure[i] = std::move(landmark);
}
Bundle_Adjustment_Ceres bundle_adjustment_obj;
const bool b_BA_Status = bundle_adjustment_obj.Adjust(sfm_data, b_refine_pose, b_refine_pose, b_refine_intrinsic, false);
if (b_BA_Status)
{
pose = sfm_data.poses[0];
}
return b_BA_Status;
}
} // namespace sfm
} // namespace openMVG
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include "robot_interface/arm_ctrl.h"
using namespace std;
TEST(ArmControlTest, testConstructorDefaultValues)
{
ArmCtrl ac ("robot", "left");
EXPECT_EQ ("robot", ac.getName());
EXPECT_EQ ( "left", ac.getLimb());
EXPECT_TRUE (ac.isRobotUsed());
EXPECT_EQ (100.0, ac.getCtrlFreq());
EXPECT_TRUE (ac.useForces());
EXPECT_TRUE (ac.useTracIK());
EXPECT_FALSE(ac.useCartCtrl());
EXPECT_FALSE(ac.isExperimental());
EXPECT_FALSE(ac.isCtrlRunning());
EXPECT_EQ (START, int(ac.getState()));
}
TEST(ArmControlTest, testConstructorCustomValues)
{
std::string name = "robot";
std::string limb = "left";
bool use_forces = false;
bool use_robot = false;
bool use_trac_ik = false;
bool use_cart_ctrl = false;
ArmCtrl ac(name, limb, use_robot, use_forces, use_trac_ik, use_cart_ctrl);
EXPECT_EQ (name, ac.getName());
EXPECT_EQ (limb, ac.getLimb());
EXPECT_FALSE(ac.isRobotUsed());
EXPECT_FALSE(ac.useForces());
EXPECT_FALSE(ac.useTracIK());
EXPECT_FALSE(ac.useCartCtrl());
EXPECT_TRUE (ac.getInternalRecovery());
}
TEST(ArmControlTest, testPublicSetterGetterMethods)
{
std::string name = "robot";
std::string limb = "left";
//overrides default constructor values for these variables; these
// values are the opposite of the default values
bool use_forces = true;
bool use_robot = false;
bool use_trac_ik = true;
bool use_cart_ctrl = false;
ArmCtrl ac(name, limb, use_robot, use_forces, use_trac_ik, use_cart_ctrl);
//Setter Methods
int obj = 5; //some random obj id number
vector<int> objs (4, 100); //some random value vector
ac.setState ( DONE);
ac.setObjectID ( obj);
ac.setObjectIDs ( objs);
ac.setAction (ACTION_HOME);
//Getter methods
EXPECT_EQ ( DONE, int(ac.getState()));
EXPECT_EQ (ACTION_HOME, ac.getAction());
EXPECT_EQ ( "", ac.getPrevAction());
EXPECT_EQ ( obj, ac.getObjectID());
EXPECT_EQ ( objs, ac.getObjectIDs());
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv)
{
ros::init(argc, argv, "arm_control_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Converted tab to spaces<commit_after>#include <gtest/gtest.h>
#include "robot_interface/arm_ctrl.h"
using namespace std;
TEST(ArmControlTest, testConstructorDefaultValues)
{
ArmCtrl ac ("robot", "left");
EXPECT_EQ ("robot", ac.getName());
EXPECT_EQ ( "left", ac.getLimb());
EXPECT_TRUE (ac.isRobotUsed());
EXPECT_EQ (100.0, ac.getCtrlFreq());
EXPECT_TRUE (ac.useForces());
EXPECT_TRUE (ac.useTracIK());
EXPECT_FALSE(ac.useCartCtrl());
EXPECT_FALSE(ac.isExperimental());
EXPECT_FALSE(ac.isCtrlRunning());
EXPECT_EQ (START, int(ac.getState()));
}
TEST(ArmControlTest, testConstructorCustomValues)
{
std::string name = "robot";
std::string limb = "left";
bool use_forces = false;
bool use_robot = false;
bool use_trac_ik = false;
bool use_cart_ctrl = false;
ArmCtrl ac(name, limb, use_robot, use_forces, use_trac_ik, use_cart_ctrl);
EXPECT_EQ (name, ac.getName());
EXPECT_EQ (limb, ac.getLimb());
EXPECT_FALSE(ac.isRobotUsed());
EXPECT_FALSE(ac.useForces());
EXPECT_FALSE(ac.useTracIK());
EXPECT_FALSE(ac.useCartCtrl());
EXPECT_TRUE (ac.getInternalRecovery());
}
TEST(ArmControlTest, testPublicSetterGetterMethods)
{
std::string name = "robot";
std::string limb = "left";
//overrides default constructor values for these variables; these
// values are the opposite of the default values
bool use_forces = true;
bool use_robot = false;
bool use_trac_ik = true;
bool use_cart_ctrl = false;
ArmCtrl ac(name, limb, use_robot, use_forces, use_trac_ik, use_cart_ctrl);
//Setter Methods
int obj = 5; //some random obj id number
vector<int> objs (4, 100); //some random value vector
ac.setState ( DONE);
ac.setObjectID ( obj);
ac.setObjectIDs ( objs);
ac.setAction (ACTION_HOME);
//Getter methods
EXPECT_EQ ( DONE, int(ac.getState()));
EXPECT_EQ (ACTION_HOME, ac.getAction());
EXPECT_EQ ( "", ac.getPrevAction());
EXPECT_EQ ( obj, ac.getObjectID());
EXPECT_EQ ( objs, ac.getObjectIDs());
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv)
{
ros::init(argc, argv, "arm_control_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#ifndef __NOD_DISC_BASE__
#define __NOD_DISC_BASE__
#include <vector>
#include <memory>
#include <string>
#include <stdio.h>
#include <stdint.h>
#include "Util.hpp"
#include "IDiscIO.hpp"
#include "IFileIO.hpp"
namespace NOD
{
class ExtractionContext;
class DiscBase
{
public:
virtual ~DiscBase() {}
struct Header
{
char gameID[6];
char discNum;
char discVersion;
char audioStreaming;
char streamBufSz;
char unk[14];
uint32_t wiiMagic;
uint32_t gcnMagic;
char gameTitle[64];
Header(IDiscIO& dio)
{
std::unique_ptr<IDiscIO::IReadStream> s = dio.beginReadStream(0);
s->read(this, sizeof(*this));
wiiMagic = SBig(wiiMagic);
gcnMagic = SBig(gcnMagic);
}
};
class FSTNode
{
uint32_t typeAndNameOffset;
uint32_t offset;
uint32_t length;
public:
inline bool isDir() const {return ((SBig(typeAndNameOffset) >> 24) != 0);}
inline uint32_t getNameOffset() const {return SBig(typeAndNameOffset) & 0xffffff;}
inline uint32_t getOffset() const {return SBig(offset);}
inline uint32_t getLength() const {return SBig(length);}
};
class IPartition
{
public:
virtual ~IPartition() {}
enum Kind
{
PART_DATA,
PART_UPDATE,
PART_CHANNEL
};
struct DOLHeader
{
uint32_t textOff[7];
uint32_t dataOff[11];
uint32_t textStarts[7];
uint32_t dataStarts[11];
uint32_t textSizes[7];
uint32_t dataSizes[11];
uint32_t bssStart;
uint32_t bssSize;
uint32_t entryPoint;
};
class Node
{
public:
enum Kind
{
NODE_FILE,
NODE_DIRECTORY
};
private:
friend class IPartition;
const IPartition& m_parent;
Kind m_kind;
uint64_t m_discOffset;
uint64_t m_discLength;
std::string m_name;
std::vector<Node>::iterator m_childrenBegin;
std::vector<Node>::iterator m_childrenEnd;
public:
Node(const IPartition& parent, const FSTNode& node, const char* name)
: m_parent(parent),
m_kind(node.isDir() ? NODE_DIRECTORY : NODE_FILE),
m_discOffset(parent.normalizeOffset(node.getOffset())),
m_discLength(node.getLength()),
m_name(name) {}
inline Kind getKind() const {return m_kind;}
inline const std::string& getName() const {return m_name;}
inline uint64_t size() const {return m_discLength;}
std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const
{
if (m_kind != NODE_FILE)
{
LogModule.report(LogVisor::Error, "unable to stream a non-file %s", m_name.c_str());
return std::unique_ptr<IPartReadStream>();
}
return m_parent.beginReadStream(m_discOffset + offset);
}
std::unique_ptr<uint8_t[]> getBuf() const
{
if (m_kind != NODE_FILE)
{
LogModule.report(LogVisor::Error, "unable to buffer a non-file %s", m_name.c_str());
return std::unique_ptr<uint8_t[]>();
}
uint8_t* buf = new uint8_t[m_discLength];
beginReadStream()->read(buf, m_discLength);
return std::unique_ptr<uint8_t[]>(buf);
}
inline std::vector<Node>::iterator rawBegin() const {return m_childrenBegin;}
inline std::vector<Node>::iterator rawEnd() const {return m_childrenEnd;}
class DirectoryIterator : std::iterator<std::forward_iterator_tag, Node>
{
friend class Node;
std::vector<Node>::iterator m_it;
DirectoryIterator(const std::vector<Node>::iterator& it)
: m_it(it) {}
public:
inline bool operator!=(const DirectoryIterator& other) {return m_it != other.m_it;}
inline bool operator==(const DirectoryIterator& other) {return m_it == other.m_it;}
inline DirectoryIterator& operator++()
{
if (m_it->m_kind == NODE_DIRECTORY)
m_it = m_it->rawEnd();
else
++m_it;
return *this;
}
inline Node& operator*() {return *m_it;}
inline Node* operator->() {return &*m_it;}
};
inline DirectoryIterator begin() const {return DirectoryIterator(m_childrenBegin);}
inline DirectoryIterator end() const {return DirectoryIterator(m_childrenEnd);}
inline DirectoryIterator find(const std::string& name) const
{
if (m_kind == NODE_DIRECTORY)
{
DirectoryIterator it=begin();
for (; it != end() ; ++it)
{
if (!it->getName().compare(name))
return it;
}
return it;
}
return end();
}
bool extractToDirectory(const SystemString& basePath, const ExtractionContext& ctx) const;
};
protected:
uint64_t m_dolOff;
uint64_t m_fstOff;
uint64_t m_fstSz;
uint64_t m_apploaderSz;
std::vector<Node> m_nodes;
void parseFST(IPartReadStream& s);
uint64_t m_dolSz;
void parseDOL(IPartReadStream& s);
const DiscBase& m_parent;
Kind m_kind;
uint64_t m_offset;
public:
IPartition(const DiscBase& parent, Kind kind, uint64_t offset)
: m_parent(parent), m_kind(kind), m_offset(offset) {}
virtual uint64_t normalizeOffset(uint64_t anOffset) const {return anOffset;}
inline Kind getKind() const {return m_kind;}
virtual std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const=0;
inline std::unique_ptr<IPartReadStream> beginDOLReadStream(uint64_t offset=0) const
{return beginReadStream(m_dolOff + offset);}
inline std::unique_ptr<IPartReadStream> beginFSTReadStream(uint64_t offset=0) const
{return beginReadStream(m_fstOff + offset);}
inline std::unique_ptr<IPartReadStream> beginApploaderReadStream(uint64_t offset=0) const
{return beginReadStream(0x2440 + offset);}
inline const Node& getFSTRoot() const {return m_nodes[0];}
inline Node& getFSTRoot() {return m_nodes[0];}
bool extractToDirectory(const SystemString& path, const ExtractionContext& ctx);
inline uint64_t getDOLSize() const {return m_dolSz;}
inline std::unique_ptr<uint8_t[]> getDOLBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_dolSz]);
beginDOLReadStream()->read(buf.get(), m_dolSz);
return buf;
}
inline uint64_t getFSTSize() const {return m_fstSz;}
inline std::unique_ptr<uint8_t[]> getFSTBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_fstSz]);
beginFSTReadStream()->read(buf.get(), m_fstSz);
return buf;
}
inline uint64_t getApploaderSize() const {return m_apploaderSz;}
inline std::unique_ptr<uint8_t[]> getApploaderBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_apploaderSz]);
beginApploaderReadStream()->read(buf.get(), m_apploaderSz);
return buf;
}
};
protected:
std::unique_ptr<IDiscIO> m_discIO;
Header m_header;
std::vector<std::unique_ptr<IPartition>> m_partitions;
public:
DiscBase(std::unique_ptr<IDiscIO>&& dio)
: m_discIO(std::move(dio)), m_header(*m_discIO) {}
virtual bool commit()=0;
inline const Header& getHeader() const {return m_header;}
inline const IDiscIO& getDiscIO() const {return *m_discIO;}
inline IPartition* getDataPartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::PART_DATA)
return part.get();
return nullptr;
}
inline IPartition* getUpdatePartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::PART_UPDATE)
return part.get();
return nullptr;
}
inline void extractToDirectory(const SystemString& path, const ExtractionContext& ctx)
{
for (std::unique_ptr<IPartition>& part : m_partitions)
part->extractToDirectory(path, ctx);
}
};
using Partition = DiscBase::IPartition;
using Node = Partition::Node;
}
#endif // __NOD_DISC_BASE__
<commit_msg>Silenced windows warning<commit_after>#ifndef __NOD_DISC_BASE__
#define __NOD_DISC_BASE__
#include <vector>
#include <memory>
#include <string>
#include <stdio.h>
#include <stdint.h>
#include "Util.hpp"
#include "IDiscIO.hpp"
#include "IFileIO.hpp"
namespace NOD
{
struct ExtractionContext;
class DiscBase
{
public:
virtual ~DiscBase() {}
struct Header
{
char gameID[6];
char discNum;
char discVersion;
char audioStreaming;
char streamBufSz;
char unk[14];
uint32_t wiiMagic;
uint32_t gcnMagic;
char gameTitle[64];
Header(IDiscIO& dio)
{
std::unique_ptr<IDiscIO::IReadStream> s = dio.beginReadStream(0);
s->read(this, sizeof(*this));
wiiMagic = SBig(wiiMagic);
gcnMagic = SBig(gcnMagic);
}
};
class FSTNode
{
uint32_t typeAndNameOffset;
uint32_t offset;
uint32_t length;
public:
inline bool isDir() const {return ((SBig(typeAndNameOffset) >> 24) != 0);}
inline uint32_t getNameOffset() const {return SBig(typeAndNameOffset) & 0xffffff;}
inline uint32_t getOffset() const {return SBig(offset);}
inline uint32_t getLength() const {return SBig(length);}
};
class IPartition
{
public:
virtual ~IPartition() {}
enum Kind
{
PART_DATA,
PART_UPDATE,
PART_CHANNEL
};
struct DOLHeader
{
uint32_t textOff[7];
uint32_t dataOff[11];
uint32_t textStarts[7];
uint32_t dataStarts[11];
uint32_t textSizes[7];
uint32_t dataSizes[11];
uint32_t bssStart;
uint32_t bssSize;
uint32_t entryPoint;
};
class Node
{
public:
enum Kind
{
NODE_FILE,
NODE_DIRECTORY
};
private:
friend class IPartition;
const IPartition& m_parent;
Kind m_kind;
uint64_t m_discOffset;
uint64_t m_discLength;
std::string m_name;
std::vector<Node>::iterator m_childrenBegin;
std::vector<Node>::iterator m_childrenEnd;
public:
Node(const IPartition& parent, const FSTNode& node, const char* name)
: m_parent(parent),
m_kind(node.isDir() ? NODE_DIRECTORY : NODE_FILE),
m_discOffset(parent.normalizeOffset(node.getOffset())),
m_discLength(node.getLength()),
m_name(name) {}
inline Kind getKind() const {return m_kind;}
inline const std::string& getName() const {return m_name;}
inline uint64_t size() const {return m_discLength;}
std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const
{
if (m_kind != NODE_FILE)
{
LogModule.report(LogVisor::Error, "unable to stream a non-file %s", m_name.c_str());
return std::unique_ptr<IPartReadStream>();
}
return m_parent.beginReadStream(m_discOffset + offset);
}
std::unique_ptr<uint8_t[]> getBuf() const
{
if (m_kind != NODE_FILE)
{
LogModule.report(LogVisor::Error, "unable to buffer a non-file %s", m_name.c_str());
return std::unique_ptr<uint8_t[]>();
}
uint8_t* buf = new uint8_t[m_discLength];
beginReadStream()->read(buf, m_discLength);
return std::unique_ptr<uint8_t[]>(buf);
}
inline std::vector<Node>::iterator rawBegin() const {return m_childrenBegin;}
inline std::vector<Node>::iterator rawEnd() const {return m_childrenEnd;}
class DirectoryIterator : std::iterator<std::forward_iterator_tag, Node>
{
friend class Node;
std::vector<Node>::iterator m_it;
DirectoryIterator(const std::vector<Node>::iterator& it)
: m_it(it) {}
public:
inline bool operator!=(const DirectoryIterator& other) {return m_it != other.m_it;}
inline bool operator==(const DirectoryIterator& other) {return m_it == other.m_it;}
inline DirectoryIterator& operator++()
{
if (m_it->m_kind == NODE_DIRECTORY)
m_it = m_it->rawEnd();
else
++m_it;
return *this;
}
inline Node& operator*() {return *m_it;}
inline Node* operator->() {return &*m_it;}
};
inline DirectoryIterator begin() const {return DirectoryIterator(m_childrenBegin);}
inline DirectoryIterator end() const {return DirectoryIterator(m_childrenEnd);}
inline DirectoryIterator find(const std::string& name) const
{
if (m_kind == NODE_DIRECTORY)
{
DirectoryIterator it=begin();
for (; it != end() ; ++it)
{
if (!it->getName().compare(name))
return it;
}
return it;
}
return end();
}
bool extractToDirectory(const SystemString& basePath, const ExtractionContext& ctx) const;
};
protected:
uint64_t m_dolOff;
uint64_t m_fstOff;
uint64_t m_fstSz;
uint64_t m_apploaderSz;
std::vector<Node> m_nodes;
void parseFST(IPartReadStream& s);
uint64_t m_dolSz;
void parseDOL(IPartReadStream& s);
const DiscBase& m_parent;
Kind m_kind;
uint64_t m_offset;
public:
IPartition(const DiscBase& parent, Kind kind, uint64_t offset)
: m_parent(parent), m_kind(kind), m_offset(offset) {}
virtual uint64_t normalizeOffset(uint64_t anOffset) const {return anOffset;}
inline Kind getKind() const {return m_kind;}
virtual std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const=0;
inline std::unique_ptr<IPartReadStream> beginDOLReadStream(uint64_t offset=0) const
{return beginReadStream(m_dolOff + offset);}
inline std::unique_ptr<IPartReadStream> beginFSTReadStream(uint64_t offset=0) const
{return beginReadStream(m_fstOff + offset);}
inline std::unique_ptr<IPartReadStream> beginApploaderReadStream(uint64_t offset=0) const
{return beginReadStream(0x2440 + offset);}
inline const Node& getFSTRoot() const {return m_nodes[0];}
inline Node& getFSTRoot() {return m_nodes[0];}
bool extractToDirectory(const SystemString& path, const ExtractionContext& ctx);
inline uint64_t getDOLSize() const {return m_dolSz;}
inline std::unique_ptr<uint8_t[]> getDOLBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_dolSz]);
beginDOLReadStream()->read(buf.get(), m_dolSz);
return buf;
}
inline uint64_t getFSTSize() const {return m_fstSz;}
inline std::unique_ptr<uint8_t[]> getFSTBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_fstSz]);
beginFSTReadStream()->read(buf.get(), m_fstSz);
return buf;
}
inline uint64_t getApploaderSize() const {return m_apploaderSz;}
inline std::unique_ptr<uint8_t[]> getApploaderBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_apploaderSz]);
beginApploaderReadStream()->read(buf.get(), m_apploaderSz);
return buf;
}
};
protected:
std::unique_ptr<IDiscIO> m_discIO;
Header m_header;
std::vector<std::unique_ptr<IPartition>> m_partitions;
public:
DiscBase(std::unique_ptr<IDiscIO>&& dio)
: m_discIO(std::move(dio)), m_header(*m_discIO) {}
virtual bool commit()=0;
inline const Header& getHeader() const {return m_header;}
inline const IDiscIO& getDiscIO() const {return *m_discIO;}
inline IPartition* getDataPartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::PART_DATA)
return part.get();
return nullptr;
}
inline IPartition* getUpdatePartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::PART_UPDATE)
return part.get();
return nullptr;
}
inline void extractToDirectory(const SystemString& path, const ExtractionContext& ctx)
{
for (std::unique_ptr<IPartition>& part : m_partitions)
part->extractToDirectory(path, ctx);
}
};
using Partition = DiscBase::IPartition;
using Node = Partition::Node;
}
#endif // __NOD_DISC_BASE__
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "mesh_resource_marker.h"
#include "marker_selection_handler.h"
#include "rviz/default_plugin/marker_display.h"
#include "rviz/selection/selection_manager.h"
#include "rviz/visualization_manager.h"
#include "rviz/mesh_loader.h"
#include "marker_display.h"
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreEntity.h>
#include <OGRE/OgreSubEntity.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreTextureManager.h>
namespace rviz
{
MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, VisualizationManager* manager, Ogre::SceneNode* parent_node)
: MarkerBase(owner, manager, parent_node)
, entity_(0)
{
}
MeshResourceMarker::~MeshResourceMarker()
{
reset();
}
void MeshResourceMarker::reset()
{
//destroy entity
if (entity_)
{
vis_manager_->getSceneManager()->destroyEntity( entity_ );
entity_ = 0;
}
// destroy all the materials we've created
S_MaterialPtr::iterator it;
for ( it = materials_.begin(); it!=materials_.end(); it++ )
{
Ogre::MaterialPtr material = *it;
if (!material.isNull())
{
for (size_t i = 0; i < material->getNumTechniques(); ++i)
{
Ogre::Technique* t = material->getTechnique(i);
// hack hack hack, really need to do a shader-based way of picking, rather than
// creating a texture for each object
if (t->getSchemeName() == "Pick")
{
Ogre::TextureManager::getSingleton().remove(t->getPass(0)->getTextureUnitState(0)->getTextureName());
}
}
material->unload();
Ogre::MaterialManager::getSingleton().remove(material->getName());
}
}
materials_.clear();
}
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);
bool need_color = false;
scene_node_->setVisible(false);
if( !entity_ ||
old_message->mesh_resource != new_message->mesh_resource ||
old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials )
{
reset();
if (new_message->mesh_resource.empty())
{
return;
}
if (loadMeshFromResource(new_message->mesh_resource).isNull())
{
std::stringstream ss;
ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
if ( owner_ )
{
owner_->setMarkerStatus(getID(), status_levels::Error, ss.str());
}
ROS_DEBUG("%s", ss.str().c_str());
return;
}
static uint32_t count = 0;
std::stringstream ss;
ss << "mesh_resource_marker_" << count++;
std::string id = ss.str();
entity_ = vis_manager_->getSceneManager()->createEntity(id, new_message->mesh_resource);
scene_node_->attachObject(entity_);
need_color = true;
if ( new_message->mesh_use_embedded_materials )
{
// make clones of all embedded materials so selection works correctly
S_MaterialPtr materials = getMaterials();
S_MaterialPtr::iterator it;
for ( it = materials.begin(); it!=materials.end(); it++ )
{
Ogre::MaterialPtr new_material = (*it)->clone( id + (*it)->getName() );
materials_.insert( new_material );
}
// make sub-entities use cloned materials
for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
{
std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
entity_->getSubEntity(i)->setMaterialName( id + mat_name );
}
}
else
{
// create a new single material for all the sub-entities
ss << "Material";
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create( ss.str(), ROS_PACKAGE_NAME );
material->setReceiveShadows(false);
material->getTechnique(0)->setLightingEnabled(true);
material->getTechnique(0)->setAmbient( 0.5, 0.5, 0.5 );
entity_->setMaterial( material );
materials_.insert( material );
}
vis_manager_->getSelectionManager()->removeObject(coll_);
coll_ = vis_manager_->getSelectionManager()->createCollisionForEntity(entity_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))), coll_);
}
if( need_color ||
old_message->color.r != new_message->color.r ||
old_message->color.g != new_message->color.g ||
old_message->color.b != new_message->color.b ||
old_message->color.a != new_message->color.a )
{
float r = new_message->color.r;
float g = new_message->color.g;
float b = new_message->color.b;
float a = new_message->color.a;
// Old way was to ignore the color and alpha when using embedded
// materials, which meant you could leave them unset, which means
// 0. Since we now USE the color and alpha values, leaving them
// all 0 will mean the object will be invisible. Therefore detect
// the situation where RGBA are all 0 and treat that the same as
// all 1 (full white).
if( new_message->mesh_use_embedded_materials && r == 0 && g == 0 && b == 0 && a == 0 )
{
r = 1; g = 1; b = 1; a = 1;
}
Ogre::SceneBlendType blending;
bool depth_write;
if ( a < 0.9998 )
{
blending = Ogre::SBT_TRANSPARENT_ALPHA;
depth_write = false;
}
else
{
blending = Ogre::SBT_REPLACE;
depth_write = true;
}
S_MaterialPtr::iterator it;
for( it = materials_.begin(); it != materials_.end(); it++ )
{
Ogre::Technique* technique = (*it)->getTechnique( 0 );
technique->setAmbient( r*0.5, g*0.5, b*0.5 );
technique->setDiffuse( r, g, b, a );
technique->setSceneBlending( blending );
technique->setDepthWriteEnabled( depth_write );
}
}
Ogre::Vector3 pos, scale;
Ogre::Quaternion orient;
transform(new_message, pos, orient, scale);
scene_node_->setVisible(true);
setPosition(pos);
setOrientation(orient);
// In Ogre, mesh surface normals are not normalized if object is not
// scaled. This forces the surface normals to be renormalized by
// invisibly tweaking the scale.
if( scale.x == 1.0 && scale.y == 1.0 && scale.z == 1.0 )
{
scale.z = 1.0001;
}
scene_node_->setScale(scale);
}
S_MaterialPtr MeshResourceMarker::getMaterials()
{
S_MaterialPtr materials;
extractMaterials( entity_, materials );
return materials;
}
}
<commit_msg>rviz: fixed bug #5359, setting mesh_resource incorrectly in interactive marker leads to seg fault.<commit_after>/*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "mesh_resource_marker.h"
#include "marker_selection_handler.h"
#include "rviz/default_plugin/marker_display.h"
#include "rviz/selection/selection_manager.h"
#include "rviz/visualization_manager.h"
#include "rviz/mesh_loader.h"
#include "marker_display.h"
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreEntity.h>
#include <OGRE/OgreSubEntity.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreTextureManager.h>
namespace rviz
{
MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, VisualizationManager* manager, Ogre::SceneNode* parent_node)
: MarkerBase(owner, manager, parent_node)
, entity_(0)
{
}
MeshResourceMarker::~MeshResourceMarker()
{
reset();
}
void MeshResourceMarker::reset()
{
//destroy entity
if (entity_)
{
vis_manager_->getSceneManager()->destroyEntity( entity_ );
entity_ = 0;
}
// destroy all the materials we've created
S_MaterialPtr::iterator it;
for ( it = materials_.begin(); it!=materials_.end(); it++ )
{
Ogre::MaterialPtr material = *it;
if (!material.isNull())
{
for (size_t i = 0; i < material->getNumTechniques(); ++i)
{
Ogre::Technique* t = material->getTechnique(i);
// hack hack hack, really need to do a shader-based way of picking, rather than
// creating a texture for each object
if (t->getSchemeName() == "Pick")
{
Ogre::TextureManager::getSingleton().remove(t->getPass(0)->getTextureUnitState(0)->getTextureName());
}
}
material->unload();
Ogre::MaterialManager::getSingleton().remove(material->getName());
}
}
materials_.clear();
}
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);
bool need_color = false;
scene_node_->setVisible(false);
if( !entity_ ||
old_message->mesh_resource != new_message->mesh_resource ||
old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials )
{
reset();
if (new_message->mesh_resource.empty())
{
return;
}
if (loadMeshFromResource(new_message->mesh_resource).isNull())
{
std::stringstream ss;
ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
if ( owner_ )
{
owner_->setMarkerStatus(getID(), status_levels::Error, ss.str());
}
ROS_DEBUG("%s", ss.str().c_str());
return;
}
static uint32_t count = 0;
std::stringstream ss;
ss << "mesh_resource_marker_" << count++;
std::string id = ss.str();
entity_ = vis_manager_->getSceneManager()->createEntity(id, new_message->mesh_resource);
scene_node_->attachObject(entity_);
need_color = true;
if ( new_message->mesh_use_embedded_materials )
{
// make clones of all embedded materials so selection works correctly
S_MaterialPtr materials = getMaterials();
S_MaterialPtr::iterator it;
for ( it = materials.begin(); it!=materials.end(); it++ )
{
Ogre::MaterialPtr new_material = (*it)->clone( id + (*it)->getName() );
materials_.insert( new_material );
}
// make sub-entities use cloned materials
for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
{
std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
entity_->getSubEntity(i)->setMaterialName( id + mat_name );
}
}
else
{
// create a new single material for all the sub-entities
ss << "Material";
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create( ss.str(), ROS_PACKAGE_NAME );
material->setReceiveShadows(false);
material->getTechnique(0)->setLightingEnabled(true);
material->getTechnique(0)->setAmbient( 0.5, 0.5, 0.5 );
entity_->setMaterial( material );
materials_.insert( material );
}
vis_manager_->getSelectionManager()->removeObject(coll_);
coll_ = vis_manager_->getSelectionManager()->createCollisionForEntity(entity_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))), coll_);
}
if( need_color ||
old_message->color.r != new_message->color.r ||
old_message->color.g != new_message->color.g ||
old_message->color.b != new_message->color.b ||
old_message->color.a != new_message->color.a )
{
float r = new_message->color.r;
float g = new_message->color.g;
float b = new_message->color.b;
float a = new_message->color.a;
// Old way was to ignore the color and alpha when using embedded
// materials, which meant you could leave them unset, which means
// 0. Since we now USE the color and alpha values, leaving them
// all 0 will mean the object will be invisible. Therefore detect
// the situation where RGBA are all 0 and treat that the same as
// all 1 (full white).
if( new_message->mesh_use_embedded_materials && r == 0 && g == 0 && b == 0 && a == 0 )
{
r = 1; g = 1; b = 1; a = 1;
}
Ogre::SceneBlendType blending;
bool depth_write;
if ( a < 0.9998 )
{
blending = Ogre::SBT_TRANSPARENT_ALPHA;
depth_write = false;
}
else
{
blending = Ogre::SBT_REPLACE;
depth_write = true;
}
S_MaterialPtr::iterator it;
for( it = materials_.begin(); it != materials_.end(); it++ )
{
Ogre::Technique* technique = (*it)->getTechnique( 0 );
technique->setAmbient( r*0.5, g*0.5, b*0.5 );
technique->setDiffuse( r, g, b, a );
technique->setSceneBlending( blending );
technique->setDepthWriteEnabled( depth_write );
}
}
Ogre::Vector3 pos, scale;
Ogre::Quaternion orient;
transform(new_message, pos, orient, scale);
scene_node_->setVisible(true);
setPosition(pos);
setOrientation(orient);
// In Ogre, mesh surface normals are not normalized if object is not
// scaled. This forces the surface normals to be renormalized by
// invisibly tweaking the scale.
if( scale.x == 1.0 && scale.y == 1.0 && scale.z == 1.0 )
{
scale.z = 1.0001;
}
scene_node_->setScale(scale);
}
S_MaterialPtr MeshResourceMarker::getMaterials()
{
S_MaterialPtr materials;
if( entity_ )
{
extractMaterials( entity_, materials );
}
return materials;
}
}
<|endoftext|>
|
<commit_before>#include <gst/gst.h>
#include "MediaPipeline.hpp"
#include <WebRtcEndpointImplFactory.hpp>
#include "WebRtcEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/filesystem.hpp>
#define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl"
#define FACTORY_NAME "webrtcendpoint"
namespace kurento
{
static const std::string CERTTOOL_TEMPLATE = "autoCerttool.tmpl";
static const std::string CERT_KEY_PEM_FILE = "autoCertkey.pem";
static const uint DEFAULT_STUN_PORT = 0;
static const std::string DEFAULT_STUN_ADDRESS = "77.72.174.167";
static std::shared_ptr<std::string> pemCertificate;
static std::mutex mutex;
static std::shared_ptr<boost::filesystem::path> temporalDirectory;
static void
remove_certificate (boost::filesystem::path *p)
{
boost::filesystem::remove_all (*p);
delete p;
}
static void
create_pem_certificate ()
{
int ret;
boost::filesystem::path p = boost::filesystem::unique_path (
boost::filesystem::temp_directory_path() / "WebRtcEndpoint_%%%%%%%%" );
boost::filesystem::create_directories (p);
temporalDirectory = std::shared_ptr <boost::filesystem::path>
(new boost::filesystem::path (p), remove_certificate);
boost::filesystem::path pemFile = p / CERT_KEY_PEM_FILE;
std::string pemGenerationCommand =
"/bin/sh -c \"certtool --generate-privkey --outfile " + pemFile .string() +
"\"";
ret = system (pemGenerationCommand.c_str() );
if (ret == -1) {
return;
}
boost::filesystem::path templateFile = p / CERTTOOL_TEMPLATE;
std::string certtoolCommand = "/bin/sh -c \"echo 'organization = kurento' > " +
templateFile.string() + " && certtool --generate-self-signed --load-privkey " +
pemFile.string() + " --template " + templateFile.string() + " >> " +
pemFile.string() + " 2>/dev/null\"";
ret = system (certtoolCommand.c_str() );
if (ret == -1) {
return;
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pemFile.string() ) );
}
static std::shared_ptr<std::string>
getPemCertificate (const boost::property_tree::ptree &conf)
{
std::unique_lock<std::mutex> lock (mutex);
if (pemCertificate) {
return pemCertificate;
}
try {
boost::filesystem::path pem_certificate_file_name (
conf.get<std::string> ("modules.kurento.WebRtcEndpoint.pemCertificate") );
if (pem_certificate_file_name.is_relative() ) {
pem_certificate_file_name = pem_certificate_file_name /
boost::filesystem::path (conf.get<std::string> ("configPath") );
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pem_certificate_file_name.string() ) );
return pemCertificate;
} catch (boost::property_tree::ptree_error &e) {
}
create_pem_certificate();
return pemCertificate;
}
WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf,
std::shared_ptr<MediaPipeline>
mediaPipeline) : SdpEndpointImpl (conf,
std::dynamic_pointer_cast<MediaObjectImpl>
(mediaPipeline), FACTORY_NAME)
{
uint stunPort;
std::string stunAddress;
std::string turnURL;
//set properties
try {
stunPort = conf.get<uint> ("modules.WebRtcEndpoint.stunServerPort");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Setting default port %d to stun server",
DEFAULT_STUN_PORT);
stunPort = DEFAULT_STUN_PORT;
}
if (stunPort != 0) {
try {
stunAddress =
conf.get<std::string> ("modules.WebRtcEndpoint.stunServerAddress");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Setting default address %s to stun server",
DEFAULT_STUN_ADDRESS.c_str() );
stunAddress = DEFAULT_STUN_ADDRESS;
}
if (!stunAddress.empty() ) {
GST_INFO ("stun port %d\n", stunPort );
g_object_set ( G_OBJECT (element), "stun-server-port",
stunPort, NULL);
GST_INFO ("stun address %s\n", stunAddress.c_str() );
g_object_set ( G_OBJECT (element), "stun-server",
stunAddress.c_str(),
NULL);
}
}
try {
turnURL = conf.get<std::string> ("modules.WebRtcEndpoint.turnURL");
GST_INFO ("turn info: %s\n", turnURL.c_str() );
g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(),
NULL);
} catch (boost::property_tree::ptree_error &e) {
}
g_object_set ( G_OBJECT (element), "certificate-pem-file",
getPemCertificate (conf)->c_str(), NULL);
}
MediaObjectImpl *
WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree
&conf, std::shared_ptr<MediaPipeline>
mediaPipeline) const
{
return new WebRtcEndpointImpl (conf, mediaPipeline);
}
WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor;
WebRtcEndpointImpl::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} /* kurento */
<commit_msg>webrtcendpoint: Fix getting certificate path from config<commit_after>#include <gst/gst.h>
#include "MediaPipeline.hpp"
#include <WebRtcEndpointImplFactory.hpp>
#include "WebRtcEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <boost/filesystem.hpp>
#define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl"
#define FACTORY_NAME "webrtcendpoint"
namespace kurento
{
static const std::string CERTTOOL_TEMPLATE = "autoCerttool.tmpl";
static const std::string CERT_KEY_PEM_FILE = "autoCertkey.pem";
static const uint DEFAULT_STUN_PORT = 0;
static const std::string DEFAULT_STUN_ADDRESS = "77.72.174.167";
static std::shared_ptr<std::string> pemCertificate;
static std::mutex mutex;
static std::shared_ptr<boost::filesystem::path> temporalDirectory;
static void
remove_certificate (boost::filesystem::path *p)
{
boost::filesystem::remove_all (*p);
delete p;
}
static void
create_pem_certificate ()
{
int ret;
boost::filesystem::path p = boost::filesystem::unique_path (
boost::filesystem::temp_directory_path() / "WebRtcEndpoint_%%%%%%%%" );
boost::filesystem::create_directories (p);
temporalDirectory = std::shared_ptr <boost::filesystem::path>
(new boost::filesystem::path (p), remove_certificate);
boost::filesystem::path pemFile = p / CERT_KEY_PEM_FILE;
std::string pemGenerationCommand =
"/bin/sh -c \"certtool --generate-privkey --outfile " + pemFile .string() +
"\"";
ret = system (pemGenerationCommand.c_str() );
if (ret == -1) {
return;
}
boost::filesystem::path templateFile = p / CERTTOOL_TEMPLATE;
std::string certtoolCommand = "/bin/sh -c \"echo 'organization = kurento' > " +
templateFile.string() + " && certtool --generate-self-signed --load-privkey " +
pemFile.string() + " --template " + templateFile.string() + " >> " +
pemFile.string() + " 2>/dev/null\"";
ret = system (certtoolCommand.c_str() );
if (ret == -1) {
return;
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pemFile.string() ) );
}
static std::shared_ptr<std::string>
getPemCertificate (const boost::property_tree::ptree &conf)
{
std::unique_lock<std::mutex> lock (mutex);
if (pemCertificate) {
return pemCertificate;
}
try {
boost::filesystem::path pem_certificate_file_name (
conf.get<std::string> ("modules.kurento.WebRtcEndpoint.pemCertificate") );
if (pem_certificate_file_name.is_relative() ) {
pem_certificate_file_name = boost::filesystem::path (
conf.get<std::string> ("configPath") ) / pem_certificate_file_name;
}
pemCertificate = std::shared_ptr <std::string> (new std::string (
pem_certificate_file_name.string() ) );
return pemCertificate;
} catch (boost::property_tree::ptree_error &e) {
}
create_pem_certificate();
return pemCertificate;
}
WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf,
std::shared_ptr<MediaPipeline>
mediaPipeline) : SdpEndpointImpl (conf,
std::dynamic_pointer_cast<MediaObjectImpl>
(mediaPipeline), FACTORY_NAME)
{
uint stunPort;
std::string stunAddress;
std::string turnURL;
//set properties
try {
stunPort = conf.get<uint> ("modules.WebRtcEndpoint.stunServerPort");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Setting default port %d to stun server",
DEFAULT_STUN_PORT);
stunPort = DEFAULT_STUN_PORT;
}
if (stunPort != 0) {
try {
stunAddress =
conf.get<std::string> ("modules.WebRtcEndpoint.stunServerAddress");
} catch (boost::property_tree::ptree_error &e) {
GST_INFO ("Setting default address %s to stun server",
DEFAULT_STUN_ADDRESS.c_str() );
stunAddress = DEFAULT_STUN_ADDRESS;
}
if (!stunAddress.empty() ) {
GST_INFO ("stun port %d\n", stunPort );
g_object_set ( G_OBJECT (element), "stun-server-port",
stunPort, NULL);
GST_INFO ("stun address %s\n", stunAddress.c_str() );
g_object_set ( G_OBJECT (element), "stun-server",
stunAddress.c_str(),
NULL);
}
}
try {
turnURL = conf.get<std::string> ("modules.WebRtcEndpoint.turnURL");
GST_INFO ("turn info: %s\n", turnURL.c_str() );
g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(),
NULL);
} catch (boost::property_tree::ptree_error &e) {
}
g_object_set ( G_OBJECT (element), "certificate-pem-file",
getPemCertificate (conf)->c_str(), NULL);
}
MediaObjectImpl *
WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree
&conf, std::shared_ptr<MediaPipeline>
mediaPipeline) const
{
return new WebRtcEndpointImpl (conf, mediaPipeline);
}
WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor;
WebRtcEndpointImpl::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} /* kurento */
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_CONV_DBN_INL
#define DLL_CONV_DBN_INL
#include <tuple>
#include "etl/dyn_vector.hpp"
#include "etl/dyn_matrix.hpp"
#include "conv_rbm.hpp"
#include "tuple_utils.hpp"
#include "dbn_trainer.hpp"
#include "conjugate_gradient.hpp"
#include "dbn_common.hpp"
#include "svm_common.hpp"
namespace dll {
/*!
* \brief A Deep Belief Network implementation
*/
template<typename Desc>
struct conv_dbn {
using desc = Desc;
using this_type = conv_dbn<desc>;
using tuple_type = typename desc::layers::tuple_type;
tuple_type tuples;
static constexpr const std::size_t layers = desc::layers::layers;
template <std::size_t N>
using rbm_type = typename std::tuple_element<N, tuple_type>::type;
using weight = typename rbm_type<0>::weight;
#ifdef DLL_SVM_SUPPORT
svm::model svm_model; ///< The learned model
svm::problem problem; ///< libsvm is stupid, therefore, you cannot destroy the problem if you want to use the model...
bool svm_loaded = false; ///< Indicates if a SVM model has been loaded (and therefore must be saved)
#endif //DLL_SVM_SUPPORT
//No arguments by default
conv_dbn(){};
//No copying
conv_dbn(const conv_dbn& dbn) = delete;
conv_dbn& operator=(const conv_dbn& dbn) = delete;
//No moving
conv_dbn(conv_dbn&& dbn) = delete;
conv_dbn& operator=(conv_dbn&& dbn) = delete;
void display() const {
std::size_t parameters = 0;
detail::for_each(tuples, [¶meters](auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NV = rbm_t::NV;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
printf("RBM: %lux%lu -> %lux%lu (%lu)\n", NV, NV, NH, NH, K);
});
}
void store(std::ostream& os) const {
detail::for_each(tuples, [&os](auto& rbm){
rbm.store(os);
});
#ifdef DLL_SVM_SUPPORT
svm_store(*this, os);
#endif //DLL_SVM_SUPPORT
}
void load(std::istream& is){
detail::for_each(tuples, [&is](auto& rbm){
rbm.load(is);
});
#ifdef DLL_SVM_SUPPORT
svm_load(*this, is);
#endif //DLL_SVM_SUPPORT
}
template<std::size_t N>
auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
static constexpr std::size_t rbm_nv(){
return rbm_type<N>::NV;
}
template<std::size_t N>
static constexpr std::size_t rbm_nh(){
return rbm_type<N>::NH;
}
template<std::size_t N>
static constexpr std::size_t rbm_k(){
return rbm_type<N>::K;
}
/*{{{ Pretrain */
/*!
* \brief Pretrain the network by training all layers in an unsupervised
* manner.
*/
template<typename Samples>
void pretrain(const Samples& training_data, std::size_t max_epochs){
using visible_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>;
using hidden_t = std::vector<etl::dyn_vector<etl::dyn_matrix<weight>>>;
using watcher_t = typename desc::template watcher_t<this_type>;
watcher_t watcher;
watcher.pretraining_begin(*this);
//Convert data to an useful form
visible_t data;
data.reserve(training_data.size());
for(auto& sample : training_data){
data.emplace_back(sample);
}
hidden_t next_a;
hidden_t next_s;
visible_t next;
auto input = std::ref(data);
detail::for_each_i(tuples, [&watcher, this, &input, &next, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
auto input_size = static_cast<const visible_t&>(input).size();
watcher.template pretrain_layer<rbm_t>(*this, I, input_size);
rbm.template train<
visible_t,
!watcher_t::ignore_sub, //Enable the RBM Watcher or not
typename dbn_detail::rbm_watcher_t<watcher_t>::type> //Replace the RBM watcher if not void
(static_cast<const visible_t&>(input), max_epochs);
//Get the activation probabilities for the next level
if(I < layers - 1){
next_a.clear();
next_a.reserve(input_size);
next_s.clear();
next_s.reserve(input_size);
//TODO Review that
for(std::size_t i = 0; i < input_size; ++i){
next_a.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
next_s.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
}
for(std::size_t i = 0; i < input_size; ++i){
rbm.v1 = static_cast<const visible_t&>(input)[i];
rbm.activate_hidden(next_a[i], next_s[i], rbm.v1, rbm.v1);
}
next.clear();
next.reserve(input_size);
//TODO Check the order of the output
for(std::size_t i = 0; i < input_size; ++i){
next.emplace_back(NH * NH * K);
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[i][j * NH * NH + k * NH + l] = next_a[i](k)(j,k);
}
}
}
}
input = std::ref(next);
}
});
watcher.pretraining_end(*this);
}
/*}}}*/
/*{{{ Predict */
template<typename Sample, typename Output>
void activation_probabilities(const Sample& item_data, Output& result){
using visible_t = etl::dyn_vector<typename Sample::value_type>;
using hidden_t = etl::dyn_vector<etl::dyn_matrix<weight>>;
visible_t item(item_data);
auto input = std::cref(item);
detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
static visible_t next(K * NH * NH);
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
rbm.v1 = static_cast<const Sample&>(input);
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
input = std::cref(next);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NH = rbm_nh<layers - 1>();
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
auto& last_rbm = layer<layers - 1>();
last_rbm.v1 = static_cast<const Sample&>(input);
last_rbm.activate_hidden(next_a, next_s, last_rbm.v1, last_rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
result[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
}
template<typename Sample>
etl::dyn_vector<weight> activation_probabilities(const Sample& item_data){
etl::dyn_vector<weight> result(rbm_nh<layers - 1>() * rbm_nh<layers - 1>() * rbm_k<layers - 1>());
activation_probabilities(item_data, result);
return result;
}
template<typename Weights>
size_t predict_label(const Weights& result){
size_t label = 0;
weight max = 0;
for(size_t l = 0; l < result.size(); ++l){
auto value = result[l];
if(value > max){
max = value;
label = l;
}
}
return label;
}
template<typename Sample>
size_t predict(const Sample& item){
auto result = activation_probabilities(item);
return predict_label(result);;
}
/*}}}*/
#ifdef DLL_SVM_SUPPORT
/*{{{ SVM Training and prediction */
/*}}}*/
#endif //DLL_SVM_SUPPORT
};
} //end of namespace dll
#endif
<commit_msg>Add support for SVM in CDBN<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_CONV_DBN_INL
#define DLL_CONV_DBN_INL
#include <tuple>
#include "etl/dyn_vector.hpp"
#include "etl/dyn_matrix.hpp"
#include "conv_rbm.hpp"
#include "tuple_utils.hpp"
#include "dbn_trainer.hpp"
#include "conjugate_gradient.hpp"
#include "dbn_common.hpp"
#include "svm_common.hpp"
namespace dll {
/*!
* \brief A Deep Belief Network implementation
*/
template<typename Desc>
struct conv_dbn {
using desc = Desc;
using this_type = conv_dbn<desc>;
using tuple_type = typename desc::layers::tuple_type;
tuple_type tuples;
static constexpr const std::size_t layers = desc::layers::layers;
template <std::size_t N>
using rbm_type = typename std::tuple_element<N, tuple_type>::type;
using weight = typename rbm_type<0>::weight;
#ifdef DLL_SVM_SUPPORT
svm::model svm_model; ///< The learned model
svm::problem problem; ///< libsvm is stupid, therefore, you cannot destroy the problem if you want to use the model...
bool svm_loaded = false; ///< Indicates if a SVM model has been loaded (and therefore must be saved)
#endif //DLL_SVM_SUPPORT
//No arguments by default
conv_dbn(){};
//No copying
conv_dbn(const conv_dbn& dbn) = delete;
conv_dbn& operator=(const conv_dbn& dbn) = delete;
//No moving
conv_dbn(conv_dbn&& dbn) = delete;
conv_dbn& operator=(conv_dbn&& dbn) = delete;
void display() const {
std::size_t parameters = 0;
detail::for_each(tuples, [¶meters](auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NV = rbm_t::NV;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
printf("RBM: %lux%lu -> %lux%lu (%lu)\n", NV, NV, NH, NH, K);
});
}
void store(std::ostream& os) const {
detail::for_each(tuples, [&os](auto& rbm){
rbm.store(os);
});
#ifdef DLL_SVM_SUPPORT
svm_store(*this, os);
#endif //DLL_SVM_SUPPORT
}
void load(std::istream& is){
detail::for_each(tuples, [&is](auto& rbm){
rbm.load(is);
});
#ifdef DLL_SVM_SUPPORT
svm_load(*this, is);
#endif //DLL_SVM_SUPPORT
}
template<std::size_t N>
auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type {
return std::get<N>(tuples);
}
template<std::size_t N>
static constexpr std::size_t rbm_nv(){
return rbm_type<N>::NV;
}
template<std::size_t N>
static constexpr std::size_t rbm_nh(){
return rbm_type<N>::NH;
}
template<std::size_t N>
static constexpr std::size_t rbm_k(){
return rbm_type<N>::K;
}
/*{{{ Pretrain */
/*!
* \brief Pretrain the network by training all layers in an unsupervised
* manner.
*/
template<typename Samples>
void pretrain(const Samples& training_data, std::size_t max_epochs){
using visible_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>;
using hidden_t = std::vector<etl::dyn_vector<etl::dyn_matrix<weight>>>;
using watcher_t = typename desc::template watcher_t<this_type>;
watcher_t watcher;
watcher.pretraining_begin(*this);
//Convert data to an useful form
visible_t data;
data.reserve(training_data.size());
for(auto& sample : training_data){
data.emplace_back(sample);
}
hidden_t next_a;
hidden_t next_s;
visible_t next;
auto input = std::ref(data);
detail::for_each_i(tuples, [&watcher, this, &input, &next, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
auto input_size = static_cast<const visible_t&>(input).size();
watcher.template pretrain_layer<rbm_t>(*this, I, input_size);
rbm.template train<
visible_t,
!watcher_t::ignore_sub, //Enable the RBM Watcher or not
typename dbn_detail::rbm_watcher_t<watcher_t>::type> //Replace the RBM watcher if not void
(static_cast<const visible_t&>(input), max_epochs);
//Get the activation probabilities for the next level
if(I < layers - 1){
next_a.clear();
next_a.reserve(input_size);
next_s.clear();
next_s.reserve(input_size);
//TODO Review that
for(std::size_t i = 0; i < input_size; ++i){
next_a.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
next_s.emplace_back(K, etl::dyn_matrix<weight>(NH, NH));
}
for(std::size_t i = 0; i < input_size; ++i){
rbm.v1 = static_cast<const visible_t&>(input)[i];
rbm.activate_hidden(next_a[i], next_s[i], rbm.v1, rbm.v1);
}
next.clear();
next.reserve(input_size);
//TODO Check the order of the output
for(std::size_t i = 0; i < input_size; ++i){
next.emplace_back(NH * NH * K);
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[i][j * NH * NH + k * NH + l] = next_a[i](k)(j,k);
}
}
}
}
input = std::ref(next);
}
});
watcher.pretraining_end(*this);
}
/*}}}*/
/*{{{ Predict */
template<typename Sample, typename Output>
void activation_probabilities(const Sample& item_data, Output& result){
using visible_t = etl::dyn_vector<typename Sample::value_type>;
using hidden_t = etl::dyn_vector<etl::dyn_matrix<weight>>;
visible_t item(item_data);
auto input = std::cref(item);
detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){
if(I != layers - 1){
typedef typename std::remove_reference<decltype(rbm)>::type rbm_t;
constexpr const auto NH = rbm_t::NH;
constexpr const auto K = rbm_t::K;
static visible_t next(K * NH * NH);
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
rbm.v1 = static_cast<const Sample&>(input);
rbm.activate_hidden(next_a, next_s, rbm.v1, rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
next[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
input = std::cref(next);
}
});
constexpr const auto K = rbm_k<layers - 1>();
constexpr const auto NH = rbm_nh<layers - 1>();
static hidden_t next_a(K, etl::dyn_matrix<weight>(NH, NH));
static hidden_t next_s(K, etl::dyn_matrix<weight>(NH, NH));
auto& last_rbm = layer<layers - 1>();
last_rbm.v1 = static_cast<const Sample&>(input);
last_rbm.activate_hidden(next_a, next_s, last_rbm.v1, last_rbm.v1);
//TODO Check the order of the output
for(std::size_t j = 0; j < NH; ++j){
for(std::size_t k = 0; k < NH; ++k){
for(std::size_t l = 0; l < K; ++l){
result[j * NH * NH + k * NH + l] = next_a(k)(j,k);
}
}
}
}
template<typename Sample>
etl::dyn_vector<weight> activation_probabilities(const Sample& item_data){
etl::dyn_vector<weight> result(rbm_nh<layers - 1>() * rbm_nh<layers - 1>() * rbm_k<layers - 1>());
activation_probabilities(item_data, result);
return result;
}
template<typename Weights>
size_t predict_label(const Weights& result){
size_t label = 0;
weight max = 0;
for(size_t l = 0; l < result.size(); ++l){
auto value = result[l];
if(value > max){
max = value;
label = l;
}
}
return label;
}
template<typename Sample>
size_t predict(const Sample& item){
auto result = activation_probabilities(item);
return predict_label(result);;
}
/*}}}*/
#ifdef DLL_SVM_SUPPORT
/*{{{ SVM Training and prediction */
template<typename Samples, typename Labels>
bool svm_train(const Samples& training_data, const Labels& labels, svm_parameter& parameters){
auto n_samples = training_data.size();
std::vector<etl::dyn_vector<double>> svm_samples;
//Get all the activation probabilities
for(std::size_t i = 0; i < n_samples; ++i){
svm_samples.emplace_back(rbm_nh<layers - 1>() * rbm_nh<layers - 1>() * rbm_k<layers - 1>());
activation_probabilities(training_data[i], svm_samples[i]);
}
//static_cast ensure using the correct overload
problem = svm::make_problem(labels, static_cast<const std::vector<etl::dyn_vector<double>>&>(svm_samples));
//Make libsvm quiet
svm::make_quiet();
//Make sure parameters are not messed up
if(!svm::check(problem, parameters)){
return false;
}
//Train the SVM
svm_model = svm::train(problem, parameters);
svm_loaded = true;
return true;
}
template<typename Samples, typename Labels>
bool svm_train(const Samples& training_data, const Labels& labels){
auto parameters = svm::default_parameters();
parameters.svm_type = C_SVC;
parameters.kernel_type = RBF;
parameters.probability = 1;
parameters.C = 2.8;
parameters.gamma = 0.0073;
return svm_train(training_data, labels, parameters);
}
template<typename Sample>
double svm_predict(const Sample& sample){
etl::dyn_vector<double> svm_sample(rbm_nh<layers - 1>() * rbm_nh<layers - 1>() * rbm_k<layers - 1>());
activation_probabilities(sample, svm_sample);
return svm::predict(svm_model, svm_sample);
}
/*}}}*/
#endif //DLL_SVM_SUPPORT
};
} //end of namespace dll
#endif
<|endoftext|>
|
<commit_before>//
// tcp.hpp
// fibio
//
// Created by Chen Xu on 14-3-8.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#ifndef fibio_tcp_hpp
#define fibio_tcp_hpp
#include <asio/ip/tcp.hpp>
namespace fibio { namespace io {
namespace tcp {
typedef asio::ip::tcp::resolver::query query;
typedef asio::ip::tcp::endpoint endpoint;
typedef asio::ip::tcp::socket socket;
typedef asio::ip::tcp::acceptor acceptor;
} // End of namespace fibio::io::tcp
tcp::endpoint resolve(const tcp::query &addr);
tcp::acceptor listen(const tcp::endpoint &ep, bool reuse_addr=true);
tcp::socket accept(tcp::acceptor &a);
tcp::socket connect(const tcp::endpoint &remote_ep, const tcp::endpoint &local_ep=tcp::endpoint(), uint64_t timeout=0);
size_t read_some(tcp::socket &s, char *buffer, size_t sz, uint64_t timeout_usec=0);
size_t write_some(tcp::socket &s, const char *buffer, size_t sz, uint64_t timeout_usec=0);
tcp::endpoint resolve(const tcp::query &addr, std::error_code &);
tcp::acceptor listen(const tcp::endpoint &ep, bool reuse_addr, std::error_code &);
// socket accept(acceptor &a, std::error_code &);
std::error_code connect(tcp::socket &,const tcp::endpoint &remote_ep, const tcp::endpoint &local_ep, uint64_t timeout);
size_t read_some(tcp::socket &s, char *buffer, size_t sz, uint64_t timeout_usec, std::error_code &);
size_t write_some(tcp::socket &s, const char *buffer, size_t sz, uint64_t timeout_usec, std::error_code &);
}} // End of namespace fibio::io
#endif
<commit_msg>accept with error_code<commit_after>//
// tcp.hpp
// fibio
//
// Created by Chen Xu on 14-3-8.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#ifndef fibio_tcp_hpp
#define fibio_tcp_hpp
#include <asio/ip/tcp.hpp>
namespace fibio { namespace io {
namespace tcp {
typedef asio::ip::tcp::resolver::query query;
typedef asio::ip::tcp::endpoint endpoint;
typedef asio::ip::tcp::socket socket;
typedef asio::ip::tcp::acceptor acceptor;
} // End of namespace fibio::io::tcp
tcp::endpoint resolve(const tcp::query &addr);
tcp::acceptor listen(const tcp::endpoint &ep, bool reuse_addr=true);
tcp::socket accept(tcp::acceptor &a);
tcp::socket connect(const tcp::endpoint &remote_ep, const tcp::endpoint &local_ep=tcp::endpoint(), uint64_t timeout=0);
size_t read_some(tcp::socket &s, char *buffer, size_t sz, uint64_t timeout_usec=0);
size_t write_some(tcp::socket &s, const char *buffer, size_t sz, uint64_t timeout_usec=0);
tcp::endpoint resolve(const tcp::query &addr, std::error_code &);
tcp::acceptor listen(const tcp::endpoint &ep, bool reuse_addr, std::error_code &);
tcp::socket accept(tcp::acceptor &a, std::error_code &);
std::error_code connect(tcp::socket &,const tcp::endpoint &remote_ep, const tcp::endpoint &local_ep, uint64_t timeout);
size_t read_some(tcp::socket &s, char *buffer, size_t sz, uint64_t timeout_usec, std::error_code &);
size_t write_some(tcp::socket &s, const char *buffer, size_t sz, uint64_t timeout_usec, std::error_code &);
}} // End of namespace fibio::io
#endif
<|endoftext|>
|
<commit_before>// Copyright 2017-2021 Global Phasing Ltd.
//
// Modify various properties of the model.
// For modifications that depend on entities or connectivity see polyheur.hpp.
#ifndef GEMMI_MODIFY_HPP_
#define GEMMI_MODIFY_HPP_
#include "model.hpp"
#include "util.hpp" // for vector_remove_if
#include <set>
namespace gemmi {
/// Remove alternative conformations.
template<class T> void remove_alternative_conformations(T& obj) {
for (auto& child : obj.children())
remove_alternative_conformations(child);
}
template<> inline void remove_alternative_conformations(Chain& chain) {
std::set<SeqId> seqids;
for (size_t i = 0; i < chain.residues.size(); ) {
if (seqids.insert(chain.residues[i].seqid).second)
++i;
else
chain.residues.erase(chain.residues.begin() + i);
}
for (Residue& residue : chain.residues) {
std::set<std::string> names;
for (size_t i = 0; i < residue.atoms.size(); ) {
Atom& atom = residue.atoms[i];
atom.altloc = '\0';
if (names.insert(atom.name).second)
++i;
else
residue.atoms.erase(residue.atoms.begin() + i);
}
}
}
/// Remove hydrogens.
template<class T> void remove_hydrogens(T& obj) {
for (auto& child : obj.children())
remove_hydrogens(child);
}
template<> inline void remove_hydrogens(Residue& res) {
vector_remove_if(res.atoms, [](const Atom& a) {
return a.element == El::H || a.element == El::D;
});
}
/// Set isotropic ADP to the range (b_min, b_max). Values smaller than
/// b_min are changed to b_min, values larger than b_max to b_max.
/// Anisotropic ADP is left unchanged.
template<class T> void assign_b_iso(T& obj, float b_min, float b_max) {
for (auto& child : obj.children())
assign_b_iso(child, b_min, b_max);
}
template<> inline void assign_b_iso(Atom& atom, float b_min, float b_max) {
atom.b_iso = std::min(std::max(atom.b_iso, b_min), b_max);
}
/// Remove anisotropic ADP
template<class T> void remove_anisou(T& obj) {
for (auto& child : obj.children())
remove_anisou(child);
}
template<> inline void remove_anisou(Atom& atom) {
atom.aniso = {0, 0, 0, 0, 0, 0};
}
/// Set absent ANISOU to value from B_iso
template<class T> void ensure_anisou(T& obj) {
for (auto& child : obj.children())
ensure_anisou(child);
}
template<> inline void ensure_anisou(Atom& atom) {
if (!atom.aniso.nonzero()) {
float u = float(1. / gemmi::u_to_b() * atom.b_iso);
atom.aniso = {u, u, u, 0.f, 0.f, 0.f};
}
}
/// apply Transform to both atom's position and ADP
template<class T> void transform_pos_and_adp(T& obj, const Transform& tr) {
for (auto& child : obj.children())
transform_pos_and_adp(child, tr);
}
template<> inline void transform_pos_and_adp(Atom& atom, const Transform& tr) {
atom.pos = Position(tr.apply(atom.pos));
if (atom.aniso.nonzero())
atom.aniso = atom.aniso.transformed_by<float>(tr.mat);
}
/// set atom site serial numbers to 1, 2, ...
inline void assign_serial_numbers(Model& model) {
int serial = 0;
for (CRA cra : model.all())
cra.atom->serial = ++serial;
}
inline void assign_serial_numbers(Structure& st) {
for (Model& model : st.models)
assign_serial_numbers(model);
}
/// Hydrogens modelled as H/D mixture (altlocs H and D with the same position
/// and ADP, but with refined fraction of D), it can be stored in a file either
/// as two atoms (H and D) or, using CCP4/Refmac extension, as H atoms with
/// the ccp4_deuterium_fraction parameter.
/// This function switches fraction -> altlocs
inline void expand_hd_mixture(Structure& st) {
if (!st.has_d_fraction)
return;
for (Model& model : st.models)
for (Chain& chain : model.chains)
for (Residue& res : chain.residues)
for (size_t i = res.atoms.size(); i-- != 0; ) {
Atom& atom = res.atoms[i];
float d_fraction = atom.fraction;
if (atom.element == El::H && d_fraction > 0) {
if (d_fraction >= 1) {
atom.element = El::D;
if (atom.name[0] == 'H')
atom.name[0] = 'D';
} else {
int alt_offset = atom.altloc;
if (alt_offset) {
alt_offset -= 'A';
// we don't expect 4+ altlocs - ignore such cases
if (alt_offset < 0 || alt_offset >= 3)
continue;
}
atom.altloc = 'A' + alt_offset;
float d_occ = atom.occ * d_fraction;
atom.occ *= (1 - d_fraction);
auto deut = res.atoms.insert(res.atoms.begin() + i + 1, atom);
deut->altloc = 'D' + alt_offset;
deut->element = El::D;
deut->occ = d_occ;
if (deut->name[0] == 'H')
deut->name[0] = 'D';
}
}
}
st.has_d_fraction = false;
}
inline bool replace_deuterium_with_fraction(Residue& res) {
bool found = false;
for (auto d = res.atoms.end(); d-- != res.atoms.begin(); )
if (d->element == El::D) {
found = true;
auto h = res.atoms.begin();
for (; h != res.atoms.end(); ++h)
if (h->element == El::H && h->pos.approx(d->pos, 1e-9))
break;
if (h != res.atoms.end()) {
h->occ += d->occ;
h->fraction = h->occ > 0.f ? d->occ / h->occ : 0.f;
if (h->altloc) {
bool keep_altloc = false;
for (auto i = res.atoms.begin(); i != res.atoms.end(); ++i)
if (i != d && i != h && (i->name == h->name || i->name == d->name))
keep_altloc = true;
if (!keep_altloc)
h->altloc = '\0';
}
res.atoms.erase(d);
} else {
d->element = El::H;
d->fraction = 1;
if (d->name[0] == 'D')
d->name[0] = 'H';
}
}
return found;
}
/// Switch H/D altlocs at the same position to H w/ ccp4_deuterium_fraction.
inline void collapse_hd_mixture(Structure& st) {
if (st.has_d_fraction)
return;
for (Model& model : st.models)
for (Chain& chain : model.chains)
for (Residue& res : chain.residues)
if (replace_deuterium_with_fraction(res))
st.has_d_fraction = true;
}
} // namespace gemmi
#endif
<commit_msg>reverted "collapse_hd_mixture(): change D's atom name..."<commit_after>// Copyright 2017-2021 Global Phasing Ltd.
//
// Modify various properties of the model.
// For modifications that depend on entities or connectivity see polyheur.hpp.
#ifndef GEMMI_MODIFY_HPP_
#define GEMMI_MODIFY_HPP_
#include "model.hpp"
#include "util.hpp" // for vector_remove_if
#include <set>
namespace gemmi {
/// Remove alternative conformations.
template<class T> void remove_alternative_conformations(T& obj) {
for (auto& child : obj.children())
remove_alternative_conformations(child);
}
template<> inline void remove_alternative_conformations(Chain& chain) {
std::set<SeqId> seqids;
for (size_t i = 0; i < chain.residues.size(); ) {
if (seqids.insert(chain.residues[i].seqid).second)
++i;
else
chain.residues.erase(chain.residues.begin() + i);
}
for (Residue& residue : chain.residues) {
std::set<std::string> names;
for (size_t i = 0; i < residue.atoms.size(); ) {
Atom& atom = residue.atoms[i];
atom.altloc = '\0';
if (names.insert(atom.name).second)
++i;
else
residue.atoms.erase(residue.atoms.begin() + i);
}
}
}
/// Remove hydrogens.
template<class T> void remove_hydrogens(T& obj) {
for (auto& child : obj.children())
remove_hydrogens(child);
}
template<> inline void remove_hydrogens(Residue& res) {
vector_remove_if(res.atoms, [](const Atom& a) {
return a.element == El::H || a.element == El::D;
});
}
/// Set isotropic ADP to the range (b_min, b_max). Values smaller than
/// b_min are changed to b_min, values larger than b_max to b_max.
/// Anisotropic ADP is left unchanged.
template<class T> void assign_b_iso(T& obj, float b_min, float b_max) {
for (auto& child : obj.children())
assign_b_iso(child, b_min, b_max);
}
template<> inline void assign_b_iso(Atom& atom, float b_min, float b_max) {
atom.b_iso = std::min(std::max(atom.b_iso, b_min), b_max);
}
/// Remove anisotropic ADP
template<class T> void remove_anisou(T& obj) {
for (auto& child : obj.children())
remove_anisou(child);
}
template<> inline void remove_anisou(Atom& atom) {
atom.aniso = {0, 0, 0, 0, 0, 0};
}
/// Set absent ANISOU to value from B_iso
template<class T> void ensure_anisou(T& obj) {
for (auto& child : obj.children())
ensure_anisou(child);
}
template<> inline void ensure_anisou(Atom& atom) {
if (!atom.aniso.nonzero()) {
float u = float(1. / gemmi::u_to_b() * atom.b_iso);
atom.aniso = {u, u, u, 0.f, 0.f, 0.f};
}
}
/// apply Transform to both atom's position and ADP
template<class T> void transform_pos_and_adp(T& obj, const Transform& tr) {
for (auto& child : obj.children())
transform_pos_and_adp(child, tr);
}
template<> inline void transform_pos_and_adp(Atom& atom, const Transform& tr) {
atom.pos = Position(tr.apply(atom.pos));
if (atom.aniso.nonzero())
atom.aniso = atom.aniso.transformed_by<float>(tr.mat);
}
/// set atom site serial numbers to 1, 2, ...
inline void assign_serial_numbers(Model& model) {
int serial = 0;
for (CRA cra : model.all())
cra.atom->serial = ++serial;
}
inline void assign_serial_numbers(Structure& st) {
for (Model& model : st.models)
assign_serial_numbers(model);
}
/// Hydrogens modelled as H/D mixture (altlocs H and D with the same position
/// and ADP, but with refined fraction of D), it can be stored in a file either
/// as two atoms (H and D) or, using CCP4/Refmac extension, as H atoms with
/// the ccp4_deuterium_fraction parameter.
/// This function switches fraction -> altlocs
inline void expand_hd_mixture(Structure& st) {
if (!st.has_d_fraction)
return;
for (Model& model : st.models)
for (Chain& chain : model.chains)
for (Residue& res : chain.residues)
for (size_t i = res.atoms.size(); i-- != 0; ) {
Atom& atom = res.atoms[i];
float d_fraction = atom.fraction;
if (atom.element == El::H && d_fraction > 0) {
if (d_fraction >= 1) {
atom.element = El::D;
if (atom.name[0] == 'H')
atom.name[0] = 'D';
} else {
int alt_offset = atom.altloc;
if (alt_offset) {
alt_offset -= 'A';
// we don't expect 4+ altlocs - ignore such cases
if (alt_offset < 0 || alt_offset >= 3)
continue;
}
atom.altloc = 'A' + alt_offset;
float d_occ = atom.occ * d_fraction;
atom.occ *= (1 - d_fraction);
auto deut = res.atoms.insert(res.atoms.begin() + i + 1, atom);
deut->altloc = 'D' + alt_offset;
deut->element = El::D;
deut->occ = d_occ;
if (deut->name[0] == 'H')
deut->name[0] = 'D';
}
}
}
st.has_d_fraction = false;
}
inline bool replace_deuterium_with_fraction(Residue& res) {
bool found = false;
for (auto d = res.atoms.end(); d-- != res.atoms.begin(); )
if (d->element == El::D) {
found = true;
auto h = res.atoms.begin();
for (; h != res.atoms.end(); ++h)
if (h->element == El::H && h->pos.approx(d->pos, 1e-9))
break;
if (h != res.atoms.end()) {
h->occ += d->occ;
h->fraction = h->occ > 0.f ? d->occ / h->occ : 0.f;
if (h->altloc) {
bool keep_altloc = false;
for (auto i = res.atoms.begin(); i != res.atoms.end(); ++i)
if (i != d && i != h && (i->name == h->name || i->name == d->name))
keep_altloc = true;
if (!keep_altloc)
h->altloc = '\0';
}
res.atoms.erase(d);
} else {
d->element = El::H;
d->fraction = 1;
// Atom name is left unchanged. prepare_topology() first calls this
// function and then conditionally changes the name (Dxx -> Hxx).
}
}
return found;
}
/// Switch H/D altlocs at the same position to H w/ ccp4_deuterium_fraction.
inline void collapse_hd_mixture(Structure& st) {
if (st.has_d_fraction)
return;
for (Model& model : st.models)
for (Chain& chain : model.chains)
for (Residue& res : chain.residues)
if (replace_deuterium_with_fraction(res))
st.has_d_fraction = true;
}
} // namespace gemmi
#endif
<|endoftext|>
|
<commit_before>#ifndef _GRL_REALTIME_HPP_
#define _GRL_REALTIME_HPP_
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <mach/mach_init.h>
#include <mach/thread_policy.h>
#include <mach/sched.h>
#include <pthread.h>
#include <unistd.h>
#include <err.h>
#include <sys/param.h>
static inline uint64_t
nanos_to_abs(uint64_t ns, uint32_t numer, uint32_t denom)
{
return (uint64_t)(ns * (((double)denom) / ((double)numer)));
}
/**
* THREAD_TIME_CONSTRAINT_POLICY:
*
* This scheduling mode is for threads which have real time
* constraints on their execution.
*
* Parameters:
*
* @param period: This is the nominal amount of time between separate
* processing arrivals, specified in absolute time units. A
* value of 0 indicates that there is no inherent periodicity in
* the computation. (nanoseconds)
*
* @param computation: This is the nominal amount of computation
* time needed during a separate processing arrival, specified
* in absolute time units. (nanoseconds)
*
* @param constraint: This is the maximum amount of real time that
* may elapse from the start of a separate processing arrival
* to the end of computation for logically correct functioning,
* specified in absolute time units. Must be (>= computation).
* Note that latency = (constraint - computation). (nanoseconds)
*
* @param preemptible: This indicates that the computation may be
* interrupted, subject to the constraint specified above
* Should almost always be false unless you really need it. (bool)
*
* @see http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/tools/tests/xnu_quick_test/sched_tests.c
* @see https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html
*/
inline int set_realtime(int period, int computation, int constraint, bool preemptible = false) {
struct mach_timebase_info mti;
struct thread_time_constraint_policy ttcpolicy;
kern_return_t kret;
kret = mach_timebase_info(&mti);
if (kret != KERN_SUCCESS) {
warnx("Could not get timebase info %d", kret);
return;
}
thread_port_t threadport = pthread_mach_thread_np(pthread_self());
ttcpolicy.period = nanos_to_abs(period, mti.numer, mti.denom);
ttcpolicy.computation = nanos_to_abs(computation, mti.numer, mti.denom); // HZ/3300;
ttcpolicy.constraint = nanos_to_abs(constraint, mti.numer, mti.denom); // HZ/2200;
ttcpolicy.preemptible = preemptible;
if ((kret=thread_policy_set(threadport,
THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy,
THREAD_TIME_CONSTRAINT_POLICY_COUNT)) != KERN_SUCCESS) {
fprintf(stderr, "set_realtime() failed.\n");
warnx("Failed to set_realtime %d", kret);
return 0;
}
return 1;
}
#endif // __APPLE__
#endif<commit_msg>small changes to realtime.hpp<commit_after>#ifndef _GRL_REALTIME_HPP_
#define _GRL_REALTIME_HPP_
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <mach/mach_init.h>
#include <mach/thread_policy.h>
//#include <mach/sched.h>
#include <pthread.h>
#include <unistd.h>
#include <err.h>
#include <sys/param.h>
static inline uint64_t
nanos_to_abs(uint64_t ns, uint32_t numer, uint32_t denom)
{
return (uint64_t)(ns * (((double)denom) / ((double)numer)));
}
/**
* THREAD_TIME_CONSTRAINT_POLICY:
*
* This scheduling mode is for threads which have real time
* constraints on their execution.
*
* Parameters:
*
* @param period: This is the nominal amount of time between separate
* processing arrivals, specified in absolute time units. A
* value of 0 indicates that there is no inherent periodicity in
* the computation. (nanoseconds)
*
* @param computation: This is the nominal amount of computation
* time needed during a separate processing arrival, specified
* in absolute time units. (nanoseconds)
*
* @param constraint: This is the maximum amount of real time that
* may elapse from the start of a separate processing arrival
* to the end of computation for logically correct functioning,
* specified in absolute time units. Must be (>= computation).
* Note that latency = (constraint - computation). (nanoseconds)
*
* @param preemptible: This indicates that the computation may be
* interrupted, subject to the constraint specified above
* Should almost always be false unless you really need it. (bool)
*
* @see http://www.opensource.apple.com/source/xnu/xnu-2050.18.24/tools/tests/xnu_quick_test/sched_tests.c
* @see https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html
*/
inline int set_realtime(int period, int computation, int constraint, bool preemptible = false) {
struct mach_timebase_info mti;
struct thread_time_constraint_policy ttcpolicy;
kern_return_t kret;
kret = mach_timebase_info(&mti);
if (kret != KERN_SUCCESS) {
warnx("Could not get timebase info %d", kret);
return 0;
}
thread_port_t threadport = pthread_mach_thread_np(pthread_self());
ttcpolicy.period = nanos_to_abs(period, mti.numer, mti.denom);
ttcpolicy.computation = nanos_to_abs(computation, mti.numer, mti.denom); // HZ/3300;
ttcpolicy.constraint = nanos_to_abs(constraint, mti.numer, mti.denom); // HZ/2200;
ttcpolicy.preemptible = preemptible;
if ((kret=thread_policy_set(threadport,
THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy,
THREAD_TIME_CONSTRAINT_POLICY_COUNT)) != KERN_SUCCESS) {
fprintf(stderr, "set_realtime() failed.\n");
warnx("Failed to set_realtime %d", kret);
return 0;
}
return 1;
}
#endif // __APPLE__
#endif<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_COLOR_HPP
#define MAPNIK_COLOR_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/global.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/operators.hpp>
#pragma GCC diagnostic pop
// stl
#include <sstream>
#include <cstdint>
namespace mapnik {
class MAPNIK_DECL color : boost::equality_comparable<color>
{
public:
std::uint8_t red_;
std::uint8_t green_;
std::uint8_t blue_;
std::uint8_t alpha_;
bool premultiplied_;
// default ctor
color()
: red_(0xff),
green_(0xff),
blue_(0xff),
alpha_(0xff),
premultiplied_(false)
{}
color(std::uint8_t _red, std::uint8_t _green, std::uint8_t _blue, std::uint8_t _alpha = 0xff, bool premultiplied = false)
: red_(_red),
green_(_green),
blue_(_blue),
alpha_(_alpha),
premultiplied_(premultiplied)
{}
color(std::uint32_t _rgba, bool premultiplied = false)
: red_(_rgba & 0xff),
green_((_rgba >> 8) & 0xff),
blue_((_rgba >> 16) & 0xff),
alpha_((_rgba >> 24) & 0xff),
premultiplied_(premultiplied) {}
// copy ctor
color(const color& rhs)
: red_(rhs.red_),
green_(rhs.green_),
blue_(rhs.blue_),
alpha_(rhs.alpha_),
premultiplied_(rhs.premultiplied_)
{}
// move ctor
color(color && rhs)
: red_(std::move(rhs.red_)),
green_(std::move(rhs.green_)),
blue_(std::move(rhs.blue_)),
alpha_(std::move(rhs.alpha_)),
premultiplied_(std::move(rhs.premultiplied_)) {}
color( std::string const& str, bool premultiplied = false);
std::string to_string() const;
std::string to_hex_string() const;
bool premultiply();
bool demultiply();
color& operator=(color rhs)
{
swap(rhs);
return *this;
}
inline bool operator==(color const& rhs) const
{
return (red_== rhs.red()) &&
(green_ == rhs.green()) &&
(blue_ == rhs.blue()) &&
(alpha_ == rhs.alpha());
}
inline std::uint8_t red() const
{
return red_;
}
inline std::uint8_t green() const
{
return green_;
}
inline std::uint8_t blue() const
{
return blue_;
}
inline std::uint8_t alpha() const
{
return alpha_;
}
inline void set_red(std::uint8_t _red)
{
red_ = _red;
}
inline void set_green(std::uint8_t _green)
{
green_ = _green;
}
inline void set_blue(std::uint8_t _blue)
{
blue_ = _blue;
}
inline void set_alpha(std::uint8_t _alpha)
{
alpha_ = _alpha;
}
inline bool get_premultiplied() const
{
return premultiplied_;
}
inline void set_premultiplied(bool status)
{
premultiplied_ = status;
}
inline unsigned rgba() const
{
return static_cast<unsigned>((alpha_ << 24) | (blue_ << 16) | (green_ << 8) | (red_)) ;
}
private:
void swap(color & rhs)
{
std::swap(red_, rhs.red_);
std::swap(green_,rhs.green_);
std::swap(blue_,rhs.blue_);
std::swap(alpha_,rhs.alpha_);
std::swap(premultiplied_, rhs.premultiplied_);
}
};
template <typename charT, typename traits>
std::basic_ostream<charT, traits> &
operator << ( std::basic_ostream<charT, traits> & s, mapnik::color const& c )
{
s << c.to_string();
return s;
}
// hash
inline std::size_t hash_value(color const& c)
{
return c.rgba();
}
}
#endif // MAPNIK_COLOR_HPP
<commit_msg>fix operator== (ref #4137)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_COLOR_HPP
#define MAPNIK_COLOR_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/global.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/operators.hpp>
#pragma GCC diagnostic pop
// stl
#include <sstream>
#include <cstdint>
namespace mapnik {
class MAPNIK_DECL color : boost::equality_comparable<color>
{
public:
std::uint8_t red_;
std::uint8_t green_;
std::uint8_t blue_;
std::uint8_t alpha_;
bool premultiplied_;
// default ctor
color()
: red_(0xff),
green_(0xff),
blue_(0xff),
alpha_(0xff),
premultiplied_(false)
{}
color(std::uint8_t _red, std::uint8_t _green, std::uint8_t _blue, std::uint8_t _alpha = 0xff, bool premultiplied = false)
: red_(_red),
green_(_green),
blue_(_blue),
alpha_(_alpha),
premultiplied_(premultiplied)
{}
color(std::uint32_t _rgba, bool premultiplied = false)
: red_(_rgba & 0xff),
green_((_rgba >> 8) & 0xff),
blue_((_rgba >> 16) & 0xff),
alpha_((_rgba >> 24) & 0xff),
premultiplied_(premultiplied) {}
// copy ctor
color(const color& rhs)
: red_(rhs.red_),
green_(rhs.green_),
blue_(rhs.blue_),
alpha_(rhs.alpha_),
premultiplied_(rhs.premultiplied_)
{}
// move ctor
color(color && rhs)
: red_(std::move(rhs.red_)),
green_(std::move(rhs.green_)),
blue_(std::move(rhs.blue_)),
alpha_(std::move(rhs.alpha_)),
premultiplied_(std::move(rhs.premultiplied_)) {}
color( std::string const& str, bool premultiplied = false);
std::string to_string() const;
std::string to_hex_string() const;
bool premultiply();
bool demultiply();
color& operator=(color rhs)
{
swap(rhs);
return *this;
}
inline bool operator==(color const& rhs) const
{
return (red_== rhs.red_) &&
(green_ == rhs.green_) &&
(blue_ == rhs.blue_) &&
(alpha_ == rhs.alpha_) &&
(premultiplied_ == rhs.premultiplied_);
}
inline std::uint8_t red() const
{
return red_;
}
inline std::uint8_t green() const
{
return green_;
}
inline std::uint8_t blue() const
{
return blue_;
}
inline std::uint8_t alpha() const
{
return alpha_;
}
inline void set_red(std::uint8_t _red)
{
red_ = _red;
}
inline void set_green(std::uint8_t _green)
{
green_ = _green;
}
inline void set_blue(std::uint8_t _blue)
{
blue_ = _blue;
}
inline void set_alpha(std::uint8_t _alpha)
{
alpha_ = _alpha;
}
inline bool get_premultiplied() const
{
return premultiplied_;
}
inline void set_premultiplied(bool val)
{
premultiplied_ = val;
}
inline unsigned rgba() const
{
return static_cast<unsigned>((alpha_ << 24) | (blue_ << 16) | (green_ << 8) | (red_)) ;
}
private:
void swap(color & rhs)
{
std::swap(red_, rhs.red_);
std::swap(green_,rhs.green_);
std::swap(blue_,rhs.blue_);
std::swap(alpha_,rhs.alpha_);
std::swap(premultiplied_, rhs.premultiplied_);
}
};
template <typename charT, typename traits>
std::basic_ostream<charT, traits> &
operator << ( std::basic_ostream<charT, traits> & s, mapnik::color const& c )
{
s << c.to_string();
return s;
}
// hash
inline std::size_t hash_value(color const& c)
{
return c.rgba();
}
}
#endif // MAPNIK_COLOR_HPP
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_COORD_HPP
#define MAPNIK_COORD_HPP
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/operators.hpp>
#pragma GCC diagnostic pop
namespace mapnik {
template <typename T,int dim>
struct coord {
using type = T;
};
template <typename T>
struct coord<T,2>
: boost::addable<coord<T,2>,
boost::addable2<coord<T,2>,T,
boost::subtractable<coord<T,2>,
boost::subtractable2<coord<T,2>,T,
boost::dividable2<coord<T,2>, T,
boost::multipliable2<coord<T,2>, T > > > > > >
{
using type = T;
T x;
T y;
public:
coord()
: x(),y() {}
coord(T x_,T y_)
: x(x_),y(y_) {}
coord(coord<T,2> const& rhs)
: x(rhs.x),
y(rhs.y) {}
template <typename T2>
coord (coord<T2,2> const& rhs)
: x(type(rhs.x)),
y(type(rhs.y)) {}
coord(coord<T,2> && rhs) noexcept
: x(std::move(rhs.x)),
y(std::move(rhs.y)) {}
coord<T,2>& operator=(coord<T,2> rhs)
{
swap(rhs);
return *this;
}
template <typename T2>
coord<T,2>& operator=(const coord<T2,2>& rhs)
{
coord<T,2> tmp(rhs);
swap(rhs);
return *this;
}
template <typename T2>
bool operator==(coord<T2,2> const& rhs)
{
return x == rhs.x && y == rhs.y;
}
coord<T,2>& operator+=(coord<T,2> const& rhs)
{
x+=rhs.x;
y+=rhs.y;
return *this;
}
coord<T,2>& operator+=(T rhs)
{
x+=rhs;
y+=rhs;
return *this;
}
coord<T,2>& operator-=(coord<T,2> const& rhs)
{
x-=rhs.x;
y-=rhs.y;
return *this;
}
coord<T,2>& operator-=(T rhs)
{
x-=rhs;
y-=rhs;
return *this;
}
coord<T,2>& operator*=(T t)
{
x*=t;
y*=t;
return *this;
}
coord<T,2>& operator/=(T t)
{
x/=t;
y/=t;
return *this;
}
private:
void swap(coord<T,2> & rhs)
{
std::swap(this->x, rhs.x);
std::swap(this->y, rhs.y);
}
};
template <typename T>
struct coord<T,3>
{
using type = T;
T x;
T y;
T z;
public:
coord()
: x(),y(),z() {}
coord(T x_,T y_,T z_)
: x(x_),y(y_),z(z_) {}
template <typename T2>
coord (coord<T2,3> const& rhs)
: x(type(rhs.x)),
y(type(rhs.y)),
z(type(rhs.z)) {}
coord(coord<T,3> && rhs) noexcept
: x(std::move(rhs.x)),
y(std::move(rhs.y)),
z(std::move(rhs.z)) {}
coord<T,3> operator=(coord<T,3> rhs)
{
swap(rhs);
return *this;
}
template <typename T2>
coord<T,3>& operator=(coord<T2,3> const& rhs)
{
coord<T,3> tmp(rhs);
swap(tmp);
return *this;
}
private:
void swap(coord<T,3> & rhs)
{
std::swap(this->x, rhs.x);
std::swap(this->y, rhs.y);
std::swap(this->z, rhs.z);
}
};
using coord2d = coord<double,2>;
using coord2i = coord<int,2>;
}
#endif // MAPNIK_COORD_HPP
<commit_msg>add coord2f type<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_COORD_HPP
#define MAPNIK_COORD_HPP
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/operators.hpp>
#pragma GCC diagnostic pop
namespace mapnik {
template <typename T,int dim>
struct coord {
using type = T;
};
template <typename T>
struct coord<T,2>
: boost::addable<coord<T,2>,
boost::addable2<coord<T,2>,T,
boost::subtractable<coord<T,2>,
boost::subtractable2<coord<T,2>,T,
boost::dividable2<coord<T,2>, T,
boost::multipliable2<coord<T,2>, T > > > > > >
{
using type = T;
T x;
T y;
public:
coord()
: x(),y() {}
coord(T x_,T y_)
: x(x_),y(y_) {}
coord(coord<T,2> const& rhs)
: x(rhs.x),
y(rhs.y) {}
template <typename T2>
coord (coord<T2,2> const& rhs)
: x(type(rhs.x)),
y(type(rhs.y)) {}
coord(coord<T,2> && rhs) noexcept
: x(std::move(rhs.x)),
y(std::move(rhs.y)) {}
coord<T,2>& operator=(coord<T,2> rhs)
{
swap(rhs);
return *this;
}
template <typename T2>
coord<T,2>& operator=(const coord<T2,2>& rhs)
{
coord<T,2> tmp(rhs);
swap(rhs);
return *this;
}
template <typename T2>
bool operator==(coord<T2,2> const& rhs)
{
return x == rhs.x && y == rhs.y;
}
coord<T,2>& operator+=(coord<T,2> const& rhs)
{
x+=rhs.x;
y+=rhs.y;
return *this;
}
coord<T,2>& operator+=(T rhs)
{
x+=rhs;
y+=rhs;
return *this;
}
coord<T,2>& operator-=(coord<T,2> const& rhs)
{
x-=rhs.x;
y-=rhs.y;
return *this;
}
coord<T,2>& operator-=(T rhs)
{
x-=rhs;
y-=rhs;
return *this;
}
coord<T,2>& operator*=(T t)
{
x*=t;
y*=t;
return *this;
}
coord<T,2>& operator/=(T t)
{
x/=t;
y/=t;
return *this;
}
private:
void swap(coord<T,2> & rhs)
{
std::swap(this->x, rhs.x);
std::swap(this->y, rhs.y);
}
};
template <typename T>
struct coord<T,3>
{
using type = T;
T x;
T y;
T z;
public:
coord()
: x(),y(),z() {}
coord(T x_,T y_,T z_)
: x(x_),y(y_),z(z_) {}
template <typename T2>
coord (coord<T2,3> const& rhs)
: x(type(rhs.x)),
y(type(rhs.y)),
z(type(rhs.z)) {}
coord(coord<T,3> && rhs) noexcept
: x(std::move(rhs.x)),
y(std::move(rhs.y)),
z(std::move(rhs.z)) {}
coord<T,3> operator=(coord<T,3> rhs)
{
swap(rhs);
return *this;
}
template <typename T2>
coord<T,3>& operator=(coord<T2,3> const& rhs)
{
coord<T,3> tmp(rhs);
swap(tmp);
return *this;
}
private:
void swap(coord<T,3> & rhs)
{
std::swap(this->x, rhs.x);
std::swap(this->y, rhs.y);
std::swap(this->z, rhs.z);
}
};
using coord2d = coord<double,2>;
using coord2f = coord<float,2>;
using coord2i = coord<int,2>;
}
#endif // MAPNIK_COORD_HPP
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_OPTIONALBROADCAST_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_OPTIONALBROADCAST_HPP
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/as_operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/is_valid_expression.hpp>
#include <limits>
#include <string>
#include <type_traits>
#include <set>
#include <utility>
namespace stan {
namespace math {
/**
* Represents an optional broadcasting operation in kernel generator
* expressions.
* @tparam T type of argument
* @tparam Colwise whether to broadcast colwise
* @tparam Rowwise whether to broadcast rowwise
*/
template <typename T, bool Colwise, bool Rowwise>
class optional_broadcast_
: public operation_cl<optional_broadcast_<T, Colwise, Rowwise>,
typename std::remove_reference_t<T>::Scalar, T> {
public:
using Scalar = typename std::remove_reference_t<T>::Scalar;
using base
= operation_cl<optional_broadcast_<T, Colwise, Rowwise>, Scalar, T>;
using base::var_name;
/**
* Constructor
* @param a expression
*/
explicit optional_broadcast_(T&& a) : base(std::forward<T>(a)) {}
/**
* Creates a deep copy of this expression.
* @return copy of \c *this
*/
inline auto deep_copy() {
auto&& arg_copy = this->template get_arg<0>().deep_copy();
return optional_broadcast_<std::remove_reference_t<decltype(arg_copy)>,
Colwise, Rowwise>{std::move(arg_copy)};
}
/**
* generates kernel code for this and nested expressions.
* @param[in,out] generated set of already generated operations
* @param ng name generator for this kernel
* @param row_idx_name row index variable name
* @param col_idx_name column index variable name
* @return part of kernel with code for this and nested expressions
*/
inline kernel_parts generate(const std::string& row_idx_name,
const std::string& col_idx_name,
const std::string& var_name_arg) const {
kernel_parts res;
res.body
+= type_str<Scalar>() + " " + var_name + " = " + var_name_arg + ";\n";
if (Colwise) {
res.args += "int " + var_name + "is_multirow, ";
}
if (Rowwise) {
res.args += "int " + var_name + "is_multicol, ";
}
return res;
}
/**
* Sets index/indices along broadcasted dimmension(s) to 0.
* @param[in, out] row_idx_name row index
* @param[in, out] col_idx_name column index
*/
inline void modify_argument_indices(std::string& row_idx_name,
std::string& col_idx_name) const {
if (Colwise) {
row_idx_name = "(" + row_idx_name + " * " + var_name + "is_multirow)";
}
if (Rowwise) {
col_idx_name = "(" + col_idx_name + " * " + var_name + "is_multicol)";
}
}
/**
* Sets kernel arguments for this and nested expressions.
* @param[in,out] generated set of expressions that already set their kernel
* arguments
* @param kernel kernel to set arguments on
* @param[in,out] arg_num consecutive number of the first argument to set.
* This is incremented for each argument set by this function.
*/
inline void set_args(std::set<const operation_cl_base*>& generated,
cl::Kernel& kernel, int& arg_num) const {
if (generated.count(this) == 0) {
generated.insert(this);
this->template get_arg<0>().set_args(generated, kernel, arg_num);
if (Colwise) {
kernel.setArg(arg_num++, static_cast<int>(
this->template get_arg<0>().rows() != 1));
}
if (Rowwise) {
kernel.setArg(arg_num++, static_cast<int>(
this->template get_arg<0>().cols() != 1));
}
}
}
/**
* Number of rows of a matrix that would be the result of evaluating this
* expression.
* @return number of rows
*/
inline int rows() const {
return Colwise && this->template get_arg<0>().rows() == 1
? base::dynamic
: this->template get_arg<0>().rows();
}
/**
* Number of columns of a matrix that would be the result of evaluating this
* expression.
* @return number of columns
*/
inline int cols() const {
return Rowwise && this->template get_arg<0>().cols() == 1
? base::dynamic
: this->template get_arg<0>().cols();
}
/**
* View of a matrix that would be the result of evaluating this expression.
* @return view
*/
inline matrix_cl_view view() const {
matrix_cl_view view = this->template get_arg<0>().view();
if (Colwise && this->template get_arg<0>().rows() == 1) {
view = either(view, matrix_cl_view::Lower);
}
if (Rowwise && this->template get_arg<0>().cols() == 1) {
view = either(view, matrix_cl_view::Upper);
}
return view;
}
/**
* Determine index of bottom diagonal written.
* @return index of bottom diagonal
*/
inline int bottom_diagonal() const {
if (Colwise && this->template get_arg<0>().rows() == 1) {
return std::numeric_limits<int>::min();
} else {
return this->template get_arg<0>().bottom_diagonal();
}
}
/**
* Determine index of top diagonal written.
* @return index of top diagonal
*/
inline int top_diagonal() const {
if (Rowwise && this->template get_arg<0>().cols() == 1) {
return std::numeric_limits<int>::max();
} else {
return this->template get_arg<0>().top_diagonal();
}
}
};
/**
* Brodcast an expression in specified dimension(s) if the size along that
* dimmension equals to 1. In that case further
* expressions can use this expression as if had any size in the broadcast
* dimension, repeating the values.
*
* Broadcasting evaluates argument expression multiple times. For performance
* reasons don't broadcast slow operations. Instead evaluate them in a separate
* kernel.
* @tparam Colwise whether to broadcast colwise
* @tparam Rowwise whether to broadcast rowwise
* @tparam T type of input expression
* @param a input expression
* @return broadcast expression
*/
template <bool Colwise, bool Rowwise, typename T,
typename = require_all_valid_expressions_and_none_scalar_t<T>>
inline optional_broadcast_<as_operation_cl_t<T>, Colwise, Rowwise>
optional_broadcast(T&& a) {
auto&& a_operation = as_operation_cl(std::forward<T>(a)).deep_copy();
return optional_broadcast_<as_operation_cl_t<T>, Colwise, Rowwise>(
std::move(a_operation));
}
/**
* Broadcast an expression in rowwise dimmension if the number of columns equals
* to 1. In that case further expressions can use this expression as if had any
* number of columns, repeating the values.
*
* Broadcasting evaluates argument expression multiple times. For performance
* reasons don't broadcast slow operations. Instead evaluate them in a separate
* kernel.
* @tparam T type of input expression
* @param a input expression
* @return broadcast expression
*/
template <typename T,
typename = require_all_valid_expressions_and_none_scalar_t<T>>
inline auto rowwise_optional_broadcast(T&& a) {
return optional_broadcast<false, true>(std::forward<T>(a));
}
/**
* Broadcast an expression in colwise dimmension if the number of rows equals
* to 1. In that case further expressions can use this expression as if had any
* number of rows, repeating the values.
*
* Broadcasting evaluates argument expression multiple times. For performance
* reasons don't broadcast slow operations. Instead evaluate them in a separate
* kernel.
* @tparam T type of input expression
* @param a input expression
* @return broadcast expression
*/
template <typename T,
typename = require_all_valid_expressions_and_none_scalar_t<T>>
inline auto colwise_optional_broadcast(T&& a) {
return optional_broadcast<true, false>(std::forward<T>(a));
}
} // namespace math
} // namespace stan
#endif
<commit_msg>added missing ifdef<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_OPTIONALBROADCAST_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_OPTIONALBROADCAST_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/as_operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/is_valid_expression.hpp>
#include <limits>
#include <string>
#include <type_traits>
#include <set>
#include <utility>
namespace stan {
namespace math {
/**
* Represents an optional broadcasting operation in kernel generator
* expressions.
* @tparam T type of argument
* @tparam Colwise whether to broadcast colwise
* @tparam Rowwise whether to broadcast rowwise
*/
template <typename T, bool Colwise, bool Rowwise>
class optional_broadcast_
: public operation_cl<optional_broadcast_<T, Colwise, Rowwise>,
typename std::remove_reference_t<T>::Scalar, T> {
public:
using Scalar = typename std::remove_reference_t<T>::Scalar;
using base
= operation_cl<optional_broadcast_<T, Colwise, Rowwise>, Scalar, T>;
using base::var_name;
/**
* Constructor
* @param a expression
*/
explicit optional_broadcast_(T&& a) : base(std::forward<T>(a)) {}
/**
* Creates a deep copy of this expression.
* @return copy of \c *this
*/
inline auto deep_copy() {
auto&& arg_copy = this->template get_arg<0>().deep_copy();
return optional_broadcast_<std::remove_reference_t<decltype(arg_copy)>,
Colwise, Rowwise>{std::move(arg_copy)};
}
/**
* generates kernel code for this and nested expressions.
* @param[in,out] generated set of already generated operations
* @param ng name generator for this kernel
* @param row_idx_name row index variable name
* @param col_idx_name column index variable name
* @return part of kernel with code for this and nested expressions
*/
inline kernel_parts generate(const std::string& row_idx_name,
const std::string& col_idx_name,
const std::string& var_name_arg) const {
kernel_parts res;
res.body
+= type_str<Scalar>() + " " + var_name + " = " + var_name_arg + ";\n";
if (Colwise) {
res.args += "int " + var_name + "is_multirow, ";
}
if (Rowwise) {
res.args += "int " + var_name + "is_multicol, ";
}
return res;
}
/**
* Sets index/indices along broadcasted dimmension(s) to 0.
* @param[in, out] row_idx_name row index
* @param[in, out] col_idx_name column index
*/
inline void modify_argument_indices(std::string& row_idx_name,
std::string& col_idx_name) const {
if (Colwise) {
row_idx_name = "(" + row_idx_name + " * " + var_name + "is_multirow)";
}
if (Rowwise) {
col_idx_name = "(" + col_idx_name + " * " + var_name + "is_multicol)";
}
}
/**
* Sets kernel arguments for this and nested expressions.
* @param[in,out] generated set of expressions that already set their kernel
* arguments
* @param kernel kernel to set arguments on
* @param[in,out] arg_num consecutive number of the first argument to set.
* This is incremented for each argument set by this function.
*/
inline void set_args(std::set<const operation_cl_base*>& generated,
cl::Kernel& kernel, int& arg_num) const {
if (generated.count(this) == 0) {
generated.insert(this);
this->template get_arg<0>().set_args(generated, kernel, arg_num);
if (Colwise) {
kernel.setArg(arg_num++, static_cast<int>(
this->template get_arg<0>().rows() != 1));
}
if (Rowwise) {
kernel.setArg(arg_num++, static_cast<int>(
this->template get_arg<0>().cols() != 1));
}
}
}
/**
* Number of rows of a matrix that would be the result of evaluating this
* expression.
* @return number of rows
*/
inline int rows() const {
return Colwise && this->template get_arg<0>().rows() == 1
? base::dynamic
: this->template get_arg<0>().rows();
}
/**
* Number of columns of a matrix that would be the result of evaluating this
* expression.
* @return number of columns
*/
inline int cols() const {
return Rowwise && this->template get_arg<0>().cols() == 1
? base::dynamic
: this->template get_arg<0>().cols();
}
/**
* View of a matrix that would be the result of evaluating this expression.
* @return view
*/
inline matrix_cl_view view() const {
matrix_cl_view view = this->template get_arg<0>().view();
if (Colwise && this->template get_arg<0>().rows() == 1) {
view = either(view, matrix_cl_view::Lower);
}
if (Rowwise && this->template get_arg<0>().cols() == 1) {
view = either(view, matrix_cl_view::Upper);
}
return view;
}
/**
* Determine index of bottom diagonal written.
* @return index of bottom diagonal
*/
inline int bottom_diagonal() const {
if (Colwise && this->template get_arg<0>().rows() == 1) {
return std::numeric_limits<int>::min();
} else {
return this->template get_arg<0>().bottom_diagonal();
}
}
/**
* Determine index of top diagonal written.
* @return index of top diagonal
*/
inline int top_diagonal() const {
if (Rowwise && this->template get_arg<0>().cols() == 1) {
return std::numeric_limits<int>::max();
} else {
return this->template get_arg<0>().top_diagonal();
}
}
};
/**
* Brodcast an expression in specified dimension(s) if the size along that
* dimmension equals to 1. In that case further
* expressions can use this expression as if had any size in the broadcast
* dimension, repeating the values.
*
* Broadcasting evaluates argument expression multiple times. For performance
* reasons don't broadcast slow operations. Instead evaluate them in a separate
* kernel.
* @tparam Colwise whether to broadcast colwise
* @tparam Rowwise whether to broadcast rowwise
* @tparam T type of input expression
* @param a input expression
* @return broadcast expression
*/
template <bool Colwise, bool Rowwise, typename T,
typename = require_all_valid_expressions_and_none_scalar_t<T>>
inline optional_broadcast_<as_operation_cl_t<T>, Colwise, Rowwise>
optional_broadcast(T&& a) {
auto&& a_operation = as_operation_cl(std::forward<T>(a)).deep_copy();
return optional_broadcast_<as_operation_cl_t<T>, Colwise, Rowwise>(
std::move(a_operation));
}
/**
* Broadcast an expression in rowwise dimmension if the number of columns equals
* to 1. In that case further expressions can use this expression as if had any
* number of columns, repeating the values.
*
* Broadcasting evaluates argument expression multiple times. For performance
* reasons don't broadcast slow operations. Instead evaluate them in a separate
* kernel.
* @tparam T type of input expression
* @param a input expression
* @return broadcast expression
*/
template <typename T,
typename = require_all_valid_expressions_and_none_scalar_t<T>>
inline auto rowwise_optional_broadcast(T&& a) {
return optional_broadcast<false, true>(std::forward<T>(a));
}
/**
* Broadcast an expression in colwise dimmension if the number of rows equals
* to 1. In that case further expressions can use this expression as if had any
* number of rows, repeating the values.
*
* Broadcasting evaluates argument expression multiple times. For performance
* reasons don't broadcast slow operations. Instead evaluate them in a separate
* kernel.
* @tparam T type of input expression
* @param a input expression
* @return broadcast expression
*/
template <typename T,
typename = require_all_valid_expressions_and_none_scalar_t<T>>
inline auto colwise_optional_broadcast(T&& a) {
return optional_broadcast<true, false>(std::forward<T>(a));
}
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|>
|
<commit_before>/**
Copyright (c) 2016 Ryan Porter
*/
/*
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
angularNodes
Maya math nodes operate on double values. This means that Maya must create a
unit conversion node when connecting to or from a doubleAngle value, such as
the rotate attributes of a transform. This quickly pollutes a scene with these
unitConversion nodes, which have a negative measurable effect on rig performance.
These nodes operation on doubleAngle values as inputs and outputs, eliminating
the need for a unit conversion node in most cases.
*/
#include "n_angleBinaryOp.h"
#include "n_angleMultiOp.h"
#include "n_angleScalarOp.h"
#include "n_angleUnaryOp.h"
#include "n_clampAngle.h"
#include <maya/MFnPlugin.h>
#include <maya/MTypeId.h>
#include <maya/MString.h>
const char* kAUTHOR = "Ryan Porter";
const char* kVERSION = "1.0.0";
const char* kREQUIRED_API_VERSION = "Any";
MString ClampAngleNode::kNODE_NAME = "clampAngle";
MString AngleBinaryOpNode::kNODE_NAME = "angleBinaryOp";
MString AngleMultiOpNode::kNODE_NAME = "angleMultiOp";
MString AngleScalarOpNode::kNODE_NAME = "angleScalarOp";
MString AngleUnaryOpNode::kNODE_NAME = "angleUnaryOp";
MTypeId ClampAngleNode::kNODE_ID = 0x00126b11;
MTypeId AngleBinaryOpNode::kNODE_ID = 0x00126b12;
MTypeId AngleMultiOpNode::kNODE_ID = 0x00126b13;
MTypeId AngleScalarOpNode::kNODE_ID = 0x00126b14;
MTypeId AngleUnaryOpNode::kNODE_ID = 0x00126b15;
#define REGISTER_NODE(NODE) \
status = fnPlugin.registerNode( \
NODE::kNODE_NAME, \
NODE::kNODE_ID, \
NODE::creator, \
NODE::initialize \
); \
CHECK_MSTATUS_AND_RETURN_IT(status); \
#define DEREGISTER_NODE(NODE) \
status = fnPlugin.deregisterNode( \
NODE::kNODE_ID \
); \
CHECK_MSTATUS_AND_RETURN_IT(status); \
MStatus initializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
REGISTER_NODE(AngleMultiOpNode);
REGISTER_NODE(AngleBinaryOpNode);
REGISTER_NODE(AngleScalarOpNode);
REGISTER_NODE(AngleUnaryOpNode);
REGISTER_NODE(ClampAngleNode);
return MS::kSuccess;
}
MStatus uninitializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
DEREGISTER_NODE(AngleMultiOpNode);
DEREGISTER_NODE(AngleBinaryOpNode);
DEREGISTER_NODE(AngleScalarOpNode);
DEREGISTER_NODE(AngleUnaryOpNode);
DEREGISTER_NODE(ClampAngleNode);
return MS::kSuccess;
}
<commit_msg>Change nodeID for clampAngle node to limit overlap with arrayNodes<commit_after>/**
Copyright (c) 2016 Ryan Porter
*/
/*
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
angularNodes
Maya math nodes operate on double values. This means that Maya must create a
unit conversion node when connecting to or from a doubleAngle value, such as
the rotate attributes of a transform. This quickly pollutes a scene with these
unitConversion nodes, which have a negative measurable effect on rig performance.
These nodes operation on doubleAngle values as inputs and outputs, eliminating
the need for a unit conversion node in most cases.
*/
#include "n_angleBinaryOp.h"
#include "n_angleMultiOp.h"
#include "n_angleScalarOp.h"
#include "n_angleUnaryOp.h"
#include "n_clampAngle.h"
#include <maya/MFnPlugin.h>
#include <maya/MTypeId.h>
#include <maya/MString.h>
const char* kAUTHOR = "Ryan Porter";
const char* kVERSION = "1.0.0";
const char* kREQUIRED_API_VERSION = "Any";
MString ClampAngleNode::kNODE_NAME = "clampAngle";
MString AngleBinaryOpNode::kNODE_NAME = "angleBinaryOp";
MString AngleMultiOpNode::kNODE_NAME = "angleMultiOp";
MString AngleScalarOpNode::kNODE_NAME = "angleScalarOp";
MString AngleUnaryOpNode::kNODE_NAME = "angleUnaryOp";
MTypeId AngleBinaryOpNode::kNODE_ID = 0x00126b12;
MTypeId AngleMultiOpNode::kNODE_ID = 0x00126b13;
MTypeId AngleScalarOpNode::kNODE_ID = 0x00126b14;
MTypeId AngleUnaryOpNode::kNODE_ID = 0x00126b15;
MTypeId ClampAngleNode::kNODE_ID = 0x00126b16;
#define REGISTER_NODE(NODE) \
status = fnPlugin.registerNode( \
NODE::kNODE_NAME, \
NODE::kNODE_ID, \
NODE::creator, \
NODE::initialize \
); \
CHECK_MSTATUS_AND_RETURN_IT(status); \
#define DEREGISTER_NODE(NODE) \
status = fnPlugin.deregisterNode( \
NODE::kNODE_ID \
); \
CHECK_MSTATUS_AND_RETURN_IT(status); \
MStatus initializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
REGISTER_NODE(AngleMultiOpNode);
REGISTER_NODE(AngleBinaryOpNode);
REGISTER_NODE(AngleScalarOpNode);
REGISTER_NODE(AngleUnaryOpNode);
REGISTER_NODE(ClampAngleNode);
return MS::kSuccess;
}
MStatus uninitializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
DEREGISTER_NODE(AngleMultiOpNode);
DEREGISTER_NODE(AngleBinaryOpNode);
DEREGISTER_NODE(AngleScalarOpNode);
DEREGISTER_NODE(AngleUnaryOpNode);
DEREGISTER_NODE(ClampAngleNode);
return MS::kSuccess;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/debug.hpp>
#include <mapnik/image_reader.hpp>
#include <mapnik/noncopyable.hpp>
extern "C"
{
#include <png.h>
}
#include <boost/scoped_array.hpp>
namespace mapnik
{
class png_reader : public image_reader
{
struct png_file_guard
{
png_file_guard(FILE * fd)
: fd_(fd) {}
~png_file_guard()
{
if (fd_) fclose(fd_);
}
FILE * fd_;
};
private:
std::string fileName_;
unsigned width_;
unsigned height_;
int bit_depth_;
int color_type_;
public:
explicit png_reader(std::string const& fileName);
~png_reader();
unsigned width() const;
unsigned height() const;
bool premultiplied_alpha() const { return false; } //http://www.libpng.org/pub/png/spec/1.1/PNG-Rationale.html
void read(unsigned x,unsigned y,image_data_32& image);
private:
void init();
};
namespace
{
image_reader* create_png_reader(std::string const& file)
{
return new png_reader(file);
}
const bool registered = register_image_reader("png",create_png_reader);
}
png_reader::png_reader(std::string const& fileName)
: fileName_(fileName),
width_(0),
height_(0),
bit_depth_(0),
color_type_(0)
{
init();
}
png_reader::~png_reader() {}
void user_error_fn(png_structp png_ptr, png_const_charp error_msg)
{
throw image_reader_exception("failed to read invalid png");
}
void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)
{
MAPNIK_LOG_DEBUG(png_reader) << "libpng warning: '" << warning_msg << "'";
}
static void
png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_size_t check;
check = (png_size_t)fread(data, (png_size_t)1, length,
(FILE *)png_get_io_ptr(png_ptr));
if (check != length)
{
png_error(png_ptr, "Read Error");
}
}
void png_reader::init()
{
FILE *fp=fopen(fileName_.c_str(),"rb");
if (!fp) throw image_reader_exception("cannot open image file "+fileName_);
png_file_guard guard(fp);
png_byte header[8];
memset(header,0,8);
if ( fread(header,1,8,fp) != 8)
{
throw image_reader_exception("Could not read " + fileName_);
}
int is_png=!png_sig_cmp(header,0,8);
if (!is_png)
{
throw image_reader_exception(fileName_ + " is not a png file");
}
png_structp png_ptr = png_create_read_struct
(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr)
{
throw image_reader_exception("failed to allocate png_ptr");
}
// catch errors in a custom way to avoid the need for setjmp
png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);
png_infop info_ptr;
try
{
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_read_struct(&png_ptr,0,0);
throw image_reader_exception("failed to create info_ptr");
}
}
catch (std::exception const& /*ex*/)
{
png_destroy_read_struct(&png_ptr,0,0);
throw;
}
png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);
png_set_sig_bytes(png_ptr,8);
png_read_info(png_ptr, info_ptr);
png_uint_32 width, height;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth_, &color_type_,0,0,0);
width_=width;
height_=height;
MAPNIK_LOG_DEBUG(png_reader) << "png_reader: bit_depth=" << bit_depth_ << ",color_type=" << color_type_;
png_destroy_read_struct(&png_ptr,&info_ptr,0);
}
unsigned png_reader::width() const
{
return width_;
}
unsigned png_reader::height() const
{
return height_;
}
void png_reader::read(unsigned x0, unsigned y0,image_data_32& image)
{
FILE *fp=fopen(fileName_.c_str(),"rb");
if (!fp) throw image_reader_exception("cannot open image file "+fileName_);
png_file_guard guard(fp);
png_structp png_ptr = png_create_read_struct
(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr)
{
throw image_reader_exception("failed to allocate png_ptr");
}
// catch errors in a custom way to avoid the need for setjmp
png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);
png_infop info_ptr;
try
{
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_read_struct(&png_ptr,0,0);
throw image_reader_exception("failed to create info_ptr");
}
}
catch (std::exception const& /*ex*/)
{
png_destroy_read_struct(&png_ptr,0,0);
throw;
}
png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);
png_read_info(png_ptr, info_ptr);
if (color_type_ == PNG_COLOR_TYPE_PALETTE)
png_set_expand(png_ptr);
if (color_type_ == PNG_COLOR_TYPE_GRAY && bit_depth_ < 8)
png_set_expand(png_ptr);
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_expand(png_ptr);
if (bit_depth_ == 16)
png_set_strip_16(png_ptr);
if (color_type_ == PNG_COLOR_TYPE_GRAY ||
color_type_ == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
// quick hack -- only work in >=libpng 1.2.7
png_set_add_alpha(png_ptr,0xff,PNG_FILLER_AFTER); //rgba
double gamma;
if (png_get_gAMA(png_ptr, info_ptr, &gamma))
png_set_gamma(png_ptr, 2.2, gamma);
if (x0 == 0 && y0 == 0 && image.width() >= width_ && image.height() >= height_)
{
if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7)
{
png_set_interlace_handling(png_ptr); // FIXME: libpng bug?
// according to docs png_read_image
// "..automatically handles interlacing,
// so you don't need to call png_set_interlace_handling()"
}
png_read_update_info(png_ptr, info_ptr);
// we can read whole image at once
// alloc row pointers
boost::scoped_array<png_byte*> rows(new png_bytep[height_]);
for (unsigned i=0; i<height_; ++i)
rows[i] = (png_bytep)image.getRow(i);
png_read_image(png_ptr, rows.get());
}
else
{
png_read_update_info(png_ptr, info_ptr);
unsigned w=std::min(unsigned(image.width()),width_ - x0);
unsigned h=std::min(unsigned(image.height()),height_ - y0);
unsigned rowbytes=png_get_rowbytes(png_ptr, info_ptr);
boost::scoped_array<png_byte> row(new png_byte[rowbytes]);
//START read image rows
for (unsigned i = 0;i < height_; ++i)
{
png_read_row(png_ptr,row.get(),0);
if (i >= y0 && i < (y0 + h))
{
image.setRow(i-y0,reinterpret_cast<unsigned*>(&row[x0 * 4]),w);
}
}
//END
}
png_read_end(png_ptr,0);
png_destroy_read_struct(&png_ptr, &info_ptr,0);
}
}
<commit_msg>avoid png_struct leak - refs #1783<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <mapnik/debug.hpp>
#include <mapnik/image_reader.hpp>
#include <mapnik/noncopyable.hpp>
extern "C"
{
#include <png.h>
}
#include <boost/scoped_array.hpp>
namespace mapnik
{
class png_reader : public image_reader
{
struct png_file_guard
{
png_file_guard(FILE * fd)
: fd_(fd) {}
~png_file_guard()
{
if (fd_) fclose(fd_);
}
FILE * fd_;
};
struct png_struct_guard
{
png_struct_guard(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
: p_(png_ptr_ptr),
i_(info_ptr_ptr) {}
~png_struct_guard()
{
png_destroy_read_struct(p_,i_,0);
}
png_structpp p_;
png_infopp i_;
};
private:
std::string fileName_;
unsigned width_;
unsigned height_;
int bit_depth_;
int color_type_;
public:
explicit png_reader(std::string const& fileName);
~png_reader();
unsigned width() const;
unsigned height() const;
bool premultiplied_alpha() const { return false; } //http://www.libpng.org/pub/png/spec/1.1/PNG-Rationale.html
void read(unsigned x,unsigned y,image_data_32& image);
private:
void init();
};
namespace
{
image_reader* create_png_reader(std::string const& file)
{
return new png_reader(file);
}
const bool registered = register_image_reader("png",create_png_reader);
}
png_reader::png_reader(std::string const& fileName)
: fileName_(fileName),
width_(0),
height_(0),
bit_depth_(0),
color_type_(0)
{
init();
}
png_reader::~png_reader() {}
void user_error_fn(png_structp png_ptr, png_const_charp error_msg)
{
throw image_reader_exception("failed to read invalid png");
}
void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)
{
MAPNIK_LOG_DEBUG(png_reader) << "libpng warning: '" << warning_msg << "'";
}
static void
png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_size_t check;
check = (png_size_t)fread(data, (png_size_t)1, length,
(FILE *)png_get_io_ptr(png_ptr));
if (check != length)
{
png_error(png_ptr, "Read Error");
}
}
void png_reader::init()
{
FILE *fp=fopen(fileName_.c_str(),"rb");
if (!fp) throw image_reader_exception("cannot open image file "+fileName_);
png_file_guard guard(fp);
png_byte header[8];
memset(header,0,8);
if ( fread(header,1,8,fp) != 8)
{
throw image_reader_exception("Could not read " + fileName_);
}
int is_png=!png_sig_cmp(header,0,8);
if (!is_png)
{
throw image_reader_exception(fileName_ + " is not a png file");
}
png_structp png_ptr = png_create_read_struct
(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr)
{
throw image_reader_exception("failed to allocate png_ptr");
}
// catch errors in a custom way to avoid the need for setjmp
png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);
png_infop info_ptr;
png_struct_guard sguard(&png_ptr,&info_ptr);
info_ptr = png_create_info_struct(png_ptr);
png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);
png_set_sig_bytes(png_ptr,8);
png_read_info(png_ptr, info_ptr);
png_uint_32 width, height;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth_, &color_type_,0,0,0);
width_=width;
height_=height;
MAPNIK_LOG_DEBUG(png_reader) << "png_reader: bit_depth=" << bit_depth_ << ",color_type=" << color_type_;
}
unsigned png_reader::width() const
{
return width_;
}
unsigned png_reader::height() const
{
return height_;
}
void png_reader::read(unsigned x0, unsigned y0,image_data_32& image)
{
FILE *fp=fopen(fileName_.c_str(),"rb");
if (!fp) throw image_reader_exception("cannot open image file "+fileName_);
png_file_guard guard(fp);
png_structp png_ptr = png_create_read_struct
(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr)
{
throw image_reader_exception("failed to allocate png_ptr");
}
// catch errors in a custom way to avoid the need for setjmp
png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);
png_infop info_ptr;
png_struct_guard sguard(&png_ptr,&info_ptr);
info_ptr = png_create_info_struct(png_ptr);
png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);
png_read_info(png_ptr, info_ptr);
if (color_type_ == PNG_COLOR_TYPE_PALETTE)
png_set_expand(png_ptr);
if (color_type_ == PNG_COLOR_TYPE_GRAY && bit_depth_ < 8)
png_set_expand(png_ptr);
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_expand(png_ptr);
if (bit_depth_ == 16)
png_set_strip_16(png_ptr);
if (color_type_ == PNG_COLOR_TYPE_GRAY ||
color_type_ == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
// quick hack -- only work in >=libpng 1.2.7
png_set_add_alpha(png_ptr,0xff,PNG_FILLER_AFTER); //rgba
double gamma;
if (png_get_gAMA(png_ptr, info_ptr, &gamma))
png_set_gamma(png_ptr, 2.2, gamma);
if (x0 == 0 && y0 == 0 && image.width() >= width_ && image.height() >= height_)
{
if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7)
{
png_set_interlace_handling(png_ptr); // FIXME: libpng bug?
// according to docs png_read_image
// "..automatically handles interlacing,
// so you don't need to call png_set_interlace_handling()"
}
png_read_update_info(png_ptr, info_ptr);
// we can read whole image at once
// alloc row pointers
boost::scoped_array<png_byte*> rows(new png_bytep[height_]);
for (unsigned i=0; i<height_; ++i)
rows[i] = (png_bytep)image.getRow(i);
png_read_image(png_ptr, rows.get());
}
else
{
png_read_update_info(png_ptr, info_ptr);
unsigned w=std::min(unsigned(image.width()),width_ - x0);
unsigned h=std::min(unsigned(image.height()),height_ - y0);
unsigned rowbytes=png_get_rowbytes(png_ptr, info_ptr);
boost::scoped_array<png_byte> row(new png_byte[rowbytes]);
//START read image rows
for (unsigned i = 0;i < height_; ++i)
{
png_read_row(png_ptr,row.get(),0);
if (i >= y0 && i < (y0 + h))
{
image.setRow(i-y0,reinterpret_cast<unsigned*>(&row[x0 * 4]),w);
}
}
//END
}
png_read_end(png_ptr,0);
png_destroy_read_struct(&png_ptr, &info_ptr,0);
}
}
<|endoftext|>
|
<commit_before>/*
* ============================================================================
*
* Filename: qc-qualtrim.cc
* Description: Trim low qualtiy sequences via various methods
* License: GPLv3+
* Author: Kevin Murray, spam@kdmurray.id.au
*
* ============================================================================
*/
#include <yaml-cpp/yaml.h>
#include "qc-qualtrim.hh"
namespace qcpp
{
WindowedQualTrim::
WindowedQualTrim(const std::string &name, int8_t phred_cutoff,
int8_t phred_offset, size_t len_cutoff, size_t window_size):
ReadProcessor(name),
_num_reads_trimmed(0),
_num_reads_dropped(0),
_phred_cutoff(phred_cutoff),
_phred_offset(phred_offset),
_len_cutoff(len_cutoff),
_window_size(window_size)
{
}
WindowedQualTrim::
WindowedQualTrim(const std::string &name, int8_t phred_cutoff,
int8_t phred_offset, size_t len_cutoff):
WindowedQualTrim(name, phred_offset, phred_cutoff, len_cutoff, 0)
{
}
void
WindowedQualTrim::
process_read(Read &the_read)
{
int64_t win_sum = 0;
size_t win_start = 0;
size_t win_size = 0;
float win_avg = 0.0;
size_t read_len = the_read.size();
size_t first_to_keep = 0;
size_t last_to_keep = read_len - 1;
bool need_trimming = false;
_num_reads++;
// Throw out reads which are already too short
if (read_len < _len_cutoff) {
_num_reads_dropped++;
return;
}
// Caclulate window size
if (_window_size > 0) {
// Use the size we've been told to
win_size = _window_size;
} else if (read_len > 20) {
// Use 10% of the read length
win_size = read_len * 0.1;
} else {
// Read too short, use whole read
win_size = the_read.size();
}
// Trim until the first base which is of acceptable quality
while (_qual_of_base(the_read, win_start) < _phred_cutoff) {
need_trimming = true;
win_start++;
}
first_to_keep = win_start;
// pre-sum the first window
for (size_t i = win_start; i < win_size; i++) {
win_sum += _qual_of_base(the_read, i);
}
// Trim with windows
for (; win_start < read_len - win_size + 1; win_start++) {
win_avg = win_sum / (float)win_size;
// IF the window is below threshold
if (win_avg < _phred_cutoff || win_start >= read_len - win_size) {
last_to_keep = win_start - 1;
while (_qual_of_base(the_read, ++last_to_keep) >= _phred_cutoff);
if (last_to_keep < read_len - 1) {
need_trimming = true;
}
break;
}
win_sum -= _qual_of_base(the_read, win_start);
win_sum += _qual_of_base(the_read, win_start + win_size);
}
if ((last_to_keep - first_to_keep) < _len_cutoff) {
the_read.erase();
_num_reads_dropped++;
} else if (need_trimming) {
if (last_to_keep < read_len - 1) {
the_read.erase(last_to_keep);
}
if (first_to_keep > 0) {
the_read.erase(0, first_to_keep);
}
_num_reads_trimmed++;
}
}
void
WindowedQualTrim::
process_read_pair(ReadPair &the_read_pair)
{
process_read(the_read_pair.first);
process_read(the_read_pair.second);
}
std::string
WindowedQualTrim::
report()
{
std::ostringstream ss;
YAML::Emitter yml;
float percent_trimmed = (_num_reads_trimmed * 2 / (float) _num_reads ) * 100;
float percent_dropped = (_num_reads_dropped * 2 / (float) _num_reads ) * 100;
yml << YAML::BeginSeq;
yml << YAML::BeginMap;
yml << YAML::Key << "WindowedQualTrim"
<< YAML::Value
<< YAML::BeginMap
<< YAML::Key << "name"
<< YAML::Value << _name
<< YAML::Key << "parameters"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "phred_cutoff"
<< YAML::Value << _phred_cutoff
<< YAML::Key << "phred_offset"
<< YAML::Value << _phred_offset
<< YAML::Key << "len_cutoff"
<< YAML::Value << _len_cutoff
<< YAML::Key << "window_size"
<< YAML::Value << _window_size
<< YAML::EndMap
<< YAML::Key << "output"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "num_reads"
<< YAML::Value << _num_reads
<< YAML::Key << "num_trimmed"
<< YAML::Value << (_num_reads_trimmed * 2)
<< YAML::Key << "num_dropped"
<< YAML::Value << (_num_reads_dropped * 2)
<< YAML::Key << "percent_trimmed"
<< YAML::Value << percent_trimmed
<< YAML::Key << "percent_dropped"
<< YAML::Value << percent_dropped
<< YAML::EndMap
<< YAML::EndMap;
yml << YAML::EndMap;
yml << YAML::EndSeq;
ss << yml.c_str() << "\n";
return ss.str();
}
} // end namespace qcpp
<commit_msg>Bugfixes and improvements to qualtrim<commit_after>/*
* ============================================================================
*
* Filename: qc-qualtrim.cc
* Description: Trim low qualtiy sequences via various methods
* License: GPLv3+
* Author: Kevin Murray, spam@kdmurray.id.au
*
* ============================================================================
*/
#include <yaml-cpp/yaml.h>
#include "qc-qualtrim.hh"
namespace qcpp
{
WindowedQualTrim::
WindowedQualTrim(const std::string &name, int8_t phred_cutoff,
int8_t phred_offset, size_t len_cutoff, size_t window_size):
ReadProcessor(name),
_num_reads_trimmed(0),
_num_reads_dropped(0),
_phred_cutoff(phred_cutoff),
_phred_offset(phred_offset),
_len_cutoff(len_cutoff),
_window_size(window_size)
{
}
WindowedQualTrim::
WindowedQualTrim(const std::string &name, int8_t phred_cutoff,
int8_t phred_offset, size_t len_cutoff):
WindowedQualTrim(name, phred_offset, phred_cutoff, len_cutoff, 0)
{
}
void
WindowedQualTrim::
process_read(Read &the_read)
{
int64_t win_sum = 0;
size_t win_start = 0;
size_t win_size = 0;
float win_avg = 0.0;
size_t read_len = the_read.size();
size_t keep_from = 0;
size_t keep_until = 0;
_num_reads++;
// Throw out reads which are already too short
if (read_len < _len_cutoff) {
_num_reads_dropped++;
return;
}
// Caclulate window size
if (_window_size > 0) {
// Use the size we've been told to
win_size = _window_size;
} else if (read_len > 20) {
// Use 10% of the read length
win_size = read_len * 0.1;
} else {
// Read too short, use whole read
win_size = the_read.size();
}
// Trim until the first base which is of acceptable quality
while (_qual_of_base(the_read, win_start) < _phred_cutoff) {
win_start++;
}
keep_from = win_start;
// pre-sum the first window
for (size_t i = win_start; i < win_size; i++) {
win_sum += _qual_of_base(the_read, i);
}
// Trim with windows
for (; win_start < read_len - win_size + 1; win_start += 1) {
keep_until = win_start;
win_avg = win_sum / (float)win_size;
if (win_avg < _phred_cutoff) {
// If the window is below threshold, stop and trim below
break;
}
win_sum -= _qual_of_base(the_read, win_start);
win_sum += _qual_of_base(the_read, win_start + win_size);
}
// Find the last position above the threshold, trim there
while (keep_until < read_len) {
if (_qual_of_base(the_read, keep_until) < _phred_cutoff) {
// Don't increment keep_until, as we should cut at this position
break;
}
keep_until++;
}
size_t new_len = keep_until - keep_from;
if (new_len < _len_cutoff) {
the_read.erase();
_num_reads_dropped++;
return;
}
bool trimmed = false;
if (keep_until < read_len) {
the_read.erase(keep_until);
trimmed = true;
}
if (keep_from > 0) {
the_read.erase(0, keep_from);
trimmed = true;
}
if (trimmed) {
_num_reads_trimmed++;
}
}
void
WindowedQualTrim::
process_read_pair(ReadPair &the_read_pair)
{
process_read(the_read_pair.first);
process_read(the_read_pair.second);
}
std::string
WindowedQualTrim::
report()
{
std::ostringstream ss;
YAML::Emitter yml;
float percent_trimmed = (_num_reads_trimmed * 2 / (float) _num_reads ) * 100;
float percent_dropped = (_num_reads_dropped * 2 / (float) _num_reads ) * 100;
yml << YAML::BeginSeq;
yml << YAML::BeginMap;
yml << YAML::Key << "WindowedQualTrim"
<< YAML::Value
<< YAML::BeginMap
<< YAML::Key << "name"
<< YAML::Value << _name
<< YAML::Key << "parameters"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "phred_cutoff"
<< YAML::Value << _phred_cutoff
<< YAML::Key << "phred_offset"
<< YAML::Value << _phred_offset
<< YAML::Key << "len_cutoff"
<< YAML::Value << _len_cutoff
<< YAML::Key << "window_size"
<< YAML::Value << _window_size
<< YAML::EndMap
<< YAML::Key << "output"
<< YAML::Value << YAML::BeginMap
<< YAML::Key << "num_reads"
<< YAML::Value << _num_reads
<< YAML::Key << "num_trimmed"
<< YAML::Value << (_num_reads_trimmed * 2)
<< YAML::Key << "num_dropped"
<< YAML::Value << (_num_reads_dropped * 2)
<< YAML::Key << "percent_trimmed"
<< YAML::Value << percent_trimmed
<< YAML::Key << "percent_dropped"
<< YAML::Value << percent_dropped
<< YAML::EndMap
<< YAML::EndMap;
yml << YAML::EndMap;
yml << YAML::EndSeq;
ss << yml.c_str() << "\n";
return ss.str();
}
} // end namespace qcpp
<|endoftext|>
|
<commit_before>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/algorithm/string/predicate.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "bitcoin:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if (mq.try_send(strURI, strlen(strURI), 0))
// if URI could be sent to the message queue exit here
exit(0);
else
// if URI could not be sent to the message queue do a normal Bitcoin-Qt startup
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
// don't log the "file not found" exception, because that's normal for
// the first start of the first instance
if (ex.get_error_code() != boost::interprocess::not_found_error)
{
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Bitcoin");
app.setOrganizationDomain("bitcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Bitcoin-Qt-testnet");
else
app.setApplicationName("Bitcoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "bitcoin:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
#endif
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>Fix Typo<commit_after>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/algorithm/string/predicate.hpp>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "bitcoin:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if (mq.try_send(strURI, strlen(strURI), 0))
// if URI could be sent to the message queue exit here
exit(0);
else
// if URI could not be sent to the message queue do a normal Bitcoin-Qt startup
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
// don't log the "file not found" exception, because that's normal for
// the first start of the first instance
if (ex.get_error_code() != boost::interprocess::not_found_error)
{
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Bitcoin");
app.setOrganizationDomain("bitcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Bitcoin-Qt-testnet");
else
app.setApplicationName("Bitcoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// TODO: implement URI support on the Mac.
#if !defined(MAC_OSX)
// Place this here as guiref has to be defined if we dont want to lose URIs
ipcInit();
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "bitcoin:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
#endif
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and it's threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, 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.
*/
/*
* Main function & globals for the ep_unit_test target.
*/
#include "programs/engine_testapp/mock_server.h"
#include "bucket_logger.h"
#include "configuration.h"
#include "ep_time.h"
#include "hash_table.h"
#include <folly/portability/GMock.h>
#include <getopt.h>
#include <logger/logger.h>
#include <memcached/server_log_iface.h>
/* static storage for environment variable set by putenv(). */
static char allow_no_stats_env[] = "ALLOW_NO_STATS_UPDATE=yeah";
int main(int argc, char **argv) {
bool verbose_logging = false;
// Initialise GoogleMock (and GoogleTest), consuming any cmd-line arguments
// it owns before we check our own.
::testing::InitGoogleMock(&argc, argv);
// Parse command-line options.
int cmd;
bool invalid_argument = false;
while (!invalid_argument &&
(cmd = getopt(argc, argv, "v")) != EOF) {
switch (cmd) {
case 'v':
verbose_logging = true;
break;
default:
std::cerr << "Usage: " << argv[0] << " [-v] [gtest_options...]" << std::endl
<< std::endl
<< " -v Verbose - Print verbose output to stderr."
<< std::endl << std::endl;
invalid_argument = true;
break;
}
}
putenv(allow_no_stats_env);
// Create a blackhole logger to prevent Address sanitizer error when
// calling mock_init_alloc_hooks
cb::logger::createBlackholeLogger();
mock_init_alloc_hooks();
init_mock_server();
// Create the console logger for test case output
cb::logger::createConsoleLogger();
const auto spd_log_level = verbose_logging
? spdlog::level::level_enum::debug
: spdlog::level::level_enum::critical;
// Set the logging level in the api then setup the BucketLogger
get_mock_server_api()->log->get_spdlogger()->set_level(spd_log_level);
BucketLogger::setLoggerAPI(get_mock_server_api()->log);
// Need to initialize ep_real_time and friends.
initialize_time_functions(get_mock_server_api()->core);
auto ret = RUN_ALL_TESTS();
globalBucketLogger.reset();
return ret;
}
<commit_msg>Don't advance time in ep_unit_tests<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, 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.
*/
/*
* Main function & globals for the ep_unit_test target.
*/
#include "programs/engine_testapp/mock_server.h"
#include "bucket_logger.h"
#include "configuration.h"
#include "ep_time.h"
#include "hash_table.h"
#include <folly/portability/GMock.h>
#include <getopt.h>
#include <logger/logger.h>
#include <memcached/config_parser.h>
#include <memcached/server_core_iface.h>
#include <memcached/server_log_iface.h>
/* static storage for environment variable set by putenv(). */
static char allow_no_stats_env[] = "ALLOW_NO_STATS_UPDATE=yeah";
/**
* Implementation of ServerCoreIface for unit tests.
*
* In unit tests time stands still, to give deterministic behaviour.
*/
class UnitTestServerCore : public ServerCoreIface {
public:
rel_time_t get_current_time() override {
// Return a fixed time of '0'.
return 0;
}
rel_time_t realtime(rel_time_t exptime) override {
throw std::runtime_error(
"UnitTestServerCore::realtime() not implemented");
}
time_t abstime(rel_time_t reltime) override {
return get_current_time() + reltime;
}
time_t limit_abstime(time_t t, std::chrono::seconds limit) override {
throw std::runtime_error(
"UnitTestServerCore::limit_abstime() not implemented");
}
int parse_config(const char* str,
config_item* items,
FILE* error) override {
return ::parse_config(str, items, error);
}
void shutdown() override {
throw std::runtime_error(
"UnitTestServerCore::shutdown() not implemented");
}
size_t get_max_item_iovec_size() override {
return 1;
}
void trigger_tick() override {
throw std::runtime_error(
"UnitTestServerCore::trigger_tick() not implemented");
}
};
int main(int argc, char **argv) {
bool verbose_logging = false;
// Initialise GoogleMock (and GoogleTest), consuming any cmd-line arguments
// it owns before we check our own.
::testing::InitGoogleMock(&argc, argv);
// Parse command-line options.
int cmd;
bool invalid_argument = false;
while (!invalid_argument &&
(cmd = getopt(argc, argv, "v")) != EOF) {
switch (cmd) {
case 'v':
verbose_logging = true;
break;
default:
std::cerr << "Usage: " << argv[0] << " [-v] [gtest_options...]" << std::endl
<< std::endl
<< " -v Verbose - Print verbose output to stderr."
<< std::endl << std::endl;
invalid_argument = true;
break;
}
}
putenv(allow_no_stats_env);
// Create a blackhole logger to prevent Address sanitizer error when
// calling mock_init_alloc_hooks
cb::logger::createBlackholeLogger();
mock_init_alloc_hooks();
init_mock_server();
// Create the console logger for test case output
cb::logger::createConsoleLogger();
const auto spd_log_level = verbose_logging
? spdlog::level::level_enum::debug
: spdlog::level::level_enum::critical;
// Set the logging level in the api then setup the BucketLogger
get_mock_server_api()->log->get_spdlogger()->set_level(spd_log_level);
BucketLogger::setLoggerAPI(get_mock_server_api()->log);
// Need to initialize ep_real_time and friends.
UnitTestServerCore unitTestServerCore;
initialize_time_functions(&unitTestServerCore);
auto ret = RUN_ALL_TESTS();
globalBucketLogger.reset();
return ret;
}
<|endoftext|>
|
<commit_before>#include <QApplication>
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin URI
if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString(),QClipboard::Selection);
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "bitcoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Bitcoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Bitcoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Bitcoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
<commit_msg>Bitcoin-Qt: fix copy via context-menu broken<commit_after>#include <QApplication>
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin URI
if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item (global clipboard)
qApp->clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
// Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
qApp->clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "bitcoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Bitcoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Bitcoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Bitcoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 liblcf authors
* This file is released under the MIT License
* http://opensource.org/licenses/MIT
*/
#include <cstdarg>
#include "reader_lcf.h"
// Statics
std::string LcfReader::error_str;
LcfReader::LcfReader(const char* filename, std::string encoding) :
filename(filename),
encoding(encoding),
stream(fopen(filename, "rb"))
{
}
LcfReader::LcfReader(const std::string& filename, std::string encoding) :
filename(filename),
encoding(encoding),
stream(fopen(filename.c_str(), "rb"))
{
}
LcfReader::~LcfReader() {
Close();
}
void LcfReader::Close() {
if (stream != NULL)
fclose(stream);
stream = NULL;
}
size_t LcfReader::Read0(void *ptr, size_t size, size_t nmemb) {
return fread(ptr, size, nmemb, stream);
}
void LcfReader::Read(void *ptr, size_t size, size_t nmemb) {
#ifdef NDEBUG
Read0(ptr, size, nmemb);
#else
assert(Read0(ptr, size, nmemb) == nmemb);
#endif
}
template <>
void LcfReader::Read<bool>(bool& ref) {
ref = ReadInt() > 0;
}
template <>
void LcfReader::Read<uint8_t>(uint8_t& ref) {
Read(&ref, 1, 1);
}
template <>
void LcfReader::Read<int16_t>(int16_t& ref) {
Read(&ref, 2, 1);
SwapByteOrder(ref);
}
template <>
void LcfReader::Read<uint32_t>(uint32_t& ref) {
Read(&ref, 4, 1);
SwapByteOrder(ref);
}
int LcfReader::ReadInt() {
int value = 0;
unsigned char temp = 0;
do {
value <<= 7;
if (Read0(&temp, 1, 1) == 0) {
assert(value == 0);
return 0;
}
value |= temp & 0x7F;
} while (temp & 0x80);
return value;
}
template <>
void LcfReader::Read<int>(int& ref) {
ref = ReadInt();
}
template <>
void LcfReader::Read<double>(double& ref) {
Read(&ref, 8, 1);
SwapByteOrder(ref);
}
template <>
void LcfReader::Read<bool>(std::vector<bool> &buffer, size_t size) {
buffer.clear();
for (unsigned i = 0; i < size; ++i) {
uint8_t val;
Read(&val, 1, 1);
buffer.push_back(val > 0);
}
}
template <>
void LcfReader::Read<uint8_t>(std::vector<uint8_t> &buffer, size_t size) {
buffer.clear();
for (unsigned int i = 0; i < size; ++i) {
uint8_t val;
Read(&val, 1, 1);
buffer.push_back(val);
}
}
template <>
void LcfReader::Read<int16_t>(std::vector<int16_t> &buffer, size_t size) {
buffer.clear();
size_t items = size / 2;
for (unsigned int i = 0; i < items; ++i) {
int16_t val;
Read(&val, 2, 1);
SwapByteOrder(val);
buffer.push_back(val);
}
}
template <>
void LcfReader::Read<uint32_t>(std::vector<uint32_t> &buffer, size_t size) {
buffer.clear();
size_t items = size / 4;
for (unsigned int i = 0; i < items; ++i) {
uint32_t val;
Read(&val, 4, 1);
SwapByteOrder(val);
buffer.push_back(val);
}
}
void LcfReader::ReadString(std::string& ref, size_t size) {
char* chars = new char[size + 1];
chars[size] = '\0';
Read(chars, 1, size);
ref = Encode(std::string(chars));
delete[] chars;
}
bool LcfReader::IsOk() const {
return (stream != NULL && !ferror(stream));
}
bool LcfReader::Eof() const {
return feof(stream) != 0;
}
void LcfReader::Seek(size_t pos, SeekMode mode) {
switch (mode) {
case LcfReader::FromStart:
fseek(stream, pos, SEEK_SET);
break;
case LcfReader::FromCurrent:
fseek(stream, pos, SEEK_CUR);
break;
case LcfReader::FromEnd:
fseek(stream, pos, SEEK_END);
break;
default:
assert(false && "Invalid SeekMode");
}
}
uint32_t LcfReader::Tell() {
return (uint32_t)ftell(stream);
}
bool LcfReader::Ungetch(uint8_t ch) {
return (ungetc(ch, stream) == ch);
}
#ifdef _DEBUG
void LcfReader::SkipDebug(const struct LcfReader::Chunk& chunk_info, const char* srcfile) {
// Dump the Chunk Data in Debug Mode
#ifdef _WIN32
const char* srcfilename = strrchr(srcfile, '\\');
#else
const char* srcfilename = strrchr(srcfile, '/');
#endif
if (srcfilename == NULL) {
srcfilename = srcfile;
} else {
srcfilename++;
}
fprintf(stderr, "Skipped Chunk %02X (%d byte) in %s at %X (%s)\n",
chunk_info.ID, chunk_info.length, filename.c_str(), Tell(),
srcfilename);
for (uint32_t i = 0; i < chunk_info.length; ++i) {
uint8_t byte;
LcfReader::Read(byte);
fprintf(stderr, "%02X ", byte);
if ((i+1) % 16 == 0) {
fprintf(stderr, "\n");
}
}
fprintf(stderr, "\n");
}
#else
void LcfReader::Skip(const struct LcfReader::Chunk& chunk_info) {
Seek((size_t)chunk_info.length, FromCurrent);
}
#endif
void LcfReader::SetError(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
char str[256];
vsprintf(str, fmt, args);
error_str = str;
//Output::ErrorStr((std::string)str);
va_end(args);
}
const std::string& LcfReader::GetError() {
return error_str;
}
std::string LcfReader::Encode(const std::string& str_to_encode) {
return ReaderUtil::Recode(str_to_encode, encoding, "UTF-8");
}
int LcfReader::IntSize(unsigned int x) {
int result = 0;
do {
x >>= 7;
result++;
} while (x != 0);
return result;
}
#ifdef WORDS_BIGENDIAN
void LcfReader::SwapByteOrder(uint16_t& us)
{
us = (us >> 8) |
(us << 8);
}
void LcfReader::SwapByteOrder(uint32_t& ui)
{
ui = (ui >> 24) |
((ui<<8) & 0x00FF0000) |
((ui>>8) & 0x0000FF00) |
(ui << 24);
}
void LcfReader::SwapByteOrder(double& d)
{
uint32_t *p = reinterpret_cast<uint32_t *>(&d);
SwapByteOrder(p[0]);
SwapByteOrder(p[1]);
uint32_t tmp = p[0];
p[0] = p[1];
p[1] = tmp;
}
#else
void LcfReader::SwapByteOrder(uint16_t& /* us */) {}
void LcfReader::SwapByteOrder(uint32_t& /* ui */) {}
void LcfReader::SwapByteOrder(double& /* d */) {}
#endif
void LcfReader::SwapByteOrder(int16_t& s)
{
SwapByteOrder((uint16_t&) s);
}
<commit_msg>Add another debugging print<commit_after>/*
* Copyright (c) 2014 liblcf authors
* This file is released under the MIT License
* http://opensource.org/licenses/MIT
*/
#include <cstdarg>
#include "reader_lcf.h"
#ifdef NDEBUG
# include <stdio.h>
#endif
// Statics
std::string LcfReader::error_str;
LcfReader::LcfReader(const char* filename, std::string encoding) :
filename(filename),
encoding(encoding),
stream(fopen(filename, "rb"))
{
}
LcfReader::LcfReader(const std::string& filename, std::string encoding) :
filename(filename),
encoding(encoding),
stream(fopen(filename.c_str(), "rb"))
{
}
LcfReader::~LcfReader() {
Close();
}
void LcfReader::Close() {
if (stream != NULL)
fclose(stream);
stream = NULL;
}
size_t LcfReader::Read0(void *ptr, size_t size, size_t nmemb) {
size_t result = fread(ptr, size, nmemb, stream);
#ifdef NDEBUG
if (result != nmemb && !Eof()) {
perror("Reading error: ");
}
#endif
return result;
}
void LcfReader::Read(void *ptr, size_t size, size_t nmemb) {
#ifdef NDEBUG
Read0(ptr, size, nmemb);
#else
assert(Read0(ptr, size, nmemb) == nmemb);
#endif
}
template <>
void LcfReader::Read<bool>(bool& ref) {
ref = ReadInt() > 0;
}
template <>
void LcfReader::Read<uint8_t>(uint8_t& ref) {
Read(&ref, 1, 1);
}
template <>
void LcfReader::Read<int16_t>(int16_t& ref) {
Read(&ref, 2, 1);
SwapByteOrder(ref);
}
template <>
void LcfReader::Read<uint32_t>(uint32_t& ref) {
Read(&ref, 4, 1);
SwapByteOrder(ref);
}
int LcfReader::ReadInt() {
int value = 0;
unsigned char temp = 0;
do {
value <<= 7;
if (Read0(&temp, 1, 1) == 0) {
assert(value == 0);
return 0;
}
value |= temp & 0x7F;
} while (temp & 0x80);
return value;
}
template <>
void LcfReader::Read<int>(int& ref) {
ref = ReadInt();
}
template <>
void LcfReader::Read<double>(double& ref) {
Read(&ref, 8, 1);
SwapByteOrder(ref);
}
template <>
void LcfReader::Read<bool>(std::vector<bool> &buffer, size_t size) {
buffer.clear();
for (unsigned i = 0; i < size; ++i) {
uint8_t val;
Read(&val, 1, 1);
buffer.push_back(val > 0);
}
}
template <>
void LcfReader::Read<uint8_t>(std::vector<uint8_t> &buffer, size_t size) {
buffer.clear();
for (unsigned int i = 0; i < size; ++i) {
uint8_t val;
Read(&val, 1, 1);
buffer.push_back(val);
}
}
template <>
void LcfReader::Read<int16_t>(std::vector<int16_t> &buffer, size_t size) {
buffer.clear();
size_t items = size / 2;
for (unsigned int i = 0; i < items; ++i) {
int16_t val;
Read(&val, 2, 1);
SwapByteOrder(val);
buffer.push_back(val);
}
}
template <>
void LcfReader::Read<uint32_t>(std::vector<uint32_t> &buffer, size_t size) {
buffer.clear();
size_t items = size / 4;
for (unsigned int i = 0; i < items; ++i) {
uint32_t val;
Read(&val, 4, 1);
SwapByteOrder(val);
buffer.push_back(val);
}
}
void LcfReader::ReadString(std::string& ref, size_t size) {
char* chars = new char[size + 1];
chars[size] = '\0';
Read(chars, 1, size);
ref = Encode(std::string(chars));
delete[] chars;
}
bool LcfReader::IsOk() const {
return (stream != NULL && !ferror(stream));
}
bool LcfReader::Eof() const {
return feof(stream) != 0;
}
void LcfReader::Seek(size_t pos, SeekMode mode) {
switch (mode) {
case LcfReader::FromStart:
fseek(stream, pos, SEEK_SET);
break;
case LcfReader::FromCurrent:
fseek(stream, pos, SEEK_CUR);
break;
case LcfReader::FromEnd:
fseek(stream, pos, SEEK_END);
break;
default:
assert(false && "Invalid SeekMode");
}
}
uint32_t LcfReader::Tell() {
return (uint32_t)ftell(stream);
}
bool LcfReader::Ungetch(uint8_t ch) {
return (ungetc(ch, stream) == ch);
}
#ifdef _DEBUG
void LcfReader::SkipDebug(const struct LcfReader::Chunk& chunk_info, const char* srcfile) {
// Dump the Chunk Data in Debug Mode
#ifdef _WIN32
const char* srcfilename = strrchr(srcfile, '\\');
#else
const char* srcfilename = strrchr(srcfile, '/');
#endif
if (srcfilename == NULL) {
srcfilename = srcfile;
} else {
srcfilename++;
}
fprintf(stderr, "Skipped Chunk %02X (%d byte) in %s at %X (%s)\n",
chunk_info.ID, chunk_info.length, filename.c_str(), Tell(),
srcfilename);
for (uint32_t i = 0; i < chunk_info.length; ++i) {
uint8_t byte;
LcfReader::Read(byte);
fprintf(stderr, "%02X ", byte);
if ((i+1) % 16 == 0) {
fprintf(stderr, "\n");
}
}
fprintf(stderr, "\n");
}
#else
void LcfReader::Skip(const struct LcfReader::Chunk& chunk_info) {
Seek((size_t)chunk_info.length, FromCurrent);
}
#endif
void LcfReader::SetError(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
char str[256];
vsprintf(str, fmt, args);
error_str = str;
//Output::ErrorStr((std::string)str);
va_end(args);
}
const std::string& LcfReader::GetError() {
return error_str;
}
std::string LcfReader::Encode(const std::string& str_to_encode) {
return ReaderUtil::Recode(str_to_encode, encoding, "UTF-8");
}
int LcfReader::IntSize(unsigned int x) {
int result = 0;
do {
x >>= 7;
result++;
} while (x != 0);
return result;
}
#ifdef WORDS_BIGENDIAN
void LcfReader::SwapByteOrder(uint16_t& us)
{
us = (us >> 8) |
(us << 8);
}
void LcfReader::SwapByteOrder(uint32_t& ui)
{
ui = (ui >> 24) |
((ui<<8) & 0x00FF0000) |
((ui>>8) & 0x0000FF00) |
(ui << 24);
}
void LcfReader::SwapByteOrder(double& d)
{
uint32_t *p = reinterpret_cast<uint32_t *>(&d);
SwapByteOrder(p[0]);
SwapByteOrder(p[1]);
uint32_t tmp = p[0];
p[0] = p[1];
p[1] = tmp;
}
#else
void LcfReader::SwapByteOrder(uint16_t& /* us */) {}
void LcfReader::SwapByteOrder(uint32_t& /* ui */) {}
void LcfReader::SwapByteOrder(double& /* d */) {}
#endif
void LcfReader::SwapByteOrder(int16_t& s)
{
SwapByteOrder((uint16_t&) s);
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <set>
// UNSUPPORTED: c++98, c++03, c++11, c++14
// UNSUPPORTED: libcpp-no-deduction-guides
// UNSUPPORTED: apple-clang-9.1
// template<class InputIterator,
// class Compare = less<iter-value-type<InputIterator>>,
// class Allocator = allocator<iter-value-type<InputIterator>>>
// multiset(InputIterator, InputIterator,
// Compare = Compare(), Allocator = Allocator())
// -> multiset<iter-value-type<InputIterator>, Compare, Allocator>;
// template<class Key, class Compare = less<Key>,
// class Allocator = allocator<Key>>
// multiset(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
// -> multiset<Key, Compare, Allocator>;
// template<class InputIterator, class Allocator>
// multiset(InputIterator, InputIterator, Allocator)
// -> multiset<iter-value-type<InputIterator>,
// less<iter-value-type<InputIterator>>, Allocator>;
// template<class Key, class Allocator>
// multiset(initializer_list<Key>, Allocator)
// -> multiset<Key, less<Key>, Allocator>;
//#include <algorithm> // std::equal
//#include <cassert>
//#include <climits> // INT_MAX
//#include <functional>
//#include <set>
//#include <type_traits>
//
//#include "test_allocator.h"
struct NotAnAllocator {
friend bool operator<(NotAnAllocator, NotAnAllocator) { return false; }
};
void main() {
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr));
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int>);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr), std::greater<int>());
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int, std::greater<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr), std::greater<int>(),
test_allocator<int>(0, 42));
ASSERT_SAME_TYPE(
decltype(s),
momo::stdish::multiset<int, std::greater<int>, test_allocator<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 42);
}
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s(source);
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<long>);
assert(s.size() == 0);
}
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s{ source }; // braces instead of parens
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<long>);
assert(s.size() == 0);
}
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s(source, momo::stdish::multiset<long>::allocator_type());
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<long>);
assert(s.size() == 0);
}
{
momo::stdish::multiset s{ 1, 2, 1, INT_MAX, 3 };
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int>);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
{
momo::stdish::multiset s({ 1, 2, 1, INT_MAX, 3 }, std::greater<int>());
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int, std::greater<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
{
momo::stdish::multiset s({ 1, 2, 1, INT_MAX, 3 }, std::greater<int>(),
test_allocator<int>(0, 43));
ASSERT_SAME_TYPE(
decltype(s),
momo::stdish::multiset<int, std::greater<int>, test_allocator<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 43);
}
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr), test_allocator<int>(0, 44));
ASSERT_SAME_TYPE(decltype(s),
momo::stdish::multiset<int, std::less<int>, test_allocator<int> >);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 44);
}
{
momo::stdish::multiset s({ 1, 2, 1, INT_MAX, 3 }, test_allocator<int>(0, 45));
ASSERT_SAME_TYPE(decltype(s),
momo::stdish::multiset<int, std::less<int>, test_allocator<int> >);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 45);
}
{
NotAnAllocator a;
momo::stdish::multiset s{ a }; // multiset(initializer_list<NotAnAllocator>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<NotAnAllocator>);
assert(s.size() == 1);
}
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s{ source, source }; // multiset(initializer_list<multiset<long>>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<momo::stdish::multiset<long> >);
assert(s.size() == 2);
}
{
NotAnAllocator a;
momo::stdish::multiset s{ a, a }; // multiset(initializer_list<NotAnAllocator>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<NotAnAllocator>);
assert(s.size() == 2);
}
{
int source[3] = { 3, 4, 5 };
momo::stdish::multiset s(source, source + 3); // multiset(InputIterator, InputIterator)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int>);
assert(s.size() == 3);
}
{
int source[3] = { 3, 4, 5 };
momo::stdish::multiset s{ source, source + 3 }; // multiset(initializer_list<int*>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int *>);
assert(s.size() == 2);
}
}
<commit_msg>Deduction: multiset<commit_after>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <set>
// UNSUPPORTED: c++98, c++03, c++11, c++14
// UNSUPPORTED: libcpp-no-deduction-guides
// UNSUPPORTED: apple-clang-9.1
// template<class InputIterator,
// class Compare = less<iter-value-type<InputIterator>>,
// class Allocator = allocator<iter-value-type<InputIterator>>>
// multiset(InputIterator, InputIterator,
// Compare = Compare(), Allocator = Allocator())
// -> multiset<iter-value-type<InputIterator>, Compare, Allocator>;
// template<class Key, class Compare = less<Key>,
// class Allocator = allocator<Key>>
// multiset(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
// -> multiset<Key, Compare, Allocator>;
// template<class InputIterator, class Allocator>
// multiset(InputIterator, InputIterator, Allocator)
// -> multiset<iter-value-type<InputIterator>,
// less<iter-value-type<InputIterator>>, Allocator>;
// template<class Key, class Allocator>
// multiset(initializer_list<Key>, Allocator)
// -> multiset<Key, less<Key>, Allocator>;
//#include <algorithm> // std::equal
//#include <cassert>
//#include <climits> // INT_MAX
//#include <functional>
//#include <set>
//#include <type_traits>
//
//#include "test_allocator.h"
struct NotAnAllocator {
friend bool operator<(NotAnAllocator, NotAnAllocator) { return false; }
};
void main() {
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr));
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int>);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr), std::greater<int>());
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int, std::greater<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr), std::greater<int>(),
test_allocator<int>(0, 42));
ASSERT_SAME_TYPE(
decltype(s),
momo::stdish::multiset<int, std::greater<int>, test_allocator<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 42);
}
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s(source);
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<long>);
assert(s.size() == 0);
}
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s{ source }; // braces instead of parens
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<long>);
assert(s.size() == 0);
}
#if !defined(__GNUC__) && !defined(__clang__)
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s(source, momo::stdish::multiset<long>::allocator_type());
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<long>);
assert(s.size() == 0);
}
#endif
#if !defined(__GNUC__)
{
momo::stdish::multiset s{ 1, 2, 1, INT_MAX, 3 };
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int>);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
#endif
{
momo::stdish::multiset s({ 1, 2, 1, INT_MAX, 3 }, std::greater<int>());
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int, std::greater<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
}
{
momo::stdish::multiset s({ 1, 2, 1, INT_MAX, 3 }, std::greater<int>(),
test_allocator<int>(0, 43));
ASSERT_SAME_TYPE(
decltype(s),
momo::stdish::multiset<int, std::greater<int>, test_allocator<int> >);
const int expected_s[] = { INT_MAX, 3, 2, 1, 1 };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 43);
}
{
const int arr[] = { 1, 2, 1, INT_MAX, 3 };
momo::stdish::multiset s(std::begin(arr), std::end(arr), test_allocator<int>(0, 44));
ASSERT_SAME_TYPE(decltype(s),
momo::stdish::multiset<int, std::less<int>, test_allocator<int> >);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 44);
}
{
momo::stdish::multiset s({ 1, 2, 1, INT_MAX, 3 }, test_allocator<int>(0, 45));
ASSERT_SAME_TYPE(decltype(s),
momo::stdish::multiset<int, std::less<int>, test_allocator<int> >);
const int expected_s[] = { 1, 1, 2, 3, INT_MAX };
assert(std::equal(s.begin(), s.end(), std::begin(expected_s),
std::end(expected_s)));
assert(s.get_allocator().get_id() == 45);
}
#if !defined(__GNUC__)
{
NotAnAllocator a;
momo::stdish::multiset s{ a }; // multiset(initializer_list<NotAnAllocator>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<NotAnAllocator>);
assert(s.size() == 1);
}
{
momo::stdish::multiset<long> source;
momo::stdish::multiset s{ source, source }; // multiset(initializer_list<multiset<long>>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<momo::stdish::multiset<long> >);
assert(s.size() == 2);
}
{
NotAnAllocator a;
momo::stdish::multiset s{ a, a }; // multiset(initializer_list<NotAnAllocator>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<NotAnAllocator>);
assert(s.size() == 2);
}
#endif
{
int source[3] = { 3, 4, 5 };
momo::stdish::multiset s(source, source + 3); // multiset(InputIterator, InputIterator)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int>);
assert(s.size() == 3);
}
#if !defined(__GNUC__)
{
int source[3] = { 3, 4, 5 };
momo::stdish::multiset s{ source, source + 3 }; // multiset(initializer_list<int*>)
ASSERT_SAME_TYPE(decltype(s), momo::stdish::multiset<int *>);
assert(s.size() == 2);
}
#endif
}
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library 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
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// <h1>FEMSystem Example 1 - Unsteady Navier-Stokes Equations with
// FEMSystem</h1>
// \author Roy Stogner
// \date 2006
//
// This example shows how the transient nonlinear problem from
// example 13 can be solved using the
// DifferentiableSystem class framework
// C++ includes
#include <iomanip>
// Basic include files
#include "libmesh/equation_systems.h"
#include "libmesh/error_vector.h"
#include "libmesh/getpot.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh.h"
#include "libmesh/replicated_mesh.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_refinement.h"
#include "libmesh/uniform_refinement_estimator.h"
#include "libmesh/auto_ptr.h" // libmesh_make_unique
#include "libmesh/enum_solver_package.h"
#include "libmesh/enum_norm_type.h"
// The systems and solvers we may use
#include "naviersystem.h"
#include "libmesh/diff_solver.h"
#include "libmesh/petsc_diff_solver.h"
#include "libmesh/newton_solver.h"
#include "libmesh/euler_solver.h"
#include "libmesh/steady_solver.h"
#include "libmesh/partitioner.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// The main program.
int main (int argc, char ** argv)
{
// Initialize libMesh.
LibMeshInit init (argc, argv);
// This example requires a linear solver package.
libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
"--enable-petsc, --enable-trilinos, or --enable-eigen");
// This example fails without at least double precision FP
#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
libmesh_example_requires(false, "--disable-singleprecision");
#endif
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_requires(false, "--enable-amr");
#else
// Trilinos and Eigen solvers NaN by default here.
// We'll skip this example for now.
libmesh_example_requires(libMesh::default_solver_package() != EIGEN_SOLVERS, "--enable-petsc");
libmesh_example_requires(libMesh::default_solver_package() != TRILINOS_SOLVERS, "--enable-petsc");
// Parse the input file
GetPot infile("fem_system_ex1.in");
// Override input file arguments from the command line
infile.parse_command_line(argc, argv);
// Read in parameters from the input file
const Real global_tolerance = infile("global_tolerance", 0.);
const unsigned int nelem_target = infile("n_elements", 400);
const bool transient = infile("transient", true);
const Real deltat = infile("deltat", 0.005);
unsigned int n_timesteps = infile("n_timesteps", 20);
const unsigned int coarsegridsize = infile("coarsegridsize", 1);
const unsigned int coarserefinements = infile("coarserefinements", 0);
const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10);
const unsigned int dim = infile("dimension", 2);
const std::string slvr_type = infile("solver_type", "newton");
const std::string mesh_type = infile("mesh_type" , "replicated");
#ifdef LIBMESH_HAVE_EXODUS_API
const unsigned int write_interval = infile("write_interval", 5);
#endif
// Skip higher-dimensional examples on a lower-dimensional libMesh build
libmesh_example_requires(dim <= LIBMESH_DIM, "2D/3D support");
// We have only defined 2 and 3 dimensional problems
libmesh_assert (dim == 2 || dim == 3);
// Create a mesh, with dimension to be overridden later, distributed
// across the default MPI communicator.
std::shared_ptr<UnstructuredMesh> mesh;
if (mesh_type == "distributed")
mesh.reset(new DistributedMesh(init.comm()));
else if (mesh_type == "replicated")
mesh.reset(new ReplicatedMesh(init.comm()));
else
libmesh_error_msg("Error: specified mesh_type not understood");
// And an object to refine it
MeshRefinement mesh_refinement(*mesh);
mesh_refinement.coarsen_by_parents() = true;
mesh_refinement.absolute_global_tolerance() = global_tolerance;
mesh_refinement.nelem_target() = nelem_target;
mesh_refinement.refine_fraction() = 0.3;
mesh_refinement.coarsen_fraction() = 0.3;
mesh_refinement.coarsen_threshold() = 0.1;
// Use the MeshTools::Generation mesh generator to create a uniform
// grid on the square [-1,1]^D. We instruct the mesh generator
// to build a mesh of 8x8 Quad9 elements in 2D, or Hex27
// elements in 3D. Building these higher-order elements allows
// us to use higher-order approximation, as in example 3.
if (dim == 2)
MeshTools::Generation::build_square (*mesh,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
QUAD9);
else if (dim == 3)
MeshTools::Generation::build_cube (*mesh,
coarsegridsize,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
0., 1.,
HEX27);
if (slvr_type == "petscdiff")
{
mesh->allow_renumbering(false);
mesh->allow_remote_element_removal(false);
mesh->partitioner() = nullptr;
}
mesh_refinement.uniformly_refine(coarserefinements);
// Print information about the mesh to the screen.
mesh->print_info();
// Create an equation systems object.
EquationSystems equation_systems (*mesh);
// Declare the system "Navier-Stokes" and its variables.
NavierSystem & system =
equation_systems.add_system<NavierSystem> ("Navier-Stokes");
// Solve this as a time-dependent or steady system
if (transient)
system.time_solver = libmesh_make_unique<EulerSolver>(system);
else
{
system.time_solver = libmesh_make_unique<SteadySolver>(system);
libmesh_assert_equal_to (n_timesteps, 1);
}
// Initialize the system
equation_systems.init ();
// Set the time stepping options
system.deltat = deltat;
// And the nonlinear solver options
if (slvr_type == "newton")
system.time_solver->diff_solver() = libmesh_make_unique<NewtonSolver>(system);
else if (slvr_type == "petscdiff")
#if defined(LIBMESH_HAVE_PETSC) && defined(LIBMESH_HAVE_METAPHYSICL)
system.time_solver->diff_solver() = libmesh_make_unique<PetscDiffSolver>(system);
#else
libmesh_example_requires(false, "--enable-petsc --enable-metaphysicl-required");
#endif
else
libmesh_error_msg("Error: specified solver_type not understood");
DiffSolver & solver = *(system.time_solver->diff_solver().get());
solver.init();
solver.quiet = infile("solver_quiet", true);
solver.verbose = !solver.quiet;
solver.max_nonlinear_iterations =
infile("max_nonlinear_iterations", 15);
solver.relative_step_tolerance =
infile("relative_step_tolerance", 1.e-3);
solver.relative_residual_tolerance =
infile("relative_residual_tolerance", 0.0);
solver.absolute_residual_tolerance =
infile("absolute_residual_tolerance", 0.0);
// And the linear solver options
solver.max_linear_iterations =
infile("max_linear_iterations", 50000);
solver.initial_linear_tolerance =
infile("initial_linear_tolerance", 1.e-3);
// Print information about the system to the screen.
equation_systems.print_info();
// Now we begin the timestep loop to compute the time-accurate
// solution of the equations.
for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
{
// A pretty update message
libMesh::out << "\n\nSolving time step "
<< t_step
<< ", time = "
<< system.time
<< std::endl;
// Adaptively solve the timestep
unsigned int a_step = 0;
for (; a_step != max_adaptivesteps; ++a_step)
{
system.solve();
system.postprocess();
ErrorVector error;
std::unique_ptr<ErrorEstimator> error_estimator;
// To solve to a tolerance in this problem we
// need a better estimator than Kelly
if (global_tolerance != 0.)
{
// We can't adapt to both a tolerance and a mesh
// size at once
libmesh_assert_equal_to (nelem_target, 0);
UniformRefinementEstimator * u = new UniformRefinementEstimator;
// The lid-driven cavity problem isn't in H1, so
// lets estimate L2 error
u->error_norm = L2;
error_estimator.reset(u);
}
else
{
// If we aren't adapting to a tolerance we need a
// target mesh size
libmesh_assert_greater (nelem_target, 0);
// Kelly is a lousy estimator to use for a problem
// not in H1 - if we were doing more than a few
// timesteps we'd need to turn off or limit the
// maximum level of our adaptivity eventually
error_estimator.reset(new KellyErrorEstimator);
}
// Calculate error based on u and v (and w?) but not p
std::vector<Real> weights(2,1.0); // u, v
if (dim == 3)
weights.push_back(1.0); // w
weights.push_back(0.0); // p
// Keep the same default norm type.
std::vector<FEMNormType>
norms(1, error_estimator->error_norm.type(0));
error_estimator->error_norm = SystemNorm(norms, weights);
error_estimator->estimate_error(system, error);
// Print out status at each adaptive step.
Real global_error = error.l2_norm();
libMesh::out << "Adaptive step "
<< a_step
<< ": "
<< std::endl;
if (global_tolerance != 0.)
libMesh::out << "Global_error = "
<< global_error
<< std::endl;
if (global_tolerance != 0.)
libMesh::out << "Worst element error = "
<< error.maximum()
<< ", mean = "
<< error.mean()
<< std::endl;
if (global_tolerance != 0.)
{
// If we've reached our desired tolerance, we
// don't need any more adaptive steps
if (global_error < global_tolerance)
break;
mesh_refinement.flag_elements_by_error_tolerance(error);
}
else
{
// If flag_elements_by_nelem_target returns true, this
// should be our last adaptive step.
if (mesh_refinement.flag_elements_by_nelem_target(error))
{
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
a_step = max_adaptivesteps;
break;
}
}
// Carry out the adaptive mesh refinement/coarsening
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
libMesh::out << "Refined mesh to "
<< mesh->n_active_elem()
<< " active elements and "
<< equation_systems.n_active_dofs()
<< " active dofs."
<< std::endl;
}
// Do one last solve if necessary
if (a_step == max_adaptivesteps)
{
system.solve();
system.postprocess();
}
// Advance to the next timestep in a transient problem
system.time_solver->advance_timestep();
#ifdef LIBMESH_HAVE_EXODUS_API
// Write out this timestep if we're requested to
if ((t_step+1)%write_interval == 0)
{
std::ostringstream file_name;
// We write the file in the ExodusII format.
file_name << "out_"
<< std::setw(3)
<< std::setfill('0')
<< std::right
<< t_step+1
<< ".e";
ExodusII_IO(*mesh).write_timestep(file_name.str(),
equation_systems,
1, // This number indicates how many time steps
// are being written to the file
system.time);
}
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
}
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done.
return 0;
}
<commit_msg>Disable fem_system_ex1 if complex numbers are enabled.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library 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
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// <h1>FEMSystem Example 1 - Unsteady Navier-Stokes Equations with
// FEMSystem</h1>
// \author Roy Stogner
// \date 2006
//
// This example shows how the transient nonlinear problem from
// example 13 can be solved using the
// DifferentiableSystem class framework
// C++ includes
#include <iomanip>
// Basic include files
#include "libmesh/equation_systems.h"
#include "libmesh/error_vector.h"
#include "libmesh/getpot.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh.h"
#include "libmesh/replicated_mesh.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_refinement.h"
#include "libmesh/uniform_refinement_estimator.h"
#include "libmesh/auto_ptr.h" // libmesh_make_unique
#include "libmesh/enum_solver_package.h"
#include "libmesh/enum_norm_type.h"
// The systems and solvers we may use
#include "naviersystem.h"
#include "libmesh/diff_solver.h"
#include "libmesh/petsc_diff_solver.h"
#include "libmesh/newton_solver.h"
#include "libmesh/euler_solver.h"
#include "libmesh/steady_solver.h"
#include "libmesh/partitioner.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// The main program.
int main (int argc, char ** argv)
{
// Initialize libMesh.
LibMeshInit init (argc, argv);
// This example requires a linear solver package.
libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
"--enable-petsc, --enable-trilinos, or --enable-eigen");
// This example fails without at least double precision FP
#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
libmesh_example_requires(false, "--disable-singleprecision");
#endif
// This example uses the new PetscDMWrapper which currently does not
// compile when complex numbers are enabled.
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
libmesh_example_requires(false, "--disable-complex");
#endif
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_requires(false, "--enable-amr");
#else
// Trilinos and Eigen solvers NaN by default here.
// We'll skip this example for now.
libmesh_example_requires(libMesh::default_solver_package() != EIGEN_SOLVERS, "--enable-petsc");
libmesh_example_requires(libMesh::default_solver_package() != TRILINOS_SOLVERS, "--enable-petsc");
// Parse the input file
GetPot infile("fem_system_ex1.in");
// Override input file arguments from the command line
infile.parse_command_line(argc, argv);
// Read in parameters from the input file
const Real global_tolerance = infile("global_tolerance", 0.);
const unsigned int nelem_target = infile("n_elements", 400);
const bool transient = infile("transient", true);
const Real deltat = infile("deltat", 0.005);
unsigned int n_timesteps = infile("n_timesteps", 20);
const unsigned int coarsegridsize = infile("coarsegridsize", 1);
const unsigned int coarserefinements = infile("coarserefinements", 0);
const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10);
const unsigned int dim = infile("dimension", 2);
const std::string slvr_type = infile("solver_type", "newton");
const std::string mesh_type = infile("mesh_type" , "replicated");
#ifdef LIBMESH_HAVE_EXODUS_API
const unsigned int write_interval = infile("write_interval", 5);
#endif
// Skip higher-dimensional examples on a lower-dimensional libMesh build
libmesh_example_requires(dim <= LIBMESH_DIM, "2D/3D support");
// We have only defined 2 and 3 dimensional problems
libmesh_assert (dim == 2 || dim == 3);
// Create a mesh, with dimension to be overridden later, distributed
// across the default MPI communicator.
std::shared_ptr<UnstructuredMesh> mesh;
if (mesh_type == "distributed")
mesh.reset(new DistributedMesh(init.comm()));
else if (mesh_type == "replicated")
mesh.reset(new ReplicatedMesh(init.comm()));
else
libmesh_error_msg("Error: specified mesh_type not understood");
// And an object to refine it
MeshRefinement mesh_refinement(*mesh);
mesh_refinement.coarsen_by_parents() = true;
mesh_refinement.absolute_global_tolerance() = global_tolerance;
mesh_refinement.nelem_target() = nelem_target;
mesh_refinement.refine_fraction() = 0.3;
mesh_refinement.coarsen_fraction() = 0.3;
mesh_refinement.coarsen_threshold() = 0.1;
// Use the MeshTools::Generation mesh generator to create a uniform
// grid on the square [-1,1]^D. We instruct the mesh generator
// to build a mesh of 8x8 Quad9 elements in 2D, or Hex27
// elements in 3D. Building these higher-order elements allows
// us to use higher-order approximation, as in example 3.
if (dim == 2)
MeshTools::Generation::build_square (*mesh,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
QUAD9);
else if (dim == 3)
MeshTools::Generation::build_cube (*mesh,
coarsegridsize,
coarsegridsize,
coarsegridsize,
0., 1.,
0., 1.,
0., 1.,
HEX27);
if (slvr_type == "petscdiff")
{
mesh->allow_renumbering(false);
mesh->allow_remote_element_removal(false);
mesh->partitioner() = nullptr;
}
mesh_refinement.uniformly_refine(coarserefinements);
// Print information about the mesh to the screen.
mesh->print_info();
// Create an equation systems object.
EquationSystems equation_systems (*mesh);
// Declare the system "Navier-Stokes" and its variables.
NavierSystem & system =
equation_systems.add_system<NavierSystem> ("Navier-Stokes");
// Solve this as a time-dependent or steady system
if (transient)
system.time_solver = libmesh_make_unique<EulerSolver>(system);
else
{
system.time_solver = libmesh_make_unique<SteadySolver>(system);
libmesh_assert_equal_to (n_timesteps, 1);
}
// Initialize the system
equation_systems.init ();
// Set the time stepping options
system.deltat = deltat;
// And the nonlinear solver options
if (slvr_type == "newton")
system.time_solver->diff_solver() = libmesh_make_unique<NewtonSolver>(system);
else if (slvr_type == "petscdiff")
#if defined(LIBMESH_HAVE_PETSC) && defined(LIBMESH_HAVE_METAPHYSICL)
system.time_solver->diff_solver() = libmesh_make_unique<PetscDiffSolver>(system);
#else
libmesh_example_requires(false, "--enable-petsc --enable-metaphysicl-required");
#endif
else
libmesh_error_msg("Error: specified solver_type not understood");
DiffSolver & solver = *(system.time_solver->diff_solver().get());
solver.init();
solver.quiet = infile("solver_quiet", true);
solver.verbose = !solver.quiet;
solver.max_nonlinear_iterations =
infile("max_nonlinear_iterations", 15);
solver.relative_step_tolerance =
infile("relative_step_tolerance", 1.e-3);
solver.relative_residual_tolerance =
infile("relative_residual_tolerance", 0.0);
solver.absolute_residual_tolerance =
infile("absolute_residual_tolerance", 0.0);
// And the linear solver options
solver.max_linear_iterations =
infile("max_linear_iterations", 50000);
solver.initial_linear_tolerance =
infile("initial_linear_tolerance", 1.e-3);
// Print information about the system to the screen.
equation_systems.print_info();
// Now we begin the timestep loop to compute the time-accurate
// solution of the equations.
for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
{
// A pretty update message
libMesh::out << "\n\nSolving time step "
<< t_step
<< ", time = "
<< system.time
<< std::endl;
// Adaptively solve the timestep
unsigned int a_step = 0;
for (; a_step != max_adaptivesteps; ++a_step)
{
system.solve();
system.postprocess();
ErrorVector error;
std::unique_ptr<ErrorEstimator> error_estimator;
// To solve to a tolerance in this problem we
// need a better estimator than Kelly
if (global_tolerance != 0.)
{
// We can't adapt to both a tolerance and a mesh
// size at once
libmesh_assert_equal_to (nelem_target, 0);
UniformRefinementEstimator * u = new UniformRefinementEstimator;
// The lid-driven cavity problem isn't in H1, so
// lets estimate L2 error
u->error_norm = L2;
error_estimator.reset(u);
}
else
{
// If we aren't adapting to a tolerance we need a
// target mesh size
libmesh_assert_greater (nelem_target, 0);
// Kelly is a lousy estimator to use for a problem
// not in H1 - if we were doing more than a few
// timesteps we'd need to turn off or limit the
// maximum level of our adaptivity eventually
error_estimator.reset(new KellyErrorEstimator);
}
// Calculate error based on u and v (and w?) but not p
std::vector<Real> weights(2,1.0); // u, v
if (dim == 3)
weights.push_back(1.0); // w
weights.push_back(0.0); // p
// Keep the same default norm type.
std::vector<FEMNormType>
norms(1, error_estimator->error_norm.type(0));
error_estimator->error_norm = SystemNorm(norms, weights);
error_estimator->estimate_error(system, error);
// Print out status at each adaptive step.
Real global_error = error.l2_norm();
libMesh::out << "Adaptive step "
<< a_step
<< ": "
<< std::endl;
if (global_tolerance != 0.)
libMesh::out << "Global_error = "
<< global_error
<< std::endl;
if (global_tolerance != 0.)
libMesh::out << "Worst element error = "
<< error.maximum()
<< ", mean = "
<< error.mean()
<< std::endl;
if (global_tolerance != 0.)
{
// If we've reached our desired tolerance, we
// don't need any more adaptive steps
if (global_error < global_tolerance)
break;
mesh_refinement.flag_elements_by_error_tolerance(error);
}
else
{
// If flag_elements_by_nelem_target returns true, this
// should be our last adaptive step.
if (mesh_refinement.flag_elements_by_nelem_target(error))
{
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
a_step = max_adaptivesteps;
break;
}
}
// Carry out the adaptive mesh refinement/coarsening
mesh_refinement.refine_and_coarsen_elements();
equation_systems.reinit();
libMesh::out << "Refined mesh to "
<< mesh->n_active_elem()
<< " active elements and "
<< equation_systems.n_active_dofs()
<< " active dofs."
<< std::endl;
}
// Do one last solve if necessary
if (a_step == max_adaptivesteps)
{
system.solve();
system.postprocess();
}
// Advance to the next timestep in a transient problem
system.time_solver->advance_timestep();
#ifdef LIBMESH_HAVE_EXODUS_API
// Write out this timestep if we're requested to
if ((t_step+1)%write_interval == 0)
{
std::ostringstream file_name;
// We write the file in the ExodusII format.
file_name << "out_"
<< std::setw(3)
<< std::setfill('0')
<< std::right
<< t_step+1
<< ".e";
ExodusII_IO(*mesh).write_timestep(file_name.str(),
equation_systems,
1, // This number indicates how many time steps
// are being written to the file
system.time);
}
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
}
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done.
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more
* contributor license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <getopt.h>
#include <stdint.h>
#include <sys/time.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <stdexcept>
#include <vector>
#include <openssl/sha.h>
#include <jansson.h>
#include <readosm.h>
#include "throwstream.h"
#include "scoped.h"
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/aerospike_query.h>
#include <aerospike/as_hashmap.h>
#include <aerospike/as_key.h>
#include <aerospike/as_query.h>
#include <aerospike/as_record.h>
using namespace std;
namespace {
// Some things have defaults
char const * DEF_HOST = "localhost";
int const DEF_PORT = 3000;
char const * DEF_NAMESPACE = "test";
char const * DEF_SET = "osm";
string g_host = DEF_HOST;
int g_port = DEF_PORT;
string g_user;
string g_pass;
string g_namespace = DEF_NAMESPACE;
string g_set = DEF_SET;
string g_infile;
char const * g_valbin = "val";
char const * g_locbin = "loc";
char const * g_mapbin = "map";
char const * g_hshbin = "hash";
char const * g_locndx = "osm-loc-index";
size_t g_npoints = 0;
int64_t id_to_hash(int64_t const & id)
{
uint8_t obuf[32];
SHA256((uint8_t *) &id, sizeof(id), obuf);
int64_t hshval;
memcpy((void *) &hshval, obuf, sizeof(hshval));
hshval &= 0x7fffffffffffffff; // Don't be negative
return hshval;
}
int
handle_node(void const * user_data, readosm_node const * node)
{
aerospike * asp = (aerospike *) user_data;
// First scan the tags to see if there is a name.
char const * name = NULL;
for (int ii = 0; ii < node->tag_count; ++ii) {
if (strcmp(node->tags[ii].key, "name") == 0) {
name = node->tags[ii].value;
break;
}
}
if (!name)
return READOSM_OK;
int64_t hshval = id_to_hash(node->id);
size_t ntags = node->tag_count;
// We'll insert all the tags + lat and long.
as_map * asmap = (as_map *) as_hashmap_new(ntags + 2);
Scoped<json_t *> valobj(json_object(), NULL, json_decref);
for (int ii = 0; ii < node->tag_count; ++ii) {
as_map_set(asmap,
(as_val *) as_string_new((char *) node->tags[ii].key, false),
(as_val *) as_string_new((char *) node->tags[ii].value, false));
json_object_set_new(valobj,
node->tags[ii].key,
json_string(node->tags[ii].value));
}
as_map_set(asmap,
(as_val *) as_string_new((char *) "latitude", false),
(as_val *) as_double_new(node->latitude));
as_map_set(asmap,
(as_val *) as_string_new((char *) "longitude", false),
(as_val *) as_double_new(node->longitude));
json_object_set_new(valobj, "latitude", json_real(node->latitude));
json_object_set_new(valobj, "longitude", json_real(node->longitude));
Scoped<char *> valstr(json_dumps(valobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
cout << valstr << endl;
// Construct the GeoJSON loc bin value.
Scoped<json_t *> locobj(json_object(), NULL, json_decref);
json_object_set_new(locobj, "type", json_string("Point"));
Scoped<json_t *> coordobj(json_array(), NULL, json_decref);
json_array_append_new(coordobj, json_real(node->longitude));
json_array_append_new(coordobj, json_real(node->latitude));
json_object_set(locobj, "coordinates", coordobj);
Scoped<char *> locstr(json_dumps(locobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
as_key key;
as_key_init_int64(&key, g_namespace.c_str(), g_set.c_str(), node->id);
uint16_t nbins = 4;
as_record rec;
as_record_inita(&rec, nbins);
as_record_set_geojson_str(&rec, g_locbin, locstr);
as_record_set_str(&rec, g_valbin, valstr);
as_record_set_map(&rec, g_mapbin, asmap);
as_record_set_int64(&rec, g_hshbin, hshval);
as_error err;
as_status rv = aerospike_key_put(asp, &err, NULL, &key, &rec);
as_record_destroy(&rec);
as_key_destroy(&key);
if (rv != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_key_put failed: "
<< err.code << " - " << err.message);
++g_npoints;
// cout << json_dumps(rootobj, JSON_COMPACT) << endl;
return READOSM_OK;
}
uint64_t
now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * (uint64_t) 1000000) + tv.tv_usec;
}
void
setup_aerospike(aerospike * asp)
{
as_config cfg;
as_config_init(&cfg);
as_config_add_host(&cfg, g_host.c_str(), g_port);
if (! g_user.empty())
as_config_set_user(&cfg, g_user.c_str(), g_pass.c_str());
aerospike_init(asp, &cfg);
as_error err;
if (aerospike_connect(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_connect failed: "
<< err.code << " - " << err.message);
}
void
create_indexes(aerospike * asp)
{
{
as_error err;
as_index_task task;
if (aerospike_index_create(asp, &err, &task, NULL,
g_namespace.c_str(), g_set.c_str(),
g_locbin, g_locndx,
AS_INDEX_GEO2DSPHERE) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_index_create() returned "
<< err.code << " - " << err.message);
// Wait for the system metadata to spread to all nodes.
aerospike_index_create_wait(&err, &task, 0);
}
}
void
cleanup_aerospike(aerospike * asp)
{
as_error err;
if (aerospike_close(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_close failed: "
<< err.code << " - " << err.message);
aerospike_destroy(asp);
}
void
usage(int & argc, char ** & argv)
{
cerr << "usage: " << argv[0] << " [options] -l <latitude> <longitude>" << endl
<< " options:" << endl
<< " -u, --usage display usage" << endl
<< " -h, --host=HOST database host [" << DEF_HOST << "]" << endl
<< " -p, --port=PORT database port [" << DEF_PORT << "]" << endl
<< " -U, --user=USER username [<none>]" << endl
<< " -P, --password=PASSWORD password [<none>]" << endl
<< " -n, --namespace=NAMESPACE query namespace [" << DEF_NAMESPACE << "]" << endl
<< " -s, --set=SET query set [" << DEF_SET << "]" << endl
;
}
void
parse_arguments(int & argc, char ** & argv)
{
char * endp;
static struct option long_options[] =
{
{"usage", no_argument, 0, 'u'},
{"host", required_argument, 0, 'h'},
{"port", required_argument, 0, 'p'},
{"user", required_argument, 0, 'U'},
{"password", required_argument, 0, 'P'},
{"namespace", required_argument, 0, 'n'},
{"set", required_argument, 0, 's'},
{0, 0, 0, 0}
};
while (true)
{
int optndx = 0;
int opt = getopt_long(argc, argv, "uh:p:U:P:n:s:",
long_options, &optndx);
// Are we done processing arguments?
if (opt == -1)
break;
switch (opt) {
case 'u':
usage(argc, argv);
exit(0);
break;
case 'h':
g_host = optarg;
break;
case 'p':
g_port = strtol(optarg, &endp, 0);
if (*endp != '\0')
throwstream(runtime_error, "invalid port value: " << optarg);
break;
case 'U':
g_user = optarg;
break;
case 'P':
g_pass = optarg;
break;
case 'n':
g_namespace = optarg;
break;
case 's':
g_set = optarg;
break;
case'?':
// getopt_long already printed an error message
usage(argc, argv);
exit(1);
break;
default:
throwstream(runtime_error, "unexpected option: " << char(opt));
break;
}
}
if (optind >= argc)
throwstream(runtime_error, "missing input-file argument");
g_infile = argv[optind];
}
int
run(int & argc, char ** & argv)
{
parse_arguments(argc, argv);
const void * osm_handle;
int ret;
ret = readosm_open (g_infile.c_str(), &osm_handle);
if (ret != READOSM_OK)
throwstream(runtime_error, "OPEN error: " << ret);
Scoped<void const *> osm(osm_handle, NULL,
(void (*)(const void*)) readosm_close);
uint64_t t0 = now();
aerospike as;
Scoped<aerospike *> asp(&as, NULL, cleanup_aerospike);
setup_aerospike(asp);
create_indexes(asp);
ret = readosm_parse(osm_handle,
(const void *) asp,
handle_node,
NULL,
NULL);
if (ret != READOSM_OK)
throwstream(runtime_error, "PARSE error: " << ret);
uint64_t t1 = now();
cerr << "Loaded " << dec << g_npoints << " points"
<< " in " << ((t1 - t0) / 1e6) << " seconds" << endl;
return 0;
}
} // end namespace
int
main(int argc, char ** argv)
{
try
{
return run(argc, argv);
}
catch (exception const & ex)
{
cerr << "EXCEPTION: " << ex.what() << endl;
return 1;
}
}
<commit_msg>osm_load/cplusplus: added osmid to value<commit_after>/*
* Copyright 2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more
* contributor license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <getopt.h>
#include <stdint.h>
#include <sys/time.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <stdexcept>
#include <vector>
#include <openssl/sha.h>
#include <jansson.h>
#include <readosm.h>
#include "throwstream.h"
#include "scoped.h"
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/aerospike_query.h>
#include <aerospike/as_hashmap.h>
#include <aerospike/as_key.h>
#include <aerospike/as_query.h>
#include <aerospike/as_record.h>
using namespace std;
namespace {
// Some things have defaults
char const * DEF_HOST = "localhost";
int const DEF_PORT = 3000;
char const * DEF_NAMESPACE = "test";
char const * DEF_SET = "osm";
string g_host = DEF_HOST;
int g_port = DEF_PORT;
string g_user;
string g_pass;
string g_namespace = DEF_NAMESPACE;
string g_set = DEF_SET;
string g_infile;
char const * g_valbin = "val";
char const * g_locbin = "loc";
char const * g_mapbin = "map";
char const * g_hshbin = "hash";
char const * g_locndx = "osm-loc-index";
size_t g_npoints = 0;
int64_t id_to_hash(int64_t const & id)
{
uint8_t obuf[32];
SHA256((uint8_t *) &id, sizeof(id), obuf);
int64_t hshval;
memcpy((void *) &hshval, obuf, sizeof(hshval));
hshval &= 0x7fffffffffffffff; // Don't be negative
return hshval;
}
int
handle_node(void const * user_data, readosm_node const * node)
{
aerospike * asp = (aerospike *) user_data;
// First scan the tags to see if there is a name.
char const * name = NULL;
for (int ii = 0; ii < node->tag_count; ++ii) {
if (strcmp(node->tags[ii].key, "name") == 0) {
name = node->tags[ii].value;
break;
}
}
if (!name)
return READOSM_OK;
int64_t hshval = id_to_hash(node->id);
size_t ntags = node->tag_count;
// We'll insert all the tags + osmid, lat and long.
as_map * asmap = (as_map *) as_hashmap_new(ntags + 3);
Scoped<json_t *> valobj(json_object(), NULL, json_decref);
for (int ii = 0; ii < node->tag_count; ++ii) {
as_map_set(asmap,
(as_val *) as_string_new((char *) node->tags[ii].key, false),
(as_val *) as_string_new((char *) node->tags[ii].value, false));
json_object_set_new(valobj,
node->tags[ii].key,
json_string(node->tags[ii].value));
}
// Insert osmid
as_map_set(asmap,
(as_val *) as_string_new((char *) "osmid", false),
(as_val *) as_integer_new(node->id));
json_object_set_new(valobj, "osmid", json_real(node->id));
// Insert latitude and longitude
as_map_set(asmap,
(as_val *) as_string_new((char *) "latitude", false),
(as_val *) as_double_new(node->latitude));
as_map_set(asmap,
(as_val *) as_string_new((char *) "longitude", false),
(as_val *) as_double_new(node->longitude));
json_object_set_new(valobj, "latitude", json_real(node->latitude));
json_object_set_new(valobj, "longitude", json_real(node->longitude));
Scoped<char *> valstr(json_dumps(valobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
// cout << valstr << endl;
// Construct the GeoJSON loc bin value.
Scoped<json_t *> locobj(json_object(), NULL, json_decref);
json_object_set_new(locobj, "type", json_string("Point"));
Scoped<json_t *> coordobj(json_array(), NULL, json_decref);
json_array_append_new(coordobj, json_real(node->longitude));
json_array_append_new(coordobj, json_real(node->latitude));
json_object_set(locobj, "coordinates", coordobj);
Scoped<char *> locstr(json_dumps(locobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
as_key key;
as_key_init_int64(&key, g_namespace.c_str(), g_set.c_str(), node->id);
uint16_t nbins = 4;
as_record rec;
as_record_inita(&rec, nbins);
as_record_set_geojson_str(&rec, g_locbin, locstr);
as_record_set_str(&rec, g_valbin, valstr);
as_record_set_map(&rec, g_mapbin, asmap);
as_record_set_int64(&rec, g_hshbin, hshval);
as_error err;
as_status rv = aerospike_key_put(asp, &err, NULL, &key, &rec);
as_record_destroy(&rec);
as_key_destroy(&key);
if (rv != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_key_put failed: "
<< err.code << " - " << err.message);
++g_npoints;
// cout << json_dumps(rootobj, JSON_COMPACT) << endl;
return READOSM_OK;
}
uint64_t
now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * (uint64_t) 1000000) + tv.tv_usec;
}
void
setup_aerospike(aerospike * asp)
{
as_config cfg;
as_config_init(&cfg);
as_config_add_host(&cfg, g_host.c_str(), g_port);
if (! g_user.empty())
as_config_set_user(&cfg, g_user.c_str(), g_pass.c_str());
aerospike_init(asp, &cfg);
as_error err;
if (aerospike_connect(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_connect failed: "
<< err.code << " - " << err.message);
}
void
create_indexes(aerospike * asp)
{
{
as_error err;
as_index_task task;
if (aerospike_index_create(asp, &err, &task, NULL,
g_namespace.c_str(), g_set.c_str(),
g_locbin, g_locndx,
AS_INDEX_GEO2DSPHERE) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_index_create() returned "
<< err.code << " - " << err.message);
// Wait for the system metadata to spread to all nodes.
aerospike_index_create_wait(&err, &task, 0);
}
}
void
cleanup_aerospike(aerospike * asp)
{
as_error err;
if (aerospike_close(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_close failed: "
<< err.code << " - " << err.message);
aerospike_destroy(asp);
}
void
usage(int & argc, char ** & argv)
{
cerr << "usage: " << argv[0] << " [options] <infile>" << endl
<< " options:" << endl
<< " -u, --usage display usage" << endl
<< " -h, --host=HOST database host [" << DEF_HOST << "]" << endl
<< " -p, --port=PORT database port [" << DEF_PORT << "]" << endl
<< " -U, --user=USER username [<none>]" << endl
<< " -P, --password=PASSWORD password [<none>]" << endl
<< " -n, --namespace=NAMESPACE query namespace [" << DEF_NAMESPACE << "]" << endl
<< " -s, --set=SET query set [" << DEF_SET << "]" << endl
;
}
void
parse_arguments(int & argc, char ** & argv)
{
char * endp;
static struct option long_options[] =
{
{"usage", no_argument, 0, 'u'},
{"host", required_argument, 0, 'h'},
{"port", required_argument, 0, 'p'},
{"user", required_argument, 0, 'U'},
{"password", required_argument, 0, 'P'},
{"namespace", required_argument, 0, 'n'},
{"set", required_argument, 0, 's'},
{0, 0, 0, 0}
};
while (true)
{
int optndx = 0;
int opt = getopt_long(argc, argv, "uh:p:U:P:n:s:",
long_options, &optndx);
// Are we done processing arguments?
if (opt == -1)
break;
switch (opt) {
case 'u':
usage(argc, argv);
exit(0);
break;
case 'h':
g_host = optarg;
break;
case 'p':
g_port = strtol(optarg, &endp, 0);
if (*endp != '\0')
throwstream(runtime_error, "invalid port value: " << optarg);
break;
case 'U':
g_user = optarg;
break;
case 'P':
g_pass = optarg;
break;
case 'n':
g_namespace = optarg;
break;
case 's':
g_set = optarg;
break;
case'?':
// getopt_long already printed an error message
usage(argc, argv);
exit(1);
break;
default:
throwstream(runtime_error, "unexpected option: " << char(opt));
break;
}
}
if (optind >= argc)
throwstream(runtime_error, "missing input-file argument");
g_infile = argv[optind];
}
int
run(int & argc, char ** & argv)
{
parse_arguments(argc, argv);
const void * osm_handle;
int ret;
ret = readosm_open (g_infile.c_str(), &osm_handle);
if (ret != READOSM_OK)
throwstream(runtime_error, "OPEN error: " << ret);
Scoped<void const *> osm(osm_handle, NULL,
(void (*)(const void*)) readosm_close);
uint64_t t0 = now();
aerospike as;
Scoped<aerospike *> asp(&as, NULL, cleanup_aerospike);
setup_aerospike(asp);
create_indexes(asp);
ret = readosm_parse(osm_handle,
(const void *) asp,
handle_node,
NULL,
NULL);
if (ret != READOSM_OK)
throwstream(runtime_error, "PARSE error: " << ret);
uint64_t t1 = now();
cerr << "Loaded " << dec << g_npoints << " points"
<< " in " << ((t1 - t0) / 1e6) << " seconds" << endl;
return 0;
}
} // end namespace
int
main(int argc, char ** argv)
{
try
{
return run(argc, argv);
}
catch (exception const & ex)
{
cerr << "EXCEPTION: " << ex.what() << endl;
return 1;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: register3rdcomponents.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2007-07-11 15:02:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#ifndef __FRAMEWORK_JOBS_HELPONSTARTUP_HXX_
#include <jobs/helponstartup.hxx>
#endif
#ifndef __FRAMEWORK_TABWIN_TABWINFACTORY_HXX_
#include <tabwin/tabwinfactory.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_SYSTEMEXEC_HXX_
#include <dispatch/systemexec.hxx>
#endif
#ifndef __FRAMEWORK_JOBS_SHELLJOB_HXX_
#include <jobs/shelljob.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::HelpOnStartup )
COMPONENTINFO( ::framework::TabWinFactory )
COMPONENTINFO( ::framework::SystemExec )
COMPONENTINFO( ::framework::ShellJob )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::HelpOnStartup ) else
IFFACTORY( ::framework::TabWinFactory ) else
IFFACTORY( ::framework::SystemExec ) else
IFFACTORY( ::framework::ShellJob )
)
<commit_msg>INTEGRATION: CWS changefileheader (1.7.130); FILE MERGED 2008/04/01 10:58:11 thb 1.7.130.2: #i85898# Stripping all external header guards 2008/03/28 15:35:25 rt 1.7.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: register3rdcomponents.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#include <macros/registration.hxx>
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#include <jobs/helponstartup.hxx>
#include <tabwin/tabwinfactory.hxx>
#include <dispatch/systemexec.hxx>
#include <jobs/shelljob.hxx>
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::HelpOnStartup )
COMPONENTINFO( ::framework::TabWinFactory )
COMPONENTINFO( ::framework::SystemExec )
COMPONENTINFO( ::framework::ShellJob )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::HelpOnStartup ) else
IFFACTORY( ::framework::TabWinFactory ) else
IFFACTORY( ::framework::SystemExec ) else
IFFACTORY( ::framework::ShellJob )
)
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macrosmenucontroller.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:08:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
#include <uielement/macrosmenucontroller.hxx>
#include <threadhelp/resetableguard.hxx>
#include "services.h"
#include <classes/resource.hrc>
#include <classes/fwkresid.hxx>
#include <helper/imageproducer.hxx>
#include <com/sun/star/awt/MenuItemStyle.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/XModuleManager.hpp>
#include <comphelper/processfactory.hxx>
#include <vcl/svapp.hxx>
#include <vcl/i18nhelp.hxx>
#include <tools/urlobj.hxx>
#include <rtl/ustrbuf.hxx>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::util;
using namespace com::sun::star::style;
using namespace com::sun::star::container;
using namespace ::com::sun::star::frame;
namespace framework
{
class
DEFINE_XSERVICEINFO_MULTISERVICE ( MacrosMenuController ,
OWeakObject ,
SERVICENAME_POPUPMENUCONTROLLER ,
IMPLEMENTATIONNAME_MACROSMENUCONTROLLER
)
DEFINE_INIT_SERVICE ( MacrosMenuController, {} )
MacrosMenuController::MacrosMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) :
PopupMenuControllerBase( xServiceManager ),
m_xServiceManager( xServiceManager)
{
}
MacrosMenuController::~MacrosMenuController()
{
OSL_TRACE("calling dtor");
}
// private function
void MacrosMenuController::fillPopupMenu( Reference< css::awt::XPopupMenu >& rPopupMenu )
{
VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXMenu::GetImplementation( rPopupMenu );
PopupMenu* pPopupMenu = 0;
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
resetPopupMenu( rPopupMenu );
if ( pVCLPopupMenu )
pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu();
// insert basic
String aCommand = String::CreateFromAscii( ".uno:MacroDialog" );
String aDisplayName = RetrieveLabelFromCommand( aCommand );
pPopupMenu->InsertItem( 2, aDisplayName );
pPopupMenu->SetItemCommand( 2, aCommand );
//pPopupMenu->SetHelpId( 2, HID_SVX_BASIC_MACRO_ORGANIZER );
pPopupMenu->SetHelpId( 2, 40012 );
// insert providers but not basic or java
addScriptItems( pPopupMenu, 4);
}
// XEventListener
void SAL_CALL MacrosMenuController::disposing( const EventObject& ) throw ( RuntimeException )
{
Reference< css::awt::XMenuListener > xHolder(( OWeakObject *)this, UNO_QUERY );
ResetableGuard aLock( m_aLock );
OSL_TRACE("disposing");
m_xFrame.clear();
m_xDispatch.clear();
m_xServiceManager.clear();
if ( m_xPopupMenu.is() )
{
m_xPopupMenu->removeMenuListener( Reference< css::awt::XMenuListener >(( OWeakObject *)this, UNO_QUERY ));
OSL_TRACE("removed listener");
}
m_xPopupMenu.clear();
}
// XStatusListener
void SAL_CALL MacrosMenuController::statusChanged( const FeatureStateEvent& ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_xPopupMenu.is() )
{
fillPopupMenu( m_xPopupMenu );
}
}
// XMenuListener
void SAL_CALL MacrosMenuController::highlight( const css::awt::MenuEvent& ) throw (RuntimeException)
{
}
void SAL_CALL MacrosMenuController::select( const css::awt::MenuEvent& rEvent ) throw (RuntimeException)
{
Reference< css::awt::XPopupMenu > xPopupMenu;
Reference< XDispatch > xDispatch;
Reference< XMultiServiceFactory > xServiceManager;
ResetableGuard aLock( m_aLock );
xPopupMenu = m_xPopupMenu;
xDispatch = m_xDispatch;
xServiceManager = m_xServiceManager;
aLock.unlock();
if ( xPopupMenu.is() && xDispatch.is() )
{
VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXPopupMenu::GetImplementation( xPopupMenu );
if ( pVCLPopupMenu )
{
css::util::URL aTargetURL;
Sequence<PropertyValue> aArgs;
Reference< XURLTransformer > xURLTransformer( xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
PopupMenu* pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu();
aTargetURL.Complete = pPopupMenu->GetItemCommand( rEvent.MenuId );
}
xURLTransformer->parseStrict( aTargetURL );
// need to requery, since we handle more than one type of Command
// if we don't do this only .uno:ScriptOrganizer commands are executed
xDispatch = m_xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );
if( xDispatch.is() )
{
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
// xDispatch->dispatch( aTargetURL, aArgs );
Application::PostUserEvent( STATIC_LINK(0, MacrosMenuController , ExecuteHdl_Impl), pExecuteInfo );
}
else
{
}
}
}
}
IMPL_STATIC_LINK_NOINSTANCE( MacrosMenuController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
try
{
// Asynchronous execution as this can lead to our own destruction!
// Framework can recycle our current frame and the layout manager disposes all user interface
// elements if a component gets detached from its frame!
pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
}
catch ( Exception& )
{
}
delete pExecuteInfo;
return 0;
}
void SAL_CALL MacrosMenuController::activate( const css::awt::MenuEvent& ) throw (RuntimeException)
{
}
void SAL_CALL MacrosMenuController::deactivate( const css::awt::MenuEvent& ) throw (RuntimeException)
{
}
// XPopupMenuController
void SAL_CALL MacrosMenuController::setPopupMenu( const Reference< css::awt::XPopupMenu >& xPopupMenu ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( m_xFrame.is() && !m_xPopupMenu.is() )
{
// Create popup menu on demand
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
m_xPopupMenu = xPopupMenu;
m_xPopupMenu->addMenuListener( Reference< css::awt::XMenuListener >( (OWeakObject*)this, UNO_QUERY ));
Reference< XURLTransformer > xURLTransformer( m_xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY );
m_xDispatchProvider = xDispatchProvider;
com::sun::star::util::URL aTargetURL;
aTargetURL.Complete = m_aCommandURL;
xURLTransformer->parseStrict( aTargetURL );
m_xDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );
updatePopupMenu();
}
}
// XInitialization
void SAL_CALL MacrosMenuController::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
PopupMenuControllerBase::initialize( aArguments );
}
String MacrosMenuController::RetrieveLabelFromCommand( const String& aCmdURL )
{
String aLabel;
// Retrieve popup menu labels
if ( !m_aModuleIdentifier.getLength() )
{
Reference< XModuleManager > xModuleManager( ::comphelper::getProcessServiceFactory()->createInstance(
SERVICENAME_MODULEMANAGER ), UNO_QUERY_THROW );
Reference< XInterface > xIfac( m_xFrame, UNO_QUERY );
m_aModuleIdentifier = xModuleManager->identify( xIfac );
if ( m_aModuleIdentifier.getLength() > 0 )
{
Reference< XNameAccess > xNameAccess( ::comphelper::getProcessServiceFactory()->createInstance(
SERVICENAME_UICOMMANDDESCRIPTION ), UNO_QUERY );
if ( xNameAccess.is() )
{
Any a = xNameAccess->getByName( m_aModuleIdentifier );
Reference< XNameAccess > xUICommands;
a >>= m_xUICommandLabels;
}
}
}
if ( m_xUICommandLabels.is() )
{
try
{
if ( aCmdURL.Len() > 0 )
{
rtl::OUString aStr;
Sequence< PropertyValue > aPropSeq;
Any a( m_xUICommandLabels->getByName( aCmdURL ));
if ( a >>= aPropSeq )
{
for ( sal_Int32 i = 0; i < aPropSeq.getLength(); i++ )
{
if ( aPropSeq[i].Name.equalsAscii( "Label" ))
{
aPropSeq[i].Value >>= aStr;
break;
}
}
}
aLabel = aStr;
}
}
catch ( com::sun::star::uno::Exception& )
{
}
}
return aLabel;
}
void MacrosMenuController::addScriptItems( PopupMenu* pPopupMenu, USHORT startItemId )
{
const String aCmdBase = String::CreateFromAscii( ".uno:ScriptOrganizer?ScriptOrganizer.Language:string=" );
const String ellipsis = String::CreateFromAscii( "..." );
const ::rtl::OUString providerKey =
::rtl::OUString::createFromAscii("com.sun.star.script.provider.ScriptProviderFor" );
const ::rtl::OUString languageProviderName =
::rtl::OUString::createFromAscii("com.sun.star.script.provider.LanguageScriptProvider" );
USHORT itemId = startItemId;
Reference< XContentEnumerationAccess > xEnumAccess = Reference< XContentEnumerationAccess >( m_xServiceManager, UNO_QUERY_THROW );
Reference< XEnumeration > xEnum = xEnumAccess->createContentEnumeration ( languageProviderName );
while ( xEnum->hasMoreElements() )
{
Reference< XServiceInfo > xServiceInfo;
if ( sal_False == ( xEnum->nextElement() >>= xServiceInfo ) )
{
break;
}
Sequence< ::rtl::OUString > serviceNames = xServiceInfo->getSupportedServiceNames();
if ( serviceNames.getLength() > 0 )
{
for ( sal_Int32 index = 0; index < serviceNames.getLength(); index++ )
{
if ( serviceNames[ index ].indexOf( providerKey ) == 0 )
{
::rtl::OUString serviceName = serviceNames[ index ];
String aCommand = aCmdBase;
String aDisplayName = String( serviceName.copy( providerKey.getLength() ) );
if( aDisplayName.Equals( String::CreateFromAscii( "Java" ) ) || aDisplayName.Equals( String::CreateFromAscii( "Basic" ) ) )
{
// no entries for Java & Basic added elsewhere
break;
}
aCommand.Append( aDisplayName );
aDisplayName.Append( ellipsis );
pPopupMenu->InsertItem( itemId, aDisplayName );
pPopupMenu->SetItemCommand( itemId, aCommand );
//pPopupMenu->SetHelpId( itemId, HID_SVX_COMMON_MACRO_ORGANIZER );
pPopupMenu->SetHelpId( itemId, 40014 );
itemId++;
break;
}
}
}
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.10.224); FILE MERGED 2008/03/28 15:35:35 rt 1.10.224.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macrosmenucontroller.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
#include <uielement/macrosmenucontroller.hxx>
#include <threadhelp/resetableguard.hxx>
#include "services.h"
#include <classes/resource.hrc>
#include <classes/fwkresid.hxx>
#include <helper/imageproducer.hxx>
#include <com/sun/star/awt/MenuItemStyle.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/XModuleManager.hpp>
#include <comphelper/processfactory.hxx>
#include <vcl/svapp.hxx>
#include <vcl/i18nhelp.hxx>
#include <tools/urlobj.hxx>
#include <rtl/ustrbuf.hxx>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::util;
using namespace com::sun::star::style;
using namespace com::sun::star::container;
using namespace ::com::sun::star::frame;
namespace framework
{
class
DEFINE_XSERVICEINFO_MULTISERVICE ( MacrosMenuController ,
OWeakObject ,
SERVICENAME_POPUPMENUCONTROLLER ,
IMPLEMENTATIONNAME_MACROSMENUCONTROLLER
)
DEFINE_INIT_SERVICE ( MacrosMenuController, {} )
MacrosMenuController::MacrosMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) :
PopupMenuControllerBase( xServiceManager ),
m_xServiceManager( xServiceManager)
{
}
MacrosMenuController::~MacrosMenuController()
{
OSL_TRACE("calling dtor");
}
// private function
void MacrosMenuController::fillPopupMenu( Reference< css::awt::XPopupMenu >& rPopupMenu )
{
VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXMenu::GetImplementation( rPopupMenu );
PopupMenu* pPopupMenu = 0;
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
resetPopupMenu( rPopupMenu );
if ( pVCLPopupMenu )
pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu();
// insert basic
String aCommand = String::CreateFromAscii( ".uno:MacroDialog" );
String aDisplayName = RetrieveLabelFromCommand( aCommand );
pPopupMenu->InsertItem( 2, aDisplayName );
pPopupMenu->SetItemCommand( 2, aCommand );
//pPopupMenu->SetHelpId( 2, HID_SVX_BASIC_MACRO_ORGANIZER );
pPopupMenu->SetHelpId( 2, 40012 );
// insert providers but not basic or java
addScriptItems( pPopupMenu, 4);
}
// XEventListener
void SAL_CALL MacrosMenuController::disposing( const EventObject& ) throw ( RuntimeException )
{
Reference< css::awt::XMenuListener > xHolder(( OWeakObject *)this, UNO_QUERY );
ResetableGuard aLock( m_aLock );
OSL_TRACE("disposing");
m_xFrame.clear();
m_xDispatch.clear();
m_xServiceManager.clear();
if ( m_xPopupMenu.is() )
{
m_xPopupMenu->removeMenuListener( Reference< css::awt::XMenuListener >(( OWeakObject *)this, UNO_QUERY ));
OSL_TRACE("removed listener");
}
m_xPopupMenu.clear();
}
// XStatusListener
void SAL_CALL MacrosMenuController::statusChanged( const FeatureStateEvent& ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_xPopupMenu.is() )
{
fillPopupMenu( m_xPopupMenu );
}
}
// XMenuListener
void SAL_CALL MacrosMenuController::highlight( const css::awt::MenuEvent& ) throw (RuntimeException)
{
}
void SAL_CALL MacrosMenuController::select( const css::awt::MenuEvent& rEvent ) throw (RuntimeException)
{
Reference< css::awt::XPopupMenu > xPopupMenu;
Reference< XDispatch > xDispatch;
Reference< XMultiServiceFactory > xServiceManager;
ResetableGuard aLock( m_aLock );
xPopupMenu = m_xPopupMenu;
xDispatch = m_xDispatch;
xServiceManager = m_xServiceManager;
aLock.unlock();
if ( xPopupMenu.is() && xDispatch.is() )
{
VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXPopupMenu::GetImplementation( xPopupMenu );
if ( pVCLPopupMenu )
{
css::util::URL aTargetURL;
Sequence<PropertyValue> aArgs;
Reference< XURLTransformer > xURLTransformer( xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
PopupMenu* pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu();
aTargetURL.Complete = pPopupMenu->GetItemCommand( rEvent.MenuId );
}
xURLTransformer->parseStrict( aTargetURL );
// need to requery, since we handle more than one type of Command
// if we don't do this only .uno:ScriptOrganizer commands are executed
xDispatch = m_xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );
if( xDispatch.is() )
{
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
// xDispatch->dispatch( aTargetURL, aArgs );
Application::PostUserEvent( STATIC_LINK(0, MacrosMenuController , ExecuteHdl_Impl), pExecuteInfo );
}
else
{
}
}
}
}
IMPL_STATIC_LINK_NOINSTANCE( MacrosMenuController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
try
{
// Asynchronous execution as this can lead to our own destruction!
// Framework can recycle our current frame and the layout manager disposes all user interface
// elements if a component gets detached from its frame!
pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
}
catch ( Exception& )
{
}
delete pExecuteInfo;
return 0;
}
void SAL_CALL MacrosMenuController::activate( const css::awt::MenuEvent& ) throw (RuntimeException)
{
}
void SAL_CALL MacrosMenuController::deactivate( const css::awt::MenuEvent& ) throw (RuntimeException)
{
}
// XPopupMenuController
void SAL_CALL MacrosMenuController::setPopupMenu( const Reference< css::awt::XPopupMenu >& xPopupMenu ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( m_xFrame.is() && !m_xPopupMenu.is() )
{
// Create popup menu on demand
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
m_xPopupMenu = xPopupMenu;
m_xPopupMenu->addMenuListener( Reference< css::awt::XMenuListener >( (OWeakObject*)this, UNO_QUERY ));
Reference< XURLTransformer > xURLTransformer( m_xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY );
m_xDispatchProvider = xDispatchProvider;
com::sun::star::util::URL aTargetURL;
aTargetURL.Complete = m_aCommandURL;
xURLTransformer->parseStrict( aTargetURL );
m_xDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );
updatePopupMenu();
}
}
// XInitialization
void SAL_CALL MacrosMenuController::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
PopupMenuControllerBase::initialize( aArguments );
}
String MacrosMenuController::RetrieveLabelFromCommand( const String& aCmdURL )
{
String aLabel;
// Retrieve popup menu labels
if ( !m_aModuleIdentifier.getLength() )
{
Reference< XModuleManager > xModuleManager( ::comphelper::getProcessServiceFactory()->createInstance(
SERVICENAME_MODULEMANAGER ), UNO_QUERY_THROW );
Reference< XInterface > xIfac( m_xFrame, UNO_QUERY );
m_aModuleIdentifier = xModuleManager->identify( xIfac );
if ( m_aModuleIdentifier.getLength() > 0 )
{
Reference< XNameAccess > xNameAccess( ::comphelper::getProcessServiceFactory()->createInstance(
SERVICENAME_UICOMMANDDESCRIPTION ), UNO_QUERY );
if ( xNameAccess.is() )
{
Any a = xNameAccess->getByName( m_aModuleIdentifier );
Reference< XNameAccess > xUICommands;
a >>= m_xUICommandLabels;
}
}
}
if ( m_xUICommandLabels.is() )
{
try
{
if ( aCmdURL.Len() > 0 )
{
rtl::OUString aStr;
Sequence< PropertyValue > aPropSeq;
Any a( m_xUICommandLabels->getByName( aCmdURL ));
if ( a >>= aPropSeq )
{
for ( sal_Int32 i = 0; i < aPropSeq.getLength(); i++ )
{
if ( aPropSeq[i].Name.equalsAscii( "Label" ))
{
aPropSeq[i].Value >>= aStr;
break;
}
}
}
aLabel = aStr;
}
}
catch ( com::sun::star::uno::Exception& )
{
}
}
return aLabel;
}
void MacrosMenuController::addScriptItems( PopupMenu* pPopupMenu, USHORT startItemId )
{
const String aCmdBase = String::CreateFromAscii( ".uno:ScriptOrganizer?ScriptOrganizer.Language:string=" );
const String ellipsis = String::CreateFromAscii( "..." );
const ::rtl::OUString providerKey =
::rtl::OUString::createFromAscii("com.sun.star.script.provider.ScriptProviderFor" );
const ::rtl::OUString languageProviderName =
::rtl::OUString::createFromAscii("com.sun.star.script.provider.LanguageScriptProvider" );
USHORT itemId = startItemId;
Reference< XContentEnumerationAccess > xEnumAccess = Reference< XContentEnumerationAccess >( m_xServiceManager, UNO_QUERY_THROW );
Reference< XEnumeration > xEnum = xEnumAccess->createContentEnumeration ( languageProviderName );
while ( xEnum->hasMoreElements() )
{
Reference< XServiceInfo > xServiceInfo;
if ( sal_False == ( xEnum->nextElement() >>= xServiceInfo ) )
{
break;
}
Sequence< ::rtl::OUString > serviceNames = xServiceInfo->getSupportedServiceNames();
if ( serviceNames.getLength() > 0 )
{
for ( sal_Int32 index = 0; index < serviceNames.getLength(); index++ )
{
if ( serviceNames[ index ].indexOf( providerKey ) == 0 )
{
::rtl::OUString serviceName = serviceNames[ index ];
String aCommand = aCmdBase;
String aDisplayName = String( serviceName.copy( providerKey.getLength() ) );
if( aDisplayName.Equals( String::CreateFromAscii( "Java" ) ) || aDisplayName.Equals( String::CreateFromAscii( "Basic" ) ) )
{
// no entries for Java & Basic added elsewhere
break;
}
aCommand.Append( aDisplayName );
aDisplayName.Append( ellipsis );
pPopupMenu->InsertItem( itemId, aDisplayName );
pPopupMenu->SetItemCommand( itemId, aCommand );
//pPopupMenu->SetHelpId( itemId, HID_SVX_COMMON_MACRO_ORGANIZER );
pPopupMenu->SetHelpId( itemId, 40014 );
itemId++;
break;
}
}
}
}
}
}
<|endoftext|>
|
<commit_before>// @(#)root/base:$Id$
// Author: Maarten Ballintijn 21/06/2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TParameter<AParamType> //
// //
// Named parameter, streamable and storable. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TParameter.h"
templateClassImp(TParameter)
// Specialization of Merge for Bool_t to make windows happy
template <>
Int_t TParameter<Bool_t>::Merge(TCollection *in)
{
// Merge objects in the list.
// Returns the number of objects that were in the list.
TIter nxo(in);
Int_t n = 0;
while (TObject *o = nxo()) {
TParameter<Bool_t> *c = dynamic_cast<TParameter<Bool_t> *>(o);
if (c) {
if (TestBit(TParameter::kMultiply))
fVal *= c->GetVal();
else
fVal += c->GetVal();
n++;
}
}
return n;
}
<commit_msg>From Gerri: fix warning on Windows.<commit_after>// @(#)root/base:$Id$
// Author: Maarten Ballintijn 21/06/2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TParameter<AParamType> //
// //
// Named parameter, streamable and storable. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TParameter.h"
templateClassImp(TParameter)
// Specialization of Merge for Bool_t to make windows happy
template <>
Int_t TParameter<Bool_t>::Merge(TCollection *in)
{
// Merge objects in the list.
// Returns the number of objects that were in the list.
TIter nxo(in);
Int_t n = 0;
while (TObject *o = nxo()) {
TParameter<Bool_t> *c = dynamic_cast<TParameter<Bool_t> *>(o);
if (c) {
if (TestBit(TParameter::kMultiply))
fVal &= (Bool_t) c->GetVal();
else
fVal |= (Bool_t) c->GetVal();
n++;
}
}
return n;
}
<|endoftext|>
|
<commit_before>/* SHAPE - waveshaping instrument
This differs from insts.std/WAVESHAPE in that it accepts input from
a file or bus, and it offers a different way of performing amplitude
normalization.
p0 = output start time
p1 = input start time
p2 = input duration
p3 = amplitude multiplier *
p4 = minimum distortion index
p5 = maximum distortion index
p6 = reference to an amplitude normalization table, or 0 for no norm. **
p7 = input channel [optional, default is 0]
p8 = percent of signal to left output channel [optional, default is .5]
p9 = reference to waveshaping tranfer function table [optional; if missing,
must use gen 2] ***
p10 = index guide [optional; if missing, can use gen 3] ****
p3 (amplitude), p4 (min index), p5 (max index), p8 (pan) and p10 (index)
can receive dynamic updates from a table or real-time control source.
The amplitude normalization function allows you to decouple amplitude and
timbral change, to some extent. (Read about this in the Roads "Computer
Music Tutorial" chapter on waveshaping.) The table maps incoming signal
amplitudes, on the X axis, to amplitude multipliers, on the Y axis. The
multipliers should be from 0 to 1. The amplitude multipliers are applied
to the output signal, along with whatever overall amplitude curve is in
effect. Generally, you'll want a normalization curve that starts high and
moves lower (see SHAPE2.sco) for the higher signal amplitudes. This will
keep the bright and dark timbres more equal in amplitude.
----
Notes about backward compatibility with pre-v4 scores:
* If an old-style gen table 1 is present, its values will be multiplied
by the p3 amplitude multiplier, even if the latter is dynamic.
** If p6 is a non-zero constant, then that is the number of an old-style
gen table slot to use for the amplitude normalization function.
*** If p9 is missing, you must use an old-style gen table 2 for the
waveshaping transfer function.
**** If p10 is missing, you can use an old-style gen table 3 for the
distortion index curve. Otherwise, a constant 1.0 will be used.
John Gibson <johgibso at indiana dot edu>, 3 Jan 2002; rev for v4, 7/21/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <math.h>
#include <Instrument.h>
#include <PField.h>
#include "SHAPE.h"
#include <rt.h>
#include <rtdefs.h>
SHAPE :: SHAPE() : Instrument()
{
in = NULL;
amp_table = NULL;
ampnorm = NULL;
index_table = NULL;
norm_index = 0.0;
branch = 0;
}
SHAPE :: ~SHAPE()
{
delete [] in;
delete amp_table;
delete index_table;
delete shaper;
delete ampnorm;
delete dcblocker;
}
int SHAPE :: init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float inskip = p[1];
float dur = p[2];
amp = p[3];
min_index = p[4];
max_index = p[5];
int ampnorm_genno = (int) p[6];
inchan = n_args > 7 ? (int) p[7] : 0; /* default is chan 0 */
if (n_args < 7)
return die("SHAPE", "Needs at least 7 arguments.");
nsamps = rtsetoutput(outskip, dur, this);
if (rtsetinput(inskip, this) != 0)
return DONT_SCHEDULE;
if (inchan >= inputChannels())
return die("SHAPE", "You asked for channel %d of a %d-channel file.",
inchan, inputChannels());
if (max_index < min_index)
return die("SHAPE",
"Max. distortion index must not be less than min. index.");
double *function = floc(1);
if (function) {
int len = fsize(1);
amp_table = new TableL(dur, function, len);
}
function = NULL;
int tablelen = 0;
if (n_args > 9) { // handle table coming in as optional p9 TablePField
const PField &field = getPField(9);
tablelen = field.values();
function = (double *) field;
}
if (function == NULL) {
function = floc(2);
if (function == NULL)
return die("SHAPE", "Either use the transfer function pfield (p9) "
"or make an old-style gen function in slot 2.");
tablelen = fsize(2);
}
shaper = new WavShape();
shaper->setTransferFunc(function, tablelen);
function = NULL;
if (n_args > 10) { // handle table coming in as optional p10 TablePField
const PField &field = getPField(10);
int len = field.values();
function = (double *) field;
if (function)
index_table = new TableL(dur, function, len);
}
if (function == NULL) {
function = floc(3);
if (function) {
int len = fsize(3);
index_table = new TableL(dur, function, len);
}
else {
advise("SHAPE", "Setting distortion index curve to all 1's.");
index = 1.0;
}
}
/* Construct the <ampnorm> WavShape object if (1) p6 is a TablePField, or
(2) if p6 is non-zero, in which case use p6 as the gen slot for the
amp norm function. If p6 is zero, then don't construct <ampnorm>.
*/
function = NULL;
const PField &field = getPField(6);
tablelen = field.values();
function = (double *) field;
if (function == NULL) { // no table pfield
if (ampnorm_genno > 0) {
function = floc(ampnorm_genno);
if (function == NULL)
return die("SHAPE", "You specified table %d as the amplitude "
"normalization function, but you didn't create the table.",
ampnorm_genno);
tablelen = fsize(ampnorm_genno);
}
}
if (function) {
ampnorm = new WavShape();
ampnorm->setTransferFunc(function, tablelen);
}
dcblocker = new DCBlock();
skip = (int) (SR / (float) resetval);
return nSamps();
}
int SHAPE :: configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
void SHAPE :: doupdate()
{
double p[11];
update(p, 11, kAmp | kMinIndex | kMaxIndex | kPan | kIndex);
amp = p[3];
if (amp_table)
amp *= amp_table->tick(currentFrame(), 1.0);
min_index = p[4];
max_index = p[5];
if (max_index < min_index)
max_index = min_index;
if (nargs > 10) // use index PField
index = p[10];
else if (index_table) {
index = index_table->tick(currentFrame(), 1.0);
index = min_index + (index * (max_index - min_index));
}
// scale index vals to range [-1, 1] in order to use WavShape
if (ampnorm)
norm_index = (index / (max_index / 2.0)) - 1.0;
pctleft = nargs > 8 ? p[8] : 0.5; // default is .5
}
int SHAPE :: run()
{
const int samps = framesToRun() * inputChannels();
rtgetin(in, this, samps);
for (int i = 0; i < samps; i += inputChannels()) {
if (--branch <= 0) {
doupdate();
branch = skip;
}
// NB: WavShape deals with samples in range [-1, 1].
float insig = in[i + inchan] * (1.0 / 32768.0);
float outsig = shaper->tick(insig * index);
if (outsig) {
if (ampnorm)
outsig = dcblocker->tick(outsig) * ampnorm->tick(norm_index);
else
outsig = dcblocker->tick(outsig);
}
float out[2];
out[0] = outsig * amp * 32768.0;
if (outputChannels() == 2) {
out[1] = out[0] * (1.0 - pctleft);
out[0] *= pctleft;
}
rtaddout(out);
increment();
}
return framesToRun();
}
Instrument *makeSHAPE()
{
SHAPE *inst;
inst = new SHAPE();
inst->set_bus_config("SHAPE");
return inst;
}
void rtprofile()
{
RT_INTRO("SHAPE", makeSHAPE);
}
<commit_msg>Fix index handling.<commit_after>/* SHAPE - waveshaping instrument
This differs from insts.std/WAVESHAPE in that it accepts input from
a file or bus, and it offers a different way of performing amplitude
normalization.
p0 = output start time
p1 = input start time
p2 = input duration
p3 = amplitude multiplier *
p4 = minimum distortion index
p5 = maximum distortion index
p6 = reference to an amplitude normalization table, or 0 for no norm. **
p7 = input channel [optional, default is 0]
p8 = percent of signal to left output channel [optional, default is .5]
p9 = reference to waveshaping tranfer function table [optional; if missing,
must use gen 2] ***
p10 = index guide [optional; if missing, can use gen 3] ****
p3 (amplitude), p4 (min index), p5 (max index), p8 (pan) and p10 (index)
can receive dynamic updates from a table or real-time control source.
The amplitude normalization function allows you to decouple amplitude and
timbral change, to some extent. (Read about this in the Roads "Computer
Music Tutorial" chapter on waveshaping.) The table maps incoming signal
amplitudes, on the X axis, to amplitude multipliers, on the Y axis. The
multipliers should be from 0 to 1. The amplitude multipliers are applied
to the output signal, along with whatever overall amplitude curve is in
effect. Generally, you'll want a normalization curve that starts high and
moves lower (see SHAPE2.sco) for the higher signal amplitudes. This will
keep the bright and dark timbres more equal in amplitude.
----
Notes about backward compatibility with pre-v4 scores:
* If an old-style gen table 1 is present, its values will be multiplied
by the p3 amplitude multiplier, even if the latter is dynamic.
** If p6 is a non-zero constant, then that is the number of an old-style
gen table slot to use for the amplitude normalization function.
*** If p9 is missing, you must use an old-style gen table 2 for the
waveshaping transfer function.
**** If p10 is missing, you can use an old-style gen table 3 for the
distortion index curve. Otherwise, a constant 1.0 will be used.
John Gibson <johgibso at indiana dot edu>, 3 Jan 2002; rev for v4, 7/21/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <math.h>
#include <Instrument.h>
#include <PField.h>
#include "SHAPE.h"
#include <rt.h>
#include <rtdefs.h>
SHAPE :: SHAPE() : Instrument()
{
in = NULL;
amp_table = NULL;
ampnorm = NULL;
index_table = NULL;
norm_index = 0.0;
branch = 0;
}
SHAPE :: ~SHAPE()
{
delete [] in;
delete amp_table;
delete index_table;
delete shaper;
delete ampnorm;
delete dcblocker;
}
int SHAPE :: init(double p[], int n_args)
{
nargs = n_args;
float outskip = p[0];
float inskip = p[1];
float dur = p[2];
amp = p[3];
min_index = p[4];
max_index = p[5];
int ampnorm_genno = (int) p[6];
inchan = n_args > 7 ? (int) p[7] : 0; /* default is chan 0 */
if (n_args < 7)
return die("SHAPE", "Needs at least 7 arguments.");
nsamps = rtsetoutput(outskip, dur, this);
if (rtsetinput(inskip, this) != 0)
return DONT_SCHEDULE;
if (inchan >= inputChannels())
return die("SHAPE", "You asked for channel %d of a %d-channel file.",
inchan, inputChannels());
if (max_index < min_index)
return die("SHAPE",
"Max. distortion index must not be less than min. index.");
double *function = floc(1);
if (function) {
int len = fsize(1);
amp_table = new TableL(dur, function, len);
}
function = NULL;
int tablelen = 0;
if (n_args > 9) { // handle table coming in as optional p9 TablePField
const PField &field = getPField(9);
tablelen = field.values();
function = (double *) field;
}
if (function == NULL) {
function = floc(2);
if (function == NULL)
return die("SHAPE", "Either use the transfer function pfield (p9) "
"or make an old-style gen function in slot 2.");
tablelen = fsize(2);
}
shaper = new WavShape();
shaper->setTransferFunc(function, tablelen);
function = NULL;
if (n_args < 11) { // no p10 guide PField, must use gen table
function = floc(3);
if (function) {
int len = fsize(3);
index_table = new TableL(dur, function, len);
}
else
advise("SHAPE", "Setting distortion index curve to all 1's.");
}
/* Construct the <ampnorm> WavShape object if (1) p6 is a TablePField, or
(2) if p6 is non-zero, in which case use p6 as the gen slot for the
amp norm function. If p6 is zero, then don't construct <ampnorm>.
*/
function = NULL;
const PField &field = getPField(6);
tablelen = field.values();
function = (double *) field;
if (function == NULL) { // no table pfield
if (ampnorm_genno > 0) {
function = floc(ampnorm_genno);
if (function == NULL)
return die("SHAPE", "You specified table %d as the amplitude "
"normalization function, but you didn't create the table.",
ampnorm_genno);
tablelen = fsize(ampnorm_genno);
}
}
if (function) {
ampnorm = new WavShape();
ampnorm->setTransferFunc(function, tablelen);
}
dcblocker = new DCBlock();
skip = (int) (SR / (float) resetval);
return nSamps();
}
int SHAPE :: configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
void SHAPE :: doupdate()
{
double p[11];
update(p, 11, kAmp | kMinIndex | kMaxIndex | kPan | kIndex);
amp = p[3];
if (amp_table)
amp *= amp_table->tick(currentFrame(), 1.0);
min_index = p[4];
max_index = p[5];
if (max_index < min_index)
max_index = min_index;
float rawindex;
if (nargs > 10) // use index PField
rawindex = p[10];
else if (index_table) // use gen 3
rawindex = index_table->tick(currentFrame(), 1.0);
else
rawindex = 1.0;
index = min_index + (rawindex * (max_index - min_index));
// scale index vals to range [-1, 1] in order to use WavShape
if (ampnorm)
norm_index = (index / (max_index / 2.0)) - 1.0;
pctleft = nargs > 8 ? p[8] : 0.5; // default is .5
}
int SHAPE :: run()
{
const int samps = framesToRun() * inputChannels();
rtgetin(in, this, samps);
for (int i = 0; i < samps; i += inputChannels()) {
if (--branch <= 0) {
doupdate();
branch = skip;
}
// NB: WavShape deals with samples in range [-1, 1].
float insig = in[i + inchan] * (1.0 / 32768.0);
float outsig = shaper->tick(insig * index);
if (outsig) {
if (ampnorm)
outsig = dcblocker->tick(outsig) * ampnorm->tick(norm_index);
else
outsig = dcblocker->tick(outsig);
}
float out[2];
out[0] = outsig * amp * 32768.0;
if (outputChannels() == 2) {
out[1] = out[0] * (1.0 - pctleft);
out[0] *= pctleft;
}
rtaddout(out);
increment();
}
return framesToRun();
}
Instrument *makeSHAPE()
{
SHAPE *inst;
inst = new SHAPE();
inst->set_bus_config("SHAPE");
return inst;
}
void rtprofile()
{
RT_INTRO("SHAPE", makeSHAPE);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <depthai-shared/datatype/RawIMUData.hpp>
#include <nlohmann/json.hpp>
namespace dai {
/**
* Available IMU sensors.
* More details about each sensor can be found in the datasheet:
* \link https://www.ceva-dsp.com/wp-content/uploads/2019/10/BNO080_085-Datasheet.pdf \endlink
*/
enum class IMUSensor : std::int32_t {
/**
* Section 2.1.1
*
* Acceleration of the device without any postprocessing, straight from the sensor.
* Units are [m/s^2]
*/
ACCELEROMETER_RAW = 0x14,
/**
* Section 2.1.1
*
* Acceleration of the device including gravity.
* Units are [m/s^2]
*/
ACCELEROMETER = 0x01,
/**
* Section 2.1.1
*
* Acceleration of the device with gravity removed.
* Units are [m/s^2]
*/
LINEAR_ACCELERATION = 0x04,
/**
* Section 2.1.1
*
* Gravity.
* Units are [m/s^2]
*/
GRAVITY = 0x06,
/**
* Section 2.1.2
*
* The angular velocity of the device without any postprocessing, straight from the sensor.
* Units are [rad/s]
*/
GYROSCOPE_RAW = 0x15,
/**
* Section 2.1.2
*
* The angular velocity of the device.
* Units are [rad/s]
*/
GYROSCOPE_CALIBRATED = 0x02,
/**
* Section 2.1.2
*
* Angular velocity without bias compensation.
* Units are [rad/s]
*/
GYROSCOPE_UNCALIBRATED = 0x07,
/**
* Section 2.1.3
*
* Magnetic field measurement without any postprocessing, straight from the sensor.
* Units are [uTesla]
*/
MAGNETOMETER_RAW = 0x16,
/**
* Section 2.1.3
*
* The fully calibrated magnetic field measurement.
* Units are [uTesla]
*/
MAGNETOMETER_CALIBRATED = 0x03,
/**
* Section 2.1.3
*
* The magnetic field measurement without hard-iron offset applied.
* Units are [uTesla]
*/
MAGNETOMETER_UNCALIBRATED = 0x0f,
/**
* Section 2.2
*
* The rotation vector provides an orientation output that is expressed as a quaternion referenced to magnetic north
* and gravity. It is produced by fusing the outputs of the accelerometer, gyroscope and magnetometer. The rotation
* vector is the most accurate orientation estimate available. The magnetometer provides correction in yaw to
* reduce drift and the gyroscope enables the most responsive performance.
*/
ROTATION_VECTOR = 0x05,
/**
* Section 2.2
*
* The game rotation vector is an orientation output that is expressed as a quaternion with no specific reference for
* heading, while roll and pitch are referenced against gravity. It is produced by fusing the outputs of the
* accelerometer and the gyroscope (i.e. no magnetometer). The game rotation vector does not use the
* magnetometer to correct the gyroscopes drift in yaw. This is a deliberate omission (as specified by Google) to
* allow gaming applications to use a smoother representation of the orientation without the jumps that an
* instantaneous correction provided by a magnetic field update could provide. Long term the output will likely drift in
* yaw due to the characteristics of gyroscopes, but this is seen as preferable for this output versus a corrected output.
*/
GAME_ROTATION_VECTOR = 0x08,
/**
* Section 2.2
*
* The geomagnetic rotation vector is an orientation output that is expressed as a quaternion referenced to magnetic
* north and gravity. It is produced by fusing the outputs of the accelerometer and magnetometer. The gyroscope is
* specifically excluded in order to produce a rotation vector output using less power than is required to produce the
* rotation vector of section 2.2.4. The consequences of removing the gyroscope are:
* Less responsive output since the highly dynamic outputs of the gyroscope are not used
* More errors in the presence of varying magnetic fields.
*/
GEOMAGNETIC_ROTATION_VECTOR = 0x09,
/**
* Section 2.2
*
* Estimates of the magnetic field and the roll/pitch of the device can create a potential correction in the rotation
* vector produced. For applications (typically augmented or virtual reality applications) where a sudden jump can be
* disturbing, the output is adjusted to prevent these jumps in a manner that takes account of the velocity of the
* sensor system.
*/
ARVR_STABILIZED_ROTATION_VECTOR = 0x28,
/**
* Section 2.2
*
* While the magnetometer is removed from the calculation of the game rotation vector, the accelerometer itself can
* create a potential correction in the rotation vector produced (i.e. the estimate of gravity changes). For applications
* (typically augmented or virtual reality applications) where a sudden jump can be disturbing, the output is adjusted
* to prevent these jumps in a manner that takes account of the velocity of the sensor system. This process is called
* AR/VR stabilization.
*/
ARVR_STABILIZED_GAME_ROTATION_VECTOR = 0x29,
// GYRO_INTEGRATED_ROTATION_VECTOR = 0x2A,
};
struct IMUSensorConfig {
/* Sensitivity enabled */
bool sensitivityEnabled = false;
/* Change sensitivity - true if relative; false if absolute */
bool sensitivityRelative = false; /**< @brief Change reports relative (vs absolute) */
// TODO write utility function to convert float to Q point notation, sensor specific
/* 16-bit signed fixed point integer.
* In case of absolute sensitivity represents the value a
* sensor output must exceed in order to trigger another input
* report.
* In case of relative sensitivity represents the the amount
* by which a sensor output must change from the previous
* input report in order to trigger another input report
* A setting of 0 causes all reports to be sent.
*/
uint16_t changeSensitivity = 0; /**< @brief Report-on-change threshold */
/* Rate of reports per second. (hertz)
* 0 means disabled
*/
uint32_t reportRate = 100;
IMUSensor sensorId;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUSensorConfig, sensitivityEnabled, sensitivityRelative, changeSensitivity, reportRate, sensorId);
struct IMUProperties {
/* Enabled IMU sensors */
std::vector<IMUSensorConfig> imuSensors;
/* Above this packet threshold data will be sent to host, if queue is not blocked */
std::int32_t batchReportThreshold = 1;
/* Maximum number of IMU packets in a batch. Maximum 5. */
std::int32_t maxBatchReports = 5;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUProperties, imuSensors, batchReportThreshold, maxBatchReports);
} // namespace dai
<commit_msg>Fixed link render issue<commit_after>#pragma once
#include <depthai-shared/datatype/RawIMUData.hpp>
#include <nlohmann/json.hpp>
namespace dai {
/**
* Available IMU sensors.
* More details about each sensor can be found in the datasheet:
*
* https://www.ceva-dsp.com/wp-content/uploads/2019/10/BNO080_085-Datasheet.pdf
*/
enum class IMUSensor : std::int32_t {
/**
* Section 2.1.1
*
* Acceleration of the device without any postprocessing, straight from the sensor.
* Units are [m/s^2]
*/
ACCELEROMETER_RAW = 0x14,
/**
* Section 2.1.1
*
* Acceleration of the device including gravity.
* Units are [m/s^2]
*/
ACCELEROMETER = 0x01,
/**
* Section 2.1.1
*
* Acceleration of the device with gravity removed.
* Units are [m/s^2]
*/
LINEAR_ACCELERATION = 0x04,
/**
* Section 2.1.1
*
* Gravity.
* Units are [m/s^2]
*/
GRAVITY = 0x06,
/**
* Section 2.1.2
*
* The angular velocity of the device without any postprocessing, straight from the sensor.
* Units are [rad/s]
*/
GYROSCOPE_RAW = 0x15,
/**
* Section 2.1.2
*
* The angular velocity of the device.
* Units are [rad/s]
*/
GYROSCOPE_CALIBRATED = 0x02,
/**
* Section 2.1.2
*
* Angular velocity without bias compensation.
* Units are [rad/s]
*/
GYROSCOPE_UNCALIBRATED = 0x07,
/**
* Section 2.1.3
*
* Magnetic field measurement without any postprocessing, straight from the sensor.
* Units are [uTesla]
*/
MAGNETOMETER_RAW = 0x16,
/**
* Section 2.1.3
*
* The fully calibrated magnetic field measurement.
* Units are [uTesla]
*/
MAGNETOMETER_CALIBRATED = 0x03,
/**
* Section 2.1.3
*
* The magnetic field measurement without hard-iron offset applied.
* Units are [uTesla]
*/
MAGNETOMETER_UNCALIBRATED = 0x0f,
/**
* Section 2.2
*
* The rotation vector provides an orientation output that is expressed as a quaternion referenced to magnetic north
* and gravity. It is produced by fusing the outputs of the accelerometer, gyroscope and magnetometer. The rotation
* vector is the most accurate orientation estimate available. The magnetometer provides correction in yaw to
* reduce drift and the gyroscope enables the most responsive performance.
*/
ROTATION_VECTOR = 0x05,
/**
* Section 2.2
*
* The game rotation vector is an orientation output that is expressed as a quaternion with no specific reference for
* heading, while roll and pitch are referenced against gravity. It is produced by fusing the outputs of the
* accelerometer and the gyroscope (i.e. no magnetometer). The game rotation vector does not use the
* magnetometer to correct the gyroscopes drift in yaw. This is a deliberate omission (as specified by Google) to
* allow gaming applications to use a smoother representation of the orientation without the jumps that an
* instantaneous correction provided by a magnetic field update could provide. Long term the output will likely drift in
* yaw due to the characteristics of gyroscopes, but this is seen as preferable for this output versus a corrected output.
*/
GAME_ROTATION_VECTOR = 0x08,
/**
* Section 2.2
*
* The geomagnetic rotation vector is an orientation output that is expressed as a quaternion referenced to magnetic
* north and gravity. It is produced by fusing the outputs of the accelerometer and magnetometer. The gyroscope is
* specifically excluded in order to produce a rotation vector output using less power than is required to produce the
* rotation vector of section 2.2.4. The consequences of removing the gyroscope are:
* Less responsive output since the highly dynamic outputs of the gyroscope are not used
* More errors in the presence of varying magnetic fields.
*/
GEOMAGNETIC_ROTATION_VECTOR = 0x09,
/**
* Section 2.2
*
* Estimates of the magnetic field and the roll/pitch of the device can create a potential correction in the rotation
* vector produced. For applications (typically augmented or virtual reality applications) where a sudden jump can be
* disturbing, the output is adjusted to prevent these jumps in a manner that takes account of the velocity of the
* sensor system.
*/
ARVR_STABILIZED_ROTATION_VECTOR = 0x28,
/**
* Section 2.2
*
* While the magnetometer is removed from the calculation of the game rotation vector, the accelerometer itself can
* create a potential correction in the rotation vector produced (i.e. the estimate of gravity changes). For applications
* (typically augmented or virtual reality applications) where a sudden jump can be disturbing, the output is adjusted
* to prevent these jumps in a manner that takes account of the velocity of the sensor system. This process is called
* AR/VR stabilization.
*/
ARVR_STABILIZED_GAME_ROTATION_VECTOR = 0x29,
// GYRO_INTEGRATED_ROTATION_VECTOR = 0x2A,
};
struct IMUSensorConfig {
/* Sensitivity enabled */
bool sensitivityEnabled = false;
/* Change sensitivity - true if relative; false if absolute */
bool sensitivityRelative = false; /**< @brief Change reports relative (vs absolute) */
// TODO write utility function to convert float to Q point notation, sensor specific
/* 16-bit signed fixed point integer.
* In case of absolute sensitivity represents the value a
* sensor output must exceed in order to trigger another input
* report.
* In case of relative sensitivity represents the the amount
* by which a sensor output must change from the previous
* input report in order to trigger another input report
* A setting of 0 causes all reports to be sent.
*/
uint16_t changeSensitivity = 0; /**< @brief Report-on-change threshold */
/* Rate of reports per second. (hertz)
* 0 means disabled
*/
uint32_t reportRate = 100;
IMUSensor sensorId;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUSensorConfig, sensitivityEnabled, sensitivityRelative, changeSensitivity, reportRate, sensorId);
struct IMUProperties {
/* Enabled IMU sensors */
std::vector<IMUSensorConfig> imuSensors;
/* Above this packet threshold data will be sent to host, if queue is not blocked */
std::int32_t batchReportThreshold = 1;
/* Maximum number of IMU packets in a batch. Maximum 5. */
std::int32_t maxBatchReports = 5;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUProperties, imuSensors, batchReportThreshold, maxBatchReports);
} // namespace dai
<|endoftext|>
|
<commit_before>/*
* Copyright 2011,
* Olivier Stasse, CNRS
*
* CNRS
*
* This file is part of sot-core.
* sot-core is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-core 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 Lesser General Public License for more details. You should
* have received a copy of the GNU Lesser General Public License along
* with sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#define ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#include <vector>
#include <map>
#include <string>
#include <sot/core/api.hh>
namespace dynamicgraph {
namespace sot {
class SOT_CORE_EXPORT NamedVector
{
private:
std::string name_;
std::vector<double> values_;
public:
NamedVector() {}
~NamedVector() {}
const std::string & getName() const
{ return name_;}
void setName(const std::string & aname)
{ name_ = aname;}
const std::vector<double> & getValues() const
{ return values_;}
void setValues(const std::vector<double> & values)
{ values_ = values;}
};
typedef NamedVector SensorValues;
typedef NamedVector ControlValues;
class SOT_CORE_EXPORT AbstractSotExternalInterface
{
public:
AbstractSotExternalInterface(){}
virtual ~AbstractSotExternalInterface(){}
virtual void setupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void nominalSetSensors(std::map<std::string, SensorValues> &sensorsIn)=0;
virtual void cleanupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void getControl(std::map<std::string,ControlValues> &)=0;
};
}
}
typedef dynamicgraph::sot::AbstractSotExternalInterface * createSotExternalInterface_t();
typedef void destroySotExternalInterface_t (dynamicgraph::sot::AbstractSotExternalInterface *);
#endif
<commit_msg>[abstract-sot-external-interface] add function to change default device control type<commit_after>/*
* Copyright 2011,
* Olivier Stasse, CNRS
*
* CNRS
*
* This file is part of sot-core.
* sot-core is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* sot-core 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 Lesser General Public License for more details. You should
* have received a copy of the GNU Lesser General Public License along
* with sot-core. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#define ABSTRACT_SOT_EXTERNAL_INTERFACE_HH
#include <vector>
#include <map>
#include <string>
#include <sot/core/api.hh>
namespace dynamicgraph {
namespace sot {
class SOT_CORE_EXPORT NamedVector
{
private:
std::string name_;
std::vector<double> values_;
public:
NamedVector() {}
~NamedVector() {}
const std::string & getName() const
{ return name_;}
void setName(const std::string & aname)
{ name_ = aname;}
const std::vector<double> & getValues() const
{ return values_;}
void setValues(const std::vector<double> & values)
{ values_ = values;}
};
typedef NamedVector SensorValues;
typedef NamedVector ControlValues;
class SOT_CORE_EXPORT AbstractSotExternalInterface
{
public:
AbstractSotExternalInterface(){}
virtual ~AbstractSotExternalInterface(){}
virtual void setupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void nominalSetSensors(std::map<std::string, SensorValues> &sensorsIn)=0;
virtual void cleanupSetSensors(std::map<std::string,SensorValues> &sensorsIn)=0;
virtual void getControl(std::map<std::string,ControlValues> &)=0;
virtual void setSecondOrderIntegration(void)=0;
};
}
}
typedef dynamicgraph::sot::AbstractSotExternalInterface * createSotExternalInterface_t();
typedef void destroySotExternalInterface_t (dynamicgraph::sot::AbstractSotExternalInterface *);
#endif
<|endoftext|>
|
<commit_before>#ifndef VIGRA_MERGE_GRAPH_CALLBACKS_HXX
#define VIGRA_MERGE_GRAPH_CALLBACKS_HXX
/* std library */
#include <vector>
/* boost */
#include <boost/function.hpp>
namespace vigra {
template<class NODE,class EDGE>
class NewMergeGraphCallbacks{
public:
//callbacks typedefs
typedef boost::function<void (const NODE & ,const NODE &)> MergeNodeCallBackType;
typedef boost::function<void (const EDGE & ,const EDGE &)> MergeEdgeCallBackType;
typedef boost::function<void (const EDGE &)> EraseEdgeCallBackType;
NewMergeGraphCallbacks(){}
template<class OBJ,class F>
void registerMergeNodeCallBack(OBJ & obj,F f){
MergeNodeCallBackType internalF ;
internalF = boost::bind(boost::mem_fn(f), &obj , _1,_2);
mergeNodeCallbacks_.push_back(internalF);
}
template<class OBJ,class F>
void registerMergeEdgeCallBack(OBJ & obj,F f){
MergeEdgeCallBackType internalF ;
internalF = boost::bind(boost::mem_fn(f), &obj , _1,_2);
mergeEdgeCallbacks_.push_back(internalF);
}
template<class OBJ,class F>
void registerEraseEdgeCallBack(OBJ & obj,F f){
EraseEdgeCallBackType internalF ;
internalF = boost::bind(boost::mem_fn(f), &obj , _1);
eraseEdgeCallbacks_.push_back(internalF);
}
void registerMergeNodeCallBack(MergeNodeCallBackType f){
mergeNodeCallbacks_.push_back(f);
}
void registerMergeEdgeCallBack(MergeEdgeCallBackType f){
mergeEdgeCallbacks_.push_back(f);
}
void registerEraseEdgeCallBack(EraseEdgeCallBackType f){
eraseEdgeCallbacks_.push_back(f);
}
protected:
void callMergeNodeCallbacks(const NODE & a,const NODE & b){
for(size_t i=0;i<mergeNodeCallbacks_.size();++i)
mergeNodeCallbacks_[i](a,b);
}
void callMergeEdgeCallbacks(const EDGE & a,const EDGE & b){
for(size_t i=0;i<mergeEdgeCallbacks_.size();++i)
mergeEdgeCallbacks_[i](a,b);
}
void callEraseEdgeCallbacks(const EDGE & a){
for(size_t i=0;i<eraseEdgeCallbacks_.size();++i)
eraseEdgeCallbacks_[i](a);
}
private:
// callback vectors
std::vector<MergeNodeCallBackType> mergeNodeCallbacks_;
std::vector<MergeEdgeCallBackType> mergeEdgeCallbacks_;
std::vector<EraseEdgeCallBackType> eraseEdgeCallbacks_;
};
} // end namespace vigra
#endif //VIGRA_MERGE_GRAPH_CALLBACKS_HXX<commit_msg>replaced signals2 with bind.hpp since singlas2 are not needed<commit_after>#ifndef VIGRA_MERGE_GRAPH_CALLBACKS_HXX
#define VIGRA_MERGE_GRAPH_CALLBACKS_HXX
/* std library */
#include <vector>
/* boost */
#include <boost/function.hpp>
#include <boost/bind.hpp>
namespace vigra {
template<class NODE,class EDGE>
class NewMergeGraphCallbacks{
public:
//callbacks typedefs
typedef boost::function<void (const NODE & ,const NODE &)> MergeNodeCallBackType;
typedef boost::function<void (const EDGE & ,const EDGE &)> MergeEdgeCallBackType;
typedef boost::function<void (const EDGE &)> EraseEdgeCallBackType;
NewMergeGraphCallbacks(){}
template<class OBJ,class F>
void registerMergeNodeCallBack(OBJ & obj,F f){
MergeNodeCallBackType internalF ;
internalF = boost::bind(boost::mem_fn(f), &obj , _1,_2);
mergeNodeCallbacks_.push_back(internalF);
}
template<class OBJ,class F>
void registerMergeEdgeCallBack(OBJ & obj,F f){
MergeEdgeCallBackType internalF ;
internalF = boost::bind(boost::mem_fn(f), &obj , _1,_2);
mergeEdgeCallbacks_.push_back(internalF);
}
template<class OBJ,class F>
void registerEraseEdgeCallBack(OBJ & obj,F f){
EraseEdgeCallBackType internalF ;
internalF = boost::bind(boost::mem_fn(f), &obj , _1);
eraseEdgeCallbacks_.push_back(internalF);
}
void registerMergeNodeCallBack(MergeNodeCallBackType f){
mergeNodeCallbacks_.push_back(f);
}
void registerMergeEdgeCallBack(MergeEdgeCallBackType f){
mergeEdgeCallbacks_.push_back(f);
}
void registerEraseEdgeCallBack(EraseEdgeCallBackType f){
eraseEdgeCallbacks_.push_back(f);
}
protected:
void callMergeNodeCallbacks(const NODE & a,const NODE & b){
for(size_t i=0;i<mergeNodeCallbacks_.size();++i)
mergeNodeCallbacks_[i](a,b);
}
void callMergeEdgeCallbacks(const EDGE & a,const EDGE & b){
for(size_t i=0;i<mergeEdgeCallbacks_.size();++i)
mergeEdgeCallbacks_[i](a,b);
}
void callEraseEdgeCallbacks(const EDGE & a){
for(size_t i=0;i<eraseEdgeCallbacks_.size();++i)
eraseEdgeCallbacks_[i](a);
}
private:
// callback vectors
std::vector<MergeNodeCallBackType> mergeNodeCallbacks_;
std::vector<MergeEdgeCallBackType> mergeEdgeCallbacks_;
std::vector<EraseEdgeCallBackType> eraseEdgeCallbacks_;
};
} // end namespace vigra
#endif //VIGRA_MERGE_GRAPH_CALLBACKS_HXX<|endoftext|>
|
<commit_before>/*
* Steve Vaught
* This program uses the Unlicense
*/
// == Include statements ==
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <random>
using namespace std;
// == Function prototypes ==
string buildRandomString(int length);
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0,std::distance(start, end) -1);
std::advance(start,dis(g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start,end,gen);
}
// == Main ==
int main(){
string target("Methinks it is like a weasel");
cout << buildRandomString( target.length() ) << endl;
return 0;
}
string buildRandomString(int length){
vector<char> alphanumerics
{
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z',
' '
}; //include space in the alphabet
string randstring = "";
for (auto i = 0; i < length; i++){
randstring.push_back( *select_randomly(alphanumerics.begin(), alphanumerics.end()) );
}
return randstring;
} //end buildRandomString
<commit_msg>initial work on mutate<commit_after>/*
* Steve Vaught
* This program uses the Unlicense
*/
// == Include statements ==
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <random>
using namespace std;
// == Function prototypes ==
string buildRandomString(int length);
void mutate(string& scrambled, const string target);
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0,std::distance(start, end) -1);
std::advance(start,dis(g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start,end,gen);
}
// == Main ==
int main(){
string target("Methinks it is like a weasel");
string scrambled = buildRandomString( target.length() );
while( fitness(target,scrambled) != 0 ) {
mutate(scrambled, target);
}
return 0;
}
string buildRandomString(int length){
vector<char> alphanumerics
{
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z',
' '
}; //include space in the alphabet
string randstring = "";
for (auto i = 0; i < length; i++){
randstring.push_back( *select_randomly(alphanumerics.begin(), alphanumerics.end()) );
}
return randstring;
} //end buildRandomString
void mutate(string& scrambled, const string target){
}
<|endoftext|>
|
<commit_before>#include "webcam.hpp"
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
// imshow("flow mask", gray.mul(flow));
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
// this mask gets rid of anything far away from red stuff
// lips have a lot of red
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat erodeKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, erodeKernel);
Mat dilateKernel = ellipticKernel(69,79);
dilate(smallMask1, smallMask1, dilateKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
// update background with new morph mask
// average what we know is background with prior background
// erode it first since we really want to be sure it's bg
// Mat erodeKernel = ellipticKernel(21);
Mat erodedMask;
erode(mask, erodedMask, erodeKernel);
Mat mask_;
subtract(1,erodedMask,mask_);
Mat mask3, mask3_;
channel[0] = erodedMask;
channel[1] = erodedMask;
channel[2] = erodedMask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_) + blurred_img.mul(mask3_))/2;
imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = tracker1+1;
Mat classifyThis = image.clone();
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, tracker2, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
rectangle(image, scaled, Scalar(255,0,0));
}
imshow("MOUTH", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
// imshow("flow mask", gray.mul(flow));
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
// imshow("dark mask", gray.mul(kindofdark));
// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
*/
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat erodeKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, erodeKernel);
Mat dilateKernel = ellipticKernel(69,79);
dilate(smallMask1, smallMask1, dilateKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
// imshow("morph mask", gray.mul(mask));
// update background with new morph mask
// average what we know is background with prior background
// erode it first since we really want to be sure it's bg
// Mat erodeKernel = ellipticKernel(21);
Mat erodedMask;
erode(mask, erodedMask, erodeKernel);
Mat mask_;
subtract(1,erodedMask,mask_);
Mat mask3, mask3_;
channel[0] = erodedMask;
channel[1] = erodedMask;
channel[2] = erodedMask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_) + blurred_img.mul(mask3_))/2;
imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = tracker1+1;
Mat classifyThis = image.clone();
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, tracker2, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
rectangle(image, scaled, Scalar(255,0,0));
}
imshow("MOUTH", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/base:$Id: 6da0b5b613bbcfaa3a5cd4074e7b2be2448dfb31 $
// Author: Fons Rademakers 04/05/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TBuffer
\ingroup Base
Buffer base class used for serializing objects.
*/
#include "TBuffer.h"
#include "TClass.h"
#include "TProcessID.h"
const Int_t kExtraSpace = 8; // extra space at end of buffer (used for free block count)
ClassImp(TBuffer);
/// Default streamer implementation used by ClassDefInline to avoid
/// requirement to include TBuffer.h
void ROOT::Internal::DefaultStreamer(TBuffer &R__b, const TClass *cl, void *objpointer)
{
if (R__b.IsReading())
R__b.ReadClassBuffer(cl, objpointer);
else
R__b.WriteClassBuffer(cl, objpointer);
}
////////////////////////////////////////////////////////////////////////////////
/// The user has provided memory than we don't own, thus we can not extent it
/// either.
static char *R__NoReAllocChar(char *, size_t, size_t)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create an I/O buffer object. Mode should be either TBuffer::kRead or
/// TBuffer::kWrite. By default the I/O buffer has a size of
/// TBuffer::kInitialSize (1024) bytes.
TBuffer::TBuffer(EMode mode)
{
fBufSize = kInitialSize;
fMode = mode;
fVersion = 0;
fParent = 0;
SetBit(kIsOwner);
fBuffer = new char[fBufSize+kExtraSpace];
fBufCur = fBuffer;
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( 0 );
}
////////////////////////////////////////////////////////////////////////////////
/// Create an I/O buffer object. Mode should be either TBuffer::kRead or
/// TBuffer::kWrite.
TBuffer::TBuffer(EMode mode, Int_t bufsiz)
{
if (bufsiz < kMinimalSize) bufsiz = kMinimalSize;
fBufSize = bufsiz;
fMode = mode;
fVersion = 0;
fParent = 0;
SetBit(kIsOwner);
fBuffer = new char[fBufSize+kExtraSpace];
fBufCur = fBuffer;
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( 0 );
}
////////////////////////////////////////////////////////////////////////////////
/// Create an I/O buffer object. Mode should be either TBuffer::kRead or
/// TBuffer::kWrite. By default the I/O buffer has a size of
/// TBuffer::kInitialSize (1024) bytes. An external buffer can be passed
/// to TBuffer via the buf argument. By default this buffer will be adopted
/// unless adopt is false.
///
/// If the new buffer is _not_ adopted and no memory allocation routine
/// is provided, a Fatal error will be issued if the Buffer attempts to
/// expand.
TBuffer::TBuffer(EMode mode, Int_t bufsiz, void *buf, Bool_t adopt, ReAllocCharFun_t reallocfunc)
{
fBufSize = bufsiz;
fMode = mode;
fVersion = 0;
fParent = 0;
SetBit(kIsOwner);
if (buf) {
fBuffer = (char *)buf;
if ( (fMode&kWrite)!=0 ) {
fBufSize -= kExtraSpace;
}
if (!adopt) ResetBit(kIsOwner);
} else {
if (fBufSize < kMinimalSize) {
fBufSize = kMinimalSize;
}
fBuffer = new char[fBufSize+kExtraSpace];
}
fBufCur = fBuffer;
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( reallocfunc );
if (buf && ( (fMode&kWrite)!=0 ) && fBufSize < 0) {
Expand( kMinimalSize );
}
}
////////////////////////////////////////////////////////////////////////////////
/// Delete an I/O buffer object.
TBuffer::~TBuffer()
{
if (TestBit(kIsOwner)) {
//printf("Deleting fBuffer=%lx\n", fBuffer);
delete [] fBuffer;
}
fBuffer = 0;
fParent = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Automatically calculate a new size and expand the buffer to fit at least size_needed.
/// The goals is to minimize the number of memory allocation and the memory allocation
/// which avoiding too much memory wastage.
///
/// If the size_needed is larger than the current size, the policy
/// is to expand to double the current size or the size_needed which ever is largest.
void TBuffer::AutoExpand(Int_t size_needed)
{
if (size_needed > fBufSize) {
if (size_needed > 2*fBufSize) {
Expand(size_needed);
} else {
Expand(2*fBufSize);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Sets a new buffer in an existing TBuffer object. If newsiz=0 then the
/// new buffer is expected to have the same size as the previous buffer.
/// The current buffer position is reset to the start of the buffer.
/// If the TBuffer owned the previous buffer, it will be deleted prior
/// to accepting the new buffer. By default the new buffer will be
/// adopted unless adopt is false.
///
/// If the new buffer is _not_ adopted and no memory allocation routine
/// is provided, a Fatal error will be issued if the Buffer attempts to
/// expand.
void TBuffer::SetBuffer(void *buf, UInt_t newsiz, Bool_t adopt, ReAllocCharFun_t reallocfunc)
{
if (fBuffer && TestBit(kIsOwner))
delete [] fBuffer;
if (adopt)
SetBit(kIsOwner);
else
ResetBit(kIsOwner);
fBuffer = (char *)buf;
fBufCur = fBuffer;
if (newsiz > 0) {
if ( (fMode&kWrite)!=0 ) {
fBufSize = newsiz - kExtraSpace;
} else {
fBufSize = newsiz;
}
}
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( reallocfunc );
if (buf && ( (fMode&kWrite)!=0 ) && fBufSize < 0) {
Expand( kMinimalSize );
}
}
////////////////////////////////////////////////////////////////////////////////
/// Expand (or shrink) the I/O buffer to newsize bytes.
/// If copy is true (the default), the existing content of the
/// buffer is preserved, otherwise the buffer is returned zero-ed out.
///
/// In order to avoid losing data, if the current length is greater than
/// the requested size, we only shrink down to the current length.
void TBuffer::Expand(Int_t newsize, Bool_t copy)
{
Int_t l = Length();
if ( (l > newsize) && copy ) {
newsize = l;
}
if ( (fMode&kWrite)!=0 ) {
fBuffer = fReAllocFunc(fBuffer, newsize+kExtraSpace,
copy ? fBufSize+kExtraSpace : 0);
} else {
fBuffer = fReAllocFunc(fBuffer, newsize,
copy ? fBufSize : 0);
}
if (fBuffer == 0) {
if (fReAllocFunc == TStorage::ReAllocChar) {
Fatal("Expand","Failed to expand the data buffer using TStorage::ReAllocChar.");
} else if (fReAllocFunc == R__NoReAllocChar) {
Fatal("Expand","Failed to expand the data buffer because TBuffer does not own it and no custom memory reallocator was provided.");
} else {
Fatal("Expand","Failed to expand the data buffer using custom memory reallocator 0x%lx.", (Long_t)fReAllocFunc);
}
}
fBufSize = newsize;
fBufCur = fBuffer + l;
fBufMax = fBuffer + fBufSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to parent of this buffer.
TObject *TBuffer::GetParent() const
{
return fParent;
}
////////////////////////////////////////////////////////////////////////////////
/// Set parent owning this buffer.
void TBuffer::SetParent(TObject *parent)
{
fParent = parent;
}
////////////////////////////////////////////////////////////////////////////////
/// Return the reallocation method currently used.
ReAllocCharFun_t TBuffer::GetReAllocFunc() const
{
return fReAllocFunc;
}
////////////////////////////////////////////////////////////////////////////////
/// Set which memory reallocation method to use. If reallocafunc is null,
/// reset it to the default value (TStorage::ReAlloc)
void TBuffer::SetReAllocFunc(ReAllocCharFun_t reallocfunc )
{
if (reallocfunc) {
fReAllocFunc = reallocfunc;
} else {
if (TestBit(kIsOwner)) {
fReAllocFunc = TStorage::ReAllocChar;
} else {
fReAllocFunc = R__NoReAllocChar;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set buffer in read mode.
void TBuffer::SetReadMode()
{
if ( (fMode&kWrite)!=0 ) {
// We had reserved space for the free block count,
// release it,
fBufSize += kExtraSpace;
}
fMode = kRead;
}
////////////////////////////////////////////////////////////////////////////////
/// Set buffer in write mode.
void TBuffer::SetWriteMode()
{
if ( (fMode&kWrite)==0 ) {
// We had not yet reserved space for the free block count,
// reserve it now.
fBufSize -= kExtraSpace;
}
fMode = kWrite;
}
////////////////////////////////////////////////////////////////////////////////
/// Forward to TROOT::GetClass().
TClass *TBuffer::GetClass(const std::type_info &typeinfo)
{
return TClass::GetClass(typeinfo);
}
////////////////////////////////////////////////////////////////////////////////
/// Forward to TROOT::GetClass().
TClass *TBuffer::GetClass(const char *className)
{
return TClass::GetClass(className);
}
////////////////////////////////////////////////////////////////////////////////
/// Return the current Process-ID.
TProcessID *TBuffer::ReadProcessID(UShort_t pidf)
{
if (!pidf) return TProcessID::GetPID(); //may happen when cloning an object
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Always return 0 (current processID).
UShort_t TBuffer::WriteProcessID(TProcessID *)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Push a new data cache area onto the list of area to be used for
/// temporarily store 'missing' data members.
void TBuffer::PushDataCache(TVirtualArray *obj)
{
fCacheStack.push_back(obj);
}
////////////////////////////////////////////////////////////////////////////////
/// Return the 'current' data cache area from the list of area to be used for
/// temporarily store 'missing' data members.
TVirtualArray *TBuffer::PeekDataCache() const
{
if (fCacheStack.empty()) return 0;
return fCacheStack.back();
}
////////////////////////////////////////////////////////////////////////////////
/// Pop and Return the 'current' data cache area from the list of area to be used for
/// temporarily store 'missing' data members.
TVirtualArray *TBuffer::PopDataCache()
{
TVirtualArray *val = PeekDataCache();
fCacheStack.pop_back();
return val;
}
////////////////////////////////////////////////////////////////////////////////
/// Byte-swap N primitive-elements in the buffer.
/// Bulk API relies on this function.
Bool_t TBuffer::ByteSwapBuffer(Long64_t n, EDataType type)
{
char *input_buf = GetCurrent();
if ((type == EDataType::kShort_t) || (type == EDataType::kUShort_t)) {
#ifdef R__BYTESWAP
Short_t *buf __attribute__((aligned(8))) = reinterpret_cast<Short_t*>(input_buf);
for (int idx=0; idx<n; idx++) {
Short_t tmp = *reinterpret_cast<Short_t*>(buf + idx); // Makes a copy of the values; frombuf can't handle aliasing.
char *tmp_ptr = reinterpret_cast<char *>(&tmp);
frombuf(tmp_ptr, buf + idx);
}
#endif
} else if ((type == EDataType::kFloat_t) || (type == EDataType::kInt_t) || (type == EDataType::kUInt_t)) {
#ifdef R__BYTESWAP
Float_t *buf __attribute__((aligned(8))) = reinterpret_cast<Float_t*>(input_buf);
for (int idx=0; idx<n; idx++) {
Float_t tmp = *reinterpret_cast<Float_t*>(buf + idx); // Makes a copy of the values; frombuf can't handle aliasing.
char *tmp_ptr = reinterpret_cast<char *>(&tmp);
frombuf(tmp_ptr, buf + idx);
}
#endif
} else if ((type == EDataType::kDouble_t) || (type == EDataType::kLong64_t) || (type == EDataType::kULong64_t)) {
#ifdef R__BYTESWAP
Double_t *buf __attribute__((aligned(8))) = reinterpret_cast<Double_t*>(input_buf);
for (int idx=0; idx<n; idx++) {
Double_t tmp = *reinterpret_cast<Double_t*>(buf + idx); // Makes a copy of the values; frombuf can't handle aliasing.
char *tmp_ptr = reinterpret_cast<char*>(&tmp);
frombuf(tmp_ptr, buf + idx);
}
#endif
} else {
return false;
}
return true;
}
<commit_msg>Prevent (attempt at) creation of TBuffer larger than 2Gb<commit_after>// @(#)root/base:$Id: 6da0b5b613bbcfaa3a5cd4074e7b2be2448dfb31 $
// Author: Fons Rademakers 04/05/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TBuffer
\ingroup Base
Buffer base class used for serializing objects.
*/
#include "TBuffer.h"
#include "TClass.h"
#include "TProcessID.h"
constexpr Int_t kExtraSpace = 8; // extra space at end of buffer (used for free block count)
constexpr Int_t kMaxBufferSize = 0x7FFFFFFE; // largest possible size.
ClassImp(TBuffer);
/// Default streamer implementation used by ClassDefInline to avoid
/// requirement to include TBuffer.h
void ROOT::Internal::DefaultStreamer(TBuffer &R__b, const TClass *cl, void *objpointer)
{
if (R__b.IsReading())
R__b.ReadClassBuffer(cl, objpointer);
else
R__b.WriteClassBuffer(cl, objpointer);
}
////////////////////////////////////////////////////////////////////////////////
/// The user has provided memory than we don't own, thus we can not extent it
/// either.
static char *R__NoReAllocChar(char *, size_t, size_t)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create an I/O buffer object. Mode should be either TBuffer::kRead or
/// TBuffer::kWrite. By default the I/O buffer has a size of
/// TBuffer::kInitialSize (1024) bytes.
TBuffer::TBuffer(EMode mode)
{
fBufSize = kInitialSize;
fMode = mode;
fVersion = 0;
fParent = 0;
SetBit(kIsOwner);
fBuffer = new char[fBufSize+kExtraSpace];
fBufCur = fBuffer;
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( 0 );
}
////////////////////////////////////////////////////////////////////////////////
/// Create an I/O buffer object. Mode should be either TBuffer::kRead or
/// TBuffer::kWrite.
TBuffer::TBuffer(EMode mode, Int_t bufsiz)
{
if (bufsiz < 0)
Fatal("TBuffer","Request to create a buffer with a negative size, likely due to an integer overflow: 0x%x for a max of 0x%x.", bufsiz, kMaxBufferSize);
if (bufsiz < kMinimalSize) bufsiz = kMinimalSize;
fBufSize = bufsiz;
fMode = mode;
fVersion = 0;
fParent = 0;
SetBit(kIsOwner);
fBuffer = new char[fBufSize+kExtraSpace];
fBufCur = fBuffer;
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( 0 );
}
////////////////////////////////////////////////////////////////////////////////
/// Create an I/O buffer object. Mode should be either TBuffer::kRead or
/// TBuffer::kWrite. By default the I/O buffer has a size of
/// TBuffer::kInitialSize (1024) bytes. An external buffer can be passed
/// to TBuffer via the buf argument. By default this buffer will be adopted
/// unless adopt is false.
///
/// If the new buffer is _not_ adopted and no memory allocation routine
/// is provided, a Fatal error will be issued if the Buffer attempts to
/// expand.
TBuffer::TBuffer(EMode mode, Int_t bufsiz, void *buf, Bool_t adopt, ReAllocCharFun_t reallocfunc)
{
if (bufsiz < 0)
Fatal("TBuffer","Request to create a buffer with a negative size, likely due to an integer overflow: 0x%x for a max of 0x%x.", bufsiz, kMaxBufferSize);
fBufSize = bufsiz;
fMode = mode;
fVersion = 0;
fParent = 0;
SetBit(kIsOwner);
if (buf) {
fBuffer = (char *)buf;
if ( (fMode&kWrite)!=0 ) {
fBufSize -= kExtraSpace;
}
if (!adopt) ResetBit(kIsOwner);
} else {
if (fBufSize < kMinimalSize) {
fBufSize = kMinimalSize;
}
fBuffer = new char[(Long64_t)fBufSize+kExtraSpace];
}
fBufCur = fBuffer;
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( reallocfunc );
if (buf && ( (fMode&kWrite)!=0 ) && fBufSize < 0) {
Expand( kMinimalSize );
}
}
////////////////////////////////////////////////////////////////////////////////
/// Delete an I/O buffer object.
TBuffer::~TBuffer()
{
if (TestBit(kIsOwner)) {
//printf("Deleting fBuffer=%lx\n", fBuffer);
delete [] fBuffer;
}
fBuffer = 0;
fParent = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Automatically calculate a new size and expand the buffer to fit at least size_needed.
/// The goals is to minimize the number of memory allocation and the memory allocation
/// which avoiding too much memory wastage.
///
/// If the size_needed is larger than the current size, the policy
/// is to expand to double the current size or the size_needed which ever is largest.
void TBuffer::AutoExpand(Int_t size_needed)
{
if (size_needed < 0) {
Fatal("AutoExpand","Request to expand to a negative size, likely due to an integer overflow: 0x%x for a max of 0x%x.", size_needed, kMaxBufferSize);
}
if (size_needed > fBufSize) {
Long64_t doubling = 2LLU * fBufSize;
if (doubling > kMaxBufferSize)
doubling = kMaxBufferSize;
if (size_needed > doubling) {
Expand(size_needed);
} else {
Expand(doubling);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Sets a new buffer in an existing TBuffer object. If newsiz=0 then the
/// new buffer is expected to have the same size as the previous buffer.
/// The current buffer position is reset to the start of the buffer.
/// If the TBuffer owned the previous buffer, it will be deleted prior
/// to accepting the new buffer. By default the new buffer will be
/// adopted unless adopt is false.
///
/// If the new buffer is _not_ adopted and no memory allocation routine
/// is provided, a Fatal error will be issued if the Buffer attempts to
/// expand.
void TBuffer::SetBuffer(void *buf, UInt_t newsiz, Bool_t adopt, ReAllocCharFun_t reallocfunc)
{
if (fBuffer && TestBit(kIsOwner))
delete [] fBuffer;
if (adopt)
SetBit(kIsOwner);
else
ResetBit(kIsOwner);
fBuffer = (char *)buf;
fBufCur = fBuffer;
if (newsiz > 0) {
if ( (fMode&kWrite)!=0 ) {
fBufSize = newsiz - kExtraSpace;
} else {
fBufSize = newsiz;
}
}
fBufMax = fBuffer + fBufSize;
SetReAllocFunc( reallocfunc );
if (buf && ( (fMode&kWrite)!=0 ) && fBufSize < 0) {
Expand( kMinimalSize );
}
}
////////////////////////////////////////////////////////////////////////////////
/// Expand (or shrink) the I/O buffer to newsize bytes.
/// If copy is true (the default), the existing content of the
/// buffer is preserved, otherwise the buffer is returned zero-ed out.
///
/// In order to avoid losing data, if the current length is greater than
/// the requested size, we only shrink down to the current length.
void TBuffer::Expand(Int_t newsize, Bool_t copy)
{
Int_t l = Length();
if ( (l > newsize) && copy ) {
newsize = l;
}
const Int_t extraspace = (fMode&kWrite)!=0 ? kExtraSpace : 0;
if ( ((Long64_t)newsize+extraspace) > kMaxBufferSize) {
if (l < kMaxBufferSize) {
newsize = kMaxBufferSize - extraspace;
} else {
Fatal("Expand","Requested size (%d) is too large (max is %d).", newsize, kMaxBufferSize);
}
}
if ( (fMode&kWrite)!=0 ) {
fBuffer = fReAllocFunc(fBuffer, newsize+kExtraSpace,
copy ? fBufSize+kExtraSpace : 0);
} else {
fBuffer = fReAllocFunc(fBuffer, newsize,
copy ? fBufSize : 0);
}
if (fBuffer == 0) {
if (fReAllocFunc == TStorage::ReAllocChar) {
Fatal("Expand","Failed to expand the data buffer using TStorage::ReAllocChar.");
} else if (fReAllocFunc == R__NoReAllocChar) {
Fatal("Expand","Failed to expand the data buffer because TBuffer does not own it and no custom memory reallocator was provided.");
} else {
Fatal("Expand","Failed to expand the data buffer using custom memory reallocator 0x%lx.", (Long_t)fReAllocFunc);
}
}
fBufSize = newsize;
fBufCur = fBuffer + l;
fBufMax = fBuffer + fBufSize;
}
////////////////////////////////////////////////////////////////////////////////
/// Return pointer to parent of this buffer.
TObject *TBuffer::GetParent() const
{
return fParent;
}
////////////////////////////////////////////////////////////////////////////////
/// Set parent owning this buffer.
void TBuffer::SetParent(TObject *parent)
{
fParent = parent;
}
////////////////////////////////////////////////////////////////////////////////
/// Return the reallocation method currently used.
ReAllocCharFun_t TBuffer::GetReAllocFunc() const
{
return fReAllocFunc;
}
////////////////////////////////////////////////////////////////////////////////
/// Set which memory reallocation method to use. If reallocafunc is null,
/// reset it to the default value (TStorage::ReAlloc)
void TBuffer::SetReAllocFunc(ReAllocCharFun_t reallocfunc )
{
if (reallocfunc) {
fReAllocFunc = reallocfunc;
} else {
if (TestBit(kIsOwner)) {
fReAllocFunc = TStorage::ReAllocChar;
} else {
fReAllocFunc = R__NoReAllocChar;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Set buffer in read mode.
void TBuffer::SetReadMode()
{
if ( (fMode&kWrite)!=0 ) {
// We had reserved space for the free block count,
// release it,
fBufSize += kExtraSpace;
}
fMode = kRead;
}
////////////////////////////////////////////////////////////////////////////////
/// Set buffer in write mode.
void TBuffer::SetWriteMode()
{
if ( (fMode&kWrite)==0 ) {
// We had not yet reserved space for the free block count,
// reserve it now.
fBufSize -= kExtraSpace;
}
fMode = kWrite;
}
////////////////////////////////////////////////////////////////////////////////
/// Forward to TROOT::GetClass().
TClass *TBuffer::GetClass(const std::type_info &typeinfo)
{
return TClass::GetClass(typeinfo);
}
////////////////////////////////////////////////////////////////////////////////
/// Forward to TROOT::GetClass().
TClass *TBuffer::GetClass(const char *className)
{
return TClass::GetClass(className);
}
////////////////////////////////////////////////////////////////////////////////
/// Return the current Process-ID.
TProcessID *TBuffer::ReadProcessID(UShort_t pidf)
{
if (!pidf) return TProcessID::GetPID(); //may happen when cloning an object
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Always return 0 (current processID).
UShort_t TBuffer::WriteProcessID(TProcessID *)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Push a new data cache area onto the list of area to be used for
/// temporarily store 'missing' data members.
void TBuffer::PushDataCache(TVirtualArray *obj)
{
fCacheStack.push_back(obj);
}
////////////////////////////////////////////////////////////////////////////////
/// Return the 'current' data cache area from the list of area to be used for
/// temporarily store 'missing' data members.
TVirtualArray *TBuffer::PeekDataCache() const
{
if (fCacheStack.empty()) return 0;
return fCacheStack.back();
}
////////////////////////////////////////////////////////////////////////////////
/// Pop and Return the 'current' data cache area from the list of area to be used for
/// temporarily store 'missing' data members.
TVirtualArray *TBuffer::PopDataCache()
{
TVirtualArray *val = PeekDataCache();
fCacheStack.pop_back();
return val;
}
////////////////////////////////////////////////////////////////////////////////
/// Byte-swap N primitive-elements in the buffer.
/// Bulk API relies on this function.
Bool_t TBuffer::ByteSwapBuffer(Long64_t n, EDataType type)
{
char *input_buf = GetCurrent();
if ((type == EDataType::kShort_t) || (type == EDataType::kUShort_t)) {
#ifdef R__BYTESWAP
Short_t *buf __attribute__((aligned(8))) = reinterpret_cast<Short_t*>(input_buf);
for (int idx=0; idx<n; idx++) {
Short_t tmp = *reinterpret_cast<Short_t*>(buf + idx); // Makes a copy of the values; frombuf can't handle aliasing.
char *tmp_ptr = reinterpret_cast<char *>(&tmp);
frombuf(tmp_ptr, buf + idx);
}
#endif
} else if ((type == EDataType::kFloat_t) || (type == EDataType::kInt_t) || (type == EDataType::kUInt_t)) {
#ifdef R__BYTESWAP
Float_t *buf __attribute__((aligned(8))) = reinterpret_cast<Float_t*>(input_buf);
for (int idx=0; idx<n; idx++) {
Float_t tmp = *reinterpret_cast<Float_t*>(buf + idx); // Makes a copy of the values; frombuf can't handle aliasing.
char *tmp_ptr = reinterpret_cast<char *>(&tmp);
frombuf(tmp_ptr, buf + idx);
}
#endif
} else if ((type == EDataType::kDouble_t) || (type == EDataType::kLong64_t) || (type == EDataType::kULong64_t)) {
#ifdef R__BYTESWAP
Double_t *buf __attribute__((aligned(8))) = reinterpret_cast<Double_t*>(input_buf);
for (int idx=0; idx<n; idx++) {
Double_t tmp = *reinterpret_cast<Double_t*>(buf + idx); // Makes a copy of the values; frombuf can't handle aliasing.
char *tmp_ptr = reinterpret_cast<char*>(&tmp);
frombuf(tmp_ptr, buf + idx);
}
#endif
} else {
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>// Original Author: Brian Bockelman
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ZipZSTD.h"
#include "ROOT/RConfig.hxx"
#include "zdict.h"
#include <zstd.h>
#include <memory>
#include <iostream>
static const int kHeaderSize = 9;
static const size_t errorCodeSmallBuffer = 18446744073709551546U;
void R__zipZSTD(int cxlevel, int *srcsize, char *src, int *tgtsize, char *tgt, int *irep)
{
using Ctx_ptr = std::unique_ptr<ZSTD_CCtx, decltype(&ZSTD_freeCCtx)>;
Ctx_ptr fCtx{ZSTD_createCCtx(), &ZSTD_freeCCtx};
*irep = 0;
size_t retval = ZSTD_compressCCtx(fCtx.get(),
&tgt[kHeaderSize], static_cast<size_t>(*tgtsize - kHeaderSize),
src, static_cast<size_t>(*srcsize),
2*cxlevel);
if (R__unlikely(ZSTD_isError(retval))) {
std::cerr << "Error in zip ZSTD. Type = " << ZSTD_getErrorName(retval) <<
" . Code = " << retval << std::endl;
return;
}
else {
*irep = static_cast<size_t>(retval + kHeaderSize);
}
size_t deflate_size = retval;
size_t inflate_size = static_cast<size_t>(*srcsize);
tgt[0] = 'Z';
tgt[1] = 'S';
tgt[2] = '\1';
tgt[3] = deflate_size & 0xff;
tgt[4] = (deflate_size >> 8) & 0xff;
tgt[5] = (deflate_size >> 16) & 0xff;
tgt[6] = inflate_size & 0xff;
tgt[7] = (inflate_size >> 8) & 0xff;
tgt[8] = (inflate_size >> 16) & 0xff;
}
void R__unzipZSTD(int *srcsize, unsigned char *src, int *tgtsize, unsigned char *tgt, int *irep)
{
using Ctx_ptr = std::unique_ptr<ZSTD_DCtx, decltype(&ZSTD_freeDCtx)>;
Ctx_ptr fCtx{ZSTD_createDCtx(), &ZSTD_freeDCtx};
*irep = 0;
if (R__unlikely(src[0] != 'Z' || src[1] != 'S')) {
std::cerr << "R__unzipZSTD: algorithm run against buffer with incorrect header (got " <<
src[0] << src[1] << "; expected ZS)." << std::endl;
return;
}
int ZSTD_version = ZSTD_versionNumber() / (100 * 100);
if (R__unlikely(src[2] != ZSTD_version)) {
std::cerr << "R__unzipZSTD: This version of ZSTD is incompatible with the on-disk version "
"got "<< src[2] << "; expected "<< ZSTD_version << ")" << std::endl;
return;
}
size_t retval = ZSTD_decompressDCtx(fCtx.get(),
(char *)tgt, static_cast<size_t>(*tgtsize),
(char *)&src[kHeaderSize], static_cast<size_t>(*srcsize - kHeaderSize));
/* The error code 18446744073709551546 arises when the tgt buffer is too small
* However this error is already handled outside of the compression algorithm
*/
if (R__unlikely(ZSTD_isError(retval)) && retval != 18446744073709551546U) {
std::cerr << "Error in unzip ZSTD. Type = " << ZSTD_getErrorName(retval) <<
" . Code = " << retval << std::endl;
return;
}
else {
*irep = retval;
}
}
<commit_msg>Actually use unused variable (error code)<commit_after>// Original Author: Brian Bockelman
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ZipZSTD.h"
#include "ROOT/RConfig.hxx"
#include "zdict.h"
#include <zstd.h>
#include <memory>
#include <iostream>
static const int kHeaderSize = 9;
static const size_t errorCodeSmallBuffer = 18446744073709551546U;
void R__zipZSTD(int cxlevel, int *srcsize, char *src, int *tgtsize, char *tgt, int *irep)
{
using Ctx_ptr = std::unique_ptr<ZSTD_CCtx, decltype(&ZSTD_freeCCtx)>;
Ctx_ptr fCtx{ZSTD_createCCtx(), &ZSTD_freeCCtx};
*irep = 0;
size_t retval = ZSTD_compressCCtx(fCtx.get(),
&tgt[kHeaderSize], static_cast<size_t>(*tgtsize - kHeaderSize),
src, static_cast<size_t>(*srcsize),
2*cxlevel);
if (R__unlikely(ZSTD_isError(retval))) {
std::cerr << "Error in zip ZSTD. Type = " << ZSTD_getErrorName(retval) <<
" . Code = " << retval << std::endl;
return;
}
else {
*irep = static_cast<size_t>(retval + kHeaderSize);
}
size_t deflate_size = retval;
size_t inflate_size = static_cast<size_t>(*srcsize);
tgt[0] = 'Z';
tgt[1] = 'S';
tgt[2] = '\1';
tgt[3] = deflate_size & 0xff;
tgt[4] = (deflate_size >> 8) & 0xff;
tgt[5] = (deflate_size >> 16) & 0xff;
tgt[6] = inflate_size & 0xff;
tgt[7] = (inflate_size >> 8) & 0xff;
tgt[8] = (inflate_size >> 16) & 0xff;
}
void R__unzipZSTD(int *srcsize, unsigned char *src, int *tgtsize, unsigned char *tgt, int *irep)
{
using Ctx_ptr = std::unique_ptr<ZSTD_DCtx, decltype(&ZSTD_freeDCtx)>;
Ctx_ptr fCtx{ZSTD_createDCtx(), &ZSTD_freeDCtx};
*irep = 0;
if (R__unlikely(src[0] != 'Z' || src[1] != 'S')) {
std::cerr << "R__unzipZSTD: algorithm run against buffer with incorrect header (got " <<
src[0] << src[1] << "; expected ZS)." << std::endl;
return;
}
int ZSTD_version = ZSTD_versionNumber() / (100 * 100);
if (R__unlikely(src[2] != ZSTD_version)) {
std::cerr << "R__unzipZSTD: This version of ZSTD is incompatible with the on-disk version "
"got "<< src[2] << "; expected "<< ZSTD_version << ")" << std::endl;
return;
}
size_t retval = ZSTD_decompressDCtx(fCtx.get(),
(char *)tgt, static_cast<size_t>(*tgtsize),
(char *)&src[kHeaderSize], static_cast<size_t>(*srcsize - kHeaderSize));
/* The error code 18446744073709551546 arises when the tgt buffer is too small
* However this error is already handled outside of the compression algorithm
*/
if (R__unlikely(ZSTD_isError(retval)) && retval != errorCodeSmallBuffer) {
std::cerr << "Error in unzip ZSTD. Type = " << ZSTD_getErrorName(retval) <<
" . Code = " << retval << std::endl;
return;
}
else {
*irep = retval;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2016 iNuron NV
This file is part of Open vStorage Open Source Edition (OSE), as available from
http://www.openvstorage.org and
http://www.openvstorage.com.
This file is free software; you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License v3 (GNU AGPLv3)
as published by the Free Software Foundation, in version 3 as it comes
in the <LICENSE.txt> file of the Open vStorage OSE distribution.
Open vStorage is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY of any kind.
*/
#include "asd_access.h"
#include "rdma_transport.h"
#include "tcp_transport.h"
#include <iostream>
#include <mutex>
namespace alba {
namespace asd {
using alba::proxy_protocol::OsdInfo;
#define LOCK() std::lock_guard<std::mutex> lock(_mutex)
ConnectionPool::ConnectionPool(std::unique_ptr<OsdInfo> config, size_t capacity)
: config_(std::move(config)), capacity_(capacity) {
ALBA_LOG(INFO, "Created pool for asd client " << *config_ << ", capacity "
<< capacity);
}
ConnectionPool::~ConnectionPool() { clear_(connections_); }
std::unique_ptr<Asd_client> ConnectionPool::pop_(Connections &conns) {
std::unique_ptr<Asd_client> c;
if (not conns.empty()) {
c = std::unique_ptr<Asd_client>(&conns.front());
conns.pop_front();
}
return c;
}
void ConnectionPool::clear_(Connections &conns) {
while (not conns.empty()) {
pop_(conns);
}
}
std::unique_ptr<Asd_client> ConnectionPool::make_one_() const {
auto duration = std::chrono::seconds(5);
std::unique_ptr<transport::Transport> transport;
if (config_->use_rdma) {
;
transport =
std::unique_ptr<transport::Transport>(new transport::RDMA_transport(
config_->ips[0], std::to_string(config_->port), duration));
} else {
transport =
std::unique_ptr<transport::Transport>(new transport::TCP_transport(
config_->ips[0], std::to_string(config_->port), duration));
}
std::unique_ptr<Asd_client> c(
new Asd_client(duration, std::move(transport), config_->long_id));
return c;
}
void ConnectionPool::release_connection(std::unique_ptr<Asd_client> conn) {
LOCK();
if (conn) {
_fast_path_failures = 0;
if (connections_.size() < capacity_) {
connections_.push_front(*conn.release());
return;
}
} else {
_failure_time = std::chrono::steady_clock::now();
_fast_path_failures++;
}
}
std::unique_ptr<Asd_client> ConnectionPool::get_connection() {
std::unique_ptr<Asd_client> conn;
{
LOCK();
if (_fast_path_failures >= 15) {
if (duration_cast<seconds>(steady_clock::now() - _failure_time).count() <
120) {
return std::unique_ptr<Asd_client>(nullptr);
}
}
conn = pop_(connections_);
}
if (not conn) {
conn = make_one_();
}
return conn;
}
size_t ConnectionPool::size() const {
LOCK();
return connections_.size();
}
size_t ConnectionPool::capacity() const {
LOCK();
return capacity_;
}
void ConnectionPool::capacity(size_t cap) {
Connections tmp;
{
LOCK();
std::swap(capacity_, cap);
if (connections_.size() > capacity_) {
for (size_t i = 0; i < capacity_; ++i) {
Asd_client &c = connections_.front();
connections_.pop_front();
tmp.push_front(c);
}
std::swap(tmp, connections_);
}
}
clear_(tmp);
ALBA_LOG(INFO, *config_ << ": updated capacity from " << cap << " to "
<< capacity());
}
ConnectionPool *
ConnectionPools::get_connection_pool(const proxy_protocol::OsdInfo &osd_info,
int connection_pool_size) {
if (!osd_info.kind_asd) {
return nullptr;
}
LOCK();
auto it = connection_pools_.find(osd_info.long_id);
if (it == connection_pools_.end()) {
ALBA_LOG(INFO, "asd ConnenctionPools adding ConnectionPool for "
<< osd_info.long_id);
proxy_protocol::OsdInfo *osd_info_copy =
new proxy_protocol::OsdInfo(osd_info);
connection_pools_.emplace(
osd_info.long_id,
std::unique_ptr<ConnectionPool>(new ConnectionPool(
std::unique_ptr<proxy_protocol::OsdInfo>(osd_info_copy),
connection_pool_size)));
it = connection_pools_.find(osd_info.long_id);
}
return it->second.get();
}
}
}
<commit_msg>initialize attribute (keep valgrind happy)<commit_after>/*
Copyright (C) 2016 iNuron NV
This file is part of Open vStorage Open Source Edition (OSE), as available from
http://www.openvstorage.org and
http://www.openvstorage.com.
This file is free software; you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License v3 (GNU AGPLv3)
as published by the Free Software Foundation, in version 3 as it comes
in the <LICENSE.txt> file of the Open vStorage OSE distribution.
Open vStorage is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY of any kind.
*/
#include "asd_access.h"
#include "rdma_transport.h"
#include "tcp_transport.h"
#include <iostream>
#include <mutex>
namespace alba {
namespace asd {
using alba::proxy_protocol::OsdInfo;
#define LOCK() std::lock_guard<std::mutex> lock(_mutex)
ConnectionPool::ConnectionPool(std::unique_ptr<OsdInfo> config, size_t capacity)
: config_(std::move(config)),
capacity_(capacity),
_fast_path_failures(0) {
ALBA_LOG(INFO, "Created pool for asd client " << *config_ << ", capacity "
<< capacity);
}
ConnectionPool::~ConnectionPool() { clear_(connections_); }
std::unique_ptr<Asd_client> ConnectionPool::pop_(Connections &conns) {
std::unique_ptr<Asd_client> c;
if (not conns.empty()) {
c = std::unique_ptr<Asd_client>(&conns.front());
conns.pop_front();
}
return c;
}
void ConnectionPool::clear_(Connections &conns) {
while (not conns.empty()) {
pop_(conns);
}
}
std::unique_ptr<Asd_client> ConnectionPool::make_one_() const {
auto duration = std::chrono::seconds(5);
std::unique_ptr<transport::Transport> transport;
if (config_->use_rdma) {
;
transport =
std::unique_ptr<transport::Transport>(new transport::RDMA_transport(
config_->ips[0], std::to_string(config_->port), duration));
} else {
transport =
std::unique_ptr<transport::Transport>(new transport::TCP_transport(
config_->ips[0], std::to_string(config_->port), duration));
}
std::unique_ptr<Asd_client> c(
new Asd_client(duration, std::move(transport), config_->long_id));
return c;
}
void ConnectionPool::release_connection(std::unique_ptr<Asd_client> conn) {
LOCK();
if (conn) {
_fast_path_failures = 0;
if (connections_.size() < capacity_) {
connections_.push_front(*conn.release());
return;
}
} else {
_failure_time = std::chrono::steady_clock::now();
_fast_path_failures++;
}
}
std::unique_ptr<Asd_client> ConnectionPool::get_connection() {
std::unique_ptr<Asd_client> conn;
{
LOCK();
if (_fast_path_failures >= 15) {
if (duration_cast<seconds>(steady_clock::now() - _failure_time).count() <
120) {
return std::unique_ptr<Asd_client>(nullptr);
}
}
conn = pop_(connections_);
}
if (not conn) {
conn = make_one_();
}
return conn;
}
size_t ConnectionPool::size() const {
LOCK();
return connections_.size();
}
size_t ConnectionPool::capacity() const {
LOCK();
return capacity_;
}
void ConnectionPool::capacity(size_t cap) {
Connections tmp;
{
LOCK();
std::swap(capacity_, cap);
if (connections_.size() > capacity_) {
for (size_t i = 0; i < capacity_; ++i) {
Asd_client &c = connections_.front();
connections_.pop_front();
tmp.push_front(c);
}
std::swap(tmp, connections_);
}
}
clear_(tmp);
ALBA_LOG(INFO, *config_ << ": updated capacity from " << cap << " to "
<< capacity());
}
ConnectionPool *
ConnectionPools::get_connection_pool(const proxy_protocol::OsdInfo &osd_info,
int connection_pool_size) {
if (!osd_info.kind_asd) {
return nullptr;
}
LOCK();
auto it = connection_pools_.find(osd_info.long_id);
if (it == connection_pools_.end()) {
ALBA_LOG(INFO, "asd ConnenctionPools adding ConnectionPool for "
<< osd_info.long_id);
proxy_protocol::OsdInfo *osd_info_copy =
new proxy_protocol::OsdInfo(osd_info);
connection_pools_.emplace(
osd_info.long_id,
std::unique_ptr<ConnectionPool>(new ConnectionPool(
std::unique_ptr<proxy_protocol::OsdInfo>(osd_info_copy),
connection_pool_size)));
it = connection_pools_.find(osd_info.long_id);
}
return it->second.get();
}
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* Raphael Hiesgen <raphael.hiesgen@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef SMART_PTR_HPP
#define SMART_PTR_HPP
#include <memory>
#include <algorithm>
#include <type_traits>
namespace cppa { namespace opencl {
template<typename T, cl_int (*ref)(T), cl_int (*deref)(T)>
class smart_ptr {
typedef typename std::remove_pointer<T>::type element_type;
typedef element_type* pointer;
typedef element_type& reference;
typedef const element_type* const_pointer;
typedef const element_type& const_reference;
public:
smart_ptr(pointer ptr = nullptr) : m_ptr(ptr) {
if (m_ptr) ref(m_ptr);
}
~smart_ptr() { reset(); }
smart_ptr(const smart_ptr& other) : m_ptr(other.m_ptr) {
if (m_ptr) ref(m_ptr);
}
smart_ptr(smart_ptr&& other) : m_ptr(other.m_ptr) {
other.m_ptr = nullptr;
}
smart_ptr& operator=(pointer ptr) {
reset(ptr);
return *this;
}
smart_ptr& operator=(smart_ptr&& other) {
std::swap(m_ptr, other.m_ptr);
return *this;
}
smart_ptr& operator=(const smart_ptr& other) {
smart_ptr tmp{other};
std::swap(m_ptr, tmp.m_ptr);
return *this;
}
inline void reset(pointer ptr = nullptr) {
if (m_ptr) deref(m_ptr);
m_ptr = ptr;
if (ptr) ref(ptr);
}
// does not modify reference count of ptr
inline void adopt(pointer ptr) {
reset();
m_ptr = ptr;
}
inline pointer get() const { return m_ptr; }
inline pointer operator->() const { return m_ptr; }
inline reference operator*() const { return *m_ptr; }
inline bool operator!() const { return m_ptr == nullptr; }
inline explicit operator bool() const { return m_ptr != nullptr; }
private:
pointer m_ptr;
};
typedef smart_ptr<cl_mem,clRetainMemObject,clReleaseMemObject> mem_ptr;
typedef smart_ptr<cl_kernel,clRetainKernel,clReleaseKernel> kernel_ptr;
typedef smart_ptr<cl_device_id,clRetainDevice,clReleaseDevice> device_ptr;
typedef smart_ptr<cl_context,clRetainContext,clReleaseContext> context_ptr;
typedef smart_ptr<cl_program,clRetainProgram,clReleaseProgram> program_ptr;
typedef smart_ptr<cl_command_queue,clRetainCommandQueue,clReleaseCommandQueue>
command_queue_ptr;
} } // namespace cppa::opencl
#endif // SMART_PTR_HPP
<commit_msg>Added smart pointer for opencl types<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* Raphael Hiesgen <raphael.hiesgen@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation, either version 3 of the License *
* or (at your option) any later version. *
* *
* libcppa 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef SMART_PTR_HPP
#define SMART_PTR_HPP
#include <memory>
#include <algorithm>
#include <type_traits>
namespace cppa { namespace opencl {
template<typename T, cl_int (*ref)(T), cl_int (*deref)(T)>
class smart_ptr {
typedef typename std::remove_pointer<T>::type element_type;
typedef element_type* pointer;
typedef element_type& reference;
typedef const element_type* const_pointer;
typedef const element_type& const_reference;
public:
smart_ptr(pointer ptr = nullptr) : m_ptr(ptr) {
if (m_ptr) ref(m_ptr);
}
~smart_ptr() { reset(); }
smart_ptr(const smart_ptr& other) : m_ptr(other.m_ptr) {
if (m_ptr) ref(m_ptr);
}
smart_ptr(smart_ptr&& other) : m_ptr(other.m_ptr) {
other.m_ptr = nullptr;
}
smart_ptr& operator=(pointer ptr) {
reset(ptr);
return *this;
}
smart_ptr& operator=(smart_ptr&& other) {
std::swap(m_ptr, other.m_ptr);
return *this;
}
smart_ptr& operator=(const smart_ptr& other) {
smart_ptr tmp{other};
std::swap(m_ptr, tmp.m_ptr);
return *this;
}
inline void reset(pointer ptr = nullptr) {
if (m_ptr) deref(m_ptr);
m_ptr = ptr;
if (ptr) ref(ptr);
}
// does not modify reference count of ptr
inline void adopt(pointer ptr) {
reset();
m_ptr = ptr;
}
inline pointer get() const { return m_ptr; }
inline pointer operator->() const { return m_ptr; }
inline reference operator*() const { return *m_ptr; }
inline bool operator!() const { return m_ptr == nullptr; }
inline explicit operator bool() const { return m_ptr != nullptr; }
private:
pointer m_ptr;
};
typedef smart_ptr<cl_mem,clRetainMemObject,clReleaseMemObject> mem_ptr;
typedef smart_ptr<cl_event,clRetainEvent,clReleaseEvent> event_ptr;
typedef smart_ptr<cl_kernel,clRetainKernel,clReleaseKernel> kernel_ptr;
typedef smart_ptr<cl_device_id,clRetainDevice,clReleaseDevice> device_ptr;
typedef smart_ptr<cl_context,clRetainContext,clReleaseContext> context_ptr;
typedef smart_ptr<cl_program,clRetainProgram,clReleaseProgram> program_ptr;
typedef smart_ptr<cl_command_queue,clRetainCommandQueue,clReleaseCommandQueue>
command_queue_ptr;
} } // namespace cppa::opencl
#endif // SMART_PTR_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "BigDecimal.h"
#include <sstream>
using namespace std;
using namespace db::crypto;
BigDecimal::BigDecimal(long double value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(double value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(long long value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(unsigned long long value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(int value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(unsigned int value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(const char* value)
{
initialize();
*this = value;
}
BigDecimal::BigDecimal(const string& value)
{
initialize();
*this = value;
}
BigDecimal::BigDecimal(const BigDecimal& copy)
{
initialize();
mSignificand = copy.mSignificand;
mExponent = copy.mExponent;
}
BigDecimal::~BigDecimal()
{
}
void BigDecimal::initialize()
{
mPrecision = 10;
mRoundingMode = HALF_UP;
}
void BigDecimal::setExponent(int exponent)
{
if(exponent > mExponent)
{
// multiply significand by power difference
mSignificand *= BigInteger::TEN.pow(exponent - mExponent);
}
mExponent = exponent;
}
void BigDecimal::synchronizeExponents(BigDecimal& bd1, BigDecimal& bd2)
{
// only do work if exponents are different
if(bd1.mExponent != bd2.mExponent)
{
// use the larger exponent to retain precision
if(bd1.mExponent > bd2.mExponent)
{
bd2.setExponent(bd1.mExponent);
}
else
{
bd1.setExponent(bd2.mExponent);
}
}
}
BigDecimal& BigDecimal::operator=(const BigDecimal& rhs)
{
mSignificand = rhs.mSignificand;
mExponent = rhs.mExponent;
return *this;
}
BigDecimal& BigDecimal::operator=(long double rhs)
{
// convert double to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(double rhs)
{
// convert double to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(long long rhs)
{
// convert long to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(unsigned long long rhs)
{
// convert long to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(int rhs)
{
// convert int to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(unsigned int rhs)
{
// convert int to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(const char* rhs)
{
*this = string(rhs);
return *this;
}
BigDecimal& BigDecimal::operator=(const string& rhs)
{
string temp;
// find decimal point
unsigned int dot = rhs.rfind('.');
if(dot != string::npos)
{
// check for scientific notation
unsigned int e = rhs.rfind('e');
if(e != string::npos && e != rhs.length() - 2)
{
// parse exponent
mExponent = -strtoll(rhs.c_str() + e + 1, NULL, 10);
// add number of places between the e and the decimal point
mExponent += e - dot - 1;
// remove decimal point and e
temp.append(rhs.substr(0, dot));
temp.append(rhs.substr(dot + 1, e - dot));
}
else
{
// set exponent to the number of places between dot and end of string
mExponent = rhs.length() - dot - 1;
// remove decimal point
temp.append(rhs.substr(0, dot));
if(dot != rhs.length() - 1)
{
temp.append(rhs.substr(dot + 1));
}
}
}
else
{
// no decimal point, set exponent to 0
mExponent = 0;
temp = rhs;
}
// parse significand
mSignificand = temp;
// if exponent is negative, scale the significand so the exponent is zero
if(mExponent < 0)
{
mExponent = -mExponent;
mSignificand *= BigInteger::TEN.pow(mExponent);
mExponent = 0;
}
return *this;
}
bool BigDecimal::operator==(const BigDecimal& rhs)
{
BigDecimal temp = rhs;
synchronizeExponents(*this, temp);
return this->mSignificand == temp.mSignificand;
}
bool BigDecimal::operator==(long double rhs)
{
return getDouble() == rhs;
}
bool BigDecimal::operator!=(const BigDecimal& rhs)
{
return !(*this == rhs);
}
bool BigDecimal::operator!=(long double rhs)
{
return !(*this == rhs);
}
bool BigDecimal::operator<(const BigDecimal& rhs)
{
bool rval = false;
if(isNegative() && !rhs.isNegative())
{
rval = true;
}
else if(isNegative() == rhs.isNegative())
{
BigDecimal temp = rhs;
synchronizeExponents(*this, temp);
if(mSignificand < temp.mSignificand)
{
rval = true;
}
}
return rval;
}
bool BigDecimal::operator>(const BigDecimal& rhs)
{
bool rval = false;
if(!isNegative() && rhs.isNegative())
{
rval = true;
}
else if(isNegative() == rhs.isNegative())
{
BigDecimal temp = rhs;
synchronizeExponents(*this, temp);
if(mSignificand > temp.mSignificand)
{
rval = true;
}
}
return rval;
}
bool BigDecimal::operator<=(const BigDecimal& rhs)
{
return *this < rhs || *this == rhs;
}
bool BigDecimal::operator>=(const BigDecimal& rhs)
{
return *this > rhs || *this == rhs;
}
BigDecimal BigDecimal::operator+(const BigDecimal& rhs)
{
BigDecimal rval = *this;
BigDecimal temp = rhs;
synchronizeExponents(rval, temp);
rval.mSignificand += temp.mSignificand;
return rval;
}
BigDecimal BigDecimal::operator-(const BigDecimal& rhs)
{
BigDecimal rval = *this;
BigDecimal temp = rhs;
synchronizeExponents(rval, temp);
rval.mSignificand -= temp.mSignificand;
return rval;
}
BigDecimal BigDecimal::operator*(const BigDecimal& rhs)
{
BigDecimal rval = *this;
// perform multiplication and then add exponents
rval.mSignificand *= rhs.mSignificand;
rval.mExponent += rhs.mExponent;
return rval;
}
BigDecimal BigDecimal::operator/(const BigDecimal& rhs)
{
BigDecimal rval = *this;
// add the divisor's exponent to the dividend so that when a division is
// performed, the exponents subtract to reproduce the original scale
rval.setExponent(rval.mExponent + rhs.mExponent);
// do division with remainder
BigDecimal remainder;
rval.mSignificand.divide(
rhs.mSignificand, rval.mSignificand, remainder.mSignificand);
// see if there is a remainder to add to the result
if(remainder.mSignificand != 0)
{
// determine if the remainder should be rounded up
bool roundUp = (mRoundingMode == UP) ? true : false;
if(mRoundingMode == HALF_UP)
{
// if twice the remainder is greater than or equal to the divisor,
// then it is at least half as large as the divisor
if((remainder.mSignificand + remainder.mSignificand).absCompare(
rhs.mSignificand) >= 0)
{
roundUp = true;
}
}
// raise remainder to digits of precision (taking into account the
// remainder has the same scale as the dividend rval)
unsigned int digits = 0;
if(mPrecision - rval.mExponent > 0)
{
digits = mPrecision - rval.mExponent;
remainder.mSignificand *= BigInteger::TEN.pow(digits);
}
// perform division on significand
remainder.mSignificand /= rhs.mSignificand;
// set remainder exponent to digits of precision
remainder.mExponent = mPrecision;
// round up if appropriate
if(roundUp)
{
BigDecimal bd;
bd.mSignificand = 1;
bd.mExponent = mPrecision;
rval += bd;
}
// add remainder
rval += remainder;
}
return rval;
}
BigDecimal BigDecimal::operator%(const BigDecimal& rhs)
{
BigDecimal rval = *this;
BigDecimal temp = rhs;
synchronizeExponents(rval, temp);
rval.mSignificand %= temp.mSignificand;
return rval;
}
BigDecimal& BigDecimal::operator+=(const BigDecimal& rhs)
{
*this = *this + rhs;
return *this;
}
BigDecimal& BigDecimal::operator-=(const BigDecimal& rhs)
{
*this = *this - rhs;
return *this;
}
BigDecimal& BigDecimal::operator*=(const BigDecimal& rhs)
{
*this = *this * rhs;
return *this;
}
BigDecimal& BigDecimal::operator/=(const BigDecimal& rhs)
{
*this = *this / rhs;
return *this;
}
BigDecimal& BigDecimal::operator%=(const BigDecimal& rhs)
{
*this = *this % rhs;
return *this;
}
bool BigDecimal::isZero() const
{
return mSignificand.isZero();
}
void BigDecimal::setNegative(bool negative)
{
mSignificand.setNegative(negative);
}
bool BigDecimal::isNegative() const
{
return mSignificand.isNegative();
}
long double BigDecimal::getDouble() const
{
// get value as a string
string str;
toString(str);
// parse long double
return strtold(str.c_str(), NULL);
}
void BigDecimal::setPrecision(unsigned int precision, RoundingMode roundingMode)
{
mPrecision = precision;
mRoundingMode = roundingMode;
}
unsigned int BigDecimal::getPrecision()
{
return mPrecision;
}
void BigDecimal::round()
{
// write out to a string
string str;
toString(str);
// find exponent
unsigned int dot = str.rfind('.');
if(dot != string::npos)
{
// determine if there are more digits than the precision allows
if(str.length() - (dot + 1) > mPrecision)
{
// get the extra digits
string extra = str.substr(dot + 1 + mPrecision);
// set new exponent by subtracting extra length
mExponent -= extra.length();
// truncate significand
mSignificand = (str.substr(0, dot) + str.substr(dot + 1, mExponent));
// round significand according to rounding mode
if(mRoundingMode == UP)
{
// add 1 with the same exponent
BigDecimal bd = 1;
bd.mExponent = mExponent;
*this += bd;
}
else if(mRoundingMode == HALF_UP)
{
// (52 = '4', 57 = '9')
if(extra.at(0) > 52 && extra.at(0) <= 57)
{
// add 1 with the same exponent
BigDecimal bd = 1;
bd.mExponent = mExponent;
*this += bd;
}
}
}
}
}
string& BigDecimal::toString(string& str) const
{
// write out significand
mSignificand.toString(str);
if(mExponent < 0)
{
// append zeros
int zeros = -mExponent - str.length();
if(zeros > 0)
{
str.append(0, zeros, '0');
}
else
{
// insert decimal point
str.insert(str.length() + mExponent, 1, '.');
}
}
else if(mExponent > 0)
{
// prepend zeros
int zeros = mExponent - str.length();
if(zeros > 0)
{
str.insert(0, zeros, '0');
}
if((unsigned int)mExponent == str.length())
{
// prepend "0."
str.insert(0, 1, '.');
str.insert(0, 1, '0');
}
else
{
// insert decimal point
str.insert(str.length() - mExponent, 1, '.');
}
}
return str;
}
ostream& operator<<(ostream& os, const BigDecimal& bd)
{
string str;
os << bd.toString(str);
return os;
}
istream& operator>>(istream& is, BigDecimal& bd)
{
string str;
is >> str;
bd = str;
return is;
}
<commit_msg>Made sure to initialize exponent.<commit_after>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "BigDecimal.h"
#include <sstream>
using namespace std;
using namespace db::crypto;
BigDecimal::BigDecimal(long double value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(double value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(long long value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(unsigned long long value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(int value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(unsigned int value)
{
initialize();
if(value != 0)
{
*this = value;
}
}
BigDecimal::BigDecimal(const char* value)
{
initialize();
*this = value;
}
BigDecimal::BigDecimal(const string& value)
{
initialize();
*this = value;
}
BigDecimal::BigDecimal(const BigDecimal& copy)
{
initialize();
mSignificand = copy.mSignificand;
mExponent = copy.mExponent;
}
BigDecimal::~BigDecimal()
{
}
void BigDecimal::initialize()
{
mExponent = 0;
mPrecision = 10;
mRoundingMode = HALF_UP;
}
void BigDecimal::setExponent(int exponent)
{
if(exponent > mExponent)
{
// multiply significand by power difference
mSignificand *= BigInteger::TEN.pow(exponent - mExponent);
}
mExponent = exponent;
}
void BigDecimal::synchronizeExponents(BigDecimal& bd1, BigDecimal& bd2)
{
// only do work if exponents are different
if(bd1.mExponent != bd2.mExponent)
{
// use the larger exponent to retain precision
if(bd1.mExponent > bd2.mExponent)
{
bd2.setExponent(bd1.mExponent);
}
else
{
bd1.setExponent(bd2.mExponent);
}
}
}
BigDecimal& BigDecimal::operator=(const BigDecimal& rhs)
{
mSignificand = rhs.mSignificand;
mExponent = rhs.mExponent;
return *this;
}
BigDecimal& BigDecimal::operator=(long double rhs)
{
// convert double to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(double rhs)
{
// convert double to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(long long rhs)
{
// convert long to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(unsigned long long rhs)
{
// convert long to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(int rhs)
{
// convert int to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(unsigned int rhs)
{
// convert int to string
ostringstream oss;
oss << rhs;
return *this = oss.str();
}
BigDecimal& BigDecimal::operator=(const char* rhs)
{
*this = string(rhs);
return *this;
}
BigDecimal& BigDecimal::operator=(const string& rhs)
{
string temp;
// find decimal point
unsigned int dot = rhs.rfind('.');
if(dot != string::npos)
{
// check for scientific notation
unsigned int e = rhs.rfind('e');
if(e != string::npos && e != rhs.length() - 2)
{
// parse exponent
mExponent = -strtoll(rhs.c_str() + e + 1, NULL, 10);
// add number of places between the e and the decimal point
mExponent += e - dot - 1;
// remove decimal point and e
temp.append(rhs.substr(0, dot));
temp.append(rhs.substr(dot + 1, e - dot));
}
else
{
// set exponent to the number of places between dot and end of string
mExponent = rhs.length() - dot - 1;
// remove decimal point
temp.append(rhs.substr(0, dot));
if(dot != rhs.length() - 1)
{
temp.append(rhs.substr(dot + 1));
}
}
}
else
{
// no decimal point, set exponent to 0
mExponent = 0;
temp = rhs;
}
// parse significand
mSignificand = temp;
// if exponent is negative, scale the significand so the exponent is zero
if(mExponent < 0)
{
mExponent = -mExponent;
mSignificand *= BigInteger::TEN.pow(mExponent);
mExponent = 0;
}
return *this;
}
bool BigDecimal::operator==(const BigDecimal& rhs)
{
BigDecimal temp = rhs;
synchronizeExponents(*this, temp);
return this->mSignificand == temp.mSignificand;
}
bool BigDecimal::operator==(long double rhs)
{
return getDouble() == rhs;
}
bool BigDecimal::operator!=(const BigDecimal& rhs)
{
return !(*this == rhs);
}
bool BigDecimal::operator!=(long double rhs)
{
return !(*this == rhs);
}
bool BigDecimal::operator<(const BigDecimal& rhs)
{
bool rval = false;
if(isNegative() && !rhs.isNegative())
{
rval = true;
}
else if(isNegative() == rhs.isNegative())
{
BigDecimal temp = rhs;
synchronizeExponents(*this, temp);
if(mSignificand < temp.mSignificand)
{
rval = true;
}
}
return rval;
}
bool BigDecimal::operator>(const BigDecimal& rhs)
{
bool rval = false;
if(!isNegative() && rhs.isNegative())
{
rval = true;
}
else if(isNegative() == rhs.isNegative())
{
BigDecimal temp = rhs;
synchronizeExponents(*this, temp);
if(mSignificand > temp.mSignificand)
{
rval = true;
}
}
return rval;
}
bool BigDecimal::operator<=(const BigDecimal& rhs)
{
return *this < rhs || *this == rhs;
}
bool BigDecimal::operator>=(const BigDecimal& rhs)
{
return *this > rhs || *this == rhs;
}
BigDecimal BigDecimal::operator+(const BigDecimal& rhs)
{
BigDecimal rval = *this;
BigDecimal temp = rhs;
synchronizeExponents(rval, temp);
rval.mSignificand += temp.mSignificand;
return rval;
}
BigDecimal BigDecimal::operator-(const BigDecimal& rhs)
{
BigDecimal rval = *this;
BigDecimal temp = rhs;
synchronizeExponents(rval, temp);
rval.mSignificand -= temp.mSignificand;
return rval;
}
BigDecimal BigDecimal::operator*(const BigDecimal& rhs)
{
BigDecimal rval = *this;
// perform multiplication and then add exponents
rval.mSignificand *= rhs.mSignificand;
rval.mExponent += rhs.mExponent;
return rval;
}
BigDecimal BigDecimal::operator/(const BigDecimal& rhs)
{
BigDecimal rval = *this;
// add the divisor's exponent to the dividend so that when a division is
// performed, the exponents subtract to reproduce the original scale
rval.setExponent(rval.mExponent + rhs.mExponent);
// do division with remainder
BigDecimal remainder;
rval.mSignificand.divide(
rhs.mSignificand, rval.mSignificand, remainder.mSignificand);
// see if there is a remainder to add to the result
if(remainder.mSignificand != 0)
{
// determine if the remainder should be rounded up
bool roundUp = (mRoundingMode == UP) ? true : false;
if(mRoundingMode == HALF_UP)
{
// if twice the remainder is greater than or equal to the divisor,
// then it is at least half as large as the divisor
if((remainder.mSignificand + remainder.mSignificand).absCompare(
rhs.mSignificand) >= 0)
{
roundUp = true;
}
}
// raise remainder to digits of precision (taking into account the
// remainder has the same scale as the dividend rval)
unsigned int digits = 0;
if(mPrecision - rval.mExponent > 0)
{
digits = mPrecision - rval.mExponent;
remainder.mSignificand *= BigInteger::TEN.pow(digits);
}
// perform division on significand
remainder.mSignificand /= rhs.mSignificand;
// set remainder exponent to digits of precision
remainder.mExponent = mPrecision;
// round up if appropriate
if(roundUp)
{
BigDecimal bd;
bd.mSignificand = 1;
bd.mExponent = mPrecision;
rval += bd;
}
// add remainder
rval += remainder;
}
return rval;
}
BigDecimal BigDecimal::operator%(const BigDecimal& rhs)
{
BigDecimal rval = *this;
BigDecimal temp = rhs;
synchronizeExponents(rval, temp);
rval.mSignificand %= temp.mSignificand;
return rval;
}
BigDecimal& BigDecimal::operator+=(const BigDecimal& rhs)
{
*this = *this + rhs;
return *this;
}
BigDecimal& BigDecimal::operator-=(const BigDecimal& rhs)
{
*this = *this - rhs;
return *this;
}
BigDecimal& BigDecimal::operator*=(const BigDecimal& rhs)
{
*this = *this * rhs;
return *this;
}
BigDecimal& BigDecimal::operator/=(const BigDecimal& rhs)
{
*this = *this / rhs;
return *this;
}
BigDecimal& BigDecimal::operator%=(const BigDecimal& rhs)
{
*this = *this % rhs;
return *this;
}
bool BigDecimal::isZero() const
{
return mSignificand.isZero();
}
void BigDecimal::setNegative(bool negative)
{
mSignificand.setNegative(negative);
}
bool BigDecimal::isNegative() const
{
return mSignificand.isNegative();
}
long double BigDecimal::getDouble() const
{
// get value as a string
string str;
toString(str);
// parse long double
return strtold(str.c_str(), NULL);
}
void BigDecimal::setPrecision(unsigned int precision, RoundingMode roundingMode)
{
mPrecision = precision;
mRoundingMode = roundingMode;
}
unsigned int BigDecimal::getPrecision()
{
return mPrecision;
}
void BigDecimal::round()
{
// write out to a string
string str;
toString(str);
// find exponent
unsigned int dot = str.rfind('.');
if(dot != string::npos)
{
// determine if there are more digits than the precision allows
if(str.length() - (dot + 1) > mPrecision)
{
// get the extra digits
string extra = str.substr(dot + 1 + mPrecision);
// set new exponent by subtracting extra length
mExponent -= extra.length();
// truncate significand
mSignificand = (str.substr(0, dot) + str.substr(dot + 1, mExponent));
// round significand according to rounding mode
if(mRoundingMode == UP)
{
// add 1 with the same exponent
BigDecimal bd = 1;
bd.mExponent = mExponent;
*this += bd;
}
else if(mRoundingMode == HALF_UP)
{
// (52 = '4', 57 = '9')
if(extra.at(0) > 52 && extra.at(0) <= 57)
{
// add 1 with the same exponent
BigDecimal bd = 1;
bd.mExponent = mExponent;
*this += bd;
}
}
}
}
}
string& BigDecimal::toString(string& str) const
{
// write out significand
mSignificand.toString(str);
if(mExponent < 0)
{
// append zeros
int zeros = -mExponent - str.length();
if(zeros > 0)
{
str.append(0, zeros, '0');
}
else
{
// insert decimal point
str.insert(str.length() + mExponent, 1, '.');
}
}
else if(mExponent > 0)
{
// prepend zeros
int zeros = mExponent - str.length();
if(zeros > 0)
{
str.insert(0, zeros, '0');
}
if((unsigned int)mExponent == str.length())
{
// prepend "0."
str.insert(0, 1, '.');
str.insert(0, 1, '0');
}
else
{
// insert decimal point
str.insert(str.length() - mExponent, 1, '.');
}
}
return str;
}
ostream& operator<<(ostream& os, const BigDecimal& bd)
{
string str;
os << bd.toString(str);
return os;
}
istream& operator>>(istream& is, BigDecimal& bd)
{
string str;
is >> str;
bd = str;
return is;
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "cvmfs_config.h"
#include "util_concurrency.h"
#include <unistd.h>
#include <cassert>
#ifdef CVMFS_NAMESPACE_GUARD
namespace CVMFS_NAMESPACE_GUARD {
#endif
unsigned int GetNumberOfCpuCores() {
const int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
if (numCPU <= 0) {
LogCvmfs(kLogSpooler, kLogWarning, "Unable to determine the available "
"number of processors in the system... "
"falling back to default '%d'",
kFallbackNumberOfCpus);
return kFallbackNumberOfCpus;
}
return static_cast<unsigned int>(numCPU);
}
Signal::Signal() : fired_(false) {
int retval = pthread_mutex_init(&lock_, NULL);
assert(retval == 0);
retval = pthread_cond_init(&signal_, NULL);
assert(retval == 0);
}
Signal::~Signal() {
assert(IsSleeping());
assert(0 == pthread_cond_destroy(&signal_));
assert(0 == pthread_mutex_destroy(&lock_));
}
void Signal::Wait() {
MutexLockGuard guard(lock_);
while (!fired_) {
int retval = pthread_cond_wait(&signal_, &lock_);
assert(retval == 0);
}
fired_ = false;
}
void Signal::Wakeup() {
MutexLockGuard guard(lock_);
fired_ = true;
int retval = pthread_cond_broadcast(&signal_);
assert(retval == 0);
}
bool Signal::IsSleeping() {
MutexLockGuard guard(lock_);
return fired_ == false;
}
#ifdef CVMFS_NAMESPACE_GUARD
} // namespace CVMFS_NAMESPACE_GUARD
#endif
<commit_msg>remove side effects from assert<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "cvmfs_config.h"
#include "util_concurrency.h"
#include <unistd.h>
#include <cassert>
#ifdef CVMFS_NAMESPACE_GUARD
namespace CVMFS_NAMESPACE_GUARD {
#endif
unsigned int GetNumberOfCpuCores() {
const int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
if (numCPU <= 0) {
LogCvmfs(kLogSpooler, kLogWarning, "Unable to determine the available "
"number of processors in the system... "
"falling back to default '%d'",
kFallbackNumberOfCpus);
return kFallbackNumberOfCpus;
}
return static_cast<unsigned int>(numCPU);
}
Signal::Signal() : fired_(false) {
int retval = pthread_mutex_init(&lock_, NULL);
assert(retval == 0);
retval = pthread_cond_init(&signal_, NULL);
assert(retval == 0);
}
Signal::~Signal() {
assert(IsSleeping());
int res = pthread_cond_destroy(&signal_);
assert(0 == res);
res = pthread_mutex_destroy(&lock_);
assert(0 == res);
}
void Signal::Wait() {
MutexLockGuard guard(lock_);
while (!fired_) {
int retval = pthread_cond_wait(&signal_, &lock_);
assert(retval == 0);
}
fired_ = false;
}
void Signal::Wakeup() {
MutexLockGuard guard(lock_);
fired_ = true;
int retval = pthread_cond_broadcast(&signal_);
assert(retval == 0);
}
bool Signal::IsSleeping() {
MutexLockGuard guard(lock_);
return fired_ == false;
}
#ifdef CVMFS_NAMESPACE_GUARD
} // namespace CVMFS_NAMESPACE_GUARD
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2014 David Edmundson <davidedmundson@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "im-persons-data-source.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Presence>
#include "KTp/contact-factory.h"
#include "KTp/global-contact-manager.h"
#include "KTp/types.h"
#include "debug.h"
#include <KPeopleBackend/AllContactsMonitor>
#include <KPluginFactory>
#include <KPluginLoader>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QPixmap>
using namespace KPeople;
class KTpAllContacts : public AllContactsMonitor
{
Q_OBJECT
public:
KTpAllContacts();
~KTpAllContacts();
virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE;
private Q_SLOTS:
void loadCache();
void onAccountManagerReady(Tp::PendingOperation *op);
void onContactChanged();
void onContactInvalidated();
void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);
private:
QString createUri(const KTp::ContactPtr &contact) const;
//presence names indexed by ConnectionPresenceType
QHash<QString, KTp::ContactPtr> m_contacts;
QMap<QString, AbstractContact::Ptr> m_contactVCards;
};
class TelepathyContact : public KPeople::AbstractContact
{
public:
virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE
{
// Check if the contact is valid first
if (m_contact && m_contact->manager() && m_contact->manager()->connection() && m_account) {
if (key == AbstractContact::NameProperty)
return m_contact->alias();
else if(key == AbstractContact::GroupsProperty)
return m_contact->groups();
else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID)
return m_contact->id();
else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH)
return m_account->objectPath();
else if(key == S_KPEOPLE_PROPERTY_PRESENCE)
return s_presenceStrings.value(m_contact->presence().type());
else if (key == AbstractContact::PictureProperty)
return m_contact->avatarPixmap();
}
return m_properties[key];
}
void insertProperty(const QString &key, const QVariant &value)
{
m_properties[key] = value;
}
void setContact(const KTp::ContactPtr &contact)
{
m_contact = contact;
}
void setAccount(const Tp::AccountPtr &account)
{
m_account = account;
}
private:
KTp::ContactPtr m_contact;
Tp::AccountPtr m_account;
QVariantMap m_properties;
};
KTpAllContacts::KTpAllContacts()
{
Tp::registerTypes();
loadCache();
}
KTpAllContacts::~KTpAllContacts()
{
}
void KTpAllContacts::loadCache()
{
QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache"));
QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp");
QDir().mkpath(path);
db.setDatabaseName(path+QStringLiteral("/cache.db"));
if (!db.open()) {
qWarning() << "couldn't open database" << db.databaseName();
}
QSqlQuery query(db);
query.exec(QLatin1String("SELECT groupName FROM groups ORDER BY groupId;"));
QStringList groupsList;
while (query.next()) {
groupsList.append(query.value(0).toString());
}
if (!groupsList.isEmpty()) {
query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName, groupsIds FROM contacts;"));
} else {
query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName FROM contacts;"));
}
while (query.next()) {
QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact);
const QString accountId = query.value(0).toString();
const QString contactId = query.value(1).toString();
addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString());
addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(query.value(3).toString()));
if (!groupsList.isEmpty()) {
QVariantList contactGroups;
Q_FOREACH (const QString &groupIdStr, query.value(4).toString().split(QLatin1String(","))) {
bool convSuccess;
int groupId = groupIdStr.toInt(&convSuccess);
if ((!convSuccess) || (groupId >= groupsList.count()))
continue;
contactGroups.append(groupsList.at(groupId));
}
addressee->insertProperty(QStringLiteral("groups"), contactGroups);
}
addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]);
const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId;
m_contactVCards[uri] = addressee;
Q_EMIT contactAdded(uri, addressee);
}
//now start fetching the up-to-date information
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
emitInitialFetchComplete(true);
}
QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const
{
// so real ID will look like
// ktp://gabble/jabber/blah/asdfjwer?foo@bar.com
// ? is used as it is not a valid character in the dbus path that makes up the account UID
return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id();
}
void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName();
qCWarning(KTP_KPEOPLE) << op->errorMessage();
return;
}
qCDebug(KTP_KPEOPLE) << "Account manager ready";
connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());
}
void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_contacts.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) {
const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);
const QString uri = createUri(contact);
m_contacts.remove(uri);
m_contactVCards.remove(uri);
Q_EMIT contactRemoved(uri);
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);
const QString uri = createUri(ktpContact);
AbstractContact::Ptr vcard = m_contactVCards.value(uri);
bool added = false;
if (!vcard) {
vcard = AbstractContact::Ptr(new TelepathyContact);
m_contactVCards[uri] = vcard;
added = true;
}
static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact);
static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact));
m_contacts.insert(uri, ktpContact);
if (added) {
Q_EMIT contactAdded(uri, vcard);
} else {
Q_EMIT contactChanged(uri, vcard);
}
connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(invalidated()),
this, SLOT(onContactInvalidated()));
connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(addedToGroup(QString)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)),
this, SLOT(onContactChanged()));
}
}
void KTpAllContacts::onContactChanged()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
Q_EMIT contactChanged(uri, m_contactVCards.value(uri));
}
void KTpAllContacts::onContactInvalidated()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
m_contacts.remove(uri);
//set to offline and emit changed
AbstractContact::Ptr vcard = m_contactVCards[uri];
TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data());
tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline"));
Q_EMIT contactChanged(uri, vcard);
}
QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts()
{
return m_contactVCards;
}
IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)
: BasePersonsDataSource(parent)
{
Q_UNUSED(args);
}
IMPersonsDataSource::~IMPersonsDataSource()
{
}
QString IMPersonsDataSource::sourcePluginId() const
{
return QStringLiteral("ktp");
}
AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()
{
return new KTpAllContacts();
}
K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); )
K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") )
#include "im-persons-data-source.moc"
<commit_msg>[kpeople] Groups need to be SELECTed DISTINCTly<commit_after>/*
Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2014 David Edmundson <davidedmundson@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "im-persons-data-source.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/Presence>
#include "KTp/contact-factory.h"
#include "KTp/global-contact-manager.h"
#include "KTp/types.h"
#include "debug.h"
#include <KPeopleBackend/AllContactsMonitor>
#include <KPluginFactory>
#include <KPluginLoader>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QPixmap>
using namespace KPeople;
class KTpAllContacts : public AllContactsMonitor
{
Q_OBJECT
public:
KTpAllContacts();
~KTpAllContacts();
virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE;
private Q_SLOTS:
void loadCache();
void onAccountManagerReady(Tp::PendingOperation *op);
void onContactChanged();
void onContactInvalidated();
void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved);
private:
QString createUri(const KTp::ContactPtr &contact) const;
//presence names indexed by ConnectionPresenceType
QHash<QString, KTp::ContactPtr> m_contacts;
QMap<QString, AbstractContact::Ptr> m_contactVCards;
};
class TelepathyContact : public KPeople::AbstractContact
{
public:
virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE
{
// Check if the contact is valid first
if (m_contact && m_contact->manager() && m_contact->manager()->connection() && m_account) {
if (key == AbstractContact::NameProperty)
return m_contact->alias();
else if(key == AbstractContact::GroupsProperty)
return m_contact->groups();
else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID)
return m_contact->id();
else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH)
return m_account->objectPath();
else if(key == S_KPEOPLE_PROPERTY_PRESENCE)
return s_presenceStrings.value(m_contact->presence().type());
else if (key == AbstractContact::PictureProperty)
return m_contact->avatarPixmap();
}
return m_properties[key];
}
void insertProperty(const QString &key, const QVariant &value)
{
m_properties[key] = value;
}
void setContact(const KTp::ContactPtr &contact)
{
m_contact = contact;
}
void setAccount(const Tp::AccountPtr &account)
{
m_account = account;
}
private:
KTp::ContactPtr m_contact;
Tp::AccountPtr m_account;
QVariantMap m_properties;
};
KTpAllContacts::KTpAllContacts()
{
Tp::registerTypes();
loadCache();
}
KTpAllContacts::~KTpAllContacts()
{
}
void KTpAllContacts::loadCache()
{
QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache"));
QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp");
QDir().mkpath(path);
db.setDatabaseName(path+QStringLiteral("/cache.db"));
if (!db.open()) {
qWarning() << "couldn't open database" << db.databaseName();
}
QSqlQuery query(db);
query.exec(QLatin1String("SELECT DISTINCT groupName FROM groups ORDER BY groupId;"));
QStringList groupsList;
while (query.next()) {
groupsList.append(query.value(0).toString());
}
if (!groupsList.isEmpty()) {
query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName, groupsIds FROM contacts;"));
} else {
query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName FROM contacts;"));
}
while (query.next()) {
QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact);
const QString accountId = query.value(0).toString();
const QString contactId = query.value(1).toString();
addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString());
addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(query.value(3).toString()));
if (!groupsList.isEmpty()) {
QVariantList contactGroups;
Q_FOREACH (const QString &groupIdStr, query.value(4).toString().split(QLatin1String(","))) {
bool convSuccess;
int groupId = groupIdStr.toInt(&convSuccess);
if ((!convSuccess) || (groupId >= groupsList.count()))
continue;
contactGroups.append(groupsList.at(groupId));
}
addressee->insertProperty(QStringLiteral("groups"), contactGroups);
}
addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId);
addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]);
const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId;
m_contactVCards[uri] = addressee;
Q_EMIT contactAdded(uri, addressee);
}
//now start fetching the up-to-date information
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
emitInitialFetchComplete(true);
}
QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const
{
// so real ID will look like
// ktp://gabble/jabber/blah/asdfjwer?foo@bar.com
// ? is used as it is not a valid character in the dbus path that makes up the account UID
return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id();
}
void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName();
qCWarning(KTP_KPEOPLE) << op->errorMessage();
return;
}
qCDebug(KTP_KPEOPLE) << "Account manager ready";
connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts());
}
void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
if (!m_contacts.isEmpty()) {
Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) {
const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);
const QString uri = createUri(contact);
m_contacts.remove(uri);
m_contactVCards.remove(uri);
Q_EMIT contactRemoved(uri);
}
}
Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact);
const QString uri = createUri(ktpContact);
AbstractContact::Ptr vcard = m_contactVCards.value(uri);
bool added = false;
if (!vcard) {
vcard = AbstractContact::Ptr(new TelepathyContact);
m_contactVCards[uri] = vcard;
added = true;
}
static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact);
static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact));
m_contacts.insert(uri, ktpContact);
if (added) {
Q_EMIT contactAdded(uri, vcard);
} else {
Q_EMIT contactChanged(uri, vcard);
}
connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(invalidated()),
this, SLOT(onContactInvalidated()));
connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(addedToGroup(QString)),
this, SLOT(onContactChanged()));
connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)),
this, SLOT(onContactChanged()));
}
}
void KTpAllContacts::onContactChanged()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
Q_EMIT contactChanged(uri, m_contactVCards.value(uri));
}
void KTpAllContacts::onContactInvalidated()
{
const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender()));
const QString uri = createUri(contact);
m_contacts.remove(uri);
//set to offline and emit changed
AbstractContact::Ptr vcard = m_contactVCards[uri];
TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data());
tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline"));
Q_EMIT contactChanged(uri, vcard);
}
QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts()
{
return m_contactVCards;
}
IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args)
: BasePersonsDataSource(parent)
{
Q_UNUSED(args);
}
IMPersonsDataSource::~IMPersonsDataSource()
{
}
QString IMPersonsDataSource::sourcePluginId() const
{
return QStringLiteral("ktp");
}
AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor()
{
return new KTpAllContacts();
}
K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); )
K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") )
#include "im-persons-data-source.moc"
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef ROCPRIM_INTRINSICS_WARP_SHUFFLE_HPP_
#define ROCPRIM_INTRINSICS_WARP_SHUFFLE_HPP_
#include <type_traits>
#include "../config.hpp"
#include "thread.hpp"
/// \addtogroup collectivewarpmodule
/// @{
BEGIN_ROCPRIM_NAMESPACE
namespace detail
{
template<class T, class ShuffleOp>
ROCPRIM_DEVICE inline
T warp_shuffle_op(T input, ShuffleOp&& op)
{
constexpr int words_no = (sizeof(T) + sizeof(int) - 1) / sizeof(int);
int * shfl_input = reinterpret_cast<int *>(&input);
int shfl_output_words[words_no];
T * shlf_output = reinterpret_cast<T*>(shfl_output_words);
#pragma unroll
for(int i = 0; i < words_no; i++)
{
shfl_output_words[i] = op(shfl_input[i]);
}
return *shlf_output;
}
} // end namespace detail
/// \brief Shuffle for any data type.
///
/// Each thread in warp obtains \p input from <tt>src_lane</tt>-th thread
/// in warp. If \p width is less than warp_size() then each subsection of the
/// warp behaves as a separate entity with a starting logical lane id of 0.
/// If \p src_lane is not in [0; \p width) range, the returned value is
/// equal to \p input passed by the <tt>src_lane modulo width</tt> thread.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param src_lane - warp if of a thread whose \p input should be returned
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle(T input, const int src_lane, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#ifdef ROCPRIM_HC_API
return hc::__shfl(v, src_lane, width);
#else
return __shfl(v, src_lane, width);
#endif
}
);
}
/// \brief Shuffle up for any data type.
///
/// <tt>i</tt>-th thread in warp obtains \p input from <tt>i-delta</tt>-th
/// thread in warp. If \p <tt>i-delta</tt> is not in [0; \p width) range,
/// thread's own \p input is returned.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param delta - offset for calculating source lane id
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle_up(T input, const unsigned int delta, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#ifdef ROCPRIM_HC_API
return hc::__shfl_up(v, delta, width);
#else
return __shfl_up(v, delta, width);
#endif
}
);
}
/// \brief Shuffle down for any data type.
///
/// <tt>i</tt>-th thread in warp obtains \p input from <tt>i+delta</tt>-th
/// thread in warp. If \p <tt>i+delta</tt> is not in [0; \p width) range,
/// thread's own \p input is returned.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param delta - offset for calculating source lane id
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle_down(T input, const unsigned int delta, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#ifdef ROCPRIM_HC_API
return hc::__shfl_down(v, delta, width);
#else
return __shfl_down(v, delta, width);
#endif
}
);
}
/// \brief Shuffle XOR for any data type.
///
/// <tt>i</tt>-th thread in warp obtains \p input from <tt>i^lane_mask</tt>-th
/// thread in warp.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param lane_mask - mask used for calculating source lane id
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle_xor(T input, const int lane_mask, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#ifdef ROCPRIM_HC_API
return hc::__shfl_xor(v, lane_mask, width);
#else
return __shfl_xor(v, lane_mask, width);
#endif
}
);
}
END_ROCPRIM_NAMESPACE
#endif // ROCPRIM_INTRINSICS_WARP_SHUFFLE_HPP_
/// @}
// end of group collectivewarpmodule
<commit_msg>Workaround for __shfl* bug in HIP<commit_after>// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef ROCPRIM_INTRINSICS_WARP_SHUFFLE_HPP_
#define ROCPRIM_INTRINSICS_WARP_SHUFFLE_HPP_
#include <type_traits>
#include "../config.hpp"
#include "thread.hpp"
/// \addtogroup collectivewarpmodule
/// @{
BEGIN_ROCPRIM_NAMESPACE
namespace detail
{
template<class T, class ShuffleOp>
ROCPRIM_DEVICE inline
T warp_shuffle_op(T input, ShuffleOp&& op)
{
constexpr int words_no = (sizeof(T) + sizeof(int) - 1) / sizeof(int);
int * shfl_input = reinterpret_cast<int *>(&input);
int shfl_output_words[words_no];
T * shlf_output = reinterpret_cast<T*>(shfl_output_words);
#pragma unroll
for(int i = 0; i < words_no; i++)
{
shfl_output_words[i] = op(shfl_input[i]);
}
return *shlf_output;
}
} // end namespace detail
/// \brief Shuffle for any data type.
///
/// Each thread in warp obtains \p input from <tt>src_lane</tt>-th thread
/// in warp. If \p width is less than warp_size() then each subsection of the
/// warp behaves as a separate entity with a starting logical lane id of 0.
/// If \p src_lane is not in [0; \p width) range, the returned value is
/// equal to \p input passed by the <tt>src_lane modulo width</tt> thread.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param src_lane - warp if of a thread whose \p input should be returned
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle(T input, const int src_lane, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#if defined(ROCPRIM_HC_API) || defined(__HIP_PLATFORM_HCC__)
return hc::__shfl(v, src_lane, width);
#else
return __shfl(v, src_lane, width);
#endif
}
);
}
/// \brief Shuffle up for any data type.
///
/// <tt>i</tt>-th thread in warp obtains \p input from <tt>i-delta</tt>-th
/// thread in warp. If \p <tt>i-delta</tt> is not in [0; \p width) range,
/// thread's own \p input is returned.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param delta - offset for calculating source lane id
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle_up(T input, const unsigned int delta, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#if defined(ROCPRIM_HC_API) || defined(__HIP_PLATFORM_HCC__)
return hc::__shfl_up(v, delta, width);
#else
return __shfl_up(v, delta, width);
#endif
}
);
}
/// \brief Shuffle down for any data type.
///
/// <tt>i</tt>-th thread in warp obtains \p input from <tt>i+delta</tt>-th
/// thread in warp. If \p <tt>i+delta</tt> is not in [0; \p width) range,
/// thread's own \p input is returned.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param delta - offset for calculating source lane id
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle_down(T input, const unsigned int delta, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#if defined(ROCPRIM_HC_API) || defined(__HIP_PLATFORM_HCC__)
return hc::__shfl_down(v, delta, width);
#else
return __shfl_down(v, delta, width);
#endif
}
);
}
/// \brief Shuffle XOR for any data type.
///
/// <tt>i</tt>-th thread in warp obtains \p input from <tt>i^lane_mask</tt>-th
/// thread in warp.
///
/// Note: The optional \p width parameter must be a power of 2; results are
/// undefined if it is not a power of 2, or it is greater than warp_size().
///
/// \param input - input to pass to other threads
/// \param lane_mask - mask used for calculating source lane id
/// \param width - logical warp width
template<class T>
ROCPRIM_DEVICE inline
T warp_shuffle_xor(T input, const int lane_mask, const int width = warp_size())
{
return detail::warp_shuffle_op(
input,
[=](int v) -> int
{
#if defined(ROCPRIM_HC_API) || defined(__HIP_PLATFORM_HCC__)
return hc::__shfl_xor(v, lane_mask, width);
#else
return __shfl_xor(v, lane_mask, width);
#endif
}
);
}
END_ROCPRIM_NAMESPACE
#endif // ROCPRIM_INTRINSICS_WARP_SHUFFLE_HPP_
/// @}
// end of group collectivewarpmodule
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#include <unistd.h>
#include <crdr_chibios/sys/sys.h>
#include <uavcan_stm32/uavcan_stm32.hpp>
#include <uavcan/protocol/global_time_sync_slave.hpp>
namespace app
{
namespace
{
uavcan_stm32::CanInitHelper<> can;
typedef uavcan::Node<4096> Node;
uavcan::LazyConstructor<Node> node_;
Node& getNode()
{
if (!node_.isConstructed())
{
node_.construct<uavcan::ICanDriver&, uavcan::ISystemClock&>(can.driver, uavcan_stm32::SystemClock::instance());
}
return *node_;
}
void ledSet(bool state)
{
palWritePad(GPIO_PORT_LED, GPIO_PIN_LED, state);
}
int init()
{
int res = 0;
halInit();
chibios_rt::System::init();
sdStart(&STDOUT_SD, NULL);
res = can.init(1000000);
if (res < 0)
{
goto leave;
}
leave:
return res;
}
__attribute__((noreturn))
void die(int status)
{
lowsyslog("Now I am dead x_x %i\n", status);
while (1)
{
ledSet(false);
sleep(1);
ledSet(true);
sleep(1);
}
}
class : public chibios_rt::BaseStaticThread<2048>
{
public:
msg_t main()
{
/*
* Setting up the node parameters
*/
Node& node = app::getNode();
node.setNodeID(64);
node.setName("org.uavcan.stm32_test_stm32f107");
/*
* Initializing the UAVCAN node - this may take a while
*/
while (true)
{
uavcan::NodeInitializationResult init_result;
const int uavcan_start_res = node.start(init_result);
if (uavcan_start_res < 0)
{
lowsyslog("Node initialization failure: %i, will try agin soon\n", uavcan_start_res);
}
else if (!init_result.isOk())
{
lowsyslog("Network conflict with %u, will try again soon\n", init_result.conflicting_node.get());
}
else
{
break;
}
::sleep(3);
}
/*
* Time synchronizer
*/
static uavcan::GlobalTimeSyncSlave time_sync_slave(node);
{
const int res = time_sync_slave.start();
if (res < 0)
{
die(res);
}
}
/*
* Main loop
*/
lowsyslog("UAVCAN node started\n");
node.setStatusOk();
while (true)
{
const int spin_res = node.spin(uavcan::MonotonicDuration::fromMSec(5000));
if (spin_res < 0)
{
lowsyslog("Spin failure: %i\n", spin_res);
}
lowsyslog("Time sync master: %u\n", unsigned(time_sync_slave.getMasterNodeID().get()));
}
return msg_t();
}
} uavcan_node_thread;
}
}
int main()
{
const int init_res = app::init();
if (init_res != 0)
{
app::die(init_res);
}
lowsyslog("Starting the UAVCAN thread\n");
app::uavcan_node_thread.start(LOWPRIO);
app::getNode().getLogger().setLevel(uavcan::protocol::debug::LogLevel::INFO);
while (true)
{
for (int i = 0; i < 200; i++)
{
app::ledSet(app::can.driver.hadActivity());
::usleep(25000);
}
const uavcan::UtcTime utc = uavcan_stm32::clock::getUtc();
lowsyslog("UTC %lu sec, %li corr, %lu jumps\n",
static_cast<unsigned long>(utc.toMSec() / 1000),
uavcan_stm32::clock::getUtcSpeedCorrectionPPM(),
uavcan_stm32::clock::getUtcAjdustmentJumpCount());
if (app::getNode().isStarted())
{
app::getNode().logInfo("app", "UTC %* sec, %* corr, %* jumps",
utc.toMSec() / 1000,
uavcan_stm32::clock::getUtcSpeedCorrectionPPM(),
uavcan_stm32::clock::getUtcAjdustmentJumpCount());
}
}
}
<commit_msg>STM32: Super aggressive memory allocation (testing)<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#include <unistd.h>
#include <crdr_chibios/sys/sys.h>
#include <uavcan_stm32/uavcan_stm32.hpp>
#include <uavcan/protocol/global_time_sync_slave.hpp>
namespace app
{
namespace
{
uavcan_stm32::CanInitHelper<128> can;
typedef uavcan::Node<8192> Node;
uavcan::LazyConstructor<Node> node_;
Node& getNode()
{
if (!node_.isConstructed())
{
node_.construct<uavcan::ICanDriver&, uavcan::ISystemClock&>(can.driver, uavcan_stm32::SystemClock::instance());
}
return *node_;
}
void ledSet(bool state)
{
palWritePad(GPIO_PORT_LED, GPIO_PIN_LED, state);
}
int init()
{
int res = 0;
halInit();
chibios_rt::System::init();
sdStart(&STDOUT_SD, NULL);
res = can.init(1000000);
if (res < 0)
{
goto leave;
}
leave:
return res;
}
__attribute__((noreturn))
void die(int status)
{
lowsyslog("Now I am dead x_x %i\n", status);
while (1)
{
ledSet(false);
sleep(1);
ledSet(true);
sleep(1);
}
}
class : public chibios_rt::BaseStaticThread<8192>
{
public:
msg_t main()
{
/*
* Setting up the node parameters
*/
Node& node = app::getNode();
node.setNodeID(64);
node.setName("org.uavcan.stm32_test_stm32f107");
/*
* Initializing the UAVCAN node - this may take a while
*/
while (true)
{
uavcan::NodeInitializationResult init_result;
const int uavcan_start_res = node.start(init_result);
if (uavcan_start_res < 0)
{
lowsyslog("Node initialization failure: %i, will try agin soon\n", uavcan_start_res);
}
else if (!init_result.isOk())
{
lowsyslog("Network conflict with %u, will try again soon\n", init_result.conflicting_node.get());
}
else
{
break;
}
::sleep(3);
}
/*
* Time synchronizer
*/
static uavcan::GlobalTimeSyncSlave time_sync_slave(node);
{
const int res = time_sync_slave.start();
if (res < 0)
{
die(res);
}
}
/*
* Main loop
*/
lowsyslog("UAVCAN node started\n");
node.setStatusOk();
while (true)
{
const int spin_res = node.spin(uavcan::MonotonicDuration::fromMSec(5000));
if (spin_res < 0)
{
lowsyslog("Spin failure: %i\n", spin_res);
}
lowsyslog("Time sync master: %u\n", unsigned(time_sync_slave.getMasterNodeID().get()));
}
return msg_t();
}
} uavcan_node_thread;
}
}
int main()
{
const int init_res = app::init();
if (init_res != 0)
{
app::die(init_res);
}
lowsyslog("Starting the UAVCAN thread\n");
app::uavcan_node_thread.start(LOWPRIO);
app::getNode().getLogger().setLevel(uavcan::protocol::debug::LogLevel::INFO);
while (true)
{
for (int i = 0; i < 200; i++)
{
app::ledSet(app::can.driver.hadActivity());
::usleep(25000);
}
const uavcan::UtcTime utc = uavcan_stm32::clock::getUtc();
lowsyslog("UTC %lu sec, %li corr, %lu jumps\n",
static_cast<unsigned long>(utc.toMSec() / 1000),
uavcan_stm32::clock::getUtcSpeedCorrectionPPM(),
uavcan_stm32::clock::getUtcAjdustmentJumpCount());
if (app::getNode().isStarted())
{
app::getNode().logInfo("app", "UTC %* sec, %* corr, %* jumps",
utc.toMSec() / 1000,
uavcan_stm32::clock::getUtcSpeedCorrectionPPM(),
uavcan_stm32::clock::getUtcAjdustmentJumpCount());
}
}
}
<|endoftext|>
|
<commit_before>//147. Insertion Sort List
/*
Sort a linked list using insertion sort.
Author: Xinyu Liu
*/
#include <iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution{
public:
ListNode* insertionSortList(ListNode* head){
ListNode* L = new ListNode(INT_MIN);
ListNode* i ;
while (head){
i = L;
while (i ->next && i ->next ->val < head ->val){
i = i->next;
}
ListNode* insert = new ListNode(head -> val);
insert ->next = i ->next;
i ->next = insert;
head = head ->next;
}
return L->next;
}
};
void main(){
ListNode n1(6), n2(5), n3(3);
n1.next = &n2;
n2.next = &n3;
Solution sol;
ListNode* n_sort = sol.insertionSortList(&n1);
}
<commit_msg>Update 147_Insertion_Sort_List.cpp<commit_after>//147. Insertion Sort List
/*
Sort a linked list using insertion sort.
Author: Xinyu Liu
*/
#include <iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution{
public:
ListNode* insertionSortList(ListNode* head){
ListNode L(INT_MIN);
L.next = head;
if(!head||!head->next)
{
return head;
}
head = head->next;
L.next->next = NULL;
ListNode* i;
while (head){
i = &L;
while (i ->next && i ->next ->val < head ->val){
i = i->next;
}
ListNode* insert = head;
head = head ->next;
insert->next = i ->next;
i ->next = insert;
}
return L.next;
}
};
<|endoftext|>
|
<commit_before>#include "../Include/CMenuNode.h"
using namespace cocos2d;
namespace LM
{
CMenuNode::CMenuNode(const std::string& a_rNormalImage,
const std::string& a_rSelectedImage,
CCallback a_fpCallback,
EAnchor a_eAnchor,
int a_iXPosition,
int a_iYPosition) :
CEntityNode(a_eAnchor, a_iXPosition, a_iYPosition),
m_sNormalImage(a_rNormalImage),
m_sSelectedImage(a_rSelectedImage),
m_fpClickedCallback(a_fpCallback)
{
}
void CMenuNode::Init()
{
auto m_pMenuItemImage = MenuItemImage::create(
m_sNormalImage,
m_sSelectedImage,
m_fpClickedCallback);
m_pMenuItemImage->setPosition(Vec2::ZERO);
m_pCocosEntity = Menu::create(m_pMenuItemImage, NULL);
//m_pCocosEntity->setPosition(Vec2(m_iXPosition, m_iYPosition));
PopulateParent();
}
} // namespace LM
<commit_msg>[FIX] added a fix to MenuNode not using the anchor point for placement in CMenuNode.cpp<commit_after>#include "../Include/CMenuNode.h"
using namespace cocos2d;
namespace LM
{
CMenuNode::CMenuNode(const std::string& a_rNormalImage,
const std::string& a_rSelectedImage,
CCallback a_fpCallback,
EAnchor a_eAnchor,
int a_iXPosition,
int a_iYPosition) :
CEntityNode(a_eAnchor, a_iXPosition, a_iYPosition),
m_sNormalImage(a_rNormalImage),
m_sSelectedImage(a_rSelectedImage),
m_fpClickedCallback(a_fpCallback)
{
}
void CMenuNode::Init()
{
auto m_pMenuItemImage = MenuItemImage::create(
m_sNormalImage,
m_sSelectedImage,
m_fpClickedCallback);
m_pMenuItemImage->setPosition(Vec2::ZERO);
m_pCocosEntity = Menu::create(m_pMenuItemImage, NULL);
//m_pCocosEntity->setPosition(Vec2(m_iXPosition, m_iYPosition));
PopulateParent();
// weird hack because cocos2d::Menu does not use its anchor point
m_pMenuItemImage->setPosition(m_pCocosEntity->getPosition());
m_pMenuItemImage->setAnchorPoint(m_pCocosEntity->getAnchorPoint());
m_pCocosEntity->setPosition(Vec2::ZERO);
}
} // namespace LM
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageNonMaximumSuppression.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageNonMaximumSuppression.h"
//----------------------------------------------------------------------------
// Description:
// Construct an instance of vtkImageNonMaximumSuppression fitler.
vtkImageNonMaximumSuppression::vtkImageNonMaximumSuppression()
{
this->SetAxes(VTK_IMAGE_X_AXIS,VTK_IMAGE_Y_AXIS);
this->SetOutputScalarType(VTK_FLOAT);
}
//----------------------------------------------------------------------------
// The trickiest part of the whole filter. Place Component Axis as number 4.
// The supper class and the execute method will not loop over it.
void vtkImageNonMaximumSuppression::SetAxes(int num, int *axes)
{
int idx, count;
int newAxes[VTK_IMAGE_DIMENSIONS];
if (num > 4)
{
vtkErrorMacro(<< "SetAxes: too many axes.");
num = 4;
}
// Save the actual number of axes for execute method.
this->NumberOfAxes = num;
// First set the axes to fill in all axes.
this->vtkImageDyadicFilter::SetAxes(num, axes);
// Copy the first four (non component) axes.
count = 0;
idx = 0;
while (count < 4)
{
if (this->Axes[idx] != VTK_IMAGE_COMPONENT_AXIS)
{
newAxes[count] = this->Axes[idx];
++count;
}
++idx;
if (idx >= VTK_IMAGE_DIMENSIONS)
{
vtkErrorMacro(<< "SetAxes: Could not find axes");
return;
}
}
// Last axis is component
newAxes[4] = VTK_IMAGE_COMPONENT_AXIS;
this->vtkImageDyadicFilter::SetAxes(5, newAxes);
}
//----------------------------------------------------------------------------
// Description:
// This method is passed a region that holds the image extent of this filters
// input, and changes the region to hold the image extent of this filters
// output.
void vtkImageNonMaximumSuppression::ComputeOutputImageInformation(
vtkImageRegion *inRegion1, vtkImageRegion *inRegion2,
vtkImageRegion *outRegion)
{
int extent[VTK_IMAGE_EXTENT_DIMENSIONS];
int idx;
inRegion1->GetImageExtent(VTK_IMAGE_DIMENSIONS, extent);
// To avoid compiler warnings
inRegion2 = inRegion2;
if ( ! this->HandleBoundaries)
{
// shrink output image extent.
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
extent[idx*2] += 1;
extent[idx*2+1] -= 1;
}
}
extent[8] = 0;
extent[9] = 0;
outRegion->SetImageExtent(VTK_IMAGE_DIMENSIONS, extent);
}
//----------------------------------------------------------------------------
// Description:
// This method computes the input extent necessary to generate the output.
void vtkImageNonMaximumSuppression::ComputeRequiredInputRegionExtent(
vtkImageRegion *outRegion,
vtkImageRegion *inRegion1, vtkImageRegion *inRegion2)
{
int extent[VTK_IMAGE_EXTENT_DIMENSIONS];
int *imageExtent;
int idx;
imageExtent = inRegion1->GetImageExtent();
outRegion->GetExtent(VTK_IMAGE_DIMENSIONS, extent);
extent[8] = 0;
extent[9] = 0;
// grow input image extent.
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
extent[idx*2] -= 1;
extent[idx*2+1] += 1;
if (this->HandleBoundaries)
{
// we must clip extent with image extent if we hanlde boundaries.
if (extent[idx*2] < imageExtent[idx*2])
{
extent[idx*2] = imageExtent[idx*2];
}
if (extent[idx*2 + 1] > imageExtent[idx*2 + 1])
{
extent[idx*2 + 1] = imageExtent[idx*2 + 1];
}
}
}
inRegion1->SetExtent(VTK_IMAGE_DIMENSIONS, extent);
extent[9] = this->NumberOfAxes - 1;
inRegion2->SetExtent(VTK_IMAGE_DIMENSIONS, extent);
}
//----------------------------------------------------------------------------
// Description:
// This method executes the filter for boundary pixels.
void vtkImageNonMaximumSuppression::Execute(vtkImageRegion *inRegion1,
vtkImageRegion *inRegion2,
vtkImageRegion *outRegion)
{
int idx;
int *imageExtent, *incs;
int outIdxs[VTK_IMAGE_DIMENSIONS], *idxs;
// For looping though output (and input) pixels.
int min0, max0, min1, max1, min2, max2, min3, max3;
int outIdx0, outIdx1, outIdx2, outIdx3;
int outInc0, outInc1, outInc2, outInc3;
float *outPtr0, *outPtr1, *outPtr2, *outPtr3;
int in1Inc0, in1Inc1, in1Inc2, in1Inc3;
float *in1Ptr0, *in1Ptr1, *in1Ptr2, *in1Ptr3;
int in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2Inc4;
float *in2Ptr0, *in2Ptr1, *in2Ptr2, *in2Ptr3, *in2Ptr4;
int neighborA, neighborB;
float d, ratio[VTK_IMAGE_DIMENSIONS], *thresh;
// This filter expects that output and input are type float.
if (outRegion->GetScalarType() != VTK_FLOAT ||
inRegion1->GetScalarType() != VTK_FLOAT ||
inRegion2->GetScalarType() != VTK_FLOAT)
{
vtkErrorMacro(<< "Execute: output ScalarType, "
<< vtkImageScalarTypeNameMacro(outRegion->GetScalarType())
<< ", must be float");
return;
}
// Gradient is computed with aspect ratio (world coordinates)
// Compute how to split up the quadrents into bins.
inRegion2->GetAspectRatio(ratio);
d = 0.0;
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
d += ratio[idx];
}
d = (float)(this->NumberOfAxes) / d;
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
ratio[idx] = 0.38268343 * ratio[idx] * d;
//thresh[idx] = 0.414214 * ratio[idx]
// / sqrt(d - 0.82842712 * ratio[idx] * ratio[idx]);
}
// Get information to march through data
inRegion1->GetIncrements(in1Inc0, in1Inc1, in1Inc2, in1Inc3);
inRegion2->GetIncrements(in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2Inc4);
outRegion->GetIncrements(outInc0, outInc1, outInc2, outInc3);
outRegion->GetExtent(min0, max0, min1, max1, min2, max2, min3, max3);
// We want the input pixel to correspond to output
in1Ptr3 = (float *)(inRegion1->GetScalarPointer(min0, min1, min2, min3));
in2Ptr3 = (float *)(inRegion2->GetScalarPointer(min0, min1, min2, min3));
outPtr3 = (float *)(outRegion->GetScalarPointer());
// loop through pixels of output
for (outIdx3 = min3; outIdx3 <= max3; ++outIdx3)
{
outIdxs[3] = outIdx3;
outPtr2 = outPtr3;
in1Ptr2 = in1Ptr3;
in2Ptr2 = in2Ptr3;
for (outIdx2 = min2; outIdx2 <= max2; ++outIdx2)
{
outIdxs[2] = outIdx2;
outPtr1 = outPtr2;
in1Ptr1 = in1Ptr2;
in2Ptr1 = in2Ptr2;
for (outIdx1 = min1; outIdx1 <= max1; ++outIdx1)
{
outIdxs[1] = outIdx1;
outPtr0 = outPtr1;
in1Ptr0 = in1Ptr1;
in2Ptr0 = in2Ptr1;
for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0)
{
outIdxs[0] = outIdx0;
// Use vector (in2) to determine which neighbors to use.
in2Ptr4 = in2Ptr0;
idxs = outIdxs;
thresh = ratio;
incs = inRegion1->GetIncrements();
imageExtent = inRegion1->GetImageExtent();
neighborA = neighborB = 0;
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
// Normalize the vector.
d = *in2Ptr4 / *in1Ptr0;
// Vector points positive along this axis?
// (can point along multiple axes)
if (d > *thresh)
{
if (*idxs < imageExtent[1]) // max
{
neighborA += *incs;
}
if (*idxs > *imageExtent) // min
{
neighborB -= *incs;
}
}
// Vector points negative along this axis?
else if (d < *thresh)
{
if (*idxs < imageExtent[1]) // max
{
neighborB += *incs;
}
if (*idxs > *imageExtent) //min
{
neighborA -= *incs;
}
}
// Increment pointers
in2Ptr4 += in2Inc4;
++idxs;
++incs;
++thresh;
imageExtent += 2;
}
// Set Output Magnitude
if (in1Ptr0[neighborA] > *in1Ptr0 || in1Ptr0[neighborB] > *in1Ptr0)
{
*outPtr0 = 0.0;
}
else
{
*outPtr0 = *in1Ptr0;
// also check for them being equal is neighbor with larger ptr
if ((neighborA > neighborB)&&(in1Ptr0[neighborA] == *in1Ptr0))
{
*outPtr0 = 0.0;
}
if ((neighborB > neighborA)&&(in1Ptr0[neighborB] == *in1Ptr0))
{
*outPtr0 = 0.0;
}
}
outPtr0 += outInc0;
in1Ptr0 += in1Inc0;
in2Ptr0 += in2Inc0;
}
outPtr1 += outInc1;
in1Ptr1 += in1Inc1;
in2Ptr1 += in2Inc1;
}
outPtr2 += outInc2;
in1Ptr2 += in1Inc2;
in2Ptr2 += in2Inc2;
}
outPtr3 += outInc3;
in1Ptr3 += in1Inc3;
in2Ptr3 += in2Inc3;
}
}
<commit_msg>forgot negative sign<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageNonMaximumSuppression.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageNonMaximumSuppression.h"
//----------------------------------------------------------------------------
// Description:
// Construct an instance of vtkImageNonMaximumSuppression fitler.
vtkImageNonMaximumSuppression::vtkImageNonMaximumSuppression()
{
this->SetAxes(VTK_IMAGE_X_AXIS,VTK_IMAGE_Y_AXIS);
this->SetOutputScalarType(VTK_FLOAT);
}
//----------------------------------------------------------------------------
// The trickiest part of the whole filter. Place Component Axis as number 4.
// The supper class and the execute method will not loop over it.
void vtkImageNonMaximumSuppression::SetAxes(int num, int *axes)
{
int idx, count;
int newAxes[VTK_IMAGE_DIMENSIONS];
if (num > 4)
{
vtkErrorMacro(<< "SetAxes: too many axes.");
num = 4;
}
// Save the actual number of axes for execute method.
this->NumberOfAxes = num;
// First set the axes to fill in all axes.
this->vtkImageDyadicFilter::SetAxes(num, axes);
// Copy the first four (non component) axes.
count = 0;
idx = 0;
while (count < 4)
{
if (this->Axes[idx] != VTK_IMAGE_COMPONENT_AXIS)
{
newAxes[count] = this->Axes[idx];
++count;
}
++idx;
if (idx >= VTK_IMAGE_DIMENSIONS)
{
vtkErrorMacro(<< "SetAxes: Could not find axes");
return;
}
}
// Last axis is component
newAxes[4] = VTK_IMAGE_COMPONENT_AXIS;
this->vtkImageDyadicFilter::SetAxes(5, newAxes);
}
//----------------------------------------------------------------------------
// Description:
// This method is passed a region that holds the image extent of this filters
// input, and changes the region to hold the image extent of this filters
// output.
void vtkImageNonMaximumSuppression::ComputeOutputImageInformation(
vtkImageRegion *inRegion1, vtkImageRegion *inRegion2,
vtkImageRegion *outRegion)
{
int extent[VTK_IMAGE_EXTENT_DIMENSIONS];
int idx;
inRegion1->GetImageExtent(VTK_IMAGE_DIMENSIONS, extent);
// To avoid compiler warnings
inRegion2 = inRegion2;
if ( ! this->HandleBoundaries)
{
// shrink output image extent.
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
extent[idx*2] += 1;
extent[idx*2+1] -= 1;
}
}
extent[8] = 0;
extent[9] = 0;
outRegion->SetImageExtent(VTK_IMAGE_DIMENSIONS, extent);
}
//----------------------------------------------------------------------------
// Description:
// This method computes the input extent necessary to generate the output.
void vtkImageNonMaximumSuppression::ComputeRequiredInputRegionExtent(
vtkImageRegion *outRegion,
vtkImageRegion *inRegion1, vtkImageRegion *inRegion2)
{
int extent[VTK_IMAGE_EXTENT_DIMENSIONS];
int *imageExtent;
int idx;
imageExtent = inRegion1->GetImageExtent();
outRegion->GetExtent(VTK_IMAGE_DIMENSIONS, extent);
extent[8] = 0;
extent[9] = 0;
// grow input image extent.
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
extent[idx*2] -= 1;
extent[idx*2+1] += 1;
if (this->HandleBoundaries)
{
// we must clip extent with image extent if we hanlde boundaries.
if (extent[idx*2] < imageExtent[idx*2])
{
extent[idx*2] = imageExtent[idx*2];
}
if (extent[idx*2 + 1] > imageExtent[idx*2 + 1])
{
extent[idx*2 + 1] = imageExtent[idx*2 + 1];
}
}
}
inRegion1->SetExtent(VTK_IMAGE_DIMENSIONS, extent);
extent[9] = this->NumberOfAxes - 1;
inRegion2->SetExtent(VTK_IMAGE_DIMENSIONS, extent);
}
//----------------------------------------------------------------------------
// Description:
// This method executes the filter for boundary pixels.
void vtkImageNonMaximumSuppression::Execute(vtkImageRegion *inRegion1,
vtkImageRegion *inRegion2,
vtkImageRegion *outRegion)
{
int idx;
int *imageExtent, *incs;
int outIdxs[VTK_IMAGE_DIMENSIONS], *idxs;
// For looping though output (and input) pixels.
int min0, max0, min1, max1, min2, max2, min3, max3;
int outIdx0, outIdx1, outIdx2, outIdx3;
int outInc0, outInc1, outInc2, outInc3;
float *outPtr0, *outPtr1, *outPtr2, *outPtr3;
int in1Inc0, in1Inc1, in1Inc2, in1Inc3;
float *in1Ptr0, *in1Ptr1, *in1Ptr2, *in1Ptr3;
int in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2Inc4;
float *in2Ptr0, *in2Ptr1, *in2Ptr2, *in2Ptr3, *in2Ptr4;
int neighborA, neighborB;
float d, ratio[VTK_IMAGE_DIMENSIONS], *thresh;
// This filter expects that output and input are type float.
if (outRegion->GetScalarType() != VTK_FLOAT ||
inRegion1->GetScalarType() != VTK_FLOAT ||
inRegion2->GetScalarType() != VTK_FLOAT)
{
vtkErrorMacro(<< "Execute: output ScalarType, "
<< vtkImageScalarTypeNameMacro(outRegion->GetScalarType())
<< ", must be float");
return;
}
// Gradient is computed with aspect ratio (world coordinates)
// Compute how to split up the quadrents into bins.
inRegion2->GetAspectRatio(ratio);
d = 0.0;
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
d += ratio[idx];
}
d = (float)(this->NumberOfAxes) / d;
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
ratio[idx] = 0.38268343 * ratio[idx] * d;
//thresh[idx] = 0.414214 * ratio[idx]
// / sqrt(d - 0.82842712 * ratio[idx] * ratio[idx]);
}
// Get information to march through data
inRegion1->GetIncrements(in1Inc0, in1Inc1, in1Inc2, in1Inc3);
inRegion2->GetIncrements(in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2Inc4);
outRegion->GetIncrements(outInc0, outInc1, outInc2, outInc3);
outRegion->GetExtent(min0, max0, min1, max1, min2, max2, min3, max3);
// We want the input pixel to correspond to output
in1Ptr3 = (float *)(inRegion1->GetScalarPointer(min0, min1, min2, min3));
in2Ptr3 = (float *)(inRegion2->GetScalarPointer(min0, min1, min2, min3));
outPtr3 = (float *)(outRegion->GetScalarPointer());
// loop through pixels of output
for (outIdx3 = min3; outIdx3 <= max3; ++outIdx3)
{
outIdxs[3] = outIdx3;
outPtr2 = outPtr3;
in1Ptr2 = in1Ptr3;
in2Ptr2 = in2Ptr3;
for (outIdx2 = min2; outIdx2 <= max2; ++outIdx2)
{
outIdxs[2] = outIdx2;
outPtr1 = outPtr2;
in1Ptr1 = in1Ptr2;
in2Ptr1 = in2Ptr2;
for (outIdx1 = min1; outIdx1 <= max1; ++outIdx1)
{
outIdxs[1] = outIdx1;
outPtr0 = outPtr1;
in1Ptr0 = in1Ptr1;
in2Ptr0 = in2Ptr1;
for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0)
{
outIdxs[0] = outIdx0;
// Use vector (in2) to determine which neighbors to use.
in2Ptr4 = in2Ptr0;
idxs = outIdxs;
thresh = ratio;
incs = inRegion1->GetIncrements();
imageExtent = inRegion1->GetImageExtent();
neighborA = neighborB = 0;
for (idx = 0; idx < this->NumberOfAxes; ++idx)
{
// Normalize the vector.
d = *in2Ptr4 / *in1Ptr0;
// Vector points positive along this axis?
// (can point along multiple axes)
if (d > *thresh)
{
if (*idxs < imageExtent[1]) // max
{
neighborA += *incs;
}
if (*idxs > *imageExtent) // min
{
neighborB -= *incs;
}
}
// Vector points negative along this axis?
else if (d < -(*thresh))
{
if (*idxs < imageExtent[1]) // max
{
neighborB += *incs;
}
if (*idxs > *imageExtent) //min
{
neighborA -= *incs;
}
}
// Increment pointers
in2Ptr4 += in2Inc4;
++idxs;
++incs;
++thresh;
imageExtent += 2;
}
// Set Output Magnitude
if (in1Ptr0[neighborA] > *in1Ptr0 || in1Ptr0[neighborB] > *in1Ptr0)
{
*outPtr0 = 0.0;
}
else
{
*outPtr0 = *in1Ptr0;
// also check for them being equal is neighbor with larger ptr
if ((neighborA > neighborB)&&(in1Ptr0[neighborA] == *in1Ptr0))
{
*outPtr0 = 0.0;
}
if ((neighborB > neighborA)&&(in1Ptr0[neighborB] == *in1Ptr0))
{
*outPtr0 = 0.0;
}
}
outPtr0 += outInc0;
in1Ptr0 += in1Inc0;
in2Ptr0 += in2Inc0;
}
outPtr1 += outInc1;
in1Ptr1 += in1Inc1;
in2Ptr1 += in2Inc1;
}
outPtr2 += outInc2;
in1Ptr2 += in1Inc2;
in2Ptr2 += in2Inc2;
}
outPtr3 += outInc3;
in1Ptr3 += in1Inc3;
in2Ptr3 += in2Inc3;
}
}
<|endoftext|>
|
<commit_before>/*
* uex_mem_services_sv_impl.c
*
* Created on: Jan 7, 2018
* Author: ballance
*/
#include "uex_mem_services.h"
#include "uex_dpi.h"
#include <stdio.h>
#include <stdexcept>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
// Memory Services
int _uex_iowrite8(uint8_t v, uint64_t a);
int _uex_ioread8(uint8_t *v, uint64_t a);
int _uex_iowrite16(uint16_t v, uint64_t a);
int _uex_ioread16(uint16_t *v, uint64_t a);
int _uex_iowrite32(uint32_t v, uint64_t a);
int _uex_ioread32(uint32_t *v, uint64_t a);
int _uex_iowrite64(uint64_t v, uint64_t a);
int _uex_ioread64(uint64_t *v, uint64_t a);
#ifdef __cplusplus
}
#endif
void *uex_malloc(uint32_t sz) {
return malloc(sz);
}
void uex_free(void *p) {
free(p);
}
void *uex_ioremap(void *p, uint32_t sz, uint32_t flags) {
return p;
}
void uex_iounmap(void *p) {
// NOP
}
void uex_iowrite8(uint8_t v, void *p) {
uint64_t a = reinterpret_cast<uint64_t>(p);
if (_uex_iowrite8(v, a)) {
throw std::runtime_error("uex_iowrite8");
}
}
uint8_t uex_ioread8(void *p) {
uint8_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread8(&v, a)) {
throw std::runtime_error("uex_ioread8");
}
return v;
}
void uex_iowrite16(uint16_t v, void *p) {
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_iowrite16(v, a)) {
throw std::runtime_error("uex_iowrite16");
}
}
uint16_t uex_ioread16(void *p) {
uint16_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread16(&v, a)) {
throw std::runtime_error("uex_ioread16");
}
return v;
}
void uex_iowrite32(uint32_t v, void *p) {
svSetScope(uex_svScope());
uint64_t a = reinterpret_cast<uint64_t>(p);
if (_uex_iowrite32(v, a)) {
throw std::runtime_error("uex_iowrite32");
}
}
uint32_t uex_ioread32(void *p) {
uint32_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread32(&v, a)) {
throw std::runtime_error("uex_ioread32");
}
return v;
}
void uex_iowrite64(uint64_t v, void *p) {
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_iowrite64(v, a)) {
throw std::runtime_error("uex_iowrite64");
}
}
uint64_t uex_ioread64(void *p) {
uint64_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread64(&v, a)) {
throw std::runtime_error("uex_ioread64");
}
return v;
}
<commit_msg>Fix for memory access<commit_after>/*
* uex_mem_services_sv_impl.c
*
* Created on: Jan 7, 2018
* Author: ballance
*/
#include "uex_mem_services.h"
#include "uex_dpi.h"
#include <stdio.h>
#include <stdexcept>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
// Memory Services
int _uex_iowrite8(uint8_t v, uint64_t a);
int _uex_ioread8(uint8_t *v, uint64_t a);
int _uex_iowrite16(uint16_t v, uint64_t a);
int _uex_ioread16(uint16_t *v, uint64_t a);
int _uex_iowrite32(uint32_t v, uint64_t a);
int _uex_ioread32(uint32_t *v, uint64_t a);
int _uex_iowrite64(uint64_t v, uint64_t a);
int _uex_ioread64(uint64_t *v, uint64_t a);
#ifdef __cplusplus
}
#endif
void *uex_malloc(uint32_t sz) {
return malloc(sz);
}
void uex_free(void *p) {
free(p);
}
void *uex_ioremap(void *p, uint32_t sz, uint32_t flags) {
return p;
}
void uex_iounmap(void *p) {
// NOP
}
void uex_iowrite8(uint8_t v, void *p) {
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_iowrite8(v, a)) {
throw std::runtime_error("uex_iowrite8");
}
}
uint8_t uex_ioread8(void *p) {
uint8_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread8(&v, a)) {
throw std::runtime_error("uex_ioread8");
}
return v;
}
void uex_iowrite16(uint16_t v, void *p) {
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_iowrite16(v, a)) {
throw std::runtime_error("uex_iowrite16");
}
}
uint16_t uex_ioread16(void *p) {
uint16_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread16(&v, a)) {
throw std::runtime_error("uex_ioread16");
}
return v;
}
void uex_iowrite32(uint32_t v, void *p) {
svSetScope(uex_svScope());
uint64_t a = reinterpret_cast<uint64_t>(p);
if (_uex_iowrite32(v, a)) {
throw std::runtime_error("uex_iowrite32");
}
}
uint32_t uex_ioread32(void *p) {
uint32_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread32(&v, a)) {
throw std::runtime_error("uex_ioread32");
}
return v;
}
void uex_iowrite64(uint64_t v, void *p) {
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_iowrite64(v, a)) {
throw std::runtime_error("uex_iowrite64");
}
}
uint64_t uex_ioread64(void *p) {
uint64_t v;
uint64_t a = reinterpret_cast<uint64_t>(p);
svSetScope(uex_svScope());
if (_uex_ioread64(&v, a)) {
throw std::runtime_error("uex_ioread64");
}
return v;
}
<|endoftext|>
|
<commit_before>#ifndef ENGINE_COMMON_UTILITY_DEBUG_REMOTERY_HPP
#define ENGINE_COMMON_UTILITY_DEBUG_REMOTERY_HPP
#pragma once
#include <remotery.h>
#include "utility/text/ustring.hpp"
#include <string>
#include <set>
namespace engine
{
class remotery_t
{
public:
remotery_t() : rmt(nullptr)
{
rmtSettings* settings = rmt_Settings();
settings->limit_connections_to_localhost = true;
rmtError ret_code = rmt_CreateGlobalInstance(&rmt);
}
~remotery_t()
{
rmt_DestroyGlobalInstance(rmt);
}
void prof_begin_section(const char * name)
{
rmt_BeginCPUSampleDynamic(name, RMTSF_None);
}
void prof_end_section()
{
rmt_EndCPUSample();
}
void name_current_thread(const ustring_t & name)
{
rmt_SetCurrentThreadName(name.get_cstring());
}
private:
Remotery* rmt;
};
}
#endif<commit_msg>Fixed a crash in remotery destructor<commit_after>#ifndef ENGINE_COMMON_UTILITY_DEBUG_REMOTERY_HPP
#define ENGINE_COMMON_UTILITY_DEBUG_REMOTERY_HPP
#pragma once
#include <remotery.h>
#include "utility/text/ustring.hpp"
#include <string>
#include <set>
namespace engine
{
class remotery_t
{
public:
remotery_t() : rmt(nullptr)
{
rmtSettings* settings = rmt_Settings();
settings->limit_connections_to_localhost = true;
rmtError ret_code = rmt_CreateGlobalInstance(&rmt);
}
~remotery_t()
{
if(rmt)
{
rmt_DestroyGlobalInstance(rmt);
rmt = nullptr;
}
}
void prof_begin_section(const char * name)
{
rmt_BeginCPUSampleDynamic(name, RMTSF_None);
}
void prof_end_section()
{
rmt_EndCPUSample();
}
void name_current_thread(const ustring_t & name)
{
rmt_SetCurrentThreadName(name.get_cstring());
}
private:
Remotery* rmt;
};
}
#endif<|endoftext|>
|
<commit_before>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "segbot_gui/QuestionDialog.h"
#include <string>
#include <stdlib.h>
#include <vector>
std::string status_shirt, status_object, status_board;
std::string shirt_color, object_name;
std::string file_shirt, file_object, file_board;
void callback_shirt(const std_msgs::String::ConstPtr& msg)
{
if (msg->data.find("running") != std::string::npos)
status_shirt = "ongoing";
else {
status_shirt = "finished";
int pos = msg->data.find(":");
file_shirt = msg->data.substr(pos + 1);
}
}
void callback_object(const std_msgs::String::ConstPtr& msg)
{
if (msg->data.find("running") != std::string::npos)
status_object = "ongoing";
else {
status_object = "finished";
int pos = msg->data.find(":");
file_object = msg->data.substr(pos + 1);
}
}
void callback_board(const std_msgs::String::ConstPtr& msg)
{
if (msg->data.find("running") != std::string::npos)
status_board = "ongoing";
else {
status_board = "finished";
int pos = msg->data.find(":");
file_board = msg->data.substr(pos + 1);
}
}
int main(int argc, char **argv){
ros::init(argc, argv, "scav_hunt");
ros::NodeHandle nh;
ros::ServiceClient client =
nh.serviceClient<segbot_gui::QuestionDialog>("question_dialog");
segbot_gui::QuestionDialog srv;
ros::Subscriber sub1 = nh.subscribe("segbot_blue_shirt_status", 1000,
callback_shirt);
ros::Subscriber sub2 = nh.subscribe("segbot_object_detection_status", 1000,
callback_object);
ros::Subscriber sub3 = nh.subscribe("segbot_whiteboard_status", 1000,
callback_board);
ros::Rate rate(10);
std::string message_finished, message_todo, message_ending;
std::vector<std::string> buttons;
message_finished = "Finished tasks:";
message_todo = "\nTodo tasks:";
message_ending = "\nClick buttons to see how I performed in the tasks\n";
while (ros::ok())
{
rate.sleep();
ros::spinOnce();
if (status_shirt.find("ongoing") != std::string::npos)
message_todo += "\n\t* find a person wearing '" +
shirt_color + " shirt";
else
{
message_finished += "\n\t* find a person wearing '" +
shirt_color + " shirt";
buttons.push_back("color shirt");
}
if (status_object.find("ongoing") != std::string::npos)
message_todo += "\n\t* take a picture of object '" + object_name;
else
{
message_finished += "\n\t* take a picture of object '" + object_name;
buttons.push_back("object detection");
}
if (status_board.find("ongoing") != std::string::npos)
message_todo += "\n\t* find a person standing near a whiteboard";
else
{
message_finished += "\n\t* find a person standing near a whiteboard";
buttons.push_back("whiteboard");
}
if (message_finished.length() + message_todo.length() < 30) {
srv.request.type = 0;
srv.request.message = message_finished + "\n" + message_todo +
"\n" + message_ending;
}
else
{
srv.request.type = 1;
srv.request.message = message_finished + "\n" + message_todo;
srv.request.options = buttons;
}
if (!client.call(srv))
{
ROS_ERROR("Failed to call service question_dialog");
return 1;
}
if (srv.response.index < 0)
continue;
else if (buttons[srv.response.index].find("shirt") != std::string::npos)
system("eog " + file_shirt);
else if (buttons[srv.response.index].find("object") != std::string::npos)
system("eog " + file_object);
else if (buttons[srv.response.index].find("board") != std::string::npos)
system("eog " + file_board);
}
}
<commit_msg>minor<commit_after>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "segbot_gui/QuestionDialog.h"
#include <string>
#include <stdlib.h>
#include <vector>
std::string status_shirt, status_object, status_board;
std::string shirt_color, object_name;
std::string file_shirt, file_object, file_board;
void callback_shirt(const std_msgs::String::ConstPtr& msg)
{
if (msg->data.find("running") != std::string::npos)
status_shirt = "ongoing";
else {
status_shirt = "finished";
int pos = msg->data.find(":");
file_shirt = msg->data.substr(pos + 1);
}
}
void callback_object(const std_msgs::String::ConstPtr& msg)
{
if (msg->data.find("running") != std::string::npos)
status_object = "ongoing";
else {
status_object = "finished";
int pos = msg->data.find(":");
file_object = msg->data.substr(pos + 1);
}
}
void callback_board(const std_msgs::String::ConstPtr& msg)
{
if (msg->data.find("running") != std::string::npos)
status_board = "ongoing";
else {
status_board = "finished";
int pos = msg->data.find(":");
file_board = msg->data.substr(pos + 1);
}
}
int main(int argc, char **argv){
ros::init(argc, argv, "scav_hunt");
ros::NodeHandle nh;
ros::ServiceClient client =
nh.serviceClient<segbot_gui::QuestionDialog>("question_dialog");
segbot_gui::QuestionDialog srv;
ros::Subscriber sub1 = nh.subscribe("segbot_blue_shirt_status", 1000,
callback_shirt);
ros::Subscriber sub2 = nh.subscribe("segbot_object_detection_status", 1000,
callback_object);
ros::Subscriber sub3 = nh.subscribe("segbot_whiteboard_status", 1000,
callback_board);
ros::Rate rate(10);
std::string message_finished, message_todo, message_ending;
std::vector<std::string> buttons;
message_finished = "Finished tasks:";
message_todo = "\nTodo tasks:";
message_ending = "\nClick buttons to see how I performed in the tasks\n";
while (ros::ok())
{
rate.sleep();
ros::spinOnce();
if (status_shirt.find("ongoing") != std::string::npos)
message_todo += "\n\t* find a person wearing '" +
shirt_color + " shirt";
else
{
message_finished += "\n\t* find a person wearing '" +
shirt_color + " shirt";
buttons.push_back("color shirt");
}
if (status_object.find("ongoing") != std::string::npos)
message_todo += "\n\t* take a picture of object '" + object_name;
else
{
message_finished += "\n\t* take a picture of object '" + object_name;
buttons.push_back("object detection");
}
if (status_board.find("ongoing") != std::string::npos)
message_todo += "\n\t* find a person standing near a whiteboard";
else
{
message_finished += "\n\t* find a person standing near a whiteboard";
buttons.push_back("whiteboard");
}
if (message_finished.length() + message_todo.length() < 30) {
srv.request.type = 0;
srv.request.message = message_finished + "\n" + message_todo +
"\n" + message_ending;
}
else
{
srv.request.type = 1;
srv.request.message = message_finished + "\n" + message_todo;
srv.request.options = buttons;
}
if (!client.call(srv))
{
ROS_ERROR("Failed to call service question_dialog");
return 1;
}
std::string eog = "eog ";
if (srv.response.index < 0)
continue;
else if (buttons[srv.response.index].find("shirt") != std::string::npos)
system((eog + file_shirt).c_str());
else if (buttons[srv.response.index].find("object") != std::string::npos)
system((eog + file_object).c_str());
else if (buttons[srv.response.index].find("board") != std::string::npos)
system((eog + file_board).c_str());
}
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "Tester.h"
#include <fenv.h>
#include <stdio.h>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <google/protobuf/text_format.h>
#include "paddle/utils/GlobalConstants.h"
#include "paddle/utils/PythonUtil.h"
#include "paddle/utils/Stat.h"
#include "paddle/utils/Util.h"
#include "TesterConfig.h"
#include "paddle/gserver/gradientmachines/GradientMachineMode.h"
#include "paddle/gserver/gradientmachines/NeuralNetwork.h"
#include "paddle/gserver/layers/ValidationLayer.h"
namespace paddle {
Tester::Tester(const std::shared_ptr<TrainerConfigHelper>& config,
std::unique_ptr<TesterConfig>&& intconfig,
const GradientMachinePtr& gradientMachine,
const std::shared_ptr<ParameterUpdater>& parameterUpdater,
std::shared_ptr<DataProvider> testDataProvider)
: config_(config),
intconfig_(std::move(intconfig)),
gradientMachine_(gradientMachine),
parameterUpdater_(parameterUpdater),
testDataProvider_(testDataProvider) {
if (config_->getOptConfig().use_sparse_remote_updater()) {
LOG(FATAL) << "It's prohibited to set sparse_remote_update "
<< "in some layers if testing will be under going "
<< "in the middle of training. You can do testing "
<< "within separate process.";
}
testEvaluator_.reset(gradientMachine_->makeEvaluator());
if (intconfig_->distributeTest) {
testParameterClient_.reset(new ParameterClient2(true));
}
if (testParameterClient_) {
testParameterClient_->init(gradientMachine_->getParameters());
}
std::unique_ptr<ParameterUtilConfig> paramConfig(
new ParameterUtilConfig(intconfig_->saveOnlyOne,
intconfig_->savingPeriod,
intconfig_->loadsaveParametersInPserver,
intconfig_->config));
paramUtil_.reset(new ParameterUtil(
config_, std::move(paramConfig), gradientMachine_, parameterUpdater_));
}
void Tester::startTestPeriod() {
if (testDataProvider_) {
testDataProvider_->reset();
}
testEvaluator_->start();
testContext_.cost = 0;
testContext_.numSamples = 0;
parameterUpdater_->apply();
if (intconfig_->prevBatchState) {
gradientMachine_->getState(*intconfig_->trainState);
gradientMachine_->setState(*intconfig_->testState);
}
}
void Tester::testOneDataBatch(const DataBatch& dataBatch,
std::vector<Argument>* outArgs) {
testContext_.cost +=
forwardOneBatch(dataBatch, testEvaluator_.get(), outArgs);
testContext_.numSamples += dataBatch.getSize();
}
void Tester::testOnePeriod() {
DataBatch dataBatch;
int64_t batchSize = config_->getOptConfig().batch_size();
std::vector<Argument> outArgs;
startTestPeriod();
while (testDataProvider_->getNextBatch(batchSize, &dataBatch) != 0) {
testOneDataBatch(dataBatch, &outArgs);
}
finishTestPeriod();
}
void Tester::finishTestPeriod() {
if (intconfig_->prevBatchState) {
gradientMachine_->resetState();
}
testEvaluator_->finish();
CHECK_GT(testContext_.numSamples, 0)
<< "There is no samples in your test batch. Possibly "
"wrong implementation of DataProvidor.reset()";
LOG(INFO) << " Test samples=" << testContext_.numSamples
<< " cost=" << testContext_.cost / testContext_.numSamples
<< " Eval: " << *testEvaluator_;
parameterUpdater_->restore();
if (intconfig_->prevBatchState) {
gradientMachine_->getState(*intconfig_->testState);
gradientMachine_->setState(*intconfig_->trainState);
}
}
int64_t Tester::testOneBatchById(int64_t batchId) {
DataBatch dataBatch;
int32_t batchSize = config_->getOptConfig().batch_size();
testDataProvider_->getNextBatch(batchSize, &dataBatch);
int64_t actualBatchSize = dataBatch.getSize();
if (actualBatchSize == 0) {
return 0;
}
std::vector<Argument> outArgs;
stats_ += std::pair<int64_t, real>{
actualBatchSize,
forwardOneBatch(dataBatch, testEvaluator_.get(), &outArgs)};
if (((batchId + 1) % intconfig_->logPeriod) == 0) {
LOG(INFO) << " Batch=" << batchId + 1 << " " << stats_.getStats(false);
}
return actualBatchSize;
}
real Tester::forwardOneBatch(const DataBatch& dataBatch,
Evaluator* evaluator,
std::vector<Argument>* pOutArgs) {
auto& outArgs = *pOutArgs;
const std::vector<Argument>& inArgs = dataBatch.getStreams();
if (intconfig_->loadsaveParametersInPserver) {
REGISTER_TIMER("prefetch");
gradientMachine_->prefetch(inArgs);
parameterUpdater_->getParametersRemote(false /*full parameter*/,
true /*after apply*/);
}
gradientMachine_->forward(inArgs, &outArgs, PASS_TEST);
// write features if set this flag and outArgs is not empty
std::string featFile = intconfig_->featFile;
if (!featFile.empty() && outArgs.empty()) {
size_t numOutputs = outArgs.size();
std::vector<MatrixPtr> featMatrices;
featMatrices.resize(numOutputs);
for (size_t i = 0; i < numOutputs; ++i) {
featMatrices[i] = Matrix::create(outArgs[i].value->getHeight(),
outArgs[i].value->getWidth(),
false,
false); // CPU data buffer
featMatrices[i]->copyFrom(*(outArgs[i].value), HPPL_STREAM_DEFAULT);
}
hl_stream_synchronize(HPPL_STREAM_DEFAULT);
FILE* fp = fopen(featFile.c_str(), "ab+");
PCHECK(!ferror(fp)) << "Fail to open " << featFile;
size_t sampleNum = featMatrices[0]->getHeight();
for (size_t i = 0; i < sampleNum; ++i) {
for (size_t j = 0; j < numOutputs; ++j) {
size_t dim = featMatrices[j]->getWidth();
fwrite(featMatrices[j]->getData() + i * dim, sizeof(real), dim, fp);
}
}
fclose(fp);
}
if (evaluator) {
gradientMachine_->eval(evaluator);
}
// Save the output layers if predict_output_dir is not empty
std::string predictOutputDir = intconfig_->predictOutputDir;
if (!predictOutputDir.empty() && !outArgs.empty()) {
CHECK(intconfig_->testing) << "Only valid in test mode";
if (!os_.is_open()) {
// TODO(yuyang18): Refactor these lines.
constexpr int kBufLen = 100;
char buf[kBufLen];
snprintf(buf, kBufLen, "rank-%05d", intconfig_->trainerId);
mkDir(predictOutputDir.c_str());
std::string filename = path::join(predictOutputDir, buf);
os_.open(filename, std::ofstream::trunc);
CHECK(os_.is_open()) << "Failed to open file " << filename;
}
printOutput(outArgs, os_);
return 0.0; // In this case, there is no meaning to calculate cost
}
return Argument::sumCosts(outArgs);
}
void Tester::testOnePassBatch(int passId) {
stats_.reset();
const std::vector<Argument> inArgs;
gradientMachine_->forward(inArgs, nullptr, PASS_TEST);
int64_t num;
real cost;
gradientMachine_->getStats(cost, num);
stats_ += std::pair<int64_t, real>{num, cost};
gradientMachine_->onPassEnd();
LOG(INFO) << " Pass=" << passId << " " << stats_.getStats(false);
}
void Tester::testOnePass(int passId) {
stats_.reset();
int64_t batchId = 0;
int num = 0;
if (intconfig_->prevBatchState) {
gradientMachine_->resetState();
}
testEvaluator_->start();
do {
num = testOneBatchById(batchId);
++batchId;
} while (num > 0);
gradientMachine_->onPassEnd();
testEvaluator_->finish();
LOG(INFO) << " Pass=" << passId << " " << stats_.getStats(false)
<< " Eval: " << *testEvaluator_;
if (intconfig_->distributeTest) {
testEvaluator_->distributeEval(testParameterClient_.get());
if (0 == intconfig_->trainerId) {
LOG(INFO) << "distribute eval: " << *testEvaluator_;
}
}
}
void Tester::test() {
CHECK(testDataProvider_) << "TestData is not specified";
testDataProvider_->setSkipShuffle();
testDataProvider_->reset();
gradientMachine_->start(*config_, testDataProvider_);
// For evaluation
std::vector<std::string> modelList;
std::string modelListFromConfig = intconfig_->modelList;
std::string initModelPath = intconfig_->initModelPath;
if (!modelListFromConfig.empty()) {
loadFileList(modelListFromConfig, modelList);
intconfig_->testPass = 0;
intconfig_->numPasses = modelList.size();
intconfig_->savingPeriod = 1;
CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
} else if (!initModelPath.empty()) {
modelList.push_back(initModelPath);
intconfig_->testPass = 0;
intconfig_->numPasses = 1;
intconfig_->savingPeriod = 1;
CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
}
for (int i = intconfig_->testPass; i < intconfig_->numPasses; ++i) {
int passId = i;
if (passId % intconfig_->savingPeriod == 0) {
if (intconfig_->testWait) {
while (paramUtil_->loadParameters(
passId, true /*local*/, true /*remote*/) == false) {
LOG(INFO) << "Waiting for parameters of pass " << passId;
sleep(60); // sleep 60s
}
} else {
if (modelList.size() == 0) {
CHECK_EQ(paramUtil_->loadParameters(
passId, true /*local*/, true /*remote*/),
true);
} else {
paramUtil_->loadParametersWithPath(
modelList[i], true /*local*/, true /*remote*/);
}
}
if (IGradientMachineMode::trainWholeDataInOneBatch(intconfig_->mode)) {
testOnePassBatch(passId);
} else {
testOnePass(passId);
}
if (passId + intconfig_->savingPeriod < intconfig_->numPasses) {
// if there is at least 1 more pass to test, then call reset,
// otherwise not.
testDataProvider_->reset();
}
}
}
gradientMachine_->finish();
}
void Tester::printOutput(const std::vector<Argument>& outArgs,
std::ostream& os) {
size_t numOutputs = outArgs.size();
size_t numIns = outArgs[0].getBatchSize();
if (cpuMat_.size() != numOutputs || cpuVec_.size() != numOutputs) {
cpuMat_.resize(numOutputs, nullptr);
cpuVec_.resize(numOutputs, nullptr);
}
for (size_t i = 0; i < numOutputs; ++i) {
if (outArgs[i].value != nullptr) {
if (outArgs[i].value->useGpu()) {
if (dynamic_cast<GpuMatrix*>(outArgs[i].value.get())) {
size_t dim = outArgs[i].value->getWidth();
Matrix::resizeOrCreate(cpuMat_[i], numIns, dim, false, false);
cpuMat_[i]->copyFrom(*outArgs[i].value);
} else if (dynamic_cast<GpuSparseMatrix*>(outArgs[i].value.get())) {
auto sparseMat =
dynamic_cast<GpuSparseMatrix*>(outArgs[i].value.get());
cpuMat_[i] = Matrix::createSparseMatrix(sparseMat->getHeight(),
sparseMat->getWidth(),
sparseMat->getElementCnt(),
sparseMat->getValueType(),
sparseMat->format_,
false, /* trans */
false); /* useGpu */
hl_stream_t stream = HPPL_STREAM_DEFAULT;
cpuMat_[i]->copyFrom(*sparseMat, stream);
} else {
LOG(WARNING) << "Not supported gpu matrix type";
}
}
} else if (outArgs[i].ids != nullptr) {
if (outArgs[i].ids->useGpu()) {
IVector::resizeOrCreate(cpuVec_[i], outArgs[i].ids->getSize(), false);
cpuVec_[i]->copyFrom(*outArgs[i].ids);
}
} else if (outArgs[i].strs != nullptr) {
continue;
} else {
LOG(WARNING) << "outArgs[" << i << "] has no data to print";
}
}
for (size_t i = 0; i < numIns; ++i) {
for (size_t j = 0; j < numOutputs; ++j) {
if (outArgs[j].value != nullptr) {
if (outArgs[j].value->useGpu()) {
cpuMat_[j]->printOneRow(os, i);
} else {
outArgs[j].value->printOneRow(os, i);
}
} else if (outArgs[j].ids != nullptr) {
if (outArgs[j].ids->useGpu()) {
cpuVec_[j]->printOneElement(os, i);
} else {
outArgs[j].ids->printOneElement(os, i);
}
} else if (outArgs[j].strs != nullptr) {
os << (*outArgs[j].strs)[i] << ";";
}
}
os << std::endl;
}
}
} // namespace paddle
<commit_msg>follow comments: more readable LOG<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "Tester.h"
#include <fenv.h>
#include <stdio.h>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <google/protobuf/text_format.h>
#include "paddle/utils/GlobalConstants.h"
#include "paddle/utils/PythonUtil.h"
#include "paddle/utils/Stat.h"
#include "paddle/utils/Util.h"
#include "TesterConfig.h"
#include "paddle/gserver/gradientmachines/GradientMachineMode.h"
#include "paddle/gserver/gradientmachines/NeuralNetwork.h"
#include "paddle/gserver/layers/ValidationLayer.h"
namespace paddle {
Tester::Tester(const std::shared_ptr<TrainerConfigHelper>& config,
std::unique_ptr<TesterConfig>&& intconfig,
const GradientMachinePtr& gradientMachine,
const std::shared_ptr<ParameterUpdater>& parameterUpdater,
std::shared_ptr<DataProvider> testDataProvider)
: config_(config),
intconfig_(std::move(intconfig)),
gradientMachine_(gradientMachine),
parameterUpdater_(parameterUpdater),
testDataProvider_(testDataProvider) {
if (config_->getOptConfig().use_sparse_remote_updater()) {
LOG(FATAL) << "It's prohibited to set sparse_remote_update "
<< "when doing train and test jobs in the same "
<< "process. You could run paddle --job=test in "
<< "a separate process.";
}
testEvaluator_.reset(gradientMachine_->makeEvaluator());
if (intconfig_->distributeTest) {
testParameterClient_.reset(new ParameterClient2(true));
}
if (testParameterClient_) {
testParameterClient_->init(gradientMachine_->getParameters());
}
std::unique_ptr<ParameterUtilConfig> paramConfig(
new ParameterUtilConfig(intconfig_->saveOnlyOne,
intconfig_->savingPeriod,
intconfig_->loadsaveParametersInPserver,
intconfig_->config));
paramUtil_.reset(new ParameterUtil(
config_, std::move(paramConfig), gradientMachine_, parameterUpdater_));
}
void Tester::startTestPeriod() {
if (testDataProvider_) {
testDataProvider_->reset();
}
testEvaluator_->start();
testContext_.cost = 0;
testContext_.numSamples = 0;
parameterUpdater_->apply();
if (intconfig_->prevBatchState) {
gradientMachine_->getState(*intconfig_->trainState);
gradientMachine_->setState(*intconfig_->testState);
}
}
void Tester::testOneDataBatch(const DataBatch& dataBatch,
std::vector<Argument>* outArgs) {
testContext_.cost +=
forwardOneBatch(dataBatch, testEvaluator_.get(), outArgs);
testContext_.numSamples += dataBatch.getSize();
}
void Tester::testOnePeriod() {
DataBatch dataBatch;
int64_t batchSize = config_->getOptConfig().batch_size();
std::vector<Argument> outArgs;
startTestPeriod();
while (testDataProvider_->getNextBatch(batchSize, &dataBatch) != 0) {
testOneDataBatch(dataBatch, &outArgs);
}
finishTestPeriod();
}
void Tester::finishTestPeriod() {
if (intconfig_->prevBatchState) {
gradientMachine_->resetState();
}
testEvaluator_->finish();
CHECK_GT(testContext_.numSamples, 0)
<< "There is no samples in your test batch. Possibly "
"wrong implementation of DataProvidor.reset()";
LOG(INFO) << " Test samples=" << testContext_.numSamples
<< " cost=" << testContext_.cost / testContext_.numSamples
<< " Eval: " << *testEvaluator_;
parameterUpdater_->restore();
if (intconfig_->prevBatchState) {
gradientMachine_->getState(*intconfig_->testState);
gradientMachine_->setState(*intconfig_->trainState);
}
}
int64_t Tester::testOneBatchById(int64_t batchId) {
DataBatch dataBatch;
int32_t batchSize = config_->getOptConfig().batch_size();
testDataProvider_->getNextBatch(batchSize, &dataBatch);
int64_t actualBatchSize = dataBatch.getSize();
if (actualBatchSize == 0) {
return 0;
}
std::vector<Argument> outArgs;
stats_ += std::pair<int64_t, real>{
actualBatchSize,
forwardOneBatch(dataBatch, testEvaluator_.get(), &outArgs)};
if (((batchId + 1) % intconfig_->logPeriod) == 0) {
LOG(INFO) << " Batch=" << batchId + 1 << " " << stats_.getStats(false);
}
return actualBatchSize;
}
real Tester::forwardOneBatch(const DataBatch& dataBatch,
Evaluator* evaluator,
std::vector<Argument>* pOutArgs) {
auto& outArgs = *pOutArgs;
const std::vector<Argument>& inArgs = dataBatch.getStreams();
if (intconfig_->loadsaveParametersInPserver) {
REGISTER_TIMER("prefetch");
gradientMachine_->prefetch(inArgs);
parameterUpdater_->getParametersRemote(false /*full parameter*/,
true /*after apply*/);
}
gradientMachine_->forward(inArgs, &outArgs, PASS_TEST);
// write features if set this flag and outArgs is not empty
std::string featFile = intconfig_->featFile;
if (!featFile.empty() && outArgs.empty()) {
size_t numOutputs = outArgs.size();
std::vector<MatrixPtr> featMatrices;
featMatrices.resize(numOutputs);
for (size_t i = 0; i < numOutputs; ++i) {
featMatrices[i] = Matrix::create(outArgs[i].value->getHeight(),
outArgs[i].value->getWidth(),
false,
false); // CPU data buffer
featMatrices[i]->copyFrom(*(outArgs[i].value), HPPL_STREAM_DEFAULT);
}
hl_stream_synchronize(HPPL_STREAM_DEFAULT);
FILE* fp = fopen(featFile.c_str(), "ab+");
PCHECK(!ferror(fp)) << "Fail to open " << featFile;
size_t sampleNum = featMatrices[0]->getHeight();
for (size_t i = 0; i < sampleNum; ++i) {
for (size_t j = 0; j < numOutputs; ++j) {
size_t dim = featMatrices[j]->getWidth();
fwrite(featMatrices[j]->getData() + i * dim, sizeof(real), dim, fp);
}
}
fclose(fp);
}
if (evaluator) {
gradientMachine_->eval(evaluator);
}
// Save the output layers if predict_output_dir is not empty
std::string predictOutputDir = intconfig_->predictOutputDir;
if (!predictOutputDir.empty() && !outArgs.empty()) {
CHECK(intconfig_->testing) << "Only valid in test mode";
if (!os_.is_open()) {
// TODO(yuyang18): Refactor these lines.
constexpr int kBufLen = 100;
char buf[kBufLen];
snprintf(buf, kBufLen, "rank-%05d", intconfig_->trainerId);
mkDir(predictOutputDir.c_str());
std::string filename = path::join(predictOutputDir, buf);
os_.open(filename, std::ofstream::trunc);
CHECK(os_.is_open()) << "Failed to open file " << filename;
}
printOutput(outArgs, os_);
return 0.0; // In this case, there is no meaning to calculate cost
}
return Argument::sumCosts(outArgs);
}
void Tester::testOnePassBatch(int passId) {
stats_.reset();
const std::vector<Argument> inArgs;
gradientMachine_->forward(inArgs, nullptr, PASS_TEST);
int64_t num;
real cost;
gradientMachine_->getStats(cost, num);
stats_ += std::pair<int64_t, real>{num, cost};
gradientMachine_->onPassEnd();
LOG(INFO) << " Pass=" << passId << " " << stats_.getStats(false);
}
void Tester::testOnePass(int passId) {
stats_.reset();
int64_t batchId = 0;
int num = 0;
if (intconfig_->prevBatchState) {
gradientMachine_->resetState();
}
testEvaluator_->start();
do {
num = testOneBatchById(batchId);
++batchId;
} while (num > 0);
gradientMachine_->onPassEnd();
testEvaluator_->finish();
LOG(INFO) << " Pass=" << passId << " " << stats_.getStats(false)
<< " Eval: " << *testEvaluator_;
if (intconfig_->distributeTest) {
testEvaluator_->distributeEval(testParameterClient_.get());
if (0 == intconfig_->trainerId) {
LOG(INFO) << "distribute eval: " << *testEvaluator_;
}
}
}
void Tester::test() {
CHECK(testDataProvider_) << "TestData is not specified";
testDataProvider_->setSkipShuffle();
testDataProvider_->reset();
gradientMachine_->start(*config_, testDataProvider_);
// For evaluation
std::vector<std::string> modelList;
std::string modelListFromConfig = intconfig_->modelList;
std::string initModelPath = intconfig_->initModelPath;
if (!modelListFromConfig.empty()) {
loadFileList(modelListFromConfig, modelList);
intconfig_->testPass = 0;
intconfig_->numPasses = modelList.size();
intconfig_->savingPeriod = 1;
CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
} else if (!initModelPath.empty()) {
modelList.push_back(initModelPath);
intconfig_->testPass = 0;
intconfig_->numPasses = 1;
intconfig_->savingPeriod = 1;
CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
}
for (int i = intconfig_->testPass; i < intconfig_->numPasses; ++i) {
int passId = i;
if (passId % intconfig_->savingPeriod == 0) {
if (intconfig_->testWait) {
while (paramUtil_->loadParameters(
passId, true /*local*/, true /*remote*/) == false) {
LOG(INFO) << "Waiting for parameters of pass " << passId;
sleep(60); // sleep 60s
}
} else {
if (modelList.size() == 0) {
CHECK_EQ(paramUtil_->loadParameters(
passId, true /*local*/, true /*remote*/),
true);
} else {
paramUtil_->loadParametersWithPath(
modelList[i], true /*local*/, true /*remote*/);
}
}
if (IGradientMachineMode::trainWholeDataInOneBatch(intconfig_->mode)) {
testOnePassBatch(passId);
} else {
testOnePass(passId);
}
if (passId + intconfig_->savingPeriod < intconfig_->numPasses) {
// if there is at least 1 more pass to test, then call reset,
// otherwise not.
testDataProvider_->reset();
}
}
}
gradientMachine_->finish();
}
void Tester::printOutput(const std::vector<Argument>& outArgs,
std::ostream& os) {
size_t numOutputs = outArgs.size();
size_t numIns = outArgs[0].getBatchSize();
if (cpuMat_.size() != numOutputs || cpuVec_.size() != numOutputs) {
cpuMat_.resize(numOutputs, nullptr);
cpuVec_.resize(numOutputs, nullptr);
}
for (size_t i = 0; i < numOutputs; ++i) {
if (outArgs[i].value != nullptr) {
if (outArgs[i].value->useGpu()) {
if (dynamic_cast<GpuMatrix*>(outArgs[i].value.get())) {
size_t dim = outArgs[i].value->getWidth();
Matrix::resizeOrCreate(cpuMat_[i], numIns, dim, false, false);
cpuMat_[i]->copyFrom(*outArgs[i].value);
} else if (dynamic_cast<GpuSparseMatrix*>(outArgs[i].value.get())) {
auto sparseMat =
dynamic_cast<GpuSparseMatrix*>(outArgs[i].value.get());
cpuMat_[i] = Matrix::createSparseMatrix(sparseMat->getHeight(),
sparseMat->getWidth(),
sparseMat->getElementCnt(),
sparseMat->getValueType(),
sparseMat->format_,
false, /* trans */
false); /* useGpu */
hl_stream_t stream = HPPL_STREAM_DEFAULT;
cpuMat_[i]->copyFrom(*sparseMat, stream);
} else {
LOG(WARNING) << "Not supported gpu matrix type";
}
}
} else if (outArgs[i].ids != nullptr) {
if (outArgs[i].ids->useGpu()) {
IVector::resizeOrCreate(cpuVec_[i], outArgs[i].ids->getSize(), false);
cpuVec_[i]->copyFrom(*outArgs[i].ids);
}
} else if (outArgs[i].strs != nullptr) {
continue;
} else {
LOG(WARNING) << "outArgs[" << i << "] has no data to print";
}
}
for (size_t i = 0; i < numIns; ++i) {
for (size_t j = 0; j < numOutputs; ++j) {
if (outArgs[j].value != nullptr) {
if (outArgs[j].value->useGpu()) {
cpuMat_[j]->printOneRow(os, i);
} else {
outArgs[j].value->printOneRow(os, i);
}
} else if (outArgs[j].ids != nullptr) {
if (outArgs[j].ids->useGpu()) {
cpuVec_[j]->printOneElement(os, i);
} else {
outArgs[j].ids->printOneElement(os, i);
}
} else if (outArgs[j].strs != nullptr) {
os << (*outArgs[j].strs)[i] << ";";
}
}
os << std::endl;
}
}
} // namespace paddle
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: testMetaMesh.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <stdio.h>
#include <iostream>
#include <ctype.h>
#include <metaMesh.h>
#include <metaScene.h>
bool TestingMetaMesh(MetaMesh* _mesh)
{
int j;
// Testing Points
std::cout << "Testing Points : ";
typedef MetaMesh::PointListType PointListType;
PointListType::const_iterator it2 = _mesh->GetPoints().begin();
for(j=0;j< _mesh->GetPoints().size();j++)
{
if( ((*it2)->m_Id != j)
|| ((*it2)->m_X[0] != j)
|| ((*it2)->m_X[1] != j)
|| ((*it2)->m_X[2] != j)
)
{
std::cout << (*it2)->m_Id << " : " << (*it2)->m_X[0]
<< " " << (*it2)->m_X[1] << " " << (*it2)->m_X[2] << std::endl;
std::cout << "[FAILED]" << std::endl;
return 1;
}
it2++;
}
std::cout << "[PASSED]" << std::endl;
// Testing cells
std::cout << "Testing Cells : ";
typedef MetaMesh::CellListType CellListType;
CellListType::const_iterator it3 = _mesh->GetCells(MET_TETRAHEDRON_CELL).begin();
for(j=0;j< _mesh->GetCells(MET_TETRAHEDRON_CELL).size();j++)
{
if( ((*it3)->m_Dim != 4)
|| ((*it3)->m_Id != j)
)
{
std::cout << "Cell Type = " << (*it3)->m_Dim << " : " << (*it3)->m_Id << " : ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
for(unsigned int k=0;k<(*it3)->m_Dim;k++)
{
if((*it3)->m_PointsId[k] != j+k)
{
std::cout << (*it3)->m_PointsId[k] << " ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
}
it3++;
}
it3 = _mesh->GetCells(MET_TRIANGLE_CELL).begin();
for(j=0;j< _mesh->GetCells(MET_TRIANGLE_CELL).size();j++)
{
if( ((*it3)->m_Dim != 3)
|| ((*it3)->m_Id != j)
)
{
std::cout << "Cell Type = " << (*it3)->m_Dim << " : " << (*it3)->m_Id << " : ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
for(unsigned int k=0;k<(*it3)->m_Dim;k++)
{
if((*it3)->m_PointsId[k] != j+k)
{
std::cout << (*it3)->m_PointsId[k] << " ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
}
it3++;
}
std::cout << "[PASSED]" << std::endl;
// Testing cell links
std::cout << "Testing CellLinks : ";
typedef MetaMesh::CellLinkListType CellLinkListType;
CellLinkListType::const_iterator it_link = _mesh->GetCellLinks().begin();
for(j=0;j< _mesh->GetCellLinks().size();j++)
{
if((*it_link)->m_Id != j)
{
std::cout << "CellLink ID = " << (*it_link)->m_Id << " : " ;
std::cout << "[FAILED]" << std::endl;
return 1;
}
std::list<int>::const_iterator it_link2 = (*it_link)->m_Links.begin();
while(it_link2 != (*it_link)->m_Links.end())
{
if(*it_link2 != j+1)
{
std::cout << "[FAILED]" << std::endl;
return 1;
}
it_link2++;
}
it_link++;
}
std::cout << "[PASSED]" << std::endl;
// Testing PointData
std::cout << "Testing PointData : ";
typedef MetaMesh::PointDataListType PointDataListType;
PointDataListType::const_iterator it_pd = _mesh->GetPointData().begin();
for(j=0;j< _mesh->GetPointData().size();j++)
{
if(((*it_pd)->m_Id != j) || ((int)(static_cast<MeshData<int>*>(*it_pd)->m_Data) != j))
{
std::cout << "PointData ID = " << (*it_pd)->m_Id << " : " << (int)(static_cast<MeshData<int>*>(*it_pd)->m_Data) << std::endl;
std::cout << "[FAILED]" << std::endl;
return 1;
}
it_pd++;
}
std::cout << "[PASSED]" << std::endl;
// Testing CellData
std::cout << "Testing CellData : ";
typedef MetaMesh::CellDataListType CellDataListType;
CellDataListType::const_iterator it_cd = _mesh->GetCellData().begin();
float f = (float)(0.1);
for(j=0;j< _mesh->GetCellData().size();j++)
{
if(((*it_cd)->m_Id != j) || ((float)(static_cast<MeshData<float>*>(*it_cd)->m_Data) != f))
{
std::cout << "CellData ID = " << (*it_cd)->m_Id << " : " << (float)(static_cast<MeshData<float>*>(*it_cd)->m_Data) << " : " << f << std::endl;
std::cout << "[FAILED]" << std::endl;
return 1;
}
f += (float)0.2;
it_cd++;
}
std::cout << "[PASSED]" << std::endl;
return 0;
}
/** Main */
int testMetaMesh(int , char * [])
{
MetaScene myScene = MetaScene(3);
std::cout << "Creating mesh: ";
MetaMesh* mesh = new MetaMesh(3);
mesh->ID(0);
// Add Points
MeshPoint* pnt;
int i;
for(i=0;i<10;i++)
{
pnt = new MeshPoint(3);
pnt->m_X[0]=pnt->m_X[1]=pnt->m_X[2]=static_cast<float>(i);
pnt->m_Id=i;
mesh->GetPoints().push_back(pnt);
}
// Add Cells
MeshCell* cell;
for(i=0;i<6;i++)
{
cell = new MeshCell(4); // tetrahedra
cell->m_Id = i;
cell->m_PointsId[0]=i;
cell->m_PointsId[1]=i+1;
cell->m_PointsId[2]=i+2;
cell->m_PointsId[3]=i+3;
mesh->GetCells(MET_TETRAHEDRON_CELL).push_back(cell);
}
// Add other type of cells
for(i=0;i<4;i++)
{
cell = new MeshCell(3); // triangle
cell->m_Id = i;
cell->m_PointsId[0]=i;
cell->m_PointsId[1]=i+1;
cell->m_PointsId[2]=i+2;
mesh->GetCells(MET_TRIANGLE_CELL).push_back(cell);
}
// Add cell links
for(i=0;i<3;i++)
{
MeshCellLink* link = new MeshCellLink();
link->m_Id = i;
link->m_Links.push_back(i+1);
mesh->GetCellLinks().push_back(link);
}
// Add point data
for(i=0;i<5;i++)
{
MeshData<int>* pd = new MeshData<int>();
pd->m_Id = i;
pd->m_Data = i;
mesh->GetPointData().push_back(pd);
}
// Add cell data
float f = (float)(0.1);
for(i=0;i<4;i++)
{
MeshData<float>* cd = new MeshData<float>();
cd->m_Id = i;
cd->m_Data = f;
f+=(float)(0.2);
mesh->GetCellData().push_back(cd);
}
std::cout << "[PASSED]" << std::endl;
// Write the mesh
std::cout << "Writing non binary Mesh : ";
myScene.AddObject(mesh);
myScene.BinaryData(false);
myScene.Write("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
std::cout << "Reading non binary Mesh : ";
// Read the mesh
MetaScene myScene2 = MetaScene();
myScene2.InitializeEssential(3);
myScene2.Read("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
typedef MetaScene::ObjectListType ListType;
ListType * list = myScene2.GetObjectList();
ListType::iterator it = list->begin();
for(i=0;i< list->size();i++)
{
if(!strncmp((*it)->ObjectTypeName(),"Mesh",4))
{
MetaMesh* mesh2 = dynamic_cast<MetaMesh*>(*it);
if(TestingMetaMesh(mesh2))
{
std::cout << "[FAILED]" << std::endl;
return 1;
}
(mesh2)->PrintInfo();
}
it++;
}
// Now testing Binary mesh
std::cout << "Writing binary Mesh : ";
myScene.BinaryData(true);
myScene.Write("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
std::cout << "Reading binary Mesh : ";
// Read the mesh
MetaScene myScene3 = MetaScene();
myScene3.InitializeEssential(3);
myScene3.Read("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
list = myScene3.GetObjectList();
it = list->begin();
for(i=0;i< list->size();i++)
{
if(!strncmp((*it)->ObjectTypeName(),"Mesh",4))
{
MetaMesh* mesh2 = dynamic_cast<MetaMesh*>(*it);
if(TestingMetaMesh(mesh2))
{
std::cout << "[FAILED]" << std::endl;
return 1;
}
(mesh2)->PrintInfo();
}
it++;
}
std::cout << "[DONE]" << std::endl;
return 0;
}
<commit_msg>FIX: Comparison between floats<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: testMetaMesh.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <stdio.h>
#include <iostream>
#include <ctype.h>
#include <metaMesh.h>
#include <metaScene.h>
#include <math.h>
bool TestingMetaMesh(MetaMesh* _mesh)
{
int j;
// Testing Points
std::cout << "Testing Points : ";
typedef MetaMesh::PointListType PointListType;
PointListType::const_iterator it2 = _mesh->GetPoints().begin();
for(j=0;j< _mesh->GetPoints().size();j++)
{
if( ((*it2)->m_Id != j)
|| ((*it2)->m_X[0] != j)
|| ((*it2)->m_X[1] != j)
|| ((*it2)->m_X[2] != j)
)
{
std::cout << (*it2)->m_Id << " : " << (*it2)->m_X[0]
<< " " << (*it2)->m_X[1] << " " << (*it2)->m_X[2] << std::endl;
std::cout << "[FAILED]" << std::endl;
return 1;
}
it2++;
}
std::cout << "[PASSED]" << std::endl;
// Testing cells
std::cout << "Testing Cells : ";
typedef MetaMesh::CellListType CellListType;
CellListType::const_iterator it3 = _mesh->GetCells(MET_TETRAHEDRON_CELL).begin();
for(j=0;j< _mesh->GetCells(MET_TETRAHEDRON_CELL).size();j++)
{
if( ((*it3)->m_Dim != 4)
|| ((*it3)->m_Id != j)
)
{
std::cout << "Cell Type = " << (*it3)->m_Dim << " : " << (*it3)->m_Id << " : ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
for(unsigned int k=0;k<(*it3)->m_Dim;k++)
{
if((*it3)->m_PointsId[k] != j+k)
{
std::cout << (*it3)->m_PointsId[k] << " ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
}
it3++;
}
it3 = _mesh->GetCells(MET_TRIANGLE_CELL).begin();
for(j=0;j< _mesh->GetCells(MET_TRIANGLE_CELL).size();j++)
{
if( ((*it3)->m_Dim != 3)
|| ((*it3)->m_Id != j)
)
{
std::cout << "Cell Type = " << (*it3)->m_Dim << " : " << (*it3)->m_Id << " : ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
for(unsigned int k=0;k<(*it3)->m_Dim;k++)
{
if((*it3)->m_PointsId[k] != j+k)
{
std::cout << (*it3)->m_PointsId[k] << " ";
std::cout << "[FAILED]" << std::endl;
return 1;
}
}
it3++;
}
std::cout << "[PASSED]" << std::endl;
// Testing cell links
std::cout << "Testing CellLinks : ";
typedef MetaMesh::CellLinkListType CellLinkListType;
CellLinkListType::const_iterator it_link = _mesh->GetCellLinks().begin();
for(j=0;j< _mesh->GetCellLinks().size();j++)
{
if((*it_link)->m_Id != j)
{
std::cout << "CellLink ID = " << (*it_link)->m_Id << " : " ;
std::cout << "[FAILED]" << std::endl;
return 1;
}
std::list<int>::const_iterator it_link2 = (*it_link)->m_Links.begin();
while(it_link2 != (*it_link)->m_Links.end())
{
if(*it_link2 != j+1)
{
std::cout << "[FAILED]" << std::endl;
return 1;
}
it_link2++;
}
it_link++;
}
std::cout << "[PASSED]" << std::endl;
// Testing PointData
std::cout << "Testing PointData : ";
typedef MetaMesh::PointDataListType PointDataListType;
PointDataListType::const_iterator it_pd = _mesh->GetPointData().begin();
for(j=0;j< _mesh->GetPointData().size();j++)
{
if(((*it_pd)->m_Id != j) || ((int)(static_cast<MeshData<int>*>(*it_pd)->m_Data) != j))
{
std::cout << "PointData ID = " << (*it_pd)->m_Id << " : " << (int)(static_cast<MeshData<int>*>(*it_pd)->m_Data) << std::endl;
std::cout << "[FAILED]" << std::endl;
return 1;
}
it_pd++;
}
std::cout << "[PASSED]" << std::endl;
// Testing CellData
std::cout << "Testing CellData : ";
typedef MetaMesh::CellDataListType CellDataListType;
CellDataListType::const_iterator it_cd = _mesh->GetCellData().begin();
float f = (float)(0.1);
for(j=0;j< _mesh->GetCellData().size();j++)
{
if(((*it_cd)->m_Id != j) || (fabs((float)(static_cast<MeshData<float>*>(*it_cd)->m_Data)-f)>0.001))
{
std::cout << "CellData ID = " << (*it_cd)->m_Id << " : " << (float)(static_cast<MeshData<float>*>(*it_cd)->m_Data) << " : " << f << std::endl;
std::cout << "[FAILED]" << std::endl;
return 1;
}
f += (float)0.2;
it_cd++;
}
std::cout << "[PASSED]" << std::endl;
return 0;
}
/** Main */
int testMetaMesh(int , char * [])
{
MetaScene myScene = MetaScene(3);
std::cout << "Creating mesh: ";
MetaMesh* mesh = new MetaMesh(3);
mesh->ID(0);
// Add Points
MeshPoint* pnt;
int i;
for(i=0;i<10;i++)
{
pnt = new MeshPoint(3);
pnt->m_X[0]=pnt->m_X[1]=pnt->m_X[2]=static_cast<float>(i);
pnt->m_Id=i;
mesh->GetPoints().push_back(pnt);
}
// Add Cells
MeshCell* cell;
for(i=0;i<6;i++)
{
cell = new MeshCell(4); // tetrahedra
cell->m_Id = i;
cell->m_PointsId[0]=i;
cell->m_PointsId[1]=i+1;
cell->m_PointsId[2]=i+2;
cell->m_PointsId[3]=i+3;
mesh->GetCells(MET_TETRAHEDRON_CELL).push_back(cell);
}
// Add other type of cells
for(i=0;i<4;i++)
{
cell = new MeshCell(3); // triangle
cell->m_Id = i;
cell->m_PointsId[0]=i;
cell->m_PointsId[1]=i+1;
cell->m_PointsId[2]=i+2;
mesh->GetCells(MET_TRIANGLE_CELL).push_back(cell);
}
// Add cell links
for(i=0;i<3;i++)
{
MeshCellLink* link = new MeshCellLink();
link->m_Id = i;
link->m_Links.push_back(i+1);
mesh->GetCellLinks().push_back(link);
}
// Add point data
for(i=0;i<5;i++)
{
MeshData<int>* pd = new MeshData<int>();
pd->m_Id = i;
pd->m_Data = i;
mesh->GetPointData().push_back(pd);
}
// Add cell data
float f = (float)(0.1);
for(i=0;i<4;i++)
{
MeshData<float>* cd = new MeshData<float>();
cd->m_Id = i;
cd->m_Data = f;
f+=(float)(0.2);
mesh->GetCellData().push_back(cd);
}
std::cout << "[PASSED]" << std::endl;
// Write the mesh
std::cout << "Writing non binary Mesh : ";
myScene.AddObject(mesh);
myScene.BinaryData(false);
myScene.Write("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
std::cout << "Reading non binary Mesh : ";
// Read the mesh
MetaScene myScene2 = MetaScene();
myScene2.InitializeEssential(3);
myScene2.Read("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
typedef MetaScene::ObjectListType ListType;
ListType * list = myScene2.GetObjectList();
ListType::iterator it = list->begin();
for(i=0;i< list->size();i++)
{
if(!strncmp((*it)->ObjectTypeName(),"Mesh",4))
{
MetaMesh* mesh2 = dynamic_cast<MetaMesh*>(*it);
if(TestingMetaMesh(mesh2))
{
std::cout << "[FAILED]" << std::endl;
return 1;
}
(mesh2)->PrintInfo();
}
it++;
}
// Now testing Binary mesh
std::cout << "Writing binary Mesh : ";
myScene.BinaryData(true);
myScene.Write("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
std::cout << "Reading binary Mesh : ";
// Read the mesh
MetaScene myScene3 = MetaScene();
myScene3.InitializeEssential(3);
myScene3.Read("metamesh.msh");
std::cout << "[PASSED]" << std::endl;
list = myScene3.GetObjectList();
it = list->begin();
for(i=0;i< list->size();i++)
{
if(!strncmp((*it)->ObjectTypeName(),"Mesh",4))
{
MetaMesh* mesh2 = dynamic_cast<MetaMesh*>(*it);
if(TestingMetaMesh(mesh2))
{
std::cout << "[FAILED]" << std::endl;
return 1;
}
(mesh2)->PrintInfo();
}
it++;
}
std::cout << "[DONE]" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlDataSourceSettings.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:03:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBA_XMLDATASOURCESETTINGS_HXX
#include "xmlDataSourceSettings.hxx"
#endif
#ifndef DBA_XMLDATASOURCESETTING_HXX
#include "xmlDataSourceSetting.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#include <vector>
namespace dbaxml
{
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
OXMLDataSourceSettings::OXMLDataSourceSettings( ODBFilter& rImport
,sal_uInt16 nPrfx
,const OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,OXMLDataSource& _rParent) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_rParent(_rParent)
{
}
// -----------------------------------------------------------------------------
OXMLDataSourceSettings::~OXMLDataSourceSettings()
{
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLDataSourceSettings::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetOwnImport().GetDataSourceInfoElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_DATA_SOURCE_SETTING:
GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLDataSourceSetting( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_rParent );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLDataSourceSettings::GetOwnImport()
{
return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba201b (1.3.94); FILE MERGED 2005/09/21 07:26:45 oj 1.3.94.2: RESYNC: (1.3-1.4); FILE MERGED 2005/07/11 13:37:05 fs 1.3.94.1: merging CWS dba201 into CWS dba201b<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlDataSourceSettings.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2005-09-23 12:09:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBA_XMLDATASOURCESETTINGS_HXX
#include "xmlDataSourceSettings.hxx"
#endif
#ifndef DBA_XMLDATASOURCESETTING_HXX
#include "xmlDataSourceSetting.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include <vector>
namespace dbaxml
{
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLDataSourceSettings)
OXMLDataSourceSettings::OXMLDataSourceSettings( ODBFilter& rImport
,sal_uInt16 nPrfx
,const OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,OXMLDataSource& _rParent) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_rParent(_rParent)
{
DBG_CTOR(OXMLDataSourceSettings,NULL);
}
// -----------------------------------------------------------------------------
OXMLDataSourceSettings::~OXMLDataSourceSettings()
{
DBG_DTOR(OXMLDataSourceSettings,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLDataSourceSettings::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetOwnImport().GetDataSourceInfoElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_DATA_SOURCE_SETTING:
GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLDataSourceSetting( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_rParent );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLDataSourceSettings::GetOwnImport()
{
return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
* Copyright (C) 2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/workqueue.h>
#include <px4_platform_common/defines.h>
#include <drivers/drv_hrt.h>
#include <uORB/uORB.h>
#include <uORB/topics/input_rc.h>
namespace navio_sysfs_rc_in
{
extern "C" __EXPORT int navio_sysfs_rc_in_main(int argc, char *argv[]);
#define RCINPUT_DEVICE_PATH_BASE "/sys/kernel/rcio/rcin"
#define RCINPUT_MEASURE_INTERVAL_US 20000 // microseconds
class RcInput
{
public:
RcInput() :
_shouldExit(false),
_isRunning(false),
_work{},
_rcinput_pub(nullptr),
_channels(8), //D8R-II plus
_data{}
{ }
~RcInput()
{
work_cancel(HPWORK, &_work);
_isRunning = false;
}
/* @return 0 on success, -errno on failure */
int start();
/* @return 0 on success, -errno on failure */
void stop();
/* Trampoline for the work queue. */
static void cycle_trampoline(void *arg);
bool isRunning() { return _isRunning; }
private:
void _cycle();
void _measure();
bool _shouldExit;
bool _isRunning;
struct work_s _work;
orb_advert_t _rcinput_pub;
int _channels;
int _ch_fd[input_rc_s::RC_INPUT_MAX_CHANNELS] {};
struct input_rc_s _data;
int navio_rc_init();
};
int RcInput::navio_rc_init()
{
int i;
char buf[64];
for (i = 0; i < _channels; ++i) {
::snprintf(buf, sizeof(buf), "%s/ch%d", RCINPUT_DEVICE_PATH_BASE, i);
int fd = ::open(buf, O_RDONLY);
if (fd < 0) {
PX4_WARN("error: open %d failed", i);
break;
}
_ch_fd[i] = fd;
}
for (; i < input_rc_s::RC_INPUT_MAX_CHANNELS; ++i) {
_data.values[i] = UINT16_MAX;
}
_rcinput_pub = orb_advertise(ORB_ID(input_rc), &_data);
if (_rcinput_pub == nullptr) {
PX4_WARN("error: advertise failed");
return -1;
}
return 0;
}
int RcInput::start()
{
int result = 0;
result = navio_rc_init();
if (result != 0) {
PX4_WARN("error: RC initialization failed");
return -1;
}
_isRunning = true;
result = work_queue(HPWORK, &_work, (worker_t)&RcInput::cycle_trampoline, this, 0);
if (result == -1) {
_isRunning = false;
}
return result;
}
void RcInput::stop()
{
_shouldExit = true;
}
void RcInput::cycle_trampoline(void *arg)
{
RcInput *dev = static_cast<RcInput *>(arg);
dev->_cycle();
}
void RcInput::_cycle()
{
_measure();
if (!_shouldExit) {
work_queue(HPWORK, &_work, (worker_t)&RcInput::cycle_trampoline, this,
USEC2TICK(RCINPUT_MEASURE_INTERVAL_US));
}
}
void RcInput::_measure(void)
{
uint64_t ts;
char buf[12];
for (int i = 0; i < _channels; ++i) {
int res;
if ((res = ::pread(_ch_fd[i], buf, sizeof(buf) - 1, 0)) < 0) {
_data.values[i] = UINT16_MAX;
continue;
}
buf[sizeof(buf) - 1] = '\0';
_data.values[i] = atoi(buf);
}
ts = hrt_absolute_time();
_data.timestamp = ts;
_data.timestamp_last_signal = ts;
_data.channel_count = _channels;
_data.rssi = 100;
_data.rc_lost_frame_count = 0;
_data.rc_total_frame_count = 1;
_data.rc_ppm_frame_length = 100;
_data.rc_failsafe = false;
_data.rc_lost = false;
_data.input_source = input_rc_s::RC_INPUT_SOURCE_PX4IO_PPM;
orb_publish(ORB_ID(input_rc), _rcinput_pub, &_data);
}
/**
* Print the correct usage.
*/
static void usage(const char *reason);
static void
usage(const char *reason)
{
if (reason) {
PX4_ERR("%s", reason);
}
PX4_INFO("usage: navio_sysfs_rc_in {start|stop|status}");
}
static RcInput *rc_input = nullptr;
int navio_sysfs_rc_in_main(int argc, char *argv[])
{
if (argc < 2) {
usage("missing command");
return 1;
}
if (!strcmp(argv[1], "start")) {
if (rc_input != nullptr && rc_input->isRunning()) {
PX4_WARN("already running");
/* this is not an error */
return 0;
}
rc_input = new RcInput();
// Check if alloc worked.
if (rc_input == nullptr) {
PX4_ERR("alloc failed");
return -1;
}
int ret = rc_input->start();
if (ret != 0) {
PX4_ERR("start failed");
}
return 0;
}
if (!strcmp(argv[1], "stop")) {
if (rc_input == nullptr || !rc_input->isRunning()) {
PX4_WARN("not running");
/* this is not an error */
return 0;
}
rc_input->stop();
// Wait for task to die
int i = 0;
do {
/* wait up to 3s */
usleep(100000);
} while (rc_input->isRunning() && ++i < 30);
delete rc_input;
rc_input = nullptr;
return 0;
}
if (!strcmp(argv[1], "status")) {
if (rc_input != nullptr && rc_input->isRunning()) {
PX4_INFO("running");
} else {
PX4_INFO("not running\n");
}
return 0;
}
usage("unrecognized command");
return 1;
}
}; // namespace navio_sysfs_rc_in
<commit_msg>navio_sysfs_rc_in orb_publish usage to uORB::PublicationMulti<><commit_after>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
* Copyright (C) 2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/workqueue.h>
#include <px4_platform_common/defines.h>
#include <drivers/drv_hrt.h>
#include <uORB/PublicationMulti.hpp>
#include <uORB/topics/input_rc.h>
namespace navio_sysfs_rc_in
{
extern "C" __EXPORT int navio_sysfs_rc_in_main(int argc, char *argv[]);
#define RCINPUT_DEVICE_PATH_BASE "/sys/kernel/rcio/rcin"
#define RCINPUT_MEASURE_INTERVAL_US 20000 // microseconds
class RcInput
{
public:
RcInput() :
_shouldExit(false),
_isRunning(false),
_work{},
_rcinput_pub(nullptr),
_channels(8), //D8R-II plus
_data{}
{ }
~RcInput()
{
work_cancel(HPWORK, &_work);
_isRunning = false;
}
/* @return 0 on success, -errno on failure */
int start();
/* @return 0 on success, -errno on failure */
void stop();
/* Trampoline for the work queue. */
static void cycle_trampoline(void *arg);
bool isRunning() { return _isRunning; }
private:
void _cycle();
void _measure();
bool _shouldExit;
bool _isRunning;
struct work_s _work;
uORB::PublicationMulti<input_rc_s> _rcinput_pub{ORB_ID(input_rc)};
int _channels;
int _ch_fd[input_rc_s::RC_INPUT_MAX_CHANNELS] {};
struct input_rc_s _data;
int navio_rc_init();
};
int RcInput::navio_rc_init()
{
int i;
char buf[64];
for (i = 0; i < _channels; ++i) {
::snprintf(buf, sizeof(buf), "%s/ch%d", RCINPUT_DEVICE_PATH_BASE, i);
int fd = ::open(buf, O_RDONLY);
if (fd < 0) {
PX4_WARN("error: open %d failed", i);
break;
}
_ch_fd[i] = fd;
}
for (; i < input_rc_s::RC_INPUT_MAX_CHANNELS; ++i) {
_data.values[i] = UINT16_MAX;
}
return 0;
}
int RcInput::start()
{
int result = 0;
result = navio_rc_init();
if (result != 0) {
PX4_WARN("error: RC initialization failed");
return -1;
}
_isRunning = true;
result = work_queue(HPWORK, &_work, (worker_t)&RcInput::cycle_trampoline, this, 0);
if (result == -1) {
_isRunning = false;
}
return result;
}
void RcInput::stop()
{
_shouldExit = true;
}
void RcInput::cycle_trampoline(void *arg)
{
RcInput *dev = static_cast<RcInput *>(arg);
dev->_cycle();
}
void RcInput::_cycle()
{
_measure();
if (!_shouldExit) {
work_queue(HPWORK, &_work, (worker_t)&RcInput::cycle_trampoline, this,
USEC2TICK(RCINPUT_MEASURE_INTERVAL_US));
}
}
void RcInput::_measure(void)
{
uint64_t ts;
char buf[12];
for (int i = 0; i < _channels; ++i) {
int res;
if ((res = ::pread(_ch_fd[i], buf, sizeof(buf) - 1, 0)) < 0) {
_data.values[i] = UINT16_MAX;
continue;
}
buf[sizeof(buf) - 1] = '\0';
_data.values[i] = atoi(buf);
}
ts = hrt_absolute_time();
_data.timestamp = ts;
_data.timestamp_last_signal = ts;
_data.channel_count = _channels;
_data.rssi = 100;
_data.rc_lost_frame_count = 0;
_data.rc_total_frame_count = 1;
_data.rc_ppm_frame_length = 100;
_data.rc_failsafe = false;
_data.rc_lost = false;
_data.input_source = input_rc_s::RC_INPUT_SOURCE_PX4IO_PPM;
_rcinput_pub.publish(_data);
}
/**
* Print the correct usage.
*/
static void usage(const char *reason);
static void
usage(const char *reason)
{
if (reason) {
PX4_ERR("%s", reason);
}
PX4_INFO("usage: navio_sysfs_rc_in {start|stop|status}");
}
static RcInput *rc_input = nullptr;
int navio_sysfs_rc_in_main(int argc, char *argv[])
{
if (argc < 2) {
usage("missing command");
return 1;
}
if (!strcmp(argv[1], "start")) {
if (rc_input != nullptr && rc_input->isRunning()) {
PX4_WARN("already running");
/* this is not an error */
return 0;
}
rc_input = new RcInput();
// Check if alloc worked.
if (rc_input == nullptr) {
PX4_ERR("alloc failed");
return -1;
}
int ret = rc_input->start();
if (ret != 0) {
PX4_ERR("start failed");
}
return 0;
}
if (!strcmp(argv[1], "stop")) {
if (rc_input == nullptr || !rc_input->isRunning()) {
PX4_WARN("not running");
/* this is not an error */
return 0;
}
rc_input->stop();
// Wait for task to die
int i = 0;
do {
/* wait up to 3s */
usleep(100000);
} while (rc_input->isRunning() && ++i < 30);
delete rc_input;
rc_input = nullptr;
return 0;
}
if (!strcmp(argv[1], "status")) {
if (rc_input != nullptr && rc_input->isRunning()) {
PX4_INFO("running");
} else {
PX4_INFO("not running\n");
}
return 0;
}
usage("unrecognized command");
return 1;
}
}; // namespace navio_sysfs_rc_in
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "tap-gesture-detector.h"
// EXTERNAL INCLUDES
#include <cmath>
#include <dali/public-api/math/vector2.h>
#include <dali/integration-api/events/gesture-requests.h>
#include <dali/integration-api/events/touch-event-integ.h>
#include <base/core-event-interface.h>
// INTERNAL INCLUDES
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
// TODO: Set these according to DPI
const float MAXIMUM_MOTION_ALLOWED = 20.0f;
const unsigned long MAXIMUM_TIME_ALLOWED = 500u;
} // unnamed namespace
TapGestureDetector::TapGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::TapGestureRequest& request)
: GestureDetector(screenSize, Gesture::Tap),
mCoreEventInterface(coreEventInterface),
mState(Clear),
mMinimumTapsRequired(request.minTaps),
mMaximumTapsRequired(request.maxTaps),
mTapsRegistered(0),
mTouchPosition(),
mTouchTime(0u),
mLastTapTime(0u)
{
}
TapGestureDetector::~TapGestureDetector()
{
}
void TapGestureDetector::SendEvent(const Integration::TouchEvent& event)
{
if (event.GetPointCount() == 1)
{
const TouchPoint& point = event.points[0];
TouchPoint::State pointState = point.state;
switch (mState)
{
case Clear:
{
if (pointState == TouchPoint::Down)
{
SetupForTouchDown( event, point );
}
break;
}
case Touched:
{
// Only progress from a touch up event
if ( pointState == TouchPoint::Up )
{
mLastTapTime = mTouchTime;
EmitSingleTap( event.time, point );
mState = Registered;
}
break;
}
case Registered:
{
if ( pointState == TouchPoint::Up )
{
// This is a possible multiple tap, so has it been quick enough ?
unsigned long timeDelta = abs( event.time - mLastTapTime );
if ( timeDelta > MAXIMUM_TIME_ALLOWED )
{
mLastTapTime = event.time;
EmitSingleTap( event.time, point );
mState = Clear;
break;
}
else
{
++mTapsRegistered;
EmitGesture( Gesture::Started, event.time );
mState = Clear;
}
break;
}
if (pointState == TouchPoint::Down)
{
Vector2 distanceDelta(abs(mTouchPosition.x - point.screen.x),
abs(mTouchPosition.y - point.screen.y));
unsigned long timeDelta = abs( mTouchTime - mLastTapTime );
if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
distanceDelta.y > MAXIMUM_MOTION_ALLOWED ||
timeDelta > MAXIMUM_TIME_ALLOWED )
{
SetupForTouchDown( event, point );
}
else
{
EmitPossibleState( event );
}
}
break;
}
case Failed:
default:
{
mState = Clear;
break;
}
}
}
else
{
mState = Failed;
// We have entered a multi-touch event so emit registered gestures if required.
EmitGesture(Gesture::Started, event.time);
}
}
void TapGestureDetector::SetupForTouchDown( const Integration::TouchEvent& event, const TouchPoint& point )
{
mTouchPosition.x = point.screen.x;
mTouchPosition.y = point.screen.y;
mTouchTime = event.time;
mLastTapTime = 0u;
mTapsRegistered = 0;
mState = Touched;
EmitPossibleState( event );
}
void TapGestureDetector::EmitPossibleState( const Integration::TouchEvent& event )
{
Integration::TapGestureEvent tapEvent( Gesture::Possible );
tapEvent.point = mTouchPosition;
tapEvent.time = event.time;
mCoreEventInterface.QueueCoreEvent(tapEvent);
}
void TapGestureDetector::Update(const Integration::GestureRequest& request)
{
const Integration::TapGestureRequest& tap = static_cast<const Integration::TapGestureRequest&>(request);
mMinimumTapsRequired = tap.minTaps;
mMaximumTapsRequired = tap.maxTaps;
}
void TapGestureDetector::EmitGesture( Gesture::State state, unsigned int time )
{
if ( (state == Gesture::Cancelled) ||
(mTapsRegistered >= mMinimumTapsRequired && mTapsRegistered <= mMaximumTapsRequired) )
{
Integration::TapGestureEvent event( state );
EmitTap( time, event );
}
}
void TapGestureDetector::EmitSingleTap( unsigned int time, const TouchPoint& point )
{
Integration::TapGestureEvent event( Gesture::Started );
Vector2 distanceDelta(abs(mTouchPosition.x - point.screen.x),
abs(mTouchPosition.y - point.screen.y));
if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
distanceDelta.y > MAXIMUM_MOTION_ALLOWED )
{
event.state = Gesture::Cancelled;
}
mTapsRegistered = 1u;
EmitTap( time, event );
}
void TapGestureDetector::EmitTap( unsigned int time, Integration::TapGestureEvent& event )
{
event.numberOfTaps = mTapsRegistered;
event.point = mTouchPosition;
event.time = time;
mCoreEventInterface.QueueCoreEvent(event);
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<commit_msg>Process Interrupted event when tap gesture detector is Touched status.<commit_after>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "tap-gesture-detector.h"
// EXTERNAL INCLUDES
#include <cmath>
#include <dali/public-api/math/vector2.h>
#include <dali/integration-api/events/gesture-requests.h>
#include <dali/integration-api/events/touch-event-integ.h>
#include <base/core-event-interface.h>
// INTERNAL INCLUDES
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
// TODO: Set these according to DPI
const float MAXIMUM_MOTION_ALLOWED = 20.0f;
const unsigned long MAXIMUM_TIME_ALLOWED = 500u;
} // unnamed namespace
TapGestureDetector::TapGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::TapGestureRequest& request)
: GestureDetector(screenSize, Gesture::Tap),
mCoreEventInterface(coreEventInterface),
mState(Clear),
mMinimumTapsRequired(request.minTaps),
mMaximumTapsRequired(request.maxTaps),
mTapsRegistered(0),
mTouchPosition(),
mTouchTime(0u),
mLastTapTime(0u)
{
}
TapGestureDetector::~TapGestureDetector()
{
}
void TapGestureDetector::SendEvent(const Integration::TouchEvent& event)
{
if (event.GetPointCount() == 1)
{
const TouchPoint& point = event.points[0];
TouchPoint::State pointState = point.state;
switch (mState)
{
case Clear:
{
if (pointState == TouchPoint::Down)
{
SetupForTouchDown( event, point );
}
break;
}
case Touched:
{
if ( pointState == TouchPoint::Up )
{
mLastTapTime = mTouchTime;
EmitSingleTap( event.time, point );
mState = Registered;
}
else if (pointState == TouchPoint::Interrupted)
{
mState = Clear;
}
break;
}
case Registered:
{
if ( pointState == TouchPoint::Up )
{
// This is a possible multiple tap, so has it been quick enough ?
unsigned long timeDelta = abs( event.time - mLastTapTime );
if ( timeDelta > MAXIMUM_TIME_ALLOWED )
{
mLastTapTime = event.time;
EmitSingleTap( event.time, point );
mState = Clear;
break;
}
else
{
++mTapsRegistered;
EmitGesture( Gesture::Started, event.time );
mState = Clear;
}
break;
}
if (pointState == TouchPoint::Down)
{
Vector2 distanceDelta(abs(mTouchPosition.x - point.screen.x),
abs(mTouchPosition.y - point.screen.y));
unsigned long timeDelta = abs( mTouchTime - mLastTapTime );
if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
distanceDelta.y > MAXIMUM_MOTION_ALLOWED ||
timeDelta > MAXIMUM_TIME_ALLOWED )
{
SetupForTouchDown( event, point );
}
else
{
EmitPossibleState( event );
}
}
break;
}
case Failed:
default:
{
mState = Clear;
break;
}
}
}
else
{
mState = Failed;
// We have entered a multi-touch event so emit registered gestures if required.
EmitGesture(Gesture::Started, event.time);
}
}
void TapGestureDetector::SetupForTouchDown( const Integration::TouchEvent& event, const TouchPoint& point )
{
mTouchPosition.x = point.screen.x;
mTouchPosition.y = point.screen.y;
mTouchTime = event.time;
mLastTapTime = 0u;
mTapsRegistered = 0;
mState = Touched;
EmitPossibleState( event );
}
void TapGestureDetector::EmitPossibleState( const Integration::TouchEvent& event )
{
Integration::TapGestureEvent tapEvent( Gesture::Possible );
tapEvent.point = mTouchPosition;
tapEvent.time = event.time;
mCoreEventInterface.QueueCoreEvent(tapEvent);
}
void TapGestureDetector::Update(const Integration::GestureRequest& request)
{
const Integration::TapGestureRequest& tap = static_cast<const Integration::TapGestureRequest&>(request);
mMinimumTapsRequired = tap.minTaps;
mMaximumTapsRequired = tap.maxTaps;
}
void TapGestureDetector::EmitGesture( Gesture::State state, unsigned int time )
{
if ( (state == Gesture::Cancelled) ||
(mTapsRegistered >= mMinimumTapsRequired && mTapsRegistered <= mMaximumTapsRequired) )
{
Integration::TapGestureEvent event( state );
EmitTap( time, event );
}
}
void TapGestureDetector::EmitSingleTap( unsigned int time, const TouchPoint& point )
{
Integration::TapGestureEvent event( Gesture::Started );
Vector2 distanceDelta(abs(mTouchPosition.x - point.screen.x),
abs(mTouchPosition.y - point.screen.y));
if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
distanceDelta.y > MAXIMUM_MOTION_ALLOWED )
{
event.state = Gesture::Cancelled;
}
mTapsRegistered = 1u;
EmitTap( time, event );
}
void TapGestureDetector::EmitTap( unsigned int time, Integration::TapGestureEvent& event )
{
event.numberOfTaps = mTapsRegistered;
event.point = mTouchPosition;
event.time = time;
mCoreEventInterface.QueueCoreEvent(event);
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<|endoftext|>
|
<commit_before>//
// ex7_13.cpp
// Exercise 7.13
//
// Created by pezy on 11/9/14.
//
#include "ex7_12.h"
int main()
{
Sales_data total(std::cin);
if (!total.isbn().empty())
{
std::istream &is = std::cin;
while (is) {
Sales_data trans(is);
if (total.isbn() == trans.isbn())
total.combine(trans);
else {
print(std::cout, total) << std::endl;
total = trans;
}
}
}
else
{
std::cerr << "No data?!" << std::endl;
return -1;
}
return 0;
}
<commit_msg>Update ex7_13.cpp<commit_after>//
// ex7_13.cpp
// Exercise 7.13
//
// Created by pezy on 11/9/14.
//
#include "ex7_12.h"
int main()
{
Sales_data total(std::cin);
if (!total.isbn().empty())
{
std::istream &is = std::cin;
while (is) {
Sales_data trans(is);
if (total.isbn() == trans.isbn())
total.combine(trans);
else {
print(std::cout, total) << std::endl;
total = trans;
}
}
print(std::cout, total) << std::endl;
}
else
{
std::cerr << "No data?!" << std::endl;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/base:$Id$
// Author: Rene Brun 05/02/2007
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TVirtualStreamerInfo Abstract Interface class //
// //
// Abstract Interface describing Streamer information for one class. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TSystem.h"
#include "TClass.h"
#include "TVirtualMutex.h"
#include "TInterpreter.h"
#include "TVirtualStreamerInfo.h"
#include "TPluginManager.h"
#include "TStreamerElement.h"
#include "TError.h"
TVirtualStreamerInfo *TVirtualStreamerInfo::fgInfoFactory = 0;
Bool_t TVirtualStreamerInfo::fgCanDelete = kTRUE;
Bool_t TVirtualStreamerInfo::fgOptimize = kTRUE;
Bool_t TVirtualStreamerInfo::fgStreamMemberWise = kTRUE;
ClassImp(TVirtualStreamerInfo)
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo() : fOptimized(kFALSE), fIsBuilt(kFALSE), fIsCompiled(kFALSE)
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(TClass *cl)
: TNamed(cl->GetName(),""), fOptimized(kFALSE), fIsBuilt(kFALSE), fIsCompiled(kFALSE)
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(const TVirtualStreamerInfo& info)
: TNamed(info), fOptimized(kFALSE), fIsBuilt(kFALSE), fIsCompiled(kFALSE)
{
//copy constructor
}
//______________________________________________________________________________
TVirtualStreamerInfo& TVirtualStreamerInfo::operator=(const TVirtualStreamerInfo& info)
{
//assignment operator
if(this!=&info) {
TNamed::operator=(info);
}
return *this;
}
//______________________________________________________________________________
TVirtualStreamerInfo::~TVirtualStreamerInfo()
{
// Destructor
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanDelete()
{
// static function returning true if ReadBuffer can delete object
return fgCanDelete;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanOptimize()
{
// static function returning true if optimization can be on
return fgOptimize;
}
//______________________________________________________________________________
const char *TVirtualStreamerInfo::GetElementCounterStart(const char *dmTitle)
{
// Given a comment/title declaring an array counter, for example:
// //[fArraySize] array of size fArraySize
// return the start of the array dimension declaration start in the string
// (so the location of the 'f'.
for (const char *lbracket = dmTitle; *lbracket; ++lbracket) {
// = ::strchr(dmTitle, '[');
if ( (*lbracket) == '[' ) return lbracket;
if ( (*lbracket) != '/' && !isspace(*lbracket) ) {
// Allow only comment delimiters and white spaces
// before the array information.
return 0;
}
}
return 0;
}
//______________________________________________________________________________
TStreamerBasicType *TVirtualStreamerInfo::GetElementCounter(const char *countName, TClass *cl)
{
// Get pointer to a TStreamerBasicType in TClass *cl
//static function
TVirtualStreamerInfo *info;
{
R__LOCKGUARD(gInterpreterMutex);
const TObjArray *sinfos = cl->GetStreamerInfos();
info = (TVirtualStreamerInfo *)sinfos->At(cl->GetClassVersion());
}
if (!info || !info->IsCompiled()) {
// Even if the streamerInfo exist, it could still need to be 'build'
// It is important to figure this out, because
// a) if it is not build, we need to build
// b) if is build, we should not build it (or we could end up in an
// infinite loop, if the element and its counter are in the same
// class!
info = cl->GetStreamerInfo();
}
if (!info) return 0;
TStreamerElement *element = (TStreamerElement *)info->GetElements()->FindObject(countName);
if (!element) return 0;
if (element->IsA() == TStreamerBasicType::Class()) return (TStreamerBasicType*)element;
return 0;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::GetStreamMemberWise()
{
// Return whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
//
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
return fgStreamMemberWise;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Optimize(Bool_t opt)
{
// This is a static function.
// Set optimization option.
// When this option is activated (default), consecutive data members
// of the same type are merged into an array (faster).
// Optimization must be off in TTree split mode.
fgOptimize = opt;
}
//______________________________________________________________________________
TVirtualStreamerInfo *TVirtualStreamerInfo::Factory()
{
// Static function returning a pointer to a new TVirtualStreamerInfo object.
// If the Info factory does not exist, it is created via the plugin manager.
// In reality the factory is an empty TStreamerInfo object.
if (!fgInfoFactory) {
TPluginHandler *h;
if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualStreamerInfo","TStreamerInfo"))) {
if (h->LoadPlugin() == -1) {
::Fatal("TVirtualStreamerInfo::Factory",
"The plugin handler for TVirtualStreamerInfo was found but failed to load!");
}
fgInfoFactory = (TVirtualStreamerInfo*) h->ExecPlugin(0);
if (fgInfoFactory == 0) {
::Fatal("TVirtualStreamerInfo::Factory",
"The plugin handler for TVirtualStreamerInfo was found but failed to create the factory object!");
}
} else {
TString filename("$ROOTSYS/etc/plugins/TVirtualStreamerInfo");
gSystem->ExpandPathName(filename);
if (gSystem->AccessPathName(filename)) {
::Fatal("TVirtualStreamerInfo::Factory",
"Cannot find the plugin handler for TVirtualStreamerInfo! "
"$ROOTSYS/etc/plugins/TVirtualStreamerInfo does not exist "
"or is inaccessible.");
} else {
::Fatal("TVirtualStreamerInfo::Factory",
"Cannot find the plugin handler for TVirtualStreamerInfo! "
"However $ROOTSYS/etc/plugins/TVirtualStreamerInfo is accessible, "
"Check the content of this directory!");
}
}
}
return fgInfoFactory;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetCanDelete(Bool_t opt)
{
// This is a static function.
// Set object delete option.
// When this option is activated (default), ReadBuffer automatically
// delete objects when a data member is a pointer to an object.
// If your constructor is not presetting pointers to 0, you must
// call this static function TStreamerInfo::SetCanDelete(kFALSE);
fgCanDelete = opt;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetFactory(TVirtualStreamerInfo *factory)
{
//static function: Set the StreamerInfo factory
fgInfoFactory = factory;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::SetStreamMemberWise(Bool_t enable)
{
// Set whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
// This function returns the previous value of fgStreamMemberWise.
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
Bool_t prev = fgStreamMemberWise;
fgStreamMemberWise = enable;
return prev;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Streamer(TBuffer &R__b)
{
// Stream an object of class TVirtualStreamerInfo.
TNamed::Streamer(R__b);
}
<commit_msg>Extend comment<commit_after>// @(#)root/base:$Id$
// Author: Rene Brun 05/02/2007
/*************************************************************************
* Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TVirtualStreamerInfo Abstract Interface class //
// //
// Abstract Interface describing Streamer information for one class. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TSystem.h"
#include "TClass.h"
#include "TVirtualMutex.h"
#include "TInterpreter.h"
#include "TVirtualStreamerInfo.h"
#include "TPluginManager.h"
#include "TStreamerElement.h"
#include "TError.h"
TVirtualStreamerInfo *TVirtualStreamerInfo::fgInfoFactory = 0;
Bool_t TVirtualStreamerInfo::fgCanDelete = kTRUE;
Bool_t TVirtualStreamerInfo::fgOptimize = kTRUE;
Bool_t TVirtualStreamerInfo::fgStreamMemberWise = kTRUE;
ClassImp(TVirtualStreamerInfo)
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo() : fOptimized(kFALSE), fIsBuilt(kFALSE), fIsCompiled(kFALSE)
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(TClass *cl)
: TNamed(cl->GetName(),""), fOptimized(kFALSE), fIsBuilt(kFALSE), fIsCompiled(kFALSE)
{
// Default constructor.
}
//______________________________________________________________________________
TVirtualStreamerInfo::TVirtualStreamerInfo(const TVirtualStreamerInfo& info)
: TNamed(info), fOptimized(kFALSE), fIsBuilt(kFALSE), fIsCompiled(kFALSE)
{
//copy constructor
}
//______________________________________________________________________________
TVirtualStreamerInfo& TVirtualStreamerInfo::operator=(const TVirtualStreamerInfo& info)
{
//assignment operator
if(this!=&info) {
TNamed::operator=(info);
}
return *this;
}
//______________________________________________________________________________
TVirtualStreamerInfo::~TVirtualStreamerInfo()
{
// Destructor
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanDelete()
{
// static function returning true if ReadBuffer can delete object
return fgCanDelete;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::CanOptimize()
{
// static function returning true if optimization can be on
return fgOptimize;
}
//______________________________________________________________________________
const char *TVirtualStreamerInfo::GetElementCounterStart(const char *dmTitle)
{
// Given a comment/title declaring an array counter, for example:
// //[fArraySize] array of size fArraySize
// return the start of the array dimension declaration start in the string
// (so the location of the 'f'.
for (const char *lbracket = dmTitle; *lbracket; ++lbracket) {
// = ::strchr(dmTitle, '[');
if ( (*lbracket) == '[' ) return lbracket;
if ( (*lbracket) != '/' && !isspace(*lbracket) ) {
// Allow only comment delimiters and white spaces
// before the array information.
return 0;
}
}
return 0;
}
//______________________________________________________________________________
TStreamerBasicType *TVirtualStreamerInfo::GetElementCounter(const char *countName, TClass *cl)
{
// Get pointer to a TStreamerBasicType in TClass *cl
//static function
TVirtualStreamerInfo *info;
{
R__LOCKGUARD(gInterpreterMutex);
const TObjArray *sinfos = cl->GetStreamerInfos();
info = (TVirtualStreamerInfo *)sinfos->At(cl->GetClassVersion());
}
if (!info || !info->IsCompiled()) {
// Even if the streamerInfo exist, it could still need to be 'build'
// It is important to figure this out, because
// a) if it is not build, we need to build
// b) if is build, we should not build it (or we could end up in an
// infinite loop, if the element and its counter are in the same
// class!
// Checking IsCompiled is sufficint here even-though it is set only at
// the end of the call to Build as this function has an
// internal recursion prevention (setting and testing kBuildRunning).
info = cl->GetStreamerInfo();
}
if (!info) return 0;
TStreamerElement *element = (TStreamerElement *)info->GetElements()->FindObject(countName);
if (!element) return 0;
if (element->IsA() == TStreamerBasicType::Class()) return (TStreamerBasicType*)element;
return 0;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::GetStreamMemberWise()
{
// Return whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
//
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
return fgStreamMemberWise;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Optimize(Bool_t opt)
{
// This is a static function.
// Set optimization option.
// When this option is activated (default), consecutive data members
// of the same type are merged into an array (faster).
// Optimization must be off in TTree split mode.
fgOptimize = opt;
}
//______________________________________________________________________________
TVirtualStreamerInfo *TVirtualStreamerInfo::Factory()
{
// Static function returning a pointer to a new TVirtualStreamerInfo object.
// If the Info factory does not exist, it is created via the plugin manager.
// In reality the factory is an empty TStreamerInfo object.
if (!fgInfoFactory) {
TPluginHandler *h;
if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualStreamerInfo","TStreamerInfo"))) {
if (h->LoadPlugin() == -1) {
::Fatal("TVirtualStreamerInfo::Factory",
"The plugin handler for TVirtualStreamerInfo was found but failed to load!");
}
fgInfoFactory = (TVirtualStreamerInfo*) h->ExecPlugin(0);
if (fgInfoFactory == 0) {
::Fatal("TVirtualStreamerInfo::Factory",
"The plugin handler for TVirtualStreamerInfo was found but failed to create the factory object!");
}
} else {
TString filename("$ROOTSYS/etc/plugins/TVirtualStreamerInfo");
gSystem->ExpandPathName(filename);
if (gSystem->AccessPathName(filename)) {
::Fatal("TVirtualStreamerInfo::Factory",
"Cannot find the plugin handler for TVirtualStreamerInfo! "
"$ROOTSYS/etc/plugins/TVirtualStreamerInfo does not exist "
"or is inaccessible.");
} else {
::Fatal("TVirtualStreamerInfo::Factory",
"Cannot find the plugin handler for TVirtualStreamerInfo! "
"However $ROOTSYS/etc/plugins/TVirtualStreamerInfo is accessible, "
"Check the content of this directory!");
}
}
}
return fgInfoFactory;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetCanDelete(Bool_t opt)
{
// This is a static function.
// Set object delete option.
// When this option is activated (default), ReadBuffer automatically
// delete objects when a data member is a pointer to an object.
// If your constructor is not presetting pointers to 0, you must
// call this static function TStreamerInfo::SetCanDelete(kFALSE);
fgCanDelete = opt;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::SetFactory(TVirtualStreamerInfo *factory)
{
//static function: Set the StreamerInfo factory
fgInfoFactory = factory;
}
//______________________________________________________________________________
Bool_t TVirtualStreamerInfo::SetStreamMemberWise(Bool_t enable)
{
// Set whether the TStreamerInfos will save the collections in
// "member-wise" order whenever possible. The default is to store member-wise.
// kTRUE indicates member-wise storing
// kFALSE inddicates object-wise storing
// This function returns the previous value of fgStreamMemberWise.
// A collection can be saved member wise when it contain is guaranteed to be
// homogeneous. For example std::vector<THit> can be stored member wise,
// while std::vector<THit*> can not (possible use of polymorphism).
Bool_t prev = fgStreamMemberWise;
fgStreamMemberWise = enable;
return prev;
}
//______________________________________________________________________________
void TVirtualStreamerInfo::Streamer(TBuffer &R__b)
{
// Stream an object of class TVirtualStreamerInfo.
TNamed::Streamer(R__b);
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// configuration.cpp
//
// Identification: benchmark/ycsb/configuration.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#undef NDEBUG
#include <iomanip>
#include <algorithm>
#include "backend/benchmark/ycsb/ycsb_configuration.h"
#include "backend/common/logger.h"
#undef NDEBUG
namespace peloton {
namespace benchmark {
namespace ycsb {
void Usage(FILE *out) {
fprintf(out,
"Command line options : ycsb <options> \n"
" -h --help : Print help message \n"
" -k --scale_factor : # of tuples \n"
" -d --duration : execution duration \n"
" -s --snapshot_duration : snapshot duration \n"
" -c --column_count : # of columns \n"
" -u --write_ratio : Fraction of updates \n"
" -b --backend_count : # of backends \n"
" -l --enable_logging : enable_logging (0 or 1) \n"
" -x --sync_commit : enable synchronous commit (0 or 1) \n"
" -q --flush_freq : set the frequency of log fsync\n");
// TODO add description for wait_time, file_size, log_buffer_size,
// checkpointer
exit(EXIT_FAILURE);
}
static struct option opts[] = {
{"scale_factor", optional_argument, NULL, 'k'},
{"duration", optional_argument, NULL, 'd'},
{"snapshot_duration", optional_argument, NULL, 's'},
{"column_count", optional_argument, NULL, 'c'},
{"update_ratio", optional_argument, NULL, 'u'},
{"backend_count", optional_argument, NULL, 'b'},
{"enable_logging", optional_argument, NULL, 'l'},
{"sync_commit", optional_argument, NULL, 'x'},
{"wait_time", optional_argument, NULL, 'w'},
{"file_size", optional_argument, NULL, 'f'},
{"log_buffer_size", optional_argument, NULL, 'z'},
{"checkpointer", optional_argument, NULL, 'p'},
{"flush_freq", optional_argument, NULL, 'q'},
{NULL, 0, NULL, 0},
};
void ValidateScaleFactor(const configuration &state) {
if (state.scale_factor <= 0) {
LOG_ERROR("Invalid scale_factor :: %d", state.scale_factor);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d", "scale_factor", state.scale_factor);
}
void ValidateColumnCount(const configuration &state) {
if (state.column_count <= 0) {
LOG_ERROR("Invalid column_count :: %d", state.column_count);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d", "column_count", state.column_count);
}
void ValidateUpdateRatio(const configuration &state) {
if (state.update_ratio < 0 || state.update_ratio > 1) {
LOG_ERROR("Invalid update_ratio :: %lf", state.update_ratio);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %lf", "update_ratio", state.update_ratio);
}
void ValidateBackendCount(const configuration &state) {
if (state.backend_count <= 0) {
LOG_ERROR("Invalid backend_count :: %d", state.backend_count);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d", "backend_count", state.backend_count);
}
void ValidateDuration(const configuration &state) {
if (state.duration <= 0) {
LOG_ERROR("Invalid duration :: %lf", state.duration);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %lf", "execution duration", state.duration);
}
void ValidateSnapshotDuration(const configuration &state) {
if (state.snapshot_duration <= 0) {
LOG_ERROR("Invalid snapshot_duration :: %lf", state.snapshot_duration);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %lf", "snapshot_duration", state.snapshot_duration);
}
void ValidateLogging(const configuration &state) {
// I tried setting NDEBUG but I still get an unused error
(void) state;
// TODO validate that sync_commit is enabled only when logging is enabled
LOG_INFO("%s : %d", "logging_enabled", state.logging_enabled);
LOG_INFO("%s : %d", "synchronous_commit", state.sync_commit);
LOG_INFO("%s : %d", "wait_time", (int)state.wait_timeout);
}
void ValidateFlushFreq(const configuration &state) {
if (state.flush_freq <= 0) {
LOG_ERROR("Invalid flush_freq :: %d", state.flush_freq);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d microseconds", "flush_freq", state.flush_freq);
}
void ParseArguments(int argc, char *argv[], configuration &state) {
// Default Values
state.scale_factor = 1;
state.duration = 10;
state.snapshot_duration = 0.1;
state.column_count = 10;
state.update_ratio = 0.5;
state.backend_count = 2;
state.logging_enabled = 0;
state.sync_commit = 0;
state.wait_timeout = 0;
state.file_size = 32;
state.log_buffer_size = 32768;
state.checkpointer = 0;
state.flush_freq = 0;
// Parse args
while (1) {
int idx = 0;
int c = getopt_long(argc, argv, "ahk:d:s:c:u:b:l:x:w:f:z:p:q:", opts, &idx);
if (c == -1) break;
switch (c) {
case 'k':
state.scale_factor = atoi(optarg);
break;
case 'd':
state.duration = atof(optarg);
break;
case 's':
state.snapshot_duration = atof(optarg);
break;
case 'c':
state.column_count = atoi(optarg);
break;
case 'u':
state.update_ratio = atof(optarg);
break;
case 'b':
state.backend_count = atoi(optarg);
break;
case 'x':
state.sync_commit = atoi(optarg);
break;
case 'l':
state.logging_enabled = atoi(optarg);
break;
case 'w':
state.wait_timeout = atol(optarg);
break;
case 'f':
state.file_size = atoi(optarg);
break;
case 'z':
state.log_buffer_size = atoi(optarg);
break;
case 'p':
state.checkpointer = atoi(optarg);
break;
case 'q':
state.flush_freq = atoi(optarg);
break;
case 'h':
Usage(stderr);
exit(EXIT_FAILURE);
break;
default:
fprintf(stderr, "\nUnknown option: -%c-\n", c);
Usage(stderr);
exit(EXIT_FAILURE);
}
}
// Print configuration
ValidateScaleFactor(state);
ValidateColumnCount(state);
ValidateUpdateRatio(state);
ValidateBackendCount(state);
ValidateLogging(state);
ValidateDuration(state);
ValidateSnapshotDuration(state);
ValidateFlushFreq(state);
}
} // namespace ycsb
} // namespace benchmark
} // namespace peloton
<commit_msg>allow 0us flush time in ycsb<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// configuration.cpp
//
// Identification: benchmark/ycsb/configuration.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#undef NDEBUG
#include <iomanip>
#include <algorithm>
#include "backend/benchmark/ycsb/ycsb_configuration.h"
#include "backend/common/logger.h"
#undef NDEBUG
namespace peloton {
namespace benchmark {
namespace ycsb {
void Usage(FILE *out) {
fprintf(out,
"Command line options : ycsb <options> \n"
" -h --help : Print help message \n"
" -k --scale_factor : # of tuples \n"
" -d --duration : execution duration \n"
" -s --snapshot_duration : snapshot duration \n"
" -c --column_count : # of columns \n"
" -u --write_ratio : Fraction of updates \n"
" -b --backend_count : # of backends \n"
" -l --enable_logging : enable_logging (0 or 1) \n"
" -x --sync_commit : enable synchronous commit (0 or 1) \n"
" -q --flush_freq : set the frequency of log fsync\n");
// TODO add description for wait_time, file_size, log_buffer_size,
// checkpointer
exit(EXIT_FAILURE);
}
static struct option opts[] = {
{"scale_factor", optional_argument, NULL, 'k'},
{"duration", optional_argument, NULL, 'd'},
{"snapshot_duration", optional_argument, NULL, 's'},
{"column_count", optional_argument, NULL, 'c'},
{"update_ratio", optional_argument, NULL, 'u'},
{"backend_count", optional_argument, NULL, 'b'},
{"enable_logging", optional_argument, NULL, 'l'},
{"sync_commit", optional_argument, NULL, 'x'},
{"wait_time", optional_argument, NULL, 'w'},
{"file_size", optional_argument, NULL, 'f'},
{"log_buffer_size", optional_argument, NULL, 'z'},
{"checkpointer", optional_argument, NULL, 'p'},
{"flush_freq", optional_argument, NULL, 'q'},
{NULL, 0, NULL, 0},
};
void ValidateScaleFactor(const configuration &state) {
if (state.scale_factor <= 0) {
LOG_ERROR("Invalid scale_factor :: %d", state.scale_factor);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d", "scale_factor", state.scale_factor);
}
void ValidateColumnCount(const configuration &state) {
if (state.column_count <= 0) {
LOG_ERROR("Invalid column_count :: %d", state.column_count);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d", "column_count", state.column_count);
}
void ValidateUpdateRatio(const configuration &state) {
if (state.update_ratio < 0 || state.update_ratio > 1) {
LOG_ERROR("Invalid update_ratio :: %lf", state.update_ratio);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %lf", "update_ratio", state.update_ratio);
}
void ValidateBackendCount(const configuration &state) {
if (state.backend_count <= 0) {
LOG_ERROR("Invalid backend_count :: %d", state.backend_count);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d", "backend_count", state.backend_count);
}
void ValidateDuration(const configuration &state) {
if (state.duration <= 0) {
LOG_ERROR("Invalid duration :: %lf", state.duration);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %lf", "execution duration", state.duration);
}
void ValidateSnapshotDuration(const configuration &state) {
if (state.snapshot_duration <= 0) {
LOG_ERROR("Invalid snapshot_duration :: %lf", state.snapshot_duration);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %lf", "snapshot_duration", state.snapshot_duration);
}
void ValidateLogging(const configuration &state) {
// I tried setting NDEBUG but I still get an unused error
(void) state;
// TODO validate that sync_commit is enabled only when logging is enabled
LOG_INFO("%s : %d", "logging_enabled", state.logging_enabled);
LOG_INFO("%s : %d", "synchronous_commit", state.sync_commit);
LOG_INFO("%s : %d", "wait_time", (int)state.wait_timeout);
}
void ValidateFlushFreq(const configuration &state) {
if (state.flush_freq < 0) {
LOG_ERROR("Invalid flush_freq :: %d", state.flush_freq);
exit(EXIT_FAILURE);
}
LOG_INFO("%s : %d microseconds", "flush_freq", state.flush_freq);
}
void ParseArguments(int argc, char *argv[], configuration &state) {
// Default Values
state.scale_factor = 1;
state.duration = 10;
state.snapshot_duration = 0.1;
state.column_count = 10;
state.update_ratio = 0.5;
state.backend_count = 2;
state.logging_enabled = 0;
state.sync_commit = 0;
state.wait_timeout = 0;
state.file_size = 32;
state.log_buffer_size = 32768;
state.checkpointer = 0;
state.flush_freq = 0;
// Parse args
while (1) {
int idx = 0;
int c = getopt_long(argc, argv, "ahk:d:s:c:u:b:l:x:w:f:z:p:q:", opts, &idx);
if (c == -1) break;
switch (c) {
case 'k':
state.scale_factor = atoi(optarg);
break;
case 'd':
state.duration = atof(optarg);
break;
case 's':
state.snapshot_duration = atof(optarg);
break;
case 'c':
state.column_count = atoi(optarg);
break;
case 'u':
state.update_ratio = atof(optarg);
break;
case 'b':
state.backend_count = atoi(optarg);
break;
case 'x':
state.sync_commit = atoi(optarg);
break;
case 'l':
state.logging_enabled = atoi(optarg);
break;
case 'w':
state.wait_timeout = atol(optarg);
break;
case 'f':
state.file_size = atoi(optarg);
break;
case 'z':
state.log_buffer_size = atoi(optarg);
break;
case 'p':
state.checkpointer = atoi(optarg);
break;
case 'q':
state.flush_freq = atoi(optarg);
break;
case 'h':
Usage(stderr);
exit(EXIT_FAILURE);
break;
default:
fprintf(stderr, "\nUnknown option: -%c-\n", c);
Usage(stderr);
exit(EXIT_FAILURE);
}
}
// Print configuration
ValidateScaleFactor(state);
ValidateColumnCount(state);
ValidateUpdateRatio(state);
ValidateBackendCount(state);
ValidateLogging(state);
ValidateDuration(state);
ValidateSnapshotDuration(state);
ValidateFlushFreq(state);
}
} // namespace ycsb
} // namespace benchmark
} // namespace peloton
<|endoftext|>
|
<commit_before>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/**************************************************************************
Connections
Commonality across all platforms -- move out as required.
**************************************************************************/
#include "libts.h"
#include "P_Net.h"
#define SET_TCP_NO_DELAY
#define SET_NO_LINGER
// set in the OS
// #define RECV_BUF_SIZE (1024*64)
// #define SEND_BUF_SIZE (1024*64)
#define FIRST_RANDOM_PORT 16000
#define LAST_RANDOM_PORT 32000
#define ROUNDUP(x, y) ((((x)+((y)-1))/(y))*(y))
#ifndef FD_CLOEXEC
#define FD_CLOEXEC 1
#endif
int
get_listen_backlog(void)
{
int listen_backlog = 1024;
REC_ReadConfigInteger(listen_backlog, "proxy.config.net.listen_backlog");
return listen_backlog;
}
//
// Functions
//
char const*
NetVCOptions::toString(addr_bind_style s) {
return ANY_ADDR == s ? "any"
: INTF_ADDR == s ? "interface"
: "foreign"
;
}
Connection::Connection()
: fd(NO_FD)
, is_bound(false)
, is_connected(false)
, sock_type(0)
{
memset(&addr, 0, sizeof(addr));
}
Connection::~Connection()
{
close();
}
int
Server::accept(Connection * c)
{
int res = 0;
socklen_t sz = sizeof(c->addr);
res = socketManager.accept(fd, &c->addr.sa, &sz);
if (res < 0)
return res;
c->fd = res;
if (is_debug_tag_set("iocore_net_server")) {
ip_port_text_buffer ipb1, ipb2;
Debug("iocore_net_server", "Connection accepted [Server]. %s -> %s\n"
, ats_ip_nptop(&c->addr, ipb2, sizeof(ipb2))
, ats_ip_nptop(&addr, ipb1, sizeof(ipb1))
);
}
#ifdef SET_CLOSE_ON_EXEC
if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0)
goto Lerror;
#endif
if ((res = safe_nonblocking(c->fd)) < 0)
goto Lerror;
#ifdef SEND_BUF_SIZE
socketManager.set_sndbuf_size(c->fd, SEND_BUF_SIZE);
#endif
#ifdef SET_SO_KEEPALIVE
// enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, SOCKOPT_ON, sizeof(int))) < 0)
goto Lerror;
#endif
return 0;
Lerror:
c->close();
return res;
}
int
Connection::close()
{
is_connected = false;
is_bound = false;
// don't close any of the standards
if (fd >= 2) {
int fd_save = fd;
fd = NO_FD;
return socketManager.close(fd_save);
} else {
fd = NO_FD;
return -EBADF;
}
}
static int
add_http_filter(int fd ATS_UNUSED)
{
int err = -1;
#if defined(SOL_FILTER) && defined(FIL_ATTACH)
err = setsockopt(fd, SOL_FILTER, FIL_ATTACH, "httpfilt", 9);
#endif
return err;
}
int
Server::setup_fd_for_listen(
bool non_blocking,
int recv_bufsize,
int send_bufsize,
bool transparent)
{
int res = 0;
ink_assert(fd != NO_FD);
if (http_accept_filter) {
add_http_filter(fd);
}
#ifdef SEND_BUF_SIZE
{
int send_buf_size = SEND_BUF_SIZE;
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &send_buf_size, sizeof(int)) < 0)) {
goto Lerror;
}
}
#endif
#ifdef RECV_BUF_SIZE
{
int recv_buf_size = RECV_BUF_SIZE;
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &recv_buf_size, sizeof(int))) < 0) {
goto Lerror;
}
}
#endif
if (recv_bufsize) {
if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) {
// Round down until success
int rbufsz = ROUNDUP(recv_bufsize, 1024);
while (rbufsz) {
if (socketManager.set_rcvbuf_size(fd, rbufsz)) {
rbufsz -= 1024;
} else {
break;
}
}
}
}
if (send_bufsize) {
if (socketManager.set_sndbuf_size(fd, send_bufsize)) {
// Round down until success
int sbufsz = ROUNDUP(send_bufsize, 1024);
while (sbufsz) {
if (socketManager.set_sndbuf_size(fd, sbufsz)) {
sbufsz -= 1024;
} else {
break;
}
}
}
}
#ifdef SET_CLOSE_ON_EXEC
if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) {
goto Lerror;
}
#endif
#ifdef SET_NO_LINGER
{
struct linger l;
l.l_onoff = 0;
l.l_linger = 0;
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof(l))) < 0) {
goto Lerror;
}
}
#endif
if (ats_is_ip6(&addr) && (res = safe_setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
if ((res = socketManager.ink_bind(fd, &addr.sa, ats_ip_size(&addr.sa), IPPROTO_TCP)) < 0) {
goto Lerror;
}
#ifdef SET_TCP_NO_DELAY
if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
#endif
#ifdef SET_SO_KEEPALIVE
// enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
#endif
if (transparent) {
#if TS_USE_TPROXY
Debug("http_tproxy", "Listen port inbound transparency enabled.\n");
if (safe_setsockopt(fd, SOL_IP, TS_IP_TRANSPARENT, SOCKOPT_ON, sizeof(int)) < 0) {
Error("[Server::listen] Unable to set transparent socket option [%d] %s\n", errno, strerror(errno));
_exit(1);
}
#else
Error("[Server::listen] Transparency requested but TPROXY not configured\n");
#endif
}
#if defined(TCP_MAXSEG)
if (NetProcessor::accept_mss > 0) {
if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *) &NetProcessor::accept_mss, sizeof(int))) < 0) {
goto Lerror;
}
}
#endif
if (non_blocking) {
if ((res = safe_nonblocking(fd)) < 0) {
goto Lerror;
}
}
return 0;
Lerror:
res = -errno;
// coverity[check_after_sink]
if (fd != NO_FD) {
close();
fd = NO_FD;
}
return res;
}
int
Server::listen(bool non_blocking, int recv_bufsize, int send_bufsize, bool transparent)
{
ink_assert(fd == NO_FD);
int res = 0;
int namelen;
if (!ats_is_ip(&accept_addr)) {
ats_ip4_set(&addr, INADDR_ANY, 0);
} else {
ats_ip_copy(&addr, &accept_addr);
}
fd = res = socketManager.socket(addr.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
if (res < 0) {
goto Lerror;
}
res = setup_fd_for_listen(non_blocking, recv_bufsize, send_bufsize, transparent);
if (res < 0) {
goto Lerror;
}
if ((res = safe_listen(fd, get_listen_backlog())) < 0) {
goto Lerror;
}
// Original just did this on port == 0.
namelen = sizeof(addr);
if ((res = safe_getsockname(fd, &addr.sa, &namelen))) {
goto Lerror;
}
return 0;
Lerror:
if (fd != NO_FD) {
close();
fd = NO_FD;
}
Error("Could not bind or listen to port %d (error: %d)", ats_ip_port_host_order(&addr), res);
return res;
}
<commit_msg>TS-1909: Fix trafic_cop socket binding<commit_after>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/**************************************************************************
Connections
Commonality across all platforms -- move out as required.
**************************************************************************/
#include "libts.h"
#include "P_Net.h"
#define SET_TCP_NO_DELAY
#define SET_NO_LINGER
// set in the OS
// #define RECV_BUF_SIZE (1024*64)
// #define SEND_BUF_SIZE (1024*64)
#define FIRST_RANDOM_PORT 16000
#define LAST_RANDOM_PORT 32000
#define ROUNDUP(x, y) ((((x)+((y)-1))/(y))*(y))
#ifndef FD_CLOEXEC
#define FD_CLOEXEC 1
#endif
int
get_listen_backlog(void)
{
int listen_backlog = 1024;
REC_ReadConfigInteger(listen_backlog, "proxy.config.net.listen_backlog");
return listen_backlog;
}
//
// Functions
//
char const*
NetVCOptions::toString(addr_bind_style s) {
return ANY_ADDR == s ? "any"
: INTF_ADDR == s ? "interface"
: "foreign"
;
}
Connection::Connection()
: fd(NO_FD)
, is_bound(false)
, is_connected(false)
, sock_type(0)
{
memset(&addr, 0, sizeof(addr));
}
Connection::~Connection()
{
close();
}
int
Server::accept(Connection * c)
{
int res = 0;
socklen_t sz = sizeof(c->addr);
res = socketManager.accept(fd, &c->addr.sa, &sz);
if (res < 0)
return res;
c->fd = res;
if (is_debug_tag_set("iocore_net_server")) {
ip_port_text_buffer ipb1, ipb2;
Debug("iocore_net_server", "Connection accepted [Server]. %s -> %s\n"
, ats_ip_nptop(&c->addr, ipb2, sizeof(ipb2))
, ats_ip_nptop(&addr, ipb1, sizeof(ipb1))
);
}
#ifdef SET_CLOSE_ON_EXEC
if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0)
goto Lerror;
#endif
if ((res = safe_nonblocking(c->fd)) < 0)
goto Lerror;
#ifdef SEND_BUF_SIZE
socketManager.set_sndbuf_size(c->fd, SEND_BUF_SIZE);
#endif
#ifdef SET_SO_KEEPALIVE
// enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, SOCKOPT_ON, sizeof(int))) < 0)
goto Lerror;
#endif
return 0;
Lerror:
c->close();
return res;
}
int
Connection::close()
{
is_connected = false;
is_bound = false;
// don't close any of the standards
if (fd >= 2) {
int fd_save = fd;
fd = NO_FD;
return socketManager.close(fd_save);
} else {
fd = NO_FD;
return -EBADF;
}
}
static int
add_http_filter(int fd ATS_UNUSED)
{
int err = -1;
#if defined(SOL_FILTER) && defined(FIL_ATTACH)
err = setsockopt(fd, SOL_FILTER, FIL_ATTACH, "httpfilt", 9);
#endif
return err;
}
int
Server::setup_fd_for_listen(
bool non_blocking,
int recv_bufsize,
int send_bufsize,
bool transparent)
{
int res = 0;
ink_assert(fd != NO_FD);
if (http_accept_filter) {
add_http_filter(fd);
}
#ifdef SEND_BUF_SIZE
{
int send_buf_size = SEND_BUF_SIZE;
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &send_buf_size, sizeof(int)) < 0)) {
goto Lerror;
}
}
#endif
#ifdef RECV_BUF_SIZE
{
int recv_buf_size = RECV_BUF_SIZE;
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &recv_buf_size, sizeof(int))) < 0) {
goto Lerror;
}
}
#endif
if (recv_bufsize) {
if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) {
// Round down until success
int rbufsz = ROUNDUP(recv_bufsize, 1024);
while (rbufsz) {
if (socketManager.set_rcvbuf_size(fd, rbufsz)) {
rbufsz -= 1024;
} else {
break;
}
}
}
}
if (send_bufsize) {
if (socketManager.set_sndbuf_size(fd, send_bufsize)) {
// Round down until success
int sbufsz = ROUNDUP(send_bufsize, 1024);
while (sbufsz) {
if (socketManager.set_sndbuf_size(fd, sbufsz)) {
sbufsz -= 1024;
} else {
break;
}
}
}
}
#ifdef SET_CLOSE_ON_EXEC
if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) {
goto Lerror;
}
#endif
#ifdef SET_NO_LINGER
{
struct linger l;
l.l_onoff = 0;
l.l_linger = 0;
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof(l))) < 0) {
goto Lerror;
}
}
#endif
if (ats_is_ip6(&addr) && (res = safe_setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
#ifdef SET_TCP_NO_DELAY
if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
#endif
#ifdef SET_SO_KEEPALIVE
// enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak
if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
}
#endif
if (transparent) {
#if TS_USE_TPROXY
Debug("http_tproxy", "Listen port inbound transparency enabled.\n");
if (safe_setsockopt(fd, SOL_IP, TS_IP_TRANSPARENT, SOCKOPT_ON, sizeof(int)) < 0) {
Error("[Server::listen] Unable to set transparent socket option [%d] %s\n", errno, strerror(errno));
_exit(1);
}
#else
Error("[Server::listen] Transparency requested but TPROXY not configured\n");
#endif
}
#if defined(TCP_MAXSEG)
if (NetProcessor::accept_mss > 0) {
if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *) &NetProcessor::accept_mss, sizeof(int))) < 0) {
goto Lerror;
}
}
#endif
if (non_blocking) {
if ((res = safe_nonblocking(fd)) < 0) {
goto Lerror;
}
}
return 0;
Lerror:
res = -errno;
// coverity[check_after_sink]
if (fd != NO_FD) {
close();
fd = NO_FD;
}
return res;
}
int
Server::listen(bool non_blocking, int recv_bufsize, int send_bufsize, bool transparent)
{
ink_assert(fd == NO_FD);
int res = 0;
int namelen;
if (!ats_is_ip(&accept_addr)) {
ats_ip4_set(&addr, INADDR_ANY, 0);
} else {
ats_ip_copy(&addr, &accept_addr);
}
fd = res = socketManager.socket(addr.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
if (res < 0) {
goto Lerror;
}
res = setup_fd_for_listen(non_blocking, recv_bufsize, send_bufsize, transparent);
if (res < 0) {
goto Lerror;
}
if ((res = socketManager.ink_bind(fd, &addr.sa, ats_ip_size(&addr.sa), IPPROTO_TCP)) < 0) {
goto Lerror;
}
if ((res = safe_listen(fd, get_listen_backlog())) < 0) {
goto Lerror;
}
// Original just did this on port == 0.
namelen = sizeof(addr);
if ((res = safe_getsockname(fd, &addr.sa, &namelen))) {
goto Lerror;
}
return 0;
Lerror:
if (fd != NO_FD) {
close();
fd = NO_FD;
}
Error("Could not bind or listen to port %d (error: %d)", ats_ip_port_host_order(&addr), res);
return res;
}
<|endoftext|>
|
<commit_before>//
// ClockReceiver.hpp
// Clock Signal
//
// Created by Thomas Harte on 22/07/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#ifndef ClockReceiver_hpp
#define ClockReceiver_hpp
/*
Informal pattern for all classes that run from a clock cycle:
Each will implement either or both of run_for(Cycles) and run_for(HalfCycles), as
is appropriate.
Callers that are accumulating HalfCycles but want to talk to receivers that implement
only run_for(Cycles) can use HalfCycle.flush_cycles if they have appropriate storage, or
can wrap the receiver in HalfClockReceiver in order automatically to bind half-cycle
storage to it.
Alignment rule:
run_for(Cycles) may be called only after an even number of half cycles. E.g. the following
sequence will have undefined results:
run_for(HalfCycles(1))
run_for(Cycles(1))
An easy way to ensure this as a caller is to pick only one of run_for(Cycles) and
run_for(HalfCycles) to use.
Reasoning:
Users of this template may with to implement run_for(Cycles) and run_for(HalfCycles)
where there is a need to implement at half-cycle precision but a faster execution
path can be offered for full-cycle precision. Those users are permitted to assume
phase in run_for(Cycles) and should do so to be compatible with callers that use
only run_for(Cycles).
Corollary:
Starting from nothing, the first run_for(HalfCycles(1)) will do the **first** half
of a full cycle. The second will do the second half. Etc.
*/
/*!
Provides a class that wraps a plain int, providing most of the basic arithmetic and
Boolean operators, but forcing callers and receivers to be explicit as to usage.
*/
template <class T> class WrappedInt {
public:
constexpr WrappedInt(int l) : length_(l) {}
constexpr WrappedInt() : length_(0) {}
constexpr T &operator =(const T &rhs) {
length_ = rhs.length_;
return *this;
}
constexpr T &operator +=(const T &rhs) {
length_ += rhs.length_;
return *static_cast<T *>(this);
}
constexpr T &operator -=(const T &rhs) {
length_ -= rhs.length_;
return *static_cast<T *>(this);
}
constexpr T &operator ++() {
++ length_;
return *static_cast<T *>(this);
}
constexpr T &operator ++(int) {
length_ ++;
return *static_cast<T *>(this);
}
constexpr T &operator --() {
-- length_;
return *static_cast<T *>(this);
}
constexpr T &operator --(int) {
length_ --;
return *static_cast<T *>(this);
}
constexpr T &operator %=(const T &rhs) {
length_ %= rhs.length_;
return *static_cast<T *>(this);
}
constexpr T &operator &=(const T &rhs) {
length_ &= rhs.length_;
return *static_cast<T *>(this);
}
constexpr T operator +(const T &rhs) const { return T(length_ + rhs.length_); }
constexpr T operator -(const T &rhs) const { return T(length_ - rhs.length_); }
constexpr T operator %(const T &rhs) const { return T(length_ % rhs.length_); }
constexpr T operator &(const T &rhs) const { return T(length_ & rhs.length_); }
constexpr T operator -() const { return T(- length_); }
constexpr bool operator <(const T &rhs) const { return length_ < rhs.length_; }
constexpr bool operator >(const T &rhs) const { return length_ > rhs.length_; }
constexpr bool operator <=(const T &rhs) const { return length_ <= rhs.length_; }
constexpr bool operator >=(const T &rhs) const { return length_ >= rhs.length_; }
constexpr bool operator ==(const T &rhs) const { return length_ == rhs.length_; }
constexpr bool operator !=(const T &rhs) const { return length_ != rhs.length_; }
constexpr bool operator !() const { return !length_; }
// bool operator () is not supported because it offers an implicit cast to int, which is prone silently to permit misuse
constexpr int as_int() const { return length_; }
/*!
Severs from @c this the effect of dividing by @c divisor; @c this will end up with
the value of @c this modulo @c divisor and @c divided by @c divisor is returned.
*/
constexpr T divide(const T &divisor) {
T result(length_ / divisor.length_);
length_ %= divisor.length_;
return result;
}
/*!
Flushes the value in @c this. The current value is returned, and the internal value
is reset to zero.
*/
constexpr T flush() {
T result(length_);
length_ = 0;
return result;
}
// operator int() is deliberately not provided, to avoid accidental subtitution of
// classes that use this template.
protected:
int length_;
};
/// Describes an integer number of whole cycles: pairs of clock signal transitions.
class Cycles: public WrappedInt<Cycles> {
public:
constexpr Cycles(int l) : WrappedInt<Cycles>(l) {}
constexpr Cycles() : WrappedInt<Cycles>() {}
constexpr Cycles(const Cycles &cycles) : WrappedInt<Cycles>(cycles.length_) {}
};
/// Describes an integer number of half cycles: single clock signal transitions.
class HalfCycles: public WrappedInt<HalfCycles> {
public:
constexpr HalfCycles(int l) : WrappedInt<HalfCycles>(l) {}
constexpr HalfCycles() : WrappedInt<HalfCycles>() {}
constexpr HalfCycles(const Cycles cycles) : WrappedInt<HalfCycles>(cycles.as_int() * 2) {}
constexpr HalfCycles(const HalfCycles &half_cycles) : WrappedInt<HalfCycles>(half_cycles.length_) {}
/// @returns The number of whole cycles completely covered by this span of half cycles.
constexpr Cycles cycles() {
return Cycles(length_ >> 1);
}
/// Flushes the whole cycles in @c this, subtracting that many from the total stored here.
constexpr Cycles flush_cycles() {
Cycles result(length_ >> 1);
length_ &= 1;
return result;
}
/// Flushes the half cycles in @c this, returning the number stored and setting this total to zero.
constexpr HalfCycles flush() {
HalfCycles result(length_);
length_ = 0;
return result;
}
/*!
Severs from @c this the effect of dividing by @c divisor; @c this will end up with
the value of @c this modulo @c divisor and @c divided by @c divisor is returned.
*/
constexpr Cycles divide_cycles(const Cycles &divisor) {
HalfCycles half_divisor = HalfCycles(divisor);
Cycles result(length_ / half_divisor.length_);
length_ %= half_divisor.length_;
return result;
}
};
/*!
If a component implements only run_for(Cycles), an owner can wrap it in HalfClockReceiver
automatically to gain run_for(HalfCycles).
*/
template <class T> class HalfClockReceiver: public T {
public:
using T::T;
inline void run_for(const HalfCycles half_cycles) {
half_cycles_ += half_cycles;
T::run_for(half_cycles_.flush_cycles());
}
private:
HalfCycles half_cycles_;
};
#endif /* ClockReceiver_hpp */
<commit_msg>Removes `constexpr` from things which are not const. Duh.<commit_after>//
// ClockReceiver.hpp
// Clock Signal
//
// Created by Thomas Harte on 22/07/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#ifndef ClockReceiver_hpp
#define ClockReceiver_hpp
/*
Informal pattern for all classes that run from a clock cycle:
Each will implement either or both of run_for(Cycles) and run_for(HalfCycles), as
is appropriate.
Callers that are accumulating HalfCycles but want to talk to receivers that implement
only run_for(Cycles) can use HalfCycle.flush_cycles if they have appropriate storage, or
can wrap the receiver in HalfClockReceiver in order automatically to bind half-cycle
storage to it.
Alignment rule:
run_for(Cycles) may be called only after an even number of half cycles. E.g. the following
sequence will have undefined results:
run_for(HalfCycles(1))
run_for(Cycles(1))
An easy way to ensure this as a caller is to pick only one of run_for(Cycles) and
run_for(HalfCycles) to use.
Reasoning:
Users of this template may with to implement run_for(Cycles) and run_for(HalfCycles)
where there is a need to implement at half-cycle precision but a faster execution
path can be offered for full-cycle precision. Those users are permitted to assume
phase in run_for(Cycles) and should do so to be compatible with callers that use
only run_for(Cycles).
Corollary:
Starting from nothing, the first run_for(HalfCycles(1)) will do the **first** half
of a full cycle. The second will do the second half. Etc.
*/
/*!
Provides a class that wraps a plain int, providing most of the basic arithmetic and
Boolean operators, but forcing callers and receivers to be explicit as to usage.
*/
template <class T> class WrappedInt {
public:
constexpr WrappedInt(int l) : length_(l) {}
constexpr WrappedInt() : length_(0) {}
constexpr T &operator =(const T &rhs) {
length_ = rhs.length_;
return *this;
}
constexpr T &operator +=(const T &rhs) {
length_ += rhs.length_;
return *static_cast<T *>(this);
}
constexpr T &operator -=(const T &rhs) {
length_ -= rhs.length_;
return *static_cast<T *>(this);
}
T &operator ++() {
++ length_;
return *static_cast<T *>(this);
}
T &operator ++(int) {
length_ ++;
return *static_cast<T *>(this);
}
T &operator --() {
-- length_;
return *static_cast<T *>(this);
}
T &operator --(int) {
length_ --;
return *static_cast<T *>(this);
}
T &operator %=(const T &rhs) {
length_ %= rhs.length_;
return *static_cast<T *>(this);
}
T &operator &=(const T &rhs) {
length_ &= rhs.length_;
return *static_cast<T *>(this);
}
constexpr T operator +(const T &rhs) const { return T(length_ + rhs.length_); }
constexpr T operator -(const T &rhs) const { return T(length_ - rhs.length_); }
constexpr T operator %(const T &rhs) const { return T(length_ % rhs.length_); }
constexpr T operator &(const T &rhs) const { return T(length_ & rhs.length_); }
constexpr T operator -() const { return T(- length_); }
constexpr bool operator <(const T &rhs) const { return length_ < rhs.length_; }
constexpr bool operator >(const T &rhs) const { return length_ > rhs.length_; }
constexpr bool operator <=(const T &rhs) const { return length_ <= rhs.length_; }
constexpr bool operator >=(const T &rhs) const { return length_ >= rhs.length_; }
constexpr bool operator ==(const T &rhs) const { return length_ == rhs.length_; }
constexpr bool operator !=(const T &rhs) const { return length_ != rhs.length_; }
constexpr bool operator !() const { return !length_; }
// bool operator () is not supported because it offers an implicit cast to int, which is prone silently to permit misuse
constexpr int as_int() const { return length_; }
/*!
Severs from @c this the effect of dividing by @c divisor; @c this will end up with
the value of @c this modulo @c divisor and @c divided by @c divisor is returned.
*/
T divide(const T &divisor) {
T result(length_ / divisor.length_);
length_ %= divisor.length_;
return result;
}
/*!
Flushes the value in @c this. The current value is returned, and the internal value
is reset to zero.
*/
T flush() {
T result(length_);
length_ = 0;
return result;
}
// operator int() is deliberately not provided, to avoid accidental subtitution of
// classes that use this template.
protected:
int length_;
};
/// Describes an integer number of whole cycles: pairs of clock signal transitions.
class Cycles: public WrappedInt<Cycles> {
public:
constexpr Cycles(int l) : WrappedInt<Cycles>(l) {}
constexpr Cycles() : WrappedInt<Cycles>() {}
constexpr Cycles(const Cycles &cycles) : WrappedInt<Cycles>(cycles.length_) {}
};
/// Describes an integer number of half cycles: single clock signal transitions.
class HalfCycles: public WrappedInt<HalfCycles> {
public:
constexpr HalfCycles(int l) : WrappedInt<HalfCycles>(l) {}
constexpr HalfCycles() : WrappedInt<HalfCycles>() {}
constexpr HalfCycles(const Cycles cycles) : WrappedInt<HalfCycles>(cycles.as_int() * 2) {}
constexpr HalfCycles(const HalfCycles &half_cycles) : WrappedInt<HalfCycles>(half_cycles.length_) {}
/// @returns The number of whole cycles completely covered by this span of half cycles.
constexpr Cycles cycles() {
return Cycles(length_ >> 1);
}
/// Flushes the whole cycles in @c this, subtracting that many from the total stored here.
Cycles flush_cycles() {
Cycles result(length_ >> 1);
length_ &= 1;
return result;
}
/// Flushes the half cycles in @c this, returning the number stored and setting this total to zero.
HalfCycles flush() {
HalfCycles result(length_);
length_ = 0;
return result;
}
/*!
Severs from @c this the effect of dividing by @c divisor; @c this will end up with
the value of @c this modulo @c divisor and @c divided by @c divisor is returned.
*/
Cycles divide_cycles(const Cycles &divisor) {
HalfCycles half_divisor = HalfCycles(divisor);
Cycles result(length_ / half_divisor.length_);
length_ %= half_divisor.length_;
return result;
}
};
/*!
If a component implements only run_for(Cycles), an owner can wrap it in HalfClockReceiver
automatically to gain run_for(HalfCycles).
*/
template <class T> class HalfClockReceiver: public T {
public:
using T::T;
inline void run_for(const HalfCycles half_cycles) {
half_cycles_ += half_cycles;
T::run_for(half_cycles_.flush_cycles());
}
private:
HalfCycles half_cycles_;
};
#endif /* ClockReceiver_hpp */
<|endoftext|>
|
<commit_before>//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "test_utils/ANGLETest.h"
using namespace angle;
namespace
{
class UniformTest : public ANGLETest
{
protected:
UniformTest()
: mProgram(0),
mUniformFLocation(-1),
mUniformILocation(-1),
mUniformBLocation(-1)
{
setWindowWidth(128);
setWindowHeight(128);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
}
void SetUp() override
{
ANGLETest::SetUp();
const std::string &vertexShader = "void main() { gl_Position = vec4(1); }";
const std::string &fragShader =
"precision mediump float;\n"
"uniform float uniF;\n"
"uniform int uniI;\n"
"uniform bool uniB;\n"
"void main() { gl_FragColor = vec4(uniF + float(uniI) + (uniB ? 1.0 : 0.0)); }";
mProgram = CompileProgram(vertexShader, fragShader);
ASSERT_NE(mProgram, 0u);
mUniformFLocation = glGetUniformLocation(mProgram, "uniF");
ASSERT_NE(mUniformFLocation, -1);
mUniformILocation = glGetUniformLocation(mProgram, "uniI");
ASSERT_NE(mUniformILocation, -1);
mUniformBLocation = glGetUniformLocation(mProgram, "uniB");
ASSERT_NE(mUniformBLocation, -1);
ASSERT_GL_NO_ERROR();
}
void TearDown() override
{
glDeleteProgram(mProgram);
ANGLETest::TearDown();
}
GLuint mProgram;
GLint mUniformFLocation;
GLint mUniformILocation;
GLint mUniformBLocation;
};
TEST_P(UniformTest, GetUniformNoCurrentProgram)
{
glUseProgram(mProgram);
glUniform1f(mUniformFLocation, 1.0f);
glUniform1i(mUniformILocation, 1);
glUseProgram(0);
GLfloat f;
glGetnUniformfvEXT(mProgram, mUniformFLocation, 4, &f);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1.0f, f);
glGetUniformfv(mProgram, mUniformFLocation, &f);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1.0f, f);
GLint i;
glGetnUniformivEXT(mProgram, mUniformILocation, 4, &i);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1, i);
glGetUniformiv(mProgram, mUniformILocation, &i);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1, i);
}
TEST_P(UniformTest, UniformArrayLocations)
{
// TODO(geofflang): Figure out why this is broken on Intel OpenGL
if (isIntel() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE)
{
std::cout << "Test skipped on Intel OpenGL." << std::endl;
return;
}
const std::string vertexShader = SHADER_SOURCE
(
precision mediump float;
uniform float uPosition[4];
void main(void)
{
gl_Position = vec4(uPosition[0], uPosition[1], uPosition[2], uPosition[3]);
}
);
const std::string fragShader = SHADER_SOURCE
(
precision mediump float;
uniform float uColor[4];
void main(void)
{
gl_FragColor = vec4(uColor[0], uColor[1], uColor[2], uColor[3]);
}
);
GLuint program = CompileProgram(vertexShader, fragShader);
ASSERT_NE(program, 0u);
// Array index zero should be equivalent to the un-indexed uniform
EXPECT_NE(-1, glGetUniformLocation(program, "uPosition"));
EXPECT_EQ(glGetUniformLocation(program, "uPosition"), glGetUniformLocation(program, "uPosition[0]"));
EXPECT_NE(-1, glGetUniformLocation(program, "uColor"));
EXPECT_EQ(glGetUniformLocation(program, "uColor"), glGetUniformLocation(program, "uColor[0]"));
// All array uniform locations should be unique
GLint positionLocations[4] =
{
glGetUniformLocation(program, "uPosition[0]"),
glGetUniformLocation(program, "uPosition[1]"),
glGetUniformLocation(program, "uPosition[2]"),
glGetUniformLocation(program, "uPosition[3]"),
};
GLint colorLocations[4] =
{
glGetUniformLocation(program, "uColor[0]"),
glGetUniformLocation(program, "uColor[1]"),
glGetUniformLocation(program, "uColor[2]"),
glGetUniformLocation(program, "uColor[3]"),
};
for (size_t i = 0; i < 4; i++)
{
EXPECT_NE(-1, positionLocations[i]);
EXPECT_NE(-1, colorLocations[i]);
for (size_t j = i + 1; j < 4; j++)
{
EXPECT_NE(positionLocations[i], positionLocations[j]);
EXPECT_NE(colorLocations[i], colorLocations[j]);
}
}
glDeleteProgram(program);
}
// Test that float to integer GetUniform rounds values correctly.
TEST_P(UniformTest, FloatUniformStateQuery)
{
std::vector<GLfloat> inValues;
std::vector<GLfloat> expectedFValues;
std::vector<GLint> expectedIValues;
GLfloat intMaxF = static_cast<GLfloat>(std::numeric_limits<GLint>::max());
GLfloat intMinF = static_cast<GLfloat>(std::numeric_limits<GLint>::min());
// TODO(jmadill): Investigate rounding of .5
inValues.push_back(-1.0f);
inValues.push_back(-0.6f);
// inValues.push_back(-0.5f); // undefined behaviour?
inValues.push_back(-0.4f);
inValues.push_back(0.0f);
inValues.push_back(0.4f);
// inValues.push_back(0.5f); // undefined behaviour?
inValues.push_back(0.6f);
inValues.push_back(1.0f);
inValues.push_back(999999.2f);
inValues.push_back(intMaxF * 2.0f);
inValues.push_back(intMaxF + 1.0f);
inValues.push_back(intMinF * 2.0f);
inValues.push_back(intMinF - 1.0f);
for (GLfloat value : inValues)
{
expectedFValues.push_back(value);
GLfloat clampedValue = std::max(intMinF, std::min(intMaxF, value));
GLfloat rounded = roundf(clampedValue);
expectedIValues.push_back(static_cast<GLint>(rounded));
}
glUseProgram(mProgram);
ASSERT_GL_NO_ERROR();
for (size_t index = 0; index < inValues.size(); ++index)
{
GLfloat inValue = inValues[index];
GLfloat expectedValue = expectedFValues[index];
glUniform1f(mUniformFLocation, inValue);
GLfloat testValue;
glGetUniformfv(mProgram, mUniformFLocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
for (size_t index = 0; index < inValues.size(); ++index)
{
GLfloat inValue = inValues[index];
GLint expectedValue = expectedIValues[index];
glUniform1f(mUniformFLocation, inValue);
GLint testValue;
glGetUniformiv(mProgram, mUniformFLocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
}
// Test that integer to float GetUniform rounds values correctly.
TEST_P(UniformTest, IntUniformStateQuery)
{
std::vector<GLint> inValues;
std::vector<GLint> expectedIValues;
std::vector<GLfloat> expectedFValues;
GLint intMax = std::numeric_limits<GLint>::max();
GLint intMin = std::numeric_limits<GLint>::min();
inValues.push_back(-1);
inValues.push_back(0);
inValues.push_back(1);
inValues.push_back(999999);
inValues.push_back(intMax);
inValues.push_back(intMax - 1);
inValues.push_back(intMin);
inValues.push_back(intMin + 1);
for (GLint value : inValues)
{
expectedIValues.push_back(value);
expectedFValues.push_back(static_cast<GLfloat>(value));
}
glUseProgram(mProgram);
ASSERT_GL_NO_ERROR();
for (size_t index = 0; index < inValues.size(); ++index)
{
GLint inValue = inValues[index];
GLint expectedValue = expectedIValues[index];
glUniform1i(mUniformILocation, inValue);
GLint testValue;
glGetUniformiv(mProgram, mUniformILocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
for (size_t index = 0; index < inValues.size(); ++index)
{
GLint inValue = inValues[index];
GLfloat expectedValue = expectedFValues[index];
glUniform1i(mUniformILocation, inValue);
GLfloat testValue;
glGetUniformfv(mProgram, mUniformILocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
}
// Test that queries of boolean uniforms round correctly.
TEST_P(UniformTest, BooleanUniformStateQuery)
{
glUseProgram(mProgram);
GLint intValue = 0;
GLfloat floatValue = 0.0f;
glUniform1i(mUniformBLocation, GL_FALSE);
glGetUniformiv(mProgram, mUniformBLocation, &intValue);
EXPECT_EQ(0, intValue);
glGetUniformfv(mProgram, mUniformBLocation, &floatValue);
EXPECT_EQ(0.0f, floatValue);
glUniform1i(mUniformBLocation, GL_TRUE);
glGetUniformiv(mProgram, mUniformBLocation, &intValue);
EXPECT_EQ(1, intValue);
glGetUniformfv(mProgram, mUniformBLocation, &floatValue);
EXPECT_EQ(1.0f, floatValue);
ASSERT_GL_NO_ERROR();
}
// Use this to select which configurations (e.g. which renderer, which GLES major version) these tests should be run against.
ANGLE_INSTANTIATE_TEST(UniformTest, ES2_D3D9(), ES2_D3D11(), ES2_OPENGL());
} // namespace
<commit_msg>Suppress failing Uniform test on AMD.<commit_after>//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "test_utils/ANGLETest.h"
using namespace angle;
namespace
{
class UniformTest : public ANGLETest
{
protected:
UniformTest()
: mProgram(0),
mUniformFLocation(-1),
mUniformILocation(-1),
mUniformBLocation(-1)
{
setWindowWidth(128);
setWindowHeight(128);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
}
void SetUp() override
{
ANGLETest::SetUp();
const std::string &vertexShader = "void main() { gl_Position = vec4(1); }";
const std::string &fragShader =
"precision mediump float;\n"
"uniform float uniF;\n"
"uniform int uniI;\n"
"uniform bool uniB;\n"
"void main() { gl_FragColor = vec4(uniF + float(uniI) + (uniB ? 1.0 : 0.0)); }";
mProgram = CompileProgram(vertexShader, fragShader);
ASSERT_NE(mProgram, 0u);
mUniformFLocation = glGetUniformLocation(mProgram, "uniF");
ASSERT_NE(mUniformFLocation, -1);
mUniformILocation = glGetUniformLocation(mProgram, "uniI");
ASSERT_NE(mUniformILocation, -1);
mUniformBLocation = glGetUniformLocation(mProgram, "uniB");
ASSERT_NE(mUniformBLocation, -1);
ASSERT_GL_NO_ERROR();
}
void TearDown() override
{
glDeleteProgram(mProgram);
ANGLETest::TearDown();
}
GLuint mProgram;
GLint mUniformFLocation;
GLint mUniformILocation;
GLint mUniformBLocation;
};
TEST_P(UniformTest, GetUniformNoCurrentProgram)
{
glUseProgram(mProgram);
glUniform1f(mUniformFLocation, 1.0f);
glUniform1i(mUniformILocation, 1);
glUseProgram(0);
GLfloat f;
glGetnUniformfvEXT(mProgram, mUniformFLocation, 4, &f);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1.0f, f);
glGetUniformfv(mProgram, mUniformFLocation, &f);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1.0f, f);
GLint i;
glGetnUniformivEXT(mProgram, mUniformILocation, 4, &i);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1, i);
glGetUniformiv(mProgram, mUniformILocation, &i);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(1, i);
}
TEST_P(UniformTest, UniformArrayLocations)
{
// TODO(geofflang): Figure out why this is broken on Intel OpenGL
if (isIntel() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE)
{
std::cout << "Test skipped on Intel OpenGL." << std::endl;
return;
}
const std::string vertexShader = SHADER_SOURCE
(
precision mediump float;
uniform float uPosition[4];
void main(void)
{
gl_Position = vec4(uPosition[0], uPosition[1], uPosition[2], uPosition[3]);
}
);
const std::string fragShader = SHADER_SOURCE
(
precision mediump float;
uniform float uColor[4];
void main(void)
{
gl_FragColor = vec4(uColor[0], uColor[1], uColor[2], uColor[3]);
}
);
GLuint program = CompileProgram(vertexShader, fragShader);
ASSERT_NE(program, 0u);
// Array index zero should be equivalent to the un-indexed uniform
EXPECT_NE(-1, glGetUniformLocation(program, "uPosition"));
EXPECT_EQ(glGetUniformLocation(program, "uPosition"), glGetUniformLocation(program, "uPosition[0]"));
EXPECT_NE(-1, glGetUniformLocation(program, "uColor"));
EXPECT_EQ(glGetUniformLocation(program, "uColor"), glGetUniformLocation(program, "uColor[0]"));
// All array uniform locations should be unique
GLint positionLocations[4] =
{
glGetUniformLocation(program, "uPosition[0]"),
glGetUniformLocation(program, "uPosition[1]"),
glGetUniformLocation(program, "uPosition[2]"),
glGetUniformLocation(program, "uPosition[3]"),
};
GLint colorLocations[4] =
{
glGetUniformLocation(program, "uColor[0]"),
glGetUniformLocation(program, "uColor[1]"),
glGetUniformLocation(program, "uColor[2]"),
glGetUniformLocation(program, "uColor[3]"),
};
for (size_t i = 0; i < 4; i++)
{
EXPECT_NE(-1, positionLocations[i]);
EXPECT_NE(-1, colorLocations[i]);
for (size_t j = i + 1; j < 4; j++)
{
EXPECT_NE(positionLocations[i], positionLocations[j]);
EXPECT_NE(colorLocations[i], colorLocations[j]);
}
}
glDeleteProgram(program);
}
// Test that float to integer GetUniform rounds values correctly.
TEST_P(UniformTest, FloatUniformStateQuery)
{
// TODO(jmadill): remove this suppression once we support ANGLE-only state queries.
if (isAMD() && (GetParam() == ES2_OPENGL() || GetParam() == ES3_OPENGL()))
{
std::cout << "Skipping test due to a driver bug on AMD." << std::endl;
return;
}
std::vector<GLfloat> inValues;
std::vector<GLfloat> expectedFValues;
std::vector<GLint> expectedIValues;
GLfloat intMaxF = static_cast<GLfloat>(std::numeric_limits<GLint>::max());
GLfloat intMinF = static_cast<GLfloat>(std::numeric_limits<GLint>::min());
// TODO(jmadill): Investigate rounding of .5
inValues.push_back(-1.0f);
inValues.push_back(-0.6f);
// inValues.push_back(-0.5f); // undefined behaviour?
inValues.push_back(-0.4f);
inValues.push_back(0.0f);
inValues.push_back(0.4f);
// inValues.push_back(0.5f); // undefined behaviour?
inValues.push_back(0.6f);
inValues.push_back(1.0f);
inValues.push_back(999999.2f);
inValues.push_back(intMaxF * 2.0f);
inValues.push_back(intMaxF + 1.0f);
inValues.push_back(intMinF * 2.0f);
inValues.push_back(intMinF - 1.0f);
for (GLfloat value : inValues)
{
expectedFValues.push_back(value);
GLfloat clampedValue = std::max(intMinF, std::min(intMaxF, value));
GLfloat rounded = roundf(clampedValue);
expectedIValues.push_back(static_cast<GLint>(rounded));
}
glUseProgram(mProgram);
ASSERT_GL_NO_ERROR();
for (size_t index = 0; index < inValues.size(); ++index)
{
GLfloat inValue = inValues[index];
GLfloat expectedValue = expectedFValues[index];
glUniform1f(mUniformFLocation, inValue);
GLfloat testValue;
glGetUniformfv(mProgram, mUniformFLocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
for (size_t index = 0; index < inValues.size(); ++index)
{
GLfloat inValue = inValues[index];
GLint expectedValue = expectedIValues[index];
glUniform1f(mUniformFLocation, inValue);
GLint testValue;
glGetUniformiv(mProgram, mUniformFLocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
}
// Test that integer to float GetUniform rounds values correctly.
TEST_P(UniformTest, IntUniformStateQuery)
{
// TODO(jmadill): remove this suppression once we support ANGLE-only state queries.
if (isAMD() && (GetParam() == ES2_OPENGL() || GetParam() == ES3_OPENGL()))
{
std::cout << "Skipping test due to a driver bug on AMD." << std::endl;
return;
}
std::vector<GLint> inValues;
std::vector<GLint> expectedIValues;
std::vector<GLfloat> expectedFValues;
GLint intMax = std::numeric_limits<GLint>::max();
GLint intMin = std::numeric_limits<GLint>::min();
inValues.push_back(-1);
inValues.push_back(0);
inValues.push_back(1);
inValues.push_back(999999);
inValues.push_back(intMax);
inValues.push_back(intMax - 1);
inValues.push_back(intMin);
inValues.push_back(intMin + 1);
for (GLint value : inValues)
{
expectedIValues.push_back(value);
expectedFValues.push_back(static_cast<GLfloat>(value));
}
glUseProgram(mProgram);
ASSERT_GL_NO_ERROR();
for (size_t index = 0; index < inValues.size(); ++index)
{
GLint inValue = inValues[index];
GLint expectedValue = expectedIValues[index];
glUniform1i(mUniformILocation, inValue);
GLint testValue;
glGetUniformiv(mProgram, mUniformILocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
for (size_t index = 0; index < inValues.size(); ++index)
{
GLint inValue = inValues[index];
GLfloat expectedValue = expectedFValues[index];
glUniform1i(mUniformILocation, inValue);
GLfloat testValue;
glGetUniformfv(mProgram, mUniformILocation, &testValue);
ASSERT_GL_NO_ERROR();
EXPECT_EQ(expectedValue, testValue);
}
}
// Test that queries of boolean uniforms round correctly.
TEST_P(UniformTest, BooleanUniformStateQuery)
{
glUseProgram(mProgram);
GLint intValue = 0;
GLfloat floatValue = 0.0f;
glUniform1i(mUniformBLocation, GL_FALSE);
glGetUniformiv(mProgram, mUniformBLocation, &intValue);
EXPECT_EQ(0, intValue);
glGetUniformfv(mProgram, mUniformBLocation, &floatValue);
EXPECT_EQ(0.0f, floatValue);
glUniform1i(mUniformBLocation, GL_TRUE);
glGetUniformiv(mProgram, mUniformBLocation, &intValue);
EXPECT_EQ(1, intValue);
glGetUniformfv(mProgram, mUniformBLocation, &floatValue);
EXPECT_EQ(1.0f, floatValue);
ASSERT_GL_NO_ERROR();
}
// Use this to select which configurations (e.g. which renderer, which GLES major version) these tests should be run against.
ANGLE_INSTANTIATE_TEST(UniformTest, ES2_D3D9(), ES2_D3D11(), ES2_OPENGL());
} // namespace
<|endoftext|>
|
<commit_before>/*MIT License
Copyright (c) 2018 MTA SZTAKI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "apeRigidBodyImpl.h"
ape::RigidBodyImpl::RigidBodyImpl(std::string name,bool isHostCreated)
: ape::IRigidBody(name), ape::Replica("Rigidbody", isHostCreated)
{
mpEventManagerImpl = ((ape::EventManagerImpl*)ape::IEventManager::getSingletonPtr());
mpSceneManager = ape::ISceneManager::getSingletonPtr();
mMass = 1.0f;
mLinearFriction = 0.5f;
mRollingFriction = 0.0f;
mSpinningFriction = 0.0f;
mLinearDamping = 0.0f;
mAngularDamping = 0.0f;
mRestitution = 0.0f;
mRBType = ape::RigidBodyType::DYNAMIC;
mGeometry = ape::GeometryWeakPtr();
mGeometryName = std::string();
mBouyancyEnabled = false;
mColliderType = ape::RigidBodyColliderType::AUTO;
}
ape::RigidBodyImpl::~RigidBodyImpl()
{
}
/// Physics parameter setters
void ape::RigidBodyImpl::setMass(float mass)
{
if (mRBType == ape::RigidBodyType::DYNAMIC)
mMass = mass > 0.0f ? mass : 1.0f;
else if (mRBType == ape::RigidBodyType::STATIC ||
mRBType == ape::RigidBodyType::KINEMATIC)
{
mMass = 0.0f;
}
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_MASS));
}
void ape::RigidBodyImpl::setFriction(float linearFric, float rollingFric, float spinningFric)
{
mLinearFriction = linearFric;
mRollingFriction = rollingFric;
mSpinningFriction = spinningFric;
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_FRICTION));
}
void ape::RigidBodyImpl::setDamping(float linearDamping, float angularDamping)
{
mLinearDamping = linearDamping;
mAngularDamping = angularDamping;
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_DAMPING));
}
void ape::RigidBodyImpl::setRestitution(float rest)
{
mRestitution = rest;
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_RESTITUTION));
}
void ape::RigidBodyImpl::setToDynamic(float mass)
{
mRBType = ape::RigidBodyType::DYNAMIC;
this->setMass(mass);
}
void ape::RigidBodyImpl::setToStatic()
{
mRBType = ape::RigidBodyType::STATIC;
this->setMass(0.0f);
}
void ape::RigidBodyImpl::setToKinematic()
{
mRBType = ape::RigidBodyType::KINEMATIC;
this->setMass(0.0f);
}
void ape::RigidBodyImpl::setBouyancy(bool enable)
{
mBouyancyEnabled = enable;
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_BOUYANCY));
}
bool ape::RigidBodyImpl::bouyancyEnabled()
{
return mBouyancyEnabled;
}
/// Physics parameter getters
float ape::RigidBodyImpl::getMass()
{
return mMass;
}
float ape::RigidBodyImpl::getLinearFriction()
{
return mLinearFriction;
}
float ape::RigidBodyImpl::getRollingFriction()
{
return mRollingFriction;
}
float ape::RigidBodyImpl::getSpinningFriction()
{
return mSpinningFriction;
}
float ape::RigidBodyImpl::getLinearDamping()
{
return mLinearDamping;
}
float ape::RigidBodyImpl::getAngularDamping()
{
return mAngularDamping;
}
float ape::RigidBodyImpl::getRestitution()
{
return mRestitution;
}
ape::RigidBodyType ape::RigidBodyImpl::getRBType()
{
return mRBType;
}
bool ape::RigidBodyImpl::isStatic()
{
return mRBType == ape::RigidBodyType::STATIC;
}
bool ape::RigidBodyImpl::isKinematic()
{
return mRBType == ape::RigidBodyType::KINEMATIC;
}
ape::RigidBodyColliderType ape::RigidBodyImpl::getColliderType()
{
return mColliderType;
}
/// Parent node and geometry
void ape::RigidBodyImpl::setParentNode(ape::NodeWeakPtr parentNode)
{
if (auto parentNodeSP = parentNode.lock())
{
mParentNode = parentNode;
mParentNodeName = parentNodeSP->getName();
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_PARENTNODE));
}
else
mParentNode = ape::NodeWeakPtr();
}
ape::NodeWeakPtr ape::RigidBodyImpl::getParentNode()
{
return mParentNode;
}
void ape::RigidBodyImpl::setGeometry(ape::GeometryWeakPtr geometry, ape::RigidBodyColliderType colliderType = ape::RigidBodyColliderType::AUTO)
{
if (auto geometrySP = geometry.lock())
{
mGeometry = geometry;
mGeometryName = geometrySP->getName();
mColliderType = colliderType;
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_SHAPE));
}
else
mGeometry = ape::GeometryWeakPtr();
}
ape::GeometryWeakPtr ape::RigidBodyImpl::getGeometry()
{
return mGeometry;
}
std::string ape::RigidBodyImpl::getGeometryName()
{
return mGeometryName;
}
/// Replica
void ape::RigidBodyImpl::WriteAllocationID(RakNet::Connection_RM3 *destinationConnection, RakNet::BitStream *allocationIdBitstream) const
{
allocationIdBitstream->Write(mObjectType);
allocationIdBitstream->Write(RakNet::RakString(mName.c_str()));
}
RakNet::RM3SerializationResult ape::RigidBodyImpl::Serialize(RakNet::SerializeParameters *serializeParameters)
{
RakNet::VariableDeltaSerializer::SerializationContext serializationContext;
serializeParameters->pro[0].reliability = RELIABLE_ORDERED;
mVariableDeltaSerializer.BeginIdenticalSerialize(&serializationContext, serializeParameters->whenLastSerialized == 0, &serializeParameters->outputBitstream[0]);
/// Physics parameters serialization
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mMass);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mLinearFriction);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mRollingFriction);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mSpinningFriction);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mLinearDamping);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mAngularDamping);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mRestitution);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mRBType);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mBouyancyEnabled);
mVariableDeltaSerializer.SerializeVariable(&serializationContext, mColliderType);
/// ParentNode, userNode and Geometry serialization
mVariableDeltaSerializer.SerializeVariable(&serializationContext, RakNet::RakString(mParentNodeName.c_str()));
mVariableDeltaSerializer.SerializeVariable(&serializationContext, RakNet::RakString(mGeometryName.c_str()));
mVariableDeltaSerializer.SerializeVariable(&serializationContext, RakNet::RakString(mUserNodeName.c_str()));
mVariableDeltaSerializer.EndSerialize(&serializationContext);
return RakNet::RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION;
}
void ape::RigidBodyImpl::Deserialize(RakNet::DeserializeParameters *deserializeParameters)
{
RakNet::VariableDeltaSerializer::DeserializationContext deserializationContext;
mVariableDeltaSerializer.BeginDeserialize(&deserializationContext, &deserializeParameters->serializationBitstream[0]);
/// Physics paremeters
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mMass))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_MASS));
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mLinearFriction))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_FRICTION));
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mRollingFriction))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_FRICTION));
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mSpinningFriction))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_FRICTION));
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mLinearDamping))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_DAMPING));
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mAngularDamping))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_DAMPING));
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mRestitution))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_RESTITUTION));
/*if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mRBType))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_TYPE));*/
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mBouyancyEnabled))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_BOUYANCY));
/*if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, mColliderType))
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_COLLIDER));*/
RakNet::RakString parentName;
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, parentName))
{
mParentNodeName = parentName.C_String();
mParentNode = mpSceneManager->getNode(mParentNodeName);
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_PARENTNODE));
}
RakNet::RakString geometryName;
if (mVariableDeltaSerializer.DeserializeVariable(&deserializationContext, geometryName))
{
if (auto geometry = std::static_pointer_cast<ape::Geometry>(mpSceneManager->getEntity(geometryName.C_String()).lock()))
{
mGeometry = geometry;
mGeometryName = geometry->getName();
mpEventManagerImpl->fireEvent(ape::Event(mName, ape::Event::Type::RIGIDBODY_SHAPE));
}
}
mVariableDeltaSerializer.EndDeserialize(&deserializationContext);
}<commit_msg>Delete ApeRigidBodyImpl.cpp<commit_after><|endoftext|>
|
<commit_before>#include "libs/base/tasks_m7.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include <cstdio>
extern "C" void app_main(void *param) {
printf("Hello world FreeRTOS.\r\n");
while (true) {
taskYIELD();
}
}
<commit_msg>Have HelloWorldFreeRTOS toggle LEDs<commit_after>#include "libs/base/tasks_m7.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include "third_party/nxp/rt1176-sdk/devices/MIMXRT1176/drivers/fsl_gpio.h"
#include <cstdio>
extern "C" void app_main(void *param) {
printf("Hello world FreeRTOS.\r\n");
gpio_pin_config_t user_led = {kGPIO_DigitalOutput, 0, kGPIO_NoIntmode};
GPIO_PinInit(GPIO13, 6, &user_led);
gpio_pin_config_t pwr_led = {kGPIO_DigitalOutput, 0, kGPIO_NoIntmode};
GPIO_PinInit(GPIO13, 5, &pwr_led);
bool on = true;
while (true) {
on = !on;
GPIO_PinWrite(GPIO13, 5, on);
GPIO_PinWrite(GPIO13, 6, on);
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2008-2012, Shane Liesegang
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of any
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "../Actors/GridActor.h"
#include "../Infrastructure/Common.h"
GridActor::GridActor()
{
//yay for magic numbers! (default parameters of the grid)
_lineColor = Color(.76f, .83f, 1.0f);
_axisColor = Color(1.0f, .41f, .6f);
_interval = 1.0f;
_minCoord = Vector2(-100.0f, -100.0f);
_maxCoord = Vector2(100.0f, 100.0f);
RecalculatePoints();
}
GridActor::GridActor(const Color& lines, const Color& axis, float interval, const Vector2& minCoord, const Vector2& maxCoord)
{
_lineColor = lines;
_axisColor = axis;
_interval = interval;
_minCoord = minCoord;
_maxCoord = maxCoord;
RecalculatePoints();
}
void GridActor::SetLineColor(const Color& lineCol)
{
_lineColor = lineCol;
}
const Color& GridActor::GetLineColor() const
{
return _lineColor;
}
void GridActor::SetAxisColor(const Color& axisCol)
{
_axisColor = axisCol;
}
const Color& GridActor::GetAxisColor() const
{
return _axisColor;
}
void GridActor::SetInterval(float interval)
{
_interval = interval;
}
const float GridActor::GetInterval() const
{
return _interval;
}
void GridActor::SetMinCoord(const Vector2& minCoord)
{
_minCoord = minCoord;
RecalculatePoints();
}
const Vector2 GridActor::GetMinCoord() const
{
return _minCoord;
}
void GridActor::SetMaxCoord(const Vector2& maxCoord)
{
_maxCoord = maxCoord;
RecalculatePoints();
}
const Vector2 GridActor::GetMaxCoord() const
{
return _maxCoord;
}
void GridActor::RecalculatePoints()
{
_points.clear();
float i;
for (i = _minCoord.X; i < _maxCoord.X; i += _interval)
{
_points.push_back(i);
_points.push_back(_minCoord.Y);
_points.push_back(i);
_points.push_back(_maxCoord.Y);
}
for (i = _minCoord.Y; i < _maxCoord.Y; i += _interval)
{
_points.push_back(_minCoord.X);
_points.push_back(i);
_points.push_back(_maxCoord.X);
_points.push_back(i);
}
_axes[0] = _minCoord.X;
_axes[1] = 0.0f;
_axes[2] = _maxCoord.X;
_axes[3] = 0.0f;
_axes[4] = 0.0f;
_axes[5] = _minCoord.Y;
_axes[6] = 0.0f;
_axes[7] = _maxCoord.Y;
}
void GridActor::Render()
{
// lines
glEnableClientState(GL_VERTEX_ARRAY);
glLineWidth(1.0f);
glColor4f(_lineColor.R, _lineColor.G, _lineColor.B, 1.0f);
glVertexPointer(2, GL_FLOAT, 0, &_points[0]);
glDrawArrays(GL_LINES, 0, _points.size() / 2);
// axes
glColor4f(_axisColor.R, _axisColor.G, _axisColor.B, 1.0f);
glVertexPointer(2, GL_FLOAT, 0, _axes);
glDrawArrays(GL_LINES, 0, 4);
}
<commit_msg>Grid actor was drawing a ton of extra lines!<commit_after>//////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2008-2012, Shane Liesegang
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of any
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "../Actors/GridActor.h"
#include "../Infrastructure/Common.h"
GridActor::GridActor()
{
//yay for magic numbers! (default parameters of the grid)
_lineColor = Color(.76f, .83f, 1.0f);
_axisColor = Color(1.0f, .41f, .6f);
_interval = 1.0f;
_minCoord = Vector2(-20.0f, -20.0f);
_maxCoord = Vector2(20.0f, 20.0f);
RecalculatePoints();
}
GridActor::GridActor(const Color& lines, const Color& axis, float interval, const Vector2& minCoord, const Vector2& maxCoord)
{
_lineColor = lines;
_axisColor = axis;
_interval = interval;
_minCoord = minCoord;
_maxCoord = maxCoord;
RecalculatePoints();
}
void GridActor::SetLineColor(const Color& lineCol)
{
_lineColor = lineCol;
}
const Color& GridActor::GetLineColor() const
{
return _lineColor;
}
void GridActor::SetAxisColor(const Color& axisCol)
{
_axisColor = axisCol;
}
const Color& GridActor::GetAxisColor() const
{
return _axisColor;
}
void GridActor::SetInterval(float interval)
{
_interval = interval;
}
const float GridActor::GetInterval() const
{
return _interval;
}
void GridActor::SetMinCoord(const Vector2& minCoord)
{
_minCoord = minCoord;
RecalculatePoints();
}
const Vector2 GridActor::GetMinCoord() const
{
return _minCoord;
}
void GridActor::SetMaxCoord(const Vector2& maxCoord)
{
_maxCoord = maxCoord;
RecalculatePoints();
}
const Vector2 GridActor::GetMaxCoord() const
{
return _maxCoord;
}
void GridActor::RecalculatePoints()
{
_points.clear();
float i;
for (i = _minCoord.X; i < _maxCoord.X; i += _interval)
{
_points.push_back(i);
_points.push_back(_minCoord.Y);
_points.push_back(i);
_points.push_back(_maxCoord.Y);
}
for (i = _minCoord.Y; i < _maxCoord.Y; i += _interval)
{
_points.push_back(_minCoord.X);
_points.push_back(i);
_points.push_back(_maxCoord.X);
_points.push_back(i);
}
_axes[0] = _minCoord.X;
_axes[1] = 0.0f;
_axes[2] = _maxCoord.X;
_axes[3] = 0.0f;
_axes[4] = 0.0f;
_axes[5] = _minCoord.Y;
_axes[6] = 0.0f;
_axes[7] = _maxCoord.Y;
}
void GridActor::Render()
{
// lines
glEnableClientState(GL_VERTEX_ARRAY);
glLineWidth(1.0f);
glColor4f(_lineColor.R, _lineColor.G, _lineColor.B, 1.0f);
glVertexPointer(2, GL_FLOAT, 0, &_points[0]);
glDrawArrays(GL_LINES, 0, _points.size() / 2);
// axes
glColor4f(_axisColor.R, _axisColor.G, _axisColor.B, 1.0f);
glVertexPointer(2, GL_FLOAT, 0, _axes);
glDrawArrays(GL_LINES, 0, 4);
}
<|endoftext|>
|
<commit_before>
#include "Uniforms.h"
namespace ion
{
namespace Graphics
{
template <>
EValueType IUniformTyped<float>::GetType() const
{
return EValueType::Float;
}
template <>
EValueType IUniformTyped<vec2f>::GetType() const
{
return EValueType::Float2;
}
template <>
EValueType IUniformTyped<vec3f>::GetType() const
{
return EValueType::Float3;
}
template <>
EValueType IUniformTyped<vec4f>::GetType() const
{
return EValueType::Float4;
}
template <>
EValueType IUniformTyped<color3f>::GetType() const
{
return EValueType::Float3;
}
template <>
EValueType IUniformTyped<color4f>::GetType() const
{
return EValueType::Float4;
}
template <>
EValueType IUniformTyped<glm::mat4>::GetType() const
{
return EValueType::Matrix4x4;
}
template <>
EValueType IUniformTyped<int>::GetType() const
{
return EValueType::SignedInt32;
}
}
}
<commit_msg>Add support for uint uniforms<commit_after>
#include "Uniforms.h"
namespace ion
{
namespace Graphics
{
template <>
EValueType IUniformTyped<float>::GetType() const
{
return EValueType::Float;
}
template <>
EValueType IUniformTyped<vec2f>::GetType() const
{
return EValueType::Float2;
}
template <>
EValueType IUniformTyped<vec3f>::GetType() const
{
return EValueType::Float3;
}
template <>
EValueType IUniformTyped<vec4f>::GetType() const
{
return EValueType::Float4;
}
template <>
EValueType IUniformTyped<color3f>::GetType() const
{
return EValueType::Float3;
}
template <>
EValueType IUniformTyped<color4f>::GetType() const
{
return EValueType::Float4;
}
template <>
EValueType IUniformTyped<glm::mat4>::GetType() const
{
return EValueType::Matrix4x4;
}
template <>
EValueType IUniformTyped<int>::GetType() const
{
return EValueType::SignedInt32;
}
template <>
EValueType IUniformTyped<uint>::GetType() const
{
return EValueType::UnsignedInt32;
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: myucp_resultset.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:40:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBA_UCPRESULTSET_HXX
#define DBA_UCPRESULTSET_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
// @@@ Adjust namespace name.
namespace dbaccess {
class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper
{
rtl::Reference< ODocumentContainer > m_xContent;
com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > m_xEnv;
private:
virtual void initStatic();
virtual void initDynamic();
public:
DynamicResultSet(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< ODocumentContainer >& rxContent,
const com::sun::star::ucb::OpenCommandArgument2& rCommand,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& rxEnv );
};
}
#endif // DBA_UCPRESULTSET_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.166); FILE MERGED 2008/03/31 13:26:47 rt 1.4.166.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: myucp_resultset.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef DBA_UCPRESULTSET_HXX
#define DBA_UCPRESULTSET_HXX
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
// @@@ Adjust namespace name.
namespace dbaccess {
class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper
{
rtl::Reference< ODocumentContainer > m_xContent;
com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > m_xEnv;
private:
virtual void initStatic();
virtual void initDynamic();
public:
DynamicResultSet(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< ODocumentContainer >& rxContent,
const com::sun::star::ucb::OpenCommandArgument2& rCommand,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& rxEnv );
};
}
#endif // DBA_UCPRESULTSET_HXX
<|endoftext|>
|
<commit_before>/* Copyright 2012 K2Informatics GmbH, Root Laengenbold, Switzerland
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "platform.h"
#include "logger.h"
#include "port.h"
#include "cmd_queue.h"
#include "transcoder.h"
#include "threads.h"
#include "marshal.h"
bool log_flag;
int main(int argc, char * argv[])
{
#ifdef __WIN32__
_setmode( _fileno( stdout ), _O_BINARY );
_setmode( _fileno( stdin ), _O_BINARY );
#endif
transcoder::instance();
#if 0
unsigned char b[] = {
// 131,106 // term_to_binary(""). term_to_binary([]).
// 131,104,0 //term_to_binary({}).
131,109,0,0,0,0 // term_to_binary(<<>>).
};
vector<unsigned char> buf(b, b + sizeof(b) / sizeof(b[0]));
term t;
transcoder::instance().decode(buf, t);
vector<unsigned char> buf1 = transcoder::instance().encode(t);
term t1;
t1.integer((unsigned long long)0xFFFFFFFFFFFFFFFF);
vector<unsigned char> buf2 = transcoder::instance().encode(t1);
#endif
log_flag = false;
// Max term byte size
if (argc >= 2) {
max_term_byte_size = atol(argv[1]);
}
// Enable Logging
if (argc >= 3) {
if (strcmp(argv[2], "true") == 0)
log_flag = true;
}
// Log listner port
int log_tcp_port = 0;
if (argc >= 4) {
log_tcp_port = atol(argv[3]);
const char * ret = logger::init(log_tcp_port);
if(ret != NULL) {
return -1;
}
}
REMOTE_LOG(INF, "Port process configs : erlang term max size 0x%08X bytes, logging %s, TCP port for logs %d"
, max_term_byte_size, (log_flag ? "enabled" : "disabled"), log_tcp_port);
threads::init();
port& prt = port::instance();
vector<unsigned char> read_buf;
while(prt.read_cmd(read_buf) > 0) {
cmd_queue::push(read_buf);
#ifndef USING_THREAD_POOL
threads::start();
#endif
}
threads::run_threads = false;
REMOTE_LOG(DBG, "erloci terminating...");
return 0;
}
<commit_msg>debug pring NLS_LANG env var<commit_after>/* Copyright 2012 K2Informatics GmbH, Root Laengenbold, Switzerland
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "platform.h"
#include "logger.h"
#include "port.h"
#include "cmd_queue.h"
#include "transcoder.h"
#include "threads.h"
#include "marshal.h"
bool log_flag;
int main(int argc, char * argv[])
{
char *nls_lang;
nls_lang = getenv("NLS_LANG");
#ifdef __WIN32__
_setmode( _fileno( stdout ), _O_BINARY );
_setmode( _fileno( stdin ), _O_BINARY );
#endif
transcoder::instance();
#if 0
unsigned char b[] = {
// 131,106 // term_to_binary(""). term_to_binary([]).
// 131,104,0 //term_to_binary({}).
131,109,0,0,0,0 // term_to_binary(<<>>).
};
vector<unsigned char> buf(b, b + sizeof(b) / sizeof(b[0]));
term t;
transcoder::instance().decode(buf, t);
vector<unsigned char> buf1 = transcoder::instance().encode(t);
term t1;
t1.integer((unsigned long long)0xFFFFFFFFFFFFFFFF);
vector<unsigned char> buf2 = transcoder::instance().encode(t1);
#endif
log_flag = false;
// Max term byte size
if (argc >= 2) {
max_term_byte_size = atol(argv[1]);
}
// Enable Logging
if (argc >= 3) {
if (strcmp(argv[2], "true") == 0)
log_flag = true;
}
// Log listner port
int log_tcp_port = 0;
if (argc >= 4) {
log_tcp_port = atol(argv[3]);
const char * ret = logger::init(log_tcp_port);
if(ret != NULL) {
return -1;
}
}
if(nls_lang == NULL)
nls_lang = "";
REMOTE_LOG(
INF,
"Port process configs : erlang term max size 0x%08X bytes, logging %s, TCP port for logs %d,"
" NLS_LANG %s",
max_term_byte_size, (log_flag ? "enabled" : "disabled"), log_tcp_port, nls_lang);
threads::init();
port& prt = port::instance();
vector<unsigned char> read_buf;
while(prt.read_cmd(read_buf) > 0) {
cmd_queue::push(read_buf);
#ifndef USING_THREAD_POOL
threads::start();
#endif
}
threads::run_threads = false;
REMOTE_LOG(DBG, "erloci terminating...");
return 0;
}
<|endoftext|>
|
<commit_before>/** \brief Updates Zeder (via Ingo's SQL database) w/ the last N issues of harvested articles for each journal.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "DnsUtil.h"
#include "IniFile.h"
#include "MARC.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"
namespace {
// Please note that Zeder PPN entries are separated by spaces and, unlike what the column names "print_ppn" and
// "online_ppn" imply may in rare cases contain space-separated lists of PPN's.
inline auto SplitZederPPNs(const std::string &ppns) {
std::vector<std::string> individual_ppns;
StringUtil::Split(ppns, ' ', &individual_ppns);
return individual_ppns;
}
struct ZederIdAndType {
unsigned zeder_id_;
char type_; // 'p' or 'e' for "print" or "electronic"
public:
ZederIdAndType(const unsigned zeder_id, const char type)
: zeder_id_(zeder_id), type_(type) { }
};
std::unordered_map<std::string, ZederIdAndType> GetPPNsToZederIdsAndTypesMap(const std::string &system_type) {
const Zeder::SimpleZeder zeder(system_type == "ixtheo" ? Zeder::IXTHEO : Zeder::KRIMDOK, { "eppn", "pppn" });
if (unlikely(zeder.empty()))
LOG_ERROR("found no Zeder entries matching any of our requested columns!"
" (This *should* not happen as we included the column ID!)");
std::unordered_map<std::string, ZederIdAndType> ppns_to_zeder_ids_and_types_map;
unsigned included_journal_count(0);
std::set<std::string> bundle_ppns; // We use a std::set because it is automatically being sorted for us.
for (const auto &journal : zeder) {
if (journal.empty())
continue;
++included_journal_count;
const auto print_ppns(SplitZederPPNs(journal.lookup("pppn")));
const auto online_ppns(SplitZederPPNs(journal.lookup("eppn")));
if (print_ppns.empty() and online_ppns.empty()) {
--included_journal_count;
LOG_WARNING("Zeder entry #" + std::to_string(journal.getId()) + " is missing print and online PPN's!");
continue;
}
for (const auto &print_ppn : print_ppns)
ppns_to_zeder_ids_and_types_map.emplace(print_ppn, ZederIdAndType(journal.getId(), 'p'));
for (const auto &online_ppn : online_ppns)
ppns_to_zeder_ids_and_types_map.emplace(online_ppn, ZederIdAndType(journal.getId(), 'e'));
}
LOG_INFO("downloaded information for " + std::to_string(included_journal_count) + " journal(s) from Zeder.");
return ppns_to_zeder_ids_and_types_map;
}
// \return the year as a small integer or 0 if we could not parse it.
unsigned short YearStringToShort(const std::string &year_as_string) {
unsigned short year_as_unsigned_short;
if (not StringUtil::ToUnsignedShort(year_as_string, &year_as_unsigned_short))
return 0;
return year_as_unsigned_short;
}
struct DbEntry {
std::string jahr_;
std::string band_;
std::string heft_;
std::string seitenbereich_;
public:
DbEntry(const std::string &jahr, const std::string &band, const std::string &heft, const std::string &seitenbereich)
: jahr_(jahr), band_(band), heft_(heft), seitenbereich_(seitenbereich) { }
DbEntry() = default;
DbEntry(const DbEntry &other) = default;
bool operator==(const DbEntry &rhs) const;
};
bool DbEntry::operator==(const DbEntry &rhs) const {
return jahr_ == rhs.jahr_ and band_ == rhs.band_ and heft_ == rhs.heft_ and seitenbereich_ == rhs.seitenbereich_;
}
size_t GetExistingDbEntries(const IniFile &ini_file, const std::string &hostname, const std::string &system_type,
std::unordered_map<std::string, DbEntry> * const existing_entries)
{
DbConnection db_connection(ini_file, "DatabaseSelect");
db_connection.queryOrDie("SELECT MAX(timestamp),Zeder_ID,PPN,Jahr,Band,Heft,Seitenbereich"
" FROM zeder.erschliessung WHERE Quellrechner='" + hostname + "' AND Systemtyp='"
+ system_type + "' GROUP BY Zeder_ID,PPN");
auto result_set(db_connection.getLastResultSet());
while (const auto row = result_set.getNextRow())
(*existing_entries)[row["Zeder_ID"] + "+" + row["PPN"]] =
DbEntry(row["Jahr"], row["Band"], row["Heft"], row["Seitenbereich"]);
return existing_entries->size();
}
bool AlreadyPresentInDB(const std::unordered_map<std::string, DbEntry> &existing_entries,
const std::string &zeder_id, const std::string &ppn, const DbEntry &test_entry)
{
const auto key_and_entry(existing_entries.find(zeder_id + "+" + ppn));
if (key_and_entry == existing_entries.cend())
return false;
return key_and_entry->second == test_entry;
}
void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::string &system_type,
const std::unordered_map<std::string, ZederIdAndType> &ppns_to_zeder_ids_and_types_map,
const IniFile &ini_file, DbConnection * const db_connection)
{
const auto JOB_START_TIME(std::to_string(std::time(nullptr)));
const auto HOSTNAME(DnsUtil::GetHostname());
std::unordered_map<std::string, DbEntry> existing_entries;
LOG_INFO("Found " + std::to_string(GetExistingDbEntries(ini_file, HOSTNAME, system_type, &existing_entries))
+ " existing database entries.");
const std::vector<std::string> COLUMN_NAMES{ "timestamp", "Quellrechner", "Systemtyp", "Zeder_ID", "PPN_Typ",
"PPN", "Jahr", "Band", "Heft", "Seitenbereich" };
std::vector<std::vector<std::optional<std::string>>> column_values;
const unsigned SQL_INSERT_BATCH_SIZE(20);
unsigned total_count(0), inserted_count(0);
while (const auto record = reader->read()) {
++total_count;
writer->write(record); // For the next pipeline phase.
const std::string superior_control_number(record.getSuperiorControlNumber());
if (superior_control_number.empty())
continue;
const auto ppn_and_zeder_id_and_ppn_type(ppns_to_zeder_ids_and_types_map.find(superior_control_number));
if (ppn_and_zeder_id_and_ppn_type == ppns_to_zeder_ids_and_types_map.cend())
continue;
const auto _936_field(record.findTag("936"));
if (_936_field == record.end())
continue;
const std::string pages(_936_field->getFirstSubfieldWithCode('h'));
std::string volume;
std::string issue(_936_field->getFirstSubfieldWithCode('e'));
if (issue.empty())
issue = _936_field->getFirstSubfieldWithCode('d');
else
volume = _936_field->getFirstSubfieldWithCode('d');
const std::string year(_936_field->getFirstSubfieldWithCode('j'));
const std::string zeder_id(std::to_string(ppn_and_zeder_id_and_ppn_type->second.zeder_id_));
const std::string ppn_type(1, ppn_and_zeder_id_and_ppn_type->second.type_);
const std::string year_as_string(std::to_string(YearStringToShort(year)));
if (AlreadyPresentInDB(existing_entries, zeder_id, superior_control_number,
DbEntry(year_as_string, volume, issue, pages)))
continue;
const std::vector<std::optional<std::string>> new_column_values{
{ /* timestamp */ JOB_START_TIME },
{ /* Quellrechner */ HOSTNAME },
{ /* Systemtyp */ system_type, },
{ /* Zeder_ID */ zeder_id },
{ /* PPN_Typ */ ppn_type },
{ /* PPN */ superior_control_number },
{ /* Jahr */ year_as_string },
{ /* Band */ volume },
{ /* Heft */ issue },
{ /* Seitenbereich */ pages },
};
column_values.emplace_back(new_column_values);
if (column_values.size() == SQL_INSERT_BATCH_SIZE) {
db_connection->insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
column_values.clear();
}
++inserted_count;
}
if (not column_values.empty())
db_connection->insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
LOG_INFO("Processed " + std::to_string(total_count) + " records and inserted " + std::to_string(inserted_count)
+ " into Ingo's database.");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
::Usage("[--min-log-level=log_level] system_type marc_input marc_output\n"
"\twhere \"system_type\" must be one of ixtheo|krimdok");
std::string system_type;
if (__builtin_strcmp("ixtheo", argv[1]) == 0)
system_type = "ixtheo";
else if (__builtin_strcmp("krimdok", argv[1]) == 0)
system_type = "krimdok";
else
LOG_ERROR("system_type must be one of ixtheo|krimdok!");
const auto ppns_to_zeder_ids_and_types_map(GetPPNsToZederIdsAndTypesMap(system_type));
IniFile ini_file;
DbConnection db_connection(ini_file, "DatabaseInsert");
const auto marc_reader(MARC::Reader::Factory(argv[2]));
const auto marc_writer(MARC::Writer::Factory(argv[3]));
ProcessRecords(marc_reader.get(), marc_writer.get(), system_type, ppns_to_zeder_ids_and_types_map,
ini_file, &db_connection);
return EXIT_SUCCESS;
}
<commit_msg>Implemented Mario's naming suggestions.<commit_after>/** \brief Updates Zeder (via Ingo's SQL database) w/ the last N issues of harvested articles for each journal.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2018-2020 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "DnsUtil.h"
#include "IniFile.h"
#include "MARC.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"
namespace {
// Please note that Zeder PPN entries are separated by spaces and, unlike what the column names "print_ppn" and
// "online_ppn" imply may in rare cases contain space-separated lists of PPN's.
inline auto SplitZederPPNs(const std::string &ppns) {
std::vector<std::string> individual_ppns;
StringUtil::Split(ppns, ' ', &individual_ppns);
return individual_ppns;
}
struct ZederIdAndType {
unsigned zeder_id_;
char type_; // 'p' or 'e' for "print" or "electronic"
public:
ZederIdAndType(const unsigned zeder_id, const char type)
: zeder_id_(zeder_id), type_(type) { }
};
std::unordered_map<std::string, ZederIdAndType> GetPPNsToZederIdsAndTypesMap(const std::string &system_type) {
const Zeder::SimpleZeder zeder(system_type == "ixtheo" ? Zeder::IXTHEO : Zeder::KRIMDOK, { "eppn", "pppn" });
if (unlikely(zeder.empty()))
LOG_ERROR("found no Zeder entries matching any of our requested columns!"
" (This *should* not happen as we included the column ID!)");
std::unordered_map<std::string, ZederIdAndType> ppns_to_zeder_ids_and_types_map;
unsigned included_journal_count(0);
std::set<std::string> bundle_ppns; // We use a std::set because it is automatically being sorted for us.
for (const auto &journal : zeder) {
if (journal.empty())
continue;
++included_journal_count;
const auto print_ppns(SplitZederPPNs(journal.lookup("pppn")));
const auto online_ppns(SplitZederPPNs(journal.lookup("eppn")));
if (print_ppns.empty() and online_ppns.empty()) {
--included_journal_count;
LOG_WARNING("Zeder entry #" + std::to_string(journal.getId()) + " is missing print and online PPN's!");
continue;
}
for (const auto &print_ppn : print_ppns)
ppns_to_zeder_ids_and_types_map.emplace(print_ppn, ZederIdAndType(journal.getId(), 'p'));
for (const auto &online_ppn : online_ppns)
ppns_to_zeder_ids_and_types_map.emplace(online_ppn, ZederIdAndType(journal.getId(), 'e'));
}
LOG_INFO("downloaded information for " + std::to_string(included_journal_count) + " journal(s) from Zeder.");
return ppns_to_zeder_ids_and_types_map;
}
// \return the year as a small integer or 0 if we could not parse it.
unsigned short YearStringToShort(const std::string &year_as_string) {
unsigned short year_as_unsigned_short;
if (not StringUtil::ToUnsignedShort(year_as_string, &year_as_unsigned_short))
return 0;
return year_as_unsigned_short;
}
struct DbEntry {
std::string jahr_;
std::string band_;
std::string heft_;
std::string seitenbereich_;
public:
DbEntry(const std::string &jahr, const std::string &band, const std::string &heft, const std::string &seitenbereich)
: jahr_(jahr), band_(band), heft_(heft), seitenbereich_(seitenbereich) { }
DbEntry() = default;
DbEntry(const DbEntry &other) = default;
bool operator==(const DbEntry &rhs) const;
};
bool DbEntry::operator==(const DbEntry &rhs) const {
return jahr_ == rhs.jahr_ and band_ == rhs.band_ and heft_ == rhs.heft_ and seitenbereich_ == rhs.seitenbereich_;
}
size_t GetExistingDbEntries(const IniFile &ini_file, const std::string &hostname, const std::string &system_type,
std::unordered_map<std::string, DbEntry> * const existing_entries)
{
DbConnection db_connection_select(ini_file, "DatabaseSelect");
db_connection_select.queryOrDie("SELECT MAX(timestamp),Zeder_ID,PPN,Jahr,Band,Heft,Seitenbereich"
" FROM zeder.erschliessung WHERE Quellrechner='" + hostname + "' AND Systemtyp='"
+ system_type + "' GROUP BY Zeder_ID,PPN");
auto result_set(db_connection_select.getLastResultSet());
while (const auto row = result_set.getNextRow())
(*existing_entries)[row["Zeder_ID"] + "+" + row["PPN"]] =
DbEntry(row["Jahr"], row["Band"], row["Heft"], row["Seitenbereich"]);
return existing_entries->size();
}
bool AlreadyPresentInDB(const std::unordered_map<std::string, DbEntry> &existing_entries,
const std::string &zeder_id, const std::string &ppn, const DbEntry &test_entry)
{
const auto key_and_entry(existing_entries.find(zeder_id + "+" + ppn));
if (key_and_entry == existing_entries.cend())
return false;
return key_and_entry->second == test_entry;
}
void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::string &system_type,
const std::unordered_map<std::string, ZederIdAndType> &ppns_to_zeder_ids_and_types_map)
{
const auto JOB_START_TIME(std::to_string(std::time(nullptr)));
const auto HOSTNAME(DnsUtil::GetHostname());
IniFile ini_file;
std::unordered_map<std::string, DbEntry> existing_entries;
LOG_INFO("Found " + std::to_string(GetExistingDbEntries(ini_file, HOSTNAME, system_type, &existing_entries))
+ " existing database entries.");
const std::vector<std::string> COLUMN_NAMES{ "timestamp", "Quellrechner", "Systemtyp", "Zeder_ID", "PPN_Typ",
"PPN", "Jahr", "Band", "Heft", "Seitenbereich" };
std::vector<std::vector<std::optional<std::string>>> column_values;
DbConnection db_connection_insert(ini_file, "DatabaseInsert");
const unsigned SQL_INSERT_BATCH_SIZE(20);
unsigned total_count(0), inserted_count(0);
while (const auto record = reader->read()) {
++total_count;
writer->write(record); // For the next pipeline phase.
const std::string superior_control_number(record.getSuperiorControlNumber());
if (superior_control_number.empty())
continue;
const auto ppn_and_zeder_id_and_ppn_type(ppns_to_zeder_ids_and_types_map.find(superior_control_number));
if (ppn_and_zeder_id_and_ppn_type == ppns_to_zeder_ids_and_types_map.cend())
continue;
const auto _936_field(record.findTag("936"));
if (_936_field == record.end())
continue;
const std::string pages(_936_field->getFirstSubfieldWithCode('h'));
std::string volume;
std::string issue(_936_field->getFirstSubfieldWithCode('e'));
if (issue.empty())
issue = _936_field->getFirstSubfieldWithCode('d');
else
volume = _936_field->getFirstSubfieldWithCode('d');
const std::string year(_936_field->getFirstSubfieldWithCode('j'));
const std::string zeder_id(std::to_string(ppn_and_zeder_id_and_ppn_type->second.zeder_id_));
const std::string ppn_type(1, ppn_and_zeder_id_and_ppn_type->second.type_);
const std::string year_as_string(std::to_string(YearStringToShort(year)));
if (AlreadyPresentInDB(existing_entries, zeder_id, superior_control_number,
DbEntry(year_as_string, volume, issue, pages)))
continue;
const std::vector<std::optional<std::string>> new_column_values{
{ /* timestamp */ JOB_START_TIME },
{ /* Quellrechner */ HOSTNAME },
{ /* Systemtyp */ system_type, },
{ /* Zeder_ID */ zeder_id },
{ /* PPN_Typ */ ppn_type },
{ /* PPN */ superior_control_number },
{ /* Jahr */ year_as_string },
{ /* Band */ volume },
{ /* Heft */ issue },
{ /* Seitenbereich */ pages },
};
column_values.emplace_back(new_column_values);
if (column_values.size() == SQL_INSERT_BATCH_SIZE) {
db_connection_insert.insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
column_values.clear();
}
++inserted_count;
}
if (not column_values.empty())
db_connection_insert.insertIntoTableOrDie("zeder.erschliessung", COLUMN_NAMES, column_values);
LOG_INFO("Processed " + std::to_string(total_count) + " records and inserted " + std::to_string(inserted_count)
+ " into Ingo's database.");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
::Usage("[--min-log-level=log_level] system_type marc_input marc_output\n"
"\twhere \"system_type\" must be one of ixtheo|krimdok");
std::string system_type;
if (__builtin_strcmp("ixtheo", argv[1]) == 0)
system_type = "ixtheo";
else if (__builtin_strcmp("krimdok", argv[1]) == 0)
system_type = "krimdok";
else
LOG_ERROR("system_type must be one of ixtheo|krimdok!");
const auto ppns_to_zeder_ids_and_types_map(GetPPNsToZederIdsAndTypesMap(system_type));
const auto marc_reader(MARC::Reader::Factory(argv[2]));
const auto marc_writer(MARC::Writer::Factory(argv[3]));
ProcessRecords(marc_reader.get(), marc_writer.get(), system_type, ppns_to_zeder_ids_and_types_map);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before><commit_msg>location_compression: safety review to init struct<commit_after><|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/tasks/traffic_decider/pull_over.h"
#include <iomanip>
#include <vector>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/proto/map_lane.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_util.h"
namespace apollo {
namespace planning {
using apollo::common::PointENU;
using apollo::common::Status;
using apollo::common::VehicleConfigHelper;
using apollo::hdmap::HDMapUtil;
using apollo::hdmap::LaneSegment;
using apollo::planning::util::GetPlanningStatus;
PullOver::PullOver(const TrafficRuleConfig& config) : TrafficRule(config) {}
Status PullOver::ApplyRule(Frame* const frame,
ReferenceLineInfo* const reference_line_info) {
frame_ = frame;
reference_line_info_ = reference_line_info;
if (!IsPullOver()) {
return Status::OK();
}
PointENU start_point;
PointENU stop_point;
double stop_heading = 0.0;
if (GetPullOverStop(&start_point, &stop_point, &stop_heading) != 0) {
ADEBUG << "Could not find a safe pull over point";
return Status::OK();
}
BuildPullOverStop(start_point, stop_point, stop_heading);
return Status::OK();
}
bool PullOver::IsPullOver() const {
auto* planning_state = GetPlanningStatus()->mutable_planning_state();
return (planning_state->has_pull_over() &&
planning_state->pull_over().in_pull_over());
}
bool PullOver::IsValidStop(const PointENU& start_point,
const PointENU& stop_point,
double stop_heading) const {
// TODO(all) implement this function
return true;
}
int PullOver::GetPullOverStop(PointENU* start_point,
PointENU* stop_point,
double* stop_heading) {
auto& pull_over_status = GetPlanningStatus()->
mutable_planning_state()->pull_over();
// reuse existing stop point
if (pull_over_status.has_start_point() &&
pull_over_status.has_stop_point() &&
pull_over_status.has_stop_heading()) {
if (IsValidStop(pull_over_status.start_point(),
pull_over_status.stop_point(),
pull_over_status.stop_heading())) {
*start_point = pull_over_status.start_point();
*stop_point = pull_over_status.stop_point();
*stop_heading = pull_over_status.stop_heading();
return 0;
}
}
// calculate new stop point if don't have a pull over stop
return SearchPullOverStop(start_point, stop_point, stop_heading);
}
int PullOver::SearchPullOverStop(PointENU* start_point,
PointENU* stop_point,
double* stop_heading) {
double stop_point_s;
if (SearchPullOverStop(&stop_point_s) != 0) {
return -1;
}
const auto& reference_line = reference_line_info_->reference_line();
if (stop_point_s > reference_line.Length()) {
return -1;
}
const auto& vehicle_param = VehicleConfigHelper::GetConfig().vehicle_param();
const double adc_width = vehicle_param.width();
// TODO(all): temporarily set stop point by lane_boarder
common::SLPoint stop_point_sl;
stop_point_sl.set_s(stop_point_s);
double lane_left_width = 0.0;
double lane_right_width = 0.0;
reference_line.GetLaneWidth(stop_point_s,
&lane_left_width, &lane_right_width);
double stop_point_l = -(lane_right_width - adc_width / 2 -
config_.pull_over().pull_over_l_buffer());
stop_point_sl.set_l(stop_point_l);
double heading = reference_line.GetReferencePoint(stop_point_s).heading();
common::math::Vec2d point;
reference_line.SLToXY(stop_point_sl, &point);
stop_point->set_x(point.x());
stop_point->set_y(point.y());
*stop_heading = heading;
common::SLPoint start_point_sl;
start_point_sl.set_s(stop_point_s - config_.pull_over().plan_distance());
start_point_sl.set_l(0.0);
reference_line.SLToXY(start_point_sl, &point);
start_point->set_x(point.x());
start_point->set_y(point.y());
ADEBUG << "stop_point(" << stop_point->x() << ", " << stop_point->y()
<< ") heading[" << *stop_heading << "]";
return 0;
}
int PullOver::SearchPullOverStop(double* stop_point_s) {
const double adc_front_edge_s = reference_line_info_->AdcSlBoundary().end_s();
*stop_point_s = adc_front_edge_s + config_.pull_over().plan_distance();
return 0;
// TODO(all): blocked by LaneSegment issue.
// comment out now. to be added later
/*
const auto& reference_line = reference_line_info_->reference_line();
const double adc_front_edge_s = reference_line_info_->AdcSlBoundary().end_s();
const double adc_end_edge_s = reference_line_info_->AdcSlBoundary().start_s();
double pull_over_length = 0.0;
double total_check_s_distance = 0.0;
// check lanes along reference line until find enough pull_over_length
const std::vector<LaneSegment>& lane_segments =
reference_line.map_path().lane_segments();
for (auto& lane_segment : lane_segments) {
ADEBUG << "check lane_seg[" << lane_segment.lane->id().id()
<< "] length[" << lane_segment.Length()
<< "] s(" << lane_segment.start_s << ", " << lane_segment.end_s
<< ") adc_s(" << adc_end_edge_s << ", " << adc_front_edge_s << ")";
if (lane_segment.end_s < adc_front_edge_s) {
continue;
}
// check check_distance
if (total_check_s_distance > config_.pull_over().max_check_distance()) {
ADEBUG << "fail to find pull over point within max_check_distance";
return -1;
}
if (adc_front_edge_s > lane_segment.start_s &&
adc_end_edge_s < lane_segment.end_s) {
total_check_s_distance = lane_segment.end_s - adc_front_edge_s;
} else {
total_check_s_distance += lane_segment.Length();
}
// check turn type: NO_TURN/LEFT_TURN/RIGHT_TURN/U_TURN
const auto& turn = lane_segment.lane->lane().turn();
if (turn != hdmap::Lane::NO_TURN) {
ADEBUG << "path lane[" << lane_segment.lane->lane().id().id()
<< "] turn[" << Lane_LaneTurn_Name(turn) << "] can't pull over";
pull_over_length = 0.0;
continue;
}
// check rightmost driving lane:
// NONE/CITY_DRIVING/BIKING/SIDEWALK/PARKING
bool rightmost_driving_lane = true;
for (auto& neighbor_lane_id :
lane_segment.lane->lane().right_neighbor_forward_lane_id()) {
const auto neighbor_lane = HDMapUtil::BaseMapPtr()->GetLaneById(
neighbor_lane_id);
if (!neighbor_lane) {
ADEBUG << "Failed to find lane[" << neighbor_lane_id.id() << "]";
continue;
}
const auto& lane_type = neighbor_lane->lane().type();
if (lane_type == hdmap::Lane::CITY_DRIVING) {
ADEBUG << "path lane[" << lane_segment.lane->lane().id().id()
<< "]'s right neighbor forward lane["
<< neighbor_lane_id.id() << "] type["
<< Lane_LaneType_Name(lane_type) << "] can't pull over";
rightmost_driving_lane = false;
break;
}
}
if (!rightmost_driving_lane) {
pull_over_length = 0.0;
continue;
}
if (adc_front_edge_s > lane_segment.start_s &&
adc_end_edge_s < lane_segment.end_s) {
pull_over_length = lane_segment.end_s - adc_front_edge_s;
} else {
pull_over_length += lane_segment.Length();
}
ADEBUG << "pull_over_length[" << pull_over_length << "]";
const double plan_distance = config_.pull_over().plan_distance();
if (pull_over_length > plan_distance) {
double const lane_s = lane_segment.Length() -
(pull_over_length - plan_distance);
apollo::common::PointENU stop_point =
lane_segment.lane->GetSmoothPoint(lane_s);
common::SLPoint stop_point_sl;
reference_line.XYToSL(stop_point, &stop_point_sl);
*stop_point_s = stop_point_sl.s();
ADEBUG << "stop point: lane[" << lane_segment.lane->id().id()
<< "] lane_s[" << lane_s
<< "] stop_point_s[" << *stop_point_s << "]";
return 0;
}
}
return -1;
*/
}
int PullOver::BuildPullOverStop(const PointENU& start_point,
const PointENU& stop_point,
double stop_heading) {
// check
const auto& reference_line = reference_line_info_->reference_line();
common::SLPoint sl;
reference_line.XYToSL(stop_point, &sl);
if (sl.s() < 0 || sl.s() > reference_line.Length()) {
return -1;
}
// create virtual stop wall
auto pull_over_reason = GetPlanningStatus()->
planning_state().pull_over().reason();
std::string virtual_obstacle_id = PULL_OVER_VO_ID_PREFIX +
PullOverStatus_Reason_Name(pull_over_reason);
auto* obstacle = frame_->CreateStopObstacle(reference_line_info_,
virtual_obstacle_id, sl.s());
if (!obstacle) {
AERROR << "Failed to create obstacle[" << virtual_obstacle_id << "]";
return -1;
}
PathObstacle* stop_wall = reference_line_info_->AddObstacle(obstacle);
if (!stop_wall) {
AERROR << "Failed to create path_obstacle for " << virtual_obstacle_id;
return -1;
}
// build stop decision
ObjectDecisionType stop;
auto stop_decision = stop.mutable_stop();
stop_decision->set_reason_code(StopReasonCode::STOP_REASON_PULL_OVER);
stop_decision->set_distance_s(-config_.pull_over().stop_distance());
stop_decision->set_stop_heading(stop_heading);
stop_decision->mutable_stop_point()->set_x(stop_point.x());
stop_decision->mutable_stop_point()->set_y(stop_point.y());
stop_decision->mutable_stop_point()->set_z(0.0);
auto* path_decision = reference_line_info_->path_decision();
// if (!path_decision->MergeWithMainStop(
// stop.stop(), stop_wall->Id(), reference_line,
// reference_line_info_->AdcSlBoundary())) {
// ADEBUG << "signal " << virtual_obstacle_id << " is not the closest stop.";
// return -1;
// }
path_decision->AddLongitudinalDecision(
TrafficRuleConfig::RuleId_Name(config_.rule_id()), stop_wall->Id(), stop);
// record in PlanningStatus
auto* pull_over_status = GetPlanningStatus()->
mutable_planning_state()->mutable_pull_over();
pull_over_status->mutable_stop_point()->set_x(stop_point.x());
pull_over_status->mutable_stop_point()->set_y(stop_point.y());
pull_over_status->mutable_stop_point()->set_z(0.0);
pull_over_status->set_stop_heading(stop_heading);
pull_over_status->mutable_start_point()->set_x(start_point.x());
pull_over_status->mutable_start_point()->set_y(start_point.y());
pull_over_status->mutable_start_point()->set_z(0.0);
return 0;
}
} // namespace planning
} // namespace apollo
<commit_msg>planning: add back searching pull over start/stop points and its checks<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/tasks/traffic_decider/pull_over.h"
#include <iomanip>
#include <vector>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/proto/map_lane.pb.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_util.h"
namespace apollo {
namespace planning {
using apollo::common::PointENU;
using apollo::common::Status;
using apollo::common::VehicleConfigHelper;
using apollo::hdmap::HDMapUtil;
using apollo::hdmap::LaneSegment;
using apollo::planning::util::GetPlanningStatus;
PullOver::PullOver(const TrafficRuleConfig& config) : TrafficRule(config) {}
Status PullOver::ApplyRule(Frame* const frame,
ReferenceLineInfo* const reference_line_info) {
frame_ = frame;
reference_line_info_ = reference_line_info;
if (!IsPullOver()) {
return Status::OK();
}
PointENU start_point;
PointENU stop_point;
double stop_heading = 0.0;
if (GetPullOverStop(&start_point, &stop_point, &stop_heading) != 0) {
ADEBUG << "Could not find a safe pull over point";
return Status::OK();
}
BuildPullOverStop(start_point, stop_point, stop_heading);
return Status::OK();
}
bool PullOver::IsPullOver() const {
auto* planning_state = GetPlanningStatus()->mutable_planning_state();
return (planning_state->has_pull_over() &&
planning_state->pull_over().in_pull_over());
}
bool PullOver::IsValidStop(const PointENU& start_point,
const PointENU& stop_point,
double stop_heading) const {
// TODO(all) implement this function
return true;
}
int PullOver::GetPullOverStop(PointENU* start_point,
PointENU* stop_point,
double* stop_heading) {
auto& pull_over_status = GetPlanningStatus()->
mutable_planning_state()->pull_over();
// reuse existing stop point
if (pull_over_status.has_start_point() &&
pull_over_status.has_stop_point() &&
pull_over_status.has_stop_heading()) {
if (IsValidStop(pull_over_status.start_point(),
pull_over_status.stop_point(),
pull_over_status.stop_heading())) {
*start_point = pull_over_status.start_point();
*stop_point = pull_over_status.stop_point();
*stop_heading = pull_over_status.stop_heading();
return 0;
}
}
// calculate new stop point if don't have a pull over stop
return SearchPullOverStop(start_point, stop_point, stop_heading);
}
int PullOver::SearchPullOverStop(PointENU* start_point,
PointENU* stop_point,
double* stop_heading) {
double stop_point_s;
if (SearchPullOverStop(&stop_point_s) != 0) {
return -1;
}
const auto& reference_line = reference_line_info_->reference_line();
if (stop_point_s > reference_line.Length()) {
return -1;
}
const auto& vehicle_param = VehicleConfigHelper::GetConfig().vehicle_param();
const double adc_width = vehicle_param.width();
// TODO(all): temporarily set stop point by lane_boarder
common::SLPoint stop_point_sl;
stop_point_sl.set_s(stop_point_s);
double lane_left_width = 0.0;
double lane_right_width = 0.0;
reference_line.GetLaneWidth(stop_point_s,
&lane_left_width, &lane_right_width);
double stop_point_l = -(lane_right_width - adc_width / 2 -
config_.pull_over().pull_over_l_buffer());
stop_point_sl.set_l(stop_point_l);
double heading = reference_line.GetReferencePoint(stop_point_s).heading();
common::math::Vec2d point;
reference_line.SLToXY(stop_point_sl, &point);
stop_point->set_x(point.x());
stop_point->set_y(point.y());
*stop_heading = heading;
common::SLPoint start_point_sl;
start_point_sl.set_s(stop_point_s - config_.pull_over().plan_distance());
start_point_sl.set_l(0.0);
reference_line.SLToXY(start_point_sl, &point);
start_point->set_x(point.x());
start_point->set_y(point.y());
ADEBUG << "stop_point(" << stop_point->x() << ", " << stop_point->y()
<< ") heading[" << *stop_heading << "]";
return 0;
}
int PullOver::SearchPullOverStop(double* stop_point_s) {
const auto& reference_line = reference_line_info_->reference_line();
const double adc_front_edge_s = reference_line_info_->AdcSlBoundary().end_s();
double check_length = 0.0;
double total_check_length = 0.0;
double check_s = adc_front_edge_s;
constexpr double kDistanceUnit = 5.0;
while (total_check_length < config_.pull_over().max_check_distance()) {
total_check_length += kDistanceUnit;
// find next_lane to check
std::string prev_lane_id;
std::vector<hdmap::LaneInfoConstPtr> lanes;
reference_line.GetLaneFromS(check_s, &lanes);
hdmap::LaneInfoConstPtr lane;
for (auto temp_lane : lanes) {
if (temp_lane->lane().id().id() == prev_lane_id) {
continue;
}
lane = temp_lane;
prev_lane_id = temp_lane->lane().id().id();
break;
}
std::string lane_id = lane->lane().id().id();
ADEBUG << "check_s[" << check_s << "] lane[" << lane_id << "]";
// check turn type: NO_TURN/LEFT_TURN/RIGHT_TURN/U_TURN
const auto& turn = lane->lane().turn();
if (turn != hdmap::Lane::NO_TURN) {
ADEBUG << "path lane[" << lane_id
<< "] turn[" << Lane_LaneTurn_Name(turn) << "] can't pull over";
check_length = 0.0;
continue;
}
// check rightmost driving lane:
// NONE/CITY_DRIVING/BIKING/SIDEWALK/PARKING
bool rightmost_driving_lane = true;
for (auto& neighbor_lane_id :
lane->lane().right_neighbor_forward_lane_id()) {
const auto neighbor_lane = HDMapUtil::BaseMapPtr()->GetLaneById(
neighbor_lane_id);
if (!neighbor_lane) {
ADEBUG << "Failed to find lane[" << neighbor_lane_id.id() << "]";
continue;
}
const auto& lane_type = neighbor_lane->lane().type();
if (lane_type == hdmap::Lane::CITY_DRIVING) {
ADEBUG << "lane[" << lane_id << "]'s right neighbor forward lane["
<< neighbor_lane_id.id() << "] type["
<< Lane_LaneType_Name(lane_type) << "] can't pull over";
rightmost_driving_lane = false;
break;
}
}
if (!rightmost_driving_lane) {
check_length = 0.0;
continue;
}
check_length += kDistanceUnit;
if (check_length > config_.pull_over().plan_distance()) {
*stop_point_s = check_s;
ADEBUG << "stop point: lane[" << lane->id().id()
<< "] stop_point_s[" << *stop_point_s
<< "] adc_front_edge_s[" << adc_front_edge_s << "]";
return 0;
}
check_s += kDistanceUnit;
}
return -1;
}
int PullOver::BuildPullOverStop(const PointENU& start_point,
const PointENU& stop_point,
double stop_heading) {
// check
const auto& reference_line = reference_line_info_->reference_line();
common::SLPoint sl;
reference_line.XYToSL(stop_point, &sl);
if (sl.s() < 0 || sl.s() > reference_line.Length()) {
return -1;
}
// create virtual stop wall
auto pull_over_reason = GetPlanningStatus()->
planning_state().pull_over().reason();
std::string virtual_obstacle_id = PULL_OVER_VO_ID_PREFIX +
PullOverStatus_Reason_Name(pull_over_reason);
auto* obstacle = frame_->CreateStopObstacle(reference_line_info_,
virtual_obstacle_id, sl.s());
if (!obstacle) {
AERROR << "Failed to create obstacle[" << virtual_obstacle_id << "]";
return -1;
}
PathObstacle* stop_wall = reference_line_info_->AddObstacle(obstacle);
if (!stop_wall) {
AERROR << "Failed to create path_obstacle for " << virtual_obstacle_id;
return -1;
}
// build stop decision
ObjectDecisionType stop;
auto stop_decision = stop.mutable_stop();
stop_decision->set_reason_code(StopReasonCode::STOP_REASON_PULL_OVER);
stop_decision->set_distance_s(-config_.pull_over().stop_distance());
stop_decision->set_stop_heading(stop_heading);
stop_decision->mutable_stop_point()->set_x(stop_point.x());
stop_decision->mutable_stop_point()->set_y(stop_point.y());
stop_decision->mutable_stop_point()->set_z(0.0);
auto* path_decision = reference_line_info_->path_decision();
// if (!path_decision->MergeWithMainStop(
// stop.stop(), stop_wall->Id(), reference_line,
// reference_line_info_->AdcSlBoundary())) {
// ADEBUG << "signal " << virtual_obstacle_id << " is not the closest stop.";
// return -1;
// }
path_decision->AddLongitudinalDecision(
TrafficRuleConfig::RuleId_Name(config_.rule_id()), stop_wall->Id(), stop);
// record in PlanningStatus
auto* pull_over_status = GetPlanningStatus()->
mutable_planning_state()->mutable_pull_over();
pull_over_status->mutable_stop_point()->set_x(stop_point.x());
pull_over_status->mutable_stop_point()->set_y(stop_point.y());
pull_over_status->mutable_stop_point()->set_z(0.0);
pull_over_status->set_stop_heading(stop_heading);
pull_over_status->mutable_start_point()->set_x(start_point.x());
pull_over_status->mutable_start_point()->set_y(start_point.y());
pull_over_status->mutable_start_point()->set_z(0.0);
return 0;
}
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>// Bindings
#include "PyROOT.h"
#include "Adapters.h"
#include "Utility.h"
// ROOT
#include "TInterpreter.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TDataType.h"
#include "TDataMember.h"
#include "TMethod.h"
#include "TFunction.h"
#include "TMethodArg.h"
#include "TList.h"
#include "TError.h"
//- helper -------------------------------------------------------------------
namespace PyROOT {
inline std::string UnqualifiedTypeName( const std::string name ) {
return TClassEdit::ShortType(
TClassEdit::CleanType( name.c_str(), 1 ).c_str(), 5 );
}
} // namespace PyROOT
//= TReturnTypeAdapter =======================================================
std::string PyROOT::TReturnTypeAdapter::Name( unsigned int mod ) const
{
// get the name of the return type that is being adapted
std::string name = fName;
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
return name;
}
//= TMemberAdapter ===========================================================
PyROOT::TMemberAdapter::TMemberAdapter( TMethod* meth ) : fMember( meth )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethod*() const
{
// cast the adapter to a TMethod* being adapted, returns 0 on failure
return dynamic_cast< TMethod* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TFunction* func ) : fMember( func )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TFunction*() const
{
// cast the adapter to a TFunction* being adapted, returns 0 on failure
return dynamic_cast< TFunction* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TDataMember* mb ) : fMember( mb )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TDataMember*() const
{
// cast the adapter to a TDataMember* being adapted, returns 0 on failure
return dynamic_cast< TDataMember* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TMethodArg* ma ) : fMember( ma )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethodArg*() const
{
// cast the adapter to a TMethodArg* being adapted, returns 0 on failure
return dynamic_cast< TMethodArg* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::Name( unsigned int mod ) const
{
// Return name of the type described by fMember
TMethodArg* arg = (TMethodArg*)*this;
if ( arg ) {
std::string name = arg->GetTypeNormalizedName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( name );
return name;
} else if ( mod & Rflx::FINAL )
return Utility::ResolveTypedef( fMember->GetName() );
// CLING WORKAROUND -- TMethod names are fully scoped ...
TMethod* m = (TMethod*)*this;
if (m && m->GetClass()) {
std::string scoped_name = m->GetName();
std::string class_name = m->GetClass()->GetName();
std::string::size_type pos = scoped_name.find(class_name + "::");
if (pos == 0) // only accept found at start
scoped_name = scoped_name.substr(class_name.size() + 2 /* for :: */, std::string::npos);
return scoped_name;
}
// CLING WORKAROUND -- should not be null, but can be due #100389
if ( fMember != 0 )
return fMember->GetName();
return "<unknown>";
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstant() const
{
// test if the adapted member is a const method
return fMember ? (fMember->Property() & kIsConstMethod) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstructor() const
{
// test if the adapted member is a const method
return ((TFunction*)fMember) ? (((TFunction*)fMember)->ExtraProperty() & kIsConstructor) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsEnum() const
{
// test if the adapted member is of an enum type
return fMember->Property() & kIsEnum;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsPublic() const
{
// test if the adapted member represents an public (data) member
return fMember->Property() & kIsPublic;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsStatic() const
{
// test if the adapted member represents a class (data) member
return fMember->Property() & kIsStatic;
}
//____________________________________________________________________________
size_t PyROOT::TMemberAdapter::FunctionParameterSize( Bool_t required ) const
{
// get the total number of parameters that the adapted function/method takes
TFunction* func = (TFunction*)fMember;
if ( ! func )
return 0;
if ( required == true )
return func->GetNargs() - func->GetNargsOpt();
return func->GetNargs();
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TMemberAdapter::FunctionParameterAt( size_t nth ) const
{
// get the type info of the function parameter at position nth
return (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterNameAt( size_t nth ) const
{
// get the formal name, if available, of the function parameter at position nth
const char* name =
((TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth ))->GetName();
if ( name )
return name;
return "";
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterDefaultAt( size_t nth ) const
{
// get the default value, if available, of the function parameter at position nth
TMethodArg* arg = (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
const char* def = arg->GetDefault();
if ( ! def )
return "";
// special case for strings: "some value" -> ""some value"
if ( strstr( Utility::ResolveTypedef( arg->GetTypeNormalizedName() ).c_str(), "char*" ) ) {
std::string sdef = "\"";
sdef += def;
sdef += "\"";
return sdef;
}
return def;
}
//____________________________________________________________________________
PyROOT::TReturnTypeAdapter PyROOT::TMemberAdapter::ReturnType() const
{
// get the return type of the wrapped function/method
return TReturnTypeAdapter( ((TFunction*)fMember)->GetReturnTypeNormalizedName() );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TMemberAdapter::DeclaringScope() const
{
// get the declaring scope (class) of the wrapped function/method
TMethod* method = (TMethod*)*this;
if ( method )
return method->GetClass();
// happens for free-standing functions (i.e. global scope)
return std::string( "" );
}
//= TBaseAdapter =============================================================
std::string PyROOT::TBaseAdapter::Name() const
{
// get the name of the base class that is being adapted
return fBase->GetName();
}
//= TScopeAdapter ============================================================
PyROOT::TScopeAdapter::TScopeAdapter( TClass* klass ) : fClass( klass )
{
// wrap a class (scope)
if ( fClass.GetClass() != 0 )
fName = fClass->GetName();
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::TScopeAdapter( const std::string& name ) :
fClass( name.c_str() ), fName( name )
{
/* empty */
}
PyROOT::TScopeAdapter::TScopeAdapter( const TMemberAdapter& mb ) :
fClass( mb.Name( Rflx::SCOPED ).c_str() ),
fName( mb.Name( Rflx::QUALIFIED | Rflx::SCOPED ) )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TScopeAdapter::ByName( const std::string& name, Bool_t quiet )
{
// lookup a scope (class) by name
Int_t oldEIL = gErrorIgnoreLevel;
if ( quiet )
gErrorIgnoreLevel = 3000;
TClassRef klass( name.c_str() );
if (klass.GetClass() && klass->GetListOfAllPublicMethods()->GetSize() == 0) {
// sometimes I/O interferes, leading to zero methods: reload from CINT
ClassInfo_t* cl = gInterpreter->ClassInfo_Factory( name.c_str() );
if ( cl ) {
gInterpreter->SetClassInfo( klass, kTRUE );
gInterpreter->ClassInfo_Delete(cl);
}
}
gErrorIgnoreLevel = oldEIL;
return klass.GetClass();
}
//____________________________________________________________________________
std::string PyROOT::TScopeAdapter::Name( unsigned int mod ) const
{
// Return name of type described by fClass
if ( ! fClass.GetClass() || ! fClass->Property() ) {
// fundamental types have no class, and unknown classes have no property
std::string name = fName;
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
return name;
}
std::string name = fClass->GetName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! (mod & Rflx::SCOPED) ) {
// remove scope from the name
Int_t tpl_open = 0;
std::string::size_type last = 0;
for ( std::string::size_type pos = name.size() - 1; 0 < pos; --pos ) {
std::string::value_type c = name[ pos ];
// count '<' and '>' to be able to skip template contents
if ( c == '>' )
++tpl_open;
else if ( c == '<' )
--tpl_open;
else if ( tpl_open == 0 && c == ':' && 0 < pos && name[ pos-1 ] == ':' ) {
// found scope, strip name from it
name = name.substr( pos+1, std::string::npos );
}
}
}
return name;
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::BaseSize() const
{
// get the total number of base classes that this class has
if ( fClass.GetClass() && fClass->GetListOfBases() != 0 )
return fClass->GetListOfBases()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TBaseAdapter PyROOT::TScopeAdapter::BaseAt( size_t nth ) const
{
// get the nth base of this class
return (TBaseClass*)fClass->GetListOfBases()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::FunctionMemberSize() const
{
// get the total number of methods that this class has
if ( fClass.GetClass() )
return fClass->GetListOfMethods()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::FunctionMemberAt( size_t nth ) const
{
// get the nth method of this class
return (TMethod*)fClass->GetListOfMethods()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::DataMemberSize() const
{
// get the total number of data members that this class has
if ( fClass.GetClass() )
return fClass->GetListOfDataMembers()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::DataMemberAt( size_t nth ) const
{
// get the nth data member of this class
return (TDataMember*)fClass->GetListOfDataMembers()->At( nth );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::operator Bool_t() const
{
// check the validity of this scope (class)
if ( fName.empty() )
return false;
Bool_t b = kFALSE;
Int_t oldEIL = gErrorIgnoreLevel;
gErrorIgnoreLevel = 3000;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsValid( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsValid( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
gErrorIgnoreLevel = oldEIL;
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsComplete() const
{
// verify whether the dictionary of this class is fully available
Bool_t b = kFALSE;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsLoaded( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsLoaded( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsClass() const
{
// test if this scope represents a class
if ( fClass.GetClass() ) {
// some inverted logic: we don't have a TClass, but a builtin will be recognized, so
// if it is NOT a builtin, it is a class or struct (but may be missing dictionary)
return (fClass->Property() & kIsClass) || ! (fClass->Property() & kIsFundamental);
}
// no class can mean either is no class (i.e. builtin), or no dict but coming in
// through PyCintex/Reflex ... as a workaround, use TDataTypes that has a full
// enumeration of builtin types
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsStruct() const
{
// test if this scope represents a struct
if ( fClass.GetClass() ) {
// same logic as for IsClass() above ...
return (fClass->Property() & kIsStruct) || ! (fClass->Property() & kIsFundamental);
}
// same logic as for IsClass() above ...
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsNamespace() const
{
// test if this scope represents a namespace
if ( fClass.GetClass() )
return fClass->Property() & kIsNamespace;
return kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsAbstract() const
{
// test if this scope represents an abstract class
if ( fClass.GetClass() )
return fClass->Property() & kIsAbstract; // assume set only for classes
return kFALSE;
}
<commit_msg>Remove unused variable<commit_after>// Bindings
#include "PyROOT.h"
#include "Adapters.h"
#include "Utility.h"
// ROOT
#include "TInterpreter.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TDataType.h"
#include "TDataMember.h"
#include "TMethod.h"
#include "TFunction.h"
#include "TMethodArg.h"
#include "TList.h"
#include "TError.h"
//- helper -------------------------------------------------------------------
namespace PyROOT {
inline std::string UnqualifiedTypeName( const std::string name ) {
return TClassEdit::ShortType(
TClassEdit::CleanType( name.c_str(), 1 ).c_str(), 5 );
}
} // namespace PyROOT
//= TReturnTypeAdapter =======================================================
std::string PyROOT::TReturnTypeAdapter::Name( unsigned int mod ) const
{
// get the name of the return type that is being adapted
std::string name = fName;
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
return name;
}
//= TMemberAdapter ===========================================================
PyROOT::TMemberAdapter::TMemberAdapter( TMethod* meth ) : fMember( meth )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethod*() const
{
// cast the adapter to a TMethod* being adapted, returns 0 on failure
return dynamic_cast< TMethod* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TFunction* func ) : fMember( func )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TFunction*() const
{
// cast the adapter to a TFunction* being adapted, returns 0 on failure
return dynamic_cast< TFunction* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TDataMember* mb ) : fMember( mb )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TDataMember*() const
{
// cast the adapter to a TDataMember* being adapted, returns 0 on failure
return dynamic_cast< TDataMember* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TMethodArg* ma ) : fMember( ma )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethodArg*() const
{
// cast the adapter to a TMethodArg* being adapted, returns 0 on failure
return dynamic_cast< TMethodArg* >( const_cast< TDictionary* >( fMember ) );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::Name( unsigned int mod ) const
{
// Return name of the type described by fMember
TMethodArg* arg = (TMethodArg*)*this;
if ( arg ) {
std::string name = arg->GetTypeNormalizedName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( name );
return name;
} else if ( mod & Rflx::FINAL )
return Utility::ResolveTypedef( fMember->GetName() );
// CLING WORKAROUND -- TMethod names are fully scoped ...
TMethod* m = (TMethod*)*this;
if (m && m->GetClass()) {
std::string scoped_name = m->GetName();
std::string class_name = m->GetClass()->GetName();
std::string::size_type pos = scoped_name.find(class_name + "::");
if (pos == 0) // only accept found at start
scoped_name = scoped_name.substr(class_name.size() + 2 /* for :: */, std::string::npos);
return scoped_name;
}
// CLING WORKAROUND -- should not be null, but can be due #100389
if ( fMember != 0 )
return fMember->GetName();
return "<unknown>";
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstant() const
{
// test if the adapted member is a const method
return fMember ? (fMember->Property() & kIsConstMethod) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstructor() const
{
// test if the adapted member is a const method
return ((TFunction*)fMember) ? (((TFunction*)fMember)->ExtraProperty() & kIsConstructor) : kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsEnum() const
{
// test if the adapted member is of an enum type
return fMember->Property() & kIsEnum;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsPublic() const
{
// test if the adapted member represents an public (data) member
return fMember->Property() & kIsPublic;
}
//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsStatic() const
{
// test if the adapted member represents a class (data) member
return fMember->Property() & kIsStatic;
}
//____________________________________________________________________________
size_t PyROOT::TMemberAdapter::FunctionParameterSize( Bool_t required ) const
{
// get the total number of parameters that the adapted function/method takes
TFunction* func = (TFunction*)fMember;
if ( ! func )
return 0;
if ( required == true )
return func->GetNargs() - func->GetNargsOpt();
return func->GetNargs();
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TMemberAdapter::FunctionParameterAt( size_t nth ) const
{
// get the type info of the function parameter at position nth
return (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterNameAt( size_t nth ) const
{
// get the formal name, if available, of the function parameter at position nth
const char* name =
((TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth ))->GetName();
if ( name )
return name;
return "";
}
//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterDefaultAt( size_t nth ) const
{
// get the default value, if available, of the function parameter at position nth
TMethodArg* arg = (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
const char* def = arg->GetDefault();
if ( ! def )
return "";
// special case for strings: "some value" -> ""some value"
if ( strstr( Utility::ResolveTypedef( arg->GetTypeNormalizedName() ).c_str(), "char*" ) ) {
std::string sdef = "\"";
sdef += def;
sdef += "\"";
return sdef;
}
return def;
}
//____________________________________________________________________________
PyROOT::TReturnTypeAdapter PyROOT::TMemberAdapter::ReturnType() const
{
// get the return type of the wrapped function/method
return TReturnTypeAdapter( ((TFunction*)fMember)->GetReturnTypeNormalizedName() );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TMemberAdapter::DeclaringScope() const
{
// get the declaring scope (class) of the wrapped function/method
TMethod* method = (TMethod*)*this;
if ( method )
return method->GetClass();
// happens for free-standing functions (i.e. global scope)
return std::string( "" );
}
//= TBaseAdapter =============================================================
std::string PyROOT::TBaseAdapter::Name() const
{
// get the name of the base class that is being adapted
return fBase->GetName();
}
//= TScopeAdapter ============================================================
PyROOT::TScopeAdapter::TScopeAdapter( TClass* klass ) : fClass( klass )
{
// wrap a class (scope)
if ( fClass.GetClass() != 0 )
fName = fClass->GetName();
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::TScopeAdapter( const std::string& name ) :
fClass( name.c_str() ), fName( name )
{
/* empty */
}
PyROOT::TScopeAdapter::TScopeAdapter( const TMemberAdapter& mb ) :
fClass( mb.Name( Rflx::SCOPED ).c_str() ),
fName( mb.Name( Rflx::QUALIFIED | Rflx::SCOPED ) )
{
/* empty */
}
//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TScopeAdapter::ByName( const std::string& name, Bool_t quiet )
{
// lookup a scope (class) by name
Int_t oldEIL = gErrorIgnoreLevel;
if ( quiet )
gErrorIgnoreLevel = 3000;
TClassRef klass( name.c_str() );
if (klass.GetClass() && klass->GetListOfAllPublicMethods()->GetSize() == 0) {
// sometimes I/O interferes, leading to zero methods: reload from CINT
ClassInfo_t* cl = gInterpreter->ClassInfo_Factory( name.c_str() );
if ( cl ) {
gInterpreter->SetClassInfo( klass, kTRUE );
gInterpreter->ClassInfo_Delete(cl);
}
}
gErrorIgnoreLevel = oldEIL;
return klass.GetClass();
}
//____________________________________________________________________________
std::string PyROOT::TScopeAdapter::Name( unsigned int mod ) const
{
// Return name of type described by fClass
if ( ! fClass.GetClass() || ! fClass->Property() ) {
// fundamental types have no class, and unknown classes have no property
std::string name = fName;
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! ( mod & Rflx::QUALIFIED ) )
name = UnqualifiedTypeName( fName );
return name;
}
std::string name = fClass->GetName();
if ( mod & Rflx::FINAL )
name = Utility::ResolveTypedef( name );
if ( ! (mod & Rflx::SCOPED) ) {
// remove scope from the name
Int_t tpl_open = 0;
for ( std::string::size_type pos = name.size() - 1; 0 < pos; --pos ) {
std::string::value_type c = name[ pos ];
// count '<' and '>' to be able to skip template contents
if ( c == '>' )
++tpl_open;
else if ( c == '<' )
--tpl_open;
else if ( tpl_open == 0 && c == ':' && 0 < pos && name[ pos-1 ] == ':' ) {
// found scope, strip name from it
name = name.substr( pos+1, std::string::npos );
}
}
}
return name;
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::BaseSize() const
{
// get the total number of base classes that this class has
if ( fClass.GetClass() && fClass->GetListOfBases() != 0 )
return fClass->GetListOfBases()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TBaseAdapter PyROOT::TScopeAdapter::BaseAt( size_t nth ) const
{
// get the nth base of this class
return (TBaseClass*)fClass->GetListOfBases()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::FunctionMemberSize() const
{
// get the total number of methods that this class has
if ( fClass.GetClass() )
return fClass->GetListOfMethods()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::FunctionMemberAt( size_t nth ) const
{
// get the nth method of this class
return (TMethod*)fClass->GetListOfMethods()->At( nth );
}
//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::DataMemberSize() const
{
// get the total number of data members that this class has
if ( fClass.GetClass() )
return fClass->GetListOfDataMembers()->GetSize();
return 0;
}
//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::DataMemberAt( size_t nth ) const
{
// get the nth data member of this class
return (TDataMember*)fClass->GetListOfDataMembers()->At( nth );
}
//____________________________________________________________________________
PyROOT::TScopeAdapter::operator Bool_t() const
{
// check the validity of this scope (class)
if ( fName.empty() )
return false;
Bool_t b = kFALSE;
Int_t oldEIL = gErrorIgnoreLevel;
gErrorIgnoreLevel = 3000;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsValid( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsValid( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
gErrorIgnoreLevel = oldEIL;
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsComplete() const
{
// verify whether the dictionary of this class is fully available
Bool_t b = kFALSE;
std::string scname = Name( Rflx::SCOPED );
TClass* klass = TClass::GetClass( scname.c_str() );
if ( klass && klass->GetClassInfo() ) // works for normal case w/ dict
b = gInterpreter->ClassInfo_IsLoaded( klass->GetClassInfo() );
else { // special case for forward declared classes
ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
if ( ci ) {
b = gInterpreter->ClassInfo_IsLoaded( ci );
gInterpreter->ClassInfo_Delete( ci ); // we own the fresh class info
}
}
return b;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsClass() const
{
// test if this scope represents a class
if ( fClass.GetClass() ) {
// some inverted logic: we don't have a TClass, but a builtin will be recognized, so
// if it is NOT a builtin, it is a class or struct (but may be missing dictionary)
return (fClass->Property() & kIsClass) || ! (fClass->Property() & kIsFundamental);
}
// no class can mean either is no class (i.e. builtin), or no dict but coming in
// through PyCintex/Reflex ... as a workaround, use TDataTypes that has a full
// enumeration of builtin types
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsStruct() const
{
// test if this scope represents a struct
if ( fClass.GetClass() ) {
// same logic as for IsClass() above ...
return (fClass->Property() & kIsStruct) || ! (fClass->Property() & kIsFundamental);
}
// same logic as for IsClass() above ...
return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsNamespace() const
{
// test if this scope represents a namespace
if ( fClass.GetClass() )
return fClass->Property() & kIsNamespace;
return kFALSE;
}
//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsAbstract() const
{
// test if this scope represents an abstract class
if ( fClass.GetClass() )
return fClass->Property() & kIsAbstract; // assume set only for classes
return kFALSE;
}
<|endoftext|>
|
<commit_before>#include "types.h"
#include "amd64.h"
#include "mmu.h"
#include "cpu.hh"
#include "kernel.hh"
#include "bits.hh"
#include "spinlock.h"
#include "kalloc.hh"
#include "queue.h"
#include "condvar.h"
#include "proc.hh"
#include "vm.hh"
#include "wq.hh"
using namespace std;
static const char *levelnames[] = {
"PT", "PD", "PDP", "PML4"
};
static pgmap*
descend(pgmap *dir, u64 va, u64 flags, int create, int level)
{
atomic<pme_t> *entryp;
pme_t entry;
pgmap *next;
retry:
entryp = &dir->e[PX(level, va)];
entry = entryp->load();
if (entry & PTE_P) {
next = (pgmap*) p2v(PTE_ADDR(entry));
} else {
if (!create)
return nullptr;
next = (pgmap*) kalloc(levelnames[level-1]);
if (!next)
return nullptr;
memset(next, 0, PGSIZE);
if (!cmpxch(entryp, entry, v2p(next) | PTE_P | PTE_W | flags)) {
kfree((void*) next);
goto retry;
}
}
return next;
}
// Return the address of the PTE in page table pgdir
// that corresponds to linear address va. If create!=0,
// create any required page table pages.
atomic<pme_t>*
walkpgdir(pgmap *pml4, u64 va, int create)
{
auto pdp = descend(pml4, va, PTE_U, create, 3);
if (pdp == nullptr)
return nullptr;
auto pd = descend(pdp, va, PTE_U, create, 2);
if (pd == nullptr)
return nullptr;
auto pt = descend(pd, va, PTE_U, create, 1);
if (pt == nullptr)
return nullptr;
return &pt->e[PX(0,va)];
}
// Map from 0 to 128Gbytes starting at KBASE.
void
initpg(void)
{
u64 va = KBASE;
paddr pa = 0;
while (va < (KBASE+(128ull<<30))) {
auto pdp = descend(&kpml4, va, 0, 1, 3);
auto pd = descend(pdp, va, 0, 1, 2);
atomic<pme_t> *sp = &pd->e[PX(1,va)];
u64 flags = PTE_W | PTE_P | PTE_PS | PTE_NX;
*sp = pa | flags;
va += PGSIZE*512;
pa += PGSIZE*512;
}
}
// Set up kernel part of a page table.
pgmap*
setupkvm(void)
{
pgmap *pml4;
int k;
if((pml4 = (pgmap*)kalloc("PML4")) == 0)
return 0;
k = PX(3, KBASE);
memset(&pml4->e[0], 0, 8*k);
memmove(&pml4->e[k], &kpml4.e[k], 8*(512-k));
return pml4;
}
int
mapkva(pgmap *pml4, char* kva, uptr uva, size_t size)
{
for (u64 off = 0; off < size; off+=4096) {
atomic<pme_t> *pte = walkpgdir(pml4, (u64) (uva+off), 1);
if (pte == nullptr)
return -1;
*pte = v2p(kva+off) | PTE_P | PTE_U | PTE_W;
}
return 0;
}
int
setupuvm(pgmap *pml4, char *kshared, char *uwq)
{
struct todo {
char *kvm;
char *uvm;
size_t size;
} todo[] = {
{ kshared, (char*)KSHARED, KSHAREDSIZE },
{ uwq, (char*)USERWQ, USERWQSIZE }
};
for (int i = 0; i < NELEM(todo); i++) {
for (u64 off = 0; off < todo[i].size; off+=4096) {
atomic<pme_t> *pte = walkpgdir(pml4, (u64) (todo[i].uvm+off), 1);
if (pte == nullptr)
return -1;
*pte = v2p(todo[i].kvm+off) | PTE_P | PTE_U | PTE_W;
}
}
return 0;
}
// Switch h/w page table register to the kernel-only page table,
// for when no process is running.
static void
switchkvm(void)
{
lcr3(v2p(&kpml4)); // switch to the kernel page table
}
// Switch TSS and h/w page table to correspond to process p.
void
switchvm(struct proc *p)
{
u64 base = (u64) &mycpu()->ts;
pushcli();
mycpu()->gdt[TSSSEG>>3] = (struct segdesc)
SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A);
mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base);
mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE;
mycpu()->ts.iomba = (u16)__offsetof(struct taskstate, iopb);
ltr(TSSSEG);
u64 nreq = tlbflush_req.load();
if (p->vmap != 0 && p->vmap->pml4 != 0)
lcr3(v2p(p->vmap->pml4)); // switch to new address space
else
switchkvm();
mycpu()->tlbflush_done = nreq;
writefs(UDSEG);
writemsr(MSR_FS_BASE, p->user_fs_);
popcli();
}
static void
freepm(pgmap *pm, int level)
{
int i;
if (level != 0) {
for (i = 0; i < 512; i++) {
pme_t entry = pm->e[i];
if (entry & PTE_P)
freepm((pgmap*) p2v(PTE_ADDR(entry)), level - 1);
}
}
kfree(pm);
}
// Free a page table and all the physical memory pages
// in the user part.
void
freevm(pgmap *pml4)
{
int k;
int i;
if(pml4 == 0)
panic("freevm: no pgdir");
// Don't free kernel portion of the pml4
k = PX(3, KBASE);
for (i = 0; i < k; i++) {
pme_t entry = pml4->e[i];
if (entry & PTE_P) {
freepm((pgmap*) p2v(PTE_ADDR(entry)), 2);
}
}
kfree(pml4);
}
// Set up CPU's kernel segment descriptors.
// Run once at boot time on each CPU.
void
inittls(void)
{
struct cpu *c;
// Initialize cpu-local storage.
c = &cpus[cpunum()];
writegs(KDSEG);
writemsr(MSR_GS_BASE, (u64)&c->cpu);
writemsr(MSR_GS_KERNBASE, (u64)&c->cpu);
c->cpu = c;
c->proc = nullptr;
c->kmem = &kmems[cpunum()];
}
atomic<u64> tlbflush_req;
void
tlbflush()
{
u64 myreq = tlbflush_req++;
tlbflush(myreq);
}
void
tlbflush(u64 myreq)
{
// the caller may not hold any spinlock, because other CPUs might
// be spinning waiting for that spinlock, with interrupts disabled,
// so we will deadlock waiting for their TLB flush..
assert(mycpu()->ncli == 0);
for (int i = 0; i < ncpu; i++)
if (cpus[i].tlbflush_done < myreq)
lapic_tlbflush(i);
for (int i = 0; i < ncpu; i++)
while (cpus[i].tlbflush_done < myreq)
/* spin */ ;
}
<commit_msg>minor bug<commit_after>#include "types.h"
#include "amd64.h"
#include "mmu.h"
#include "cpu.hh"
#include "kernel.hh"
#include "bits.hh"
#include "spinlock.h"
#include "kalloc.hh"
#include "queue.h"
#include "condvar.h"
#include "proc.hh"
#include "vm.hh"
#include "wq.hh"
using namespace std;
static const char *levelnames[] = {
"PT", "PD", "PDP", "PML4"
};
static pgmap*
descend(pgmap *dir, u64 va, u64 flags, int create, int level)
{
atomic<pme_t> *entryp;
pme_t entry;
pgmap *next;
retry:
entryp = &dir->e[PX(level, va)];
entry = entryp->load();
if (entry & PTE_P) {
next = (pgmap*) p2v(PTE_ADDR(entry));
} else {
if (!create)
return nullptr;
next = (pgmap*) kalloc(levelnames[level-1]);
if (!next)
return nullptr;
memset(next, 0, PGSIZE);
if (!cmpxch(entryp, entry, v2p(next) | PTE_P | PTE_W | flags)) {
kfree((void*) next);
goto retry;
}
}
return next;
}
// Return the address of the PTE in page table pgdir
// that corresponds to linear address va. If create!=0,
// create any required page table pages.
atomic<pme_t>*
walkpgdir(pgmap *pml4, u64 va, int create)
{
auto pdp = descend(pml4, va, PTE_U, create, 3);
if (pdp == nullptr)
return nullptr;
auto pd = descend(pdp, va, PTE_U, create, 2);
if (pd == nullptr)
return nullptr;
auto pt = descend(pd, va, PTE_U, create, 1);
if (pt == nullptr)
return nullptr;
return &pt->e[PX(0,va)];
}
// Map from 0 to 128Gbytes starting at KBASE.
void
initpg(void)
{
u64 va = KBASE;
paddr pa = 0;
while (va < (KBASE+(128ull<<30))) {
auto pdp = descend(&kpml4, va, 0, 1, 3);
auto pd = descend(pdp, va, 0, 1, 2);
atomic<pme_t> *sp = &pd->e[PX(1,va)];
u64 flags = PTE_W | PTE_P | PTE_PS | PTE_NX;
*sp = pa | flags;
va += PGSIZE*512;
pa += PGSIZE*512;
}
}
// Set up kernel part of a page table.
pgmap*
setupkvm(void)
{
pgmap *pml4;
int k;
if((pml4 = (pgmap*)kalloc("PML4")) == 0)
return 0;
k = PX(3, KBASE);
memset(&pml4->e[0], 0, 8*k);
memmove(&pml4->e[k], &kpml4.e[k], 8*(512-k));
return pml4;
}
int
mapkva(pgmap *pml4, char* kva, uptr uva, size_t size)
{
for (u64 off = 0; off < size; off+=4096) {
atomic<pme_t> *pte = walkpgdir(pml4, (u64) (uva+off), 1);
if (pte == nullptr)
return -1;
*pte = v2p(kva+off) | PTE_P | PTE_U | PTE_W;
}
return 0;
}
int
setupuvm(pgmap *pml4, char *kshared, char *uwq)
{
struct todo {
char *kvm;
char *uvm;
size_t size;
} todo[] = {
{ kshared, (char*)KSHARED, KSHAREDSIZE },
{ uwq, (char*)USERWQ, USERWQSIZE }
};
for (int i = 0; i < NELEM(todo); i++) {
for (u64 off = 0; off < todo[i].size; off+=4096) {
atomic<pme_t> *pte = walkpgdir(pml4, (u64) (todo[i].uvm+off), 1);
if (pte == nullptr)
return -1;
*pte = v2p(todo[i].kvm+off) | PTE_P | PTE_U | PTE_W;
}
}
return 0;
}
// Switch h/w page table register to the kernel-only page table,
// for when no process is running.
static void
switchkvm(void)
{
lcr3(v2p(&kpml4)); // switch to the kernel page table
}
// Switch TSS and h/w page table to correspond to process p.
void
switchvm(struct proc *p)
{
u64 base = (u64) &mycpu()->ts;
pushcli();
mycpu()->gdt[TSSSEG>>3] = (struct segdesc)
SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A);
mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base);
mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE;
mycpu()->ts.iomba = (u16)__offsetof(struct taskstate, iopb);
ltr(TSSSEG);
u64 nreq = tlbflush_req.load();
if (p->vmap != 0 && p->vmap->pml4 != 0)
lcr3(v2p(p->vmap->pml4)); // switch to new address space
else
switchkvm();
mycpu()->tlbflush_done = nreq;
writefs(UDSEG);
writemsr(MSR_FS_BASE, p->user_fs_);
popcli();
}
static void
freepm(pgmap *pm, int level)
{
int i;
if (level != 0) {
for (i = 0; i < 512; i++) {
pme_t entry = pm->e[i];
if (entry & PTE_P)
freepm((pgmap*) p2v(PTE_ADDR(entry)), level - 1);
}
}
kfree(pm);
}
// Free a page table and all the physical memory pages
// in the user part.
void
freevm(pgmap *pml4)
{
int k;
int i;
if(pml4 == 0)
panic("freevm: no pgdir");
// Don't free kernel portion of the pml4
k = PX(3, KBASE);
for (i = 0; i < k; i++) {
pme_t entry = pml4->e[i];
if (entry & PTE_P) {
freepm((pgmap*) p2v(PTE_ADDR(entry)), 2);
}
}
kfree(pml4);
}
// Set up CPU's kernel segment descriptors.
// Run once at boot time on each CPU.
void
inittls(void)
{
struct cpu *c;
// Initialize cpu-local storage.
c = &cpus[cpunum()];
writegs(KDSEG);
writemsr(MSR_GS_BASE, (u64)&c->cpu);
writemsr(MSR_GS_KERNBASE, (u64)&c->cpu);
c->cpu = c;
c->proc = nullptr;
c->kmem = &kmems[cpunum()];
}
atomic<u64> tlbflush_req;
void
tlbflush()
{
u64 myreq = ++tlbflush_req;
tlbflush(myreq);
}
void
tlbflush(u64 myreq)
{
// the caller may not hold any spinlock, because other CPUs might
// be spinning waiting for that spinlock, with interrupts disabled,
// so we will deadlock waiting for their TLB flush..
assert(mycpu()->ncli == 0);
for (int i = 0; i < ncpu; i++)
if (cpus[i].tlbflush_done < myreq)
lapic_tlbflush(i);
for (int i = 0; i < ncpu; i++)
while (cpus[i].tlbflush_done < myreq)
/* spin */ ;
}
<|endoftext|>
|
<commit_before>#include <znc/main.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <znc/Nick.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include "twitchtmi.h"
#include "jload.h"
TwitchTMI::~TwitchTMI()
{
}
bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)
{
OnBoot();
if(GetNetwork())
{
for(CChan *ch: GetNetwork()->GetChans())
{
ch->SetTopic(CString());
CString chname = ch->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
}
}
return true;
}
bool TwitchTMI::OnBoot()
{
initCurl();
timer = new TwitchTMIUpdateTimer(this);
AddTimer(timer);
return true;
}
void TwitchTMI::OnIRCConnected()
{
PutIRC("CAP REQ :twitch.tv/membership");
}
CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)
{
if(sLine.Left(5).Equals("WHO #"))
return CModule::HALT;
if(sLine.Left(5).Equals("AWAY "))
return CModule::HALT;
if(sLine.Left(12).Equals("TWITCHCLIENT"))
return CModule::HALT;
if(sLine.Left(9).Equals("JTVCLIENT"))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)
{
CString chname = sChannel.substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnPrivMsg(CNick& nick, CString& sMessage)
{
if(nick.GetNick().Equals("jtv", true))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnChanMsg(CNick& nick, CChan& channel, CString& sMessage)
{
if(nick.GetNick().Equals("jtv", true))
return CModule::HALT;
if(sMessage == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10)
{
std::stringstream ss1, ss2;
CString mynick = GetNetwork()->GetIRCNick().GetNickMask();
ss1 << "PRIVMSG " << channel.GetName() << " :FrankerZ";
ss2 << ":" << mynick << " PRIVMSG " << channel.GetName() << " :FrankerZ";
PutIRC(ss1.str());
PutUser(ss2.str());
if(!channel.AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || channel.IsDetached()) {
channel.AddBuffer(ss2.str());
}
lastFrankerZ = std::time(nullptr);
}
return CModule::CONTINUE;
}
bool TwitchTMI::OnServerCapAvailable(const CString &sCap)
{
if(sCap == "twitch.tv/membership")
{
CUtils::PrintMessage("TwitchTMI: Requesting twitch.tv/membership cap");
return true;
}
CUtils::PrintMessage(CString("TwitchTMI: Not requesting ") + sCap + " cap");
return false;
}
TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)
:CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information")
,mod(tmod)
{
}
void TwitchTMIUpdateTimer::RunJob()
{
if(!mod->GetNetwork())
return;
for(CChan *chan: mod->GetNetwork()->GetChans())
{
CString chname = chan->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));
}
}
void TwitchTMIJob::runThread()
{
std::stringstream ss;
ss << "https://api.twitch.tv/kraken/channels/" << channel;
CString url = ss.str();
Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json");
if(root.isNull())
{
return;
}
Json::Value &titleVal = root["status"];
if(!titleVal.isString())
titleVal = root["title"];
if(!titleVal.isString())
return;
title = titleVal.asString();
}
void TwitchTMIJob::runMain()
{
if(title.empty())
return;
CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel);
if(!chan)
return;
if(!chan->GetTopic().Equals(title, true))
{
chan->SetTopic(title);
chan->SetTopicOwner("jtv");
chan->SetTopicDate((unsigned long)time(nullptr));
std::stringstream ss;
ss << ":jtv TOPIC #" << channel << " :" << title;
mod->PutUser(ss.str());
}
}
template<> void TModInfo<TwitchTMI>(CModInfo &info)
{
info.SetWikiPage("Twitch");
info.SetHasArgs(false);
}
NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module")
<commit_msg>Fix order of reFrankerZ<commit_after>#include <znc/main.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <znc/Nick.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include "twitchtmi.h"
#include "jload.h"
TwitchTMI::~TwitchTMI()
{
}
bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)
{
OnBoot();
if(GetNetwork())
{
for(CChan *ch: GetNetwork()->GetChans())
{
ch->SetTopic(CString());
CString chname = ch->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
}
}
return true;
}
bool TwitchTMI::OnBoot()
{
initCurl();
timer = new TwitchTMIUpdateTimer(this);
AddTimer(timer);
return true;
}
void TwitchTMI::OnIRCConnected()
{
PutIRC("CAP REQ :twitch.tv/membership");
}
CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)
{
if(sLine.Left(5).Equals("WHO #"))
return CModule::HALT;
if(sLine.Left(5).Equals("AWAY "))
return CModule::HALT;
if(sLine.Left(12).Equals("TWITCHCLIENT"))
return CModule::HALT;
if(sLine.Left(9).Equals("JTVCLIENT"))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)
{
CString chname = sChannel.substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnPrivMsg(CNick& nick, CString& sMessage)
{
if(nick.GetNick().Equals("jtv", true))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnChanMsg(CNick& nick, CChan& channel, CString& sMessage)
{
if(nick.GetNick().Equals("jtv", true))
return CModule::HALT;
if(sMessage == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10)
{
std::stringstream ss1, ss2;
CString mynick = GetNetwork()->GetIRCNick().GetNickMask();
ss1 << "PRIVMSG " << channel.GetName() << " :FrankerZ";
ss2 << ":" << mynick << " PRIVMSG " << channel.GetName() << " :";
PutIRC(ss1.str());
CString s2 = ss2.str();
CThreadPool::Get().addJob(new GenericJob([]() {}, [this, s2, &channel]()
{
PutUser(s2 + "FrankerZ");
if(!channel.AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || channel.IsDetached()) {
channel.AddBuffer(s2+ "{text}", "FrankerZ");
}
}));
lastFrankerZ = std::time(nullptr);
}
return CModule::CONTINUE;
}
bool TwitchTMI::OnServerCapAvailable(const CString &sCap)
{
if(sCap == "twitch.tv/membership")
{
CUtils::PrintMessage("TwitchTMI: Requesting twitch.tv/membership cap");
return true;
}
CUtils::PrintMessage(CString("TwitchTMI: Not requesting ") + sCap + " cap");
return false;
}
TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)
:CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information")
,mod(tmod)
{
}
void TwitchTMIUpdateTimer::RunJob()
{
if(!mod->GetNetwork())
return;
for(CChan *chan: mod->GetNetwork()->GetChans())
{
CString chname = chan->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));
}
}
void TwitchTMIJob::runThread()
{
std::stringstream ss;
ss << "https://api.twitch.tv/kraken/channels/" << channel;
CString url = ss.str();
Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json");
if(root.isNull())
{
return;
}
Json::Value &titleVal = root["status"];
if(!titleVal.isString())
titleVal = root["title"];
if(!titleVal.isString())
return;
title = titleVal.asString();
}
void TwitchTMIJob::runMain()
{
if(title.empty())
return;
CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel);
if(!chan)
return;
if(!chan->GetTopic().Equals(title, true))
{
chan->SetTopic(title);
chan->SetTopicOwner("jtv");
chan->SetTopicDate((unsigned long)time(nullptr));
std::stringstream ss;
ss << ":jtv TOPIC #" << channel << " :" << title;
mod->PutUser(ss.str());
}
}
template<> void TModInfo<TwitchTMI>(CModInfo &info)
{
info.SetWikiPage("Twitch");
info.SetHasArgs(false);
}
NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module")
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Dave Coleman */
#include "widgets/setup_assistant_widget.h"
#include <ros/ros.h>
#include <QApplication>
#include <QMessageBox>
#include <boost/program_options.hpp>
#include <signal.h>
static void siginthandler(int param)
{
QApplication::quit();
}
int main(int argc, char **argv)
{
// Parse parameters
namespace po = boost::program_options;
// Declare the supported options
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message")
("debug", "Run in debug/test mode")
("urdf_path", po::value<std::string>(), "Optional, relative path to URDF in URDF package")
("config_pkg", po::value<std::string>(), "Optional, pass in existing config package to load");
// Process options
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << std::endl;
return 1;
}
// Start ROS Node
ros::init(argc, argv, "moveit_setup_assistant", ros::init_options::NoSigintHandler);
// ROS Spin
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
// Create Qt Application
QApplication qtApp(argc, argv);
// Load Qt Widget
moveit_setup_assistant::SetupAssistantWidget saw( NULL, vm );
saw.setMinimumWidth(980);
saw.setMinimumHeight(550);
// saw.setWindowState( Qt::WindowMaximized );
saw.show();
signal(SIGINT, siginthandler);
// Wait here until Qt App is finished
const int result = qtApp.exec();
// Shutdown ROS
ros::shutdown();
return result;
}
<commit_msg>write float numbers always in POSIX format (#123)<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Dave Coleman */
#include "widgets/setup_assistant_widget.h"
#include <ros/ros.h>
#include <QApplication>
#include <QMessageBox>
#include <boost/program_options.hpp>
#include <signal.h>
#include <locale.h>
static void siginthandler(int param)
{
QApplication::quit();
}
int main(int argc, char **argv)
{
// Parse parameters
namespace po = boost::program_options;
// Declare the supported options
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message")
("debug", "Run in debug/test mode")
("urdf_path", po::value<std::string>(), "Optional, relative path to URDF in URDF package")
("config_pkg", po::value<std::string>(), "Optional, pass in existing config package to load");
// Process options
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << std::endl;
return 1;
}
// Start ROS Node
ros::init(argc, argv, "moveit_setup_assistant", ros::init_options::NoSigintHandler);
// ROS Spin
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
// Create Qt Application
QApplication qtApp(argc, argv);
// numeric values should always be POSIX
setlocale(LC_NUMERIC, "C");
// Load Qt Widget
moveit_setup_assistant::SetupAssistantWidget saw( NULL, vm );
saw.setMinimumWidth(980);
saw.setMinimumHeight(550);
// saw.setWindowState( Qt::WindowMaximized );
saw.show();
signal(SIGINT, siginthandler);
// Wait here until Qt App is finished
const int result = qtApp.exec();
// Shutdown ROS
ros::shutdown();
return result;
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Dave Coleman */
#include "widgets/setup_assistant_widget.h"
#include <ros/ros.h>
#include <QApplication>
#include <QMessageBox>
#include <boost/program_options.hpp>
#include <signal.h>
#include <locale.h>
static void siginthandler(int /*param*/)
{
QApplication::quit();
}
void usage(boost::program_options::options_description& desc, int exit_code)
{
std::cout << desc << std::endl;
exit(exit_code);
}
int main(int argc, char** argv)
{
// Parse parameters
namespace po = boost::program_options;
// Declare the supported options
po::options_description desc("Allowed options");
desc.add_options()("help,h", "Show help message")("debug,g", "Run in debug/test mode")(
"urdf_path,u", po::value<std::string>(), "Optional, path to URDF file in ROS package")(
"config_pkg,c", po::value<std::string>(), "Optional, pass in existing config package to load");
// Process options
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
usage(desc, 0);
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
usage(desc, 1);
}
// Start ROS Node
ros::init(argc, argv, "moveit_setup_assistant", ros::init_options::NoSigintHandler);
// ROS Spin
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
// Create Qt Application
QApplication qt_app(argc, argv);
// numeric values should always be POSIX
setlocale(LC_NUMERIC, "C");
// Load Qt Widget
moveit_setup_assistant::SetupAssistantWidget saw(nullptr, vm);
saw.setMinimumWidth(980);
saw.setMinimumHeight(550);
// saw.setWindowState( Qt::WindowMaximized );
saw.show();
signal(SIGINT, siginthandler);
// Wait here until Qt App is finished
const int result = qt_app.exec();
// Shutdown ROS
ros::shutdown();
return result;
}
<commit_msg>Increase minimal window size<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Dave Coleman */
#include "widgets/setup_assistant_widget.h"
#include <ros/ros.h>
#include <QApplication>
#include <QMessageBox>
#include <boost/program_options.hpp>
#include <signal.h>
#include <locale.h>
static void siginthandler(int /*param*/)
{
QApplication::quit();
}
void usage(boost::program_options::options_description& desc, int exit_code)
{
std::cout << desc << std::endl;
exit(exit_code);
}
int main(int argc, char** argv)
{
// Parse parameters
namespace po = boost::program_options;
// Declare the supported options
po::options_description desc("Allowed options");
desc.add_options()("help,h", "Show help message")("debug,g", "Run in debug/test mode")(
"urdf_path,u", po::value<std::string>(), "Optional, path to URDF file in ROS package")(
"config_pkg,c", po::value<std::string>(), "Optional, pass in existing config package to load");
// Process options
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
usage(desc, 0);
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
usage(desc, 1);
}
// Start ROS Node
ros::init(argc, argv, "moveit_setup_assistant", ros::init_options::NoSigintHandler);
// ROS Spin
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
// Create Qt Application
QApplication qt_app(argc, argv);
// numeric values should always be POSIX
setlocale(LC_NUMERIC, "C");
// Load Qt Widget
moveit_setup_assistant::SetupAssistantWidget saw(nullptr, vm);
saw.setMinimumWidth(1090);
saw.setMinimumHeight(600);
// saw.setWindowState( Qt::WindowMaximized );
saw.show();
signal(SIGINT, siginthandler);
// Wait here until Qt App is finished
const int result = qt_app.exec();
// Shutdown ROS
ros::shutdown();
return result;
}
<|endoftext|>
|
<commit_before>#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <BH1750.h>
#include "sensors/TemperatureSensor.hpp"
#include "sensors/RainStatusSensor.hpp"
#include <Time.h>
#include <DS1307RTC.h>
#include <SFE_BMP180.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
BH1750 lightMeter;
SFE_BMP180 barometer;
TemperatureSensor temperatureSensor(0);
RainStatusSensor rainStatusSensor(2);
float temperature;
bool rainStatus;
unsigned long lightLevel;
tmElements_t tm;
double pressure;
double getPressure(float altitude);
void getSensorData()
{
temperature = temperatureSensor.readTemperature();
rainStatus = rainStatusSensor.readRainStatus();
lightLevel = lightMeter.readLightLevel();
pressure = getPressure(406.776); // wysokość zhardcode'owana dla Nowej Rudy, DO ZMIANY!
}
void initSensors()
{
Serial.begin(9600);
lcd.begin(20, 4);
barometer.begin();
lightMeter.begin();
}
double getPressure(float altitude)
{
char status;
double temperature, pressure;
status = barometer.startTemperature();
if (status != 0)
{
delay(status);
status = barometer.getTemperature(temperature);
if(status != 0)
{
delay(status);
status = barometer.startPressure(3);
if(status != 0)
{
delay(status);
status = barometer.getPressure(pressure, temperature);
if(status != 0)
return barometer.sealevel(pressure, altitude);
}
}
}
}
<commit_msg>Dodano domyślną wartość zwracaną przez getPressure w razie błędu W razie błędów funkcja `getPressure` zwraca 0.<commit_after>#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <BH1750.h>
#include "sensors/TemperatureSensor.hpp"
#include "sensors/RainStatusSensor.hpp"
#include <Time.h>
#include <DS1307RTC.h>
#include <SFE_BMP180.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
BH1750 lightMeter;
SFE_BMP180 barometer;
TemperatureSensor temperatureSensor(0);
RainStatusSensor rainStatusSensor(2);
float temperature;
bool rainStatus;
unsigned long lightLevel;
tmElements_t tm;
double pressure;
double getPressure(float altitude);
void getSensorData()
{
temperature = temperatureSensor.readTemperature();
rainStatus = rainStatusSensor.readRainStatus();
lightLevel = lightMeter.readLightLevel();
pressure = getPressure(406.776); // wysokość zhardcode'owana dla Nowej Rudy, DO ZMIANY!
}
void initSensors()
{
Serial.begin(9600);
lcd.begin(20, 4);
barometer.begin();
lightMeter.begin();
}
double getPressure(float altitude)
{
char status;
double temperature, pressure;
status = barometer.startTemperature();
if (status != 0)
{
delay(status);
status = barometer.getTemperature(temperature);
if(status != 0)
{
delay(status);
status = barometer.startPressure(3);
if(status != 0)
{
delay(status);
status = barometer.getPressure(pressure, temperature);
if(status != 0)
return barometer.sealevel(pressure, altitude);
}
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* Twofold-ChaiScript
* (C) Copyright 2015 HicknHack Software GmbH
*
* The original code can be found at:
* https://github.com/arBmind/Twofold-ChaiScript
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ChaiScriptTargetBuilderApi.h"
#include <chaiscript/utility/utility.hpp>
namespace Twofold {
namespace intern {
namespace {
template< typename T, typename S>
std::pair<T,S> make_pair(const T& t, const S& s) {
return std::pair<T,S>(t, s);
}
} // namespace
ChaiScriptTargetBuilderApi::ChaiScriptTargetBuilderApi(const FileLineColumnPositionList &originPositions)
: m_originPositions(originPositions)
{}
void ChaiScriptTargetBuilderApi::add_class(chaiscript::Module &module)
{
chaiscript::utility::add_class<ChaiScriptTargetBuilderApi>(
module,
"TwofoldTemplate",
{},
{
{ chaiscript::fun(&append), "append" },
{ chaiscript::fun(&newLine), "newLine" },
{ chaiscript::fun(&pushIndentation), "pushIndentation" },
{ chaiscript::fun(&popIndentation), "popIndentation" },
{ chaiscript::fun(&indentPart), "indentPart" },
{ chaiscript::fun(&pushPartIndent), "pushPartIndent" },
{ chaiscript::fun(&popPartIndent), "popPartIndent" },
}
);
}
void ChaiScriptTargetBuilderApi::append(const std::string &text, int originIndex)
{
if (!text.empty()) {
m_sourceMapBuilder << OriginText { m_originPositions[originIndex], QString::fromStdString(text), Interpolation::None };
}
}
void ChaiScriptTargetBuilderApi::newLine()
{
m_sourceMapBuilder << NewLine();
}
void ChaiScriptTargetBuilderApi::pushIndentation(const std::string &_indent, int originIndex)
{
_pushIndentation(QString::fromStdString(_indent), originIndex);
}
void ChaiScriptTargetBuilderApi::_pushIndentation(const QString &indent, int originIndex)
{
QString fullIndent = indent;
if (!m_indentationStack.empty()) fullIndent.prepend(m_indentationStack.back().second);
m_indentationStack.push_back(make_pair(indent, fullIndent));
m_sourceMapBuilder.pushCaller(m_originPositions[originIndex]);
m_sourceMapBuilder.setIndentation(fullIndent);
}
void ChaiScriptTargetBuilderApi::popIndentation()
{
m_indentationStack.pop_back();
m_sourceMapBuilder.popCaller();
QString newIndent = m_indentationStack.empty() ? QString() : m_indentationStack.back().second;
m_sourceMapBuilder.setIndentation(newIndent);
}
void ChaiScriptTargetBuilderApi::indentPart(const std::string &_indent, int originIndex)
{
QString indent = QString::fromStdString(_indent);
if (m_sourceMapBuilder.isBlankLine()) {
m_partIndent = indent;
}
m_sourceMapBuilder << OriginText { m_originPositions[originIndex], indent, Interpolation::None };
}
void ChaiScriptTargetBuilderApi::pushPartIndent(int originIndex)
{
_pushIndentation(m_partIndent, originIndex);
}
void ChaiScriptTargetBuilderApi::popPartIndent()
{
m_partIndent = m_indentationStack.back().first;
popIndentation();
}
} // namespace intern
} // namespace Twofold
<commit_msg>added member function class scope<commit_after>/* Twofold-ChaiScript
* (C) Copyright 2015 HicknHack Software GmbH
*
* The original code can be found at:
* https://github.com/arBmind/Twofold-ChaiScript
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ChaiScriptTargetBuilderApi.h"
#include <chaiscript/utility/utility.hpp>
namespace Twofold {
namespace intern {
namespace {
template< typename T, typename S>
std::pair<T,S> make_pair(const T& t, const S& s) {
return std::pair<T,S>(t, s);
}
} // namespace
ChaiScriptTargetBuilderApi::ChaiScriptTargetBuilderApi(const FileLineColumnPositionList &originPositions)
: m_originPositions(originPositions)
{}
void ChaiScriptTargetBuilderApi::add_class(chaiscript::Module &module)
{
using Api = ChaiScriptTargetBuilderApi;
using namespace chaiscript;
utility::add_class<Api>(
module,
"TwofoldTemplate",
{},
{
{ fun(&Api::append), "append" },
{ fun(&Api::newLine), "newLine" },
{ fun(&Api::pushIndentation), "pushIndentation" },
{ fun(&Api::popIndentation), "popIndentation" },
{ fun(&Api::indentPart), "indentPart" },
{ fun(&Api::pushPartIndent), "pushPartIndent" },
{ fun(&Api::popPartIndent), "popPartIndent" },
});
}
void ChaiScriptTargetBuilderApi::append(const std::string &text, int originIndex)
{
if (!text.empty()) {
m_sourceMapBuilder << OriginText { m_originPositions[originIndex], QString::fromStdString(text), Interpolation::None };
}
}
void ChaiScriptTargetBuilderApi::newLine()
{
m_sourceMapBuilder << NewLine();
}
void ChaiScriptTargetBuilderApi::pushIndentation(const std::string &_indent, int originIndex)
{
_pushIndentation(QString::fromStdString(_indent), originIndex);
}
void ChaiScriptTargetBuilderApi::_pushIndentation(const QString &indent, int originIndex)
{
QString fullIndent = indent;
if (!m_indentationStack.empty()) fullIndent.prepend(m_indentationStack.back().second);
m_indentationStack.push_back(make_pair(indent, fullIndent));
m_sourceMapBuilder.pushCaller(m_originPositions[originIndex]);
m_sourceMapBuilder.setIndentation(fullIndent);
}
void ChaiScriptTargetBuilderApi::popIndentation()
{
m_indentationStack.pop_back();
m_sourceMapBuilder.popCaller();
QString newIndent = m_indentationStack.empty() ? QString() : m_indentationStack.back().second;
m_sourceMapBuilder.setIndentation(newIndent);
}
void ChaiScriptTargetBuilderApi::indentPart(const std::string &_indent, int originIndex)
{
QString indent = QString::fromStdString(_indent);
if (m_sourceMapBuilder.isBlankLine()) {
m_partIndent = indent;
}
m_sourceMapBuilder << OriginText { m_originPositions[originIndex], indent, Interpolation::None };
}
void ChaiScriptTargetBuilderApi::pushPartIndent(int originIndex)
{
_pushIndentation(m_partIndent, originIndex);
}
void ChaiScriptTargetBuilderApi::popPartIndent()
{
m_partIndent = m_indentationStack.back().first;
popIndentation();
}
} // namespace intern
} // namespace Twofold
<|endoftext|>
|
<commit_before>// Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "AllocateInTracee.h"
#include <absl/base/casts.h>
#include <absl/strings/str_format.h>
#include <linux/seccomp.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <cstdint>
#include <string>
#include <thread>
#include <vector>
#include "AccessTraceesMemory.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/SafeStrerror.h"
#include "ReadSeccompModeOfThread.h"
#include "RegisterState.h"
namespace orbit_user_space_instrumentation {
namespace {
// Execute a single syscall instruction in tracee `pid`. `syscall` identifies the syscall as in this
// list: https://github.com/torvalds/linux/blob/master/arch/x86/entry/syscalls/syscall_64.tbl
// The parameters and the ordering are the same as in the C wrapper:
// https://man7.org/linux/man-pages/dir_section_2.html
// Optionally one can specify `exclude_address`. This prevents the method from using an address
// range containing `exclude_address` as a working area. This is required for the munmap syscall
// which might otherwise choose the mapping it is removing as a working area.
[[nodiscard]] ErrorMessageOr<uint64_t> SyscallInTracee(pid_t pid, uint64_t syscall, uint64_t arg_0,
uint64_t arg_1, uint64_t arg_2,
uint64_t arg_3, uint64_t arg_4,
uint64_t arg_5, uint64_t exclude_address) {
RegisterState original_registers;
auto register_backup_result = original_registers.BackupRegisters(pid);
if (register_backup_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to backup original register state: %s",
register_backup_result.error().message()));
}
if (original_registers.GetBitness() != RegisterState::Bitness::k64Bit) {
return ErrorMessage(
"Tried to invoke syscall in 32 bit process. This is currently not supported.");
}
// Get an executable memory region.
auto memory_region_or_error = GetExistingExecutableMemoryRegion(pid, exclude_address);
if (memory_region_or_error.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to find executable memory region: %s",
memory_region_or_error.error().message()));
}
const uint64_t start_address = memory_region_or_error.value().start;
// Backup first 8 bytes.
auto backup_or_error = ReadTraceesMemory(pid, start_address, 8);
if (backup_or_error.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to read from tracee's memory: %s",
backup_or_error.error().message()));
}
const std::vector<uint8_t> backup = std::move(backup_or_error.value());
// Write `syscall` into memory. Machine code is `0x0f05`.
auto write_code_result = WriteTraceesMemory(pid, start_address, std::vector<uint8_t>{0x0f, 0x05});
if (write_code_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to write to tracee's memory: %s",
write_code_result.error().message()));
}
std::shared_ptr<void> restore_memory_on_return{
nullptr, [pid, start_address, backup](void* /*ptr*/) {
auto restore_memory_result = WriteTraceesMemory(pid, start_address, backup);
if (restore_memory_result.has_error()) {
ORBIT_ERROR("Unable to restore memory state of tracee: %s",
restore_memory_result.error().message());
}
}};
// Move instruction pointer to the `syscall` and fill registers with parameters.
RegisterState registers_for_syscall = original_registers;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rip = start_address;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rax = syscall;
// Register list for arguments can be found e.g. in the glibc wrapper:
// https://github.com/bminor/glibc/blob/master/sysdeps/unix/sysv/linux/x86_64/syscall.S#L30
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rdi = arg_0;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rsi = arg_1;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rdx = arg_2;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.r10 = arg_3;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.r8 = arg_4;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.r9 = arg_5;
auto restore_registers_result = registers_for_syscall.RestoreRegisters();
if (restore_registers_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to set registers with syscall parameters: %s",
restore_registers_result.error().message()));
}
std::shared_ptr<void> restore_registers_on_return{
nullptr, [&original_registers](void* /*ptr*/) {
auto restore_registers_result = original_registers.RestoreRegisters();
if (restore_registers_result.has_error()) {
ORBIT_ERROR("Unable to restore register state of tracee: %s",
restore_registers_result.error().message());
}
}};
// The system call could cause the thread to be killed, so we need to read the seccomp mode
// before actually executing the system call.
const std::optional<int> seccomp_mode = ReadSeccompModeOfThread(pid);
std::string seccomp_message_suffix;
if (seccomp_mode.has_value() && seccomp_mode.value() == SECCOMP_MODE_STRICT) {
seccomp_message_suffix = absl::StrFormat(
" This might be due to thread %d being in seccomp mode %d (SECCOMP_MODE_STRICT).", pid,
SECCOMP_MODE_STRICT);
} else if (seccomp_mode.has_value() && seccomp_mode.value() == SECCOMP_MODE_FILTER) {
seccomp_message_suffix = absl::StrFormat(
" This might be due to thread %d being in seccomp mode %d (SECCOMP_MODE_FILTER).", pid,
SECCOMP_MODE_FILTER);
}
// Single step to execute the syscall.
if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) != 0) {
return ErrorMessage("Failed to execute syscall with PTRACE_SINGLESTEP.");
}
int status = 0;
pid_t waited = waitpid(pid, &status, 0);
if (waited != pid || !WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP) {
return ErrorMessage(absl::StrFormat("Failed to wait for PTRACE_SINGLESTEP to execute.%s",
seccomp_message_suffix));
}
// Return value of syscalls is in rax.
RegisterState return_value;
auto return_value_result = return_value.BackupRegisters(pid);
if (return_value_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to get registers with result of syscall: %s",
return_value_result.error().message()));
}
const uint64_t result = return_value.GetGeneralPurposeRegisters()->x86_64.rax;
// Syscalls return -4095, ..., -1 on failure. And these are actually (-1 * errno)
const int64_t result_as_int = absl::bit_cast<int64_t>(result);
if (result_as_int > -4096 && result_as_int < 0) {
return ErrorMessage(absl::StrFormat("Syscall failed. Return value: %s (%d).%s",
SafeStrerror(-result_as_int), result_as_int,
seccomp_message_suffix));
}
return result;
}
} // namespace
ErrorMessageOr<std::unique_ptr<MemoryInTracee>> MemoryInTracee::Create(pid_t pid, uint64_t address,
uint64_t size) {
// Syscall will be equivalent to:
// `mmap(address, size, PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)`
// We just set `PROT_WRITE` but this permits also read access (on x86) although the read flag will
// not show up in /proc/pid/maps. Setting `PROT_READ` explicitly would be clearer but under some
// circumstances (personality setting READ_IMPLIES_EXEC) `PROT_READ` sets the flag permitting
// execution and we want to avoid that.
constexpr uint64_t kSyscallNumberMmap = 9;
auto result_or_error = SyscallInTracee(pid, kSyscallNumberMmap, address, size, PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, static_cast<uint64_t>(-1), 0,
/*exclude_address=*/0);
if (result_or_error.has_error()) {
return ErrorMessage(absl::StrFormat(
"Failed to execute mmap syscall with parameters address=%#x size=%u prot=PROT_WRITE: %s",
address, size, result_or_error.error().message()));
}
std::unique_ptr<MemoryInTracee> result(
new MemoryInTracee(pid, result_or_error.value(), size, MemoryInTracee::State::kWritable));
if (address != 0 && result->GetAddress() != address) {
auto free_memory_result = result->Free();
ORBIT_FAIL_IF(free_memory_result.has_error(), "Unable to free previously allocated memory: %s",
free_memory_result.error().message());
return ErrorMessage(
absl::StrFormat("MemoryInTracee wanted to allocate memory at %#x but got memory at a "
"different address: %#x. The memory has been freed again.",
address, result->GetAddress()));
}
return result;
}
ErrorMessageOr<void> MemoryInTracee::Free() {
// Syscall will be equivalent to:
// `munmap(address, size)`
constexpr uint64_t kSyscallNumberMunmap = 11;
auto result_or_error =
SyscallInTracee(pid_, kSyscallNumberMunmap, address_, size_, 0, 0, 0, 0, address_);
if (result_or_error.has_error()) {
return ErrorMessage(
absl::StrFormat("Failed to execute munmap syscall: %s", result_or_error.error().message()));
}
pid_ = -1;
address_ = 0;
size_ = 0;
state_ = State::kWritable;
return outcome::success();
}
ErrorMessageOr<void> MemoryInTracee::EnsureMemoryExecutable() {
if (state_ == State::kExecutable) {
return outcome::success();
}
constexpr uint64_t kSyscallNumberMprotect = 10;
auto result_or_error =
SyscallInTracee(pid_, kSyscallNumberMprotect, address_, size_, PROT_EXEC, 0, 0, 0, 0);
if (result_or_error.has_error()) {
return ErrorMessage(absl::StrFormat(
"Failed to execute mprotect syscall with parameters address=%#x size=%u prot=PROT_EXEC: %s",
address_, size_, result_or_error.error().message()));
}
state_ = State::kExecutable;
return outcome::success();
}
ErrorMessageOr<void> MemoryInTracee::EnsureMemoryWritable() {
if (state_ == State::kWritable) {
return outcome::success();
}
constexpr uint64_t kSyscallNumberMprotect = 10;
auto result_or_error =
SyscallInTracee(pid_, kSyscallNumberMprotect, address_, size_, PROT_WRITE, 0, 0, 0, 0);
if (result_or_error.has_error()) {
return ErrorMessage(
absl::StrFormat("Failed to execute mprotect syscall with parameters address=%#x size=%u "
"prot=PROT_WRITE: %s",
address_, size_, result_or_error.error().message()));
}
state_ = State::kWritable;
return outcome::success();
}
ErrorMessageOr<std::unique_ptr<AutomaticMemoryInTracee>> AutomaticMemoryInTracee::Create(
pid_t pid, uint64_t address, uint64_t size) {
// Syscall will be equivalent to:
// `mmap(address, size, PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)`
// We just set `PROT_WRITE` but this permits also read access (on x86) although the read flag will
// not show up in /proc/pid/maps. Setting `PROT_READ` explicitly would be clearer but under some
// circumstances (personality setting READ_IMPLIES_EXEC) `PROT_READ` sets the flag permitting
// execution and we want to avoid that.
constexpr uint64_t kSyscallNumberMmap = 9;
auto result_or_error = SyscallInTracee(pid, kSyscallNumberMmap, address, size, PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, static_cast<uint64_t>(-1), 0,
/*exclude_address=*/0);
if (result_or_error.has_error()) {
return ErrorMessage(
absl::StrFormat("Failed to execute mmap syscall with parameters address=%#x size=%u: %s",
address, size, result_or_error.error().message()));
}
std::unique_ptr<AutomaticMemoryInTracee> result(new AutomaticMemoryInTracee(
pid, result_or_error.value(), size, AutomaticMemoryInTracee::State::kWritable));
if (address != 0 && result->GetAddress() != address) {
auto free_memory_result = result->Free();
ORBIT_FAIL_IF(free_memory_result.has_error(), "Unable to free previously allocated memory: %s",
free_memory_result.error().message());
return ErrorMessage(absl::StrFormat(
"AutomaticMemoryInTracee wanted to allocate memory at %#x but got memory at a "
"different address: %#x. The memory has been freed again.",
address, result->GetAddress()));
}
return result;
}
AutomaticMemoryInTracee::~AutomaticMemoryInTracee() {
if (pid_ == -1) return; // Freed manually already.
auto result = Free();
if (result.has_error()) {
ORBIT_ERROR("Unable to free memory in tracee: %s", result.error().message());
}
}
} // namespace orbit_user_space_instrumentation<commit_msg>Fix access permissions in EnsureMemoryExecutable. (#4328)<commit_after>// Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "AllocateInTracee.h"
#include <absl/base/casts.h>
#include <absl/strings/str_format.h>
#include <linux/seccomp.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <cstdint>
#include <string>
#include <thread>
#include <vector>
#include "AccessTraceesMemory.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/SafeStrerror.h"
#include "ReadSeccompModeOfThread.h"
#include "RegisterState.h"
namespace orbit_user_space_instrumentation {
namespace {
// Execute a single syscall instruction in tracee `pid`. `syscall` identifies the syscall as in this
// list: https://github.com/torvalds/linux/blob/master/arch/x86/entry/syscalls/syscall_64.tbl
// The parameters and the ordering are the same as in the C wrapper:
// https://man7.org/linux/man-pages/dir_section_2.html
// Optionally one can specify `exclude_address`. This prevents the method from using an address
// range containing `exclude_address` as a working area. This is required for the munmap syscall
// which might otherwise choose the mapping it is removing as a working area.
[[nodiscard]] ErrorMessageOr<uint64_t> SyscallInTracee(pid_t pid, uint64_t syscall, uint64_t arg_0,
uint64_t arg_1, uint64_t arg_2,
uint64_t arg_3, uint64_t arg_4,
uint64_t arg_5, uint64_t exclude_address) {
RegisterState original_registers;
auto register_backup_result = original_registers.BackupRegisters(pid);
if (register_backup_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to backup original register state: %s",
register_backup_result.error().message()));
}
if (original_registers.GetBitness() != RegisterState::Bitness::k64Bit) {
return ErrorMessage(
"Tried to invoke syscall in 32 bit process. This is currently not supported.");
}
// Get an executable memory region.
auto memory_region_or_error = GetExistingExecutableMemoryRegion(pid, exclude_address);
if (memory_region_or_error.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to find executable memory region: %s",
memory_region_or_error.error().message()));
}
const uint64_t start_address = memory_region_or_error.value().start;
// Backup first 8 bytes.
auto backup_or_error = ReadTraceesMemory(pid, start_address, 8);
if (backup_or_error.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to read from tracee's memory: %s",
backup_or_error.error().message()));
}
const std::vector<uint8_t> backup = std::move(backup_or_error.value());
// Write `syscall` into memory. Machine code is `0x0f05`.
auto write_code_result = WriteTraceesMemory(pid, start_address, std::vector<uint8_t>{0x0f, 0x05});
if (write_code_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to write to tracee's memory: %s",
write_code_result.error().message()));
}
std::shared_ptr<void> restore_memory_on_return{
nullptr, [pid, start_address, backup](void* /*ptr*/) {
auto restore_memory_result = WriteTraceesMemory(pid, start_address, backup);
if (restore_memory_result.has_error()) {
ORBIT_ERROR("Unable to restore memory state of tracee: %s",
restore_memory_result.error().message());
}
}};
// Move instruction pointer to the `syscall` and fill registers with parameters.
RegisterState registers_for_syscall = original_registers;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rip = start_address;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rax = syscall;
// Register list for arguments can be found e.g. in the glibc wrapper:
// https://github.com/bminor/glibc/blob/master/sysdeps/unix/sysv/linux/x86_64/syscall.S#L30
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rdi = arg_0;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rsi = arg_1;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.rdx = arg_2;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.r10 = arg_3;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.r8 = arg_4;
registers_for_syscall.GetGeneralPurposeRegisters()->x86_64.r9 = arg_5;
auto restore_registers_result = registers_for_syscall.RestoreRegisters();
if (restore_registers_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to set registers with syscall parameters: %s",
restore_registers_result.error().message()));
}
std::shared_ptr<void> restore_registers_on_return{
nullptr, [&original_registers](void* /*ptr*/) {
auto restore_registers_result = original_registers.RestoreRegisters();
if (restore_registers_result.has_error()) {
ORBIT_ERROR("Unable to restore register state of tracee: %s",
restore_registers_result.error().message());
}
}};
// The system call could cause the thread to be killed, so we need to read the seccomp mode
// before actually executing the system call.
const std::optional<int> seccomp_mode = ReadSeccompModeOfThread(pid);
std::string seccomp_message_suffix;
if (seccomp_mode.has_value() && seccomp_mode.value() == SECCOMP_MODE_STRICT) {
seccomp_message_suffix = absl::StrFormat(
" This might be due to thread %d being in seccomp mode %d (SECCOMP_MODE_STRICT).", pid,
SECCOMP_MODE_STRICT);
} else if (seccomp_mode.has_value() && seccomp_mode.value() == SECCOMP_MODE_FILTER) {
seccomp_message_suffix = absl::StrFormat(
" This might be due to thread %d being in seccomp mode %d (SECCOMP_MODE_FILTER).", pid,
SECCOMP_MODE_FILTER);
}
// Single step to execute the syscall.
if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) != 0) {
return ErrorMessage("Failed to execute syscall with PTRACE_SINGLESTEP.");
}
int status = 0;
pid_t waited = waitpid(pid, &status, 0);
if (waited != pid || !WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP) {
return ErrorMessage(absl::StrFormat("Failed to wait for PTRACE_SINGLESTEP to execute.%s",
seccomp_message_suffix));
}
// Return value of syscalls is in rax.
RegisterState return_value;
auto return_value_result = return_value.BackupRegisters(pid);
if (return_value_result.has_error()) {
return ErrorMessage(absl::StrFormat("Failed to get registers with result of syscall: %s",
return_value_result.error().message()));
}
const uint64_t result = return_value.GetGeneralPurposeRegisters()->x86_64.rax;
// Syscalls return -4095, ..., -1 on failure. And these are actually (-1 * errno)
const int64_t result_as_int = absl::bit_cast<int64_t>(result);
if (result_as_int > -4096 && result_as_int < 0) {
return ErrorMessage(absl::StrFormat("Syscall failed. Return value: %s (%d).%s",
SafeStrerror(-result_as_int), result_as_int,
seccomp_message_suffix));
}
return result;
}
} // namespace
ErrorMessageOr<std::unique_ptr<MemoryInTracee>> MemoryInTracee::Create(pid_t pid, uint64_t address,
uint64_t size) {
// Syscall will be equivalent to:
// `mmap(address, size, PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)`
// We just set `PROT_WRITE` but this permits also read access (on x86) although the read flag will
// not show up in /proc/pid/maps. Setting `PROT_READ` explicitly would be clearer but under some
// circumstances (personality setting READ_IMPLIES_EXEC) `PROT_READ` sets the flag permitting
// execution and we want to avoid that.
constexpr uint64_t kSyscallNumberMmap = 9;
auto result_or_error = SyscallInTracee(pid, kSyscallNumberMmap, address, size, PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, static_cast<uint64_t>(-1), 0,
/*exclude_address=*/0);
if (result_or_error.has_error()) {
return ErrorMessage(absl::StrFormat(
"Failed to execute mmap syscall with parameters address=%#x size=%u prot=PROT_WRITE: %s",
address, size, result_or_error.error().message()));
}
std::unique_ptr<MemoryInTracee> result(
new MemoryInTracee(pid, result_or_error.value(), size, MemoryInTracee::State::kWritable));
if (address != 0 && result->GetAddress() != address) {
auto free_memory_result = result->Free();
ORBIT_FAIL_IF(free_memory_result.has_error(), "Unable to free previously allocated memory: %s",
free_memory_result.error().message());
return ErrorMessage(
absl::StrFormat("MemoryInTracee wanted to allocate memory at %#x but got memory at a "
"different address: %#x. The memory has been freed again.",
address, result->GetAddress()));
}
return result;
}
ErrorMessageOr<void> MemoryInTracee::Free() {
// Syscall will be equivalent to:
// `munmap(address, size)`
constexpr uint64_t kSyscallNumberMunmap = 11;
auto result_or_error =
SyscallInTracee(pid_, kSyscallNumberMunmap, address_, size_, 0, 0, 0, 0, address_);
if (result_or_error.has_error()) {
return ErrorMessage(
absl::StrFormat("Failed to execute munmap syscall: %s", result_or_error.error().message()));
}
pid_ = -1;
address_ = 0;
size_ = 0;
state_ = State::kWritable;
return outcome::success();
}
ErrorMessageOr<void> MemoryInTracee::EnsureMemoryExecutable() {
if (state_ == State::kExecutable) {
return outcome::success();
}
constexpr uint64_t kSyscallNumberMprotect = 10;
auto result_or_error = SyscallInTracee(pid_, kSyscallNumberMprotect, address_, size_,
PROT_EXEC | PROT_READ, 0, 0, 0, 0);
if (result_or_error.has_error()) {
return ErrorMessage(absl::StrFormat(
"Failed to execute mprotect syscall with parameters address=%#x size=%u prot=PROT_EXEC: %s",
address_, size_, result_or_error.error().message()));
}
state_ = State::kExecutable;
return outcome::success();
}
ErrorMessageOr<void> MemoryInTracee::EnsureMemoryWritable() {
if (state_ == State::kWritable) {
return outcome::success();
}
constexpr uint64_t kSyscallNumberMprotect = 10;
auto result_or_error =
SyscallInTracee(pid_, kSyscallNumberMprotect, address_, size_, PROT_WRITE, 0, 0, 0, 0);
if (result_or_error.has_error()) {
return ErrorMessage(
absl::StrFormat("Failed to execute mprotect syscall with parameters address=%#x size=%u "
"prot=PROT_WRITE: %s",
address_, size_, result_or_error.error().message()));
}
state_ = State::kWritable;
return outcome::success();
}
ErrorMessageOr<std::unique_ptr<AutomaticMemoryInTracee>> AutomaticMemoryInTracee::Create(
pid_t pid, uint64_t address, uint64_t size) {
// Syscall will be equivalent to:
// `mmap(address, size, PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)`
// We just set `PROT_WRITE` but this permits also read access (on x86) although the read flag will
// not show up in /proc/pid/maps. Setting `PROT_READ` explicitly would be clearer but under some
// circumstances (personality setting READ_IMPLIES_EXEC) `PROT_READ` sets the flag permitting
// execution and we want to avoid that.
constexpr uint64_t kSyscallNumberMmap = 9;
auto result_or_error = SyscallInTracee(pid, kSyscallNumberMmap, address, size, PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, static_cast<uint64_t>(-1), 0,
/*exclude_address=*/0);
if (result_or_error.has_error()) {
return ErrorMessage(
absl::StrFormat("Failed to execute mmap syscall with parameters address=%#x size=%u: %s",
address, size, result_or_error.error().message()));
}
std::unique_ptr<AutomaticMemoryInTracee> result(new AutomaticMemoryInTracee(
pid, result_or_error.value(), size, AutomaticMemoryInTracee::State::kWritable));
if (address != 0 && result->GetAddress() != address) {
auto free_memory_result = result->Free();
ORBIT_FAIL_IF(free_memory_result.has_error(), "Unable to free previously allocated memory: %s",
free_memory_result.error().message());
return ErrorMessage(absl::StrFormat(
"AutomaticMemoryInTracee wanted to allocate memory at %#x but got memory at a "
"different address: %#x. The memory has been freed again.",
address, result->GetAddress()));
}
return result;
}
AutomaticMemoryInTracee::~AutomaticMemoryInTracee() {
if (pid_ == -1) return; // Freed manually already.
auto result = Free();
if (result.has_error()) {
ORBIT_ERROR("Unable to free memory in tracee: %s", result.error().message());
}
}
} // namespace orbit_user_space_instrumentation<|endoftext|>
|
<commit_before>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <functional>
#include "common.hh"
#include "token.hh"
namespace tadpole {
enum class Precedence {
NONE,
ASSIGN, // =
TERM, // - +
FACTOR, // / *
CALL, // ()
PRIMARY,
};
template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}
class GlobalParser;
struct ParseRule {
using ParseFn = std::function<GlobalParser&, bool>;
ParseRule prefix;
ParseRule infix;
Precedence precedence;
};
struct LocalVar {
Token name;
int depth{};
bool is_upvalue{};
LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
: name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
}
};
}
<commit_msg>:construction: chore(upvalue): add upvalue declaration for compiler and parser<commit_after>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <functional>
#include "common.hh"
#include "token.hh"
namespace tadpole {
enum class Precedence {
NONE,
ASSIGN, // =
TERM, // - +
FACTOR, // / *
CALL, // ()
PRIMARY,
};
template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}
class GlobalParser;
struct ParseRule {
using ParseFn = std::function<GlobalParser&, bool>;
ParseRule prefix;
ParseRule infix;
Precedence precedence;
};
struct LocalVar {
Token name;
int depth{};
bool is_upvalue{};
LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
: name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
}
};
struct Upvalue {
u8_t index{};
bool is_local{};
Upvalue(u8_t arg_index = 0, bool arg_local = false) noexcept
: index(arg_index), is_local(arg_local) {
}
inline bool operator==(Upvalue r) const noexcept {
return index == r.index && is_local == r.is_local;
}
inline bool operator!=(Upvalue r) const noexcept { return !(*this == r); }
inline bool is_equal(u8_t arg_index, bool arg_local) const noexcept {
return index == arg_index && is_local == arg_local;
}
};
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include "colorful.hh"
#include "lexer.hh"
#include "string_object.hh"
#include "vm.hh"
#include "parser.hh"
namespace tadpole {
GlobalParser::GlobalParser(TadpoleVM& vm, Lexer& lex) noexcept
: vm_(vm), lex_(lex) {
}
void GlobalParser::iter_objects(ObjectVisitor&& visitor) {
for (FnCompiler* c = curr_compiler_; c != nullptr; c = c->enclosing())
visitor(c->fn());
}
FunctionObject* GlobalParser::compile() {
FnCompiler compiler;
init_compiler(&compiler, 0, FnType::TOPLEVEL);
advance();
while (!check(TokenKind::TK_EOF))
declaration();
FunctionObject* fn = finish_compiler();
return had_error_ ? nullptr : fn;
}
const ParseRule& GlobalParser::get_rule(TokenKind kind) const noexcept {
#define _RULE(fn) [](GlobalParser& p, bool b) { p.fn(b); }
static const ParseRule _rules[] = {
{_RULE(grouping), _RULE(call), Precedence::CALL}, // PUNCTUATOR(LPAREN, "(")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(RPAREN, ")")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(LBRACE, "{")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(RBRACE, "}")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(COMMA, ",")
{nullptr, _RULE(binary), Precedence::TERM}, // PUNCTUATOR(MINUS, "-")
{nullptr, _RULE(binary), Precedence::TERM}, // PUNCTUATOR(PLUS, "+")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(SEMI, ";")
{nullptr, _RULE(binary), Precedence::FACTOR}, // PUNCTUATOR(SLASH, "/")
{nullptr, _RULE(binary), Precedence::FACTOR}, // PUNCTUATOR(STAR, "*")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(EQ, "=")
{_RULE(variable), nullptr, Precedence::NONE}, // TOKEN(IDENTIFIER, "Identifier")
{_RULE(numeric), nullptr, Precedence::NONE}, // TOKEN(NUMERIC, "Numeric")
{_RULE(string), nullptr, Precedence::NONE}, // TOKEN(STRING, "String")
{_RULE(literal), nullptr, Precedence::NONE}, // KEYWORD(FALSE, "false")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(FN, "fn")
{_RULE(literal), nullptr, Precedence::NONE}, // KEYWORD(NIL, "nil")
{_RULE(literal), nullptr, Precedence::NONE}, // KEYWORD(TRUE, "true")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(VAR, "var")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(EOF, "Eof")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(ERR, "Error")
};
#undef _RULE
return _rules[as_type<int>(kind)];
}
void GlobalParser::error_at(const Token& tok, const str_t& msg) noexcept {
if (panic_mode_)
return;
panic_mode_ = true;
std::cerr
<< colorful::fg::red
<< "SyntaxError:" << std::endl
<< " [LINE: " << tok.lineno() << "] ERROR ";
if (tok.kind() == TokenKind::TK_EOF)
std::cerr << "at end ";
else if (tok.kind() == TokenKind::TK_ERR)
TADPOLE_UNUSED(0);
else
std::cerr << "at `" << tok.literal() << "` ";
std::cerr << ": " << msg << colorful::reset << std::endl;
}
void GlobalParser::advance() {
prev_ = curr_;
for (;;) {
curr_ = lex_.next_token();
if (!check(TokenKind::TK_ERR))
break;
error_at_current(curr_.as_string());
}
}
void GlobalParser::consume(TokenKind kind, const str_t& msg) {
if (check(kind))
advance();
else
error_at_current(msg);
}
bool GlobalParser::match(TokenKind kind) {
if (check(kind)) {
advance();
return true;
}
return false;
}
void GlobalParser::init_compiler(FnCompiler* compiler, int scope_depth, FnType fn_type) {
StringObject* fn_name{};
if (fn_type == FnType::FUNCTION)
fn_name = StringObject::create(prev_.as_string());
compiler->set_compiler(
curr_compiler_,
FunctionObject::create(fn_name),
fn_type,
scope_depth);
curr_compiler_ = compiler;
curr_compiler_->append_local({Token::make(""), curr_compiler_->scope_depth(), false});
}
FunctionObject* GlobalParser::finish_compiler() {
emit_return();
FunctionObject* fn = curr_compiler_->fn();
#if defined(_TADPOLE_DEBUG_VM)
if (!had_error_)
curr_chunk()->dis(fn->name_asstr());
#endif
curr_compiler_ = curr_compiler_->enclosing();
return fn;
}
void GlobalParser::enter_scope() {
curr_compiler_->enter_scope();
}
void GlobalParser::leave_scope() {
curr_compiler_->leave_scope([this](const LocalVar& var) {
emit_byte(var.is_upvalue ? Code::CLOSE_UPVALUE : Code::POP);
});
}
u8_t GlobalParser::identifier_constant(const Token& name) noexcept {
return curr_chunk()->add_constant(StringObject::create(name.as_string()));
}
u8_t GlobalParser::parse_variable(const str_t& msg) {
consume(TokenKind::TK_IDENTIFIER, msg);
curr_compiler_->declare_localvar(prev_, [this](const str_t& m) { error(m); });
if (curr_compiler_->scope_depth() > 0)
return 0;
return identifier_constant(prev_);
}
void GlobalParser::mark_initialized() {
if (curr_compiler_->scope_depth() == 0)
return;
curr_compiler_->peek_local().depth = curr_compiler_->scope_depth();
}
void GlobalParser::define_global(u8_t global) {
if (curr_compiler_->scope_depth() > 0) {
mark_initialized();
return;
}
emit_bytes(Code::DEF_GLOBAL, global);
}
u8_t GlobalParser::arguments() {
u8_t nargs = 0;
if (!check(TokenKind::TK_RPAREN)) {
do {
expression();
++nargs;
if (nargs > kMaxArgs)
error(from_fmt("cannot have more than `%d` arguments", kMaxArgs));
} while (match(TokenKind::TK_COMMA));
}
consume(TokenKind::TK_RPAREN, "expect `)` after function arguments");
return nargs;
}
void GlobalParser::named_variable(const Token& name, bool can_assign) {
auto errfn = [this](const str_t& msg) { error(msg); };
Code getop, setop;
int arg = curr_compiler_->resolve_local(name, errfn);
if (arg != -1) {
getop = Code::GET_LOCAL;
setop = Code::SET_LOCAL;
}
else if (arg = curr_compiler_->resolve_upvalue(name, errfn); arg != -1) {
getop = Code::GET_UPVALUE;
setop = Code::SET_UPVALUE;
}
else {
arg = identifier_constant(name);
getop = Code::GET_GLOBAL;
setop = Code::SET_GLOBAL;
}
if (can_assign && match(TokenKind::TK_EQ)) {
expression();
emit_bytes(setop, arg);
}
else {
emit_bytes(getop, arg);
}
}
void GlobalParser::parse_precedence(Precedence precedence) {
advance();
auto& prefix_fn = get_rule(prev_.kind()).prefix;
if (!prefix_fn) {
error("expect expression");
return;
}
bool can_assign = precedence <= Precedence::ASSIGN;
prefix_fn(*this, can_assign);
while (precedence <= get_rule(curr_.kind()).precedence) {
advance();
auto& infix_fn = get_rule(prev_.kind()).infix;
if (infix_fn)
infix_fn(*this, can_assign);
}
if (can_assign && match(TokenKind::TK_EQ)) {
error("invalid assignment target");
expression();
}
}
void GlobalParser::binary(bool can_assign) {}
void GlobalParser::call(bool can_assign) {}
void GlobalParser::grouping(bool can_assign) {}
void GlobalParser::literal(bool can_assign) {}
void GlobalParser::variable(bool can_assign) {}
void GlobalParser::numeric(bool can_assign) {}
void GlobalParser::string(bool can_assign) {}
void GlobalParser::block() {}
void GlobalParser::function(FnType fn_type) {}
void GlobalParser::synchronize() {
panic_mode_ = false;
while (!check(TokenKind::TK_EOF)) {
if (prev_.kind() == TokenKind::TK_SEMI)
break;
switch (curr_.kind()) {
case TokenKind::KW_FN:
case TokenKind::KW_VAR:
return;
default: break;
}
advance();
}
}
void GlobalParser::expression() {}
void GlobalParser::declaration() {}
void GlobalParser::statement() {}
void GlobalParser::fn_decl() {}
void GlobalParser::var_decl() {}
void GlobalParser::expr_stmt() {}
}
<commit_msg>:construction: chore(parser): updated the implementation of parsing methods<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include "colorful.hh"
#include "lexer.hh"
#include "string_object.hh"
#include "vm.hh"
#include "parser.hh"
namespace tadpole {
GlobalParser::GlobalParser(TadpoleVM& vm, Lexer& lex) noexcept
: vm_(vm), lex_(lex) {
}
void GlobalParser::iter_objects(ObjectVisitor&& visitor) {
for (FnCompiler* c = curr_compiler_; c != nullptr; c = c->enclosing())
visitor(c->fn());
}
FunctionObject* GlobalParser::compile() {
FnCompiler compiler;
init_compiler(&compiler, 0, FnType::TOPLEVEL);
advance();
while (!check(TokenKind::TK_EOF))
declaration();
FunctionObject* fn = finish_compiler();
return had_error_ ? nullptr : fn;
}
const ParseRule& GlobalParser::get_rule(TokenKind kind) const noexcept {
#define _RULE(fn) [](GlobalParser& p, bool b) { p.fn(b); }
static const ParseRule _rules[] = {
{_RULE(grouping), _RULE(call), Precedence::CALL}, // PUNCTUATOR(LPAREN, "(")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(RPAREN, ")")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(LBRACE, "{")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(RBRACE, "}")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(COMMA, ",")
{nullptr, _RULE(binary), Precedence::TERM}, // PUNCTUATOR(MINUS, "-")
{nullptr, _RULE(binary), Precedence::TERM}, // PUNCTUATOR(PLUS, "+")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(SEMI, ";")
{nullptr, _RULE(binary), Precedence::FACTOR}, // PUNCTUATOR(SLASH, "/")
{nullptr, _RULE(binary), Precedence::FACTOR}, // PUNCTUATOR(STAR, "*")
{nullptr, nullptr, Precedence::NONE}, // PUNCTUATOR(EQ, "=")
{_RULE(variable), nullptr, Precedence::NONE}, // TOKEN(IDENTIFIER, "Identifier")
{_RULE(numeric), nullptr, Precedence::NONE}, // TOKEN(NUMERIC, "Numeric")
{_RULE(string), nullptr, Precedence::NONE}, // TOKEN(STRING, "String")
{_RULE(literal), nullptr, Precedence::NONE}, // KEYWORD(FALSE, "false")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(FN, "fn")
{_RULE(literal), nullptr, Precedence::NONE}, // KEYWORD(NIL, "nil")
{_RULE(literal), nullptr, Precedence::NONE}, // KEYWORD(TRUE, "true")
{nullptr, nullptr, Precedence::NONE}, // KEYWORD(VAR, "var")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(EOF, "Eof")
{nullptr, nullptr, Precedence::NONE}, // TOKEN(ERR, "Error")
};
#undef _RULE
return _rules[as_type<int>(kind)];
}
void GlobalParser::error_at(const Token& tok, const str_t& msg) noexcept {
if (panic_mode_)
return;
panic_mode_ = true;
std::cerr
<< colorful::fg::red
<< "SyntaxError:" << std::endl
<< " [LINE: " << tok.lineno() << "] ERROR ";
if (tok.kind() == TokenKind::TK_EOF)
std::cerr << "at end ";
else if (tok.kind() == TokenKind::TK_ERR)
TADPOLE_UNUSED(0);
else
std::cerr << "at `" << tok.literal() << "` ";
std::cerr << ": " << msg << colorful::reset << std::endl;
}
void GlobalParser::advance() {
prev_ = curr_;
for (;;) {
curr_ = lex_.next_token();
if (!check(TokenKind::TK_ERR))
break;
error_at_current(curr_.as_string());
}
}
void GlobalParser::consume(TokenKind kind, const str_t& msg) {
if (check(kind))
advance();
else
error_at_current(msg);
}
bool GlobalParser::match(TokenKind kind) {
if (check(kind)) {
advance();
return true;
}
return false;
}
void GlobalParser::init_compiler(FnCompiler* compiler, int scope_depth, FnType fn_type) {
StringObject* fn_name{};
if (fn_type == FnType::FUNCTION)
fn_name = StringObject::create(prev_.as_string());
compiler->set_compiler(
curr_compiler_,
FunctionObject::create(fn_name),
fn_type,
scope_depth);
curr_compiler_ = compiler;
curr_compiler_->append_local({Token::make(""), curr_compiler_->scope_depth(), false});
}
FunctionObject* GlobalParser::finish_compiler() {
emit_return();
FunctionObject* fn = curr_compiler_->fn();
#if defined(_TADPOLE_DEBUG_VM)
if (!had_error_)
curr_chunk()->dis(fn->name_asstr());
#endif
curr_compiler_ = curr_compiler_->enclosing();
return fn;
}
void GlobalParser::enter_scope() {
curr_compiler_->enter_scope();
}
void GlobalParser::leave_scope() {
curr_compiler_->leave_scope([this](const LocalVar& var) {
emit_byte(var.is_upvalue ? Code::CLOSE_UPVALUE : Code::POP);
});
}
u8_t GlobalParser::identifier_constant(const Token& name) noexcept {
return curr_chunk()->add_constant(StringObject::create(name.as_string()));
}
u8_t GlobalParser::parse_variable(const str_t& msg) {
consume(TokenKind::TK_IDENTIFIER, msg);
curr_compiler_->declare_localvar(prev_, [this](const str_t& m) { error(m); });
if (curr_compiler_->scope_depth() > 0)
return 0;
return identifier_constant(prev_);
}
void GlobalParser::mark_initialized() {
if (curr_compiler_->scope_depth() == 0)
return;
curr_compiler_->peek_local().depth = curr_compiler_->scope_depth();
}
void GlobalParser::define_global(u8_t global) {
if (curr_compiler_->scope_depth() > 0) {
mark_initialized();
return;
}
emit_bytes(Code::DEF_GLOBAL, global);
}
u8_t GlobalParser::arguments() {
u8_t nargs = 0;
if (!check(TokenKind::TK_RPAREN)) {
do {
expression();
++nargs;
if (nargs > kMaxArgs)
error(from_fmt("cannot have more than `%d` arguments", kMaxArgs));
} while (match(TokenKind::TK_COMMA));
}
consume(TokenKind::TK_RPAREN, "expect `)` after function arguments");
return nargs;
}
void GlobalParser::named_variable(const Token& name, bool can_assign) {
auto errfn = [this](const str_t& msg) { error(msg); };
Code getop, setop;
int arg = curr_compiler_->resolve_local(name, errfn);
if (arg != -1) {
getop = Code::GET_LOCAL;
setop = Code::SET_LOCAL;
}
else if (arg = curr_compiler_->resolve_upvalue(name, errfn); arg != -1) {
getop = Code::GET_UPVALUE;
setop = Code::SET_UPVALUE;
}
else {
arg = identifier_constant(name);
getop = Code::GET_GLOBAL;
setop = Code::SET_GLOBAL;
}
if (can_assign && match(TokenKind::TK_EQ)) {
expression();
emit_bytes(setop, arg);
}
else {
emit_bytes(getop, arg);
}
}
void GlobalParser::parse_precedence(Precedence precedence) {
advance();
auto& prefix_fn = get_rule(prev_.kind()).prefix;
if (!prefix_fn) {
error("expect expression");
return;
}
bool can_assign = precedence <= Precedence::ASSIGN;
prefix_fn(*this, can_assign);
while (precedence <= get_rule(curr_.kind()).precedence) {
advance();
auto& infix_fn = get_rule(prev_.kind()).infix;
if (infix_fn)
infix_fn(*this, can_assign);
}
if (can_assign && match(TokenKind::TK_EQ)) {
error("invalid assignment target");
expression();
}
}
void GlobalParser::binary(bool can_assign) {
TokenKind op = prev_.kind();
parse_precedence(get_rule(op).precedence + 1);
switch (op) {
case TokenKind::TK_PLUS: emit_byte(Code::ADD); break;
case TokenKind::TK_MINUS: emit_byte(Code::SUB); break;
case TokenKind::TK_STAR: emit_byte(Code::MUL); break;
case TokenKind::TK_SLASH: emit_byte(Code::DIV); break;
default: break;
}
}
void GlobalParser::call(bool can_assign) {
emit_byte(Code::CALL_0 + arguments());
}
void GlobalParser::grouping(bool can_assign) {
expression();
consume( TokenKind::TK_RPAREN, "expect `)` after grouping expression");
}
void GlobalParser::literal(bool can_assign) {
switch (prev_.kind()) {
case TokenKind::KW_NIL: emit_byte(Code::NIL); break;
case TokenKind::KW_FALSE: emit_byte(Code::FALSE); break;
case TokenKind::KW_TRUE: emit_byte(Code::TRUE); break;
default: break;
}
}
void GlobalParser::variable(bool can_assign) {
named_variable(prev_, can_assign);
}
void GlobalParser::numeric(bool can_assign) {
emit_constant(prev_.as_numeric());
}
void GlobalParser::string(bool can_assign) {
emit_constant(StringObject::create(prev_.as_string()));
}
void GlobalParser::block() {
while (!check(TokenKind::TK_EOF) && !check(TokenKind::TK_RBRACE))
declaration();
consume(TokenKind::TK_RBRACE, "expect `}` after block body");
}
void GlobalParser::function(FnType fn_type) {
FnCompiler fn_compiler;
init_compiler(&fn_compiler, 1, fn_type);
consume(TokenKind::TK_LPAREN, "expect `(` after function name");
if (!check(TokenKind::TK_RPAREN)) {
do {
u8_t param_constant = parse_variable("expect function parameters' name");
define_global(param_constant);
curr_compiler_->fn()->inc_arity();
if (curr_compiler_->fn()->arity() > kMaxArgs)
error(from_fmt("cannot have more than `%d` parameters", kMaxArgs));
} while (match(TokenKind::TK_COMMA));
}
consume(TokenKind::TK_RPAREN, "expect `)` after function parameters");
consume(TokenKind::TK_LBRACE, "expect `{` before function body");
block();
leave_scope();
FunctionObject* fn = finish_compiler();
emit_bytes(Code::CLOSURE, curr_chunk()->add_constant(fn));
for (sz_t i = 0; i < fn->upvalues_count(); ++i) {
auto& upvalue = fn_compiler.get_upvalue(i);
emit_bytes(upvalue.is_local ? 1 : 0, upvalue.index);
}
}
void GlobalParser::synchronize() {
panic_mode_ = false;
while (!check(TokenKind::TK_EOF)) {
if (prev_.kind() == TokenKind::TK_SEMI)
break;
switch (curr_.kind()) {
case TokenKind::KW_FN:
case TokenKind::KW_VAR:
return;
default: break;
}
advance();
}
}
void GlobalParser::expression() {}
void GlobalParser::declaration() {}
void GlobalParser::statement() {}
void GlobalParser::fn_decl() {}
void GlobalParser::var_decl() {}
void GlobalParser::expr_stmt() {}
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "StylesheetConstructionContextDefault.hpp"
#include <algorithm>
#include <PlatformSupport/STLHelper.hpp>
#include <PlatformSupport/URISupport.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathEnvSupport.hpp>
#include <XPath/XPathFactory.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include "StylesheetRoot.hpp"
#include "XSLTEngineImpl.hpp"
#include "XSLTInputSource.hpp"
StylesheetConstructionContextDefault::StylesheetConstructionContextDefault(
XSLTEngineImpl& processor,
XPathEnvSupport& xpathEnvSupport,
XPathFactory& xpathFactory) :
StylesheetConstructionContext(),
m_processor(processor),
m_xpathEnvSupport(xpathEnvSupport),
m_xpathFactory(xpathFactory),
m_xpathProcessor(new XPathProcessorImpl),
m_stylesheets()
{
}
StylesheetConstructionContextDefault::~StylesheetConstructionContextDefault()
{
reset();
}
void
StylesheetConstructionContextDefault::error(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
m_processor.error(msg, styleNode, sourceNode);
}
void
StylesheetConstructionContextDefault::error(
const char* msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
error(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::warn(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
m_processor.warn(msg, styleNode, sourceNode);
}
void
StylesheetConstructionContextDefault::warn(
const char* msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
warn(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::message(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
m_processor.message(msg, styleNode, sourceNode);
}
void
StylesheetConstructionContextDefault::message(
const char* msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
message(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
for_each(m_stylesheets.begin(),
m_stylesheets.end(),
DeleteFunctor<StylesheetRoot>());
m_stylesheets.clear();
m_xpathFactory.reset();
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XalanDOMString& theBaseIdentifier)
{
StylesheetRoot* const theStylesheetRoot =
new StylesheetRoot(theBaseIdentifier, *this);
m_stylesheets.insert(theStylesheetRoot);
return theStylesheetRoot;
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XSLTInputSource& theInputSource)
{
const XMLCh* const theSystemID =
theInputSource.getSystemId();
const XalanDOMString theBaseIdentifier =
theSystemID == 0 ? XalanDOMString() :
XalanDOMString(theSystemID);
return create(theBaseIdentifier);
}
Stylesheet*
StylesheetConstructionContextDefault::create(
StylesheetRoot& theStylesheetRoot,
const XalanDOMString& theBaseIdentifier)
{
Stylesheet* const theStylesheet =
new Stylesheet(
theStylesheetRoot,
theBaseIdentifier,
*this);
return theStylesheet;
}
void
StylesheetConstructionContextDefault::destroy(StylesheetRoot* theStylesheetRoot)
{
const StylesheetSetType::iterator i =
m_stylesheets.find(theStylesheetRoot);
if (i != m_stylesheets.end())
{
m_stylesheets.erase(i);
delete theStylesheetRoot;
}
}
int
StylesheetConstructionContextDefault::getAttrTok(const XalanDOMString& name) const
{
return m_processor.getAttrTok(XalanDOMString(name));
}
int
StylesheetConstructionContextDefault::getAttrTok(const XalanDOMChar* name) const
{
assert(name != 0);
// $$$ ToDo: Explicit XalanDOMString constructor
return m_processor.getAttrTok(XalanDOMString(name));
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(const XalanDOMString& urlString)
{
return URISupport::getURLFromString(urlString);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(const XalanDOMString& urlString)
{
return URISupport::getURLStringFromString(urlString);
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLFromString(urlString, base);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLStringFromString(urlString, base);
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXSLTNamespaceURI() const
{
return XSLTEngineImpl::getXSLNameSpaceURL();
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
m_xpathProcessor->initMatchPattern(*xpath,
str,
resolver,
m_xpathEnvSupport);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
// $$$ ToDo: Explicit XalanDOMString constructor
return createMatchPattern(XalanDOMString(str), resolver);
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
// $$$ ToDo: Explicit XalanDOMString constructor
m_xpathProcessor->initXPath(*xpath,
str,
resolver,
m_xpathEnvSupport);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
// $$$ ToDo: Explicit XalanDOMString constructor
return createXPath(XalanDOMString(str), resolver);
}
const Locator*
StylesheetConstructionContextDefault::getLocatorFromStack() const
{
return m_processor.getLocatorFromStack();
}
void
StylesheetConstructionContextDefault::pushLocatorOnStack(const Locator* locator)
{
m_processor.pushLocatorOnStack(locator);
}
void
StylesheetConstructionContextDefault::popLocatorStack()
{
m_processor.popLocatorStack();
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXalanXSLNameSpaceURL() const
{
return XSLTEngineImpl::getXalanXSLNameSpaceURL();
}
XalanDocument*
StylesheetConstructionContextDefault::parseXML(
const XalanDOMString& urlString,
DocumentHandler* docHandler,
XalanDocument* docToRegister)
{
return m_processor.parseXML(urlString, docHandler, docToRegister);
}
int
StylesheetConstructionContextDefault::getElementToken(const XalanDOMString& name) const
{
return m_processor.getElementToken(name);
}
double
StylesheetConstructionContextDefault::getXSLTVersionSupported() const
{
return XSLTEngineImpl::getXSLTVerSupported();
}
<commit_msg>Set new XPath flag to indicate that they are embedded in a compiled stylesheet.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "StylesheetConstructionContextDefault.hpp"
#include <algorithm>
#include <PlatformSupport/STLHelper.hpp>
#include <PlatformSupport/URISupport.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathEnvSupport.hpp>
#include <XPath/XPathFactory.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include "StylesheetRoot.hpp"
#include "XSLTEngineImpl.hpp"
#include "XSLTInputSource.hpp"
StylesheetConstructionContextDefault::StylesheetConstructionContextDefault(
XSLTEngineImpl& processor,
XPathEnvSupport& xpathEnvSupport,
XPathFactory& xpathFactory) :
StylesheetConstructionContext(),
m_processor(processor),
m_xpathEnvSupport(xpathEnvSupport),
m_xpathFactory(xpathFactory),
m_xpathProcessor(new XPathProcessorImpl),
m_stylesheets()
{
}
StylesheetConstructionContextDefault::~StylesheetConstructionContextDefault()
{
reset();
}
void
StylesheetConstructionContextDefault::error(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
m_processor.error(msg, styleNode, sourceNode);
}
void
StylesheetConstructionContextDefault::error(
const char* msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
error(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::warn(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
m_processor.warn(msg, styleNode, sourceNode);
}
void
StylesheetConstructionContextDefault::warn(
const char* msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
warn(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::message(
const XalanDOMString& msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
m_processor.message(msg, styleNode, sourceNode);
}
void
StylesheetConstructionContextDefault::message(
const char* msg,
const XalanNode* sourceNode,
const XalanNode* styleNode) const
{
message(TranscodeFromLocalCodePage(msg), sourceNode, styleNode);
}
void
StylesheetConstructionContextDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
for_each(m_stylesheets.begin(),
m_stylesheets.end(),
DeleteFunctor<StylesheetRoot>());
m_stylesheets.clear();
m_xpathFactory.reset();
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XalanDOMString& theBaseIdentifier)
{
StylesheetRoot* const theStylesheetRoot =
new StylesheetRoot(theBaseIdentifier, *this);
m_stylesheets.insert(theStylesheetRoot);
return theStylesheetRoot;
}
StylesheetRoot*
StylesheetConstructionContextDefault::create(const XSLTInputSource& theInputSource)
{
const XMLCh* const theSystemID =
theInputSource.getSystemId();
const XalanDOMString theBaseIdentifier =
theSystemID == 0 ? XalanDOMString() :
XalanDOMString(theSystemID);
return create(theBaseIdentifier);
}
Stylesheet*
StylesheetConstructionContextDefault::create(
StylesheetRoot& theStylesheetRoot,
const XalanDOMString& theBaseIdentifier)
{
Stylesheet* const theStylesheet =
new Stylesheet(
theStylesheetRoot,
theBaseIdentifier,
*this);
return theStylesheet;
}
void
StylesheetConstructionContextDefault::destroy(StylesheetRoot* theStylesheetRoot)
{
const StylesheetSetType::iterator i =
m_stylesheets.find(theStylesheetRoot);
if (i != m_stylesheets.end())
{
m_stylesheets.erase(i);
delete theStylesheetRoot;
}
}
int
StylesheetConstructionContextDefault::getAttrTok(const XalanDOMString& name) const
{
return m_processor.getAttrTok(XalanDOMString(name));
}
int
StylesheetConstructionContextDefault::getAttrTok(const XalanDOMChar* name) const
{
assert(name != 0);
// $$$ ToDo: Explicit XalanDOMString constructor
return m_processor.getAttrTok(XalanDOMString(name));
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(const XalanDOMString& urlString)
{
return URISupport::getURLFromString(urlString);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(const XalanDOMString& urlString)
{
return URISupport::getURLStringFromString(urlString);
}
StylesheetConstructionContextDefault::URLAutoPtrType
StylesheetConstructionContextDefault::getURLFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLFromString(urlString, base);
}
XalanDOMString
StylesheetConstructionContextDefault::getURLStringFromString(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
return URISupport::getURLStringFromString(urlString, base);
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXSLTNamespaceURI() const
{
return XSLTEngineImpl::getXSLNameSpaceURL();
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
m_xpathProcessor->initMatchPattern(*xpath,
str,
resolver,
m_xpathEnvSupport);
xpath->setInStylesheet(true);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createMatchPattern(
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
// $$$ ToDo: Explicit XalanDOMString constructor
return createMatchPattern(XalanDOMString(str), resolver);
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const XalanDOMString& str,
const PrefixResolver& resolver)
{
XPath* const xpath = m_xpathFactory.create();
// $$$ ToDo: Explicit XalanDOMString constructor
m_xpathProcessor->initXPath(*xpath,
str,
resolver,
m_xpathEnvSupport);
xpath->setInStylesheet(true);
return xpath;
}
XPath*
StylesheetConstructionContextDefault::createXPath(
const XalanDOMChar* str,
const PrefixResolver& resolver)
{
assert(str != 0);
// $$$ ToDo: Explicit XalanDOMString constructor
return createXPath(XalanDOMString(str), resolver);
}
const Locator*
StylesheetConstructionContextDefault::getLocatorFromStack() const
{
return m_processor.getLocatorFromStack();
}
void
StylesheetConstructionContextDefault::pushLocatorOnStack(const Locator* locator)
{
m_processor.pushLocatorOnStack(locator);
}
void
StylesheetConstructionContextDefault::popLocatorStack()
{
m_processor.popLocatorStack();
}
const XalanDOMString&
StylesheetConstructionContextDefault::getXalanXSLNameSpaceURL() const
{
return XSLTEngineImpl::getXalanXSLNameSpaceURL();
}
XalanDocument*
StylesheetConstructionContextDefault::parseXML(
const XalanDOMString& urlString,
DocumentHandler* docHandler,
XalanDocument* docToRegister)
{
return m_processor.parseXML(urlString, docHandler, docToRegister);
}
int
StylesheetConstructionContextDefault::getElementToken(const XalanDOMString& name) const
{
return m_processor.getElementToken(name);
}
double
StylesheetConstructionContextDefault::getXSLTVersionSupported() const
{
return XSLTEngineImpl::getXSLTVerSupported();
}
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "bssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/project/project.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
using namespace foundation;
/*
Quick ref:
----------
sigma_a absorption coeff.
sigma_s scattering coeff.
g anisotropy
sigma_t extinction coeff. -> sigma_a + sigma_s
sigma_s_prime reduced scattering coeff. -> sigma_s * (1 - g)
sigma_t_prime reduced extinction coeff. -> sigma_a + sigma_s_prime
sigma_tr effective extinction coeff. -> sqrt( 3 * sigma_a * sigma_t_prime)
Texture mapping:
----------------
alpha_prime -> sigma_s_prime / sigma_t_prime
ld mean free path -> 1 / sigma_tr
sigma_t_prime = sigma_tr / sqrt( 3 * (1 - alpha_prime))
sigma_s_prime = alpha_prime * sigma_t_prime
sigma_a = sigma_t_prime - sigma_s_prime
*/
namespace renderer
{
//
// BSSRDF class implementation.
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID BSSRDF::get_class_uid()
{
return g_class_uid;
}
BSSRDF::BSSRDF(
const char* name,
const ParamArray& params)
: ConnectableEntity(g_class_uid, params)
, m_lighting_conditions(0)
{
set_name(name);
}
bool BSSRDF::on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch)
{
m_lighting_conditions = &project.get_frame()->get_lighting_conditions();
return true;
}
void BSSRDF::on_frame_end(
const Project& project,
const Assembly& assembly)
{
m_lighting_conditions = 0;
}
size_t BSSRDF::compute_input_data_size(
const Assembly& assembly) const
{
return get_inputs().compute_data_size();
}
void BSSRDF::evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset) const
{
input_evaluator.evaluate(get_inputs(), shading_point.get_uv(0), offset);
}
bool BSSRDF::sample(
const void* data,
BSSRDFSample& sample) const
{
sample.get_sampling_context().split_in_place(1, 1);
const double r = sample.get_sampling_context().next_double2();
const Basis3d& shading_basis = sample.get_shading_point().get_shading_basis();
if (r <= 0.5)
{
sample.set_sample_basis(shading_basis);
sample.set_use_offset_origin(true);
}
else if (r <= 0.75)
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_u(),
shading_basis.get_tangent_v(),
shading_basis.get_normal()));
}
else
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_v(),
shading_basis.get_normal(),
shading_basis.get_tangent_u()));
}
Vector2d d;
if (do_sample(data, sample, d))
{
sample.set_origin(
sample.get_shading_point().get_point() +
sample.get_sample_basis().get_tangent_u() * d.x +
sample.get_sample_basis().get_tangent_v() * d.y);
return true;
}
return false;
}
double BSSRDF::pdf(
const void* data,
const ShadingPoint& outgoing_point,
const ShadingPoint& incoming_point,
const Basis3d& basis,
const size_t channel) const
{
// From PBRT 3.
const Vector3d d = outgoing_point.get_point() - incoming_point.get_point();
const Vector3d dlocal(
dot(basis.get_tangent_u(), d),
dot(basis.get_tangent_v(), d),
dot(basis.get_normal() , d));
const Vector3d& n = incoming_point.get_shading_normal();
const Vector3d nlocal(
dot(basis.get_tangent_u(), n),
dot(basis.get_tangent_v(), n),
dot(basis.get_normal() , n));
return
pdf(data, channel, std::sqrt(square(dlocal.y) + square(dlocal.z))) * 0.125 * std::abs(nlocal[0]) +
pdf(data, channel, std::sqrt(square(dlocal.z) + square(dlocal.x))) * 0.125 * std::abs(nlocal[1]) +
pdf(data, channel, std::sqrt(square(dlocal.x) + square(dlocal.y))) * 0.250 * std::abs(nlocal[2]);
}
//
// Reference:
//
// A better dipole, Eugene d’Eon
// http://www.eugenedeon.com/papers/betterdipole.pdf
//
double BSSRDF::fresnel_moment_1(const double eta)
{
return
eta >= 1.0
? (-9.23372 + eta * (22.2272 + eta * (-20.9292 + eta * (10.2291 + eta * (-2.54396 + 0.254913 * eta))))) * 0.5
: (0.919317 + eta * (-3.4793 + eta * (6.75335 + eta * (-7.80989 + eta *(4.98554 - 1.36881 * eta))))) * 0.5;
}
double BSSRDF::fresnel_moment_2(const double eta)
{
double r = -1641.1 + eta * (1213.67 + eta * (-568.556 + eta * (164.798 + eta * (-27.0181 + 1.91826 * eta))));
r += (((135.926 / eta) - 656.175) / eta + 1376.53) / eta;
return r * 0.33333333;
}
} // namespace renderer
<commit_msg>minor code tweaks/cleanups.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "bssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/project/project.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
using namespace foundation;
namespace renderer
{
//
// BSSRDF class implementation.
//
// Quick reference
// ---------------
//
// sigma_a absorption coeff.
// sigma_s scattering coeff.
// g anisotropy
//
// sigma_t extinction coeff. -> sigma_a + sigma_s
// sigma_s_prime reduced scattering coeff. -> sigma_s * (1 - g)
// sigma_t_prime reduced extinction coeff. -> sigma_a + sigma_s_prime
// sigma_tr effective extinction coeff. -> sqrt(3 * sigma_a * sigma_t_prime)
//
// Texture mapping
// ---------------
//
// alpha_prime -> sigma_s_prime / sigma_t_prime
// ld mean free path -> 1 / sigma_tr
//
// sigma_t_prime = sigma_tr / sqrt(3 * (1 - alpha_prime))
// sigma_s_prime = alpha_prime * sigma_t_prime
// sigma_a = sigma_t_prime - sigma_s_prime
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID BSSRDF::get_class_uid()
{
return g_class_uid;
}
BSSRDF::BSSRDF(
const char* name,
const ParamArray& params)
: ConnectableEntity(g_class_uid, params)
, m_lighting_conditions(0)
{
set_name(name);
}
bool BSSRDF::on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch)
{
m_lighting_conditions = &project.get_frame()->get_lighting_conditions();
return true;
}
void BSSRDF::on_frame_end(
const Project& project,
const Assembly& assembly)
{
m_lighting_conditions = 0;
}
size_t BSSRDF::compute_input_data_size(
const Assembly& assembly) const
{
return get_inputs().compute_data_size();
}
void BSSRDF::evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset) const
{
input_evaluator.evaluate(get_inputs(), shading_point.get_uv(0), offset);
}
bool BSSRDF::sample(
const void* data,
BSSRDFSample& sample) const
{
sample.get_sampling_context().split_in_place(1, 1);
const double r = sample.get_sampling_context().next_double2();
const Basis3d& shading_basis = sample.get_shading_point().get_shading_basis();
if (r <= 0.5)
{
sample.set_sample_basis(shading_basis);
sample.set_use_offset_origin(true);
}
else if (r <= 0.75)
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_u(),
shading_basis.get_tangent_v(),
shading_basis.get_normal()));
}
else
{
sample.set_sample_basis(
Basis3d(
shading_basis.get_tangent_v(),
shading_basis.get_normal(),
shading_basis.get_tangent_u()));
}
Vector2d d;
if (do_sample(data, sample, d))
{
sample.set_origin(
sample.get_shading_point().get_point() +
sample.get_sample_basis().get_tangent_u() * d.x +
sample.get_sample_basis().get_tangent_v() * d.y);
return true;
}
return false;
}
double BSSRDF::pdf(
const void* data,
const ShadingPoint& outgoing_point,
const ShadingPoint& incoming_point,
const Basis3d& basis,
const size_t channel) const
{
// From PBRT 3.
const Vector3d d = outgoing_point.get_point() - incoming_point.get_point();
const Vector3d dlocal(
dot(basis.get_tangent_u(), d),
dot(basis.get_tangent_v(), d),
dot(basis.get_normal() , d));
const Vector3d& n = incoming_point.get_shading_normal();
const Vector3d nlocal(
dot(basis.get_tangent_u(), n),
dot(basis.get_tangent_v(), n),
dot(basis.get_normal() , n));
return
pdf(data, channel, std::sqrt(square(dlocal.y) + square(dlocal.z))) * 0.125 * std::abs(nlocal[0]) +
pdf(data, channel, std::sqrt(square(dlocal.z) + square(dlocal.x))) * 0.125 * std::abs(nlocal[1]) +
pdf(data, channel, std::sqrt(square(dlocal.x) + square(dlocal.y))) * 0.250 * std::abs(nlocal[2]);
}
//
// Reference:
//
// A better dipole, Eugene d’Eon
// http://www.eugenedeon.com/papers/betterdipole.pdf
//
double BSSRDF::fresnel_moment_1(const double eta)
{
return
eta >= 1.0
? (-9.23372 + eta * (22.2272 + eta * (-20.9292 + eta * (10.2291 + eta * (-2.54396 + 0.254913 * eta))))) * 0.5
: (0.919317 + eta * (-3.4793 + eta * (6.75335 + eta * (-7.80989 + eta *(4.98554 - 1.36881 * eta))))) * 0.5;
}
double BSSRDF::fresnel_moment_2(const double eta)
{
// todo: precompute 1/eta?
double r = -1641.1 + eta * (1213.67 + eta * (-568.556 + eta * (164.798 + eta * (-27.0181 + 1.91826 * eta))));
r += (((135.926 / eta) - 656.175) / eta + 1376.53) / eta;
return r * 0.33333333;
}
} // namespace renderer
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/public-api/object/weak-handle.h>
// INTERNAL INCLUDES
#include <dali/internal/event/common/base-object-impl.h>
namespace Dali
{
struct WeakHandleBase::Impl : public BaseObject::Impl::Observer
{
// Construction
Impl()
: mObject( nullptr )
{
}
// Construction
Impl( BaseHandle& handle )
: mObject( nullptr )
{
if( handle )
{
mObject = static_cast<Dali::BaseObject*>( handle.GetObjectPtr() );
if( mObject )
{
BaseObject::Impl::Get( *mObject ).AddObserver( *this );
}
}
}
// Destruction
~Impl()
{
Reset();
}
void Reset()
{
if( mObject )
{
BaseObject::Impl::Get( *mObject ).RemoveObserver( *this );
mObject = nullptr;
}
}
/**
* From BaseObject::Impl::Observer
*/
virtual void ObjectDestroyed( BaseObject& object )
{
mObject = nullptr;
}
// Data
Dali::BaseObject* mObject;
};
WeakHandleBase::WeakHandleBase()
: mImpl( new Impl() )
{
}
WeakHandleBase::WeakHandleBase( BaseHandle& handle )
: mImpl( new Impl( handle ) )
{
}
WeakHandleBase::~WeakHandleBase()
{
delete mImpl;
mImpl = nullptr;
}
WeakHandleBase::WeakHandleBase(const WeakHandleBase& handle)
: mImpl( nullptr )
{
BaseHandle object = handle.GetBaseHandle();
mImpl = new Impl(object);
}
WeakHandleBase& WeakHandleBase::operator=( const WeakHandleBase& rhs )
{
if( this != &rhs )
{
delete mImpl;
BaseHandle handle = rhs.GetBaseHandle();
mImpl = new Impl(handle);
}
return *this;
}
WeakHandleBase::WeakHandleBase( WeakHandleBase&& rhs )
: mImpl( rhs.mImpl )
{
rhs.mImpl = nullptr;
}
WeakHandleBase& WeakHandleBase::operator=( WeakHandleBase&& rhs )
{
if (this != &rhs)
{
mImpl = rhs.mImpl;
rhs.mImpl = nullptr;
}
return *this;
}
bool WeakHandleBase::operator==( const WeakHandleBase& rhs ) const
{
return this->mImpl->mObject == rhs.mImpl->mObject;
}
bool WeakHandleBase::operator!=( const WeakHandleBase& rhs ) const
{
return !( *this == rhs );
}
BaseHandle WeakHandleBase::GetBaseHandle() const
{
return mImpl ? BaseHandle( mImpl->mObject ) : BaseHandle();
}
void WeakHandleBase::Reset()
{
mImpl->Reset();
}
} // Dali
<commit_msg>Fix memory leak of WeakHandle<commit_after>/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/public-api/object/weak-handle.h>
// INTERNAL INCLUDES
#include <dali/internal/event/common/base-object-impl.h>
namespace Dali
{
struct WeakHandleBase::Impl : public BaseObject::Impl::Observer
{
// Construction
Impl()
: mObject( nullptr )
{
}
// Construction
Impl( BaseHandle& handle )
: mObject( nullptr )
{
if( handle )
{
mObject = static_cast<Dali::BaseObject*>( handle.GetObjectPtr() );
if( mObject )
{
BaseObject::Impl::Get( *mObject ).AddObserver( *this );
}
}
}
// Destruction
~Impl()
{
Reset();
}
void Reset()
{
if( mObject )
{
BaseObject::Impl::Get( *mObject ).RemoveObserver( *this );
mObject = nullptr;
}
}
/**
* From BaseObject::Impl::Observer
*/
virtual void ObjectDestroyed( BaseObject& object )
{
mObject = nullptr;
}
// Data
Dali::BaseObject* mObject;
};
WeakHandleBase::WeakHandleBase()
: mImpl( new Impl() )
{
}
WeakHandleBase::WeakHandleBase( BaseHandle& handle )
: mImpl( new Impl( handle ) )
{
}
WeakHandleBase::~WeakHandleBase()
{
delete mImpl;
mImpl = nullptr;
}
WeakHandleBase::WeakHandleBase(const WeakHandleBase& handle)
: mImpl( nullptr )
{
BaseHandle object = handle.GetBaseHandle();
mImpl = new Impl(object);
}
WeakHandleBase& WeakHandleBase::operator=( const WeakHandleBase& rhs )
{
if( this != &rhs )
{
delete mImpl;
BaseHandle handle = rhs.GetBaseHandle();
mImpl = new Impl(handle);
}
return *this;
}
WeakHandleBase::WeakHandleBase( WeakHandleBase&& rhs )
: mImpl( rhs.mImpl )
{
rhs.mImpl = nullptr;
}
WeakHandleBase& WeakHandleBase::operator=( WeakHandleBase&& rhs )
{
if (this != &rhs)
{
delete mImpl;
mImpl = rhs.mImpl;
rhs.mImpl = nullptr;
}
return *this;
}
bool WeakHandleBase::operator==( const WeakHandleBase& rhs ) const
{
return this->mImpl->mObject == rhs.mImpl->mObject;
}
bool WeakHandleBase::operator!=( const WeakHandleBase& rhs ) const
{
return !( *this == rhs );
}
BaseHandle WeakHandleBase::GetBaseHandle() const
{
return mImpl ? BaseHandle( mImpl->mObject ) : BaseHandle();
}
void WeakHandleBase::Reset()
{
mImpl->Reset();
}
} // Dali
<|endoftext|>
|
<commit_before>/** \file rss_subset_aggregator.cc
* \brief Aggregates RSS feeds.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cinttypes>
#include <cstring>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "EmailSender.h"
#include "FileUtil.h"
#include "HtmlUtil.h"
#include "MiscUtil.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "SyndicationFormat.h"
#include "Template.h"
#include "UBTools.h"
#include "XmlWriter.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage(
"--mode=(email|rss_xml) (user_id|error_email_address) subsystem_type]\n"
"If the mode is \"rss_xml\" a VuFind user_id needs to be specified, o/w an error email address should be provided.");
}
struct HarvestedRSSItem {
SyndicationFormat::Item item_;
std::string feed_title_;
std::string website_url_;
HarvestedRSSItem(const SyndicationFormat::Item item, const std::string &feed_title, const std::string &website_url)
: item_(item), feed_title_(feed_title), website_url_(website_url) { }
};
struct ChannelDesc {
std::string title_;
std::string link_;
public:
ChannelDesc(const std::string &title, const std::string &link): title_(title), link_(link) { }
};
const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = {
{ "relbib", ChannelDesc("RelBib RSS Aggregator", "https://relbib.de/") },
{ "ixtheo", ChannelDesc("IxTheo RSS Aggregator", "https://ixtheo.de/") },
{ "krimdok", ChannelDesc("KrimDok RSS Aggregator", "https://krimdok.uni-tuebingen.de/") },
};
std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) {
const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type));
if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend())
LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!");
if (entry == "title")
return subsystem_type_and_channel_desc->second.title_;
if (entry == "link")
return subsystem_type_and_channel_desc->second.link_;
LOG_ERROR("unknown entry name \"" + entry + "\"!");
}
void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items,
XmlWriter * const xml_writer) {
xml_writer->openTag("rss", { { "version", "2.0" } });
xml_writer->openTag("channel");
xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title"));
xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link"));
xml_writer->writeTagsWithData("description", "RSS Aggregator");
for (const auto &harvested_item : harvested_items) {
xml_writer->openTag("item");
const auto title(harvested_item.item_.getTitle());
if (not title.empty())
xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle());
xml_writer->writeTagsWithData("link", harvested_item.item_.getLink());
const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */ 500));
if (not description.empty())
xml_writer->writeTagsWithData("description", description);
xml_writer->writeTagsWithData("pubDate",
TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC));
xml_writer->writeTagsWithData("guid", harvested_item.item_.getId());
xml_writer->closeTag("item", /* suppress_indent */ false);
}
xml_writer->closeTag("channel");
xml_writer->closeTag("rss");
}
struct FeedNameAndURL {
std::string name_;
std::string url_;
public:
FeedNameAndURL() = default;
FeedNameAndURL(const FeedNameAndURL &other) = default;
FeedNameAndURL(const std::string &name, const std::string &url): name_(name), url_(url) { }
};
// \return True if a notification email was sent successfully, o/w false.
bool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email,
const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) {
const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template");
std::string template_filename(template_filename_prefix + "." + language);
if (not FileUtil::Exists(template_filename))
template_filename = template_filename_prefix + ".en";
static const std::string email_template(FileUtil::ReadStringOrDie(template_filename));
Template::Map names_to_values_map;
names_to_values_map.insertScalar("user_name", user_address);
std::vector<std::string> item_titles, item_urls, website_urls, feed_names;
for (const auto &harvested_item : harvested_items) {
item_titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle()));
item_urls.emplace_back(harvested_item.item_.getLink());
website_urls.emplace_back(harvested_item.website_url_);
feed_names.emplace_back(harvested_item.feed_title_);
}
names_to_values_map.insertArray("item_titles", item_titles);
names_to_values_map.insertArray("item_urls", item_urls);
names_to_values_map.insertArray("website_urls", website_urls);
names_to_values_map.insertArray("feed_names", feed_names);
const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map));
const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, "title"), email_body,
EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML));
if (retcode <= 299)
return true;
LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!");
return false;
}
const unsigned DEFAULT_XML_INDENT_AMOUNT(2);
void GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) {
XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie("/dev/stdout").release(), XmlWriter::WriteTheXmlDeclaration,
DEFAULT_XML_INDENT_AMOUNT);
WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer);
}
bool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender,
const std::string &user_email, const std::string &user_address, const std::string &language, const bool send_email,
const std::string &subsystem_type, DbConnection * const db_connection) {
db_connection->queryOrDie("SELECT rss_feeds_id FROM tuefind_rss_subscriptions WHERE user_id=" + user_id);
auto rss_subscriptions_result_set(db_connection->getLastResultSet());
std::vector<std::string> feed_ids;
while (const auto row = rss_subscriptions_result_set.getNextRow())
feed_ids.emplace_back(row["rss_feeds_id"]);
if (feed_ids.empty())
return false;
std::vector<HarvestedRSSItem> harvested_items;
std::string max_insertion_time;
for (const auto &feed_id : feed_ids) {
db_connection->queryOrDie("SELECT feed_name,website_url FROM tuefind_rss_feeds WHERE id=" + feed_id);
auto feed_result_set(db_connection->getLastResultSet());
const auto feed_row(feed_result_set.getNextRow());
const auto feed_name(feed_row["feed_name"]);
const auto website_url(feed_row["website_url"]);
feed_result_set.~DbResultSet();
std::string query(
"SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM "
"tuefind_rss_items WHERE rss_feeds_id="
+ feed_id);
if (send_email)
query += " AND insertion_time > '" + rss_feed_last_notification + "'";
db_connection->queryOrDie(query);
auto items_result_set(db_connection->getLastResultSet());
while (const auto item_row = items_result_set.getNextRow()) {
harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"],
item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])),
feed_name, website_url);
const auto insertion_time(item_row["insertion_time"]);
if (insertion_time > max_insertion_time)
max_insertion_time = insertion_time;
}
}
if (harvested_items.empty())
return false;
if (send_email) {
if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items))
return true;
db_connection->queryOrDie("UPDATE user SET tuefind_rss_feed_last_notification='" + max_insertion_time + "' WHERE id=" + user_id);
} else
GenerateFeed(subsystem_type, harvested_items);
return true;
}
} // unnamed namespace
struct UserInfo {
std::string user_id_;
std::string first_name_;
std::string last_name_;
std::string email_;
std::string rss_feed_last_notification_;
std::string language_code_;
public:
UserInfo() = default;
UserInfo(const UserInfo &other) = default;
UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email,
const std::string &rss_feed_last_notification, const std::string &language_code)
: user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email),
rss_feed_last_notification_(rss_feed_last_notification), language_code_(language_code) { }
};
int Main(int argc, char *argv[]) {
if (argc != 4)
Usage();
std::string error_email_address, vufind_user_id;
if (std::strcmp(argv[1], "--mode=email") == 0)
error_email_address = argv[2];
else if (std::strcmp(argv[1], "--mode=rss_xml") == 0)
vufind_user_id = argv[2];
else
Usage();
const std::string subsystem_type(argv[3]);
if (subsystem_type != "ixtheo" and subsystem_type != "relbib" and subsystem_type != "krimdok")
LOG_ERROR("subsystem_type must be one of {ixtheo,relbib,krimdok}!");
auto db_connection(DbConnection::VuFindMySQLFactory());
std::string sql_query(
"SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails"
",tuefind_rss_feed_last_notification,last_language FROM user");
if (vufind_user_id.empty())
sql_query += " WHERE tuefind_rss_feed_send_emails IS TRUE";
else
sql_query += " WHERE id=" + db_connection.escapeAndQuoteString(vufind_user_id);
db_connection.queryOrDie(sql_query);
auto user_result_set(db_connection.getLastResultSet());
std::unordered_map<std::string, UserInfo> ids_to_user_infos_map;
while (const auto user_row = user_result_set.getNextRow()) {
const std::string last_language(user_row["last_language"]);
ids_to_user_infos_map[user_row["id"]] =
UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"],
user_row["tuefind_rss_feed_last_notification"], (last_language.empty() ? "en" : last_language));
}
unsigned feed_generation_count(0), email_sent_count(0);
for (const auto &[user_id, user_info] : ids_to_user_infos_map) {
if (vufind_user_id.empty() and not EmailSender::IsValidEmailAddress(user_info.email_)) {
LOG_WARNING("no valid email address for vufind.user.id " + user_id + "!");
continue;
}
if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, error_email_address, user_info.email_,
MiscUtil::GenerateAddress(user_info.first_name_, user_info.last_name_, "Subscriber"), user_info.language_code_,
vufind_user_id.empty(), subsystem_type, &db_connection))
{
if (vufind_user_id.empty())
++email_sent_count;
++feed_generation_count;
}
}
LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count)
+ " email(s).");
return EXIT_SUCCESS;
}
<commit_msg>rss_subset_aggregator: Added ORDER BY statements (+ statement-related refactoring)<commit_after>/** \file rss_subset_aggregator.cc
* \brief Aggregates RSS feeds.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cinttypes>
#include <cstring>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "EmailSender.h"
#include "FileUtil.h"
#include "HtmlUtil.h"
#include "MiscUtil.h"
#include "SqlUtil.h"
#include "StringUtil.h"
#include "SyndicationFormat.h"
#include "Template.h"
#include "UBTools.h"
#include "XmlWriter.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage(
"--mode=(email|rss_xml) (user_id|error_email_address) subsystem_type]\n"
"If the mode is \"rss_xml\" a VuFind user_id needs to be specified, o/w an error email address should be provided.");
}
struct HarvestedRSSItem {
SyndicationFormat::Item item_;
std::string feed_title_;
std::string website_url_;
HarvestedRSSItem(const SyndicationFormat::Item item, const std::string &feed_title, const std::string &website_url)
: item_(item), feed_title_(feed_title), website_url_(website_url) { }
};
struct ChannelDesc {
std::string title_;
std::string link_;
public:
ChannelDesc(const std::string &title, const std::string &link): title_(title), link_(link) { }
};
const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = {
{ "relbib", ChannelDesc("RelBib RSS Aggregator", "https://relbib.de/") },
{ "ixtheo", ChannelDesc("IxTheo RSS Aggregator", "https://ixtheo.de/") },
{ "krimdok", ChannelDesc("KrimDok RSS Aggregator", "https://krimdok.uni-tuebingen.de/") },
};
std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) {
const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type));
if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend())
LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!");
if (entry == "title")
return subsystem_type_and_channel_desc->second.title_;
if (entry == "link")
return subsystem_type_and_channel_desc->second.link_;
LOG_ERROR("unknown entry name \"" + entry + "\"!");
}
void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items,
XmlWriter * const xml_writer) {
xml_writer->openTag("rss", { { "version", "2.0" } });
xml_writer->openTag("channel");
xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title"));
xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link"));
xml_writer->writeTagsWithData("description", "RSS Aggregator");
for (const auto &harvested_item : harvested_items) {
xml_writer->openTag("item");
const auto title(harvested_item.item_.getTitle());
if (not title.empty())
xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle());
xml_writer->writeTagsWithData("link", harvested_item.item_.getLink());
const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */ 500));
if (not description.empty())
xml_writer->writeTagsWithData("description", description);
xml_writer->writeTagsWithData("pubDate",
TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC));
xml_writer->writeTagsWithData("guid", harvested_item.item_.getId());
xml_writer->closeTag("item", /* suppress_indent */ false);
}
xml_writer->closeTag("channel");
xml_writer->closeTag("rss");
}
struct FeedNameAndURL {
std::string name_;
std::string url_;
public:
FeedNameAndURL() = default;
FeedNameAndURL(const FeedNameAndURL &other) = default;
FeedNameAndURL(const std::string &name, const std::string &url): name_(name), url_(url) { }
};
// \return True if a notification email was sent successfully, o/w false.
bool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email,
const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) {
const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template");
std::string template_filename(template_filename_prefix + "." + language);
if (not FileUtil::Exists(template_filename))
template_filename = template_filename_prefix + ".en";
static const std::string email_template(FileUtil::ReadStringOrDie(template_filename));
Template::Map names_to_values_map;
names_to_values_map.insertScalar("user_name", user_address);
std::vector<std::string> item_titles, item_urls, website_urls, feed_names;
for (const auto &harvested_item : harvested_items) {
item_titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle()));
item_urls.emplace_back(harvested_item.item_.getLink());
website_urls.emplace_back(harvested_item.website_url_);
feed_names.emplace_back(harvested_item.feed_title_);
}
names_to_values_map.insertArray("item_titles", item_titles);
names_to_values_map.insertArray("item_urls", item_urls);
names_to_values_map.insertArray("website_urls", website_urls);
names_to_values_map.insertArray("feed_names", feed_names);
const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map));
const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, "title"), email_body,
EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML));
if (retcode <= 299)
return true;
LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!");
return false;
}
const unsigned DEFAULT_XML_INDENT_AMOUNT(2);
void GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) {
XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie("/dev/stdout").release(), XmlWriter::WriteTheXmlDeclaration,
DEFAULT_XML_INDENT_AMOUNT);
WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer);
}
bool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender,
const std::string &user_email, const std::string &user_address, const std::string &language, const bool send_email,
const std::string &subsystem_type, DbConnection * const db_connection) {
db_connection->queryOrDie(
"SELECT rss_feeds_id, feed_name, website_url "
"FROM tuefind_rss_subscriptions "
"LEFT JOIN tuefind_rss_feeds ON tuefind_rss_subscriptions.rss_feeds_id = tuefind_rss_feeds.id "
"WHERE tuefind_rss_subscriptions.user_id=" + user_id + " "
"ORDER BY feed_name ASC "
);
auto feeds_result_set(db_connection->getLastResultSet());
if (feeds_result_set.empty())
return false;
std::vector<HarvestedRSSItem> harvested_items;
std::string max_insertion_time;
while (const auto feed_row = feeds_result_set.getNextRow()) {
const auto feed_id(feed_row["rss_feeds_id"]);
const auto feed_name(feed_row["feed_name"]);
const auto website_url(feed_row["website_url"]);
std::string query(
"SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM "
"tuefind_rss_items WHERE rss_feeds_id="
+ feed_id);
if (send_email)
query += " AND insertion_time > '" + rss_feed_last_notification + "' ";
query += "ORDER BY pub_date ASC";
db_connection->queryOrDie(query);
auto items_result_set(db_connection->getLastResultSet());
while (const auto item_row = items_result_set.getNextRow()) {
harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"],
item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])),
feed_name, website_url);
const auto insertion_time(item_row["insertion_time"]);
if (insertion_time > max_insertion_time)
max_insertion_time = insertion_time;
}
}
if (harvested_items.empty())
return false;
if (send_email) {
if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items))
return true;
db_connection->queryOrDie("UPDATE user SET tuefind_rss_feed_last_notification='" + max_insertion_time + "' WHERE id=" + user_id);
} else
GenerateFeed(subsystem_type, harvested_items);
return true;
}
} // unnamed namespace
struct UserInfo {
std::string user_id_;
std::string first_name_;
std::string last_name_;
std::string email_;
std::string rss_feed_last_notification_;
std::string language_code_;
public:
UserInfo() = default;
UserInfo(const UserInfo &other) = default;
UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email,
const std::string &rss_feed_last_notification, const std::string &language_code)
: user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email),
rss_feed_last_notification_(rss_feed_last_notification), language_code_(language_code) { }
};
int Main(int argc, char *argv[]) {
if (argc != 4)
Usage();
std::string error_email_address, vufind_user_id;
if (std::strcmp(argv[1], "--mode=email") == 0)
error_email_address = argv[2];
else if (std::strcmp(argv[1], "--mode=rss_xml") == 0)
vufind_user_id = argv[2];
else
Usage();
const std::string subsystem_type(argv[3]);
if (subsystem_type != "ixtheo" and subsystem_type != "relbib" and subsystem_type != "krimdok")
LOG_ERROR("subsystem_type must be one of {ixtheo,relbib,krimdok}!");
auto db_connection(DbConnection::VuFindMySQLFactory());
std::string sql_query(
"SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails"
",tuefind_rss_feed_last_notification,last_language FROM user");
if (vufind_user_id.empty())
sql_query += " WHERE tuefind_rss_feed_send_emails IS TRUE";
else
sql_query += " WHERE id=" + db_connection.escapeAndQuoteString(vufind_user_id);
db_connection.queryOrDie(sql_query);
auto user_result_set(db_connection.getLastResultSet());
std::unordered_map<std::string, UserInfo> ids_to_user_infos_map;
while (const auto user_row = user_result_set.getNextRow()) {
const std::string last_language(user_row["last_language"]);
ids_to_user_infos_map[user_row["id"]] =
UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"],
user_row["tuefind_rss_feed_last_notification"], (last_language.empty() ? "en" : last_language));
}
unsigned feed_generation_count(0), email_sent_count(0);
for (const auto &[user_id, user_info] : ids_to_user_infos_map) {
if (vufind_user_id.empty() and not EmailSender::IsValidEmailAddress(user_info.email_)) {
LOG_WARNING("no valid email address for vufind.user.id " + user_id + "!");
continue;
}
if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, error_email_address, user_info.email_,
MiscUtil::GenerateAddress(user_info.first_name_, user_info.last_name_, "Subscriber"), user_info.language_code_,
vufind_user_id.empty(), subsystem_type, &db_connection))
{
if (vufind_user_id.empty())
++email_sent_count;
++feed_generation_count;
}
}
LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count)
+ " email(s).");
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "blinkstick/blinkstick.hpp"
#include <hidapi/hidapi.h>
#include <array>
#include <cstdarg>
#include <string>
namespace
{
constexpr int VENDOR_ID = 0X20A0;
constexpr int PRODUCT_ID = 0X41E5;
bool print_debug = false;
std::shared_ptr<hid_device> get_device(hid_device_info* device_info)
{
return std::shared_ptr<hid_device>(
hid_open_path(device_info->path),
[](hid_device* device)
{
if (device)
{
hid_close(device);
}
});
}
}
namespace blinkstick
{
void debug(const char* fmt, ...)
{
if (print_debug)
{
char buffer[256];
va_list ap;
va_start(ap, fmt);
vsprintf(buffer, fmt, ap);
va_end(ap);
puts(buffer);
}
}
void enable_logging()
{
print_debug = true;
debug("STARTING BLINKSTICK WITH DEBUG LOGGING");
}
int get_major_version(hid_device_info* device_info)
{
const std::wstring serial = device_info->serial_number;
try
{
return std::stoi(serial.substr(serial.size() - 3, 1));
}
catch (const std::exception&)
{
}
return 0;
}
device_type get_type(hid_device_info* device_info)
{
const auto major_version = get_major_version(device_info);
if (major_version == 1)
{
return device_type::basic;
}
else if (major_version == 2)
{
return device_type::pro;
}
else if (major_version == 3)
{
switch (device_info->release_number)
{
case 0x0200:
return device_type::square;
case 0x0201:
return device_type::strip;
case 0x0202:
return device_type::nano;
case 0x0203:
return device_type::flex;
}
}
return device_type::unknown;
}
std::vector<device> find_all()
{
std::vector<device> devices;
debug("initializing usb context");
const int res = hid_init();
if (res != 0)
{
debug("failed to initialize hid");
return devices;
}
auto all_devices = hid_enumerate(VENDOR_ID, PRODUCT_ID);
if (all_devices == nullptr)
{
return devices;
}
auto device_info = all_devices;
do
{
if(auto device = get_device(device_info); !device)
{
debug("could not open device");
}
else
{
debug("found device: %s", device_info->path);
devices.emplace_back(std::move(device), get_type(device_info));
}
} while ((device_info = device_info->next));
hid_free_enumeration(all_devices);
return devices;
}
device find()
{
const auto devices = find_all();
if (devices.empty())
{
return device{ nullptr, device_type::unknown };
}
return devices.front();
}
void finalise()
{
hid_exit();
}
}
<commit_msg>Bugfix/crash when parsing serial number (#6)<commit_after>#include "blinkstick/blinkstick.hpp"
#include <hidapi/hidapi.h>
#include <array>
#include <cstdarg>
#include <string>
namespace
{
constexpr int VENDOR_ID = 0X20A0;
constexpr int PRODUCT_ID = 0X41E5;
bool print_debug = false;
std::shared_ptr<hid_device> get_device(hid_device_info* device_info)
{
return std::shared_ptr<hid_device>(
hid_open_path(device_info->path),
[](hid_device* device)
{
if (device)
{
hid_close(device);
}
});
}
}
namespace blinkstick
{
void debug(const char* fmt, ...)
{
if (print_debug)
{
char buffer[256];
va_list ap;
va_start(ap, fmt);
vsprintf(buffer, fmt, ap);
va_end(ap);
puts(buffer);
}
}
void enable_logging()
{
print_debug = true;
debug("STARTING BLINKSTICK WITH DEBUG LOGGING");
}
int get_major_version(hid_device_info* device_info)
{
if(device_info->serial_number == nullptr)
{
debug("No serial number");
return 0;
}
const std::wstring serial = device_info->serial_number;
try
{
return std::stoi(serial.substr(serial.size() - 3, 1));
}
catch (const std::exception&)
{
debug("Failed to parse serial number");
}
return 0;
}
device_type get_type(hid_device_info* device_info)
{
const auto major_version = get_major_version(device_info);
if (major_version == 1)
{
return device_type::basic;
}
else if (major_version == 2)
{
return device_type::pro;
}
else if (major_version == 3)
{
switch (device_info->release_number)
{
case 0x0200:
return device_type::square;
case 0x0201:
return device_type::strip;
case 0x0202:
return device_type::nano;
case 0x0203:
return device_type::flex;
}
}
return device_type::unknown;
}
std::vector<device> find_all()
{
std::vector<device> devices;
debug("initializing usb context");
const int res = hid_init();
if (res != 0)
{
debug("failed to initialize hid");
return devices;
}
auto all_devices = hid_enumerate(VENDOR_ID, PRODUCT_ID);
if (all_devices == nullptr)
{
return devices;
}
auto device_info = all_devices;
do
{
if(auto device = get_device(device_info); !device)
{
debug("could not open device");
}
else
{
debug("found device: %s", device_info->path);
devices.emplace_back(std::move(device), get_type(device_info));
}
} while ((device_info = device_info->next));
hid_free_enumeration(all_devices);
return devices;
}
device find()
{
const auto devices = find_all();
if (devices.empty())
{
return device{ nullptr, device_type::unknown };
}
return devices.front();
}
void finalise()
{
hid_exit();
}
}
<|endoftext|>
|
<commit_before>#include <StdAfx.h>
#include <UI/Dialogs/Editors/HexEditor.h>
#include <UI/FileDialogEx.h>
#include <UI/ViewPane/CountedTextPane.h>
#include <UI/ViewPane/SmartViewPane.h>
#include <UI/ViewPane/SplitterPane.h>
#include <UI/ViewPane/TreePane.h>
#include <MAPI/Cache/GlobalCache.h>
#include <MAPI/MAPIFunctions.h>
namespace dialog
{
namespace editor
{
static std::wstring CLASS = L"CHexEditor";
enum __HexEditorFields
{
HEXED_TEXT,
HEXED_ANSI,
HEXED_UNICODE,
HEXED_BASE64,
HEXED_HEX,
HEXED_TREE,
HEXED_SMARTVIEW
};
CHexEditor::CHexEditor(_In_ ui::CParentWnd* pParentWnd, _In_ cache::CMapiObjects* lpMapiObjects)
: CEditor(
pParentWnd,
IDS_HEXEDITOR,
NULL,
CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_ACTION2 | CEDITOR_BUTTON_ACTION3,
IDS_IMPORT,
IDS_EXPORT,
IDS_CLOSE)
{
TRACE_CONSTRUCTOR(CLASS);
m_lpMapiObjects = lpMapiObjects;
if (m_lpMapiObjects) m_lpMapiObjects->AddRef();
auto splitter = viewpane::SplitterPane::CreateHorizontalPane(HEXED_TEXT, IDS_TEXTANSIUNICODE);
AddPane(splitter);
splitter->SetPaneOne(viewpane::TextPane::CreateMultiLinePane(HEXED_ANSI, NULL, false));
splitter->SetPaneTwo(viewpane::TextPane::CreateMultiLinePane(HEXED_UNICODE, NULL, false));
AddPane(viewpane::CountedTextPane::Create(HEXED_BASE64, IDS_BASE64STRING, false, IDS_CCH));
AddPane(viewpane::CountedTextPane::Create(HEXED_HEX, IDS_HEX, false, IDS_CB));
auto tree = viewpane::TreePane::Create(HEXED_TREE, IDS_HEX, true);
AddPane(tree);
tree->m_Tree.ItemSelectedCallback = [&](HTREEITEM hItem) -> void {
auto pane = dynamic_cast<viewpane::TreePane*>(GetPane(HEXED_TREE));
if (pane)
{
WCHAR szText[255] = {};
auto item = TVITEMEXW{};
item.mask = TVIF_TEXT;
item.pszText = szText;
item.cchTextMax = _countof(szText);
item.hItem = hItem;
WC_B_S(::SendMessage(pane->m_Tree.GetSafeHwnd(), TVM_GETITEMW, 0, reinterpret_cast<LPARAM>(&item)));
SetStringW(HEXED_ANSI, szText);
}
};
AddPane(viewpane::SmartViewPane::Create(HEXED_SMARTVIEW, IDS_SMARTVIEW));
DisplayParentedDialog(pParentWnd, 1000);
}
CHexEditor::~CHexEditor()
{
TRACE_DESTRUCTOR(CLASS);
if (m_lpMapiObjects) m_lpMapiObjects->Release();
}
void CHexEditor::OnOK()
{
ShowWindow(SW_HIDE);
delete this;
}
void CHexEditor::OnCancel() { OnOK(); }
_Check_return_ ULONG CHexEditor::HandleChange(const UINT nID)
{
const auto paneID = CEditor::HandleChange(nID);
if (paneID == static_cast<ULONG>(-1)) return static_cast<ULONG>(-1);
auto lpb = LPBYTE{};
size_t cb = 0;
std::wstring szEncodeStr;
size_t cchEncodeStr = 0;
switch (paneID)
{
case HEXED_ANSI:
{
auto text = GetStringA(HEXED_ANSI);
SetStringA(HEXED_UNICODE, text);
lpb = LPBYTE(text.c_str());
cb = text.length() * sizeof(CHAR);
szEncodeStr = strings::Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr);
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_UNICODE: // Unicode string changed
{
auto text = GetStringW(HEXED_UNICODE);
SetStringW(HEXED_ANSI, text);
lpb = LPBYTE(text.c_str());
cb = text.length() * sizeof(WCHAR);
szEncodeStr = strings::Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr);
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_BASE64: // base64 changed
{
auto szTmpString = GetStringW(HEXED_BASE64);
// remove any whitespace before decoding
szTmpString = strings::StripCRLF(szTmpString);
cchEncodeStr = szTmpString.length();
auto bin = strings::Base64Decode(szTmpString);
lpb = bin.data();
cb = bin.size();
SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb));
if (!(cb % 2)) // Set Unicode String
{
SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR)));
}
else
{
SetStringW(HEXED_UNICODE, L"");
}
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_HEX: // binary changed
{
auto bin = GetBinary(HEXED_HEX);
lpb = bin.data();
cb = bin.size();
SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb)); // ansi string
if (!(cb % 2)) // Set Unicode String
{
SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR)));
}
else
{
SetStringW(HEXED_UNICODE, L"");
}
szEncodeStr = strings::Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr);
}
break;
default:
break;
}
if (HEXED_SMARTVIEW != paneID)
{
// length of base64 encoded string
auto lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_BASE64));
if (lpPane)
{
lpPane->SetCount(cchEncodeStr);
}
lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_HEX));
if (lpPane)
{
lpPane->SetCount(cb);
}
}
// Update any parsing we've got:
UpdateParser();
// Force the new layout
OnRecalcLayout();
return paneID;
}
void CHexEditor::UpdateParser() const
{
// Find out how to interpret the data
auto lpPane = dynamic_cast<viewpane::SmartViewPane*>(GetPane(HEXED_SMARTVIEW));
if (lpPane)
{
auto bin = GetBinary(HEXED_HEX);
lpPane->Parse(SBinary{ULONG(bin.size()), bin.data()});
}
}
// Import
void CHexEditor::OnEditAction1()
{
auto file = file::CFileDialogExW::OpenFile(
strings::emptystring, strings::emptystring, OFN_FILEMUSTEXIST, strings::loadstring(IDS_ALLFILES), this);
if (!file.empty())
{
cache::CGlobalCache::getInstance().MAPIInitialize(NULL);
LPSTREAM lpStream = nullptr;
// Get a Stream interface on the input file
EC_H_S(mapi::MyOpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer, STGM_READ, file, &lpStream));
if (lpStream)
{
auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX));
if (lpPane)
{
lpPane->SetBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
// Export
void CHexEditor::OnEditAction2()
{
auto file = file::CFileDialogExW::SaveAs(
strings::emptystring,
strings::emptystring,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
strings::loadstring(IDS_ALLFILES),
this);
if (!file.empty())
{
cache::CGlobalCache::getInstance().MAPIInitialize(NULL);
LPSTREAM lpStream = nullptr;
// Get a Stream interface on the output file
EC_H_S(mapi::MyOpenStreamOnFile(
MAPIAllocateBuffer, MAPIFreeBuffer, STGM_CREATE | STGM_READWRITE, file, &lpStream));
if (lpStream)
{
const auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX));
if (lpPane)
{
lpPane->GetBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
// Close
void CHexEditor::OnEditAction3() { OnOK(); }
} // namespace editor
} // namespace dialog
<commit_msg>Simplify callback setup<commit_after>#include <StdAfx.h>
#include <UI/Dialogs/Editors/HexEditor.h>
#include <UI/FileDialogEx.h>
#include <UI/ViewPane/CountedTextPane.h>
#include <UI/ViewPane/SmartViewPane.h>
#include <UI/ViewPane/SplitterPane.h>
#include <UI/ViewPane/TreePane.h>
#include <MAPI/Cache/GlobalCache.h>
#include <MAPI/MAPIFunctions.h>
namespace dialog
{
namespace editor
{
static std::wstring CLASS = L"CHexEditor";
enum __HexEditorFields
{
HEXED_TEXT,
HEXED_ANSI,
HEXED_UNICODE,
HEXED_BASE64,
HEXED_HEX,
HEXED_TREE,
HEXED_SMARTVIEW
};
CHexEditor::CHexEditor(_In_ ui::CParentWnd* pParentWnd, _In_ cache::CMapiObjects* lpMapiObjects)
: CEditor(
pParentWnd,
IDS_HEXEDITOR,
NULL,
CEDITOR_BUTTON_ACTION1 | CEDITOR_BUTTON_ACTION2 | CEDITOR_BUTTON_ACTION3,
IDS_IMPORT,
IDS_EXPORT,
IDS_CLOSE)
{
TRACE_CONSTRUCTOR(CLASS);
m_lpMapiObjects = lpMapiObjects;
if (m_lpMapiObjects) m_lpMapiObjects->AddRef();
auto splitter = viewpane::SplitterPane::CreateHorizontalPane(HEXED_TEXT, IDS_TEXTANSIUNICODE);
AddPane(splitter);
splitter->SetPaneOne(viewpane::TextPane::CreateMultiLinePane(HEXED_ANSI, NULL, false));
splitter->SetPaneTwo(viewpane::TextPane::CreateMultiLinePane(HEXED_UNICODE, NULL, false));
AddPane(viewpane::CountedTextPane::Create(HEXED_BASE64, IDS_BASE64STRING, false, IDS_CCH));
AddPane(viewpane::CountedTextPane::Create(HEXED_HEX, IDS_HEX, false, IDS_CB));
auto tree = viewpane::TreePane::Create(HEXED_TREE, IDS_HEX, true);
AddPane(tree);
tree->m_Tree.ItemSelectedCallback = [&](auto hItem) {
auto pane = dynamic_cast<viewpane::TreePane*>(GetPane(HEXED_TREE));
if (pane)
{
WCHAR szText[255] = {};
auto item = TVITEMEXW{};
item.mask = TVIF_TEXT;
item.pszText = szText;
item.cchTextMax = _countof(szText);
item.hItem = hItem;
WC_B_S(::SendMessage(pane->m_Tree.GetSafeHwnd(), TVM_GETITEMW, 0, reinterpret_cast<LPARAM>(&item)));
SetStringW(HEXED_ANSI, szText);
}
};
AddPane(viewpane::SmartViewPane::Create(HEXED_SMARTVIEW, IDS_SMARTVIEW));
DisplayParentedDialog(pParentWnd, 1000);
}
CHexEditor::~CHexEditor()
{
TRACE_DESTRUCTOR(CLASS);
if (m_lpMapiObjects) m_lpMapiObjects->Release();
}
void CHexEditor::OnOK()
{
ShowWindow(SW_HIDE);
delete this;
}
void CHexEditor::OnCancel() { OnOK(); }
_Check_return_ ULONG CHexEditor::HandleChange(const UINT nID)
{
const auto paneID = CEditor::HandleChange(nID);
if (paneID == static_cast<ULONG>(-1)) return static_cast<ULONG>(-1);
auto lpb = LPBYTE{};
size_t cb = 0;
std::wstring szEncodeStr;
size_t cchEncodeStr = 0;
switch (paneID)
{
case HEXED_ANSI:
{
auto text = GetStringA(HEXED_ANSI);
SetStringA(HEXED_UNICODE, text);
lpb = LPBYTE(text.c_str());
cb = text.length() * sizeof(CHAR);
szEncodeStr = strings::Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr);
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_UNICODE: // Unicode string changed
{
auto text = GetStringW(HEXED_UNICODE);
SetStringW(HEXED_ANSI, text);
lpb = LPBYTE(text.c_str());
cb = text.length() * sizeof(WCHAR);
szEncodeStr = strings::Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr);
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_BASE64: // base64 changed
{
auto szTmpString = GetStringW(HEXED_BASE64);
// remove any whitespace before decoding
szTmpString = strings::StripCRLF(szTmpString);
cchEncodeStr = szTmpString.length();
auto bin = strings::Base64Decode(szTmpString);
lpb = bin.data();
cb = bin.size();
SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb));
if (!(cb % 2)) // Set Unicode String
{
SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR)));
}
else
{
SetStringW(HEXED_UNICODE, L"");
}
SetBinary(HEXED_HEX, lpb, cb);
}
break;
case HEXED_HEX: // binary changed
{
auto bin = GetBinary(HEXED_HEX);
lpb = bin.data();
cb = bin.size();
SetStringA(HEXED_ANSI, std::string(LPCSTR(lpb), cb)); // ansi string
if (!(cb % 2)) // Set Unicode String
{
SetStringW(HEXED_UNICODE, std::wstring(LPWSTR(lpb), cb / sizeof(WCHAR)));
}
else
{
SetStringW(HEXED_UNICODE, L"");
}
szEncodeStr = strings::Base64Encode(cb, lpb);
cchEncodeStr = szEncodeStr.length();
SetStringW(HEXED_BASE64, szEncodeStr);
}
break;
default:
break;
}
if (HEXED_SMARTVIEW != paneID)
{
// length of base64 encoded string
auto lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_BASE64));
if (lpPane)
{
lpPane->SetCount(cchEncodeStr);
}
lpPane = dynamic_cast<viewpane::CountedTextPane*>(GetPane(HEXED_HEX));
if (lpPane)
{
lpPane->SetCount(cb);
}
}
// Update any parsing we've got:
UpdateParser();
// Force the new layout
OnRecalcLayout();
return paneID;
}
void CHexEditor::UpdateParser() const
{
// Find out how to interpret the data
auto lpPane = dynamic_cast<viewpane::SmartViewPane*>(GetPane(HEXED_SMARTVIEW));
if (lpPane)
{
auto bin = GetBinary(HEXED_HEX);
lpPane->Parse(SBinary{ULONG(bin.size()), bin.data()});
}
}
// Import
void CHexEditor::OnEditAction1()
{
auto file = file::CFileDialogExW::OpenFile(
strings::emptystring, strings::emptystring, OFN_FILEMUSTEXIST, strings::loadstring(IDS_ALLFILES), this);
if (!file.empty())
{
cache::CGlobalCache::getInstance().MAPIInitialize(NULL);
LPSTREAM lpStream = nullptr;
// Get a Stream interface on the input file
EC_H_S(mapi::MyOpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer, STGM_READ, file, &lpStream));
if (lpStream)
{
auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX));
if (lpPane)
{
lpPane->SetBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
// Export
void CHexEditor::OnEditAction2()
{
auto file = file::CFileDialogExW::SaveAs(
strings::emptystring,
strings::emptystring,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
strings::loadstring(IDS_ALLFILES),
this);
if (!file.empty())
{
cache::CGlobalCache::getInstance().MAPIInitialize(NULL);
LPSTREAM lpStream = nullptr;
// Get a Stream interface on the output file
EC_H_S(mapi::MyOpenStreamOnFile(
MAPIAllocateBuffer, MAPIFreeBuffer, STGM_CREATE | STGM_READWRITE, file, &lpStream));
if (lpStream)
{
const auto lpPane = dynamic_cast<viewpane::TextPane*>(GetPane(HEXED_HEX));
if (lpPane)
{
lpPane->GetBinaryStream(lpStream);
}
lpStream->Release();
}
}
}
// Close
void CHexEditor::OnEditAction3() { OnOK(); }
} // namespace editor
} // namespace dialog
<|endoftext|>
|
<commit_before><commit_msg>Don't ignore special character input on the Mac.<commit_after><|endoftext|>
|
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/android/router/media_router_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/memory/scoped_vector.h"
#include "chrome/browser/media/router/media_routes_observer.h"
#include "chrome/browser/media/router/media_sinks_observer.h"
#include "chrome/browser/media/router/presentation_session_messages_observer.h"
#include "jni/ChromeMediaRouter_jni.h"
using base::android::ConvertUTF8ToJavaString;
using base::android::ConvertJavaStringToUTF8;
using base::android::ScopedJavaLocalRef;
using base::android::AttachCurrentThread;
namespace media_router {
MediaRouterAndroid::CreateMediaRouteRequest::CreateMediaRouteRequest(
const MediaSource& source,
const MediaSink& sink,
const std::string& presentation_id,
const std::vector<MediaRouteResponseCallback>& callbacks)
: media_source(source),
media_sink(sink),
presentation_id(presentation_id),
callbacks(callbacks) {}
MediaRouterAndroid::CreateMediaRouteRequest::~CreateMediaRouteRequest() {}
MediaRouterAndroid::MediaRouterAndroid(content::BrowserContext*) {
JNIEnv* env = base::android::AttachCurrentThread();
java_media_router_.Reset(Java_ChromeMediaRouter_create(
env,
reinterpret_cast<jlong>(this),
base::android::GetApplicationContext()));
}
MediaRouterAndroid::~MediaRouterAndroid() {
}
// static
bool MediaRouterAndroid::Register(JNIEnv* env) {
bool ret = RegisterNativesImpl(env);
DCHECK(g_ChromeMediaRouter_clazz);
return ret;
}
void MediaRouterAndroid::CreateRoute(
const MediaSource::Id& source_id,
const MediaSink::Id& sink_id,
const GURL& origin,
int tab_id,
const std::vector<MediaRouteResponseCallback>& callbacks) {
if (!origin.is_valid()) {
for (const MediaRouteResponseCallback& callback : callbacks)
callback.Run(nullptr, "", "Invalid origin");
return;
}
// TODO(avayvod): unify presentation id generation code between platforms.
// https://crbug.com/522239
std::string presentation_id("mr_");
presentation_id += base::GenerateGUID();
CreateMediaRouteRequest* request = new CreateMediaRouteRequest(
MediaSource(source_id),
MediaSink(sink_id, std::string()),
presentation_id,
callbacks);
int create_route_request_id = create_route_requests_.Add(request);
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jsource_id =
base::android::ConvertUTF8ToJavaString(env, source_id);
ScopedJavaLocalRef<jstring> jsink_id =
base::android::ConvertUTF8ToJavaString(env, sink_id);
ScopedJavaLocalRef<jstring> jpresentation_id =
base::android::ConvertUTF8ToJavaString(env, presentation_id);
Java_ChromeMediaRouter_createRoute(
env,
java_media_router_.obj(),
jsource_id.obj(),
jsink_id.obj(),
jpresentation_id.obj(),
create_route_request_id);
}
void MediaRouterAndroid::JoinRoute(
const MediaSource::Id& source,
const std::string& presentation_id,
const GURL& origin,
int tab_id,
const std::vector<MediaRouteResponseCallback>& callbacks) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::CloseRoute(const MediaRoute::Id& route_id) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jroute_id =
base::android::ConvertUTF8ToJavaString(env, route_id);
Java_ChromeMediaRouter_closeRoute(
env, java_media_router_.obj(), jroute_id.obj());
}
void MediaRouterAndroid::SendRouteMessage(
const MediaRoute::Id& route_id,
const std::string& message,
const SendRouteMessageCallback& callback) {
int callback_id = message_callbacks_.Add(
new SendRouteMessageCallback(callback));
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jroute_id =
base::android::ConvertUTF8ToJavaString(env, route_id);
ScopedJavaLocalRef<jstring> jmessage =
base::android::ConvertUTF8ToJavaString(env, message);
Java_ChromeMediaRouter_sendStringMessage(
env,
java_media_router_.obj(),
jroute_id.obj(),
jmessage.obj(),
callback_id);
}
void MediaRouterAndroid::SendRouteBinaryMessage(
const MediaRoute::Id& route_id,
scoped_ptr<std::vector<uint8>> data,
const SendRouteMessageCallback& callback) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::ClearIssue(const Issue::Id& issue_id) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::OnPresentationSessionDetached(
const MediaRoute::Id& route_id) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::RegisterMediaSinksObserver(
MediaSinksObserver* observer) {
const std::string& source_id = observer->source().id();
base::ObserverList<MediaSinksObserver>* observer_list =
sinks_observers_.get(source_id);
if (!observer_list) {
observer_list = new base::ObserverList<MediaSinksObserver>;
sinks_observers_.add(source_id, make_scoped_ptr(observer_list));
} else {
DCHECK(!observer_list->HasObserver(observer));
}
observer_list->AddObserver(observer);
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jsource_id =
base::android::ConvertUTF8ToJavaString(env, source_id);
Java_ChromeMediaRouter_startObservingMediaSinks(
env, java_media_router_.obj(), jsource_id.obj());
}
void MediaRouterAndroid::UnregisterMediaSinksObserver(
MediaSinksObserver* observer) {
const std::string& source_id = observer->source().id();
auto* observer_list = sinks_observers_.get(source_id);
if (!observer_list || !observer_list->HasObserver(observer))
return;
// If we are removing the final observer for the source, then stop
// observing sinks for it.
// might_have_observers() is reliable here on the assumption that this call
// is not inside the ObserverList iteration.
observer_list->RemoveObserver(observer);
if (!observer_list->might_have_observers()) {
sinks_observers_.erase(source_id);
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jsource_id =
base::android::ConvertUTF8ToJavaString(env, source_id);
Java_ChromeMediaRouter_stopObservingMediaSinks(
env, java_media_router_.obj(), jsource_id.obj());
}
}
void MediaRouterAndroid::RegisterMediaRoutesObserver(
MediaRoutesObserver* observer) {
DVLOG(2) << "Added MediaRoutesObserver: " << observer;
routes_observers_.AddObserver(observer);
}
void MediaRouterAndroid::UnregisterMediaRoutesObserver(
MediaRoutesObserver* observer) {
if (!routes_observers_.HasObserver(observer))
return;
routes_observers_.RemoveObserver(observer);
}
void MediaRouterAndroid::RegisterIssuesObserver(IssuesObserver* observer) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::UnregisterIssuesObserver(IssuesObserver* observer) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::RegisterPresentationSessionMessagesObserver(
PresentationSessionMessagesObserver* observer) {
const MediaRoute::Id& route_id = observer->route_id();
auto* observer_list = messages_observers_.get(route_id);
if (!observer_list) {
observer_list = new base::ObserverList<PresentationSessionMessagesObserver>;
messages_observers_.add(route_id, make_scoped_ptr(observer_list));
} else {
DCHECK(!observer_list->HasObserver(observer));
}
observer_list->AddObserver(observer);
}
void MediaRouterAndroid::UnregisterPresentationSessionMessagesObserver(
PresentationSessionMessagesObserver* observer) {
const MediaRoute::Id& route_id = observer->route_id();
auto* observer_list = messages_observers_.get(route_id);
DCHECK(observer_list->HasObserver(observer));
observer_list->RemoveObserver(observer);
if (!observer_list->might_have_observers())
messages_observers_.erase(route_id);
}
void MediaRouterAndroid::OnSinksReceived(
JNIEnv* env,
jobject obj,
jstring jsource_urn,
jint jcount) {
std::vector<MediaSink> sinks_converted;
sinks_converted.reserve(jcount);
for (int i = 0; i < jcount; ++i) {
ScopedJavaLocalRef<jstring> jsink_urn =
Java_ChromeMediaRouter_getSinkUrn(
env, java_media_router_.obj(), jsource_urn, i);
ScopedJavaLocalRef<jstring> jsink_name =
Java_ChromeMediaRouter_getSinkName(
env, java_media_router_.obj(), jsource_urn, i);
sinks_converted.push_back(
MediaSink(ConvertJavaStringToUTF8(env, jsink_urn.obj()),
ConvertJavaStringToUTF8(env, jsink_name.obj())));
}
std::string source_urn = ConvertJavaStringToUTF8(env, jsource_urn);
auto it = sinks_observers_.find(source_urn);
if (it != sinks_observers_.end()) {
FOR_EACH_OBSERVER(MediaSinksObserver, *it->second,
OnSinksReceived(sinks_converted));
}
}
void MediaRouterAndroid::OnRouteCreated(
JNIEnv* env,
jobject obj,
jstring jmedia_route_id,
jint jcreate_route_request_id,
jboolean jis_local) {
CreateMediaRouteRequest* request =
create_route_requests_.Lookup(jcreate_route_request_id);
if (!request)
return;
MediaRoute route(
ConvertJavaStringToUTF8(env, jmedia_route_id),
request->media_source,
request->media_sink,
std::string(),
jis_local,
std::string());
for (const MediaRouteResponseCallback& callback : request->callbacks)
callback.Run(&route, request->presentation_id, std::string());
create_route_requests_.Remove(jcreate_route_request_id);
active_routes_.push_back(route);
FOR_EACH_OBSERVER(MediaRoutesObserver, routes_observers_,
OnRoutesUpdated(active_routes_));
}
void MediaRouterAndroid::OnRouteCreationError(
JNIEnv* env,
jobject obj,
jstring jerror_text,
jint jcreate_route_request_id) {
CreateMediaRouteRequest* request =
create_route_requests_.Lookup(jcreate_route_request_id);
if (!request)
return;
std::string error_text = ConvertJavaStringToUTF8(env, jerror_text);
for (const MediaRouteResponseCallback& callback : request->callbacks)
callback.Run(nullptr, std::string(), error_text);
create_route_requests_.Remove(jcreate_route_request_id);
}
void MediaRouterAndroid::OnRouteClosed(JNIEnv* env,
jobject obj,
jstring jmedia_route_id) {
MediaRoute::Id route_id = ConvertJavaStringToUTF8(env, jmedia_route_id);
for (auto it = active_routes_.begin(); it != active_routes_.end(); ++it)
if (it->media_route_id() == route_id) {
active_routes_.erase(it);
break;
}
FOR_EACH_OBSERVER(MediaRoutesObserver, routes_observers_,
OnRoutesUpdated(active_routes_));
}
void MediaRouterAndroid::OnMessageSentResult(
JNIEnv* env, jobject obj, jboolean jsuccess, jint jcallback_id) {
SendRouteMessageCallback* callback = message_callbacks_.Lookup(jcallback_id);
callback->Run(jsuccess);
message_callbacks_.Remove(jcallback_id);
}
// Notifies the media router about a message received from the media route.
void MediaRouterAndroid::OnMessage(
JNIEnv* env, jobject obj, jstring jmedia_route_id, jstring jmessage) {
MediaRoute::Id route_id = ConvertJavaStringToUTF8(env, jmedia_route_id);
auto* observer_list = messages_observers_.get(route_id);
if (!observer_list)
return;
ScopedVector<content::PresentationSessionMessage> session_messages;
scoped_ptr<content::PresentationSessionMessage> message(
new content::PresentationSessionMessage(content::TEXT));
message->message = ConvertJavaStringToUTF8(env, jmessage);
session_messages.push_back(message.Pass());
FOR_EACH_OBSERVER(PresentationSessionMessagesObserver, *observer_list,
OnMessagesReceived(session_messages, true));
}
} // namespace media_router
<commit_msg>[Presentation API, Android] Implement joining presentations by id<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/android/router/media_router_android.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/memory/scoped_vector.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/media/router/media_routes_observer.h"
#include "chrome/browser/media/router/media_sinks_observer.h"
#include "chrome/browser/media/router/presentation_session_messages_observer.h"
#include "jni/ChromeMediaRouter_jni.h"
#include "url/gurl.h"
using base::android::ConvertUTF8ToJavaString;
using base::android::ConvertJavaStringToUTF8;
using base::android::ScopedJavaLocalRef;
using base::android::AttachCurrentThread;
namespace media_router {
MediaRouterAndroid::CreateMediaRouteRequest::CreateMediaRouteRequest(
const MediaSource& source,
const MediaSink& sink,
const std::string& presentation_id,
const std::vector<MediaRouteResponseCallback>& callbacks)
: media_source(source),
media_sink(sink),
presentation_id(presentation_id),
callbacks(callbacks) {}
MediaRouterAndroid::CreateMediaRouteRequest::~CreateMediaRouteRequest() {}
MediaRouterAndroid::MediaRouterAndroid(content::BrowserContext*) {
JNIEnv* env = base::android::AttachCurrentThread();
java_media_router_.Reset(Java_ChromeMediaRouter_create(
env,
reinterpret_cast<jlong>(this),
base::android::GetApplicationContext()));
}
MediaRouterAndroid::~MediaRouterAndroid() {
}
// static
bool MediaRouterAndroid::Register(JNIEnv* env) {
bool ret = RegisterNativesImpl(env);
DCHECK(g_ChromeMediaRouter_clazz);
return ret;
}
void MediaRouterAndroid::CreateRoute(
const MediaSource::Id& source_id,
const MediaSink::Id& sink_id,
const GURL& origin,
int tab_id,
const std::vector<MediaRouteResponseCallback>& callbacks) {
if (!origin.is_valid()) {
for (const MediaRouteResponseCallback& callback : callbacks)
callback.Run(nullptr, "", "Invalid origin");
return;
}
// TODO(avayvod): unify presentation id generation code between platforms.
// https://crbug.com/522239
std::string presentation_id("mr_");
presentation_id += base::GenerateGUID();
CreateMediaRouteRequest* request = new CreateMediaRouteRequest(
MediaSource(source_id),
MediaSink(sink_id, std::string()),
presentation_id,
callbacks);
int create_route_request_id = create_route_requests_.Add(request);
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jsource_id =
base::android::ConvertUTF8ToJavaString(env, source_id);
ScopedJavaLocalRef<jstring> jsink_id =
base::android::ConvertUTF8ToJavaString(env, sink_id);
ScopedJavaLocalRef<jstring> jpresentation_id =
base::android::ConvertUTF8ToJavaString(env, presentation_id);
Java_ChromeMediaRouter_createRoute(
env,
java_media_router_.obj(),
jsource_id.obj(),
jsink_id.obj(),
jpresentation_id.obj(),
create_route_request_id);
}
void MediaRouterAndroid::JoinRoute(
const MediaSource::Id& source,
const std::string& presentation_id,
const GURL& origin,
int tab_id,
const std::vector<MediaRouteResponseCallback>& callbacks) {
GURL source_url(source);
DCHECK(source_url.is_valid());
const MediaRoute* matching_route = nullptr;
for (const auto& route : active_routes_) {
GURL route_source_url(route.media_source().id());
DCHECK(route_source_url.is_valid());
if (route_source_url.scheme() != source_url.scheme() ||
route_source_url.username() != source_url.username() ||
route_source_url.password() != source_url.password() ||
route_source_url.host() != source_url.host() ||
route_source_url.port() != source_url.port() ||
route_source_url.path() != source_url.path() ||
route_source_url.query() != source_url.query()) {
// Allow the ref() to be different.
continue;
}
// Since ref() could be different, use the existing route's source id.
const std::string& sink_id = route.media_sink().id();
const std::string& potential_route_id = base::StringPrintf(
"route:%s/%s/%s",
presentation_id.c_str(),
sink_id.c_str(),
route.media_source().id().c_str());
if (potential_route_id == route.media_route_id()) {
matching_route = &route;
break;
}
}
if (!matching_route) {
for (const auto& callback : callbacks)
callback.Run(nullptr, std::string(), "No routes found");
return;
}
for (const auto& callback : callbacks)
callback.Run(matching_route, presentation_id, std::string());
}
void MediaRouterAndroid::CloseRoute(const MediaRoute::Id& route_id) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jroute_id =
base::android::ConvertUTF8ToJavaString(env, route_id);
Java_ChromeMediaRouter_closeRoute(
env, java_media_router_.obj(), jroute_id.obj());
}
void MediaRouterAndroid::SendRouteMessage(
const MediaRoute::Id& route_id,
const std::string& message,
const SendRouteMessageCallback& callback) {
int callback_id = message_callbacks_.Add(
new SendRouteMessageCallback(callback));
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jroute_id =
base::android::ConvertUTF8ToJavaString(env, route_id);
ScopedJavaLocalRef<jstring> jmessage =
base::android::ConvertUTF8ToJavaString(env, message);
Java_ChromeMediaRouter_sendStringMessage(
env,
java_media_router_.obj(),
jroute_id.obj(),
jmessage.obj(),
callback_id);
}
void MediaRouterAndroid::SendRouteBinaryMessage(
const MediaRoute::Id& route_id,
scoped_ptr<std::vector<uint8>> data,
const SendRouteMessageCallback& callback) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::ClearIssue(const Issue::Id& issue_id) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::OnPresentationSessionDetached(
const MediaRoute::Id& route_id) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::RegisterMediaSinksObserver(
MediaSinksObserver* observer) {
const std::string& source_id = observer->source().id();
base::ObserverList<MediaSinksObserver>* observer_list =
sinks_observers_.get(source_id);
if (!observer_list) {
observer_list = new base::ObserverList<MediaSinksObserver>;
sinks_observers_.add(source_id, make_scoped_ptr(observer_list));
} else {
DCHECK(!observer_list->HasObserver(observer));
}
observer_list->AddObserver(observer);
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jsource_id =
base::android::ConvertUTF8ToJavaString(env, source_id);
Java_ChromeMediaRouter_startObservingMediaSinks(
env, java_media_router_.obj(), jsource_id.obj());
}
void MediaRouterAndroid::UnregisterMediaSinksObserver(
MediaSinksObserver* observer) {
const std::string& source_id = observer->source().id();
auto* observer_list = sinks_observers_.get(source_id);
if (!observer_list || !observer_list->HasObserver(observer))
return;
// If we are removing the final observer for the source, then stop
// observing sinks for it.
// might_have_observers() is reliable here on the assumption that this call
// is not inside the ObserverList iteration.
observer_list->RemoveObserver(observer);
if (!observer_list->might_have_observers()) {
sinks_observers_.erase(source_id);
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jsource_id =
base::android::ConvertUTF8ToJavaString(env, source_id);
Java_ChromeMediaRouter_stopObservingMediaSinks(
env, java_media_router_.obj(), jsource_id.obj());
}
}
void MediaRouterAndroid::RegisterMediaRoutesObserver(
MediaRoutesObserver* observer) {
DVLOG(2) << "Added MediaRoutesObserver: " << observer;
routes_observers_.AddObserver(observer);
}
void MediaRouterAndroid::UnregisterMediaRoutesObserver(
MediaRoutesObserver* observer) {
if (!routes_observers_.HasObserver(observer))
return;
routes_observers_.RemoveObserver(observer);
}
void MediaRouterAndroid::RegisterIssuesObserver(IssuesObserver* observer) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::UnregisterIssuesObserver(IssuesObserver* observer) {
NOTIMPLEMENTED();
}
void MediaRouterAndroid::RegisterPresentationSessionMessagesObserver(
PresentationSessionMessagesObserver* observer) {
const MediaRoute::Id& route_id = observer->route_id();
auto* observer_list = messages_observers_.get(route_id);
if (!observer_list) {
observer_list = new base::ObserverList<PresentationSessionMessagesObserver>;
messages_observers_.add(route_id, make_scoped_ptr(observer_list));
} else {
DCHECK(!observer_list->HasObserver(observer));
}
observer_list->AddObserver(observer);
}
void MediaRouterAndroid::UnregisterPresentationSessionMessagesObserver(
PresentationSessionMessagesObserver* observer) {
const MediaRoute::Id& route_id = observer->route_id();
auto* observer_list = messages_observers_.get(route_id);
DCHECK(observer_list->HasObserver(observer));
observer_list->RemoveObserver(observer);
if (!observer_list->might_have_observers())
messages_observers_.erase(route_id);
}
void MediaRouterAndroid::OnSinksReceived(
JNIEnv* env,
jobject obj,
jstring jsource_urn,
jint jcount) {
std::vector<MediaSink> sinks_converted;
sinks_converted.reserve(jcount);
for (int i = 0; i < jcount; ++i) {
ScopedJavaLocalRef<jstring> jsink_urn =
Java_ChromeMediaRouter_getSinkUrn(
env, java_media_router_.obj(), jsource_urn, i);
ScopedJavaLocalRef<jstring> jsink_name =
Java_ChromeMediaRouter_getSinkName(
env, java_media_router_.obj(), jsource_urn, i);
sinks_converted.push_back(
MediaSink(ConvertJavaStringToUTF8(env, jsink_urn.obj()),
ConvertJavaStringToUTF8(env, jsink_name.obj())));
}
std::string source_urn = ConvertJavaStringToUTF8(env, jsource_urn);
auto it = sinks_observers_.find(source_urn);
if (it != sinks_observers_.end()) {
FOR_EACH_OBSERVER(MediaSinksObserver, *it->second,
OnSinksReceived(sinks_converted));
}
}
void MediaRouterAndroid::OnRouteCreated(
JNIEnv* env,
jobject obj,
jstring jmedia_route_id,
jint jcreate_route_request_id,
jboolean jis_local) {
CreateMediaRouteRequest* request =
create_route_requests_.Lookup(jcreate_route_request_id);
if (!request)
return;
MediaRoute route(
ConvertJavaStringToUTF8(env, jmedia_route_id),
request->media_source,
request->media_sink,
std::string(),
jis_local,
std::string());
for (const MediaRouteResponseCallback& callback : request->callbacks)
callback.Run(&route, request->presentation_id, std::string());
create_route_requests_.Remove(jcreate_route_request_id);
active_routes_.push_back(route);
FOR_EACH_OBSERVER(MediaRoutesObserver, routes_observers_,
OnRoutesUpdated(active_routes_));
}
void MediaRouterAndroid::OnRouteCreationError(
JNIEnv* env,
jobject obj,
jstring jerror_text,
jint jcreate_route_request_id) {
CreateMediaRouteRequest* request =
create_route_requests_.Lookup(jcreate_route_request_id);
if (!request)
return;
std::string error_text = ConvertJavaStringToUTF8(env, jerror_text);
for (const MediaRouteResponseCallback& callback : request->callbacks)
callback.Run(nullptr, std::string(), error_text);
create_route_requests_.Remove(jcreate_route_request_id);
}
void MediaRouterAndroid::OnRouteClosed(JNIEnv* env,
jobject obj,
jstring jmedia_route_id) {
MediaRoute::Id route_id = ConvertJavaStringToUTF8(env, jmedia_route_id);
for (auto it = active_routes_.begin(); it != active_routes_.end(); ++it)
if (it->media_route_id() == route_id) {
active_routes_.erase(it);
break;
}
FOR_EACH_OBSERVER(MediaRoutesObserver, routes_observers_,
OnRoutesUpdated(active_routes_));
}
void MediaRouterAndroid::OnMessageSentResult(
JNIEnv* env, jobject obj, jboolean jsuccess, jint jcallback_id) {
SendRouteMessageCallback* callback = message_callbacks_.Lookup(jcallback_id);
callback->Run(jsuccess);
message_callbacks_.Remove(jcallback_id);
}
// Notifies the media router about a message received from the media route.
void MediaRouterAndroid::OnMessage(
JNIEnv* env, jobject obj, jstring jmedia_route_id, jstring jmessage) {
MediaRoute::Id route_id = ConvertJavaStringToUTF8(env, jmedia_route_id);
auto* observer_list = messages_observers_.get(route_id);
if (!observer_list)
return;
ScopedVector<content::PresentationSessionMessage> session_messages;
scoped_ptr<content::PresentationSessionMessage> message(
new content::PresentationSessionMessage(content::TEXT));
message->message = ConvertJavaStringToUTF8(env, jmessage);
session_messages.push_back(message.Pass());
FOR_EACH_OBSERVER(PresentationSessionMessagesObserver, *observer_list,
OnMessagesReceived(session_messages, true));
}
} // namespace media_router
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef.h"
#include "include/cef_runnable.h"
#include "cefclient.h"
#include "client_handler.h"
#include "resource.h"
#include <commdlg.h>
#include <direct.h>
#include <sstream>
#include <shellapi.h>
#define MAX_LOADSTRING 100
#define MAX_URL_LENGTH 255
#define BUTTON_WIDTH 72
#define URLBAR_HEIGHT 24
// Global Variables:
HINSTANCE hInst; // current instance
char szWorkingDir[MAX_PATH]; // The current working directory
UINT uFindMsg; // Message identifier for find events.
HWND hFindDlg = NULL; // Handle for the find dialog.
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
// The global ClientHandler reference.
extern CefRefPtr<ClientHandler> g_handler;
extern CefRefPtr<CefCommandLine> g_command_line;
#if defined(OS_WIN)
// Add Common Controls to the application manifest because it's required to
// support the default tooltip implementation.
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
// Program entry point function.
int APIENTRY wWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Retrieve the current working directory.
if(_getcwd(szWorkingDir, MAX_PATH) == NULL)
szWorkingDir[0] = 0;
// Parse command line arguments. The passed in values are ignored on Windows.
AppInitCommandLine(0, NULL);
CefSettings settings;
CefRefPtr<CefApp> app;
// Populate the settings based on command line arguments.
AppGetSettings(settings, app);
// Initialize CEF.
CefInitialize(settings, app);
HACCEL hAccelTable;
LPCWSTR optName = L"CefClient";
int optWidth = 800;
int optHeight = 600;
if (g_command_line->HasSwitch("name"))
optName = LPCWSTR(g_command_line->GetSwitchValue("name").c_str());
// @TODO figure out why these lead to garbled optName
// if (g_command_line->HasSwitch("width"))
// optWidth = _wtoi(g_command_line->GetSwitchValue("width").c_str());
// if (g_command_line->HasSwitch("height"))
// optHeight = _wtoi(g_command_line->GetSwitchValue("height").c_str());
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CEFCLIENT));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_CEFCLIENT);
wcex.lpszClassName = optName;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
if (!RegisterClassEx(&wcex)) return FALSE;
// Perform window initialization
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(
optName,
optName,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
CW_USEDEFAULT, 0,
optWidth,
optHeight,
NULL, NULL, hInstance, NULL);
if (!hWnd) return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CEFCLIENT));
// Register the find event message.
uFindMsg = RegisterWindowMessage(FINDMSGSTRING);
int result = 0;
if (!settings.multi_threaded_message_loop) {
// Run the CEF message loop. This function will block until the application
// recieves a WM_QUIT message.
CefRunMessageLoop();
} else {
MSG msg;
// Run the application message loop.
while (GetMessage(&msg, NULL, 0, 0)) {
// Allow processing of find dialog messages.
if (hFindDlg && IsDialogMessage(hFindDlg, &msg))
continue;
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
result = (int)msg.wParam;
}
// Shut down CEF.
CefShutdown();
return result;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HWND backWnd = NULL, forwardWnd = NULL, reloadWnd = NULL,
stopWnd = NULL, editWnd = NULL;
static WNDPROC editWndOldProc = NULL;
// Static members used for the find dialog.
static FINDREPLACE fr;
static WCHAR szFindWhat[80] = {0};
static WCHAR szLastFindWhat[80] = {0};
static bool findNext = false;
static bool lastMatchCase = false;
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
// Callback for the main window
switch (message)
{
case WM_CREATE:
{
// Create the single static handler class instance
g_handler = new ClientHandler();
g_handler->SetMainHwnd(hWnd);
// Create the child windows used for navigation
RECT rect;
int x = 0;
GetClientRect(hWnd, &rect);
CefWindowInfo info;
CefBrowserSettings settings;
// Populate the settings based on command line arguments.
AppGetBrowserSettings(settings);
// Initialize window info to the defaults for a child window
info.SetAsChild(hWnd, rect);
// Creat the new child browser window
CefString url = CefString("http://google.com");
if (g_command_line->HasSwitch("url"))
url = g_command_line->GetSwitchValue("url");
CefBrowser::CreateBrowser(info,
static_cast<CefRefPtr<CefClient> >(g_handler),
url, settings);
}
return 0;
case WM_COMMAND:
{
CefRefPtr<CefBrowser> browser;
if(g_handler.get())
browser = g_handler->GetBrowser();
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_EXIT:
DestroyWindow(hWnd);
return 0;
case ID_WARN_DOWNLOADCOMPLETE:
case ID_WARN_DOWNLOADERROR:
if(g_handler.get()) {
std::wstringstream ss;
ss << L"File \"" <<
std::wstring(CefString(g_handler->GetLastDownloadFile())) <<
L"\" ";
if(wmId == ID_WARN_DOWNLOADCOMPLETE)
ss << L"downloaded successfully.";
else
ss << L"failed to download.";
MessageBox(hWnd, ss.str().c_str(), L"File Download",
MB_OK | MB_ICONINFORMATION);
}
return 0;
}
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
case WM_SETFOCUS:
if(g_handler.get() && g_handler->GetBrowserHwnd())
{
// Pass focus to the browser window
PostMessage(g_handler->GetBrowserHwnd(), WM_SETFOCUS, wParam, NULL);
}
return 0;
case WM_SIZE:
if(g_handler.get() && g_handler->GetBrowserHwnd())
{
// Resize the browser window to match the new frame window size
RECT rect;
GetClientRect(hWnd, &rect);
HDWP hdwp = BeginDeferWindowPos(1);
hdwp = DeferWindowPos(hdwp, g_handler->GetBrowserHwnd(), NULL,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
SWP_NOZORDER);
EndDeferWindowPos(hdwp);
}
break;
case WM_ERASEBKGND:
if(g_handler.get() && g_handler->GetBrowserHwnd())
{
// Dont erase the background if the browser window has been loaded
// (this avoids flashing)
return 0;
}
break;
case WM_CLOSE:
if (g_handler.get()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
if (browser.get()) {
// Let the browser window know we are about to destroy it.
browser->ParentWindowWillClose();
}
}
break;
case WM_DESTROY:
// The frame window has exited
PostQuitMessage(0);
return 0;
// Restricts window resizing smaller than the values below.
case WM_GETMINMAXINFO:
int minwidth = 600;
int minheight = 400;
// @TODO find out why these lead to garbled optName.
// if (g_command_line->HasSwitch("minwidth"))
// minwidth = _wtoi(g_command_line->GetSwitchValue("minwidth").c_str());
// if (g_command_line->HasSwitch("minheight"))
// minheight = _wtoi(g_command_line->GetSwitchValue("minheight").c_str());
LPMINMAXINFO pMMI = (LPMINMAXINFO)lParam;
pMMI->ptMinTrackSize.x = minwidth;
pMMI->ptMinTrackSize.y = minheight;
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// Global functions
std::string AppGetWorkingDirectory()
{
return szWorkingDir;
}
<commit_msg>Add --ico=[file.ico] flag for setting a custom icon.<commit_after>// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "include/cef.h"
#include "include/cef_runnable.h"
#include "cefclient.h"
#include "client_handler.h"
#include "resource.h"
#include <commdlg.h>
#include <direct.h>
#include <sstream>
#include <shellapi.h>
#define MAX_LOADSTRING 100
#define MAX_URL_LENGTH 255
#define BUTTON_WIDTH 72
#define URLBAR_HEIGHT 24
// Global Variables:
HINSTANCE hInst; // current instance
char szWorkingDir[MAX_PATH]; // The current working directory
UINT uFindMsg; // Message identifier for find events.
HWND hFindDlg = NULL; // Handle for the find dialog.
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
// The global ClientHandler reference.
extern CefRefPtr<ClientHandler> g_handler;
extern CefRefPtr<CefCommandLine> g_command_line;
#if defined(OS_WIN)
// Add Common Controls to the application manifest because it's required to
// support the default tooltip implementation.
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
// Program entry point function.
int APIENTRY wWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Retrieve the current working directory.
if(_getcwd(szWorkingDir, MAX_PATH) == NULL)
szWorkingDir[0] = 0;
// Parse command line arguments. The passed in values are ignored on Windows.
AppInitCommandLine(0, NULL);
CefSettings settings;
CefRefPtr<CefApp> app;
// Populate the settings based on command line arguments.
AppGetSettings(settings, app);
// Initialize CEF.
CefInitialize(settings, app);
HACCEL hAccelTable;
LPCWSTR optName = L"CefClient";
int optWidth = 800;
int optHeight = 600;
if (g_command_line->HasSwitch("name"))
optName = LPCWSTR(g_command_line->GetSwitchValue("name").c_str());
// @TODO figure out why these lead to garbled optName
// if (g_command_line->HasSwitch("width"))
// optWidth = _wtoi(g_command_line->GetSwitchValue("width").c_str());
// if (g_command_line->HasSwitch("height"))
// optHeight = _wtoi(g_command_line->GetSwitchValue("height").c_str());
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CEFCLIENT));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_CEFCLIENT);
wcex.lpszClassName = optName;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
if (!RegisterClassEx(&wcex)) return FALSE;
// Perform window initialization
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(
optName,
optName,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
CW_USEDEFAULT, 0,
optWidth,
optHeight,
NULL, NULL, hInstance, NULL);
if (!hWnd) return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CEFCLIENT));
// Register the find event message.
uFindMsg = RegisterWindowMessage(FINDMSGSTRING);
int result = 0;
if (!settings.multi_threaded_message_loop) {
// Run the CEF message loop. This function will block until the application
// recieves a WM_QUIT message.
CefRunMessageLoop();
} else {
MSG msg;
// Run the application message loop.
while (GetMessage(&msg, NULL, 0, 0)) {
// Allow processing of find dialog messages.
if (hFindDlg && IsDialogMessage(hFindDlg, &msg))
continue;
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
result = (int)msg.wParam;
}
// Shut down CEF.
CefShutdown();
return result;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HWND backWnd = NULL, forwardWnd = NULL, reloadWnd = NULL,
stopWnd = NULL, editWnd = NULL;
static WNDPROC editWndOldProc = NULL;
// Static members used for the find dialog.
static FINDREPLACE fr;
static WCHAR szFindWhat[80] = {0};
static WCHAR szLastFindWhat[80] = {0};
static bool findNext = false;
static bool lastMatchCase = false;
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
// Callback for the main window
switch (message)
{
case WM_CREATE:
{
// Create the single static handler class instance
g_handler = new ClientHandler();
g_handler->SetMainHwnd(hWnd);
// Create the child windows used for navigation
RECT rect;
int x = 0;
GetClientRect(hWnd, &rect);
CefWindowInfo info;
CefBrowserSettings settings;
// Populate the settings based on command line arguments.
AppGetBrowserSettings(settings);
// Initialize window info to the defaults for a child window
info.SetAsChild(hWnd, rect);
// Creat the new child browser window
CefString url = CefString("http://google.com");
if (g_command_line->HasSwitch("url"))
url = g_command_line->GetSwitchValue("url");
CefBrowser::CreateBrowser(info,
static_cast<CefRefPtr<CefClient> >(g_handler),
url, settings);
// Set window icon if --ico flag is set.
if (g_command_line->HasSwitch("ico")) {
LPCWSTR ico = L"";
ico = LPCWSTR(g_command_line->GetSwitchValue("ico").c_str());
HANDLE hIconBig = LoadImage(NULL, ico, IMAGE_ICON, 32, 32, LR_LOADFROMFILE);
HANDLE hIconSmall = LoadImage(NULL, ico, IMAGE_ICON, 16, 16, LR_LOADFROMFILE);
SendMessage(hWnd, WM_SETICON, ICON_BIG, LPARAM(hIconBig));
SendMessage(hWnd, WM_SETICON, ICON_SMALL, LPARAM(hIconSmall));
}
}
return 0;
case WM_COMMAND:
{
CefRefPtr<CefBrowser> browser;
if(g_handler.get())
browser = g_handler->GetBrowser();
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_EXIT:
DestroyWindow(hWnd);
return 0;
case ID_WARN_DOWNLOADCOMPLETE:
case ID_WARN_DOWNLOADERROR:
if(g_handler.get()) {
std::wstringstream ss;
ss << L"File \"" <<
std::wstring(CefString(g_handler->GetLastDownloadFile())) <<
L"\" ";
if(wmId == ID_WARN_DOWNLOADCOMPLETE)
ss << L"downloaded successfully.";
else
ss << L"failed to download.";
MessageBox(hWnd, ss.str().c_str(), L"File Download",
MB_OK | MB_ICONINFORMATION);
}
return 0;
}
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
case WM_SETFOCUS:
if(g_handler.get() && g_handler->GetBrowserHwnd())
{
// Pass focus to the browser window
PostMessage(g_handler->GetBrowserHwnd(), WM_SETFOCUS, wParam, NULL);
}
return 0;
case WM_SIZE:
if(g_handler.get() && g_handler->GetBrowserHwnd())
{
// Resize the browser window to match the new frame window size
RECT rect;
GetClientRect(hWnd, &rect);
HDWP hdwp = BeginDeferWindowPos(1);
hdwp = DeferWindowPos(hdwp, g_handler->GetBrowserHwnd(), NULL,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
SWP_NOZORDER);
EndDeferWindowPos(hdwp);
}
break;
case WM_ERASEBKGND:
if(g_handler.get() && g_handler->GetBrowserHwnd())
{
// Dont erase the background if the browser window has been loaded
// (this avoids flashing)
return 0;
}
break;
case WM_CLOSE:
if (g_handler.get()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
if (browser.get()) {
// Let the browser window know we are about to destroy it.
browser->ParentWindowWillClose();
}
}
break;
case WM_DESTROY:
// The frame window has exited
PostQuitMessage(0);
return 0;
// Restricts window resizing smaller than the values below.
case WM_GETMINMAXINFO:
int minwidth = 600;
int minheight = 400;
// @TODO find out why these lead to garbled optName.
// if (g_command_line->HasSwitch("minwidth"))
// minwidth = _wtoi(g_command_line->GetSwitchValue("minwidth").c_str());
// if (g_command_line->HasSwitch("minheight"))
// minheight = _wtoi(g_command_line->GetSwitchValue("minheight").c_str());
LPMINMAXINFO pMMI = (LPMINMAXINFO)lParam;
pMMI->ptMinTrackSize.x = minwidth;
pMMI->ptMinTrackSize.y = minheight;
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// Global functions
std::string AppGetWorkingDirectory()
{
return szWorkingDir;
}
<|endoftext|>
|
<commit_before>#include <string.h>
#include "glm/gtx/bit.hpp"
#include "stbimage/stb_image.h"
#include "pixelboost/file/fileSystem.h"
#include "pixelboost/graphics/device/texture.h"
using namespace pb;
Texture::Texture()
: _Data(0)
{
}
Texture::~Texture()
{
if (_Data)
delete[] _Data;
}
bool Texture::LoadFromBytes(const unsigned char* data, int width, int height, bool createMips, TextureFormat format, bool hasPremultipliedAlpha)
{
#ifdef PIXELBOOST_GRAPHICS_HANDLE_CONTEXT_LOST
if (_Data != 0 && _Data != data)
{
delete[] _Data;
_Data = 0;
}
_DataFormat = format;
_DataCreateMips = createMips;
_Size = glm::vec2(width, height);
if (_Data == 0)
{
switch (format)
{
case kTextureFormatRGB:
_Data = new unsigned char[width*height*3];
memcpy(_Data, data, width*height*3);
case kTextureFormatRGBA:
_Data = new unsigned char[width*height*4];
memcpy(_Data, data, width*height*4);
break;
}
}
#endif
_HasPremultipliedAlpha = hasPremultipliedAlpha;
return true;
}
bool Texture::LoadFromFile(pb::FileLocation location, const std::string& path, bool createMips, bool hasPremultipliedAlpha)
{
std::vector<unsigned char> data;
unsigned char* decoded;
pb::File* file = pb::FileSystem::Instance()->OpenFile(location, path);
if (!file)
return false;
file->ReadAll(data);
int width, height, components;
decoded = stbi_load_from_memory(&data[0], data.size(), &width, &height, &components, STBI_default);
if (!glm::isPowerOfTwo(width) || !glm::isPowerOfTwo(height))
createMips = false;
delete file;
bool status = LoadFromBytes(decoded, width, height, createMips, components == 3 ? kTextureFormatRGB : kTextureFormatRGBA, hasPremultipliedAlpha);
stbi_image_free(decoded);
return status;
}
const glm::vec2& Texture::GetSize() const
{
return _Size;
}
bool Texture::HasPremultipliedAlpha() const
{
return _HasPremultipliedAlpha;
}
void Texture::OnContextLost()
{
LoadFromBytes(_Data, _Size.x, _Size.y, _DataCreateMips, _DataFormat, _HasPremultipliedAlpha);
}
<commit_msg>Add support for reading jpeg+png alpha files<commit_after>#include <string.h>
#include "glm/gtx/bit.hpp"
#include "stbimage/stb_image.h"
#include "pixelboost/file/fileSystem.h"
#include "pixelboost/graphics/device/texture.h"
using namespace pb;
Texture::Texture()
: _Data(0)
{
}
Texture::~Texture()
{
if (_Data)
delete[] _Data;
}
bool Texture::LoadFromBytes(const unsigned char* data, int width, int height, bool createMips, TextureFormat format, bool hasPremultipliedAlpha)
{
#ifdef PIXELBOOST_GRAPHICS_HANDLE_CONTEXT_LOST
if (_Data != 0 && _Data != data)
{
delete[] _Data;
_Data = 0;
}
_DataFormat = format;
_DataCreateMips = createMips;
_Size = glm::vec2(width, height);
if (_Data == 0)
{
switch (format)
{
case kTextureFormatRGB:
_Data = new unsigned char[width*height*3];
memcpy(_Data, data, width*height*3);
case kTextureFormatRGBA:
_Data = new unsigned char[width*height*4];
memcpy(_Data, data, width*height*4);
break;
}
}
#endif
_HasPremultipliedAlpha = hasPremultipliedAlpha;
return true;
}
bool Texture::LoadFromFile(pb::FileLocation location, const std::string& path, bool createMips, bool hasPremultipliedAlpha)
{
bool status = true;
if (path.substr(path.length()-4) == ".jpa")
{
pb::File* file = pb::FileSystem::Instance()->OpenFile(location, path);
if (!file)
return false;
int rgbLength;
int alphaLength;
file->Read(rgbLength);
file->Read(alphaLength);
unsigned char* encodedRgbData = new unsigned char[rgbLength];
unsigned char* encodedAlphaData = new unsigned char[alphaLength];
file->Read(encodedRgbData, rgbLength);
file->Read(encodedAlphaData, alphaLength);
int width, height, components;
unsigned char* decodedRgb = stbi_load_from_memory(encodedRgbData, rgbLength, &width, &height, &components, STBI_default);
unsigned char* decodedAlpha = stbi_load_from_memory(encodedAlphaData, alphaLength, &width, &height, &components, STBI_default);
unsigned char* decoded = new unsigned char[width*height*4];
unsigned char* decodedTemp = decoded;
unsigned char* rgbTemp = decodedRgb;
unsigned char* alphaTemp = decodedAlpha;
for (int y=0; y<height; y++)
{
for (int x=0; x<width; x++)
{
decodedTemp[0] = rgbTemp[0];
decodedTemp[1] = rgbTemp[1];
decodedTemp[2] = rgbTemp[2];
decodedTemp[3] = *alphaTemp;
decodedTemp += 4;
rgbTemp += 3;
alphaTemp++;
}
}
stbi_image_free(decodedRgb);
stbi_image_free(decodedAlpha);
status = LoadFromBytes(decoded, width, height, createMips, kTextureFormatRGBA, hasPremultipliedAlpha);
delete[] decoded;
} else {
std::vector<unsigned char> data;
unsigned char* decoded;
pb::File* file = pb::FileSystem::Instance()->OpenFile(location, path);
if (!file)
return false;
file->ReadAll(data);
int width, height, components;
decoded = stbi_load_from_memory(&data[0], data.size(), &width, &height, &components, STBI_default);
if (!glm::isPowerOfTwo(width) || !glm::isPowerOfTwo(height))
createMips = false;
delete file;
status = LoadFromBytes(decoded, width, height, createMips, components == 3 ? kTextureFormatRGB : kTextureFormatRGBA, hasPremultipliedAlpha);
stbi_image_free(decoded);
}
return status;
}
const glm::vec2& Texture::GetSize() const
{
return _Size;
}
bool Texture::HasPremultipliedAlpha() const
{
return _HasPremultipliedAlpha;
}
void Texture::OnContextLost()
{
LoadFromBytes(_Data, _Size.x, _Size.y, _DataCreateMips, _DataFormat, _HasPremultipliedAlpha);
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#define __STDC_FORMAT_MACROS
#include "authz_session.h"
#include <errno.h>
#include <inttypes.h>
#ifdef __APPLE__
#include <sys/sysctl.h>
#endif
#include <cassert>
#include <cstdio>
#include <vector>
#include "authz/authz_fetch.h"
#include "logging.h"
#include "platform.h"
#include "statistics.h"
#include "util/posix.h"
using namespace std; // NOLINT
AuthzSessionManager::AuthzSessionManager()
: deadline_sweep_pids_(0)
, deadline_sweep_creds_(0)
, authz_fetcher_(NULL)
, no_pid_(NULL)
, no_session_(NULL)
, n_fetch_(NULL)
, n_grant_(NULL)
, n_deny_(NULL)
{
int retval = pthread_mutex_init(&lock_pid2session_, NULL);
assert(retval == 0);
retval = pthread_mutex_init(&lock_session2cred_, NULL);
assert(retval == 0);
session2cred_.Init(16, SessionKey(), HashSessionKey);
pid2session_.Init(16, PidKey(), HashPidKey);
}
AuthzSessionManager::~AuthzSessionManager() {
int retval = pthread_mutex_destroy(&lock_pid2session_);
assert(retval == 0);
retval = pthread_mutex_destroy(&lock_session2cred_);
assert(retval == 0);
SessionKey empty_key;
for (unsigned i = 0; i < session2cred_.capacity(); ++i) {
if (session2cred_.keys()[i] != empty_key) {
if ((session2cred_.values() + i)->token.data != NULL)
free((session2cred_.values() + i)->token.data);
}
}
}
AuthzSessionManager *AuthzSessionManager::Create(
AuthzFetcher *authz_fetcher,
perf::Statistics *statistics)
{
AuthzSessionManager *authz_mgr = new AuthzSessionManager();
authz_mgr->authz_fetcher_ = authz_fetcher;
authz_mgr->no_pid_ = statistics->Register("authz.no_pid", "cached pids");
authz_mgr->no_session_ = statistics->Register(
"authz.no_session", "cached sessions");
authz_mgr->n_fetch_ = statistics->Register(
"authz.n_fetch", "overall number of authz helper invocations");
authz_mgr->n_grant_ = statistics->Register(
"authz.n_grant", "overall number of granted membership queries");
authz_mgr->n_deny_ = statistics->Register(
"authz.n_deny", "overall number of denied membership queries");
return authz_mgr;
}
/**
* Gathers SID, birthday, uid, and gid from given PID.
*/
bool AuthzSessionManager::GetPidInfo(pid_t pid, PidKey *pid_key) {
int retval;
// TODO(jblomer): better in platform.h? Maybe a bit too bulky for that?
#ifdef __APPLE__
pid_key->sid = getsid(pid);
if (pid_key->sid == static_cast<pid_t>(-1)) {
LogCvmfs(kLogAuthz, kLogDebug, "failed to get sid (%s)", strerror(errno));
return false;
}
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
struct kinfo_proc kp;
size_t len = sizeof(kp);
retval = sysctl(mib, 4, &kp, &len, NULL, 0);
if (retval == -1) {
LogCvmfs(kLogAuthz, kLogDebug, "failed to get pid info (%s)",
strerror(errno));
return false;
}
pid_key->uid = kp.kp_eproc.e_pcred.p_ruid;
pid_key->gid = kp.kp_eproc.e_pcred.p_rgid;
int64_t usec =
static_cast<int64_t>(kp.kp_proc.p_un.__p_starttime.tv_sec) * 1000000;
usec += static_cast<int64_t>(kp.kp_proc.p_un.__p_starttime.tv_usec);
pid_key->pid_bday = usec;
pid_key->pid = pid;
return true;
#endif
const int kMaxProcPath = 64; // Enough to store /proc/PID/stat
char pid_path[kMaxProcPath];
if (snprintf(pid_path, kMaxProcPath, "/proc/%d/stat", pid) >= kMaxProcPath) {
return false;
}
FILE *fp_stat = fopen(pid_path, "r");
if (fp_stat == NULL) {
LogCvmfs(kLogAuthz, kLogDebug, "Failed to open status file /proc/%d/stat: (errno=%d) %s", pid, errno, strerror(errno));
LogCvmfs(kLogAuthz, kLogSyslogWarn | kLogDebug, "Authorization for session %d disappeared", pid);
return false;
}
// The uid and gid can be gathered from /proc/$PID/stat file ownership
int fd_stat = fileno(fp_stat);
platform_stat64 info;
retval = platform_fstat(fd_stat, &info);
if (retval != 0) {
fclose(fp_stat);
LogCvmfs(kLogAuthz, kLogDebug,
"Failed to get stat information of running process.");
return false;
}
pid_key->uid = info.st_uid;
pid_key->gid = info.st_gid;
// TODO(bbockelm): EINTR handling
retval = fscanf(fp_stat, "%*d %*s %*c %*d %*d %d %*d %*d %*u %*u %*u %*u "
"%*u %*u %*u %*d %*d %*d %*d %*d %*d %" SCNu64,
&(pid_key->sid), &(pid_key->pid_bday));
fclose(fp_stat);
if (retval != 2) {
if (errno == 0) {
errno = EINVAL;
}
LogCvmfs(kLogAuthz, kLogDebug, "Failed to parse status file for "
"pid %d: (errno=%d) %s, fscanf result %d", pid, errno,
strerror(errno), retval);
return false;
}
pid_key->pid = pid;
return true;
}
/**
* Caller is responsible for freeing the returned token.
*/
AuthzToken *AuthzSessionManager::GetTokenCopy(
const pid_t pid,
const std::string &membership)
{
SessionKey session_key;
PidKey pid_key;
bool retval = LookupSessionKey(pid, &pid_key, &session_key);
if (!retval)
return NULL;
AuthzData authz_data;
const bool granted =
LookupAuthzData(pid_key, session_key, membership, &authz_data);
if (!granted)
return NULL;
return authz_data.token.DeepCopy();
}
bool AuthzSessionManager::IsMemberOf(
const pid_t pid,
const std::string &membership)
{
SessionKey session_key;
PidKey pid_key;
bool retval = LookupSessionKey(pid, &pid_key, &session_key);
if (!retval)
return false;
AuthzData authz_data;
return LookupAuthzData(pid_key, session_key, membership, &authz_data);
}
/**
* Calls out to the AuthzFetcher if the data is not cached. Verifies the
* membership.
*/
bool AuthzSessionManager::LookupAuthzData(
const PidKey &pid_key,
const SessionKey &session_key,
const std::string &membership,
AuthzData *authz_data)
{
assert(authz_data != NULL);
LockMutex(&lock_session2cred_);
MaySweepCreds();
bool found = session2cred_.Lookup(session_key, authz_data);
UnlockMutex(&lock_session2cred_);
if (found) {
LogCvmfs(kLogAuthz, kLogDebug,
"cached authz data for sid %d, membership %s, status %d",
session_key.sid, authz_data->membership.c_str(),
authz_data->status);
const bool granted = authz_data->IsGranted(membership);
if (granted)
perf::Inc(n_grant_);
else
perf::Inc(n_deny_);
return granted;
}
// Not found in cache, ask for help
perf::Inc(n_fetch_);
unsigned ttl;
authz_data->status = authz_fetcher_->Fetch(
AuthzFetcher::QueryInfo(pid_key.pid, pid_key.uid, pid_key.gid, membership),
&(authz_data->token), &ttl);
authz_data->deadline = platform_monotonic_time() + ttl;
if (authz_data->status == kAuthzOk)
authz_data->membership = membership;
LogCvmfs(kLogAuthz, kLogDebug,
"fetched authz data for sid %d (pid %d), membership %s, status %d, "
"ttl %u", session_key.sid, pid_key.pid,
authz_data->membership.c_str(), authz_data->status, ttl);
LockMutex(&lock_session2cred_);
if (!session2cred_.Contains(session_key))
perf::Inc(no_session_);
session2cred_.Insert(session_key, *authz_data);
UnlockMutex(&lock_session2cred_);
const bool granted = authz_data->status == kAuthzOk;
if (granted)
perf::Inc(n_grant_);
else
perf::Inc(n_deny_);
return granted;
}
/**
* Translate a PID and its birthday into an SID and its birthday. The Session
* ID and its birthday together with UID and GID make the Session Key. The
* translation result is cached in pid2session_.
*/
bool AuthzSessionManager::LookupSessionKey(
pid_t pid,
PidKey *pid_key,
SessionKey *session_key)
{
assert(pid_key != NULL);
assert(session_key != NULL);
if (!GetPidInfo(pid, pid_key))
return false;
LockMutex(&lock_pid2session_);
bool found = pid2session_.Lookup(*pid_key, session_key);
MaySweepPids();
UnlockMutex(&lock_pid2session_);
if (found) {
LogCvmfs(kLogAuthz, kLogDebug,
"Session key %d/%" PRIu64 " in cache; sid=%d, bday=%" PRIu64,
pid_key->pid, pid_key->pid_bday,
session_key->sid, session_key->sid_bday);
return true;
}
LogCvmfs(kLogAuthz, kLogDebug, "Session key not found in cache, getting information from OS");
PidKey sid_key;
if (!GetPidInfo(pid_key->sid, &sid_key))
return false;
session_key->sid = sid_key.pid;
session_key->sid_bday = sid_key.pid_bday;
LockMutex(&lock_pid2session_);
pid_key->deadline = platform_monotonic_time() + kPidLifetime;
if (!pid2session_.Contains(*pid_key))
perf::Inc(no_pid_);
pid2session_.Insert(*pid_key, *session_key);
UnlockMutex(&lock_pid2session_);
LogCvmfs(kLogAuthz, kLogDebug, "Lookup key %d/%" PRIu64 "; sid=%d, bday=%llu",
pid_key->pid, pid_key->pid_bday,
session_key->sid, session_key->sid_bday);
return true;
}
/**
* Scan through old sessions only every so often.
*/
void AuthzSessionManager::MaySweepCreds() {
uint64_t now = platform_monotonic_time();
if (now >= deadline_sweep_creds_) {
SweepCreds(now);
deadline_sweep_creds_ = now + kSweepInterval;
}
}
/**
* Scan through old PIDs only every so often.
*/
void AuthzSessionManager::MaySweepPids() {
uint64_t now = platform_monotonic_time();
if (now >= deadline_sweep_pids_) {
SweepPids(now);
deadline_sweep_pids_ = now + kSweepInterval;
}
}
/**
* Remove cache PIDs with expired cache life time.
* TODO(jblomer): a generalized sweeping can become part of smallhash
*/
void AuthzSessionManager::SweepCreds(uint64_t now) {
SessionKey empty_key;
vector<SessionKey> trash_bin;
for (unsigned i = 0; i < session2cred_.capacity(); ++i) {
SessionKey this_key = session2cred_.keys()[i];
if (this_key != empty_key) {
if (now >= (session2cred_.values() + i)->deadline)
trash_bin.push_back(this_key);
}
}
for (unsigned i = 0; i < trash_bin.size(); ++i) {
session2cred_.Erase(trash_bin[i]);
perf::Dec(no_session_);
}
}
/**
* Remove cache PIDs with expired cache life time.
* TODO(jblomer): a generalized sweeping can become part of smallhash
*/
void AuthzSessionManager::SweepPids(uint64_t now) {
PidKey empty_key;
vector<PidKey> trash_bin;
for (unsigned i = 0; i < pid2session_.capacity(); ++i) {
PidKey this_key = pid2session_.keys()[i];
if (this_key != empty_key) {
if (now >= this_key.deadline)
trash_bin.push_back(this_key);
}
}
for (unsigned i = 0; i < trash_bin.size(); ++i) {
pid2session_.Erase(trash_bin[i]);
perf::Dec(no_pid_);
}
}
<commit_msg>Fix linter errors<commit_after>/**
* This file is part of the CernVM File System.
*/
#define __STDC_FORMAT_MACROS
#include "authz_session.h"
#include <errno.h>
#include <inttypes.h>
#ifdef __APPLE__
#include <sys/sysctl.h>
#endif
#include <cassert>
#include <cstdio>
#include <cstring>
#include <vector>
#include "authz/authz_fetch.h"
#include "logging.h"
#include "platform.h"
#include "statistics.h"
#include "util/posix.h"
using namespace std; // NOLINT
AuthzSessionManager::AuthzSessionManager()
: deadline_sweep_pids_(0)
, deadline_sweep_creds_(0)
, authz_fetcher_(NULL)
, no_pid_(NULL)
, no_session_(NULL)
, n_fetch_(NULL)
, n_grant_(NULL)
, n_deny_(NULL)
{
int retval = pthread_mutex_init(&lock_pid2session_, NULL);
assert(retval == 0);
retval = pthread_mutex_init(&lock_session2cred_, NULL);
assert(retval == 0);
session2cred_.Init(16, SessionKey(), HashSessionKey);
pid2session_.Init(16, PidKey(), HashPidKey);
}
AuthzSessionManager::~AuthzSessionManager() {
int retval = pthread_mutex_destroy(&lock_pid2session_);
assert(retval == 0);
retval = pthread_mutex_destroy(&lock_session2cred_);
assert(retval == 0);
SessionKey empty_key;
for (unsigned i = 0; i < session2cred_.capacity(); ++i) {
if (session2cred_.keys()[i] != empty_key) {
if ((session2cred_.values() + i)->token.data != NULL)
free((session2cred_.values() + i)->token.data);
}
}
}
AuthzSessionManager *AuthzSessionManager::Create(
AuthzFetcher *authz_fetcher,
perf::Statistics *statistics)
{
AuthzSessionManager *authz_mgr = new AuthzSessionManager();
authz_mgr->authz_fetcher_ = authz_fetcher;
authz_mgr->no_pid_ = statistics->Register("authz.no_pid", "cached pids");
authz_mgr->no_session_ = statistics->Register(
"authz.no_session", "cached sessions");
authz_mgr->n_fetch_ = statistics->Register(
"authz.n_fetch", "overall number of authz helper invocations");
authz_mgr->n_grant_ = statistics->Register(
"authz.n_grant", "overall number of granted membership queries");
authz_mgr->n_deny_ = statistics->Register(
"authz.n_deny", "overall number of denied membership queries");
return authz_mgr;
}
/**
* Gathers SID, birthday, uid, and gid from given PID.
*/
bool AuthzSessionManager::GetPidInfo(pid_t pid, PidKey *pid_key) {
int retval;
// TODO(jblomer): better in platform.h? Maybe a bit too bulky for that?
#ifdef __APPLE__
pid_key->sid = getsid(pid);
if (pid_key->sid == static_cast<pid_t>(-1)) {
LogCvmfs(kLogAuthz, kLogDebug, "failed to get sid (%s)", strerror(errno));
return false;
}
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
struct kinfo_proc kp;
size_t len = sizeof(kp);
retval = sysctl(mib, 4, &kp, &len, NULL, 0);
if (retval == -1) {
LogCvmfs(kLogAuthz, kLogDebug, "failed to get pid info (%s)",
strerror(errno));
return false;
}
pid_key->uid = kp.kp_eproc.e_pcred.p_ruid;
pid_key->gid = kp.kp_eproc.e_pcred.p_rgid;
int64_t usec =
static_cast<int64_t>(kp.kp_proc.p_un.__p_starttime.tv_sec) * 1000000;
usec += static_cast<int64_t>(kp.kp_proc.p_un.__p_starttime.tv_usec);
pid_key->pid_bday = usec;
pid_key->pid = pid;
return true;
#endif
const int kMaxProcPath = 64; // Enough to store /proc/PID/stat
char pid_path[kMaxProcPath];
if (snprintf(pid_path, kMaxProcPath, "/proc/%d/stat", pid) >= kMaxProcPath) {
return false;
}
FILE *fp_stat = fopen(pid_path, "r");
if (fp_stat == NULL) {
LogCvmfs(kLogAuthz, kLogDebug, "Failed to open status file /proc/%d/stat: (errno=%d) %s",
pid, errno, strerror(errno));
LogCvmfs(kLogAuthz, kLogSyslogWarn | kLogDebug, "Authorization for session %d disappeared", pid);
return false;
}
// The uid and gid can be gathered from /proc/$PID/stat file ownership
int fd_stat = fileno(fp_stat);
platform_stat64 info;
retval = platform_fstat(fd_stat, &info);
if (retval != 0) {
fclose(fp_stat);
LogCvmfs(kLogAuthz, kLogDebug,
"Failed to get stat information of running process.");
return false;
}
pid_key->uid = info.st_uid;
pid_key->gid = info.st_gid;
// TODO(bbockelm): EINTR handling
retval = fscanf(fp_stat, "%*d %*s %*c %*d %*d %d %*d %*d %*u %*u %*u %*u "
"%*u %*u %*u %*d %*d %*d %*d %*d %*d %" SCNu64,
&(pid_key->sid), &(pid_key->pid_bday));
fclose(fp_stat);
if (retval != 2) {
if (errno == 0) {
errno = EINVAL;
}
LogCvmfs(kLogAuthz, kLogDebug, "Failed to parse status file for "
"pid %d: (errno=%d) %s, fscanf result %d", pid, errno,
strerror(errno), retval);
return false;
}
pid_key->pid = pid;
return true;
}
/**
* Caller is responsible for freeing the returned token.
*/
AuthzToken *AuthzSessionManager::GetTokenCopy(
const pid_t pid,
const std::string &membership)
{
SessionKey session_key;
PidKey pid_key;
bool retval = LookupSessionKey(pid, &pid_key, &session_key);
if (!retval)
return NULL;
AuthzData authz_data;
const bool granted =
LookupAuthzData(pid_key, session_key, membership, &authz_data);
if (!granted)
return NULL;
return authz_data.token.DeepCopy();
}
bool AuthzSessionManager::IsMemberOf(
const pid_t pid,
const std::string &membership)
{
SessionKey session_key;
PidKey pid_key;
bool retval = LookupSessionKey(pid, &pid_key, &session_key);
if (!retval)
return false;
AuthzData authz_data;
return LookupAuthzData(pid_key, session_key, membership, &authz_data);
}
/**
* Calls out to the AuthzFetcher if the data is not cached. Verifies the
* membership.
*/
bool AuthzSessionManager::LookupAuthzData(
const PidKey &pid_key,
const SessionKey &session_key,
const std::string &membership,
AuthzData *authz_data)
{
assert(authz_data != NULL);
LockMutex(&lock_session2cred_);
MaySweepCreds();
bool found = session2cred_.Lookup(session_key, authz_data);
UnlockMutex(&lock_session2cred_);
if (found) {
LogCvmfs(kLogAuthz, kLogDebug,
"cached authz data for sid %d, membership %s, status %d",
session_key.sid, authz_data->membership.c_str(),
authz_data->status);
const bool granted = authz_data->IsGranted(membership);
if (granted)
perf::Inc(n_grant_);
else
perf::Inc(n_deny_);
return granted;
}
// Not found in cache, ask for help
perf::Inc(n_fetch_);
unsigned ttl;
authz_data->status = authz_fetcher_->Fetch(
AuthzFetcher::QueryInfo(pid_key.pid, pid_key.uid, pid_key.gid, membership),
&(authz_data->token), &ttl);
authz_data->deadline = platform_monotonic_time() + ttl;
if (authz_data->status == kAuthzOk)
authz_data->membership = membership;
LogCvmfs(kLogAuthz, kLogDebug,
"fetched authz data for sid %d (pid %d), membership %s, status %d, "
"ttl %u", session_key.sid, pid_key.pid,
authz_data->membership.c_str(), authz_data->status, ttl);
LockMutex(&lock_session2cred_);
if (!session2cred_.Contains(session_key))
perf::Inc(no_session_);
session2cred_.Insert(session_key, *authz_data);
UnlockMutex(&lock_session2cred_);
const bool granted = authz_data->status == kAuthzOk;
if (granted)
perf::Inc(n_grant_);
else
perf::Inc(n_deny_);
return granted;
}
/**
* Translate a PID and its birthday into an SID and its birthday. The Session
* ID and its birthday together with UID and GID make the Session Key. The
* translation result is cached in pid2session_.
*/
bool AuthzSessionManager::LookupSessionKey(
pid_t pid,
PidKey *pid_key,
SessionKey *session_key)
{
assert(pid_key != NULL);
assert(session_key != NULL);
if (!GetPidInfo(pid, pid_key))
return false;
LockMutex(&lock_pid2session_);
bool found = pid2session_.Lookup(*pid_key, session_key);
MaySweepPids();
UnlockMutex(&lock_pid2session_);
if (found) {
LogCvmfs(kLogAuthz, kLogDebug,
"Session key %d/%" PRIu64 " in cache; sid=%d, bday=%" PRIu64,
pid_key->pid, pid_key->pid_bday,
session_key->sid, session_key->sid_bday);
return true;
}
LogCvmfs(kLogAuthz, kLogDebug, "Session key not found in cache, getting information from OS");
PidKey sid_key;
if (!GetPidInfo(pid_key->sid, &sid_key))
return false;
session_key->sid = sid_key.pid;
session_key->sid_bday = sid_key.pid_bday;
LockMutex(&lock_pid2session_);
pid_key->deadline = platform_monotonic_time() + kPidLifetime;
if (!pid2session_.Contains(*pid_key))
perf::Inc(no_pid_);
pid2session_.Insert(*pid_key, *session_key);
UnlockMutex(&lock_pid2session_);
LogCvmfs(kLogAuthz, kLogDebug, "Lookup key %d/%" PRIu64 "; sid=%d, bday=%llu",
pid_key->pid, pid_key->pid_bday,
session_key->sid, session_key->sid_bday);
return true;
}
/**
* Scan through old sessions only every so often.
*/
void AuthzSessionManager::MaySweepCreds() {
uint64_t now = platform_monotonic_time();
if (now >= deadline_sweep_creds_) {
SweepCreds(now);
deadline_sweep_creds_ = now + kSweepInterval;
}
}
/**
* Scan through old PIDs only every so often.
*/
void AuthzSessionManager::MaySweepPids() {
uint64_t now = platform_monotonic_time();
if (now >= deadline_sweep_pids_) {
SweepPids(now);
deadline_sweep_pids_ = now + kSweepInterval;
}
}
/**
* Remove cache PIDs with expired cache life time.
* TODO(jblomer): a generalized sweeping can become part of smallhash
*/
void AuthzSessionManager::SweepCreds(uint64_t now) {
SessionKey empty_key;
vector<SessionKey> trash_bin;
for (unsigned i = 0; i < session2cred_.capacity(); ++i) {
SessionKey this_key = session2cred_.keys()[i];
if (this_key != empty_key) {
if (now >= (session2cred_.values() + i)->deadline)
trash_bin.push_back(this_key);
}
}
for (unsigned i = 0; i < trash_bin.size(); ++i) {
session2cred_.Erase(trash_bin[i]);
perf::Dec(no_session_);
}
}
/**
* Remove cache PIDs with expired cache life time.
* TODO(jblomer): a generalized sweeping can become part of smallhash
*/
void AuthzSessionManager::SweepPids(uint64_t now) {
PidKey empty_key;
vector<PidKey> trash_bin;
for (unsigned i = 0; i < pid2session_.capacity(); ++i) {
PidKey this_key = pid2session_.keys()[i];
if (this_key != empty_key) {
if (now >= this_key.deadline)
trash_bin.push_back(this_key);
}
}
for (unsigned i = 0; i < trash_bin.size(); ++i) {
pid2session_.Erase(trash_bin[i]);
perf::Dec(no_pid_);
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: VectorConfidenceConnected.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates the use of the Confidence connected concept
// applied to images with vector pixel types. The Confidence connected
// algorithm is implemented for vector images in the class
// \doxygen{VectorConfidenceConnected}. The basic difference between the
// scalar and vector version is that the vector version uses the covariance
// matrix instead of a variance, and a vector mean instead of a scalar mean.
// The membership of a vector pixel value to the region is measured using the
// Mahalanobis distance as implemented in the class
// \subdoxygen{Statistics}{MahalanobisDistanceImageFunction}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkVectorConfidenceConnectedImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRGBPixel.h"
int main( int argc, char *argv[] )
{
if( argc < 7 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImage outputImage seedX seedY multiplier iterations" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// We now declare the image type using a pixel type and a particular
// dimension. In this case the \code{float} type is used for the pixels due
// to the requirements of the smoothing filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char PixelComponentType;
typedef itk::RGBPixel< PixelComponentType > InputPixelType;
const unsigned int Dimension = 2;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
// Software Guide : EndCodeSnippet
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
//
// We instantiate reader and writer types
//
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// We now declare the type of the region growing filter. In this case it is
// the \doxygen{VectorConfidenceConnectedImageFilter}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::VectorConfidenceConnectedImageFilter<
InputImageType,
OutputImageType > ConnectedFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then, we construct one filter of this class using the \code{New()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ConnectedFilterType::Pointer confidenceConnected = ConnectedFilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now it is time to connect the pipeline. This is pretty linear in our
// example.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
confidenceConnected->SetInput( reader->GetOutput() );
writer->SetInput( confidenceConnected->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \doxygen{VectorConfidenceConnectedImageFilter} has two parameters
// to be defined. First, the factor $f$ that the defines how large
// the range of intensities will be. Small values of the multiplier
// will restrict the inclusion of pixels to those having very
// similar intensities to those in the current region. Larger
// values of the multiplier will relax the accepting condition and
// will result in more generous growth of the region. Values that
// are too large will make the region ingest neighbor regions in
// the image that may actually belong to separate anatomical
// structures.
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetMultiplier()}
//
// Software Guide : EndLatex
const double multiplier = atof( argv[5] );
// Software Guide : BeginCodeSnippet
confidenceConnected->SetMultiplier( multiplier );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The number of iterations may be decided based on the homogeneity of the
// intensities of the anatomical structure to be segmented. Highly homogeneous
// regions may only require a couple of iterations. Regions with ramp
// effects, like MRI images with inhomogenous fields, may require
// more iterations. In practice, it seems to be more relevant to carefully
// select the multiplier factor than the number of iterations.
// However, keep in mind that there is no reason to assume that this
// algorithm should converge to a stable region. It is possible that by
// letting the algorithm run for more iterations the region will end up
// engulfing the entire image.
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetNumberOfIterations()}
//
// Software Guide : EndLatex
const unsigned int iterations = atoi( argv[6] );
// Software Guide : BeginCodeSnippet
confidenceConnected->SetNumberOfIterations( iterations );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output of this filter is a binary image with zero-value pixels
// everywhere except on the extracted region. The intensity value to be put
// inside the region is selected with the method \code{SetReplaceValue()}
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetReplaceValue()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
confidenceConnected->SetReplaceValue( 255 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The initialization of the algorithm requires the user to provide a seed
// point. It is convenient to select this point to be placed in a
// \emph{typical} region of the anatomical structure to be segmented. A
// small neighborhood around the seed point will be used to compute the
// initial mean and standard deviation for the inclusion criterion. The seed
// is passed in the form of a \doxygen{Index} to the \code{SetSeed()} method.
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetSeed()}
// \index{itk::VectorConfidenceConnectedImageFilter!SetInitialNeighborhoodRadius()}
//
// Software Guide : EndLatex
InputImageType::IndexType index;
index[0] = atoi( argv[3] );
index[1] = atoi( argv[4] );
// Software Guide : BeginCodeSnippet
confidenceConnected->SetSeed( index );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
//
// The size of the initial neighborhood around the seed is defined with the
// method \code{SetInitialNeighborhoodRadius()}. The neighborhood will be
// defined as an $N$-Dimensional rectangular region with $2r+1$ pixels on
// the side, where $r$ is the value passed as initial neighborhood radius.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
confidenceConnected->SetInitialNeighborhoodRadius( 3 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The invocation of the \code{Update()} method on the writer triggers the
// execution of the pipeline. It is usually wise to put update calls in a
// \code{try/catch} block in case errors occur and exceptions are thrown.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
writer->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Let's now run this example using as input the image
// \code{VisibleWomanEyeSlice.png} provided in the directory
// \code{Insight/Examples/Data}. We can easily segment the major anatomical
// structures by providing seeds in the appropriate locations. For example,
//
// \begin{center}
// \begin{tabular}{|l|c|c|c|c|}
// \hline
// Structure & Seed Index & Multiplier & Iterations & Output Image \\ \hline \\ \hline
// Rectum & $(70,120)$ & 50 & 10 & Second from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline
// Rectum & $(23, 93)$ & 45 & 10 & Third from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline
// Vitreo & $(66, 66)$ & 15 & 20 & Fourth from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline
// \end{tabular}
// \end{center}
//
// \begin{figure} \center
// \includegraphics[width=0.24\textwidth]{VisibleWomanEyeSlice.eps}
// \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput1.eps}
// \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput2.eps}
// \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput3.eps}
// \itkcaption[VectorConfidenceConnected segmentation results]{Segmentation results of
// the VectorConfidenceConnected filter for various seed points.}
// \label{fig:VectorConfidenceConnectedOutput}
// \end{figure}
//
// The coloration of muscular tissue makes it easy to distinguish from the
// surrounding anatomical strucures. The optic nerf on the other hand has
// similar coloration to neighborhor structures.
//
// Software Guide : EndLatex
return 0;
}
<commit_msg>DOC: Parameters fixed for the ones used in the VisibleWoman eye.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: VectorConfidenceConnected.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates the use of the Confidence connected concept
// applied to images with vector pixel types. The Confidence connected
// algorithm is implemented for vector images in the class
// \doxygen{VectorConfidenceConnected}. The basic difference between the
// scalar and vector version is that the vector version uses the covariance
// matrix instead of a variance, and a vector mean instead of a scalar mean.
// The membership of a vector pixel value to the region is measured using the
// Mahalanobis distance as implemented in the class
// \subdoxygen{Statistics}{MahalanobisDistanceImageFunction}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkVectorConfidenceConnectedImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRGBPixel.h"
int main( int argc, char *argv[] )
{
if( argc < 7 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImage outputImage seedX seedY multiplier iterations" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// We now declare the image type using a pixel type and a particular
// dimension. In this case the \code{float} type is used for the pixels due
// to the requirements of the smoothing filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char PixelComponentType;
typedef itk::RGBPixel< PixelComponentType > InputPixelType;
const unsigned int Dimension = 2;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
// Software Guide : EndCodeSnippet
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
//
// We instantiate reader and writer types
//
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// We now declare the type of the region growing filter. In this case it is
// the \doxygen{VectorConfidenceConnectedImageFilter}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::VectorConfidenceConnectedImageFilter<
InputImageType,
OutputImageType > ConnectedFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then, we construct one filter of this class using the \code{New()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ConnectedFilterType::Pointer confidenceConnected = ConnectedFilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now it is time to connect the pipeline. This is pretty linear in our
// example.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
confidenceConnected->SetInput( reader->GetOutput() );
writer->SetInput( confidenceConnected->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \doxygen{VectorConfidenceConnectedImageFilter} has two parameters
// to be defined. First, the factor $f$ that the defines how large
// the range of intensities will be. Small values of the multiplier
// will restrict the inclusion of pixels to those having very
// similar intensities to those in the current region. Larger
// values of the multiplier will relax the accepting condition and
// will result in more generous growth of the region. Values that
// are too large will make the region ingest neighbor regions in
// the image that may actually belong to separate anatomical
// structures.
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetMultiplier()}
//
// Software Guide : EndLatex
const double multiplier = atof( argv[5] );
// Software Guide : BeginCodeSnippet
confidenceConnected->SetMultiplier( multiplier );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The number of iterations may be decided based on the homogeneity of the
// intensities of the anatomical structure to be segmented. Highly homogeneous
// regions may only require a couple of iterations. Regions with ramp
// effects, like MRI images with inhomogenous fields, may require
// more iterations. In practice, it seems to be more relevant to carefully
// select the multiplier factor than the number of iterations.
// However, keep in mind that there is no reason to assume that this
// algorithm should converge to a stable region. It is possible that by
// letting the algorithm run for more iterations the region will end up
// engulfing the entire image.
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetNumberOfIterations()}
//
// Software Guide : EndLatex
const unsigned int iterations = atoi( argv[6] );
// Software Guide : BeginCodeSnippet
confidenceConnected->SetNumberOfIterations( iterations );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output of this filter is a binary image with zero-value pixels
// everywhere except on the extracted region. The intensity value to be put
// inside the region is selected with the method \code{SetReplaceValue()}
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetReplaceValue()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
confidenceConnected->SetReplaceValue( 255 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The initialization of the algorithm requires the user to provide a seed
// point. It is convenient to select this point to be placed in a
// \emph{typical} region of the anatomical structure to be segmented. A
// small neighborhood around the seed point will be used to compute the
// initial mean and standard deviation for the inclusion criterion. The seed
// is passed in the form of a \doxygen{Index} to the \code{SetSeed()} method.
//
// \index{itk::VectorConfidenceConnectedImageFilter!SetSeed()}
// \index{itk::VectorConfidenceConnectedImageFilter!SetInitialNeighborhoodRadius()}
//
// Software Guide : EndLatex
InputImageType::IndexType index;
index[0] = atoi( argv[3] );
index[1] = atoi( argv[4] );
// Software Guide : BeginCodeSnippet
confidenceConnected->SetSeed( index );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
//
// The size of the initial neighborhood around the seed is defined with the
// method \code{SetInitialNeighborhoodRadius()}. The neighborhood will be
// defined as an $N$-Dimensional rectangular region with $2r+1$ pixels on
// the side, where $r$ is the value passed as initial neighborhood radius.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
confidenceConnected->SetInitialNeighborhoodRadius( 3 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The invocation of the \code{Update()} method on the writer triggers the
// execution of the pipeline. It is usually wise to put update calls in a
// \code{try/catch} block in case errors occur and exceptions are thrown.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
writer->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Let's now run this example using as input the image
// \code{VisibleWomanEyeSlice.png} provided in the directory
// \code{Insight/Examples/Data}. We can easily segment the major anatomical
// structures by providing seeds in the appropriate locations. For example,
//
// \begin{center}
// \begin{tabular}{|l|c|c|c|c|}
// \hline
// Structure & Seed Index & Multiplier & Iterations & Output Image \\ \hline \\ \hline
// Rectum & $(70,120)$ & 7 & 1 & Second from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline
// Rectum & $(23, 93)$ & 7 & 1 & Third from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline
// Vitreo & $(66, 66)$ & 3 & 1 & Fourth from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline
// \end{tabular}
// \end{center}
//
// \begin{figure} \center
// \includegraphics[width=0.24\textwidth]{VisibleWomanEyeSlice.eps}
// \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput1.eps}
// \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput2.eps}
// \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput3.eps}
// \itkcaption[VectorConfidenceConnected segmentation results]{Segmentation results of
// the VectorConfidenceConnected filter for various seed points.}
// \label{fig:VectorConfidenceConnectedOutput}
// \end{figure}
//
// The coloration of muscular tissue makes it easy to distinguish from the
// surrounding anatomical strucures. The optic vitrea on the other hand has
// a coloration that is not very homogeneous inside the eyeball and does not
// allow to generate a full segmentation based only on color.
//
// Software Guide : EndLatex
return 0;
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include "statistics_database.h"
struct Stats {
std::string files_added;
std::string files_removed;
std::string files_changed;
std::string dir_added;
std::string dir_removed;
std::string dir_changed;
std::string bytes_added;
std::string bytes_removed;
explicit Stats(const perf::Statistics *statistics):
files_added(statistics->
Lookup("Publish.n_files_added")->ToString()),
files_removed(statistics->
Lookup("Publish.n_files_removed")->ToString()),
files_changed(statistics->
Lookup("Publish.n_files_changed")->ToString()),
dir_added(statistics->
Lookup("Publish.n_directories_added")->ToString()),
dir_removed(statistics->
Lookup("Publish.n_directories_removed")->ToString()),
dir_changed(statistics->
Lookup("Publish.n_directories_changed")->ToString()),
bytes_added(statistics->
Lookup("Publish.sz_added_bytes")->ToString()),
bytes_removed(statistics->
Lookup("Publish.sz_removed_bytes")->ToString()) {
}
};
const float StatisticsDatabase::kLatestCompatibleSchema = 1.0f;
float StatisticsDatabase::kLatestSchema = 1.0f;
unsigned StatisticsDatabase::kLatestSchemaRevision =
RevisionFlags::kInitialRevision;
unsigned int StatisticsDatabase::instances = 0;
bool StatisticsDatabase::compacting_fails = false;
namespace {
/**
* Get UTC Time.
*
* @return a timestamp in "YYYY-MM-DD HH:MM:SS" format
*/
std::string GetGMTimestamp() {
struct tm time_ptr;
char date_and_time[50];
time_t t = time(NULL);
gmtime_r(&t, &time_ptr); // take UTC
// timestamp format
strftime(date_and_time, 50, "%Y-%m-%d %H:%M:%S", &time_ptr);
std::string timestamp(date_and_time);
return timestamp;
}
/**
* Build the insert statement.
*
* @param stats a struct with all values stored in strings
* @return the insert statement
*/
std::string PrepareStatement(struct Stats stats) {
std::string insert_statement =
"INSERT INTO publish_statistics ("
"timestamp,"
"files_added,"
"files_removed,"
"files_changed,"
"directories_added,"
"directories_removed,"
"directories_changed,"
"sz_bytes_added,"
"sz_bytes_removed)"
" VALUES("
"'"+GetGMTimestamp()+"',"+ // TEXT
stats.files_added+"," +
stats.files_removed +","+
stats.files_changed + "," +
stats.dir_added + "," +
stats.dir_removed + "," +
stats.dir_changed + "," +
stats.bytes_added + "," +
stats.bytes_removed + ");";
return insert_statement;
}
} // namespace
bool StatisticsDatabase::CreateEmptyDatabase() {
++create_empty_db_calls;
return sqlite::Sql(sqlite_db(),
"CREATE TABLE publish_statistics ("
"timestamp TEXT,"
"files_added INTEGER,"
"files_removed INTEGER,"
"files_changed INTEGER,"
"directories_added INTEGER,"
"directories_removed INTEGER,"
"directories_changed INTEGER,"
"sz_bytes_added INTEGER,"
"sz_bytes_removed INTEGER,"
"CONSTRAINT pk_publish_statistics PRIMARY KEY (timestamp));").Execute();
}
bool StatisticsDatabase::CheckSchemaCompatibility() {
++check_compatibility_calls;
return (schema_version() > kLatestCompatibleSchema - 0.1 &&
schema_version() < kLatestCompatibleSchema + 0.1);
}
bool StatisticsDatabase::LiveSchemaUpgradeIfNecessary() {
++live_upgrade_calls;
const unsigned int revision = schema_revision();
if (revision == RevisionFlags::kInitialRevision) {
return true;
}
if (revision == RevisionFlags::kUpdatableRevision) {
set_schema_revision(RevisionFlags::kUpdatedRevision);
StoreSchemaRevision();
return true;
}
if (revision == RevisionFlags::kFailingRevision) {
return false;
}
return false;
}
bool StatisticsDatabase::CompactDatabase() const {
++compact_calls;
return !compacting_fails;
}
StatisticsDatabase::~StatisticsDatabase() {
--StatisticsDatabase::instances;
}
int StatisticsDatabase::StoreStatistics(const perf::Statistics *statistics) {
sqlite::Sql insert(this->sqlite_db(), PrepareStatement(Stats(statistics)));
if (!this->BeginTransaction()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "BeginTransaction failed!");
return -1;
}
if (!insert.Execute()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "insert.Execute failed!");
return -2;
}
if (!insert.Reset()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "insert.Reset() failed!");
return -3;
}
if (!this->CommitTransaction()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "CommitTransaction failed!");
return -4;
}
return 0;
}
std::string StatisticsDatabase::GetDBPath(std::string repo_name) {
// default location
const std::string db_default_path =
"/var/spool/cvmfs/" + repo_name + "/stats.db";
const std::string repo_config_file =
"/etc/cvmfs/repositories.d/" + repo_name + "/server.conf";
SimpleOptionsParser parser;
if (!parser.TryParsePath(repo_config_file)) {
LogCvmfs(kLogCvmfs, kLogSyslogErr,
"Could not parse repository configuration: %s.",
repo_config_file.c_str());
return db_default_path;
}
std::string statistics_db = "";
if (!parser.GetValue("CVMFS_STATISTICS_DB", &statistics_db)) {
LogCvmfs(kLogCvmfs, kLogSyslogErr,
"Missing parameter %s in repository configuration file.",
"CVMFS_STATISTICS_DB");
return db_default_path;
}
std::string dirname = GetParentPath(statistics_db);
int mode = S_IRUSR | S_IWUSR | S_IXUSR |
S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; // 755
if (!MkdirDeep(dirname, mode, true)) {
LogCvmfs(kLogCvmfs, kLogSyslogErr,
"Couldn't write statistics at the specified path %s.",
statistics_db.c_str());
return db_default_path;
}
return statistics_db;
}
StatisticsDatabase::StatisticsDatabase(const std::string &filename,
const OpenMode open_mode) :
sqlite::Database<StatisticsDatabase>(filename, open_mode),
create_empty_db_calls(0), check_compatibility_calls(0),
live_upgrade_calls(0), compact_calls(0)
{
++StatisticsDatabase::instances;
}
<commit_msg>Avoid the copy of a struct Stats in PrepareStatement method<commit_after>/**
* This file is part of the CernVM File System.
*/
#include "statistics_database.h"
struct Stats {
std::string files_added;
std::string files_removed;
std::string files_changed;
std::string dir_added;
std::string dir_removed;
std::string dir_changed;
std::string bytes_added;
std::string bytes_removed;
explicit Stats(const perf::Statistics *statistics):
files_added(statistics->
Lookup("Publish.n_files_added")->ToString()),
files_removed(statistics->
Lookup("Publish.n_files_removed")->ToString()),
files_changed(statistics->
Lookup("Publish.n_files_changed")->ToString()),
dir_added(statistics->
Lookup("Publish.n_directories_added")->ToString()),
dir_removed(statistics->
Lookup("Publish.n_directories_removed")->ToString()),
dir_changed(statistics->
Lookup("Publish.n_directories_changed")->ToString()),
bytes_added(statistics->
Lookup("Publish.sz_added_bytes")->ToString()),
bytes_removed(statistics->
Lookup("Publish.sz_removed_bytes")->ToString()) {
}
};
const float StatisticsDatabase::kLatestCompatibleSchema = 1.0f;
float StatisticsDatabase::kLatestSchema = 1.0f;
unsigned StatisticsDatabase::kLatestSchemaRevision =
RevisionFlags::kInitialRevision;
unsigned int StatisticsDatabase::instances = 0;
bool StatisticsDatabase::compacting_fails = false;
namespace {
/**
* Get UTC Time.
*
* @return a timestamp in "YYYY-MM-DD HH:MM:SS" format
*/
std::string GetGMTimestamp() {
struct tm time_ptr;
char date_and_time[50];
time_t t = time(NULL);
gmtime_r(&t, &time_ptr); // take UTC
// timestamp format
strftime(date_and_time, 50, "%Y-%m-%d %H:%M:%S", &time_ptr);
std::string timestamp(date_and_time);
return timestamp;
}
/**
* Build the insert statement.
*
* @param stats a struct with all values stored in strings
* @return the insert statement
*/
std::string PrepareStatement(const struct Stats &stats) {
std::string insert_statement =
"INSERT INTO publish_statistics ("
"timestamp,"
"files_added,"
"files_removed,"
"files_changed,"
"directories_added,"
"directories_removed,"
"directories_changed,"
"sz_bytes_added,"
"sz_bytes_removed)"
" VALUES("
"'"+GetGMTimestamp()+"',"+ // TEXT
stats.files_added+"," +
stats.files_removed +","+
stats.files_changed + "," +
stats.dir_added + "," +
stats.dir_removed + "," +
stats.dir_changed + "," +
stats.bytes_added + "," +
stats.bytes_removed + ");";
return insert_statement;
}
} // namespace
bool StatisticsDatabase::CreateEmptyDatabase() {
++create_empty_db_calls;
return sqlite::Sql(sqlite_db(),
"CREATE TABLE publish_statistics ("
"timestamp TEXT,"
"files_added INTEGER,"
"files_removed INTEGER,"
"files_changed INTEGER,"
"directories_added INTEGER,"
"directories_removed INTEGER,"
"directories_changed INTEGER,"
"sz_bytes_added INTEGER,"
"sz_bytes_removed INTEGER,"
"CONSTRAINT pk_publish_statistics PRIMARY KEY (timestamp));").Execute();
}
bool StatisticsDatabase::CheckSchemaCompatibility() {
++check_compatibility_calls;
return (schema_version() > kLatestCompatibleSchema - 0.1 &&
schema_version() < kLatestCompatibleSchema + 0.1);
}
bool StatisticsDatabase::LiveSchemaUpgradeIfNecessary() {
++live_upgrade_calls;
const unsigned int revision = schema_revision();
if (revision == RevisionFlags::kInitialRevision) {
return true;
}
if (revision == RevisionFlags::kUpdatableRevision) {
set_schema_revision(RevisionFlags::kUpdatedRevision);
StoreSchemaRevision();
return true;
}
if (revision == RevisionFlags::kFailingRevision) {
return false;
}
return false;
}
bool StatisticsDatabase::CompactDatabase() const {
++compact_calls;
return !compacting_fails;
}
StatisticsDatabase::~StatisticsDatabase() {
--StatisticsDatabase::instances;
}
int StatisticsDatabase::StoreStatistics(const perf::Statistics *statistics) {
sqlite::Sql insert(this->sqlite_db(), PrepareStatement(Stats(statistics)));
if (!this->BeginTransaction()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "BeginTransaction failed!");
return -1;
}
if (!insert.Execute()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "insert.Execute failed!");
return -2;
}
if (!insert.Reset()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "insert.Reset() failed!");
return -3;
}
if (!this->CommitTransaction()) {
LogCvmfs(kLogCvmfs, kLogSyslogErr, "CommitTransaction failed!");
return -4;
}
return 0;
}
std::string StatisticsDatabase::GetDBPath(std::string repo_name) {
// default location
const std::string db_default_path =
"/var/spool/cvmfs/" + repo_name + "/stats.db";
const std::string repo_config_file =
"/etc/cvmfs/repositories.d/" + repo_name + "/server.conf";
SimpleOptionsParser parser;
if (!parser.TryParsePath(repo_config_file)) {
LogCvmfs(kLogCvmfs, kLogSyslogErr,
"Could not parse repository configuration: %s.",
repo_config_file.c_str());
return db_default_path;
}
std::string statistics_db = "";
if (!parser.GetValue("CVMFS_STATISTICS_DB", &statistics_db)) {
LogCvmfs(kLogCvmfs, kLogSyslogErr,
"Missing parameter %s in repository configuration file.",
"CVMFS_STATISTICS_DB");
return db_default_path;
}
std::string dirname = GetParentPath(statistics_db);
int mode = S_IRUSR | S_IWUSR | S_IXUSR |
S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; // 755
if (!MkdirDeep(dirname, mode, true)) {
LogCvmfs(kLogCvmfs, kLogSyslogErr,
"Couldn't write statistics at the specified path %s.",
statistics_db.c_str());
return db_default_path;
}
return statistics_db;
}
StatisticsDatabase::StatisticsDatabase(const std::string &filename,
const OpenMode open_mode) :
sqlite::Database<StatisticsDatabase>(filename, open_mode),
create_empty_db_calls(0), check_compatibility_calls(0),
live_upgrade_calls(0), compact_calls(0)
{
++StatisticsDatabase::instances;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdbtstrings.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-17 06:53:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#include "sdbtstrings.hrc"
namespace sdbtools
{
#include "stringconstants.cxx"
}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.258); FILE MERGED 2008/03/31 13:27:04 rt 1.3.258.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdbtstrings.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#include "sdbtstrings.hrc"
namespace sdbtools
{
#include "stringconstants.cxx"
}
<|endoftext|>
|
<commit_before>///
/// @file WheelFactorization.hpp
/// @brief Classes and structs related to wheel factorization.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef WHEELFACTORIZATION_HPP
#define WHEELFACTORIZATION_HPP
#include "config.hpp"
#include "toString.hpp"
#include "pmath.hpp"
#include "primesieve_error.hpp"
#include <stdint.h>
#include <limits>
#include <cstddef>
#include <cassert>
namespace primesieve {
/// The WheelInit data structure is used to calculate the first
/// multiple >= start of each sieving prime.
///
struct WheelInit
{
uint8_t nextMultipleFactor;
uint8_t wheelIndex;
};
extern const WheelInit wheel30Init[30];
extern const WheelInit wheel210Init[210];
/// The WheelElement data structure is used to skip multiples of
/// small primes using wheel factorization.
///
struct WheelElement
{
/// Bitmask used to unset the bit corresponding to the current
/// multiple of a SievingPrime object.
uint8_t unsetBit;
/// Factor used to calculate the next multiple of a sieving prime
/// that is not divisible by any of the wheel factors.
uint8_t nextMultipleFactor;
/// Overflow needed to correct the next multiple index
/// (due to sievingPrime = prime / 30).
uint8_t correct;
/// Used to calculate the next wheel index:
/// wheelIndex += next;
int8_t next;
};
extern const WheelElement wheel30[8*8];
extern const WheelElement wheel210[48*8];
/// Sieving primes are used to cross-off multiples (of itself).
/// Each SievingPrime object contains a sieving prime and the position
/// of its next multiple within the SieveOfEratosthenes array
/// (i.e. multipleIndex) and a wheelIndex.
///
class SievingPrime
{
public:
enum
{
MAX_MULTIPLEINDEX = (1 << 23) - 1,
MAX_WHEELINDEX = (1 << (32 - 23)) - 1
};
uint_t getSievingPrime() const
{
return sievingPrime_;
}
uint_t getMultipleIndex() const
{
return indexes_ & MAX_MULTIPLEINDEX;
}
uint_t getWheelIndex() const
{
return indexes_ >> 23;
}
void setMultipleIndex(uint_t multipleIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
indexes_ = static_cast<uint32_t>(indexes_ | multipleIndex);
}
void setWheelIndex(uint_t wheelIndex)
{
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = static_cast<uint32_t>(wheelIndex << 23);
}
void set(uint_t multipleIndex,
uint_t wheelIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = static_cast<uint32_t>(multipleIndex | (wheelIndex << 23));
}
void set(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
set(multipleIndex, wheelIndex);
sievingPrime_ = static_cast<uint32_t>(sievingPrime);
}
private:
/// multipleIndex = 23 least significant bits of indexes_.
/// wheelIndex = 9 most significant bits of indexes_.
uint32_t indexes_;
uint32_t sievingPrime_;
};
/// The Bucket data structure is used to store sieving primes.
/// @see http://www.ieeta.pt/~tos/software/prime_sieve.html
/// The Bucket class is designed as a singly linked list, once there
/// is no more space in the current Bucket a new Bucket node is
/// allocated.
///
class Bucket
{
public:
Bucket(const Bucket&) { reset(); }
Bucket() { reset(); }
SievingPrime* begin() { return &sievingPrimes_[0]; }
SievingPrime* last() { return &sievingPrimes_[config::BUCKETSIZE - 1]; }
SievingPrime* end() { return prime_; }
Bucket* next() { return next_; }
bool hasNext() const { return next_ != NULL; }
bool empty() { return begin() == end(); }
void reset() { prime_ = begin(); }
void setNext(Bucket* next)
{
next_ = next;
}
/// Store a sieving prime in the bucket.
/// @return false if the bucket is full else true.
///
bool store(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
prime_->set(sievingPrime, multipleIndex, wheelIndex);
return prime_++ != last();
}
private:
SievingPrime* prime_;
Bucket* next_;
SievingPrime sievingPrimes_[config::BUCKETSIZE];
};
/// The abstract WheelFactorization class is used skip multiples of
/// small primes in the sieve of Eratosthenes. The EratSmall,
/// EratMedium and EratBig classes are derived from
/// WheelFactorization.
///
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
class WheelFactorization
{
public:
/// @brief Add a new sieving prime.
///
/// Calculate the first multiple > segmentLow of prime and the
/// position within the SieveOfEratosthenes array of that multiple
/// and its wheel index. When done store the sieving prime.
///
void addSievingPrime(uint_t prime, uint64_t segmentLow)
{
segmentLow += 6;
// calculate the first multiple (of prime) > segmentLow
uint64_t quotient = segmentLow / prime + 1;
uint64_t multiple = prime * quotient;
// prime not needed for sieving
if (multiple > stop_)
return;
// ensure multiple >= prime * prime
if (quotient < prime)
{
multiple = isquare<uint64_t>(prime);
quotient = prime;
}
// calculate the next multiple of prime that is not
// divisible by any of the wheel's factors
uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor;
uint64_t multipleDist = prime * nextMultipleFactor;
if (multiple > stop_ - multipleDist)
return;
multipleDist += multiple - segmentLow;
uint_t multipleIndex = static_cast<uint_t>(multipleDist / NUMBERS_PER_BYTE);
uint_t wheelIndex = wheelOffsets_[prime % NUMBERS_PER_BYTE] + INIT[quotient % MODULO].wheelIndex;
storeSievingPrime(prime, multipleIndex, wheelIndex);
}
protected:
/// @param stop Upper bound for sieving.
/// @param sieveSize Sieve size in bytes.
///
WheelFactorization(uint64_t stop, uint_t sieveSize) :
stop_(stop)
{
const uint_t maxSieveSize = SievingPrime::MAX_MULTIPLEINDEX + 1;
if (sieveSize > maxSieveSize)
throw primesieve_error("WheelFactorization: sieveSize must be <= " + toString(maxSieveSize));
}
virtual ~WheelFactorization()
{ }
virtual void storeSievingPrime(uint_t, uint_t, uint_t) = 0;
static uint_t getMaxFactor()
{
return WHEEL[0].nextMultipleFactor;
}
/// Cross-off the current multiple (unset bit) of sievingPrime and
/// calculate its next multiple i.e. multipleIndex.
///
static void unsetBit(byte_t* sieve, uint_t sievingPrime, uint_t* multipleIndex, uint_t* wheelIndex)
{
sieve[*multipleIndex] &= WHEEL[*wheelIndex].unsetBit;
*multipleIndex += WHEEL[*wheelIndex].nextMultipleFactor * sievingPrime;
*multipleIndex += WHEEL[*wheelIndex].correct;
*wheelIndex += WHEEL[*wheelIndex].next;
}
private:
static const uint_t wheelOffsets_[30];
const uint64_t stop_;
DISALLOW_COPY_AND_ASSIGN(WheelFactorization);
};
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
const uint_t
WheelFactorization<MODULO, SIZE, INIT, WHEEL>::wheelOffsets_[30] =
{
0, SIZE * 7, 0, 0, 0, 0,
0, SIZE * 0, 0, 0, 0, SIZE * 1,
0, SIZE * 2, 0, 0, 0, SIZE * 3,
0, SIZE * 4, 0, 0, 0, SIZE * 5,
0, 0, 0, 0, 0, SIZE * 6
};
/// 3rd wheel, skips multiples of 2, 3 and 5
typedef WheelFactorization<30, 8, wheel30Init, wheel30> Modulo30Wheel_t;
/// 4th wheel, skips multiples of 2, 3, 5 and 7
typedef WheelFactorization<210, 48, wheel210Init, wheel210> Modulo210Wheel_t;
} // namespace primesieve
#endif
<commit_msg>Discard sieving prime on integer overflow<commit_after>///
/// @file WheelFactorization.hpp
/// @brief Classes and structs related to wheel factorization.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef WHEELFACTORIZATION_HPP
#define WHEELFACTORIZATION_HPP
#include "config.hpp"
#include "toString.hpp"
#include "pmath.hpp"
#include "primesieve_error.hpp"
#include <stdint.h>
#include <limits>
#include <cstddef>
#include <cassert>
namespace primesieve {
/// The WheelInit data structure is used to calculate the first
/// multiple >= start of each sieving prime.
///
struct WheelInit
{
uint8_t nextMultipleFactor;
uint8_t wheelIndex;
};
extern const WheelInit wheel30Init[30];
extern const WheelInit wheel210Init[210];
/// The WheelElement data structure is used to skip multiples of
/// small primes using wheel factorization.
///
struct WheelElement
{
/// Bitmask used to unset the bit corresponding to the current
/// multiple of a SievingPrime object.
uint8_t unsetBit;
/// Factor used to calculate the next multiple of a sieving prime
/// that is not divisible by any of the wheel factors.
uint8_t nextMultipleFactor;
/// Overflow needed to correct the next multiple index
/// (due to sievingPrime = prime / 30).
uint8_t correct;
/// Used to calculate the next wheel index:
/// wheelIndex += next;
int8_t next;
};
extern const WheelElement wheel30[8*8];
extern const WheelElement wheel210[48*8];
/// Sieving primes are used to cross-off multiples (of itself).
/// Each SievingPrime object contains a sieving prime and the position
/// of its next multiple within the SieveOfEratosthenes array
/// (i.e. multipleIndex) and a wheelIndex.
///
class SievingPrime
{
public:
enum
{
MAX_MULTIPLEINDEX = (1 << 23) - 1,
MAX_WHEELINDEX = (1 << (32 - 23)) - 1
};
uint_t getSievingPrime() const
{
return sievingPrime_;
}
uint_t getMultipleIndex() const
{
return indexes_ & MAX_MULTIPLEINDEX;
}
uint_t getWheelIndex() const
{
return indexes_ >> 23;
}
void setMultipleIndex(uint_t multipleIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
indexes_ = static_cast<uint32_t>(indexes_ | multipleIndex);
}
void setWheelIndex(uint_t wheelIndex)
{
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = static_cast<uint32_t>(wheelIndex << 23);
}
void set(uint_t multipleIndex,
uint_t wheelIndex)
{
assert(multipleIndex <= MAX_MULTIPLEINDEX);
assert(wheelIndex <= MAX_WHEELINDEX);
indexes_ = static_cast<uint32_t>(multipleIndex | (wheelIndex << 23));
}
void set(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
set(multipleIndex, wheelIndex);
sievingPrime_ = static_cast<uint32_t>(sievingPrime);
}
private:
/// multipleIndex = 23 least significant bits of indexes_.
/// wheelIndex = 9 most significant bits of indexes_.
uint32_t indexes_;
uint32_t sievingPrime_;
};
/// The Bucket data structure is used to store sieving primes.
/// @see http://www.ieeta.pt/~tos/software/prime_sieve.html
/// The Bucket class is designed as a singly linked list, once there
/// is no more space in the current Bucket a new Bucket node is
/// allocated.
///
class Bucket
{
public:
Bucket(const Bucket&) { reset(); }
Bucket() { reset(); }
SievingPrime* begin() { return &sievingPrimes_[0]; }
SievingPrime* last() { return &sievingPrimes_[config::BUCKETSIZE - 1]; }
SievingPrime* end() { return prime_; }
Bucket* next() { return next_; }
bool hasNext() const { return next_ != NULL; }
bool empty() { return begin() == end(); }
void reset() { prime_ = begin(); }
void setNext(Bucket* next)
{
next_ = next;
}
/// Store a sieving prime in the bucket.
/// @return false if the bucket is full else true.
///
bool store(uint_t sievingPrime,
uint_t multipleIndex,
uint_t wheelIndex)
{
prime_->set(sievingPrime, multipleIndex, wheelIndex);
return prime_++ != last();
}
private:
SievingPrime* prime_;
Bucket* next_;
SievingPrime sievingPrimes_[config::BUCKETSIZE];
};
/// The abstract WheelFactorization class is used skip multiples of
/// small primes in the sieve of Eratosthenes. The EratSmall,
/// EratMedium and EratBig classes are derived from
/// WheelFactorization.
///
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
class WheelFactorization
{
public:
/// @brief Add a new sieving prime.
///
/// Calculate the first multiple > segmentLow of prime and the
/// position within the SieveOfEratosthenes array of that multiple
/// and its wheel index. When done store the sieving prime.
///
void addSievingPrime(uint_t prime, uint64_t segmentLow)
{
segmentLow += 6;
// calculate the first multiple (of prime) > segmentLow
uint64_t quotient = segmentLow / prime + 1;
uint64_t multiple = prime * quotient;
// prime not needed for sieving
if (multiple > stop_ ||
multiple < segmentLow)
return;
// ensure multiple >= prime * prime
if (quotient < prime)
{
multiple = isquare<uint64_t>(prime);
quotient = prime;
}
// calculate the next multiple of prime that is not
// divisible by any of the wheel's factors
uint64_t nextMultipleFactor = INIT[quotient % MODULO].nextMultipleFactor;
uint64_t multipleDist = prime * nextMultipleFactor;
if (multiple > stop_ - multipleDist)
return;
multipleDist += multiple - segmentLow;
uint_t multipleIndex = static_cast<uint_t>(multipleDist / NUMBERS_PER_BYTE);
uint_t wheelIndex = wheelOffsets_[prime % NUMBERS_PER_BYTE] + INIT[quotient % MODULO].wheelIndex;
storeSievingPrime(prime, multipleIndex, wheelIndex);
}
protected:
/// @param stop Upper bound for sieving.
/// @param sieveSize Sieve size in bytes.
///
WheelFactorization(uint64_t stop, uint_t sieveSize) :
stop_(stop)
{
const uint_t maxSieveSize = SievingPrime::MAX_MULTIPLEINDEX + 1;
if (sieveSize > maxSieveSize)
throw primesieve_error("WheelFactorization: sieveSize must be <= " + toString(maxSieveSize));
}
virtual ~WheelFactorization()
{ }
virtual void storeSievingPrime(uint_t, uint_t, uint_t) = 0;
static uint_t getMaxFactor()
{
return WHEEL[0].nextMultipleFactor;
}
/// Cross-off the current multiple (unset bit) of sievingPrime and
/// calculate its next multiple i.e. multipleIndex.
///
static void unsetBit(byte_t* sieve, uint_t sievingPrime, uint_t* multipleIndex, uint_t* wheelIndex)
{
sieve[*multipleIndex] &= WHEEL[*wheelIndex].unsetBit;
*multipleIndex += WHEEL[*wheelIndex].nextMultipleFactor * sievingPrime;
*multipleIndex += WHEEL[*wheelIndex].correct;
*wheelIndex += WHEEL[*wheelIndex].next;
}
private:
static const uint_t wheelOffsets_[30];
const uint64_t stop_;
DISALLOW_COPY_AND_ASSIGN(WheelFactorization);
};
template <uint_t MODULO, uint_t SIZE, const WheelInit* INIT, const WheelElement* WHEEL>
const uint_t
WheelFactorization<MODULO, SIZE, INIT, WHEEL>::wheelOffsets_[30] =
{
0, SIZE * 7, 0, 0, 0, 0,
0, SIZE * 0, 0, 0, 0, SIZE * 1,
0, SIZE * 2, 0, 0, 0, SIZE * 3,
0, SIZE * 4, 0, 0, 0, SIZE * 5,
0, 0, 0, 0, 0, SIZE * 6
};
/// 3rd wheel, skips multiples of 2, 3 and 5
typedef WheelFactorization<30, 8, wheel30Init, wheel30> Modulo30Wheel_t;
/// 4th wheel, skips multiples of 2, 3, 5 and 7
typedef WheelFactorization<210, 48, wheel210Init, wheel210> Modulo210Wheel_t;
} // namespace primesieve
#endif
<|endoftext|>
|
<commit_before>/** @addtogroup Synchronization
* @{
* \copyright TU Dresden ZIH. All rights reserved.
* \authors Martin Flehmig, Marc Hartung, Marcus Walther
* \date Oct 2015
*/
#ifndef INCLUDE_SYNCHRONIZATION_INTERPOLATION_HPP_
#define INCLUDE_SYNCHRONIZATION_INTERPOLATION_HPP_
#include "Stdafx.hpp"
#include "fmi/ValueCollection.hpp"
#include "synchronization/HistoryEntry.hpp"
namespace Synchronization
{
class Interpolation
{
public:
Interpolation(const real_type & tolerance = 1.0e-5);
/**
* Interpolates a new ValueCollection out of Data in the given DataHistory regarding the given point_type of time
* @arg curTime the given point_type of time, where for the interpolation takes place
* @arg dh DataHistory containing the needed data. dh should enclose curTime
* @arg order order+1 time stamps are used for interpolation.
*/
FMI::ValueCollection interpolate(const real_type & curTime, const set<HistoryEntry> & dh, int_type order) const;
/**
* Interpolates a new ValueCollection out of Data in the given DataHistory regarding the given point_type of time
* @arg curTime the given point_type of time, where for the interpolation takes place
* @arg dh DataHistory containing the needed data. dh should enclose curTime
*/
FMI::ValueCollection interpolate(const real_type & curTime, const set<HistoryEntry> & dh) const;
real_type getTolerance() const;
FMI::ValueCollection interpolateHistory(const vector<HistoryEntry> & entries, const tuple<size_type, size_type> & range,
const size_type & curI, const size_type & time);
private:
template<typename T>
vector<T> internalInterpolate(const real_type & curTime, const list<const HistoryEntry*> & in) const
{
throw runtime_error("Interpolation: order not supported");
}
list<const HistoryEntry*> internalCollect(const real_type & curTime, const set<HistoryEntry> & dh, size_type n) const;
template<typename T>
vector<T> interpolateValues(const vector<HistoryEntry> & entries, const size_type & startI, const size_type & endI,
const size_type & time)
{
throw runtime_error("Interpolation: type not supported");
}
real_type _tolerance;
}; // End class Interpolation
template<>
vector<real_type> Interpolation::interpolateValues(const std::vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
template<>
vector<int_type> Interpolation::interpolateValues(const std::vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
template<>
vector<bool_type> Interpolation::interpolateValues(const std::vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
template<>
vector<string_type> Interpolation::interpolateValues(const std::vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
} /* End namespace Synchronization */
#endif /* INCLUDE_SYNCHRONIZATION_INTERPOLATION_HPP_ */
/**
* @}
*/
<commit_msg>remove namespace std and harmonize files<commit_after>/** @addtogroup Synchronization
* @{
* \copyright TU Dresden ZIH. All rights reserved.
* \authors Martin Flehmig, Marc Hartung, Marcus Walther
* \date Oct 2015
*/
#ifndef INCLUDE_SYNCHRONIZATION_INTERPOLATION_HPP_
#define INCLUDE_SYNCHRONIZATION_INTERPOLATION_HPP_
#include "Stdafx.hpp"
#include "fmi/ValueCollection.hpp"
#include "synchronization/HistoryEntry.hpp"
namespace Synchronization
{
class Interpolation
{
public:
Interpolation(const real_type & tolerance = 1.0e-5);
/**
* Interpolates a new ValueCollection out of Data in the given DataHistory regarding the given point_type of time
* @arg curTime the given point_type of time, where for the interpolation takes place
* @arg dh DataHistory containing the needed data. dh should enclose curTime
* @arg order order+1 time stamps are used for interpolation.
*/
FMI::ValueCollection interpolate(const real_type & curTime, const set<HistoryEntry> & dh, int_type order) const;
/**
* Interpolates a new ValueCollection out of Data in the given DataHistory regarding the given point_type of time
* @arg curTime the given point_type of time, where for the interpolation takes place
* @arg dh DataHistory containing the needed data. dh should enclose curTime
*/
FMI::ValueCollection interpolate(const real_type & curTime, const set<HistoryEntry> & dh) const;
real_type getTolerance() const;
FMI::ValueCollection interpolateHistory(const vector<HistoryEntry> & entries,
const tuple<size_type, size_type> & range, const size_type & curI,
const size_type & time);
private:
template<typename T>
vector<T> internalInterpolate(const real_type & curTime, const list<const HistoryEntry*> & in) const
{
throw runtime_error("Interpolation: order not supported");
}
list<const HistoryEntry*> internalCollect(const real_type & curTime, const set<HistoryEntry> & dh,
size_type n) const;
template<typename T>
vector<T> interpolateValues(const vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time)
{
throw runtime_error("Interpolation: type not supported");
}
real_type _tolerance;
}; // End class Interpolation
template<>
vector<real_type> Interpolation::interpolateValues(const vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
template<>
vector<int_type> Interpolation::interpolateValues(const vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
template<>
vector<bool_type> Interpolation::interpolateValues(const vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
template<>
vector<string_type> Interpolation::interpolateValues(const vector<HistoryEntry> & entries, const size_type & startI,
const size_type & endI, const size_type & time);
} /* End namespace Synchronization */
#endif /* INCLUDE_SYNCHRONIZATION_INTERPOLATION_HPP_ */
/**
* @}
*/
<|endoftext|>
|
<commit_before>#ifndef _TOOLBOX_CPP_STACK_ALLOCATOR_HPP_
#define _TOOLBOX_CPP_STACK_ALLOCATOR_HPP_
#include <cstddef>
#include <type_traits>
#include <new>
namespace toolbox
{
namespace alloc
{
template<typename T, std::size_t N>
struct stack_allocator
{
using value_type = T;
template<typename U> struct rebind
{
using other = stack_allocator<U, N>;
};
stack_allocator()
{
}
~stack_allocator()
{
}
stack_allocator(const stack_allocator &) :
size_ (0)
{
}
stack_allocator(stack_allocator &&) = delete;
void operator=(const stack_allocator &) = delete;
void operator=(stack_allocator &&) = delete;
T* allocate(std::size_t n)
{
if (size_ + n > N)
throw std::bad_alloc {};
auto res = reinterpret_cast<T *>(&storage_[size_]);
size_ += n;
return res;
}
void deallocate(T* ptr, std::size_t n)
{
if (ptr + n == reinterpret_cast<T *>(&storage_[size_])) {
size_ -= n;
}
}
std::size_t available() const
{
return N - size_;
}
std::size_t used() const
{
return size_;
}
private:
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_[N];
std::size_t size_ = 0;
};
} // namespace alloc
} // namespace toolbox
#endif
<commit_msg>alloc: add missing traits<commit_after>#ifndef _TOOLBOX_CPP_STACK_ALLOCATOR_HPP_
#define _TOOLBOX_CPP_STACK_ALLOCATOR_HPP_
#include <cstddef>
#include <type_traits>
#include <new>
namespace toolbox
{
namespace alloc
{
template<typename T, std::size_t N>
struct stack_allocator
{
using value_type = T;
using pointer = T *;
using const_pointer = const T *;
using reference = T&;
using const_reference = const T &;
template<typename U> struct rebind
{
using other = stack_allocator<U, N>;
};
stack_allocator()
{
}
~stack_allocator()
{
}
stack_allocator(const stack_allocator &) :
size_ (0)
{
}
stack_allocator(stack_allocator &&) = delete;
void operator=(const stack_allocator &) = delete;
void operator=(stack_allocator &&) = delete;
T* allocate(std::size_t n)
{
if (size_ + n > N)
throw std::bad_alloc {};
auto res = reinterpret_cast<T *>(&storage_[size_]);
size_ += n;
return res;
}
void deallocate(T* ptr, std::size_t n)
{
if (ptr + n == reinterpret_cast<T *>(&storage_[size_])) {
size_ -= n;
}
}
std::size_t available() const
{
return N - size_;
}
std::size_t used() const
{
return size_;
}
private:
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_[N];
std::size_t size_ = 0;
};
} // namespace alloc
} // namespace toolbox
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#ifndef VCF2MULTIALIGN_BIT_STRING_FILE_HH
#define VCF2MULTIALIGN_BIT_STRING_FILE_HH
#include <vcf2multialign/types.hh>
namespace vcf2multialign {
class bit_string_file
{
protected:
file_ostream *m_stream{};
public:
bit_string_file() = default;
bit_string_file(file_ostream &stream):
m_stream(&stream)
{
}
// Just write bytes for now.
bool is_open() const { return m_stream && m_stream->is_open(); }
void close() { if (m_stream) m_stream->close(); m_stream = nullptr; }
void write_ones(std::size_t count) { std::fill_n(std::ostream_iterator <char>(*m_stream), count, '1'); }
void write_zeros(std::size_t count) { std::fill_n(std::ostream_iterator <char>(*m_stream), count, '0'); }
void flush() { *m_stream << std::flush; }
};
}
#endif
<commit_msg>Revert "Make the file closable"<commit_after>/*
* Copyright (c) 2017 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#ifndef VCF2MULTIALIGN_BIT_STRING_FILE_HH
#define VCF2MULTIALIGN_BIT_STRING_FILE_HH
#include <vcf2multialign/types.hh>
namespace vcf2multialign {
class bit_string_file
{
protected:
file_ostream *m_stream{};
public:
bit_string_file() = default;
bit_string_file(file_ostream &stream):
m_stream(&stream)
{
}
// Just write bytes for now.
bool is_open() const { return m_stream && m_stream->is_open(); }
void write_ones(std::size_t count) { std::fill_n(std::ostream_iterator <char>(*m_stream), count, '1'); }
void write_zeros(std::size_t count) { std::fill_n(std::ostream_iterator <char>(*m_stream), count, '0'); }
void flush() { *m_stream << std::flush; }
};
}
#endif
<|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <atomic>
#include <condition_variable>
#include <functional>
#include <thread>
#include <visionaray/math/math.h>
#include "macros.h"
#include "sched_common.h"
#include "semaphore.h"
namespace visionaray
{
namespace detail
{
static const int tile_width = 16;
static const int tile_height = 16;
inline int div_up(int a, int b)
{
return (a + b - 1) / b;
}
struct sync_params
{
sync_params()
: render_loop_exit(false)
{
}
std::mutex mutex;
std::condition_variable threads_start;
visionaray::semaphore threads_ready;
std::atomic<long> tile_idx_counter;
std::atomic<long> tile_fin_counter;
std::atomic<long> tile_num;
std::atomic<bool> render_loop_exit;
};
} // detail
template <typename R>
struct tiled_sched<R>::impl
{
typedef std::function<void(recti const&)> render_tile_func;
impl() = default;
std::vector<std::thread> threads;
detail::sync_params sync_params;
recti viewport;
render_tile_func render_tile;
};
template <typename R>
tiled_sched<R>::tiled_sched()
: impl_(new impl())
{
for (unsigned i = 0; i < 8; ++i)
{
impl_->threads.emplace_back([this](){ render_loop(); });
}
}
template <typename R>
tiled_sched<R>::~tiled_sched()
{
impl_->sync_params.render_loop_exit = true;
impl_->sync_params.threads_start.notify_all();
for (auto& t : impl_->threads)
{
if (t.joinable())
{
t.join();
}
}
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::frame(K kernel, SP sched_params, unsigned frame_num)
{
sched_params.rt.begin_frame();
impl_->viewport = sched_params.cam.get_viewport();
typedef typename R::scalar_type scalar_type;
// typedef matrix<4, 4, scalar_type> matrix_type;
typedef typename SP::color_traits color_traits;
// auto inv_view_matrix = matrix_type( inverse(sched_params.cam.get_view_matrix()) );
// auto inv_proj_matrix = matrix_type( inverse(sched_params.cam.get_proj_matrix()) );
auto viewport = sched_params.cam.get_viewport();
recti xviewport(viewport.x, viewport.y, viewport.w - 1, viewport.h - 1);
// front, side, and up vectors form an orthonormal basis
auto f = normalize( sched_params.cam.eye() - sched_params.cam.center() );
auto s = normalize( cross(sched_params.cam.up(), f) );
auto u = cross(f, s);
auto eye = vector<3, scalar_type>(sched_params.cam.eye());
auto cam_u = vector<3, scalar_type>(s) * scalar_type( tan(sched_params.cam.fovy() / 2.0f) * sched_params.cam.aspect() );
auto cam_v = vector<3, scalar_type>(u) * scalar_type( tan(sched_params.cam.fovy() / 2.0f) );
auto cam_w = vector<3, scalar_type>(-f);
impl_->render_tile = [=](recti const& tile)
{
using namespace detail;
unsigned numx = tile_width / packet_size<scalar_type>::w;
unsigned numy = tile_height / packet_size<scalar_type>::h;
for (unsigned i = 0; i < numx * numy; ++i)
{
auto pos = vec2i(i % numx, i / numx);
auto x = tile.x + pos.x * packet_size<scalar_type>::w;
auto y = tile.y + pos.y * packet_size<scalar_type>::h;
recti xpixel(x, y, packet_size<scalar_type>::w - 1, packet_size<scalar_type>::h - 1);
if ( !overlapping(xviewport, xpixel) )
{
continue;
}
sample_pixel<R, color_traits>
(
x, y, frame_num, viewport, sched_params.rt.color(),
kernel, typename SP::pixel_sampler_type(),
// inv_view_matrix, inv_proj_matrix
eye, cam_u, cam_v, cam_w
);
}
};
auto w = impl_->viewport.w - impl_->viewport.x;
auto h = impl_->viewport.h - impl_->viewport.y;
auto numtilesx = detail::div_up(w, detail::tile_width);
auto numtilesy = detail::div_up(h, detail::tile_height);
auto& sparams = impl_->sync_params;
sparams.tile_idx_counter = 0;
sparams.tile_fin_counter = 0;
sparams.tile_num = numtilesx * numtilesy;
// render frame
sparams.threads_start.notify_all();
sparams.threads_ready.wait();
sched_params.rt.end_frame();
}
template <typename R>
void tiled_sched<R>::render_loop()
{
for (;;)
{
auto& sparams = impl_->sync_params;
{
std::unique_lock<std::mutex> l( sparams.mutex );
sparams.threads_start.wait(l);
}
// case event.exit:
if (sparams.render_loop_exit)
{
break;
}
// case event.render:
for (;;)
{
auto tile_idx = sparams.tile_idx_counter.fetch_add(1);
if (tile_idx >= sparams.tile_num)
{
break;
}
auto w = impl_->viewport.w;
auto tilew = detail::tile_width;
auto tileh = detail::tile_height;
auto numtilesx = detail::div_up( w, tilew );
recti tile
(
impl_->viewport.x + (tile_idx % numtilesx) * tilew,
impl_->viewport.y + (tile_idx / numtilesx) * tileh,
tilew,
tileh
);
impl_->render_tile(tile);
auto num_tiles_fin = sparams.tile_fin_counter.fetch_add(1);
if (num_tiles_fin >= sparams.tile_num - 1)
{
assert(num_tiles_fin == sparams.tile_num - 1);
sparams.threads_ready.notify();
break;
}
}
}
}
} // visionaray
<commit_msg>Support both sched_param types in tiled scheduler<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <atomic>
#include <condition_variable>
#include <functional>
#include <thread>
#include <visionaray/math/math.h>
#include "macros.h"
#include "sched_common.h"
#include "semaphore.h"
namespace visionaray
{
namespace detail
{
static const int tile_width = 16;
static const int tile_height = 16;
inline int div_up(int a, int b)
{
return (a + b - 1) / b;
}
struct sync_params
{
sync_params()
: render_loop_exit(false)
{
}
std::mutex mutex;
std::condition_variable threads_start;
visionaray::semaphore threads_ready;
std::atomic<long> tile_idx_counter;
std::atomic<long> tile_fin_counter;
std::atomic<long> tile_num;
std::atomic<bool> render_loop_exit;
};
} // detail
//-------------------------------------------------------------------------------------------------
// Private implementation
//
template <typename R>
struct tiled_sched<R>::impl
{
typedef std::function<void(recti const&)> render_tile_func;
impl() = default;
template <typename K, typename SP>
void init_render_func(K kernel, SP sched_params, unsigned frame_num);
template <typename K, typename RT, typename PxSamplerT>
void init_render_func(K kernel, sched_params<RT, PxSamplerT> sched_params, unsigned frame_num);
std::vector<std::thread> threads;
detail::sync_params sync_params;
recti viewport;
render_tile_func render_tile;
};
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::impl::init_render_func(K kernel, SP sparams, unsigned frame_num)
{
// assume that SP has members view_matrix and proj_matrix
using scalar_type = typename R::scalar_type;
using matrix_type = matrix<4, 4, scalar_type>;
using color_traits = typename SP::color_traits;
viewport = sparams.viewport;
auto inv_view_matrix = matrix_type( inverse(sparams.view_matrix) );
auto inv_proj_matrix = matrix_type( inverse(sparams.proj_matrix) );
recti xviewport(viewport.x, viewport.y, viewport.w - 1, viewport.h - 1);
render_tile = [=](recti const& tile)
{
using namespace detail;
unsigned numx = tile_width / packet_size<scalar_type>::w;
unsigned numy = tile_height / packet_size<scalar_type>::h;
for (unsigned i = 0; i < numx * numy; ++i)
{
auto pos = vec2i(i % numx, i / numx);
auto x = tile.x + pos.x * packet_size<scalar_type>::w;
auto y = tile.y + pos.y * packet_size<scalar_type>::h;
recti xpixel(x, y, packet_size<scalar_type>::w - 1, packet_size<scalar_type>::h - 1);
if ( !overlapping(xviewport, xpixel) )
{
continue;
}
sample_pixel<R, color_traits>
(
x, y, frame_num, viewport, sparams.rt.color(),
kernel, typename SP::pixel_sampler_type(),
inv_view_matrix, inv_proj_matrix
);
}
};
}
template <typename R>
template <typename K, typename RT, typename PxSamplerT>
void tiled_sched<R>::impl::init_render_func(K kernel, sched_params<RT, PxSamplerT> sparams, unsigned frame_num)
{
// overload for pinhole cam
using SP = sched_params<RT, PxSamplerT>;
using scalar_type = typename R::scalar_type;
using color_traits = typename SP::color_traits;
viewport = sparams.cam.get_viewport();
recti xviewport(viewport.x, viewport.y, viewport.w - 1, viewport.h - 1);
// front, side, and up vectors form an orthonormal basis
auto f = normalize( sparams.cam.eye() - sparams.cam.center() );
auto s = normalize( cross(sparams.cam.up(), f) );
auto u = cross(f, s);
auto eye = vector<3, scalar_type>(sparams.cam.eye());
auto cam_u = vector<3, scalar_type>(s) * scalar_type( tan(sparams.cam.fovy() / 2.0f) * sparams.cam.aspect() );
auto cam_v = vector<3, scalar_type>(u) * scalar_type( tan(sparams.cam.fovy() / 2.0f) );
auto cam_w = vector<3, scalar_type>(-f);
render_tile = [=](recti const& tile)
{
using namespace detail;
unsigned numx = tile_width / packet_size<scalar_type>::w;
unsigned numy = tile_height / packet_size<scalar_type>::h;
for (unsigned i = 0; i < numx * numy; ++i)
{
auto pos = vec2i(i % numx, i / numx);
auto x = tile.x + pos.x * packet_size<scalar_type>::w;
auto y = tile.y + pos.y * packet_size<scalar_type>::h;
recti xpixel(x, y, packet_size<scalar_type>::w - 1, packet_size<scalar_type>::h - 1);
if ( !overlapping(xviewport, xpixel) )
{
continue;
}
sample_pixel<R, color_traits>
(
x, y, frame_num, viewport, sparams.rt.color(),
kernel, typename SP::pixel_sampler_type(),
eye, cam_u, cam_v, cam_w
);
}
};
}
//-------------------------------------------------------------------------------------------------
// tiled_sched implementation
//
template <typename R>
tiled_sched<R>::tiled_sched()
: impl_(new impl())
{
for (unsigned i = 0; i < 8; ++i)
{
impl_->threads.emplace_back([this](){ render_loop(); });
}
}
template <typename R>
tiled_sched<R>::~tiled_sched()
{
impl_->sync_params.render_loop_exit = true;
impl_->sync_params.threads_start.notify_all();
for (auto& t : impl_->threads)
{
if (t.joinable())
{
t.join();
}
}
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::frame(K kernel, SP sched_params, unsigned frame_num)
{
sched_params.rt.begin_frame();
impl_->init_render_func(kernel, sched_params, frame_num);
auto w = impl_->viewport.w - impl_->viewport.x;
auto h = impl_->viewport.h - impl_->viewport.y;
auto numtilesx = detail::div_up(w, detail::tile_width);
auto numtilesy = detail::div_up(h, detail::tile_height);
auto& sparams = impl_->sync_params;
sparams.tile_idx_counter = 0;
sparams.tile_fin_counter = 0;
sparams.tile_num = numtilesx * numtilesy;
// render frame
sparams.threads_start.notify_all();
sparams.threads_ready.wait();
sched_params.rt.end_frame();
}
template <typename R>
void tiled_sched<R>::render_loop()
{
for (;;)
{
auto& sparams = impl_->sync_params;
{
std::unique_lock<std::mutex> l( sparams.mutex );
sparams.threads_start.wait(l);
}
// case event.exit:
if (sparams.render_loop_exit)
{
break;
}
// case event.render:
for (;;)
{
auto tile_idx = sparams.tile_idx_counter.fetch_add(1);
if (tile_idx >= sparams.tile_num)
{
break;
}
auto w = impl_->viewport.w;
auto tilew = detail::tile_width;
auto tileh = detail::tile_height;
auto numtilesx = detail::div_up( w, tilew );
recti tile
(
impl_->viewport.x + (tile_idx % numtilesx) * tilew,
impl_->viewport.y + (tile_idx / numtilesx) * tileh,
tilew,
tileh
);
impl_->render_tile(tile);
auto num_tiles_fin = sparams.tile_fin_counter.fetch_add(1);
if (num_tiles_fin >= sparams.tile_num - 1)
{
assert(num_tiles_fin == sparams.tile_num - 1);
sparams.threads_ready.notify();
break;
}
}
}
}
} // visionaray
<|endoftext|>
|
<commit_before>#pragma warning(disable:4996)
#include "MainWindowProxy.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"
#include "NativeToolbarQt.h"
#include "rho/rubyext/NativeToolbarExt.h"
#undef null
#include <QString>
#include <QApplication>
#include <QtGui/QAction>
#include "QtMainWindow.h"
IMPLEMENT_LOGCLASS(CMainWindowProxy,"MainWindowProxy");
extern "C" int rho_wmsys_has_touchscreen();
using namespace rho;
using namespace rho::common;
CMainWindowProxy::CMainWindowProxy(void):
qtApplication(NULL),
qtMainWindow(NULL)
{
}
CMainWindowProxy::~CMainWindowProxy(void)
{
if (qtMainWindow) delete (QtMainWindow*)qtMainWindow;
if (qtApplication) delete (QApplication*)qtApplication;
}
void CMainWindowProxy::navigate(const wchar_t* url)
{
LOG(INFO) + "navigate: '"+url+"'";
((QtMainWindow*)qtMainWindow)->navigate(QUrl(QString::fromWCharArray(url)));
}
void CMainWindowProxy::setCallback(IMainWindowCallback* callback)
{
((QtMainWindow*)qtMainWindow)->setCallback(callback);
}
void* CMainWindowProxy::init(IMainWindowCallback* callback, const wchar_t* title)
{
int argc = 0;
qtApplication = (void*)new QApplication(argc, 0);
qtMainWindow = (void*)new QtMainWindow();
((QtMainWindow*)qtMainWindow)->setWindowTitle(QString::fromWCharArray(title));
((QtMainWindow*)qtMainWindow)->setCallback(callback);
((QtMainWindow*)qtMainWindow)->show();
return (void*)((QtMainWindow*)qtMainWindow)->winId();
}
void CMainWindowProxy::messageLoop(void)
{
qApp->exec();
}
void CMainWindowProxy::GoBack(void)
{
LOG(INFO) + "back";
((QtMainWindow*)qtMainWindow)->GoBack();
}
void CMainWindowProxy::GoForward(void)
{
LOG(INFO) + "forward";
((QtMainWindow*)qtMainWindow)->GoForward();
}
void CMainWindowProxy::Refresh(void)
{
LOG(INFO) + "refresh";
((QtMainWindow*)qtMainWindow)->Refresh();
}
bool CMainWindowProxy::isStarted()
{
return true;
}
int CMainWindowProxy::getHeight()
{
return ((QtMainWindow*)qtMainWindow)->toolbarGetHeight();
}
void CMainWindowProxy::removeToolbar()
{
((QtMainWindow*)qtMainWindow)->toolbarHide();
}
void CMainWindowProxy::removeAllButtons()
{
((QtMainWindow*)qtMainWindow)->toolbarRemoveAllButtons();
}
static QColor getColorFromString(const char* szColor)
{
if ( !szColor || !*szColor )
return QColor(0, 0, 0);
int c = atoi(szColor);
int cR = (c & 0xFF0000) >> 16;
int cG = (c & 0xFF00) >> 8;
int cB = (c & 0xFF);
return QColor(cR, cG, cB);
}
void CMainWindowProxy::createToolbar(rho_param *p)
{
if (!rho_rhodesapp_check_mode() || !rho_wmsys_has_touchscreen() )
return;
int bar_type = TOOLBAR_TYPE;
std::auto_ptr<QColor> m_rgbBackColor (NULL);
std::auto_ptr<QColor> m_rgbMaskColor (NULL);
int m_nHeight = CNativeToolbar::MIN_TOOLBAR_HEIGHT;
rho_param *params = NULL;
switch (p->type)
{
case RHO_PARAM_ARRAY:
params = p;
break;
case RHO_PARAM_HASH:
{
for (int i = 0, lim = p->v.hash->size; i < lim; ++i)
{
const char *name = p->v.hash->name[i];
rho_param *value = p->v.hash->value[i];
if (strcasecmp(name, "background_color") == 0)
m_rgbBackColor.reset(new QColor(getColorFromString(value->v.string)));
else if (strcasecmp(name, "mask_color") == 0)
m_rgbMaskColor.reset(new QColor(getColorFromString(value->v.string)));
else if (strcasecmp(name, "view_height") == 0)
m_nHeight = atoi(value->v.string);
else if (strcasecmp(name, "buttons") == 0 || strcasecmp(name, "tabs") == 0)
params = value;
}
}
break;
default: {
LOG(ERROR) + "Unexpected parameter type for create_nativebar, should be Array or Hash";
return;
}
}
if (!params) {
LOG(ERROR) + "Wrong parameters for create_nativebar";
return;
}
int size = params->v.array->size;
if ( size == 0 )
{
removeToolbar();
return;
}
removeAllButtons();
int nSeparators = 0;
bool wasSeparator = false;
for (int ipass=0; ipass < 2; ++ipass) {
for (int i = 0; i < size; ++i)
{
rho_param *hash = params->v.array->value[i];
if (hash->type != RHO_PARAM_HASH) {
LOG(ERROR) + "Unexpected type of array item for create_nativebar, should be Hash";
return;
}
const char *label = NULL;
const char *action = NULL;
const char *icon = NULL;
const char *colored_icon = NULL;
int nItemWidth = 0;
for (int j = 0, lim = hash->v.hash->size; j < lim; ++j)
{
const char *name = hash->v.hash->name[j];
rho_param *value = hash->v.hash->value[j];
if (value->type != RHO_PARAM_STRING) {
LOG(ERROR) + "Unexpected '" + name + "' type, should be String";
return;
}
if (strcasecmp(name, "label") == 0)
label = value->v.string;
else if (strcasecmp(name, "action") == 0)
action = value->v.string;
else if (strcasecmp(name, "icon") == 0)
icon = value->v.string;
else if (strcasecmp(name, "colored_icon") == 0)
colored_icon = value->v.string;
else if (strcasecmp(name, "width") == 0)
nItemWidth = atoi(value->v.string);
}
if (label == NULL && bar_type == TOOLBAR_TYPE)
label = "";
if ( label == NULL || action == NULL) {
LOG(ERROR) + "Illegal argument for create_nativebar";
return;
}
if ( strcasecmp(action, "forward") == 0 && rho_conf_getBool("jqtouch_mode") )
continue;
if (!action) action = "";
if (ipass==0) {
if (strcasecmp(action, "separator")==0)
++nSeparators;
} else {
LOG(INFO) + "addToolbarButton: Label: '"+label+"';Action: '"+action+"'";
if (strcasecmp(action, "separator")==0) {
if (nSeparators!=1)
((QtMainWindow*)qtMainWindow)->toolbarAddSeparator();
else
wasSeparator = true;
} else {
String strImagePath;
if ( icon && *icon )
strImagePath = rho::common::CFilePath::join( RHODESAPP().getAppRootPath(), icon );
else {
if ( strcasecmp(action, "options")==0 )
strImagePath = "res/options_btn.wm.png";
else if ( strcasecmp(action, "home")==0 )
strImagePath = "res/home_btn.wm.png";
else if ( strcasecmp(action, "refresh")==0 )
strImagePath = "res/refresh_btn.wm.png";
else if ( strcasecmp(action, "back")==0 )
strImagePath = "res/back_btn.wm.png";
else if ( strcasecmp(action, "forward")==0 )
strImagePath = "res/forward_btn.wm.png";
strImagePath = strImagePath.length() > 0 ? CFilePath::join( RHODESAPP().getRhodesPath(), "lib/framework/" + strImagePath) : String();
}
((QtMainWindow*)qtMainWindow)->toolbarAddAction(QIcon(QString(strImagePath.c_str())), QString(label), action, wasSeparator);
}
}
}
}
((QtMainWindow*)qtMainWindow)->setToolbarStyle(false, (m_rgbBackColor.get()!=NULL ? m_rgbBackColor->name() : ""));
((QtMainWindow*)qtMainWindow)->toolbarShow();
}
void CMainWindowProxy::menuClear()
{
((QtMainWindow*)qtMainWindow)->menuClear();
}
void CMainWindowProxy::menuAddSeparator()
{
((QtMainWindow*)qtMainWindow)->menuAddSeparator();
}
void CMainWindowProxy::menuAddAction(const char* label, int item)
{
((QtMainWindow*)qtMainWindow)->menuAddAction(QString(label), item);
}
<commit_msg>emulator: fix images in toolbar<commit_after>#pragma warning(disable:4996)
#include "MainWindowProxy.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"
#include "NativeToolbarQt.h"
#include "rho/rubyext/NativeToolbarExt.h"
#undef null
#include <QString>
#include <QApplication>
#include <QtGui/QAction>
#include "QtMainWindow.h"
IMPLEMENT_LOGCLASS(CMainWindowProxy,"MainWindowProxy");
extern "C" int rho_wmsys_has_touchscreen();
using namespace rho;
using namespace rho::common;
CMainWindowProxy::CMainWindowProxy(void):
qtApplication(NULL),
qtMainWindow(NULL)
{
}
CMainWindowProxy::~CMainWindowProxy(void)
{
if (qtMainWindow) delete (QtMainWindow*)qtMainWindow;
if (qtApplication) delete (QApplication*)qtApplication;
}
void CMainWindowProxy::navigate(const wchar_t* url)
{
LOG(INFO) + "navigate: '"+url+"'";
((QtMainWindow*)qtMainWindow)->navigate(QUrl(QString::fromWCharArray(url)));
}
void CMainWindowProxy::setCallback(IMainWindowCallback* callback)
{
((QtMainWindow*)qtMainWindow)->setCallback(callback);
}
void* CMainWindowProxy::init(IMainWindowCallback* callback, const wchar_t* title)
{
int argc = 0;
qtApplication = (void*)new QApplication(argc, 0);
qtMainWindow = (void*)new QtMainWindow();
((QtMainWindow*)qtMainWindow)->setWindowTitle(QString::fromWCharArray(title));
((QtMainWindow*)qtMainWindow)->setCallback(callback);
((QtMainWindow*)qtMainWindow)->show();
return (void*)((QtMainWindow*)qtMainWindow)->winId();
}
void CMainWindowProxy::messageLoop(void)
{
qApp->exec();
}
void CMainWindowProxy::GoBack(void)
{
LOG(INFO) + "back";
((QtMainWindow*)qtMainWindow)->GoBack();
}
void CMainWindowProxy::GoForward(void)
{
LOG(INFO) + "forward";
((QtMainWindow*)qtMainWindow)->GoForward();
}
void CMainWindowProxy::Refresh(void)
{
LOG(INFO) + "refresh";
((QtMainWindow*)qtMainWindow)->Refresh();
}
bool CMainWindowProxy::isStarted()
{
return true;
}
int CMainWindowProxy::getHeight()
{
return ((QtMainWindow*)qtMainWindow)->toolbarGetHeight();
}
void CMainWindowProxy::removeToolbar()
{
((QtMainWindow*)qtMainWindow)->toolbarHide();
}
void CMainWindowProxy::removeAllButtons()
{
((QtMainWindow*)qtMainWindow)->toolbarRemoveAllButtons();
}
static QColor getColorFromString(const char* szColor)
{
if ( !szColor || !*szColor )
return QColor(0, 0, 0);
int c = atoi(szColor);
int cR = (c & 0xFF0000) >> 16;
int cG = (c & 0xFF00) >> 8;
int cB = (c & 0xFF);
return QColor(cR, cG, cB);
}
void CMainWindowProxy::createToolbar(rho_param *p)
{
if (!rho_rhodesapp_check_mode() || !rho_wmsys_has_touchscreen() )
return;
int bar_type = TOOLBAR_TYPE;
std::auto_ptr<QColor> m_rgbBackColor (NULL);
std::auto_ptr<QColor> m_rgbMaskColor (NULL);
int m_nHeight = CNativeToolbar::MIN_TOOLBAR_HEIGHT;
rho_param *params = NULL;
switch (p->type)
{
case RHO_PARAM_ARRAY:
params = p;
break;
case RHO_PARAM_HASH:
{
for (int i = 0, lim = p->v.hash->size; i < lim; ++i)
{
const char *name = p->v.hash->name[i];
rho_param *value = p->v.hash->value[i];
if (strcasecmp(name, "background_color") == 0)
m_rgbBackColor.reset(new QColor(getColorFromString(value->v.string)));
else if (strcasecmp(name, "mask_color") == 0)
m_rgbMaskColor.reset(new QColor(getColorFromString(value->v.string)));
else if (strcasecmp(name, "view_height") == 0)
m_nHeight = atoi(value->v.string);
else if (strcasecmp(name, "buttons") == 0 || strcasecmp(name, "tabs") == 0)
params = value;
}
}
break;
default: {
LOG(ERROR) + "Unexpected parameter type for create_nativebar, should be Array or Hash";
return;
}
}
if (!params) {
LOG(ERROR) + "Wrong parameters for create_nativebar";
return;
}
int size = params->v.array->size;
if ( size == 0 )
{
removeToolbar();
return;
}
removeAllButtons();
int nSeparators = 0;
bool wasSeparator = false;
for (int ipass=0; ipass < 2; ++ipass) {
for (int i = 0; i < size; ++i)
{
rho_param *hash = params->v.array->value[i];
if (hash->type != RHO_PARAM_HASH) {
LOG(ERROR) + "Unexpected type of array item for create_nativebar, should be Hash";
return;
}
const char *label = NULL;
const char *action = NULL;
const char *icon = NULL;
const char *colored_icon = NULL;
int nItemWidth = 0;
for (int j = 0, lim = hash->v.hash->size; j < lim; ++j)
{
const char *name = hash->v.hash->name[j];
rho_param *value = hash->v.hash->value[j];
if (value->type != RHO_PARAM_STRING) {
LOG(ERROR) + "Unexpected '" + name + "' type, should be String";
return;
}
if (strcasecmp(name, "label") == 0)
label = value->v.string;
else if (strcasecmp(name, "action") == 0)
action = value->v.string;
else if (strcasecmp(name, "icon") == 0)
icon = value->v.string;
else if (strcasecmp(name, "colored_icon") == 0)
colored_icon = value->v.string;
else if (strcasecmp(name, "width") == 0)
nItemWidth = atoi(value->v.string);
}
if (label == NULL && bar_type == TOOLBAR_TYPE)
label = "";
if ( label == NULL || action == NULL) {
LOG(ERROR) + "Illegal argument for create_nativebar";
return;
}
if ( strcasecmp(action, "forward") == 0 && rho_conf_getBool("jqtouch_mode") )
continue;
if (!action) action = "";
if (ipass==0) {
if (strcasecmp(action, "separator")==0)
++nSeparators;
} else {
LOG(INFO) + "addToolbarButton: Label: '"+label+"';Action: '"+action+"'";
if (strcasecmp(action, "separator")==0) {
if (nSeparators!=1)
((QtMainWindow*)qtMainWindow)->toolbarAddSeparator();
else
wasSeparator = true;
} else {
String strImagePath;
if ( icon && *icon )
strImagePath = rho::common::CFilePath::join( RHODESAPP().getRhoRootPath(), icon );
else {
if ( strcasecmp(action, "options")==0 )
strImagePath = "res/options_btn.wm.png";
else if ( strcasecmp(action, "home")==0 )
strImagePath = "res/home_btn.wm.png";
else if ( strcasecmp(action, "refresh")==0 )
strImagePath = "res/refresh_btn.wm.png";
else if ( strcasecmp(action, "back")==0 )
strImagePath = "res/back_btn.wm.png";
else if ( strcasecmp(action, "forward")==0 )
strImagePath = "res/forward_btn.wm.png";
strImagePath = strImagePath.length() > 0 ? CFilePath::join( RHODESAPP().getRhodesPath(), "lib/framework/" + strImagePath) : String();
}
((QtMainWindow*)qtMainWindow)->toolbarAddAction(QIcon(QString(strImagePath.c_str())), QString(label), action, wasSeparator);
}
}
}
}
((QtMainWindow*)qtMainWindow)->setToolbarStyle(false, (m_rgbBackColor.get()!=NULL ? m_rgbBackColor->name() : ""));
((QtMainWindow*)qtMainWindow)->toolbarShow();
}
void CMainWindowProxy::menuClear()
{
((QtMainWindow*)qtMainWindow)->menuClear();
}
void CMainWindowProxy::menuAddSeparator()
{
((QtMainWindow*)qtMainWindow)->menuAddSeparator();
}
void CMainWindowProxy::menuAddAction(const char* label, int item)
{
((QtMainWindow*)qtMainWindow)->menuAddAction(QString(label), item);
}
<|endoftext|>
|
<commit_before>/*
* (C) 2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "../cli/cli.h"
#include "tests.h"
#include <iostream>
#include <sstream>
#include <string>
#include <set>
#include <deque>
#include <cstdlib>
#include <botan/version.h>
#include <botan/loadstor.h>
#include <botan/hash.h>
#if defined(BOTAN_HAS_HMAC_DRBG)
#include <botan/hmac_drbg.h>
#endif
#if defined(BOTAN_HAS_SYSTEM_RNG)
#include <botan/system_rng.h>
#endif
#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)
#include <botan/auto_rng.h>
#endif
#if defined(BOTAN_HAS_OPENSSL)
#include <botan/internal/openssl.h>
#endif
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
#include <thread>
#include <future>
#endif
namespace {
class Test_Runner final : public Botan_CLI::Command
{
public:
Test_Runner()
: Command("test --threads=0 --run-long-tests --run-online-tests --test-runs=1 --drbg-seed= --data-dir="
" --pkcs11-lib= --provider= --log-success *suites") {}
std::string help_text() const override
{
std::ostringstream err;
const std::string& spec = cmd_spec();
err << "Usage: botan-test"
<< spec.substr(spec.find_first_of(' '), std::string::npos)
<< "\n\nAvailable test suites\n"
<< "----------------\n";
size_t line_len = 0;
for(auto const& test : Botan_Tests::Test::registered_tests())
{
err << test << " ";
line_len += test.size() + 1;
if(line_len > 64)
{
err << "\n";
line_len = 0;
}
}
if(line_len > 0)
{
err << "\n";
}
return err.str();
}
void go() override
{
const size_t threads = get_arg_sz("threads");
const std::string drbg_seed = get_arg("drbg-seed");
const bool log_success = flag_set("log-success");
const bool run_online_tests = flag_set("run-online-tests");
const bool run_long_tests = flag_set("run-long-tests");
const std::string data_dir = get_arg_or("data-dir", "src/tests/data");
const std::string pkcs11_lib = get_arg("pkcs11-lib");
const std::string provider = get_arg("provider");
const size_t runs = get_arg_sz("test-runs");
std::vector<std::string> req = get_arg_list("suites");
if(req.empty())
{
/*
If nothing was requested on the command line, run everything. First
run the "essentials" to smoke test, then everything else in
alphabetical order.
*/
req = {"block", "stream", "hash", "mac", "modes", "aead"
"kdf", "pbkdf", "hmac_drbg", "x931_rng", "util"
};
std::set<std::string> all_others = Botan_Tests::Test::registered_tests();
if(pkcs11_lib.empty())
{
// do not run pkcs11 tests by default unless pkcs11-lib set
for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();)
{
if((*iter).find("pkcs11") != std::string::npos)
{
iter = all_others.erase(iter);
}
else
{
++iter;
}
}
}
for(auto f : req)
{
all_others.erase(f);
}
req.insert(req.end(), all_others.begin(), all_others.end());
}
else if(req.size() == 1 && req.at(0) == "pkcs11")
{
req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa",
"pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509"
};
}
else
{
std::set<std::string> all = Botan_Tests::Test::registered_tests();
for(auto const& r : req)
{
if(all.find(r) == all.end())
{
throw Botan_CLI::CLI_Usage_Error("Unknown test suite: " + r);
}
}
}
output() << "Testing " << Botan::version_string() << "\n";
output() << "Starting tests";
if(threads > 1)
{
output() << " threads:" << threads;
}
if(!pkcs11_lib.empty())
{
output() << " pkcs11 library:" << pkcs11_lib;
}
Botan_Tests::Provider_Filter pf;
if(!provider.empty())
{
output() << " provider:" << provider;
pf.set(provider);
}
#if defined(BOTAN_HAS_OPENSSL)
if(provider.empty() || provider == "openssl")
{
ERR_load_crypto_strings();
}
#endif
std::unique_ptr<Botan::RandomNumberGenerator> rng;
#if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_64)
std::vector<uint8_t> seed = Botan::hex_decode(drbg_seed);
if(seed.empty())
{
const uint64_t ts = Botan_Tests::Test::timestamp();
seed.resize(8);
Botan::store_be(ts, seed.data());
}
output() << " rng:HMAC_DRBG with seed '" << Botan::hex_encode(seed) << "'";
// Expand out the seed to 512 bits to make the DRBG happy
std::unique_ptr<Botan::HashFunction> sha512(Botan::HashFunction::create("SHA-512"));
sha512->update(seed);
seed.resize(sha512->output_length());
sha512->final(seed.data());
std::unique_ptr<Botan::HMAC_DRBG> drbg(new Botan::HMAC_DRBG("SHA-384"));
drbg->initialize_with(seed.data(), seed.size());
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
rng.reset(new Botan::Serialized_RNG(drbg.release()));
#else
rng = std::move(drbg);
#endif
#else
if(drbg_seed != "")
{
throw Botan_Tests::Test_Error("HMAC_DRBG disabled in build, cannot specify DRBG seed");
}
#if defined(BOTAN_HAS_SYSTEM_RNG)
output() << " rng:system";
rng.reset(new Botan::System_RNG);
#elif defined(BOTAN_HAS_AUTO_SEEDING_RNG)
output() << " rng:autoseeded";
rng.reset(new Botan::Serialized_RNG(new Botan::AutoSeeded_RNG));
#else
// last ditch fallback for RNG-less build
class Bogus_Fallback_RNG final : public Botan::RandomNumberGenerator
{
public:
std::string name() const override
{
return "Bogus_Fallback_RNG";
}
void clear() override
{
/* ignored */
}
void randomize(uint8_t out[], size_t len) override
{
for(size_t i = 0; i != len; ++i)
{
out[i] = std::rand();
}
}
bool is_seeded() const override
{
return true;
}
void add_entropy(const uint8_t[], size_t) override
{
/* ignored */
}
};
rng.reset(new Bogus_Fallback_RNG);
#endif
#endif
output() << "\n";
Botan_Tests::Test::setup_tests(log_success, run_online_tests, run_long_tests,
data_dir, pkcs11_lib, pf, rng.get());
for(size_t i = 0; i != runs; ++i)
{
const size_t failed = run_tests(req, output(), threads);
// Throw so main returns an error
if(failed)
{
throw Botan_Tests::Test_Error("Test suite failure");
}
}
}
private:
std::string report_out(const std::vector<Botan_Tests::Test::Result>& results,
size_t& tests_failed,
size_t& tests_ran)
{
std::ostringstream out;
std::map<std::string, Botan_Tests::Test::Result> combined;
for(auto const& result : results)
{
const std::string who = result.who();
auto i = combined.find(who);
if(i == combined.end())
{
combined.insert(std::make_pair(who, Botan_Tests::Test::Result(who)));
i = combined.find(who);
}
i->second.merge(result);
}
for(auto const& result : combined)
{
out << result.second.result_string(verbose());
tests_failed += result.second.tests_failed();
tests_ran += result.second.tests_run();
}
return out.str();
}
size_t run_tests(const std::vector<std::string>& tests_to_run,
std::ostream& out,
size_t threads)
{
size_t tests_ran = 0, tests_failed = 0;
const uint64_t start_time = Botan_Tests::Test::timestamp();
if(threads <= 1)
{
for(auto const& test_name : tests_to_run)
{
try
{
out << test_name << ':' << std::endl;
const auto results = Botan_Tests::Test::run_test(test_name, false);
out << report_out(results, tests_failed, tests_ran) << std::flush;
}
catch(std::exception& e)
{
out << "Test " << test_name << " failed with exception " << e.what() << std::flush;
}
}
}
else
{
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
/*
We're not doing this in a particularly nice way, and variance in time is
high so commonly we'll 'run dry' by blocking on the first future. But
plain C++11 <thread> is missing a lot of tools we'd need (like
wait_for_any on a set of futures) and there is no point pulling in an
additional dependency just for this. In any case it helps somewhat
(50-100% speedup) and provides a proof of concept for parallel testing.
*/
typedef std::future<std::vector<Botan_Tests::Test::Result>> FutureResults;
std::deque<FutureResults> fut_results;
for(auto const& test_name : tests_to_run)
{
auto run_it = [test_name]() -> std::vector<Botan_Tests::Test::Result>
{
try
{
return Botan_Tests::Test::run_test(test_name, false);
}
catch(std::exception& e)
{
Botan_Tests::Test::Result r(test_name);
r.test_failure("Exception thrown", e.what());
return std::vector<Botan_Tests::Test::Result> {r};
}
};
fut_results.push_back(std::async(std::launch::async, run_it));
while(fut_results.size() > threads)
{
out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush;
fut_results.pop_front();
}
}
while(fut_results.size() > 0)
{
out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush;
fut_results.pop_front();
}
#else
out << "Threading support disabled\n";
return 1;
#endif
}
const uint64_t total_ns = Botan_Tests::Test::timestamp() - start_time;
out << "Tests complete ran " << tests_ran << " tests in "
<< Botan_Tests::Test::format_time(total_ns) << " ";
if(tests_failed > 0)
{
out << tests_failed << " tests failed";
}
else if(tests_ran > 0)
{
out << "all tests ok";
}
out << std::endl;
return tests_failed;
}
};
BOTAN_REGISTER_COMMAND("test", Test_Runner);
}
int main(int argc, char* argv[])
{
std::cerr << Botan::runtime_version_check(BOTAN_VERSION_MAJOR, BOTAN_VERSION_MINOR, BOTAN_VERSION_PATCH);
try
{
std::unique_ptr<Botan_CLI::Command> cmd(Botan_CLI::Command::get_cmd("test"));
if(!cmd)
{
std::cerr << "Unable to retrieve testing helper (program bug)\n"; // WTF
return 1;
}
std::vector<std::string> args(argv + 1, argv + argc);
return cmd->run(args);
}
catch(Botan::Exception& e)
{
std::cerr << "Exiting with library exception " << e.what() << std::endl;
}
catch(std::exception& e)
{
std::cerr << "Exiting with std exception " << e.what() << std::endl;
}
catch(...)
{
std::cerr << "Exiting with unknown exception" << std::endl;
}
}
<commit_msg>Refactor how test RNG is created<commit_after>/*
* (C) 2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "../cli/cli.h"
#include "tests.h"
#include <iostream>
#include <sstream>
#include <string>
#include <set>
#include <deque>
#include <cstdlib>
#include <botan/version.h>
#include <botan/loadstor.h>
#include <botan/hash.h>
#if defined(BOTAN_HAS_HMAC_DRBG)
#include <botan/hmac_drbg.h>
#endif
#if defined(BOTAN_HAS_SYSTEM_RNG)
#include <botan/system_rng.h>
#endif
#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)
#include <botan/auto_rng.h>
#endif
#if defined(BOTAN_HAS_OPENSSL)
#include <botan/internal/openssl.h>
#endif
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
#include <thread>
#include <future>
#endif
namespace {
class Test_Runner final : public Botan_CLI::Command
{
public:
Test_Runner()
: Command("test --threads=0 --run-long-tests --run-online-tests --test-runs=1 --drbg-seed= --data-dir="
" --pkcs11-lib= --provider= --log-success *suites") {}
std::unique_ptr<Botan::RandomNumberGenerator>
create_test_rng(const std::string& drbg_seed)
{
std::unique_ptr<Botan::RandomNumberGenerator> rng;
#if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_64)
std::vector<uint8_t> seed = Botan::hex_decode(drbg_seed);
if(seed.empty())
{
const uint64_t ts = Botan_Tests::Test::timestamp();
seed.resize(8);
Botan::store_be(ts, seed.data());
}
output() << " rng:HMAC_DRBG with seed '" << Botan::hex_encode(seed) << "'\n";
// Expand out the seed to 512 bits to make the DRBG happy
std::unique_ptr<Botan::HashFunction> sha512(Botan::HashFunction::create("SHA-512"));
sha512->update(seed);
seed.resize(sha512->output_length());
sha512->final(seed.data());
std::unique_ptr<Botan::HMAC_DRBG> drbg(new Botan::HMAC_DRBG("SHA-384"));
drbg->initialize_with(seed.data(), seed.size());
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
rng.reset(new Botan::Serialized_RNG(drbg.release()));
#else
rng = std::move(drbg);
#endif
#endif
if(!rng && drbg_seed != "")
throw Botan_Tests::Test_Error("HMAC_DRBG disabled in build, cannot specify DRBG seed");
#if defined(BOTAN_HAS_SYSTEM_RNG)
if(!rng)
{
output() << " rng:system\n";
rng.reset(new Botan::System_RNG);
}
#endif
#if defined(BOTAN_HAS_AUTO_SEEDING_RNG)
if(!rng)
{
output() << " rng:autoseeded\n";
rng.reset(new Botan::Serialized_RNG(new Botan::AutoSeeded_RNG));
}
#endif
if(!rng)
{
// last ditch fallback for RNG-less build
class Bogus_Fallback_RNG final : public Botan::RandomNumberGenerator
{
public:
std::string name() const override { return "Bogus_Fallback_RNG"; }
void clear() override { /* ignored */ }
void add_entropy(const uint8_t[], size_t) override { /* ignored */ }
bool is_seeded() const override { return true; }
void randomize(uint8_t out[], size_t len) override
{
for(size_t i = 0; i != len; ++i)
{
out[i] = std::rand();
}
}
};
output() << " rng:bogus\n";
rng.reset(new Bogus_Fallback_RNG);
}
return rng;
}
std::string help_text() const override
{
std::ostringstream err;
const std::string& spec = cmd_spec();
err << "Usage: botan-test"
<< spec.substr(spec.find_first_of(' '), std::string::npos)
<< "\n\nAvailable test suites\n"
<< "----------------\n";
size_t line_len = 0;
for(auto const& test : Botan_Tests::Test::registered_tests())
{
err << test << " ";
line_len += test.size() + 1;
if(line_len > 64)
{
err << "\n";
line_len = 0;
}
}
if(line_len > 0)
{
err << "\n";
}
return err.str();
}
void go() override
{
const size_t threads = get_arg_sz("threads");
const std::string drbg_seed = get_arg("drbg-seed");
const bool log_success = flag_set("log-success");
const bool run_online_tests = flag_set("run-online-tests");
const bool run_long_tests = flag_set("run-long-tests");
const std::string data_dir = get_arg_or("data-dir", "src/tests/data");
const std::string pkcs11_lib = get_arg("pkcs11-lib");
const std::string provider = get_arg("provider");
const size_t runs = get_arg_sz("test-runs");
std::vector<std::string> req = get_arg_list("suites");
if(req.empty())
{
/*
If nothing was requested on the command line, run everything. First
run the "essentials" to smoke test, then everything else in
alphabetical order.
*/
req = {"block", "stream", "hash", "mac", "modes", "aead"
"kdf", "pbkdf", "hmac_drbg", "x931_rng", "util"
};
std::set<std::string> all_others = Botan_Tests::Test::registered_tests();
if(pkcs11_lib.empty())
{
// do not run pkcs11 tests by default unless pkcs11-lib set
for(std::set<std::string>::iterator iter = all_others.begin(); iter != all_others.end();)
{
if((*iter).find("pkcs11") != std::string::npos)
{
iter = all_others.erase(iter);
}
else
{
++iter;
}
}
}
for(auto f : req)
{
all_others.erase(f);
}
req.insert(req.end(), all_others.begin(), all_others.end());
}
else if(req.size() == 1 && req.at(0) == "pkcs11")
{
req = {"pkcs11-manage", "pkcs11-module", "pkcs11-slot", "pkcs11-session", "pkcs11-object", "pkcs11-rsa",
"pkcs11-ecdsa", "pkcs11-ecdh", "pkcs11-rng", "pkcs11-x509"
};
}
else
{
std::set<std::string> all = Botan_Tests::Test::registered_tests();
for(auto const& r : req)
{
if(all.find(r) == all.end())
{
throw Botan_CLI::CLI_Usage_Error("Unknown test suite: " + r);
}
}
}
output() << "Testing " << Botan::version_string() << "\n";
output() << "Starting tests";
if(threads > 1)
{
output() << " threads:" << threads;
}
if(!pkcs11_lib.empty())
{
output() << " pkcs11 library:" << pkcs11_lib;
}
Botan_Tests::Provider_Filter pf;
if(!provider.empty())
{
output() << " provider:" << provider;
pf.set(provider);
}
#if defined(BOTAN_HAS_OPENSSL)
if(provider.empty() || provider == "openssl")
{
ERR_load_crypto_strings();
}
#endif
std::unique_ptr<Botan::RandomNumberGenerator> rng = create_test_rng(drbg_seed);
Botan_Tests::Test::setup_tests(log_success, run_online_tests, run_long_tests,
data_dir, pkcs11_lib, pf, rng.get());
for(size_t i = 0; i != runs; ++i)
{
const size_t failed = run_tests(req, output(), threads);
// Throw so main returns an error
if(failed)
{
throw Botan_Tests::Test_Error("Test suite failure");
}
}
}
private:
std::string report_out(const std::vector<Botan_Tests::Test::Result>& results,
size_t& tests_failed,
size_t& tests_ran)
{
std::ostringstream out;
std::map<std::string, Botan_Tests::Test::Result> combined;
for(auto const& result : results)
{
const std::string who = result.who();
auto i = combined.find(who);
if(i == combined.end())
{
combined.insert(std::make_pair(who, Botan_Tests::Test::Result(who)));
i = combined.find(who);
}
i->second.merge(result);
}
for(auto const& result : combined)
{
out << result.second.result_string(verbose());
tests_failed += result.second.tests_failed();
tests_ran += result.second.tests_run();
}
return out.str();
}
size_t run_tests(const std::vector<std::string>& tests_to_run,
std::ostream& out,
size_t threads)
{
size_t tests_ran = 0, tests_failed = 0;
const uint64_t start_time = Botan_Tests::Test::timestamp();
if(threads <= 1)
{
for(auto const& test_name : tests_to_run)
{
try
{
out << test_name << ':' << std::endl;
const auto results = Botan_Tests::Test::run_test(test_name, false);
out << report_out(results, tests_failed, tests_ran) << std::flush;
}
catch(std::exception& e)
{
out << "Test " << test_name << " failed with exception " << e.what() << std::flush;
}
}
}
else
{
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
/*
We're not doing this in a particularly nice way, and variance in time is
high so commonly we'll 'run dry' by blocking on the first future. But
plain C++11 <thread> is missing a lot of tools we'd need (like
wait_for_any on a set of futures) and there is no point pulling in an
additional dependency just for this. In any case it helps somewhat
(50-100% speedup) and provides a proof of concept for parallel testing.
*/
typedef std::future<std::vector<Botan_Tests::Test::Result>> FutureResults;
std::deque<FutureResults> fut_results;
for(auto const& test_name : tests_to_run)
{
auto run_it = [test_name]() -> std::vector<Botan_Tests::Test::Result>
{
try
{
return Botan_Tests::Test::run_test(test_name, false);
}
catch(std::exception& e)
{
Botan_Tests::Test::Result r(test_name);
r.test_failure("Exception thrown", e.what());
return std::vector<Botan_Tests::Test::Result> {r};
}
};
fut_results.push_back(std::async(std::launch::async, run_it));
while(fut_results.size() > threads)
{
out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush;
fut_results.pop_front();
}
}
while(fut_results.size() > 0)
{
out << report_out(fut_results[0].get(), tests_failed, tests_ran) << std::flush;
fut_results.pop_front();
}
#else
out << "Threading support disabled\n";
return 1;
#endif
}
const uint64_t total_ns = Botan_Tests::Test::timestamp() - start_time;
out << "Tests complete ran " << tests_ran << " tests in "
<< Botan_Tests::Test::format_time(total_ns) << " ";
if(tests_failed > 0)
{
out << tests_failed << " tests failed";
}
else if(tests_ran > 0)
{
out << "all tests ok";
}
out << std::endl;
return tests_failed;
}
};
BOTAN_REGISTER_COMMAND("test", Test_Runner);
}
int main(int argc, char* argv[])
{
std::cerr << Botan::runtime_version_check(BOTAN_VERSION_MAJOR, BOTAN_VERSION_MINOR, BOTAN_VERSION_PATCH);
try
{
std::unique_ptr<Botan_CLI::Command> cmd(Botan_CLI::Command::get_cmd("test"));
if(!cmd)
{
std::cerr << "Unable to retrieve testing helper (program bug)\n"; // WTF
return 1;
}
std::vector<std::string> args(argv + 1, argv + argc);
return cmd->run(args);
}
catch(Botan::Exception& e)
{
std::cerr << "Exiting with library exception " << e.what() << std::endl;
}
catch(std::exception& e)
{
std::cerr << "Exiting with std exception " << e.what() << std::endl;
}
catch(...)
{
std::cerr << "Exiting with unknown exception" << std::endl;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "systems/OpenGLSystem.h"
#include "systems/OpenALSystem.h"
#include "systems/BulletPhysics.h"
#include "systems/FactorySystem.h"
#include "controllers/GUIController.h"
#include "controllers/FPSCamera.h"
#include "components/PhysicsController.h"
#include "components/GLScreenQuad.h"
#include "SCParser.h"
#include "systems/WebGUISystem.h"
#include "OS.h"
#include "components/SpotLight.h"
#ifdef _WIN32
#include <windows.h>
#endif
int main(int argCount, char **argValues) {
Sigma::WebGUISystem webguisys;
CefRefPtr<Sigma::WebGUISystem> app(&webguisys);
#ifdef _WIN32
CefMainArgs mainArgs(GetModuleHandle(NULL));
int exitCode = CefExecuteProcess(mainArgs, app.get(), nullptr);
#else
CefMainArgs mainArgs(argCount, argValues);
int exitCode = CefExecuteProcess(mainArgs, app.get());
#endif
if (exitCode >= 0) {
return exitCode;
}
Sigma::OS glfwos;
Sigma::OpenGLSystem glsys;
Sigma::OpenALSystem alsys;
Sigma::BulletPhysics bphys;
Sigma::FactorySystem& factory = Sigma::FactorySystem::getInstance();
factory.register_Factory(glsys);
factory.register_Factory(alsys);
factory.register_Factory(bphys);
factory.register_Factory(webguisys);
if (!glfwos.InitializeWindow(1024, 768, "Sigma GLFW Test Window")) {
std::cerr << "Failed creating the window or context." << std::endl;
return -1;
}
/////////////////////////////
// Start the openGL system //
/////////////////////////////
std::cout << "Initializing OpenGL system." << std::endl;
const int* version = glsys.Start();
glsys.SetViewportSize(glfwos.GetWindowWidth(), glfwos.GetWindowHeight());
if (version[0] == -1) {
std::cerr << "Error starting OpenGL!" << std::endl;
return -1;
}
else {
std::cout << "OpenGL version: " << version[0] << "." << version[1] << std::endl;
}
//////////////////////////////
// Setup deferred rendering //
//////////////////////////////
// Create render target for the GBuffer, Light Accumulation buffer, and final composite buffer
unsigned int geoBuffer = glsys.createRenderTarget(glfwos.GetWindowWidth(), glfwos.GetWindowHeight(), true);
glsys.createRTBuffer(geoBuffer, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE); // Diffuse texture
glsys.createRTBuffer(geoBuffer, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE); // Normal texture
glsys.createRTBuffer(geoBuffer, GL_R32F, GL_RED, GL_FLOAT); // Depth texture
glsys.initRenderTarget(geoBuffer); // Create the opengl assets
///////////////////
// Setup physics //
///////////////////
bphys.Start();
///////////////
// Setup GUI //
///////////////
webguisys.Start(mainArgs);
webguisys.SetWindowSize(glfwos.GetWindowWidth(), glfwos.GetWindowHeight());
/////////////////
// Setup Sound //
/////////////////
std::cout << "Initializing OpenAL system." << std::endl;
alsys.Start();
alsys.test(); // try sound
////////////////
// Load scene //
////////////////
// Parse the scene file to retrieve entities
Sigma::parser::SCParser parser;
std::cout << "Parsing test.sc scene file." << std::endl;
if (!parser.Parse("test.sc")) {
assert(0 && "Failed to load entities from file.");
}
std::cout << "Generating Entities." << std::endl;
// Create each entity's components
for (unsigned int i = 0; i < parser.EntityCount(); ++i) {
Sigma::parser::Entity* e = parser.GetEntity(i);
for (auto itr = e->components.begin(); itr != e->components.end(); ++itr) {
// Currently, physicsmover components must come after gl* components
if((*itr).type == "PhysicsMover") {
Sigma::GLTransform *transform = glsys.GetTransformFor(e->id);
if(transform) {
Property p("transform", transform);
itr->properties.push_back(p);
}
else {
assert(0 && "Invalid entity id");
}
}
factory.create(itr->type,e->id, const_cast<std::vector<Property>&>(itr->properties));
}
}
//////////////////////
// Setup user input //
//////////////////////
// View and ViewMover creation has been moved to test.sc, but for
// now provide sensible defaults. Final engine should require
// definition in scene file. Currently entity ID for view must be 1
// for this to work.
// No view provided, create a default FPS view
if(!glsys.GetView()) {
std::vector<Property> props;
Property p_x("x", 0.0f);
Property p_y("y", 0.0f);
Property p_z("z", 0.0f);
props.push_back(p_x);
props.push_back(p_y);
props.push_back(p_z);
glsys.createGLView(1, props);
}
//Create the controller
//Perhaps a little awkward currently, should create a generic
//controller class ancestor
bphys.initViewMover(*glsys.GetView()->Transform());
Sigma::event::handler::FPSCamera theCamera(*bphys.getViewMover());
glsys.GetView()->Transform()->SetEuler(true);
glsys.GetView()->Transform()->SetMaxRotation(glm::vec3(45.0f,0,0));
glfwos.RegisterKeyboardEventHandler(&theCamera);
glfwos.RegisterMouseEventHandler(&theCamera);
theCamera.os = &glfwos;
// Sync bullet physics object with gl camera
///////////////////
// Configure GUI //
///////////////////
Sigma::event::handler::GUIController guicon;
guicon.SetGUI(webguisys.getComponent(100, Sigma::WebGUIView::getStaticComponentTypeName()));
glfwos.RegisterKeyboardEventHandler(&guicon);
glfwos.RegisterMouseEventHandler(&guicon);
// Call now to clear the delta after startup.
glfwos.GetDeltaTime();
{
Sigma::ALSound *als = (Sigma::ALSound *)alsys.getComponent(200, Sigma::ALSound::getStaticComponentTypeName());
if(als) {
als->Play(Sigma::PLAYBACK_LOOP);
}
}
enum FlashlightState {
FL_ON,
FL_TURNING_ON,
FL_OFF,
FL_TURNING_OFF
};
FlashlightState fs = FL_OFF;
while (!glfwos.Closing()) {
// Get time in ms, store it in seconds too
double deltaSec = glfwos.GetDeltaTime();
// Process input
if(glfwos.CheckKeyState(Sigma::event::KS_DOWN, GLFW_KEY_F)) {
if(fs==FL_OFF) {
fs=FL_TURNING_ON;
} else if (fs==FL_ON) {
fs=FL_TURNING_OFF;
}
}
if(glfwos.CheckKeyState(Sigma::event::KS_UP, GLFW_KEY_F)) {
if(fs==FL_TURNING_ON) {
// Enable flashlight
Sigma::SpotLight *spotlight = static_cast<Sigma::SpotLight *>(glsys.getComponent(151, Sigma::SpotLight::getStaticComponentTypeName()));
spotlight->enabled = true;
// Rotate flashlight up
// Enable spotlight
fs=FL_ON;
} else if (fs==FL_TURNING_OFF) {
// Disable spotlight
Sigma::SpotLight *spotlight = static_cast<Sigma::SpotLight *>(glsys.getComponent(151, Sigma::SpotLight::getStaticComponentTypeName()));
spotlight->enabled = false;
// Rotate flashlight down
// Disable flashlight
fs=FL_OFF;
}
}
///////////////////////
// Update subsystems //
///////////////////////
// Pass in delta time in seconds
bphys.Update(deltaSec);
webguisys.Update(deltaSec);
alsys.Update();
// Update the renderer and present
if (glsys.Update(deltaSec)) {
glfwos.SwapBuffers();
}
glfwos.OSMessageLoop();
}
CefShutdown();
return 0;
}
<commit_msg>Removed the GUI controller for this release<commit_after>#include <iostream>
#include "systems/OpenGLSystem.h"
#include "systems/OpenALSystem.h"
#include "systems/BulletPhysics.h"
#include "systems/FactorySystem.h"
#include "controllers/GUIController.h"
#include "controllers/FPSCamera.h"
#include "components/PhysicsController.h"
#include "components/GLScreenQuad.h"
#include "SCParser.h"
#include "systems/WebGUISystem.h"
#include "OS.h"
#include "components/SpotLight.h"
#ifdef _WIN32
#include <windows.h>
#endif
int main(int argCount, char **argValues) {
Sigma::WebGUISystem webguisys;
CefRefPtr<Sigma::WebGUISystem> app(&webguisys);
#ifdef _WIN32
CefMainArgs mainArgs(GetModuleHandle(NULL));
int exitCode = CefExecuteProcess(mainArgs, app.get(), nullptr);
#else
CefMainArgs mainArgs(argCount, argValues);
int exitCode = CefExecuteProcess(mainArgs, app.get());
#endif
if (exitCode >= 0) {
return exitCode;
}
Sigma::OS glfwos;
Sigma::OpenGLSystem glsys;
Sigma::OpenALSystem alsys;
Sigma::BulletPhysics bphys;
Sigma::FactorySystem& factory = Sigma::FactorySystem::getInstance();
factory.register_Factory(glsys);
factory.register_Factory(alsys);
factory.register_Factory(bphys);
factory.register_Factory(webguisys);
if (!glfwos.InitializeWindow(1024, 768, "Sigma GLFW Test Window")) {
std::cerr << "Failed creating the window or context." << std::endl;
return -1;
}
/////////////////////////////
// Start the openGL system //
/////////////////////////////
std::cout << "Initializing OpenGL system." << std::endl;
const int* version = glsys.Start();
glsys.SetViewportSize(glfwos.GetWindowWidth(), glfwos.GetWindowHeight());
if (version[0] == -1) {
std::cerr << "Error starting OpenGL!" << std::endl;
return -1;
}
else {
std::cout << "OpenGL version: " << version[0] << "." << version[1] << std::endl;
}
//////////////////////////////
// Setup deferred rendering //
//////////////////////////////
// Create render target for the GBuffer, Light Accumulation buffer, and final composite buffer
unsigned int geoBuffer = glsys.createRenderTarget(glfwos.GetWindowWidth(), glfwos.GetWindowHeight(), true);
glsys.createRTBuffer(geoBuffer, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE); // Diffuse texture
glsys.createRTBuffer(geoBuffer, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE); // Normal texture
glsys.createRTBuffer(geoBuffer, GL_R32F, GL_RED, GL_FLOAT); // Depth texture
glsys.initRenderTarget(geoBuffer); // Create the opengl assets
///////////////////
// Setup physics //
///////////////////
bphys.Start();
///////////////
// Setup GUI //
///////////////
webguisys.Start(mainArgs);
webguisys.SetWindowSize(glfwos.GetWindowWidth(), glfwos.GetWindowHeight());
/////////////////
// Setup Sound //
/////////////////
std::cout << "Initializing OpenAL system." << std::endl;
alsys.Start();
alsys.test(); // try sound
////////////////
// Load scene //
////////////////
// Parse the scene file to retrieve entities
Sigma::parser::SCParser parser;
std::cout << "Parsing test.sc scene file." << std::endl;
if (!parser.Parse("test.sc")) {
assert(0 && "Failed to load entities from file.");
}
std::cout << "Generating Entities." << std::endl;
// Create each entity's components
for (unsigned int i = 0; i < parser.EntityCount(); ++i) {
Sigma::parser::Entity* e = parser.GetEntity(i);
for (auto itr = e->components.begin(); itr != e->components.end(); ++itr) {
// Currently, physicsmover components must come after gl* components
if((*itr).type == "PhysicsMover") {
Sigma::GLTransform *transform = glsys.GetTransformFor(e->id);
if(transform) {
Property p("transform", transform);
itr->properties.push_back(p);
}
else {
assert(0 && "Invalid entity id");
}
}
factory.create(itr->type,e->id, const_cast<std::vector<Property>&>(itr->properties));
}
}
//////////////////////
// Setup user input //
//////////////////////
// View and ViewMover creation has been moved to test.sc, but for
// now provide sensible defaults. Final engine should require
// definition in scene file. Currently entity ID for view must be 1
// for this to work.
// No view provided, create a default FPS view
if(!glsys.GetView()) {
std::vector<Property> props;
Property p_x("x", 0.0f);
Property p_y("y", 0.0f);
Property p_z("z", 0.0f);
props.push_back(p_x);
props.push_back(p_y);
props.push_back(p_z);
glsys.createGLView(1, props);
}
//Create the controller
//Perhaps a little awkward currently, should create a generic
//controller class ancestor
bphys.initViewMover(*glsys.GetView()->Transform());
Sigma::event::handler::FPSCamera theCamera(*bphys.getViewMover());
glsys.GetView()->Transform()->SetEuler(true);
glsys.GetView()->Transform()->SetMaxRotation(glm::vec3(45.0f,0,0));
glfwos.RegisterKeyboardEventHandler(&theCamera);
glfwos.RegisterMouseEventHandler(&theCamera);
theCamera.os = &glfwos;
// Sync bullet physics object with gl camera
///////////////////
// Configure GUI //
///////////////////
Sigma::event::handler::GUIController guicon;
guicon.SetGUI(webguisys.getComponent(100, Sigma::WebGUIView::getStaticComponentTypeName()));
glfwos.RegisterKeyboardEventHandler(&guicon);
glfwos.RegisterMouseEventHandler(&guicon);
// Call now to clear the delta after startup.
glfwos.GetDeltaTime();
{
Sigma::ALSound *als = (Sigma::ALSound *)alsys.getComponent(200, Sigma::ALSound::getStaticComponentTypeName());
if(als) {
als->Play(Sigma::PLAYBACK_LOOP);
}
}
enum FlashlightState {
FL_ON,
FL_TURNING_ON,
FL_OFF,
FL_TURNING_OFF
};
FlashlightState fs = FL_OFF;
while (!glfwos.Closing()) {
// Get time in ms, store it in seconds too
double deltaSec = glfwos.GetDeltaTime();
// Process input
if(glfwos.CheckKeyState(Sigma::event::KS_DOWN, GLFW_KEY_F)) {
if(fs==FL_OFF) {
fs=FL_TURNING_ON;
} else if (fs==FL_ON) {
fs=FL_TURNING_OFF;
}
}
if(glfwos.CheckKeyState(Sigma::event::KS_UP, GLFW_KEY_F)) {
if(fs==FL_TURNING_ON) {
// Enable flashlight
Sigma::SpotLight *spotlight = static_cast<Sigma::SpotLight *>(glsys.getComponent(151, Sigma::SpotLight::getStaticComponentTypeName()));
spotlight->enabled = true;
// Rotate flashlight up
// Enable spotlight
fs=FL_ON;
} else if (fs==FL_TURNING_OFF) {
// Disable spotlight
Sigma::SpotLight *spotlight = static_cast<Sigma::SpotLight *>(glsys.getComponent(151, Sigma::SpotLight::getStaticComponentTypeName()));
spotlight->enabled = false;
// Rotate flashlight down
// Disable flashlight
fs=FL_OFF;
}
}
///////////////////////
// Update subsystems //
///////////////////////
// Pass in delta time in seconds
bphys.Update(deltaSec);
webguisys.Update(deltaSec);
alsys.Update();
// Update the renderer and present
if (glsys.Update(deltaSec)) {
glfwos.SwapBuffers();
}
glfwos.OSMessageLoop();
}
CefShutdown();
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.