commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
a922cf7677993abd77ed92313b57afd61bce9281 | tools/transform_point_cloud.cpp | tools/transform_point_cloud.cpp | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, 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 copyright holder(s) 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.
*
* $Id$
*
*/
#include <pcl/PCLPointCloud2.h>
#include <pcl/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/common/transforms.h>
#include <cmath>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -trans dx,dy,dz = the translation (default: ");
print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
print_info (" -quat w,x,y,z = rotation as quaternion\n");
print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
print_info (" -scale x,y,z = scale each dimension with these values\n");
print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n");
print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
print_info (" Note: If a rotation is not specified, it will default to no rotation.\n");
print_info (" If redundant or conflicting transforms are specified, then:\n");
print_info (" -axisangle will override -quat\n");
print_info (" -matrix (3x3) will take override -axisangle and -quat\n");
print_info (" -matrix (4x4) will take override all other arguments\n");
}
void
printElapsedTimeAndNumberOfPoints (double t, int w, int h = 1)
{
print_info ("[done, "); print_value ("%g", t); print_info (" ms : ");
print_value ("%d", w*h); print_info (" points]\n");
}
bool
loadCloud (const std::string &filename, pcl::PCLPointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename PointT> void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
Eigen::Matrix4f &tform)
{
transformPointCloud (input, output, tform);
}
template <> void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <> void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
PointCloud<PointXYZRGBNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <typename PointT> void
transformPointCloud2AsType (const pcl::PCLPointCloud2 &input, pcl::PCLPointCloud2 &output,
Eigen::Matrix4f &tform)
{
PointCloud<PointT> cloud;
fromPCLPointCloud2 (input, cloud);
transformPointCloudHelper (cloud, cloud, tform);
toPCLPointCloud2 (cloud, output);
}
void
transformPointCloud2 (const pcl::PCLPointCloud2 &input, pcl::PCLPointCloud2 &output,
Eigen::Matrix4f &tform)
{
// Check for 'rgb' and 'normals' fields
bool has_rgb = false;
bool has_normals = false;
for (size_t i = 0; i < input.fields.size (); ++i)
{
if (input.fields[i].name.find("rgb") != std::string::npos)
has_rgb = true;
if (input.fields[i].name == "normal_x")
has_normals = true;
}
// Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
if (!has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZ> (input, output, tform);
else if (has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
else if (!has_rgb && has_normals)
transformPointCloud2AsType<PointNormal> (input, output, tform);
else // (has_rgb && has_normals)
transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}
void
compute (const pcl::PCLPointCloud2::ConstPtr &input, pcl::PCLPointCloud2 &output,
Eigen::Matrix4f &tform)
{
TicToc tt;
tt.tic ();
print_highlight ("Transforming ");
transformPointCloud2 (*input, output, tform);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
void
saveCloud (const std::string &filename, const pcl::PCLPointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
PCDWriter w;
w.writeBinaryCompressed (filename, output);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
template <typename T> void
multiply (pcl::PCLPointCloud2 &cloud, int field_offset, double multiplier)
{
T val;
memcpy (&val, &cloud.data[field_offset], sizeof (T));
val = static_cast<T> (val * static_cast<T> (multiplier));
memcpy (&cloud.data[field_offset], &val, sizeof (T));
}
void
scaleInPlace (pcl::PCLPointCloud2 &cloud, double* multiplier)
{
// Obtain the x, y, and z indices
int x_idx = pcl::getFieldIndex (cloud, "x");
int y_idx = pcl::getFieldIndex (cloud, "y");
int z_idx = pcl::getFieldIndex (cloud, "z");
Eigen::Array3i xyz_offset (cloud.fields[x_idx].offset, cloud.fields[y_idx].offset, cloud.fields[z_idx].offset);
for (uint32_t cp = 0; cp < cloud.width * cloud.height; ++cp)
{
// Assume all 3 fields are the same (XYZ)
assert ((cloud.fields[x_idx].datatype == cloud.fields[y_idx].datatype));
assert ((cloud.fields[x_idx].datatype == cloud.fields[z_idx].datatype));
switch (cloud.fields[x_idx].datatype)
{
case pcl::PCLPointField::INT8:
for (int i = 0; i < 3; ++i) multiply<int8_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::UINT8:
for (int i = 0; i < 3; ++i) multiply<uint8_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::INT16:
for (int i = 0; i < 3; ++i) multiply<int16_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::UINT16:
for (int i = 0; i < 3; ++i) multiply<uint16_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::INT32:
for (int i = 0; i < 3; ++i) multiply<int32_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::UINT32:
for (int i = 0; i < 3; ++i) multiply<uint32_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::FLOAT32:
for (int i = 0; i < 3; ++i) multiply<float> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::FLOAT64:
for (int i = 0; i < 3; ++i) multiply<double> (cloud, xyz_offset[i], multiplier[i]);
break;
}
xyz_offset += cloud.point_step;
}
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);
bool help = false;
parse_argument (argc, argv, "-h", help);
if (argc < 3 || help)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Initialize the transformation matrix
Eigen::Matrix4f tform;
tform.setIdentity ();
// Command line parsing
float dx, dy, dz;
std::vector<float> values;
if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
{
tform (0, 3) = dx;
tform (1, 3) = dy;
tform (2, 3) = dz;
}
if (parse_x_arguments (argc, argv, "-quat", values) > -1)
{
if (values.size () == 4)
{
const float& x = values[0];
const float& y = values[1];
const float& z = values[2];
const float& w = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
}
else
{
print_error ("Wrong number of values given (%lu): ", values.size ());
print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
}
}
if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
{
if (values.size () == 4)
{
const float& ax = values[0];
const float& ay = values[1];
const float& az = values[2];
const float& theta = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
}
else
{
print_error ("Wrong number of values given (%lu): ", values.size ());
print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
}
}
if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
{
if (values.size () == 9 || values.size () == 16)
{
int n = values.size () == 9 ? 3 : 4;
for (int r = 0; r < n; ++r)
for (int c = 0; c < n; ++c)
tform (r, c) = values[n*r+c];
}
else
{
print_error ("Wrong number of values given (%lu): ", values.size ());
print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
}
}
// Load the first file
pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the transform
pcl::PCLPointCloud2 output;
compute (cloud, output, tform);
// Check if a scaling parameter has been given
double divider[3];
if (parse_3x_arguments (argc, argv, "-scale", divider[0], divider[1], divider[2]) > -1)
{
print_highlight ("Scaling XYZ data with the following values: %f, %f, %f\n", divider[0], divider[1], divider[2]);
scaleInPlace (output, divider);
}
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
| /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, 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 copyright holder(s) 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.
*
* $Id$
*
*/
#include <pcl/PCLPointCloud2.h>
#include <pcl/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/common/transforms.h>
#include <cmath>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
void
printHelp (int, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -trans dx,dy,dz = the translation (default: ");
print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
print_info (" -quat x,y,z,w = rotation as quaternion\n");
print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
print_info (" -scale x,y,z = scale each dimension with these values\n");
print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n");
print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
print_info (" Note: If a rotation is not specified, it will default to no rotation.\n");
print_info (" If redundant or conflicting transforms are specified, then:\n");
print_info (" -axisangle will override -quat\n");
print_info (" -matrix (3x3) will take override -axisangle and -quat\n");
print_info (" -matrix (4x4) will take override all other arguments\n");
}
void
printElapsedTimeAndNumberOfPoints (double t, int w, int h = 1)
{
print_info ("[done, "); print_value ("%g", t); print_info (" ms : ");
print_value ("%d", w*h); print_info (" points]\n");
}
bool
loadCloud (const std::string &filename, pcl::PCLPointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename PointT> void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
Eigen::Matrix4f &tform)
{
transformPointCloud (input, output, tform);
}
template <> void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <> void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
PointCloud<PointXYZRGBNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <typename PointT> void
transformPointCloud2AsType (const pcl::PCLPointCloud2 &input, pcl::PCLPointCloud2 &output,
Eigen::Matrix4f &tform)
{
PointCloud<PointT> cloud;
fromPCLPointCloud2 (input, cloud);
transformPointCloudHelper (cloud, cloud, tform);
toPCLPointCloud2 (cloud, output);
}
void
transformPointCloud2 (const pcl::PCLPointCloud2 &input, pcl::PCLPointCloud2 &output,
Eigen::Matrix4f &tform)
{
// Check for 'rgb' and 'normals' fields
bool has_rgb = false;
bool has_normals = false;
for (size_t i = 0; i < input.fields.size (); ++i)
{
if (input.fields[i].name.find("rgb") != std::string::npos)
has_rgb = true;
if (input.fields[i].name == "normal_x")
has_normals = true;
}
// Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
if (!has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZ> (input, output, tform);
else if (has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
else if (!has_rgb && has_normals)
transformPointCloud2AsType<PointNormal> (input, output, tform);
else // (has_rgb && has_normals)
transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}
void
compute (const pcl::PCLPointCloud2::ConstPtr &input, pcl::PCLPointCloud2 &output,
Eigen::Matrix4f &tform)
{
TicToc tt;
tt.tic ();
print_highlight ("Transforming ");
transformPointCloud2 (*input, output, tform);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
void
saveCloud (const std::string &filename, const pcl::PCLPointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
PCDWriter w;
w.writeBinaryCompressed (filename, output);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
template <typename T> void
multiply (pcl::PCLPointCloud2 &cloud, int field_offset, double multiplier)
{
T val;
memcpy (&val, &cloud.data[field_offset], sizeof (T));
val = static_cast<T> (val * static_cast<T> (multiplier));
memcpy (&cloud.data[field_offset], &val, sizeof (T));
}
void
scaleInPlace (pcl::PCLPointCloud2 &cloud, double* multiplier)
{
// Obtain the x, y, and z indices
int x_idx = pcl::getFieldIndex (cloud, "x");
int y_idx = pcl::getFieldIndex (cloud, "y");
int z_idx = pcl::getFieldIndex (cloud, "z");
Eigen::Array3i xyz_offset (cloud.fields[x_idx].offset, cloud.fields[y_idx].offset, cloud.fields[z_idx].offset);
for (uint32_t cp = 0; cp < cloud.width * cloud.height; ++cp)
{
// Assume all 3 fields are the same (XYZ)
assert ((cloud.fields[x_idx].datatype == cloud.fields[y_idx].datatype));
assert ((cloud.fields[x_idx].datatype == cloud.fields[z_idx].datatype));
switch (cloud.fields[x_idx].datatype)
{
case pcl::PCLPointField::INT8:
for (int i = 0; i < 3; ++i) multiply<int8_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::UINT8:
for (int i = 0; i < 3; ++i) multiply<uint8_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::INT16:
for (int i = 0; i < 3; ++i) multiply<int16_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::UINT16:
for (int i = 0; i < 3; ++i) multiply<uint16_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::INT32:
for (int i = 0; i < 3; ++i) multiply<int32_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::UINT32:
for (int i = 0; i < 3; ++i) multiply<uint32_t> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::FLOAT32:
for (int i = 0; i < 3; ++i) multiply<float> (cloud, xyz_offset[i], multiplier[i]);
break;
case pcl::PCLPointField::FLOAT64:
for (int i = 0; i < 3; ++i) multiply<double> (cloud, xyz_offset[i], multiplier[i]);
break;
}
xyz_offset += cloud.point_step;
}
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);
bool help = false;
parse_argument (argc, argv, "-h", help);
if (argc < 3 || help)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Initialize the transformation matrix
Eigen::Matrix4f tform;
tform.setIdentity ();
// Command line parsing
float dx, dy, dz;
std::vector<float> values;
if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
{
tform (0, 3) = dx;
tform (1, 3) = dy;
tform (2, 3) = dz;
}
if (parse_x_arguments (argc, argv, "-quat", values) > -1)
{
if (values.size () == 4)
{
const float& x = values[0];
const float& y = values[1];
const float& z = values[2];
const float& w = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
}
else
{
print_error ("Wrong number of values given (%lu): ", values.size ());
print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
}
}
if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
{
if (values.size () == 4)
{
const float& ax = values[0];
const float& ay = values[1];
const float& az = values[2];
const float& theta = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
}
else
{
print_error ("Wrong number of values given (%lu): ", values.size ());
print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
}
}
if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
{
if (values.size () == 9 || values.size () == 16)
{
int n = values.size () == 9 ? 3 : 4;
for (int r = 0; r < n; ++r)
for (int c = 0; c < n; ++c)
tform (r, c) = values[n*r+c];
}
else
{
print_error ("Wrong number of values given (%lu): ", values.size ());
print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
}
}
// Load the first file
pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the transform
pcl::PCLPointCloud2 output;
compute (cloud, output, tform);
// Check if a scaling parameter has been given
double divider[3];
if (parse_3x_arguments (argc, argv, "-scale", divider[0], divider[1], divider[2]) > -1)
{
print_highlight ("Scaling XYZ data with the following values: %f, %f, %f\n", divider[0], divider[1], divider[2]);
scaleInPlace (output, divider);
}
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
| Fix error in print info of transform point cloud. | Fix error in print info of transform point cloud.
| C++ | bsd-3-clause | ipa-rmb/pcl,stefanbuettner/pcl,damienjadeduff/pcl,ipa-rmb/pcl,ipa-rmb/pcl,lebronzhang/pcl,lebronzhang/pcl,drmateo/pcl,damienjadeduff/pcl,drmateo/pcl,drmateo/pcl,lebronzhang/pcl,ipa-rmb/pcl,drmateo/pcl,stefanbuettner/pcl,damienjadeduff/pcl,ipa-rmb/pcl,stefanbuettner/pcl,lebronzhang/pcl,stefanbuettner/pcl,drmateo/pcl,damienjadeduff/pcl,stefanbuettner/pcl,lebronzhang/pcl,damienjadeduff/pcl |
300a961704d943ce8fa956632fd894122af58345 | elsa/in/k0005a.cc | elsa/in/k0005a.cc | // declaring variables and member functions with class name
// originally found in package bombermaze
struct S1 {
int S1::varName;
};
struct S2 {
int S2::funcName() {}
};
struct otherS { int funcName(); };
struct S3 {
//ERROR(1): int otherS::funcName() {}
};
| // declaring variables and member functions with class name
// originally found in package bombermaze
struct S1 {
int S1::varName;
};
struct S2 {
int S2::funcName() {}
};
struct otherS { int funcName(); };
struct S3 {
//ERROR(1): int otherS::funcName() {}
};
template <typename T>
struct S4 {
int S4<T>::varName;
};
template <typename T>
struct S5 {
int S5<T>::funcName() {}
};
| Add template version | Add template version
| C++ | bsd-3-clause | angavrilov/olmar,angavrilov/olmar,angavrilov/olmar,angavrilov/olmar |
89ac8c00b45569146e3c7cd68c5c0981617610e5 | akonadi/clients/akonadi/listcommand.cpp | akonadi/clients/akonadi/listcommand.cpp | /*
This file is part of Akonadi.
Copyright (c) 2006 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "listcommand.h"
#include "out.h"
#include <libakonadi/collectionlistjob.h>
#include <libakonadi/messagefetchjob.h>
#include <libakonadi/itemfetchjob.h>
#include <kmime/kmime_message.h>
ListCommand::ListCommand( const QString &path )
: mPath( path )
{
if ( mPath.isEmpty() ) mPath = "/";
}
void ListCommand::exec()
{
Akonadi::CollectionListJob collectionJob( mPath.toUtf8() );
if ( !collectionJob.exec() ) {
err() << "Error listing collection '" << mPath << "': "
<< collectionJob.errorText()
<< endl;
return;
} else {
foreach( Akonadi::Collection *collection, collectionJob.collections() ) {
out() << collection->name() << endl;
}
}
if ( mPath.indexOf( "/", 1 ) > 0 ) {
Akonadi::ItemFetchJob itemFetchJob( mPath.toUtf8() );
if ( !itemFetchJob.exec() ) {
err() << "Error listing items at '" << mPath << "': "
<< itemFetchJob.errorText()
<< endl;
} else {
foreach( Akonadi::Item *item, itemFetchJob.items() ) {
QString str;
str = "Item: " + item->reference().persistanceID();
if ( !item->reference().externalUrl().isEmpty() ) {
str += " [" + item->reference().externalUrl().toString() + ']';
}
if ( !item->flags().isEmpty() ) {
str += " ( ";
foreach( QByteArray flag, item->flags() ) {
str += flag + ' ';
}
str += ')';
}
str += " [" + item->mimeType() + ']';
out() << str << endl;
}
}
#if 0
Akonadi::MessageFetchJob messageJob( mPath.toUtf8() );
if ( !messageJob.exec() ) {
err() << "Error listing messages at '" << mPath << "': "
<< messageJob.errorText()
<< endl;
} else {
foreach( Akonadi::Message *m, messageJob.messages() ) {
KMime::Message *message = m->mime();
out() << "Subject: " << message->subject()->asUnicodeString() << endl;
}
}
#endif
}
}
| /*
This file is part of Akonadi.
Copyright (c) 2006 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "listcommand.h"
#include "out.h"
#include <libakonadi/collectionlistjob.h>
#include <libakonadi/messagefetchjob.h>
#include <libakonadi/itemfetchjob.h>
#include <kmime/kmime_message.h>
ListCommand::ListCommand( const QString &path )
: mPath( path )
{
if ( mPath.isEmpty() ) mPath = "/";
}
void ListCommand::exec()
{
Akonadi::CollectionListJob collectionJob( mPath.toUtf8() );
if ( !collectionJob.exec() ) {
err() << "Error listing collection '" << mPath << "': "
<< collectionJob.errorText()
<< endl;
return;
} else {
foreach( Akonadi::Collection *collection, collectionJob.collections() ) {
out() << collection->name() << endl;
}
}
if ( mPath.indexOf( "/", 1 ) > 0 ) {
Akonadi::ItemFetchJob itemFetchJob( mPath.toUtf8() );
if ( !itemFetchJob.exec() ) {
err() << "Error listing items at '" << mPath << "': "
<< itemFetchJob.errorText()
<< endl;
} else {
foreach( Akonadi::Item *item, itemFetchJob.items() ) {
QString str;
str = QLatin1String("Item: ") + QString::number( item->reference().persistanceID() );
if ( !item->reference().externalUrl().isEmpty() ) {
str += QLatin1String(" [") + item->reference().externalUrl().toString() + QLatin1Char(']');
}
if ( !item->flags().isEmpty() ) {
str += QLatin1String(" ( ");
foreach( QByteArray flag, item->flags() ) {
str += flag + QLatin1Char(' ');
}
str += QLatin1Char(')');
}
str += QLatin1String(" [") + item->mimeType() + QLatin1Char(']');
out() << str << endl;
}
}
#if 0
Akonadi::MessageFetchJob messageJob( mPath.toUtf8() );
if ( !messageJob.exec() ) {
err() << "Error listing messages at '" << mPath << "': "
<< messageJob.errorText()
<< endl;
} else {
foreach( Akonadi::Message *m, messageJob.messages() ) {
KMime::Message *message = m->mime();
out() << "Subject: " << message->subject()->asUnicodeString() << endl;
}
}
#endif
}
}
| fix output, some type errors would have been helpful here... | fix output, some type errors would have been helpful here...
svn path=/trunk/KDE/kdepim/; revision=602245
| C++ | lgpl-2.1 | lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi |
b2761ea7fb7cc90079d8d313a41b9bf031c4add1 | grune-json/grammar.cpp | grune-json/grammar.cpp | #include "grune-json/grune-json.hpp"
#include "grune/grammar.hpp"
using namespace grune;
json11::Json grune::to_json(const grammar& value)
{
return { };
}
bool grune::from_json(const json11::Json& js, grammar& )
{
return false;
}
| #include "grune-json/grune-json.hpp"
#include "grune/grammar.hpp"
using namespace grune;
using namespace json11;
Json grune::to_json(const grammar& value)
{
return Json::object {
{ "non_terminals", value.non_terminals() },
{ "terminals", value.terminals() },
{ "rules", value.productions() },
{ "start", value.start_symbol() }
};
}
bool grune::from_json(const Json& js, grammar& g)
{
g = {
js["non_terminals"].as<sequence>(),
js["terminals"].as<sequence>(),
js["rules"].as<production_list>(),
js["start"].as<symbol>()
};
return true;
}
| Add grammar serialization. | Add grammar serialization.
| C++ | mit | Fifty-Nine/grune |
d603886a08e68b25ceffa8ffcc334b41f60718ea | Library/Sources/Stroika/Foundation/Database/SQLite.cpp | Library/Sources/Stroika/Foundation/Database/SQLite.cpp | /*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/Format.h"
#include "../Debug/Trace.h"
#include "SQLite.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Debug;
using namespace Database;
using namespace Database::SQLite;
using namespace Execution;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#if qHasFeature_sqlite && defined (_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment (lib, "sqlite.lib")
#endif
#if qHasFeature_sqlite
/*
********************************************************************************
************************* SQLite::DB::Statement ********************************
********************************************************************************
*/
DB::Statement::Statement (sqlite3* db, const String& query)
{
RequireNotNull (db);
#if USE_NOISY_TRACE_IN_THIS_MODULE_
TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::Statement"));
DbgTrace (L"(db=%p,query='%s')", db, query.c_str ());
#endif
int rc = ::sqlite3_prepare_v2 (db, query.AsUTF8 ().c_str (), -1, &fStatementObj_, NULL);
if (rc != SQLITE_OK) {
Execution::Throw (StringException (Characters::Format (L"SQLite Error %s:", String::FromUTF8 (::sqlite3_errmsg (db)).c_str ())));
}
AssertNotNull (fStatementObj_);
fParamsCount_ = ::sqlite3_column_count (fStatementObj_);
for (unsigned int i = 0; i < fParamsCount_; ++i) {
fColNames_ += String::FromUTF8 (::sqlite3_column_name (fStatementObj_, i));
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"sqlite3_column_decltype(i) = %s", ::sqlite3_column_decltype (fStatementObj_, i) == nullptr ? L"{nullptr}" : String::FromUTF8 (::sqlite3_column_decltype (fStatementObj_, i)).c_str ());
#endif
// add VaroamtVa;ue"::Type list based on sqlite3_column_decltype
}
}
/// returns 'missing' on EOF, exception on error
auto DB::Statement::GetNextRow () -> Optional<RowType> {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::GetNextRow"));
#endif
// @todo redo with https://www.sqlite.org/c3ref/value.html
int rc;
AssertNotNull (fStatementObj_);
if (( rc = ::sqlite3_step (fStatementObj_)) == SQLITE_ROW)
{
RowType row;
for (unsigned int i = 0; i < fParamsCount_; ++i) {
// redo as sqlite3_column_text16
// @todo AND iether use value object or check INTERANL TYOPE - https://www.sqlite.org/c3ref/column_blob.html and return the right one - NULL, INTEGER, FLOAT, TEXT, BLOB
VariantValue v;
switch (::sqlite3_column_type (fStatementObj_, i)) {
case SQLITE_INTEGER: {
v = VariantValue (::sqlite3_column_int (fStatementObj_, i));
}
break;
case SQLITE_FLOAT: {
v = VariantValue (::sqlite3_column_double (fStatementObj_, i));
}
break;
case SQLITE_BLOB: {
#if 1
// this will work badly, so dont use!!!
AssertNotImplemented ();
v = VariantValue (String::FromUTF8 (reinterpret_cast<const char*> (::sqlite3_column_text (fStatementObj_, i))));
#else
// @todo - support this once we support BLOB in VariantValue
const void* sqlite3_column_blob(sqlite3_fStatementObj_*, int iCol);
int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
v = VariantValue (String::FromUTF8 (reinterpret_cast<const char*> (::sqlite3_column_text (fStatementObj_, i))));
#endif
}
break;
case SQLITE_NULL: {
// default to null value
}
break;
case SQLITE_TEXT: {
AssertNotNull (::sqlite3_column_text (fStatementObj_, i));
v = VariantValue (String::FromUTF8 (reinterpret_cast<const char*> (::sqlite3_column_text (fStatementObj_, i))));
}
break;
default: {
AssertNotReached ();
}
break;
}
row.Add (fColNames_[i], v);
}
return row;
}
return Optional<RowType> ();
}
DB::Statement::~Statement ()
{
AssertNotNull (fStatementObj_);
::sqlite3_finalize (fStatementObj_);
}
/*
********************************************************************************
********************************** SQLite::DB **********************************
********************************************************************************
*/
DB::DB (const String& experimentDBFullPath, const function<void(DB&)>& dbInitializer)
{
TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
// @todo - code cleanup!!!
int e;
if ((e = ::sqlite3_open_v2 ((L"file://" + experimentDBFullPath).AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_CANTOPEN) {
if ((e = ::sqlite3_open_v2 ((L"file://" + experimentDBFullPath).AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
try {
dbInitializer (*this);
}
catch (...) {
Verify (::sqlite3_close (fDB_) == SQLITE_OK);
Execution::ReThrow ();
}
}
}
else if (e != SQLITE_OK) {
Assert (fDB_ == nullptr);
// @todo add error string
Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
}
}
DB:: ~DB ()
{
AssertNotNull (fDB_);
Verify (::sqlite3_close (fDB_) == SQLITE_OK);
}
void DB::Exec (const String& cmd2Exec)
{
char* db_err {};
int e = ::sqlite3_exec (fDB_, cmd2Exec.AsUTF8 ().c_str (), NULL, 0, &db_err);
if (e != SQLITE_OK) {
if (db_err == nullptr or * db_err == '\0') {
DbgTrace (L"Failed doing sqllite command: %s", cmd2Exec.c_str ());
Execution::Throw (StringException (Characters::Format (L"SQLite Error %d", e)));
}
else {
Execution::Throw (StringException (Characters::Format (L"SQLite Error %d: %s", e, String::FromUTF8 (db_err).c_str ())));
}
}
}
#endif
| /*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/Format.h"
#include "../Debug/Trace.h"
#include "SQLite.h"
using namespace Stroika::Foundation;
using namespace Characters;
using namespace Debug;
using namespace Database;
using namespace Database::SQLite;
using namespace Execution;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#if qHasFeature_sqlite && defined (_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment (lib, "sqlite.lib")
#endif
#if qHasFeature_sqlite
/*
********************************************************************************
************************* SQLite::DB::Statement ********************************
********************************************************************************
*/
DB::Statement::Statement (sqlite3* db, const String& query)
{
RequireNotNull (db);
#if USE_NOISY_TRACE_IN_THIS_MODULE_
TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::Statement"));
DbgTrace (L"(db=%p,query='%s')", db, query.c_str ());
#endif
int rc = ::sqlite3_prepare_v2 (db, query.AsUTF8 ().c_str (), -1, &fStatementObj_, NULL);
if (rc != SQLITE_OK) {
Execution::Throw (StringException (Characters::Format (L"SQLite Error %s:", String::FromUTF8 (::sqlite3_errmsg (db)).c_str ())));
}
AssertNotNull (fStatementObj_);
fParamsCount_ = ::sqlite3_column_count (fStatementObj_);
for (unsigned int i = 0; i < fParamsCount_; ++i) {
fColNames_ += String::FromUTF8 (::sqlite3_column_name (fStatementObj_, i));
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"sqlite3_column_decltype(i) = %s", ::sqlite3_column_decltype (fStatementObj_, i) == nullptr ? L"{nullptr}" : String::FromUTF8 (::sqlite3_column_decltype (fStatementObj_, i)).c_str ());
#endif
// add VaroamtVa;ue"::Type list based on sqlite3_column_decltype
}
}
/// returns 'missing' on EOF, exception on error
auto DB::Statement::GetNextRow () -> Optional<RowType> {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::GetNextRow"));
#endif
// @todo redo with https://www.sqlite.org/c3ref/value.html
int rc;
AssertNotNull (fStatementObj_);
if (( rc = ::sqlite3_step (fStatementObj_)) == SQLITE_ROW)
{
RowType row;
for (unsigned int i = 0; i < fParamsCount_; ++i) {
// redo as sqlite3_column_text16
// @todo AND iether use value object or check INTERANL TYOPE - https://www.sqlite.org/c3ref/column_blob.html and return the right one - NULL, INTEGER, FLOAT, TEXT, BLOB
VariantValue v;
switch (::sqlite3_column_type (fStatementObj_, i)) {
case SQLITE_INTEGER: {
v = VariantValue (::sqlite3_column_int (fStatementObj_, i));
}
break;
case SQLITE_FLOAT: {
v = VariantValue (::sqlite3_column_double (fStatementObj_, i));
}
break;
case SQLITE_BLOB: {
const Byte* data = reinterpret_cast<const Byte*> (::sqlite3_column_blob (fStatementObj_, i));
size_t byteCount = static_cast<size_t> (::sqlite3_column_bytes (fStatementObj_, i));
v = VariantValue (Memory::BLOB (data, data + byteCount));
}
break;
case SQLITE_NULL: {
// default to null value
}
break;
case SQLITE_TEXT: {
AssertNotNull (::sqlite3_column_text (fStatementObj_, i));
v = VariantValue (String::FromUTF8 (reinterpret_cast<const char*> (::sqlite3_column_text (fStatementObj_, i))));
}
break;
default: {
AssertNotReached ();
}
break;
}
row.Add (fColNames_[i], v);
}
return row;
}
return Optional<RowType> ();
}
DB::Statement::~Statement ()
{
AssertNotNull (fStatementObj_);
::sqlite3_finalize (fStatementObj_);
}
/*
********************************************************************************
********************************** SQLite::DB **********************************
********************************************************************************
*/
DB::DB (const String& experimentDBFullPath, const function<void(DB&)>& dbInitializer)
{
TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
// @todo - code cleanup!!!
int e;
if ((e = ::sqlite3_open_v2 ((L"file://" + experimentDBFullPath).AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_CANTOPEN) {
if ((e = ::sqlite3_open_v2 ((L"file://" + experimentDBFullPath).AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
try {
dbInitializer (*this);
}
catch (...) {
Verify (::sqlite3_close (fDB_) == SQLITE_OK);
Execution::ReThrow ();
}
}
}
else if (e != SQLITE_OK) {
Assert (fDB_ == nullptr);
// @todo add error string
Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
}
}
DB:: ~DB ()
{
AssertNotNull (fDB_);
Verify (::sqlite3_close (fDB_) == SQLITE_OK);
}
void DB::Exec (const String& cmd2Exec)
{
char* db_err {};
int e = ::sqlite3_exec (fDB_, cmd2Exec.AsUTF8 ().c_str (), NULL, 0, &db_err);
if (e != SQLITE_OK) {
if (db_err == nullptr or * db_err == '\0') {
DbgTrace (L"Failed doing sqllite command: %s", cmd2Exec.c_str ());
Execution::Throw (StringException (Characters::Format (L"SQLite Error %d", e)));
}
else {
Execution::Throw (StringException (Characters::Format (L"SQLite Error %d: %s", e, String::FromUTF8 (db_err).c_str ())));
}
}
}
#endif
| Support BLOB (untested) in SQLite wrapper | Support BLOB (untested) in SQLite wrapper
| C++ | mit | SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika |
a661ccf6ae539dd29fc45cf3e7fbf92003a25e56 | include/target/linux/syscalls/io.cc | include/target/linux/syscalls/io.cc | #ifndef SYSCALL_IO_H_
#define SYSCALL_IO_H_
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#include <errno.h>
#define stdin 0
#define stdout 1
#define stderr 2
struct linux_dirent {
unsigned long d_ino;
unsigned long d_off;
unsigned short d_reclen;
char d_name[1];
};
/*
* System calls defined in this file.
*/
namespace Syscall {
SYSTEM_CALL int open(const char *, int);
SYSTEM_CALL int create(const char *, int, mode_t);
SYSTEM_CALL int dup(int);
SYSTEM_CALL int dup2(int, int);
#if SYSCALL_EXISTS(dup3)
SYSTEM_CALL int dup3(int, int, int);
#endif
SYSTEM_CALL off_t lseek(int, off_t, int);
SYSTEM_CALL ssize_t read(int, void *, size_t);
SYSTEM_CALL ssize_t write(int, const void *, size_t);
SYSTEM_CALL int fsync(int);
SYSTEM_CALL int poll(struct pollfd *, nfds_t, int);
SYSTEM_CALL int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
SYSTEM_CALL int getdents(unsigned int, struct linux_dirent *, unsigned int);
SYSTEM_CALL ssize_t readlink(const char *, char *, size_t);
SYSTEM_CALL int fstat(int, struct stat *);
SYSTEM_CALL int stat(int, struct stat *);
SYSTEM_CALL int unlink(const char *);
SYSTEM_CALL int close(int);
SYSTEM_CALL int mkdir(const char *, mode_t);
SYSTEM_CALL int rmdir(const char *);
SYSTEM_CALL int getcwd(char *, size_t);
SYSTEM_CALL int chdir(const char *);
SYSTEM_CALL int fchdir(int fd);
SYSTEM_CALL int chroot(const char *);
SYSTEM_CALL int fcntl(int, int);
SYSTEM_CALL int fcntl(int, int, void *);
SYSTEM_CALL
int open(const char *path, int flags)
{
return DO_SYSCALL(openat, AT_FDCWD, path, flags);
}
SYSTEM_CALL
int create(const char *path, int flags, mode_t mode)
{
return DO_SYSCALL(openat, AT_FDCWD, path, flags | O_CREAT, mode);
}
SYSTEM_CALL
int dup(int oldfd)
{
return DO_SYSCALL(dup, oldfd);
}
/* Some architectures deprecated dup2 in favor of dup3. */
#if SYSCALL_EXISTS(dup3)
SYSTEM_CALL
int dup3(int oldfd, int newfd, int flags)
{
return DO_SYSCALL(dup3, oldfd, newfd, flags);
}
#endif
SYSTEM_CALL
int dup2(int filedes, int filedes2)
{
#if !SYSCALL_EXISTS(dup2) && SYSCALL_EXISTS(dup3)
return dup3(filedes, filedes2, 0);
#else
return DO_SYSCALL(dup2, filedes, filedes2);
#endif
}
SYSTEM_CALL
off_t lseek(int fd, off_t offset, int whence)
{
return DO_SYSCALL(lseek, fd, offset, whence);
}
SYSTEM_CALL
ssize_t read(int fd, void *buf, size_t count)
{
return DO_SYSCALL(read, fd, buf, count);
}
SYSTEM_CALL
ssize_t write(int fd, const void *buf, size_t count)
{
return DO_SYSCALL(write, fd, buf, count);
}
SYSTEM_CALL
int fsync(int fildes)
{
return DO_SYSCALL(fsync, fildes);
}
SYSTEM_CALL
int poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
return DO_SYSCALL(poll, fds, nfds, timeout);
}
SYSTEM_CALL
int select(int nfds, fd_set *read_fds, fd_set *write_fds, fd_set *except_fds, struct timeval *timeout)
{
#if defined(__mips__) || defined(__arm__)
return DO_SYSCALL(_newselect, nfds, read_fds, write_fds, except_fds, timeout);
#else
return DO_SYSCALL(select, nfds, read_fds, write_fds, except_fds, timeout);
#endif
}
SYSTEM_CALL
int getdents(unsigned int fd, struct linux_dirent *dirp, unsigned int count)
{
return DO_SYSCALL(getdents, fd, dirp, count);
}
SYSTEM_CALL
ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
{
return DO_SYSCALL(readlink, pathname, buf, bufsiz);
}
SYSTEM_CALL
int fstat(int fd, struct stat *buf)
{
return DO_SYSCALL(fstat, fd, buf);
}
SYSTEM_CALL
int stat(int fd, struct stat *buf)
{
return DO_SYSCALL(stat, fd, buf);
}
SYSTEM_CALL
int unlink(const char *path)
{
return DO_SYSCALL(unlink, path);
}
SYSTEM_CALL
int close(int fd)
{
return DO_SYSCALL(close, fd);
}
SYSTEM_CALL
int mkdir(const char *path, mode_t mode)
{
return DO_SYSCALL(mkdir, path, mode);
}
SYSTEM_CALL
int rmdir(const char *path)
{
return DO_SYSCALL(rmdir, path);
}
SYSTEM_CALL
int getcwd(char *buf, size_t size)
{
return DO_SYSCALL(getcwd, buf, size);
}
SYSTEM_CALL
int chdir(const char *path)
{
return DO_SYSCALL(chdir, path);
}
SYSTEM_CALL
int fchdir(int fd)
{
return DO_SYSCALL(fchdir, fd);
}
SYSTEM_CALL
int chroot(const char *path)
{
return DO_SYSCALL(chroot, path);
}
SYSTEM_CALL
int fcntl(int fd, int cmd)
{
return DO_SYSCALL(fcntl, fd, cmd);
}
/*
* The best solution would be an 'auto' arg here.
* But gcc has a bug and cannot generate the syscall correctly.
* Keep it like this until gcc is fixed (probably never), or
* until gcc support is definitely dropped in favor of clang.
*/
SYSTEM_CALL
int fcntl(int fd, int cmd, void *arg)
{
return DO_SYSCALL(fcntl, fd, cmd, arg);
}
}
#endif
| #ifndef SYSCALL_IO_H_
#define SYSCALL_IO_H_
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#include <errno.h>
struct linux_dirent {
unsigned long d_ino;
unsigned long d_off;
unsigned short d_reclen;
char d_name[1];
};
/*
* System calls defined in this file.
*/
namespace Syscall {
SYSTEM_CALL int open(const char *, int);
SYSTEM_CALL int create(const char *, int, mode_t);
SYSTEM_CALL int dup(int);
SYSTEM_CALL int dup2(int, int);
#if SYSCALL_EXISTS(dup3)
SYSTEM_CALL int dup3(int, int, int);
#endif
SYSTEM_CALL off_t lseek(int, off_t, int);
SYSTEM_CALL ssize_t read(int, void *, size_t);
SYSTEM_CALL ssize_t write(int, const void *, size_t);
SYSTEM_CALL int fsync(int);
SYSTEM_CALL int poll(struct pollfd *, nfds_t, int);
SYSTEM_CALL int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
SYSTEM_CALL int getdents(unsigned int, struct linux_dirent *, unsigned int);
SYSTEM_CALL ssize_t readlink(const char *, char *, size_t);
SYSTEM_CALL int fstat(int, struct stat *);
SYSTEM_CALL int stat(int, struct stat *);
SYSTEM_CALL int unlink(const char *);
SYSTEM_CALL int close(int);
SYSTEM_CALL int mkdir(const char *, mode_t);
SYSTEM_CALL int rmdir(const char *);
SYSTEM_CALL int getcwd(char *, size_t);
SYSTEM_CALL int chdir(const char *);
SYSTEM_CALL int fchdir(int fd);
SYSTEM_CALL int chroot(const char *);
SYSTEM_CALL int fcntl(int, int);
SYSTEM_CALL int fcntl(int, int, void *);
SYSTEM_CALL
int open(const char *path, int flags)
{
return DO_SYSCALL(openat, AT_FDCWD, path, flags);
}
SYSTEM_CALL
int create(const char *path, int flags, mode_t mode)
{
return DO_SYSCALL(openat, AT_FDCWD, path, flags | O_CREAT, mode);
}
SYSTEM_CALL
int dup(int oldfd)
{
return DO_SYSCALL(dup, oldfd);
}
/* Some architectures deprecated dup2 in favor of dup3. */
#if SYSCALL_EXISTS(dup3)
SYSTEM_CALL
int dup3(int oldfd, int newfd, int flags)
{
return DO_SYSCALL(dup3, oldfd, newfd, flags);
}
#endif
SYSTEM_CALL
int dup2(int filedes, int filedes2)
{
#if !SYSCALL_EXISTS(dup2) && SYSCALL_EXISTS(dup3)
return dup3(filedes, filedes2, 0);
#else
return DO_SYSCALL(dup2, filedes, filedes2);
#endif
}
SYSTEM_CALL
off_t lseek(int fd, off_t offset, int whence)
{
return DO_SYSCALL(lseek, fd, offset, whence);
}
SYSTEM_CALL
ssize_t read(int fd, void *buf, size_t count)
{
return DO_SYSCALL(read, fd, buf, count);
}
SYSTEM_CALL
ssize_t write(int fd, const void *buf, size_t count)
{
return DO_SYSCALL(write, fd, buf, count);
}
SYSTEM_CALL
int fsync(int fildes)
{
return DO_SYSCALL(fsync, fildes);
}
SYSTEM_CALL
int poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
return DO_SYSCALL(poll, fds, nfds, timeout);
}
SYSTEM_CALL
int select(int nfds, fd_set *read_fds, fd_set *write_fds, fd_set *except_fds, struct timeval *timeout)
{
#if defined(__mips__) || defined(__arm__)
return DO_SYSCALL(_newselect, nfds, read_fds, write_fds, except_fds, timeout);
#else
return DO_SYSCALL(select, nfds, read_fds, write_fds, except_fds, timeout);
#endif
}
SYSTEM_CALL
int getdents(unsigned int fd, struct linux_dirent *dirp, unsigned int count)
{
return DO_SYSCALL(getdents, fd, dirp, count);
}
SYSTEM_CALL
ssize_t readlink(const char *pathname, char *buf, size_t bufsiz)
{
return DO_SYSCALL(readlink, pathname, buf, bufsiz);
}
SYSTEM_CALL
int fstat(int fd, struct stat *buf)
{
return DO_SYSCALL(fstat, fd, buf);
}
SYSTEM_CALL
int stat(int fd, struct stat *buf)
{
return DO_SYSCALL(stat, fd, buf);
}
SYSTEM_CALL
int unlink(const char *path)
{
return DO_SYSCALL(unlink, path);
}
SYSTEM_CALL
int close(int fd)
{
return DO_SYSCALL(close, fd);
}
SYSTEM_CALL
int mkdir(const char *path, mode_t mode)
{
return DO_SYSCALL(mkdir, path, mode);
}
SYSTEM_CALL
int rmdir(const char *path)
{
return DO_SYSCALL(rmdir, path);
}
SYSTEM_CALL
int getcwd(char *buf, size_t size)
{
return DO_SYSCALL(getcwd, buf, size);
}
SYSTEM_CALL
int chdir(const char *path)
{
return DO_SYSCALL(chdir, path);
}
SYSTEM_CALL
int fchdir(int fd)
{
return DO_SYSCALL(fchdir, fd);
}
SYSTEM_CALL
int chroot(const char *path)
{
return DO_SYSCALL(chroot, path);
}
SYSTEM_CALL
int fcntl(int fd, int cmd)
{
return DO_SYSCALL(fcntl, fd, cmd);
}
/*
* The best solution would be an 'auto' arg here.
* But gcc has a bug and cannot generate the syscall correctly.
* Keep it like this until gcc is fixed (probably never), or
* until gcc support is definitely dropped in favor of clang.
*/
SYSTEM_CALL
int fcntl(int fd, int cmd, void *arg)
{
return DO_SYSCALL(fcntl, fd, cmd, arg);
}
}
#endif
| remove unused defines | linux/syscalls/io: remove unused defines
| C++ | mit | gdelugre/shell-factory,gdelugre/shell-factory,gdelugre/shell-factory |
ef8ba75194cfcd3838c8fedbcb327e2478a0982d | include/target/posix/pico/socket.cc | include/target/posix/pico/socket.cc | #ifndef POSIX_PICO_SOCKET_H_
#define POSIX_PICO_SOCKET_H_
#include <sys/socket.h>
#include <sys/un.h>
namespace Pico {
namespace Network {
template <AddressType>
struct Address;
template <>
struct Address<AddressType::UNIX>
{
char *path;
};
using UnixAddress = Address<AddressType::UNIX>;
FUNCTION
uint16_t host_to_net(uint16_t port)
{
return CPU::to_big_endian(port);
}
template <AddressType>
struct Sockaddr;
template <>
struct Sockaddr<AddressType::IPV4>
{
static constexpr int family = AF_INET;
using type = struct sockaddr_in;
FUNCTION
struct sockaddr_in pack(IpAddress const ip, uint16_t port, size_t& size)
{
struct sockaddr_in addr;
addr.sin_family = family;
addr.sin_port = host_to_net(port);
addr.sin_addr.s_addr = ip.value;
size = sizeof(addr);
return addr;
}
};
template <>
struct Sockaddr<AddressType::IPV6>
{
static constexpr int family = AF_INET6;
using type = struct sockaddr_in6;
FUNCTION
struct sockaddr_in6 pack(IpAddress6 const ip, uint16_t port, size_t& size)
{
struct sockaddr_in6 addr;
addr.sin6_flowinfo = 0;
addr.sin6_family = AF_INET6;
addr.sin6_port = host_to_net(port);
Memory::copy(&addr.sin6_addr.s6_addr, &ip, sizeof(ip));
size = sizeof(addr);
return addr;
}
};
template <>
struct Sockaddr<AddressType::UNIX>
{
static constexpr int family = AF_UNIX;
using type = struct sockaddr_un;
FUNCTION
struct sockaddr_un pack(UnixAddress const unixaddr, size_t& size)
{
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
String::copy(addr.sun_path, unixaddr.path, sizeof(addr.sun_path));
size = sizeof(addr.sun_family) + String::length(unixaddr.path);
return addr;
}
};
METHOD
ssize_t SocketIO::in(void *buf, size_t count)
{
return Syscall::recv(fd, buf, count, MSG_WAITALL);
}
METHOD
ssize_t SocketIO::out(const void *buf, size_t count)
{
// Use write(2) instead of send(2) since it takes 3 arguments instead of 4.
// This produces slightly smaller code.
return Syscall::write(fd, buf, count);
}
CONSTRUCTOR
Socket::Socket(int domain, int type, int protocol)
{
int fd = Syscall::socket(domain, type, protocol);
if ( Target::is_error(fd) )
fd = Target::invalid_handle;
io = SocketIO(fd);
}
CONSTRUCTOR
SequencedSocket::SequencedSocket(int domain, int protocol) : Socket(domain, SOCK_SEQPACKET, protocol) {}
CONSTRUCTOR
DatagramSocket::DatagramSocket(int domain, int protocol) : Socket(domain, SOCK_DGRAM, protocol) {}
CONSTRUCTOR
UdpSocket::UdpSocket() : DatagramSocket(AF_INET, IPPROTO_IP) {}
CONSTRUCTOR
Udp6Socket::Udp6Socket() : DatagramSocket(AF_INET6, IPPROTO_IP) {}
CONSTRUCTOR
StreamSocket::StreamSocket(int domain, int protocol) : Socket(domain, SOCK_STREAM, protocol) {}
CONSTRUCTOR
TcpSocket::TcpSocket() : StreamSocket(AF_INET, IPPROTO_IP) {}
CONSTRUCTOR
Tcp6Socket::Tcp6Socket() : StreamSocket(AF_INET6, IPPROTO_IP) {}
CONSTRUCTOR
UnixStreamSocket::UnixStreamSocket() : StreamSocket(AF_UNIX, 0) {}
METHOD
int Socket::get(int level, int optname, void *val, unsigned *len)
{
return Syscall::getsockopt(this->file_desc(), level, optname, val, len);
}
METHOD
int Socket::set(int level, int optname, void *val, unsigned len)
{
return Syscall::setsockopt(this->file_desc(), level, optname, val, len);
}
template <AddressType T>
METHOD
int Socket::bind(Address<T> addr)
{
size_t addr_len;
auto bind_addr = Sockaddr<T>::pack(addr, addr_len);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), addr_len);
}
template <AddressType T>
METHOD
int Socket::bind(Address<T> addr, uint16_t port, bool reuse_addr)
{
if ( reuse_addr )
{
int option = 1;
set(SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
}
size_t addr_len;
auto bind_addr = Sockaddr<T>::pack(addr, port, addr_len);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), addr_len);
}
template <AddressType T>
METHOD
int Socket::connect(Address<T> addr)
{
static_assert(T == AddressType::UNIX || T == AddressType::UNIX_ABSTRACT,
"This method only supports UNIX address sockets.");
size_t addr_len;
auto serv_addr = Sockaddr<T>::pack(addr, addr_len);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), addr_len);
}
template <AddressType T>
METHOD
int Socket::connect(Address<T> addr, uint16_t port)
{
size_t addr_len;
auto serv_addr = Sockaddr<T>::pack(addr, port, addr_len);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), addr_len);
}
METHOD
int StreamSocket::listen(int backlog)
{
return Syscall::listen(this->file_desc(), backlog);
}
template <bool Fork>
METHOD
StreamSocket StreamSocket::accept()
{
do {
int client_fd = Syscall::accept(this->file_desc(), nullptr, 0);
if ( Target::is_error(client_fd) )
continue;
if ( Fork )
{
if ( Syscall::fork() == 0 )
return StreamSocket(client_fd);
else
Syscall::close(client_fd);
}
else
return StreamSocket(client_fd);
} while ( Fork );
}
METHOD
int UnixStreamSocket::send_io(SingleIO const& io)
{
char dummy = 0;
int fd = io.file_desc();
struct msghdr msg = {};
char buf[CMSG_SPACE(sizeof(fd))] = {0};
struct iovec iov = { .iov_base = &dummy, .iov_len = sizeof(dummy) };
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
*((int *) CMSG_DATA(cmsg)) = fd;
return Syscall::sendmsg(this->file_desc(), &msg, 0);
}
METHOD
SingleIO UnixStreamSocket::recv_io()
{
char dummy;
int fd = Target::invalid_handle;
struct msghdr msg = {};
char buf[CMSG_SPACE(sizeof(fd))] = {0};
struct iovec iov = { .iov_base = &dummy, .iov_len = sizeof(dummy) };
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
if ( Syscall::recvmsg(this->file_desc(), &msg, 0) == -1 )
return SingleIO(fd);
for ( struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
cmsg != nullptr;
cmsg = CMSG_NXTHDR(&msg, cmsg) )
{
if ( cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS )
{
fd = *((int *) CMSG_DATA(cmsg));
break;
}
}
return SingleIO(fd);
}
}
}
#endif
| #ifndef POSIX_PICO_SOCKET_H_
#define POSIX_PICO_SOCKET_H_
#include <sys/socket.h>
#include <sys/un.h>
namespace Pico {
namespace Network {
template <AddressType>
struct Address;
template <>
struct Address<AddressType::UNIX>
{
char *path;
};
using UnixAddress = Address<AddressType::UNIX>;
FUNCTION
uint16_t host_to_net(uint16_t port)
{
return CPU::to_big_endian(port);
}
template <AddressType>
struct Sockaddr;
template <>
struct Sockaddr<AddressType::IPV4>
{
static constexpr int family = AF_INET;
using type = struct sockaddr_in;
FUNCTION
struct sockaddr_in pack(IpAddress const ip, uint16_t port, size_t& size)
{
struct sockaddr_in addr;
addr.sin_family = family;
addr.sin_port = host_to_net(port);
addr.sin_addr.s_addr = ip.value;
size = sizeof(addr);
return addr;
}
};
template <>
struct Sockaddr<AddressType::IPV6>
{
static constexpr int family = AF_INET6;
using type = struct sockaddr_in6;
FUNCTION
struct sockaddr_in6 pack(IpAddress6 const ip, uint16_t port, size_t& size)
{
struct sockaddr_in6 addr;
addr.sin6_flowinfo = 0;
addr.sin6_family = AF_INET6;
addr.sin6_port = host_to_net(port);
Memory::copy(&addr.sin6_addr.s6_addr, &ip, sizeof(ip));
size = sizeof(addr);
return addr;
}
};
template <>
struct Sockaddr<AddressType::UNIX>
{
static constexpr int family = AF_UNIX;
using type = struct sockaddr_un;
FUNCTION
struct sockaddr_un pack(UnixAddress const unixaddr, size_t& size)
{
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
String::copy(addr.sun_path, unixaddr.path, sizeof(addr.sun_path));
size = sizeof(addr.sun_family) + String::length(unixaddr.path);
return addr;
}
};
METHOD
ssize_t SocketIO::in(void *buf, size_t count)
{
return Syscall::recv(fd, buf, count, MSG_WAITALL);
}
METHOD
ssize_t SocketIO::out(const void *buf, size_t count)
{
// Use write(2) instead of send(2) since it takes 3 arguments instead of 4.
// This produces slightly smaller code.
return Syscall::write(fd, buf, count);
}
CONSTRUCTOR
Socket::Socket(int domain, int type, int protocol)
{
int fd = Syscall::socket(domain, type, protocol);
if ( Target::is_error(fd) )
fd = Target::invalid_handle;
io = SocketIO(fd);
}
CONSTRUCTOR
SequencedSocket::SequencedSocket(int domain, int protocol) : Socket(domain, SOCK_SEQPACKET, protocol) {}
CONSTRUCTOR
DatagramSocket::DatagramSocket(int domain, int protocol) : Socket(domain, SOCK_DGRAM, protocol) {}
CONSTRUCTOR
UdpSocket::UdpSocket() : DatagramSocket(AF_INET, IPPROTO_IP) {}
CONSTRUCTOR
Udp6Socket::Udp6Socket() : DatagramSocket(AF_INET6, IPPROTO_IP) {}
CONSTRUCTOR
StreamSocket::StreamSocket(int domain, int protocol) : Socket(domain, SOCK_STREAM, protocol) {}
CONSTRUCTOR
TcpSocket::TcpSocket() : StreamSocket(AF_INET, IPPROTO_IP) {}
CONSTRUCTOR
Tcp6Socket::Tcp6Socket() : StreamSocket(AF_INET6, IPPROTO_IP) {}
CONSTRUCTOR
UnixStreamSocket::UnixStreamSocket() : StreamSocket(AF_UNIX, 0) {}
METHOD
int Socket::get(int level, int optname, void *val, unsigned *len)
{
return Syscall::getsockopt(this->file_desc(), level, optname, val, len);
}
METHOD
int Socket::set(int level, int optname, void *val, unsigned len)
{
return Syscall::setsockopt(this->file_desc(), level, optname, val, len);
}
template <AddressType T>
METHOD
int Socket::bind(Address<T> addr)
{
size_t addr_len;
auto bind_addr = Sockaddr<T>::pack(addr, addr_len);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), addr_len);
}
template <AddressType T>
METHOD
int Socket::bind(Address<T> addr, uint16_t port, bool reuse_addr)
{
if ( reuse_addr )
{
int option = 1;
set(SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
}
size_t addr_len;
auto bind_addr = Sockaddr<T>::pack(addr, port, addr_len);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), addr_len);
}
template <AddressType T>
METHOD
int Socket::connect(Address<T> addr)
{
size_t addr_len;
auto serv_addr = Sockaddr<T>::pack(addr, addr_len);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), addr_len);
}
template <AddressType T>
METHOD
int Socket::connect(Address<T> addr, uint16_t port)
{
size_t addr_len;
auto serv_addr = Sockaddr<T>::pack(addr, port, addr_len);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), addr_len);
}
METHOD
int StreamSocket::listen(int backlog)
{
return Syscall::listen(this->file_desc(), backlog);
}
template <bool Fork>
METHOD
StreamSocket StreamSocket::accept()
{
do {
int client_fd = Syscall::accept(this->file_desc(), nullptr, 0);
if ( Target::is_error(client_fd) )
continue;
if ( Fork )
{
if ( Syscall::fork() == 0 )
return StreamSocket(client_fd);
else
Syscall::close(client_fd);
}
else
return StreamSocket(client_fd);
} while ( Fork );
}
METHOD
int UnixStreamSocket::send_io(SingleIO const& io)
{
char dummy = 0;
int fd = io.file_desc();
struct msghdr msg = {};
char buf[CMSG_SPACE(sizeof(fd))] = {0};
struct iovec iov = { .iov_base = &dummy, .iov_len = sizeof(dummy) };
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
*((int *) CMSG_DATA(cmsg)) = fd;
return Syscall::sendmsg(this->file_desc(), &msg, 0);
}
METHOD
SingleIO UnixStreamSocket::recv_io()
{
char dummy;
int fd = Target::invalid_handle;
struct msghdr msg = {};
char buf[CMSG_SPACE(sizeof(fd))] = {0};
struct iovec iov = { .iov_base = &dummy, .iov_len = sizeof(dummy) };
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
if ( Syscall::recvmsg(this->file_desc(), &msg, 0) == -1 )
return SingleIO(fd);
for ( struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
cmsg != nullptr;
cmsg = CMSG_NXTHDR(&msg, cmsg) )
{
if ( cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS )
{
fd = *((int *) CMSG_DATA(cmsg));
break;
}
}
return SingleIO(fd);
}
}
}
#endif
| remove static_assert | posix/pico: remove static_assert
| C++ | mit | gdelugre/shell-factory,gdelugre/shell-factory,gdelugre/shell-factory |
d72401262ccbea98610bf56c5fa4f5b22fe3ced2 | kernel/src/bs_kernel_ston.cpp | kernel/src/bs_kernel_ston.cpp | // This file is part of BlueSky
//
// BlueSky 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.
//
// BlueSky is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with BlueSky; if not, see <http://www.gnu.org/licenses/>.
//
// C++ Implementation: bs_kernel_ston
//
// Description:
//
//
// Author: Гагарин Александр Владимирович <[email protected]>, (C) 2008
//
#include "bs_kernel.h"
#include "thread_pool.h"
#include "bs_report.h"
#include "bs_log_scribers.h"
#include "bs_kernel_tools.h"
//#define LOKI_CLASS_LEVEL_THREADING
#include "loki/Singleton.h"
using namespace Loki;
using namespace std;
namespace blue_sky { namespace bs_private {
static bool kernel_alive = false;
/*-----------------------------------------------------------------------------
* Specific logging system wrappers
*-----------------------------------------------------------------------------*/
struct bs_log_wrapper : public bs_log
{
bs_log_wrapper ()
{
if (kernel_alive)
{
register_signals ();
}
this->add_channel (sp_channel (new bs_channel (OUT_LOG)));
this->add_channel (sp_channel (new bs_channel (ERR_LOG)));
char *c_dir = NULL;
if (!(c_dir = getenv("BS_KERNEL_DIR")))
c_dir = (char *)".";
this->get_locked (OUT_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::cout_scriber ("COUT")));
this->get_locked (OUT_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::file_scriber ("FILE", string(c_dir) + string("/blue_sky.log"), ios::out|ios::app)));
this->get_locked (ERR_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::cout_scriber ("COUT")));
this->get_locked (ERR_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::file_scriber ("FILE", string(c_dir) + string("/errors.log"), ios::out|ios::app)));
this->get_locked (OUT_LOG, __FILE__, __LINE__) << output_time;
this->get_locked (ERR_LOG, __FILE__, __LINE__) << output_time;
}
//static bool &
//kernel_dead ()
//{
// static bool kernel_dead_ = false;
// return kernel_dead_;
//}
bs_log &
get_log ()
{
return *this;
}
void
register_signals ()
{
this->add_signal (BS_SIGNAL_RANGE (bs_log));
}
};
struct thread_log_wrapper : public thread_log
{
thread_log_wrapper ()
{
}
thread_log &
get_log ()
{
return *this;
}
void
register_signals ()
{
}
//static bool &
//kernel_dead ()
//{
// static bool kernel_dead_ = false;
// return kernel_dead_;
//}
};
/// @brief Wrapper allowing to do some initialization on first give_kernel()::Instance() call
/// just after the kernel class is created
struct wrapper_kernel {
kernel k_;
kernel& (wrapper_kernel::*ref_fun_)();
static void kernel_cleanup();
// constructor
wrapper_kernel()
: ref_fun_(&wrapper_kernel::initial_kernel_getter)
{
kernel_alive = true;
}
// normal getter - just returns kernel reference
kernel& usual_kernel_getter() {
return k_;
}
// when kernel reference is obtained for the first time
kernel& initial_kernel_getter() {
// first switch to usual getter to avoid infinite constructor recursion during load_plugins()
ref_fun_ = &wrapper_kernel::usual_kernel_getter;
// initialize kernel
k_.init();
#ifdef BS_AUTOLOAD_PLUGINS
// load plugins
k_.LoadPlugins();
#endif
#ifdef BSPY_EXPORTING
// if we build with Python support
// register function that cleans up kernel
// when Python interpreter exits
Py_AtExit(&kernel_cleanup);
#endif
// return reference
return k_;
}
kernel& k_ref() {
return (this->*ref_fun_)();
}
~wrapper_kernel() {
// signal that it is destroyed
kernel_alive = false;
}
};
typedef SingletonHolder < bs_log_wrapper, CreateUsingNew, PhoenixSingleton > bs_log_holder;
typedef SingletonHolder < thread_log_wrapper, CreateUsingNew, PhoenixSingleton > thread_log_holder;
} // namespace bs_private
/*-----------------------------------------------------------------------------
* kernel signleton instantiation
*-----------------------------------------------------------------------------*/
//! multithreaded kernel singleton - disables
//typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,
// DefaultLifetime, ClassLevelLockable > kernel_holder;
// kernel itself is fully multithreaded so we can use simple singleton
// typedef SingletonHolder< bs_private::wrapper_kernel > kernel_holder;
//kernel singletone - master, fabs die after kernel dies
typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,
FollowIntoDeath::With< DefaultLifetime >::AsMasterLifetime > kernel_holder;
template< >
BS_API kernel& singleton< kernel >::Instance()
{
//cout << "give_kernel.Instance() entered" << endl;
return kernel_holder::Instance().k_ref();
}
void bs_private::wrapper_kernel::kernel_cleanup() {
BS_KERNEL.cleanup();
}
//! thread pool singleton
typedef SingletonHolder< blue_sky::worker_thread_pool, CreateUsingNew,
FollowIntoDeath::AfterMaster< kernel_holder >::IsDestroyed > wtp_holder;
typedef singleton< worker_thread_pool > give_wtp;
template< >
worker_thread_pool& singleton< worker_thread_pool >::Instance() {
return wtp_holder::Instance();
}
// void kernel::add_task(const blue_sky::sp_com& task)
// {
// give_wtp::Instance().add_command(task);
// }
/*-----------------------------------------------------------------------------
* log singletons instantiation
*-----------------------------------------------------------------------------*/
typedef singleton <bs_log> bs_log_singleton;
typedef singleton <thread_log> thread_log_singleton;
template <>
bs_log &
singleton <bs_log>::Instance()
{
return bs_private::bs_log_holder::Instance().get_log ();
}
template <>
thread_log &
singleton <thread_log>::Instance ()
{
return bs_private::thread_log_holder::Instance ().get_log ();
}
bs_log &
kernel::get_log ()
{
return bs_log_singleton::Instance ();
}
thread_log &
kernel::get_tlog ()
{
return thread_log_singleton::Instance ();
}
} // namespace blue_sky
| // This file is part of BlueSky
//
// BlueSky 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.
//
// BlueSky is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with BlueSky; if not, see <http://www.gnu.org/licenses/>.
//
// C++ Implementation: bs_kernel_ston
//
// Description:
//
//
// Author: Гагарин Александр Владимирович <[email protected]>, (C) 2008
//
#include "bs_kernel.h"
#include "thread_pool.h"
#include "bs_report.h"
#include "bs_log_scribers.h"
#include "bs_kernel_tools.h"
//#define LOKI_CLASS_LEVEL_THREADING
#include "loki/Singleton.h"
using namespace Loki;
using namespace std;
namespace {
using namespace blue_sky;
/*-----------------------------------------------------------------------------
* Specific logging system wrappers
*-----------------------------------------------------------------------------*/
struct bs_log_wrapper : public bs_log
{
static bool kernel_alive;
bs_log_wrapper ()
{
if (kernel_alive)
{
register_signals ();
}
this->add_channel (sp_channel (new bs_channel (OUT_LOG)));
this->add_channel (sp_channel (new bs_channel (ERR_LOG)));
char *c_dir = NULL;
if (!(c_dir = getenv("BS_KERNEL_DIR")))
c_dir = (char *)".";
this->get_locked (OUT_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::cout_scriber ("COUT")));
this->get_locked (OUT_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::file_scriber ("FILE", string(c_dir) + string("/blue_sky.log"), ios::out|ios::app)));
this->get_locked (ERR_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::cout_scriber ("COUT")));
this->get_locked (ERR_LOG, __FILE__, __LINE__).get_channel ()->attach(sp_stream(new log::detail::file_scriber ("FILE", string(c_dir) + string("/errors.log"), ios::out|ios::app)));
this->get_locked (OUT_LOG, __FILE__, __LINE__) << output_time;
this->get_locked (ERR_LOG, __FILE__, __LINE__) << output_time;
}
//static bool &
//kernel_dead ()
//{
// static bool kernel_dead_ = false;
// return kernel_dead_;
//}
bs_log &
get_log ()
{
return *this;
}
void
register_signals ()
{
this->add_signal (BS_SIGNAL_RANGE (bs_log));
}
};
bool bs_log_wrapper::kernel_alive = false;
struct thread_log_wrapper : public thread_log
{
thread_log_wrapper ()
{
}
thread_log &
get_log ()
{
return *this;
}
void
register_signals ()
{
}
//static bool &
//kernel_dead ()
//{
// static bool kernel_dead_ = false;
// return kernel_dead_;
//}
};
typedef SingletonHolder < bs_log_wrapper, CreateUsingNew, PhoenixSingleton > bs_log_holder;
typedef SingletonHolder < thread_log_wrapper, CreateUsingNew, PhoenixSingleton > thread_log_holder;
} // eof hidden namespace
namespace blue_sky {
namespace bs_private {
//static bool kernel_alive = false;
/// @brief Wrapper allowing to do some initialization on first give_kernel()::Instance() call
/// just after the kernel class is created
struct wrapper_kernel {
kernel k_;
kernel& (wrapper_kernel::*ref_fun_)();
static void kernel_cleanup();
// constructor
wrapper_kernel()
: ref_fun_(&wrapper_kernel::initial_kernel_getter)
{
bs_log_wrapper::kernel_alive = true;
}
// normal getter - just returns kernel reference
kernel& usual_kernel_getter() {
return k_;
}
// when kernel reference is obtained for the first time
kernel& initial_kernel_getter() {
// first switch to usual getter to avoid infinite constructor recursion during load_plugins()
ref_fun_ = &wrapper_kernel::usual_kernel_getter;
// initialize kernel
k_.init();
#ifdef BS_AUTOLOAD_PLUGINS
// load plugins
k_.LoadPlugins();
#endif
#ifdef BSPY_EXPORTING
// if we build with Python support
// register function that cleans up kernel
// when Python interpreter exits
//Py_AtExit(&kernel_cleanup);
#endif
// return reference
return k_;
}
kernel& k_ref() {
return (this->*ref_fun_)();
}
~wrapper_kernel() {
// signal that it is destroyed
bs_log_wrapper::kernel_alive = false;
}
};
} // eof bs_private namespace
/*-----------------------------------------------------------------------------
* kernel signleton instantiation
*-----------------------------------------------------------------------------*/
//! multithreaded kernel singleton - disables
//typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,
// DefaultLifetime, ClassLevelLockable > kernel_holder;
// kernel itself is fully multithreaded so we can use simple singleton
// typedef SingletonHolder< bs_private::wrapper_kernel > kernel_holder;
//kernel singletone - master, fabs die after kernel dies
typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,
FollowIntoDeath::With< DefaultLifetime >::AsMasterLifetime > kernel_holder;
template< >
BS_API kernel& singleton< kernel >::Instance()
{
//cout << "give_kernel.Instance() entered" << endl;
return kernel_holder::Instance().k_ref();
}
void bs_private::wrapper_kernel::kernel_cleanup() {
BS_KERNEL.cleanup();
}
//! thread pool singleton
typedef SingletonHolder< blue_sky::worker_thread_pool, CreateUsingNew,
FollowIntoDeath::AfterMaster< kernel_holder >::IsDestroyed > wtp_holder;
typedef singleton< worker_thread_pool > give_wtp;
template< >
worker_thread_pool& singleton< worker_thread_pool >::Instance() {
return wtp_holder::Instance();
}
// void kernel::add_task(const blue_sky::sp_com& task)
// {
// give_wtp::Instance().add_command(task);
// }
/*-----------------------------------------------------------------------------
* log singletons instantiation
*-----------------------------------------------------------------------------*/
typedef singleton <bs_log> bs_log_singleton;
typedef singleton <thread_log> thread_log_singleton;
template< >
bs_log& singleton< bs_log >::Instance()
{
return bs_log_holder::Instance().get_log();
}
template< >
thread_log& singleton< thread_log >::Instance()
{
return thread_log_holder::Instance().get_log();
}
bs_log& kernel::get_log()
{
return bs_log_singleton::Instance();
}
thread_log& kernel::get_tlog()
{
return thread_log_singleton::Instance();
}
} // namespace blue_sky
| bring back changes to kernel ston, but don't register cleanup function at Python interpreter exit | KERNEL: bring back changes to kernel ston, but don't register cleanup
function at Python interpreter exit
Causing problems in Windows
| C++ | mpl-2.0 | uentity/bluesky,uentity/bluesky,uentity/bluesky,uentity/bluesky,uentity/bluesky |
46baed916455aec73435891f81f80ed988aeeaf9 | kernel/src/python/py_node.cpp | kernel/src/python/py_node.cpp | /// @file
/// @author uentity
/// @date 22.04.2019
/// @brief BS node Python bindings
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/
#include <bs/python/tree.h>
#include <bs/python/container_iterator.h>
#include <boost/uuid/uuid_io.hpp>
#include <pybind11/functional.h>
#include <pybind11/chrono.h>
NAMESPACE_BEGIN(blue_sky::python)
using namespace tree;
/*-----------------------------------------------------------------------------
* hidden details
*-----------------------------------------------------------------------------*/
NAMESPACE_BEGIN()
// helpers to omit code duplication
// ------- contains
template<Key K>
bool contains(const node& N, std::string key) {
return N.index(std::move(key), K).has_value();
}
bool contains_link(const node& N, const link& l) {
return N.index(l.id()).has_value();
}
bool contains_obj(const node& N, const sp_obj& obj) {
return N.index(obj->id(), Key::OID).has_value();
}
// ------- find
template<Key K, bool Throw = true>
auto find(const node& N, std::string key) -> link {
if(auto r = N.find(std::move(key), K))
return r;
if constexpr(Throw) {
py::gil_scoped_acquire();
std::string msg = "Node doesn't contain link ";
switch(K) {
default:
case Key::ID:
msg += "with ID = "; break;
case Key::OID:
msg += "to object with ID = "; break;
case Key::Name:
msg += "with name = "; break;
case Key::Type:
msg += "with type = "; break;
}
throw py::key_error(msg + key);
}
return {};
}
template<bool Throw = true>
link find_obj(const node& N, const sp_obj& obj) {
return find<Key::OID, Throw>(N, obj->id());
}
auto find_by_idx(const node& N, long idx) {
// support for Pythonish indexing from both ends
if(auto positive_idx = idx < 0 ? N.size() + idx : std::size_t(idx); positive_idx < N.size())
return N.find(positive_idx);
py::gil_scoped_acquire();
throw py::key_error("Index out of bounds");
}
// ------- index
template<Key K>
auto index(const node& N, std::string key) -> std::size_t {
if(auto i = N.index(std::move(key), K)) return *i;
py::gil_scoped_acquire();
throw py::index_error();
}
auto index_link(const node& N, const link& l) {
if(auto i = N.index(l.id())) return *i;
py::gil_scoped_acquire();
throw py::index_error();
}
auto index_obj(const node& N, const sp_obj& obj) {
if(auto i = N.index(obj->id(), Key::OID)) return *i;
py::gil_scoped_acquire();
throw py::index_error();
}
// ------- deep search
template<Key K>
auto deep_search(const node& N, std::string key) -> link {
return N.deep_search(std::move(key), K);
}
auto deep_search_obj(const node& N, const sp_obj& obj) {
return N.deep_search(obj->id(), Key::OID);
}
// ------- equal_range
template<Key K>
auto equal_range(const node& N, std::string key) -> links_v {
return N.equal_range(std::move(key), K);
//py::gil_scoped_acquire();
//return make_container_iterator(std::move(res));
}
// ------- erase
template<Key K>
void erase(node& N, const std::string& key) {
N.erase(key, K);
}
void erase_link(node& N, const link& l) {
N.erase(l.id());
}
void erase_obj(node& N, const sp_obj& obj) {
N.erase(obj->id(), Key::OID);
}
void erase_idx(node& N, const long idx) {
// support for Pythonish indexing from both ends
if(std::size_t(std::abs(idx)) > N.size()) {
py::gil_scoped_acquire();
throw py::key_error("Index out of bounds");
}
N.erase(idx < 0 ? N.size() + idx : idx);
}
NAMESPACE_END() // hidden ns
void py_bind_node(py::module& m) {
///////////////////////////////////////////////////////////////////////////////
// Node
//
auto node_pyface = py::class_<node, objbase, std::shared_ptr<node>>(m, "node")
BSPY_EXPORT_DEF(node)
.def(py::init<>())
.def("__len__", &node::size, nogil)
// [FIXME] segfaults if `gil_scoped_release` is applied as call guard
.def("__iter__", [](const node& N) {
py::gil_scoped_release();
auto res = N.leafs();
return make_container_iterator(std::move(res));
})
.def("leafs", &node::leafs, "Key"_a = Key::AnyOrder, "Return snapshot of node content", nogil)
// check by link ID
.def("__contains__", &contains_link, "link"_a)
.def("contains", &contains_link, "link"_a, "Check if node contains given link")
.def("__contains__", &contains<Key::ID>, "lid"_a)
.def("contains", &contains<Key::ID>, "lid"_a, "Check if node contains link with given ID")
// ... by object
.def("__contains__", &contains_obj, "obj"_a)
.def("contains", &contains_obj, "obj"_a, "Check if node contains link to given object")
// check by link name
.def("contains_name", &contains<Key::Name>,
"link_name"_a, "Check if node contains link with given name")
// check by object ID
.def("contains_oid", &contains<Key::OID>,
"oid"_a, "Check if node contains link to object with given ID")
// check by object type
.def("contains_type", &contains<Key::Type>,
"obj_type_id"_a, "Check if node contain links to objects of given type")
// get item by int index
.def("__getitem__", [](const node& N, const long idx) {
return find_by_idx(N, idx);
}, "link_idx"_a, nogil)
// search by link ID
.def("__getitem__", &find<Key::ID>, "lid"_a, nogil)
.def("find", &find<Key::ID, false>, "lid"_a, "Find link with given ID", nogil)
// search by object instance
.def("__getitem__", &find_obj<>, "obj"_a, nogil)
.def("find", &find_obj<false>, "obj"_a, "Find link to given object", nogil)
// search by object ID
.def("find_oid", &find<Key::OID, false>, "oid"_a, "Find link to object with given ID", nogil)
// search by link name
.def("find_name", &find<Key::Name, false>, "link_name"_a, "Find link with given name", nogil)
// obtain index in custom order from link ID
.def("index", &index<Key::ID>, "lid"_a, "Find index of link with given ID", nogil)
// ...from link itself
.def("index", &index_link, "link"_a, "Find index of given link", nogil)
// ... from object
.def("index", &index_obj, "obj"_a, "Find index of link to given object", nogil)
// ... from OID
.def("index_oid", &index<Key::OID>, "oid"_a, "Find index of link to object with given ID", nogil)
// ... from link name
.def("index_name", &index<Key::Name>, "name"_a, "Find index of link with given name", nogil)
// deep search by object
.def("deep_search", &deep_search_obj, "obj"_a, "Deep search for link to given object", nogil)
// deep search by link ID
.def("deep_search", &deep_search<Key::ID>, "lid"_a, "Deep search for link with given ID", nogil)
// deep search by link name
.def("deep_search_name", &deep_search<Key::Name>, "link_name"_a,
"Deep search for link with given name", nogil)
// deep search by object ID
.def("deep_search_oid", &deep_search<Key::OID>, "oid"_a,
"Deep search for link to object with given ID", nogil)
// deep serach by specified key type
.def("deep_search", py::overload_cast<std::string, Key>(&node::deep_search, py::const_),
"key"_a, "key_meaning"_a, "Deep search by key with specified treatment", nogil)
// deep equal range
.def("deep_equal_range", &node::deep_equal_range,
"key"_a, "key_meaning"_a, "Deep search all links with given key & treatment", nogil)
.def("equal_range", &equal_range<Key::Name>, "link_name"_a, nogil)
.def("equal_range_oid", &equal_range<Key::OID>, "OID"_a, nogil)
.def("equal_type", &equal_range<Key::Type>, "obj_type_id"_a, nogil)
// insert given link
.def("insert", [](node& N, link l, InsertPolicy pol = InsertPolicy::AllowDupNames) {
return N.insert(std::move(l), pol).second;
}, "link"_a, "pol"_a = InsertPolicy::AllowDupNames, "Insert given link", nogil)
// insert link at given index
.def("insert", [](node& N, link l, const long idx, InsertPolicy pol = InsertPolicy::AllowDupNames) {
return N.insert(std::move(l), idx, pol).second;
}, "link"_a, "idx"_a, "pol"_a = InsertPolicy::AllowDupNames, "Insert link at given index", nogil)
// insert hard link to given object
.def("insert", [](node& N, std::string name, sp_obj obj, InsertPolicy pol = InsertPolicy::AllowDupNames) {
return N.insert(std::move(name), std::move(obj), pol).second;
}, "name"_a, "obj"_a, "pol"_a = InsertPolicy::AllowDupNames,
"Insert hard link to given object", nogil)
.def("insert", [](node& N, links_v ls, InsertPolicy pol) {
return N.insert(std::move(ls), pol);
}, "ls"_a, "pol"_a = InsertPolicy::AllowDupNames, "insert bunch of links at once", nogil)
// erase by given index
.def("__delitem__", &erase_idx, "idx"_a, nogil)
.def("erase", &erase_idx, "idx"_a, "Erase link with given index", nogil)
// erase given link
.def("__delitem__", &erase_link, "link"_a, nogil)
.def("erase", &erase_link, "link"_a, "Erase given link", nogil)
// erase by given link ID
.def("__delitem__", &erase<Key::ID>, "lid"_a, nogil)
.def("erase", &erase<Key::ID>, "lid"_a, "Erase link with given ID", nogil)
// erase by object instance
.def("__delitem__", &erase_obj, "obj"_a, nogil)
.def("erase", &erase_obj, "obj"_a, "Erase links to given object", nogil)
// erase by link name
.def("erase_name", &erase<Key::Name>, "link_name"_a, "Erase links with given name", nogil)
// erase by OID
.def("erase_oid", &erase<Key::OID>, "oid"_a, "Erase links to object with given ID", nogil)
// erase by obj type
.def("erase_type", &erase<Key::Type>, "obj_type_id"_a, "Erase all links pointing to objects of given type", nogil)
// misc container-related functions
.def_property_readonly("size", &node::size, nogil)
.def_property_readonly("empty", &node::empty, nogil)
.def("clear", &node::clear, "Clears all node contents", nogil)
.def("keys", &node::skeys, "key_type"_a = Key::ID, "ordering"_a = Key::AnyOrder, nogil)
.def("ikeys", &node::ikeys, "ordering"_a = Key::AnyOrder, nogil)
// link rename
.def("rename", py::overload_cast<std::string, std::string>(&node::rename),
"old_name"_a, "new_name"_a, "Rename all links with given old_name", nogil)
// by index offset
.def("rename", py::overload_cast<std::size_t, std::string>(&node::rename),
"idx"_a, "new_name"_a, "Rename link with given index", nogil)
// by ID
.def("rename", py::overload_cast<lid_type, std::string>(&node::rename),
"lid"_a, "new_name"_a, "Rename link with given ID", nogil)
.def("rearrange", py::overload_cast<lids_v>(&node::rearrange), "new_order"_a,
"Apply custom order to node")
.def("rearrange", py::overload_cast<std::vector<std::size_t>>(&node::rearrange), "new_order"_a,
"Apply custom order to node")
// misc API
.def_property_readonly("handle", &node::handle,
"Returns a single link that owns this node in overall tree"
)
.def("propagate_owner", &node::propagate_owner, "deep"_a = false,
"Set owner of all contained links to this node (if deep, fix owner in entire subtree)"
)
// events subscrition
.def("subscribe", &node::subscribe, "event_cb"_a, "events"_a = Event::All, nogil)
.def_static("unsubscribe", &node::unsubscribe, "event_cb_id"_a)
.def("disconnect", &node::disconnect, "deep"_a = true, "Stop receiving messages from tree", nogil)
;
// [TODO] remove it later (added for compatibility)
node_pyface.attr("Key") = m.attr("Key");
node_pyface.attr("InsertPolicy") = m.attr("InsertPolicy");
}
NAMESPACE_END(blue_sky::python)
| /// @file
/// @author uentity
/// @date 22.04.2019
/// @brief BS node Python bindings
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/
#include <bs/python/tree.h>
#include <bs/python/container_iterator.h>
#include <boost/uuid/uuid_io.hpp>
#include <pybind11/functional.h>
#include <pybind11/chrono.h>
NAMESPACE_BEGIN(blue_sky::python)
using namespace tree;
/*-----------------------------------------------------------------------------
* hidden details
*-----------------------------------------------------------------------------*/
NAMESPACE_BEGIN()
// helpers to omit code duplication
// ------- contains
template<Key K>
bool contains(const node& N, std::string key) {
return N.index(std::move(key), K).has_value();
}
bool contains_link(const node& N, const link& l) {
return N.index(l.id()).has_value();
}
bool contains_obj(const node& N, const sp_obj& obj) {
return N.index(obj->id(), Key::OID).has_value();
}
// ------- find
template<bool Throw = true>
auto find(const node& N, std::string key, Key meaning) -> link {
if(auto r = N.find(std::move(key), meaning))
return r;
if constexpr(Throw) {
py::gil_scoped_acquire();
std::string msg = "Node doesn't contain link ";
switch(meaning) {
default:
case Key::ID:
msg += "with ID = "; break;
case Key::OID:
msg += "to object with ID = "; break;
case Key::Name:
msg += "with name = "; break;
case Key::Type:
msg += "with type = "; break;
}
throw py::key_error(msg + key);
}
return {};
}
template<Key K, bool Throw = true>
auto find(const node& N, std::string key) -> link {
return find<Throw>(N, std::move(key), K);
}
template<bool Throw = true>
link find_obj(const node& N, const sp_obj& obj) {
return find<Throw>(N, obj->id(), Key::OID);
}
auto find_by_idx(const node& N, long idx) {
// support for Pythonish indexing from both ends
if(auto positive_idx = idx < 0 ? N.size() + idx : std::size_t(idx); positive_idx < N.size())
return N.find(positive_idx);
py::gil_scoped_acquire();
throw py::key_error("Index out of bounds");
}
// ------- index
// [NOTE] don't throw by default
template<Key K, bool Throw = false>
auto index(const node& N, std::string key) -> py::int_ {
if(auto i = N.index(std::move(key), K))
return *i;
if constexpr(Throw) {
py::gil_scoped_acquire();
throw py::index_error();
}
else return py::none();
}
auto index_obj(const node& N, const sp_obj& obj) {
return index<Key::OID, false>(N, obj->id());
}
auto index_link(const node& N, const link& l) {
return N.index(l.id());
}
// ------- deep search
template<Key K>
auto deep_search(const node& N, std::string key) -> link {
return N.deep_search(std::move(key), K);
}
auto deep_search_obj(const node& N, const sp_obj& obj) {
return N.deep_search(obj->id(), Key::OID);
}
// ------- erase
template<Key K>
void erase(node& N, const std::string& key) {
N.erase(key, K);
}
void erase_link(node& N, const link& l) {
N.erase(l.id());
}
void erase_obj(node& N, const sp_obj& obj) {
N.erase(obj->id(), Key::OID);
}
void erase_idx(node& N, const long idx) {
// support for Pythonish indexing from both ends
if(std::size_t(std::abs(idx)) > N.size()) {
py::gil_scoped_acquire();
throw py::key_error("Index out of bounds");
}
N.erase(idx < 0 ? N.size() + idx : idx);
}
NAMESPACE_END() // hidden ns
void py_bind_node(py::module& m) {
///////////////////////////////////////////////////////////////////////////////
// Node
//
auto node_pyface = py::class_<node, objbase, std::shared_ptr<node>>(m, "node")
BSPY_EXPORT_DEF(node)
.def(py::init<>())
.def("__len__", &node::size, nogil)
// [FIXME] segfaults if `gil_scoped_release` is applied as call guard
.def("__iter__", [](const node& N) {
py::gil_scoped_release();
auto res = N.leafs();
return make_container_iterator(std::move(res));
})
.def("leafs", &node::leafs, "Key"_a = Key::AnyOrder, "Return snapshot of node content", nogil)
// check by link ID
.def("__contains__", &contains_link, "link"_a)
.def("contains", &contains_link, "link"_a, "Check if node contains given link")
.def("__contains__", &contains<Key::ID>, "lid"_a)
.def("contains", &contains<Key::ID>, "lid"_a, "Check if node contains link with given ID")
// ... by object
.def("__contains__", &contains_obj, "obj"_a)
.def("contains", &contains_obj, "obj"_a, "Check if node contains link to given object")
// check by link name
.def("contains_name", &contains<Key::Name>,
"link_name"_a, "Check if node contains link with given name")
// check by object ID
.def("contains_oid", &contains<Key::OID>,
"oid"_a, "Check if node contains link to object with given ID")
// check by object type
.def("contains_type", &contains<Key::Type>,
"obj_type_id"_a, "Check if node contain links to objects of given type")
// get item by int index
.def("__getitem__", &find_by_idx, "link_idx"_a, nogil)
// search by link ID
.def("__getitem__", &find<Key::ID>, "lid"_a, nogil)
.def("find", &find<Key::ID, false>, "lid"_a, "Find link with given ID", nogil)
// search by object instance
.def("__getitem__", &find_obj, "obj"_a, nogil)
.def("find", &find_obj<false>, "obj"_a, "Find link to given object", nogil)
// search by string key & key treatment
.def("find", py::overload_cast<std::string, Key>(&node::find, py::const_),
"key"_a, "key_meaning"_a, "Find link by key with specified treatment", nogil)
// obtain index in custom order from link ID
.def("index", &index<Key::ID>, "lid"_a, "Find index of link with given ID", nogil)
// ...from link itself
.def("index", &index_link, "link"_a, "Find index of given link", nogil)
// ... from object
.def("index", &index_obj, "obj"_a, "Find index of link to given object", nogil)
// ... from string key with specified treatment
.def("index", py::overload_cast<std::string, Key>(&node::index, py::const_),
"key"_a, "key_meaning"_a, "Find index of link with specified key and treatment", nogil)
// deep search by object
.def("deep_search", &deep_search_obj, "obj"_a, "Deep search for link to given object", nogil)
// deep search by link ID
.def("deep_search", &deep_search<Key::ID>, "lid"_a, "Deep search for link with given ID", nogil)
// deep serach by specified key type
.def("deep_search", py::overload_cast<std::string, Key>(&node::deep_search, py::const_),
"key"_a, "key_meaning"_a, "Deep search by key with specified treatment", nogil)
// equal range
.def("equal_range", &node::equal_range,
"key"_a, "key_meaning"_a = Key::Name, "Find all leafs with given key", nogil)
.def("deep_equal_range", &node::deep_equal_range,
"key"_a, "key_meaning"_a, "Deep search all links with given key & treatment", nogil)
// insert given link
.def("insert", [](node& N, link l, InsertPolicy pol = InsertPolicy::AllowDupNames) {
return N.insert(std::move(l), pol).second;
}, "link"_a, "pol"_a = InsertPolicy::AllowDupNames, "Insert given link", nogil)
// insert link at given index
.def("insert", [](node& N, link l, const long idx, InsertPolicy pol = InsertPolicy::AllowDupNames) {
return N.insert(std::move(l), idx, pol).second;
}, "link"_a, "idx"_a, "pol"_a = InsertPolicy::AllowDupNames, "Insert link at given index", nogil)
// insert hard link to given object
.def("insert", [](node& N, std::string name, sp_obj obj, InsertPolicy pol = InsertPolicy::AllowDupNames) {
return N.insert(std::move(name), std::move(obj), pol).second;
}, "name"_a, "obj"_a, "pol"_a = InsertPolicy::AllowDupNames,
"Insert hard link to given object", nogil)
.def("insert", [](node& N, links_v ls, InsertPolicy pol) {
return N.insert(std::move(ls), pol);
}, "ls"_a, "pol"_a = InsertPolicy::AllowDupNames, "insert bunch of links at once", nogil)
// erase by given index
.def("__delitem__", &erase_idx, "idx"_a, nogil)
.def("erase", &erase_idx, "idx"_a, "Erase link with given index", nogil)
// erase given link
.def("__delitem__", &erase_link, "link"_a, nogil)
.def("erase", &erase_link, "link"_a, "Erase given link", nogil)
// erase by given link ID
.def("__delitem__", &erase<Key::ID>, "lid"_a, nogil)
.def("erase", &erase<Key::ID>, "lid"_a, "Erase link with given ID", nogil)
// erase by object instance
.def("__delitem__", &erase_obj, "obj"_a, nogil)
.def("erase", &erase_obj, "obj"_a, "Erase links to given object", nogil)
// generic erase by key & meaning
.def("erase", py::overload_cast<std::string, Key>(&node::erase),
"key"_a, "key_meaning"_a = Key::Name, "Erase all leafs with given key", nogil)
// misc container-related functions
.def_property_readonly("size", &node::size, nogil)
.def_property_readonly("empty", &node::empty, nogil)
.def("clear", &node::clear, "Clears all node contents", nogil)
.def("keys", &node::skeys, "key_type"_a = Key::ID, "ordering"_a = Key::AnyOrder, nogil)
.def("ikeys", &node::ikeys, "ordering"_a = Key::AnyOrder, nogil)
// link rename
.def("rename", py::overload_cast<std::string, std::string>(&node::rename),
"old_name"_a, "new_name"_a, "Rename all links with given old_name", nogil)
// by index offset
.def("rename", py::overload_cast<std::size_t, std::string>(&node::rename),
"idx"_a, "new_name"_a, "Rename link with given index", nogil)
// by ID
.def("rename", py::overload_cast<lid_type, std::string>(&node::rename),
"lid"_a, "new_name"_a, "Rename link with given ID", nogil)
.def("rearrange", py::overload_cast<lids_v>(&node::rearrange), "new_order"_a,
"Apply custom order to node")
.def("rearrange", py::overload_cast<std::vector<std::size_t>>(&node::rearrange), "new_order"_a,
"Apply custom order to node")
// misc API
.def_property_readonly("handle", &node::handle,
"Returns a single link that owns this node in overall tree"
)
.def("propagate_owner", &node::propagate_owner, "deep"_a = false,
"Set owner of all contained links to this node (if deep, fix owner in entire subtree)"
)
// events subscrition
.def("subscribe", &node::subscribe, "event_cb"_a, "events"_a = Event::All, nogil)
.def_static("unsubscribe", &node::unsubscribe, "event_cb_id"_a)
.def("disconnect", &node::disconnect, "deep"_a = true, "Stop receiving messages from tree", nogil)
;
// [TODO] remove it later (added for compatibility)
node_pyface.attr("Key") = m.attr("Key");
node_pyface.attr("InsertPolicy") = m.attr("InsertPolicy");
}
NAMESPACE_END(blue_sky::python)
| update bindings to be in line with C++ `node` class | python/node: update bindings to be in line with C++ `node` class
Remove binded overloads with key-related postfixes `find_name()`,
`find_oid()`, etc.
| C++ | mpl-2.0 | uentity/blue-sky-re,uentity/blue-sky-re,uentity/blue-sky-re |
f9d9770a41b219f15c9dd46bd83cbf3d5b05bd2f | src/webextension.cc | src/webextension.cc | #include <dbus/dbus-glib.h>
#include <webkit2/webkit-web-extension.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <string.h>
#include "dbus.h"
#include "utils.h"
static GDBusConnection* connection;
static void dispatch_ignore_event(WebKitWebPage* page, gchar* eventName, const gchar* uri) {
gchar* ignoreName = g_strconcat("r", eventName, NULL);
WebKitDOMDocument* document = webkit_web_page_get_dom_document(page);
WebKitDOMDOMWindow* window = webkit_dom_document_get_default_view(document);
GError* error = NULL;
WebKitDOMEvent* event = webkit_dom_document_create_event(document, "KeyboardEvent", &error);
g_object_unref(document);
if (error != NULL) {
g_printerr("Cannot create event in dispatch_ignore_event: %s\n", error->message);
g_error_free(error);
return;
}
webkit_dom_keyboard_event_init_keyboard_event(
(WebKitDOMKeyboardEvent*)event, ignoreName, FALSE, TRUE,
window, uri, 0, FALSE, FALSE, FALSE, FALSE, FALSE
);
webkit_dom_event_target_dispatch_event(WEBKIT_DOM_EVENT_TARGET(window), event, &error);
g_object_unref(window);
g_object_unref(event);
if (error != NULL) {
g_printerr("Cannot dispatch event in dispatch_ignore_event: %s\n", error->message);
g_error_free(error);
}
}
static gboolean web_page_send_request(WebKitWebPage* page, WebKitURIRequest* request, WebKitURIResponse* redirected_response, gpointer data) {
GError* error = NULL;
// ignore redirected requests - it's transparent to the user
if (redirected_response != NULL) {
return FALSE;
}
gchar* eventName = (gchar*)data;
const char* uri = webkit_uri_request_get_uri(request);
SoupMessageHeaders* headers = webkit_uri_request_get_http_headers(request);
GVariantDict dictIn;
GVariant* variantIn = soup_headers_to_gvariant_dict(headers);
g_variant_dict_init(&dictIn, variantIn);
g_variant_dict_insert(&dictIn, "uri", "s", uri);
variantIn = g_variant_dict_end(&dictIn);
GVariant* tuple[1];
tuple[0] = variantIn;
GVariant* results = g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK, "HandleRequest", g_variant_new_tuple(tuple, 1), G_VARIANT_TYPE_TUPLE, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
g_variant_dict_clear(&dictIn);
if (results == NULL) {
g_printerr("ERR g_dbus_connection_call_sync %s\n", error->message);
g_error_free(error);
return FALSE;
}
GVariantDict dictOut;
g_variant_dict_init(&dictOut, g_variant_get_child_value(results, 0));
const gchar* newuri = NULL;
const gchar* cancel = NULL;
const gchar* ignore = NULL;
gboolean ret = FALSE;
if (g_variant_dict_lookup(&dictOut, "cancel", "s", &cancel)
&& cancel != NULL && !g_strcmp0(cancel, "1")) {
// returning TRUE blocks requests - it's better to set an empty uri - it sets status to 0;
webkit_uri_request_set_uri(request, "");
} else {
if (g_variant_dict_lookup(&dictOut, "uri", "s", &newuri) && newuri != NULL) {
webkit_uri_request_set_uri(request, newuri);
}
if (g_variant_dict_lookup(&dictOut, "ignore", "s", &ignore)
&& ignore != NULL && !g_strcmp0(ignore, "1")) {
dispatch_ignore_event(page, eventName, uri);
}
}
g_variant_dict_remove(&dictOut, "uri");
results = g_variant_dict_end(&dictOut);
update_soup_headers_with_dict(headers, results);
g_variant_unref(results);
return ret;
}
static void web_page_created_callback(WebKitWebExtension* extension, WebKitWebPage* web_page, gpointer data) {
g_signal_connect(web_page, "send-request", G_CALLBACK(web_page_send_request), data);
}
static gboolean custom_listener(WebKitDOMDOMWindow* window, WebKitDOMEvent* event, gpointer data) {
char* message = webkit_dom_keyboard_event_get_key_identifier((WebKitDOMKeyboardEvent*)event);
g_object_unref(event);
GError* error = NULL;
GVariant* vmessage = g_variant_new("(s)", message);
g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK,
"NotifyEvent", vmessage, G_VARIANT_TYPE("()"), G_DBUS_CALL_FLAGS_NONE, -1, NULL,
&error);
g_variant_unref(vmessage);
g_free(message);
if (error != NULL) {
g_printerr("Failed to finish dbus call: %s\n", error->message);
g_error_free(error);
}
return TRUE;
}
WebKitDOMDOMWindow* prevWin = NULL;
WebKitDOMDocument* prevDoc = NULL;
static void window_object_cleared_callback(WebKitScriptWorld* world, WebKitWebPage* page, WebKitFrame* frame, gchar* eventName) {
if (prevWin != NULL) {
webkit_dom_event_target_remove_event_listener(WEBKIT_DOM_EVENT_TARGET(prevWin), eventName, G_CALLBACK(custom_listener), FALSE);
g_object_unref(prevWin);
g_object_unref(prevDoc);
prevWin = NULL;
prevDoc = NULL;
}
prevDoc = webkit_web_page_get_dom_document(page);
prevWin = webkit_dom_document_get_default_view(prevDoc);
webkit_dom_event_target_add_event_listener(WEBKIT_DOM_EVENT_TARGET(prevWin), eventName, G_CALLBACK(custom_listener), FALSE, NULL);
}
extern "C" {
G_MODULE_EXPORT void webkit_web_extension_initialize_with_user_data(WebKitWebExtension* extension, const GVariant* constData) {
gchar* address = NULL;
gchar* eventName = NULL;
g_variant_get((GVariant*)constData, "(ss)", &address, &eventName);
g_signal_connect(webkit_script_world_get_default(), "window-object-cleared", G_CALLBACK(window_object_cleared_callback), eventName);
g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), eventName);
GError* error = NULL;
connection = g_dbus_connection_new_for_address_sync(address, G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, NULL, NULL, &error);
if (connection == NULL) {
g_printerr("Failed to open connection to bus: %s\n", error->message);
g_error_free(error);
}
}
}
| #include <dbus/dbus-glib.h>
#include <webkit2/webkit-web-extension.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <string.h>
#include "dbus.h"
#include "utils.h"
static GDBusConnection* connection;
static void dispatch_ignore_event(WebKitWebPage* page, gchar* eventName, const gchar* uri) {
gchar* ignoreName = g_strconcat("r", eventName, NULL);
WebKitDOMDocument* document = webkit_web_page_get_dom_document(page);
WebKitDOMDOMWindow* window = webkit_dom_document_get_default_view(document);
GError* error = NULL;
WebKitDOMEvent* event = webkit_dom_document_create_event(document, "KeyboardEvent", &error);
g_object_unref(document);
if (error != NULL) {
g_printerr("Cannot create event in dispatch_ignore_event: %s\n", error->message);
g_error_free(error);
return;
}
webkit_dom_keyboard_event_init_keyboard_event(
(WebKitDOMKeyboardEvent*)event, ignoreName, FALSE, TRUE,
window, uri, 0, FALSE, FALSE, FALSE, FALSE, FALSE
);
webkit_dom_event_target_dispatch_event(WEBKIT_DOM_EVENT_TARGET(window), event, &error);
g_object_unref(window);
g_object_unref(event);
if (error != NULL) {
g_printerr("Cannot dispatch event in dispatch_ignore_event: %s\n", error->message);
g_error_free(error);
}
}
static gboolean web_page_send_request(WebKitWebPage* page, WebKitURIRequest* request, WebKitURIResponse* redirected_response, gpointer data) {
GError* error = NULL;
// ignore redirected requests - it's transparent to the user
if (redirected_response != NULL) {
return FALSE;
}
gchar* eventName = (gchar*)data;
const char* uri = webkit_uri_request_get_uri(request);
SoupMessageHeaders* headers = webkit_uri_request_get_http_headers(request);
GVariantDict dictIn;
GVariant* variantIn = soup_headers_to_gvariant_dict(headers);
g_variant_dict_init(&dictIn, variantIn);
g_variant_dict_insert(&dictIn, "uri", "s", uri);
variantIn = g_variant_dict_end(&dictIn);
GVariant* tuple[1];
tuple[0] = variantIn;
GVariant* results = g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK, "HandleRequest", g_variant_new_tuple(tuple, 1), G_VARIANT_TYPE_TUPLE, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
g_variant_dict_clear(&dictIn);
if (results == NULL) {
g_printerr("ERR g_dbus_connection_call_sync %s\n", error->message);
g_error_free(error);
return FALSE;
}
GVariantDict dictOut;
g_variant_dict_init(&dictOut, g_variant_get_child_value(results, 0));
const gchar* newuri = NULL;
const gchar* cancel = NULL;
const gchar* ignore = NULL;
gboolean ret = FALSE;
if (g_variant_dict_lookup(&dictOut, "cancel", "s", &cancel)
&& cancel != NULL && !g_strcmp0(cancel, "1")) {
// returning TRUE blocks requests - it's better to set an empty uri - it sets status to 0;
webkit_uri_request_set_uri(request, "");
} else {
if (g_variant_dict_lookup(&dictOut, "uri", "s", &newuri) && newuri != NULL) {
webkit_uri_request_set_uri(request, newuri);
}
if (g_variant_dict_lookup(&dictOut, "ignore", "s", &ignore)
&& ignore != NULL && !g_strcmp0(ignore, "1")) {
dispatch_ignore_event(page, eventName, uri);
}
}
g_variant_dict_remove(&dictOut, "uri");
results = g_variant_dict_end(&dictOut);
update_soup_headers_with_dict(headers, results);
g_variant_unref(results);
return ret;
}
static void web_page_created_callback(WebKitWebExtension* extension, WebKitWebPage* web_page, gpointer data) {
g_signal_connect(web_page, "send-request", G_CALLBACK(web_page_send_request), data);
}
static gboolean event_listener(WebKitDOMDOMWindow* view, WebKitDOMEvent* event, gpointer data) {
char* message = webkit_dom_keyboard_event_get_key_identifier((WebKitDOMKeyboardEvent*)event);
GError* error = NULL;
g_dbus_connection_call_sync(connection, NULL, DBUS_OBJECT_WKGTK, DBUS_INTERFACE_WKGTK,
"NotifyEvent", g_variant_new("(s)", message), G_VARIANT_TYPE("()"), G_DBUS_CALL_FLAGS_NONE, -1, NULL,
&error);
if (error != NULL) {
g_printerr("Failed to finish dbus call: %s\n", error->message);
g_error_free(error);
}
g_free(message);
return TRUE;
}
static void window_object_cleared_callback(WebKitScriptWorld* world, WebKitWebPage* page, WebKitFrame* frame, gchar* eventName) {
WebKitDOMDocument* document = webkit_web_page_get_dom_document(page);
WebKitDOMDOMWindow* window = webkit_dom_document_get_default_view(document);
webkit_dom_event_target_add_event_listener(WEBKIT_DOM_EVENT_TARGET(window), eventName, G_CALLBACK(event_listener), false, NULL);
}
extern "C" {
G_MODULE_EXPORT void webkit_web_extension_initialize_with_user_data(WebKitWebExtension* extension, const GVariant* constData) {
gchar* address = NULL;
gchar* eventName = NULL;
g_variant_get((GVariant*)constData, "(ss)", &address, &eventName);
g_signal_connect(webkit_script_world_get_default(), "window-object-cleared", G_CALLBACK(window_object_cleared_callback), eventName);
g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), eventName);
GError* error = NULL;
connection = g_dbus_connection_new_for_address_sync(address, G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, NULL, NULL, &error);
if (connection == NULL) {
g_printerr("Failed to open connection to bus: %s\n", error->message);
g_error_free(error);
}
}
}
| Revert "Remove event listener, plugs a leak" | Revert "Remove event listener, plugs a leak"
This reverts commit cb619567b74ed2403e4ef49f13901be53ac0464c.
| C++ | mit | kapouer/node-webkitgtk,kapouer/node-webkitgtk,kapouer/node-webkitgtk,kapouer/node-webkitgtk |
e8f3776c159283209fa68ae0646d4e1e6af22960 | cql3/sets.hh | cql3/sets.hh | /*
* 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.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_SETS_HH
#define CQL3_SETS_HH
#include "cql3/abstract_marker.hh"
#include "maps.hh"
#include "column_specification.hh"
#include "column_identifier.hh"
#include "to_string.hh"
#include <unordered_set>
namespace cql3 {
#if 0
package org.apache.cassandra.cql3;
import java.nio.ByteBuffer;
import java.util.*;
import com.google.common.base.Joiner;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.composites.CellName;
import org.apache.cassandra.db.composites.Composite;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.MapType;
import org.apache.cassandra.db.marshal.SetType;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.serializers.CollectionSerializer;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.transport.Server;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
#endif
/**
* Static helper methods and classes for sets.
*/
class sets {
sets() = delete;
public:
static shared_ptr<column_specification> value_spec_of(shared_ptr<column_specification> column) {
return make_shared<column_specification>(column->ks_name, column->cf_name,
::make_shared<column_identifier>(sprint("value(%s)", *column->name), true),
dynamic_pointer_cast<set_type_impl>(column->type)->get_elements_type());
}
class literal : public term::raw {
std::vector<shared_ptr<term::raw>> _elements;
public:
explicit literal(std::vector<shared_ptr<term::raw>> elements)
: _elements(std::move(elements)) {
}
shared_ptr<term> prepare(const sstring& keyspace, shared_ptr<column_specification> receiver) {
validate_assignable_to(keyspace, receiver);
// We've parsed empty maps as a set literal to break the ambiguity so
// handle that case now
if (_elements.empty() && dynamic_pointer_cast<map_type_impl>(receiver->type)) {
// use empty_type for comparator, set is empty anyway.
std::map<bytes, bytes, serialized_compare> m(empty_type->as_less_comparator());
return ::make_shared<maps::value>(std::move(m));
}
auto value_spec = value_spec_of(receiver);
std::vector<shared_ptr<term>> values;
values.reserve(_elements.size());
bool all_terminal = true;
for (shared_ptr<term::raw> rt : _elements)
{
auto t = rt->prepare(keyspace, value_spec);
if (t->contains_bind_marker()) {
throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: bind variables are not supported inside collection literals", *receiver->name));
}
if (dynamic_pointer_cast<non_terminal>(t)) {
all_terminal = false;
}
values.push_back(std::move(t));
}
auto compare = dynamic_pointer_cast<set_type_impl>(receiver->type)->get_elements_type()->as_less_comparator();
auto value = ::make_shared<delayed_value>(compare, std::move(values));
if (all_terminal) {
return value->bind(query_options::DEFAULT);
} else {
return value;
}
}
void validate_assignable_to(const sstring& keyspace, shared_ptr<column_specification> receiver) {
if (!dynamic_pointer_cast<set_type_impl>(receiver->type)) {
// We've parsed empty maps as a set literal to break the ambiguity so
// handle that case now
if (dynamic_pointer_cast<map_type_impl>(receiver->type) && _elements.empty()) {
return;
}
throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s of type %s", *receiver->name, *receiver->type->as_cql3_type()));
}
auto&& value_spec = value_spec_of(receiver);
for (shared_ptr<term::raw> rt : _elements) {
if (!is_assignable(rt->test_assignment(keyspace, value_spec))) {
throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: value %s is not of type %s", *receiver->name, *rt, *value_spec->type->as_cql3_type()));
}
}
}
assignment_testable::test_result
test_assignment(const sstring& keyspace, shared_ptr<column_specification> receiver) {
if (!dynamic_pointer_cast<set_type_impl>(receiver->type)) {
// We've parsed empty maps as a set literal to break the ambiguity so handle that case now
if (dynamic_pointer_cast<map_type_impl>(receiver->type) && _elements.empty()) {
return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
}
return assignment_testable::test_result::NOT_ASSIGNABLE;
}
// If there is no elements, we can't say it's an exact match (an empty set if fundamentally polymorphic).
if (_elements.empty()) {
return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
}
auto&& value_spec = value_spec_of(receiver);
// FIXME: make assignment_testable::test_all() accept ranges
std::vector<shared_ptr<assignment_testable>> to_test(_elements.begin(), _elements.end());
return assignment_testable::test_all(keyspace, value_spec, to_test);
}
virtual sstring to_string() override {
return "{" + join(", ", _elements) + "}";
}
};
class value : public terminal, collection_terminal {
std::set<bytes, serialized_compare> _elements;
public:
value(std::set<bytes, serialized_compare> elements)
: _elements(std::move(elements)) {
}
static value from_serialized(bytes_view v, set_type type, int version) {
try {
// Collections have this small hack that validate cannot be called on a serialized object,
// but compose does the validation (so we're fine).
// FIXME: deserializeForNativeProtocol?!
auto s = boost::any_cast<set_type_impl::native_type>(type->deserialize(v, version));
std::set<bytes, serialized_compare> elements(type->as_less_comparator());
for (auto&& element : s) {
elements.insert(elements.end(), type->get_elements_type()->decompose(element));
}
return value(std::move(elements));
} catch (marshal_exception& e) {
throw exceptions::invalid_request_exception(e.why());
}
}
virtual bytes_opt get(const query_options& options) override {
return get_with_protocol_version(options.get_protocol_version());
}
virtual bytes get_with_protocol_version(int protocol_version) override {
return collection_type_impl::pack(_elements.begin(), _elements.end(),
_elements.size(), protocol_version);
}
bool equals(set_type st, const value& v) {
if (_elements.size() != v._elements.size()) {
return false;
}
auto&& elements_type = st->get_elements_type();
return std::equal(_elements.begin(), _elements.end(),
v._elements.begin(),
[elements_type] (bytes_view v1, bytes_view v2) {
return elements_type->equal(v1, v2);
});
}
virtual sstring to_string() const override {
sstring result = "{";
bool first = true;
for (auto&& e : _elements) {
if (!first) {
result += ", ";
}
first = true;
result += to_hex(e);
}
result += "}";
return result;
}
};
// See Lists.DelayedValue
class delayed_value : public non_terminal {
serialized_compare _comparator;
std::vector<shared_ptr<term>> _elements;
public:
delayed_value(serialized_compare comparator, std::vector<shared_ptr<term>> elements)
: _comparator(std::move(comparator)), _elements(std::move(elements)) {
}
virtual bool contains_bind_marker() const override {
// False since we don't support them in collection
return false;
}
virtual void collect_marker_specification(shared_ptr<variable_specifications> bound_names) override {
}
virtual shared_ptr<terminal> bind(const query_options& options) {
std::set<bytes, serialized_compare> buffers(_comparator);
for (auto&& t : _elements) {
bytes_opt b = t->bind_and_get(options);
if (!b) {
throw exceptions::invalid_request_exception("null is not supported inside collections");
}
// We don't support value > 64K because the serialization format encode the length as an unsigned short.
if (b->size() > std::numeric_limits<uint16_t>::max()) {
throw exceptions::invalid_request_exception(sprint("Set value is too long. Set values are limited to %d bytes but %d bytes value provided",
std::numeric_limits<uint16_t>::max(),
b->size()));
}
buffers.insert(buffers.end(), std::move(*b));
}
return ::make_shared<value>(std::move(buffers));
}
};
class marker : public abstract_marker {
public:
marker(int32_t bind_index, ::shared_ptr<column_specification> receiver)
: abstract_marker{bind_index, std::move(receiver)}
{ }
#if 0
protected Marker(int bindIndex, ColumnSpecification receiver)
{
super(bindIndex, receiver);
assert receiver.type instanceof SetType;
}
#endif
virtual ::shared_ptr<terminal> bind(const query_options& options) override {
throw std::runtime_error("");
}
#if 0
public Value bind(QueryOptions options) throws InvalidRequestException
{
ByteBuffer value = options.getValues().get(bindIndex);
return value == null ? null : Value.fromSerialized(value, (SetType)receiver.type, options.getProtocolVersion());
}
#endif
};
#if 0
public static class Setter extends Operation
{
public Setter(ColumnDefinition column, Term t)
{
super(column, t);
}
public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException
{
if (column.type.isMultiCell())
{
// delete + add
CellName name = cf.getComparator().create(prefix, column);
cf.addAtom(params.makeTombstoneForOverwrite(name.slice()));
}
Adder.doAdd(t, cf, prefix, column, params);
}
}
public static class Adder extends Operation
{
public Adder(ColumnDefinition column, Term t)
{
super(column, t);
}
public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException
{
assert column.type.isMultiCell() : "Attempted to add items to a frozen set";
doAdd(t, cf, prefix, column, params);
}
static void doAdd(Term t, ColumnFamily cf, Composite prefix, ColumnDefinition column, UpdateParameters params) throws InvalidRequestException
{
Term.Terminal value = t.bind(params.options);
Sets.Value setValue = (Sets.Value)value;
if (column.type.isMultiCell())
{
if (value == null)
return;
Set<ByteBuffer> toAdd = setValue.elements;
for (ByteBuffer bb : toAdd)
{
CellName cellName = cf.getComparator().create(prefix, column, bb);
cf.addColumn(params.makeColumn(cellName, ByteBufferUtil.EMPTY_BYTE_BUFFER));
}
}
else
{
// for frozen sets, we're overwriting the whole cell
CellName cellName = cf.getComparator().create(prefix, column);
if (value == null)
cf.addAtom(params.makeTombstone(cellName));
else
cf.addColumn(params.makeColumn(cellName, ((Value) value).getWithProtocolVersion(Server.CURRENT_VERSION)));
}
}
}
// Note that this is reused for Map subtraction too (we subtract a set from a map)
public static class Discarder extends Operation
{
public Discarder(ColumnDefinition column, Term t)
{
super(column, t);
}
public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException
{
assert column.type.isMultiCell() : "Attempted to remove items from a frozen set";
Term.Terminal value = t.bind(params.options);
if (value == null)
return;
// This can be either a set or a single element
Set<ByteBuffer> toDiscard = value instanceof Constants.Value
? Collections.singleton(((Constants.Value)value).bytes)
: ((Sets.Value)value).elements;
for (ByteBuffer bb : toDiscard)
{
cf.addColumn(params.makeTombstone(cf.getComparator().create(prefix, column, bb)));
}
}
}
#endif
};
}
#endif
| /*
* 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.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_SETS_HH
#define CQL3_SETS_HH
#include "cql3/abstract_marker.hh"
#include "maps.hh"
#include "column_specification.hh"
#include "column_identifier.hh"
#include "to_string.hh"
#include <unordered_set>
namespace cql3 {
#if 0
package org.apache.cassandra.cql3;
import java.nio.ByteBuffer;
import java.util.*;
import com.google.common.base.Joiner;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.composites.CellName;
import org.apache.cassandra.db.composites.Composite;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.MapType;
import org.apache.cassandra.db.marshal.SetType;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.serializers.CollectionSerializer;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.transport.Server;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
#endif
/**
* Static helper methods and classes for sets.
*/
class sets {
sets() = delete;
public:
static shared_ptr<column_specification> value_spec_of(shared_ptr<column_specification> column) {
return make_shared<column_specification>(column->ks_name, column->cf_name,
::make_shared<column_identifier>(sprint("value(%s)", *column->name), true),
dynamic_pointer_cast<set_type_impl>(column->type)->get_elements_type());
}
class literal : public term::raw {
std::vector<shared_ptr<term::raw>> _elements;
public:
explicit literal(std::vector<shared_ptr<term::raw>> elements)
: _elements(std::move(elements)) {
}
shared_ptr<term> prepare(const sstring& keyspace, shared_ptr<column_specification> receiver) {
validate_assignable_to(keyspace, receiver);
// We've parsed empty maps as a set literal to break the ambiguity so
// handle that case now
if (_elements.empty() && dynamic_pointer_cast<map_type_impl>(receiver->type)) {
// use empty_type for comparator, set is empty anyway.
std::map<bytes, bytes, serialized_compare> m(empty_type->as_less_comparator());
return ::make_shared<maps::value>(std::move(m));
}
auto value_spec = value_spec_of(receiver);
std::vector<shared_ptr<term>> values;
values.reserve(_elements.size());
bool all_terminal = true;
for (shared_ptr<term::raw> rt : _elements)
{
auto t = rt->prepare(keyspace, value_spec);
if (t->contains_bind_marker()) {
throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: bind variables are not supported inside collection literals", *receiver->name));
}
if (dynamic_pointer_cast<non_terminal>(t)) {
all_terminal = false;
}
values.push_back(std::move(t));
}
auto compare = dynamic_pointer_cast<set_type_impl>(receiver->type)->get_elements_type()->as_less_comparator();
auto value = ::make_shared<delayed_value>(compare, std::move(values));
if (all_terminal) {
return value->bind(query_options::DEFAULT);
} else {
return value;
}
}
void validate_assignable_to(const sstring& keyspace, shared_ptr<column_specification> receiver) {
if (!dynamic_pointer_cast<set_type_impl>(receiver->type)) {
// We've parsed empty maps as a set literal to break the ambiguity so
// handle that case now
if (dynamic_pointer_cast<map_type_impl>(receiver->type) && _elements.empty()) {
return;
}
throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s of type %s", *receiver->name, *receiver->type->as_cql3_type()));
}
auto&& value_spec = value_spec_of(receiver);
for (shared_ptr<term::raw> rt : _elements) {
if (!is_assignable(rt->test_assignment(keyspace, value_spec))) {
throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: value %s is not of type %s", *receiver->name, *rt, *value_spec->type->as_cql3_type()));
}
}
}
assignment_testable::test_result
test_assignment(const sstring& keyspace, shared_ptr<column_specification> receiver) {
if (!dynamic_pointer_cast<set_type_impl>(receiver->type)) {
// We've parsed empty maps as a set literal to break the ambiguity so handle that case now
if (dynamic_pointer_cast<map_type_impl>(receiver->type) && _elements.empty()) {
return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
}
return assignment_testable::test_result::NOT_ASSIGNABLE;
}
// If there is no elements, we can't say it's an exact match (an empty set if fundamentally polymorphic).
if (_elements.empty()) {
return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
}
auto&& value_spec = value_spec_of(receiver);
// FIXME: make assignment_testable::test_all() accept ranges
std::vector<shared_ptr<assignment_testable>> to_test(_elements.begin(), _elements.end());
return assignment_testable::test_all(keyspace, value_spec, to_test);
}
virtual sstring to_string() override {
return "{" + join(", ", _elements) + "}";
}
};
class value : public terminal, collection_terminal {
public:
std::set<bytes, serialized_compare> _elements;
public:
value(std::set<bytes, serialized_compare> elements)
: _elements(std::move(elements)) {
}
static value from_serialized(bytes_view v, set_type type, int version) {
try {
// Collections have this small hack that validate cannot be called on a serialized object,
// but compose does the validation (so we're fine).
// FIXME: deserializeForNativeProtocol?!
auto s = boost::any_cast<set_type_impl::native_type>(type->deserialize(v, version));
std::set<bytes, serialized_compare> elements(type->as_less_comparator());
for (auto&& element : s) {
elements.insert(elements.end(), type->get_elements_type()->decompose(element));
}
return value(std::move(elements));
} catch (marshal_exception& e) {
throw exceptions::invalid_request_exception(e.why());
}
}
virtual bytes_opt get(const query_options& options) override {
return get_with_protocol_version(options.get_protocol_version());
}
virtual bytes get_with_protocol_version(int protocol_version) override {
return collection_type_impl::pack(_elements.begin(), _elements.end(),
_elements.size(), protocol_version);
}
bool equals(set_type st, const value& v) {
if (_elements.size() != v._elements.size()) {
return false;
}
auto&& elements_type = st->get_elements_type();
return std::equal(_elements.begin(), _elements.end(),
v._elements.begin(),
[elements_type] (bytes_view v1, bytes_view v2) {
return elements_type->equal(v1, v2);
});
}
virtual sstring to_string() const override {
sstring result = "{";
bool first = true;
for (auto&& e : _elements) {
if (!first) {
result += ", ";
}
first = true;
result += to_hex(e);
}
result += "}";
return result;
}
};
// See Lists.DelayedValue
class delayed_value : public non_terminal {
serialized_compare _comparator;
std::vector<shared_ptr<term>> _elements;
public:
delayed_value(serialized_compare comparator, std::vector<shared_ptr<term>> elements)
: _comparator(std::move(comparator)), _elements(std::move(elements)) {
}
virtual bool contains_bind_marker() const override {
// False since we don't support them in collection
return false;
}
virtual void collect_marker_specification(shared_ptr<variable_specifications> bound_names) override {
}
virtual shared_ptr<terminal> bind(const query_options& options) {
std::set<bytes, serialized_compare> buffers(_comparator);
for (auto&& t : _elements) {
bytes_opt b = t->bind_and_get(options);
if (!b) {
throw exceptions::invalid_request_exception("null is not supported inside collections");
}
// We don't support value > 64K because the serialization format encode the length as an unsigned short.
if (b->size() > std::numeric_limits<uint16_t>::max()) {
throw exceptions::invalid_request_exception(sprint("Set value is too long. Set values are limited to %d bytes but %d bytes value provided",
std::numeric_limits<uint16_t>::max(),
b->size()));
}
buffers.insert(buffers.end(), std::move(*b));
}
return ::make_shared<value>(std::move(buffers));
}
};
class marker : public abstract_marker {
public:
marker(int32_t bind_index, ::shared_ptr<column_specification> receiver)
: abstract_marker{bind_index, std::move(receiver)}
{ }
#if 0
protected Marker(int bindIndex, ColumnSpecification receiver)
{
super(bindIndex, receiver);
assert receiver.type instanceof SetType;
}
#endif
virtual ::shared_ptr<terminal> bind(const query_options& options) override {
throw std::runtime_error("");
}
#if 0
public Value bind(QueryOptions options) throws InvalidRequestException
{
ByteBuffer value = options.getValues().get(bindIndex);
return value == null ? null : Value.fromSerialized(value, (SetType)receiver.type, options.getProtocolVersion());
}
#endif
};
#if 0
public static class Setter extends Operation
{
public Setter(ColumnDefinition column, Term t)
{
super(column, t);
}
public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException
{
if (column.type.isMultiCell())
{
// delete + add
CellName name = cf.getComparator().create(prefix, column);
cf.addAtom(params.makeTombstoneForOverwrite(name.slice()));
}
Adder.doAdd(t, cf, prefix, column, params);
}
}
public static class Adder extends Operation
{
public Adder(ColumnDefinition column, Term t)
{
super(column, t);
}
public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException
{
assert column.type.isMultiCell() : "Attempted to add items to a frozen set";
doAdd(t, cf, prefix, column, params);
}
static void doAdd(Term t, ColumnFamily cf, Composite prefix, ColumnDefinition column, UpdateParameters params) throws InvalidRequestException
{
Term.Terminal value = t.bind(params.options);
Sets.Value setValue = (Sets.Value)value;
if (column.type.isMultiCell())
{
if (value == null)
return;
Set<ByteBuffer> toAdd = setValue.elements;
for (ByteBuffer bb : toAdd)
{
CellName cellName = cf.getComparator().create(prefix, column, bb);
cf.addColumn(params.makeColumn(cellName, ByteBufferUtil.EMPTY_BYTE_BUFFER));
}
}
else
{
// for frozen sets, we're overwriting the whole cell
CellName cellName = cf.getComparator().create(prefix, column);
if (value == null)
cf.addAtom(params.makeTombstone(cellName));
else
cf.addColumn(params.makeColumn(cellName, ((Value) value).getWithProtocolVersion(Server.CURRENT_VERSION)));
}
}
}
// Note that this is reused for Map subtraction too (we subtract a set from a map)
public static class Discarder extends Operation
{
public Discarder(ColumnDefinition column, Term t)
{
super(column, t);
}
public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException
{
assert column.type.isMultiCell() : "Attempted to remove items from a frozen set";
Term.Terminal value = t.bind(params.options);
if (value == null)
return;
// This can be either a set or a single element
Set<ByteBuffer> toDiscard = value instanceof Constants.Value
? Collections.singleton(((Constants.Value)value).bytes)
: ((Sets.Value)value).elements;
for (ByteBuffer bb : toDiscard)
{
cf.addColumn(params.makeTombstone(cf.getComparator().create(prefix, column, bb)));
}
}
}
#endif
};
}
#endif
| make sets::value::_elements public | cql: make sets::value::_elements public
Users of a value will want to make use of it.
| C++ | agpl-3.0 | senseb/scylla,capturePointer/scylla,glommer/scylla,rluta/scylla,dwdm/scylla,scylladb/scylla,victorbriz/scylla,duarten/scylla,wildinto/scylla,eklitzke/scylla,stamhe/scylla,tempbottle/scylla,glommer/scylla,avikivity/scylla,rentongzhang/scylla,aruanruan/scylla,linearregression/scylla,scylladb/scylla,shaunstanislaus/scylla,wildinto/scylla,asias/scylla,kjniemi/scylla,gwicke/scylla,aruanruan/scylla,acbellini/scylla,guiquanz/scylla,raphaelsc/scylla,dwdm/scylla,acbellini/scylla,rentongzhang/scylla,phonkee/scylla,asias/scylla,aruanruan/scylla,asias/scylla,bowlofstew/scylla,linearregression/scylla,raphaelsc/scylla,respu/scylla,justintung/scylla,bowlofstew/scylla,stamhe/scylla,duarten/scylla,senseb/scylla,bowlofstew/scylla,scylladb/scylla,shaunstanislaus/scylla,shaunstanislaus/scylla,avikivity/scylla,gwicke/scylla,duarten/scylla,glommer/scylla,tempbottle/scylla,respu/scylla,rluta/scylla,capturePointer/scylla,kangkot/scylla,avikivity/scylla,kjniemi/scylla,acbellini/scylla,eklitzke/scylla,kangkot/scylla,tempbottle/scylla,eklitzke/scylla,rentongzhang/scylla,guiquanz/scylla,capturePointer/scylla,victorbriz/scylla,gwicke/scylla,stamhe/scylla,rluta/scylla,phonkee/scylla,kangkot/scylla,kjniemi/scylla,linearregression/scylla,justintung/scylla,dwdm/scylla,raphaelsc/scylla,victorbriz/scylla,senseb/scylla,scylladb/scylla,respu/scylla,guiquanz/scylla,phonkee/scylla,justintung/scylla,wildinto/scylla |
62fe9d0bef2e763bd18cf6659aa37b02338780ce | src/collision.cpp | src/collision.cpp | #include "../includes/declarations.h"
//Function used to check collision with the balls. Attribute obstacle checks if the ball is the black or red.
bool checkCollision(int xp, int yp)
{
int xc, yc, r;
for (int i = 0; i < num_circles; i++)
{
xc = circles[i].x;
yc = circles[i].y;
r = circles[i].r;
if ((xc - xp)*(xc-xp) + (yc - yp)*(yc-yp) <= r*r )
{
if(circles[i].hit==false)
collected--;
circles[i].hit = true;
if(circles[i].obstacle==true)
{
circles[i].hit=false;
resetAll();
return false;
}
if(collected==0)
{
level++;
next_level=true;
}
return true;
}
}
return false;
}
//Function used for Level Select Screen
bool inCircle(int xp, int yp, float xc, float yc)
{
double r = 0.083 * WIDTH;
if (sqrt(pow((xc - xp), 2) + pow((yc - yp), 2)) <= r)
return true;
return false;
}
| #include "../includes/declarations.h"
//Function used to check collision with the balls. Attribute obstacle checks if the ball is the black or red.
bool checkCollision(int xp, int yp)
{
int xc, yc, r;
for (int i = 0; i < num_circles; i++)
{
xc = circles[i].x;
yc = circles[i].y;
r = circles[i].r;
if ((xc - xp)*(xc-xp) + (yc - yp)*(yc-yp) <= r*r )
{
if(circles[i].hit==false)
collected--;
circles[i].hit = true;
if(circles[i].obstacle==true)
{
circles[i].hit=false;
resetAll();
return false;
}
if(collected==0)
{
level++;
next_level=true;
}
return true;
}
}
return false;
}
//Function used for Level Select Screen
bool inCircle(int xp, int yp, float xc, float yc)
{
double r = 0.083 * WIDTH;
if ((xc - xp)*(xc-xp) + (yc - yp)*(yc-yp) <= r*r )
return true;
return false;
}
| Update collision.cpp | Update collision.cpp | C++ | mit | therealkbhat/OpenBlek,kbhat95/OpenBlek |
dfeea22c8e0a32e992f79c997e26cca106855dba | test/msgpack_decoder.cpp | test/msgpack_decoder.cpp | #include "inc/cxx/msgpack.hpp"
#include "test/catch.hpp"
#include "test/utils.hpp"
using namespace std::string_literals;
using namespace cxx::literals;
using namespace test::literals;
using msgpack = cxx::msgpack;
TEST_CASE("msgpack throws exception on unsupported tag")
{
REQUIRE_THROWS_AS(msgpack::decode("c7"_hex), msgpack::unsupported); // ext8
REQUIRE_THROWS_AS(msgpack::decode("c8"_hex), msgpack::unsupported); // ext16
REQUIRE_THROWS_AS(msgpack::decode("c9"_hex), msgpack::unsupported); // ext32
REQUIRE_THROWS_AS(msgpack::decode("ca"_hex), msgpack::unsupported); // float32
REQUIRE_THROWS_AS(msgpack::decode("cb"_hex), msgpack::unsupported); // float64
REQUIRE_THROWS_AS(msgpack::decode("d4"_hex), msgpack::unsupported); // fixext1
REQUIRE_THROWS_AS(msgpack::decode("d5"_hex), msgpack::unsupported); // fixext2
REQUIRE_THROWS_AS(msgpack::decode("d6"_hex), msgpack::unsupported); // fixext4
REQUIRE_THROWS_AS(msgpack::decode("d7"_hex), msgpack::unsupported); // fixext8
REQUIRE_THROWS_AS(msgpack::decode("d8"_hex), msgpack::unsupported); // fixext16
REQUIRE_THROWS_AS(msgpack::decode("de"_hex), msgpack::unsupported); // map16
REQUIRE_THROWS_AS(msgpack::decode("df"_hex), msgpack::unsupported); // map32
}
TEST_CASE("msgpack throws truncation_error on empty buffer")
{
REQUIRE_THROWS_AS(msgpack::decode(""_hex), msgpack::truncation_error);
}
TEST_CASE("msgpack can decode integers")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("cc"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("ce00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("ce000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("cf00000000000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d0"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d1ff"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d2ffffff"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d3ffffffffffffff"_hex), msgpack::truncation_error);
}
SECTION("limits")
{
REQUIRE_THROWS_AS(msgpack::decode("cfffffffffffffffff"_hex), msgpack::unsupported);
}
REQUIRE(msgpack::decode("00"_hex) == 0x00);
REQUIRE(msgpack::decode("7f"_hex) == 0x7f);
REQUIRE(msgpack::decode("cc00"_hex) == 0x00);
REQUIRE(msgpack::decode("ccff"_hex) == 0xff);
REQUIRE(msgpack::decode("cd0000"_hex) == 0x00);
REQUIRE(msgpack::decode("cdffff"_hex) == 0xffff);
REQUIRE(msgpack::decode("ce00000000"_hex) == 0x00);
REQUIRE(msgpack::decode("ceffffffff"_hex) == 0xffffffff);
REQUIRE(msgpack::decode("cf0000000000000000"_hex) == 0x00);
REQUIRE(msgpack::decode("cf1fffffffffffffff"_hex) == 0x1fffffffffffffff);
REQUIRE(msgpack::decode("cf7fffffffffffffff"_hex) == std::numeric_limits<std::int64_t>::max());
REQUIRE(msgpack::decode("e0"_hex) == -0x20);
REQUIRE(msgpack::decode("ef"_hex) == -0x11);
REQUIRE(msgpack::decode("ff"_hex) == -0x01);
REQUIRE(msgpack::decode("d000"_hex) == 0x00);
REQUIRE(msgpack::decode("d001"_hex) == 0x01);
REQUIRE(msgpack::decode("d080"_hex) == -0x80);
REQUIRE(msgpack::decode("d0ff"_hex) == -0x01);
REQUIRE(msgpack::decode("d10000"_hex) == 0x00);
REQUIRE(msgpack::decode("d10001"_hex) == 0x01);
REQUIRE(msgpack::decode("d18000"_hex) == -0x8000);
REQUIRE(msgpack::decode("d18fff"_hex) == -0x7001);
REQUIRE(msgpack::decode("d1ffff"_hex) == -0x01);
REQUIRE(msgpack::decode("d200000000"_hex) == 0x00);
REQUIRE(msgpack::decode("d200000001"_hex) == 0x01);
REQUIRE(msgpack::decode("d280000000"_hex) == -0x80000000l);
REQUIRE(msgpack::decode("d28fffffff"_hex) == -0x70000001l);
REQUIRE(msgpack::decode("d2ffffffff"_hex) == -0x01);
REQUIRE(msgpack::decode("d30000000000000000"_hex) == 0x00);
REQUIRE(msgpack::decode("d30000000000000001"_hex) == 0x01);
REQUIRE(msgpack::decode("d37fffffffffffffff"_hex) == std::numeric_limits<std::int64_t>::max());
REQUIRE(msgpack::decode("d38000000000000000"_hex) == std::numeric_limits<std::int64_t>::min());
REQUIRE(msgpack::decode("d38fffffffffffffff"_hex) == -0x7000000000000001l);
REQUIRE(msgpack::decode("d3ffffffffffffffff"_hex) == -0x01);
SECTION("leftovers")
{
auto const bytes = "ef7fcdff77d18fff00"_hex;
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == -0x11);
REQUIRE(msgpack::decode(leftovers) == 0x7f);
REQUIRE(msgpack::decode(leftovers) == 0xff77);
REQUIRE(msgpack::decode(leftovers) == -0x7001);
REQUIRE(std::size(leftovers) == 1);
}
}
TEST_CASE("msgpack can decode simple values")
{
REQUIRE(msgpack::decode("c0"_hex) == cxx::json::null);
REQUIRE(msgpack::decode("c2"_hex) == false);
REQUIRE(msgpack::decode("c3"_hex) == true);
}
TEST_CASE("msgpack can decode strings")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("d9"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("da00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("db000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("a1"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d901"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d9026c"_hex), msgpack::truncation_error);
}
REQUIRE(msgpack::decode("a0"_hex) == "");
REQUIRE(msgpack::decode("d90000"_hex) == "");
REQUIRE(msgpack::decode("da000000"_hex) == "");
REQUIRE(msgpack::decode("db0000000000"_hex) == "");
REQUIRE(msgpack::decode("a56c6f72656d"_hex) == "lorem");
REQUIRE(msgpack::decode("d9056c6f72656d"_hex) == "lorem");
REQUIRE(msgpack::decode("da00056c6f72656d"_hex) == "lorem");
REQUIRE(msgpack::decode("db000000056c6f72656d"_hex) == "lorem");
SECTION("leftovers")
{
auto const bytes =
"a0a3616263d905697073756dda0005646f6c6f72db0000000873697420616d6574d90164"_hex;
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == "");
REQUIRE(msgpack::decode(leftovers) == "abc");
REQUIRE(msgpack::decode(leftovers) == "ipsum");
REQUIRE(msgpack::decode(leftovers) == "dolor");
REQUIRE(msgpack::decode(leftovers) == "sit amet");
REQUIRE(std::size(leftovers) == 3);
}
}
TEST_CASE("msgpack can decode byte_stream")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("c4"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c401"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c500"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c50001"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c6000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c600000001"_hex), msgpack::truncation_error);
}
REQUIRE(msgpack::decode("c400"_hex) == ""_hex);
REQUIRE(msgpack::decode("c50000"_hex) == ""_hex);
REQUIRE(msgpack::decode("c600000000"_hex) == ""_hex);
REQUIRE(msgpack::decode("c403010203"_hex) == "010203"_hex);
REQUIRE(msgpack::decode("c50003010203"_hex) == "010203"_hex);
REQUIRE(msgpack::decode("c600000003010203"_hex) == "010203"_hex);
SECTION("leftovers")
{
auto const bytes = "c400c40101c500020203c600000003040506c40107"_hex;
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == ""_hex);
REQUIRE(msgpack::decode(leftovers) == "01"_hex);
REQUIRE(msgpack::decode(leftovers) == "0203"_hex);
REQUIRE(msgpack::decode(leftovers) == "040506"_hex);
REQUIRE(std::size(leftovers) == 3);
}
}
TEST_CASE("msgpack can decode array")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("91"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dc"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dc00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dc0001"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd0000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd00000001"_hex), msgpack::truncation_error);
}
SECTION("nested truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("91c4"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("9300c4"_hex), msgpack::truncation_error);
}
SECTION("empty array")
{
cxx::json::array const array;
REQUIRE(msgpack::decode("90"_hex) == array);
REQUIRE(msgpack::decode("dc0000"_hex) == array);
REQUIRE(msgpack::decode("dd00000000"_hex) == array);
}
SECTION("non-empty array")
{
cxx::json::array const a = {0};
cxx::json::array const b = {1};
cxx::json::array const c = {0x2a};
REQUIRE(msgpack::decode("9100"_hex) == a);
REQUIRE(msgpack::decode("dc000101"_hex) == b);
REQUIRE(msgpack::decode("dd000000012a"_hex) == c);
REQUIRE(msgpack::decode("9201a56c6f72656d"_hex) == cxx::json::array({1, "lorem"}));
}
SECTION("nested arrays")
{
auto const json = msgpack::decode("9190"_hex);
REQUIRE(cxx::holds_alternative<cxx::json::array>(json));
REQUIRE(std::size(json) == 1);
REQUIRE(json[0] == cxx::json::array());
REQUIRE(msgpack::decode("929091a56c6f72656d"_hex) ==
cxx::json::array({cxx::json::array(), cxx::json::array({"lorem"})}));
}
SECTION("leftovers")
{
auto const bytes = "909300a56c6f72656d2adc0001dd0000000101"_hex;
auto const array = [] {
cxx::json::array a, b;
a.push_back(1);
b.push_back(a);
return b;
}();
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == cxx::json::array());
REQUIRE(msgpack::decode(leftovers) == cxx::json::array({0, "lorem", 0x2a}));
REQUIRE(msgpack::decode(leftovers) == array);
REQUIRE(std::size(leftovers) == 0);
}
}
| #include "inc/cxx/msgpack.hpp"
#include "test/catch.hpp"
#include "test/utils.hpp"
using namespace std::string_literals;
using namespace cxx::literals;
using namespace test::literals;
using msgpack = cxx::msgpack;
TEST_CASE("msgpack throws exception on unsupported tag")
{
REQUIRE_THROWS_AS(msgpack::decode("c7"_hex), msgpack::unsupported); // ext8
REQUIRE_THROWS_AS(msgpack::decode("c8"_hex), msgpack::unsupported); // ext16
REQUIRE_THROWS_AS(msgpack::decode("c9"_hex), msgpack::unsupported); // ext32
REQUIRE_THROWS_AS(msgpack::decode("ca"_hex), msgpack::unsupported); // float32
REQUIRE_THROWS_AS(msgpack::decode("cb"_hex), msgpack::unsupported); // float64
REQUIRE_THROWS_AS(msgpack::decode("d4"_hex), msgpack::unsupported); // fixext1
REQUIRE_THROWS_AS(msgpack::decode("d5"_hex), msgpack::unsupported); // fixext2
REQUIRE_THROWS_AS(msgpack::decode("d6"_hex), msgpack::unsupported); // fixext4
REQUIRE_THROWS_AS(msgpack::decode("d7"_hex), msgpack::unsupported); // fixext8
REQUIRE_THROWS_AS(msgpack::decode("d8"_hex), msgpack::unsupported); // fixext16
REQUIRE_THROWS_AS(msgpack::decode("de"_hex), msgpack::unsupported); // map16
REQUIRE_THROWS_AS(msgpack::decode("df"_hex), msgpack::unsupported); // map32
}
TEST_CASE("msgpack throws truncation_error on empty buffer")
{
REQUIRE_THROWS_AS(msgpack::decode(""_hex), msgpack::truncation_error);
}
TEST_CASE("msgpack can decode integers")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("cc"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("ce00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("ce000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("cf00000000000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d0"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d1ff"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d2ffffff"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d3ffffffffffffff"_hex), msgpack::truncation_error);
}
SECTION("limits")
{
REQUIRE_THROWS_AS(msgpack::decode("cfffffffffffffffff"_hex), msgpack::unsupported);
}
REQUIRE(msgpack::decode("00"_hex) == 0x00);
REQUIRE(msgpack::decode("7f"_hex) == 0x7f);
REQUIRE(msgpack::decode("cc00"_hex) == 0x00);
REQUIRE(msgpack::decode("ccff"_hex) == 0xff);
REQUIRE(msgpack::decode("cd0000"_hex) == 0x00);
REQUIRE(msgpack::decode("cdffff"_hex) == 0xffff);
REQUIRE(msgpack::decode("ce00000000"_hex) == 0x00);
REQUIRE(msgpack::decode("ceffffffff"_hex) == 0xffffffff);
REQUIRE(msgpack::decode("cf0000000000000000"_hex) == 0x00);
REQUIRE(msgpack::decode("cf1fffffffffffffff"_hex) == 0x1fffffffffffffff);
REQUIRE(msgpack::decode("cf7fffffffffffffff"_hex) == std::numeric_limits<std::int64_t>::max());
REQUIRE(msgpack::decode("e0"_hex) == -0x20);
REQUIRE(msgpack::decode("ef"_hex) == -0x11);
REQUIRE(msgpack::decode("ff"_hex) == -0x01);
REQUIRE(msgpack::decode("d000"_hex) == 0x00);
REQUIRE(msgpack::decode("d001"_hex) == 0x01);
REQUIRE(msgpack::decode("d080"_hex) == -0x80);
REQUIRE(msgpack::decode("d0ff"_hex) == -0x01);
REQUIRE(msgpack::decode("d10000"_hex) == 0x00);
REQUIRE(msgpack::decode("d10001"_hex) == 0x01);
REQUIRE(msgpack::decode("d18000"_hex) == -0x8000);
REQUIRE(msgpack::decode("d18fff"_hex) == -0x7001);
REQUIRE(msgpack::decode("d1ffff"_hex) == -0x01);
REQUIRE(msgpack::decode("d200000000"_hex) == 0x00);
REQUIRE(msgpack::decode("d200000001"_hex) == 0x01);
REQUIRE(msgpack::decode("d280000000"_hex) == -0x80000000l);
REQUIRE(msgpack::decode("d28fffffff"_hex) == -0x70000001l);
REQUIRE(msgpack::decode("d2ffffffff"_hex) == -0x01);
REQUIRE(msgpack::decode("d30000000000000000"_hex) == 0x00);
REQUIRE(msgpack::decode("d30000000000000001"_hex) == 0x01);
REQUIRE(msgpack::decode("d37fffffffffffffff"_hex) == std::numeric_limits<std::int64_t>::max());
REQUIRE(msgpack::decode("d38000000000000000"_hex) == std::numeric_limits<std::int64_t>::min());
REQUIRE(msgpack::decode("d38fffffffffffffff"_hex) == -0x7000000000000001l);
REQUIRE(msgpack::decode("d3ffffffffffffffff"_hex) == -0x01);
SECTION("leftovers")
{
auto const bytes = "ef7fcdff77d18fff00"_hex;
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == -0x11);
REQUIRE(msgpack::decode(leftovers) == 0x7f);
REQUIRE(msgpack::decode(leftovers) == 0xff77);
REQUIRE(msgpack::decode(leftovers) == -0x7001);
REQUIRE(std::size(leftovers) == 1);
}
}
TEST_CASE("msgpack can decode simple values")
{
REQUIRE(msgpack::decode("c0"_hex) == cxx::json::null);
REQUIRE(msgpack::decode("c2"_hex) == false);
REQUIRE(msgpack::decode("c3"_hex) == true);
}
TEST_CASE("msgpack can decode strings")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("d9"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("da00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("db000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("a1"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d901"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("d9026c"_hex), msgpack::truncation_error);
}
REQUIRE(msgpack::decode("a0"_hex) == "");
REQUIRE(msgpack::decode("d90000"_hex) == "");
REQUIRE(msgpack::decode("da000000"_hex) == "");
REQUIRE(msgpack::decode("db0000000000"_hex) == "");
REQUIRE(msgpack::decode("a56c6f72656d"_hex) == "lorem");
REQUIRE(msgpack::decode("d9056c6f72656d"_hex) == "lorem");
REQUIRE(msgpack::decode("da00056c6f72656d"_hex) == "lorem");
REQUIRE(msgpack::decode("db000000056c6f72656d"_hex) == "lorem");
SECTION("leftovers")
{
auto const bytes =
"a0a3616263d905697073756dda0005646f6c6f72db0000000873697420616d6574d90164"_hex;
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == "");
REQUIRE(msgpack::decode(leftovers) == "abc");
REQUIRE(msgpack::decode(leftovers) == "ipsum");
REQUIRE(msgpack::decode(leftovers) == "dolor");
REQUIRE(msgpack::decode(leftovers) == "sit amet");
REQUIRE(std::size(leftovers) == 3);
}
}
TEST_CASE("msgpack can decode byte_stream")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("c4"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c401"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c500"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c50001"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c6000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("c600000001"_hex), msgpack::truncation_error);
}
REQUIRE(msgpack::decode("c400"_hex) == ""_hex);
REQUIRE(msgpack::decode("c50000"_hex) == ""_hex);
REQUIRE(msgpack::decode("c600000000"_hex) == ""_hex);
REQUIRE(msgpack::decode("c403010203"_hex) == "010203"_hex);
REQUIRE(msgpack::decode("c50003010203"_hex) == "010203"_hex);
REQUIRE(msgpack::decode("c600000003010203"_hex) == "010203"_hex);
SECTION("leftovers")
{
auto const bytes = "c400c40101c500020203c600000003040506c40107"_hex;
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == ""_hex);
REQUIRE(msgpack::decode(leftovers) == "01"_hex);
REQUIRE(msgpack::decode(leftovers) == "0203"_hex);
REQUIRE(msgpack::decode(leftovers) == "040506"_hex);
REQUIRE(std::size(leftovers) == 3);
}
}
TEST_CASE("msgpack can decode array")
{
SECTION("truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("91"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dc"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dc00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dc0001"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd00"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd0000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd000000"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("dd00000001"_hex), msgpack::truncation_error);
}
SECTION("nested truncation_error")
{
REQUIRE_THROWS_AS(msgpack::decode("91c4"_hex), msgpack::truncation_error);
REQUIRE_THROWS_AS(msgpack::decode("9300c4"_hex), msgpack::truncation_error);
}
SECTION("empty array")
{
cxx::json::array const array;
REQUIRE(msgpack::decode("90"_hex) == array);
REQUIRE(msgpack::decode("dc0000"_hex) == array);
REQUIRE(msgpack::decode("dd00000000"_hex) == array);
}
SECTION("non-empty array")
{
cxx::json::array const a = {0};
cxx::json::array const b = {1};
cxx::json::array const c = {0x2a};
REQUIRE(msgpack::decode("9100"_hex) == a);
REQUIRE(msgpack::decode("dc000101"_hex) == b);
REQUIRE(msgpack::decode("dd000000012a"_hex) == c);
REQUIRE(msgpack::decode("9201a56c6f72656d"_hex) == cxx::json::array({1, "lorem"}));
}
SECTION("nested arrays")
{
auto const json = msgpack::decode("9190"_hex);
REQUIRE(cxx::holds_alternative<cxx::json::array>(json));
REQUIRE(std::size(json) == 1);
REQUIRE(json[0] == cxx::json::array());
REQUIRE(msgpack::decode("929091a56c6f72656d"_hex) ==
cxx::json::array({cxx::json::array(), cxx::json::array({"lorem"})}));
REQUIRE_THROWS_AS(
msgpack::decode(
"91919191919191919191919191919191919191919191919191919191919191919191919191919191919191919191919191919191919191919191919191919101"_hex),
msgpack::unsupported);
}
SECTION("leftovers")
{
auto const bytes = "909300a56c6f72656d2adc0001dd0000000101"_hex;
auto const array = [] {
cxx::json::array a, b;
a.push_back(1);
b.push_back(a);
return b;
}();
cxx::json::byte_view leftovers(bytes.data(), std::size(bytes));
REQUIRE(msgpack::decode(leftovers) == cxx::json::array());
REQUIRE(msgpack::decode(leftovers) == cxx::json::array({0, "lorem", 0x2a}));
REQUIRE(msgpack::decode(leftovers) == array);
REQUIRE(std::size(leftovers) == 0);
}
}
| test for max array nesting | test for max array nesting
| C++ | mit | attugit/cxxjson,attugit/cxxjson,attugit/cxxjson |
4d3564809bf446ff3c44bd2a17a45c1a27c7dcb1 | src/community.cpp | src/community.cpp | #include "community.hpp"
#include "cut_tools.hpp"
#include "file_io.hpp"
#include "snap_tools.hpp"
#include "tensor_ops.hpp"
#include "Snap.h"
#include <iostream>
#include <stdexcept>
#include <vector>
CommDetection::CommDetection(Network& net, int num_comms, int algorithm, int cut_type,
std::string name) :
num_comms_(num_comms), num_nodes_(net.NumNodes()), algorithm_(algorithm),
cut_type_(cut_type), name_(name) {
networks_.push_back(net);
// TODO(arbenson): there is a better way to do this
labels_.push_back(std::vector<int>());
labels_[0] = Range(net.NumNodes());
}
// Run the community detection algorithm.
void CommDetection::Run() {
while (networks_.size() < num_comms_) {
Iterate();
}
}
// Report the number of triples preserved by the communities.
int CommDetection::NumTriplesPreserved() {
int sum = 0;
for (Network& net : networks_) {
sum += net.triples().size();
}
return sum;
}
// Print the node and edge counts for each of the communities;
void CommDetection::PrintCounts() {
for (Network& net : networks_) {
std::cout << net.NumNodes() << " " << net.NumEdges() << std::endl;
}
}
// Returns the categories of all nodes. The return value is a vector such
// that the i-th entry is the category of the i-th node.
std::vector<int> CommDetection::Communities() {
std::vector<int> communities(num_nodes_, -1);
for (int i = 0; i < labels_.size(); ++i) {
std::vector<int>& curr_labels = labels_[i];
for (int node : curr_labels) {
communities[node] = i;
}
}
for (int comm : communities) {
if (comm == -1) {
std::logic_error("Not all nodes assigned communities.");
}
}
return communities;
}
void CommDetection::RemoveCutFromCurrNetwork(Cutter& cutter, std::vector<int>& cut) {
std::cout << cut.size() << " of " << CurrNetwork().NumNodes()
<< " nodes cut." << std::endl;
Network net1, net2;
cutter.AddCut(cut, net1, net2);
int curr_ind = CurrNetworkIndex();
std::vector<int>& curr_labels = labels_[curr_ind];
std::vector<int> labels1, labels2;
for (int i = 0; i < net1.NumNodes(); ++i) {
labels1.push_back(curr_labels[net1.NodeIndex(i)]);
}
for (int i = 0; i < net2.NumNodes(); ++i) {
labels2.push_back(curr_labels[net2.NodeIndex(i)]);
}
networks_.erase(networks_.begin() + curr_ind);
labels_.erase(labels_.begin() + curr_ind);
networks_.push_back(net1);
networks_.push_back(net2);
labels_.push_back(labels1);
labels_.push_back(labels2);
if (networks_.size() != labels_.size()) {
throw std::logic_error("Networks and labels do not match.");
}
}
// Process the strongly connected components of the graph. We only work
// on the largest SCC.
void CommDetection::ProcessSCCs() {
Network& net = CurrNetwork();
TCnComV components;
TSnap::GetSccs(net.graph(), components);
if (components.Len() == 1) {
return;
}
int num_scc = components.Len();
std::vector< std::vector<int> > cuts(num_scc);
for (int j = 0; j < num_scc; ++j) {
TCnCom comp = components[j];
std::vector<int>& curr_cut = cuts[j];
for (int i = 0; i < comp.Len(); ++i) {
curr_cut.push_back(comp[i].Val);
}
}
// Find the largest remaining component
int argmax_ind = -1;
int max_val = -1;
for (int i = 0; i < cuts.size(); ++i) {
if (max_val == -1 || cuts[i].size() > max_val) {
argmax_ind = i;
max_val = cuts[i].size();
}
}
// Now we cut out each component
std::cout << "Removing SCC" << std::endl;
Cutter cutter(net, algorithm_, cut_type_, "");
RemoveCutFromCurrNetwork(cutter, cuts[argmax_ind]);
// TODO(arbenson): this is kindof a hack for dealing with SCCs. We don't
// want to process all of them because there are many isolated nodes.
// Instead, we continue processing until the largest community (in terms
// of the number of nodes) is a SCC.
ProcessSCCs();
}
// Run one step of recursive bisection.
void CommDetection::Iterate() {
std::cout << "Number of communities: " << networks_.size() << std::endl;
ProcessSCCs();
if (networks_.size() >= num_comms_) {
return;
}
Cutter cutter(CurrNetwork(), algorithm_, cut_type_,
name_ + "_" + AlgStr(algorithm_));
std::vector<int> cut = cutter.RunIter();
RemoveCutFromCurrNetwork(cutter, cut);
std::cout << "***" << std::endl;
}
// Get the index in our list of networks of the one with the largest
// number of triples.
int CommDetection::CurrNetworkIndex() {
int curr_ind = -1;
int curr_max_triples = 0;
for (int i = 0; i < networks_.size(); ++i) {
Network& net = networks_[i];
if (curr_ind == -1 || net.triples().size() > curr_max_triples) {
curr_ind = i;
curr_max_triples = net.triples().size();
}
}
return curr_ind;
}
| #include "community.hpp"
#include "cut_tools.hpp"
#include "file_io.hpp"
#include "snap_tools.hpp"
#include "tensor_ops.hpp"
#include "Snap.h"
#include <iostream>
#include <stdexcept>
#include <vector>
CommDetection::CommDetection(Network& net, int num_comms, int algorithm, int cut_type,
std::string name) :
num_comms_(num_comms), num_nodes_(net.NumNodes()), algorithm_(algorithm),
cut_type_(cut_type), name_(name) {
networks_.push_back(net);
// TODO(arbenson): there is a better way to do this
labels_.push_back(std::vector<int>());
labels_[0] = Range(net.NumNodes());
}
// Run the community detection algorithm.
void CommDetection::Run() {
while (networks_.size() < num_comms_) {
Iterate();
}
}
// Report the number of triples preserved by the communities.
int CommDetection::NumTriplesPreserved() {
int sum = 0;
for (Network& net : networks_) {
sum += net.triples().size();
}
return sum;
}
// Print the node and edge counts for each of the communities;
void CommDetection::PrintCounts() {
for (Network& net : networks_) {
std::cout << net.NumNodes() << " " << net.NumEdges() << std::endl;
}
}
// Returns the categories of all nodes. The return value is a vector such
// that the i-th entry is the category of the i-th node.
std::vector<int> CommDetection::Communities() {
std::vector<int> communities(num_nodes_, -1);
for (int i = 0; i < labels_.size(); ++i) {
std::vector<int>& curr_labels = labels_[i];
for (int node : curr_labels) {
communities[node] = i;
}
}
for (int comm : communities) {
if (comm == -1) {
std::logic_error("Not all nodes assigned communities.");
}
}
return communities;
}
void CommDetection::RemoveCutFromCurrNetwork(Cutter& cutter, std::vector<int>& cut) {
std::cout << cut.size() << " of " << CurrNetwork().NumNodes()
<< " nodes cut." << std::endl;
Network net1, net2;
cutter.AddCut(cut, net1, net2);
int curr_ind = CurrNetworkIndex();
std::vector<int>& curr_labels = labels_[curr_ind];
std::vector<int> labels1, labels2;
for (int i = 0; i < net1.NumNodes(); ++i) {
labels1.push_back(curr_labels[net1.NodeIndex(i)]);
}
for (int i = 0; i < net2.NumNodes(); ++i) {
labels2.push_back(curr_labels[net2.NodeIndex(i)]);
}
networks_.erase(networks_.begin() + curr_ind);
labels_.erase(labels_.begin() + curr_ind);
networks_.push_back(net1);
networks_.push_back(net2);
labels_.push_back(labels1);
labels_.push_back(labels2);
if (networks_.size() != labels_.size()) {
throw std::logic_error("Networks and labels do not match.");
}
}
// Process the strongly connected components of the graph. We only work
// on the largest SCC.
void CommDetection::ProcessSCCs() {
Network& net = CurrNetwork();
TCnComV components;
TSnap::GetSccs(net.graph(), components);
if (components.Len() == 1) {
return;
}
int num_scc = components.Len();
std::vector< std::vector<int> > cuts(num_scc);
for (int j = 0; j < num_scc; ++j) {
TCnCom comp = components[j];
std::vector<int>& curr_cut = cuts[j];
for (int i = 0; i < comp.Len(); ++i) {
curr_cut.push_back(comp[i].Val);
}
}
// Find the largest remaining component
int argmax_ind = -1;
int max_val = -1;
for (int i = 0; i < cuts.size(); ++i) {
if (max_val == -1 || cuts[i].size() > max_val) {
argmax_ind = i;
max_val = cuts[i].size();
}
}
// Now we cut out each component
std::cout << "Removing SCC" << std::endl;
Cutter cutter(net, algorithm_, cut_type_, "");
RemoveCutFromCurrNetwork(cutter, cuts[argmax_ind]);
// TODO(arbenson): this is kindof a hack for dealing with SCCs. We don't
// want to process all of them because there are many isolated nodes.
// Instead, we continue processing until the largest community (in terms
// of the number of nodes) is a SCC.
if (networks_.size() >= num_comms_) {
return;
}
ProcessSCCs();
}
// Run one step of recursive bisection.
void CommDetection::Iterate() {
std::cout << "Number of communities: " << networks_.size() << std::endl;
ProcessSCCs();
if (networks_.size() >= num_comms_) {
return;
}
Cutter cutter(CurrNetwork(), algorithm_, cut_type_,
name_ + "_" + AlgStr(algorithm_));
std::vector<int> cut = cutter.RunIter();
RemoveCutFromCurrNetwork(cutter, cut);
std::cout << "***" << std::endl;
}
// Get the index in our list of networks of the one with the largest
// number of triples.
int CommDetection::CurrNetworkIndex() {
int curr_ind = -1;
int curr_max_triples = 0;
for (int i = 0; i < networks_.size(); ++i) {
Network& net = networks_[i];
if (curr_ind == -1 || net.triples().size() > curr_max_triples) {
curr_ind = i;
curr_max_triples = net.triples().size();
}
}
return curr_ind;
}
| quit early if total number of communities found. | quit early if total number of communities found.
| C++ | bsd-2-clause | arbenson/tensor-sc,Peratham/tensor-sc,Peratham/tensor-sc,Peratham/tensor-sc,arbenson/tensor-sc,arbenson/tensor-sc,arbenson/tensor-sc,Peratham/tensor-sc |
34b5e0ee363e12de57bd5b2ed54acf93e51000a8 | BalancingRobot/BalancingRobot/Main.cpp | BalancingRobot/BalancingRobot/Main.cpp | // Main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "arduino.h"
#include "Gyroscope.h"
#include "Motors.h"
#include "Regulator.h"
#include "KeyboardController.h"
#define TICK_PER_SECOND 75
#define TICK_LENGTH_MICROSECONDS 1000000L / TICK_PER_SECOND
int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}
Gyroscope gyroscope;
Motors motors;
Regulator angleRegulator(TICK_PER_SECOND);
Regulator speedRegulator(TICK_PER_SECOND / 2);
KeyboardController keyboard;
Integrator speedIntegrator(TICK_PER_SECOND);
float targetSpeed = 0;
float targetAngle = 0;
void setup()
{
motors.init();
gyroscope.init();
keyboard.init();
/*
PID coefficients may vary depending on mechanical properties of the robot/motors/battery
Here are some instructions how to tune the PID
http://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops
*/
// Angle regulator. This PID adjusts the desired angle (normally 0) depending
// on the mean spead of the robot. The goal is to keep the mean speed near 0.
// (robot is staying on one place and does not not drive away)
angleRegulator.init(-0.02, 0, 0); // P is negative, because to compensate positive speed we mast tilt the robot little bit back
// Speed regulator. This PID gets the desired angle from the angle regulator and
// adjusts the acceleartion (power applied to motors) to keep the angle near the desired value.
speedRegulator.init(35, 0.2, 0);
wprintf(L"Press Esc to exit\n");
}
// the loop routine runs over and over again forever:
void loop()
{
wprintf(L"Calibration in 3 seconds\n");
delay(3000);
wprintf(L"Calibrating...");
gyroscope.calibrate();
wprintf(L"Cycle tyme in microseconds: %ld \n", TICK_LENGTH_MICROSECONDS);
// main cycle
delay(100);
unsigned long lastIteration = micros();
unsigned long nextIteration = lastIteration + TICK_LENGTH_MICROSECONDS;
int n = 0;
do {
float actualAngle, deltaAngle;
while (micros() < nextIteration)
{
// do nothing
}
unsigned long now = micros();
gyroscope.getAngleFiltered(actualAngle, deltaAngle, now);
targetAngle = angleRegulator.getResult(speedIntegrator.getSum(), 0, now - lastIteration);
float motorSpeed = 0;
motorSpeed = speedRegulator.getResult(actualAngle - targetAngle, deltaAngle, now - lastIteration);
n++;
if (n % 20 == 0) // Print on every 20th iteration
{
wprintf(L"%d\t%f\t%f\t%f\t%f\n", n, targetAngle, actualAngle, deltaAngle, motorSpeed);
}
motors.setSpeedBoth(motorSpeed);
speedIntegrator.pushValue(motorSpeed);
lastIteration = now;
nextIteration = now + TICK_LENGTH_MICROSECONDS;
keyboard.processEvents();
if (keyboard.shouldExit())
{
break;
}
} while (true);
motors.stopAll();
wprintf(L"Exiting...\n");
exit(0);
} | // Main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "arduino.h"
#include "Gyroscope.h"
#include "Motors.h"
#include "Regulator.h"
#include "KeyboardController.h"
#define TICK_PER_SECOND 75
#define TICK_LENGTH_MICROSECONDS 1000000L / TICK_PER_SECOND
int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}
Gyroscope gyroscope;
Motors motors;
Regulator angleRegulator(TICK_PER_SECOND);
Regulator speedRegulator(TICK_PER_SECOND / 2);
KeyboardController keyboard;
Integrator speedIntegrator(TICK_PER_SECOND);
float targetSpeed = 0;
float targetAngle = 0;
void setup()
{
motors.init();
gyroscope.init();
keyboard.init();
/*
PID coefficients may vary depending on mechanical properties of the robot/motors/battery
Here are some instructions how to tune the PID
http://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops
*/
// Angle regulator. This PID adjusts the desired angle (normally 0) depending
// on the mean speed of the robot. The goal is to keep the mean speed near 0.
// (robot is staying on one place and does not drive away)
angleRegulator.init(-0.02, 0, 0); // P is negative, because to compensate positive speed we mast tilt the robot little bit back
// Speed regulator. This PID gets the desired angle from the angle regulator and
// adjusts the acceleration (power applied to motors) to keep the angle near the desired value.
speedRegulator.init(35, 0.2, 0);
wprintf(L"Press Esc to exit\n");
}
// the loop routine runs over and over again forever:
void loop()
{
wprintf(L"Calibration in 3 seconds\n");
delay(3000);
wprintf(L"Calibrating...");
gyroscope.calibrate();
wprintf(L"Cycle tyme in microseconds: %ld \n", TICK_LENGTH_MICROSECONDS);
// main cycle
delay(100);
unsigned long lastIteration = micros();
unsigned long nextIteration = lastIteration + TICK_LENGTH_MICROSECONDS;
int n = 0;
do {
float actualAngle, deltaAngle;
while (micros() < nextIteration)
{
// do nothing
}
unsigned long now = micros();
gyroscope.getAngleFiltered(actualAngle, deltaAngle, now);
targetAngle = angleRegulator.getResult(speedIntegrator.getSum(), 0, now - lastIteration);
float motorSpeed = 0;
motorSpeed = speedRegulator.getResult(actualAngle - targetAngle, deltaAngle, now - lastIteration);
n++;
if (n % 20 == 0) // Print on every 20th iteration
{
wprintf(L"%d\t%f\t%f\t%f\t%f\n", n, targetAngle, actualAngle, deltaAngle, motorSpeed);
}
motors.setSpeedBoth(motorSpeed);
speedIntegrator.pushValue(motorSpeed);
lastIteration = now;
nextIteration = now + TICK_LENGTH_MICROSECONDS;
keyboard.processEvents();
if (keyboard.shouldExit())
{
break;
}
} while (true);
motors.stopAll();
wprintf(L"Exiting...\n");
exit(0);
} | Fix typos | Fix typos
| C++ | mit | cazacov/IntelGalileo,cazacov/IntelGalileo,cazacov/IntelGalileo |
4ef281e227e02b15aaadf4508bc0326fabd3aba8 | PWG/DevNanoAOD/AliAnalysisTaskNanoAODnormalisation.cxx | PWG/DevNanoAOD/AliAnalysisTaskNanoAODnormalisation.cxx | #include "AliAnalysisTaskNanoAODnormalisation.h"
#include <AliAnalysisManager.h>
#include <AliAODInputHandler.h>
#include <AliESDtrackCuts.h>
#include <AliInputEventHandler.h>
#include <AliNanoFilterNormalisation.h>
#include <AliVEvent.h>
#include <TChain.h>
#include <TObject.h>
#include <algorithm>
#include <cmath>
#include <iostream>
namespace {
constexpr char kNames[2][16 ]{"Filter","Skimming"};
}
AliAnalysisTaskNanoAODnormalisation::AliAnalysisTaskNanoAODnormalisation(std::string taskName) : AliAnalysisTaskSE{taskName.data()},
fOutputList{nullptr},
fCurrentFileName{""},
fNmultBins{100},
fMinMult{0.},
fMaxMult{100.f},
fCandidateEvents{nullptr},
fSelectedEvents{nullptr},
fCandidateEventsUE{nullptr},
fSelectedEventsUE{nullptr}
{
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
}
AliAnalysisTaskNanoAODnormalisation::~AliAnalysisTaskNanoAODnormalisation() {
if (fOutputList)
delete fOutputList;
}
void AliAnalysisTaskNanoAODnormalisation::UserCreateOutputObjects() {
fOutputList = new TList;
fOutputList->SetOwner(true);
for (int iF{0}; iF < 2; ++iF) {
fCandidateEvents[iF] = new TH2D(Form("fCandidateEvents_%s",kNames[iF]), ";Multiplicity estimator;", fNmultBins, fMinMult, fMaxMult, 5, -0.5, 4.5);
fSelectedEvents[iF] = (TH2D*) fCandidateEvents[iF]->Clone(Form("fSelectedEvents_%s",kNames[iF]));
fCandidateEventsUE[iF] = new TH2D(Form("fCandidateEventsUE_%s",kNames[iF]), ";Multiplicity estimator;", fNmultBins, fMinMult, fMaxMult, 5, -0.5, 4.5);
fSelectedEventsUE[iF] = (TH2D*) fCandidateEvents[iF]->Clone(Form("fSelectedEventsUE_%s",kNames[iF]));
std::string labels[5]{"Input events", "Triggered events", "Triggered + Quality cuts", "Triggered + QC + Reco vertex", "Analysis events"};
for (int iType{0}; iType < 5; ++iType) {
fCandidateEvents[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
fSelectedEvents[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
fCandidateEventsUE[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
fSelectedEventsUE[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
}
fOutputList->Add(fCandidateEvents[iF]);
fOutputList->Add(fSelectedEvents[iF]);
fOutputList->Add(fCandidateEventsUE[iF]);
fOutputList->Add(fSelectedEventsUE[iF]);
}
PostData(1, fOutputList);
}
void AliAnalysisTaskNanoAODnormalisation::FillHistograms(TH2D* candidate[2], TH2D* selected[2]) {
AliAODInputHandler* handler = dynamic_cast<AliAODInputHandler*>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!handler) {
::Warning("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing input handler");
return;
}
TList* userInfo = handler->GetUserInfo();
if (!userInfo) {
::Warning("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing User Info");
return;
}
for (int iF{0}; iF < 2; ++iF) {
AliNanoFilterNormalisation* normalisation = (AliNanoFilterNormalisation*)userInfo->FindObject(Form("NanoAOD%s_scaler",kNames[iF]));
if (!normalisation) {
if (!iF)
::Fatal("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing filtering scalers!");
else
::Warning("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing skimming scalers!");
return;
}
candidate[iF]->Add(normalisation->GetCandidateEventsHistogram());
selected[iF]->Add(normalisation->GetSelectedEventsHistogram());
}
PostData(1, fOutputList);
}
Bool_t AliAnalysisTaskNanoAODnormalisation::UserNotify() {
FillHistograms(fCandidateEvents,fSelectedEvents);
return true;
}
/// This is temporary to check if the UserNotify gives us the expected information
void AliAnalysisTaskNanoAODnormalisation::UserExec(Option_t*) {
if (fCurrentFileName != CurrentFileName()) {
fCurrentFileName = CurrentFileName();
FillHistograms(fCandidateEventsUE,fSelectedEventsUE);
}
}
AliAnalysisTaskNanoAODnormalisation* AliAnalysisTaskNanoAODnormalisation::AddTask(std::string name) {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AliAnalysisTaskNanoAODnormalisation::AddTask", "No analysis manager to connect to.");
return nullptr;
}
if (!mgr->GetInputEventHandler()) {
::Error("AliAnalysisTaskNanoAODnormalisation::AddTask", "This task requires an input event handler");
return nullptr;
}
AliAnalysisTaskNanoAODnormalisation *task = new AliAnalysisTaskNanoAODnormalisation(name);
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Normalisation", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:%s", AliAnalysisManager::GetCommonFileName(), "NanoAODNormalisation"));
mgr->ConnectOutput(task, 1, coutput1);
return task;
}
| #include "AliAnalysisTaskNanoAODnormalisation.h"
#include <AliAnalysisManager.h>
#include <AliAODInputHandler.h>
#include <AliESDtrackCuts.h>
#include <AliInputEventHandler.h>
#include <AliNanoFilterNormalisation.h>
#include <AliVEvent.h>
#include <TChain.h>
#include <TObject.h>
#include <algorithm>
#include <cmath>
#include <iostream>
namespace {
constexpr char kNames[2][16 ]{"Filter","Skimming"};
}
AliAnalysisTaskNanoAODnormalisation::AliAnalysisTaskNanoAODnormalisation(std::string taskName) : AliAnalysisTaskSE{taskName.data()},
fOutputList{nullptr},
fCurrentFileName{""},
fNmultBins{100},
fMinMult{0.},
fMaxMult{100.f},
fCandidateEvents{nullptr},
fSelectedEvents{nullptr},
fCandidateEventsUE{nullptr},
fSelectedEventsUE{nullptr}
{
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
}
AliAnalysisTaskNanoAODnormalisation::~AliAnalysisTaskNanoAODnormalisation() {
if (fOutputList)
delete fOutputList;
}
void AliAnalysisTaskNanoAODnormalisation::UserCreateOutputObjects() {
fOutputList = new TList;
fOutputList->SetOwner(true);
for (int iF{0}; iF < 2; ++iF) {
fCandidateEvents[iF] = new TH2D(Form("fCandidateEvents_%s",kNames[iF]), ";Multiplicity estimator;", fNmultBins, fMinMult, fMaxMult, 5, -0.5, 4.5);
fSelectedEvents[iF] = (TH2D*) fCandidateEvents[iF]->Clone(Form("fSelectedEvents_%s",kNames[iF]));
fCandidateEventsUE[iF] = new TH2D(Form("fCandidateEventsUE_%s",kNames[iF]), ";Multiplicity estimator;", fNmultBins, fMinMult, fMaxMult, 5, -0.5, 4.5);
fSelectedEventsUE[iF] = (TH2D*) fCandidateEvents[iF]->Clone(Form("fSelectedEventsUE_%s",kNames[iF]));
std::string labels[5]{"Input events", "Triggered events", "Triggered + Quality cuts", "Triggered + QC + Reco vertex", "Analysis events"};
for (int iType{0}; iType < 5; ++iType) {
fCandidateEvents[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
fSelectedEvents[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
fCandidateEventsUE[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
fSelectedEventsUE[iF]->GetYaxis()->SetBinLabel(iType + 1, labels[iType].data());
}
fOutputList->Add(fCandidateEvents[iF]);
fOutputList->Add(fSelectedEvents[iF]);
fOutputList->Add(fCandidateEventsUE[iF]);
fOutputList->Add(fSelectedEventsUE[iF]);
}
PostData(1, fOutputList);
}
void AliAnalysisTaskNanoAODnormalisation::FillHistograms(TH2D* candidate[2], TH2D* selected[2]) {
AliAODInputHandler* handler = dynamic_cast<AliAODInputHandler*>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!handler) {
::Warning("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing input handler");
return;
}
TList* userInfo = handler->GetUserInfo();
if (!userInfo) {
::Warning("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing User Info");
return;
}
for (int iF{0}; iF < 2; ++iF) {
AliNanoFilterNormalisation* normalisation = (AliNanoFilterNormalisation*)userInfo->FindObject(Form("NanoAOD%s_scaler",kNames[iF]));
if (!normalisation) {
if (!iF)
::Fatal("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing filtering scalers!");
else
::Warning("AliAnalysisTaskNanoAODnormalisation::FillHistograms","Missing skimming scalers!");
continue;
}
candidate[iF]->Add(normalisation->GetCandidateEventsHistogram());
selected[iF]->Add(normalisation->GetSelectedEventsHistogram());
}
PostData(1, fOutputList);
}
Bool_t AliAnalysisTaskNanoAODnormalisation::UserNotify() {
FillHistograms(fCandidateEvents,fSelectedEvents);
return true;
}
/// This is temporary to check if the UserNotify gives us the expected information
void AliAnalysisTaskNanoAODnormalisation::UserExec(Option_t*) {
if (fCurrentFileName != CurrentFileName()) {
fCurrentFileName = CurrentFileName();
FillHistograms(fCandidateEventsUE,fSelectedEventsUE);
}
}
AliAnalysisTaskNanoAODnormalisation* AliAnalysisTaskNanoAODnormalisation::AddTask(std::string name) {
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AliAnalysisTaskNanoAODnormalisation::AddTask", "No analysis manager to connect to.");
return nullptr;
}
if (!mgr->GetInputEventHandler()) {
::Error("AliAnalysisTaskNanoAODnormalisation::AddTask", "This task requires an input event handler");
return nullptr;
}
AliAnalysisTaskNanoAODnormalisation *task = new AliAnalysisTaskNanoAODnormalisation(name);
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Normalisation", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:%s", AliAnalysisManager::GetCommonFileName(), "NanoAODNormalisation"));
mgr->ConnectOutput(task, 1, coutput1);
return task;
}
| Use continue, such that PostData is correctly called | Use continue, such that PostData is correctly called
| C++ | bsd-3-clause | fbellini/AliPhysics,fbellini/AliPhysics,mpuccio/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics,lcunquei/AliPhysics,fcolamar/AliPhysics,lcunquei/AliPhysics,fcolamar/AliPhysics,hzanoli/AliPhysics,sebaleh/AliPhysics,carstooon/AliPhysics,dmuhlhei/AliPhysics,victor-gonzalez/AliPhysics,rbailhac/AliPhysics,lcunquei/AliPhysics,lcunquei/AliPhysics,rbailhac/AliPhysics,sebaleh/AliPhysics,preghenella/AliPhysics,victor-gonzalez/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics,pchrista/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,carstooon/AliPhysics,alisw/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,fbellini/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,amatyja/AliPhysics,rihanphys/AliPhysics,preghenella/AliPhysics,fcolamar/AliPhysics,pchrista/AliPhysics,amatyja/AliPhysics,amaringarcia/AliPhysics,hzanoli/AliPhysics,SHornung1/AliPhysics,amatyja/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,kreisl/AliPhysics,SHornung1/AliPhysics,alisw/AliPhysics,amatyja/AliPhysics,kreisl/AliPhysics,hcab14/AliPhysics,dmuhlhei/AliPhysics,lcunquei/AliPhysics,AMechler/AliPhysics,pchrista/AliPhysics,pbuehler/AliPhysics,victor-gonzalez/AliPhysics,akubera/AliPhysics,amaringarcia/AliPhysics,victor-gonzalez/AliPhysics,hcab14/AliPhysics,hcab14/AliPhysics,pchrista/AliPhysics,fbellini/AliPhysics,mpuccio/AliPhysics,sebaleh/AliPhysics,rbailhac/AliPhysics,amaringarcia/AliPhysics,amaringarcia/AliPhysics,pbuehler/AliPhysics,kreisl/AliPhysics,AMechler/AliPhysics,lcunquei/AliPhysics,alisw/AliPhysics,alisw/AliPhysics,SHornung1/AliPhysics,adriansev/AliPhysics,amatyja/AliPhysics,mpuccio/AliPhysics,rihanphys/AliPhysics,fbellini/AliPhysics,fbellini/AliPhysics,carstooon/AliPhysics,pbuehler/AliPhysics,nschmidtALICE/AliPhysics,lcunquei/AliPhysics,fcolamar/AliPhysics,carstooon/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,adriansev/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,dmuhlhei/AliPhysics,pchrista/AliPhysics,kreisl/AliPhysics,fbellini/AliPhysics,kreisl/AliPhysics,fcolamar/AliPhysics,akubera/AliPhysics,nschmidtALICE/AliPhysics,dmuhlhei/AliPhysics,alisw/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,SHornung1/AliPhysics,akubera/AliPhysics,pbuehler/AliPhysics,adriansev/AliPhysics,carstooon/AliPhysics,sebaleh/AliPhysics,preghenella/AliPhysics,akubera/AliPhysics,SHornung1/AliPhysics,alisw/AliPhysics,hcab14/AliPhysics,carstooon/AliPhysics,hzanoli/AliPhysics,adriansev/AliPhysics,hcab14/AliPhysics,hcab14/AliPhysics,akubera/AliPhysics,rbailhac/AliPhysics,hzanoli/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,akubera/AliPhysics,dmuhlhei/AliPhysics,rbailhac/AliPhysics,nschmidtALICE/AliPhysics,pchrista/AliPhysics,SHornung1/AliPhysics,alisw/AliPhysics,hzanoli/AliPhysics,adriansev/AliPhysics,preghenella/AliPhysics,amatyja/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,mpuccio/AliPhysics,hzanoli/AliPhysics,dmuhlhei/AliPhysics,akubera/AliPhysics,SHornung1/AliPhysics,hzanoli/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,preghenella/AliPhysics,carstooon/AliPhysics,dmuhlhei/AliPhysics,sebaleh/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,pchrista/AliPhysics,rihanphys/AliPhysics,amatyja/AliPhysics,AMechler/AliPhysics,hcab14/AliPhysics,AMechler/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,preghenella/AliPhysics,nschmidtALICE/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics |
ac5000625fbbe1c15664f7e2e4ba26d3378f30f7 | include/comm/buffer.hpp | include/comm/buffer.hpp | /*
* Copyright 2015 C. Brett Witherspoon
*/
#ifndef COMM_BUFFER_HPP_
#define COMM_BUFFER_HPP_
#include <atomic> // for std::atomic
#include <cstddef> // for std::size_t
#include <limits> // for std::numeric_limits
#include <memory> // for std::shared_ptr
namespace comm
{
namespace buffer
{
//! A class for buffer shared data
class impl
{
template<typename> friend class writer;
template<typename> friend class reader;
template<template<typename> class, typename> friend class base;
public:
explicit impl(size_t num_items, size_t item_size);
~impl();
impl(const impl &) = delete;
impl(impl &&) = delete;
impl & operator=(const impl &) = delete;
impl & operator=(impl &&) = delete;
private:
void * d_base;
size_t d_size;
std::atomic<size_t> d_read;
std::atomic<size_t> d_write;
};
//! A base class for a buffer
template<template<typename> class U, typename T>
class base
{
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T &;
using const_reference = const T &;
using pointer = T *;
using const_pointer = const T *;
using iterator = T *;
using const_iterator = const T *;
static_assert(std::numeric_limits<size_type>::is_modulo,
"buffer::base: size_type must support modulo arithmetic");
//! Returns an iterator to the beginning of the buffer
iterator begin();
//! Returns a constant iterator to the beginning of the buffer
const_iterator begin() const;
//! Returns a constant iterator to the beginning of the buffer
const_iterator cbegin() const { return begin(); }
//! Returns an iterator to the end of the buffer
iterator end();
//! Returns a constant iterator to the end of the buffer
const_iterator end() const;
//! Returns a constant iterator to the end of the buffer
const_iterator cend() const { return end(); }
//! Checks whether the buffer is empty
bool empty() const { return d_impl->d_write == d_impl->d_read; }
//! Returns the number of items in the buffer
size_type size() const;
//! Consume items from the buffer
void consume(size_type n);
protected:
explicit base(size_type n);
explicit base(std::shared_ptr<impl> ptr);
base(const base &) = default;
base(base &&) = default;
base & operator=(const base &) = delete;
base & operator=(base && other) = delete;
std::shared_ptr<impl> d_impl;
};
template<template<typename> class T, typename U>
base<T,U>::base(size_type n)
: d_impl{std::make_shared<impl>(n, sizeof(U))}
{ }
template<template<typename> class T, typename U>
base<T,U>::base(std::shared_ptr<impl> ptr)
: d_impl{ptr}
{ }
template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::begin()
{
const auto base = static_cast<pointer>(d_impl->d_base);
return base + static_cast<const T<U> *>(this)->position();
}
template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::begin() const
{
const auto base = static_cast<pointer>(d_impl->d_base);
return base + static_cast<const T<U> *>(this)->position();
}
template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::end()
{
return begin() + size();
}
template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::end() const
{
return begin() + size();
}
template<template<typename> class T, typename U>
typename base<T,U>::size_type base<T,U>::size() const
{
const auto max = std::numeric_limits<size_type>::max();
const auto underflow = max - d_impl->d_size / sizeof(U) + 1;
auto sz = static_cast<const T<U> *>(this)->offset();
if (sz >= underflow)
sz -= underflow;
return sz;
}
template<template<typename> class T, typename U>
void base<T,U>::consume(size_type n)
{
const auto overflow = d_impl->d_size / sizeof(U);
auto pos = static_cast<const T<U> *>(this)->position() + n;
if (pos >= overflow)
pos -= overflow;
static_cast<T<U>*>(this)->position(pos);
}
////////////////////////////////////////////////////////////////////////////////
//! A class to read from a buffer
template<typename T>
class reader : public base<reader,T>
{
template<typename> friend class writer;
template<template<typename> class, typename> friend class base;
public:
using value_type = T;
using size_type = typename base<reader,T>::size_type;
using difference_type = typename base<reader,T>::difference_type;
using reference = T &;
using const_reference = const T &;
using pointer = T *;
using const_pointer = const T *;
using iterator = T *;
using const_iterator = const T *;
private:
using base_type = base<reader,value_type>;
explicit reader(std::shared_ptr<impl> ptr);
size_type offset() const
{
return base_type::d_impl->d_write - base_type::d_impl->d_read;
}
size_type position() const
{
return base_type::d_impl->d_read;
}
void position(size_type pos)
{
base_type::d_impl->d_read = pos;
}
};
template<typename T>
reader<T>::reader(std::shared_ptr<impl> ptr)
: base<reader,T>(ptr)
{ }
////////////////////////////////////////////////////////////////////////////////
//! A class to write to a buffer
template<typename T>
class writer : public base<writer,T>
{
template<template<typename> class, typename> friend class base;
public:
using value_type = T;
using size_type = typename base<reader,T>::size_type;
using difference_type = typename base<reader,T>::difference_type;
using reference = T &;
using const_reference = const T &;
using pointer = T *;
using const_pointer = const T *;
using iterator = T *;
using const_iterator = const T *;
explicit writer(size_type n);
reader<value_type> make_reader();
private:
using base_type = base<writer,value_type>;
size_type offset() const
{
return base_type::d_impl->d_read - base_type::d_impl->d_write - 1;
}
size_type position() const
{
return base_type::d_impl->d_write;
}
void position(size_type pos) const
{
base_type::d_impl->d_write = pos;
}
};
template<typename T>
writer<T>::writer(size_type n)
: base<writer,T>{std::make_shared<impl>(n, sizeof(T))}
{ }
template<typename T>
reader<T> writer<T>::make_reader()
{
return std::move(reader<T>{base<writer,T>::d_impl});
}
} // namespace buffer
} // namespace comm
#endif /* COMM_BUFFER_HPP_ */
| /*
* Copyright 2015 C. Brett Witherspoon
*/
#ifndef COMM_BUFFER_HPP_
#define COMM_BUFFER_HPP_
#include <atomic> // for std::atomic
#include <cstddef> // for std::size_t
#include <limits> // for std::numeric_limits
#include <memory> // for std::shared_ptr
namespace comm
{
namespace buffer
{
//! A class for buffer shared data
class impl
{
public:
explicit impl(size_t num_items, size_t item_size);
~impl();
impl(const impl &) = delete;
impl(impl &&) = delete;
impl & operator=(const impl &) = delete;
impl & operator=(impl &&) = delete;
private:
template<typename> friend class writer;
template<typename> friend class reader;
template<template<typename> class, typename> friend class base;
void * d_base;
size_t d_size;
std::atomic<size_t> d_read;
std::atomic<size_t> d_write;
};
//! A base class for a buffer
template<template<typename> class U, typename T>
class base
{
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T &;
using const_reference = const T &;
using pointer = T *;
using const_pointer = const T *;
using iterator = T *;
using const_iterator = const T *;
static_assert(std::numeric_limits<size_type>::is_modulo,
"buffer::base: modulo arithmetic not supported");
//! Returns an iterator to the beginning of the buffer
iterator begin();
//! Returns a constant iterator to the beginning of the buffer
const_iterator begin() const;
//! Returns a constant iterator to the beginning of the buffer
const_iterator cbegin() const { return begin(); }
//! Returns an iterator to the end of the buffer
iterator end();
//! Returns a constant iterator to the end of the buffer
const_iterator end() const;
//! Returns a constant iterator to the end of the buffer
const_iterator cend() const { return end(); }
//! Checks whether the buffer is empty
bool empty() const { return d_impl->d_write == d_impl->d_read; }
//! Returns the number of items in the buffer
size_type size() const;
//! Consume items from the buffer
void consume(size_type n);
protected:
explicit base(size_type n);
explicit base(std::shared_ptr<impl> ptr);
base(const base &) = default;
base(base &&) = default;
base & operator=(const base &) = delete;
base & operator=(base && other) = delete;
std::shared_ptr<impl> d_impl;
};
template<template<typename> class T, typename U>
base<T,U>::base(size_type n)
: d_impl{std::make_shared<impl>(n, sizeof(U))}
{ }
template<template<typename> class T, typename U>
base<T,U>::base(std::shared_ptr<impl> ptr)
: d_impl{ptr}
{ }
template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::begin()
{
const auto base = static_cast<pointer>(d_impl->d_base);
return base + static_cast<const T<U> *>(this)->position();
}
template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::begin() const
{
const auto base = static_cast<pointer>(d_impl->d_base);
return base + static_cast<const T<U> *>(this)->position();
}
template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::end()
{
return begin() + size();
}
template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::end() const
{
return begin() + size();
}
template<template<typename> class T, typename U>
typename base<T,U>::size_type base<T,U>::size() const
{
const auto max = std::numeric_limits<size_type>::max();
const auto underflow = max - d_impl->d_size / sizeof(U) + 1;
auto sz = static_cast<const T<U> *>(this)->offset();
if (sz >= underflow)
sz -= underflow;
return sz;
}
template<template<typename> class T, typename U>
void base<T,U>::consume(size_type n)
{
const auto overflow = d_impl->d_size / sizeof(U);
auto pos = static_cast<const T<U> *>(this)->position() + n;
if (pos >= overflow)
pos -= overflow;
static_cast<T<U>*>(this)->position(pos);
}
////////////////////////////////////////////////////////////////////////////////
//! A class to read from a buffer
template<typename T>
class reader : public base<reader,T>
{
public:
using value_type = T;
using size_type = typename base<reader,T>::size_type;
using difference_type = typename base<reader,T>::difference_type;
using reference = T &;
using const_reference = const T &;
using pointer = T *;
using const_pointer = const T *;
using iterator = T *;
using const_iterator = const T *;
private:
using base_type = base<reader,value_type>;
template<typename> friend class writer;
template<template<typename> class, typename> friend class base;
explicit reader(std::shared_ptr<impl> ptr);
size_type offset() const
{
return base_type::d_impl->d_write - base_type::d_impl->d_read;
}
size_type position() const
{
return base_type::d_impl->d_read;
}
void position(size_type pos)
{
base_type::d_impl->d_read = pos;
}
};
template<typename T>
reader<T>::reader(std::shared_ptr<impl> ptr)
: base<reader,T>(ptr)
{ }
////////////////////////////////////////////////////////////////////////////////
//! A class to write to a buffer
template<typename T>
class writer : public base<writer,T>
{
public:
using value_type = T;
using size_type = typename base<reader,T>::size_type;
using difference_type = typename base<reader,T>::difference_type;
using reference = T &;
using const_reference = const T &;
using pointer = T *;
using const_pointer = const T *;
using iterator = T *;
using const_iterator = const T *;
explicit writer(size_type n);
reader<value_type> make_reader();
private:
using base_type = base<writer,value_type>;
template<template<typename> class, typename> friend class base;
size_type offset() const
{
return base_type::d_impl->d_read - base_type::d_impl->d_write - 1;
}
size_type position() const
{
return base_type::d_impl->d_write;
}
void position(size_type pos) const
{
base_type::d_impl->d_write = pos;
}
};
template<typename T>
writer<T>::writer(size_type n)
: base<writer,T>{std::make_shared<impl>(n, sizeof(T))}
{ }
template<typename T>
reader<T> writer<T>::make_reader()
{
return std::move(reader<T>{base<writer,T>::d_impl});
}
} // namespace buffer
} // namespace comm
#endif /* COMM_BUFFER_HPP_ */
| put friend declarations under private specifier | buffer: put friend declarations under private specifier
| C++ | isc | bwitherspoon/signum |
d58ab2f034685f3810c4503c9485dd985c4a6803 | contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp | contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp | #include <nntpchan/event.hpp>
#include <sys/types.h>
#include <sys/event.h>
#include <cstring>
#include <errno.h>
namespace nntpchan
{
namespace ev
{
template<size_t bufsz>
struct KqueueLoop : public Loop
{
int kfd;
size_t conns;
char readbuf[bufsz];
KqueueLoop() : kfd(kqueue()), conns(0)
{
};
virtual ~KqueueLoop()
{
::close(kfd);
}
virtual bool TrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_ADD | EV_CLEAR, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1) return false;
if(event.flags & EV_ERROR)
{
std::cerr << "KqueueLoop::TrackConn() kevent failed: " << strerror(event.data) << std::endl;
return false;
}
++conns;
return true;
}
virtual void UntrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_DELETE, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1 || event.flags & EV_ERROR)
std::cerr << "KqueueLoop::UntrackConn() kevent failed: " << strerror(event.data) << std::endl;
else
--conns;
}
virtual void Run()
{
struct kevent events[512];
struct kevent * event;
io * handler;
int ret, idx;
do
{
idx = 0;
ret = kevent(kfd, nullptr, 0, events, 512, nullptr);
if(ret > 0)
{
while(idx < ret)
{
event = &events[idx++];
handler = static_cast<io *>(event->udata);
if(event->flags & EV_EOF)
{
handler->close();
delete handler;
continue;
}
if(event->filter & EVFILT_READ && handler->acceptable())
{
int backlog = event->data;
while(backlog)
{
handler->accept();
--backlog;
}
}
if(event->filter & EVFILT_READ && handler->readable())
{
int readed = 0;
size_t readnum = event->data;
while(readnum > sizeof(readbuf))
{
int r = handler->read(readbuf, sizeof(readbuf));
if(r > 0)
{
readnum -= r;
readed += r;
}
else
readnum = 0;
}
if(readnum && readed != -1)
{
int r = handler->read(readbuf, readnum);
if(r > 0)
readed += r;
else
readed = r;
}
}
if(event->filter & EVFILT_WRITE && handler->writeable())
{
int writespace = 1024;
int written = handler->write(writespace);
if(written == -1)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
// blocking
}
else
{
perror("write()");
handler->close();
delete handler;
continue;
}
}
}
if(!handler->keepalive())
{
handler->close();
delete handler;
}
}
}
}
while(ret != -1);
}
};
}
} | #include <nntpchan/event.hpp>
#include <sys/types.h>
#include <sys/event.h>
#include <iostream>
#include <cstring>
#include <errno.h>
namespace nntpchan
{
namespace ev
{
template<size_t bufsz>
struct KqueueLoop : public Loop
{
int kfd;
size_t conns;
char readbuf[bufsz];
KqueueLoop() : kfd(kqueue()), conns(0)
{
};
virtual ~KqueueLoop()
{
::close(kfd);
}
virtual bool TrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_ADD | EV_CLEAR, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1) return false;
if(event.flags & EV_ERROR)
{
std::cerr << "KqueueLoop::TrackConn() kevent failed: " << strerror(event.data) << std::endl;
return false;
}
++conns;
return true;
}
virtual void UntrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_DELETE, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1 || event.flags & EV_ERROR)
std::cerr << "KqueueLoop::UntrackConn() kevent failed: " << strerror(event.data) << std::endl;
else
--conns;
}
virtual void Run()
{
struct kevent events[512];
struct kevent * event;
io * handler;
int ret, idx;
do
{
idx = 0;
ret = kevent(kfd, nullptr, 0, events, 512, nullptr);
if(ret > 0)
{
while(idx < ret)
{
event = &events[idx++];
handler = static_cast<io *>(event->udata);
if(event->flags & EV_EOF)
{
handler->close();
delete handler;
continue;
}
if(event->filter & EVFILT_READ && handler->acceptable())
{
int backlog = event->data;
while(backlog)
{
handler->accept();
--backlog;
}
}
if(event->filter & EVFILT_READ && handler->readable())
{
int readed = 0;
size_t readnum = event->data;
while(readnum > sizeof(readbuf))
{
int r = handler->read(readbuf, sizeof(readbuf));
if(r > 0)
{
readnum -= r;
readed += r;
}
else
readnum = 0;
}
if(readnum && readed != -1)
{
int r = handler->read(readbuf, readnum);
if(r > 0)
readed += r;
else
readed = r;
}
}
if(event->filter & EVFILT_WRITE && handler->writeable())
{
int writespace = 1024;
int written = handler->write(writespace);
if(written == -1)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
// blocking
}
else
{
perror("write()");
handler->close();
delete handler;
continue;
}
}
}
if(!handler->keepalive())
{
handler->close();
delete handler;
}
}
}
}
while(ret != -1);
}
};
}
} | correct includes | correct includes
| C++ | mit | majestrate/nntpchan,majestrate/nntpchan,majestrate/nntpchan,majestrate/nntpchan,majestrate/nntpchan,majestrate/nntpchan,majestrate/nntpchan |
9d1e65c76756fb08d3e03c879101f9f7ab3f1d5f | RenderSystems/GLES2/src/OgreGLES2FrameBufferObject.cpp | RenderSystems/GLES2/src/OgreGLES2FrameBufferObject.cpp | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreGLES2FrameBufferObject.h"
#include "OgreGLES2HardwarePixelBuffer.h"
#include "OgreGLES2FBORenderTexture.h"
#include "OgreGLES2DepthBuffer.h"
#include "OgreGLUtil.h"
#include "OgreRoot.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLES2Support.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa):
mManager(manager), mNumSamples(fsaa)
{
GLES2Support* glSupport = getGLES2SupportRef();
// Generate framebuffer object
OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB));
if(glSupport->checkExtension("GL_EXT_debug_label"))
{
OGRE_IF_IOS_VERSION_IS_GREATER_THAN(5.0)
OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mFB, 0, ("FBO #" + StringConverter::toString(mFB)).c_str()));
}
mNumSamples = 0;
mMultisampleFB = 0;
// Check multisampling if supported
if(glSupport->hasMinGLVersion(3, 0))
{
// Check samples supported
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB));
GLint maxSamples;
OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamples));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0));
mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples);
}
// Will we need a second FBO to do multisampling?
if (mNumSamples)
{
OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB));
if(glSupport->checkExtension("GL_EXT_debug_label"))
{
OGRE_IF_IOS_VERSION_IS_GREATER_THAN(5.0)
OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mMultisampleFB, 0, ("MSAA FBO #" + StringConverter::toString(mMultisampleFB)).c_str()));
}
}
else
{
mMultisampleFB = 0;
}
// Initialise state
mDepth.buffer = 0;
mStencil.buffer = 0;
for(size_t x = 0; x < OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
{
mColour[x].buffer=0;
}
}
GLES2FrameBufferObject::~GLES2FrameBufferObject()
{
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// Delete framebuffer object
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB));
if (mMultisampleFB)
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB));
}
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
void GLES2FrameBufferObject::notifyOnContextLost()
{
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB));
if (mMultisampleFB)
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB));
}
void GLES2FrameBufferObject::notifyOnContextReset(const GLES2SurfaceDesc &target)
{
// Generate framebuffer object
OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB));
// Bind target to surface 0 and initialise
bindSurface(0, target);
}
#endif
void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target)
{
assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
mColour[attachment] = target;
// Re-initialise
if(mColour[0].buffer)
initialise();
}
void GLES2FrameBufferObject::unbindSurface(size_t attachment)
{
assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
mColour[attachment].buffer = 0;
// Re-initialise if buffer 0 still bound
if(mColour[0].buffer)
initialise();
}
void GLES2FrameBufferObject::initialise()
{
// Release depth and stencil, if they were bound
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// First buffer must be bound
if(!mColour[0].buffer)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Attachment 0 must have surface attached",
"GLES2FrameBufferObject::initialise");
}
// If we're doing multisampling, then we need another FBO which contains a
// renderbuffer which is set up to multisample, and we'll blit it to the final
// FBO afterwards to perform the multisample resolve. In that case, the
// mMultisampleFB is bound during rendering and is the one with a depth/stencil
// Store basic stats
uint32 width = mColour[0].buffer->getWidth();
uint32 height = mColour[0].buffer->getHeight();
GLuint format = mColour[0].buffer->getGLFormat();
ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets();
// Bind simple buffer to add colour attachments
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB));
// Bind all attachment points to frame buffer
for(unsigned int x = 0; x < maxSupportedMRTs; ++x)
{
if(mColour[x].buffer)
{
if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible size ";
ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
ss << ". It must be of the same as the size of surface 0, ";
ss << width << "x" << height;
ss << ".";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise");
}
if(mColour[x].buffer->getGLFormat() != format)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible format.";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise");
}
if(getFormat() == PF_DEPTH)
mColour[x].buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT, mColour[x].zoffset);
else
mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset);
}
else
{
// Detach
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0));
}
}
// Now deal with depth / stencil
if (mMultisampleFB)
{
// Bind multisample buffer
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB));
// Create AA render buffer (colour)
// note, this can be shared too because we blit it to the final FBO
// right after the render is finished
mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);
// Attach it, because we won't be attaching below and non-multisample has
// actually been attached to other FBO
mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0,
mMultisampleColourBuffer.zoffset);
// depth & stencil will be dealt with below
}
// Depth buffer is not handled here anymore.
// See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor()
#if OGRE_NO_GLES3_SUPPORT == 0
GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
GLsizei n=0;
for(unsigned int x=0; x<maxSupportedMRTs; ++x)
{
// Fill attached colour buffers
if(mColour[x].buffer)
{
if(getFormat() == PF_DEPTH)
bufs[x] = GL_DEPTH_ATTACHMENT;
else
bufs[x] = GL_COLOR_ATTACHMENT0 + x;
// Keep highest used buffer + 1
n = x+1;
}
else
{
bufs[x] = GL_NONE;
}
}
// Drawbuffer extension supported, use it
if(getFormat() != PF_DEPTH)
OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs));
if (mMultisampleFB)
{
// we need a read buffer because we'll be blitting to mFB
OGRE_CHECK_GL_ERROR(glReadBuffer(bufs[0]));
}
else
{
// No read buffer, by default, if we want to read anyway we must not forget to set this.
OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE));
}
#endif
// Check status
GLuint status;
OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER));
// Bind main buffer
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
// The screen buffer is 1 on iOS
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 1));
#else
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0));
#endif
switch(status)
{
case GL_FRAMEBUFFER_COMPLETE:
// All is good
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"All framebuffer formats with this texture internal format unsupported",
"GLES2FrameBufferObject::initialise");
default:
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Framebuffer incomplete or other FBO status error",
"GLES2FrameBufferObject::initialise");
}
}
void GLES2FrameBufferObject::bind()
{
// Bind it to FBO
const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB;
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, fb));
}
void GLES2FrameBufferObject::swapBuffers()
{
if (mMultisampleFB)
{
#if OGRE_NO_GLES3_SUPPORT == 0
GLint oldfb = 0;
OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb));
// Blit from multisample buffer to final buffer, triggers resolve
uint32 width = mColour[0].buffer->getWidth();
uint32 height = mColour[0].buffer->getHeight();
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFB));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFB));
OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST));
// Unbind
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb));
#endif
}
}
void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer )
{
GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer);
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ));
if( glDepthBuffer )
{
GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer();
GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer();
//Attach depth buffer, if it has one.
if( depthBuf )
depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 );
//Attach stencil buffer, if it has one.
if( stencilBuf )
stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 );
}
else
{
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, 0));
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, 0));
}
}
//-----------------------------------------------------------------------------
void GLES2FrameBufferObject::detachDepthBuffer()
{
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ));
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 ));
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, 0 ));
}
uint32 GLES2FrameBufferObject::getWidth()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getWidth();
}
uint32 GLES2FrameBufferObject::getHeight()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getHeight();
}
PixelFormat GLES2FrameBufferObject::getFormat()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getFormat();
}
GLsizei GLES2FrameBufferObject::getFSAA()
{
return mNumSamples;
}
//-----------------------------------------------------------------------------
}
| /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreGLES2FrameBufferObject.h"
#include "OgreGLES2HardwarePixelBuffer.h"
#include "OgreGLES2FBORenderTexture.h"
#include "OgreGLES2DepthBuffer.h"
#include "OgreGLUtil.h"
#include "OgreRoot.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLES2Support.h"
namespace Ogre {
//-----------------------------------------------------------------------------
GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa):
mManager(manager), mNumSamples(fsaa)
{
GLES2Support* glSupport = getGLES2SupportRef();
// Generate framebuffer object
OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB));
if(glSupport->checkExtension("GL_EXT_debug_label"))
{
OGRE_IF_IOS_VERSION_IS_GREATER_THAN(5.0)
OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mFB, 0, ("FBO #" + StringConverter::toString(mFB)).c_str()));
}
// Check multisampling if supported
GLint maxSamples = 0;
if(glSupport->hasMinGLVersion(3, 0))
{
// Check samples supported
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB));
OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamples));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0));
}
mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples);
// Will we need a second FBO to do multisampling?
if (mNumSamples)
{
OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB));
if(glSupport->checkExtension("GL_EXT_debug_label"))
{
OGRE_IF_IOS_VERSION_IS_GREATER_THAN(5.0)
OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mMultisampleFB, 0, ("MSAA FBO #" + StringConverter::toString(mMultisampleFB)).c_str()));
}
}
else
{
mMultisampleFB = 0;
}
// Initialise state
mDepth.buffer = 0;
mStencil.buffer = 0;
for(size_t x = 0; x < OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
{
mColour[x].buffer=0;
}
}
GLES2FrameBufferObject::~GLES2FrameBufferObject()
{
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// Delete framebuffer object
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB));
if (mMultisampleFB)
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB));
}
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
void GLES2FrameBufferObject::notifyOnContextLost()
{
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB));
if (mMultisampleFB)
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB));
}
void GLES2FrameBufferObject::notifyOnContextReset(const GLES2SurfaceDesc &target)
{
// Generate framebuffer object
OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB));
// Bind target to surface 0 and initialise
bindSurface(0, target);
}
#endif
void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target)
{
assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
mColour[attachment] = target;
// Re-initialise
if(mColour[0].buffer)
initialise();
}
void GLES2FrameBufferObject::unbindSurface(size_t attachment)
{
assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS);
mColour[attachment].buffer = 0;
// Re-initialise if buffer 0 still bound
if(mColour[0].buffer)
initialise();
}
void GLES2FrameBufferObject::initialise()
{
// Release depth and stencil, if they were bound
mManager->releaseRenderBuffer(mDepth);
mManager->releaseRenderBuffer(mStencil);
mManager->releaseRenderBuffer(mMultisampleColourBuffer);
// First buffer must be bound
if(!mColour[0].buffer)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Attachment 0 must have surface attached",
"GLES2FrameBufferObject::initialise");
}
// If we're doing multisampling, then we need another FBO which contains a
// renderbuffer which is set up to multisample, and we'll blit it to the final
// FBO afterwards to perform the multisample resolve. In that case, the
// mMultisampleFB is bound during rendering and is the one with a depth/stencil
// Store basic stats
uint32 width = mColour[0].buffer->getWidth();
uint32 height = mColour[0].buffer->getHeight();
GLuint format = mColour[0].buffer->getGLFormat();
ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets();
// Bind simple buffer to add colour attachments
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB));
// Bind all attachment points to frame buffer
for(unsigned int x = 0; x < maxSupportedMRTs; ++x)
{
if(mColour[x].buffer)
{
if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible size ";
ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
ss << ". It must be of the same as the size of surface 0, ";
ss << width << "x" << height;
ss << ".";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise");
}
if(mColour[x].buffer->getGLFormat() != format)
{
StringStream ss;
ss << "Attachment " << x << " has incompatible format.";
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise");
}
if(getFormat() == PF_DEPTH)
mColour[x].buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT, mColour[x].zoffset);
else
mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset);
}
else
{
// Detach
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0));
}
}
// Now deal with depth / stencil
if (mMultisampleFB)
{
// Bind multisample buffer
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB));
// Create AA render buffer (colour)
// note, this can be shared too because we blit it to the final FBO
// right after the render is finished
mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);
// Attach it, because we won't be attaching below and non-multisample has
// actually been attached to other FBO
mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0,
mMultisampleColourBuffer.zoffset);
// depth & stencil will be dealt with below
}
// Depth buffer is not handled here anymore.
// See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor()
#if OGRE_NO_GLES3_SUPPORT == 0
GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
GLsizei n=0;
for(unsigned int x=0; x<maxSupportedMRTs; ++x)
{
// Fill attached colour buffers
if(mColour[x].buffer)
{
if(getFormat() == PF_DEPTH)
bufs[x] = GL_DEPTH_ATTACHMENT;
else
bufs[x] = GL_COLOR_ATTACHMENT0 + x;
// Keep highest used buffer + 1
n = x+1;
}
else
{
bufs[x] = GL_NONE;
}
}
// Drawbuffer extension supported, use it
if(getFormat() != PF_DEPTH)
OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs));
if (mMultisampleFB)
{
// we need a read buffer because we'll be blitting to mFB
OGRE_CHECK_GL_ERROR(glReadBuffer(bufs[0]));
}
else
{
// No read buffer, by default, if we want to read anyway we must not forget to set this.
OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE));
}
#endif
// Check status
GLuint status;
OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER));
// Bind main buffer
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
// The screen buffer is 1 on iOS
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 1));
#else
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0));
#endif
switch(status)
{
case GL_FRAMEBUFFER_COMPLETE:
// All is good
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"All framebuffer formats with this texture internal format unsupported",
"GLES2FrameBufferObject::initialise");
default:
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Framebuffer incomplete or other FBO status error",
"GLES2FrameBufferObject::initialise");
}
}
void GLES2FrameBufferObject::bind()
{
// Bind it to FBO
const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB;
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, fb));
}
void GLES2FrameBufferObject::swapBuffers()
{
if (mMultisampleFB)
{
#if OGRE_NO_GLES3_SUPPORT == 0
GLint oldfb = 0;
OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb));
// Blit from multisample buffer to final buffer, triggers resolve
uint32 width = mColour[0].buffer->getWidth();
uint32 height = mColour[0].buffer->getHeight();
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFB));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFB));
OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST));
// Unbind
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb));
#endif
}
}
void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer )
{
GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer);
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ));
if( glDepthBuffer )
{
GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer();
GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer();
//Attach depth buffer, if it has one.
if( depthBuf )
depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 );
//Attach stencil buffer, if it has one.
if( stencilBuf )
stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 );
}
else
{
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, 0));
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, 0));
}
}
//-----------------------------------------------------------------------------
void GLES2FrameBufferObject::detachDepthBuffer()
{
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB ));
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 ));
OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, 0 ));
}
uint32 GLES2FrameBufferObject::getWidth()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getWidth();
}
uint32 GLES2FrameBufferObject::getHeight()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getHeight();
}
PixelFormat GLES2FrameBufferObject::getFormat()
{
assert(mColour[0].buffer);
return mColour[0].buffer->getFormat();
}
GLsizei GLES2FrameBufferObject::getFSAA()
{
return mNumSamples;
}
//-----------------------------------------------------------------------------
}
| allow multisampled FBOs if supported | GLES2: allow multisampled FBOs if supported | C++ | mit | paroj/ogre,paroj/ogre,OGRECave/ogre,paroj/ogre,OGRECave/ogre,OGRECave/ogre,paroj/ogre,OGRECave/ogre,paroj/ogre,OGRECave/ogre |
7f0b877b35747fbfada3c28efadd61df2f62f196 | include/libtorrent/upnp.hpp | include/libtorrent/upnp.hpp | /*
Copyright (c) 2007, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP
#include "libtorrent/socket.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/intrusive_ptr_base.hpp"
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>
#if defined(TORRENT_UPNP_LOGGING)
#include <fstream>
#endif
namespace libtorrent
{
namespace upnp_errors
{
enum error_code_enum
{
no_error = 0,
invalid_argument = 402,
action_failed = 501,
value_not_in_array = 714,
source_ip_cannot_be_wildcarded = 715,
external_port_cannot_be_wildcarded = 716,
port_mapping_conflict = 718,
internal_port_must_match_external = 724,
only_permanent_leases_supported = 725,
remote_host_must_be_wildcard = 726,
external_port_must_be_wildcard = 727,
};
}
#if BOOST_VERSION < 103500
extern asio::error::error_category upnp_category;
#else
struct TORRENT_EXPORT upnp_error_category : boost::system::error_category
{
virtual const char* name() const;
virtual std::string message(int ev) const;
virtual boost::system::error_condition default_error_condition(int ev) const
{ return boost::system::error_condition(ev, *this); }
};
extern TORRENT_EXPORT upnp_error_category upnp_category;
#endif
// int: port-mapping index
// int: external port
// std::string: error message
// an empty string as error means success
// a port-mapping index of -1 means it's
// an informational log message
typedef boost::function<void(int, int, error_code const&)> portmap_callback_t;
typedef boost::function<void(char const*)> log_callback_t;
class TORRENT_EXPORT upnp : public intrusive_ptr_base<upnp>
{
public:
upnp(io_service& ios, connection_queue& cc
, address const& listen_interface, std::string const& user_agent
, portmap_callback_t const& cb, log_callback_t const& lcb
, bool ignore_nonrouters, void* state = 0);
~upnp();
void* drain_state();
enum protocol_type { none = 0, udp = 1, tcp = 2 };
int add_mapping(protocol_type p, int external_port, int local_port);
void delete_mapping(int mapping_index);
bool get_mapping(int mapping_index, int& local_port, int& external_port, int& protocol) const;
void discover_device();
void close();
std::string router_model()
{
mutex_t::scoped_lock l(m_mutex);
return m_model;
}
private:
typedef boost::mutex mutex_t;
void discover_device_impl(mutex_t::scoped_lock& l);
static address_v4 upnp_multicast_address;
static udp::endpoint upnp_multicast_endpoint;
enum { default_lease_time = 3600 };
void resend_request(error_code const& e);
void on_reply(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred);
struct rootdevice;
void next(rootdevice& d, int i, mutex_t::scoped_lock& l);
void update_map(rootdevice& d, int i, mutex_t::scoped_lock& l);
void on_upnp_xml(error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, http_connection& c);
void on_upnp_map_response(error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping, http_connection& c);
void on_upnp_unmap_response(error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping, http_connection& c);
void on_expire(error_code const& e);
void disable(error_code const& ec, mutex_t::scoped_lock& l);
void return_error(int mapping, int code, mutex_t::scoped_lock& l);
void log(char const* msg, mutex_t::scoped_lock& l);
void delete_port_mapping(rootdevice& d, int i);
void create_port_mapping(http_connection& c, rootdevice& d, int i);
void post(upnp::rootdevice const& d, char const* soap
, char const* soap_action, mutex_t::scoped_lock& l);
int num_mappings() const { return int(m_mappings.size()); }
struct global_mapping_t
{
global_mapping_t()
: protocol(none)
, external_port(0)
, local_port(0)
{}
int protocol;
int external_port;
int local_port;
};
struct mapping_t
{
enum action_t { action_none, action_add, action_delete };
mapping_t()
: action(action_none)
, local_port(0)
, external_port(0)
, protocol(none)
, failcount(0)
{}
// the time the port mapping will expire
ptime expires;
int action;
// the local port for this mapping. If this is set
// to 0, the mapping is not in use
int local_port;
// the external (on the NAT router) port
// for the mapping. This is the port we
// should announce to others
int external_port;
// 2 = udp, 1 = tcp
int protocol;
// the number of times this mapping has failed
int failcount;
};
struct rootdevice
{
rootdevice(): service_namespace(0)
, lease_duration(default_lease_time)
, supports_specific_external(true)
, disabled(false)
{
#ifdef TORRENT_DEBUG
magic = 1337;
#endif
}
#ifdef TORRENT_DEBUG
~rootdevice()
{
TORRENT_ASSERT(magic == 1337);
magic = 0;
}
#endif
// the interface url, through which the list of
// supported interfaces are fetched
std::string url;
// the url to the WANIP or WANPPP interface
std::string control_url;
// either the WANIP namespace or the WANPPP namespace
char const* service_namespace;
std::vector<mapping_t> mapping;
// this is the hostname, port and path
// component of the url or the control_url
// if it has been found
std::string hostname;
int port;
std::string path;
int lease_duration;
// true if the device supports specifying a
// specific external port, false if it doesn't
bool supports_specific_external;
bool disabled;
mutable boost::shared_ptr<http_connection> upnp_connection;
#ifdef TORRENT_DEBUG
int magic;
#endif
void close() const
{
TORRENT_ASSERT(magic == 1337);
if (!upnp_connection) return;
upnp_connection->close();
upnp_connection.reset();
}
bool operator<(rootdevice const& rhs) const
{ return url < rhs.url; }
};
struct upnp_state_t
{
std::vector<global_mapping_t> mappings;
std::set<rootdevice> devices;
};
std::vector<global_mapping_t> m_mappings;
std::string const& m_user_agent;
// the set of devices we've found
std::set<rootdevice> m_devices;
portmap_callback_t m_callback;
log_callback_t m_log_callback;
// current retry count
int m_retry_count;
io_service& m_io_service;
// the udp socket used to send and receive
// multicast messages on the network
broadcast_socket m_socket;
// used to resend udp packets in case
// they time out
deadline_timer m_broadcast_timer;
// timer used to refresh mappings
deadline_timer m_refresh_timer;
bool m_disabled;
bool m_closing;
bool m_ignore_non_routers;
connection_queue& m_cc;
mutex_t m_mutex;
std::string m_model;
};
}
#endif
| /*
Copyright (c) 2007, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP
#include "libtorrent/socket.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/intrusive_ptr_base.hpp"
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>
#if defined(TORRENT_UPNP_LOGGING)
#include <fstream>
#endif
namespace libtorrent
{
namespace upnp_errors
{
enum error_code_enum
{
no_error = 0,
invalid_argument = 402,
action_failed = 501,
value_not_in_array = 714,
source_ip_cannot_be_wildcarded = 715,
external_port_cannot_be_wildcarded = 716,
port_mapping_conflict = 718,
internal_port_must_match_external = 724,
only_permanent_leases_supported = 725,
remote_host_must_be_wildcard = 726,
external_port_must_be_wildcard = 727,
};
}
#if BOOST_VERSION < 103500
extern asio::error::error_category upnp_category;
#else
struct TORRENT_EXPORT upnp_error_category : boost::system::error_category
{
virtual const char* name() const;
virtual std::string message(int ev) const;
virtual boost::system::error_condition default_error_condition(int ev) const
{ return boost::system::error_condition(ev, *this); }
};
extern TORRENT_EXPORT upnp_error_category upnp_category;
#endif
// int: port-mapping index
// int: external port
// std::string: error message
// an empty string as error means success
// a port-mapping index of -1 means it's
// an informational log message
typedef boost::function<void(int, int, error_code const&)> portmap_callback_t;
typedef boost::function<void(char const*)> log_callback_t;
class TORRENT_EXPORT upnp : public intrusive_ptr_base<upnp>
{
public:
upnp(io_service& ios, connection_queue& cc
, address const& listen_interface, std::string const& user_agent
, portmap_callback_t const& cb, log_callback_t const& lcb
, bool ignore_nonrouters, void* state = 0);
~upnp();
void* drain_state();
enum protocol_type { none = 0, udp = 1, tcp = 2 };
int add_mapping(protocol_type p, int external_port, int local_port);
void delete_mapping(int mapping_index);
bool get_mapping(int mapping_index, int& local_port, int& external_port, int& protocol) const;
void discover_device();
void close();
std::string router_model()
{
mutex_t::scoped_lock l(m_mutex);
return m_model;
}
private:
typedef boost::mutex mutex_t;
void discover_device_impl(mutex_t::scoped_lock& l);
static address_v4 upnp_multicast_address;
static udp::endpoint upnp_multicast_endpoint;
// there are routers that's don't support timed
// port maps, without returning error 725. It seems
// safer to always assume that we have to ask for
// permanent leases
enum { default_lease_time = 0 };
void resend_request(error_code const& e);
void on_reply(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred);
struct rootdevice;
void next(rootdevice& d, int i, mutex_t::scoped_lock& l);
void update_map(rootdevice& d, int i, mutex_t::scoped_lock& l);
void on_upnp_xml(error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, http_connection& c);
void on_upnp_map_response(error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping, http_connection& c);
void on_upnp_unmap_response(error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping, http_connection& c);
void on_expire(error_code const& e);
void disable(error_code const& ec, mutex_t::scoped_lock& l);
void return_error(int mapping, int code, mutex_t::scoped_lock& l);
void log(char const* msg, mutex_t::scoped_lock& l);
void delete_port_mapping(rootdevice& d, int i);
void create_port_mapping(http_connection& c, rootdevice& d, int i);
void post(upnp::rootdevice const& d, char const* soap
, char const* soap_action, mutex_t::scoped_lock& l);
int num_mappings() const { return int(m_mappings.size()); }
struct global_mapping_t
{
global_mapping_t()
: protocol(none)
, external_port(0)
, local_port(0)
{}
int protocol;
int external_port;
int local_port;
};
struct mapping_t
{
enum action_t { action_none, action_add, action_delete };
mapping_t()
: action(action_none)
, local_port(0)
, external_port(0)
, protocol(none)
, failcount(0)
{}
// the time the port mapping will expire
ptime expires;
int action;
// the local port for this mapping. If this is set
// to 0, the mapping is not in use
int local_port;
// the external (on the NAT router) port
// for the mapping. This is the port we
// should announce to others
int external_port;
// 2 = udp, 1 = tcp
int protocol;
// the number of times this mapping has failed
int failcount;
};
struct rootdevice
{
rootdevice(): service_namespace(0)
, lease_duration(default_lease_time)
, supports_specific_external(true)
, disabled(false)
{
#ifdef TORRENT_DEBUG
magic = 1337;
#endif
}
#ifdef TORRENT_DEBUG
~rootdevice()
{
TORRENT_ASSERT(magic == 1337);
magic = 0;
}
#endif
// the interface url, through which the list of
// supported interfaces are fetched
std::string url;
// the url to the WANIP or WANPPP interface
std::string control_url;
// either the WANIP namespace or the WANPPP namespace
char const* service_namespace;
std::vector<mapping_t> mapping;
// this is the hostname, port and path
// component of the url or the control_url
// if it has been found
std::string hostname;
int port;
std::string path;
int lease_duration;
// true if the device supports specifying a
// specific external port, false if it doesn't
bool supports_specific_external;
bool disabled;
mutable boost::shared_ptr<http_connection> upnp_connection;
#ifdef TORRENT_DEBUG
int magic;
#endif
void close() const
{
TORRENT_ASSERT(magic == 1337);
if (!upnp_connection) return;
upnp_connection->close();
upnp_connection.reset();
}
bool operator<(rootdevice const& rhs) const
{ return url < rhs.url; }
};
struct upnp_state_t
{
std::vector<global_mapping_t> mappings;
std::set<rootdevice> devices;
};
std::vector<global_mapping_t> m_mappings;
std::string const& m_user_agent;
// the set of devices we've found
std::set<rootdevice> m_devices;
portmap_callback_t m_callback;
log_callback_t m_log_callback;
// current retry count
int m_retry_count;
io_service& m_io_service;
// the udp socket used to send and receive
// multicast messages on the network
broadcast_socket m_socket;
// used to resend udp packets in case
// they time out
deadline_timer m_broadcast_timer;
// timer used to refresh mappings
deadline_timer m_refresh_timer;
bool m_disabled;
bool m_closing;
bool m_ignore_non_routers;
connection_queue& m_cc;
mutex_t m_mutex;
std::string m_model;
};
}
#endif
| set default lease duration to 0 for UPnP (permanent lease) | set default lease duration to 0 for UPnP (permanent lease) | C++ | bsd-3-clause | mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code |
16e09ea01ccac0dd51c0242a8cf48df3bc120825 | src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp | src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp | /***************************************************************************
* Copyright (c) 2012 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <gp_Ax2.hxx>
# include <gp_Dir.hxx>
# include <gp_Pnt.hxx>
# include <TopoDS.hxx>
# include <TopoDS_Wire.hxx>
# include <BRepOffsetAPI_MakePipeShell.hxx>
# include <Standard_Version.hxx>
# include <TopTools_ListIteratorOfListOfShape.hxx>
#endif
#include "TopoShapePy.h"
#include "BRepOffsetAPI_MakePipeShellPy.h"
#include "BRepOffsetAPI_MakePipeShellPy.cpp"
#include "Tools.h"
#include "OCCError.h"
#include <Base/VectorPy.h>
#include <Base/GeometryPyCXX.h>
using namespace Part;
PyObject *BRepOffsetAPI_MakePipeShellPy::PyMake(struct _typeobject *, PyObject *args, PyObject *) // Python wrapper
{
// create a new instance of BRepOffsetAPI_MakePipeShellPy and the Twin object
PyObject* obj;
if (!PyArg_ParseTuple(args, "O!",&(TopoShapePy::Type),&obj))
return 0;
const TopoDS_Shape& wire = static_cast<TopoShapePy*>(obj)->getTopoShapePtr()->getShape();
if (!wire.IsNull() && wire.ShapeType() == TopAbs_WIRE) {
return new BRepOffsetAPI_MakePipeShellPy(new BRepOffsetAPI_MakePipeShell(TopoDS::Wire(wire)));
}
PyErr_SetString(PartExceptionOCCError, "A valid wire is needed as argument");
return 0;
}
// constructor method
int BRepOffsetAPI_MakePipeShellPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/)
{
return 0;
}
// returns a string which represents the object e.g. when printed in python
std::string BRepOffsetAPI_MakePipeShellPy::representation(void) const
{
return std::string("<BRepOffsetAPI_MakePipeShell object>");
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setFrenetMode(PyObject *args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args, "O!",&PyBool_Type,&obj))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(PyObject_IsTrue(obj) ? Standard_True : Standard_False);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setTrihedronMode(PyObject *args)
{
PyObject *pnt, *dir;
if (!PyArg_ParseTuple(args, "O!O!",&Base::VectorPy::Type,&pnt
,&Base::VectorPy::Type,&dir))
return 0;
gp_Pnt p = Base::convertTo<gp_Pnt>(Py::Vector(pnt,false).toVector());
gp_Dir d = Base::convertTo<gp_Dir>(Py::Vector(dir,false).toVector());
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(gp_Ax2(p,d));
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setBiNormalMode(PyObject *args)
{
PyObject *dir;
if (!PyArg_ParseTuple(args, "O!",&Base::VectorPy::Type,&dir))
return 0;
gp_Dir d = Base::convertTo<gp_Dir>(Py::Vector(dir,false).toVector());
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(d);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setSpineSupport(PyObject *args)
{
PyObject *shape;
if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&shape))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(s);
return Py::new_reference_to(Py::Boolean(ok ? true : false));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setAuxiliarySpine(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060700
PyObject *spine, *curv, *keep;
if (!PyArg_ParseTuple(args, "O!O!O!",&Part::TopoShapePy::Type,&spine
,&PyBool_Type,&curv
,&PyLong_Type,&keep))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(spine)->getTopoShapePtr()->getShape();
if (s.IsNull() || s.ShapeType() != TopAbs_WIRE) {
PyErr_SetString(PyExc_TypeError, "spine is not a wire");
return 0;
}
BRepFill_TypeOfContact typeOfCantact;
switch (PyLong_AsLong(keep)) {
case 1:
typeOfCantact = BRepFill_Contact;
break;
case 2:
typeOfCantact = BRepFill_ContactOnBorder;
break;
default:
typeOfCantact = BRepFill_NoContact;
break;
}
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(
TopoDS::Wire(s),
PyObject_IsTrue(curv) ? Standard_True : Standard_False,
typeOfCantact);
Py_Return;
#else
PyObject *spine, *curv, *keep;
if (!PyArg_ParseTuple(args, "O!O!O!",&Part::TopoShapePy::Type,&spine
,&PyBool_Type,&curv
,&PyBool_Type,&keep))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(spine)->getTopoShapePtr()->getShape();
if (s.IsNull() || s.ShapeType() != TopAbs_WIRE) {
PyErr_SetString(PyExc_TypeError, "spine is not a wire");
return 0;
}
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(
TopoDS::Wire(s),
PyObject_IsTrue(curv) ? Standard_True : Standard_False,
PyObject_IsTrue(keep) ? Standard_True : Standard_False);
Py_Return;
#endif
}
PyObject* BRepOffsetAPI_MakePipeShellPy::add(PyObject *args)
{
PyObject *prof, *curv=Py_False, *keep=Py_False;
if (!PyArg_ParseTuple(args, "O!|O!O!",&Part::TopoShapePy::Type,&prof
,&PyBool_Type,&curv
,&PyBool_Type,&keep))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(prof)->getTopoShapePtr()->getShape();
this->getBRepOffsetAPI_MakePipeShellPtr()->Add(s,
PyObject_IsTrue(curv) ? Standard_True : Standard_False,
PyObject_IsTrue(keep) ? Standard_True : Standard_False);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::remove(PyObject *args)
{
PyObject *prof;
if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&prof))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(prof)->getTopoShapePtr()->getShape();
this->getBRepOffsetAPI_MakePipeShellPtr()->Delete(s);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::isReady(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->IsReady();
return Py::new_reference_to(Py::Boolean(ok ? true : false));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::getStatus(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
Standard_Integer val = this->getBRepOffsetAPI_MakePipeShellPtr()->GetStatus();
return Py::new_reference_to(Py::Long(val));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::makeSolid(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->MakeSolid();
return Py::new_reference_to(Py::Boolean(ok ? true : false));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::build(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->Build();
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::shape(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
const TopoDS_Shape& shape = this->getBRepOffsetAPI_MakePipeShellPtr()->Shape();
return new TopoShapePy(new TopoShape(shape));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::firstShape(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
TopoDS_Shape shape = this->getBRepOffsetAPI_MakePipeShellPtr()->FirstShape();
return new TopoShapePy(new TopoShape(shape));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::lastShape(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
TopoDS_Shape shape = this->getBRepOffsetAPI_MakePipeShellPtr()->LastShape();
return new TopoShapePy(new TopoShape(shape));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::generated(PyObject *args)
{
PyObject *shape;
if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&shape))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
const TopTools_ListOfShape& list = this->getBRepOffsetAPI_MakePipeShellPtr()->Generated(s);
Py::List shapes;
TopTools_ListIteratorOfListOfShape it;
for (it.Initialize(list); it.More(); it.Next()) {
const TopoDS_Shape& s = it.Value();
shapes.append(Py::asObject(new TopoShapePy(new TopoShape(s))));
}
return Py::new_reference_to(shapes);
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setTolerance(PyObject *args)
{
double tol3d, boundTol, tolAngular;
if (!PyArg_ParseTuple(args, "ddd",&tol3d,&boundTol,&tolAngular))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetTolerance(tol3d, boundTol, tolAngular);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setTransitionMode(PyObject *args)
{
int mode;
if (!PyArg_ParseTuple(args, "i",&mode))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetTransitionMode(BRepBuilderAPI_TransitionMode(mode));
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxDegree(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060800
int degree;
if (!PyArg_ParseTuple(args, "i",°ree))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMaxDegree(degree);
Py_Return;
#else
PyErr_SetString(PyExc_RuntimeError, "requires OCC >= 6.8");
return 0;
#endif
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxSegments(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060800
int nbseg;
if (!PyArg_ParseTuple(args, "i",&nbseg))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMaxSegments(nbseg);
Py_Return;
#else
PyErr_SetString(PyExc_RuntimeError, "requires OCC >= 6.8");
return 0;
#endif
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setForceApproxC1(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060700
PyObject *obj;
if (!PyArg_ParseTuple(args, "O!",&PyBool_Type,&obj))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetForceApproxC1(PyObject_IsTrue(obj) ? Standard_True : Standard_False);
Py_Return;
#else
PyErr_SetString(PyExc_RuntimeError, "requires OCC >= 6.7");
return 0;
#endif
}
PyObject *BRepOffsetAPI_MakePipeShellPy::getCustomAttributes(const char* ) const
{
return 0;
}
int BRepOffsetAPI_MakePipeShellPy::setCustomAttributes(const char* , PyObject *)
{
return 0;
}
| /***************************************************************************
* Copyright (c) 2012 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <gp_Ax2.hxx>
# include <gp_Dir.hxx>
# include <gp_Pnt.hxx>
# include <TopoDS.hxx>
# include <TopoDS_Wire.hxx>
# include <BRepOffsetAPI_MakePipeShell.hxx>
# include <Standard_Version.hxx>
# include <TopTools_ListIteratorOfListOfShape.hxx>
#endif
#include "TopoShapePy.h"
#include "BRepOffsetAPI_MakePipeShellPy.h"
#include "BRepOffsetAPI_MakePipeShellPy.cpp"
#include "Tools.h"
#include "OCCError.h"
#include <Base/VectorPy.h>
#include <Base/GeometryPyCXX.h>
using namespace Part;
PyObject *BRepOffsetAPI_MakePipeShellPy::PyMake(struct _typeobject *, PyObject *args, PyObject *) // Python wrapper
{
// create a new instance of BRepOffsetAPI_MakePipeShellPy and the Twin object
PyObject* obj;
if (!PyArg_ParseTuple(args, "O!",&(TopoShapePy::Type),&obj))
return 0;
const TopoDS_Shape& wire = static_cast<TopoShapePy*>(obj)->getTopoShapePtr()->getShape();
if (!wire.IsNull() && wire.ShapeType() == TopAbs_WIRE) {
return new BRepOffsetAPI_MakePipeShellPy(new BRepOffsetAPI_MakePipeShell(TopoDS::Wire(wire)));
}
PyErr_SetString(PartExceptionOCCError, "A valid wire is needed as argument");
return 0;
}
// constructor method
int BRepOffsetAPI_MakePipeShellPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/)
{
return 0;
}
// returns a string which represents the object e.g. when printed in python
std::string BRepOffsetAPI_MakePipeShellPy::representation(void) const
{
return std::string("<BRepOffsetAPI_MakePipeShell object>");
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setFrenetMode(PyObject *args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args, "O!",&PyBool_Type,&obj))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(PyObject_IsTrue(obj) ? Standard_True : Standard_False);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setTrihedronMode(PyObject *args)
{
PyObject *pnt, *dir;
if (!PyArg_ParseTuple(args, "O!O!",&Base::VectorPy::Type,&pnt
,&Base::VectorPy::Type,&dir))
return 0;
gp_Pnt p = Base::convertTo<gp_Pnt>(Py::Vector(pnt,false).toVector());
gp_Dir d = Base::convertTo<gp_Dir>(Py::Vector(dir,false).toVector());
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(gp_Ax2(p,d));
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setBiNormalMode(PyObject *args)
{
PyObject *dir;
if (!PyArg_ParseTuple(args, "O!",&Base::VectorPy::Type,&dir))
return 0;
gp_Dir d = Base::convertTo<gp_Dir>(Py::Vector(dir,false).toVector());
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(d);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setSpineSupport(PyObject *args)
{
PyObject *shape;
if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&shape))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(s);
return Py::new_reference_to(Py::Boolean(ok ? true : false));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setAuxiliarySpine(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060700
PyObject *spine, *curv, *keep;
if (!PyArg_ParseTuple(args, "O!O!O!",&Part::TopoShapePy::Type,&spine
,&PyBool_Type,&curv
,&PyLong_Type,&keep))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(spine)->getTopoShapePtr()->getShape();
if (s.IsNull() || s.ShapeType() != TopAbs_WIRE) {
PyErr_SetString(PyExc_TypeError, "spine is not a wire");
return 0;
}
BRepFill_TypeOfContact typeOfCantact;
switch (PyLong_AsLong(keep)) {
case 1:
typeOfCantact = BRepFill_Contact;
break;
case 2:
typeOfCantact = BRepFill_ContactOnBorder;
break;
default:
typeOfCantact = BRepFill_NoContact;
break;
}
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(
TopoDS::Wire(s),
PyObject_IsTrue(curv) ? Standard_True : Standard_False,
typeOfCantact);
Py_Return;
#else
PyObject *spine, *curv, *keep;
if (!PyArg_ParseTuple(args, "O!O!O!",&Part::TopoShapePy::Type,&spine
,&PyBool_Type,&curv
,&PyBool_Type,&keep))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(spine)->getTopoShapePtr()->getShape();
if (s.IsNull() || s.ShapeType() != TopAbs_WIRE) {
PyErr_SetString(PyExc_TypeError, "spine is not a wire");
return 0;
}
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(
TopoDS::Wire(s),
PyObject_IsTrue(curv) ? Standard_True : Standard_False,
PyObject_IsTrue(keep) ? Standard_True : Standard_False);
Py_Return;
#endif
}
PyObject* BRepOffsetAPI_MakePipeShellPy::add(PyObject *args)
{
PyObject *prof, *curv=Py_False, *keep=Py_False;
if (!PyArg_ParseTuple(args, "O!|O!O!",&Part::TopoShapePy::Type,&prof
,&PyBool_Type,&curv
,&PyBool_Type,&keep))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(prof)->getTopoShapePtr()->getShape();
this->getBRepOffsetAPI_MakePipeShellPtr()->Add(s,
PyObject_IsTrue(curv) ? Standard_True : Standard_False,
PyObject_IsTrue(keep) ? Standard_True : Standard_False);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::remove(PyObject *args)
{
PyObject *prof;
if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&prof))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(prof)->getTopoShapePtr()->getShape();
this->getBRepOffsetAPI_MakePipeShellPtr()->Delete(s);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::isReady(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->IsReady();
return Py::new_reference_to(Py::Boolean(ok ? true : false));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::getStatus(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
Standard_Integer val = this->getBRepOffsetAPI_MakePipeShellPtr()->GetStatus();
return Py::new_reference_to(Py::Long(val));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::makeSolid(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->MakeSolid();
return Py::new_reference_to(Py::Boolean(ok ? true : false));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::build(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->Build();
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::shape(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
const TopoDS_Shape& shape = this->getBRepOffsetAPI_MakePipeShellPtr()->Shape();
return new TopoShapePy(new TopoShape(shape));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::firstShape(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
TopoDS_Shape shape = this->getBRepOffsetAPI_MakePipeShellPtr()->FirstShape();
return new TopoShapePy(new TopoShape(shape));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::lastShape(PyObject *args)
{
if (!PyArg_ParseTuple(args, ""))
return 0;
TopoDS_Shape shape = this->getBRepOffsetAPI_MakePipeShellPtr()->LastShape();
return new TopoShapePy(new TopoShape(shape));
}
PyObject* BRepOffsetAPI_MakePipeShellPy::generated(PyObject *args)
{
PyObject *shape;
if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&shape))
return 0;
const TopoDS_Shape& s = static_cast<Part::TopoShapePy*>(shape)->getTopoShapePtr()->getShape();
const TopTools_ListOfShape& list = this->getBRepOffsetAPI_MakePipeShellPtr()->Generated(s);
Py::List shapes;
TopTools_ListIteratorOfListOfShape it;
for (it.Initialize(list); it.More(); it.Next()) {
const TopoDS_Shape& s = it.Value();
shapes.append(Py::asObject(new TopoShapePy(new TopoShape(s))));
}
return Py::new_reference_to(shapes);
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setTolerance(PyObject *args)
{
double tol3d, boundTol, tolAngular;
if (!PyArg_ParseTuple(args, "ddd",&tol3d,&boundTol,&tolAngular))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetTolerance(tol3d, boundTol, tolAngular);
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setTransitionMode(PyObject *args)
{
int mode;
if (!PyArg_ParseTuple(args, "i",&mode))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetTransitionMode(BRepBuilderAPI_TransitionMode(mode));
Py_Return;
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxDegree(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060800
int degree;
if (!PyArg_ParseTuple(args, "i",°ree))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMaxDegree(degree);
Py_Return;
#else
(void)args;
PyErr_SetString(PyExc_RuntimeError, "requires OCC >= 6.8");
return 0;
#endif
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxSegments(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060800
int nbseg;
if (!PyArg_ParseTuple(args, "i",&nbseg))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetMaxSegments(nbseg);
Py_Return;
#else
(void)args;
PyErr_SetString(PyExc_RuntimeError, "requires OCC >= 6.8");
return 0;
#endif
}
PyObject* BRepOffsetAPI_MakePipeShellPy::setForceApproxC1(PyObject *args)
{
#if OCC_VERSION_HEX >= 0x060700
PyObject *obj;
if (!PyArg_ParseTuple(args, "O!",&PyBool_Type,&obj))
return 0;
this->getBRepOffsetAPI_MakePipeShellPtr()->SetForceApproxC1(PyObject_IsTrue(obj) ? Standard_True : Standard_False);
Py_Return;
#else
PyErr_SetString(PyExc_RuntimeError, "requires OCC >= 6.7");
return 0;
#endif
}
PyObject *BRepOffsetAPI_MakePipeShellPy::getCustomAttributes(const char* ) const
{
return 0;
}
int BRepOffsetAPI_MakePipeShellPy::setCustomAttributes(const char* , PyObject *)
{
return 0;
}
| fix warning of unused variable | fix warning of unused variable
| C++ | lgpl-2.1 | Fat-Zer/FreeCAD_sf_master,Fat-Zer/FreeCAD_sf_master,Fat-Zer/FreeCAD_sf_master,Fat-Zer/FreeCAD_sf_master,Fat-Zer/FreeCAD_sf_master |
b237656a19f5334183ed934393ae65130c129456 | glc_openglexception.cpp | glc_openglexception.cpp | /****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_openglexception.cpp implementation of the GLC_OpenGlException class.
#include "glc_openglexception.h"
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
GLC_OpenGlException::GLC_OpenGlException(const QString& message, GLenum glError)
:GLC_Exception(message)
{
switch (glError)
{
case GL_INVALID_ENUM :
m_GlErrorDescription= "GLenum argument out of range";
break;
case GL_INVALID_VALUE :
m_GlErrorDescription= "Numeric argument out of range";
break;
case GL_INVALID_OPERATION :
m_GlErrorDescription= "Operation illegal in current state";
break;
case GL_STACK_OVERFLOW :
m_GlErrorDescription= "Command would cause a stack overflow";
break;
case GL_STACK_UNDERFLOW :
m_GlErrorDescription= "Command would cause a stack underflow";
break;
case GL_OUT_OF_MEMORY :
m_GlErrorDescription= "Not enough memmory left to execute command";
break;
default :
m_GlErrorDescription= "VERY BAD : UNKNOWN ERROR";
break;
}
}
GLC_OpenGlException::~GLC_OpenGlException() throw()
{
}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// Return exception description
const char* GLC_OpenGlException::what() const throw()
{
QString exceptionmsg("GLC_OpenGlException : ");
exceptionmsg.append(m_ErrorDescription);
exceptionmsg.append(m_GlErrorDescription);
return exceptionmsg.toAscii().data();
}
| /****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon ([email protected])
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_openglexception.cpp implementation of the GLC_OpenGlException class.
#include "glc_openglexception.h"
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
GLC_OpenGlException::GLC_OpenGlException(const QString& message, GLenum glError)
:GLC_Exception(message)
{
switch (glError)
{
case GL_INVALID_ENUM :
m_GlErrorDescription= "GLenum argument out of range";
break;
case GL_INVALID_VALUE :
m_GlErrorDescription= "Numeric argument out of range";
break;
case GL_INVALID_OPERATION :
m_GlErrorDescription= "Operation illegal in current state";
break;
case GL_STACK_OVERFLOW :
m_GlErrorDescription= "Command would cause a stack overflow";
break;
case GL_STACK_UNDERFLOW :
m_GlErrorDescription= "Command would cause a stack underflow";
break;
case GL_OUT_OF_MEMORY :
m_GlErrorDescription= "Not enough memmory left to execute command";
break;
case GL_TABLE_TOO_LARGE :
m_GlErrorDescription= "The specified table exceeds the implementation's maximum supported table size";
break;
default :
m_GlErrorDescription= "VERY BAD : UNKNOWN ERROR";
break;
}
}
GLC_OpenGlException::~GLC_OpenGlException() throw()
{
}
//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
// Return exception description
const char* GLC_OpenGlException::what() const throw()
{
QString exceptionmsg("GLC_OpenGlException : ");
exceptionmsg.append(m_ErrorDescription);
exceptionmsg.append(m_GlErrorDescription);
return exceptionmsg.toAscii().data();
}
| add new OpenGL error description | add new OpenGL error description
| C++ | lgpl-2.1 | 3drepo/GLC_lib |
5638dac889bddb16420d8321067c783438a5deaf | include/signum/math.hpp | include/signum/math.hpp | /*
* Copyright 2015, 2016 C. Brett Witherspoon
*
* This file is part of the signum library
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef SIGNUM_MATH_HPP_
#define SIGNUM_MATH_HPP_
#include <type_traits>
namespace signum
{
namespace math
{
/**
* \brief Return the absolute value of the argument.
*
* Until C++14 the STL version of this function is not constexpr, so we use
* this.
*
* \param v the argument
* \return the absolute value of v
*
*/
template<typename T>
constexpr T abs(T v)
{
static_assert(std::is_arithmetic<T>::value,
"template argument must be an arithmetic type.");
return (v < 0) ? -v : v;
}
/**
* \brief Return the maximum of the arguments
*
* Until C++14 the STL version of this function is not constexpr, so we use
* this.
*
* \param a an argument
* \param b an argument
* \return the maximum of a and b
*/
template<typename T>
constexpr T max(T a, T b)
{
static_assert(std::is_arithmetic<T>::value,
"template argument must be an arithmetic type.");
return (a > b) ? a : b;
}
/**
* \brief Compute the greatest common divisor of the arguments
* \param a an integer
* \param b an integer
* \return the greatest common divisor of a and b
*/
template<typename T>
constexpr T gcd(T a, T b)
{
static_assert(std::is_integral<T>::value,
"template argument must be an integral type.");
return (b == 0) ? a : gcd(b, a % b);
}
/**
* \brief Compute the least common multiple of the aruments
* \param a an integer
* \param b an integer
* \return the least common multiple of a and b
*/
template <typename T>
constexpr T lcm(T a, T b)
{
return (a == 0 and b == 0) ? 0 : (abs(a) / gcd(a, b)) * abs(b);
}
/**
* \brief Compute the next higher power of two
* \param a an integer
* \return the smallest power of two greater then a
*/
template <typename T>
constexpr T nextpow2(T a)
{
static_assert(std::is_integral<T>::value,
"template argument must be an integral type.");
T n = 1;
while (n < a) n <<= 1;
return n;
}
} /* namespace math */
} /* namespace signum */
#endif /* SIGNUM_MATH_HPP_ */
| /*
* Copyright 2015-2018 C. Brett Witherspoon
*
* This file is part of the signum library
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef SIGNUM_MATH_HPP_
#define SIGNUM_MATH_HPP_
#include <type_traits>
namespace signum
{
namespace math
{
/**
* \brief Return the absolute value of the argument.
*
* Until C++14 the STL version of this function is not constexpr, so we use
* this.
*
* \param v the argument
* \return the absolute value of v
*
*/
template<typename T>
constexpr T abs(T v)
{
static_assert(std::is_arithmetic<T>::value,
"template argument must be an arithmetic type.");
return (v < 0) ? -v : v;
}
/**
* \brief Return the maximum of the arguments
*
* Until C++14 the STL version of this function is not constexpr, so we use
* this.
*
* \param a an argument
* \param b an argument
* \return the maximum of a and b
*/
template<typename T>
constexpr T max(T a, T b)
{
static_assert(std::is_arithmetic<T>::value,
"template argument must be an arithmetic type.");
return (a > b) ? a : b;
}
/**
* \brief Compute the greatest common divisor of the arguments
* \param a an integer
* \param b an integer
* \return the greatest common divisor of a and b
*/
template<typename T>
constexpr T gcd(T a, T b)
{
static_assert(std::is_integral<T>::value,
"template argument must be an integral type.");
return (b == 0) ? a : gcd(b, a % b);
}
/**
* \brief Compute the least common multiple of the aruments
* \param a an integer
* \param b an integer
* \return the least common multiple of a and b
*/
template <typename T>
constexpr T lcm(T a, T b)
{
return (a == 0 and b == 0) ? 0 : (abs(a) / gcd(a, b)) * abs(b);
}
/**
* \brief Compute the next higher power of two
* \param a an integer
* \return the smallest power of two greater then a
*/
template <typename T>
constexpr T nextpow2(T a)
{
static_assert(std::is_integral<T>::value,
"template argument must be an integral type.");
T n = 1;
while (n < a) n <<= 1;
return n;
}
/**
* \brief Determine if an integral value is a power of two
* \param a an integral value
* \return true if the integral value is a power of two or false otherwise
*/
template <typename T>
constexpr bool ispow2(T x)
{
static_assert(std::is_integral<T>::value,
"template argument must be an integral type.");
return !(x == 0 || (x & (x - 1)));
}
} /* namespace math */
} /* namespace signum */
#endif /* SIGNUM_MATH_HPP_ */
| add ispow2 | math: add ispow2
| C++ | isc | bwitherspoon/signum |
861d87d5526a25aef49d8acc99ba5a8ee12a8337 | include/svx/svddrag.hxx | include/svx/svddrag.hxx | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#ifndef INCLUDED_SVX_SVDDRAG_HXX
#define INCLUDED_SVX_SVDDRAG_HXX
#include <tools/gen.hxx>
#include <tools/fract.hxx>
#include <svx/svxdllapi.h>
// Status information for specialized object dragging. In order for the model
// to stay status free, the status data is kept on the View
// and handed over to the object at the appropriate time as a parameter.
// This also includes the status of the operation and Interactive
// Object creation. In this case, pHdl is null.
class SdrHdl;
class SdrView;
class SdrPageView;
class SdrDragMethod;
struct SVX_DLLPUBLIC SdrDragStatUserData
{
};
class SVX_DLLPUBLIC SdrDragStat {
protected:
SdrHdl* pHdl; // The Handle for the User
SdrView* pView;
SdrPageView* pPageView;
std::vector<Point*> aPnts; // All previous Points: [0]=Start, [Count()-2]=Prev
Point aRef1; // Referencepoint: Resize fixed point, (axis of rotation,
Point aRef2; // axis of reflection, ...)
Point aPos0; // Position at the last Event
Point aRealPos0; // Position at the last Event
Point aRealNow; // Current dragging position without Snap, Ortho and Limit
Point aRealLast; // RealPos of the last Point (for MinMoved)
Rectangle aActionRect;
// Backup for compatible extensions which otherwise would become incompatible
Point aReservePoint1;
Point aReservePoint2;
Point aReservePoint3;
Point aReservePoint4;
Rectangle aReserveRect1;
Rectangle aReserveRect2;
bool bEndDragChangesAttributes;
bool bEndDragChangesGeoAndAttributes;
bool bMouseIsUp;
bool aReserveBool3;
bool aReserveBool4;
long aReserveLong1;
long aReserveLong2;
long aReserveLong3;
long aReserveLong4;
void* aReservePtr1;
void* aReservePtr2;
void* aReservePtr3;
void* aReservePtr4;
bool bShown; // Xor visible?
sal_uInt16 nMinMov; // So much has to be minimally moved first
bool bMinMoved; // MinMove surpassed?
bool bHorFixed; // Dragging only vertical
bool bVerFixed; // Dragging only horizontal
bool bWantNoSnap; // To decide if pObj-> MovCreate () should use NoSnapPos or not.
// Therefore, NoSnapPos is written into the buffer.
bool bOrtho4;
bool bOrtho8;
SdrDragMethod* pDragMethod;
protected:
void Clear(bool bLeaveOne);
Point& Pnt(sal_uIntPtr nNum) { return *aPnts[nNum]; }
//public:
SdrDragStatUserData* pUser; // Userdata
public:
SdrDragStat(): aPnts() { pUser=NULL; Reset(); }
~SdrDragStat() { Clear(false); }
void Reset();
SdrView* GetView() const { return pView; }
void SetView(SdrView* pV) { pView=pV; }
SdrPageView* GetPageView() const { return pPageView; }
void SetPageView(SdrPageView* pPV) { pPageView=pPV; }
const Point& GetPoint(sal_uIntPtr nNum) const { return *aPnts[nNum]; }
sal_uIntPtr GetPointAnz() const { return aPnts.size(); }
const Point& GetStart() const { return GetPoint(0); }
Point& Start() { return Pnt(0); }
const Point& GetPrev() const { return GetPoint(GetPointAnz()-(GetPointAnz()>=2 ? 2:1)); }
Point& Prev() { return Pnt(GetPointAnz()-(GetPointAnz()>=2 ? 2:1)); }
const Point& GetPos0() const { return aPos0; }
Point& Pos0() { return aPos0; }
const Point& GetNow() const { return GetPoint(GetPointAnz()-1); }
Point& Now() { return Pnt(GetPointAnz()-1); }
const Point& GetRealNow() const { return aRealNow; }
Point& RealNow() { return aRealNow; }
const Point& GetRef1() const { return aRef1; }
Point& Ref1() { return aRef1; }
const Point& GetRef2() const { return aRef2; }
Point& Ref2() { return aRef2; }
const SdrHdl* GetHdl() const { return pHdl; }
void SetHdl(SdrHdl* pH) { pHdl=pH; }
SdrDragStatUserData* GetUser() const { return pUser; }
void SetUser(SdrDragStatUserData* pU) { pUser=pU; }
bool IsShown() const { return bShown; }
void SetShown(bool bOn) { bShown=bOn; }
bool IsMinMoved() const { return bMinMoved; }
void SetMinMoved() { bMinMoved=true; }
void ResetMinMoved() { bMinMoved=false; }
void SetMinMove(sal_uInt16 nDist) { nMinMov=nDist; if (nMinMov<1) nMinMov=1; }
sal_uInt16 GetMinMove() const { return nMinMov; }
bool IsHorFixed() const { return bHorFixed; }
void SetHorFixed(bool bOn) { bHorFixed=bOn; }
bool IsVerFixed() const { return bVerFixed; }
void SetVerFixed(bool bOn) { bVerFixed=bOn; }
// Here, the object can say: "I do not want to snap to coordinates!"
// for example, the angle of the arc ...
bool IsNoSnap() const { return bWantNoSnap; }
void SetNoSnap(bool bOn = true) { bWantNoSnap=bOn; }
// And here the Obj say which Ortho (if there is one) can be usefully applied to him.
// Ortho4 means Ortho in four directions (for Rect and CIRT)
bool IsOrtho4Possible() const { return bOrtho4; }
void SetOrtho4Possible(bool bOn = true) { bOrtho4=bOn; }
// Ortho8 means Ortho in 8 directions (for lines)
bool IsOrtho8Possible() const { return bOrtho8; }
void SetOrtho8Possible(bool bOn = true) { bOrtho8=bOn; }
// Is set by an object that was dragged.
bool IsEndDragChangesAttributes() const { return bEndDragChangesAttributes; }
void SetEndDragChangesAttributes(bool bOn) { bEndDragChangesAttributes=bOn; }
bool IsEndDragChangesGeoAndAttributes() const { return bEndDragChangesGeoAndAttributes; }
void SetEndDragChangesGeoAndAttributes(bool bOn) { bEndDragChangesGeoAndAttributes=bOn; }
// Is set by the view and can be evaluated by Obj
bool IsMouseDown() const { return !bMouseIsUp; }
void SetMouseDown(bool bDown) { bMouseIsUp=!bDown; }
Point KorregPos(const Point& rNow, const Point& rPrev) const;
void Reset(const Point& rPnt);
void NextMove(const Point& rPnt);
void NextPoint(bool bSaveReal=false);
void PrevPoint();
bool CheckMinMoved(const Point& rPnt);
long GetDX() const { return GetNow().X()-GetPrev().X(); }
long GetDY() const { return GetNow().Y()-GetPrev().Y(); }
Fraction GetXFact() const;
Fraction GetYFact() const;
SdrDragMethod* GetDragMethod() const { return pDragMethod; }
void SetDragMethod(SdrDragMethod* pMth) { pDragMethod=pMth; }
const Rectangle& GetActionRect() const { return aActionRect; }
void SetActionRect(const Rectangle& rR) { aActionRect=rR; }
// Also considering 1stPointAsCenter
void TakeCreateRect(Rectangle& rRect) const;
};
#endif // INCLUDED_SVX_SVDDRAG_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#ifndef INCLUDED_SVX_SVDDRAG_HXX
#define INCLUDED_SVX_SVDDRAG_HXX
#include <tools/gen.hxx>
#include <tools/fract.hxx>
#include <svx/svxdllapi.h>
// Status information for specialized object dragging. In order for the model
// to stay status free, the status data is kept on the View
// and handed over to the object at the appropriate time as a parameter.
// This also includes the status of the operation and Interactive
// Object creation. In this case, pHdl is null.
class SdrHdl;
class SdrView;
class SdrPageView;
class SdrDragMethod;
struct SVX_DLLPUBLIC SdrDragStatUserData
{
};
class SVX_DLLPUBLIC SdrDragStat {
protected:
SdrHdl* pHdl; // The Handle for the User
SdrView* pView;
SdrPageView* pPageView;
std::vector<Point*> aPnts; // All previous Points: [0]=Start, [Count()-2]=Prev
Point aRef1; // Referencepoint: Resize fixed point, (axis of rotation,
Point aRef2; // axis of reflection, ...)
Point aPos0; // Position at the last Event
Point aRealPos0; // Position at the last Event
Point aRealNow; // Current dragging position without Snap, Ortho and Limit
Point aRealLast; // RealPos of the last Point (for MinMoved)
Rectangle aActionRect;
bool bEndDragChangesAttributes;
bool bEndDragChangesGeoAndAttributes;
bool bMouseIsUp;
bool bShown; // Xor visible?
sal_uInt16 nMinMov; // So much has to be minimally moved first
bool bMinMoved; // MinMove surpassed?
bool bHorFixed; // Dragging only vertical
bool bVerFixed; // Dragging only horizontal
bool bWantNoSnap; // To decide if pObj-> MovCreate () should use NoSnapPos or not.
// Therefore, NoSnapPos is written into the buffer.
bool bOrtho4;
bool bOrtho8;
SdrDragMethod* pDragMethod;
protected:
void Clear(bool bLeaveOne);
Point& Pnt(sal_uIntPtr nNum) { return *aPnts[nNum]; }
//public:
SdrDragStatUserData* pUser; // Userdata
public:
SdrDragStat(): aPnts() { pUser=NULL; Reset(); }
~SdrDragStat() { Clear(false); }
void Reset();
SdrView* GetView() const { return pView; }
void SetView(SdrView* pV) { pView=pV; }
SdrPageView* GetPageView() const { return pPageView; }
void SetPageView(SdrPageView* pPV) { pPageView=pPV; }
const Point& GetPoint(sal_uIntPtr nNum) const { return *aPnts[nNum]; }
sal_uIntPtr GetPointAnz() const { return aPnts.size(); }
const Point& GetStart() const { return GetPoint(0); }
Point& Start() { return Pnt(0); }
const Point& GetPrev() const { return GetPoint(GetPointAnz()-(GetPointAnz()>=2 ? 2:1)); }
Point& Prev() { return Pnt(GetPointAnz()-(GetPointAnz()>=2 ? 2:1)); }
const Point& GetPos0() const { return aPos0; }
Point& Pos0() { return aPos0; }
const Point& GetNow() const { return GetPoint(GetPointAnz()-1); }
Point& Now() { return Pnt(GetPointAnz()-1); }
const Point& GetRealNow() const { return aRealNow; }
Point& RealNow() { return aRealNow; }
const Point& GetRef1() const { return aRef1; }
Point& Ref1() { return aRef1; }
const Point& GetRef2() const { return aRef2; }
Point& Ref2() { return aRef2; }
const SdrHdl* GetHdl() const { return pHdl; }
void SetHdl(SdrHdl* pH) { pHdl=pH; }
SdrDragStatUserData* GetUser() const { return pUser; }
void SetUser(SdrDragStatUserData* pU) { pUser=pU; }
bool IsShown() const { return bShown; }
void SetShown(bool bOn) { bShown=bOn; }
bool IsMinMoved() const { return bMinMoved; }
void SetMinMoved() { bMinMoved=true; }
void ResetMinMoved() { bMinMoved=false; }
void SetMinMove(sal_uInt16 nDist) { nMinMov=nDist; if (nMinMov<1) nMinMov=1; }
sal_uInt16 GetMinMove() const { return nMinMov; }
bool IsHorFixed() const { return bHorFixed; }
void SetHorFixed(bool bOn) { bHorFixed=bOn; }
bool IsVerFixed() const { return bVerFixed; }
void SetVerFixed(bool bOn) { bVerFixed=bOn; }
// Here, the object can say: "I do not want to snap to coordinates!"
// for example, the angle of the arc ...
bool IsNoSnap() const { return bWantNoSnap; }
void SetNoSnap(bool bOn = true) { bWantNoSnap=bOn; }
// And here the Obj say which Ortho (if there is one) can be usefully applied to him.
// Ortho4 means Ortho in four directions (for Rect and CIRT)
bool IsOrtho4Possible() const { return bOrtho4; }
void SetOrtho4Possible(bool bOn = true) { bOrtho4=bOn; }
// Ortho8 means Ortho in 8 directions (for lines)
bool IsOrtho8Possible() const { return bOrtho8; }
void SetOrtho8Possible(bool bOn = true) { bOrtho8=bOn; }
// Is set by an object that was dragged.
bool IsEndDragChangesAttributes() const { return bEndDragChangesAttributes; }
void SetEndDragChangesAttributes(bool bOn) { bEndDragChangesAttributes=bOn; }
bool IsEndDragChangesGeoAndAttributes() const { return bEndDragChangesGeoAndAttributes; }
void SetEndDragChangesGeoAndAttributes(bool bOn) { bEndDragChangesGeoAndAttributes=bOn; }
// Is set by the view and can be evaluated by Obj
bool IsMouseDown() const { return !bMouseIsUp; }
void SetMouseDown(bool bDown) { bMouseIsUp=!bDown; }
Point KorregPos(const Point& rNow, const Point& rPrev) const;
void Reset(const Point& rPnt);
void NextMove(const Point& rPnt);
void NextPoint(bool bSaveReal=false);
void PrevPoint();
bool CheckMinMoved(const Point& rPnt);
long GetDX() const { return GetNow().X()-GetPrev().X(); }
long GetDY() const { return GetNow().Y()-GetPrev().Y(); }
Fraction GetXFact() const;
Fraction GetYFact() const;
SdrDragMethod* GetDragMethod() const { return pDragMethod; }
void SetDragMethod(SdrDragMethod* pMth) { pDragMethod=pMth; }
const Rectangle& GetActionRect() const { return aActionRect; }
void SetActionRect(const Rectangle& rR) { aActionRect=rR; }
// Also considering 1stPointAsCenter
void TakeCreateRect(Rectangle& rRect) const;
};
#endif // INCLUDED_SVX_SVDDRAG_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| Drop unused "reserve" fields | Drop unused "reserve" fields
Probably a relic from the past, when people tried to avoid changing public
headers incompatibly to avoid causing recompilations for their
colleagues... We are long past such concerns. The talk about "extensions" in
the comment is most likely obsolete.
Change-Id: If90ca02685bf82ed529becb715b4c614287fdc57
| C++ | mpl-2.0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core |
36a493b69167e3d5babb218a5bdbad25667e4620 | includes/gcl/functional.hpp | includes/gcl/functional.hpp | #pragma once
#include <utility>
namespace gcl::functional
{
template <class... Ts>
struct overload : Ts... {
using Ts::operator()...;
using bases_types = std::tuple<Ts...>; // allow operator() function_traits
};
template <class... Ts>
overload(Ts...) -> overload<Ts...>; // not required in C++20, but Msvc need this deduction guide for some reasons ...
template <typename T>
decltype(auto) wrap(T&& func)
{ // wrap any functor into a deductible type/value
return [func](auto&&... args) -> decltype(auto) {
return std::invoke(func, std::forward<decltype(args)>(args)...);
};
}
}
| #pragma once
#include <utility>
namespace gcl::functional
{
template <class... Ts>
struct overload : Ts... {
using Ts::operator()...;
using bases_types = std::tuple<Ts...>; // allow operator() function_traits
};
template <class... Ts>
overload(Ts...) -> overload<Ts...>; // not required in C++20, but Msvc need this deduction guide for some reasons ...
template <typename T>
decltype(auto) wrap(T&& func)
{ // wrap any functor into a deductible type/value
return [func](auto&&... args) -> decltype(auto) {
return std::invoke(func, std::forward<decltype(args)>(args)...);
};
}
}
#include <gcl/mp/function_traits.hpp>
namespace gcl::functional::type_traits
{
template <class>
struct is_overload : std::false_type {};
template <class... Ts>
struct is_overload<gcl::functional::overload<Ts...>> : std::true_type {};
template <class... Ts>
constexpr static auto is_overload_v = is_overload<Ts...>::value;
template <typename T>
struct overload_arguments;
template <typename ... Ts>
struct overload_arguments<gcl::functional::overload<Ts...>>
{
using type = decltype(std::tuple_cat(typename gcl::mp::function_traits_t<decltype(&Ts::operator())>::arguments{}...));
};
template <typename T>
using overload_arguments_t = typename overload_arguments<T>::type;
}
| add type_traits : is_overload, overload_arguments | [functional] add type_traits : is_overload, overload_arguments
| C++ | apache-2.0 | GuillaumeDua/GCL_CPP |
a7d5a0d67f08d9960ba6b68a8022b7b82d6f5604 | molequeue/jobitemmodel.cpp | molequeue/jobitemmodel.cpp | /******************************************************************************
This source file is part of the MoleQueue project.
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "jobitemmodel.h"
#include "job.h"
#include "jobmanager.h"
#include <QtCore/QDebug>
namespace MoleQueue {
JobItemModel::JobItemModel(QObject *parentObject)
: QAbstractItemModel(parentObject),
m_jobManager(NULL)
{
connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
this, SIGNAL(rowCountChanged()));
connect(this, SIGNAL(rowsRemoved(QModelIndex, int, int)),
this, SIGNAL(rowCountChanged()));
connect(this, SIGNAL(modelReset()),
this, SIGNAL(rowCountChanged()));
connect(this, SIGNAL(layoutChanged()),
this, SIGNAL(rowCountChanged()));
}
void JobItemModel::setJobManager(JobManager *newJobManager)
{
if (m_jobManager == newJobManager)
return;
if (m_jobManager)
m_jobManager->disconnect(this);
m_jobManager = newJobManager;
connect(newJobManager, SIGNAL(jobUpdated(MoleQueue::Job)),
this, SLOT(jobUpdated(MoleQueue::Job)));
reset();
}
int JobItemModel::rowCount(const QModelIndex &modelIndex) const
{
if (m_jobManager && !modelIndex.isValid())
return m_jobManager->count();
else
return 0;
}
int JobItemModel::columnCount(const QModelIndex &) const
{
return COLUMN_COUNT;
}
QVariant JobItemModel::headerData(int section, Qt::Orientation orientation,
int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch (section) {
case MOLEQUEUE_ID:
return QVariant("#");
case JOB_TITLE:
return QVariant("Job Title");
case NUM_CORES:
return QVariant("Cores");
case QUEUE_NAME:
return QVariant("Queue");
case PROGRAM_NAME:
return QVariant("Program");
case JOB_STATE:
return QVariant("Status");
default:
return QVariant();
}
}
return QVariant();
}
QVariant JobItemModel::data(const QModelIndex &modelIndex, int role) const
{
if (!m_jobManager || !modelIndex.isValid() ||
modelIndex.column() + 1 > COLUMN_COUNT)
return QVariant();
Job job = m_jobManager->jobAt(modelIndex.row());
if (job.isValid()) {
if (role == Qt::DisplayRole) {
switch (modelIndex.column()) {
case MOLEQUEUE_ID:
return QVariant(QString::number(job.moleQueueId()));
case JOB_TITLE:
return QVariant(job.description());
case NUM_CORES:
return QVariant(QString::number(job.numberOfCores()));
case QUEUE_NAME: {
if (job.queueId() != InvalidId)
return QVariant(QString("%1 (%2)").arg(job.queue())
.arg(QString::number(job.queueId())));
else
return QVariant(job.queue());
}
case PROGRAM_NAME:
return QVariant(job.program());
case JOB_STATE:
return MoleQueue::jobStateToString(job.jobState());
default:
return QVariant();
}
}
else if (role == FetchJobRole) {
return QVariant::fromValue(job);
}
}
return QVariant();
}
bool JobItemModel::removeRows(int row, int count, const QModelIndex &)
{
beginRemoveRows(QModelIndex(), row, row + count - 1);
endRemoveRows();
return true;
}
bool JobItemModel::insertRows(int row, int count, const QModelIndex &)
{
beginInsertRows(QModelIndex(), row, row + count - 1);
endInsertRows();
return true;
}
Qt::ItemFlags JobItemModel::flags(const QModelIndex &) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
QModelIndex JobItemModel::index(int row, int column,
const QModelIndex &/*modelIndex*/) const
{
if (m_jobManager && row >= 0 && row < m_jobManager->count())
return createIndex(row, column);
else
return QModelIndex();
}
void JobItemModel::jobUpdated(const Job &job)
{
if (!m_jobManager)
return;
int row = m_jobManager->indexOf(job);
if (row >= 0)
emit dataChanged(index(row, 0), index(row, COLUMN_COUNT));
}
} // End of namespace
| /******************************************************************************
This source file is part of the MoleQueue project.
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "jobitemmodel.h"
#include "job.h"
#include "jobmanager.h"
#include <QtCore/QDebug>
namespace MoleQueue {
JobItemModel::JobItemModel(QObject *parentObject)
: QAbstractItemModel(parentObject),
m_jobManager(NULL)
{
connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
this, SIGNAL(rowCountChanged()));
connect(this, SIGNAL(rowsRemoved(QModelIndex, int, int)),
this, SIGNAL(rowCountChanged()));
connect(this, SIGNAL(modelReset()),
this, SIGNAL(rowCountChanged()));
connect(this, SIGNAL(layoutChanged()),
this, SIGNAL(rowCountChanged()));
}
void JobItemModel::setJobManager(JobManager *newJobManager)
{
if (m_jobManager == newJobManager)
return;
if (m_jobManager)
m_jobManager->disconnect(this);
m_jobManager = newJobManager;
connect(newJobManager, SIGNAL(jobUpdated(MoleQueue::Job)),
this, SLOT(jobUpdated(MoleQueue::Job)));
reset();
}
int JobItemModel::rowCount(const QModelIndex &modelIndex) const
{
if (m_jobManager && !modelIndex.isValid())
return m_jobManager->count();
else
return 0;
}
int JobItemModel::columnCount(const QModelIndex &) const
{
return COLUMN_COUNT;
}
QVariant JobItemModel::headerData(int section, Qt::Orientation orientation,
int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch (section) {
case MOLEQUEUE_ID:
return QVariant("#");
case JOB_TITLE:
return QVariant("Job Title");
case NUM_CORES:
return QVariant("Cores");
case QUEUE_NAME:
return QVariant("Queue");
case PROGRAM_NAME:
return QVariant("Program");
case JOB_STATE:
return QVariant("Status");
default:
return QVariant();
}
}
return QVariant();
}
QVariant JobItemModel::data(const QModelIndex &modelIndex, int role) const
{
if (!m_jobManager || !modelIndex.isValid() ||
modelIndex.column() + 1 > COLUMN_COUNT)
return QVariant();
Job job = m_jobManager->jobAt(modelIndex.row());
if (job.isValid()) {
if (role == Qt::DisplayRole) {
switch (modelIndex.column()) {
case MOLEQUEUE_ID:
return QVariant(job.moleQueueId());
case JOB_TITLE:
return QVariant(job.description());
case NUM_CORES:
return QVariant(job.numberOfCores());
case QUEUE_NAME: {
if (job.queueId() != InvalidId)
return QVariant(QString("%1 (%2)").arg(job.queue())
.arg(QString::number(job.queueId())));
else
return QVariant(job.queue());
}
case PROGRAM_NAME:
return QVariant(job.program());
case JOB_STATE:
return MoleQueue::jobStateToString(job.jobState());
default:
return QVariant();
}
}
else if (role == FetchJobRole) {
return QVariant::fromValue(job);
}
}
return QVariant();
}
bool JobItemModel::removeRows(int row, int count, const QModelIndex &)
{
beginRemoveRows(QModelIndex(), row, row + count - 1);
endRemoveRows();
return true;
}
bool JobItemModel::insertRows(int row, int count, const QModelIndex &)
{
beginInsertRows(QModelIndex(), row, row + count - 1);
endInsertRows();
return true;
}
Qt::ItemFlags JobItemModel::flags(const QModelIndex &) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
QModelIndex JobItemModel::index(int row, int column,
const QModelIndex &/*modelIndex*/) const
{
if (m_jobManager && row >= 0 && row < m_jobManager->count())
return createIndex(row, column);
else
return QModelIndex();
}
void JobItemModel::jobUpdated(const Job &job)
{
if (!m_jobManager)
return;
int row = m_jobManager->indexOf(job);
if (row >= 0)
emit dataChanged(index(row, 0), index(row, COLUMN_COUNT));
}
} // End of namespace
| Fix sorting in job table. | Fix sorting in job table.
Return variant wrapped integers where appropriate, rather
than converting to strings. This keeps the sorting proxy
model from doing a lexical sort.
Change-Id: I2a6083afeeb171b3899f69bf799e2441bb5e1460
| C++ | bsd-3-clause | OpenChemistry/molequeue,OpenChemistry/molequeue,OpenChemistry/molequeue |
5a2eb26fc8a3f2c931b672808ee3d7d0a0d7686f | test/unit/math/mix/prob/normal_test.cpp | test/unit/math/mix/prob/normal_test.cpp | #include <stan/math/mix.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/fun/util.hpp>
#include <vector>
std::vector<double> test_fun(double y, double mu, double sigma) {
using stan::math::normal_log;
using stan::math::var;
var y_var = y;
var mu_var = mu;
var sigma_var = sigma;
std::vector<var> x;
x.push_back(y_var);
x.push_back(mu_var);
x.push_back(sigma_var);
var logp = normal_log<false>(y_var, mu_var, sigma_var);
std::vector<double> grad;
logp.grad(x, grad);
return grad;
}
TEST(ProbAgradDistributionsNormal, derivatives) {
using stan::math::fvar;
using stan::math::normal_log;
std::vector<double> grad = test_fun(0, 0, 1);
fvar<double> lp = normal_log<false>(0, 0, fvar<double>(1.0, 1));
EXPECT_FLOAT_EQ(grad[2], lp.tangent());
fvar<fvar<double> > y(1.0);
fvar<double> x(1.0, 2.0);
EXPECT_NO_THROW(normal_log(y, 1, 1));
EXPECT_FLOAT_EQ(normal_log(x, 1, 1).val_, -0.918938533204672741780);
EXPECT_FLOAT_EQ(normal_log(x, 2, 1).d_, 2);
}
TEST(ProbAgradDistributionsNormal, FvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::normal_log;
using stan::math::var;
fvar<var> y_(2, 1);
double mu(0);
double sigma(1);
fvar<var> logp = normal_log(y_, mu, sigma);
AVEC y = createAVEC(y_.val_);
VEC g;
logp.val_.grad(y, g);
EXPECT_FLOAT_EQ(-2, g[0]);
}
TEST(ProbAgradDistributionsNormal, FvarVar_2ndDeriv1) {
using stan::math::fvar;
using stan::math::normal_log;
using stan::math::var;
double y_(1);
fvar<var> mu(0, 1);
double sigma(1);
fvar<var> logp = normal_log(y_, mu, sigma);
AVEC y = createAVEC(mu.val_);
VEC g;
logp.d_.grad(y, g);
EXPECT_FLOAT_EQ(-1, g[0]);
}
TEST(ProbAgradDistributionsNormal, FvarVar_2ndDeriv2) {
using stan::math::fvar;
using stan::math::normal_log;
using stan::math::var;
double y_(1);
double mu(0);
fvar<var> sigma(1, 1);
fvar<var> logp = normal_log(y_, mu, sigma);
AVEC y = createAVEC(sigma.val_);
VEC g;
logp.d_.grad(y, g);
EXPECT_FLOAT_EQ(-2, g[0]);
}
| #include <stan/math/mix.hpp>
#include <test/unit/math/test_ad.hpp>
TEST(mathMixScalFun, normal_lpdf) {
auto f = [](const double mu, const double sigma) {
return [=](const auto& y) { return stan::math::normal_lpdf(y, mu, sigma); };
};
stan::test::expect_ad(f(0, 1), -2.3);
stan::test::expect_ad(f(0, 1), 0.0);
stan::test::expect_ad(f(0, 1), 1.7);
}
| Convert test to expect_ad | Convert test to expect_ad
| C++ | bsd-3-clause | stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math |
7f86ed5b37d83a96e6ff2af40d104a4734889e55 | scripts/perfanalysis.cpp | scripts/perfanalysis.cpp | // Compile with
// g++ perfanalysis.cpp -o perfanalyis -std=c++14 -Wall -O3
#include <algorithm>
#include <iostream>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include <memory>
using namespace std;
struct Event {
static const regex re;
string threadName;
int tid;
string cpu;
double startTime;
double duration;
string name;
string inbrackets;
bool isRet;
Event(string& line) : isRet(false) {
std::smatch match_obj;
if(!std::regex_search(line, match_obj, re)){
throw std::logic_error("could not parse line");
}
threadName = match_obj[1];
tid = std::stoi(match_obj[2]);
cpu = match_obj[3];
startTime = std::stod(match_obj[4]);
duration = 0;
name = match_obj[6];
inbrackets = match_obj[7];
if (match_obj[9].length() > 0) {
isRet = true;
name.erase(name.end() - 3, name.end()); // remove Ret suffix form name
}
}
bool empty() { return name.empty(); }
string id() { return to_string(tid) + name; }
string pretty() {
return to_string(duration) + " " + name + " " + to_string(startTime);
}
bool operator<(Event const& other) {
if (name < other.name) {
return true;
} else if (name > other.name) {
return false;
} else {
return duration < other.duration;
}
}
};
// sample output:
// arangod 32636 [005] 16678249.324973: probe_arangod:insertLocalRet: (14a7f60 <- 14a78d6)
// process tid core timepoint scope:name frame
const regex Event::re(
R"_(\s*(\S+))_" // name 1
R"_(\s+(\d+))_" // tid 2
R"_(\s+\[(\d+)\])_" // cup 3
R"_(\s+(\d+\.\d+):)_" // time 4
R"_(\s+([^: ]+):([^: ]+):)_" // scope:func 5:6
R"_(\s+\(([0-9a-f]+)(\s+<-\s+([0-9a-f]+))?\))_" // (start -> stop) 7 -> 9
,
std::regex_constants::ECMAScript | std::regex_constants::optimize);
int main(int /*argc*/, char* /*argv*/ []) {
unordered_map<string, unique_ptr<Event>> table;
vector<unique_ptr<Event>> list;
string line;
while (getline(cin, line)) {
auto event = std::make_unique<Event>(line);
if (!event->empty()) {
string id = event->id();
// insert to table if it is not a function return
if (!event->isRet) {
auto it = table.find(id);
if (it != table.end()) {
cout << "Alarm, double event found:\n" << line << std::endl;
} else {
table.insert(make_pair(id, std::move(event)));
}
// update duration in table
} else {
auto it = table.find(id);
if (it == table.end()) {
cout << "Return for unknown event found:\n" << line << std::endl;
} else {
unique_ptr<Event> ev = std::move(it->second);
table.erase(it);
ev->duration = event->startTime - ev->startTime;
list.push_back(std::move(ev));
}
}
}
}
cout << "Unreturned events:\n";
for (auto& p : table) {
cout << p.second->pretty() << "\n";
}
sort(list.begin(), list.end(),
[](unique_ptr<Event>const& a, unique_ptr<Event>const& b) -> bool { return *a < *b; });
cout << "Events sorted by name and time:\n";
for (auto& e : list) {
cout << e->pretty() << "\n";
}
return 0;
}
| // Compile with
// g++ perfanalysis.cpp -o perfanalyis -std=c++14 -Wall -O3
#include <algorithm>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
struct StrTok {
string& s;
size_t pos;
bool done;
void advance() {
while (pos < s.size() && s[pos] == ' ') {
++pos;
}
done = pos >= s.size();
}
StrTok(string& t) : s(t), pos(0), done(false) {
advance();
}
const char* get() {
if (done) {
return nullptr;
}
auto p = s.find(' ', pos);
if (p == string::npos) {
done = true;
return s.c_str() + pos;
}
s[p] = 0;
auto ret = s.c_str() + pos;
pos = p + 1;
advance();
return ret;
}
};
struct Event {
string threadName;
int tid;
string cpu;
double startTime;
double duration;
string name;
string inbrackets;
bool isRet;
Event(string& line) : isRet(false) {
StrTok tok(line);
const char* p = tok.get();
const char* q;
if (p != nullptr) {
threadName = p;
p = tok.get();
tid = strtol(p, nullptr, 10);
p = tok.get();
cpu = p;
p = tok.get();
startTime = strtod(p, nullptr);
p = tok.get();
name = p;
name.pop_back();
q = tok.get();
if (strcmp(q, "cs:") == 0) {
return;
}
if (name.compare(0, 14, "probe_arangod:") == 0) {
name = name.substr(14);
}
auto l = name.size();
if (l >= 3 && name[l-1] == 't' && name[l-2] == 'e' &&
name[l-3] == 'R') {
isRet = true;
name.pop_back();
name.pop_back();
name.pop_back();
}
inbrackets = q;
}
}
bool empty() { return name.empty(); }
string id() { return to_string(tid) + name; }
string pretty() {
return to_string(duration) + " " + name + " " + to_string(startTime);
}
bool operator<(Event const& other) {
if (name < other.name) {
return true;
} else if (name > other.name) {
return false;
} else {
return duration < other.duration;
}
}
};
int main(int /*argc*/, char* /*argv*/ []) {
unordered_map<string, unique_ptr<Event>> table;
vector<unique_ptr<Event>> list;
string line;
while (getline(cin, line)) {
auto event = make_unique<Event>(line);
if (!event->empty()) {
string id = event->id();
// insert to table if it is not a function return
if (!event->isRet) {
auto it = table.find(id);
if (it != table.end()) {
cout << "Alarm, double event found:\n" << line << endl;
} else {
table.insert(make_pair(id, move(event)));
}
// update duration in table
} else {
auto it = table.find(id);
if (it == table.end()) {
cout << "Return for unknown event found:\n" << line << endl;
} else {
unique_ptr<Event> ev = move(it->second);
table.erase(it);
ev->duration = event->startTime - ev->startTime;
list.push_back(move(ev));
}
}
}
}
cout << "Unreturned events:\n";
for (auto& p : table) {
cout << p.second->pretty() << "\n";
}
sort(list.begin(), list.end(),
[](unique_ptr<Event>const& a, unique_ptr<Event>const& b) -> bool { return *a < *b; });
cout << "Events sorted by name and time:\n";
string current;
size_t startPos = 0;
bool bootstrap = true;
auto printStats = [&](size_t i) -> void {
cout << "Statistics in microseconds for " << current << ":\n"
<< " Number of calls: " << i - startPos << "\n"
<< " Minimal time : "
<< static_cast<uint64_t>(list[startPos]->duration * 1000000.0) << "\n";
size_t pos = (i - startPos) / 2 + startPos;
cout << " 50%ile : "
<< static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n";
pos = ((i - startPos) * 90) / 100 + startPos;
cout << " 90%ile : "
<< static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n";
pos = ((i - startPos) * 99) / 100 + startPos;
cout << " 99%ile : "
<< static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n";
pos = ((i - startPos) * 999) / 1000 + startPos;
cout << " 99.9%ile : "
<< static_cast<uint64_t>(list[pos]->duration * 1000000.0) << "\n";
cout << " Maximal time : "
<< static_cast<uint64_t>(list[i-1]->duration * 1000000.0) << "\n";
size_t j = (i-startPos > 30) ? i-30 : startPos;
cout << " Top " << i-j << " times :";
while (j < i) {
cout << " " << static_cast<uint64_t>(list[j++]->duration * 1000000.0);
}
cout << "\n" << endl;
};
for (size_t i = 0; i < list.size(); ++i) {
unique_ptr<Event>& e = list[i];
if (e->name != current) {
if (!bootstrap) {
printStats(i);
}
bootstrap = false;
startPos = i;
current = e->name;
}
cout << e->pretty() << "\n";
}
printStats(list.size());
return 0;
}
| Speed up perfanalysis and add statistics. | Speed up perfanalysis and add statistics.
| C++ | apache-2.0 | joerg84/arangodb,arangodb/arangodb,fceller/arangodb,hkernbach/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,wiltonlazary/arangodb,baslr/ArangoDB,baslr/ArangoDB,arangodb/arangodb,graetzer/arangodb,hkernbach/arangodb,baslr/ArangoDB,hkernbach/arangodb,graetzer/arangodb,baslr/ArangoDB,Simran-B/arangodb,fceller/arangodb,fceller/arangodb,Simran-B/arangodb,fceller/arangodb,graetzer/arangodb,wiltonlazary/arangodb,joerg84/arangodb,hkernbach/arangodb,Simran-B/arangodb,hkernbach/arangodb,joerg84/arangodb,joerg84/arangodb,graetzer/arangodb,baslr/ArangoDB,Simran-B/arangodb,hkernbach/arangodb,Simran-B/arangodb,fceller/arangodb,hkernbach/arangodb,fceller/arangodb,hkernbach/arangodb,joerg84/arangodb,joerg84/arangodb,fceller/arangodb,graetzer/arangodb,hkernbach/arangodb,Simran-B/arangodb,fceller/arangodb,fceller/arangodb,arangodb/arangodb,wiltonlazary/arangodb,graetzer/arangodb,arangodb/arangodb,baslr/ArangoDB,wiltonlazary/arangodb,graetzer/arangodb,graetzer/arangodb,baslr/ArangoDB,arangodb/arangodb,arangodb/arangodb,Simran-B/arangodb,graetzer/arangodb,baslr/ArangoDB,baslr/ArangoDB,wiltonlazary/arangodb,joerg84/arangodb,arangodb/arangodb,joerg84/arangodb,graetzer/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,baslr/ArangoDB,joerg84/arangodb,baslr/ArangoDB,graetzer/arangodb,hkernbach/arangodb,hkernbach/arangodb,graetzer/arangodb,graetzer/arangodb,joerg84/arangodb,baslr/ArangoDB,graetzer/arangodb,fceller/arangodb,Simran-B/arangodb,joerg84/arangodb,baslr/ArangoDB,joerg84/arangodb,joerg84/arangodb,Simran-B/arangodb,wiltonlazary/arangodb,Simran-B/arangodb,arangodb/arangodb,hkernbach/arangodb,baslr/ArangoDB,joerg84/arangodb |
20a58a5a8aa06ff79d6ed8dde5f3c47ffb39d138 | test/test_restclient.cpp | test/test_restclient.cpp | #include "restclient.h"
#include <gtest/gtest.h>
#include <string>
class RestClientTest : public ::testing::Test
{
protected:
int foo;
std::string url;
std::string ctype;
std::string data;
RestClientTest()
{
}
virtual ~RestClientTest()
{
}
virtual void SetUp()
{
foo = 0;
url = "http://localhost:4567";
ctype = "";
data = "";
}
virtual void TearDown()
{
}
};
// Tests
TEST_F(RestClientTest, TestRestClientGET)
{
RestClient::get(url);
EXPECT_EQ(0, foo);
}
TEST_F(RestClientTest, TestRestClientPOST)
{
RestClient::post(url, ctype, data);
EXPECT_EQ(0, foo);
}
TEST_F(RestClientTest, TestRestClientPUT)
{
RestClient::put(url, ctype, data);
EXPECT_EQ(0, foo);
}
TEST_F(RestClientTest, TestRestClientDELETE)
{
RestClient::del(url);
EXPECT_EQ(0, foo);
}
| #include "restclient.h"
#include <gtest/gtest.h>
#include <string>
class RestClientTest : public ::testing::Test
{
protected:
int foo;
std::string url;
std::string ctype;
std::string data;
RestClientTest()
{
}
virtual ~RestClientTest()
{
}
virtual void SetUp()
{
foo = 0;
url = "http://localhost:4567";
ctype = "";
data = "";
}
virtual void TearDown()
{
}
};
// Tests
TEST_F(RestClientTest, TestRestClientGETBody)
{
RestClient::response res = RestClient::get(url);
EXPECT_EQ("GET succesful.", res.body);
}
TEST_F(RestClientTest, TestRestClientPOST)
{
RestClient::post(url, ctype, data);
EXPECT_EQ(0, foo);
}
TEST_F(RestClientTest, TestRestClientPUT)
{
RestClient::put(url, ctype, data);
EXPECT_EQ(0, foo);
}
TEST_F(RestClientTest, TestRestClientDELETE)
{
RestClient::del(url);
EXPECT_EQ(0, foo);
}
| check correct return body | check correct return body | C++ | mit | 69736c616d/restclient-cpp,benjam60/restclient-cpp,embeddedmz/restclient-cpp,69736c616d/restclient-cpp,mrtazz/restclient-cpp,69736c616d/restclient-cpp,benjam60/restclient-cpp,seem-sky/restclient-cpp,seem-sky/restclient-cpp,seem-sky/restclient-cpp,mrtazz/restclient-cpp,seem-sky/restclient-cpp,69736c616d/restclient-cpp,benjam60/restclient-cpp,embeddedmz/restclient-cpp,benjam60/restclient-cpp |
35f4cab09f326d6b46ed6a65f098d8f333f2821b | test/unit/BoundsTest.cpp | test/unit/BoundsTest.cpp | /******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <boost/test/unit_test.hpp>
#include <libpc/Bounds.hpp>
#include <iostream>
#include <sstream>
#include <string>
using namespace libpc;
BOOST_AUTO_TEST_SUITE(BoundsTest)
BOOST_AUTO_TEST_CASE(test_ctor)
{
Bounds<int> b1;
BOOST_CHECK(b1.size() == 0);
BOOST_CHECK(b1.empty());
Bounds<int> b2(1,2,3,4);
BOOST_CHECK(b2.size() == 2);
BOOST_CHECK(!b2.empty());
Bounds<int> b3(1,2,3,4,5,6);
BOOST_CHECK(b3.size() == 3);
BOOST_CHECK(!b3.empty());
}
BOOST_AUTO_TEST_CASE(test_equals)
{
Bounds<int> b1(1,2,3,4);
Bounds<int> b2(1,2,3,4);
Bounds<int> b3(1,2,32,4);
Bounds<int> b4(1,2,3,4,5,6);
BOOST_CHECK(b1 == b1);
BOOST_CHECK(b1 == b2);
BOOST_CHECK(b2 == b1);
BOOST_CHECK(b1 != b3);
BOOST_CHECK(b3 != b1);
BOOST_CHECK(b1 != b4);
BOOST_CHECK(b1 != b4);
BOOST_CHECK(b4 != b1);
}
BOOST_AUTO_TEST_CASE(test_ctor2)
{
Bounds<int> b1(1,2,3,4);
Bounds<int> b2(b1);
BOOST_CHECK(b1==b2);
Range<int> v1(1,3);
Range<int> v2(2,4);
std::vector< Range<int> > rv;
rv.push_back(v1);
rv.push_back(v2);
Bounds<int> b3(rv);
BOOST_CHECK(b3==b1);
BOOST_CHECK(b3.dimensions() == rv);
std::vector<int> vlo;
vlo.push_back(1);
vlo.push_back(2);
std::vector<int> vhi;
vhi.push_back(3);
vhi.push_back(4);
Bounds<int> b4(vlo, vhi);
BOOST_CHECK(b4==b1);
Bounds<int> b5 = b1;
BOOST_CHECK(b5==b1);
}
BOOST_AUTO_TEST_CASE(test_accessor)
{
Bounds<int> b2(1,2,3,4,5,6);
BOOST_CHECK(b2.getMinimum(0)==1);
BOOST_CHECK(b2.getMinimum(1)==2);
BOOST_CHECK(b2.getMinimum(2)==3);
BOOST_CHECK(b2.getMaximum(0)==4);
BOOST_CHECK(b2.getMaximum(1)==5);
BOOST_CHECK(b2.getMaximum(2)==6);
Vector<int> vmin(1,2,3);
Vector<int> vmax(4,5,6);
BOOST_CHECK(b2.getMinimum()==vmin);
BOOST_CHECK(b2.getMaximum()==vmax);
}
BOOST_AUTO_TEST_CASE(test_math)
{
Bounds<int> r(1,2,3,9,8,7);
BOOST_CHECK(r.volume() ==8*6*4);
std::vector<int> shiftVec;
shiftVec.push_back(10);
shiftVec.push_back(11);
shiftVec.push_back(12);
r.shift(shiftVec);
Bounds<int> r2(11, 13, 15, 19, 19, 19);
BOOST_CHECK(r == r2);
std::vector<int> scaleVec;
scaleVec.push_back(2);
scaleVec.push_back(3);
scaleVec.push_back(4);
r2.scale(scaleVec);
Bounds<int> r3(22, 39, 60, 38, 57, 76);
BOOST_CHECK(r2 == r3);
BOOST_CHECK(r2.volume() == 16 * 18 * 16);
}
BOOST_AUTO_TEST_CASE(test_clip)
{
Bounds<int> r1(0,0,10,10);
Bounds<int> r2(1,1,11,11);
r1.clip(r2);
Bounds<int> r3(1,1,10,10);
BOOST_CHECK(r1==r3);
Bounds<int> r4(2,4,6,8);
r1.clip(r4);
BOOST_CHECK(r1==r4);
Bounds<int> r5(20,40,60,80);
r1.clip(r5);
// BUG: seems wrong -- need to better define semantics of clip, etc
Bounds<int> r6(20,40,6,8);
BOOST_CHECK(r1==r6);
}
BOOST_AUTO_TEST_CASE(test_intersect)
{
Bounds<int> r1(0,0,10,10);
Bounds<int> r2(1,1,11,11);
Bounds<int> r3(100,100,101,101);
Bounds<int> r4(2,4,6,8);
BOOST_CHECK(r1.overlaps(r1));
BOOST_CHECK(r1.overlaps(r2));
BOOST_CHECK(r2.overlaps(r1));
BOOST_CHECK(!r1.overlaps(r3));
BOOST_CHECK(!r3.overlaps(r1));
BOOST_CHECK(r1.contains(r1));
BOOST_CHECK(!r1.contains(r2));
BOOST_CHECK(r1.contains(r4));
Vector<int> v1(5,6);
Vector<int> v2(5,60);
BOOST_CHECK(r1.contains(v1));
BOOST_CHECK(!r1.contains(v2));
}
BOOST_AUTO_TEST_CASE(test_grow)
{
Bounds<int> r1(50,51,100,101);
Bounds<int> r2(0,1,10,201);
r1.grow(r2);
Bounds<int> r3(0,1,100,201);
BOOST_CHECK(r1 == r3);
Bounds<int> r4(0,1,10,11);
Vector<int> ptLo(-1,-2);
Vector<int> ptHi(20,201);
r4.grow(ptLo);
r4.grow(ptHi);
Bounds<int> r5(-1,-2,20,201);
BOOST_CHECK(r4 == r5);
return;
}
BOOST_AUTO_TEST_CASE(test_dump)
{
Bounds<int> r(1,2,3,7,8,9);
std::ostringstream s;
s << r;
BOOST_CHECK(s.str() == "([1 .. 7], [2 .. 8], [3 .. 9])");
return;
}
BOOST_AUTO_TEST_CASE(test_static)
{
Bounds<boost::uint8_t> t = Bounds<boost::uint8_t>::getDefaultSpatialExtent();
std::vector<boost::uint8_t> minv;
minv.push_back(0);
minv.push_back(0);
minv.push_back(0);
std::vector<boost::uint8_t> maxv;
maxv.push_back(255);
maxv.push_back(255);
maxv.push_back(255);
BOOST_CHECK(t.getMinimum() == minv);
BOOST_CHECK(t.getMaximum() == maxv);
}
BOOST_AUTO_TEST_CASE(test_output)
{
Bounds<double> b2(1,2,101,102);
Bounds<double> b3(1,2,3,101,102,103);
std::stringstream oss;
oss << b2;
std::string b2s = oss.str();
BOOST_CHECK(b2s == "([1 , 101], [2, 102])");
return;
}
BOOST_AUTO_TEST_CASE(test_input)
{
Bounds<int> r(1,2,10,20);
std::stringstream iss;
iss << "[10 .. 20]";
Bounds<int> rr;
iss >> rr;
BOOST_CHECK(r == rr);
return;
}
BOOST_AUTO_TEST_SUITE_END()
| /******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <boost/test/unit_test.hpp>
#include <libpc/Bounds.hpp>
#include <iostream>
#include <sstream>
#include <string>
using namespace libpc;
BOOST_AUTO_TEST_SUITE(BoundsTest)
BOOST_AUTO_TEST_CASE(test_ctor)
{
Bounds<int> b1;
BOOST_CHECK(b1.size() == 0);
BOOST_CHECK(b1.empty());
Bounds<int> b2(1,2,3,4);
BOOST_CHECK(b2.size() == 2);
BOOST_CHECK(!b2.empty());
Bounds<int> b3(1,2,3,4,5,6);
BOOST_CHECK(b3.size() == 3);
BOOST_CHECK(!b3.empty());
}
BOOST_AUTO_TEST_CASE(test_equals)
{
Bounds<int> b1(1,2,3,4);
Bounds<int> b2(1,2,3,4);
Bounds<int> b3(1,2,32,4);
Bounds<int> b4(1,2,3,4,5,6);
BOOST_CHECK(b1 == b1);
BOOST_CHECK(b1 == b2);
BOOST_CHECK(b2 == b1);
BOOST_CHECK(b1 != b3);
BOOST_CHECK(b3 != b1);
BOOST_CHECK(b1 != b4);
BOOST_CHECK(b1 != b4);
BOOST_CHECK(b4 != b1);
}
BOOST_AUTO_TEST_CASE(test_ctor2)
{
Bounds<int> b1(1,2,3,4);
Bounds<int> b2(b1);
BOOST_CHECK(b1==b2);
Range<int> v1(1,3);
Range<int> v2(2,4);
std::vector< Range<int> > rv;
rv.push_back(v1);
rv.push_back(v2);
Bounds<int> b3(rv);
BOOST_CHECK(b3==b1);
BOOST_CHECK(b3.dimensions() == rv);
std::vector<int> vlo;
vlo.push_back(1);
vlo.push_back(2);
std::vector<int> vhi;
vhi.push_back(3);
vhi.push_back(4);
Bounds<int> b4(vlo, vhi);
BOOST_CHECK(b4==b1);
Bounds<int> b5 = b1;
BOOST_CHECK(b5==b1);
}
BOOST_AUTO_TEST_CASE(test_accessor)
{
Bounds<int> b2(1,2,3,4,5,6);
BOOST_CHECK(b2.getMinimum(0)==1);
BOOST_CHECK(b2.getMinimum(1)==2);
BOOST_CHECK(b2.getMinimum(2)==3);
BOOST_CHECK(b2.getMaximum(0)==4);
BOOST_CHECK(b2.getMaximum(1)==5);
BOOST_CHECK(b2.getMaximum(2)==6);
Vector<int> vmin(1,2,3);
Vector<int> vmax(4,5,6);
BOOST_CHECK(b2.getMinimum()==vmin);
BOOST_CHECK(b2.getMaximum()==vmax);
}
BOOST_AUTO_TEST_CASE(test_math)
{
Bounds<int> r(1,2,3,9,8,7);
BOOST_CHECK(r.volume() ==8*6*4);
std::vector<int> shiftVec;
shiftVec.push_back(10);
shiftVec.push_back(11);
shiftVec.push_back(12);
r.shift(shiftVec);
Bounds<int> r2(11, 13, 15, 19, 19, 19);
BOOST_CHECK(r == r2);
std::vector<int> scaleVec;
scaleVec.push_back(2);
scaleVec.push_back(3);
scaleVec.push_back(4);
r2.scale(scaleVec);
Bounds<int> r3(22, 39, 60, 38, 57, 76);
BOOST_CHECK(r2 == r3);
BOOST_CHECK(r2.volume() == 16 * 18 * 16);
}
BOOST_AUTO_TEST_CASE(test_clip)
{
Bounds<int> r1(0,0,10,10);
Bounds<int> r2(1,1,11,11);
r1.clip(r2);
Bounds<int> r3(1,1,10,10);
BOOST_CHECK(r1==r3);
Bounds<int> r4(2,4,6,8);
r1.clip(r4);
BOOST_CHECK(r1==r4);
Bounds<int> r5(20,40,60,80);
r1.clip(r5);
// BUG: seems wrong -- need to better define semantics of clip, etc
Bounds<int> r6(20,40,6,8);
BOOST_CHECK(r1==r6);
}
BOOST_AUTO_TEST_CASE(test_intersect)
{
Bounds<int> r1(0,0,10,10);
Bounds<int> r2(1,1,11,11);
Bounds<int> r3(100,100,101,101);
Bounds<int> r4(2,4,6,8);
BOOST_CHECK(r1.overlaps(r1));
BOOST_CHECK(r1.overlaps(r2));
BOOST_CHECK(r2.overlaps(r1));
BOOST_CHECK(!r1.overlaps(r3));
BOOST_CHECK(!r3.overlaps(r1));
BOOST_CHECK(r1.contains(r1));
BOOST_CHECK(!r1.contains(r2));
BOOST_CHECK(r1.contains(r4));
Vector<int> v1(5,6);
Vector<int> v2(5,60);
BOOST_CHECK(r1.contains(v1));
BOOST_CHECK(!r1.contains(v2));
}
BOOST_AUTO_TEST_CASE(test_grow)
{
Bounds<int> r1(50,51,100,101);
Bounds<int> r2(0,1,10,201);
r1.grow(r2);
Bounds<int> r3(0,1,100,201);
BOOST_CHECK(r1 == r3);
Bounds<int> r4(0,1,10,11);
Vector<int> ptLo(-1,-2);
Vector<int> ptHi(20,201);
r4.grow(ptLo);
r4.grow(ptHi);
Bounds<int> r5(-1,-2,20,201);
BOOST_CHECK(r4 == r5);
return;
}
BOOST_AUTO_TEST_CASE(test_dump)
{
Bounds<int> r(1,2,3,7,8,9);
std::ostringstream s;
s << r;
BOOST_CHECK(s.str() == "([1 .. 7], [2 .. 8], [3 .. 9])");
return;
}
BOOST_AUTO_TEST_CASE(test_static)
{
Bounds<boost::uint8_t> t = Bounds<boost::uint8_t>::getDefaultSpatialExtent();
std::vector<boost::uint8_t> minv;
minv.push_back(0);
minv.push_back(0);
minv.push_back(0);
std::vector<boost::uint8_t> maxv;
maxv.push_back(255);
maxv.push_back(255);
maxv.push_back(255);
BOOST_CHECK(t.getMinimum() == minv);
BOOST_CHECK(t.getMaximum() == maxv);
}
BOOST_AUTO_TEST_CASE(test_output)
{
Bounds<double> b2(1,2,101,102);
Bounds<double> b3(1,2,3,101,102,103);
std::stringstream oss;
oss << b2;
std::string b2s = oss.str();
BOOST_CHECK(b2s == "([1 , 101], [2, 102])");
return;
}
BOOST_AUTO_TEST_CASE(test_input)
{
Bounds<double> r(1,2,10,20);
std::stringstream iss;
iss << "[10 .. 20]";
Bounds<double> rr;
iss >> rr;
BOOST_CHECK(r == rr);
return;
}
BOOST_AUTO_TEST_SUITE_END()
| build fix | build fix
| C++ | bsd-3-clause | radiantbluetechnologies/PDAL,mtCarto/PDAL,mpgerlek/PDAL-old,Sciumo/PDAL,Sciumo/PDAL,verma/PDAL,verma/PDAL,verma/PDAL,jwomeara/PDAL,lucadelu/PDAL,jwomeara/PDAL,mtCarto/PDAL,jwomeara/PDAL,verma/PDAL,Sciumo/PDAL,lucadelu/PDAL,mpgerlek/PDAL-old,boundlessgeo/PDAL,radiantbluetechnologies/PDAL,verma/PDAL,mtCarto/PDAL,boundlessgeo/PDAL,DougFirErickson/PDAL,lucadelu/PDAL,DougFirErickson/PDAL,radiantbluetechnologies/PDAL,jwomeara/PDAL,lucadelu/PDAL,mpgerlek/PDAL-old,verma/PDAL,mpgerlek/PDAL-old,boundlessgeo/PDAL,Sciumo/PDAL,verma/PDAL,boundlessgeo/PDAL,radiantbluetechnologies/PDAL,DougFirErickson/PDAL,mtCarto/PDAL,DougFirErickson/PDAL |
d876696dccecd9fcf466d09533fb2050349ec93c | sdk-remote/src/liburbi/urbi-launch.cc | sdk-remote/src/liburbi/urbi-launch.cc | /*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <string>
#include <libport/cassert>
#include <cstdarg>
#include <libport/cstdlib>
#include <iostream>
#include <stdexcept>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/debug.hh>
#include <libport/foreach.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include <libport/windows.hh>
#include <libport/option-parser.hh>
#include <urbi/exit.hh>
#include <urbi/package-info.hh>
#include <urbi/uclient.hh>
#include <urbi/urbi-root.hh>
GD_CATEGORY(Urbi.UrbiLaunch);
using namespace urbi;
using libport::program_name;
static UCallbackAction
onError(const UMessage& msg)
{
LIBPORT_USE(msg);
GD_FERROR("%s: load module error: %s", program_name(), msg.message);
return URBI_CONTINUE;
}
static UCallbackAction
onDone(const UMessage&)
{
::exit(0);
}
static int
connect_plugin(const std::string& host, int port,
const libport::cli_args_type& modules)
{
UClient cl(host, port);
if (cl.error())
// UClient already displayed an error message.
::exit(1);
cl.setErrorCallback(callback(&onError));
cl.setCallback(callback(&onDone), "output");
foreach (const std::string& m, modules)
cl << "loadModule(\"" << m << "\");";
cl << "output << 1;";
while (true)
sleep(1);
return 0;
}
static void
usage(libport::OptionParser& parser)
{
std::cout <<
"usage: " << program_name() <<
" [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\n"
"Start an UObject in either remote or plugin mode.\n"
<< parser <<
"\n"
"MODULE_NAMES is a list of modules.\n"
"UOPTIONS are passed to urbi::main in remote and start modes.\n"
"\n"
"Exit values:\n"
" 0 success\n"
" " << EX_NOINPUT << " some of the MODULES are missing\n"
" " << EX_OSFILE << " libuobject is missing\n"
" * other kinds of errors\n"
;
::exit(EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit(EX_OK);
}
static
int
urbi_launch_(int argc, const char* argv[], UrbiRoot& urbi_root)
{
libport::program_initialize(argc, argv);
// The options passed to urbi::main.
libport::cli_args_type args;
args << argv[0];
libport::OptionValue
arg_custom("start using the shared library FILE", "custom", 'c', "FILE"),
arg_pfile("file containing the port to listen to", "port-file", 0, "FILE");
libport::OptionFlag
arg_plugin("start as a plugin uobject on a running server", "plugin", 'p'),
arg_remote("start as a remote uobject", "remote", 'r'),
arg_start("start an urbi server and connect as plugin", "start", 's');
libport::OptionsEnd arg_end;
libport::OptionParser opt_parser;
opt_parser << "Urbi-Launch options:"
<< libport::opts::help
<< libport::opts::version
<< arg_custom
#ifndef LIBPORT_DEBUG_DISABLE
<< libport::opts::debug
#endif
<< "Mode selection:"
<< arg_plugin
<< arg_remote
<< arg_start
<< "Urbi-Launch options for plugin mode:"
<< libport::opts::host
<< libport::opts::port
<< arg_pfile
<< arg_end;
// The list of modules.
libport::cli_args_type modules;
try
{
modules = opt_parser(libport::program_arguments());
}
catch (const libport::Error& e)
{
foreach (std::string wrong_arg, e.errors())
libport::invalid_option(wrong_arg);
}
if (libport::opts::version.get())
version();
if (libport::opts::help.get())
usage(opt_parser);
// Connection mode.
enum ConnectMode
{
/// Start a new engine and plug the module
MODE_PLUGIN_START,
/// Load the module in a running engine as a plugin
MODE_PLUGIN_LOAD,
/// Connect the module to a running engine (remote uobject)
MODE_REMOTE
};
ConnectMode connect_mode =
arg_plugin.get() ? MODE_PLUGIN_LOAD
: arg_remote.get() ? MODE_REMOTE
: arg_start.get() ? MODE_PLUGIN_START
: MODE_REMOTE;
// Server host name.
std::string host = libport::opts::host.value(UClient::default_host());
if (libport::opts::host.filled())
args << "--host" << host;
// Server port.
int port = libport::opts::port.get<int>(urbi::UClient::URBI_PORT);
if (libport::opts::port.filled())
args << "--port" << libport::opts::port.value();
if (arg_pfile.filled())
{
std::string file = arg_pfile.value();
if (connect_mode == MODE_PLUGIN_LOAD)
port = libport::file_contents_get<int>(file);
args << "--port-file" << file;
}
// Modules to load.
if (connect_mode == MODE_PLUGIN_LOAD)
return connect_plugin(host, port, modules);
foreach (const std::string& s, modules)
args << "--module" << s;
// Other arguments.
args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());
// Open the right core library.
if (arg_custom.filled())
urbi_root.load_custom(arg_custom.value());
else if (connect_mode == MODE_REMOTE)
urbi_root.load_remote();
else
urbi_root.load_plugin();
return urbi_root.urbi_main(args, true, true);
}
extern "C"
{
int
URBI_SDK_API
urbi_launch(int argc, const char* argv[], UrbiRoot& root)
try
{
return urbi_launch_(argc, argv, root);
}
catch (const std::exception& e)
{
std::cerr << argv[0] << ": " << e.what() << std::endl
<< libport::exit(EX_FAIL);
}
}
| /*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <string>
#include <libport/cassert>
#include <cstdarg>
#include <libport/cstdlib>
#include <iostream>
#include <stdexcept>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/debug.hh>
#include <libport/foreach.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include <libport/windows.hh>
#include <libport/option-parser.hh>
#include <urbi/exit.hh>
#include <urbi/package-info.hh>
#include <urbi/uclient.hh>
#include <urbi/urbi-root.hh>
GD_CATEGORY(Urbi.UrbiLaunch);
using namespace urbi;
using libport::program_name;
static UCallbackAction
onError(const UMessage& msg)
{
LIBPORT_USE(msg);
GD_FERROR("%s: load module error: %s", program_name(), msg.message);
return URBI_CONTINUE;
}
static UCallbackAction
onDone(const UMessage&)
{
::exit(0);
}
static int
connect_plugin(const std::string& host, int port,
const libport::cli_args_type& modules)
{
UClient cl(host, port);
if (cl.error())
// UClient already displayed an error message.
::exit(1);
cl.setErrorCallback(callback(&onError));
cl.setCallback(callback(&onDone), "output");
foreach (const std::string& m, modules)
cl << "loadModule(\"" << m << "\");";
cl << "output << 1;";
while (true)
sleep(1);
return 0;
}
static void
usage(libport::OptionParser& parser)
{
std::cout <<
"usage: " << program_name() <<
" [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\n"
"Start an UObject in either remote or plugin mode.\n"
<< parser <<
"\n"
"MODULE_NAMES is a list of modules.\n"
"UOPTIONS are passed to urbi::main in remote and start modes.\n"
"\n"
"Exit values:\n"
" 0 success\n"
" " << EX_NOINPUT << " some of the MODULES are missing\n"
" " << EX_OSFILE << " libuobject is missing\n"
" * other kinds of errors\n"
;
::exit(EX_OK);
}
static
void
version()
{
std::cout << urbi::package_info() << std::endl
<< libport::exit(EX_OK);
}
static
int
urbi_launch_(int argc, const char* argv[], UrbiRoot& urbi_root)
{
libport::program_initialize(argc, argv);
// The options passed to urbi::main.
libport::cli_args_type args;
args << argv[0];
libport::OptionValue
arg_custom("start using the shared library FILE", "custom", 'c', "FILE");
libport::OptionFlag
arg_plugin("start as a plugin uobject on a running server", "plugin", 'p'),
arg_remote("start as a remote uobject", "remote", 'r'),
arg_start("start an urbi server and connect as plugin", "start", 's');
libport::OptionsEnd arg_end;
libport::OptionParser opt_parser;
opt_parser
<< "Urbi-Launch options:"
<< libport::opts::help
<< libport::opts::version
<< arg_custom
#ifndef LIBPORT_DEBUG_DISABLE
<< libport::opts::debug
#endif
<< "Mode selection:"
<< arg_plugin
<< arg_remote
<< arg_start
<< "For plugin mode:"
<< libport::opts::host
<< libport::opts::port
<< libport::opts::port_file
<< arg_end;
// The list of modules.
libport::cli_args_type modules;
try
{
modules = opt_parser(libport::program_arguments());
}
catch (const libport::Error& e)
{
foreach (std::string wrong_arg, e.errors())
libport::invalid_option(wrong_arg);
}
if (libport::opts::version.get())
version();
if (libport::opts::help.get())
usage(opt_parser);
// Connection mode.
enum ConnectMode
{
/// Start a new engine and plug the module
MODE_PLUGIN_START,
/// Load the module in a running engine as a plugin
MODE_PLUGIN_LOAD,
/// Connect the module to a running engine (remote uobject)
MODE_REMOTE
};
ConnectMode connect_mode =
arg_plugin.get() ? MODE_PLUGIN_LOAD
: arg_remote.get() ? MODE_REMOTE
: arg_start.get() ? MODE_PLUGIN_START
: MODE_REMOTE;
// Server host name.
std::string host = libport::opts::host.value(UClient::default_host());
if (libport::opts::host.filled())
args << "--host" << host;
// Server port.
int port = libport::opts::port.get<int>(urbi::UClient::URBI_PORT);
if (libport::opts::port.filled())
args << "--port" << libport::opts::port.value();
if (libport::opts::port_file.filled())
{
std::string file = libport::opts::port_file.value();
if (connect_mode == MODE_PLUGIN_LOAD)
port = libport::file_contents_get<int>(file);
args << "--port-file" << file;
}
// Modules to load.
if (connect_mode == MODE_PLUGIN_LOAD)
return connect_plugin(host, port, modules);
foreach (const std::string& s, modules)
args << "--module" << s;
// Other arguments, after `--'.
args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());
// Open the right core library.
if (arg_custom.filled())
urbi_root.load_custom(arg_custom.value());
else if (connect_mode == MODE_REMOTE)
urbi_root.load_remote();
else
urbi_root.load_plugin();
return urbi_root.urbi_main(args, true, true);
}
extern "C"
{
int
URBI_SDK_API
urbi_launch(int argc, const char* argv[], UrbiRoot& root)
try
{
return urbi_launch_(argc, argv, root);
}
catch (const std::exception& e)
{
std::cerr << argv[0] << ": " << e.what() << std::endl
<< libport::exit(EX_FAIL);
}
}
| Use predefined options. | Urbi.Launch: Use predefined options.
* sdk-remote/src/liburbi/urbi-launch.cc (arg_pfile): Remove, use
libport::opts::port_file instead.
| C++ | bsd-3-clause | urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi |
11d455a7c1e255ed0b510b3e3779bde305acbc08 | searchcore/src/apps/proton/proton.cpp | searchcore/src/apps/proton/proton.cpp | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/searchcore/proton/server/proton.h>
#include <vespa/storage/storageserver/storagenode.h>
#include <vespa/metrics/metricmanager.h>
#include <vespa/vespalib/util/signalhandler.h>
#include <vespa/vespalib/util/programoptions.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/config/common/exceptions.h>
#include <vespa/config/common/configcontext.h>
#include <vespa/fnet/transport.h>
#include <vespa/fastos/thread.h>
#include <vespa/fastos/app.h>
#include <iostream>
#include <thread>
#include <vespa/log/log.h>
LOG_SETUP("proton");
typedef vespalib::SignalHandler SIG;
using vespa::config::search::core::ProtonConfig;
struct Params
{
std::string identity;
std::string serviceidentity;
uint64_t subscribeTimeout;
Params();
~Params();
};
Params::Params()
: identity(),
serviceidentity(),
subscribeTimeout(60)
{}
Params::~Params() = default;
class App : public FastOS_Application
{
private:
static void setupSignals();
Params parseParams();
public:
int Main() override;
};
void
App::setupSignals()
{
SIG::PIPE.ignore();
SIG::INT.hook();
SIG::TERM.hook();
}
Params
App::parseParams()
{
Params params;
vespalib::ProgramOptions parser(_argc, _argv);
parser.setSyntaxMessage("proton -- the nextgen search core");
parser.addOption("identity", params.identity, "Node identity and config id");
std::string empty;
parser.addOption("serviceidentity", params.serviceidentity, empty, "Service node identity and config id");
parser.addOption("subscribeTimeout", params.subscribeTimeout, UINT64_C(600000), "Initial config subscribe timeout");
try {
parser.parse();
} catch (vespalib::InvalidCommandLineArgumentsException &e) {
parser.writeSyntaxPage(std::cerr);
throw;
}
return params;
}
using storage::spi::PersistenceProvider;
#include <vespa/storageserver/app/servicelayerprocess.h>
class ProtonServiceLayerProcess : public storage::ServiceLayerProcess {
proton::Proton & _proton;
metrics::MetricManager* _metricManager;
public:
ProtonServiceLayerProcess(const config::ConfigUri & configUri,
proton::Proton & proton);
~ProtonServiceLayerProcess() override { shutdown(); }
void shutdown() override;
void setupProvider() override;
storage::spi::PersistenceProvider& getProvider() override;
void setMetricManager(metrics::MetricManager& mm) {
// The service layer will call init(...) and stop() on the metric
// manager provided. Current design is that rather than depending
// on every component properly unregistering metrics and update
// hooks, the service layer stops metric manager ahead of shutting
// down component.
_metricManager = &mm;
}
int64_t getGeneration() const override;
};
ProtonServiceLayerProcess::ProtonServiceLayerProcess(const config::ConfigUri & configUri,
proton::Proton & proton)
: ServiceLayerProcess(configUri),
_proton(proton),
_metricManager(nullptr)
{
setMetricManager(_proton.getMetricManager());
}
void
ProtonServiceLayerProcess::shutdown()
{
ServiceLayerProcess::shutdown();
}
void
ProtonServiceLayerProcess::setupProvider()
{
if (_metricManager != nullptr) {
_context.getComponentRegister().setMetricManager(*_metricManager);
}
}
storage::spi::PersistenceProvider &
ProtonServiceLayerProcess::getProvider()
{
return _proton.getPersistence();
}
int64_t
ProtonServiceLayerProcess::getGeneration() const
{
int64_t slGen = storage::ServiceLayerProcess::getGeneration();
int64_t protonGen = _proton.getConfigGeneration();
return std::min(slGen, protonGen);
}
namespace {
class ExitOnSignal {
std::atomic<bool> _stop;
std::thread _thread;
public:
ExitOnSignal();
~ExitOnSignal();
void operator()();
};
ExitOnSignal::ExitOnSignal()
: _stop(false),
_thread()
{
_thread = std::thread(std::ref(*this));
}
ExitOnSignal::~ExitOnSignal()
{
_stop.store(true, std::memory_order_relaxed);
_thread.join();
}
void
ExitOnSignal::operator()()
{
while (!_stop.load(std::memory_order_relaxed)) {
if (SIG::INT.check() || SIG::TERM.check()) {
EV_STOPPING("proton", "unclean shutdown after interrupted init");
std::_Exit(0);
}
std::this_thread::sleep_for(100ms);
}
}
}
int
App::Main()
{
proton::Proton::UP protonUP;
try {
setupSignals();
Params params = parseParams();
LOG(debug, "identity: '%s'", params.identity.c_str());
LOG(debug, "serviceidentity: '%s'", params.serviceidentity.c_str());
LOG(debug, "subscribeTimeout: '%" PRIu64 "'", params.subscribeTimeout);
std::chrono::milliseconds subscribeTimeout(params.subscribeTimeout);
FastOS_ThreadPool threadPool(128_Ki);
uint32_t numProcs = std::thread::hardware_concurrency();
FNET_Transport transport(fnet::TransportConfig(std::max(1u, std::min(4u, numProcs/8))));
transport.Start(&threadPool);
config::ConfigServerSpec configServerSpec(transport);
config::ConfigUri identityUri(params.identity, std::make_shared<config::ConfigContext>(configServerSpec));
protonUP = std::make_unique<proton::Proton>(threadPool, transport, identityUri,
_argc > 0 ? _argv[0] : "proton", subscribeTimeout);
proton::Proton & proton = *protonUP;
proton::BootstrapConfig::SP configSnapshot = proton.init();
if (proton.hasAbortedInit()) {
EV_STOPPING("proton", "shutdown after aborted init");
} else {
const ProtonConfig &protonConfig = configSnapshot->getProtonConfig();
vespalib::string basedir = protonConfig.basedir;
vespalib::mkdir(basedir, true);
{
ExitOnSignal exit_on_signal;
proton.init(configSnapshot);
}
configSnapshot.reset();
std::unique_ptr<ProtonServiceLayerProcess> spiProton;
if ( ! params.serviceidentity.empty()) {
spiProton = std::make_unique<ProtonServiceLayerProcess>(identityUri.createWithNewId(params.serviceidentity), proton);
spiProton->setupConfig(subscribeTimeout);
spiProton->createNode();
EV_STARTED("servicelayer");
} else {
proton.getMetricManager().init(identityUri, proton.getThreadPool());
}
EV_STARTED("proton");
while (!(SIG::INT.check() || SIG::TERM.check() || (spiProton && spiProton->getNode().attemptedStopped()))) {
std::this_thread::sleep_for(1000ms);
if (spiProton && spiProton->configUpdated()) {
storage::ResumeGuard guard(spiProton->getNode().pause());
spiProton->updateConfig();
}
}
// Ensure metric manager and state server are shut down before we start tearing
// down any service layer components that they may end up transitively using.
protonUP->shutdown_config_fetching_and_state_exposing_components_once();
if (spiProton) {
spiProton->getNode().requestShutdown("controlled shutdown");
spiProton->shutdown();
EV_STOPPING("servicelayer", "clean shutdown");
}
protonUP.reset();
transport.ShutDown(true);
EV_STOPPING("proton", "clean shutdown");
}
} catch (const vespalib::InvalidCommandLineArgumentsException &e) {
LOG(warning, "Invalid commandline arguments: '%s'", e.what());
return 1;
} catch (const config::ConfigTimeoutException &e) {
LOG(warning, "Error subscribing to initial config: '%s'", e.what());
return 1;
} catch (const vespalib::PortListenException &e) {
LOG(warning, "Failed listening to a network port(%d) with protocol(%s): '%s'",
e.get_port(), e.get_protocol().c_str(), e.what());
return 1;
} catch (const vespalib::NetworkSetupFailureException & e) {
LOG(warning, "Network failure: '%s'", e.what());
return 1;
} catch (const config::InvalidConfigException & e) {
LOG(warning, "Invalid config failure: '%s'", e.what());
return 1;
} catch (const vespalib::IllegalStateException & e) {
LOG(error, "Unknown IllegalStateException: '%s'", e.what());
throw;
}
protonUP.reset();
LOG(debug, "Fully stopped, all destructors run.)");
return 0;
}
int main(int argc, char **argv) {
App app;
return app.Entry(argc, argv);
}
| // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/searchcore/proton/server/proton.h>
#include <vespa/storage/storageserver/storagenode.h>
#include <vespa/metrics/metricmanager.h>
#include <vespa/vespalib/util/signalhandler.h>
#include <vespa/vespalib/util/programoptions.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/config/common/exceptions.h>
#include <vespa/config/common/configcontext.h>
#include <vespa/fnet/transport.h>
#include <vespa/fastos/thread.h>
#include <vespa/fastos/app.h>
#include <iostream>
#include <thread>
#include <vespa/log/log.h>
LOG_SETUP("proton");
typedef vespalib::SignalHandler SIG;
using vespa::config::search::core::ProtonConfig;
struct Params
{
std::string identity;
std::string serviceidentity;
uint64_t subscribeTimeout;
Params();
~Params();
};
Params::Params()
: identity(),
serviceidentity(),
subscribeTimeout(60)
{}
Params::~Params() = default;
class App : public FastOS_Application
{
private:
static void setupSignals();
Params parseParams();
public:
int Main() override;
};
void
App::setupSignals()
{
SIG::PIPE.ignore();
SIG::INT.hook();
SIG::TERM.hook();
}
Params
App::parseParams()
{
Params params;
vespalib::ProgramOptions parser(_argc, _argv);
parser.setSyntaxMessage("proton -- the nextgen search core");
parser.addOption("identity", params.identity, "Node identity and config id");
std::string empty;
parser.addOption("serviceidentity", params.serviceidentity, empty, "Service node identity and config id");
parser.addOption("subscribeTimeout", params.subscribeTimeout, UINT64_C(600000), "Initial config subscribe timeout");
try {
parser.parse();
} catch (vespalib::InvalidCommandLineArgumentsException &e) {
parser.writeSyntaxPage(std::cerr);
throw;
}
return params;
}
using storage::spi::PersistenceProvider;
#include <vespa/storageserver/app/servicelayerprocess.h>
class ProtonServiceLayerProcess : public storage::ServiceLayerProcess {
proton::Proton & _proton;
metrics::MetricManager* _metricManager;
public:
ProtonServiceLayerProcess(const config::ConfigUri & configUri,
proton::Proton & proton);
~ProtonServiceLayerProcess() override { shutdown(); }
void shutdown() override;
void setupProvider() override;
storage::spi::PersistenceProvider& getProvider() override;
void setMetricManager(metrics::MetricManager& mm) {
// The service layer will call init(...) and stop() on the metric
// manager provided. Current design is that rather than depending
// on every component properly unregistering metrics and update
// hooks, the service layer stops metric manager ahead of shutting
// down component.
_metricManager = &mm;
}
int64_t getGeneration() const override;
};
ProtonServiceLayerProcess::ProtonServiceLayerProcess(const config::ConfigUri & configUri,
proton::Proton & proton)
: ServiceLayerProcess(configUri),
_proton(proton),
_metricManager(nullptr)
{
setMetricManager(_proton.getMetricManager());
}
void
ProtonServiceLayerProcess::shutdown()
{
ServiceLayerProcess::shutdown();
}
void
ProtonServiceLayerProcess::setupProvider()
{
if (_metricManager != nullptr) {
_context.getComponentRegister().setMetricManager(*_metricManager);
}
}
storage::spi::PersistenceProvider &
ProtonServiceLayerProcess::getProvider()
{
return _proton.getPersistence();
}
int64_t
ProtonServiceLayerProcess::getGeneration() const
{
int64_t slGen = storage::ServiceLayerProcess::getGeneration();
int64_t protonGen = _proton.getConfigGeneration();
return std::min(slGen, protonGen);
}
namespace {
class ExitOnSignal {
std::atomic<bool> _stop;
std::thread _thread;
public:
ExitOnSignal();
~ExitOnSignal();
void operator()();
};
ExitOnSignal::ExitOnSignal()
: _stop(false),
_thread()
{
_thread = std::thread(std::ref(*this));
}
ExitOnSignal::~ExitOnSignal()
{
_stop.store(true, std::memory_order_relaxed);
_thread.join();
}
void
ExitOnSignal::operator()()
{
while (!_stop.load(std::memory_order_relaxed)) {
if (SIG::INT.check() || SIG::TERM.check()) {
EV_STOPPING("proton", "unclean shutdown after interrupted init");
std::_Exit(0);
}
std::this_thread::sleep_for(100ms);
}
}
fnet::TransportConfig
buildTransportConfig() {
uint32_t numProcs = std::thread::hardware_concurrency();
return fnet::TransportConfig(std::max(1u, std::min(4u, numProcs/8)));
}
}
int
App::Main()
{
proton::Proton::UP protonUP;
try {
setupSignals();
Params params = parseParams();
LOG(debug, "identity: '%s'", params.identity.c_str());
LOG(debug, "serviceidentity: '%s'", params.serviceidentity.c_str());
LOG(debug, "subscribeTimeout: '%" PRIu64 "'", params.subscribeTimeout);
std::chrono::milliseconds subscribeTimeout(params.subscribeTimeout);
FastOS_ThreadPool threadPool(128_Ki);
FNET_Transport transport(buildTransportConfig());
transport.Start(&threadPool);
config::ConfigServerSpec configServerSpec(transport);
config::ConfigUri identityUri(params.identity, std::make_shared<config::ConfigContext>(configServerSpec));
protonUP = std::make_unique<proton::Proton>(threadPool, transport, identityUri,
_argc > 0 ? _argv[0] : "proton", subscribeTimeout);
proton::Proton & proton = *protonUP;
proton::BootstrapConfig::SP configSnapshot = proton.init();
if (proton.hasAbortedInit()) {
EV_STOPPING("proton", "shutdown after aborted init");
} else {
const ProtonConfig &protonConfig = configSnapshot->getProtonConfig();
vespalib::string basedir = protonConfig.basedir;
vespalib::mkdir(basedir, true);
{
ExitOnSignal exit_on_signal;
proton.init(configSnapshot);
}
configSnapshot.reset();
std::unique_ptr<ProtonServiceLayerProcess> spiProton;
if ( ! params.serviceidentity.empty()) {
spiProton = std::make_unique<ProtonServiceLayerProcess>(identityUri.createWithNewId(params.serviceidentity), proton);
spiProton->setupConfig(subscribeTimeout);
spiProton->createNode();
EV_STARTED("servicelayer");
} else {
proton.getMetricManager().init(identityUri, proton.getThreadPool());
}
EV_STARTED("proton");
while (!(SIG::INT.check() || SIG::TERM.check() || (spiProton && spiProton->getNode().attemptedStopped()))) {
std::this_thread::sleep_for(1000ms);
if (spiProton && spiProton->configUpdated()) {
storage::ResumeGuard guard(spiProton->getNode().pause());
spiProton->updateConfig();
}
}
// Ensure metric manager and state server are shut down before we start tearing
// down any service layer components that they may end up transitively using.
protonUP->shutdown_config_fetching_and_state_exposing_components_once();
if (spiProton) {
spiProton->getNode().requestShutdown("controlled shutdown");
spiProton->shutdown();
EV_STOPPING("servicelayer", "clean shutdown");
}
protonUP.reset();
transport.ShutDown(true);
EV_STOPPING("proton", "clean shutdown");
}
} catch (const vespalib::InvalidCommandLineArgumentsException &e) {
LOG(warning, "Invalid commandline arguments: '%s'", e.what());
return 1;
} catch (const config::ConfigTimeoutException &e) {
LOG(warning, "Error subscribing to initial config: '%s'", e.what());
return 1;
} catch (const vespalib::PortListenException &e) {
LOG(warning, "Failed listening to a network port(%d) with protocol(%s): '%s'",
e.get_port(), e.get_protocol().c_str(), e.what());
return 1;
} catch (const vespalib::NetworkSetupFailureException & e) {
LOG(warning, "Network failure: '%s'", e.what());
return 1;
} catch (const config::InvalidConfigException & e) {
LOG(warning, "Invalid config failure: '%s'", e.what());
return 1;
} catch (const vespalib::IllegalStateException & e) {
LOG(error, "Unknown IllegalStateException: '%s'", e.what());
throw;
}
protonUP.reset();
LOG(debug, "Fully stopped, all destructors run.)");
return 0;
}
int main(int argc, char **argv) {
App app;
return app.Entry(argc, argv);
}
| Use a config builder. | Use a config builder.
| C++ | apache-2.0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa |
f20198b0883ae1744ddec08711a63b86e50bcb82 | drag2d/src/drag2d/view/ObjectVector.inl | drag2d/src/drag2d/view/ObjectVector.inl | #ifndef _DRAG2D_VECTOR_CONTAINER_INL_
#define _DRAG2D_VECTOR_CONTAINER_INL_
namespace d2d
{
template<class T>
inline ObjectVector<T>::ObjectVector()
{
}
template<class T>
inline ObjectVector<T>::~ObjectVector()
{
Clear();
}
template<class T>
void ObjectVector<T>::Traverse(IVisitor& visitor, bool order) const
{
Traverse(m_objs, visitor, order);
}
template<class T>
void ObjectVector<T>::Traverse(IVisitor& visitor, DataTraverseType type, bool order) const
{
Traverse(m_objs, visitor, type, order);
}
template<class T>
bool ObjectVector<T>::Remove(T* obj)
{
return Remove(m_objs, obj);
}
template<class T>
bool ObjectVector<T>::Insert(T* obj)
{
return Insert(m_objs, obj);
}
template<class T>
bool ObjectVector<T>::Insert(T* obj, int idx)
{
return Insert(m_objs, obj, idx);
}
template<class T>
bool ObjectVector<T>::Clear()
{
return Clear(m_objs);
}
template<class T>
bool ObjectVector<T>::ResetOrder(const T* obj, bool up)
{
return ResetOrder(m_objs, obj, up);
}
template<class T>
bool ObjectVector<T>::ResetOrderMost(const T* obj, bool up)
{
return ResetOrderMost(m_objs, obj, up);
}
template<class T>
bool ObjectVector<T>::IsExist(T* obj) const
{
for (int i = 0, n = m_objs.size(); i < n; ++i) {
if (obj == m_objs[i]) {
return true;
}
}
return false;
}
template<class T>
int ObjectVector<T>::Size() const
{
return m_objs.size();
}
template<class T>
inline void ObjectVector<T>::Traverse(const std::vector<T*>& objs, IVisitor& visitor, bool order/* = true*/)
{
if (order)
{
std::vector<T*>::const_iterator itr = objs.begin();
for ( ; itr != objs.end(); ++itr)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
else
{
std::vector<T*>::const_reverse_iterator itr = objs.rbegin();
for ( ; itr != objs.rend(); ++itr)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
}
template<class T>
inline void ObjectVector<T>::Traverse(const std::vector<T*>& objs,
IVisitor& visitor,
DataTraverseType type,
bool order)
{
if (order)
{
std::vector<T*>::const_iterator itr = objs.begin();
for ( ; itr != objs.end(); ++itr)
{
if (type == DT_EDITABLE && (*itr)->editable ||
type == DT_VISIBLE && (*itr)->visiable ||
type == DT_ALL || type == DT_SELECTABLE)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
}
else
{
std::vector<T*>::const_reverse_iterator itr = objs.rbegin();
for ( ; itr != objs.rend(); ++itr)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
}
template<class T>
inline bool ObjectVector<T>::Remove(std::vector<T*>& objs,
T* obj)
{
for (size_t i = 0, n = objs.size(); i < n; ++i)
{
if (objs[i] == obj)
{
obj->Release();
objs.erase(objs.begin() + i);
return true;
}
}
return false;
}
template<class T>
inline bool ObjectVector<T>::Insert(std::vector<T*>& objs,
T* obj)
{
obj->Retain();
objs.push_back(obj);
return true;
}
template<class T>
inline bool ObjectVector<T>::Insert(std::vector<T*>& objs, T* obj, int idx)
{
obj->Retain();
if (objs.empty() || idx >= (int)objs.size()) {
objs.push_back(obj);
} else if (idx < 0) {
objs.insert(objs.begin(), obj);
} else {
objs.insert(objs.begin() + idx, obj);
}
return true;
}
template<class T>
inline bool ObjectVector<T>::Clear(std::vector<T*>& objs)
{
bool ret = !objs.empty();
for (size_t i = 0, n = objs.size(); i < n; ++i)
objs[i]->Release();
objs.clear();
return ret;
}
template<class T>
inline bool ObjectVector<T>::ResetOrder(std::vector<T*>& objs,
const T* obj,
bool up)
{
for (size_t i = 0, n = objs.size(); i < n; ++i)
{
if (objs[i] == obj)
{
if (up && i != n - 1)
{
std::swap(objs[i], objs[i + 1]);
return true;
}
else if (!up && i != 0)
{
std::swap(objs[i], objs[i - 1]);
return true;
}
return false;
}
}
return false;
}
template<class T>
inline bool ObjectVector<T>::ResetOrderMost(std::vector<T*>& objs, const T* obj, bool up) {
for (int i = 0, n = objs.size(); i < n; ++i) {
if (objs[i] == obj) {
if (up && i != n - 1) {
std::swap(objs[i], objs[n - 1]);
return true;
} else if (!up && i != 0) {
std::swap(objs[i], objs[0]);
return true;
}
return false;
}
}
return false;
}
}
#endif // _DRAG2D_VECTOR_CONTAINER_INL_ | #ifndef _DRAG2D_VECTOR_CONTAINER_INL_
#define _DRAG2D_VECTOR_CONTAINER_INL_
namespace d2d
{
template<class T>
inline ObjectVector<T>::ObjectVector()
{
}
template<class T>
inline ObjectVector<T>::~ObjectVector()
{
Clear();
}
template<class T>
void ObjectVector<T>::Traverse(IVisitor& visitor, bool order) const
{
Traverse(m_objs, visitor, order);
}
template<class T>
void ObjectVector<T>::Traverse(IVisitor& visitor, DataTraverseType type, bool order) const
{
Traverse(m_objs, visitor, type, order);
}
template<class T>
bool ObjectVector<T>::Remove(T* obj)
{
return Remove(m_objs, obj);
}
template<class T>
bool ObjectVector<T>::Insert(T* obj)
{
return Insert(m_objs, obj);
}
template<class T>
bool ObjectVector<T>::Insert(T* obj, int idx)
{
return Insert(m_objs, obj, idx);
}
template<class T>
bool ObjectVector<T>::Clear()
{
return Clear(m_objs);
}
template<class T>
bool ObjectVector<T>::ResetOrder(const T* obj, bool up)
{
return ResetOrder(m_objs, obj, up);
}
template<class T>
bool ObjectVector<T>::ResetOrderMost(const T* obj, bool up)
{
return ResetOrderMost(m_objs, obj, up);
}
template<class T>
bool ObjectVector<T>::IsExist(T* obj) const
{
for (int i = 0, n = m_objs.size(); i < n; ++i) {
if (obj == m_objs[i]) {
return true;
}
}
return false;
}
template<class T>
int ObjectVector<T>::Size() const
{
return m_objs.size();
}
template<class T>
inline void ObjectVector<T>::Traverse(const std::vector<T*>& objs, IVisitor& visitor, bool order/* = true*/)
{
if (order)
{
std::vector<T*>::const_iterator itr = objs.begin();
for ( ; itr != objs.end(); ++itr)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
else
{
std::vector<T*>::const_reverse_iterator itr = objs.rbegin();
for ( ; itr != objs.rend(); ++itr)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
}
template<class T>
inline void ObjectVector<T>::Traverse(const std::vector<T*>& objs,
IVisitor& visitor,
DataTraverseType type,
bool order)
{
if (order)
{
std::vector<T*>::const_iterator itr = objs.begin();
for ( ; itr != objs.end(); ++itr)
{
if (type == DT_EDITABLE && (*itr)->editable ||
type == DT_VISIBLE && (*itr)->visiable ||
type == DT_ALL || type == DT_SELECTABLE)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
}
else
{
std::vector<T*>::const_reverse_iterator itr = objs.rbegin();
for ( ; itr != objs.rend(); ++itr)
{
bool hasNext;
visitor.Visit(*itr, hasNext);
if (!hasNext) break;
}
}
}
template<class T>
inline bool ObjectVector<T>::Remove(std::vector<T*>& objs,
T* obj)
{
for (size_t i = 0, n = objs.size(); i < n; ++i)
{
if (objs[i] == obj)
{
obj->Release();
objs.erase(objs.begin() + i);
return true;
}
}
return false;
}
template<class T>
inline bool ObjectVector<T>::Insert(std::vector<T*>& objs,
T* obj)
{
obj->Retain();
objs.push_back(obj);
return true;
}
template<class T>
inline bool ObjectVector<T>::Insert(std::vector<T*>& objs, T* obj, int idx)
{
obj->Retain();
if (objs.empty() || idx >= (int)objs.size()) {
objs.push_back(obj);
} else if (idx < 0) {
objs.insert(objs.begin(), obj);
} else {
objs.insert(objs.begin() + idx, obj);
}
return true;
}
template<class T>
inline bool ObjectVector<T>::Clear(std::vector<T*>& objs)
{
bool ret = !objs.empty();
for (size_t i = 0, n = objs.size(); i < n; ++i)
objs[i]->Release();
objs.clear();
return ret;
}
template<class T>
inline bool ObjectVector<T>::ResetOrder(std::vector<T*>& objs,
const T* obj,
bool up)
{
for (size_t i = 0, n = objs.size(); i < n; ++i)
{
if (objs[i] == obj)
{
if (up && i != n - 1)
{
std::swap(objs[i], objs[i + 1]);
return true;
}
else if (!up && i != 0)
{
std::swap(objs[i], objs[i - 1]);
return true;
}
return false;
}
}
return false;
}
template<class T>
inline bool ObjectVector<T>::ResetOrderMost(std::vector<T*>& objs, const T* obj, bool up) {
for (int i = 0, n = objs.size(); i < n; ++i) {
if (objs[i] != obj) {
continue;
}
if (up && i != n - 1) {
T* tmp = objs[i];
for (int j = i + 1; j < n; ++j) {
objs[j-1] = objs[j];
}
objs[n - 1] = tmp;
return true;
} else if (!up && i != 0) {
T* tmp = objs[i];
for (int j = i - 1; j >= 0; --j) {
objs[j+1] = objs[j];
}
objs[0] = tmp;
return true;
}
return false;
}
return false;
}
}
#endif // _DRAG2D_VECTOR_CONTAINER_INL_ | order most | [FIXED] order most
Former-commit-id: 7b8ea9e0dd8c30246babe76358dd2ccb5434d929 | C++ | mit | xzrunner/easyeditor,xzrunner/easyeditor |
334ae5d516ef82c14d6952bdc882d1919f988b28 | src/dev/x86/pc.cc | src/dev/x86/pc.cc | /*
* Copyright (c) 2008 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Gabe Black
*/
/** @file
* Implementation of PC platform.
*/
#include <deque>
#include <string>
#include <vector>
#include "arch/x86/intmessage.hh"
#include "arch/x86/x86_traits.hh"
#include "cpu/intr_control.hh"
#include "dev/terminal.hh"
#include "dev/x86/i82094aa.hh"
#include "dev/x86/i8254.hh"
#include "dev/x86/pc.hh"
#include "dev/x86/south_bridge.hh"
#include "sim/system.hh"
using namespace std;
using namespace TheISA;
Pc::Pc(const Params *p)
: Platform(p), system(p->system)
{
southBridge = NULL;
// set the back pointer from the system to myself
system->platform = this;
}
void
Pc::init()
{
assert(southBridge);
/*
* Initialize the timer.
*/
I8254 & timer = *southBridge->pit;
//Timer 0, mode 2, no bcd, 16 bit count
timer.writeControl(0x34);
//Timer 0, latch command
timer.writeControl(0x00);
//Write a 16 bit count of 0
timer.writeCounter(0, 0);
timer.writeCounter(0, 0);
/*
* Initialize the I/O APIC.
*/
I82094AA & ioApic = *southBridge->ioApic;
I82094AA::RedirTableEntry entry = 0;
entry.deliveryMode = DeliveryMode::ExtInt;
entry.vector = 0x20;
ioApic.writeReg(0x10, entry.bottomDW);
ioApic.writeReg(0x11, entry.topDW);
}
Tick
Pc::intrFrequency()
{
panic("Need implementation\n");
M5_DUMMY_RETURN
}
void
Pc::postConsoleInt()
{
warn_once("Don't know what interrupt to post for console.\n");
//panic("Need implementation\n");
}
void
Pc::clearConsoleInt()
{
warn_once("Don't know what interrupt to clear for console.\n");
//panic("Need implementation\n");
}
void
Pc::postPciInt(int line)
{
panic("Need implementation\n");
}
void
Pc::clearPciInt(int line)
{
panic("Need implementation\n");
}
Addr
Pc::pciToDma(Addr pciAddr) const
{
panic("Need implementation\n");
M5_DUMMY_RETURN
}
Addr
Pc::calcConfigAddr(int bus, int dev, int func)
{
assert(func < 8);
assert(dev < 32);
assert(bus == 0);
return (PhysAddrPrefixPciConfig | (func << 8) | (dev << 11));
}
Pc *
PcParams::create()
{
return new Pc(this);
}
| /*
* Copyright (c) 2008 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Gabe Black
*/
/** @file
* Implementation of PC platform.
*/
#include <deque>
#include <string>
#include <vector>
#include "arch/x86/intmessage.hh"
#include "arch/x86/x86_traits.hh"
#include "cpu/intr_control.hh"
#include "dev/terminal.hh"
#include "dev/x86/i82094aa.hh"
#include "dev/x86/i8254.hh"
#include "dev/x86/pc.hh"
#include "dev/x86/south_bridge.hh"
#include "sim/system.hh"
using namespace std;
using namespace TheISA;
Pc::Pc(const Params *p)
: Platform(p), system(p->system)
{
southBridge = NULL;
// set the back pointer from the system to myself
system->platform = this;
}
void
Pc::init()
{
assert(southBridge);
/*
* Initialize the timer.
*/
I8254 & timer = *southBridge->pit;
//Timer 0, mode 2, no bcd, 16 bit count
timer.writeControl(0x34);
//Timer 0, latch command
timer.writeControl(0x00);
//Write a 16 bit count of 0
timer.writeCounter(0, 0);
timer.writeCounter(0, 0);
/*
* Initialize the I/O APIC.
*/
I82094AA & ioApic = *southBridge->ioApic;
I82094AA::RedirTableEntry entry = 0;
entry.deliveryMode = DeliveryMode::ExtInt;
entry.vector = 0x20;
ioApic.writeReg(0x10, entry.bottomDW);
ioApic.writeReg(0x11, entry.topDW);
entry.deliveryMode = DeliveryMode::Fixed;
entry.vector = 0x24;
ioApic.writeReg(0x18, entry.bottomDW);
ioApic.writeReg(0x19, entry.topDW);
entry.mask = 1;
entry.vector = 0x21;
ioApic.writeReg(0x12, entry.bottomDW);
ioApic.writeReg(0x13, entry.topDW);
entry.vector = 0x20;
ioApic.writeReg(0x14, entry.bottomDW);
ioApic.writeReg(0x15, entry.topDW);
entry.vector = 0x28;
ioApic.writeReg(0x20, entry.bottomDW);
ioApic.writeReg(0x21, entry.topDW);
entry.vector = 0x2C;
ioApic.writeReg(0x28, entry.bottomDW);
ioApic.writeReg(0x29, entry.topDW);
}
Tick
Pc::intrFrequency()
{
panic("Need implementation\n");
M5_DUMMY_RETURN
}
void
Pc::postConsoleInt()
{
warn_once("Don't know what interrupt to post for console.\n");
//panic("Need implementation\n");
}
void
Pc::clearConsoleInt()
{
warn_once("Don't know what interrupt to clear for console.\n");
//panic("Need implementation\n");
}
void
Pc::postPciInt(int line)
{
panic("Need implementation\n");
}
void
Pc::clearPciInt(int line)
{
panic("Need implementation\n");
}
Addr
Pc::pciToDma(Addr pciAddr) const
{
panic("Need implementation\n");
M5_DUMMY_RETURN
}
Addr
Pc::calcConfigAddr(int bus, int dev, int func)
{
assert(func < 8);
assert(dev < 32);
assert(bus == 0);
return (PhysAddrPrefixPciConfig | (func << 8) | (dev << 11));
}
Pc *
PcParams::create()
{
return new Pc(this);
}
| Configure the IO APIC more. | X86: Configure the IO APIC more.
| C++ | bsd-3-clause | haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,LingxiaoJIA/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5,LingxiaoJIA/gem5,haowu4682/gem5,haowu4682/gem5 |
17b60a5d5ebbb8956da0fa0d31aee1557ddc7fa2 | src/kinect_tomato_searcher/src/tomato_broadcaster.cpp | src/kinect_tomato_searcher/src/tomato_broadcaster.cpp | #include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/TransformStamped.h>
class TomatoBroadcaster {
tf2_ros::TransformBroadcaster broadcaster_;
geometry_msgs::TransformStamped transform_;
ros::Subscriber sub_;
public:
TomatoBroadcaster(ros::NodeHandle node_handle)
: transform_ {},
sub_ {node_handle.subscribe<geometry_msgs::PointStamped>("tomato_point/trusted", 1, &TomatoBroadcaster::callback, this)}
{
}
private:
void callback(const geometry_msgs::PointStamped::ConstPtr& msg)
{
transform_.header = msg->header;
transform_.header.frame_id = "kinect";
transform_.child_frame_id = "tomato";
transform_.transform.translation.x = msg->point.x;
transform_.transform.translation.y = msg->point.y;
transform_.transform.translation.z = msg->point.z;
transform_.transform.rotation.w = 1.0;
broadcaster_.sendTransform(transform_);
}
};
int main(int argc, char** argv){
ros::init(argc, argv, "tomato_point_broadcaster");
ros::NodeHandle node_handle;
TomatoBroadcaster broadcaster {node_handle};
ros::spin();
return 0;
}
| #include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/TransformStamped.h>
class TomatoBroadcaster {
tf2_ros::TransformBroadcaster broadcaster_;
geometry_msgs::TransformStamped transform_;
ros::Subscriber sub_;
public:
TomatoBroadcaster(ros::NodeHandle node_handle)
: transform_ {},
sub_ {node_handle.subscribe<geometry_msgs::PointStamped>("tomato_point", 1, &TomatoBroadcaster::callback, this)}
{
}
private:
void callback(const geometry_msgs::PointStamped::ConstPtr& msg)
{
transform_.header = msg->header;
transform_.header.frame_id = "kinect";
transform_.child_frame_id = "tomato";
transform_.transform.translation.x = msg->point.x;
transform_.transform.translation.y = msg->point.y;
transform_.transform.translation.z = msg->point.z;
transform_.transform.rotation.w = 1.0;
broadcaster_.sendTransform(transform_);
}
};
int main(int argc, char** argv){
ros::init(argc, argv, "tomato_point_broadcaster");
ros::NodeHandle node_handle;
TomatoBroadcaster broadcaster {node_handle};
ros::spin();
return 0;
}
| Fix topic name | Fix topic name
| C++ | mit | agrirobo/arcsys2,agrirobo/arcsys2 |
46a3e3cdace278b323f8fdce5ec50da6506cdd19 | lib/afsm/include/afsm/fsm.hpp | lib/afsm/include/afsm/fsm.hpp | /*
* fsm.hpp
*
* Created on: 25 мая 2016 г.
* Author: sergey.fedorov
*/
#ifndef AFSM_FSM_HPP_
#define AFSM_FSM_HPP_
#include <afsm/detail/base_states.hpp>
#include <afsm/detail/observer.hpp>
#include <deque>
namespace afsm {
//----------------------------------------------------------------------------
// State
//----------------------------------------------------------------------------
template < typename T, typename FSM >
class state : public detail::state_base< T > {
public:
using enclosing_fsm_type = FSM;
public:
state(enclosing_fsm_type& fsm)
: state::state_type{}, fsm_{&fsm}
{}
state(state const& rhs) = default;
state(state&& rhs) = default;
state(enclosing_fsm_type& fsm, state const& rhs)
: state::state_type{static_cast<typename state::state_type const&>(rhs)}, fsm_{&fsm}
{}
state(enclosing_fsm_type& fsm, state&& rhs)
: state::state_type{static_cast<typename state::state_type&&>(rhs)}, fsm_{&fsm}
{}
state&
operator = (state const& rhs)
{
state{rhs}.swap(*this);
return *this;
}
state&
operator = (state&& rhs)
{
swap(rhs);
return *this;
}
void
swap(state& rhs) noexcept
{
static_cast<typename state::state_type&>(*this).swap(rhs);
}
template < typename Event >
actions::event_process_result
process_event( Event&& evt )
{
return process_event_impl(::std::forward<Event>(evt),
detail::event_process_selector<
Event,
typename state::internal_events,
typename state::deferred_events>{} );
}
enclosing_fsm_type&
enclosing_fsm()
{ return *fsm_; }
enclosing_fsm_type const&
enclosing_fsm() const
{ return *fsm_; }
void
enclosing_fsm(enclosing_fsm_type& fsm)
{ fsm_ = &fsm; }
template < typename Event >
void
state_enter(Event&&) {}
template < typename Event >
void
state_exit(Event&&) {}
private:
template < typename Event >
actions::event_process_result
process_event_impl(Event&& evt,
detail::process_type<actions::event_process_result::process> const&)
{
return actions::handle_in_state_event(::std::forward<Event>(evt), *fsm_, *this);
}
template < typename Event >
constexpr actions::event_process_result
process_event_impl(Event&&,
detail::process_type<actions::event_process_result::defer> const&) const
{
return actions::event_process_result::defer;
}
template < typename Event >
constexpr actions::event_process_result
process_event_impl(Event&&,
detail::process_type<actions::event_process_result::refuse> const&) const
{
return actions::event_process_result::refuse;
}
private:
enclosing_fsm_type* fsm_;
};
//----------------------------------------------------------------------------
// Inner state machine
//----------------------------------------------------------------------------
template < typename T, typename FSM >
class inner_state_machine : public detail::state_machine_base< T, none, inner_state_machine<T, FSM> > {
public:
using enclosing_fsm_type = FSM;
using this_type = inner_state_machine<T, FSM>;
using base_machine_type = detail::state_machine_base< T, none, this_type >;
public:
inner_state_machine(enclosing_fsm_type& fsm)
: base_machine_type{this}, fsm_{&fsm} {}
inner_state_machine(inner_state_machine const& rhs)
: base_machine_type{this, rhs}, fsm_{rhs.fsm_} {}
inner_state_machine(inner_state_machine&& rhs)
: base_machine_type{this, ::std::move(rhs)},
fsm_{rhs.fsm_}
{
}
inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine const& rhs)
: base_machine_type{static_cast<base_machine_type const&>(rhs)}, fsm_{&fsm} {}
inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine&& rhs)
: base_machine_type{static_cast<base_machine_type&&>(rhs)}, fsm_{&fsm} {}
void
swap(inner_state_machine& rhs) noexcept
{
using ::std::swap;
static_cast<base_machine_type&>(*this).swap(rhs);
swap(fsm_, rhs.fsm_);
}
inner_state_machine&
operator = (inner_state_machine const& rhs)
{
inner_state_machine tmp{rhs};
swap(tmp);
return *this;
}
inner_state_machine&
operator = (inner_state_machine&& rhs)
{
swap(rhs);
return *this;
}
template < typename Event >
actions::event_process_result
process_event( Event&& event )
{
return process_event_impl(*fsm_, ::std::forward<Event>(event),
detail::event_process_selector<
Event,
typename inner_state_machine::handled_events,
typename inner_state_machine::deferred_events>{} );
}
enclosing_fsm_type&
enclosing_fsm()
{ return *fsm_; }
enclosing_fsm_type const&
enclosing_fsm() const
{ return *fsm_; }
void
enclosing_fsm(enclosing_fsm_type& fsm)
{ fsm_ = &fsm; }
private:
using base_machine_type::process_event_impl;
private:
enclosing_fsm_type* fsm_;
};
//----------------------------------------------------------------------------
// State machine
//----------------------------------------------------------------------------
template < typename T, typename Mutex, typename Observer,
template<typename> class ObserverWrapper >
class state_machine :
public detail::state_machine_base< T, Mutex,
state_machine<T, Mutex, Observer> >,
public ObserverWrapper<Observer> {
public:
static_assert( ::psst::meta::is_empty< typename T::deferred_events >::value,
"Outer state machine cannot defer events" );
using this_type = state_machine<T, Mutex, Observer>;
using base_machine_type = detail::state_machine_base< T, Mutex, this_type >;
using mutex_type = Mutex;
using lock_guard = typename detail::lock_guard_type<mutex_type>::type;
using observer_wrapper = ObserverWrapper<Observer>;
using event_invokation = ::std::function< actions::event_process_result() >;
using event_queue = ::std::deque< event_invokation >;
public:
state_machine()
: base_machine_type{this},
stack_size_{0},
mutex_{},
queued_events_{},
queue_size_{0},
deferred_mutex_{},
deferred_events_{}
{}
template<typename ... Args>
explicit
state_machine(Args&& ... args)
: base_machine_type(this, ::std::forward<Args>(args)...),
stack_size_{0},
mutex_{},
queued_events_{},
queue_size_{0},
deferred_mutex_{},
deferred_events_{}
{}
template < typename Event >
actions::event_process_result
process_event( Event&& event )
{
if (!stack_size_++) {
auto res = process_event_dispatch(::std::forward<Event>(event));
--stack_size_;
// Process enqueued events
process_event_queue();
return res;
} else {
--stack_size_;
// Enqueue event
enqueue_event(::std::forward<Event>(event));
return actions::event_process_result::defer;
}
}
private:
template < typename Event >
actions::event_process_result
process_event_dispatch( Event&& event )
{
return process_event_impl(::std::forward<Event>(event),
detail::event_process_selector<
Event,
typename state_machine::handled_events>{} );
}
template < typename Event >
actions::event_process_result
process_event_impl(Event&& event,
detail::process_type<actions::event_process_result::process> const& sel)
{
using actions::event_process_result;
observer_wrapper::start_process_event(*this, ::std::forward<Event>(event));
auto res = base_machine_type::process_event_impl(*this, ::std::forward<Event>(event), sel );
switch (res) {
case event_process_result::process:
observer_wrapper::state_changed(*this);
// Changed state. Process deferred events
process_deferred_queue();
break;
case event_process_result::process_in_state:
observer_wrapper::processed_in_state(*this, ::std::forward<Event>(event));
break;
case event_process_result::defer:
// Add event to deferred queue
defer_event(::std::forward<Event>(event));
break;
case event_process_result::refuse:
// The event cannot be processed in current state
observer_wrapper::reject_event(*this, ::std::forward<Event>(event));
break;
default:
break;
}
return res;
}
template < typename Event >
actions::event_process_result
process_event_impl(Event&&,
detail::process_type<actions::event_process_result::refuse> const&)
{
static_assert( detail::event_process_selector<
Event,
typename state_machine::handled_events,
typename state_machine::deferred_events>::value
!= actions::event_process_result::refuse,
"Event type is not handled by this state machine" );
return actions::event_process_result::refuse;
}
template < typename Event >
void
enqueue_event(Event&& event)
{
{
lock_guard lock{mutex_};
++queue_size_;
observer_wrapper::enqueue_event(*this, ::std::forward<Event>(event));
Event evt = event;
queued_events_.emplace_back([&, evt]() mutable {
return process_event_dispatch(::std::move(evt));
});
}
// Process enqueued events in case we've been waiting for queue
// mutex release
process_event_queue();
}
void
lock_and_swap_queue(event_queue& queue)
{
lock_guard lock{mutex_};
::std::swap(queued_events_, queue);
queue_size_ -= queue.size();
}
void
process_event_queue()
{
// TODO replace those if's with atomic compare and swap
if (stack_size_)
return;
if (stack_size_++) {
--stack_size_;
return;
}
observer_wrapper::start_process_events_queue(*this);
while (queue_size_ > 0) {
event_queue postponed;
lock_and_swap_queue(postponed);
for (auto const& event : postponed) {
event();
}
}
--stack_size_;
observer_wrapper::end_process_events_queue(*this);
if (queue_size_ > 0) {
process_event_queue();
}
}
template < typename Event >
void
defer_event(Event&& event)
{
lock_guard lock{deferred_mutex_};
observer_wrapper::defer_event(*this, ::std::forward<Event>(event));
Event evt = event;
deferred_events_.emplace_back([&, evt]() mutable {
return process_event_dispatch(::std::move(evt));
});
}
void
process_deferred_queue()
{
using actions::event_process_result;
if (stack_size_++ <= 1) {
event_queue deferred;
{
lock_guard lock{deferred_mutex_};
::std::swap(deferred_events_, deferred);
}
while (!deferred.empty()) {
observer_wrapper::start_process_deferred_queue(*this);
auto res = event_process_result::refuse;
while (!deferred.empty()) {
auto event = deferred.front();
deferred.pop_front();
res = event();
if (res == event_process_result::process)
break;
}
{
lock_guard lock{deferred_mutex_};
deferred_events_.insert(deferred_events_.end(), deferred.begin(), deferred.end());
deferred.clear();
}
if (res == event_process_result::process) {
::std::swap(deferred_events_, deferred);
}
observer_wrapper::end_process_deferred_queue(*this);
}
}
--stack_size_;
}
private:
using atomic_counter = ::std::atomic< ::std::size_t >;
atomic_counter stack_size_;
mutex_type mutex_;
event_queue queued_events_;
atomic_counter queue_size_;
mutex_type deferred_mutex_;
event_queue deferred_events_;
};
} /* namespace afsm */
#endif /* AFSM_FSM_HPP_ */
| /*
* fsm.hpp
*
* Created on: 25 мая 2016 г.
* Author: sergey.fedorov
*/
#ifndef AFSM_FSM_HPP_
#define AFSM_FSM_HPP_
#include <afsm/detail/base_states.hpp>
#include <afsm/detail/observer.hpp>
#include <deque>
namespace afsm {
//----------------------------------------------------------------------------
// State
//----------------------------------------------------------------------------
template < typename T, typename FSM >
class state : public detail::state_base< T > {
public:
using enclosing_fsm_type = FSM;
public:
state(enclosing_fsm_type& fsm)
: state::state_type{}, fsm_{&fsm}
{}
state(state const& rhs) = default;
state(state&& rhs) = default;
state(enclosing_fsm_type& fsm, state const& rhs)
: state::state_type{static_cast<typename state::state_type const&>(rhs)}, fsm_{&fsm}
{}
state(enclosing_fsm_type& fsm, state&& rhs)
: state::state_type{static_cast<typename state::state_type&&>(rhs)}, fsm_{&fsm}
{}
state&
operator = (state const& rhs)
{
state{rhs}.swap(*this);
return *this;
}
state&
operator = (state&& rhs)
{
swap(rhs);
return *this;
}
void
swap(state& rhs) noexcept
{
static_cast<typename state::state_type&>(*this).swap(rhs);
}
template < typename Event >
actions::event_process_result
process_event( Event&& evt )
{
return process_event_impl(::std::forward<Event>(evt),
detail::event_process_selector<
Event,
typename state::internal_events,
typename state::deferred_events>{} );
}
enclosing_fsm_type&
enclosing_fsm()
{ return *fsm_; }
enclosing_fsm_type const&
enclosing_fsm() const
{ return *fsm_; }
void
enclosing_fsm(enclosing_fsm_type& fsm)
{ fsm_ = &fsm; }
template < typename Event >
void
state_enter(Event&&) {}
template < typename Event >
void
state_exit(Event&&) {}
private:
template < typename Event >
actions::event_process_result
process_event_impl(Event&& evt,
detail::process_type<actions::event_process_result::process> const&)
{
return actions::handle_in_state_event(::std::forward<Event>(evt), *fsm_, *this);
}
template < typename Event >
constexpr actions::event_process_result
process_event_impl(Event&&,
detail::process_type<actions::event_process_result::defer> const&) const
{
return actions::event_process_result::defer;
}
template < typename Event >
constexpr actions::event_process_result
process_event_impl(Event&&,
detail::process_type<actions::event_process_result::refuse> const&) const
{
return actions::event_process_result::refuse;
}
private:
enclosing_fsm_type* fsm_;
};
//----------------------------------------------------------------------------
// Inner state machine
//----------------------------------------------------------------------------
template < typename T, typename FSM >
class inner_state_machine : public detail::state_machine_base< T, none, inner_state_machine<T, FSM> > {
public:
using enclosing_fsm_type = FSM;
using this_type = inner_state_machine<T, FSM>;
using base_machine_type = detail::state_machine_base< T, none, this_type >;
public:
inner_state_machine(enclosing_fsm_type& fsm)
: base_machine_type{this}, fsm_{&fsm} {}
inner_state_machine(inner_state_machine const& rhs)
: base_machine_type{this, rhs}, fsm_{rhs.fsm_} {}
inner_state_machine(inner_state_machine&& rhs)
: base_machine_type{this, ::std::move(rhs)},
fsm_{rhs.fsm_}
{
}
inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine const& rhs)
: base_machine_type{static_cast<base_machine_type const&>(rhs)}, fsm_{&fsm} {}
inner_state_machine(enclosing_fsm_type& fsm, inner_state_machine&& rhs)
: base_machine_type{static_cast<base_machine_type&&>(rhs)}, fsm_{&fsm} {}
void
swap(inner_state_machine& rhs) noexcept
{
using ::std::swap;
static_cast<base_machine_type&>(*this).swap(rhs);
swap(fsm_, rhs.fsm_);
}
inner_state_machine&
operator = (inner_state_machine const& rhs)
{
inner_state_machine tmp{rhs};
swap(tmp);
return *this;
}
inner_state_machine&
operator = (inner_state_machine&& rhs)
{
swap(rhs);
return *this;
}
template < typename Event >
actions::event_process_result
process_event( Event&& event )
{
return process_event_impl(*fsm_, ::std::forward<Event>(event),
detail::event_process_selector<
Event,
typename inner_state_machine::handled_events,
typename inner_state_machine::deferred_events>{} );
}
enclosing_fsm_type&
enclosing_fsm()
{ return *fsm_; }
enclosing_fsm_type const&
enclosing_fsm() const
{ return *fsm_; }
void
enclosing_fsm(enclosing_fsm_type& fsm)
{ fsm_ = &fsm; }
private:
using base_machine_type::process_event_impl;
private:
enclosing_fsm_type* fsm_;
};
//----------------------------------------------------------------------------
// State machine
//----------------------------------------------------------------------------
template < typename T, typename Mutex, typename Observer,
template<typename> class ObserverWrapper >
class state_machine :
public detail::state_machine_base< T, Mutex,
state_machine<T, Mutex, Observer> >,
public ObserverWrapper<Observer> {
public:
static_assert( ::psst::meta::is_empty< typename T::deferred_events >::value,
"Outer state machine cannot defer events" );
using this_type = state_machine<T, Mutex, Observer>;
using base_machine_type = detail::state_machine_base< T, Mutex, this_type >;
using mutex_type = Mutex;
using lock_guard = typename detail::lock_guard_type<mutex_type>::type;
using observer_wrapper = ObserverWrapper<Observer>;
using event_invokation = ::std::function< actions::event_process_result() >;
using event_queue = ::std::deque< event_invokation >;
public:
state_machine()
: base_machine_type{this},
is_top_{},
mutex_{},
queued_events_{},
queue_size_{0},
deferred_mutex_{},
deferred_events_{}
{}
template<typename ... Args>
explicit
state_machine(Args&& ... args)
: base_machine_type(this, ::std::forward<Args>(args)...),
is_top_{},
mutex_{},
queued_events_{},
queue_size_{0},
deferred_mutex_{},
deferred_events_{}
{}
template < typename Event >
actions::event_process_result
process_event( Event&& event )
{
if (!is_top_.test_and_set()) {
auto res = process_event_dispatch(::std::forward<Event>(event));
is_top_.clear();
// Process enqueued events
process_event_queue();
return res;
} else {
// Enqueue event
enqueue_event(::std::forward<Event>(event));
return actions::event_process_result::defer;
}
}
private:
template < typename Event >
actions::event_process_result
process_event_dispatch( Event&& event )
{
return process_event_impl(::std::forward<Event>(event),
detail::event_process_selector<
Event,
typename state_machine::handled_events>{} );
}
template < typename Event >
actions::event_process_result
process_event_impl(Event&& event,
detail::process_type<actions::event_process_result::process> const& sel)
{
using actions::event_process_result;
observer_wrapper::start_process_event(*this, ::std::forward<Event>(event));
auto res = base_machine_type::process_event_impl(*this, ::std::forward<Event>(event), sel );
switch (res) {
case event_process_result::process:
observer_wrapper::state_changed(*this);
// Changed state. Process deferred events
process_deferred_queue();
break;
case event_process_result::process_in_state:
observer_wrapper::processed_in_state(*this, ::std::forward<Event>(event));
break;
case event_process_result::defer:
// Add event to deferred queue
defer_event(::std::forward<Event>(event));
break;
case event_process_result::refuse:
// The event cannot be processed in current state
observer_wrapper::reject_event(*this, ::std::forward<Event>(event));
break;
default:
break;
}
return res;
}
template < typename Event >
actions::event_process_result
process_event_impl(Event&&,
detail::process_type<actions::event_process_result::refuse> const&)
{
static_assert( detail::event_process_selector<
Event,
typename state_machine::handled_events,
typename state_machine::deferred_events>::value
!= actions::event_process_result::refuse,
"Event type is not handled by this state machine" );
return actions::event_process_result::refuse;
}
template < typename Event >
void
enqueue_event(Event&& event)
{
{
lock_guard lock{mutex_};
++queue_size_;
observer_wrapper::enqueue_event(*this, ::std::forward<Event>(event));
Event evt = event;
queued_events_.emplace_back([&, evt]() mutable {
return process_event_dispatch(::std::move(evt));
});
}
// Process enqueued events in case we've been waiting for queue
// mutex release
process_event_queue();
}
void
lock_and_swap_queue(event_queue& queue)
{
lock_guard lock{mutex_};
::std::swap(queued_events_, queue);
queue_size_ -= queue.size();
}
void
process_event_queue()
{
while (queue_size_ > 0 && !is_top_.test_and_set()) {
observer_wrapper::start_process_events_queue(*this);
while (queue_size_ > 0) {
event_queue postponed;
lock_and_swap_queue(postponed);
for (auto const& event : postponed) {
event();
}
}
observer_wrapper::end_process_events_queue(*this);
is_top_.clear();
}
}
template < typename Event >
void
defer_event(Event&& event)
{
lock_guard lock{deferred_mutex_};
observer_wrapper::defer_event(*this, ::std::forward<Event>(event));
Event evt = event;
deferred_events_.emplace_back([&, evt]() mutable {
return process_event_dispatch(::std::move(evt));
});
}
void
process_deferred_queue()
{
using actions::event_process_result;
event_queue deferred;
{
lock_guard lock{deferred_mutex_};
::std::swap(deferred_events_, deferred);
}
while (!deferred.empty()) {
observer_wrapper::start_process_deferred_queue(*this);
auto res = event_process_result::refuse;
while (!deferred.empty()) {
auto event = deferred.front();
deferred.pop_front();
res = event();
if (res == event_process_result::process)
break;
}
{
lock_guard lock{deferred_mutex_};
deferred_events_.insert(deferred_events_.end(), deferred.begin(), deferred.end());
deferred.clear();
}
if (res == event_process_result::process) {
::std::swap(deferred_events_, deferred);
}
observer_wrapper::end_process_deferred_queue(*this);
}
}
private:
using atomic_counter = ::std::atomic< ::std::size_t >;
::std::atomic_flag is_top_;
mutex_type mutex_;
event_queue queued_events_;
atomic_counter queue_size_;
mutex_type deferred_mutex_;
event_queue deferred_events_;
};
} /* namespace afsm */
#endif /* AFSM_FSM_HPP_ */
| Replace atomic counter with atomic flag. | Replace atomic counter with atomic flag.
| C++ | artistic-2.0 | zmij/pg_async |
c86ba1b560057b3644eae919e1c1ddd18a291c78 | transforms/Apple/H264Encode.cpp | transforms/Apple/H264Encode.cpp | /*
Video Core
Copyright (C) 2014 James G. Hurley
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 <stdio.h>
#include <videocore/transforms/Apple/H264Encode.h>
#include <VideoToolbox/VideoToolbox.h>
namespace videocore { namespace Apple {
void vtCallback(void *outputCallbackRefCon,
void *sourceFrameRefCon,
OSStatus status,
VTEncodeInfoFlags infoFlags,
CMSampleBufferRef sampleBuffer )
{
CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sampleBuffer);
char* bufferData;
size_t size;
CMBlockBufferGetDataPointer(block, 0, NULL, &size, &bufferData);
((H264Encode*)outputCallbackRefCon)->compressionSessionOutput((uint8_t*)bufferData,size);
}
H264Encode::H264Encode( int frame_w, int frame_h, int fps, int bitrate )
: m_frameW(frame_w), m_frameH(frame_h), m_fps(fps), m_bitrate(bitrate)
{
setupCompressionSession();
}
H264Encode::~H264Encode()
{
VTCompressionSessionInvalidate((VTCompressionSessionRef)m_compressionSession);
CFRelease((VTCompressionSessionRef)m_compressionSession);
}
void
H264Encode::setupCompressionSession()
{
// Parts of this code pulled from https://github.com/galad87/HandBrake-QuickSync-Mac/blob/2c1332958f7095c640cbcbcb45ffc955739d5945/libhb/platform/macosx/encvt_h264.c
OSStatus err = noErr;
CFStringRef key = kVTVideoEncoderSpecification_EncoderID;
CFStringRef value = CFSTR("com.apple.videotoolbox.videoencoder.h264.gva"); // this needs to be verified on iOS with VTCopyVideoEncoderList
CFStringRef bkey = CFSTR("EnableHardwareAcceleratedVideoEncoder");
CFBooleanRef bvalue = kCFBooleanTrue;
CFStringRef ckey = CFSTR("RequireHardwareAcceleratedVideoEncoder");
CFBooleanRef cvalue = kCFBooleanTrue;
CFMutableDictionaryRef encoderSpecifications = CFDictionaryCreateMutable(
kCFAllocatorDefault,
3,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(encoderSpecifications, bkey, bvalue);
CFDictionaryAddValue(encoderSpecifications, ckey, cvalue);
CFDictionaryAddValue(encoderSpecifications, key, value);
err = VTCompressionSessionCreate(
kCFAllocatorDefault,
job->width,
job->height,
kCMVideoCodecType_H264,
encoderSpecifications,
NULL,
NULL,
&vtCallback,
this,
&session);
if(err == noErr) {
m_session = session;
const int v = m_fps * 2; // 2-second kfi
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_MaxKeyFrameInterval, &v);
}
if(err == noErr) {
const int v = m_fps / 2; // limit the number of frames kept in the buffer
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_MaxFrameDelayCount, &v);
}
if(err == noErr) {
const int v = m_fps;
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_ExpectedFrameRate, &v);
}
}
void
H264Encode::compressionSessionOutput(const uint8_t *data, size_t size)
{
}
}
} | /*
Video Core
Copyright (C) 2014 James G. Hurley
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 <stdio.h>
#include <videocore/transforms/Apple/H264Encode.h>
#include <VideoToolbox/VideoToolbox.h>
namespace videocore { namespace Apple {
void vtCallback(void *outputCallbackRefCon,
void *sourceFrameRefCon,
OSStatus status,
VTEncodeInfoFlags infoFlags,
CMSampleBufferRef sampleBuffer )
{
CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sampleBuffer);
char* bufferData;
size_t size;
CMBlockBufferGetDataPointer(block, 0, NULL, &size, &bufferData);
((H264Encode*)outputCallbackRefCon)->compressionSessionOutput((uint8_t*)bufferData,size);
}
H264Encode::H264Encode( int frame_w, int frame_h, int fps, int bitrate )
: m_frameW(frame_w), m_frameH(frame_h), m_fps(fps), m_bitrate(bitrate)
{
setupCompressionSession();
}
H264Encode::~H264Encode()
{
VTCompressionSessionInvalidate((VTCompressionSessionRef)m_compressionSession);
CFRelease((VTCompressionSessionRef)m_compressionSession);
}
void
H264Encode::setupCompressionSession()
{
// Parts of this code pulled from https://github.com/galad87/HandBrake-QuickSync-Mac/blob/2c1332958f7095c640cbcbcb45ffc955739d5945/libhb/platform/macosx/encvt_h264.c
// More info from WWDC 2014 Session 513
OSStatus err = noErr;
#if !TARGET_OS_IPHONE
/** iOS is always hardware-accelerated **/
CFStringRef key = kVTVideoEncoderSpecification_EncoderID;
CFStringRef value = CFSTR("com.apple.videotoolbox.videoencoder.h264.gva"); // this needs to be verified on iOS with VTCopyVideoEncoderList
CFStringRef bkey = CFSTR("EnableHardwareAcceleratedVideoEncoder");
CFBooleanRef bvalue = kCFBooleanTrue;
CFStringRef ckey = CFSTR("RequireHardwareAcceleratedVideoEncoder");
CFBooleanRef cvalue = kCFBooleanTrue;
CFMutableDictionaryRef encoderSpecifications = CFDictionaryCreateMutable(
kCFAllocatorDefault,
3,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(encoderSpecifications, bkey, bvalue);
CFDictionaryAddValue(encoderSpecifications, ckey, cvalue);
CFDictionaryAddValue(encoderSpecifications, key, value);
#endif
err = VTCompressionSessionCreate(
kCFAllocatorDefault,
m_frameW,
m_frameH,
kCMVideoCodecType_H264,
encoderSpecifications,
NULL,
NULL,
&vtCallback,
this,
&session);
if(err == noErr) {
m_session = session;
const int v = m_fps * 2; // 2-second kfi
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_MaxKeyFrameInterval, &v);
}
if(err == noErr) {
const int v = m_fps / 2; // limit the number of frames kept in the buffer
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_MaxFrameDelayCount, &v);
}
if(err == noErr) {
const int v = m_fps;
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_ExpectedFrameRate, &v);
}
if(err == noErr) {
const int v = 0;
err = VTSessionSetProperty(session , kVTCompressionPropertyKey_AllowFrameReordering, &v);
}
if(err == noErr) {
const int v = m_bitrate;
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_AverageBitRate, &v);
}
if(err == noErr) {
const int v = 1;
err = VTSessionSetProperty(session, kVTCompressionPropertyKey_RealTime, &v);
}
}
void
H264Encode::compressionSessionOutput(const uint8_t *data, size_t size)
{
}
}
} | Add some more settings to the setup of VTCompressionSession - still need to download Xcode 6 to actually build a working encoder - doing that now\! | Add some more settings to the setup of VTCompressionSession - still need to download Xcode 6 to actually build a working encoder - doing that now\!
| C++ | mit | maxcampolo/VideoCore,0dayZh/VideoCore,Firekast-io/VideoCore,dourgulf/VideoCore,0dayZh/VideoCore,sigvef/VideoCore,bellchen/VideoCore,musicallyapp/VideoCore,ppamorim/VideoCore,musicallyapp/VideoCore,cristeahub/VideoCore,JustineKay/VideoCore,JALsnipe/VideoCore,dymx101/VideoCore,dourgulf/VideoCore,amikey/VideoCore,VladSumtsov/VideoCore,amikey/VideoCore,Firekast-io/VideoCore,neshume/VideoCore,JALsnipe/VideoCore,cine-io/VideoCore,JustineKay/VideoCore,VladSumtsov/VideoCore,leemon20/VideoCore,dymx101/VideoCore,ArenaCloud/VideoCore,cine-io/VideoCore,JALsnipe/VideoCore,amikey/VideoCore,Firekast-io/VideoCore,sigvef/VideoCore,gouravd/VideoCore,jrstv/VideoCore,maxcampolo/VideoCore,JustineKay/VideoCore,ppamorim/VideoCore,JALsnipe/VideoCore,maxcampolo/VideoCore,dourgulf/VideoCore,gouravd/VideoCore,ArenaCloud/VideoCore,neshume/VideoCore,jgh-/VideoCore,bellchen/VideoCore,jgh-/VideoCore,jrstv/VideoCore,dymx101/VideoCore,musicallyapp/VideoCore,cristeahub/VideoCore,PavlyukDev/VideoCore,JustineKay/VideoCore,VladSumtsov/VideoCore,cristeahub/VideoCore,ArenaCloud/VideoCore,TradeCast/VideoCore,PavlyukDev/VideoCore,VladSumtsov/VideoCore,sigvef/VideoCore,TradeCast/VideoCore,jgh-/VideoCore,amikey/VideoCore,sigvef/VideoCore,neshume/VideoCore,ppamorim/VideoCore,leemon20/VideoCore,ArenaCloud/VideoCore,neshume/VideoCore,cristeahub/VideoCore,musicallyapp/VideoCore,cine-io/VideoCore,ppamorim/VideoCore,leemon20/VideoCore,gouravd/VideoCore,jgh-/VideoCore,PavlyukDev/VideoCore,TradeCast/VideoCore,PavlyukDev/VideoCore,bellchen/VideoCore,dymx101/VideoCore,jrstv/VideoCore,0dayZh/VideoCore,leemon20/VideoCore,maxcampolo/VideoCore,maxcampolo/VideoCore,jrstv/VideoCore |
ff46b740582b622bb6e1384740c75a334dc40a59 | src/mlpack/methods/range_search/range_search_impl.hpp | src/mlpack/methods/range_search/range_search_impl.hpp | /**
* @file range_search_impl.hpp
* @author Ryan Curtin
*
* Implementation of the RangeSearch class.
*/
#ifndef __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
#define __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
// Just in case it hasn't been included.
#include "range_search.hpp"
// The rules for traversal.
#include "range_search_rules.hpp"
namespace mlpack {
namespace range {
template<typename TreeType>
TreeType* BuildTree(
typename TreeType::Mat& dataset,
std::vector<size_t>& oldFromNew,
typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == true, TreeType*
>::type = 0)
{
return new TreeType(dataset, oldFromNew);
}
//! Call the tree constructor that does not do mapping.
template<typename TreeType>
TreeType* BuildTree(
const typename TreeType::Mat& dataset,
const std::vector<size_t>& /* oldFromNew */,
const typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == false, TreeType*
>::type = 0)
{
return new TreeType(dataset);
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
const typename TreeType::Mat& referenceSetIn,
const typename TreeType::Mat& querySetIn,
const bool naive,
const bool singleMode,
const MetricType metric) :
referenceSet(tree::TreeTraits<TreeType>::RearrangesDataset ? referenceCopy
: referenceSetIn),
querySet(tree::TreeTraits<TreeType>::RearrangesDataset ? queryCopy
: querySetIn),
treeOwner(!naive), // If in naive mode, we are not building any trees.
hasQuerySet(true),
naive(naive),
singleMode(!naive && singleMode), // Naive overrides single mode.
metric(metric),
numPrunes(0)
{
// Build the trees.
Timer::Start("range_search/tree_building");
// Copy the datasets, if they will be modified during tree building.
if (tree::TreeTraits<TreeType>::RearrangesDataset)
{
referenceCopy = referenceSetIn;
queryCopy = querySetIn;
}
// If in naive mode, then we do not need to build trees.
if (!naive)
{
// The const_cast is safe; if RearrangesDataset == false, then it'll be
// casted back to const anyway, and if not, referenceSet points to
// referenceCopy, which isn't const.
referenceTree = BuildTree<TreeType>(
const_cast<typename TreeType::Mat&>(referenceSet),
oldFromNewReferences);
if (!singleMode)
queryTree = BuildTree<TreeType>(
const_cast<typename TreeType::Mat&>(querySet), oldFromNewQueries);
}
Timer::Stop("range_search/tree_building");
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
const typename TreeType::Mat& referenceSetIn,
const bool naive,
const bool singleMode,
const MetricType metric) :
referenceSet(tree::TreeTraits<TreeType>::RearrangesDataset ? referenceCopy
: referenceSetIn),
querySet(tree::TreeTraits<TreeType>::RearrangesDataset ? referenceCopy
: referenceSetIn),
queryTree(NULL),
treeOwner(!naive), // If in naive mode, we are not building any trees.
hasQuerySet(false),
naive(naive),
singleMode(!naive && singleMode), // Naive overrides single mode.
metric(metric),
numPrunes(0)
{
// Build the trees.
Timer::Start("range_search/tree_building");
// Copy the dataset, if it will be modified during tree building.
if (tree::TreeTraits<TreeType>::RearrangesDataset)
referenceCopy = referenceSetIn;
// If in naive mode, then we do not need to build trees.
if (!naive)
{
// The const_cast is safe; if RearrangesDataset == false, then it'll be
// casted back to const anyway, and if not, referenceSet points to
// referenceCopy, which isn't const.
referenceTree = BuildTree<TreeType>(
const_cast<typename TreeType::Mat&>(referenceSet),
oldFromNewReferences);
if (!singleMode)
queryTree = new TreeType(*referenceTree);
}
Timer::Stop("range_search/tree_building");
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
TreeType* referenceTree,
TreeType* queryTree,
const typename TreeType::Mat& referenceSet,
const typename TreeType::Mat& querySet,
const bool singleMode,
const MetricType metric) :
referenceSet(referenceSet),
querySet(querySet),
referenceTree(referenceTree),
queryTree(queryTree),
treeOwner(false),
hasQuerySet(true),
naive(false),
singleMode(singleMode),
metric(metric),
numPrunes(0)
{
// Nothing else to initialize.
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
TreeType* referenceTree,
const typename TreeType::Mat& referenceSet,
const bool singleMode,
const MetricType metric) :
referenceSet(referenceSet),
querySet(referenceSet),
referenceTree(referenceTree),
queryTree(NULL),
treeOwner(false),
hasQuerySet(false),
naive(false),
singleMode(singleMode),
metric(metric),
numPrunes(0)
{
// If doing dual-tree range search, we must clone the reference tree.
if (!singleMode)
queryTree = new TreeType(*referenceTree);
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::~RangeSearch()
{
if (treeOwner)
{
if (referenceTree)
delete referenceTree;
if (queryTree)
delete queryTree;
}
// If doing dual-tree search with one dataset, we cloned the reference tree.
if (!treeOwner && !hasQuerySet && !(singleMode || naive))
delete queryTree;
}
template<typename MetricType, typename TreeType>
void RangeSearch<MetricType, TreeType>::Search(
const math::Range& range,
std::vector<std::vector<size_t> >& neighbors,
std::vector<std::vector<double> >& distances)
{
Timer::Start("range_search/computing_neighbors");
// Set size of prunes to 0.
numPrunes = 0;
// If we have built the trees ourselves, then we will have to map all the
// indices back to their original indices when this computation is finished.
// To avoid extra copies, we will store the unmapped neighbors and distances
// in a separate object.
std::vector<std::vector<size_t> >* neighborPtr = &neighbors;
std::vector<std::vector<double> >* distancePtr = &distances;
// Mapping is only necessary if the tree rearranges points.
if (tree::TreeTraits<TreeType>::RearrangesDataset)
{
if (treeOwner && !(singleMode && hasQuerySet))
distancePtr = new std::vector<std::vector<double> >; // Query indices need to be mapped.
if (treeOwner)
neighborPtr = new std::vector<std::vector<size_t> >; // All indices need mapping.
}
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(querySet.n_cols);
distancePtr->clear();
distancePtr->resize(querySet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, TreeType> RuleType;
RuleType rules(referenceSet, querySet, range, *neighborPtr, *distancePtr,
metric);
if (naive)
{
// The naive brute-force solution.
for (size_t i = 0; i < querySet.n_cols; ++i)
for (size_t j = 0; j < referenceSet.n_cols; ++j)
rules.BaseCase(i, j);
}
else if (singleMode)
{
// Create the traverser.
typename TreeType::template SingleTreeTraverser<RuleType> traverser(rules);
// Now have it traverse for each point.
for (size_t i = 0; i < querySet.n_cols; ++i)
traverser.Traverse(i, *referenceTree);
numPrunes = traverser.NumPrunes();
}
else // Dual-tree recursion.
{
// Create the traverser.
typename TreeType::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*queryTree, *referenceTree);
numPrunes = traverser.NumPrunes();
}
Timer::Stop("range_search/computing_neighbors");
// Output number of prunes.
Log::Info << "Number of pruned nodes during computation: " << numPrunes
<< "." << std::endl;
// Map points back to original indices, if necessary.
if (!treeOwner || !tree::TreeTraits<TreeType>::RearrangesDataset)
{
// No mapping needed. We are done.
return;
}
else if (treeOwner && hasQuerySet && !singleMode) // Map both sets.
{
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
size_t queryMapping = oldFromNewQueries[i];
distances[queryMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[queryMapping].resize(distances[queryMapping].size());
for (size_t j = 0; j < distances[queryMapping].size(); j++)
{
neighbors[queryMapping][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (treeOwner && !hasQuerySet)
{
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
size_t refMapping = oldFromNewReferences[i];
distances[refMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[refMapping].resize(distances[refMapping].size());
for (size_t j = 0; j < distances[refMapping].size(); j++)
{
neighbors[refMapping][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (treeOwner && hasQuerySet && singleMode) // Map only references.
{
neighbors.clear();
neighbors.resize(querySet.n_cols);
// Map indices of neighbors.
for (size_t i = 0; i < neighbors.size(); i++)
{
neighbors[i].resize((*neighborPtr)[i].size());
for (size_t j = 0; j < neighbors[i].size(); j++)
{
neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary object.
delete neighborPtr;
}
}
template<typename MetricType, typename TreeType>
std::string RangeSearch<MetricType, TreeType>::ToString() const
{
std::ostringstream convert;
convert << "Range Search [" << this << "]" << std::endl;
if (treeOwner)
convert << " Tree Owner: TRUE" << std::endl;
if (naive)
convert << " Naive: TRUE" << std::endl;
convert << " Metric: " << std::endl <<
mlpack::util::Indent(metric.ToString(),2);
return convert.str();
}
}; // namespace range
}; // namespace mlpack
#endif
| /**
* @file range_search_impl.hpp
* @author Ryan Curtin
*
* Implementation of the RangeSearch class.
*/
#ifndef __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
#define __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
// Just in case it hasn't been included.
#include "range_search.hpp"
// The rules for traversal.
#include "range_search_rules.hpp"
namespace mlpack {
namespace range {
template<typename TreeType>
TreeType* BuildTree(
typename TreeType::Mat& dataset,
std::vector<size_t>& oldFromNew,
typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == true, TreeType*
>::type = 0)
{
return new TreeType(dataset, oldFromNew);
}
//! Call the tree constructor that does not do mapping.
template<typename TreeType>
TreeType* BuildTree(
const typename TreeType::Mat& dataset,
const std::vector<size_t>& /* oldFromNew */,
const typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == false, TreeType*
>::type = 0)
{
return new TreeType(dataset);
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
const typename TreeType::Mat& referenceSetIn,
const typename TreeType::Mat& querySetIn,
const bool naive,
const bool singleMode,
const MetricType metric) :
referenceSet(tree::TreeTraits<TreeType>::RearrangesDataset ? referenceCopy
: referenceSetIn),
querySet(tree::TreeTraits<TreeType>::RearrangesDataset ? queryCopy
: querySetIn),
referenceTree(NULL),
queryTree(NULL),
treeOwner(!naive), // If in naive mode, we are not building any trees.
hasQuerySet(true),
naive(naive),
singleMode(!naive && singleMode), // Naive overrides single mode.
metric(metric),
numPrunes(0)
{
// Build the trees.
Timer::Start("range_search/tree_building");
// Copy the datasets, if they will be modified during tree building.
if (tree::TreeTraits<TreeType>::RearrangesDataset)
{
referenceCopy = referenceSetIn;
queryCopy = querySetIn;
}
// If in naive mode, then we do not need to build trees.
if (!naive)
{
// The const_cast is safe; if RearrangesDataset == false, then it'll be
// casted back to const anyway, and if not, referenceSet points to
// referenceCopy, which isn't const.
referenceTree = BuildTree<TreeType>(
const_cast<typename TreeType::Mat&>(referenceSet),
oldFromNewReferences);
if (!singleMode)
queryTree = BuildTree<TreeType>(
const_cast<typename TreeType::Mat&>(querySet), oldFromNewQueries);
}
Timer::Stop("range_search/tree_building");
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
const typename TreeType::Mat& referenceSetIn,
const bool naive,
const bool singleMode,
const MetricType metric) :
referenceSet(tree::TreeTraits<TreeType>::RearrangesDataset ? referenceCopy
: referenceSetIn),
querySet(tree::TreeTraits<TreeType>::RearrangesDataset ? referenceCopy
: referenceSetIn),
referenceTree(NULL),
queryTree(NULL),
treeOwner(!naive), // If in naive mode, we are not building any trees.
hasQuerySet(false),
naive(naive),
singleMode(!naive && singleMode), // Naive overrides single mode.
metric(metric),
numPrunes(0)
{
// Build the trees.
Timer::Start("range_search/tree_building");
// Copy the dataset, if it will be modified during tree building.
if (tree::TreeTraits<TreeType>::RearrangesDataset)
referenceCopy = referenceSetIn;
// If in naive mode, then we do not need to build trees.
if (!naive)
{
// The const_cast is safe; if RearrangesDataset == false, then it'll be
// casted back to const anyway, and if not, referenceSet points to
// referenceCopy, which isn't const.
referenceTree = BuildTree<TreeType>(
const_cast<typename TreeType::Mat&>(referenceSet),
oldFromNewReferences);
if (!singleMode)
queryTree = new TreeType(*referenceTree);
}
Timer::Stop("range_search/tree_building");
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
TreeType* referenceTree,
TreeType* queryTree,
const typename TreeType::Mat& referenceSet,
const typename TreeType::Mat& querySet,
const bool singleMode,
const MetricType metric) :
referenceSet(referenceSet),
querySet(querySet),
referenceTree(referenceTree),
queryTree(queryTree),
treeOwner(false),
hasQuerySet(true),
naive(false),
singleMode(singleMode),
metric(metric),
numPrunes(0)
{
// Nothing else to initialize.
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::RangeSearch(
TreeType* referenceTree,
const typename TreeType::Mat& referenceSet,
const bool singleMode,
const MetricType metric) :
referenceSet(referenceSet),
querySet(referenceSet),
referenceTree(referenceTree),
queryTree(NULL),
treeOwner(false),
hasQuerySet(false),
naive(false),
singleMode(singleMode),
metric(metric),
numPrunes(0)
{
// If doing dual-tree range search, we must clone the reference tree.
if (!singleMode)
queryTree = new TreeType(*referenceTree);
}
template<typename MetricType, typename TreeType>
RangeSearch<MetricType, TreeType>::~RangeSearch()
{
if (treeOwner)
{
if (referenceTree)
delete referenceTree;
if (queryTree)
delete queryTree;
}
// If doing dual-tree search with one dataset, we cloned the reference tree.
if (!treeOwner && !hasQuerySet && !(singleMode || naive))
delete queryTree;
}
template<typename MetricType, typename TreeType>
void RangeSearch<MetricType, TreeType>::Search(
const math::Range& range,
std::vector<std::vector<size_t> >& neighbors,
std::vector<std::vector<double> >& distances)
{
Timer::Start("range_search/computing_neighbors");
// Set size of prunes to 0.
numPrunes = 0;
// If we have built the trees ourselves, then we will have to map all the
// indices back to their original indices when this computation is finished.
// To avoid extra copies, we will store the unmapped neighbors and distances
// in a separate object.
std::vector<std::vector<size_t> >* neighborPtr = &neighbors;
std::vector<std::vector<double> >* distancePtr = &distances;
// Mapping is only necessary if the tree rearranges points.
if (tree::TreeTraits<TreeType>::RearrangesDataset)
{
if (treeOwner && !(singleMode && hasQuerySet))
distancePtr = new std::vector<std::vector<double> >; // Query indices need to be mapped.
if (treeOwner)
neighborPtr = new std::vector<std::vector<size_t> >; // All indices need mapping.
}
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(querySet.n_cols);
distancePtr->clear();
distancePtr->resize(querySet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, TreeType> RuleType;
RuleType rules(referenceSet, querySet, range, *neighborPtr, *distancePtr,
metric);
if (naive)
{
// The naive brute-force solution.
for (size_t i = 0; i < querySet.n_cols; ++i)
for (size_t j = 0; j < referenceSet.n_cols; ++j)
rules.BaseCase(i, j);
}
else if (singleMode)
{
// Create the traverser.
typename TreeType::template SingleTreeTraverser<RuleType> traverser(rules);
// Now have it traverse for each point.
for (size_t i = 0; i < querySet.n_cols; ++i)
traverser.Traverse(i, *referenceTree);
numPrunes = traverser.NumPrunes();
}
else // Dual-tree recursion.
{
// Create the traverser.
typename TreeType::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*queryTree, *referenceTree);
numPrunes = traverser.NumPrunes();
}
Timer::Stop("range_search/computing_neighbors");
// Output number of prunes.
Log::Info << "Number of pruned nodes during computation: " << numPrunes
<< "." << std::endl;
// Map points back to original indices, if necessary.
if (!treeOwner || !tree::TreeTraits<TreeType>::RearrangesDataset)
{
// No mapping needed. We are done.
return;
}
else if (treeOwner && hasQuerySet && !singleMode) // Map both sets.
{
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
size_t queryMapping = oldFromNewQueries[i];
distances[queryMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[queryMapping].resize(distances[queryMapping].size());
for (size_t j = 0; j < distances[queryMapping].size(); j++)
{
neighbors[queryMapping][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (treeOwner && !hasQuerySet)
{
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
size_t refMapping = oldFromNewReferences[i];
distances[refMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[refMapping].resize(distances[refMapping].size());
for (size_t j = 0; j < distances[refMapping].size(); j++)
{
neighbors[refMapping][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (treeOwner && hasQuerySet && singleMode) // Map only references.
{
neighbors.clear();
neighbors.resize(querySet.n_cols);
// Map indices of neighbors.
for (size_t i = 0; i < neighbors.size(); i++)
{
neighbors[i].resize((*neighborPtr)[i].size());
for (size_t j = 0; j < neighbors[i].size(); j++)
{
neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary object.
delete neighborPtr;
}
}
template<typename MetricType, typename TreeType>
std::string RangeSearch<MetricType, TreeType>::ToString() const
{
std::ostringstream convert;
convert << "Range Search [" << this << "]" << std::endl;
if (treeOwner)
convert << " Tree Owner: TRUE" << std::endl;
if (naive)
convert << " Naive: TRUE" << std::endl;
convert << " Metric: " << std::endl <<
mlpack::util::Indent(metric.ToString(),2);
return convert.str();
}
}; // namespace range
}; // namespace mlpack
#endif
| initialize tree pointer | initialize tree pointer
| C++ | bsd-3-clause | thirdwing/mlpack,bmswgnp/mlpack,trungda/mlpack,chenmoshushi/mlpack,erubboli/mlpack,BookChan/mlpack,thirdwing/mlpack,bmswgnp/mlpack,chenmoshushi/mlpack,Azizou/mlpack,ranjan1990/mlpack,ranjan1990/mlpack,thirdwing/mlpack,ersanliqiao/mlpack,theranger/mlpack,chenmoshushi/mlpack,darcyliu/mlpack,BookChan/mlpack,stereomatchingkiss/mlpack,Azizou/mlpack,erubboli/mlpack,darcyliu/mlpack,erubboli/mlpack,bmswgnp/mlpack,datachand/mlpack,ajjl/mlpack,darcyliu/mlpack,theranger/mlpack,theranger/mlpack,Azizou/mlpack,stereomatchingkiss/mlpack,palashahuja/mlpack,palashahuja/mlpack,lezorich/mlpack,BookChan/mlpack,datachand/mlpack,ersanliqiao/mlpack,minhpqn/mlpack,minhpqn/mlpack,lezorich/mlpack,ajjl/mlpack,ajjl/mlpack,lezorich/mlpack,minhpqn/mlpack,trungda/mlpack,stereomatchingkiss/mlpack,datachand/mlpack,ranjan1990/mlpack,trungda/mlpack,ersanliqiao/mlpack,palashahuja/mlpack |
0ce51fc04ed2091a82825775be854d4741d00ba1 | validate.cpp | validate.cpp | /*
* Copyright (c) 2014, NVIDIA CORPORATION. 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.
*/
#include <stdlib.h>
#include <memory.h>
#include <stdio.h>
#include <iostream>
#include <cuda.h>
#include <cuda_runtime_api.h>
using namespace std;
#include "gdrapi.h"
#include "common.hpp"
int main(int argc, char *argv[])
{
void *dummy;
ASSERTRT(cudaMalloc(&dummy, 0));
const size_t _size = 256*1024+16; //32*1024+8;
const size_t size = (_size + GPU_PAGE_SIZE - 1) & GPU_PAGE_MASK;
printf("buffer size: %zu\n", size);
CUdeviceptr d_A;
ASSERTDRV(cuMemAlloc(&d_A, size));
ASSERTDRV(cuMemsetD8(d_A, 0xA5, size));
//OUT << "device ptr: " << hex << d_A << dec << endl;
unsigned int flag = 1;
ASSERTDRV(cuPointerSetAttribute(&flag, CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, d_A));
uint32_t *init_buf = new uint32_t[size];
uint32_t *copy_buf = new uint32_t[size];
init_hbuf_walking_bit(init_buf, size);
memset(copy_buf, 0, sizeof(*copy_buf) * sizeof(uint32_t));
gdr_t g = gdr_open();
ASSERT_NEQ(g, (void*)0);
gdr_mh_t mh;
BEGIN_CHECK {
CUdeviceptr d_ptr = d_A;
// tokens are optional in CUDA 6.0
// wave out the test if GPUDirectRDMA is not enabled
BREAK_IF_NEQ(gdr_pin_buffer(g, d_ptr, size, 0, 0, &mh), 0);
ASSERT_NEQ(mh, 0U);
void *bar_ptr = NULL;
ASSERT_EQ(gdr_map(g, mh, &bar_ptr, size), 0);
//OUT << "bar_ptr: " << bar_ptr << endl;
gdr_info_t info;
ASSERT_EQ(gdr_get_info(g, mh, &info), 0);
int off = d_ptr - info.va;
cout << "off: " << off << endl;
uint32_t *buf_ptr = (uint32_t *)((char *)bar_ptr + off);
//OUT << "buf_ptr:" << buf_ptr << endl;
printf("check 1: MMIO CPU initialization + read back via cuMemcpy D->H\n");
init_hbuf_walking_bit(buf_ptr, size);
//mmiowcwb();
ASSERTDRV(cuMemcpyDtoH(copy_buf, d_ptr, size));
//ASSERTDRV(cuCtxSynchronize());
compare_buf(init_buf, copy_buf, size);
printf("check 2: gdr_copy_to_bar() + read back via cuMemcpy D->H\n");
gdr_copy_to_bar(buf_ptr, init_buf, size);
ASSERTDRV(cuMemcpyDtoH(copy_buf, d_ptr, size));
//ASSERTDRV(cuCtxSynchronize());
compare_buf(init_buf, copy_buf, size);
fflush(stdout);
printf("check 3: gdr_copy_to_bar() + read back via gdr_copy_from_bar()\n");
gdr_copy_to_bar(buf_ptr, init_buf, size);
gdr_copy_from_bar(copy_buf, buf_ptr, size);
//ASSERTDRV(cuCtxSynchronize());
compare_buf(init_buf, copy_buf, size);
int extra_dwords = 5;
int extra_off = extra_dwords * sizeof(uint32_t);
printf("check 4: gdr_copy_to_bar() + read back via gdr_copy_from_bar() + %d dwords offset\n", extra_dwords);
gdr_copy_to_bar(buf_ptr + extra_dwords, init_buf, size - extra_off);
gdr_copy_from_bar(copy_buf, buf_ptr + extra_dwords, size - extra_off);
compare_buf(init_buf, copy_buf, size - extra_off);
extra_off = 11;
printf("check 4: gdr_copy_to_bar() + read back via gdr_copy_from_bar() + %d bytes offset\n", extra_off);
gdr_copy_to_bar((char*)buf_ptr + extra_off, init_buf, size);
gdr_copy_from_bar(copy_buf, (char*)buf_ptr + extra_off, size);
compare_buf(init_buf, copy_buf, size);
ASSERT_EQ(gdr_unmap(g, mh, bar_ptr, size), 0);
ASSERT_EQ(gdr_unpin_buffer(g, mh), 0);
} END_CHECK;
ASSERT_EQ(gdr_close(g), 0);
ASSERTDRV(cuMemFree(d_A));
return 0;
}
/*
* Local variables:
* c-indent-level: 4
* c-basic-offset: 4
* tab-width: 4
* indent-tabs-mode: nil
* End:
*/
| /*
* Copyright (c) 2014, NVIDIA CORPORATION. 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.
*/
#include <stdlib.h>
#include <memory.h>
#include <stdio.h>
#include <iostream>
#include <cuda.h>
#include <cuda_runtime_api.h>
using namespace std;
#include "gdrapi.h"
#include "common.hpp"
int main(int argc, char *argv[])
{
void *dummy;
ASSERTRT(cudaMalloc(&dummy, 0));
const size_t _size = 256*1024+16; //32*1024+8;
const size_t size = (_size + GPU_PAGE_SIZE - 1) & GPU_PAGE_MASK;
printf("buffer size: %zu\n", size);
CUdeviceptr d_A;
ASSERTDRV(cuMemAlloc(&d_A, size));
ASSERTDRV(cuMemsetD8(d_A, 0xA5, size));
//OUT << "device ptr: " << hex << d_A << dec << endl;
unsigned int flag = 1;
ASSERTDRV(cuPointerSetAttribute(&flag, CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, d_A));
uint32_t *init_buf = new uint32_t[size];
uint32_t *copy_buf = new uint32_t[size];
init_hbuf_walking_bit(init_buf, size);
memset(copy_buf, 0, sizeof(*copy_buf) * sizeof(uint32_t));
gdr_t g = gdr_open();
ASSERT_NEQ(g, (void*)0);
gdr_mh_t mh;
BEGIN_CHECK {
CUdeviceptr d_ptr = d_A;
// tokens are optional in CUDA 6.0
// wave out the test if GPUDirectRDMA is not enabled
BREAK_IF_NEQ(gdr_pin_buffer(g, d_ptr, size, 0, 0, &mh), 0);
ASSERT_NEQ(mh, 0U);
void *bar_ptr = NULL;
ASSERT_EQ(gdr_map(g, mh, &bar_ptr, size), 0);
//OUT << "bar_ptr: " << bar_ptr << endl;
gdr_info_t info;
ASSERT_EQ(gdr_get_info(g, mh, &info), 0);
int off = d_ptr - info.va;
cout << "off: " << off << endl;
uint32_t *buf_ptr = (uint32_t *)((char *)bar_ptr + off);
//OUT << "buf_ptr:" << buf_ptr << endl;
printf("check 1: MMIO CPU initialization + read back via cuMemcpy D->H\n");
init_hbuf_walking_bit(buf_ptr, size);
//mmiowcwb();
ASSERTDRV(cuMemcpyDtoH(copy_buf, d_ptr, size));
//ASSERTDRV(cuCtxSynchronize());
compare_buf(init_buf, copy_buf, size);
printf("check 2: gdr_copy_to_bar() + read back via cuMemcpy D->H\n");
gdr_copy_to_bar(buf_ptr, init_buf, size);
ASSERTDRV(cuMemcpyDtoH(copy_buf, d_ptr, size));
//ASSERTDRV(cuCtxSynchronize());
compare_buf(init_buf, copy_buf, size);
fflush(stdout);
printf("check 3: gdr_copy_to_bar() + read back via gdr_copy_from_bar()\n");
gdr_copy_to_bar(buf_ptr, init_buf, size);
gdr_copy_from_bar(copy_buf, buf_ptr, size);
//ASSERTDRV(cuCtxSynchronize());
compare_buf(init_buf, copy_buf, size);
int extra_dwords = 5;
int extra_off = extra_dwords * sizeof(uint32_t);
printf("check 4: gdr_copy_to_bar() + read back via gdr_copy_from_bar() + %d dwords offset\n", extra_dwords);
gdr_copy_to_bar(buf_ptr + extra_dwords, init_buf, size - extra_off);
gdr_copy_from_bar(copy_buf, buf_ptr + extra_dwords, size - extra_off);
compare_buf(init_buf, copy_buf, size - extra_off);
extra_off = 11;
printf("check 5: gdr_copy_to_bar() + read back via gdr_copy_from_bar() + %d bytes offset\n", extra_off);
gdr_copy_to_bar((char*)buf_ptr + extra_off, init_buf, size);
gdr_copy_from_bar(copy_buf, (char*)buf_ptr + extra_off, size);
compare_buf(init_buf, copy_buf, size);
printf("unampping\n");
ASSERT_EQ(gdr_unmap(g, mh, bar_ptr, size), 0);
printf("unpinning\n");
ASSERT_EQ(gdr_unpin_buffer(g, mh), 0);
} END_CHECK;
ASSERT_EQ(gdr_close(g), 0);
ASSERTDRV(cuMemFree(d_A));
return 0;
}
/*
* Local variables:
* c-indent-level: 4
* c-basic-offset: 4
* tab-width: 4
* indent-tabs-mode: nil
* End:
*/
| fix index in print, add more progress msgs | fix index in print, add more progress msgs
| C++ | mit | NVIDIA/gdrcopy,NVIDIA/gdrcopy,NVIDIA/gdrcopy |
5da8b63a668e8266ba9a81dd661bfc690e9cf65b | dtool/src/cppparser/cppFunctionType.cxx | dtool/src/cppparser/cppFunctionType.cxx | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file cppFunctionType.cxx
* @author drose
* @date 1999-10-21
*/
#include "cppFunctionType.h"
#include "cppParameterList.h"
#include "cppSimpleType.h"
#include "cppInstance.h"
using std::ostream;
using std::ostringstream;
using std::string;
/**
*
*/
CPPFunctionType::
CPPFunctionType(CPPType *return_type, CPPParameterList *parameters,
int flags) :
CPPType(CPPFile()),
_return_type(return_type),
_parameters(parameters),
_flags(flags)
{
_class_owner = nullptr;
// If the parameter list contains just the token "void", it means no
// parameters.
if (_parameters != nullptr &&
_parameters->_parameters.size() == 1 &&
_parameters->_parameters.front()->_type->as_simple_type() != nullptr &&
_parameters->_parameters.front()->_type->as_simple_type()->_type ==
CPPSimpleType::T_void &&
_parameters->_parameters.front()->_ident == nullptr) {
_parameters->_parameters.clear();
}
}
/**
*
*/
CPPFunctionType::
CPPFunctionType(const CPPFunctionType ©) :
CPPType(copy),
_return_type(copy._return_type),
_parameters(copy._parameters),
_flags(copy._flags),
_class_owner(copy._class_owner)
{
}
/**
*
*/
void CPPFunctionType::
operator = (const CPPFunctionType ©) {
CPPType::operator = (copy);
_return_type = copy._return_type;
_parameters = copy._parameters;
_flags = copy._flags;
_class_owner = copy._class_owner;
}
/**
* Returns true if the function accepts the given number of parameters.
*/
bool CPPFunctionType::
accepts_num_parameters(int num_parameters) {
assert(num_parameters >= 0);
if (_parameters == nullptr) {
return (num_parameters == 0);
}
size_t actual_num_parameters = _parameters->_parameters.size();
// If we passed too many parameters, it must have an ellipsis.
if ((size_t)num_parameters > actual_num_parameters) {
return _parameters->_includes_ellipsis;
}
// Make sure all superfluous parameters have a default value.
for (size_t i = (size_t)num_parameters; i < actual_num_parameters; ++i) {
CPPInstance *param = _parameters->_parameters[i];
if (param->_initializer == nullptr) {
return false;
}
}
return true;
}
/**
* Returns true if this declaration is an actual, factual declaration, or
* false if some part of the declaration depends on a template parameter which
* has not yet been instantiated.
*/
bool CPPFunctionType::
is_fully_specified() const {
return CPPType::is_fully_specified() &&
_return_type->is_fully_specified() &&
_parameters->is_fully_specified();
}
/**
*
*/
CPPDeclaration *CPPFunctionType::
substitute_decl(CPPDeclaration::SubstDecl &subst,
CPPScope *current_scope, CPPScope *global_scope) {
SubstDecl::const_iterator si = subst.find(this);
if (si != subst.end()) {
return (*si).second;
}
CPPFunctionType *rep = new CPPFunctionType(*this);
if (_return_type != nullptr) {
rep->_return_type =
_return_type->substitute_decl(subst, current_scope, global_scope)
->as_type();
}
if (_parameters != nullptr) {
rep->_parameters =
_parameters->substitute_decl(subst, current_scope, global_scope);
}
if (rep->_return_type == _return_type &&
rep->_parameters == _parameters) {
delete rep;
rep = this;
}
rep = CPPType::new_type(rep)->as_function_type();
subst.insert(SubstDecl::value_type(this, rep));
return rep;
}
/**
* If this CPPType object is a forward reference or other nonspecified
* reference to a type that might now be known a real type, returns the real
* type. Otherwise returns the type itself.
*/
CPPType *CPPFunctionType::
resolve_type(CPPScope *current_scope, CPPScope *global_scope) {
CPPType *rtype = _return_type->resolve_type(current_scope, global_scope);
CPPParameterList *params;
if (_parameters == nullptr) {
params = nullptr;
} else {
params = _parameters->resolve_type(current_scope, global_scope);
}
if (rtype != _return_type || params != _parameters) {
CPPFunctionType *rep = new CPPFunctionType(*this);
rep->_return_type = rtype;
rep->_parameters = params;
return CPPType::new_type(rep);
}
return this;
}
/**
* Returns true if the type, or any nested type within the type, is a
* CPPTBDType and thus isn't fully determined right now. In this case,
* calling resolve_type() may or may not resolve the type.
*/
bool CPPFunctionType::
is_tbd() const {
if (_return_type->is_tbd()) {
return true;
}
return _parameters == nullptr || _parameters->is_tbd();
}
/**
* Returns true if the type is considered a Plain Old Data (POD) type.
*/
bool CPPFunctionType::
is_trivial() const {
return false;
}
/**
*
*/
void CPPFunctionType::
output(ostream &out, int indent_level, CPPScope *scope, bool complete) const {
output(out, indent_level, scope, complete, -1);
}
/**
* The additional parameter allows us to specify the number of parameters we
* wish to show the default values for. If num_default_parameters is >= 0, it
* indicates the number of default parameter values to show on output.
* Otherwise, all parameter values are shown.
*/
void CPPFunctionType::
output(ostream &out, int indent_level, CPPScope *scope, bool complete,
int num_default_parameters) const {
if (_flags & F_trailing_return_type) {
// It was declared using trailing return type, so let's format it that
// way.
out << "auto(";
_parameters->output(out, scope, true, num_default_parameters);
out << ")";
if (_flags & F_const_method) {
out << " const";
}
if (_flags & F_noexcept) {
out << " noexcept";
}
if (_flags & F_final) {
out << " final";
}
if (_flags & F_override) {
out << " override";
}
out << " -> ";
_return_type->output(out, indent_level, scope, false);
} else {
_return_type->output(out, indent_level, scope, complete);
out << "(";
_parameters->output(out, scope, true, num_default_parameters);
out << ")";
if (_flags & F_const_method) {
out << " const";
}
if (_flags & F_noexcept) {
out << " noexcept";
}
if (_flags & F_final) {
out << " final";
}
if (_flags & F_override) {
out << " override";
}
}
}
/**
* Formats a C++-looking line that defines an instance of the given type, with
* the indicated name. In most cases this will be "type name", but some types
* have special exceptions.
*/
void CPPFunctionType::
output_instance(ostream &out, int indent_level, CPPScope *scope,
bool complete, const string &prename,
const string &name) const {
output_instance(out, indent_level, scope, complete, prename, name, -1);
}
/**
* The additional parameter allows us to specify the number of parameters we
* wish to show the default values for. If num_default_parameters is >= 0, it
* indicates the number of default parameter values to show on output.
* Otherwise, all parameter values are shown.
*/
void CPPFunctionType::
output_instance(ostream &out, int indent_level, CPPScope *scope,
bool complete, const string &prename,
const string &name, int num_default_parameters) const {
ostringstream parm_string;
parm_string << "(";
_parameters->output(parm_string, scope, true, num_default_parameters);
parm_string << ")";
string str = parm_string.str();
if (_flags & (F_constructor | F_destructor)) {
// No return type for constructors and destructors.
out << prename << name << str;
} else if (_flags & F_trailing_return_type) {
// It was declared using trailing return type, so let's format it that
// way.
out << "auto ";
if (prename.empty()) {
out << name;
} else {
out << "(" << prename << name << ")";
}
out << str;
} else {
if (prename.empty()) {
_return_type->output_instance(out, indent_level, scope, complete,
"", prename + name + str);
} else {
_return_type->output_instance(out, indent_level, scope, complete,
"", "(" + prename + name + ")" + str);
}
}
if (_flags & F_const_method) {
out << " const";
}
if (_flags & F_volatile_method) {
out << " volatile";
}
if (_flags & F_noexcept) {
out << " noexcept";
}
if (_flags & F_final) {
out << " final";
}
if (_flags & F_override) {
out << " override";
}
if (_flags & F_trailing_return_type) {
out << " -> ";
_return_type->output(out, indent_level, scope, false);
}
}
/**
* Returns the number of parameters in the list that may take default values.
*/
int CPPFunctionType::
get_num_default_parameters() const {
// The trick is just to count, beginning from the end and working towards
// the front, the number of parameters that have some initializer.
if (_parameters == nullptr) {
return 0;
}
const CPPParameterList::Parameters ¶ms = _parameters->_parameters;
CPPParameterList::Parameters::const_reverse_iterator pi;
int count = 0;
for (pi = params.rbegin();
pi != params.rend() && (*pi)->_initializer != nullptr;
++pi) {
count++;
}
return count;
}
/**
*
*/
CPPDeclaration::SubType CPPFunctionType::
get_subtype() const {
return ST_function;
}
/**
*
*/
CPPFunctionType *CPPFunctionType::
as_function_type() {
return this;
}
/**
* This is similar to is_equal(), except it is more forgiving: it considers
* the functions to be equivalent only if the return type and the types of all
* parameters match.
*
* Note that this isn't symmetric to account for covariant return types.
*/
bool CPPFunctionType::
match_virtual_override(const CPPFunctionType &other) const {
if (!_return_type->is_equivalent(*other._return_type) &&
!_return_type->is_convertible_to(other._return_type)) {
return false;
}
if (((_flags ^ other._flags) & ~(F_override | F_final)) != 0) {
return false;
}
if (!_parameters->is_equivalent(*other._parameters)) {
return false;
}
return true;
}
/**
* Called by CPPDeclaration() to determine whether this type is equivalent to
* another type of the same type.
*/
bool CPPFunctionType::
is_equal(const CPPDeclaration *other) const {
const CPPFunctionType *ot = ((CPPDeclaration *)other)->as_function_type();
assert(ot != nullptr);
if (_return_type != ot->_return_type) {
return false;
}
if (_flags != ot->_flags) {
return false;
}
if (_parameters == ot->_parameters) {
return true;
}
if (_parameters == nullptr || ot->_parameters == nullptr ||
*_parameters != *ot->_parameters) {
return false;
}
return true;
}
/**
* Called by CPPDeclaration() to determine whether this type should be ordered
* before another type of the same type, in an arbitrary but fixed ordering.
*/
bool CPPFunctionType::
is_less(const CPPDeclaration *other) const {
const CPPFunctionType *ot = ((CPPDeclaration *)other)->as_function_type();
assert(ot != nullptr);
if (_return_type != ot->_return_type) {
return _return_type < ot->_return_type;
}
if (_flags != ot->_flags) {
return _flags < ot->_flags;
}
if (_parameters == ot->_parameters) {
return 0;
}
if (_parameters == nullptr || ot->_parameters == nullptr) {
return _parameters < ot->_parameters;
}
return *_parameters < *ot->_parameters;
}
| /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file cppFunctionType.cxx
* @author drose
* @date 1999-10-21
*/
#include "cppFunctionType.h"
#include "cppParameterList.h"
#include "cppSimpleType.h"
#include "cppInstance.h"
using std::ostream;
using std::ostringstream;
using std::string;
/**
*
*/
CPPFunctionType::
CPPFunctionType(CPPType *return_type, CPPParameterList *parameters,
int flags) :
CPPType(CPPFile()),
_return_type(return_type),
_parameters(parameters),
_flags(flags)
{
_class_owner = nullptr;
// If the parameter list contains just the token "void", it means no
// parameters.
if (_parameters != nullptr &&
_parameters->_parameters.size() == 1 &&
_parameters->_parameters.front()->_type->as_simple_type() != nullptr &&
_parameters->_parameters.front()->_type->as_simple_type()->_type ==
CPPSimpleType::T_void &&
_parameters->_parameters.front()->_ident == nullptr) {
_parameters->_parameters.clear();
}
}
/**
*
*/
CPPFunctionType::
CPPFunctionType(const CPPFunctionType ©) :
CPPType(copy),
_return_type(copy._return_type),
_parameters(copy._parameters),
_flags(copy._flags),
_class_owner(copy._class_owner)
{
}
/**
*
*/
void CPPFunctionType::
operator = (const CPPFunctionType ©) {
CPPType::operator = (copy);
_return_type = copy._return_type;
_parameters = copy._parameters;
_flags = copy._flags;
_class_owner = copy._class_owner;
}
/**
* Returns true if the function accepts the given number of parameters.
*/
bool CPPFunctionType::
accepts_num_parameters(int num_parameters) {
assert(num_parameters >= 0);
if (_parameters == nullptr) {
return (num_parameters == 0);
}
size_t actual_num_parameters = _parameters->_parameters.size();
// If we passed too many parameters, it must have an ellipsis.
if ((size_t)num_parameters > actual_num_parameters) {
return _parameters->_includes_ellipsis;
}
// Make sure all superfluous parameters have a default value.
for (size_t i = (size_t)num_parameters; i < actual_num_parameters; ++i) {
CPPInstance *param = _parameters->_parameters[i];
if (param->_initializer == nullptr) {
return false;
}
}
return true;
}
/**
* Returns true if this declaration is an actual, factual declaration, or
* false if some part of the declaration depends on a template parameter which
* has not yet been instantiated.
*/
bool CPPFunctionType::
is_fully_specified() const {
return CPPType::is_fully_specified() &&
_return_type->is_fully_specified() &&
_parameters->is_fully_specified();
}
/**
*
*/
CPPDeclaration *CPPFunctionType::
substitute_decl(CPPDeclaration::SubstDecl &subst,
CPPScope *current_scope, CPPScope *global_scope) {
SubstDecl::const_iterator si = subst.find(this);
if (si != subst.end()) {
return (*si).second;
}
CPPFunctionType *rep = new CPPFunctionType(*this);
if (_return_type != nullptr) {
rep->_return_type =
_return_type->substitute_decl(subst, current_scope, global_scope)
->as_type();
}
if (_parameters != nullptr) {
rep->_parameters =
_parameters->substitute_decl(subst, current_scope, global_scope);
}
if (rep->_return_type == _return_type &&
rep->_parameters == _parameters) {
delete rep;
rep = this;
}
rep = CPPType::new_type(rep)->as_function_type();
subst.insert(SubstDecl::value_type(this, rep));
return rep;
}
/**
* If this CPPType object is a forward reference or other nonspecified
* reference to a type that might now be known a real type, returns the real
* type. Otherwise returns the type itself.
*/
CPPType *CPPFunctionType::
resolve_type(CPPScope *current_scope, CPPScope *global_scope) {
CPPType *rtype = _return_type->resolve_type(current_scope, global_scope);
CPPParameterList *params;
if (_parameters == nullptr) {
params = nullptr;
} else {
params = _parameters->resolve_type(current_scope, global_scope);
}
if (rtype != _return_type || params != _parameters) {
CPPFunctionType *rep = new CPPFunctionType(*this);
rep->_return_type = rtype;
rep->_parameters = params;
return CPPType::new_type(rep);
}
return this;
}
/**
* Returns true if the type, or any nested type within the type, is a
* CPPTBDType and thus isn't fully determined right now. In this case,
* calling resolve_type() may or may not resolve the type.
*/
bool CPPFunctionType::
is_tbd() const {
if (_return_type->is_tbd()) {
return true;
}
return _parameters == nullptr || _parameters->is_tbd();
}
/**
* Returns true if the type is considered a Plain Old Data (POD) type.
*/
bool CPPFunctionType::
is_trivial() const {
return false;
}
/**
*
*/
void CPPFunctionType::
output(ostream &out, int indent_level, CPPScope *scope, bool complete) const {
output(out, indent_level, scope, complete, -1);
}
/**
* The additional parameter allows us to specify the number of parameters we
* wish to show the default values for. If num_default_parameters is >= 0, it
* indicates the number of default parameter values to show on output.
* Otherwise, all parameter values are shown.
*/
void CPPFunctionType::
output(ostream &out, int indent_level, CPPScope *scope, bool complete,
int num_default_parameters) const {
if (_flags & F_trailing_return_type) {
// It was declared using trailing return type, so let's format it that
// way.
out << "auto(";
_parameters->output(out, scope, true, num_default_parameters);
out << ")";
if (_flags & F_const_method) {
out << " const";
}
if (_flags & F_noexcept) {
out << " noexcept";
}
if (_flags & F_final) {
out << " final";
}
if (_flags & F_override) {
out << " override";
}
out << " -> ";
_return_type->output(out, indent_level, scope, false);
} else {
_return_type->output(out, indent_level, scope, complete);
out << "(";
_parameters->output(out, scope, true, num_default_parameters);
out << ")";
if (_flags & F_const_method) {
out << " const";
}
if (_flags & F_noexcept) {
out << " noexcept";
}
if (_flags & F_final) {
out << " final";
}
if (_flags & F_override) {
out << " override";
}
}
}
/**
* Formats a C++-looking line that defines an instance of the given type, with
* the indicated name. In most cases this will be "type name", but some types
* have special exceptions.
*/
void CPPFunctionType::
output_instance(ostream &out, int indent_level, CPPScope *scope,
bool complete, const string &prename,
const string &name) const {
output_instance(out, indent_level, scope, complete, prename, name, -1);
}
/**
* The additional parameter allows us to specify the number of parameters we
* wish to show the default values for. If num_default_parameters is >= 0, it
* indicates the number of default parameter values to show on output.
* Otherwise, all parameter values are shown.
*/
void CPPFunctionType::
output_instance(ostream &out, int indent_level, CPPScope *scope,
bool complete, const string &prename,
const string &name, int num_default_parameters) const {
ostringstream parm_string;
parm_string << "(";
_parameters->output(parm_string, scope, true, num_default_parameters);
parm_string << ")";
string str = parm_string.str();
if (_flags & (F_constructor | F_destructor)) {
// No return type for constructors and destructors.
out << prename << name << str;
} else if (_flags & F_trailing_return_type) {
// It was declared using trailing return type, so let's format it that
// way.
out << "auto ";
if (prename.empty()) {
out << name;
} else {
out << "(" << prename << name << ")";
}
out << str;
} else if (_flags & F_operator_typecast) {
out << "operator ";
_return_type->output_instance(out, indent_level, scope, complete, "", prename + str);
} else {
if (prename.empty()) {
_return_type->output_instance(out, indent_level, scope, complete,
"", prename + name + str);
} else {
_return_type->output_instance(out, indent_level, scope, complete,
"", "(" + prename + name + ")" + str);
}
}
if (_flags & F_const_method) {
out << " const";
}
if (_flags & F_volatile_method) {
out << " volatile";
}
if (_flags & F_noexcept) {
out << " noexcept";
}
if (_flags & F_final) {
out << " final";
}
if (_flags & F_override) {
out << " override";
}
if (_flags & F_trailing_return_type) {
out << " -> ";
_return_type->output(out, indent_level, scope, false);
}
}
/**
* Returns the number of parameters in the list that may take default values.
*/
int CPPFunctionType::
get_num_default_parameters() const {
// The trick is just to count, beginning from the end and working towards
// the front, the number of parameters that have some initializer.
if (_parameters == nullptr) {
return 0;
}
const CPPParameterList::Parameters ¶ms = _parameters->_parameters;
CPPParameterList::Parameters::const_reverse_iterator pi;
int count = 0;
for (pi = params.rbegin();
pi != params.rend() && (*pi)->_initializer != nullptr;
++pi) {
count++;
}
return count;
}
/**
*
*/
CPPDeclaration::SubType CPPFunctionType::
get_subtype() const {
return ST_function;
}
/**
*
*/
CPPFunctionType *CPPFunctionType::
as_function_type() {
return this;
}
/**
* This is similar to is_equal(), except it is more forgiving: it considers
* the functions to be equivalent only if the return type and the types of all
* parameters match.
*
* Note that this isn't symmetric to account for covariant return types.
*/
bool CPPFunctionType::
match_virtual_override(const CPPFunctionType &other) const {
if (!_return_type->is_equivalent(*other._return_type) &&
!_return_type->is_convertible_to(other._return_type)) {
return false;
}
if (((_flags ^ other._flags) & ~(F_override | F_final)) != 0) {
return false;
}
if (!_parameters->is_equivalent(*other._parameters)) {
return false;
}
return true;
}
/**
* Called by CPPDeclaration() to determine whether this type is equivalent to
* another type of the same type.
*/
bool CPPFunctionType::
is_equal(const CPPDeclaration *other) const {
const CPPFunctionType *ot = ((CPPDeclaration *)other)->as_function_type();
assert(ot != nullptr);
if (_return_type != ot->_return_type) {
return false;
}
if (_flags != ot->_flags) {
return false;
}
if (_parameters == ot->_parameters) {
return true;
}
if (_parameters == nullptr || ot->_parameters == nullptr ||
*_parameters != *ot->_parameters) {
return false;
}
return true;
}
/**
* Called by CPPDeclaration() to determine whether this type should be ordered
* before another type of the same type, in an arbitrary but fixed ordering.
*/
bool CPPFunctionType::
is_less(const CPPDeclaration *other) const {
const CPPFunctionType *ot = ((CPPDeclaration *)other)->as_function_type();
assert(ot != nullptr);
if (_return_type != ot->_return_type) {
return _return_type < ot->_return_type;
}
if (_flags != ot->_flags) {
return _flags < ot->_flags;
}
if (_parameters == ot->_parameters) {
return 0;
}
if (_parameters == nullptr || ot->_parameters == nullptr) {
return _parameters < ot->_parameters;
}
return *_parameters < *ot->_parameters;
}
| fix formatting of typecast operator | cppparser: fix formatting of typecast operator
| C++ | bsd-3-clause | chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d |
aa7afe7a17e6574ecc42d9b97542763482d88806 | dev/sensor/htu21d/export/dev/sensor/htu21d.hpp | dev/sensor/htu21d/export/dev/sensor/htu21d.hpp | //!
//! \file
//! \brief Driver for HTU21D digital humidity sensor with temperature output
//! See, http://www.meas-spec.com/downloads/HTU21D.pdf
//!
#ifndef __DEV_SENSOR_HTU21D_HPP__
#define __DEV_SENSOR_HTU21D_HPP__
#include <ecl/err.hpp>
namespace ecl
{
namespace sensor
{
//! \brief Defines resolution modes for HTU21D sensor.
//! \details Possible modes are (RM here - relative humidity):
//! rm12_t14 - 12 bits for RM, 14 bits for temperature
//! rm8_t12 - 8 bits for RM, 12 bits for temperature
//! rm10_t13 - 10 bits for RM, 13 bits for temperature
//! rm11_t11 - 11 bits for RM, 11 bits for temperature
//!
enum class htu21d_resolution
{
rm12_t14,
rm8_t12,
rm10_t13,
rm11_t11
};
//! \brief HTU21D sensor driver implementation.
//! \tparam I2C generic bus driver
//!
template <class i2c_dev>
class htu21d
{
public:
htu21d() = delete;
~htu21d() = delete;
//! \brief Inits sensor and underlying I2C platform bus.
//! \retval Status of operation.
//!
static err init();
//! \brief Performs soft reset of the sensor.
//! \note The soft reset takes around 15ms.
//! User code should wait at least 15ms to finish reset procedure.
//! \retval Status of the operation.
//!
static err soft_reset();
//! \brief Reads raw temperature sample from sensor.
//! \details Sample should be processed to receive physical value.
//! \param[out] sample Variable in which raw temp. sample will be written.
//! \retval Status of the operation.
//!
static err get_sample_temperature(uint16_t &sample);
//! \brief Reads raw relative humidity sample from sensor.
//! \details Sample should be processed to receive physical value.
//! \param[out] sample Variable in which raw RM sample will be written.
//! \retval Status of the operation.
//!
static err get_sample_humidity(uint16_t &sample);
//! \brief Reads sample from sensor and converts to a physical value.
//! \param[out] temperature Temperature in (1000 * (temperature in C degree))
//! will be written in this parameter.
//! \retval Status of the operation.
//!
static err get_temperature(int &temperature);
//! \brief Reads sample from sensor and converts to a physical value.
//! \param[out] humidity Relative humidity in (1000 * (humidity in %))
//! will be written in this parameter.
//! \retval Status of the operation.
//!
static err get_humidity(int &humidity);
//! \brief Checks end of battery status (see RM for details)
//! \retval True if battery power > 2.5V, False otherwise.
//!
static bool is_battery_low();
//! \brief Checks if on-chip heater is enabled
//! \retval True if enabled, False otherwise.
//!
static bool is_heater_enabled();
//! \brief Enables on-chip heater (see RM for details)
//! \details The heater is intended to be used for functionality diagnosis:
//! relative humidity drops upon rising temperature. The heater consumes
//! about 5.5mW and provides a temperature increase of about 0.5-1.5°C
//! \retval Status of the operation.
//!
static err enable_heater();
//! \brief Disables on-chip heater (see RM for details)
//! \retval Status of the operation.
//!
static err disable_heater();
//! \brief Sets resolution mode for measuring
//! Default mode (htu21d_resolution::rm12_t14) is entered after power on
//! \param[in] mode Can be value of type htu21d_resolution
//! \retval Status of the operation.
//!
static err set_resolution_mode(htu21d_resolution mode);
//! \brief Returns current resolution mode
//! \param[out] mode The value in which result will be written.
//! Can be value of type htu21d_resolution
//! \retval Status of the operation.
//!
static err get_resolution_mode(htu21d_resolution &mode);
private:
//! Sensor I2C commands
enum
{
TRIGGER_TEMPERATURE_HM = 0xE3,
TRIGGER_HUMIDITY_HM = 0xE5,
TRIGGER_TEMPERATURE = 0xF3,
TRIGGER_HUMIDITY = 0xF5,
WRITE_USER_REG = 0xE6,
READ_USER_REG = 0xE7,
SOFT_RESET = 0xFE
};
//! Sensor I2C address. Cannot be changed.
static constexpr uint8_t i2_addr = 0x80;
//! Used to get battery power status
static constexpr uint8_t battery_low_bit = 0x40;
//! Used to control on-chip heater
static constexpr uint8_t on_chip_heater_bit = 0x4;
//! Should be user to clear resolution bits only
static constexpr uint8_t resolution_clear_mask = 0x7E;
//! Resolution modes masks
//! Used to enable rm12_t14 mode
static constexpr uint8_t rm12_t14_mask = 0x0;
//! Used to enable rm8_t12 mode
static constexpr uint8_t rm8_t12_mask = 0x1;
//! Used to enable rm10_t13 mode
static constexpr uint8_t rm10_t13_mask = 0x80;
//! Used to enable rm11_t11 mode
static constexpr uint8_t rm11_t11_mask = 0x81;
//! Reads sample from sensor in I2C hold master mode.
//! In this mode sensor holds SCL until measurements is finished
static err i2c_get_sample_hold_master(uint8_t cmd, uint16_t &sample);
//! Reads sensor user register.
//! Allows to get useful information about sensor state
//!
static err read_user_register(uint8_t &value);
//! Writes to the sensor user register.
//! Allows to configure sensor resolution.
//!
static err write_user_register(uint8_t value);
};
template <class i2c_dev>
err htu21d<i2c_dev>::init()
{
return i2c_dev::init();
}
template <class i2c_dev>
err htu21d<i2c_dev>::soft_reset()
{
i2c_dev::platform_handle::set_slave_addr(i2_addr);
uint8_t cmd = SOFT_RESET;
i2c_dev::lock();
err rc = i2c_dev::set_buffers(&cmd, nullptr, 1);
if (rc == err::ok) {
rc = i2c_dev::xfer();
}
i2c_dev::unlock();
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::read_user_register(uint8_t &value)
{
uint8_t cmd = READ_USER_REG;
i2c_dev::platform_handle::set_slave_addr(i2_addr);
i2c_dev::lock();
err rc = i2c_dev::set_buffers(&cmd, &value, 1);
if (rc == err::ok) {
i2c_dev::xfer();
}
i2c_dev::unlock();
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::write_user_register(uint8_t value)
{
uint8_t tx_buff[] = {WRITE_USER_REG, value};
i2c_dev::platform_handle::set_slave_addr(i2_addr);
i2c_dev::lock();
err rc = i2c_dev::set_buffers(tx_buff, nullptr, sizeof(tx_buff));
if (rc == err::ok) {
i2c_dev::xfer();
}
i2c_dev::unlock();
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::i2c_get_sample_hold_master(uint8_t cmd, uint16_t &sample)
{
// MSB, LSB, CRC
uint8_t data[3] = {};
i2c_dev::platform_handle::set_slave_addr(i2_addr);
// send command to start measuring
i2c_dev::lock();
err rc = i2c_dev::set_buffers(&cmd, nullptr, 1);
if (rc == err::ok) {
rc = i2c_dev::xfer();
}
i2c_dev::unlock();
if (rc != err::ok) {
return rc;
}
// read data, last byte is CRC
i2c_dev::lock();
rc = i2c_dev::set_buffers(nullptr, data, sizeof(data));
if (rc == err::ok) {
rc = i2c_dev::xfer();
}
i2c_dev::unlock();
sample = ((data[0] << 8) | data[1]);
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_sample_temperature(uint16_t &value)
{
return i2c_get_sample_hold_master(TRIGGER_TEMPERATURE_HM, value);
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_sample_humidity(uint16_t &value)
{
return i2c_get_sample_hold_master(TRIGGER_HUMIDITY_HM, value);
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_temperature(int &value)
{
uint16_t sample = 0;
err rc = get_sample_temperature(sample);
if (rc != err::ok) {
return rc;
}
// clear last 2 bits according to RM,
// since they contain status information
sample &= ~3;
value = -46850 + ((175000 * static_cast<uint64_t>(sample)) / (1 << 16));
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_humidity(int &value)
{
uint16_t sample = 0;
err rc = get_sample_humidity(sample);
if (rc != err::ok) {
return rc;
}
// clear last 2 bits according to RM,
// since they contain status information
sample &= ~3;
value = -6000 + ((125000 * static_cast<uint64_t>(sample)) / (1 << 16));
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::set_resolution_mode(htu21d_resolution mode)
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
// clear resolution bits first
user_reg &= resolution_clear_mask;
switch (mode) {
case htu21d_resolution::rm12_t14:
user_reg |= rm12_t14_mask;
break;
case htu21d_resolution::rm8_t12:
user_reg |= rm8_t12_mask;
break;
case htu21d_resolution::rm10_t13:
user_reg |= rm10_t13_mask;
break;
case htu21d_resolution::rm11_t11:
user_reg |= rm11_t11_mask;
break;
default:
//default mode
user_reg |= rm12_t14_mask;
break;
}
rc = write_user_register(user_reg);
return err::ok;
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_resolution_mode(htu21d_resolution &mode)
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
user_reg &= ~resolution_clear_mask;
switch (user_reg) {
case rm12_t14_mask:
mode = htu21d_resolution::rm12_t14;
break;
case rm8_t12_mask:
mode = htu21d_resolution::rm8_t12;
break;
case rm10_t13_mask:
mode = htu21d_resolution::rm10_t13;
break;
case rm11_t11_mask:
mode = htu21d_resolution::rm11_t11;
break;
default:
// default mode
mode = htu21d_resolution::rm12_t14;
break;
}
return rc;
}
template <class i2c_dev>
bool htu21d<i2c_dev>::is_battery_low()
{
uint8_t user_reg = 0;
read_user_register(user_reg);
return (user_reg & battery_low_bit);
}
template <class i2c_dev>
bool htu21d<i2c_dev>::is_heater_enabled()
{
uint8_t user_reg = 0;
read_user_register(user_reg);
return (user_reg & on_chip_heater_bit);
}
template <class i2c_dev>
err htu21d<i2c_dev>::enable_heater()
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
user_reg |= on_chip_heater_bit;
rc = write_user_register(user_reg);
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::disable_heater()
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
user_reg &= ~on_chip_heater_bit;
rc = write_user_register(user_reg);
return rc;
}
} // namespace sensor
} // namespace ecl
#endif //__DEV_SENSOR_HTU21D_HPP__
| //!
//! \file
//! \brief Driver for HTU21D digital humidity sensor with temperature output
//! See, http://www.meas-spec.com/downloads/HTU21D.pdf
//!
#ifndef __DEV_SENSOR_HTU21D_HPP__
#define __DEV_SENSOR_HTU21D_HPP__
#include <ecl/err.hpp>
namespace ecl
{
namespace sensor
{
//! \brief Defines resolution modes for HTU21D sensor.
//! \details Possible modes are (RM here - relative humidity):
//! rm12_t14 - 12 bits for RM, 14 bits for temperature
//! rm8_t12 - 8 bits for RM, 12 bits for temperature
//! rm10_t13 - 10 bits for RM, 13 bits for temperature
//! rm11_t11 - 11 bits for RM, 11 bits for temperature
//!
enum class htu21d_resolution
{
rm12_t14,
rm8_t12,
rm10_t13,
rm11_t11
};
//! \brief HTU21D sensor driver implementation.
//! \tparam I2C generic bus driver
//!
template <class i2c_dev>
class htu21d
{
public:
htu21d() = delete;
~htu21d() = delete;
//! \brief Inits sensor and underlying I2C platform bus.
//! \retval Status of operation.
//!
static err init();
//! \brief Performs soft reset of the sensor.
//! \note The soft reset takes around 15ms.
//! User code should wait at least 15ms to finish reset procedure.
//! \retval Status of the operation.
//!
static err soft_reset();
//! \brief Reads raw temperature sample from sensor.
//! \details Sample should be processed to receive physical value.
//! \param[out] sample Variable in which raw temp. sample will be written.
//! \retval Status of the operation.
//!
static err get_sample_temperature(uint16_t &sample);
//! \brief Reads raw relative humidity sample from sensor.
//! \details Sample should be processed to receive physical value.
//! \param[out] sample Variable in which raw RM sample will be written.
//! \retval Status of the operation.
//!
static err get_sample_humidity(uint16_t &sample);
//! \brief Reads sample from sensor and converts to a physical value.
//! \param[out] temperature Temperature in (1000 * (temperature in C degree))
//! will be written in this parameter.
//! \retval Status of the operation.
//!
static err get_temperature(int &temperature);
//! \brief Reads sample from sensor and converts to a physical value.
//! \param[out] humidity Relative humidity in (1000 * (humidity in %))
//! will be written in this parameter.
//! \retval Status of the operation.
//!
static err get_humidity(int &humidity);
//! \brief Checks end of battery status (see RM for details)
//! \retval True if battery power > 2.5V, False otherwise.
//!
static bool is_battery_low();
//! \brief Checks if on-chip heater is enabled
//! \retval True if enabled, False otherwise.
//!
static bool is_heater_enabled();
//! \brief Enables on-chip heater (see RM for details)
//! \details The heater is intended to be used for functionality diagnosis:
//! relative humidity drops upon rising temperature. The heater consumes
//! about 5.5mW and provides a temperature increase of about 0.5-1.5°C
//! \retval Status of the operation.
//!
static err enable_heater();
//! \brief Disables on-chip heater (see RM for details)
//! \retval Status of the operation.
//!
static err disable_heater();
//! \brief Sets resolution mode for measuring
//! Default mode (htu21d_resolution::rm12_t14) is entered after power on
//! \param[in] mode Can be value of type htu21d_resolution
//! \retval Status of the operation.
//!
static err set_resolution_mode(htu21d_resolution mode);
//! \brief Returns current resolution mode
//! \param[out] mode The value in which result will be written.
//! Can be value of type htu21d_resolution
//! \retval Status of the operation.
//!
static err get_resolution_mode(htu21d_resolution &mode);
private:
//! Sensor I2C commands
enum
{
TRIGGER_TEMPERATURE_HM = 0xE3,
TRIGGER_HUMIDITY_HM = 0xE5,
TRIGGER_TEMPERATURE = 0xF3,
TRIGGER_HUMIDITY = 0xF5,
WRITE_USER_REG = 0xE6,
READ_USER_REG = 0xE7,
SOFT_RESET = 0xFE
};
//! Sensor I2C address. Cannot be changed.
static constexpr uint8_t i2_addr = 0x80;
//! Used to get battery power status
static constexpr uint8_t battery_low_bit = 0x40;
//! Used to control on-chip heater
static constexpr uint8_t on_chip_heater_bit = 0x4;
//! Should be user to clear resolution bits only
static constexpr uint8_t resolution_clear_mask = 0x7E;
//! Resolution modes masks
//! Used to enable rm12_t14 mode
static constexpr uint8_t rm12_t14_mask = 0x0;
//! Used to enable rm8_t12 mode
static constexpr uint8_t rm8_t12_mask = 0x1;
//! Used to enable rm10_t13 mode
static constexpr uint8_t rm10_t13_mask = 0x80;
//! Used to enable rm11_t11 mode
static constexpr uint8_t rm11_t11_mask = 0x81;
//! Reads sample from sensor in I2C hold master mode.
//! In this mode sensor holds SCL until measurements is finished
static err i2c_get_sample_hold_master(uint8_t cmd, uint16_t &sample);
//! Reads sensor user register.
//! Allows to get useful information about sensor state
//!
static err read_user_register(uint8_t &value);
//! Writes to the sensor user register.
//! Allows to configure sensor resolution.
//!
static err write_user_register(uint8_t value);
};
template <class i2c_dev>
err htu21d<i2c_dev>::init()
{
return i2c_dev::init();
}
template <class i2c_dev>
err htu21d<i2c_dev>::soft_reset()
{
i2c_dev::platform_handle::set_slave_addr(i2_addr);
uint8_t cmd = SOFT_RESET;
i2c_dev::lock();
err rc = i2c_dev::set_buffers(&cmd, nullptr, 1);
if (rc == err::ok) {
rc = i2c_dev::xfer();
}
i2c_dev::unlock();
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::read_user_register(uint8_t &value)
{
uint8_t cmd = READ_USER_REG;
i2c_dev::platform_handle::set_slave_addr(i2_addr);
i2c_dev::lock();
err rc = i2c_dev::set_buffers(&cmd, &value, 1);
if (rc == err::ok) {
i2c_dev::xfer();
}
i2c_dev::unlock();
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::write_user_register(uint8_t value)
{
uint8_t tx_buff[] = {WRITE_USER_REG, value};
i2c_dev::platform_handle::set_slave_addr(i2_addr);
i2c_dev::lock();
err rc = i2c_dev::set_buffers(tx_buff, nullptr, sizeof(tx_buff));
if (rc == err::ok) {
i2c_dev::xfer();
}
i2c_dev::unlock();
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::i2c_get_sample_hold_master(uint8_t cmd, uint16_t &sample)
{
// MSB, LSB, CRC
uint8_t data[3] = {};
i2c_dev::platform_handle::set_slave_addr(i2_addr);
// send command to start measuring
i2c_dev::lock();
err rc = i2c_dev::set_buffers(&cmd, nullptr, 1);
if (rc == err::ok) {
rc = i2c_dev::xfer();
}
i2c_dev::unlock();
if (rc != err::ok) {
return rc;
}
// read data, last byte is CRC
i2c_dev::lock();
rc = i2c_dev::set_buffers(nullptr, data, sizeof(data));
if (rc == err::ok) {
rc = i2c_dev::xfer();
}
i2c_dev::unlock();
sample = ((data[0] << 8) | data[1]);
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_sample_temperature(uint16_t &value)
{
return i2c_get_sample_hold_master(TRIGGER_TEMPERATURE_HM, value);
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_sample_humidity(uint16_t &value)
{
return i2c_get_sample_hold_master(TRIGGER_HUMIDITY_HM, value);
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_temperature(int &value)
{
uint16_t sample = 0;
err rc = get_sample_temperature(sample);
if (rc != err::ok) {
return rc;
}
// clear last 2 bits according to RM,
// since they contain status information
sample &= ~3;
value = -46850 + ((175720 * static_cast<uint64_t>(sample)) / (1 << 16));
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_humidity(int &value)
{
uint16_t sample = 0;
err rc = get_sample_humidity(sample);
if (rc != err::ok) {
return rc;
}
// clear last 2 bits according to RM,
// since they contain status information
sample &= ~3;
value = -6000 + ((125000 * static_cast<uint64_t>(sample)) / (1 << 16));
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::set_resolution_mode(htu21d_resolution mode)
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
// clear resolution bits first
user_reg &= resolution_clear_mask;
switch (mode) {
case htu21d_resolution::rm12_t14:
user_reg |= rm12_t14_mask;
break;
case htu21d_resolution::rm8_t12:
user_reg |= rm8_t12_mask;
break;
case htu21d_resolution::rm10_t13:
user_reg |= rm10_t13_mask;
break;
case htu21d_resolution::rm11_t11:
user_reg |= rm11_t11_mask;
break;
default:
//default mode
user_reg |= rm12_t14_mask;
break;
}
rc = write_user_register(user_reg);
return err::ok;
}
template <class i2c_dev>
err htu21d<i2c_dev>::get_resolution_mode(htu21d_resolution &mode)
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
user_reg &= ~resolution_clear_mask;
switch (user_reg) {
case rm12_t14_mask:
mode = htu21d_resolution::rm12_t14;
break;
case rm8_t12_mask:
mode = htu21d_resolution::rm8_t12;
break;
case rm10_t13_mask:
mode = htu21d_resolution::rm10_t13;
break;
case rm11_t11_mask:
mode = htu21d_resolution::rm11_t11;
break;
default:
// default mode
mode = htu21d_resolution::rm12_t14;
break;
}
return rc;
}
template <class i2c_dev>
bool htu21d<i2c_dev>::is_battery_low()
{
uint8_t user_reg = 0;
read_user_register(user_reg);
return (user_reg & battery_low_bit);
}
template <class i2c_dev>
bool htu21d<i2c_dev>::is_heater_enabled()
{
uint8_t user_reg = 0;
read_user_register(user_reg);
return (user_reg & on_chip_heater_bit);
}
template <class i2c_dev>
err htu21d<i2c_dev>::enable_heater()
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
user_reg |= on_chip_heater_bit;
rc = write_user_register(user_reg);
return rc;
}
template <class i2c_dev>
err htu21d<i2c_dev>::disable_heater()
{
uint8_t user_reg = 0;
err rc = read_user_register(user_reg);
if (rc != err::ok) {
return rc;
}
user_reg &= ~on_chip_heater_bit;
rc = write_user_register(user_reg);
return rc;
}
} // namespace sensor
} // namespace ecl
#endif //__DEV_SENSOR_HTU21D_HPP__
| Fix temperature conversion formula | HTU21D: Fix temperature conversion formula | C++ | mpl-2.0 | forGGe/theCore,RostakaGmfun/theCore,RostakaGmfun/theCore,RostakaGmfun/theCore,forGGe/theCore,RostakaGmfun/theCore,forGGe/theCore,forGGe/theCore |
3a58fa5c99268594b5e8d6e4f4d216d4dfed3552 | Framework/Source/ThirdPersonCamera.cpp | Framework/Source/ThirdPersonCamera.cpp | //
// COMP 371 Assignment Framework
//
// Created by Nicolas Bergeron on 8/7/14.
//
// Copyright (c) 2014 Concordia University. All rights reserved.
//
#pragma once
#include "ThirdPersonCamera.h"
#include "EventManager.h"
#include <GLM/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <GLFW/glfw3.h>
#include <algorithm>
using namespace glm;
float ThirdPersonCamera::fieldOfView = 45.0f;
glm::mat4 ThirdPersonCamera::GetProjectionMatrix() const {
return perspective(ThirdPersonCamera::fieldOfView, 4.0f / 3.0f, 0.1f, 100.0f);
}
ThirdPersonCamera::ThirdPersonCamera(glm::vec3 position, Model* m, float radius): Camera(), mPosition(position), mTargetModel(m), mLookAt(0.0f, 0.0f, -1.0f), mHorizontalAngle(90.0f), mVerticalAngle(0.0f), mSpeed(5.0f), mAngularSpeed(2.5f), mRadius(radius)
{
}
ThirdPersonCamera::~ThirdPersonCamera()
{
}
void ThirdPersonCamera::SetTargetModel(Model* m){
mTargetModel = m;
}
void ThirdPersonCamera::SetRadius(float r){
mRadius = r;
}
void ThirdPersonCamera::Update(float dt)
{
// Prevent from having the camera move only when the cursor is within the windows
EventManager::DisableMouseCursor();
// The Camera moves based on the User inputs
// - You can access the mouse motion with EventManager::GetMouseMotionXY()
// - For mapping A S D W, you can look in World.cpp for an example of accessing key states
// - Don't forget to use dt to control the speed of the camera motion
// Mouse motion to get the variation in angle
mHorizontalAngle -= EventManager::GetMouseMotionX() * mAngularSpeed * dt;
mVerticalAngle -= EventManager::GetMouseMotionY() * mAngularSpeed * dt;
// Clamp vertical angle to [-85, 85] degrees
mVerticalAngle = std::max(-85.0f, std::min(85.0f, mVerticalAngle));
if (mHorizontalAngle > 360)
{
mHorizontalAngle -= 360;
}
else if (mHorizontalAngle < -360)
{
mHorizontalAngle += 360;
}
float theta = radians(mHorizontalAngle);
float phi = radians(mVerticalAngle);
mLookAt = vec3(cosf(phi)*cosf(theta), sinf(phi), -cosf(phi)*sinf(theta));
vec3 sideVector = glm::cross(mLookAt, vec3(0.0f, 1.0f, 0.0f));
glm::normalize(sideVector);
// A S D W for motion along the camera basis vectors
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_SPACE) == GLFW_PRESS)
{
mPosition += glm::vec3(0.0,1.0,0.0) * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
{
mPosition -= glm::vec3(0.0, 1.0, 0.0) * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_W ) == GLFW_PRESS)
{
mPosition += mLookAt * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_S ) == GLFW_PRESS)
{
mPosition -= mLookAt * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_D ) == GLFW_PRESS)
{
mPosition += sideVector * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_A ) == GLFW_PRESS)
{
mPosition -= sideVector * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
{
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS)
{
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS)
{
}
glfwSetScrollCallback(EventManager::GetWindow(), scrollCallBack);
//Simon addition
//model positioning in front of our third person camera
mTargetModel->SetPosition(mPosition + mLookAt * mRadius);
}
glm::mat4 ThirdPersonCamera::GetViewMatrix() const
{
return glm::lookAt( mPosition, mPosition + mLookAt, vec3(0.0f, 1.0f, 0.0f) );
}
void ThirdPersonCamera::scrollCallBack(GLFWwindow* window, double xOffset, double yOffset) {
//http://www.opengl-tutorial.org/beginners-tutorials/tutorial-6-keyboard-and-mouse/
ThirdPersonCamera::fieldOfView += 5 * (float)yOffset;
} | //
// COMP 371 Assignment Framework
//
// Created by Nicolas Bergeron on 8/7/14.
//
// Copyright (c) 2014 Concordia University. All rights reserved.
//
#pragma once
#include "ThirdPersonCamera.h"
#include "EventManager.h"
#include <GLM/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <GLFW/glfw3.h>
#include <algorithm>
using namespace glm;
float ThirdPersonCamera::fieldOfView = 45.0f;
ThirdPersonCamera::ThirdPersonCamera(glm::vec3 position, Model* m, float radius): Camera(), mPosition(position), mTargetModel(m), mLookAt(0.0f, 0.0f, -1.0f), mHorizontalAngle(90.0f), mVerticalAngle(0.0f), mSpeed(5.0f), mAngularSpeed(2.5f), mRadius(radius)
{
}
ThirdPersonCamera::~ThirdPersonCamera()
{
}
void ThirdPersonCamera::SetTargetModel(Model* m){
mTargetModel = m;
}
void ThirdPersonCamera::SetRadius(float r){
mRadius = r;
}
void ThirdPersonCamera::Update(float dt)
{
// Prevent from having the camera move only when the cursor is within the windows
EventManager::DisableMouseCursor();
// The Camera moves based on the User inputs
// - You can access the mouse motion with EventManager::GetMouseMotionXY()
// - For mapping A S D W, you can look in World.cpp for an example of accessing key states
// - Don't forget to use dt to control the speed of the camera motion
// Mouse motion to get the variation in angle
mHorizontalAngle -= EventManager::GetMouseMotionX() * mAngularSpeed * dt;
mVerticalAngle -= EventManager::GetMouseMotionY() * mAngularSpeed * dt;
// Clamp vertical angle to [-85, 85] degrees
mVerticalAngle = std::max(-85.0f, std::min(85.0f, mVerticalAngle));
if (mHorizontalAngle > 360)
{
mHorizontalAngle -= 360;
}
else if (mHorizontalAngle < -360)
{
mHorizontalAngle += 360;
}
float theta = radians(mHorizontalAngle);
float phi = radians(mVerticalAngle);
mLookAt = vec3(cosf(phi)*cosf(theta), sinf(phi), -cosf(phi)*sinf(theta));
vec3 sideVector = glm::cross(mLookAt, vec3(0.0f, 1.0f, 0.0f));
glm::normalize(sideVector);
// A S D W for motion along the camera basis vectors
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_SPACE) == GLFW_PRESS)
{
mPosition += glm::vec3(0.0,1.0,0.0) * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
{
mPosition -= glm::vec3(0.0, 1.0, 0.0) * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_W ) == GLFW_PRESS)
{
mPosition += mLookAt * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_S ) == GLFW_PRESS)
{
mPosition -= mLookAt * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_D ) == GLFW_PRESS)
{
mPosition += sideVector * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_A ) == GLFW_PRESS)
{
mPosition -= sideVector * dt * mSpeed;
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
{
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS)
{
}
if (glfwGetKey(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS)
{
ThirdPersonCamera::fieldOfView = 45.0f;
}
// zooming functionality using mouse or trackpad scrolling
glfwSetScrollCallback(EventManager::GetWindow(), scrollCallBack);
//Simon addition
//model positioning in front of our third person camera
mTargetModel->SetPosition(mPosition + mLookAt * mRadius);
}
glm::mat4 ThirdPersonCamera::GetViewMatrix() const
{
return glm::lookAt( mPosition, mPosition + mLookAt, vec3(0.0f, 1.0f, 0.0f) );
}
glm::mat4 ThirdPersonCamera::GetProjectionMatrix() const {
return perspective(ThirdPersonCamera::fieldOfView, 4.0f / 3.0f, 0.1f, 100.0f);
}
/**
* Zooming functionality call back function confining field of view within upper and lower boundaries
* Must remain between [0, 180] degrees, otherwise the image flips
*/
void ThirdPersonCamera::scrollCallBack(GLFWwindow* window, double xOffset, double yOffset) {
float multiplier = 5.0f; //arbitrary
float zoom = (float)yOffset * multiplier;
float lowerBound = 15.0f;
float upperBound = 155.0f;
if(ThirdPersonCamera::fieldOfView + zoom <= lowerBound) {
ThirdPersonCamera::fieldOfView = lowerBound;
} else if(ThirdPersonCamera::fieldOfView + zoom >= upperBound) {
ThirdPersonCamera::fieldOfView = upperBound;
} else {
ThirdPersonCamera::fieldOfView += zoom;
}
} | Optimize zoom to incorporate upper and lower bounds | [Screen/View2] Optimize zoom to incorporate upper and lower bounds
| C++ | apache-2.0 | AjayAujla/Space-Shooter-5000,AjayAujla/Space-Shooter-5000,AjayAujla/Space-Shooter-5000,AjayAujla/Space-Shooter-5000,AjayAujla/Space-Shooter-5000,AjayAujla/Space-Shooter-5000,AjayAujla/Space-Shooter-5000,AjayAujla/Space-Shooter-5000 |
fe034a8d4b0685cc29e3cb4290da1e304b9eb347 | liboh/plugins/js/JSObjects/JSInvokableObject.cpp | liboh/plugins/js/JSObjects/JSInvokableObject.cpp | #include "JSInvokableObject.hpp"
#include "../JSObjectScript.hpp"
#include "JSFields.hpp"
#include "JSFunctionInvokable.hpp"
#include <cassert>
#include <vector>
namespace Sirikata
{
namespace JS
{
namespace JSInvokableObject
{
v8::Handle<v8::Value> invoke(const v8::Arguments& args)
{
/* Decode the args array and send the call to the internal object */
JSObjectScript* caller;
JSInvokableObjectInt* invokableObj;
assert(decodeJSInvokableObject(args.This(), caller, invokableObj));
assert(invokableObj);
/*
create a vector of boost::any params here
For now just take the first param and see that
FIXME
*/
std::vector<boost::any> params;
HandleScope scope;
//assert(args.Length() == 1);
for(int i =0; i < args.Length(); i++)
{
/* Pushing only string params for now */
if(args[i]->IsString())
{
v8::String::AsciiValue str(args[i]);
string s = string(*str);
params.push_back(boost::any(s));
}
else if(args[i]->IsFunction())
{
v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(args[i]);
v8::Persistent<v8::Function> function_persist = v8::Persistent<v8::Function>::New(function);
JSFunctionInvokable* invokable = new JSFunctionInvokable(function_persist, caller);
Invokable* in = invokable;
params.push_back( boost::any(in));
}
}
/* This is just a trampoline pattern */
boost::any b = invokableObj->invoke(params);
if(b.empty())
{
return v8::Undefined();
}
Invokable* newInvokableObj = boost::any_cast<Invokable*>(b);
//Invokable* newInvokableObj = (boost::unsafe_any_cast<Invokable>(&b) ); //boost::any_cast<*>( invokableObj->invoke(params) );
Local<Object> tmpObj = caller->manager()->mInvokableObjectTemplate->NewInstance();
Persistent<Object>tmpObjP = Persistent<Object>::New(tmpObj);
tmpObjP->SetInternalField(JSINVOKABLE_OBJECT_JSOBJSCRIPT_FIELD,External::New(caller));
tmpObjP->SetInternalField(JSINVOKABLE_OBJECT_SIMULATION_FIELD,External::New( new JSInvokableObjectInt(newInvokableObj) ));
tmpObjP->SetInternalField(TYPEID_FIELD,External::New( new String (JSINVOKABLE_TYPEID_STRING)));
return tmpObj;
}
boost::any JSInvokableObjectInt::invoke(std::vector<boost::any> ¶ms)
{
/* Invoke the invokable version */
SILOG(js,detailed,"JSInvokableObjectInt::invoke(): invokable_ type is " << typeid(invokable_).name());
return invokable_->invoke(params);
}
bool decodeJSInvokableObject(v8::Handle<v8::Value> senderVal, JSObjectScript*& jsObjScript, JSInvokableObjectInt*& simObj)
{
if ((!senderVal->IsObject()) || (senderVal->IsUndefined()))
{
jsObjScript = NULL;
simObj = NULL;
return false;
}
v8::Handle<v8::Object>sender = v8::Handle<v8::Object>::Cast(senderVal);
if (sender->InternalFieldCount() != JSINVOKABLE_OBJECT_TEMPLATE_FIELD_COUNT)
{
return false;
}
v8::Local<v8::External> wrapJSObj;
wrapJSObj = v8::Local<v8::External>::Cast(sender->GetInternalField(JSINVOKABLE_OBJECT_JSOBJSCRIPT_FIELD));
void* ptr = wrapJSObj->Value();
jsObjScript = static_cast<JSObjectScript*>(ptr);
if (jsObjScript == NULL)
{
simObj = NULL;
return false;
}
v8::Local<v8::External> wrapSimObjRef;
wrapSimObjRef = v8::Local<v8::External>::Cast(sender->GetInternalField(JSINVOKABLE_OBJECT_SIMULATION_FIELD));
void* ptr2 = wrapSimObjRef->Value();
simObj = static_cast<JSInvokableObject::JSInvokableObjectInt*>(ptr2);
if(!simObj)
{
jsObjScript = NULL;
return false;
}
return true;
}
}
}
}
| #include "JSInvokableObject.hpp"
#include "../JSObjectScript.hpp"
#include "JSFields.hpp"
#include "JSFunctionInvokable.hpp"
#include <cassert>
#include <vector>
namespace Sirikata
{
namespace JS
{
namespace JSInvokableObject
{
v8::Handle<v8::Value> invoke(const v8::Arguments& args)
{
/* Decode the args array and send the call to the internal object */
JSObjectScript* caller;
JSInvokableObjectInt* invokableObj;
bool decoded = decodeJSInvokableObject(args.This(), caller, invokableObj);
assert(decoded);
assert(invokableObj);
/*
create a vector of boost::any params here
For now just take the first param and see that
FIXME
*/
std::vector<boost::any> params;
HandleScope scope;
//assert(args.Length() == 1);
for(int i =0; i < args.Length(); i++)
{
/* Pushing only string params for now */
if(args[i]->IsString())
{
v8::String::AsciiValue str(args[i]);
string s = string(*str);
params.push_back(boost::any(s));
}
else if(args[i]->IsFunction())
{
v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(args[i]);
v8::Persistent<v8::Function> function_persist = v8::Persistent<v8::Function>::New(function);
JSFunctionInvokable* invokable = new JSFunctionInvokable(function_persist, caller);
Invokable* in = invokable;
params.push_back( boost::any(in));
}
}
/* This is just a trampoline pattern */
boost::any b = invokableObj->invoke(params);
if(b.empty())
{
return v8::Undefined();
}
Invokable* newInvokableObj = boost::any_cast<Invokable*>(b);
//Invokable* newInvokableObj = (boost::unsafe_any_cast<Invokable>(&b) ); //boost::any_cast<*>( invokableObj->invoke(params) );
Local<Object> tmpObj = caller->manager()->mInvokableObjectTemplate->NewInstance();
Persistent<Object>tmpObjP = Persistent<Object>::New(tmpObj);
tmpObjP->SetInternalField(JSINVOKABLE_OBJECT_JSOBJSCRIPT_FIELD,External::New(caller));
tmpObjP->SetInternalField(JSINVOKABLE_OBJECT_SIMULATION_FIELD,External::New( new JSInvokableObjectInt(newInvokableObj) ));
tmpObjP->SetInternalField(TYPEID_FIELD,External::New( new String (JSINVOKABLE_TYPEID_STRING)));
return tmpObj;
}
boost::any JSInvokableObjectInt::invoke(std::vector<boost::any> ¶ms)
{
/* Invoke the invokable version */
SILOG(js,detailed,"JSInvokableObjectInt::invoke(): invokable_ type is " << typeid(invokable_).name());
return invokable_->invoke(params);
}
bool decodeJSInvokableObject(v8::Handle<v8::Value> senderVal, JSObjectScript*& jsObjScript, JSInvokableObjectInt*& simObj)
{
if ((!senderVal->IsObject()) || (senderVal->IsUndefined()))
{
jsObjScript = NULL;
simObj = NULL;
return false;
}
v8::Handle<v8::Object>sender = v8::Handle<v8::Object>::Cast(senderVal);
if (sender->InternalFieldCount() != JSINVOKABLE_OBJECT_TEMPLATE_FIELD_COUNT)
{
return false;
}
v8::Local<v8::External> wrapJSObj;
wrapJSObj = v8::Local<v8::External>::Cast(sender->GetInternalField(JSINVOKABLE_OBJECT_JSOBJSCRIPT_FIELD));
void* ptr = wrapJSObj->Value();
jsObjScript = static_cast<JSObjectScript*>(ptr);
if (jsObjScript == NULL)
{
simObj = NULL;
return false;
}
v8::Local<v8::External> wrapSimObjRef;
wrapSimObjRef = v8::Local<v8::External>::Cast(sender->GetInternalField(JSINVOKABLE_OBJECT_SIMULATION_FIELD));
void* ptr2 = wrapSimObjRef->Value();
simObj = static_cast<JSInvokableObject::JSInvokableObjectInt*>(ptr2);
if(!simObj)
{
jsObjScript = NULL;
return false;
}
return true;
}
}
}
}
| Move call to decodeJSInvokableObject out of assert statement so it will work in Release mode. | Move call to decodeJSInvokableObject out of assert statement so it will work in Release mode.
| C++ | bsd-3-clause | sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata,sirikata/sirikata |
538d214570edeba29763678cdf9fc9415da8b6ce | example/generate_image.cpp | example/generate_image.cpp | /*
* Copyright 2016 Nu-book Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BarcodeFormat.h"
#include "MultiFormatWriter.h"
#include "BitMatrix.h"
#include "ByteMatrix.h"
#include "TextUtfEncoding.h"
#include "ZXStrConvWorkaround.h"
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
using namespace ZXing;
static void PrintUsage(const char* exePath)
{
std::cout << "Usage: " << exePath << " [-size <width>x<height>] [-margin <margin>] [-encoding <encoding>] [-ecc <level>] <format> <text> <output>" << std::endl
<< " -size Size of generated image" << std::endl
<< " -margin Margin around barcode" << std::endl
<< " -encoding Encoding used to encode input text" << std::endl
<< " -ecc Error correction level, [0-8]"
<< std::endl
<< "Supported formats are:" << std::endl
<< " AZTEC" << std::endl
<< " CODABAR" << std::endl
<< " CODE_39" << std::endl
<< " CODE_93" << std::endl
<< " CODE_128" << std::endl
<< " DATA_MATRIX" << std::endl
<< " EAN_8" << std::endl
<< " EAN_13" << std::endl
<< " ITF" << std::endl
<< " PDF_417" << std::endl
<< " QR_CODE" << std::endl
<< " UPC_A" << std::endl
<< " UPC_E" << std::endl
<< "Formats can be lowercase letters, with or without underscore." << std::endl;
}
static std::string FormatClean(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); });
str.erase(std::remove(str.begin(), str.end(), '_'), str.end());
return str;
}
static std::string ParseFormat(std::string str)
{
str = FormatClean(str);
for (int i = 0; i < (int)BarcodeFormat::FORMAT_COUNT; ++i) {
auto standardForm = ToString((BarcodeFormat)i);
if (str == FormatClean(standardForm))
return standardForm;
}
return std::string();
}
static bool ParseSize(std::string str, int* width, int* height)
{
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); });
auto xPos = str.find('x');
if (xPos != std::string::npos) {
*width = std::stoi(str.substr(0, xPos));
*height = std::stoi(str.substr(xPos + 1));
return true;
}
return false;
}
static bool ParseOptions(int argc, char* argv[], int* width, int* height, int* margin, int* eccLevel, std::string* format, std::string* text, std::string* filePath)
{
int nonOptArgCount = 0;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-size") == 0) {
if (i + 1 < argc) {
++i;
if (!ParseSize(argv[i], width, height)) {
std::cerr << "Invalid size specification: " << argv[i] << std::endl;
return false;
}
}
else {
return false;
}
}
else if (strcmp(argv[i], "-margin") == 0) {
if (i + 1 < argc) {
++i;
*margin = std::stoi(argv[i]);
}
else {
return false;
}
}
else if (strcmp(argv[i], "-ecc") == 0) {
if (i + 1 < argc) {
++i;
*eccLevel = std::stoi(argv[i]);
}
else {
return false;
}
}
else if (nonOptArgCount == 0) {
*format = ParseFormat(argv[i]);
if (format->empty()) {
std::cerr << "Unreconigned format: " << argv[i] << std::endl;
return false;
}
++nonOptArgCount;
}
else if (nonOptArgCount == 1) {
*text = argv[i];
++nonOptArgCount;
}
else if (nonOptArgCount == 2) {
*filePath = argv[i];
++nonOptArgCount;
}
else {
return false;
}
}
return !format->empty() && !text->empty() && !filePath->empty();
}
static std::string GetExtension(const std::string& path)
{
auto fileNameStart = path.find_last_of("/\\");
auto fileName = fileNameStart == std::string::npos ? path : path.substr(fileNameStart + 1);
auto extStart = fileName.find_last_of('.');
auto ext = extStart == std::string::npos ? "" : fileName.substr(extStart + 1);
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); });
return ext;
}
int main(int argc, char* argv[])
{
if (argc <= 2) {
PrintUsage(argv[0]);
return 0;
}
int width = 100, height = 100;
int margin = 10;
int eccLevel = -1;
std::string format, text, filePath;
if (!ParseOptions(argc, argv, &width, &height, &margin, &eccLevel, &format, &text, &filePath)) {
PrintUsage(argv[0]);
return -1;
}
try {
auto barcodeFormat = BarcodeFormatFromString(format);
if (barcodeFormat == BarcodeFormat::FORMAT_COUNT)
throw std::invalid_argument("Unsupported format: " + format);
MultiFormatWriter writer(barcodeFormat);
if (margin >= 0)
writer.setMargin(margin);
if (eccLevel >= 0)
writer.setEccLevel(eccLevel);
auto bitmap = writer.encode(TextUtfEncoding::FromUtf8(text), width, height).toByteMatrix();
auto ext = GetExtension(filePath);
int success = 0;
if (ext == "" || ext == "png") {
success = stbi_write_png(filePath.c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0);
}
else if (ext == "jpg" || ext == "jpeg") {
success = stbi_write_jpg(filePath.c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0);
}
if (!success) {
std::cerr << "Failed to write image: " << filePath << std::endl;
return -1;
}
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
}
return 0;
}
| /*
* Copyright 2016 Nu-book Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BarcodeFormat.h"
#include "MultiFormatWriter.h"
#include "BitMatrix.h"
#include "ByteMatrix.h"
#include "TextUtfEncoding.h"
#include "ZXStrConvWorkaround.h"
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
using namespace ZXing;
static void PrintUsage(const char* exePath)
{
std::cout << "Usage: " << exePath << " [-size <width>x<height>] [-margin <margin>] [-encoding <encoding>] [-ecc <level>] <format> <text> <output>\n"
<< " -size Size of generated image\n"
<< " -margin Margin around barcode\n"
<< " -encoding Encoding used to encode input text\n"
<< " -ecc Error correction level, [0-8]\n"
<< "\n"
<< "Supported formats are:\n"
<< " AZTEC\n"
<< " CODABAR\n"
<< " CODE_39\n"
<< " CODE_93\n"
<< " CODE_128\n"
<< " DATA_MATRIX\n"
<< " EAN_8\n"
<< " EAN_13\n"
<< " ITF\n"
<< " PDF_417\n"
<< " QR_CODE\n"
<< " UPC_A\n"
<< " UPC_E\n"
<< "Formats can be lowercase letters, with or without underscore.\n";
}
static std::string FormatClean(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); });
str.erase(std::remove(str.begin(), str.end(), '_'), str.end());
return str;
}
static std::string ParseFormat(std::string str)
{
str = FormatClean(str);
for (int i = 0; i < (int)BarcodeFormat::FORMAT_COUNT; ++i) {
auto standardForm = ToString((BarcodeFormat)i);
if (str == FormatClean(standardForm))
return standardForm;
}
return std::string();
}
static bool ParseSize(std::string str, int* width, int* height)
{
std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); });
auto xPos = str.find('x');
if (xPos != std::string::npos) {
*width = std::stoi(str.substr(0, xPos));
*height = std::stoi(str.substr(xPos + 1));
return true;
}
return false;
}
static bool ParseOptions(int argc, char* argv[], int* width, int* height, int* margin, int* eccLevel, std::string* format, std::string* text, std::string* filePath)
{
int nonOptArgCount = 0;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-size") == 0) {
if (i + 1 < argc) {
++i;
if (!ParseSize(argv[i], width, height)) {
std::cerr << "Invalid size specification: " << argv[i] << std::endl;
return false;
}
}
else {
return false;
}
}
else if (strcmp(argv[i], "-margin") == 0) {
if (i + 1 < argc) {
++i;
*margin = std::stoi(argv[i]);
}
else {
return false;
}
}
else if (strcmp(argv[i], "-ecc") == 0) {
if (i + 1 < argc) {
++i;
*eccLevel = std::stoi(argv[i]);
}
else {
return false;
}
}
else if (nonOptArgCount == 0) {
*format = ParseFormat(argv[i]);
if (format->empty()) {
std::cerr << "Unreconigned format: " << argv[i] << std::endl;
return false;
}
++nonOptArgCount;
}
else if (nonOptArgCount == 1) {
*text = argv[i];
++nonOptArgCount;
}
else if (nonOptArgCount == 2) {
*filePath = argv[i];
++nonOptArgCount;
}
else {
return false;
}
}
return !format->empty() && !text->empty() && !filePath->empty();
}
static std::string GetExtension(const std::string& path)
{
auto fileNameStart = path.find_last_of("/\\");
auto fileName = fileNameStart == std::string::npos ? path : path.substr(fileNameStart + 1);
auto extStart = fileName.find_last_of('.');
auto ext = extStart == std::string::npos ? "" : fileName.substr(extStart + 1);
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); });
return ext;
}
int main(int argc, char* argv[])
{
if (argc <= 2) {
PrintUsage(argv[0]);
return 0;
}
int width = 100, height = 100;
int margin = 10;
int eccLevel = -1;
std::string format, text, filePath;
if (!ParseOptions(argc, argv, &width, &height, &margin, &eccLevel, &format, &text, &filePath)) {
PrintUsage(argv[0]);
return -1;
}
try {
auto barcodeFormat = BarcodeFormatFromString(format);
if (barcodeFormat == BarcodeFormat::FORMAT_COUNT)
throw std::invalid_argument("Unsupported format: " + format);
MultiFormatWriter writer(barcodeFormat);
if (margin >= 0)
writer.setMargin(margin);
if (eccLevel >= 0)
writer.setEccLevel(eccLevel);
auto bitmap = writer.encode(TextUtfEncoding::FromUtf8(text), width, height).toByteMatrix();
auto ext = GetExtension(filePath);
int success = 0;
if (ext == "" || ext == "png") {
success = stbi_write_png(filePath.c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0);
}
else if (ext == "jpg" || ext == "jpeg") {
success = stbi_write_jpg(filePath.c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0);
}
if (!success) {
std::cerr << "Failed to write image: " << filePath << std::endl;
return -1;
}
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return -1;
}
return 0;
}
| replace flushing std::endl with "\n" | generate_image: replace flushing std::endl with "\n"
| C++ | apache-2.0 | huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp |
c7652667b3bcf3fa99420a48083cc716606c1fdc | src/plugins/qmljsinspector/qmljspropertyinspector.cpp | src/plugins/qmljsinspector/qmljspropertyinspector.cpp | /**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "qmljspropertyinspector.h"
#include <private/qdeclarativemetatype_p.h>
#include <utils/qtcassert.h>
#include <qdeclarativeproperty.h>
#include <QHeaderView>
#include <QItemDelegate>
#include <QLineEdit>
namespace QmlJSInspector {
namespace Internal {
// *************************************************************************
// PropertyEdit
// *************************************************************************
class PropertyEditDelegate : public QItemDelegate
{
public:
explicit PropertyEditDelegate(QObject *parent=0) : QItemDelegate(parent),
m_treeWidget(dynamic_cast<QmlJSPropertyInspector *>(parent)) {}
QWidget *createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
Q_UNUSED(option);
if (index.column() != 1)
return 0;
return new QLineEdit(parent);
}
void setEditorData(QWidget *editor, const QModelIndex &index) const
{
QVariant data = m_treeWidget->getData(index.row(),1,Qt::DisplayRole);
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
lineEdit->setText(data.toString());
}
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
Q_UNUSED(model);
int objectId = m_treeWidget->getData(index.row(),0,Qt::UserRole).toInt();
if (objectId == -1)
return;
QString propertyName = m_treeWidget->getData(index.row(),0,Qt::DisplayRole).toString();
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
QString propertyValue = lineEdit->text();
// add quotes if it's a string
if ( isStringType( m_treeWidget->getData(index.row(),2,Qt::DisplayRole).toString() ) ) {
QChar quote('\"');
if (!propertyValue.startsWith(quote))
propertyValue = quote + propertyValue;
if (!propertyValue.endsWith(quote))
propertyValue += quote;
}
m_treeWidget->propertyValueEdited(objectId, propertyName, propertyValue);
lineEdit->clearFocus();
}
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
Q_UNUSED(index);
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
lineEdit->setGeometry(option.rect);
}
private:
bool isStringType(const QString &typeName) const {
return typeName=="QString" || typeName=="QColor";
}
private:
QmlJSPropertyInspector *m_treeWidget;
};
// *************************************************************************
// FILTER
// *************************************************************************
bool PropertiesFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent);
QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent);
return (sourceModel()->data(index0).toString().contains(filterRegExp())
|| sourceModel()->data(index1).toString().contains(filterRegExp())
|| sourceModel()->data(index2).toString().contains(filterRegExp()));
}
// *************************************************************************
// QmlJSObjectTree
// *************************************************************************
inline QString cleanPropertyValue(QString propertyValue)
{
if (propertyValue == QString("<unknown value>"))
return QString();
if (propertyValue == QString("<unnamed object>"))
return QString();
return propertyValue;
}
QmlJSPropertyInspector::QmlJSPropertyInspector(QWidget *parent)
: QTreeView(parent)
{
setAttribute(Qt::WA_MacShowFocusRect, false);
setFrameStyle(QFrame::NoFrame);
setExpandsOnDoubleClick(true);
header()->setResizeMode(QHeaderView::ResizeToContents);
header()->setMinimumSectionSize(150);
setRootIsDecorated(false);
setItemDelegateForColumn(1, new PropertyEditDelegate(this));
m_filter = new PropertiesFilter(this);
m_filter->setSourceModel(&m_model);
setModel(m_filter);
}
void QmlJSPropertyInspector::filterBy(const QString &expression)
{
m_filter->setFilterWildcard(expression);
m_filter->setFilterCaseSensitivity(Qt::CaseInsensitive);
}
void QmlJSPropertyInspector::clear()
{
m_model.clear();
m_currentObjects.clear();
}
QList <int> QmlJSPropertyInspector::currentObjects() const
{
return m_currentObjects;
}
void QmlJSPropertyInspector::setCurrentObjects(const QList<QDeclarativeDebugObjectReference> &objectList)
{
if (objectList.isEmpty())
return;
clear();
foreach ( QDeclarativeDebugObjectReference obj, objectList) {
m_currentObjects << obj.debugId();
buildPropertyTree(obj);
}
}
QVariant QmlJSPropertyInspector::getData(int row, int column, int role) const
{
return m_filter->data(m_filter->index(row,column),role);
}
void QmlJSPropertyInspector::propertyValueChanged(int debugId, const QByteArray &propertyName, const QVariant &propertyValue)
{
if (m_model.rowCount() == 0)
return;
QString propertyNameS = QString(propertyName);
for (int ii=0; ii < m_model.rowCount(); ii++) {
if (m_model.data(m_model.index(ii,0),Qt::DisplayRole).toString() == propertyNameS &&
m_model.data(m_model.index(ii,0),Qt::UserRole).toInt() == debugId) {
QVariant oldData = m_model.data(m_model.index(ii,1),Qt::DisplayRole);
m_model.setData(m_model.index(ii,1),propertyValue.toString(), Qt::DisplayRole);
if (oldData != propertyValue) {
m_model.item(ii,0)->setForeground(QBrush(Qt::red));
m_model.item(ii,1)->setForeground(QBrush(Qt::red));
m_model.item(ii,2)->setForeground(QBrush(Qt::red));
}
break;
}
}
}
void QmlJSPropertyInspector::propertyValueEdited(const int objectId,const QString& propertyName, const QString& propertyValue)
{
emit changePropertyValue(objectId, propertyName, propertyValue);
}
void QmlJSPropertyInspector::buildPropertyTree(const QDeclarativeDebugObjectReference &obj)
{
// Strip off the misleading metadata
QString objTypeName = obj.className();
QString declarativeString("QDeclarative");
if (objTypeName.startsWith(declarativeString)) {
objTypeName = objTypeName.mid(declarativeString.length()).section('_',0,0);
}
// class
addRow(QString("class"),
objTypeName,
QString("qmlType"),
obj.debugId(),
false);
// id
if (!obj.idString().isEmpty()) {
addRow(QString("id"),
obj.idString(),
QString("idString"),
obj.debugId(),
false);
}
foreach (const QDeclarativeDebugPropertyReference &prop, obj.properties()) {
QString propertyName = prop.name();
if (cleanPropertyValue(prop.value().toString()).isEmpty())
continue;
addRow(propertyName, prop.value().toString(), prop.valueTypeName(), obj.debugId(), prop.hasNotifySignal());
}
m_model.setHeaderData(0,Qt::Horizontal,QVariant("name"));
m_model.setHeaderData(1,Qt::Horizontal,QVariant("value"));
m_model.setHeaderData(2,Qt::Horizontal,QVariant("type"));
}
void QmlJSPropertyInspector::addRow(const QString &name,const QString &value, const QString &type,
const int debugId, bool editable)
{
QStandardItem *nameColumn = new QStandardItem(name);
nameColumn->setToolTip(name);
nameColumn->setData(QVariant(debugId),Qt::UserRole);
nameColumn->setEditable(false);
QStandardItem *valueColumn = new QStandardItem(value);
valueColumn->setToolTip(value);
valueColumn->setEditable(editable);
QStandardItem *typeColumn = new QStandardItem(type);
typeColumn->setToolTip(type);
typeColumn->setEditable(false);
QList <QStandardItem *> newRow;
newRow << nameColumn << valueColumn << typeColumn;
m_model.appendRow(newRow);
}
} // Internal
} // QmlJSInspector
| /**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "qmljspropertyinspector.h"
#include <utils/qtcassert.h>
#include <qdeclarativeproperty.h>
#include <QHeaderView>
#include <QItemDelegate>
#include <QLineEdit>
namespace QmlJSInspector {
namespace Internal {
// *************************************************************************
// PropertyEdit
// *************************************************************************
class PropertyEditDelegate : public QItemDelegate
{
public:
explicit PropertyEditDelegate(QObject *parent=0) : QItemDelegate(parent),
m_treeWidget(dynamic_cast<QmlJSPropertyInspector *>(parent)) {}
QWidget *createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
Q_UNUSED(option);
if (index.column() != 1)
return 0;
return new QLineEdit(parent);
}
void setEditorData(QWidget *editor, const QModelIndex &index) const
{
QVariant data = m_treeWidget->getData(index.row(),1,Qt::DisplayRole);
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
lineEdit->setText(data.toString());
}
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
Q_UNUSED(model);
int objectId = m_treeWidget->getData(index.row(),0,Qt::UserRole).toInt();
if (objectId == -1)
return;
QString propertyName = m_treeWidget->getData(index.row(),0,Qt::DisplayRole).toString();
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
QString propertyValue = lineEdit->text();
// add quotes if it's a string
if ( isStringType( m_treeWidget->getData(index.row(),2,Qt::DisplayRole).toString() ) ) {
QChar quote('\"');
if (!propertyValue.startsWith(quote))
propertyValue = quote + propertyValue;
if (!propertyValue.endsWith(quote))
propertyValue += quote;
}
m_treeWidget->propertyValueEdited(objectId, propertyName, propertyValue);
lineEdit->clearFocus();
}
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
Q_UNUSED(index);
QLineEdit *lineEdit = static_cast<QLineEdit*>(editor);
lineEdit->setGeometry(option.rect);
}
private:
bool isStringType(const QString &typeName) const {
return typeName=="QString" || typeName=="QColor";
}
private:
QmlJSPropertyInspector *m_treeWidget;
};
// *************************************************************************
// FILTER
// *************************************************************************
bool PropertiesFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent);
QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent);
return (sourceModel()->data(index0).toString().contains(filterRegExp())
|| sourceModel()->data(index1).toString().contains(filterRegExp())
|| sourceModel()->data(index2).toString().contains(filterRegExp()));
}
// *************************************************************************
// QmlJSObjectTree
// *************************************************************************
inline QString cleanPropertyValue(QString propertyValue)
{
if (propertyValue == QString("<unknown value>"))
return QString();
if (propertyValue == QString("<unnamed object>"))
return QString();
return propertyValue;
}
QmlJSPropertyInspector::QmlJSPropertyInspector(QWidget *parent)
: QTreeView(parent)
{
setAttribute(Qt::WA_MacShowFocusRect, false);
setFrameStyle(QFrame::NoFrame);
setExpandsOnDoubleClick(true);
header()->setResizeMode(QHeaderView::ResizeToContents);
header()->setMinimumSectionSize(150);
setRootIsDecorated(false);
setItemDelegateForColumn(1, new PropertyEditDelegate(this));
m_filter = new PropertiesFilter(this);
m_filter->setSourceModel(&m_model);
setModel(m_filter);
}
void QmlJSPropertyInspector::filterBy(const QString &expression)
{
m_filter->setFilterWildcard(expression);
m_filter->setFilterCaseSensitivity(Qt::CaseInsensitive);
}
void QmlJSPropertyInspector::clear()
{
m_model.clear();
m_currentObjects.clear();
}
QList <int> QmlJSPropertyInspector::currentObjects() const
{
return m_currentObjects;
}
void QmlJSPropertyInspector::setCurrentObjects(const QList<QDeclarativeDebugObjectReference> &objectList)
{
if (objectList.isEmpty())
return;
clear();
foreach ( QDeclarativeDebugObjectReference obj, objectList) {
m_currentObjects << obj.debugId();
buildPropertyTree(obj);
}
}
QVariant QmlJSPropertyInspector::getData(int row, int column, int role) const
{
return m_filter->data(m_filter->index(row,column),role);
}
void QmlJSPropertyInspector::propertyValueChanged(int debugId, const QByteArray &propertyName, const QVariant &propertyValue)
{
if (m_model.rowCount() == 0)
return;
QString propertyNameS = QString(propertyName);
for (int ii=0; ii < m_model.rowCount(); ii++) {
if (m_model.data(m_model.index(ii,0),Qt::DisplayRole).toString() == propertyNameS &&
m_model.data(m_model.index(ii,0),Qt::UserRole).toInt() == debugId) {
QVariant oldData = m_model.data(m_model.index(ii,1),Qt::DisplayRole);
m_model.setData(m_model.index(ii,1),propertyValue.toString(), Qt::DisplayRole);
if (oldData != propertyValue) {
m_model.item(ii,0)->setForeground(QBrush(Qt::red));
m_model.item(ii,1)->setForeground(QBrush(Qt::red));
m_model.item(ii,2)->setForeground(QBrush(Qt::red));
}
break;
}
}
}
void QmlJSPropertyInspector::propertyValueEdited(const int objectId,const QString& propertyName, const QString& propertyValue)
{
emit changePropertyValue(objectId, propertyName, propertyValue);
}
void QmlJSPropertyInspector::buildPropertyTree(const QDeclarativeDebugObjectReference &obj)
{
// Strip off the misleading metadata
QString objTypeName = obj.className();
QString declarativeString("QDeclarative");
if (objTypeName.startsWith(declarativeString)) {
objTypeName = objTypeName.mid(declarativeString.length()).section('_',0,0);
}
// class
addRow(QString("class"),
objTypeName,
QString("qmlType"),
obj.debugId(),
false);
// id
if (!obj.idString().isEmpty()) {
addRow(QString("id"),
obj.idString(),
QString("idString"),
obj.debugId(),
false);
}
foreach (const QDeclarativeDebugPropertyReference &prop, obj.properties()) {
QString propertyName = prop.name();
if (cleanPropertyValue(prop.value().toString()).isEmpty())
continue;
addRow(propertyName, prop.value().toString(), prop.valueTypeName(), obj.debugId(), prop.hasNotifySignal());
}
m_model.setHeaderData(0,Qt::Horizontal,QVariant("name"));
m_model.setHeaderData(1,Qt::Horizontal,QVariant("value"));
m_model.setHeaderData(2,Qt::Horizontal,QVariant("type"));
}
void QmlJSPropertyInspector::addRow(const QString &name,const QString &value, const QString &type,
const int debugId, bool editable)
{
QStandardItem *nameColumn = new QStandardItem(name);
nameColumn->setToolTip(name);
nameColumn->setData(QVariant(debugId),Qt::UserRole);
nameColumn->setEditable(false);
QStandardItem *valueColumn = new QStandardItem(value);
valueColumn->setToolTip(value);
valueColumn->setEditable(editable);
QStandardItem *typeColumn = new QStandardItem(type);
typeColumn->setToolTip(type);
typeColumn->setEditable(false);
QList <QStandardItem *> newRow;
newRow << nameColumn << valueColumn << typeColumn;
m_model.appendRow(newRow);
}
} // Internal
} // QmlJSInspector
| Remove unneeded header | QmlJSInspector: Remove unneeded header
Task-number: QTCREATORBUG-3554
| C++ | lgpl-2.1 | amyvmiwei/qt-creator,danimo/qt-creator,syntheticpp/qt-creator,sandsmark/qtcreator-minimap,amyvmiwei/qt-creator,bakaiadam/collaborative_qt_creator,maui-packages/qt-creator,ostash/qt-creator-i18n-uk,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,richardmg/qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,azat/qtcreator,Distrotech/qtcreator,duythanhphan/qt-creator,kuba1/qtcreator,dmik/qt-creator-os2,syntheticpp/qt-creator,yinyunqiao/qtcreator,jonnor/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,omniacreator/qtcreator,pcacjr/qt-creator,duythanhphan/qt-creator,syntheticpp/qt-creator,renatofilho/QtCreator,KDAB/KDAB-Creator,yinyunqiao/qtcreator,danimo/qt-creator,yinyunqiao/qtcreator,jonnor/qt-creator,martyone/sailfish-qtcreator,duythanhphan/qt-creator,richardmg/qtcreator,yinyunqiao/qtcreator,renatofilho/QtCreator,hdweiss/qt-creator-visualizer,farseerri/git_code,pcacjr/qt-creator,omniacreator/qtcreator,azat/qtcreator,farseerri/git_code,KDE/android-qt-creator,kuba1/qtcreator,Distrotech/qtcreator,renatofilho/QtCreator,colede/qtcreator,kuba1/qtcreator,dmik/qt-creator-os2,danimo/qt-creator,danimo/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,malikcjm/qtcreator,malikcjm/qtcreator,ostash/qt-creator-i18n-uk,maui-packages/qt-creator,Distrotech/qtcreator,danimo/qt-creator,farseerri/git_code,danimo/qt-creator,hdweiss/qt-creator-visualizer,KDE/android-qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,farseerri/git_code,danimo/qt-creator,KDAB/KDAB-Creator,bakaiadam/collaborative_qt_creator,jonnor/qt-creator,colede/qtcreator,renatofilho/QtCreator,colede/qtcreator,AltarBeastiful/qt-creator,KDE/android-qt-creator,sandsmark/qtcreator-minimap,richardmg/qtcreator,darksylinc/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,sandsmark/qtcreator-minimap,Distrotech/qtcreator,danimo/qt-creator,duythanhphan/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,richardmg/qtcreator,malikcjm/qtcreator,sandsmark/qtcreator-minimap,KDE/android-qt-creator,hdweiss/qt-creator-visualizer,pcacjr/qt-creator,jonnor/qt-creator,KDE/android-qt-creator,dmik/qt-creator-os2,maui-packages/qt-creator,pcacjr/qt-creator,xianian/qt-creator,malikcjm/qtcreator,amyvmiwei/qt-creator,azat/qtcreator,AltarBeastiful/qt-creator,pcacjr/qt-creator,omniacreator/qtcreator,dmik/qt-creator-os2,xianian/qt-creator,malikcjm/qtcreator,farseerri/git_code,xianian/qt-creator,renatofilho/QtCreator,malikcjm/qtcreator,darksylinc/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,colede/qtcreator,darksylinc/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,syntheticpp/qt-creator,KDAB/KDAB-Creator,kuba1/qtcreator,KDE/android-qt-creator,omniacreator/qtcreator,azat/qtcreator,xianian/qt-creator,KDAB/KDAB-Creator,omniacreator/qtcreator,KDE/android-qt-creator,ostash/qt-creator-i18n-uk,pcacjr/qt-creator,syntheticpp/qt-creator,colede/qtcreator,yinyunqiao/qtcreator,duythanhphan/qt-creator,yinyunqiao/qtcreator,bakaiadam/collaborative_qt_creator,maui-packages/qt-creator,syntheticpp/qt-creator,amyvmiwei/qt-creator,malikcjm/qtcreator,KDAB/KDAB-Creator,hdweiss/qt-creator-visualizer,pcacjr/qt-creator,farseerri/git_code,syntheticpp/qt-creator,Distrotech/qtcreator,dmik/qt-creator-os2,farseerri/git_code,omniacreator/qtcreator,KDAB/KDAB-Creator,martyone/sailfish-qtcreator,colede/qtcreator,omniacreator/qtcreator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,KDE/android-qt-creator,richardmg/qtcreator,bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,colede/qtcreator,ostash/qt-creator-i18n-uk,kuba1/qtcreator,sandsmark/qtcreator-minimap,kuba1/qtcreator,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,azat/qtcreator,bakaiadam/collaborative_qt_creator,sandsmark/qtcreator-minimap,jonnor/qt-creator,xianian/qt-creator,xianian/qt-creator,duythanhphan/qt-creator,dmik/qt-creator-os2,ostash/qt-creator-i18n-uk,xianian/qt-creator,jonnor/qt-creator,danimo/qt-creator,ostash/qt-creator-i18n-uk,richardmg/qtcreator,renatofilho/QtCreator,dmik/qt-creator-os2,maui-packages/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,yinyunqiao/qtcreator,Distrotech/qtcreator,bakaiadam/collaborative_qt_creator,kuba1/qtcreator,azat/qtcreator,AltarBeastiful/qt-creator,hdweiss/qt-creator-visualizer |
f773a93813604f82e97e12453e2ce8824c6f36d8 | src/Application/OgreAssetEditorModule/OgreAssetEditorModule.cpp | src/Application/OgreAssetEditorModule/OgreAssetEditorModule.cpp | /**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file OgreAssetEditorModule.cpp
* @brief Provides editing and previewing tools for various asset types.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "OgreAssetEditorModule.h"
#include "OgreScriptEditor.h"
#include "TexturePreviewEditor.h"
#include "AudioPreviewEditor.h"
#include "MeshPreviewEditor.h"
#include "OgreMaterialEditor.h"
#include "LoggingFunctions.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "IAsset.h"
#include "OgreConversionUtils.h"
#include "MemoryLeakCheck.h"
EditorAction::EditorAction(const AssetPtr &assetPtr, const QString &text, QMenu *menu) :
QAction(text, menu),
asset(assetPtr)
{
}
OgreAssetEditorModule::OgreAssetEditorModule() : IModule("OgreAssetEditor")
{
}
OgreAssetEditorModule::~OgreAssetEditorModule()
{
}
void OgreAssetEditorModule::Initialize()
{
connect(framework_->Ui(), SIGNAL(ContextMenuAboutToOpen(QMenu *, QList<QObject *>)), SLOT(OnContextMenuAboutToOpen(QMenu *, QList<QObject *>)));
}
void OgreAssetEditorModule::Uninitialize()
{
}
bool OgreAssetEditorModule::IsSupportedAssetType(const QString &type) const
{
if (/*type == "OgreMesh" || */type == "OgreMaterial" || type == "OgreParticle" || type == "Audio" || type == "Texture")
return true;
else
return false;
}
void OgreAssetEditorModule::OnContextMenuAboutToOpen(QMenu *menu, QList<QObject *> targets)
{
if (targets.size())
{
foreach(QObject *target, targets)
if (!dynamic_cast<IAsset *>(target))
return;
AssetPtr asset = dynamic_cast<IAsset *>(targets[0])->shared_from_this();
if (IsSupportedAssetType(asset->Type()))
{
EditorAction *openAction = new EditorAction(asset, tr("Open"), menu);
openAction->setObjectName("Edit");
connect(openAction, SIGNAL(triggered()), SLOT(OpenAssetInEditor()));
menu->insertAction(menu->actions().size() > 0 ? menu->actions().first() : 0, openAction);
int offset = 1;
// Ogre materials are opened in the visual editor by default.
// Add another action for opening in raw text editor.
if (asset->Type() == "OgreMaterial")
{
EditorAction *openRawAction = new EditorAction(asset, tr("Open as text"), menu);
connect(openRawAction, SIGNAL(triggered()), SLOT(OpenAssetInEditor()));
openRawAction->setObjectName("EditRaw");
menu->insertAction(*(menu->actions().begin() + offset), openRawAction);
++offset;
}
menu->insertSeparator(*(menu->actions().begin() + offset));
}
}
}
void OgreAssetEditorModule::OpenAssetInEditor()
{
EditorAction *action = dynamic_cast<EditorAction *>(sender());
if (!action)
return;
if (action->asset.expired())
return;
QWidget *editor = 0;
AssetPtr asset = action->asset.lock();
if (asset->Type() == "OgreMesh")
{
editor = new MeshPreviewEditor(asset, framework_);
}
else if (asset->Type() == "OgreMaterial")
{
if (action->objectName() == "EditRaw")
editor = new OgreScriptEditor(asset, framework_);
else
editor = new OgreMaterialEditor(asset, framework_);
}
else if (asset->Type() == "OgreParticle")
{
editor = new OgreScriptEditor(asset, framework_);
}
else if (asset->Type() == "Audio")
{
editor = new AudioPreviewEditor(asset, framework_);
}
else if (asset->Type() == "Texture")
{
editor = new TexturePreviewEditor(asset, framework_);
}
if (editor)
{
editor->setParent(framework_->Ui()->MainWindow());
editor->setWindowFlags(Qt::Tool);
editor->setAttribute(Qt::WA_DeleteOnClose);
editor->show();
}
}
extern "C"
{
DLLEXPORT void TundraPluginMain(Framework *fw)
{
IModule *module = new OgreAssetEditorModule();
fw->RegisterModule(module);
}
}
| /**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file OgreAssetEditorModule.cpp
* @brief Provides editing and previewing tools for various asset types.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "OgreAssetEditorModule.h"
#include "OgreScriptEditor.h"
#include "TexturePreviewEditor.h"
#include "AudioPreviewEditor.h"
#include "MeshPreviewEditor.h"
#include "OgreMaterialEditor.h"
#include "LoggingFunctions.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "IAsset.h"
#include "OgreConversionUtils.h"
#include "MemoryLeakCheck.h"
EditorAction::EditorAction(const AssetPtr &assetPtr, const QString &text, QMenu *menu) :
QAction(text, menu),
asset(assetPtr)
{
}
OgreAssetEditorModule::OgreAssetEditorModule() : IModule("OgreAssetEditor")
{
}
OgreAssetEditorModule::~OgreAssetEditorModule()
{
}
void OgreAssetEditorModule::Initialize()
{
connect(framework_->Ui(), SIGNAL(ContextMenuAboutToOpen(QMenu *, QList<QObject *>)), SLOT(OnContextMenuAboutToOpen(QMenu *, QList<QObject *>)));
}
void OgreAssetEditorModule::Uninitialize()
{
}
bool OgreAssetEditorModule::IsSupportedAssetType(const QString &type) const
{
if (/*type == "OgreMesh" || */type == "OgreMaterial" || type == "OgreParticle" || type == "Audio" || type == "Texture")
return true;
else
return false;
}
void OgreAssetEditorModule::OnContextMenuAboutToOpen(QMenu *menu, QList<QObject *> targets)
{
if (targets.size())
{
foreach(QObject *target, targets)
if (!dynamic_cast<IAsset *>(target))
return;
AssetPtr asset = dynamic_cast<IAsset *>(targets[0])->shared_from_this();
if (IsSupportedAssetType(asset->Type()))
{
EditorAction *openAction = new EditorAction(asset, tr("Open"), menu);
openAction->setObjectName("Edit");
connect(openAction, SIGNAL(triggered()), SLOT(OpenAssetInEditor()));
menu->insertAction(menu->actions().size() > 0 ? menu->actions().first() : 0, openAction);
int offset = 1;
/*
// Ogre materials are opened in the visual editor by default.
// Add another action for opening in raw text editor.
if (asset->Type() == "OgreMaterial")
{
EditorAction *openRawAction = new EditorAction(asset, tr("Open as text"), menu);
connect(openRawAction, SIGNAL(triggered()), SLOT(OpenAssetInEditor()));
openRawAction->setObjectName("EditRaw");
menu->insertAction(*(menu->actions().begin() + offset), openRawAction);
++offset;
}
*/
menu->insertSeparator(*(menu->actions().begin() + offset));
}
}
}
void OgreAssetEditorModule::OpenAssetInEditor()
{
EditorAction *action = dynamic_cast<EditorAction *>(sender());
if (!action)
return;
if (action->asset.expired())
return;
QWidget *editor = 0;
AssetPtr asset = action->asset.lock();
if (asset->Type() == "OgreMesh")
{
editor = new MeshPreviewEditor(asset, framework_);
}
else if (asset->Type() == "OgreMaterial")
{
// if (action->objectName() == "EditRaw")
editor = new OgreScriptEditor(asset, framework_);
// else
// editor = new OgreMaterialEditor(asset, framework_);
}
else if (asset->Type() == "OgreParticle")
{
editor = new OgreScriptEditor(asset, framework_);
}
else if (asset->Type() == "Audio")
{
editor = new AudioPreviewEditor(asset, framework_);
}
else if (asset->Type() == "Texture")
{
editor = new TexturePreviewEditor(asset, framework_);
}
if (editor)
{
editor->setParent(framework_->Ui()->MainWindow());
editor->setWindowFlags(Qt::Tool);
editor->setAttribute(Qt::WA_DeleteOnClose);
editor->show();
}
}
extern "C"
{
DLLEXPORT void TundraPluginMain(Framework *fw)
{
IModule *module = new OgreAssetEditorModule();
fw->RegisterModule(module);
}
}
| Disable usage of the new OgreMaterialEditor by default for material assets. Committed usage code accidentally. Ironing out last small bug fixes before "officially" enabling the new editor. | Disable usage of the new OgreMaterialEditor by default for material assets. Committed usage code accidentally. Ironing out last small bug fixes before "officially" enabling the new editor.
| C++ | apache-2.0 | pharos3d/tundra,realXtend/tundra,BogusCurry/tundra,BogusCurry/tundra,AlphaStaxLLC/tundra,realXtend/tundra,jesterKing/naali,BogusCurry/tundra,realXtend/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,jesterKing/naali,AlphaStaxLLC/tundra,realXtend/tundra,pharos3d/tundra,realXtend/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,jesterKing/naali,BogusCurry/tundra,pharos3d/tundra,jesterKing/naali,jesterKing/naali,realXtend/tundra,BogusCurry/tundra,jesterKing/naali,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,jesterKing/naali,BogusCurry/tundra |
e90eee544747c4475e8d067e2a232a0a625e1435 | tests/unit/classifier/svm/SVMOcas_unittest.cc | tests/unit/classifier/svm/SVMOcas_unittest.cc | #include <gtest/gtest.h>
#include <shogun/lib/config.h>
#include <shogun/classifier/svm/SVMOcas.h>
#include <shogun/evaluation/ContingencyTableEvaluation.h>
#include <shogun/features/DataGenerator.h>
#include <shogun/features/DenseFeatures.h>
#include "environments/LinearTestEnvironment.h"
using namespace shogun;
extern LinearTestEnvironment* linear_test_env;
#ifdef HAVE_LAPACK
TEST(SVMOcasTest,train)
{
CMath::init_random(5);
std::shared_ptr<GaussianCheckerboard> mockData =
linear_test_env->getBinaryLabelData();
CDenseFeatures<float64_t>* train_feats = mockData->get_features_train();
CDenseFeatures<float64_t>* test_feats = mockData->get_features_test();
CBinaryLabels* ground_truth = (CBinaryLabels*)mockData->get_labels_test();
CSVMOcas* ocas = new CSVMOcas(1.0, train_feats, ground_truth);
ocas->parallel->set_num_threads(1);
ocas->set_epsilon(1e-5);
ocas->train();
float64_t objective = ocas->compute_primal_objective();
EXPECT_NEAR(objective, 0.024344632618686062, 1e-2);
CLabels* pred = ocas->apply(test_feats);
CAccuracyMeasure evaluate = CAccuracyMeasure();
evaluate.evaluate(pred, ground_truth);
EXPECT_GT(evaluate.get_accuracy(), 0.99);
SG_UNREF(ocas);
SG_UNREF(pred);
}
#endif // HAVE_LAPACK
| #include <gtest/gtest.h>
#include <shogun/lib/config.h>
#include <shogun/classifier/svm/SVMOcas.h>
#include <shogun/evaluation/ContingencyTableEvaluation.h>
#include <shogun/features/DataGenerator.h>
#include <shogun/features/DenseFeatures.h>
#include "environments/LinearTestEnvironment.h"
using namespace shogun;
extern LinearTestEnvironment* linear_test_env;
#ifdef HAVE_LAPACK
TEST(SVMOcasTest,train)
{
CMath::init_random(5);
std::shared_ptr<GaussianCheckerboard> mockData =
linear_test_env->getBinaryLabelData();
CDenseFeatures<float64_t>* train_feats = mockData->get_features_train();
CDenseFeatures<float64_t>* test_feats = mockData->get_features_test();
CBinaryLabels* ground_truth = (CBinaryLabels*)mockData->get_labels_test();
CSVMOcas* ocas = new CSVMOcas(1.0, train_feats, ground_truth);
ocas->parallel->set_num_threads(1);
ocas->set_epsilon(1e-5);
ocas->train();
float64_t objective = ocas->compute_primal_objective();
EXPECT_NEAR(objective, 0.024344632618686062, 1e-2);
CLabels* pred = ocas->apply(test_feats);
SG_REF(pred);
CAccuracyMeasure evaluate = CAccuracyMeasure();
evaluate.evaluate(pred, ground_truth);
EXPECT_GT(evaluate.get_accuracy(), 0.99);
SG_UNREF(ocas);
SG_UNREF(pred);
}
#endif // HAVE_LAPACK
| fix segfault via adding missing SG_REF | fix segfault via adding missing SG_REF
| C++ | bsd-3-clause | shogun-toolbox/shogun,shogun-toolbox/shogun,lisitsyn/shogun,sorig/shogun,shogun-toolbox/shogun,karlnapf/shogun,geektoni/shogun,lisitsyn/shogun,besser82/shogun,geektoni/shogun,lambday/shogun,lisitsyn/shogun,shogun-toolbox/shogun,sorig/shogun,besser82/shogun,besser82/shogun,besser82/shogun,lambday/shogun,sorig/shogun,sorig/shogun,besser82/shogun,shogun-toolbox/shogun,lisitsyn/shogun,karlnapf/shogun,geektoni/shogun,lisitsyn/shogun,karlnapf/shogun,karlnapf/shogun,karlnapf/shogun,lisitsyn/shogun,geektoni/shogun,geektoni/shogun,lambday/shogun,geektoni/shogun,sorig/shogun,karlnapf/shogun,sorig/shogun,shogun-toolbox/shogun,besser82/shogun,lambday/shogun,lambday/shogun,lambday/shogun |
991d1a5fec5c88d271ae48bac04ad9f63ec29cc9 | experimental/experimental/network/hex_dump.cpp | experimental/experimental/network/hex_dump.cpp | #include <cctype>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <network/hex_dump.h>
#include <string>
#include <utils/macros.h>
namespace experimental
{
void HexDump(const std::byte* iBuffer, std::size_t iLength)
{
constexpr const char HexCharacters[] = "0123456789abcdef";
constexpr const std::size_t Step = 16;
std::ios_base::fmtflags previousIOFlags(std::cout.flags());
std::cout << "HexDump [Length=" << iLength << "]:" << std::endl;
for (std::size_t i = 0; i < iLength; i += Step)
{
std::string hexValues(Step * 2, ' ');
std::string asciiValues;
for (std::size_t j = 0; j < Step && i + j < iLength; ++j)
{
char c = static_cast<char>(iBuffer[i + j]);
hexValues[j * 2] = HexCharacters[c >> 4];
hexValues[j * 2 + 1] = HexCharacters[c & 0xf];
asciiValues += 0 != std::isprint(c) ? c : '.';
}
std::cout << '\t' << "0x" << std::setfill('0') << std::setw(4) << std::hex << i << ": ";
for (std::size_t j = 0; j < Step * 2; j += 4)
{
std::cout << std::string_view(hexValues.data() + j, 4) << ' ';
}
std::cout << ' ' << asciiValues << std::endl;
}
std::cout.flags(previousIOFlags);
}
}
| #include <cctype>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <network/hex_dump.h>
#include <string>
#include <utils/macros.h>
namespace experimental
{
void HexDump(const std::byte* iBuffer, std::size_t iLength)
{
constexpr const char HexCharacters[] = "0123456789abcdef";
constexpr const std::size_t Step = 16;
std::ios_base::fmtflags previousIOFlags(std::cout.flags());
std::cout << "HexDump [Length=" << iLength << "]:" << std::endl;
for (std::size_t i = 0; i < iLength; i += Step)
{
std::string hexValues(Step * 2, ' ');
std::string asciiValues;
for (std::size_t j = 0; j < Step && i + j < iLength; ++j)
{
char c = static_cast<char>(iBuffer[i + j]);
hexValues[j * 2] = HexCharacters[(c & 0xf0) >> 4];
hexValues[j * 2 + 1] = HexCharacters[c & 0x0f];
asciiValues += 0 != std::isprint(c) ? c : '.';
}
std::cout << '\t' << "0x" << std::setfill('0') << std::setw(4) << std::hex << i << ": ";
for (std::size_t j = 0; j < Step * 2; j += 4)
{
std::cout << std::string_view(hexValues.data() + j, 4) << ' ';
}
std::cout << ' ' << asciiValues << std::endl;
}
std::cout.flags(previousIOFlags);
}
}
| Update hex_dump.cpp | Update hex_dump.cpp | C++ | mit | Dllieu/experimental,Dllieu/cpp_benchmark,Dllieu/cpp_benchmark,Dllieu/experimental,Dllieu/cpp_benchmark |
101d3b94d54755ce3242c0145555badb71b3762e | himan-lib/source/s3.cpp | himan-lib/source/s3.cpp | #include "s3.h"
using namespace himan;
#ifdef HAVE_S3
#include "debug.h"
#include "timer.h"
#include "util.h"
#include <iostream>
#include <libs3.h>
#include <mutex>
#include <string.h> // memcpy
namespace
{
static std::once_flag oflag;
const char* access_key = 0;
const char* secret_key = 0;
const char* security_token = 0;
S3Protocol protocol = S3ProtocolHTTP;
thread_local S3Status statusG = S3StatusOK;
void CheckS3Error(S3Status errarg, const char* file, const int line);
#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)
void HandleS3Error(himan::logger& logr, const std::string& host, const std::string& object, const std::string& op)
{
logr.Error(fmt::format("{} operation to/from host={} object=s3://{} failed", op, host, object));
const std::string errorstr = S3_get_status_name(statusG);
switch (statusG)
{
case S3StatusInternalError:
logr.Error(fmt::format("{}: is there a proxy blocking the connection?", errorstr));
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(fmt::format("{}: is proxy required but not set?", errorstr));
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(fmt::format(
"{}: are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?",
errorstr));
throw himan::kFileDataNotFound;
case S3StatusErrorAccessDenied:
logr.Error(fmt::format(
"{}: invalid credentials or access protocol (http vs https, hint: set env variable S3_PROTOCOL)?",
errorstr));
throw himan::kFileDataNotFound;
default:
logr.Error(fmt::format("S3 error: {}", errorstr));
throw himan::kFileDataNotFound;
}
}
std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName)
{
std::vector<std::string> ret;
auto fileName = fullFileName;
// strip protocol from string if it's there
const auto pos = fullFileName.find("s3://");
if (pos != std::string::npos)
{
fileName = fileName.erase(pos, 5);
}
// erase forward slash if exists (s3 buckets can't start with /)
if (fileName[0] == '/')
{
fileName = fileName.erase(0, 1);
}
auto tokens = util::Split(fileName, "/");
ret.push_back(tokens[0]);
tokens.erase(std::begin(tokens), std::begin(tokens) + 1);
std::string key;
for (const auto& piece : tokens)
{
if (!key.empty())
{
key += "/";
}
key += piece;
}
ret.push_back(key);
return ret;
}
inline void CheckS3Error(S3Status errarg, const char* file, const int line)
{
if (errarg)
{
std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl;
himan::Abort();
}
}
S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)
{
return S3StatusOK;
}
static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)
{
statusG = status;
return;
}
thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};
static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)
{
himan::buffer* ret = static_cast<himan::buffer*>(callbackData);
ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize));
memcpy(ret->data + ret->length, buffer, bufferSize);
ret->length += bufferSize;
return S3StatusOK;
}
void Initialize()
{
call_once(
oflag,
[&]()
{
access_key = getenv("S3_ACCESS_KEY_ID");
secret_key = getenv("S3_SECRET_ACCESS_KEY");
security_token = getenv("S3_SESSION_TOKEN");
logger logr("s3");
if (!access_key)
{
logr.Info("Environment variable S3_ACCESS_KEY_ID not defined");
}
if (!secret_key)
{
logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined");
}
try
{
const auto envproto = himan::util::GetEnv("S3_PROTOCOL");
if (envproto == "https")
{
protocol = S3ProtocolHTTPS;
}
else if (envproto == "http")
{
protocol = S3ProtocolHTTP;
}
else
{
logr.Warning(fmt::format("Unrecognized value found from env variable S3_PROTOCOL: '{}'", envproto));
}
}
catch (const std::invalid_argument& e)
{
}
S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL));
});
}
std::string ReadAWSRegionFromHostname(const std::string& hostname)
{
if (hostname.find("amazonaws.com") != std::string::npos)
{
// extract region name from host name, assuming aws hostname like
// s3.us-east-1.amazonaws.com
auto tokens = util::Split(hostname, ".");
logger logr("s3");
if (tokens.size() != 4)
{
logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com");
}
else
{
logr.Trace(fmt::format("s3 authentication hostname: {}", tokens[1]));
return tokens[1];
}
}
return "";
}
struct write_data
{
himan::buffer buffer;
size_t write_ptr;
};
static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)
{
write_data* data = static_cast<write_data*>(callbackData);
int bytesWritten = 0;
if (data->buffer.length)
{
bytesWritten =
static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);
memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);
data->write_ptr += bytesWritten;
data->buffer.length -= bytesWritten;
}
return bytesWritten;
}
} // namespace
buffer s3::ReadFile(const file_information& fileInformation)
{
Initialize();
logger logr("s3");
S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};
const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
buffer ret;
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(fileInformation.file_server);
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
// clang-format on
#endif
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
const unsigned long offset = fileInformation.offset.get();
const unsigned long length = fileInformation.length.get();
#ifdef S3_DEFAULT_REGION
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);
#else
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
switch (statusG)
{
case S3StatusOK:
break;
default:
HandleS3Error(logr, fileInformation.file_server, fmt::format("{}/{}", bucket, key), "Read");
break;
}
if (ret.length == 0)
{
throw himan::kFileDataNotFound;
}
return ret;
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
Initialize();
const auto bucketAndFileName = GetBucketAndFileName(objectName);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
const char* host = getenv("S3_HOSTNAME");
logger logr("s3");
if (!host)
{
logr.Fatal("Environment variable S3_HOSTNAME not defined");
himan::Abort();
}
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(std::string(host));
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
#endif
// clang-format on
S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};
write_data data;
data.buffer.data = buff.data;
data.buffer.length = buff.length;
data.write_ptr = 0;
timer t(true);
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
#ifdef S3_DEFAULT_REGION
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);
#else
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
// remove pointer to original buff so that double free doesn't occur
data.buffer.data = 0;
switch (statusG)
{
case S3StatusOK:
{
t.Stop();
const double time = static_cast<double>(t.GetTime());
const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1);
logr.Info(fmt::format("Wrote {} MB in {} ms ({:.1f} MBps) to file s3://{}/{}", size, time,
size / (time * 0.001), bucket, key));
}
break;
default:
HandleS3Error(logr, host, fmt::format("{}/{}", bucket, key), "Write");
break;
}
}
#else
buffer s3::ReadFile(const file_information& fileInformation)
{
throw std::runtime_error("S3 support not compiled");
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
throw std::runtime_error("S3 support not compiled");
}
#endif
| #include "s3.h"
using namespace himan;
#ifdef HAVE_S3
#include "debug.h"
#include "timer.h"
#include "util.h"
#include <iostream>
#include <libs3.h>
#include <mutex>
#include <string.h> // memcpy
namespace
{
static std::once_flag oflag;
const char* access_key = 0;
const char* secret_key = 0;
const char* security_token = 0;
S3Protocol protocol = S3ProtocolHTTPS;
thread_local S3Status statusG = S3StatusOK;
void CheckS3Error(S3Status errarg, const char* file, const int line);
#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)
void HandleS3Error(himan::logger& logr, const std::string& host, const std::string& object, const std::string& op)
{
logr.Error(fmt::format("{} operation to/from host={} object=s3://{} failed", op, host, object));
const std::string errorstr = S3_get_status_name(statusG);
switch (statusG)
{
case S3StatusInternalError:
logr.Error(fmt::format("{}: is there a proxy blocking the connection?", errorstr));
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(fmt::format("{}: is proxy required but not set?", errorstr));
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(fmt::format(
"{}: are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?",
errorstr));
throw himan::kFileDataNotFound;
case S3StatusErrorAccessDenied:
logr.Error(fmt::format(
"{}: invalid credentials or access protocol (http vs https, hint: set env variable S3_PROTOCOL)?",
errorstr));
throw himan::kFileDataNotFound;
default:
logr.Error(fmt::format("S3 error: {}", errorstr));
throw himan::kFileDataNotFound;
}
}
std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName)
{
std::vector<std::string> ret;
auto fileName = fullFileName;
// strip protocol from string if it's there
const auto pos = fullFileName.find("s3://");
if (pos != std::string::npos)
{
fileName = fileName.erase(pos, 5);
}
// erase forward slash if exists (s3 buckets can't start with /)
if (fileName[0] == '/')
{
fileName = fileName.erase(0, 1);
}
auto tokens = util::Split(fileName, "/");
ret.push_back(tokens[0]);
tokens.erase(std::begin(tokens), std::begin(tokens) + 1);
std::string key;
for (const auto& piece : tokens)
{
if (!key.empty())
{
key += "/";
}
key += piece;
}
ret.push_back(key);
return ret;
}
inline void CheckS3Error(S3Status errarg, const char* file, const int line)
{
if (errarg)
{
std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl;
himan::Abort();
}
}
S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)
{
return S3StatusOK;
}
static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)
{
statusG = status;
return;
}
thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};
static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)
{
himan::buffer* ret = static_cast<himan::buffer*>(callbackData);
ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize));
memcpy(ret->data + ret->length, buffer, bufferSize);
ret->length += bufferSize;
return S3StatusOK;
}
void Initialize()
{
call_once(
oflag,
[&]()
{
access_key = getenv("S3_ACCESS_KEY_ID");
secret_key = getenv("S3_SECRET_ACCESS_KEY");
security_token = getenv("S3_SESSION_TOKEN");
logger logr("s3");
if (!access_key)
{
logr.Info("Environment variable S3_ACCESS_KEY_ID not defined");
}
if (!secret_key)
{
logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined");
}
try
{
const auto envproto = himan::util::GetEnv("S3_PROTOCOL");
if (envproto == "https")
{
protocol = S3ProtocolHTTPS;
}
else if (envproto == "http")
{
protocol = S3ProtocolHTTP;
}
else
{
logr.Warning(fmt::format("Unrecognized value found from env variable S3_PROTOCOL: '{}'", envproto));
}
}
catch (const std::invalid_argument& e)
{
}
S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL));
});
}
std::string ReadAWSRegionFromHostname(const std::string& hostname)
{
if (hostname.find("amazonaws.com") != std::string::npos)
{
// extract region name from host name, assuming aws hostname like
// s3.us-east-1.amazonaws.com
auto tokens = util::Split(hostname, ".");
logger logr("s3");
if (tokens.size() != 4)
{
logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com");
}
else
{
logr.Trace(fmt::format("s3 authentication hostname: {}", tokens[1]));
return tokens[1];
}
}
return "";
}
struct write_data
{
himan::buffer buffer;
size_t write_ptr;
};
static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)
{
write_data* data = static_cast<write_data*>(callbackData);
int bytesWritten = 0;
if (data->buffer.length)
{
bytesWritten =
static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);
memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);
data->write_ptr += bytesWritten;
data->buffer.length -= bytesWritten;
}
return bytesWritten;
}
} // namespace
buffer s3::ReadFile(const file_information& fileInformation)
{
Initialize();
logger logr("s3");
S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};
const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
buffer ret;
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(fileInformation.file_server);
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
// clang-format on
#endif
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
const unsigned long offset = fileInformation.offset.get();
const unsigned long length = fileInformation.length.get();
#ifdef S3_DEFAULT_REGION
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);
#else
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
switch (statusG)
{
case S3StatusOK:
break;
default:
HandleS3Error(logr, fileInformation.file_server, fmt::format("{}/{}", bucket, key), "Read");
break;
}
if (ret.length == 0)
{
throw himan::kFileDataNotFound;
}
return ret;
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
Initialize();
const auto bucketAndFileName = GetBucketAndFileName(objectName);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
const char* host = getenv("S3_HOSTNAME");
logger logr("s3");
if (!host)
{
logr.Fatal("Environment variable S3_HOSTNAME not defined");
himan::Abort();
}
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(std::string(host));
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
#endif
// clang-format on
S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};
write_data data;
data.buffer.data = buff.data;
data.buffer.length = buff.length;
data.write_ptr = 0;
timer t(true);
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
#ifdef S3_DEFAULT_REGION
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);
#else
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
// remove pointer to original buff so that double free doesn't occur
data.buffer.data = 0;
switch (statusG)
{
case S3StatusOK:
{
t.Stop();
const double time = static_cast<double>(t.GetTime());
const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1);
logr.Info(fmt::format("Wrote {} MB in {} ms ({:.1f} MBps) to file s3://{}/{}", size, time,
size / (time * 0.001), bucket, key));
}
break;
default:
HandleS3Error(logr, host, fmt::format("{}/{}", bucket, key), "Write");
break;
}
}
#else
buffer s3::ReadFile(const file_information& fileInformation)
{
throw std::runtime_error("S3 support not compiled");
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
throw std::runtime_error("S3 support not compiled");
}
#endif
| Switch default s3 access protocol from http to https | Switch default s3 access protocol from http to https
Protocol can be changed with env variable S3_PROTOCOL
| C++ | mit | fmidev/himan,fmidev/himan,fmidev/himan |
ddcef129c07e22c3255789eca58120a4d7476b3d | Game/src/main.cpp | Game/src/main.cpp | #include "main.h"
/*
Copyright (C) 2016 AGC.
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/>.
*/
using namespace x801::game;
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exception>
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <boost/filesystem.hpp>
#include <portable_endian.h>
#include "Client.h"
#include "Credentials.h"
#include "Server.h"
#include "window/Launcher.h"
static void handleTerminate() {
try {
std::rethrow_exception(std::current_exception());
} catch (std::exception& e) {
std::cerr << "Exception thrown:\n"
<< e.what() << '\n';
} catch (const char* c) {
std::cerr << c << '\n';
exit(-1);
} catch (std::string& c) {
std::cerr << c << '\n';
exit(-1);
} catch (...) {
std::cerr << "something weird happened\n";
exit(-1);
}
exit(-2);
}
static boost::filesystem::path oldPath;
void handleExit() {
boost::filesystem::current_path(oldPath);
}
int lmain(int argc, char** argv) {
oldPath = boost::filesystem::current_path();
boost::filesystem::path ofEXE = x801::base::getPathOfCurrentExecutable();
boost::filesystem::current_path(ofEXE.parent_path());
atexit(handleExit);
at_quick_exit(handleExit);
setlocale(LC_ALL, "");
std::set_terminate(handleTerminate);
if (argc == 1) {
glfwInit();
Launcher launcher(1280, 960, 0, 0, "Experiment801", 3, 3, false);
launcher.start();
glfwTerminate();
return 0;
}
CLineConfig c;
int res = readSettings(c, argc, argv);
if (res != 0) return res;
std::cout << "Hello from Athena V.\n";
if (c.mode == CLIENT) {
curl_global_init(CURL_GLOBAL_ALL);
std::cout << "You intend to connect to a server.\n";
std::string username, password;
if (c.username.length() != 0) username = c.username;
else {
std::cout << "Username: ";
std::cin >> username;
}
if (c.password.length() != 0) password = c.password;
else {
std::cout << "Password: ";
std::cin >> password;
}
Credentials cred(username, password);
Client client(c.ip, c.port, c.useIPV6);
client.login(cred);
client.getListenThread().join();
curl_global_cleanup();
} else {
std::cout << "You intend to start a server.\n";
Server server(c.port, DEFAULT_MAX_CONNECTIONS, c.useIPV6);
}
return 0;
}
const char* x801::game::USAGE =
"Usage:\n"
" Game [-6] [-d] --client <address> <port>\n"
" Game [-6] --server <port>\n"
" -6 (--use-ipv6): use IPV6\n"
" -4 (--use-ipv4): use IPV4\n"
" --client <address> <port> (-c): start a client\n"
" --server <port> (-s): start a server\n"
" -d (--debug): for clients, enable OpenGL live debugging\n"
" (requires OpenGL 4.5 or later)\n"
" --username <username>: pass in username from command line\n"
" --password <password>: pass in password from command line\n"
" The above two options are intended for compatibility with\n"
" graphical debuggers such as bugle and are not recommended\n"
" for actually playing the game.\n"
;
int x801::game::readSettings(CLineConfig& cn, int argc, char** argv) {
bool ok = true;
ClientOrServer mode = HUH;
for (int i = 1; i < argc && ok; ++i) {
char* arg = argv[i];
if (mode != HUH) {
cn.mode = mode;
if (mode == CLIENT) {
// get an IP address and a port
cn.ip = argv[i];
if (i + 1 >= argc) ok = false;
else {
int port = atoi(argv[++i]); // Come on. SLAP ME.
if (port == 0) ok = false;
else cn.port = (uint16_t) port;
}
} else if (mode == SERVER) {
int port = atoi(argv[i]);
if (port == 0) ok = false;
else cn.port = (uint16_t) port;
}
mode = HUH;
} else if (arg[0] == '-') {
if (arg[1] == '-') {
const char* name = arg + 2;
if (!strcmp(name, "client") || !strcmp(name, "cheryl")) mode = CLIENT;
else if (!strcmp(name, "server") || !strcmp(name, "samantha")) mode = SERVER;
else if (!strcmp(name, "use-ipv6")) cn.useIPV6 = true;
else if (!strcmp(name, "use-ipv4")) cn.useIPV6 = false;
else if (!strcmp(name, "debug")) cn.debug = true;
else if (!strcmp(name, "username")) {
if (i == argc - 1) ok = false;
else {
cn.username = argv[i + 1];
++i;
}
}
else if (!strcmp(name, "password")) {
if (i == argc - 1) ok = false;
else {
cn.password = argv[i + 1];
++i;
}
}
else ok = false;
} else {
for (int j = 1; arg[j] != '\0'; ++j) {
if (mode != HUH) ok = false;
switch (arg[j]) {
case 'c':
mode = CLIENT; break;
case 's':
mode = SERVER; break;
case '6':
cn.useIPV6 = true; break;
case '4':
cn.useIPV6 = false; break;
case 'd':
cn.debug = true; break;
default:
ok = false;
}
if (!ok) break;
}
}
}
else ok = false;
}
if (!ok || cn.mode == HUH) {
std::cerr << USAGE;
return -1;
}
return 0;
}
| #include "main.h"
/*
Copyright (C) 2016 AGC.
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/>.
*/
using namespace x801::game;
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exception>
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <boost/filesystem.hpp>
#include <portable_endian.h>
#include "Client.h"
#include "Credentials.h"
#include "Server.h"
#include "window/Launcher.h"
static void handleTerminate() {
try {
std::rethrow_exception(std::current_exception());
} catch (std::exception& e) {
std::cerr << "Exception thrown:\n"
<< e.what() << '\n';
} catch (const char* c) {
std::cerr << c << '\n';
exit(-1);
} catch (std::string& c) {
std::cerr << c << '\n';
exit(-1);
} catch (...) {
std::cerr << "something weird happened\n";
exit(-1);
}
exit(-2);
}
static boost::filesystem::path oldPath;
void handleExit() {
boost::filesystem::current_path(oldPath);
}
int lmain(int argc, char** argv) {
oldPath = boost::filesystem::current_path();
boost::filesystem::path ofEXE = x801::base::getPathOfCurrentExecutable();
boost::filesystem::current_path(ofEXE.parent_path());
atexit(handleExit);
at_quick_exit(handleExit);
setlocale(LC_ALL, "");
std::set_terminate(handleTerminate);
if (argc == 1) {
glfwInit();
Launcher launcher(1280, 960, 0, 0, "Experiment801", 3, 3, false);
launcher.start();
glfwTerminate();
return 0;
}
CLineConfig c;
int res = readSettings(c, argc, argv);
if (res != 0) return res;
std::cout << "Hello from Athena V.\n";
if (c.mode == CLIENT) {
curl_global_init(CURL_GLOBAL_ALL);
std::cout << "You intend to connect to a server.\n";
std::string username, password;
if (c.username.length() != 0) username = c.username;
else {
std::cout << "Username: ";
std::cin >> username;
}
if (c.password.length() != 0) password = c.password;
else {
std::cout << "Password: ";
std::cin >> password;
}
Credentials cred(username, password);
Client client(c.ip, c.port, c.useIPV6);
client.login(cred);
client.getListenThread().join();
curl_global_cleanup();
} else {
std::cout << "You intend to start a server.\n";
Server server(c.port, DEFAULT_MAX_CONNECTIONS, c.useIPV6);
}
return 0;
}
const char* x801::game::USAGE =
"Usage:\n"
" Game [-6] [-d] --client <address> <port>\n"
" Game [-6] --server <port>\n"
" -6 (--use-ipv6): use IPV6\n"
" -4 (--use-ipv4): use IPV4\n"
" --client <address> <port> (-c): start a client\n"
" --server <port> (-s): start a server\n"
" -d (--debug): for clients, enable OpenGL live debugging\n"
" (requires OpenGL 4.5 or later)\n"
" --username <username>: pass in username from command line\n"
" --password <password>: pass in password from command line\n"
" The above two options are intended for compatibility with\n"
" graphical debuggers such as bugle and are not recommended\n"
" for actually playing the game.\n"
;
int x801::game::readSettings(CLineConfig& cn, int argc, char** argv) {
bool ok = true;
ClientOrServer mode = HUH;
for (int i = 1; i < argc && ok; ++i) {
char* arg = argv[i];
if (mode != HUH) {
cn.mode = mode;
if (mode == CLIENT) {
// get an IP address and a port
cn.ip = argv[i];
if (i + 1 >= argc) ok = false;
else {
int port = atoi(argv[++i]); // Come on. SLAP ME.
if (port == 0) ok = false;
else cn.port = (uint16_t) port;
}
} else if (mode == SERVER) {
int port = atoi(argv[i]);
if (port == 0) ok = false;
else cn.port = (uint16_t) port;
}
mode = HUH;
} else if (arg[0] == '-') {
if (arg[1] == '-') {
const char* name = arg + 2;
if (!strcmp(name, "client") || !strcmp(name, "cheryl"))
mode = CLIENT;
else if (!strcmp(name, "server") || !strcmp(name, "samantha"))
mode = SERVER;
else if (!strcmp(name, "use-ipv6"))
cn.useIPV6 = true;
else if (!strcmp(name, "use-ipv4"))
cn.useIPV6 = false;
else if (!strcmp(name, "debug"))
cn.debug = true;
else if (!strcmp(name, "username")) {
if (i == argc - 1) ok = false;
else {
cn.username = argv[i + 1];
++i;
}
}
else if (!strcmp(name, "password")) {
if (i == argc - 1) ok = false;
else {
cn.password = argv[i + 1];
++i;
}
}
else ok = false;
} else {
for (int j = 1; arg[j] != '\0'; ++j) {
if (mode != HUH) ok = false;
switch (arg[j]) {
case 'c':
mode = CLIENT; break;
case 's':
mode = SERVER; break;
case '6':
cn.useIPV6 = true; break;
case '4':
cn.useIPV6 = false; break;
case 'd':
cn.debug = true; break;
default:
ok = false;
}
if (!ok) break;
}
}
}
else ok = false;
}
if (!ok || cn.mode == HUH) {
std::cerr << USAGE;
return -1;
}
return 0;
}
| Make a few formatting improvements in main.cpp | Make a few formatting improvements in main.cpp
| C++ | agpl-3.0 | nagakawa/x801,nagakawa/x801,nagakawa/x801,nagakawa/x801,nagakawa/x801 |
d4ef927502c34ce0b486a84db4a4184db6571dde | src/gl_widget.cpp | src/gl_widget.cpp | #include "gl_widget.hpp"
#include <QPainter>
#include <QPaintEngine>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QCoreApplication>
#include <QtGui/QMouseEvent>
#include <QtGui/QGuiApplication>
#include <cmath>
#include <iostream>
#include "game_window.hpp"
#include "constants.hpp"
namespace
{
int constexpr kLeftDirection = 0;
int constexpr kRightDirection = 1;
int constexpr kUpDirection = 2;
int constexpr kDownDirection = 3;
int constexpr kWidth = 1024;
int constexpr kHeight = 768;
bool IsLeftButton(Qt::MouseButtons buttons)
{
return buttons & Qt::LeftButton;
}
bool IsLeftButton(QMouseEvent const * const e)
{
return IsLeftButton(e->button()) || IsLeftButton(e->buttons());
}
bool IsRightButton(Qt::MouseButtons buttons)
{
return buttons & Qt::RightButton;
}
bool IsRightButton(QMouseEvent const * const e)
{
return IsRightButton(e->button()) || IsRightButton(e->buttons());
}
} // namespace
GLWidget::GLWidget(GameWindow * mw, QColor const & background)
: m_mainWindow(mw)
, m_background(background)
{
m_space = std::make_shared<Space>();
setMinimumSize(Globals::Width, Globals::Height);
setFocusPolicy(Qt::StrongFocus);
}
GLWidget::~GLWidget()
{
makeCurrent();
doneCurrent();
}
void GLWidget::initializeGL()
{
initializeOpenGLFunctions();
m_texturedRect = new TexturedRect();
m_texturedRect->Initialize(this);
Images::Instance().LoadImages();
m_space->AddAlien(std::make_shared<Alien>(
100,
QVector2D(200, 600),
100,
100,
Images::Instance().GetImageAlien()));
m_space->SetSpaceShip(std::make_shared<SpaceShip>(
QVector2D(200, 600),
100,
100,
Images::Instance().GetImageSpaceShip()));
m_space->AddObstacle(std::make_shared<Obstacle>(
100,
QVector2D(200, 600),
Images::Instance().GetImageObstacle()));
AddStar();
m_time.start();
}
void GLWidget::paintGL()
{
int const elapsed = m_time.elapsed();
Update(elapsed / 1000.0f);
QPainter painter;
painter.begin(this);
painter.beginNativePainting();
glClearColor(m_background.redF(), m_background.greenF(), m_background.blueF(), 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
for (auto bullet : m_space->GetSpaceShipBullets()) {
bullet->IncreaseY(100);
}
Render();
RenderSpaceShip();
RenderBullet();
RenderObstacle();
/// Set to zero if it reaches the 1.0 .
if (m_period < 1.0)
{
m_period += 0.001f;
}
else
{
m_period = 0.0f;
for (auto it = m_random.begin() ; it != m_random.end(); ++it)
{
*it = std::make_pair(Random(0,1), Random(0,1));
}
}
// Generate a parameter for a star.
// transperancy is a value between 0.0 and 1.0 .
float transperancy = sin(m_period * 2 * PI);
RenderStar(transperancy);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
painter.endNativePainting();
if (elapsed != 0)
{
QString framesPerSecond;
framesPerSecond.setNum(m_frames / (elapsed / 1000.0), 'f', 2);
painter.setPen(Qt::white);
painter.drawText(20, 40, framesPerSecond + " fps");
}
painter.end();
if (!(m_frames % 100))
{
m_time.start();
m_frames = 0;
}
++m_frames;
update();
}
void GLWidget::resizeGL(int w, int h)
{
m_screenSize.setWidth(w);
m_screenSize.setHeight(h);
}
void GLWidget::Update(float elapsedSeconds)
{
float const kSpeed = 20.0f; // pixels per second.
if (m_directions[kUpDirection])
{
m_space->GetSpaceShip()->IncreaseY(kSpeed * elapsedSeconds);
}
if (m_directions[kDownDirection])
{
m_space->GetSpaceShip()->DecreaseY(kSpeed * elapsedSeconds);
}
if (m_directions[kLeftDirection])
{
m_space->GetSpaceShip()->DecreaseX(kSpeed * elapsedSeconds);
}
if (m_directions[kRightDirection])
{
m_space->GetSpaceShip()->IncreaseX(kSpeed * elapsedSeconds);
}
}
void GLWidget::Render()
{
for (auto alien : m_space->GetAliens()) {
m_texturedRect->Render(alien->GetTexture(),
QVector2D(200, 600),
QSize(128, 128),
m_screenSize,
1.0);
}
}
void GLWidget::RenderSpaceShip()
{
m_texturedRect->Render(m_space->GetSpaceShip()->GetTexture(),
m_space->GetSpaceShip()->GetPosition(),
QSize(128, 128),
m_screenSize,
1.0);
}
void GLWidget::RenderBullet()
{
for (auto bullet : m_space->GetSpaceShipBullets()) {
m_texturedRect->Render(bullet->GetTexture(),
bullet->GetPosition(),
QSize(128, 128),
m_screenSize,
1.0);
}
for (auto bullet : m_space->GetAlienBullets()) {
m_texturedRect->Render(bullet->GetTexture(),
bullet->GetPosition(),
QSize(128, 128),
m_screenSize,
1.0);
}
}
void GLWidget::RenderObstacle()
{
for (auto obstacle : m_space->GetObstacles()) {
m_texturedRect->Render(obstacle->GetTexture(),
QVector2D(500, 300),
QSize(128, 128),
m_screenSize,
1.0);
}
}
void GLWidget::RenderStar(float blend)
{
int i=0;
for (auto it = m_space->GetStars().begin(); it != m_space->GetStars().end() || i <m_random.size(); ++it,i++) {
m_texturedRect->Render(
(*it)->GetTexture(),
QVector2D(m_random.at(i).first*kWidth, m_random.at(i).second*kHeight),
QSize(16, 16),
m_screenSize,
blend);
}
}
void GLWidget::AddStar()
{
m_space->AddStar(std::make_shared<Star>(
QVector2D(200, 600),
Images::Instance().GetImageStar()));
m_random.push_back(std::make_pair(Random(0,1), Random(0,1)));
}
void GLWidget::mousePressEvent(QMouseEvent * e)
{
QGLWidget::mousePressEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsLeftButton(e))
{
// ...
}
}
void GLWidget::mouseDoubleClickEvent(QMouseEvent * e)
{
QGLWidget::mouseDoubleClickEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsRightButton(e))
{
// ...
}
}
void GLWidget::mouseMoveEvent(QMouseEvent * e)
{
QGLWidget::mouseMoveEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsLeftButton(e))
{
// ...
}
}
void GLWidget::mouseReleaseEvent(QMouseEvent * e)
{
QGLWidget::mouseReleaseEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsLeftButton(e))
{
// ...
}
}
void GLWidget::wheelEvent(QWheelEvent * e)
{
QGLWidget::wheelEvent(e);
int const delta = e->delta();
int const px = L2D(e->x());
int const py = L2D(e->y());
// ...
}
void GLWidget::keyPressEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_Up)
m_directions[kUpDirection] = true;
else if (e->key() == Qt::Key_Down)
m_directions[kDownDirection] = true;
else if (e->key() == Qt::Key_Left)
m_directions[kLeftDirection] = true;
else if (e->key() == Qt::Key_Right)
m_directions[kRightDirection] = true;
else if (e->key() == Qt::Key_Space)
{
std::shared_ptr<Bullet> bullet = std::make_shared<Bullet>(
m_space->GetSpaceShip()->GetPosition(),
Images::Instance().GetImageBullet(),
100);
m_space->AddSpaceShipBullet(bullet);
}
}
void GLWidget::keyReleaseEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_Up)
m_directions[kUpDirection] = false;
else if (e->key() == Qt::Key_Down)
m_directions[kDownDirection] = false;
else if (e->key() == Qt::Key_Left)
m_directions[kLeftDirection] = false;
else if (e->key() == Qt::Key_Right)
m_directions[kRightDirection] = false;
}
double GLWidget::Random(double min, double max)
{
std::uniform_real_distribution<double> distribution(min, max);
double number = distribution(m_generator);
return number;
}
| #include "gl_widget.hpp"
#include <QPainter>
#include <QPaintEngine>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QCoreApplication>
#include <QtGui/QMouseEvent>
#include <QtGui/QGuiApplication>
#include <cmath>
#include <iostream>
#include "game_window.hpp"
#include "constants.hpp"
namespace
{
int constexpr kLeftDirection = 0;
int constexpr kRightDirection = 1;
int constexpr kUpDirection = 2;
int constexpr kDownDirection = 3;
int constexpr kWidth = 1024;
int constexpr kHeight = 768;
bool IsLeftButton(Qt::MouseButtons buttons)
{
return buttons & Qt::LeftButton;
}
bool IsLeftButton(QMouseEvent const * const e)
{
return IsLeftButton(e->button()) || IsLeftButton(e->buttons());
}
bool IsRightButton(Qt::MouseButtons buttons)
{
return buttons & Qt::RightButton;
}
bool IsRightButton(QMouseEvent const * const e)
{
return IsRightButton(e->button()) || IsRightButton(e->buttons());
}
} // namespace
GLWidget::GLWidget(GameWindow * mw, QColor const & background)
: m_mainWindow(mw)
, m_background(background)
{
m_space = std::make_shared<Space>();
setMinimumSize(Globals::Width, Globals::Height);
setFocusPolicy(Qt::StrongFocus);
}
GLWidget::~GLWidget()
{
makeCurrent();
doneCurrent();
}
void GLWidget::initializeGL()
{
initializeOpenGLFunctions();
m_texturedRect = new TexturedRect();
m_texturedRect->Initialize(this);
Images::Instance().LoadImages();
m_space->AddAlien(std::make_shared<Alien>(
100,
QVector2D(200, 600),
100,
100,
Images::Instance().GetImageAlien()));
m_space->SetSpaceShip(std::make_shared<SpaceShip>(
QVector2D(200, 600),
100,
100,
Images::Instance().GetImageSpaceShip()));
m_space->AddObstacle(std::make_shared<Obstacle>(
100,
QVector2D(200, 600),
Images::Instance().GetImageObstacle()));
AddStar();
m_time.start();
}
void GLWidget::paintGL()
{
int const elapsed = m_time.elapsed();
Update(elapsed / 1000.0f);
QPainter painter;
painter.begin(this);
painter.beginNativePainting();
glClearColor(m_background.redF(), m_background.greenF(), m_background.blueF(), 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
for (auto bullet : m_space->GetSpaceShipBullets()) {
bullet->IncreaseY(100);
}
Render();
RenderSpaceShip();
RenderBullet();
RenderObstacle();
/// Set to zero if it reaches the 1.0 .
if (m_period < 1.0)
{
m_period += 0.001f;
}
else
{
m_period = 0.0f;
for (auto it = m_random.begin() ; it != m_random.end(); ++it)
{
*it = std::make_pair(Random(0,1), Random(0,1));
}
}
// Generate a parameter for a star.
// transperancy is a value between 0.0 and 1.0 .
float transperancy = static_cast<float>(sin(m_period * 2 * PI));
RenderStar(transperancy);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
painter.endNativePainting();
if (elapsed != 0)
{
QString framesPerSecond;
framesPerSecond.setNum(m_frames / (elapsed / 1000.0), 'f', 2);
painter.setPen(Qt::white);
painter.drawText(20, 40, framesPerSecond + " fps");
}
painter.end();
if (!(m_frames % 100))
{
m_time.start();
m_frames = 0;
}
++m_frames;
update();
}
void GLWidget::resizeGL(int w, int h)
{
m_screenSize.setWidth(w);
m_screenSize.setHeight(h);
}
void GLWidget::Update(float elapsedSeconds)
{
float const kSpeed = 20.0f; // pixels per second.
if (m_directions[kUpDirection])
{
m_space->GetSpaceShip()->IncreaseY(kSpeed * elapsedSeconds);
}
if (m_directions[kDownDirection])
{
m_space->GetSpaceShip()->DecreaseY(kSpeed * elapsedSeconds);
}
if (m_directions[kLeftDirection])
{
m_space->GetSpaceShip()->DecreaseX(kSpeed * elapsedSeconds);
}
if (m_directions[kRightDirection])
{
m_space->GetSpaceShip()->IncreaseX(kSpeed * elapsedSeconds);
}
}
void GLWidget::Render()
{
for (auto alien : m_space->GetAliens()) {
m_texturedRect->Render(alien->GetTexture(),
QVector2D(200, 600),
QSize(128, 128),
m_screenSize,
1.0);
}
}
void GLWidget::RenderSpaceShip()
{
m_texturedRect->Render(m_space->GetSpaceShip()->GetTexture(),
m_space->GetSpaceShip()->GetPosition(),
QSize(128, 128),
m_screenSize,
1.0);
}
void GLWidget::RenderBullet()
{
for (auto bullet : m_space->GetSpaceShipBullets()) {
m_texturedRect->Render(bullet->GetTexture(),
bullet->GetPosition(),
QSize(128, 128),
m_screenSize,
1.0);
}
for (auto bullet : m_space->GetAlienBullets()) {
m_texturedRect->Render(bullet->GetTexture(),
bullet->GetPosition(),
QSize(128, 128),
m_screenSize,
1.0);
}
}
void GLWidget::RenderObstacle()
{
for (auto obstacle : m_space->GetObstacles()) {
m_texturedRect->Render(obstacle->GetTexture(),
QVector2D(500, 300),
QSize(128, 128),
m_screenSize,
1.0);
}
}
void GLWidget::RenderStar(float blend)
{
int i=0;
for (auto it = m_space->GetStars().begin(); it != m_space->GetStars().end() || i <m_random.size(); ++it,i++) {
m_texturedRect->Render(
(*it)->GetTexture(),
QVector2D(m_random.at(i).first*kWidth, m_random.at(i).second*kHeight),
QSize(16, 16),
m_screenSize,
blend);
}
}
void GLWidget::AddStar()
{
m_space->AddStar(std::make_shared<Star>(
QVector2D(200, 600),
Images::Instance().GetImageStar()));
m_random.push_back(std::make_pair(Random(0,1), Random(0,1)));
}
void GLWidget::mousePressEvent(QMouseEvent * e)
{
QGLWidget::mousePressEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsLeftButton(e))
{
// ...
}
}
void GLWidget::mouseDoubleClickEvent(QMouseEvent * e)
{
QGLWidget::mouseDoubleClickEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsRightButton(e))
{
// ...
}
}
void GLWidget::mouseMoveEvent(QMouseEvent * e)
{
QGLWidget::mouseMoveEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsLeftButton(e))
{
// ...
}
}
void GLWidget::mouseReleaseEvent(QMouseEvent * e)
{
QGLWidget::mouseReleaseEvent(e);
int const px = L2D(e->x());
int const py = L2D(e->y());
if (IsLeftButton(e))
{
// ...
}
}
void GLWidget::wheelEvent(QWheelEvent * e)
{
QGLWidget::wheelEvent(e);
int const delta = e->delta();
int const px = L2D(e->x());
int const py = L2D(e->y());
// ...
}
void GLWidget::keyPressEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_Up)
m_directions[kUpDirection] = true;
else if (e->key() == Qt::Key_Down)
m_directions[kDownDirection] = true;
else if (e->key() == Qt::Key_Left)
m_directions[kLeftDirection] = true;
else if (e->key() == Qt::Key_Right)
m_directions[kRightDirection] = true;
else if (e->key() == Qt::Key_Space)
{
std::shared_ptr<Bullet> bullet = std::make_shared<Bullet>(
m_space->GetSpaceShip()->GetPosition(),
Images::Instance().GetImageBullet(),
100);
m_space->AddSpaceShipBullet(bullet);
}
}
void GLWidget::keyReleaseEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_Up)
m_directions[kUpDirection] = false;
else if (e->key() == Qt::Key_Down)
m_directions[kDownDirection] = false;
else if (e->key() == Qt::Key_Left)
m_directions[kLeftDirection] = false;
else if (e->key() == Qt::Key_Right)
m_directions[kRightDirection] = false;
}
double GLWidget::Random(double min, double max)
{
std::uniform_real_distribution<double> distribution(min, max);
double number = distribution(m_generator);
return number;
}
| fix bug: add cast to float | fix bug: add cast to float
| C++ | mit | Chepik/SpaceInvaders |
18cf6b1bdd86a6167adcefb6cfdadc4777539a45 | src/grid/grid.cpp | src/grid/grid.cpp | /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 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
*
*****************************************************************************/
// mapnik
#include <mapnik/grid/grid.hpp>
#include <mapnik/util/conversions.hpp>
namespace mapnik
{
template<> const grid::value_type grid::base_mask = std::numeric_limits<int>::min();
}
| /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 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
*
*****************************************************************************/
// mapnik
#include <mapnik/grid/grid.hpp>
namespace mapnik
{
template<> const grid::value_type grid::base_mask = std::numeric_limits<int>::min();
}
| remove unneeded header | remove unneeded header
| C++ | lgpl-2.1 | tomhughes/python-mapnik,naturalatlas/mapnik,Uli1/mapnik,tomhughes/mapnik,zerebubuth/mapnik,kapouer/mapnik,strk/mapnik,Uli1/mapnik,pnorman/mapnik,pnorman/mapnik,sebastic/python-mapnik,sebastic/python-mapnik,yiqingj/work,whuaegeanse/mapnik,lightmare/mapnik,pramsey/mapnik,lightmare/mapnik,whuaegeanse/mapnik,davenquinn/python-mapnik,garnertb/python-mapnik,jwomeara/mapnik,Uli1/mapnik,garnertb/python-mapnik,stefanklug/mapnik,stefanklug/mapnik,strk/mapnik,mbrukman/mapnik,Mappy/mapnik,CartoDB/mapnik,kapouer/mapnik,mapycz/python-mapnik,manz/python-mapnik,mapnik/python-mapnik,davenquinn/python-mapnik,jwomeara/mapnik,lightmare/mapnik,Airphrame/mapnik,mapycz/mapnik,CartoDB/mapnik,zerebubuth/mapnik,Airphrame/mapnik,tomhughes/python-mapnik,Airphrame/mapnik,garnertb/python-mapnik,pnorman/mapnik,mapnik/mapnik,mapnik/python-mapnik,kapouer/mapnik,jwomeara/mapnik,yohanboniface/python-mapnik,tomhughes/mapnik,mbrukman/mapnik,mapnik/python-mapnik,pramsey/mapnik,mapycz/python-mapnik,rouault/mapnik,mapnik/mapnik,mapnik/mapnik,qianwenming/mapnik,cjmayo/mapnik,CartoDB/mapnik,rouault/mapnik,yiqingj/work,davenquinn/python-mapnik,pramsey/mapnik,tomhughes/python-mapnik,stefanklug/mapnik,naturalatlas/mapnik,yiqingj/work,pramsey/mapnik,strk/mapnik,sebastic/python-mapnik,Airphrame/mapnik,kapouer/mapnik,manz/python-mapnik,yohanboniface/python-mapnik,jwomeara/mapnik,zerebubuth/mapnik,Mappy/mapnik,rouault/mapnik,manz/python-mapnik,strk/mapnik,Mappy/mapnik,qianwenming/mapnik,mapycz/mapnik,qianwenming/mapnik,stefanklug/mapnik,Mappy/mapnik,naturalatlas/mapnik,pnorman/mapnik,whuaegeanse/mapnik,qianwenming/mapnik,tomhughes/mapnik,cjmayo/mapnik,mbrukman/mapnik,cjmayo/mapnik,Uli1/mapnik,mapycz/mapnik,naturalatlas/mapnik,rouault/mapnik,tomhughes/mapnik,mbrukman/mapnik,mapnik/mapnik,whuaegeanse/mapnik,qianwenming/mapnik,yiqingj/work,lightmare/mapnik,cjmayo/mapnik,yohanboniface/python-mapnik |
6cdff99df35a058c0f9ae31b3260fed7ee574e48 | xs/src/libslic3r/SLAPrint.cpp | xs/src/libslic3r/SLAPrint.cpp | #include "SLAPrint.hpp"
#include "ClipperUtils.hpp"
#include "ExtrusionEntity.hpp"
#include "Fill/FillBase.hpp"
#include "Geometry.hpp"
#include "Surface.hpp"
#include <iostream>
#include <cstdio>
namespace Slic3r {
void
SLAPrint::slice()
{
TriangleMesh mesh = this->model->mesh();
mesh.repair();
// align to origin taking raft into account
this->bb = mesh.bounding_box();
if (this->config.raft_layers > 0) {
this->bb.min.x -= this->config.raft_offset.value;
this->bb.min.y -= this->config.raft_offset.value;
this->bb.max.x += this->config.raft_offset.value;
this->bb.max.y += this->config.raft_offset.value;
}
mesh.translate(0, 0, -bb.min.z);
this->bb.translate(0, 0, -bb.min.z);
// if we are generating a raft, first_layer_height will not affect mesh slicing
const float lh = this->config.layer_height.value;
const float first_lh = this->config.first_layer_height.value;
// generate the list of Z coordinates for mesh slicing
// (we slice each layer at half of its thickness)
this->layers.clear();
{
const float first_slice_lh = (this->config.raft_layers > 0) ? lh : first_lh;
this->layers.push_back(Layer(first_slice_lh/2, first_slice_lh));
}
while (this->layers.back().print_z + lh/2 <= mesh.stl.stats.max.z) {
this->layers.push_back(Layer(this->layers.back().print_z + lh/2, this->layers.back().print_z + lh));
}
// perform slicing and generate layers
{
std::vector<float> slice_z;
for (size_t i = 0; i < this->layers.size(); ++i)
slice_z.push_back(this->layers[i].slice_z);
std::vector<ExPolygons> slices;
TriangleMeshSlicer(&mesh).slice(slice_z, &slices);
for (size_t i = 0; i < slices.size(); ++i)
this->layers[i].slices.expolygons = slices[i];
}
// generate infill
if (this->config.fill_density < 100) {
const float shell_thickness = this->config.get_abs_value("perimeter_extrusion_width", this->config.layer_height.value);
std::auto_ptr<Fill> fill = std::auto_ptr<Fill>(Fill::new_from_type(this->config.fill_pattern.value));
//fill->bounding_box = this->bb;
fill->spacing = this->config.get_abs_value("infill_extrusion_width", this->config.layer_height.value);
fill->angle = Geometry::deg2rad(this->config.fill_angle.value);
FillParams fill_params;
fill_params.density = this->config.fill_density.value/100;
ExtrusionPath templ(erInternalInfill);
templ.width = fill->spacing;
for (size_t i = 0; i < this->layers.size(); ++i) {
Layer &layer = this->layers[i];
// In order to detect what regions of this layer need to be solid,
// perform an intersection with layers within the requested shell thickness.
Polygons internal = layer.slices;
for (size_t j = 0; j < this->layers.size(); ++j) {
const Layer &other = this->layers[j];
if (abs(other.print_z - layer.print_z) > shell_thickness) continue;
if (j == 0 || j == this->layers.size()-1) {
internal.clear();
break;
} else if (i != j) {
internal = intersection(internal, other.slices);
if (internal.empty()) break;
}
}
// If we have no internal infill, just print the whole layer as a solid slice.
if (internal.empty()) continue;
layer.solid = false;
const Polygons infill = offset(layer.slices, -scale_(shell_thickness));
// Generate solid infill.
layer.solid_infill.append(diff_ex(infill, internal, true));
// Generate internal infill.
{
fill->layer_id = i;
fill->z = layer.print_z;
const ExPolygons internal_ex = intersection_ex(infill, internal);
for (ExPolygons::const_iterator it = internal_ex.begin(); it != internal_ex.end(); ++it) {
Polylines polylines = fill->fill_surface(Surface(stInternal, *it), fill_params);
layer.infill.append(polylines, templ);
}
}
// Generate perimeter(s).
{
const Polygons perimeters = offset(layer.slices, -scale_(shell_thickness)/2);
for (Polygons::const_iterator it = perimeters.begin(); it != perimeters.end(); ++it) {
ExtrusionPath ep(erPerimeter);
ep.polyline = *it;
ep.width = shell_thickness;
layer.perimeters.append(ExtrusionLoop(ep));
}
}
}
}
// generate support material
this->sm_pillars.clear();
ExPolygons overhangs;
if (this->config.support_material) {
// flatten and merge all the overhangs
{
Polygons pp;
for (std::vector<Layer>::const_iterator it = this->layers.begin()+1; it != this->layers.end(); ++it) {
Polygons oh = diff(it->slices, (it - 1)->slices);
pp.insert(pp.end(), oh.begin(), oh.end());
}
overhangs = union_ex(pp);
}
// generate points following the shape of each island
Points pillars_pos;
const coordf_t spacing = scale_(this->config.support_material_spacing);
const coordf_t radius = scale_(this->sm_pillars_radius());
for (ExPolygons::const_iterator it = overhangs.begin(); it != overhangs.end(); ++it) {
// leave a radius/2 gap between pillars and contour to prevent lateral adhesion
for (float inset = radius * 1.5;; inset += spacing) {
// inset according to the configured spacing
Polygons curr = offset(*it, -inset);
if (curr.empty()) break;
// generate points along the contours
for (Polygons::const_iterator pg = curr.begin(); pg != curr.end(); ++pg) {
Points pp = pg->equally_spaced_points(spacing);
for (Points::const_iterator p = pp.begin(); p != pp.end(); ++p)
pillars_pos.push_back(*p);
}
}
}
// for each pillar, check which layers it applies to
for (Points::const_iterator p = pillars_pos.begin(); p != pillars_pos.end(); ++p) {
SupportPillar pillar(*p);
bool object_hit = false;
// check layers top-down
for (int i = this->layers.size()-1; i >= 0; --i) {
// check whether point is void in this layer
if (!this->layers[i].slices.contains(*p)) {
// no slice contains the point, so it's in the void
if (pillar.top_layer > 0) {
// we have a pillar, so extend it
pillar.bottom_layer = i + this->config.raft_layers;
} else if (object_hit) {
// we don't have a pillar and we're below the object, so create one
pillar.top_layer = i + this->config.raft_layers;
}
} else {
if (pillar.top_layer > 0) {
// we have a pillar which is not needed anymore, so store it and initialize a new potential pillar
this->sm_pillars.push_back(pillar);
pillar = SupportPillar(*p);
}
object_hit = true;
}
}
if (pillar.top_layer > 0) this->sm_pillars.push_back(pillar);
}
}
// generate a solid raft if requested
// (do this after support material because we take support material shape into account)
if (this->config.raft_layers > 0) {
ExPolygons raft = this->layers.front().slices;
raft.insert(raft.end(), overhangs.begin(), overhangs.end()); // take support material into account
raft = offset_ex(raft, scale_(this->config.raft_offset));
for (int i = this->config.raft_layers; i >= 1; --i) {
this->layers.insert(this->layers.begin(), Layer(0, first_lh + lh * (i-1)));
this->layers.front().slices = raft;
}
// prepend total raft height to all sliced layers
for (int i = this->config.raft_layers; i < this->layers.size(); ++i)
this->layers[i].print_z += first_lh + lh * (this->config.raft_layers-1);
}
}
void
SLAPrint::write_svg(const std::string &outputfile) const
{
const Sizef3 size = this->bb.size();
const double support_material_radius = sm_pillars_radius();
FILE* f = fopen(outputfile.c_str(), "w");
fprintf(f,
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
"<svg width=\"%f\" height=\"%f\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:slic3r=\"http://slic3r.org/namespaces/slic3r\" viewport-fill=\"black\">\n"
"<!-- Generated using Slic3r %s http://slic3r.org/ -->\n"
, size.x, size.y, SLIC3R_VERSION);
for (size_t i = 0; i < this->layers.size(); ++i) {
const Layer &layer = this->layers[i];
fprintf(f,
"\t<g id=\"layer%zu\" slic3r:z=\"%0.4f\" slic3r:slice-z=\"%0.4f\" slic3r:layer-height=\"%0.4f\">\n", i,
layer.print_z,
layer.slice_z,
layer.print_z - (i == 0 ? 0 : this->layers[i-1].print_z)
);
if (layer.solid) {
const ExPolygons &slices = layer.slices.expolygons;
for (ExPolygons::const_iterator it = slices.begin(); it != slices.end(); ++it) {
std::string pd = this->_SVG_path_d(*it);
fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:area=\"%0.4f\" />\n",
pd.c_str(), "white", "black", "0", unscale(unscale(it->area()))
);
}
} else {
// Solid infill.
const ExPolygons &solid_infill = layer.solid_infill.expolygons;
for (ExPolygons::const_iterator it = solid_infill.begin(); it != solid_infill.end(); ++it) {
std::string pd = this->_SVG_path_d(*it);
fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"infill\" />\n",
pd.c_str(), "white", "black", "0"
);
}
// Generate perimeters.
for (ExtrusionEntitiesPtr::const_iterator it = layer.perimeters.entities.begin();
it != layer.perimeters.entities.end(); ++it) {
//std::string pd = this->_SVG_path_d(it->polygon());
}
}
// don't print support material in raft layers
if (i >= this->config.raft_layers) {
// look for support material pillars belonging to this layer
for (std::vector<SupportPillar>::const_iterator it = this->sm_pillars.begin(); it != this->sm_pillars.end(); ++it) {
if (!(it->top_layer >= i && it->bottom_layer <= i)) continue;
// generate a conic tip
float radius = fminf(
support_material_radius,
(it->top_layer - i + 1) * this->config.layer_height.value
);
fprintf(f,"\t\t<circle cx=\"%f\" cy=\"%f\" r=\"%f\" stroke-width=\"0\" fill=\"white\" slic3r:type=\"support\" />\n",
unscale(it->x) - this->bb.min.x,
size.y - (unscale(it->y) - this->bb.min.y),
radius
);
}
}
fprintf(f,"\t</g>\n");
}
fprintf(f,"</svg>\n");
}
coordf_t
SLAPrint::sm_pillars_radius() const
{
coordf_t radius = this->config.support_material_extrusion_width.get_abs_value(this->config.support_material_spacing)/2;
if (radius == 0) radius = this->config.support_material_spacing / 3; // auto
return radius;
}
std::string
SLAPrint::_SVG_path_d(const Polygon &polygon) const
{
const Sizef3 size = this->bb.size();
std::ostringstream d;
d << "M ";
for (Points::const_iterator p = polygon.points.begin(); p != polygon.points.end(); ++p) {
d << unscale(p->x) - this->bb.min.x << " ";
d << size.y - (unscale(p->y) - this->bb.min.y) << " "; // mirror Y coordinates as SVG uses downwards Y
}
d << "z";
return d.str();
}
std::string
SLAPrint::_SVG_path_d(const ExPolygon &expolygon) const
{
std::string pd;
const Polygons pp = expolygon;
for (Polygons::const_iterator mp = pp.begin(); mp != pp.end(); ++mp)
pd += this->_SVG_path_d(*mp) + " ";
return pd;
}
}
| #include "SLAPrint.hpp"
#include "ClipperUtils.hpp"
#include "ExtrusionEntity.hpp"
#include "Fill/FillBase.hpp"
#include "Geometry.hpp"
#include "Surface.hpp"
#include <iostream>
#include <cstdio>
namespace Slic3r {
void
SLAPrint::slice()
{
TriangleMesh mesh = this->model->mesh();
mesh.repair();
// align to origin taking raft into account
this->bb = mesh.bounding_box();
if (this->config.raft_layers > 0) {
this->bb.min.x -= this->config.raft_offset.value;
this->bb.min.y -= this->config.raft_offset.value;
this->bb.max.x += this->config.raft_offset.value;
this->bb.max.y += this->config.raft_offset.value;
}
mesh.translate(0, 0, -bb.min.z);
this->bb.translate(0, 0, -bb.min.z);
// if we are generating a raft, first_layer_height will not affect mesh slicing
const float lh = this->config.layer_height.value;
const float first_lh = this->config.first_layer_height.value;
// generate the list of Z coordinates for mesh slicing
// (we slice each layer at half of its thickness)
this->layers.clear();
{
const float first_slice_lh = (this->config.raft_layers > 0) ? lh : first_lh;
this->layers.push_back(Layer(first_slice_lh/2, first_slice_lh));
}
while (this->layers.back().print_z + lh/2 <= mesh.stl.stats.max.z) {
this->layers.push_back(Layer(this->layers.back().print_z + lh/2, this->layers.back().print_z + lh));
}
// perform slicing and generate layers
{
std::vector<float> slice_z;
for (size_t i = 0; i < this->layers.size(); ++i)
slice_z.push_back(this->layers[i].slice_z);
std::vector<ExPolygons> slices;
TriangleMeshSlicer(&mesh).slice(slice_z, &slices);
for (size_t i = 0; i < slices.size(); ++i)
this->layers[i].slices.expolygons = slices[i];
}
// generate infill
if (this->config.fill_density < 100) {
const float shell_thickness = this->config.get_abs_value("perimeter_extrusion_width", this->config.layer_height.value);
std::auto_ptr<Fill> fill = std::auto_ptr<Fill>(Fill::new_from_type(this->config.fill_pattern.value));
fill->bounding_box.merge(Point::new_scale(bb.min.x, bb.min.y));
fill->bounding_box.merge(Point::new_scale(bb.max.x, bb.max.y));
fill->spacing = this->config.get_abs_value("infill_extrusion_width", this->config.layer_height.value);
fill->angle = Geometry::deg2rad(this->config.fill_angle.value);
FillParams fill_params;
fill_params.density = this->config.fill_density.value/100;
ExtrusionPath templ(erInternalInfill);
templ.width = fill->spacing;
for (size_t i = 0; i < this->layers.size(); ++i) {
Layer &layer = this->layers[i];
// In order to detect what regions of this layer need to be solid,
// perform an intersection with layers within the requested shell thickness.
Polygons internal = layer.slices;
for (size_t j = 0; j < this->layers.size(); ++j) {
const Layer &other = this->layers[j];
if (abs(other.print_z - layer.print_z) > shell_thickness) continue;
if (j == 0 || j == this->layers.size()-1) {
internal.clear();
break;
} else if (i != j) {
internal = intersection(internal, other.slices);
if (internal.empty()) break;
}
}
// If we have no internal infill, just print the whole layer as a solid slice.
if (internal.empty()) continue;
layer.solid = false;
const Polygons infill = offset(layer.slices, -scale_(shell_thickness));
// Generate solid infill.
layer.solid_infill.append(diff_ex(infill, internal, true));
// Generate internal infill.
{
fill->layer_id = i;
fill->z = layer.print_z;
const ExPolygons internal_ex = intersection_ex(infill, internal);
for (ExPolygons::const_iterator it = internal_ex.begin(); it != internal_ex.end(); ++it) {
Polylines polylines = fill->fill_surface(Surface(stInternal, *it), fill_params);
layer.infill.append(polylines, templ);
}
}
// Generate perimeter(s).
{
const Polygons perimeters = offset(layer.slices, -scale_(shell_thickness)/2);
for (Polygons::const_iterator it = perimeters.begin(); it != perimeters.end(); ++it) {
ExtrusionPath ep(erPerimeter);
ep.polyline = *it;
ep.width = shell_thickness;
layer.perimeters.append(ExtrusionLoop(ep));
}
}
}
}
// generate support material
this->sm_pillars.clear();
ExPolygons overhangs;
if (this->config.support_material) {
// flatten and merge all the overhangs
{
Polygons pp;
for (std::vector<Layer>::const_iterator it = this->layers.begin()+1; it != this->layers.end(); ++it) {
Polygons oh = diff(it->slices, (it - 1)->slices);
pp.insert(pp.end(), oh.begin(), oh.end());
}
overhangs = union_ex(pp);
}
// generate points following the shape of each island
Points pillars_pos;
const coordf_t spacing = scale_(this->config.support_material_spacing);
const coordf_t radius = scale_(this->sm_pillars_radius());
for (ExPolygons::const_iterator it = overhangs.begin(); it != overhangs.end(); ++it) {
// leave a radius/2 gap between pillars and contour to prevent lateral adhesion
for (float inset = radius * 1.5;; inset += spacing) {
// inset according to the configured spacing
Polygons curr = offset(*it, -inset);
if (curr.empty()) break;
// generate points along the contours
for (Polygons::const_iterator pg = curr.begin(); pg != curr.end(); ++pg) {
Points pp = pg->equally_spaced_points(spacing);
for (Points::const_iterator p = pp.begin(); p != pp.end(); ++p)
pillars_pos.push_back(*p);
}
}
}
// for each pillar, check which layers it applies to
for (Points::const_iterator p = pillars_pos.begin(); p != pillars_pos.end(); ++p) {
SupportPillar pillar(*p);
bool object_hit = false;
// check layers top-down
for (int i = this->layers.size()-1; i >= 0; --i) {
// check whether point is void in this layer
if (!this->layers[i].slices.contains(*p)) {
// no slice contains the point, so it's in the void
if (pillar.top_layer > 0) {
// we have a pillar, so extend it
pillar.bottom_layer = i + this->config.raft_layers;
} else if (object_hit) {
// we don't have a pillar and we're below the object, so create one
pillar.top_layer = i + this->config.raft_layers;
}
} else {
if (pillar.top_layer > 0) {
// we have a pillar which is not needed anymore, so store it and initialize a new potential pillar
this->sm_pillars.push_back(pillar);
pillar = SupportPillar(*p);
}
object_hit = true;
}
}
if (pillar.top_layer > 0) this->sm_pillars.push_back(pillar);
}
}
// generate a solid raft if requested
// (do this after support material because we take support material shape into account)
if (this->config.raft_layers > 0) {
ExPolygons raft = this->layers.front().slices;
raft.insert(raft.end(), overhangs.begin(), overhangs.end()); // take support material into account
raft = offset_ex(raft, scale_(this->config.raft_offset));
for (int i = this->config.raft_layers; i >= 1; --i) {
this->layers.insert(this->layers.begin(), Layer(0, first_lh + lh * (i-1)));
this->layers.front().slices = raft;
}
// prepend total raft height to all sliced layers
for (int i = this->config.raft_layers; i < this->layers.size(); ++i)
this->layers[i].print_z += first_lh + lh * (this->config.raft_layers-1);
}
}
void
SLAPrint::write_svg(const std::string &outputfile) const
{
const Sizef3 size = this->bb.size();
const double support_material_radius = sm_pillars_radius();
FILE* f = fopen(outputfile.c_str(), "w");
fprintf(f,
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
"<svg width=\"%f\" height=\"%f\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:slic3r=\"http://slic3r.org/namespaces/slic3r\" viewport-fill=\"black\">\n"
"<!-- Generated using Slic3r %s http://slic3r.org/ -->\n"
, size.x, size.y, SLIC3R_VERSION);
for (size_t i = 0; i < this->layers.size(); ++i) {
const Layer &layer = this->layers[i];
fprintf(f,
"\t<g id=\"layer%zu\" slic3r:z=\"%0.4f\" slic3r:slice-z=\"%0.4f\" slic3r:layer-height=\"%0.4f\">\n", i,
layer.print_z,
layer.slice_z,
layer.print_z - (i == 0 ? 0 : this->layers[i-1].print_z)
);
if (layer.solid) {
const ExPolygons &slices = layer.slices.expolygons;
for (ExPolygons::const_iterator it = slices.begin(); it != slices.end(); ++it) {
std::string pd = this->_SVG_path_d(*it);
fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:area=\"%0.4f\" />\n",
pd.c_str(), "white", "black", "0", unscale(unscale(it->area()))
);
}
} else {
// Solid infill.
const ExPolygons &solid_infill = layer.solid_infill.expolygons;
for (ExPolygons::const_iterator it = solid_infill.begin(); it != solid_infill.end(); ++it) {
std::string pd = this->_SVG_path_d(*it);
fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"infill\" />\n",
pd.c_str(), "white", "black", "0"
);
}
// Generate perimeters.
for (ExtrusionEntitiesPtr::const_iterator it = layer.perimeters.entities.begin();
it != layer.perimeters.entities.end(); ++it) {
//std::string pd = this->_SVG_path_d(it->polygon());
}
}
// don't print support material in raft layers
if (i >= this->config.raft_layers) {
// look for support material pillars belonging to this layer
for (std::vector<SupportPillar>::const_iterator it = this->sm_pillars.begin(); it != this->sm_pillars.end(); ++it) {
if (!(it->top_layer >= i && it->bottom_layer <= i)) continue;
// generate a conic tip
float radius = fminf(
support_material_radius,
(it->top_layer - i + 1) * this->config.layer_height.value
);
fprintf(f,"\t\t<circle cx=\"%f\" cy=\"%f\" r=\"%f\" stroke-width=\"0\" fill=\"white\" slic3r:type=\"support\" />\n",
unscale(it->x) - this->bb.min.x,
size.y - (unscale(it->y) - this->bb.min.y),
radius
);
}
}
fprintf(f,"\t</g>\n");
}
fprintf(f,"</svg>\n");
}
coordf_t
SLAPrint::sm_pillars_radius() const
{
coordf_t radius = this->config.support_material_extrusion_width.get_abs_value(this->config.support_material_spacing)/2;
if (radius == 0) radius = this->config.support_material_spacing / 3; // auto
return radius;
}
std::string
SLAPrint::_SVG_path_d(const Polygon &polygon) const
{
const Sizef3 size = this->bb.size();
std::ostringstream d;
d << "M ";
for (Points::const_iterator p = polygon.points.begin(); p != polygon.points.end(); ++p) {
d << unscale(p->x) - this->bb.min.x << " ";
d << size.y - (unscale(p->y) - this->bb.min.y) << " "; // mirror Y coordinates as SVG uses downwards Y
}
d << "z";
return d.str();
}
std::string
SLAPrint::_SVG_path_d(const ExPolygon &expolygon) const
{
std::string pd;
const Polygons pp = expolygon;
for (Polygons::const_iterator mp = pp.begin(); mp != pp.end(); ++mp)
pd += this->_SVG_path_d(*mp) + " ";
return pd;
}
}
| Apply print bounding box for SLAPrint infill | Apply print bounding box for SLAPrint infill
| C++ | agpl-3.0 | xoan/Slic3r,mcilhargey/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,platsch/Slic3r,curieos/Slic3r,curieos/Slic3r,mcilhargey/Slic3r,xoan/Slic3r,tmotl/Slic3r,platsch/Slic3r,lordofhyphens/Slic3r,mcilhargey/Slic3r,lordofhyphens/Slic3r,pieis2pi/Slic3r,tmotl/Slic3r,alexrj/Slic3r,mcilhargey/Slic3r,alexrj/Slic3r,mcilhargey/Slic3r,xoan/Slic3r,alexrj/Slic3r,tmotl/Slic3r,pieis2pi/Slic3r,xoan/Slic3r,alexrj/Slic3r,curieos/Slic3r,xoan/Slic3r,tmotl/Slic3r,curieos/Slic3r,alexrj/Slic3r,lordofhyphens/Slic3r,platsch/Slic3r,tmotl/Slic3r,alexrj/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,platsch/Slic3r,pieis2pi/Slic3r,lordofhyphens/Slic3r,platsch/Slic3r,mcilhargey/Slic3r,curieos/Slic3r,lordofhyphens/Slic3r,xoan/Slic3r,platsch/Slic3r,mcilhargey/Slic3r,lordofhyphens/Slic3r,tmotl/Slic3r |
a9043125bf29eb370ee10f9857366cf1cee642ee | sdlwindow.cpp | sdlwindow.cpp | #include <iostream>
#include <sstream>
#include "SDL.h"
#include "SDL_gfxPrimitives.h"
#include "SDL_ttf.h"
#include "sdlwindow.h"
#include "misc/fpscounter.h"
#include "controller/sdlcontroller.h"
#include "resources/imageresource.h"
#include "resources/stringfontresource.h"
namespace Zabbr {
/**
* Public constructor for the SDL initialization exception.
*
* @param s The initialization error.
*/
SDLInitializationException::SDLInitializationException(std::string s)
: fError(s) {
}
/**
* Returns the error of the exception.
*
* @return The error of the exception.
*/
std::string SDLInitializationException::getError() {
return fError;
}
/**
* Public constructor.
*/
SDLWindow::SDLWindow() {
}
/**
* Open the window.
*
* @param xres The X resolution.
* @param yres The Y resolution.
* @param fs True if running in fullscreen, false if not.
*
* @throw An SDLInitializationException if initialization fails.
*/
void SDLWindow::open(int xres, int yres, bool fs) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
throw SDLInitializationException(SDL_GetError());
}
atexit(SDL_Quit);
screen = SDL_SetVideoMode(xres, yres, 32, SDL_RESIZABLE);
if (screen == NULL) {
throw SDLInitializationException(SDL_GetError());
}
if(TTF_Init() == -1) {
throw SDLInitializationException(TTF_GetError());
}
}
/**
* Close the window.
*/
void SDLWindow::close() {
if (screen)
SDL_FreeSurface(screen);
TTF_Quit();
}
/**
* Run the mainloop.
*
* @param controller The first controller to get control of what happens.
*/
void SDLWindow::run(VSDLController* controller) {
FPSCounter fpsCounter(500);
fController = controller;
SDL_Event event;
fRunning = true;
while (fRunning) {
while (fRunning && SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
fController->keyDown(event.key);
break;
case SDL_KEYUP:
fController->keyRelease(event.key);
break;
case SDL_MOUSEMOTION:
fController->mouseMotion(event.motion);
break;
case SDL_MOUSEBUTTONUP:
fController->mouseButton(event.button);
break;
case SDL_QUIT:
fController->requestQuit();
break;
case SDL_VIDEORESIZE:
screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_RESIZABLE);
break;
}
}
if (fOldController) {
delete fOldController;
fOldController = NULL;
}
if (fRunning) { // it is possible we quit when firing events.
drawRectangle(0, 0, screen->w, screen->h, 0, 0, 0);
fController->draw();
draw();
//SDL_Delay(1);
} else {
freeController(fController);
fController = NULL;
screen = NULL;
}
if (fpsCounter.frame()) {
std::stringstream ssWMCaption;
ssWMCaption << fpsCounter.fps();
std::string WMCaption;
ssWMCaption >> WMCaption;
WMCaption = "Space-Invadors " + WMCaption + " FPS";
SDL_WM_SetCaption(WMCaption.c_str(), "Icon Title");
}
SDL_Delay(1);
}
}
/**
* Updates the physical screen so it contains the same information as the screen buffer.
*/
void SDLWindow::draw() {
SDL_Flip(screen);
}
/**
* Close the current controller and pass control to the next controller.
*
* @param next The next controller. If 0 the window closes.
*/
void SDLWindow::closeController(VSDLController* next) {
if (next != NULL) {
fOldController = fController;
fController = next;
} else {
// We keep the old controller.
fRunning = false;
SDL_Quit();
}
}
/**
* Gives control back to the parent controller, and close the current controller.
*
* @param prev The parent controller.
*/
void SDLWindow::openParentController(VSDLController* prev) {
fOldController = fController;
fController = prev;
}
/**
* Opens a new controller, but keep the current controller active.
*
* @param c The new active controller.
*/
void SDLWindow::openController(VSDLController* c) {
fController = c;
}
/**
* Draws a surface on the window.
*
* @param surface The surface to draw.
* @param x The x coordinate on the screen.
* @param y The y coordinate on the screen.
*/
void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y) {
drawSurface(surface, x, y, 1.0);
}
/**
* Draws a surface on the window.
*
* @param surface The surface to draw.
* @param x The x coordinate on the screen.
* @param y The y coordinate on the screen.
* @param scale Scale factor of the surface. Not yet implemented.
*/
void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y, double scale) {
SDL_Rect src, dest;
src.x = 0;
src.y = 0;
src.w = surface->getWidth();
src.h = surface->getHeight();
dest.x = x;
dest.y = y;
dest.w = surface->getWidth() * scale;
dest.h = surface->getHeight() * scale;
SDL_BlitSurface(surface->getSurface(), &src, screen, &dest);
}
/**
* Draws a rectangle on the screen.
*
* @param x The x coordinate of the rectangle on the screen.
* @param y The y coordinate of the rectangle on the screen.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param r The red component of the color of the rectangle.
* @param g The green component of the color of the rectangle.
* @param b The blue component of the color of the rectangle.
*/
void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b) {
SDL_Rect dest;
dest.x = x;
dest.y = y;
dest.w = w;
dest.h = h;
SDL_FillRect(screen, &dest, SDL_MapRGB(screen->format, r, g, b));
}
/**
* Draws a transparant rectangle on the screen.
*
* @param x The x coordinate of the rectangle on the screen.
* @param y The y coordinate of the rectangle on the screen.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param r The red component of the color of the rectangle.
* @param g The green component of the color of the rectangle.
* @param b The blue component of the color of the rectangle.
* @param a The alpha-channel of the rectangle, 0.0 for completely transparant, 1.0 for opaque.
*/
void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b, double a) {
boxRGBA(screen, x, y, x + w, y + h, r, g, b, a*255);
}
/**
* Get the x-resolution of the window
*
* @return The X resolution (width) of the window.
*/
int SDLWindow::getXResolution() {
return screen->w;
}
/**
* Get the y-resolution of the window
*
* @return The Y resolution (height) of the window.
*/
int SDLWindow::getYResolution() {
return screen->h;
}
/**
* Free a controller and all of its parent controllers.
*
* @param c The controller to free.
*/
void SDLWindow::freeController(VSDLController* c) {
if (c->fParentController) {
freeController(c->fParentController);
}
delete c;
}
}
| #include <iostream>
#include <sstream>
#include "SDL.h"
#include "SDL_gfxPrimitives.h"
#include "SDL_ttf.h"
#include "sdlwindow.h"
#include "misc/fpscounter.h"
#include "controller/sdlcontroller.h"
#include "resources/imageresource.h"
#include "resources/stringfontresource.h"
namespace Zabbr {
/**
* Public constructor for the SDL initialization exception.
*
* @param s The initialization error.
*/
SDLInitializationException::SDLInitializationException(std::string s)
: fError(s) {
}
/**
* Returns the error of the exception.
*
* @return The error of the exception.
*/
std::string SDLInitializationException::getError() {
return fError;
}
/**
* Public constructor.
*/
SDLWindow::SDLWindow() {
}
/**
* Open the window.
*
* @param xres The X resolution.
* @param yres The Y resolution.
* @param fs True if running in fullscreen, false if not.
*
* @throw An SDLInitializationException if initialization fails.
*/
void SDLWindow::open(int xres, int yres, bool fs) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
throw SDLInitializationException(SDL_GetError());
}
atexit(SDL_Quit);
screen = SDL_SetVideoMode(xres, yres, 32, SDL_RESIZABLE);
if (screen == NULL) {
throw SDLInitializationException(SDL_GetError());
}
if(TTF_Init() == -1) {
throw SDLInitializationException(TTF_GetError());
}
}
/**
* Close the window.
*/
void SDLWindow::close() {
if (screen)
SDL_FreeSurface(screen);
TTF_Quit();
}
/**
* Run the mainloop.
*
* @param controller The first controller to get control of what happens.
*/
void SDLWindow::run(VSDLController* controller) {
FPSCounter fpsCounter(500);
fController = controller;
SDL_Event event;
fRunning = true;
while (fRunning) {
while (fRunning && SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
fController->keyDown(event.key);
break;
case SDL_KEYUP:
fController->keyRelease(event.key);
break;
case SDL_MOUSEMOTION:
fController->mouseMotion(event.motion);
break;
case SDL_MOUSEBUTTONUP:
fController->mouseButton(event.button);
break;
case SDL_QUIT:
fController->requestQuit();
break;
case SDL_VIDEORESIZE:
screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_RESIZABLE);
break;
}
}
if (fOldController) {
delete fOldController;
fOldController = NULL;
}
if (fRunning) { // it is possible we quit when firing events.
drawRectangle(0, 0, screen->w, screen->h, 0, 0, 0);
fController->draw();
draw();
SDL_Delay(1);
} else {
freeController(fController);
fController = NULL;
screen = NULL;
}
if (fpsCounter.frame()) {
std::stringstream ssWMCaption;
ssWMCaption << fpsCounter.fps();
std::string WMCaption;
ssWMCaption >> WMCaption;
WMCaption = "Space-Invadors " + WMCaption + " FPS";
SDL_WM_SetCaption(WMCaption.c_str(), "Icon Title");
}
}
}
/**
* Updates the physical screen so it contains the same information as the screen buffer.
*/
void SDLWindow::draw() {
SDL_Flip(screen);
}
/**
* Close the current controller and pass control to the next controller.
*
* @param next The next controller. If 0 the window closes.
*/
void SDLWindow::closeController(VSDLController* next) {
if (next != NULL) {
fOldController = fController;
fController = next;
} else {
// We keep the old controller.
fRunning = false;
SDL_Quit();
}
}
/**
* Gives control back to the parent controller, and close the current controller.
*
* @param prev The parent controller.
*/
void SDLWindow::openParentController(VSDLController* prev) {
fOldController = fController;
fController = prev;
}
/**
* Opens a new controller, but keep the current controller active.
*
* @param c The new active controller.
*/
void SDLWindow::openController(VSDLController* c) {
fController = c;
}
/**
* Draws a surface on the window.
*
* @param surface The surface to draw.
* @param x The x coordinate on the screen.
* @param y The y coordinate on the screen.
*/
void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y) {
drawSurface(surface, x, y, 1.0);
}
/**
* Draws a surface on the window.
*
* @param surface The surface to draw.
* @param x The x coordinate on the screen.
* @param y The y coordinate on the screen.
* @param scale Scale factor of the surface. Not yet implemented.
*/
void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y, double scale) {
SDL_Rect src, dest;
src.x = 0;
src.y = 0;
src.w = surface->getWidth();
src.h = surface->getHeight();
dest.x = x;
dest.y = y;
dest.w = surface->getWidth() * scale;
dest.h = surface->getHeight() * scale;
SDL_BlitSurface(surface->getSurface(), &src, screen, &dest);
}
/**
* Draws a rectangle on the screen.
*
* @param x The x coordinate of the rectangle on the screen.
* @param y The y coordinate of the rectangle on the screen.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param r The red component of the color of the rectangle.
* @param g The green component of the color of the rectangle.
* @param b The blue component of the color of the rectangle.
*/
void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b) {
SDL_Rect dest;
dest.x = x;
dest.y = y;
dest.w = w;
dest.h = h;
SDL_FillRect(screen, &dest, SDL_MapRGB(screen->format, r, g, b));
}
/**
* Draws a transparant rectangle on the screen.
*
* @param x The x coordinate of the rectangle on the screen.
* @param y The y coordinate of the rectangle on the screen.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param r The red component of the color of the rectangle.
* @param g The green component of the color of the rectangle.
* @param b The blue component of the color of the rectangle.
* @param a The alpha-channel of the rectangle, 0.0 for completely transparant, 1.0 for opaque.
*/
void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b, double a) {
boxRGBA(screen, x, y, x + w, y + h, r, g, b, a*255);
}
/**
* Get the x-resolution of the window
*
* @return The X resolution (width) of the window.
*/
int SDLWindow::getXResolution() {
return screen->w;
}
/**
* Get the y-resolution of the window
*
* @return The Y resolution (height) of the window.
*/
int SDLWindow::getYResolution() {
return screen->h;
}
/**
* Free a controller and all of its parent controllers.
*
* @param c The controller to free.
*/
void SDLWindow::freeController(VSDLController* c) {
if (c->fParentController) {
freeController(c->fParentController);
}
delete c;
}
}
| Fix timing issue in gamecontroller | Fix timing issue in gamecontroller
| C++ | bsd-3-clause | nathansamson/zabbr |
26bc601272f7f89bd38991541ac711d8a66a1d5b | src/hext/rule.cpp | src/hext/rule.cpp | #include "hext/rule.h"
#include "hext/match-tree.h"
namespace hext {
rule::rule(
const std::string& html_tag_name,
bool direct_descendant,
int max_capture_limit,
std::vector<attribute>&& attrs
)
: children(),
attributes(std::move(attrs)),
tag(html_tag_name),
is_direct_desc(false),
cap_limit(max_capture_limit),
match_count(0)
{
}
rule::rule(const rule& r)
: children(r.children),
attributes(r.attributes),
tag(r.tag),
is_direct_desc(r.is_direct_desc),
cap_limit(r.cap_limit),
match_count(0)
{
}
void rule::append_child(const rule& r, int level)
{
if( level > 1 && !this->children.empty() )
{
this->children.back().append_child(r, level - 1);
return;
}
this->children.push_back(r);
}
std::vector<rule>::size_type rule::children_size() const
{
return this->children.size();
}
std::string rule::tag_name() const
{
return this->tag;
}
bool rule::is_direct_descendant() const
{
return this->is_direct_desc;
}
int rule::capture_limit() const
{
return this->cap_limit;
}
void rule::match(const GumboNode * node, match_tree * m) const
{
if( !node || !m || node->type != GUMBO_NODE_ELEMENT )
return;
if( this->matches(node) )
{
this->match_count++;
m = m->append_child_and_own(this->capture(node));
for(const auto& c : this->children)
{
if( c.cap_limit == 0 || c.match_count < c.cap_limit )
c.match_node_children(node, m);
}
}
else
{
// if this rule is a direct descendant, and it didn't match,
// all child-rules cannot be matched either.
if( !this->is_direct_desc )
if( this->cap_limit == 0 || this->match_count < this->cap_limit )
this->match_node_children(node, m);
}
}
void rule::print(std::ostream& out, int indent_level) const
{
out << ( indent_level ? std::string(indent_level * 2, ' ') : "" )
<< "<"
<< this->tag
<< " ";
for(const auto& a : this->attributes)
{
a.print(out);
out << " ";
}
out << ">\n";
for(const auto& c : this->children)
c.print(out, indent_level + 1);
}
std::unique_ptr<match_tree>
rule::capture(const GumboNode * node) const
{
std::unique_ptr<match_tree> m_node = make_unique<match_tree>();
m_node->set_rule(this);
if( !node || node->type != GUMBO_NODE_ELEMENT )
return m_node;
for(const auto& attr : this->attributes)
if( attr.is_capture() )
m_node->append_match(attr.capture(node));
return m_node;
}
bool rule::matches(const GumboNode * node) const
{
if( !node || node->type != GUMBO_NODE_ELEMENT )
return false;
if( !this->tag.empty() &&
node->v.element.tag != gumbo_tag_enum(this->tag.c_str()) )
return false;
for(const auto& attr : this->attributes)
{
if( !attr.matches(node) )
return false;
}
return true;
}
void rule::match_node_children(const GumboNode * node, match_tree * m) const
{
if( !node || !m || node->type != GUMBO_NODE_ELEMENT )
return;
const GumboVector * node_children = &node->v.element.children;
for(unsigned int i = 0; i < node_children->length; ++i)
{
this->match(
static_cast<const GumboNode *>(node_children->data[i]),
m
);
}
}
} // namespace hext
| #include "hext/rule.h"
#include "hext/match-tree.h"
namespace hext {
rule::rule(
const std::string& html_tag_name,
bool direct_descendant,
int max_capture_limit,
std::vector<attribute>&& attrs
)
: children(),
attributes(std::move(attrs)),
tag(html_tag_name),
is_direct_desc(direct_descendant),
cap_limit(max_capture_limit),
match_count(0)
{
}
rule::rule(const rule& r)
: children(r.children),
attributes(r.attributes),
tag(r.tag),
is_direct_desc(r.is_direct_desc),
cap_limit(r.cap_limit),
match_count(0)
{
}
void rule::append_child(const rule& r, int level)
{
if( level > 1 && !this->children.empty() )
{
this->children.back().append_child(r, level - 1);
return;
}
this->children.push_back(r);
}
std::vector<rule>::size_type rule::children_size() const
{
return this->children.size();
}
std::string rule::tag_name() const
{
return this->tag;
}
bool rule::is_direct_descendant() const
{
return this->is_direct_desc;
}
int rule::capture_limit() const
{
return this->cap_limit;
}
void rule::match(const GumboNode * node, match_tree * m) const
{
if( !node || !m || node->type != GUMBO_NODE_ELEMENT )
return;
if( this->matches(node) )
{
this->match_count++;
m = m->append_child_and_own(this->capture(node));
for(const auto& c : this->children)
{
if( c.cap_limit == 0 || c.match_count < c.cap_limit )
c.match_node_children(node, m);
}
}
else
{
// if this rule is a direct descendant, and it didn't match,
// all child-rules cannot be matched either.
if( !this->is_direct_desc )
if( this->cap_limit == 0 || this->match_count < this->cap_limit )
this->match_node_children(node, m);
}
}
void rule::print(std::ostream& out, int indent_level) const
{
out << ( indent_level ? std::string(indent_level * 2, ' ') : "" )
<< "<"
<< this->tag
<< " ";
for(const auto& a : this->attributes)
{
a.print(out);
out << " ";
}
out << ">\n";
for(const auto& c : this->children)
c.print(out, indent_level + 1);
}
std::unique_ptr<match_tree>
rule::capture(const GumboNode * node) const
{
std::unique_ptr<match_tree> m_node = make_unique<match_tree>();
m_node->set_rule(this);
if( !node || node->type != GUMBO_NODE_ELEMENT )
return m_node;
for(const auto& attr : this->attributes)
if( attr.is_capture() )
m_node->append_match(attr.capture(node));
return m_node;
}
bool rule::matches(const GumboNode * node) const
{
if( !node || node->type != GUMBO_NODE_ELEMENT )
return false;
if( !this->tag.empty() &&
node->v.element.tag != gumbo_tag_enum(this->tag.c_str()) )
return false;
for(const auto& attr : this->attributes)
{
if( !attr.matches(node) )
return false;
}
return true;
}
void rule::match_node_children(const GumboNode * node, match_tree * m) const
{
if( !node || !m || node->type != GUMBO_NODE_ELEMENT )
return;
const GumboVector * node_children = &node->v.element.children;
for(unsigned int i = 0; i < node_children->length; ++i)
{
this->match(
static_cast<const GumboNode *>(node_children->data[i]),
m
);
}
}
} // namespace hext
| fix direct_descendant property not being set | fix direct_descendant property not being set
| C++ | apache-2.0 | thomastrapp/hext,thomastrapp/hext,thomastrapp/hext,thomastrapp/hext,thomastrapp/hext,thomastrapp/hext,thomastrapp/hext,thomastrapp/hext |
fd57696ea5b9328afecbc38d33ec9caa867d3e1e | examples/StandaloneModularDevice/Callbacks.cpp | examples/StandaloneModularDevice/Callbacks.cpp | // ----------------------------------------------------------------------------
// Callbacks.cpp
//
//
// Authors:
// Peter Polidoro [email protected]
// ----------------------------------------------------------------------------
#include "Callbacks.h"
namespace callbacks
{
// Callbacks must be non-blocking (avoid 'delay')
//
// modular_server.getParameterValue must be cast to either:
// const char*
// long
// double
// bool
// ArduinoJson::JsonArray&
// ArduinoJson::JsonObject&
//
// For more info read about ArduinoJson parsing https://github.com/janelia-arduino/ArduinoJson
//
// modular_server.getSavedVariableValue type must match the saved variable default type
// modular_server.setSavedVariableValue type must match the saved variable default type
ModularDevice::ModularServer& modular_server = controller.getModularServer();
void executeStandaloneCallbackCallback()
{
controller.executeStandaloneCallback();
}
void getDspVar1Callback()
{
int value = controller.getDspVar1();
modular_server.writeResultToResponse(value);
}
void setDspVar1Callback()
{
long value = modular_server.getParameterValue(constants::dsp_var1_parameter_name);
controller.setDspVar1(value);
}
void getIntVar1Callback()
{
uint8_t value = controller.getIntVar1();
modular_server.writeResultToResponse(value);
}
void setIntVar1Callback()
{
long value = modular_server.getParameterValue(constants::int_var1_parameter_name);
controller.setIntVar1(value);
}
void getIntVar2Callback()
{
uint8_t value = controller.getIntVar2();
modular_server.writeResultToResponse(value);
}
void setIntVar2Callback()
{
long value = modular_server.getParameterValue(constants::int_var2_parameter_name);
controller.setIntVar2(value);
}
// Standalone Callbacks
void addIntVar1ToDspVar1Callback()
{
int dis_var1 = controller.getDspVar1();
int int_var1 = controller.getIntVar1();
controller.setDspVar1(dis_var1+int_var1);
}
void subIntVar2FromDspVar1Callback()
{
int dis_var1 = controller.getDspVar1();
int int_var2 = controller.getIntVar2();
controller.setDspVar1(dis_var1-int_var2);
}
}
| // ----------------------------------------------------------------------------
// Callbacks.cpp
//
//
// Authors:
// Peter Polidoro [email protected]
// ----------------------------------------------------------------------------
#include "Callbacks.h"
namespace callbacks
{
ModularDevice::ModularServer& modular_server = controller.getModularServer();
void executeStandaloneCallbackCallback()
{
controller.executeStandaloneCallback();
}
void getDspVar1Callback()
{
int value = controller.getDspVar1();
modular_server.writeResultToResponse(value);
}
void setDspVar1Callback()
{
long value = modular_server.getParameterValue(constants::dsp_var1_parameter_name);
controller.setDspVar1(value);
}
void getIntVar1Callback()
{
uint8_t value = controller.getIntVar1();
modular_server.writeResultToResponse(value);
}
void setIntVar1Callback()
{
long value = modular_server.getParameterValue(constants::int_var1_parameter_name);
controller.setIntVar1(value);
}
void getIntVar2Callback()
{
uint8_t value = controller.getIntVar2();
modular_server.writeResultToResponse(value);
}
void setIntVar2Callback()
{
long value = modular_server.getParameterValue(constants::int_var2_parameter_name);
controller.setIntVar2(value);
}
// Standalone Callbacks
void addIntVar1ToDspVar1Callback()
{
int dis_var1 = controller.getDspVar1();
int int_var1 = controller.getIntVar1();
controller.setDspVar1(dis_var1+int_var1);
}
void subIntVar2FromDspVar1Callback()
{
int dis_var1 = controller.getDspVar1();
int int_var2 = controller.getIntVar2();
controller.setDspVar1(dis_var1-int_var2);
}
}
| Remove spurious comments | Remove spurious comments
| C++ | bsd-3-clause | JaneliaSciComp/arduino_standalone_interface,janelia-arduino/arduino_standalone_interface,peterpolidoro/arduino_standalone_interface |
c17a113eea230c21a1a8f4c4c086721ff59130da | folly/experimental/AsymmetricMemoryBarrier.cpp | folly/experimental/AsymmetricMemoryBarrier.cpp | /*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AsymmetricMemoryBarrier.h"
#include <folly/Exception.h>
#include <folly/Indestructible.h>
#include <folly/portability/SysMembarrier.h>
#include <folly/portability/SysMman.h>
#include <mutex>
namespace folly {
namespace {
struct DummyPageCreator {
DummyPageCreator() {
get();
}
static void* get() {
static auto ptr =
kIsLinux && !detail::sysMembarrierAvailable() ? create() : nullptr;
return ptr;
}
private:
static void* create() {
auto ptr = mmap(nullptr, 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
checkUnixError(reinterpret_cast<uintptr_t>(ptr), "mmap");
// Lock the memory so it can't get paged out. If it gets paged out, changing
// its protection won't accomplish anything.
auto r = mlock(ptr, 1);
checkUnixError(r, "mlock");
return ptr;
}
};
// Make sure dummy page is always initialized before shutdown
DummyPageCreator dummyPageCreator;
void mprotectMembarrier() {
auto dummyPage = dummyPageCreator.get();
// This function is required to be safe to call on shutdown,
// so we must leak the mutex.
static Indestructible<std::mutex> mprotectMutex;
std::lock_guard<std::mutex> lg(*mprotectMutex);
int r = 0;
r = mprotect(dummyPage, 1, PROT_READ | PROT_WRITE);
checkUnixError(r, "mprotect");
r = mprotect(dummyPage, 1, PROT_READ);
checkUnixError(r, "mprotect");
}
}
void asymmetricHeavyBarrier() {
if (kIsLinux) {
static const bool useSysMembarrier = detail::sysMembarrierAvailable();
if (useSysMembarrier) {
auto r = detail::sysMembarrier();
checkUnixError(r, "membarrier");
} else {
mprotectMembarrier();
}
} else {
std::atomic_thread_fence(std::memory_order_seq_cst);
}
}
}
| /*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AsymmetricMemoryBarrier.h"
#include <folly/Exception.h>
#include <folly/Indestructible.h>
#include <folly/portability/SysMembarrier.h>
#include <folly/portability/SysMman.h>
#include <mutex>
namespace folly {
namespace {
struct DummyPageCreator {
DummyPageCreator() {
get();
}
static void* get() {
static auto ptr =
kIsLinux && !detail::sysMembarrierAvailable() ? create() : nullptr;
return ptr;
}
private:
static void* create() {
auto ptr = mmap(nullptr, 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
checkUnixError(reinterpret_cast<uintptr_t>(ptr), "mmap");
// Optimistically try to lock the page so it stays resident. Could make
// the heavy barrier faster.
auto r = mlock(ptr, 1);
if (r != 0) {
// Do nothing.
}
return ptr;
}
};
// Make sure dummy page is always initialized before shutdown.
DummyPageCreator dummyPageCreator;
void mprotectMembarrier() {
auto dummyPage = dummyPageCreator.get();
// This function is required to be safe to call on shutdown,
// so we must leak the mutex.
static Indestructible<std::mutex> mprotectMutex;
std::lock_guard<std::mutex> lg(*mprotectMutex);
int r = 0;
// We want to downgrade the page while it is resident. To do that, it must
// first be upgraded and forced to be resident.
r = mprotect(dummyPage, 1, PROT_READ | PROT_WRITE);
checkUnixError(r, "mprotect");
// Force the page to be resident. If it is already resident, almost no-op.
*static_cast<char*>(dummyPage) = 0;
// Downgrade the page. Forces a memory barrier in every core running any
// of the process's threads. On a sane platform.
r = mprotect(dummyPage, 1, PROT_READ);
checkUnixError(r, "mprotect");
}
}
void asymmetricHeavyBarrier() {
if (kIsLinux) {
static const bool useSysMembarrier = detail::sysMembarrierAvailable();
if (useSysMembarrier) {
auto r = detail::sysMembarrier();
checkUnixError(r, "membarrier");
} else {
mprotectMembarrier();
}
} else {
std::atomic_thread_fence(std::memory_order_seq_cst);
}
}
}
| Make the mprotect variant of asymmetricHeavyBarrier work when mlock fails | Make the mprotect variant of asymmetricHeavyBarrier work when mlock fails
Summary: [Folly] Make the `mprotect` variant of `asymmetricHeavyBarrier` work when `mlock` fails.
Reviewed By: djwatson
Differential Revision: D3585948
fbshipit-source-id: c3a46884434b7f9da9caa9cf203573f9e3ce7444
| C++ | apache-2.0 | mqeizi/folly,Orvid/folly,rklabs/folly,facebook/folly,floxard/folly,mqeizi/folly,facebook/folly,rklabs/folly,floxard/folly,rklabs/folly,charsyam/folly,rklabs/folly,Orvid/folly,facebook/folly,facebook/folly,mqeizi/folly,charsyam/folly,Orvid/folly,mqeizi/folly,Orvid/folly,facebook/folly,mqeizi/folly,Orvid/folly,charsyam/folly,floxard/folly,floxard/folly,rklabs/folly,floxard/folly,charsyam/folly |
580502a72c43ab2d9740192d1e95ea94db592746 | examples/platform/ameba/ota/OTAInitializer.cpp | examples/platform/ameba/ota/OTAInitializer.cpp | /*
*
* Copyright (c) 2022 Project CHIP Authors
*
* 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 "OTAInitializer.h"
#include "app/clusters/ota-requestor/DefaultOTARequestorStorage.h"
#include <app/clusters/ota-requestor/BDXDownloader.h>
#include <app/clusters/ota-requestor/DefaultOTARequestor.h>
#include <app/clusters/ota-requestor/DefaultOTARequestorDriver.h>
#include <app/clusters/ota-requestor/DefaultOTARequestorUserConsent.h>
#include <app/clusters/ota-requestor/ExtendedOTARequestorDriver.h>
#include <platform/Ameba/AmebaOTAImageProcessor.h>
using namespace chip;
using namespace chip::DeviceLayer;
namespace {
DefaultOTARequestor gRequestorCore;
DefaultOTARequestorStorage gRequestorStorage;
ExtendedOTARequestorDriver gRequestorUser;
BDXDownloader gDownloader;
AmebaOTAImageProcessor gImageProcessor;
chip::ota::DefaultOTARequestorUserConsent gUserConsentProvider;
static chip::ota::UserConsentState gUserConsentState = chip::ota::UserConsentState::kGranted;
} // namespace
extern "C" void amebaQueryImageCmdHandler()
{
ChipLogProgress(DeviceLayer, "Calling amebaQueryImageCmdHandler");
PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->TriggerImmediateQuery(); });
}
extern "C" void amebaApplyUpdateCmdHandler()
{
ChipLogProgress(DeviceLayer, "Calling amebaApplyUpdateCmdHandler");
PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->ApplyUpdate(); });
}
void OTAInitializer::InitOTARequestor(void)
{
SetRequestorInstance(&gRequestorCore);
gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage());
// Set server instance used for session establishment
gRequestorCore.Init(chip::Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader);
gImageProcessor.SetOTADownloader(&gDownloader);
// Connect the Downloader and Image Processor objects
gDownloader.SetImageProcessorDelegate(&gImageProcessor);
gRequestorUser.Init(&gRequestorCore, &gImageProcessor);
if (gUserConsentState != chip::ota::UserConsentState::kUnknown)
{
gUserConsentProvider.SetUserConsentState(gUserConsentState);
gRequestorUser.SetUserConsentDelegate(&gUserConsentProvider);
}
}
| /*
*
* Copyright (c) 2022 Project CHIP Authors
*
* 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 "OTAInitializer.h"
#include "app/clusters/ota-requestor/DefaultOTARequestorStorage.h"
#include <app/clusters/ota-requestor/BDXDownloader.h>
#include <app/clusters/ota-requestor/DefaultOTARequestor.h>
#include <app/clusters/ota-requestor/DefaultOTARequestorDriver.h>
#include <platform/Ameba/AmebaOTAImageProcessor.h>
using namespace chip;
using namespace chip::DeviceLayer;
namespace {
DefaultOTARequestor gRequestorCore;
DefaultOTARequestorStorage gRequestorStorage;
DefaultOTARequestorDriver gRequestorUser;
BDXDownloader gDownloader;
AmebaOTAImageProcessor gImageProcessor;
} // namespace
extern "C" void amebaQueryImageCmdHandler()
{
ChipLogProgress(DeviceLayer, "Calling amebaQueryImageCmdHandler");
PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->TriggerImmediateQuery(); });
}
extern "C" void amebaApplyUpdateCmdHandler()
{
ChipLogProgress(DeviceLayer, "Calling amebaApplyUpdateCmdHandler");
PlatformMgr().ScheduleWork([](intptr_t) { GetRequestorInstance()->ApplyUpdate(); });
}
void OTAInitializer::InitOTARequestor(void)
{
SetRequestorInstance(&gRequestorCore);
gRequestorStorage.Init(chip::Server::GetInstance().GetPersistentStorage());
// Set server instance used for session establishment
gRequestorCore.Init(chip::Server::GetInstance(), gRequestorStorage, gRequestorUser, gDownloader);
gImageProcessor.SetOTADownloader(&gDownloader);
// Connect the Downloader and Image Processor objects
gDownloader.SetImageProcessorDelegate(&gImageProcessor);
gRequestorUser.Init(&gRequestorCore, &gImageProcessor);
}
| Remove user consent (#22661) | [OTA] Remove user consent (#22661)
- According to spec, RequestorCanConsent should be 0 if device do not support userconsent | C++ | apache-2.0 | project-chip/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip |
72c8140d6f5945924dfab7417a98f51b23f3424e | src/vnsw/agent/vrouter/ksync/linux/vnswif_listener.cc | src/vnsw/agent/vrouter/ksync/linux/vnswif_listener.cc | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <assert.h>
#include <bits/sockaddr.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <ifaddrs.h>
#include <base/logging.h>
#include <base/util.h>
#include <cmn/agent_cmn.h>
#include <init/agent_param.h>
#include <cfg/cfg_init.h>
#include <oper/route_common.h>
#include <oper/mirror_table.h>
#include <ksync/ksync_index.h>
#include <vrouter/ksync/interface_ksync.h>
#include "vnswif_listener.h"
VnswInterfaceListenerLinux::VnswInterfaceListenerLinux(Agent *agent) :
VnswInterfaceListenerBase(agent) {
}
VnswInterfaceListenerLinux::~VnswInterfaceListenerLinux() {
}
int VnswInterfaceListenerLinux::CreateSocket() {
int s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
if (s < 0) {
LOG(ERROR, "Error <" << errno << ": " << strerror(errno) <<
"> creating socket");
assert(0);
}
/* Bind to netlink socket */
struct sockaddr_nl addr;
memset (&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_groups = (RTMGRP_IPV4_ROUTE | RTMGRP_LINK | RTMGRP_IPV4_IFADDR);
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOG(ERROR, "Error <" << errno << ": " << strerror(errno) <<
"> binding to netlink address family");
assert(0);
}
return s;
}
void VnswInterfaceListenerLinux::SyncCurrentState() {
/* Fetch Links from kernel syncronously, to allow dump request for routes
* to go through fine
*/
InitNetlinkScan(RTM_GETLINK, ++seqno_);
/* Fetch routes from kernel asyncronously and update the gateway-id */
InitNetlinkScan(RTM_GETADDR, ++seqno_);
/* Fetch routes from kernel asyncronously and update the gateway-id */
InitNetlinkScan(RTM_GETROUTE, ++seqno_);
}
// Initiate netlink scan based on type and flags
void
VnswInterfaceListenerLinux::InitNetlinkScan(uint32_t type, uint32_t seqno) {
struct nlmsghdr *nlh;
const uint32_t buf_size = VnswInterfaceListenerLinux::kMaxBufferSize;
memset(tx_buf_, 0, buf_size);
nlh = (struct nlmsghdr *)tx_buf_;
/* Fill in the nlmsg header */
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
nlh->nlmsg_type = type;
// The message is a request for dump.
nlh->nlmsg_flags = (NLM_F_DUMP | NLM_F_REQUEST);
nlh->nlmsg_seq = seqno;
struct rtgenmsg *rt_gen = (struct rtgenmsg *) NLMSG_DATA (nlh);
rt_gen->rtgen_family = AF_PACKET;
boost::system::error_code ec;
sock_.send(boost::asio::buffer(nlh,nlh->nlmsg_len), 0, ec);
assert(ec.value() == 0);
uint8_t read_buf[buf_size];
/*
* Wait/Read the response for dump request, linux kernel doesn't handle
* dump request if response for previous dump request is not complete.
*/
int end = 0;
while (end == 0) {
memset(read_buf, 0, buf_size);
std::size_t len = sock_.receive(boost::asio::buffer(read_buf,
buf_size), 0, ec);
assert(ec.value() == 0);
struct nlmsghdr *nl = (struct nlmsghdr *)read_buf;
end = NlMsgDecode(nl, len, seqno);
}
}
void VnswInterfaceListenerLinux::RegisterAsyncReadHandler() {
read_buf_ = new uint8_t[kMaxBufferSize];
sock_.async_receive(boost::asio::buffer(read_buf_, kMaxBufferSize),
boost::bind(&VnswInterfaceListenerLinux::ReadHandler, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void VnswInterfaceListenerLinux::ReadHandler(
const boost::system::error_code &error, std::size_t len) {
struct nlmsghdr *nlh;
if (error == 0) {
nlh = (struct nlmsghdr *)read_buf_;
NlMsgDecode(nlh, len, -1);
} else {
LOG(ERROR, "Error < : " << error.message() <<
"> reading packet on netlink sock");
}
if (read_buf_) {
delete [] read_buf_;
read_buf_ = NULL;
}
RegisterAsyncReadHandler();
}
/****************************************************************************
* Link Local route event handler
****************************************************************************/
int VnswInterfaceListenerLinux::AddAttr(uint8_t *buff, int type, void *data, int alen) {
struct nlmsghdr *n = (struct nlmsghdr *)buff;
int len = RTA_LENGTH(alen);
if (NLMSG_ALIGN(n->nlmsg_len) + len > VnswInterfaceListenerLinux::kMaxBufferSize)
return -1;
struct rtattr *rta = (struct rtattr*)(((char*)n)+NLMSG_ALIGN(n->nlmsg_len));
rta->rta_type = type;
rta->rta_len = len;
memcpy(RTA_DATA(rta), data, alen);
n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len;
return 0;
}
void VnswInterfaceListenerLinux::UpdateLinkLocalRoute(const Ip4Address &addr,
bool del_rt) {
struct nlmsghdr *nlh;
struct rtmsg *rtm;
uint32_t ipaddr;
memset(tx_buf_, 0, kMaxBufferSize);
nlh = (struct nlmsghdr *) tx_buf_;
rtm = (struct rtmsg *) NLMSG_DATA (nlh);
/* Fill in the nlmsg header*/
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
if (del_rt) {
nlh->nlmsg_type = RTM_DELROUTE;
nlh->nlmsg_flags = NLM_F_REQUEST;
} else {
nlh->nlmsg_type = RTM_NEWROUTE;
nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE;
}
nlh->nlmsg_seq = ++seqno_;
rtm = (struct rtmsg *) NLMSG_DATA (nlh);
rtm->rtm_table = RT_TABLE_MAIN;
rtm->rtm_family = AF_INET;
rtm->rtm_type = RTN_UNICAST;
rtm->rtm_protocol = kVnswRtmProto;
rtm->rtm_scope = RT_SCOPE_LINK;
rtm->rtm_dst_len = 32;
ipaddr = RT_TABLE_MAIN;
AddAttr(tx_buf_, RTA_TABLE, (void *) &ipaddr, 4);
ipaddr = htonl(addr.to_ulong());
AddAttr(tx_buf_, RTA_DST, (void *) &ipaddr, 4);
int if_index = if_nametoindex(agent_->vhost_interface_name().c_str());
AddAttr(tx_buf_, RTA_OIF, (void *) &if_index, 4);
boost::system::error_code ec;
sock_.send(boost::asio::buffer(nlh,nlh->nlmsg_len), 0, ec);
assert(ec.value() == 0);
}
/****************************************************************************
* Netlink message handlers
* Decodes netlink messages and enqueues events to revent_queue_
****************************************************************************/
string VnswInterfaceListenerLinux::NetlinkTypeToString(uint32_t type) {
switch (type) {
case NLMSG_DONE:
return "NLMSG_DONE";
case RTM_NEWADDR:
return "RTM_NEWADDR";
case RTM_DELADDR:
return "RTM_DELADDR";
case RTM_NEWROUTE:
return "RTM_NEWROUTE";
case RTM_DELROUTE:
return "RTM_DELROUTE";
case RTM_NEWLINK:
return "RTM_NEWLINK";
case RTM_DELLINK:
return "RTM_DELLINK";
default:
break;
}
std::stringstream str;
str << "UNHANDLED <" << type << ">";
return str.str();
}
VnswInterfaceListenerBase::Event *
VnswInterfaceListenerLinux::HandleNetlinkRouteMsg(struct nlmsghdr *nlh) {
struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA (nlh);
if (rtm->rtm_family != AF_INET || rtm->rtm_table != RT_TABLE_MAIN
|| rtm->rtm_type != RTN_UNICAST || rtm->rtm_scope != RT_SCOPE_LINK) {
LOG(DEBUG, "Ignoring Netlink route with family "
<< (uint32_t)rtm->rtm_family
<< " table " << (uint32_t)rtm->rtm_table
<< " type " << (uint32_t)rtm->rtm_type
<< " scope " << (uint32_t)rtm->rtm_family);
return NULL;
}
int oif = -1;
uint32_t dst_ip = 0;
uint32_t gw_ip = 0;
/* Get the route atttibutes len */
int rtl = RTM_PAYLOAD(nlh);
/* Loop through all attributes */
for (struct rtattr *rth = (struct rtattr *) RTM_RTA(rtm);
RTA_OK(rth, rtl); rth = RTA_NEXT(rth, rtl)) {
/* Get the gateway (Next hop) */
if (rth->rta_type == RTA_DST) {
dst_ip = *((int *)RTA_DATA(rth));
}
if (rth->rta_type == RTA_GATEWAY) {
gw_ip = *((int *)RTA_DATA(rth));
}
if (rth->rta_type == RTA_OIF) {
oif = *((int *)RTA_DATA(rth));
}
}
if (oif == -1) {
return NULL;
}
char name[IFNAMSIZ];
if_indextoname(oif, name);
Ip4Address dst_addr((unsigned long)ntohl(dst_ip));
Ip4Address gw_addr((unsigned long)ntohl(gw_ip));
LOG(DEBUG, "Handle netlink route message "
<< NetlinkTypeToString(nlh->nlmsg_type)
<< " : " << dst_addr.to_string() << "/" << rtm->rtm_dst_len
<< " Interface " << name << " GW " << gw_addr.to_string());
Event::Type type;
if (nlh->nlmsg_type == RTM_DELROUTE) {
type = Event::DEL_ROUTE;
} else {
type = Event::ADD_ROUTE;
}
return new Event(type, dst_addr, rtm->rtm_dst_len, name, gw_addr,
rtm->rtm_protocol, rtm->rtm_flags);
}
VnswInterfaceListenerBase::Event *
VnswInterfaceListenerLinux::HandleNetlinkIntfMsg(struct nlmsghdr *nlh) {
/* Get the atttibutes len */
int rtl = RTM_PAYLOAD(nlh);
const char *port_name = NULL;
struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA (nlh);
/* Loop through all attributes */
for (struct rtattr *rth = IFLA_RTA(ifi); RTA_OK(rth, rtl);
rth = RTA_NEXT(rth, rtl)) {
/* Get the interface name */
if (rth->rta_type == IFLA_IFNAME) {
port_name = (char *) RTA_DATA(rth);
}
}
assert(port_name != NULL);
LOG(DEBUG, "Handle netlink interface message "
<< NetlinkTypeToString(nlh->nlmsg_type)
<< " for interface " << port_name << " flags " << ifi->ifi_flags);
Event::Type type;
if (nlh->nlmsg_type == RTM_DELLINK) {
type = Event::DEL_INTERFACE;
} else {
type = Event::ADD_INTERFACE;
}
return new Event(type, port_name, ifi->ifi_flags);
}
VnswInterfaceListenerBase::Event *
VnswInterfaceListenerLinux::HandleNetlinkAddrMsg(struct nlmsghdr *nlh) {
struct ifaddrmsg *ifa = (struct ifaddrmsg *) NLMSG_DATA (nlh);
// Get interface name from os-index
char name[IFNAMSIZ];
if_indextoname(ifa->ifa_index, name);
LOG(DEBUG, "Handle netlink address message "
<< NetlinkTypeToString(nlh->nlmsg_type) << " for interface " << name);
uint32_t ipaddr = 0;
int rtl = IFA_PAYLOAD(nlh);
for (struct rtattr *rth = IFA_RTA(ifa); rtl && RTA_OK(rth, rtl);
rth = RTA_NEXT(rth,rtl)) {
if (rth->rta_type != IFA_LOCAL) {
continue;
}
ipaddr = ntohl(* ((uint32_t *)RTA_DATA(rth)));
}
if (ipaddr == 0)
return NULL;
assert(ipaddr != 0);
Event::Type type;
if (nlh->nlmsg_type == RTM_DELADDR) {
type = Event::DEL_ADDR;
} else {
type = Event::ADD_ADDR;
}
return new Event(type, name, Ip4Address(ipaddr), ifa->ifa_prefixlen,
ifa->ifa_flags);
}
int VnswInterfaceListenerLinux::NlMsgDecode(struct nlmsghdr *nl,
std::size_t len, uint32_t seq_no) {
Event *event = NULL;
struct nlmsghdr *nlh = nl;
for (; (NLMSG_OK(nlh, len)); nlh = NLMSG_NEXT(nlh, len)) {
switch (nlh->nlmsg_type) {
case NLMSG_DONE:
if (nlh->nlmsg_seq == seq_no) {
return 1;
}
return 0;
case RTM_NEWADDR:
case RTM_DELADDR:
event = HandleNetlinkAddrMsg(nlh);
break;
case RTM_NEWROUTE:
case RTM_DELROUTE:
event = HandleNetlinkRouteMsg(nlh);
break;
case RTM_NEWLINK:
case RTM_DELLINK:
event = HandleNetlinkIntfMsg(nlh);
break;
default:
LOG(DEBUG, "VnswInterfaceListenerLinux got message : "
<< NetlinkTypeToString(nlh->nlmsg_type));
break;
}
if (event) {
revent_queue_->Enqueue(event);
}
}
return 0;
}
| /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <assert.h>
#include <bits/sockaddr.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <ifaddrs.h>
#include <base/logging.h>
#include <base/util.h>
#include <cmn/agent_cmn.h>
#include <init/agent_param.h>
#include <cfg/cfg_init.h>
#include <oper/route_common.h>
#include <oper/mirror_table.h>
#include <ksync/ksync_index.h>
#include <vrouter/ksync/interface_ksync.h>
#include "vnswif_listener.h"
VnswInterfaceListenerLinux::VnswInterfaceListenerLinux(Agent *agent) :
VnswInterfaceListenerBase(agent) {
}
VnswInterfaceListenerLinux::~VnswInterfaceListenerLinux() {
}
int VnswInterfaceListenerLinux::CreateSocket() {
int s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
if (s < 0) {
LOG(ERROR, "Error <" << errno << ": " << strerror(errno) <<
"> creating socket");
assert(0);
}
/* Bind to netlink socket */
struct sockaddr_nl addr;
memset (&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_groups = (RTMGRP_IPV4_ROUTE | RTMGRP_LINK | RTMGRP_IPV4_IFADDR);
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOG(ERROR, "Error <" << errno << ": " << strerror(errno) <<
"> binding to netlink address family");
assert(0);
}
return s;
}
void VnswInterfaceListenerLinux::SyncCurrentState() {
/* Fetch Links from kernel syncronously, to allow dump request for routes
* to go through fine
*/
InitNetlinkScan(RTM_GETLINK, ++seqno_);
/* Fetch routes from kernel asyncronously and update the gateway-id */
InitNetlinkScan(RTM_GETADDR, ++seqno_);
/* Fetch routes from kernel asyncronously and update the gateway-id */
InitNetlinkScan(RTM_GETROUTE, ++seqno_);
}
// Initiate netlink scan based on type and flags
void
VnswInterfaceListenerLinux::InitNetlinkScan(uint32_t type, uint32_t seqno) {
struct nlmsghdr *nlh;
const uint32_t buf_size = VnswInterfaceListenerLinux::kMaxBufferSize;
memset(tx_buf_, 0, buf_size);
nlh = (struct nlmsghdr *)tx_buf_;
/* Fill in the nlmsg header */
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg));
nlh->nlmsg_type = type;
// The message is a request for dump.
nlh->nlmsg_flags = (NLM_F_DUMP | NLM_F_REQUEST);
nlh->nlmsg_seq = seqno;
struct rtgenmsg *rt_gen = (struct rtgenmsg *) NLMSG_DATA (nlh);
rt_gen->rtgen_family = AF_PACKET;
boost::system::error_code ec;
sock_.send(boost::asio::buffer(nlh,nlh->nlmsg_len), 0, ec);
assert(ec.value() == 0);
uint8_t read_buf[buf_size];
/*
* Wait/Read the response for dump request, linux kernel doesn't handle
* dump request if response for previous dump request is not complete.
*/
int end = 0;
while (end == 0) {
memset(read_buf, 0, buf_size);
std::size_t len = sock_.receive(boost::asio::buffer(read_buf,
buf_size), 0, ec);
assert(ec.value() == 0);
struct nlmsghdr *nl = (struct nlmsghdr *)read_buf;
end = NlMsgDecode(nl, len, seqno);
}
}
void VnswInterfaceListenerLinux::RegisterAsyncReadHandler() {
read_buf_ = new uint8_t[kMaxBufferSize];
sock_.async_receive(boost::asio::buffer(read_buf_, kMaxBufferSize),
boost::bind(&VnswInterfaceListenerLinux::ReadHandler, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void VnswInterfaceListenerLinux::ReadHandler(
const boost::system::error_code &error, std::size_t len) {
struct nlmsghdr *nlh;
if (error == 0) {
nlh = (struct nlmsghdr *)read_buf_;
NlMsgDecode(nlh, len, -1);
} else {
LOG(ERROR, "Error < : " << error.message() <<
"> reading packet on netlink sock");
}
if (read_buf_) {
delete [] read_buf_;
read_buf_ = NULL;
}
RegisterAsyncReadHandler();
}
/****************************************************************************
* Link Local route event handler
****************************************************************************/
int VnswInterfaceListenerLinux::AddAttr(uint8_t *buff, int type, void *data, int alen) {
struct nlmsghdr *n = (struct nlmsghdr *)buff;
int len = RTA_LENGTH(alen);
if (NLMSG_ALIGN(n->nlmsg_len) + len > VnswInterfaceListenerLinux::kMaxBufferSize)
return -1;
struct rtattr *rta = (struct rtattr*)(((char*)n)+NLMSG_ALIGN(n->nlmsg_len));
rta->rta_type = type;
rta->rta_len = len;
memcpy(RTA_DATA(rta), data, alen);
n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len;
return 0;
}
void VnswInterfaceListenerLinux::UpdateLinkLocalRoute(const Ip4Address &addr,
bool del_rt) {
struct nlmsghdr *nlh;
struct rtmsg *rtm;
uint32_t ipaddr;
memset(tx_buf_, 0, kMaxBufferSize);
nlh = (struct nlmsghdr *) tx_buf_;
rtm = (struct rtmsg *) NLMSG_DATA (nlh);
/* Fill in the nlmsg header*/
nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
if (del_rt) {
nlh->nlmsg_type = RTM_DELROUTE;
nlh->nlmsg_flags = NLM_F_REQUEST;
} else {
nlh->nlmsg_type = RTM_NEWROUTE;
nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE;
}
nlh->nlmsg_seq = ++seqno_;
rtm = (struct rtmsg *) NLMSG_DATA (nlh);
rtm->rtm_table = RT_TABLE_MAIN;
rtm->rtm_family = AF_INET;
rtm->rtm_type = RTN_UNICAST;
rtm->rtm_protocol = kVnswRtmProto;
rtm->rtm_scope = RT_SCOPE_LINK;
rtm->rtm_dst_len = 32;
ipaddr = RT_TABLE_MAIN;
AddAttr(tx_buf_, RTA_TABLE, (void *) &ipaddr, 4);
ipaddr = htonl(addr.to_ulong());
AddAttr(tx_buf_, RTA_DST, (void *) &ipaddr, 4);
int if_index = if_nametoindex(agent_->vhost_interface_name().c_str());
AddAttr(tx_buf_, RTA_OIF, (void *) &if_index, 4);
boost::system::error_code ec;
sock_.send(boost::asio::buffer(nlh,nlh->nlmsg_len), 0, ec);
assert(ec.value() == 0);
}
/****************************************************************************
* Netlink message handlers
* Decodes netlink messages and enqueues events to revent_queue_
****************************************************************************/
string VnswInterfaceListenerLinux::NetlinkTypeToString(uint32_t type) {
switch (type) {
case NLMSG_DONE:
return "NLMSG_DONE";
case RTM_NEWADDR:
return "RTM_NEWADDR";
case RTM_DELADDR:
return "RTM_DELADDR";
case RTM_NEWROUTE:
return "RTM_NEWROUTE";
case RTM_DELROUTE:
return "RTM_DELROUTE";
case RTM_NEWLINK:
return "RTM_NEWLINK";
case RTM_DELLINK:
return "RTM_DELLINK";
default:
break;
}
std::stringstream str;
str << "UNHANDLED <" << type << ">";
return str.str();
}
VnswInterfaceListenerBase::Event *
VnswInterfaceListenerLinux::HandleNetlinkRouteMsg(struct nlmsghdr *nlh) {
struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA (nlh);
if (rtm->rtm_family != AF_INET || rtm->rtm_table != RT_TABLE_MAIN
|| rtm->rtm_type != RTN_UNICAST || rtm->rtm_scope != RT_SCOPE_LINK) {
LOG(DEBUG, "Ignoring Netlink route with family "
<< (uint32_t)rtm->rtm_family
<< " table " << (uint32_t)rtm->rtm_table
<< " type " << (uint32_t)rtm->rtm_type
<< " scope " << (uint32_t)rtm->rtm_scope);
return NULL;
}
int oif = -1;
uint32_t dst_ip = 0;
uint32_t gw_ip = 0;
/* Get the route atttibutes len */
int rtl = RTM_PAYLOAD(nlh);
/* Loop through all attributes */
for (struct rtattr *rth = (struct rtattr *) RTM_RTA(rtm);
RTA_OK(rth, rtl); rth = RTA_NEXT(rth, rtl)) {
/* Get the gateway (Next hop) */
if (rth->rta_type == RTA_DST) {
dst_ip = *((int *)RTA_DATA(rth));
}
if (rth->rta_type == RTA_GATEWAY) {
gw_ip = *((int *)RTA_DATA(rth));
}
if (rth->rta_type == RTA_OIF) {
oif = *((int *)RTA_DATA(rth));
}
}
if (oif == -1) {
return NULL;
}
char name[IFNAMSIZ];
if_indextoname(oif, name);
Ip4Address dst_addr((unsigned long)ntohl(dst_ip));
Ip4Address gw_addr((unsigned long)ntohl(gw_ip));
LOG(DEBUG, "Handle netlink route message "
<< NetlinkTypeToString(nlh->nlmsg_type)
<< " : " << dst_addr.to_string() << "/"
<< (unsigned short)rtm->rtm_dst_len
<< " Interface " << name << " GW " << gw_addr.to_string());
Event::Type type;
if (nlh->nlmsg_type == RTM_DELROUTE) {
type = Event::DEL_ROUTE;
} else {
type = Event::ADD_ROUTE;
}
return new Event(type, dst_addr, rtm->rtm_dst_len, name, gw_addr,
rtm->rtm_protocol, rtm->rtm_flags);
}
VnswInterfaceListenerBase::Event *
VnswInterfaceListenerLinux::HandleNetlinkIntfMsg(struct nlmsghdr *nlh) {
/* Get the atttibutes len */
int rtl = RTM_PAYLOAD(nlh);
const char *port_name = NULL;
struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA (nlh);
/* Loop through all attributes */
for (struct rtattr *rth = IFLA_RTA(ifi); RTA_OK(rth, rtl);
rth = RTA_NEXT(rth, rtl)) {
/* Get the interface name */
if (rth->rta_type == IFLA_IFNAME) {
port_name = (char *) RTA_DATA(rth);
}
}
assert(port_name != NULL);
LOG(DEBUG, "Handle netlink interface message "
<< NetlinkTypeToString(nlh->nlmsg_type)
<< " for interface " << port_name << " flags " << ifi->ifi_flags);
Event::Type type;
if (nlh->nlmsg_type == RTM_DELLINK) {
type = Event::DEL_INTERFACE;
} else {
type = Event::ADD_INTERFACE;
}
return new Event(type, port_name, ifi->ifi_flags);
}
VnswInterfaceListenerBase::Event *
VnswInterfaceListenerLinux::HandleNetlinkAddrMsg(struct nlmsghdr *nlh) {
struct ifaddrmsg *ifa = (struct ifaddrmsg *) NLMSG_DATA (nlh);
// Get interface name from os-index
char name[IFNAMSIZ];
if_indextoname(ifa->ifa_index, name);
LOG(DEBUG, "Handle netlink address message "
<< NetlinkTypeToString(nlh->nlmsg_type) << " for interface " << name);
uint32_t ipaddr = 0;
int rtl = IFA_PAYLOAD(nlh);
for (struct rtattr *rth = IFA_RTA(ifa); rtl && RTA_OK(rth, rtl);
rth = RTA_NEXT(rth,rtl)) {
if (rth->rta_type != IFA_LOCAL) {
continue;
}
ipaddr = ntohl(* ((uint32_t *)RTA_DATA(rth)));
}
if (ipaddr == 0)
return NULL;
assert(ipaddr != 0);
Event::Type type;
if (nlh->nlmsg_type == RTM_DELADDR) {
type = Event::DEL_ADDR;
} else {
type = Event::ADD_ADDR;
}
return new Event(type, name, Ip4Address(ipaddr), ifa->ifa_prefixlen,
ifa->ifa_flags);
}
int VnswInterfaceListenerLinux::NlMsgDecode(struct nlmsghdr *nl,
std::size_t len, uint32_t seq_no) {
Event *event = NULL;
struct nlmsghdr *nlh = nl;
for (; (NLMSG_OK(nlh, len)); nlh = NLMSG_NEXT(nlh, len)) {
switch (nlh->nlmsg_type) {
case NLMSG_DONE:
if (nlh->nlmsg_seq == seq_no) {
return 1;
}
return 0;
case RTM_NEWADDR:
case RTM_DELADDR:
event = HandleNetlinkAddrMsg(nlh);
break;
case RTM_NEWROUTE:
case RTM_DELROUTE:
event = HandleNetlinkRouteMsg(nlh);
break;
case RTM_NEWLINK:
case RTM_DELLINK:
event = HandleNetlinkIntfMsg(nlh);
break;
default:
LOG(DEBUG, "VnswInterfaceListenerLinux got message : "
<< NetlinkTypeToString(nlh->nlmsg_type));
break;
}
if (event) {
revent_queue_->Enqueue(event);
}
}
return 0;
}
| Fix vrouter netlink message logging parsing | Fix vrouter netlink message logging parsing
Change-Id: I21df216fce8e2cae50e47068445fd648549524a7
Closes-Bug: #1546671
| C++ | apache-2.0 | rombie/contrail-controller,rombie/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,tcpcloud/contrail-controller,codilime/contrail-controller,tcpcloud/contrail-controller,nischalsheth/contrail-controller,nischalsheth/contrail-controller,nischalsheth/contrail-controller,codilime/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller,tcpcloud/contrail-controller,nischalsheth/contrail-controller,rombie/contrail-controller,tcpcloud/contrail-controller,eonpatapon/contrail-controller,codilime/contrail-controller,eonpatapon/contrail-controller,tcpcloud/contrail-controller,tcpcloud/contrail-controller,eonpatapon/contrail-controller,codilime/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller |
554b58db667329652042a9f9790f358cc4e1f93f | tests/fparser/autodiff.C | tests/fparser/autodiff.C | #include "libmesh/fparser_ad.hh"
// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#define VECTORMAPOBJECTTEST \
CPPUNIT_TEST( testCreate ); \
class FParserAutodiffTest : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE ( FParserAutodiffTest );
CPPUNIT_TEST ( runTests );
CPPUNIT_TEST_SUITE_END ();
private:
class ADTest {
public:
ADTest(const std::string & _func, double _min, double _max, double _dx = 1e-6, double _reltol = 1e-5, int _steps = 20, double _abstol = 1e-10) :
func(_func),
min(_min),
max(_max),
dx(_dx),
reltol(_reltol),
abstol(_abstol),
steps(_steps)
{
CPPUNIT_ASSERT_MESSAGE ("Failed to parse test function", F.Parse(func, "x") == -1);
dF.Parse(func, "x");
dFopt.Parse(func, "x");
CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of function", dF.AutoDiff("x") == -1);
dFopt.Optimize();
CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of optimized function", dFopt.AutoDiff("x") == -1);
}
bool run()
{
double x1, x2, vdF, vF1, vF2, fd;
for (double x = min; x <= max; x += (max-min) / double(steps))
{
x1 = x - dx/2.0;
x2 = x + dx/2.0;
vF1 = F.Eval(&x1);
vF2 = F.Eval(&x2);
fd = (vF2-vF1) / dx;
// CPPUNIT_ASSERT(std::abs(fd - vdF) > tol)
// CPPUNIT_ASSERT(std::abs(fd - vdFopt) > tol)
vdF = dF.Eval(&x);
if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
{
std::cout << "Error in " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
return false;
}
vdF = dFopt.Eval(&x);
if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
{
std::cout << "Error in opt " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
return false;
}
}
return true;
}
private:
std::string func;
double min, max, dx, reltol, abstol;
int steps;
FunctionParserAD F, dF, dFopt;
};
std::vector<ADTest> tests;
public:
virtual void setUp()
{
tests.push_back(ADTest("log(x) + log2(2*x) + log10(4*x)", 0.1, 3.0));
tests.push_back(ADTest("sin(x) + cos(2*x) + tan(4*x)", -5.0, 5.0, 1e-7, 1e-5, 100));
tests.push_back(ADTest("sinh(x) + cosh(x/2) + tanh(x/3)", -4.0, 4.0, 0.0001, 1e-5, 100));
tests.push_back(ADTest("plog(x,0.01)", 0.001, 0.05, 0.00001, 1e-5, 100));
tests.push_back(ADTest("2 + 4*x + 8*x^2 + 16*x^3 + 32*x^4", -5.0, 5.0, 1e-5,1e-4));
tests.push_back(ADTest("1/x^2", 0.01, 2.0, 1e-8));
tests.push_back(ADTest("sqrt(x)", 0.001, 2.0, 1e-6));
tests.push_back(ADTest("abs(x)", -1.99, 2.0));
tests.push_back(ADTest("asin(x)", -0.99, 0.99));
tests.push_back(ADTest("acos(x)", -0.99, 0.99));
tests.push_back(ADTest("atan(x)", -99, 99));
tests.push_back(ADTest("x*sin(x)*log(x)*tanh(x)", 0.001, 5, 1e-8));
tests.push_back(ADTest("exp(x) + 2*exp2(x)", -1.0, 2.0));
tests.push_back(ADTest("hypot(2*x,1) - hypot(1,4*x)", -10, 10.0));
tests.push_back(ADTest("if(x<0, (-x)^3, x^3)", -1.0, 1.0));
tests.push_back(ADTest("max(x^2-0.5,0)", -1.5, 1.5));
tests.push_back(ADTest("min(x^2-0.5,0)", -1.5, 1.5));
tests.push_back(ADTest("atan2(x,1) + atan2(2,x)", -0.99, 0.99));
tests.push_back(ADTest("0.767^sin(x)", -1.5, 1.5));
tests.push_back(ADTest("A := sin(x) + tanh(x); A + sqrt(A) - x", -1.5, 1.5));
}
void runTests()
{
const unsigned int ntests = tests.size();
unsigned int passed = 0;
for (unsigned i = 0; i < ntests; ++i)
passed += tests[i].run() ? 1 : 0;
CPPUNIT_ASSERT_EQUAL (passed, ntests);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION ( FParserAutodiffTest );
| #include "libmesh/fparser_ad.hh"
// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
class FParserAutodiffTest : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE ( FParserAutodiffTest );
CPPUNIT_TEST ( runTests );
CPPUNIT_TEST ( registerDerivativeTest );
CPPUNIT_TEST_SUITE_END ();
private:
class ADTest {
public:
ADTest(const std::string & _func, double _min, double _max, double _dx = 1e-6, double _reltol = 1e-5, int _steps = 20, double _abstol = 1e-10) :
func(_func),
min(_min),
max(_max),
dx(_dx),
reltol(_reltol),
abstol(_abstol),
steps(_steps)
{
CPPUNIT_ASSERT_MESSAGE ("Failed to parse test function", F.Parse(func, "x") == -1);
dF.Parse(func, "x");
dFopt.Parse(func, "x");
CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of function", dF.AutoDiff("x") == -1);
dFopt.Optimize();
CPPUNIT_ASSERT_MESSAGE ("Failed to take derivative of optimized function", dFopt.AutoDiff("x") == -1);
}
bool run()
{
double x1, x2, vdF, vF1, vF2, fd;
for (double x = min; x <= max; x += (max-min) / double(steps))
{
x1 = x - dx/2.0;
x2 = x + dx/2.0;
vF1 = F.Eval(&x1);
vF2 = F.Eval(&x2);
fd = (vF2-vF1) / dx;
// CPPUNIT_ASSERT(std::abs(fd - vdF) > tol)
// CPPUNIT_ASSERT(std::abs(fd - vdFopt) > tol)
vdF = dF.Eval(&x);
if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
{
std::cout << "Error in " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
return false;
}
vdF = dFopt.Eval(&x);
if (std::abs(vdF) > abstol && std::abs((fd - vdF)/vdF) > reltol && std::abs(fd - vdF)> abstol)
{
std::cout << "Error in opt " << func << ": " << fd << "!=" << vdF << " at x=" << x << '\n';
return false;
}
}
return true;
}
private:
std::string func;
double min, max, dx, reltol, abstol;
int steps;
FunctionParserAD F, dF, dFopt;
};
std::vector<ADTest> tests;
public:
virtual void setUp()
{
tests.push_back(ADTest("log(x) + log2(2*x) + log10(4*x)", 0.1, 3.0));
tests.push_back(ADTest("sin(x) + cos(2*x) + tan(4*x)", -5.0, 5.0, 1e-7, 1e-5, 100));
tests.push_back(ADTest("sinh(x) + cosh(x/2) + tanh(x/3)", -4.0, 4.0, 0.0001, 1e-5, 100));
tests.push_back(ADTest("plog(x,0.01)", 0.001, 0.05, 0.00001, 1e-5, 100));
tests.push_back(ADTest("2 + 4*x + 8*x^2 + 16*x^3 + 32*x^4", -5.0, 5.0, 1e-5,1e-4));
tests.push_back(ADTest("1/x^2", 0.01, 2.0, 1e-8));
tests.push_back(ADTest("sqrt(x)", 0.001, 2.0, 1e-6));
tests.push_back(ADTest("abs(x)", -1.99, 2.0));
tests.push_back(ADTest("asin(x)", -0.99, 0.99));
tests.push_back(ADTest("acos(x)", -0.99, 0.99));
tests.push_back(ADTest("atan(x)", -99, 99));
tests.push_back(ADTest("x*sin(x)*log(x)*tanh(x)", 0.001, 5, 1e-8));
tests.push_back(ADTest("exp(x) + 2*exp2(x)", -1.0, 2.0));
tests.push_back(ADTest("hypot(2*x,1) - hypot(1,4*x)", -10, 10.0));
tests.push_back(ADTest("if(x<0, (-x)^3, x^3)", -1.0, 1.0));
tests.push_back(ADTest("max(x^2-0.5,0)", -1.5, 1.5));
tests.push_back(ADTest("min(x^2-0.5,0)", -1.5, 1.5));
tests.push_back(ADTest("atan2(x,1) + atan2(2,x)", -0.99, 0.99));
tests.push_back(ADTest("0.767^sin(x)", -1.5, 1.5));
tests.push_back(ADTest("A := sin(x) + tanh(x); A + sqrt(A) - x", -1.5, 1.5));
}
void runTests()
{
const unsigned int ntests = tests.size();
unsigned int passed = 0;
for (unsigned i = 0; i < ntests; ++i)
passed += tests[i].run() ? 1 : 0;
CPPUNIT_ASSERT_EQUAL (passed, ntests);
}
void registerDerivativeTest()
{
FunctionParserAD R;
std::string func = "x*a";
// Parse the input expression into bytecode
R.Parse(func, "x,a,y");
R.RegisterDerivative("a", "x", "y");
// parameter vector
double p[3];
double & x = p[0];
double & a = p[1];
double & y = p[2];
FunctionParserAD dR(R);
CPPUNIT_ASSERT_EQUAL (dR.AutoDiff("x"), -1);
dR.Optimize();
// dR = a+x*y
FunctionParserAD d2R(dR);
CPPUNIT_ASSERT_EQUAL (d2R.AutoDiff("x"), -1);
d2R.Optimize();
// d2R = 2*y
// we probe the parsers and check if they agree with the reference solution
for (x = -1.0; x < 1.0; x+=0.3726)
for (a = -1.0; a < 1.0; a+=0.2642)
for (y = -1.0; y < 1.0; y+=0.3156)
{
CPPUNIT_ASSERT_DOUBLES_EQUAL(R.Eval(p), x*a, 1.e-12);
CPPUNIT_ASSERT_DOUBLES_EQUAL(dR.Eval(p), a+x*y, 1.e-12);
CPPUNIT_ASSERT_DOUBLES_EQUAL(d2R.Eval(p), 2*y, 1.e-12);
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION ( FParserAutodiffTest );
| Add unit test (#463) | Add unit test (#463)
| C++ | lgpl-2.1 | jwpeterson/libmesh,coreymbryant/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,dknez/libmesh,karpeev/libmesh,hrittich/libmesh,dknez/libmesh,pbauman/libmesh,jwpeterson/libmesh,libMesh/libmesh,pbauman/libmesh,aeslaughter/libmesh,90jrong/libmesh,coreymbryant/libmesh,libMesh/libmesh,dmcdougall/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,salazardetroya/libmesh,permcody/libmesh,svallaghe/libmesh,capitalaslash/libmesh,dschwen/libmesh,giorgiobornia/libmesh,aeslaughter/libmesh,roystgnr/libmesh,friedmud/libmesh,giorgiobornia/libmesh,friedmud/libmesh,cahaynes/libmesh,svallaghe/libmesh,permcody/libmesh,aeslaughter/libmesh,friedmud/libmesh,karpeev/libmesh,permcody/libmesh,salazardetroya/libmesh,hrittich/libmesh,hrittich/libmesh,dknez/libmesh,jiangwen84/libmesh,balborian/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,permcody/libmesh,hrittich/libmesh,dschwen/libmesh,vikramvgarg/libmesh,roystgnr/libmesh,jiangwen84/libmesh,svallaghe/libmesh,dschwen/libmesh,cahaynes/libmesh,dknez/libmesh,dschwen/libmesh,hrittich/libmesh,dmcdougall/libmesh,capitalaslash/libmesh,dmcdougall/libmesh,capitalaslash/libmesh,dschwen/libmesh,friedmud/libmesh,salazardetroya/libmesh,jwpeterson/libmesh,dmcdougall/libmesh,vikramvgarg/libmesh,pbauman/libmesh,hrittich/libmesh,benkirk/libmesh,pbauman/libmesh,salazardetroya/libmesh,90jrong/libmesh,vikramvgarg/libmesh,friedmud/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,roystgnr/libmesh,giorgiobornia/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,svallaghe/libmesh,hrittich/libmesh,vikramvgarg/libmesh,capitalaslash/libmesh,dmcdougall/libmesh,BalticPinguin/libmesh,pbauman/libmesh,permcody/libmesh,friedmud/libmesh,balborian/libmesh,Mbewu/libmesh,capitalaslash/libmesh,balborian/libmesh,svallaghe/libmesh,dknez/libmesh,90jrong/libmesh,dknez/libmesh,jwpeterson/libmesh,friedmud/libmesh,dmcdougall/libmesh,jwpeterson/libmesh,aeslaughter/libmesh,giorgiobornia/libmesh,benkirk/libmesh,salazardetroya/libmesh,dknez/libmesh,balborian/libmesh,karpeev/libmesh,dknez/libmesh,svallaghe/libmesh,friedmud/libmesh,karpeev/libmesh,vikramvgarg/libmesh,BalticPinguin/libmesh,coreymbryant/libmesh,dmcdougall/libmesh,balborian/libmesh,dschwen/libmesh,libMesh/libmesh,90jrong/libmesh,balborian/libmesh,aeslaughter/libmesh,giorgiobornia/libmesh,roystgnr/libmesh,Mbewu/libmesh,svallaghe/libmesh,capitalaslash/libmesh,coreymbryant/libmesh,karpeev/libmesh,coreymbryant/libmesh,jiangwen84/libmesh,benkirk/libmesh,cahaynes/libmesh,BalticPinguin/libmesh,libMesh/libmesh,pbauman/libmesh,jwpeterson/libmesh,cahaynes/libmesh,pbauman/libmesh,permcody/libmesh,aeslaughter/libmesh,90jrong/libmesh,libMesh/libmesh,90jrong/libmesh,cahaynes/libmesh,Mbewu/libmesh,aeslaughter/libmesh,permcody/libmesh,jiangwen84/libmesh,balborian/libmesh,dschwen/libmesh,Mbewu/libmesh,salazardetroya/libmesh,salazardetroya/libmesh,benkirk/libmesh,libMesh/libmesh,karpeev/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,jiangwen84/libmesh,libMesh/libmesh,pbauman/libmesh,hrittich/libmesh,dschwen/libmesh,giorgiobornia/libmesh,roystgnr/libmesh,cahaynes/libmesh,benkirk/libmesh,giorgiobornia/libmesh,Mbewu/libmesh,svallaghe/libmesh,karpeev/libmesh,jiangwen84/libmesh,Mbewu/libmesh,balborian/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,karpeev/libmesh,aeslaughter/libmesh,jiangwen84/libmesh,90jrong/libmesh,svallaghe/libmesh,cahaynes/libmesh,benkirk/libmesh,Mbewu/libmesh,jwpeterson/libmesh,pbauman/libmesh,cahaynes/libmesh,benkirk/libmesh,coreymbryant/libmesh,permcody/libmesh,roystgnr/libmesh,benkirk/libmesh,dmcdougall/libmesh,Mbewu/libmesh,salazardetroya/libmesh,coreymbryant/libmesh,benkirk/libmesh,90jrong/libmesh,jwpeterson/libmesh,jiangwen84/libmesh,libMesh/libmesh,hrittich/libmesh,Mbewu/libmesh,90jrong/libmesh,coreymbryant/libmesh,balborian/libmesh,vikramvgarg/libmesh,balborian/libmesh,BalticPinguin/libmesh,friedmud/libmesh |
7fb7e5b07f70df3ffa92f150a18d7c53f017ae2a | generate/templates/partials/field_accessors.cc | generate/templates/partials/field_accessors.cc | {% each fields|fieldsInfo as field %}
{% if not field.ignore %}
NAN_GETTER({{ cppClassName }}::Get{{ field.cppFunctionName }}) {
NanScope();
{{ cppClassName }} *wrapper = ObjectWrap::Unwrap<{{ cppClassName }}>(args.This());
{% if field.isEnum %}
NanReturnValue(NanNew((int)wrapper->GetValue()->{{ field.name }}));
{% elsif field.isLibgitType | or field.payloadFor %}
NanReturnValue(wrapper->{{ field.name }});
{% elsif field.isCallbackFunction %}
NanReturnValue(wrapper->{{ field.name }}->GetFunction());
{% elsif field.cppClassName == 'String' %}
if (wrapper->GetValue()->{{ field.name }}) {
NanReturnValue(NanNew<String>(wrapper->GetValue()->{{ field.name }}));
}
else {
NanReturnUndefined();
}
{% elsif field.cppClassName|isV8Value %}
NanReturnValue(NanNew<{{ field.cppClassName }}>(wrapper->GetValue()->{{ field.name }}));
{% endif %}
}
NAN_SETTER({{ cppClassName }}::Set{{ field.cppFunctionName }}) {
NanScope();
{{ cppClassName }} *wrapper = ObjectWrap::Unwrap<{{ cppClassName }}>(args.This());
{% if field.isEnum %}
if (value->IsNumber()) {
wrapper->GetValue()->{{ field.name }} = ({{ field.cType }}) value->Int32Value();
}
{% elsif field.isLibgitType %}
Handle<Object> {{ field.name }}(value->ToObject());
NanDisposePersistent(wrapper->{{ field.name }});
NanAssignPersistent(wrapper->{{ field.name }}, {{ field.name }});
wrapper->raw->{{ field.name }} = {% if not field.cType | isPointer %}*{% endif %}{% if field.cppClassName == 'GitStrarray' %}StrArrayConverter::Convert({{ field.name }}->ToObject()){% else %}ObjectWrap::Unwrap<{{ field.cppClassName }}>({{ field.name }}->ToObject())->GetValue(){% endif %};
{% elsif field.isCallbackFunction %}
if (wrapper->{{ field.name }} != NULL) {
delete wrapper->{{ field.name }};
}
if (value->IsFunction()) {
if (!wrapper->raw->{{ field.name }}) {
wrapper->raw->{{ field.name }} = ({{ field.cType }}){{ field.name }}_cppCallback;
}
wrapper->{{ field.name }} = new NanCallback(value.As<Function>());
}
{% elsif field.payloadFor %}
NanAssignPersistent(wrapper->{{ field.name }}, value);
{% elsif field.cppClassName == 'String' %}
if (wrapper->GetValue()->{{ field.name }}) {
}
String::Utf8Value str(value);
wrapper->GetValue()->{{ field.name }} = strdup(*str);
{% elsif field.isCppClassIntType %}
if (value->IsNumber()) {
wrapper->GetValue()->{{ field.name }} = value->{{field.cppClassName}}Value();
}
{% else %}
if (value->IsNumber()) {
wrapper->GetValue()->{{ field.name }} = ({{ field.cType }}) value->Int32Value();
}
{% endif %}
}
{% if field.isCallbackFunction %}
{{ field.return.type }} {{ cppClassName }}::{{ field.name }}_cppCallback (
{% each field.args|argsInfo as arg %}
{{ arg.cType }} {{ arg.name}}{% if not arg.lastArg %},{% endif %}
{% endeach %}
) {
{{ field.name|titleCase }}Baton* baton = new {{ field.name|titleCase }}Baton();
{% each field.args|argsInfo as arg %}
baton->{{ arg.name }} = {{ arg.name }};
{% endeach %}
baton->result = 0;
baton->req.data = baton;
baton->done = false;
uv_async_init(uv_default_loop(), &baton->req, (uv_async_cb) {{ field.name }}_async);
uv_async_send(&baton->req);
while(!baton->done) {
this_thread::sleep_for(chrono::milliseconds(1));
}
{% each field|returnsInfo false true as _return %}
{% if _return.isOutParam %}
*{{ _return.name }} = *baton->{{ _return.name }};
{% endif %}
{% endeach %}
return baton->result;
}
void {{ cppClassName }}::{{ field.name }}_async(uv_async_t* req, int status) {
NanScope();
{{ field.name|titleCase }}Baton* baton = static_cast<{{ field.name|titleCase }}Baton*>(req->data);
{{ cppClassName }}* instance = static_cast<{{ cppClassName }}*>(baton->payload);
if (instance->{{ field.name }}->IsEmpty()) {
{% if field.return.type == "int" %}
baton->result = {{ field.return.noResults }}; // no results acquired
{% endif %}
baton->done = true;
return;
}
{% each field.args|argsInfo as arg %}
{% if arg.name == "payload" %}
{%-- Do nothing --%}
{% elsif arg.isJsArg %}
if (baton->{{ arg.name }} == NULL) {
{% if arg.cType == "const char *" %}
baton->{{ arg.name }} = "";
{% elsif arg.cType == "unsigned int" %}
baton->{{ arg.name }} = 0;
{% endif %}
}
{% endif %}
{% endeach %}
Local<Value> argv[{{ field.args|jsArgsCount }}] = {
{% each field.args|argsInfo as arg %}
{% if arg.name == "payload" %}
{%-- payload is always the last arg --%}
NanNew(instance->{{ fields|payloadFor field.name }})
{% elsif arg.isJsArg %}
{% if arg.isEnum %}
NanNew((int)baton->{{ arg.name }}),
{% elsif arg.isLibgitType %}
NanNew({{ arg.cppClassName }}::New((void *)baton->{{ arg.name }}, false)),
{% elsif arg.cType == "size_t" %}
// HACK: NAN should really have an overload for NanNew to support size_t
NanNew((unsigned int)baton->{{ arg.name }}),
{% else %}
NanNew(baton->{{ arg.name }}),
{% endif %}
{% endif %}
{% endeach %}
};
TryCatch tryCatch;
Handle<v8::Value> result = instance->{{ field.name }}->Call({{ field.args|jsArgsCount }}, argv);
if (result->IsObject() && result->ToObject()->Has(NanNew("then"))) {
Handle<v8::Value> thenProp = result->ToObject()->Get(NanNew("then"));
if (thenProp->IsFunction()) {
// we can be reasonbly certain that the result is a promise
Local<Object> promise = result->ToObject();
NanAssignPersistent(baton->promise, promise);
uv_close((uv_handle_t*) &baton->req, NULL);
uv_async_init(uv_default_loop(), &baton->req, (uv_async_cb) {{ field.name }}_asyncPromisePolling);
uv_async_send(&baton->req);
return;
}
}
{% each field|returnsInfo false true as _return %}
if (result.IsEmpty() || result->IsNativeError()) {
baton->result = {{ field.return.error }};
}
else if (!result->IsNull() && !result->IsUndefined()) {
{% if _return.isOutParam %}
{{ _return.cppClassName }}* wrapper = ObjectWrap::Unwrap<{{ _return.cppClassName }}>(result->ToObject());
wrapper->selfFreeing = false;
baton->{{ _return.name }} = wrapper->GetRefValue();
baton->result = {{ field.return.success }};
{% else %}
if (result->IsNumber()) {
baton->result = (int)result->ToNumber()->Value();
}
else {
baton->result = {{ field.return.noResults }};
}
{% endif %}
}
else {
baton->result = {{ field.return.noResults }};
}
{% endeach %}
baton->done = true;
uv_close((uv_handle_t*) &baton->req, NULL);
}
void {{ cppClassName }}::{{ field.name }}_asyncPromisePolling(uv_async_t* req, int status) {
NanScope();
{{ field.name|titleCase }}Baton* baton = static_cast<{{ field.name|titleCase }}Baton*>(req->data);
Local<Object> promise = NanNew<Object>(baton->promise);
NanCallback* isPendingFn = new NanCallback(promise->Get(NanNew("isPending")).As<Function>());
Local<Value> argv[1]; // MSBUILD won't assign an array of length 0
Local<Boolean> isPending = isPendingFn->Call(promise, 0, argv)->ToBoolean();
if (isPending->Value()) {
uv_async_send(&baton->req);
return;
}
NanCallback* isFulfilledFn = new NanCallback(promise->Get(NanNew("isFulfilled")).As<Function>());
Local<Boolean> isFulfilled = isFulfilledFn->Call(promise, 0, argv)->ToBoolean();
if (isFulfilled->Value()) {
NanCallback* resultFn = new NanCallback(promise->Get(NanNew("value")).As<Function>());
Handle<v8::Value> result = resultFn->Call(promise, 0, argv);
{% each field|returnsInfo false true as _return %}
if (result.IsEmpty() || result->IsNativeError()) {
baton->result = {{ field.return.error }};
}
else if (!result->IsNull() && !result->IsUndefined()) {
{% if _return.isOutParam %}
{{ _return.cppClassName }}* wrapper = ObjectWrap::Unwrap<{{ _return.cppClassName }}>(result->ToObject());
wrapper->selfFreeing = false;
baton->{{ _return.name }} = wrapper->GetRefValue();
baton->result = {{ field.return.success }};
{% else %}
if (result->IsNumber()) {
baton->result = (int)result->ToNumber()->Value();
}
else{
baton->result = {{ field.return.noResults }};
}
{% endif %}
}
else {
baton->result = {{ field.return.noResults }};
}
{% endeach %}
baton->done = true;
}
else {
// promise was rejected
baton->result = {{ field.return.error }};
baton->done = false;
}
uv_close((uv_handle_t*) &baton->req, NULL);
}
{% endif %}
{% endif %}
{% endeach %}
| {% each fields|fieldsInfo as field %}
{% if not field.ignore %}
NAN_GETTER({{ cppClassName }}::Get{{ field.cppFunctionName }}) {
NanScope();
{{ cppClassName }} *wrapper = ObjectWrap::Unwrap<{{ cppClassName }}>(args.This());
{% if field.isEnum %}
NanReturnValue(NanNew((int)wrapper->GetValue()->{{ field.name }}));
{% elsif field.isLibgitType | or field.payloadFor %}
NanReturnValue(NanNew(wrapper->{{ field.name }}));
{% elsif field.isCallbackFunction %}
NanReturnValue(wrapper->{{ field.name }}->GetFunction());
{% elsif field.cppClassName == 'String' %}
if (wrapper->GetValue()->{{ field.name }}) {
NanReturnValue(NanNew<String>(wrapper->GetValue()->{{ field.name }}));
}
else {
NanReturnUndefined();
}
{% elsif field.cppClassName|isV8Value %}
NanReturnValue(NanNew<{{ field.cppClassName }}>(wrapper->GetValue()->{{ field.name }}));
{% endif %}
}
NAN_SETTER({{ cppClassName }}::Set{{ field.cppFunctionName }}) {
NanScope();
{{ cppClassName }} *wrapper = ObjectWrap::Unwrap<{{ cppClassName }}>(args.This());
{% if field.isEnum %}
if (value->IsNumber()) {
wrapper->GetValue()->{{ field.name }} = ({{ field.cType }}) value->Int32Value();
}
{% elsif field.isLibgitType %}
Handle<Object> {{ field.name }}(value->ToObject());
NanDisposePersistent(wrapper->{{ field.name }});
NanAssignPersistent(wrapper->{{ field.name }}, {{ field.name }});
wrapper->raw->{{ field.name }} = {% if not field.cType | isPointer %}*{% endif %}{% if field.cppClassName == 'GitStrarray' %}StrArrayConverter::Convert({{ field.name }}->ToObject()){% else %}ObjectWrap::Unwrap<{{ field.cppClassName }}>({{ field.name }}->ToObject())->GetValue(){% endif %};
{% elsif field.isCallbackFunction %}
if (wrapper->{{ field.name }} != NULL) {
delete wrapper->{{ field.name }};
}
if (value->IsFunction()) {
if (!wrapper->raw->{{ field.name }}) {
wrapper->raw->{{ field.name }} = ({{ field.cType }}){{ field.name }}_cppCallback;
}
wrapper->{{ field.name }} = new NanCallback(value.As<Function>());
}
{% elsif field.payloadFor %}
NanAssignPersistent(wrapper->{{ field.name }}, value);
{% elsif field.cppClassName == 'String' %}
if (wrapper->GetValue()->{{ field.name }}) {
}
String::Utf8Value str(value);
wrapper->GetValue()->{{ field.name }} = strdup(*str);
{% elsif field.isCppClassIntType %}
if (value->IsNumber()) {
wrapper->GetValue()->{{ field.name }} = value->{{field.cppClassName}}Value();
}
{% else %}
if (value->IsNumber()) {
wrapper->GetValue()->{{ field.name }} = ({{ field.cType }}) value->Int32Value();
}
{% endif %}
}
{% if field.isCallbackFunction %}
{{ field.return.type }} {{ cppClassName }}::{{ field.name }}_cppCallback (
{% each field.args|argsInfo as arg %}
{{ arg.cType }} {{ arg.name}}{% if not arg.lastArg %},{% endif %}
{% endeach %}
) {
{{ field.name|titleCase }}Baton* baton = new {{ field.name|titleCase }}Baton();
{% each field.args|argsInfo as arg %}
baton->{{ arg.name }} = {{ arg.name }};
{% endeach %}
baton->result = 0;
baton->req.data = baton;
baton->done = false;
uv_async_init(uv_default_loop(), &baton->req, (uv_async_cb) {{ field.name }}_async);
uv_async_send(&baton->req);
while(!baton->done) {
this_thread::sleep_for(chrono::milliseconds(1));
}
{% each field|returnsInfo false true as _return %}
{% if _return.isOutParam %}
*{{ _return.name }} = *baton->{{ _return.name }};
{% endif %}
{% endeach %}
return baton->result;
}
void {{ cppClassName }}::{{ field.name }}_async(uv_async_t* req, int status) {
NanScope();
{{ field.name|titleCase }}Baton* baton = static_cast<{{ field.name|titleCase }}Baton*>(req->data);
{{ cppClassName }}* instance = static_cast<{{ cppClassName }}*>(baton->payload);
if (instance->{{ field.name }}->IsEmpty()) {
{% if field.return.type == "int" %}
baton->result = {{ field.return.noResults }}; // no results acquired
{% endif %}
baton->done = true;
return;
}
{% each field.args|argsInfo as arg %}
{% if arg.name == "payload" %}
{%-- Do nothing --%}
{% elsif arg.isJsArg %}
if (baton->{{ arg.name }} == NULL) {
{% if arg.cType == "const char *" %}
baton->{{ arg.name }} = "";
{% elsif arg.cType == "unsigned int" %}
baton->{{ arg.name }} = 0;
{% endif %}
}
{% endif %}
{% endeach %}
Local<Value> argv[{{ field.args|jsArgsCount }}] = {
{% each field.args|argsInfo as arg %}
{% if arg.name == "payload" %}
{%-- payload is always the last arg --%}
NanNew(instance->{{ fields|payloadFor field.name }})
{% elsif arg.isJsArg %}
{% if arg.isEnum %}
NanNew((int)baton->{{ arg.name }}),
{% elsif arg.isLibgitType %}
NanNew({{ arg.cppClassName }}::New((void *)baton->{{ arg.name }}, false)),
{% elsif arg.cType == "size_t" %}
// HACK: NAN should really have an overload for NanNew to support size_t
NanNew((unsigned int)baton->{{ arg.name }}),
{% else %}
NanNew(baton->{{ arg.name }}),
{% endif %}
{% endif %}
{% endeach %}
};
TryCatch tryCatch;
Handle<v8::Value> result = instance->{{ field.name }}->Call({{ field.args|jsArgsCount }}, argv);
if (result->IsObject() && result->ToObject()->Has(NanNew("then"))) {
Handle<v8::Value> thenProp = result->ToObject()->Get(NanNew("then"));
if (thenProp->IsFunction()) {
// we can be reasonbly certain that the result is a promise
Local<Object> promise = result->ToObject();
NanAssignPersistent(baton->promise, promise);
uv_close((uv_handle_t*) &baton->req, NULL);
uv_async_init(uv_default_loop(), &baton->req, (uv_async_cb) {{ field.name }}_asyncPromisePolling);
uv_async_send(&baton->req);
return;
}
}
{% each field|returnsInfo false true as _return %}
if (result.IsEmpty() || result->IsNativeError()) {
baton->result = {{ field.return.error }};
}
else if (!result->IsNull() && !result->IsUndefined()) {
{% if _return.isOutParam %}
{{ _return.cppClassName }}* wrapper = ObjectWrap::Unwrap<{{ _return.cppClassName }}>(result->ToObject());
wrapper->selfFreeing = false;
baton->{{ _return.name }} = wrapper->GetRefValue();
baton->result = {{ field.return.success }};
{% else %}
if (result->IsNumber()) {
baton->result = (int)result->ToNumber()->Value();
}
else {
baton->result = {{ field.return.noResults }};
}
{% endif %}
}
else {
baton->result = {{ field.return.noResults }};
}
{% endeach %}
baton->done = true;
uv_close((uv_handle_t*) &baton->req, NULL);
}
void {{ cppClassName }}::{{ field.name }}_asyncPromisePolling(uv_async_t* req, int status) {
NanScope();
{{ field.name|titleCase }}Baton* baton = static_cast<{{ field.name|titleCase }}Baton*>(req->data);
Local<Object> promise = NanNew<Object>(baton->promise);
NanCallback* isPendingFn = new NanCallback(promise->Get(NanNew("isPending")).As<Function>());
Local<Value> argv[1]; // MSBUILD won't assign an array of length 0
Local<Boolean> isPending = isPendingFn->Call(promise, 0, argv)->ToBoolean();
if (isPending->Value()) {
uv_async_send(&baton->req);
return;
}
NanCallback* isFulfilledFn = new NanCallback(promise->Get(NanNew("isFulfilled")).As<Function>());
Local<Boolean> isFulfilled = isFulfilledFn->Call(promise, 0, argv)->ToBoolean();
if (isFulfilled->Value()) {
NanCallback* resultFn = new NanCallback(promise->Get(NanNew("value")).As<Function>());
Handle<v8::Value> result = resultFn->Call(promise, 0, argv);
{% each field|returnsInfo false true as _return %}
if (result.IsEmpty() || result->IsNativeError()) {
baton->result = {{ field.return.error }};
}
else if (!result->IsNull() && !result->IsUndefined()) {
{% if _return.isOutParam %}
{{ _return.cppClassName }}* wrapper = ObjectWrap::Unwrap<{{ _return.cppClassName }}>(result->ToObject());
wrapper->selfFreeing = false;
baton->{{ _return.name }} = wrapper->GetRefValue();
baton->result = {{ field.return.success }};
{% else %}
if (result->IsNumber()) {
baton->result = (int)result->ToNumber()->Value();
}
else{
baton->result = {{ field.return.noResults }};
}
{% endif %}
}
else {
baton->result = {{ field.return.noResults }};
}
{% endeach %}
baton->done = true;
}
else {
// promise was rejected
baton->result = {{ field.return.error }};
baton->done = false;
}
uv_close((uv_handle_t*) &baton->req, NULL);
}
{% endif %}
{% endif %}
{% endeach %}
| Fix compile issue with latest nan | Fix compile issue with latest nan
| C++ | mit | cbargren/nodegit,tannewt/nodegit,dkoontz/nodegit,nodegit/nodegit,Gum-Joe/nodegit,dancali/nodegit,taylorzane/nodegit,dancali/nodegit,saper/nodegit,danawoodman/nodegit,dkoontz/nodegit,dancali/nodegit,srajko/nodegit,jmurzy/nodegit,KenanSulayman/nodegit,nodegit/nodegit,KenanSulayman/nodegit,danawoodman/nodegit,cwahbong/nodegit,jmurzy/nodegit,cwahbong/nodegit,bengl/nodegit,Gum-Joe/nodegit,jfremy/nodegit,cbargren/nodegit,taylorzane/nodegit,saper/nodegit,dkoontz/nodegit,heavyk/nodegit,tannewt/nodegit,srajko/nodegit,cbargren/nodegit,jfremy/nodegit,chasingmaxwell/nodegit,StephanieMak/nodegit,Naituw/nodegit,cwahbong/nodegit,taylorzane/nodegit,jmurzy/nodegit,cwahbong/nodegit,jdgarcia/nodegit,tannewt/nodegit,saper/nodegit,bengl/nodegit,Gum-Joe/nodegit,StephanieMak/nodegit,jmurzy/nodegit,eunomie/nodegit,dkoontz/nodegit,StephanieMak/nodegit,kenprice/nodegit,nodegit/nodegit,cbargren/nodegit,saper/nodegit,danawoodman/nodegit,jdgarcia/nodegit,KenanSulayman/nodegit,IonicaBizauKitchen/nodegit,jdgarcia/nodegit,srajko/nodegit,heavyk/nodegit,srajko/nodegit,Naituw/nodegit,chasingmaxwell/nodegit,bengl/nodegit,freder/nodegit,chasingmaxwell/nodegit,chasingmaxwell/nodegit,jfremy/nodegit,srajko/nodegit,nodegit/nodegit,Gum-Joe/nodegit,tannewt/nodegit,KenanSulayman/nodegit,cbargren/nodegit,IonicaBizauKitchen/nodegit,kenprice/nodegit,jfremy/nodegit,nodegit/nodegit,jmurzy/nodegit,bengl/nodegit,taylorzane/nodegit,freder/nodegit,dkoontz/nodegit,dancali/nodegit,heavyk/nodegit,freder/nodegit,freder/nodegit,eunomie/nodegit,jdgarcia/nodegit,StephanieMak/nodegit,jdgarcia/nodegit,IonicaBizauKitchen/nodegit,danawoodman/nodegit,Naituw/nodegit,kenprice/nodegit,eunomie/nodegit,heavyk/nodegit,Naituw/nodegit,IonicaBizauKitchen/nodegit,kenprice/nodegit,kenprice/nodegit,eunomie/nodegit |
e6f507096e62ccad9c10107ddaa91f2669425def | libcaf_core/test/read_ini.cpp | libcaf_core/test/read_ini.cpp | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include <string>
#include <vector>
#include "caf/config.hpp"
#define CAF_SUITE read_ini
#include "caf/test/dsl.hpp"
#include "caf/detail/parser/read_ini.hpp"
using namespace caf;
namespace {
using log_type = std::vector<std::string>;
struct test_consumer {
log_type log;
test_consumer() = default;
test_consumer(const test_consumer&) = delete;
test_consumer& operator=(const test_consumer&) = delete;
test_consumer& begin_map() {
log.emplace_back("{");
return *this;
}
void end_map() {
log.emplace_back("}");
}
test_consumer& begin_list() {
log.emplace_back("[");
return *this;
}
void end_list() {
log.emplace_back("]");
}
void key(std::string name) {
add_entry("key: ", std::move(name));
}
template <class T>
void value(T x) {
config_value cv{std::move(x)};
std::string entry = "value (";
entry += cv.type_name();
entry += "): ";
entry += to_string(cv);
log.emplace_back(std::move(entry));
}
void add_entry(const char* prefix, std::string str) {
str.insert(0, prefix);
log.emplace_back(std::move(str));
}
};
struct ini_consumer {
using inner_map = std::map<std::string, config_value>;
using section_map = std::map<std::string, inner_map>;
section_map sections;
section_map::iterator current_section;
};
struct fixture {
expected<log_type> parse(std::string str, bool expect_success = true) {
detail::parser::state<std::string::iterator> res;
test_consumer f;
res.i = str.begin();
res.e = str.end();
detail::parser::read_ini(res, f);
if ((res.code == pec::success) != expect_success) {
CAF_MESSAGE("unexpected parser result state: " << res.code);
CAF_MESSAGE("input remainder: " << std::string(res.i, res.e));
}
return std::move(f.log);
}
};
template <class... Ts>
log_type make_log(Ts&&... xs) {
return log_type{std::forward<Ts>(xs)...};
}
const char* ini0 = R"(
[logger]
padding= 10
file-name = "foobar.ini" ; our file name
[scheduler] ; more settings
timing = 2us ; using microsecond resolution
impl = 'foo';some atom
x_ =.123
some-bool=true
some-other-bool=false
some-list=[
; here we have some list entries
123,
23 ; twenty-three!
,
"abc",
'def', ; some comment and a trailing comma
]
some-map={
; here we have some list entries
entry1=123,
entry2=23 ; twenty-three!
,
entry3= "abc",
entry4 = 'def', ; some comment and a trailing comma
}
[middleman]
preconnect=[<
tcp://localhost:8080
>,<udp://remotehost?trust=false>]
)";
const auto ini0_log = make_log(
"key: logger",
"{",
"key: padding",
"value (integer): 10",
"key: file-name",
"value (string): \"foobar.ini\"",
"}",
"key: scheduler",
"{",
"key: timing",
"value (timespan): 2000ns",
"key: impl",
"value (atom): 'foo'",
"key: x_",
"value (real): " + deep_to_string(.123),
"key: some-bool",
"value (boolean): true",
"key: some-other-bool",
"value (boolean): false",
"key: some-list",
"[",
"value (integer): 123",
"value (integer): 23",
"value (string): \"abc\"",
"value (atom): 'def'",
"]",
"key: some-map",
"{",
"key: entry1",
"value (integer): 123",
"key: entry2",
"value (integer): 23",
"key: entry3",
"value (string): \"abc\"",
"key: entry4",
"value (atom): 'def'",
"}",
"}",
"key: middleman",
"{",
"key: preconnect",
"[",
"value (uri): tcp://localhost:8080",
"value (uri): udp://remotehost?trust=false",
"]",
"}"
);
} // namespace <anonymous>
CAF_TEST_FIXTURE_SCOPE(read_ini_tests, fixture)
CAF_TEST(empty inis) {
CAF_CHECK_EQUAL(parse(";foo"), make_log());
CAF_CHECK_EQUAL(parse(""), make_log());
CAF_CHECK_EQUAL(parse(" "), make_log());
CAF_CHECK_EQUAL(parse(" \n "), make_log());
CAF_CHECK_EQUAL(parse(";hello\n;world"), make_log());
}
CAF_TEST(section with valid key-value pairs) {
CAF_CHECK_EQUAL(parse("[foo]"), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse(" [foo]"), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse(" [ foo] "), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse(" [ foo ] "), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse("\n[a-b];foo\n;bar"), make_log("key: a-b", "{", "}"));
CAF_CHECK_EQUAL(parse(ini0), ini0_log);
}
CAF_TEST_FIXTURE_SCOPE_END()
| /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include <string>
#include <vector>
#include "caf/config.hpp"
#define CAF_SUITE read_ini
#include "caf/test/dsl.hpp"
#include "caf/detail/parser/read_ini.hpp"
using namespace caf;
namespace {
using log_type = std::vector<std::string>;
struct test_consumer {
log_type log;
test_consumer() = default;
test_consumer(const test_consumer&) = delete;
test_consumer& operator=(const test_consumer&) = delete;
test_consumer& begin_map() {
log.emplace_back("{");
return *this;
}
void end_map() {
log.emplace_back("}");
}
test_consumer& begin_list() {
log.emplace_back("[");
return *this;
}
void end_list() {
log.emplace_back("]");
}
void key(std::string name) {
add_entry("key: ", std::move(name));
}
template <class T>
void value(T x) {
config_value cv{std::move(x)};
std::string entry = "value (";
entry += cv.type_name();
entry += "): ";
entry += to_string(cv);
log.emplace_back(std::move(entry));
}
void add_entry(const char* prefix, std::string str) {
str.insert(0, prefix);
log.emplace_back(std::move(str));
}
};
struct ini_consumer {
using inner_map = std::map<std::string, config_value>;
using section_map = std::map<std::string, inner_map>;
section_map sections;
section_map::iterator current_section;
};
struct fixture {
expected<log_type> parse(std::string str, bool expect_success = true) {
detail::parser::state<std::string::iterator> res;
test_consumer f;
res.i = str.begin();
res.e = str.end();
detail::parser::read_ini(res, f);
if ((res.code == pec::success) != expect_success) {
CAF_MESSAGE("unexpected parser result state: " << res.code);
CAF_MESSAGE("input remainder: " << std::string(res.i, res.e));
}
return std::move(f.log);
}
};
template <class... Ts>
log_type make_log(Ts&&... xs) {
return log_type{std::forward<Ts>(xs)...};
}
const char* ini0 = R"(
[logger]
padding= 10
file-name = "foobar.ini" ; our file name
[scheduler] ; more settings
timing = 2us ; using microsecond resolution
impl = 'foo';some atom
x_ =.123
some-bool=true
some-other-bool=false
some-list=[
; here we have some list entries
123,
23 ; twenty-three!
,
"abc",
'def', ; some comment and a trailing comma
]
some-map={
; here we have some list entries
entry1=123,
entry2=23 ; twenty-three!
,
entry3= "abc",
entry4 = 'def', ; some comment and a trailing comma
}
[middleman]
preconnect=[<
tcp://localhost:8080
>,<udp://remotehost?trust=false>]
)";
const auto ini0_log = make_log(
"key: logger",
"{",
"key: padding",
"value (integer): 10",
"key: file-name",
"value (string): \"foobar.ini\"",
"}",
"key: scheduler",
"{",
"key: timing",
"value (timespan): 2us",
"key: impl",
"value (atom): 'foo'",
"key: x_",
"value (real): " + deep_to_string(.123),
"key: some-bool",
"value (boolean): true",
"key: some-other-bool",
"value (boolean): false",
"key: some-list",
"[",
"value (integer): 123",
"value (integer): 23",
"value (string): \"abc\"",
"value (atom): 'def'",
"]",
"key: some-map",
"{",
"key: entry1",
"value (integer): 123",
"key: entry2",
"value (integer): 23",
"key: entry3",
"value (string): \"abc\"",
"key: entry4",
"value (atom): 'def'",
"}",
"}",
"key: middleman",
"{",
"key: preconnect",
"[",
"value (uri): tcp://localhost:8080",
"value (uri): udp://remotehost?trust=false",
"]",
"}"
);
} // namespace <anonymous>
CAF_TEST_FIXTURE_SCOPE(read_ini_tests, fixture)
CAF_TEST(empty inis) {
CAF_CHECK_EQUAL(parse(";foo"), make_log());
CAF_CHECK_EQUAL(parse(""), make_log());
CAF_CHECK_EQUAL(parse(" "), make_log());
CAF_CHECK_EQUAL(parse(" \n "), make_log());
CAF_CHECK_EQUAL(parse(";hello\n;world"), make_log());
}
CAF_TEST(section with valid key-value pairs) {
CAF_CHECK_EQUAL(parse("[foo]"), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse(" [foo]"), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse(" [ foo] "), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse(" [ foo ] "), make_log("key: foo", "{", "}"));
CAF_CHECK_EQUAL(parse("\n[a-b];foo\n;bar"), make_log("key: a-b", "{", "}"));
CAF_CHECK_EQUAL(parse(ini0), ini0_log);
}
CAF_TEST_FIXTURE_SCOPE_END()
| Fix check in INI unit test | Fix check in INI unit test
| C++ | bsd-3-clause | actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework |
27c7864085ccd71f0388ac3993ee09e062bd2ee2 | libs/platform/xlib/window.cpp | libs/platform/xlib/window.cpp |
#include "window.h"
#include <base/pointer.h>
#include <string.h>
#include <iostream>
#include <base/contract.h>
#include <base/scope_guard.h>
#include <stdexcept>
#include <gl/check.h>
namespace {
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
const int visual_attribs[] =
{
// GLX_X_RENDERABLE , True,
GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
GLX_RENDER_TYPE , GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_DEPTH_SIZE , 24,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER , True,
GLX_SAMPLE_BUFFERS , 1,
GLX_SAMPLES , 4,
None
};
/*
static bool isExtensionSupported(const char *extList, const char *extension)
{
const char *start;
const char *where, *terminator;
// Extension names should not have spaces.
where = strchr(extension, ' ');
if (where || *extension == '\0')
return false;
// It takes a bit of care to be fool-proof about parsing the
// OpenGL extensions string. Don't be fooled by sub-strings, etc.
for (start=extList;;) {
where = strstr(start, extension);
if (!where)
break;
terminator = where + strlen(extension);
if ( where == start || *(where - 1) == ' ' )
if ( *terminator == ' ' || *terminator == '\0' )
return true;
start = terminator;
}
return false;
}
*/
}
namespace platform { namespace xlib
{
////////////////////////////////////////
window::window( const std::shared_ptr<Display> &dpy )
: _display( dpy )
{
precondition( _display, "null display" );
Display *disp = _display.get();
// Check GLX version. Version 1.3 is needed for FBConfig
int glx_major, glx_minor;
if ( !glXQueryVersion( disp, &glx_major, &glx_minor ) )
throw std::runtime_error( "glx query version failed" );
if ( ( ( glx_major == 1 ) && ( glx_minor < 3 ) ) || ( glx_major < 1 ) )
throw std::runtime_error( "glx too old" );
// Get the framebuffer configs
int fbcount;
GLXFBConfig* fbc = glXChooseFBConfig( disp, DefaultScreen( disp ), visual_attribs, &fbcount );
if ( fbc == nullptr )
throw std::runtime_error( "failed to get GL framebuffer configs" );
on_scope_exit { XFree( fbc ); };
// Find the best framebuffer
int best_fbc = -1, best_num_samp = -1;
for ( int i = 0; i < fbcount; ++i )
{
XVisualInfo *vi = glXGetVisualFromFBConfig( disp, fbc[i] );
on_scope_exit { XFree( vi ); };
if ( vi != nullptr )
{
int samp_buf, samples;
glXGetFBConfigAttrib( disp, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
glXGetFBConfigAttrib( disp, fbc[i], GLX_SAMPLES, &samples );
if ( best_fbc < 0 || ( samp_buf && samples > best_num_samp ) )
best_fbc = i, best_num_samp = samples;
}
}
GLXFBConfig bestFbc = fbc[ best_fbc ];
XVisualInfo *vi = glXGetVisualFromFBConfig( disp, bestFbc );
if ( vi == nullptr )
throw std::runtime_error( "no glx visual found" );
on_scope_exit { XFree( vi ); };
XSetWindowAttributes swa;
swa.background_pixmap = None;
swa.border_pixel = 0;
swa.event_mask =
ExposureMask | StructureNotifyMask | VisibilityChangeMask |
EnterWindowMask | LeaveWindowMask |
KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask |
PointerMotionMask | ButtonMotionMask;
Window root = DefaultRootWindow( disp );
swa.colormap = XCreateColormap( disp, root, vi->visual, AllocNone );
_win = XCreateWindow( disp, root, 0, 0, 320, 240, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa );
// Get the default screen's GLX extension list
// NOTE: It is not necessary to create or make current to a context before
// calling glXGetProcAddressARB
auto glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );
// If it does, try to get a GL 4.0 context!
int atrributes[] =
{
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 3,
None
};
_glc = glXCreateContextAttribsARB( disp, bestFbc, 0, True, atrributes );
glXMakeCurrent( disp, _win, _glc );
int err = gl3wInit();
if ( err != 0 )
throw std::runtime_error( "failed to intialize gl3w" );
if ( !gl3wIsSupported( 3, 3 ) )
throw std::runtime_error( "opengl 3.3 not supported" );
// Sync to ensure any errors generated are processed.
XSync( disp, False );
}
////////////////////////////////////////
window::~window( void )
{
}
////////////////////////////////////////
void window::raise( void )
{
XRaiseWindow( _display.get(), _win );
}
////////////////////////////////////////
void window::lower( void )
{
XLowerWindow( _display.get(), _win );
}
////////////////////////////////////////
void window::set_popup( void )
{
XSetWindowAttributes swa;
swa.override_redirect = true;
XChangeWindowAttributes( _display.get(), _win, CWOverrideRedirect, &swa );
_popup = true;
}
////////////////////////////////////////
void window::show( void )
{
XMapWindow( _display.get(), _win );
if ( _popup )
XRaiseWindow( _display.get(), _win );
}
////////////////////////////////////////
void window::hide( void )
{
XUnmapWindow( _display.get(), _win );
}
////////////////////////////////////////
bool window::is_visible( void )
{
// TODO fix this
return true;
}
////////////////////////////////////////
/*
rect window::geometry( void )
{
}
*/
////////////////////////////////////////
void window::move( double x, double y )
{
XMoveWindow( _display.get(), _win, int( x + 0.5 ), int( y + 0.5 ) );
}
////////////////////////////////////////
void window::resize( double w, double h )
{
XResizeWindow( _display.get(), _win, (unsigned int)( std::max( 0.0, w ) + 0.5 ), (unsigned int)( std::max( 0.0, h ) + 0.5 ) );
}
////////////////////////////////////////
void window::set_minimum_size( double w, double h )
{
}
////////////////////////////////////////
void window::set_title( const std::string &t )
{
XStoreName( _display.get(), _win, t.c_str() );
}
////////////////////////////////////////
void window::invalidate( const base::rect &r )
{
if ( !_invalid )
{
XClearArea( _display.get(), _win, 0, 0, 0, 0, True );
_invalid = true;
}
}
////////////////////////////////////////
void window::acquire( void )
{
glXMakeCurrent( _display.get(), _win, _glc );
}
////////////////////////////////////////
void window::release( void )
{
glXMakeCurrent( _display.get(), None, nullptr );
}
////////////////////////////////////////
Window window::id( void ) const
{
return _win;
}
////////////////////////////////////////
void window::move_event( double x, double y )
{
if ( _last_x != x && _last_y != y )
{
_last_x = x;
_last_y = y;
moved( x, y );
}
}
////////////////////////////////////////
void window::resize_event( double w, double h )
{
if ( _last_w != h && _last_w != h )
{
_last_w = w;
_last_h = h;
glXMakeCurrent( _display.get(), _win, _glc );
glViewport( 0, 0, w, h );
resized( w, h );
}
}
////////////////////////////////////////
void window::expose_event( void )
{
_invalid = false;
glXMakeCurrent( _display.get(), _win, _glc );
exposed();
glXSwapBuffers( _display.get(), _win );
glFlush();
XFlush( _display.get() );
}
////////////////////////////////////////
} }
|
#include "window.h"
#include <base/pointer.h>
#include <string.h>
#include <iostream>
#include <base/contract.h>
#include <base/scope_guard.h>
#include <stdexcept>
#include <gl/check.h>
namespace {
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
const int visual_attribs[] =
{
// GLX_X_RENDERABLE , True,
GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
GLX_RENDER_TYPE , GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 2, // only use 2 in case we're on a 10-bit display
GLX_DEPTH_SIZE , 24,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER , True,
GLX_SAMPLE_BUFFERS , 1,
GLX_SAMPLES , 4,
None
};
/*
static bool isExtensionSupported(const char *extList, const char *extension)
{
const char *start;
const char *where, *terminator;
// Extension names should not have spaces.
where = strchr(extension, ' ');
if (where || *extension == '\0')
return false;
// It takes a bit of care to be fool-proof about parsing the
// OpenGL extensions string. Don't be fooled by sub-strings, etc.
for (start=extList;;) {
where = strstr(start, extension);
if (!where)
break;
terminator = where + strlen(extension);
if ( where == start || *(where - 1) == ' ' )
if ( *terminator == ' ' || *terminator == '\0' )
return true;
start = terminator;
}
return false;
}
*/
}
namespace platform { namespace xlib
{
////////////////////////////////////////
window::window( const std::shared_ptr<Display> &dpy )
: _display( dpy )
{
precondition( _display, "null display" );
Display *disp = _display.get();
// Check GLX version. Version 1.3 is needed for FBConfig
int glx_major, glx_minor;
if ( !glXQueryVersion( disp, &glx_major, &glx_minor ) )
throw std::runtime_error( "glx query version failed" );
if ( ( ( glx_major == 1 ) && ( glx_minor < 3 ) ) || ( glx_major < 1 ) )
throw std::runtime_error( "glx too old" );
// Get the framebuffer configs
int fbcount;
GLXFBConfig* fbc = glXChooseFBConfig( disp, DefaultScreen( disp ), visual_attribs, &fbcount );
if ( fbc == nullptr )
throw std::runtime_error( "failed to get GL framebuffer configs" );
on_scope_exit { XFree( fbc ); };
// Find the best framebuffer
int best_fbc = -1, best_num_samp = -1;
for ( int i = 0; i < fbcount; ++i )
{
XVisualInfo *vi = glXGetVisualFromFBConfig( disp, fbc[i] );
on_scope_exit { XFree( vi ); };
if ( vi != nullptr )
{
int samp_buf, samples;
glXGetFBConfigAttrib( disp, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
glXGetFBConfigAttrib( disp, fbc[i], GLX_SAMPLES, &samples );
if ( best_fbc < 0 || ( samp_buf && samples > best_num_samp ) )
best_fbc = i, best_num_samp = samples;
}
}
GLXFBConfig bestFbc = fbc[ best_fbc ];
XVisualInfo *vi = glXGetVisualFromFBConfig( disp, bestFbc );
if ( vi == nullptr )
throw std::runtime_error( "no glx visual found" );
on_scope_exit { XFree( vi ); };
XSetWindowAttributes swa;
swa.background_pixmap = None;
swa.border_pixel = 0;
swa.event_mask =
ExposureMask | StructureNotifyMask | VisibilityChangeMask |
EnterWindowMask | LeaveWindowMask |
KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask |
PointerMotionMask | ButtonMotionMask;
Window root = DefaultRootWindow( disp );
swa.colormap = XCreateColormap( disp, root, vi->visual, AllocNone );
_win = XCreateWindow( disp, root, 0, 0, 320, 240, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa );
// Get the default screen's GLX extension list
// NOTE: It is not necessary to create or make current to a context before
// calling glXGetProcAddressARB
auto glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );
// If it does, try to get a GL 4.0 context!
int atrributes[] =
{
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 3,
None
};
_glc = glXCreateContextAttribsARB( disp, bestFbc, 0, True, atrributes );
glXMakeCurrent( disp, _win, _glc );
int err = gl3wInit();
if ( err != 0 )
throw std::runtime_error( "failed to intialize gl3w" );
if ( !gl3wIsSupported( 3, 3 ) )
throw std::runtime_error( "opengl 3.3 not supported" );
// Sync to ensure any errors generated are processed.
XSync( disp, False );
}
////////////////////////////////////////
window::~window( void )
{
}
////////////////////////////////////////
void window::raise( void )
{
XRaiseWindow( _display.get(), _win );
}
////////////////////////////////////////
void window::lower( void )
{
XLowerWindow( _display.get(), _win );
}
////////////////////////////////////////
void window::set_popup( void )
{
XSetWindowAttributes swa;
swa.override_redirect = true;
XChangeWindowAttributes( _display.get(), _win, CWOverrideRedirect, &swa );
_popup = true;
}
////////////////////////////////////////
void window::show( void )
{
XMapWindow( _display.get(), _win );
if ( _popup )
XRaiseWindow( _display.get(), _win );
}
////////////////////////////////////////
void window::hide( void )
{
XUnmapWindow( _display.get(), _win );
}
////////////////////////////////////////
bool window::is_visible( void )
{
// TODO fix this
return true;
}
////////////////////////////////////////
/*
rect window::geometry( void )
{
}
*/
////////////////////////////////////////
void window::move( double x, double y )
{
XMoveWindow( _display.get(), _win, int( x + 0.5 ), int( y + 0.5 ) );
}
////////////////////////////////////////
void window::resize( double w, double h )
{
XResizeWindow( _display.get(), _win, (unsigned int)( std::max( 0.0, w ) + 0.5 ), (unsigned int)( std::max( 0.0, h ) + 0.5 ) );
}
////////////////////////////////////////
void window::set_minimum_size( double w, double h )
{
}
////////////////////////////////////////
void window::set_title( const std::string &t )
{
XStoreName( _display.get(), _win, t.c_str() );
}
////////////////////////////////////////
void window::invalidate( const base::rect &r )
{
if ( !_invalid )
{
XClearArea( _display.get(), _win, 0, 0, 0, 0, True );
_invalid = true;
}
}
////////////////////////////////////////
void window::acquire( void )
{
glXMakeCurrent( _display.get(), _win, _glc );
}
////////////////////////////////////////
void window::release( void )
{
glXMakeCurrent( _display.get(), None, nullptr );
}
////////////////////////////////////////
Window window::id( void ) const
{
return _win;
}
////////////////////////////////////////
void window::move_event( double x, double y )
{
if ( _last_x != x && _last_y != y )
{
_last_x = x;
_last_y = y;
moved( x, y );
}
}
////////////////////////////////////////
void window::resize_event( double w, double h )
{
if ( _last_w != h && _last_w != h )
{
_last_w = w;
_last_h = h;
glXMakeCurrent( _display.get(), _win, _glc );
glViewport( 0, 0, w, h );
resized( w, h );
}
}
////////////////////////////////////////
void window::expose_event( void )
{
_invalid = false;
glXMakeCurrent( _display.get(), _win, _glc );
exposed();
glXSwapBuffers( _display.get(), _win );
glFlush();
XFlush( _display.get() );
}
////////////////////////////////////////
} }
| fix glx fb config on 10-bit display | fix glx fb config on 10-bit display
| C++ | mit | kdt3rd/gecko,kdt3rd/gecko,kdt3rd/gecko,kdt3rd/gecko |
b01a2265114cceeaa737d078046cb48451e1bf14 | src/main_help.cpp | src/main_help.cpp | // illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver 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.
//
// illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include "main_help.hpp"
#include "Config.hpp"
#include "Logger.hpp"
#include "Player.hpp"
#include "World.hpp"
#include "data/MonsterTable.hpp"
#include "data/RaceTypeTable.hpp"
#include "data/ScheduledScriptsTable.hpp"
#include "netinterface/NetInterface.hpp"
#include "script/server.hpp"
#include <csignal>
#include <memory>
#include <sstream>
#include <string>
std::unique_ptr<ScheduledScriptsTable> scheduledScripts;
std::unique_ptr<MonsterTable> monsterDescriptions;
std::unique_ptr<RaceTypeTable> raceTypes;
// break out of the main loop if false
std::atomic_bool running;
void logout_save(Player *who, bool forced, unsigned long int thistime) {
time_t acttime = 0;
time(&acttime);
thistime = acttime - who->lastsavetime;
who->onlinetime += thistime;
static constexpr auto secondsInMinute = 60;
static constexpr auto secondsInHour = 60 * 60;
unsigned int th = thistime / secondsInHour;
unsigned int tm = (thistime % secondsInHour) / secondsInMinute;
unsigned int ts = (thistime % secondsInHour) % secondsInMinute;
unsigned int oh = who->onlinetime / secondsInHour;
unsigned int om = (who->onlinetime % secondsInHour) / secondsInMinute;
unsigned int os = (who->onlinetime % secondsInHour) % secondsInMinute;
std::stringstream onlinetime;
onlinetime << " after " << th << "h " << tm << "m " << ts << "s, onlinetime " << oh << "h " << om << "m " << os
<< "s";
Logger::info(LogFacility::Player) << (forced ? "forced " : "") << "logout: " << who->Connection->getIPAdress()
<< *who << " on " << ctime(&acttime) << onlinetime.str() << Log::end;
}
void login_save(Player *who) {
time_t acttime = 0;
time(&acttime);
static constexpr auto secondsInMinute = 60;
static constexpr auto secondsInHour = 60 * 60;
unsigned int oh = who->onlinetime / secondsInHour;
unsigned int om = (who->onlinetime % secondsInHour) / secondsInMinute;
unsigned int os = (who->onlinetime % secondsInHour) % secondsInMinute;
std::stringstream onlinetime;
onlinetime << " onlinetime till now: " << oh << "h " << om << "m " << os << "s";
Logger::info(LogFacility::Player) << "login of " << *who << " from " << who->Connection->getIPAdress() << " on "
<< ctime(&acttime) << onlinetime.str() << Log::end;
}
// process commandline arguments
auto checkArguments(const std::vector<std::string> &args) -> bool {
if (args.size() == 2) {
// config file specified on command line
if (Config::load(args.at(1))) {
Logger::info(LogFacility::Other) << "main: using configfile: " << args.at(1) << Log::end;
return true;
}
Logger::error(LogFacility::Other) << "main: error reading configfile: " << args.at(1) << Log::end;
Logger::error(LogFacility::Other) << "main: USAGE: " << args.at(0) << " configfile" << Log::end;
return false;
}
Logger::error(LogFacility::Other) << "main: invalid commandline arguments" << Log::end;
Logger::error(LogFacility::Other) << "main: USAGE: " << args.at(0) << " configfile" << Log::end;
return false;
}
// load item definitions
void loadData() {
scheduledScripts = std::make_unique<ScheduledScriptsTable>();
monsterDescriptions = std::make_unique<MonsterTable>();
raceTypes = std::make_unique<RaceTypeTable>();
script::server::reload();
}
void sig_term(int /*unused*/) {
Logger::info(LogFacility::Other) << "SIGTERM received!" << Log::end;
std::signal(SIGTERM, SIG_IGN); // NOLINT
World::get()->allowLogin(false);
running = false;
}
// signal handler for SIGSEGV
void sig_segv(int /*unused*/) {
Logger::error(LogFacility::Other) << "SIGSEGV received! Last Script: " << World::get()->currentScript->getFileName()
<< Log::end;
}
// signal handler for SIGUSR1 - Used to reload maps
void sig_usr(int /*unused*/) {
std::signal(SIGUSR1, SIG_IGN); // NOLINT
Logger::info(LogFacility::World) << "SIGUSR1 received! Importing new maps." << Log::end;
Logger::info(LogFacility::World) << "Disable login and force log out of all players." << Log::end;
World *world = World::get();
world->allowLogin(false);
world->forceLogoutOfAllPlayers();
world->import();
world->allowLogin(true);
Logger::info(LogFacility::World) << "Map import finished." << Log::end;
std::signal(SIGUSR1, sig_usr);
}
void init_sighandlers() {
std::signal(SIGPIPE, SIG_IGN); // NOLINT
std::signal(SIGCHLD, SIG_IGN); // NOLINT
std::signal(SIGINT, SIG_IGN); // NOLINT
std::signal(SIGQUIT, SIG_IGN); // NOLINT
std::signal(SIGTERM, sig_term);
std::signal(SIGSEGV, sig_segv);
std::signal(SIGUSR1, sig_usr);
}
void reset_sighandlers() {
std::signal(SIGPIPE, SIG_DFL);
std::signal(SIGTERM, SIG_DFL);
std::signal(SIGSEGV, SIG_DFL);
}
| // illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver 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.
//
// illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>.
#include "main_help.hpp"
#include "Config.hpp"
#include "Logger.hpp"
#include "Player.hpp"
#include "World.hpp"
#include "data/MonsterTable.hpp"
#include "data/RaceTypeTable.hpp"
#include "data/ScheduledScriptsTable.hpp"
#include "netinterface/NetInterface.hpp"
#include "script/server.hpp"
#include <csignal>
#include <exception>
#include <memory>
#include <sstream>
#include <string>
std::unique_ptr<ScheduledScriptsTable> scheduledScripts;
std::unique_ptr<MonsterTable> monsterDescriptions;
std::unique_ptr<RaceTypeTable> raceTypes;
// break out of the main loop if false
std::atomic_bool running;
void logout_save(Player *who, bool forced, unsigned long int thistime) {
time_t acttime = 0;
time(&acttime);
thistime = acttime - who->lastsavetime;
who->onlinetime += thistime;
static constexpr auto secondsInMinute = 60;
static constexpr auto secondsInHour = 60 * 60;
unsigned int th = thistime / secondsInHour;
unsigned int tm = (thistime % secondsInHour) / secondsInMinute;
unsigned int ts = (thistime % secondsInHour) % secondsInMinute;
unsigned int oh = who->onlinetime / secondsInHour;
unsigned int om = (who->onlinetime % secondsInHour) / secondsInMinute;
unsigned int os = (who->onlinetime % secondsInHour) % secondsInMinute;
std::stringstream onlinetime;
onlinetime << " after " << th << "h " << tm << "m " << ts << "s, onlinetime " << oh << "h " << om << "m " << os
<< "s";
Logger::info(LogFacility::Player) << (forced ? "forced " : "") << "logout: " << who->Connection->getIPAdress()
<< *who << " on " << ctime(&acttime) << onlinetime.str() << Log::end;
}
void login_save(Player *who) {
time_t acttime = 0;
time(&acttime);
static constexpr auto secondsInMinute = 60;
static constexpr auto secondsInHour = 60 * 60;
unsigned int oh = who->onlinetime / secondsInHour;
unsigned int om = (who->onlinetime % secondsInHour) / secondsInMinute;
unsigned int os = (who->onlinetime % secondsInHour) % secondsInMinute;
std::stringstream onlinetime;
onlinetime << " onlinetime till now: " << oh << "h " << om << "m " << os << "s";
Logger::info(LogFacility::Player) << "login of " << *who << " from " << who->Connection->getIPAdress() << " on "
<< ctime(&acttime) << onlinetime.str() << Log::end;
}
// process commandline arguments
auto checkArguments(const std::vector<std::string> &args) -> bool {
if (args.size() == 2) {
// config file specified on command line
if (Config::load(args.at(1))) {
Logger::info(LogFacility::Other) << "main: using configfile: " << args.at(1) << Log::end;
return true;
}
Logger::error(LogFacility::Other) << "main: error reading configfile: " << args.at(1) << Log::end;
Logger::error(LogFacility::Other) << "main: USAGE: " << args.at(0) << " configfile" << Log::end;
return false;
}
Logger::error(LogFacility::Other) << "main: invalid commandline arguments" << Log::end;
Logger::error(LogFacility::Other) << "main: USAGE: " << args.at(0) << " configfile" << Log::end;
return false;
}
// load item definitions
void loadData() {
scheduledScripts = std::make_unique<ScheduledScriptsTable>();
monsterDescriptions = std::make_unique<MonsterTable>();
raceTypes = std::make_unique<RaceTypeTable>();
script::server::reload();
}
void sig_term(int /*unused*/) {
Logger::info(LogFacility::Other) << "SIGTERM received!" << Log::end;
std::signal(SIGTERM, SIG_IGN); // NOLINT
World::get()->allowLogin(false);
running = false;
}
// signal handler for SIGSEGV
void sig_segv(int /*unused*/) {
Logger::error(LogFacility::Other) << "SIGSEGV received! Last Script: " << World::get()->currentScript->getFileName()
<< Log::end;
std::terminate();
}
// signal handler for SIGUSR1 - Used to reload maps
void sig_usr(int /*unused*/) {
std::signal(SIGUSR1, SIG_IGN); // NOLINT
Logger::info(LogFacility::World) << "SIGUSR1 received! Importing new maps." << Log::end;
Logger::info(LogFacility::World) << "Disable login and force log out of all players." << Log::end;
World *world = World::get();
world->allowLogin(false);
world->forceLogoutOfAllPlayers();
world->import();
world->allowLogin(true);
Logger::info(LogFacility::World) << "Map import finished." << Log::end;
std::signal(SIGUSR1, sig_usr);
}
void init_sighandlers() {
std::signal(SIGPIPE, SIG_IGN); // NOLINT
std::signal(SIGCHLD, SIG_IGN); // NOLINT
std::signal(SIGINT, SIG_IGN); // NOLINT
std::signal(SIGQUIT, SIG_IGN); // NOLINT
std::signal(SIGTERM, sig_term);
std::signal(SIGSEGV, sig_segv);
std::signal(SIGUSR1, sig_usr);
}
void reset_sighandlers() {
std::signal(SIGPIPE, SIG_DFL);
std::signal(SIGTERM, SIG_DFL);
std::signal(SIGSEGV, SIG_DFL);
}
| Call std::terminate on SIGSEGV to generate core dump | Call std::terminate on SIGSEGV to generate core dump
| C++ | agpl-3.0 | Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server |
e6726994fed4a3049cba03139ee029dc96345bc9 | SFMLUtilities.cpp | SFMLUtilities.cpp | #include "SFMLUtilities.h"
#include <random>
#include <iostream>
namespace zmc
{
SFMLUtilities::SFMLUtilities()
{
}
sf::Vector2f SFMLUtilities::getCenterPosition(sf::Vector2u parentSize, sf::Sprite &sprite)
{
sf::Vector2f vector((int)parentSize.x / 2 - (sprite.getTexture()->getSize().x / 2) * sprite.getScale().x , (int)parentSize.y / 2 - (sprite.getTexture()->getSize().y / 2)
* sprite.getScale().y);
return vector;
}
sf::Vector2f SFMLUtilities::getScaledSize(const sf::Sprite &sprite/*, const sf::IntRect &customRect*/)
{
sf::Vector2f vector;
// if (customRect.height > 0 || customRect.width > 0)
// vector = sf::Vector2f(customRect.width * sprite.getScale().x , customRect.height * sprite.getScale().y);
// else
vector = sf::Vector2f(sprite.getTexture()->getSize().x * sprite.getScale().x , sprite.getTexture()->getSize().y * sprite.getScale().y);
return vector;
}
const std::vector<int> SFMLUtilities::getDigits(int n)
{
std::vector<int> array;
std::vector<int> array2;
if (n == 0) {
array2.push_back(0);
return array2;
}
int number = n;
while (number > 0) {
int mod = number % 10;
array.push_back(mod);
number -= mod;
number /= 10;
}
for (unsigned int i = array.size() - 1; i < array.size(); i--) {
array2.push_back(array.at(i));
}
return array2;
}
const sf::IntRect SFMLUtilities::getScaledTextureRect(const sf::Sprite &sprite)
{
sf::IntRect intRect;
intRect.top = (int)sprite.getPosition().y;
intRect.left = (int)sprite.getPosition().x;
intRect.height = (int)getScaledSize(sprite).y;
intRect.width = (int)getScaledSize(sprite).x;
return intRect;
}
int SFMLUtilities::generateRandomNumber(int start, int end, int seed)
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(seed == 0 ? rd() : seed); // seed the generator
std::uniform_int_distribution<> distr(start, end); // define the range
return distr(eng);
}
sf::Vector2f SFMLUtilities::getFitToAlignScale(sf::Vector2u textureSize, sf::Vector2u containerSize)
{
float imageHeight = (float)textureSize.y;
float imageWidth = (float)textureSize.x;
float rImage = imageWidth / imageHeight;
float screenHeight = (float)containerSize.y;
float screenWidth = (float)containerSize.x;
float rScreen = screenWidth / screenHeight;
// rs > ri ? (wi * hs/hi, hs) : (ws, hi * ws/wi)
sf::Vector2f size(rScreen > rImage ? (imageWidth * screenHeight / imageHeight) : screenWidth,
rScreen > rImage ? screenHeight : imageHeight * screenWidth / imageWidth);
float scalex = (float)size.x / (float)textureSize.x;
float scaley = (float)size.y / (float)textureSize.y;
return sf::Vector2f(scalex, scaley);
}
float SFMLUtilities::toSFMLCoordinate(float box2dCoord)
{
return box2dCoord * 30;
}
float SFMLUtilities::toBox2DCoordinate(float sfmlCoord)
{
return sfmlCoord / 30;
}
float SFMLUtilities::toDegree(float radian)
{
const float PI = 3.14159265f;
return (radian * 180 / PI);
}
float SFMLUtilities::toRadian(float degree)
{
const float PI = 3.14159265f;
return (degree * PI / 180);
}
float SFMLUtilities::distanceBetweenTwoVectors(sf::Vector2f firstVector, sf::Vector2f secondVector)
{
return std::sqrt(std::pow((firstVector.x - secondVector.x), 2) + std::pow((firstVector.y - secondVector.y), 2));
}
float SFMLUtilities::getAngleBetweenTwoVectors(sf::Vector2f firstVector, sf::Vector2f secondVector)
{
float rotation = 0;
rotation = (float) toDegree(std::atan2(firstVector.x - secondVector.x, firstVector.y - secondVector.y));
if (rotation < 0) {
rotation += 360;
}
return rotation;
}
bool SFMLUtilities::intersects(const sf::Sprite *firstSprite, const sf::Sprite *secondSprite)
{
sf::IntRect firstRect(firstSprite->getPosition().x, firstSprite->getPosition().y
, getScaledSize(*firstSprite).x, getScaledSize(*firstSprite).y);
sf::IntRect secondRect(secondSprite->getPosition().x, secondSprite->getPosition().y
, getScaledSize(*secondSprite).x, getScaledSize(*secondSprite).y);
return firstRect.intersects(secondRect);
}
}
| #include "SFMLUtilities.h"
#include <random>
#include <iostream>
namespace zmc
{
SFMLUtilities::SFMLUtilities()
{
}
sf::Vector2f SFMLUtilities::getCenterPosition(sf::Vector2u parentSize, sf::Sprite &sprite)
{
sf::Vector2f vector((int)parentSize.x / 2 - (sprite.getTexture()->getSize().x / 2) * sprite.getScale().x , (int)parentSize.y / 2 - (sprite.getTexture()->getSize().y / 2)
* sprite.getScale().y);
return vector;
}
sf::Vector2f SFMLUtilities::getScaledSize(const sf::Sprite &sprite/*, const sf::IntRect &customRect*/)
{
sf::Vector2f vector;
// if (customRect.height > 0 || customRect.width > 0)
// vector = sf::Vector2f(customRect.width * sprite.getScale().x , customRect.height * sprite.getScale().y);
// else
vector = sf::Vector2f(sprite.getTexture()->getSize().x * sprite.getScale().x , sprite.getTexture()->getSize().y * sprite.getScale().y);
return vector;
}
const std::vector<int> SFMLUtilities::getDigits(int n)
{
std::vector<int> array;
std::vector<int> array2;
if (n == 0) {
array2.push_back(0);
return array2;
}
int number = n;
while (number > 0) {
int mod = number % 10;
array.push_back(mod);
number -= mod;
number /= 10;
}
for (unsigned int i = array.size() - 1; i < array.size(); i--) {
array2.push_back(array.at(i));
}
return array2;
}
const sf::IntRect SFMLUtilities::getScaledTextureRect(const sf::Sprite &sprite)
{
sf::IntRect intRect;
intRect.top = (int)sprite.getPosition().y;
intRect.left = (int)sprite.getPosition().x;
intRect.height = (int)getScaledSize(sprite).y;
intRect.width = (int)getScaledSize(sprite).x;
return intRect;
}
int SFMLUtilities::generateRandomNumber(int start, int end, int seed)
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(seed == 0 ? rd() : seed); // seed the generator
std::uniform_int_distribution<> distr(start, end); // define the range
return distr(eng);
}
sf::Vector2f SFMLUtilities::getFitToAlignScale(sf::Vector2u textureSize, sf::Vector2u containerSize)
{
float imageHeight = (float)textureSize.y;
float imageWidth = (float)textureSize.x;
float rImage = imageWidth / imageHeight;
float screenHeight = (float)containerSize.y;
float screenWidth = (float)containerSize.x;
float rScreen = screenWidth / screenHeight;
// rs > ri ? (wi * hs/hi, hs) : (ws, hi * ws/wi)
sf::Vector2f size(rScreen > rImage ? (imageWidth * screenHeight / imageHeight) : screenWidth,
rScreen > rImage ? screenHeight : imageHeight * screenWidth / imageWidth);
float scalex = (float)size.x / (float)textureSize.x;
float scaley = (float)size.y / (float)textureSize.y;
return sf::Vector2f(scalex, scaley);
}
float SFMLUtilities::toSFMLCoordinate(float box2dCoord)
{
return box2dCoord * 30;
}
float SFMLUtilities::toBox2DCoordinate(float sfmlCoord)
{
return sfmlCoord / 30;
}
float SFMLUtilities::toDegree(float radian)
{
const float PI = 3.14159265f;
return (radian * 180 / PI);
}
float SFMLUtilities::toRadian(float degree)
{
const float PI = 3.14159265f;
return (degree * PI / 180);
}
float SFMLUtilities::distanceBetweenTwoVectors(sf::Vector2f firstVector, sf::Vector2f secondVector)
{
return std::sqrt(std::pow((firstVector.x - secondVector.x), 2) + std::pow((firstVector.y - secondVector.y), 2));
}
float SFMLUtilities::getAngleBetweenTwoVectors(sf::Vector2f firstVector, sf::Vector2f secondVector)
{
float rotation = 0;
rotation = (float) toDegree(std::atan2(firstVector.x - secondVector.x, firstVector.y - secondVector.y));
if (rotation < 0) {
rotation += 360;
}
return rotation;
}
bool SFMLUtilities::intersects(const sf::Sprite *firstSprite, const sf::Sprite *secondSprite)
{
sf::IntRect firstRect((int)firstSprite->getPosition().x, (int)firstSprite->getPosition().y
, (int)getScaledSize(*firstSprite).x, (int)getScaledSize(*firstSprite).y);
sf::IntRect secondRect((int)secondSprite->getPosition().x, (int)secondSprite->getPosition().y
, (int)getScaledSize(*secondSprite).x, (int)getScaledSize(*secondSprite).y);
return firstRect.intersects(secondRect);
}
}
| Add int casting | Add int casting
| C++ | unlicense | Furkanzmc/SFMLUtilities |
5fd92325ba2415f1b18c1ae5b3ae7df092471b84 | Shared/Engine.cpp | Shared/Engine.cpp | /**
@file Engine.cpp
Game scene flow.
<pre>
+---------------------------------------------------------------------------------------+
| |
| +--------------------------------+ |
| | +---------------------------+ | |
V V V | | |
+-------+ +-------------+ +-----------+ +---------------+ | | |
| Title |--->| Start event |--->| Main game |-+->| Success event |-+ | |
+-------+ +-------------+ +-----------+ | +---------------+ | |
| | |
| +---------------+ | +-----------------+ |
+->| Failure event |---+->| Game over event |-+
+---------------+ +-----------------+
</pre>
*/
#include "Engine.h"
#include "Window.h"
#include <time.h>
#ifdef __ANDROID__
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__))
#else
#define LOGI(...) ((void)printf(__VA_ARGS__), (void)printf("\n"))
#define LOGE(...) ((void)printf(__VA_ARGS__), (void)printf("\n"))
#endif // __ANDROID__
namespace Mai {
int_fast64_t get_time() {
#ifdef __ANDROID__
#if 1
timespec tmp;
clock_gettime(CLOCK_MONOTONIC, &tmp);
return tmp.tv_sec * (1000UL * 1000UL * 1000UL) + tmp.tv_nsec;
#else
static int sfd = -1;
if (sfd == -1) {
sfd = open("/dev/alarm", O_RDONLY);
}
timespec ts;
const int result = ioctl(sfd, ANDROID_ALARM_GET_TIME(ANDROID_ALARM_ELAPSED_REALTIME), &ts);
if (result != 0) {
const int err = clock_gettime(CLOCK_MONOTONIC, &ts);
if (err < 0) {
LOGI("ERROR(%d) from; clock_gettime(CLOCK_MONOTONIC)", err);
}
}
return ts.tv_sec * (1000 * 1000 * 1000) + ts.tv_nsec;
#endif
#else
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
return ft.dwHighDateTime * 10000000LL + ft.dwLowDateTime * 100LL;
#endif // __ANDROID__
}
Engine::Engine(Window* p)
: initialized(false)
, pWindow(p)
, renderer()
, avgFps(30.0f)
, deltaTime(1.0f / avgFps)
, frames(0)
, latestFps(30)
, startTime(0)
, commonDataDeleter(nullptr)
{
}
Engine::~Engine() {
if (commonDataDeleter) {
commonDataDeleter(commonData.data());
}
}
Engine::State Engine::ProcessWindowEvent(Window& window) {
window.MessageLoop();
while (auto e = window.PopEvent()) {
switch (e->Type) {
case Event::EVENT_CLOSED:
TermDisplay();
return STATE_TERMINATE;
case Event::EVENT_INIT_WINDOW:
audio.reset();
audio = CreateAudioEngine();
InitDisplay();
break;
case Event::EVENT_TERM_WINDOW:
TermDisplay();
audio.reset();
break;
default:
if (pCurrentScene) {
pCurrentScene->ProcessWindowEvent(*this, *e);
}
break;
}
}
return STATE_CONTINUE;
}
/** Register the scene creation function.
@param id the identify code of the scene.
@param func the function pointer of the scene creation.
*/
void Engine::RegisterSceneCreator(int id, CreateSceneFunc func) {
sceneCreatorList.insert(std::make_pair(id, func));
}
bool Engine::SetNextScene(int sceneId) {
auto itr = sceneCreatorList.find(sceneId);
if (itr != sceneCreatorList.end()) {
pNextScene = itr->second(*this);
return true;
}
return false;
}
/** Run application.
(start)
|
(set to next scene)
|
LOADING
|
(when loaded, set to current scene)
|
RUNNABLE
|
(transition request. create next scene and set to next scene)
| |
| LOADING
| |
(when loaded, current scene set to unloading scene, and next scene set to current scene)
| |
UNLOADING RUNNABLE
| |
STOPPED |
| |
(end) |
|
+-------------+
|
(suspend request)
|
UNLOADING
|
(terminate window and suspending...)
|
(resume request)
|
(initialize window)
|
LOADING
|
RUNNABLE
|
(terminate request)
|
UNLOADING
|
STOPPED
|
(end)
*/
void Engine::Run(Window& window, int initialSceneId) {
pCurrentScene.reset();
if (!SetNextScene(initialSceneId)) {
return;
}
while (1) {
const State status = ProcessWindowEvent(window);
if (status == STATE_TERMINATE) {
return;
}
if (!initialized) {
continue;
}
// ̃V[̏.
if (!pUnloadingScene && pNextScene) {
if (pNextScene->Load(*this)) {
// ł̂ŁAÕV[A[hΏۂƂÃV[݂̃V[ɓo^.
pUnloadingScene = pCurrentScene;
pCurrentScene = pNextScene;
pNextScene.reset();
}
}
// ÕV[̔j.
if (pUnloadingScene) {
if (pUnloadingScene->Unload(*this)) {
pUnloadingScene.reset();
}
}
// ݂̃V[s.
if (pCurrentScene) {
switch (pCurrentScene->GetState()) {
case Scene::STATUSCODE_LOADING:
pCurrentScene->Load(*this);
break;
case Scene::STATUSCODE_RUNNABLE: {
#if 1
++frames;
const int64_t curTime = get_time();
if (curTime < startTime) {
startTime = curTime;
frames = 0;
} else if (curTime - startTime >= (1000UL * 1000UL * 1000UL)) {
latestFps = std::min(frames, 60);
startTime = curTime;
frames = 0;
if (latestFps > avgFps * 0.3f) { // ႷFPS̓mCYƂ݂Ȃ.
avgFps = (avgFps + latestFps) * 0.5f;
deltaTime = (deltaTime + 1.0f / latestFps) * 0.5f;
}
}
#endif
const int nextScneId = pCurrentScene->Update(*this, deltaTime);
switch (nextScneId) {
case SCENEID_TERMINATE:
TermDisplay();
return;
case SCENEID_CONTINUE:
break;
default:
SetNextScene(nextScneId);
break;
}
break;
}
case Scene::STATUSCODE_UNLOADING:
pCurrentScene->Unload(*this);
break;
case Scene::STATUSCODE_STOPPED:
break;
default:
break;
}
}
if (audio) {
audio->Update(deltaTime);
}
DrawFrame();
}
}
/**
* ݂̕\ EGL ReLXg܂B
*/
void Engine::InitDisplay() {
// GL ̏Ԃ܂B
renderer.Initialize(*pWindow);
#ifdef SHOW_DEBUG_SENSOR_OBJECT
debugSensorObj = renderer.CreateObject("octahedron", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
#endif // SHOW_DEBUG_SENSOR_OBJECT
initialized = true;
LOGI("engine_init_display");
}
void Engine::DrawFrame() {
if (initialized) {
Draw();
}
}
/**
* ݃fBXvCɊ֘AtĂ EGL ReLXg폜܂B
*/
void Engine::TermDisplay() {
initialized = false;
#ifdef SHOW_DEBUG_SENSOR_OBJECT
debugSensorObj.reset();
#endif // SHOW_DEBUG_SENSOR_OBJECT
renderer.Unload();
LOGI("engine_term_display");
}
/**
* fBXvČ݂̃t[̂݁B
*/
void Engine::Draw() {
if (!renderer.HasDisplay() || !initialized) {
// fBXvC܂B
return;
}
renderer.ClearDebugString();
char buf[32];
#if 0
sprintf(buf, "OX:%1.3f", fusedOrientation.x);
renderer.AddDebugString(8, 800 - 16 * 9, buf);
sprintf(buf, "OY:%1.3f", fusedOrientation.y);
renderer.AddDebugString(8, 800 - 16 * 8, buf);
sprintf(buf, "OZ:%1.3f", fusedOrientation.z);
renderer.AddDebugString(8, 800 - 16 * 7, buf);
sprintf(buf, "MX:%1.3f", magnet.x);
renderer.AddDebugString(8, 800 - 16 * 6, buf);
sprintf(buf, "MY:%1.3f", magnet.y);
renderer.AddDebugString(8, 800 - 16 * 5, buf);
sprintf(buf, "MZ:%1.3f", magnet.z);
renderer.AddDebugString(8, 800 - 16 * 4, buf);
sprintf(buf, "AX:%1.3f", accel.x);
renderer.AddDebugString(8, 800 - 16 * 3, buf);
sprintf(buf, "AY:%1.3f", accel.y);
renderer.AddDebugString(8, 800 - 16 * 2, buf);
sprintf(buf, "AZ:%1.3f", accel.z);
renderer.AddDebugString(8, 800 - 16 * 1, buf);
#endif
sprintf(buf, "FPS:%02d", latestFps);
renderer.AddDebugString(8, 8, buf);
sprintf(buf, "AVG:%02.1f", avgFps);
renderer.AddDebugString(8, 24, buf);
if (pCurrentScene) {
pCurrentScene->Draw(*this);
}
renderer.Swap();
}
} // namespace Mai | /**
@file Engine.cpp
Game scene flow.
<pre>
+---------------------------------------------------------------------------------------+
| |
| +--------------------------------+ |
| | +---------------------------+ | |
V V V | | |
+-------+ +-------------+ +-----------+ +---------------+ | | |
| Title |--->| Start event |--->| Main game |-+->| Success event |-+ | |
+-------+ +-------------+ +-----------+ | +---------------+ | |
| | |
| +---------------+ | +-----------------+ |
+->| Failure event |---+->| Game over event |-+
+---------------+ +-----------------+
</pre>
*/
#include "Engine.h"
#include "Window.h"
#include <time.h>
#ifdef __ANDROID__
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__))
#else
#include <stdio.h>
#define LOGI(...) ((void)printf(__VA_ARGS__), (void)printf("\n"))
#define LOGE(...) ((void)printf(__VA_ARGS__), (void)printf("\n"))
#endif // __ANDROID__
namespace Mai {
int_fast64_t get_time() {
#ifdef __ANDROID__
#if 1
timespec tmp;
clock_gettime(CLOCK_MONOTONIC, &tmp);
return tmp.tv_sec * (1000UL * 1000UL * 1000UL) + tmp.tv_nsec;
#else
static int sfd = -1;
if (sfd == -1) {
sfd = open("/dev/alarm", O_RDONLY);
}
timespec ts;
const int result = ioctl(sfd, ANDROID_ALARM_GET_TIME(ANDROID_ALARM_ELAPSED_REALTIME), &ts);
if (result != 0) {
const int err = clock_gettime(CLOCK_MONOTONIC, &ts);
if (err < 0) {
LOGI("ERROR(%d) from; clock_gettime(CLOCK_MONOTONIC)", err);
}
}
return ts.tv_sec * (1000 * 1000 * 1000) + ts.tv_nsec;
#endif
#else
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
return ft.dwHighDateTime * 10000000LL + ft.dwLowDateTime * 100LL;
#endif // __ANDROID__
}
Engine::Engine(Window* p)
: initialized(false)
, pWindow(p)
, renderer()
, avgFps(30.0f)
, deltaTime(1.0f / avgFps)
, frames(0)
, latestFps(30)
, startTime(0)
, commonDataDeleter(nullptr)
{
}
Engine::~Engine() {
if (commonDataDeleter) {
commonDataDeleter(commonData.data());
}
}
Engine::State Engine::ProcessWindowEvent(Window& window) {
window.MessageLoop();
while (auto e = window.PopEvent()) {
switch (e->Type) {
case Event::EVENT_CLOSED:
TermDisplay();
return STATE_TERMINATE;
case Event::EVENT_INIT_WINDOW:
audio.reset();
audio = CreateAudioEngine();
InitDisplay();
break;
case Event::EVENT_TERM_WINDOW:
TermDisplay();
audio.reset();
break;
default:
if (pCurrentScene) {
pCurrentScene->ProcessWindowEvent(*this, *e);
}
break;
}
}
return STATE_CONTINUE;
}
/** Register the scene creation function.
@param id the identify code of the scene.
@param func the function pointer of the scene creation.
*/
void Engine::RegisterSceneCreator(int id, CreateSceneFunc func) {
sceneCreatorList.insert(std::make_pair(id, func));
}
bool Engine::SetNextScene(int sceneId) {
auto itr = sceneCreatorList.find(sceneId);
if (itr != sceneCreatorList.end()) {
pNextScene = itr->second(*this);
return true;
}
return false;
}
/** Run application.
(start)
|
(set to next scene)
|
LOADING
|
(when loaded, set to current scene)
|
RUNNABLE
|
(transition request. create next scene and set to next scene)
| |
| LOADING
| |
(when loaded, current scene set to unloading scene, and next scene set to current scene)
| |
UNLOADING RUNNABLE
| |
STOPPED |
| |
(end) |
|
+-------------+
|
(suspend request)
|
UNLOADING
|
(terminate window and suspending...)
|
(resume request)
|
(initialize window)
|
LOADING
|
RUNNABLE
|
(terminate request)
|
UNLOADING
|
STOPPED
|
(end)
*/
void Engine::Run(Window& window, int initialSceneId) {
pCurrentScene.reset();
if (!SetNextScene(initialSceneId)) {
return;
}
while (1) {
const State status = ProcessWindowEvent(window);
if (status == STATE_TERMINATE) {
return;
}
if (!initialized) {
continue;
}
// ̃V[̏.
if (!pUnloadingScene && pNextScene) {
LOGI("[Mai::Engine] Prepare scene %p", pNextScene.get());
if (pNextScene->Load(*this)) {
// ł̂ŁAÕV[A[hΏۂƂÃV[݂̃V[ɓo^.
pUnloadingScene = pCurrentScene;
pCurrentScene = pNextScene;
pNextScene.reset();
}
}
// ÕV[̔j.
if (pUnloadingScene) {
LOGI("[Mai::Engine] Destroy scene %p", pUnloadingScene.get());
if (pUnloadingScene->Unload(*this)) {
pUnloadingScene.reset();
}
}
// ݂̃V[s.
static bool isFirstRun = true;
if (pCurrentScene) {
switch (pCurrentScene->GetState()) {
case Scene::STATUSCODE_LOADING:
LOGI("[Mai::Engine] Load scene %p", pCurrentScene.get());
pCurrentScene->Load(*this);
break;
case Scene::STATUSCODE_RUNNABLE: {
#if 1
++frames;
const int64_t curTime = get_time();
if (curTime < startTime) {
startTime = curTime;
frames = 0;
} else if (curTime - startTime >= (1000UL * 1000UL * 1000UL)) {
latestFps = std::min(frames, 60);
startTime = curTime;
frames = 0;
if (latestFps > avgFps * 0.3f) { // ႷFPS̓mCYƂ݂Ȃ.
avgFps = (avgFps + latestFps) * 0.5f;
deltaTime = (deltaTime + 1.0f / latestFps) * 0.5f;
}
}
if ((frames % 180) == 0) {
LOGI("FPS:%02.1f", avgFps);
}
#endif
if (isFirstRun) {
LOGI("[Mai::Engine] Run scene %p", pCurrentScene.get());
isFirstRun = false;
}
const int nextScneId = pCurrentScene->Update(*this, deltaTime);
switch (nextScneId) {
case SCENEID_TERMINATE:
TermDisplay();
return;
case SCENEID_CONTINUE:
break;
default:
isFirstRun = true;
LOGI("[Mai::Engine] Next scene %d", nextScneId);
SetNextScene(nextScneId);
break;
}
break;
}
case Scene::STATUSCODE_UNLOADING:
LOGI("[Mai::Engine] Unload scene %p", pCurrentScene.get());
pCurrentScene->Unload(*this);
break;
case Scene::STATUSCODE_STOPPED:
break;
default:
break;
}
}
if (audio) {
audio->Update(deltaTime);
}
DrawFrame();
}
}
/**
* ݂̕\ EGL ReLXg܂B
*/
void Engine::InitDisplay() {
// GL ̏Ԃ܂B
renderer.Initialize(*pWindow);
#ifdef SHOW_DEBUG_SENSOR_OBJECT
debugSensorObj = renderer.CreateObject("octahedron", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
#endif // SHOW_DEBUG_SENSOR_OBJECT
initialized = true;
LOGI("engine_init_display");
}
void Engine::DrawFrame() {
if (initialized) {
Draw();
}
}
/**
* ݃fBXvCɊ֘AtĂ EGL ReLXg폜܂B
*/
void Engine::TermDisplay() {
initialized = false;
#ifdef SHOW_DEBUG_SENSOR_OBJECT
debugSensorObj.reset();
#endif // SHOW_DEBUG_SENSOR_OBJECT
renderer.Unload();
LOGI("engine_term_display");
}
/**
* fBXvČ݂̃t[̂݁B
*/
void Engine::Draw() {
if (!renderer.HasDisplay() || !initialized) {
// fBXvC܂B
return;
}
renderer.ClearDebugString();
char buf[32];
#if 0
sprintf(buf, "OX:%1.3f", fusedOrientation.x);
renderer.AddDebugString(8, 800 - 16 * 9, buf);
sprintf(buf, "OY:%1.3f", fusedOrientation.y);
renderer.AddDebugString(8, 800 - 16 * 8, buf);
sprintf(buf, "OZ:%1.3f", fusedOrientation.z);
renderer.AddDebugString(8, 800 - 16 * 7, buf);
sprintf(buf, "MX:%1.3f", magnet.x);
renderer.AddDebugString(8, 800 - 16 * 6, buf);
sprintf(buf, "MY:%1.3f", magnet.y);
renderer.AddDebugString(8, 800 - 16 * 5, buf);
sprintf(buf, "MZ:%1.3f", magnet.z);
renderer.AddDebugString(8, 800 - 16 * 4, buf);
sprintf(buf, "AX:%1.3f", accel.x);
renderer.AddDebugString(8, 800 - 16 * 3, buf);
sprintf(buf, "AY:%1.3f", accel.y);
renderer.AddDebugString(8, 800 - 16 * 2, buf);
sprintf(buf, "AZ:%1.3f", accel.z);
renderer.AddDebugString(8, 800 - 16 * 1, buf);
#endif
sprintf(buf, "FPS:%02d", latestFps);
renderer.AddDebugString(8, 8, buf);
sprintf(buf, "AVG:%02.1f", avgFps);
renderer.AddDebugString(8, 24, buf);
if (pCurrentScene) {
pCurrentScene->Draw(*this);
}
renderer.Swap();
}
} // namespace Mai | Add the code to log the scene transition. | Add the code to log the scene transition.
| C++ | mit | tn-mai/NDKOpenGLES2App,tn-mai/NDKOpenGLES2App |
d46a95242ac76e9de798b1e80cb09bb841cb6656 | db/config.cc | db/config.cc | /*
* Copyright 2015 Cloudius Systems
*
*/
#include <yaml-cpp/yaml.h>
#include <boost/program_options.hpp>
#include <unordered_map>
#include <regex>
#include "config.hh"
#include "core/file.hh"
#include "core/reactor.hh"
#include "core/shared_ptr.hh"
#include "core/fstream.hh"
#include "core/do_with.hh"
#include "log.hh"
static logging::logger logger("config");
db::config::config()
:
// Initialize members to defaults.
#define _mk_init(name, type, deflt, status, desc, ...) \
name(deflt),
_make_config_values(_mk_init)
_dummy(0)
{}
namespace bpo = boost::program_options;
// Special "validator" for boost::program_options to allow reading options
// into an unordered_map<string, string> (we have in config.hh a bunch of
// those). This validator allows the parameter of each option to look like
// 'key=value'. It also allows multiple occurrences of this option to add
// multiple entries into the map. "String" can be any time which can be
// converted from std::string, e.g., sstring.
template<typename String>
static void validate(boost::any& out, const std::vector<std::string>& in,
std::unordered_map<String, String>*, int) {
if (out.empty()) {
out = boost::any(std::unordered_map<String, String>());
}
auto* p = boost::any_cast<std::unordered_map<String, String>>(&out);
for (const auto& s : in) {
auto i = s.find_first_of('=');
if (i == std::string::npos) {
throw boost::program_options::invalid_option_value(s);
}
(*p)[String(s.substr(0, i))] = String(s.substr(i+1));
}
}
namespace YAML {
/*
* Add converters as needed here...
*/
template<>
struct convert<sstring> {
static Node encode(sstring rhs) {
auto p = rhs.c_str();
return convert<const char *>::encode(p);
}
static bool decode(const Node& node, sstring& rhs) {
std::string tmp;
if (!convert<std::string>::decode(node, tmp)) {
return false;
}
rhs = tmp;
return true;
}
};
template <>
struct convert<db::config::string_list> {
static Node encode(const db::config::string_list& rhs) {
Node node(NodeType::Sequence);
for (auto& s : rhs) {
node.push_back(convert<sstring>::encode(s));
}
return node;
}
static bool decode(const Node& node, db::config::string_list& rhs) {
if (!node.IsSequence()) {
return false;
}
rhs.clear();
for (auto& n : node) {
sstring tmp;
if (!convert<sstring>::decode(n,tmp)) {
return false;
}
rhs.push_back(tmp);
}
return true;
}
};
template<typename K, typename V>
struct convert<std::unordered_map<K, V>> {
static Node encode(const std::unordered_map<K, V>& rhs) {
Node node(NodeType::Map);
for(typename std::map<K, V>::const_iterator it=rhs.begin();it!=rhs.end();++it)
node.force_insert(it->first, it->second);
return node;
}
static bool decode(const Node& node, std::unordered_map<K, V>& rhs) {
if (!node.IsMap()) {
return false;
}
rhs.clear();
for (auto& n : node) {
rhs[n.first.as<K>()] = n.second.as<V>();
}
return true;
}
};
template<>
struct convert<db::config::seed_provider_type> {
static Node encode(const db::config::seed_provider_type& rhs) {
throw std::runtime_error("should not reach");
}
static bool decode(const Node& node, db::config::seed_provider_type& rhs) {
if (!node.IsSequence()) {
return false;
}
rhs = db::config::seed_provider_type();
for (auto& n : node) {
if (!n.IsMap()) {
continue;
}
for (auto& n2 : n) {
if (n2.first.as<sstring>() == "class_name") {
rhs.class_name = n2.second.as<sstring>();
}
if (n2.first.as<sstring>() == "parameters") {
auto v = n2.second.as<std::vector<db::config::string_map>>();
if (!v.empty()) {
rhs.parameters = v.front();
}
}
}
}
return true;
}
};
}
template<typename... Args>
std::basic_ostream<Args...> & operator<<(std::basic_ostream<Args...> & os, const db::config::string_map & map) {
int n = 0;
for (auto& e : map) {
if (n > 0) {
os << ":";
}
os << e.first << "=" << e.second;
}
return os;
}
template<typename... Args>
std::basic_istream<Args...> & operator>>(std::basic_istream<Args...> & is, db::config::string_map & map) {
std::string str;
is >> str;
std::regex colon(":");
std::sregex_token_iterator s(str.begin(), str.end(), colon, -1);
std::sregex_token_iterator e;
while (s != e) {
sstring p = std::string(*s++);
auto i = p.find('=');
auto k = p.substr(0, i);
auto v = i == sstring::npos ? sstring() : p.substr(i + 1, p.size());
map.emplace(std::make_pair(k, v));
};
return is;
}
/*
* Helper type to do compile time exclusion of Unused/invalid options from
* command line.
*
* Only opts marked "used" should get a boost::opt
*
*/
template<typename T, db::config::value_status S>
struct do_value_opt;
template<typename T>
struct do_value_opt<T, db::config::value_status::Used> {
template<typename Func>
void operator()(Func&& func, const char* name, const T& dflt, T * dst, db::config::config_source & src, const char* desc) const {
func(name, dflt, dst, src, desc);
}
};
template<>
struct do_value_opt<db::config::seed_provider_type, db::config::value_status::Used> {
using seed_provider_type = db::config::seed_provider_type;
template<typename Func>
void operator()(Func&& func, const char* name, const seed_provider_type& dflt, seed_provider_type * dst, db::config::config_source & src, const char* desc) const {
func((sstring(name) + "_class_name").c_str(), dflt.class_name, &dst->class_name, src, desc);
func((sstring(name) + "_parameters").c_str(), dflt.parameters, &dst->parameters, src, desc);
}
};
template<typename T>
struct do_value_opt<T, db::config::value_status::Unused> {
template<typename... Args> void operator()(Args&&... args) const {}
};
template<typename T>
struct do_value_opt<T, db::config::value_status::Invalid> {
template<typename... Args> void operator()(Args&&... args) const {}
};
bpo::options_description db::config::get_options_description() {
bpo::options_description opts("Urchin options");
auto init = opts.add_options();
add_options(init);
return std::move(opts);
}
/*
* Our own bpo::typed_valye.
* Only difference is that we _don't_ apply defaults (they are already applied)
* Needed to make aliases work properly.
*/
template<class T, class charT = char>
class typed_value_ex : public bpo::typed_value<T, charT> {
public:
typedef bpo::typed_value<T, charT> _Super;
typed_value_ex(T* store_to)
: _Super(store_to)
{}
bool apply_default(boost::any& value_store) const override {
return false;
}
};
template<class T>
inline typed_value_ex<T>* value_ex(T* v) {
typed_value_ex<T>* r = new typed_value_ex<T>(v);
return r;
}
template<class T>
inline typed_value_ex<std::vector<T>>* value_ex(std::vector<T>* v) {
auto r = new typed_value_ex<std::vector<T>>(v);
r->multitoken();
return r;
}
bpo::options_description_easy_init& db::config::add_options(bpo::options_description_easy_init& init) {
auto opt_add =
[&init](const char* name, const auto& dflt, auto* dst, auto& src, const char* desc) mutable {
sstring tmp(name);
std::replace(tmp.begin(), tmp.end(), '_', '-');
init(tmp.c_str(),
value_ex(dst)->default_value(dflt)->notifier([&src](auto) mutable {
src = config_source::CommandLine;
})
, desc);
};
// Add all used opts as command line opts
#define _add_boost_opt(name, type, deflt, status, desc, ...) \
do_value_opt<type, value_status::status>()(opt_add, #name, type( deflt ), &name._value, name._source, desc);
_make_config_values(_add_boost_opt)
auto alias_add =
[&init](const char* name, auto& dst, const char* desc) mutable {
init(name,
value_ex(&dst._value)->notifier([dst](auto) mutable {
dst._source = config_source::CommandLine;
})
, desc);
};
// Handle "old" syntax with "aliases"
alias_add("datadir", data_file_directories, "alias for 'data-file-directories'");
alias_add("thrift-port", rpc_port, "alias for 'rpc-port'");
alias_add("cql-port", native_transport_port, "alias for 'native-transport-port'");
return init;
}
// Virtual dispatch to convert yaml->data type.
struct handle_yaml {
virtual ~handle_yaml() {};
virtual void operator()(const YAML::Node&) = 0;
virtual db::config::value_status status() const = 0;
virtual db::config::config_source source() const = 0;
};
template<typename T, db::config::value_status S>
struct handle_yaml_impl : public handle_yaml {
typedef db::config::value<T, S> value_type;
handle_yaml_impl(value_type& v, db::config::config_source& src) : _dst(v), _src(src) {}
void operator()(const YAML::Node& node) override {
_dst(node.as<T>());
_src = db::config::config_source::SettingsFile;
}
db::config::value_status status() const override {
return _dst.status();
}
db::config::config_source source() const override {
return _src;
}
value_type& _dst;
db::config::config_source&
_src;
};
void db::config::read_from_yaml(const sstring& yaml) {
read_from_yaml(yaml.c_str());
}
void db::config::read_from_yaml(const char* yaml) {
std::unordered_map<sstring, std::unique_ptr<handle_yaml>> values;
#define _add_yaml_opt(name, type, deflt, status, desc, ...) \
values.emplace(#name, std::make_unique<handle_yaml_impl<type, value_status::status>>(name, name._source));
_make_config_values(_add_yaml_opt)
/*
* Note: this is not very "half-fault" tolerant. I.e. there could be
* yaml syntax errors that origin handles and still sets the options
* where as we don't...
* There are no exhaustive attempts at converting, we rely on syntax of
* file mapping to the data type...
*/
auto doc = YAML::Load(yaml);
for (auto node : doc) {
auto label = node.first.as<sstring>();
auto i = values.find(label);
if (i == values.end()) {
logger.warn("Unknown option {} ignored.", label);
continue;
}
if (i->second->source() > config_source::SettingsFile) {
logger.debug("Option {} already set by commandline. ignored.", label);
continue;
}
switch (i->second->status()) {
case value_status::Invalid:
logger.warn("Option {} is not applicable. Ignoring.", label);
continue;
case value_status::Unused:
logger.debug("Option {} is not (yet) used.", label);
break;
default:
break;
}
if (node.second.IsNull()) {
logger.debug("Option {}, empty value. Skipping.", label);
continue;
}
// Still, a syntax error is an error warning, not a fail
try {
(*i->second)(node.second);
} catch (...) {
logger.error("Option {}, exception while converting value.", label);
}
}
}
future<> db::config::read_from_file(file f) {
return f.size().then([this, f](size_t s) {
return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) {
return in.read_exactly(s).then([this](temporary_buffer<char> buf) {
read_from_yaml(sstring(buf.begin(), buf.end()));
});
});
});
}
future<> db::config::read_from_file(const sstring& filename) {
return engine().open_file_dma(filename, open_flags::ro).then([this](file f) {
return read_from_file(std::move(f));
});
}
| /*
* Copyright 2015 Cloudius Systems
*
*/
#include <yaml-cpp/yaml.h>
#include <boost/program_options.hpp>
#include <unordered_map>
#include <regex>
#include "config.hh"
#include "core/file.hh"
#include "core/reactor.hh"
#include "core/shared_ptr.hh"
#include "core/fstream.hh"
#include "core/do_with.hh"
#include "log.hh"
static logging::logger logger("config");
db::config::config()
:
// Initialize members to defaults.
#define _mk_init(name, type, deflt, status, desc, ...) \
name(deflt),
_make_config_values(_mk_init)
_dummy(0)
{}
namespace bpo = boost::program_options;
// Special "validator" for boost::program_options to allow reading options
// into an unordered_map<string, string> (we have in config.hh a bunch of
// those). This validator allows the parameter of each option to look like
// 'key=value'. It also allows multiple occurrences of this option to add
// multiple entries into the map. "String" can be any time which can be
// converted from std::string, e.g., sstring.
template<typename String>
static void validate(boost::any& out, const std::vector<std::string>& in,
std::unordered_map<String, String>*, int) {
if (out.empty()) {
out = boost::any(std::unordered_map<String, String>());
}
auto* p = boost::any_cast<std::unordered_map<String, String>>(&out);
for (const auto& s : in) {
auto i = s.find_first_of('=');
if (i == std::string::npos) {
throw boost::program_options::invalid_option_value(s);
}
(*p)[String(s.substr(0, i))] = String(s.substr(i+1));
}
}
namespace YAML {
/*
* Add converters as needed here...
*/
template<>
struct convert<sstring> {
static Node encode(sstring rhs) {
auto p = rhs.c_str();
return convert<const char *>::encode(p);
}
static bool decode(const Node& node, sstring& rhs) {
std::string tmp;
if (!convert<std::string>::decode(node, tmp)) {
return false;
}
rhs = tmp;
return true;
}
};
template <>
struct convert<db::config::string_list> {
static Node encode(const db::config::string_list& rhs) {
Node node(NodeType::Sequence);
for (auto& s : rhs) {
node.push_back(convert<sstring>::encode(s));
}
return node;
}
static bool decode(const Node& node, db::config::string_list& rhs) {
if (!node.IsSequence()) {
return false;
}
rhs.clear();
for (auto& n : node) {
sstring tmp;
if (!convert<sstring>::decode(n,tmp)) {
return false;
}
rhs.push_back(tmp);
}
return true;
}
};
template<typename K, typename V>
struct convert<std::unordered_map<K, V>> {
static Node encode(const std::unordered_map<K, V>& rhs) {
Node node(NodeType::Map);
for(typename std::map<K, V>::const_iterator it=rhs.begin();it!=rhs.end();++it)
node.force_insert(it->first, it->second);
return node;
}
static bool decode(const Node& node, std::unordered_map<K, V>& rhs) {
if (!node.IsMap()) {
return false;
}
rhs.clear();
for (auto& n : node) {
rhs[n.first.as<K>()] = n.second.as<V>();
}
return true;
}
};
template<>
struct convert<db::config::seed_provider_type> {
static Node encode(const db::config::seed_provider_type& rhs) {
throw std::runtime_error("should not reach");
}
static bool decode(const Node& node, db::config::seed_provider_type& rhs) {
if (!node.IsSequence()) {
return false;
}
rhs = db::config::seed_provider_type();
for (auto& n : node) {
if (!n.IsMap()) {
continue;
}
for (auto& n2 : n) {
if (n2.first.as<sstring>() == "class_name") {
rhs.class_name = n2.second.as<sstring>();
}
if (n2.first.as<sstring>() == "parameters") {
auto v = n2.second.as<std::vector<db::config::string_map>>();
if (!v.empty()) {
rhs.parameters = v.front();
}
}
}
}
return true;
}
};
}
template<typename... Args>
std::basic_ostream<Args...> & operator<<(std::basic_ostream<Args...> & os, const db::config::string_map & map) {
int n = 0;
for (auto& e : map) {
if (n > 0) {
os << ":";
}
os << e.first << "=" << e.second;
}
return os;
}
template<typename... Args>
std::basic_istream<Args...> & operator>>(std::basic_istream<Args...> & is, db::config::string_map & map) {
std::string str;
is >> str;
std::regex colon(":");
std::sregex_token_iterator s(str.begin(), str.end(), colon, -1);
std::sregex_token_iterator e;
while (s != e) {
sstring p = std::string(*s++);
auto i = p.find('=');
auto k = p.substr(0, i);
auto v = i == sstring::npos ? sstring() : p.substr(i + 1, p.size());
map.emplace(std::make_pair(k, v));
};
return is;
}
/*
* Helper type to do compile time exclusion of Unused/invalid options from
* command line.
*
* Only opts marked "used" should get a boost::opt
*
*/
template<typename T, db::config::value_status S>
struct do_value_opt;
template<typename T>
struct do_value_opt<T, db::config::value_status::Used> {
template<typename Func>
void operator()(Func&& func, const char* name, const T& dflt, T * dst, db::config::config_source & src, const char* desc) const {
func(name, dflt, dst, src, desc);
}
};
template<>
struct do_value_opt<db::config::seed_provider_type, db::config::value_status::Used> {
using seed_provider_type = db::config::seed_provider_type;
template<typename Func>
void operator()(Func&& func, const char* name, const seed_provider_type& dflt, seed_provider_type * dst, db::config::config_source & src, const char* desc) const {
func((sstring(name) + "_class_name").c_str(), dflt.class_name, &dst->class_name, src, desc);
func((sstring(name) + "_parameters").c_str(), dflt.parameters, &dst->parameters, src, desc);
}
};
template<typename T>
struct do_value_opt<T, db::config::value_status::Unused> {
template<typename... Args> void operator()(Args&&... args) const {}
};
template<typename T>
struct do_value_opt<T, db::config::value_status::Invalid> {
template<typename... Args> void operator()(Args&&... args) const {}
};
bpo::options_description db::config::get_options_description() {
bpo::options_description opts("Urchin options");
auto init = opts.add_options();
add_options(init);
return std::move(opts);
}
/*
* Our own bpo::typed_valye.
* Only difference is that we _don't_ apply defaults (they are already applied)
* Needed to make aliases work properly.
*/
template<class T, class charT = char>
class typed_value_ex : public bpo::typed_value<T, charT> {
public:
typedef bpo::typed_value<T, charT> _Super;
typed_value_ex(T* store_to)
: _Super(store_to)
{}
bool apply_default(boost::any& value_store) const override {
return false;
}
};
template<class T>
inline typed_value_ex<T>* value_ex(T* v) {
typed_value_ex<T>* r = new typed_value_ex<T>(v);
return r;
}
template<class T>
inline typed_value_ex<std::vector<T>>* value_ex(std::vector<T>* v) {
auto r = new typed_value_ex<std::vector<T>>(v);
r->multitoken();
return r;
}
bpo::options_description_easy_init& db::config::add_options(bpo::options_description_easy_init& init) {
auto opt_add =
[&init](const char* name, const auto& dflt, auto* dst, auto& src, const char* desc) mutable {
sstring tmp(name);
std::replace(tmp.begin(), tmp.end(), '_', '-');
init(tmp.c_str(),
value_ex(dst)->default_value(dflt)->notifier([&src](auto) mutable {
src = config_source::CommandLine;
})
, desc);
};
// Add all used opts as command line opts
#define _add_boost_opt(name, type, deflt, status, desc, ...) \
do_value_opt<type, value_status::status>()(opt_add, #name, type( deflt ), &name._value, name._source, desc);
_make_config_values(_add_boost_opt)
auto alias_add =
[&init](const char* name, auto& dst, const char* desc) mutable {
init(name,
value_ex(&dst._value)->notifier([&dst](auto& v) mutable {
dst._source = config_source::CommandLine;
})
, desc);
};
// Handle "old" syntax with "aliases"
alias_add("datadir", data_file_directories, "alias for 'data-file-directories'");
alias_add("thrift-port", rpc_port, "alias for 'rpc-port'");
alias_add("cql-port", native_transport_port, "alias for 'native-transport-port'");
return init;
}
// Virtual dispatch to convert yaml->data type.
struct handle_yaml {
virtual ~handle_yaml() {};
virtual void operator()(const YAML::Node&) = 0;
virtual db::config::value_status status() const = 0;
virtual db::config::config_source source() const = 0;
};
template<typename T, db::config::value_status S>
struct handle_yaml_impl : public handle_yaml {
typedef db::config::value<T, S> value_type;
handle_yaml_impl(value_type& v, db::config::config_source& src) : _dst(v), _src(src) {}
void operator()(const YAML::Node& node) override {
_dst(node.as<T>());
_src = db::config::config_source::SettingsFile;
}
db::config::value_status status() const override {
return _dst.status();
}
db::config::config_source source() const override {
return _src;
}
value_type& _dst;
db::config::config_source&
_src;
};
void db::config::read_from_yaml(const sstring& yaml) {
read_from_yaml(yaml.c_str());
}
void db::config::read_from_yaml(const char* yaml) {
std::unordered_map<sstring, std::unique_ptr<handle_yaml>> values;
#define _add_yaml_opt(name, type, deflt, status, desc, ...) \
values.emplace(#name, std::make_unique<handle_yaml_impl<type, value_status::status>>(name, name._source));
_make_config_values(_add_yaml_opt)
/*
* Note: this is not very "half-fault" tolerant. I.e. there could be
* yaml syntax errors that origin handles and still sets the options
* where as we don't...
* There are no exhaustive attempts at converting, we rely on syntax of
* file mapping to the data type...
*/
auto doc = YAML::Load(yaml);
for (auto node : doc) {
auto label = node.first.as<sstring>();
auto i = values.find(label);
if (i == values.end()) {
logger.warn("Unknown option {} ignored.", label);
continue;
}
if (i->second->source() > config_source::SettingsFile) {
logger.debug("Option {} already set by commandline. ignored.", label);
continue;
}
switch (i->second->status()) {
case value_status::Invalid:
logger.warn("Option {} is not applicable. Ignoring.", label);
continue;
case value_status::Unused:
logger.debug("Option {} is not (yet) used.", label);
break;
default:
break;
}
if (node.second.IsNull()) {
logger.debug("Option {}, empty value. Skipping.", label);
continue;
}
// Still, a syntax error is an error warning, not a fail
try {
(*i->second)(node.second);
} catch (...) {
logger.error("Option {}, exception while converting value.", label);
}
}
}
future<> db::config::read_from_file(file f) {
return f.size().then([this, f](size_t s) {
return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) {
return in.read_exactly(s).then([this](temporary_buffer<char> buf) {
read_from_yaml(sstring(buf.begin(), buf.end()));
});
});
});
}
future<> db::config::read_from_file(const sstring& filename) {
return engine().open_file_dma(filename, open_flags::ro).then([this](file f) {
return read_from_file(std::move(f));
});
}
| Fix type where alias destination was copied instead of referenced | Config: Fix type where alias destination was copied instead of referenced
Fixes #310
Missing '&'.
(And no, cannot make the type non-copyable, since we want to copy config
objects).
| C++ | agpl-3.0 | duarten/scylla,bowlofstew/scylla,capturePointer/scylla,stamhe/scylla,victorbriz/scylla,raphaelsc/scylla,kangkot/scylla,rluta/scylla,phonkee/scylla,justintung/scylla,gwicke/scylla,eklitzke/scylla,senseb/scylla,shaunstanislaus/scylla,phonkee/scylla,asias/scylla,shaunstanislaus/scylla,acbellini/scylla,duarten/scylla,scylladb/scylla,senseb/scylla,gwicke/scylla,tempbottle/scylla,respu/scylla,dwdm/scylla,tempbottle/scylla,wildinto/scylla,kangkot/scylla,wildinto/scylla,aruanruan/scylla,glommer/scylla,capturePointer/scylla,respu/scylla,kjniemi/scylla,acbellini/scylla,senseb/scylla,bowlofstew/scylla,eklitzke/scylla,stamhe/scylla,duarten/scylla,acbellini/scylla,aruanruan/scylla,guiquanz/scylla,guiquanz/scylla,kjniemi/scylla,scylladb/scylla,stamhe/scylla,respu/scylla,glommer/scylla,justintung/scylla,rentongzhang/scylla,avikivity/scylla,justintung/scylla,bowlofstew/scylla,guiquanz/scylla,raphaelsc/scylla,linearregression/scylla,shaunstanislaus/scylla,scylladb/scylla,capturePointer/scylla,asias/scylla,tempbottle/scylla,kjniemi/scylla,glommer/scylla,aruanruan/scylla,dwdm/scylla,wildinto/scylla,scylladb/scylla,raphaelsc/scylla,avikivity/scylla,avikivity/scylla,linearregression/scylla,phonkee/scylla,gwicke/scylla,victorbriz/scylla,victorbriz/scylla,rentongzhang/scylla,rluta/scylla,asias/scylla,rluta/scylla,dwdm/scylla,rentongzhang/scylla,kangkot/scylla,linearregression/scylla,eklitzke/scylla |
4bc780c73ddc82b833a74968b27eb789327fa54e | test/TesterMain.cpp | test/TesterMain.cpp | #define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "gmusicapi/Module.h"
#include "gmusicapi/Musicmanager.h"
#include "TestFixture.h"
#include <boost/program_options.hpp>
#include <algorithm>
int main(int argc, char* argv[])
{
namespace po = boost::program_options;
bool wait;
bool oauth;
po::options_description desc("Other options");
desc.add_options()
("help,h", "produce help message")
("username", po::value(&TestFixture::gm_user)->required(), "Google Music username")
("password", po::value(&TestFixture::gm_pass)->required(), "Google Music password")
("refresh_token", po::value(&TestFixture::gm_refresh), "Google Music refresh token")
("android_id", po::value(&TestFixture::gm_user), "Google Music Android ID")
("wait", po::value(&wait)->default_value(false), "Wait for keystroke before starting")
("oauth", po::value(&oauth)->default_value(false), "Perform OAuth")
;
po::variables_map vm;
auto parsedOptions = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
po::store(parsedOptions, vm);
Catch::Session session;
auto usage = [&]()
{
session.showHelp(argv[0]);
Catch::cout() << desc << '\n';
};
try
{
po::notify(vm);
}
catch (std::exception& e)
{
std::cerr << e.what() << '\n';
usage();
return 1;
}
if (vm.count("help"))
{
usage();
return 0;
}
if (wait)
{
std::string s;
std::cout << "Press enter to start testing.\n";
std::cin >> s;
}
if (oauth)
{
namespace gm = GMusicApi;
gm::Module m;
gm::Musicmanager mm(m);
mm.perform_oauth();
}
auto unusedOptions = collect_unrecognized(parsedOptions.options, po::include_positional);
// convert to const char*
std::vector<const char*> unusedOptionsToCatch = { argv[0] };
std::transform(unusedOptions.begin(), unusedOptions.end(), std::back_inserter(unusedOptionsToCatch),
[](const std::string& str)
{
return str.c_str();
});
return session.run(unusedOptionsToCatch.size(), unusedOptionsToCatch.data());
}
| #define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "gmusicapi/Module.h"
#include "gmusicapi/Musicmanager.h"
#include "TestFixture.h"
#include <boost/program_options.hpp>
#include <algorithm>
int main(int argc, char* argv[])
{
namespace po = boost::program_options;
bool wait;
bool oauth;
po::options_description desc("Other options");
desc.add_options()
("help,h", "produce help message")
("username", po::value(&TestFixture::gm_user)->required(), "Google Music username")
("password", po::value(&TestFixture::gm_pass)->required(), "Google Music password")
("refresh_token", po::value(&TestFixture::gm_refresh), "Google Music refresh token")
("android_id", po::value(&TestFixture::gm_user), "Google Music Android ID")
("wait", po::value(&wait)->default_value(false), "Wait for keystroke before starting")
("oauth", po::value(&oauth)->default_value(false), "Perform OAuth")
;
po::variables_map vm;
auto parsedOptions = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
po::store(parsedOptions, vm);
Catch::Session session;
auto usage = [&]()
{
session.showHelp(argv[0]);
Catch::cout() << desc << '\n';
};
try
{
po::notify(vm);
}
catch (std::exception& e)
{
std::cerr << e.what() << '\n';
usage();
return 1;
}
if (vm.count("help"))
{
usage();
return 0;
}
if (wait)
{
std::string s;
std::cout << "Press enter to start testing.\n";
std::cin >> s;
}
if (oauth)
{
namespace gm = GMusicApi;
gm::Module m;
gm::Musicmanager mm(m);
mm.perform_oauth();
}
auto unusedOptions = collect_unrecognized(parsedOptions.options, po::include_positional);
// convert to const char*
std::vector<const char*> unusedOptionsToCatch = { argv[0] };
std::transform(unusedOptions.begin(), unusedOptions.end(), std::back_inserter(unusedOptionsToCatch),
[](const std::string& str)
{
return str.c_str();
});
return session.run(static_cast<int>(unusedOptionsToCatch.size()), unusedOptionsToCatch.data());
}
| fix amd64 | fix amd64
| C++ | mit | dvirtz/gmusicapi-cpp,dvirtz/gmusicapi-cpp,dvirtz/gmusicapi-cpp |
130eb7c7e60353b2a6de8131c7368e5d453e4372 | vexcl/backend/opencl/kernel.hpp | vexcl/backend/opencl/kernel.hpp | #ifndef VEXCL_BACKEND_OPENCL_KERNEL_HPP
#define VEXCL_BACKEND_OPENCL_KERNEL_HPP
/*
The MIT License
Copyright (c) 2012-2013 Denis Demidov <[email protected]>
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.
*/
/**
* \file vexcl/backend/opencl/kernel.hpp
* \author Denis Demidov <[email protected]>
* \brief An abstraction over OpenCL compute kernel.
*/
#include <functional>
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <CL/cl.hpp>
#include <vexcl/backend/opencl/compiler.hpp>
namespace vex {
namespace backend {
struct fixed_workgroup_size_impl {
size_t size;
};
inline fixed_workgroup_size_impl fixed_workgroup_size(size_t n) {
fixed_workgroup_size_impl s = {n};
return s;
}
/// An abstraction over OpenCL compute kernel.
class kernel {
public:
kernel() : argpos(0), w_size(0), g_size(0) {}
/// Constructor. Creates a cl::Kernel instance from source.
kernel(const cl::CommandQueue &queue,
const std::string &src,
const std::string &name,
size_t smem_per_thread = 0
)
: argpos(0), K(build_sources(qctx(queue), src), name.c_str())
{
get_launch_cfg(queue,
[smem_per_thread](size_t wgs){ return wgs * smem_per_thread; });
}
/// Constructor. Creates a cl::Kernel instance from source.
kernel(const cl::CommandQueue &queue,
const std::string &src, const std::string &name,
std::function<size_t(size_t)> smem
)
: argpos(0), K(build_sources(qctx(queue), src), name.c_str())
{
get_launch_cfg(queue, smem);
}
/// Constructor. Creates a cl::Kernel instance from source.
kernel(const cl::CommandQueue &queue,
const std::string &src, const std::string &name,
fixed_workgroup_size_impl wgs
)
: argpos(0),
K(build_sources(qctx(queue), src), name.c_str()),
w_size(wgs.size),
g_size(w_size * num_workgroups(queue))
{ }
/// Adds an argument to the kernel.
template <class Arg>
void push_arg(Arg &&arg) {
K.setArg(argpos++, arg);
}
/// Adds local memory to the kernel.
void push_smem(size_t smem_per_thread) {
cl::LocalSpaceArg smem = { smem_per_thread * w_size };
K.setArg(argpos++, smem);
}
/// Adds local memory to the kernel.
template <class F>
void push_smem(F &&f) {
push_smem( f(w_size) );
}
void operator()(const cl::CommandQueue &q) {
q.enqueueNDRangeKernel(K, cl::NullRange, g_size, w_size);
argpos = 0;
}
/// Workgroup size.
size_t workgroup_size() const {
return w_size;
}
/// Standard number of workgroups to launch on a device.
static inline size_t num_workgroups(const cl::CommandQueue &q) {
// This is a simple heuristic-based estimate. More advanced technique may
// be employed later.
return 4 * qdev(q).getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
}
/*
operator const cl::Kernel&() const {
return K;
}
*/
private:
unsigned argpos;
cl::Kernel K;
size_t w_size;
size_t g_size;
void get_launch_cfg(const cl::CommandQueue &queue, std::function<size_t(size_t)> smem) {
cl::Device dev = qdev(queue);
// Select workgroup size that would fit into the device.
w_size = dev.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>()[0];
size_t max_ws = K.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(dev);
size_t max_smem = static_cast<size_t>(dev.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>())
- static_cast<size_t>(K.getWorkGroupInfo<CL_KERNEL_LOCAL_MEM_SIZE>(dev));
// Reduce workgroup size until it satisfies resource requirements:
while( (w_size > max_ws) || (smem(w_size) > max_smem) )
w_size /= 2;
g_size = w_size * num_workgroups(queue);
}
};
} // namespace backend
} // namespace vex
#endif
| #ifndef VEXCL_BACKEND_OPENCL_KERNEL_HPP
#define VEXCL_BACKEND_OPENCL_KERNEL_HPP
/*
The MIT License
Copyright (c) 2012-2013 Denis Demidov <[email protected]>
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.
*/
/**
* \file vexcl/backend/opencl/kernel.hpp
* \author Denis Demidov <[email protected]>
* \brief An abstraction over OpenCL compute kernel.
*/
#include <functional>
#ifndef __CL_ENABLE_EXCEPTIONS
# define __CL_ENABLE_EXCEPTIONS
#endif
#include <CL/cl.hpp>
#include <vexcl/backend/opencl/compiler.hpp>
namespace vex {
namespace backend {
struct fixed_workgroup_size_impl {
size_t size;
};
inline fixed_workgroup_size_impl fixed_workgroup_size(size_t n) {
fixed_workgroup_size_impl s = {n};
return s;
}
/// An abstraction over OpenCL compute kernel.
class kernel {
public:
kernel() : argpos(0), w_size(0), g_size(0) {}
/// Constructor. Creates a cl::Kernel instance from source.
kernel(const cl::CommandQueue &queue,
const std::string &src,
const std::string &name,
size_t smem_per_thread = 0
)
: argpos(0), K(build_sources(qctx(queue), src), name.c_str())
{
get_launch_cfg(queue,
[smem_per_thread](size_t wgs){ return wgs * smem_per_thread; });
}
/// Constructor. Creates a cl::Kernel instance from source.
kernel(const cl::CommandQueue &queue,
const std::string &src, const std::string &name,
std::function<size_t(size_t)> smem
)
: argpos(0), K(build_sources(qctx(queue), src), name.c_str())
{
get_launch_cfg(queue, smem);
}
/// Constructor. Creates a cl::Kernel instance from source.
kernel(const cl::CommandQueue &queue,
const std::string &src, const std::string &name,
fixed_workgroup_size_impl wgs
)
: argpos(0),
K(build_sources(qctx(queue), src), name.c_str()),
w_size(wgs.size),
g_size(w_size * num_workgroups(queue))
{ }
/// Adds an argument to the kernel.
template <class Arg>
void push_arg(Arg &&arg) {
K.setArg(argpos++, arg);
}
/// Adds local memory to the kernel.
void push_smem(size_t smem_per_thread) {
cl::LocalSpaceArg smem = { smem_per_thread * w_size };
K.setArg(argpos++, smem);
}
/// Adds local memory to the kernel.
template <class F>
void push_smem(F &&f) {
push_smem( f(w_size) );
}
void operator()(const cl::CommandQueue &q) {
q.enqueueNDRangeKernel(K, cl::NullRange, g_size, w_size);
argpos = 0;
}
/// Workgroup size.
size_t workgroup_size() const {
return w_size;
}
/// Standard number of workgroups to launch on a device.
static inline size_t num_workgroups(const cl::CommandQueue &q) {
// This is a simple heuristic-based estimate. More advanced technique may
// be employed later.
return 4 * qdev(q).getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
}
/*
operator const cl::Kernel&() const {
return K;
}
*/
private:
unsigned argpos;
cl::Kernel K;
size_t w_size;
size_t g_size;
void get_launch_cfg(const cl::CommandQueue &queue, std::function<size_t(size_t)> smem) {
cl::Device dev = qdev(queue);
if ( is_cpu(dev) ) {
w_size = 1;
} else {
// Select workgroup size that would fit into the device.
w_size = dev.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>()[0];
size_t max_ws = K.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(dev);
size_t max_smem = static_cast<size_t>(dev.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>())
- static_cast<size_t>(K.getWorkGroupInfo<CL_KERNEL_LOCAL_MEM_SIZE>(dev));
// Reduce workgroup size until it satisfies resource requirements:
while( (w_size > max_ws) || (smem(w_size) > max_smem) )
w_size /= 2;
}
g_size = w_size * num_workgroups(queue);
}
};
} // namespace backend
} // namespace vex
#endif
| Set workgroup size to 1 for CPUs | Set workgroup size to 1 for CPUs
| C++ | mit | ddemidov/vexcl,Poulpy21/vexcl,Poulpy21/vexcl,Poulpy21/vexcl,kapadia/vexcl,kapadia/vexcl,ddemidov/vexcl |
ad98e5a62cc475fc1ed8876b285af9c09879d2cf | src/346588.cpp | src/346588.cpp | #include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <vector>
using namespace std;
typedef pair<long long ,long long> node;
long long re[1000000];
int main(int argc, char const *argv[])
{
priority_queue<node ,vector<node> ,greater<node> > pq;
pq.push(node(1,2));
node n;
int i=0;
while(i<100){
node n=pq.top();
//printf("%d",i);
pq.pop();
switch(n.second){
case 2:
pq.push(node(n.first*2,3));
case 3:
pq.push(node(n.first*3,5));
case 5:
pq.push(node(n.first*5,5));
}
re[i++]=n.first;
}
for (int j = 0; j < i; ++j)
{
printf("%d\n",re[j]);
}
return 0;
}
| #include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <vector>
using namespace std;
typedef pair<long long ,long long> node;
long long re[1000000];
int main(int argc, char const *argv[])
{
priority_queue<node ,vector<node> ,less<node> > pq;
pq.push(node(1,2));
node n;
int i=0;
while(i<100){
node n=pq.top();
//printf("%d",i);
pq.pop();
switch(n.second){
case 2:
pq.push(node(n.first*2,3));
case 3:
pq.push(node(n.first*3,5));
case 5:
pq.push(node(n.first*5,5));
}
re[i++]=n.first;
}
for (int j = 0; j < i; ++j)
{
printf("%d\n",re[j]);
}
return 0;
}
| update 346588 | update 346588
| C++ | mit | czfshine/my_oj,czfshine/my_oj,czfshine/my_oj,czfshine/my_oj |
05bb2db3ea4e3e993d1e526f0d43cc73f8d1742d | test/alignedbox.cpp | test/alignedbox.cpp | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// Eigen 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.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/QR>
template<typename BoxType> void alignedbox(const BoxType& _box)
{
/* this test covers the following files:
AlignedBox.h
*/
const int dim = _box.dim();
typedef typename BoxType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, BoxType::AmbientDimAtCompileTime, 1> VectorType;
VectorType p0 = VectorType::Random(dim);
VectorType p1 = VectorType::Random(dim);
RealScalar s1 = ei_random<RealScalar>(0,1);
BoxType b0(dim);
BoxType b1(VectorType::Random(dim),VectorType::Random(dim));
BoxType b2;
b0.extend(p0);
b0.extend(p1);
VERIFY(b0.contains(p0*s1+(1.-s1)*p1));
VERIFY(!b0.contains(p0 + (1+s1)*(p1-p0)));
(b2 = b0).extend(b1);
VERIFY(b2.contains(b0));
VERIFY(b2.contains(b1));
VERIFY_IS_APPROX(b2.clamp(b0), b0);
// casting
const int Dim = BoxType::AmbientDimAtCompileTime;
typedef typename GetDifferentType<Scalar>::type OtherScalar;
AlignedBox<OtherScalar,Dim> hp1f = b0.template cast<OtherScalar>();
VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),b0);
AlignedBox<Scalar,Dim> hp1d = b0.template cast<Scalar>();
VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),b0);
}
void test_alignedbox()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( alignedbox(AlignedBox<float,2>()) );
CALL_SUBTEST( alignedbox(AlignedBox<float,3>()) );
CALL_SUBTEST( alignedbox(AlignedBox<double,4>()) );
}
}
| // This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// Eigen 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.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/QR>
template<typename BoxType> void alignedbox(const BoxType& _box)
{
/* this test covers the following files:
AlignedBox.h
*/
const int dim = _box.dim();
typedef typename BoxType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, BoxType::AmbientDimAtCompileTime, 1> VectorType;
VectorType p0 = VectorType::Random(dim);
VectorType p1 = VectorType::Random(dim);
RealScalar s1 = ei_random<RealScalar>(0,1);
BoxType b0(dim);
BoxType b1(VectorType::Random(dim),VectorType::Random(dim));
BoxType b2;
b0.extend(p0);
b0.extend(p1);
VERIFY(b0.contains(p0*s1+(Scalar(1)-s1)*p1));
VERIFY(!b0.contains(p0 + (1+s1)*(p1-p0)));
(b2 = b0).extend(b1);
VERIFY(b2.contains(b0));
VERIFY(b2.contains(b1));
VERIFY_IS_APPROX(b2.clamp(b0), b0);
// casting
const int Dim = BoxType::AmbientDimAtCompileTime;
typedef typename GetDifferentType<Scalar>::type OtherScalar;
AlignedBox<OtherScalar,Dim> hp1f = b0.template cast<OtherScalar>();
VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),b0);
AlignedBox<Scalar,Dim> hp1d = b0.template cast<Scalar>();
VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),b0);
}
void test_alignedbox()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( alignedbox(AlignedBox<float,2>()) );
CALL_SUBTEST( alignedbox(AlignedBox<float,3>()) );
CALL_SUBTEST( alignedbox(AlignedBox<double,4>()) );
}
}
| fix a warning in test/alignedbox | fix a warning in test/alignedbox
--HG--
extra : convert_revision : svn%3A283d02a7-25f6-0310-bc7c-ecb5cbfe19da/trunk/kdesupport/eigen2%40910041
| C++ | bsd-3-clause | rotorliu/eigen,madlib/eigen_backup,mjbshaw/Eigen,madlib/eigen_backup,madlib/eigen_backup,mjbshaw/Eigen,rotorliu/eigen,mjbshaw/Eigen,mjbshaw/Eigen,madlib/eigen_backup,rotorliu/eigen,rotorliu/eigen |
0e865cfeab207f322ab164354e768202a8792019 | test/basicstuff.cpp | test/basicstuff.cpp | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// 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/.
#define EIGEN_NO_STATIC_ASSERT
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
Index rows = m.rows();
Index cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
SquareMatrixType sm1 = SquareMatrixType::Random(rows,rows), sm2(rows,rows);
Scalar x = 0;
while(x == Scalar(0)) x = internal::random<Scalar>();
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.squaredNorm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
if(cols!=1 && rows!=1)
{
VERIFY_RAISES_ASSERT(m1[0]);
VERIFY_RAISES_ASSERT((m1+m1)[0]);
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
m3.real() = m1.real();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real());
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real());
// check == / != operators
VERIFY(m1==m1);
VERIFY(m1!=m2);
VERIFY(!(m1==m2));
VERIFY(!(m1!=m1));
m1 = m2;
VERIFY(m1==m2);
VERIFY(!(m1!=m2));
// check automatic transposition
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i) = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() += sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() -= sm1.row(i);
VERIFY_IS_APPROX(sm2,-sm1.transpose());
}
template<typename MatrixType> void basicStuffComplex(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType;
Index rows = m.rows();
Index cols = m.cols();
Scalar s1 = internal::random<Scalar>(),
s2 = internal::random<Scalar>();
VERIFY(numext::real(s1)==numext::real_ref(s1));
VERIFY(numext::imag(s1)==numext::imag_ref(s1));
numext::real_ref(s1) = numext::real(s2);
numext::imag_ref(s1) = numext::imag(s2);
VERIFY(internal::isApprox(s1, s2, NumTraits<RealScalar>::epsilon()));
// extended precision in Intel FPUs means that s1 == s2 in the line above is not guaranteed.
RealMatrixType rm1 = RealMatrixType::Random(rows,cols),
rm2 = RealMatrixType::Random(rows,cols);
MatrixType cm(rows,cols);
cm.real() = rm1;
cm.imag() = rm2;
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
rm1.setZero();
rm2.setZero();
rm1 = cm.real();
rm2 = cm.imag();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
cm.real().setZero();
VERIFY(static_cast<const MatrixType&>(cm).real().isZero());
VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero());
}
#ifdef EIGEN_TEST_PART_2
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
#endif
template <typename Scalar>
void fixedSizeMatrixConstruction()
{
Scalar raw[4];
for(int k=0; k<4; ++k)
raw[k] = internal::random<Scalar>();
{
Matrix<Scalar,4,1> m(raw);
Array<Scalar,4,1> a(raw);
for(int k=0; k<4; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<4; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,4,1>(raw[0],raw[1],raw[2],raw[3])));
VERIFY((a==(Array<Scalar,4,1>(raw[0],raw[1],raw[2],raw[3]))).all());
}
{
Matrix<Scalar,3,1> m(raw);
Array<Scalar,3,1> a(raw);
for(int k=0; k<3; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<3; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,3,1>(raw[0],raw[1],raw[2])));
VERIFY((a==Array<Scalar,3,1>(raw[0],raw[1],raw[2])).all());
}
{
Matrix<Scalar,2,1> m(raw), m2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) );
Array<Scalar,2,1> a(raw), a2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) );
for(int k=0; k<2; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<2; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,2,1>(raw[0],raw[1])));
VERIFY((a==Array<Scalar,2,1>(raw[0],raw[1])).all());
for(int k=0; k<2; ++k) VERIFY(m2(k) == DenseIndex(raw[k]));
for(int k=0; k<2; ++k) VERIFY(a2(k) == DenseIndex(raw[k]));
}
{
Matrix<Scalar,1,2> m(raw),
m2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) ),
m3( (int(raw[0])), (int(raw[1])) ),
m4( (float(raw[0])), (float(raw[1])) );
Array<Scalar,1,2> a(raw), a2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) );
for(int k=0; k<2; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<2; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,1,2>(raw[0],raw[1])));
VERIFY((a==Array<Scalar,1,2>(raw[0],raw[1])).all());
for(int k=0; k<2; ++k) VERIFY(m2(k) == DenseIndex(raw[k]));
for(int k=0; k<2; ++k) VERIFY(a2(k) == DenseIndex(raw[k]));
for(int k=0; k<2; ++k) VERIFY(m3(k) == int(raw[k]));
for(int k=0; k<2; ++k) VERIFY(m4(k) == float(raw[k]));
}
{
Matrix<Scalar,1,1> m(raw), m1(raw[0]), m2( (DenseIndex(raw[0])) ), m3( (int(raw[0])) );
Array<Scalar,1,1> a(raw), a1(raw[0]), a2( (DenseIndex(raw[0])) );
VERIFY(m(0) == raw[0]);
VERIFY(a(0) == raw[0]);
VERIFY(m1(0) == raw[0]);
VERIFY(a1(0) == raw[0]);
VERIFY(m2(0) == DenseIndex(raw[0]));
VERIFY(a2(0) == DenseIndex(raw[0]));
VERIFY(m3(0) == int(raw[0]));
VERIFY_IS_EQUAL(m,(Matrix<Scalar,1,1>(raw[0])));
VERIFY((a==Array<Scalar,1,1>(raw[0])).all());
}
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( basicStuff(Matrix4d()) );
CALL_SUBTEST_3( basicStuff(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_4( basicStuff(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuff(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
}
CALL_SUBTEST_1(fixedSizeMatrixConstruction<unsigned char>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<float>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<int>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<long int>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<std::ptrdiff_t>());
CALL_SUBTEST_2(casting());
}
| // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// 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/.
#define EIGEN_NO_STATIC_ASSERT
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
Index rows = m.rows();
Index cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
SquareMatrixType sm1 = SquareMatrixType::Random(rows,rows), sm2(rows,rows);
Scalar x = 0;
while(x == Scalar(0)) x = internal::random<Scalar>();
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.squaredNorm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
if(cols!=1 && rows!=1)
{
VERIFY_RAISES_ASSERT(m1[0]);
VERIFY_RAISES_ASSERT((m1+m1)[0]);
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
m3.real() = m1.real();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real());
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real());
// check == / != operators
VERIFY(m1==m1);
VERIFY(m1!=m2);
VERIFY(!(m1==m2));
VERIFY(!(m1!=m1));
m1 = m2;
VERIFY(m1==m2);
VERIFY(!(m1!=m2));
// check automatic transposition
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i) = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() = sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() += sm1.row(i);
VERIFY_IS_APPROX(sm2,sm1.transpose());
sm2.setZero();
for(typename MatrixType::Index i=0;i<rows;++i)
sm2.col(i).noalias() -= sm1.row(i);
VERIFY_IS_APPROX(sm2,-sm1.transpose());
}
template<typename MatrixType> void basicStuffComplex(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType;
Index rows = m.rows();
Index cols = m.cols();
Scalar s1 = internal::random<Scalar>(),
s2 = internal::random<Scalar>();
VERIFY(numext::real(s1)==numext::real_ref(s1));
VERIFY(numext::imag(s1)==numext::imag_ref(s1));
numext::real_ref(s1) = numext::real(s2);
numext::imag_ref(s1) = numext::imag(s2);
VERIFY(internal::isApprox(s1, s2, NumTraits<RealScalar>::epsilon()));
// extended precision in Intel FPUs means that s1 == s2 in the line above is not guaranteed.
RealMatrixType rm1 = RealMatrixType::Random(rows,cols),
rm2 = RealMatrixType::Random(rows,cols);
MatrixType cm(rows,cols);
cm.real() = rm1;
cm.imag() = rm2;
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
rm1.setZero();
rm2.setZero();
rm1 = cm.real();
rm2 = cm.imag();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
cm.real().setZero();
VERIFY(static_cast<const MatrixType&>(cm).real().isZero());
VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero());
}
#ifdef EIGEN_TEST_PART_2
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
#endif
template <typename Scalar>
void fixedSizeMatrixConstruction()
{
Scalar raw[4];
for(int k=0; k<4; ++k)
raw[k] = internal::random<Scalar>();
{
Matrix<Scalar,4,1> m(raw);
Array<Scalar,4,1> a(raw);
for(int k=0; k<4; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<4; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,4,1>(raw[0],raw[1],raw[2],raw[3])));
VERIFY((a==(Array<Scalar,4,1>(raw[0],raw[1],raw[2],raw[3]))).all());
}
{
Matrix<Scalar,3,1> m(raw);
Array<Scalar,3,1> a(raw);
for(int k=0; k<3; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<3; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,3,1>(raw[0],raw[1],raw[2])));
VERIFY((a==Array<Scalar,3,1>(raw[0],raw[1],raw[2])).all());
}
{
Matrix<Scalar,2,1> m(raw), m2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) );
Array<Scalar,2,1> a(raw), a2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) );
for(int k=0; k<2; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<2; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,2,1>(raw[0],raw[1])));
VERIFY((a==Array<Scalar,2,1>(raw[0],raw[1])).all());
for(int k=0; k<2; ++k) VERIFY(m2(k) == DenseIndex(raw[k]));
for(int k=0; k<2; ++k) VERIFY(a2(k) == DenseIndex(raw[k]));
}
{
Matrix<Scalar,1,2> m(raw),
m2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) ),
m3( (int(raw[0])), (int(raw[1])) ),
m4( (float(raw[0])), (float(raw[1])) );
Array<Scalar,1,2> a(raw), a2( (DenseIndex(raw[0])), (DenseIndex(raw[1])) );
for(int k=0; k<2; ++k) VERIFY(m(k) == raw[k]);
for(int k=0; k<2; ++k) VERIFY(a(k) == raw[k]);
VERIFY_IS_EQUAL(m,(Matrix<Scalar,1,2>(raw[0],raw[1])));
VERIFY((a==Array<Scalar,1,2>(raw[0],raw[1])).all());
for(int k=0; k<2; ++k) VERIFY(m2(k) == DenseIndex(raw[k]));
for(int k=0; k<2; ++k) VERIFY(a2(k) == DenseIndex(raw[k]));
for(int k=0; k<2; ++k) VERIFY(m3(k) == int(raw[k]));
for(int k=0; k<2; ++k) VERIFY((m4(k)) == Scalar(float(raw[k])));
}
{
Matrix<Scalar,1,1> m(raw), m1(raw[0]), m2( (DenseIndex(raw[0])) ), m3( (int(raw[0])) );
Array<Scalar,1,1> a(raw), a1(raw[0]), a2( (DenseIndex(raw[0])) );
VERIFY(m(0) == raw[0]);
VERIFY(a(0) == raw[0]);
VERIFY(m1(0) == raw[0]);
VERIFY(a1(0) == raw[0]);
VERIFY(m2(0) == DenseIndex(raw[0]));
VERIFY(a2(0) == DenseIndex(raw[0]));
VERIFY(m3(0) == int(raw[0]));
VERIFY_IS_EQUAL(m,(Matrix<Scalar,1,1>(raw[0])));
VERIFY((a==Array<Scalar,1,1>(raw[0])).all());
}
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( basicStuff(Matrix4d()) );
CALL_SUBTEST_3( basicStuff(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_4( basicStuff(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuff(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
}
CALL_SUBTEST_1(fixedSizeMatrixConstruction<unsigned char>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<float>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<double>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<int>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<long int>());
CALL_SUBTEST_1(fixedSizeMatrixConstruction<std::ptrdiff_t>());
CALL_SUBTEST_2(casting());
}
| Fix the fact that float(int) != float(int(float(int))) | Fix the fact that float(int) != float(int(float(int)))
| C++ | bsd-3-clause | madlib/eigen,madlib/eigen,madlib/eigen,madlib/eigen |
de43ea043b9e22e4de140e2b5489756f29636a47 | src/Buffer.cpp | src/Buffer.cpp | #include "Buffer.hpp"
#include "Error.hpp"
#include "InvalidObject.hpp"
#include "BufferAccess.hpp"
#include "UniformBlock.hpp"
PyObject * MGLBuffer_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
MGLBuffer * self = (MGLBuffer *)type->tp_alloc(type, 0);
#ifdef MGL_VERBOSE
printf("MGLBuffer_tp_new %p\n", self);
#endif
if (self) {
}
return (PyObject *)self;
}
void MGLBuffer_tp_dealloc(MGLBuffer * self) {
#ifdef MGL_VERBOSE
printf("MGLBuffer_tp_dealloc %p\n", self);
#endif
MGLBuffer_Type.tp_free((PyObject *)self);
}
int MGLBuffer_tp_init(MGLBuffer * self, PyObject * args, PyObject * kwargs) {
MGLError_Set("cannot create mgl.Buffer manually");
return -1;
}
MGLBufferAccess * MGLBuffer_access(MGLBuffer * self, PyObject * args) {
int size;
int offset;
int readonly;
int args_ok = PyArg_ParseTuple(
args,
"iip",
&size,
&offset,
&readonly
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size > self->size - offset) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
MGLBufferAccess * access = MGLBufferAccess_New();
access->gl = &self->context->gl;
access->ptr = 0;
access->buffer_obj = self->buffer_obj;
access->offset = offset;
access->size = size;
access->access = readonly ? GL_MAP_READ_BIT : (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
return access;
}
PyObject * MGLBuffer_read(MGLBuffer * self, PyObject * args) {
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"II",
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of rangeoffset = %d or size = %d", offset, size);
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
void * map = gl.MapBufferRange(GL_ARRAY_BUFFER, offset, size, GL_MAP_READ_BIT);
if (!map) {
MGLError_Set("cannot map the buffer");
return 0;
}
PyObject * data = PyBytes_FromStringAndSize((const char *)map, size);
gl.UnmapBuffer(GL_ARRAY_BUFFER);
return data;
}
PyObject * MGLBuffer_read_into(MGLBuffer * self, PyObject * args) {
PyObject * data;
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"OII",
&data,
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of rangeoffset = %d or size = %d", offset, size);
return 0;
}
Py_buffer buffer_view;
int get_buffer = PyObject_GetBuffer(data, &buffer_view, PyBUF_WRITABLE);
if (get_buffer < 0) {
MGLError_Set("the buffer (%s) does not support buffer interface", Py_TYPE(data)->tp_name);
return 0;
}
if (buffer_view.len < size) {
MGLError_Set("the buffer is too small %d < %d", buffer_view.len, size);
PyBuffer_Release(&buffer_view);
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
void * map = gl.MapBufferRange(GL_ARRAY_BUFFER, offset, size, GL_MAP_READ_BIT);
memcpy(buffer_view.buf, map, size);
gl.UnmapBuffer(GL_ARRAY_BUFFER);
PyBuffer_Release(&buffer_view);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_write(MGLBuffer * self, PyObject * args) {
const char * data;
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"y#I",
&data,
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (offset < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
gl.BufferSubData(GL_ARRAY_BUFFER, (GLintptr)offset, size, data);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_clear(MGLBuffer * self, PyObject * args) {
int size;
int offset;
PyObject * chunk;
int args_ok = PyArg_ParseTuple(
args,
"iiO",
&size,
&offset,
&chunk
);
if (!args_ok) {
return 0;
}
if (size < 0) {
size = self->size - offset;
}
Py_buffer buffer_view;
if (chunk != Py_None) {
int get_buffer = PyObject_GetBuffer(chunk, &buffer_view, PyBUF_SIMPLE);
if (get_buffer < 0) {
MGLError_Set("the chunk (%s) does not support buffer interface", Py_TYPE(chunk)->tp_name);
return 0;
}
if (size % buffer_view.len != 0) {
MGLError_Set("the chunk does not fit the size");
PyBuffer_Release(&buffer_view);
return 0;
}
} else {
buffer_view.len = 0;
buffer_view.buf = 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
char * map = (char *)gl.MapBufferRange(GL_ARRAY_BUFFER, offset, size, GL_MAP_WRITE_BIT);
if (!map) {
MGLError_Set("cannot map the buffer");
return 0;
}
if (buffer_view.len) {
char * src = (char *)buffer_view.buf;
int divisor = buffer_view.len;
for (int i = 0; i < size; ++i) {
map[i] = src[i % divisor];
}
} else {
memset(map + offset, 0, size);
}
gl.UnmapBuffer(GL_ARRAY_BUFFER);
if (chunk != Py_None) {
PyBuffer_Release(&buffer_view);
}
Py_RETURN_NONE;
}
PyObject * MGLBuffer_orphan(MGLBuffer * self) {
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
gl.BufferData(GL_ARRAY_BUFFER, self->size, 0, self->dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_bind_to_uniform_block(MGLBuffer * self, PyObject * args) {
PyObject * binding;
int args_ok = PyArg_ParseTuple(
args,
"O",
&binding
);
if (!args_ok) {
return 0;
}
int block = PyLong_AsUnsignedLong(binding);
if (PyErr_Occurred()) {
MGLError_Set("the binding is invalid");
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBufferBase(GL_UNIFORM_BUFFER, block, self->buffer_obj);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_bind_to_storage_buffer(MGLBuffer * self, PyObject * args) {
int binding;
int args_ok = PyArg_ParseTuple(
args,
"i",
&binding
);
if (!args_ok) {
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBufferBase(GL_SHADER_STORAGE_BUFFER, binding, self->buffer_obj);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_release(MGLBuffer * self) {
MGLBuffer_Invalidate(self);
Py_RETURN_NONE;
}
PyMethodDef MGLBuffer_tp_methods[] = {
{"access", (PyCFunction)MGLBuffer_access, METH_VARARGS, 0},
{"read", (PyCFunction)MGLBuffer_read, METH_VARARGS, 0},
{"read_into", (PyCFunction)MGLBuffer_read_into, METH_VARARGS, 0},
{"write", (PyCFunction)MGLBuffer_write, METH_VARARGS, 0},
{"clear", (PyCFunction)MGLBuffer_clear, METH_VARARGS, 0},
{"orphan", (PyCFunction)MGLBuffer_orphan, METH_NOARGS, 0},
{"bind_to_uniform_block", (PyCFunction)MGLBuffer_bind_to_uniform_block, METH_VARARGS, 0},
{"bind_to_storage_buffer", (PyCFunction)MGLBuffer_bind_to_storage_buffer, METH_VARARGS, 0},
{"release", (PyCFunction)MGLBuffer_release, METH_NOARGS, 0},
{0},
};
PyObject * MGLBuffer_get_size(MGLBuffer * self, void * closure) {
return PyLong_FromLong(self->size);
}
PyObject * MGLBuffer_get_dynamic(MGLBuffer * self, void * closure) {
return PyBool_FromLong(self->dynamic);
}
MGLContext * MGLBuffer_get_context(MGLBuffer * self, void * closure) {
Py_INCREF(self->context);
return self->context;
}
PyObject * MGLBuffer_get_glo(MGLBuffer * self, void * closure) {
return PyLong_FromLong(self->buffer_obj);
}
PyGetSetDef MGLBuffer_tp_getseters[] = {
{(char *)"size", (getter)MGLBuffer_get_size, 0, 0, 0},
{(char *)"dynamic", (getter)MGLBuffer_get_dynamic, 0, 0, 0},
{(char *)"context", (getter)MGLBuffer_get_context, 0, 0, 0},
{(char *)"glo", (getter)MGLBuffer_get_glo, 0, 0, 0},
{0},
};
int MGLBuffer_tp_as_buffer_get_view(MGLBuffer * self, Py_buffer * view, int flags) {
int access = (flags == PyBUF_SIMPLE) ? GL_MAP_READ_BIT : (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
void * map = gl.MapBufferRange(GL_ARRAY_BUFFER, 0, self->size, access);
if (!map) {
PyErr_Format(PyExc_BufferError, "Cannot map buffer");
view->obj = 0;
return -1;
}
view->buf = map;
view->len = self->size;
view->itemsize = 1;
view->format = 0;
view->ndim = 0;
view->shape = 0;
view->strides = 0;
view->suboffsets = 0;
Py_INCREF(self);
view->obj = (PyObject *)self;
return 0;
}
void MGLBuffer_tp_as_buffer_release_view(MGLBuffer * self, Py_buffer * view) {
const GLMethods & gl = self->context->gl;
gl.UnmapBuffer(GL_ARRAY_BUFFER);
}
PyBufferProcs MGLBuffer_tp_as_buffer = {
PyBufferProcs_PADDING
(getbufferproc)MGLBuffer_tp_as_buffer_get_view, // getbufferproc bf_getbuffer
(releasebufferproc)MGLBuffer_tp_as_buffer_release_view, // releasebufferproc bf_releasebuffer
};
PyTypeObject MGLBuffer_Type = {
PyVarObject_HEAD_INIT(0, 0)
"mgl.Buffer", // tp_name
sizeof(MGLBuffer), // tp_basicsize
0, // tp_itemsize
(destructor)MGLBuffer_tp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
&MGLBuffer_tp_as_buffer, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
0, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
MGLBuffer_tp_methods, // tp_methods
0, // tp_members
MGLBuffer_tp_getseters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)MGLBuffer_tp_init, // tp_init
0, // tp_alloc
MGLBuffer_tp_new, // tp_new
};
MGLBuffer * MGLBuffer_New() {
MGLBuffer * self = (MGLBuffer *)MGLBuffer_tp_new(&MGLBuffer_Type, 0, 0);
return self;
}
void MGLBuffer_Invalidate(MGLBuffer * buffer) {
if (Py_TYPE(buffer) == &MGLInvalidObject_Type) {
#ifdef MGL_VERBOSE
printf("MGLBuffer_Invalidate %p already released\n", buffer);
#endif
return;
}
#ifdef MGL_VERBOSE
printf("MGLBuffer_Invalidate %p\n", buffer);
#endif
const GLMethods & gl = buffer->context->gl;
gl.DeleteBuffers(1, (GLuint *)&buffer->buffer_obj);
Py_DECREF(buffer->context);
Py_TYPE(buffer) = &MGLInvalidObject_Type;
Py_DECREF(buffer);
}
| #include "Buffer.hpp"
#include "Error.hpp"
#include "InvalidObject.hpp"
#include "BufferAccess.hpp"
#include "UniformBlock.hpp"
PyObject * MGLBuffer_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
MGLBuffer * self = (MGLBuffer *)type->tp_alloc(type, 0);
#ifdef MGL_VERBOSE
printf("MGLBuffer_tp_new %p\n", self);
#endif
if (self) {
}
return (PyObject *)self;
}
void MGLBuffer_tp_dealloc(MGLBuffer * self) {
#ifdef MGL_VERBOSE
printf("MGLBuffer_tp_dealloc %p\n", self);
#endif
MGLBuffer_Type.tp_free((PyObject *)self);
}
int MGLBuffer_tp_init(MGLBuffer * self, PyObject * args, PyObject * kwargs) {
MGLError_Set("cannot create mgl.Buffer manually");
return -1;
}
MGLBufferAccess * MGLBuffer_access(MGLBuffer * self, PyObject * args) {
int size;
int offset;
int readonly;
int args_ok = PyArg_ParseTuple(
args,
"iip",
&size,
&offset,
&readonly
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size > self->size - offset) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
MGLBufferAccess * access = MGLBufferAccess_New();
access->gl = &self->context->gl;
access->ptr = 0;
access->buffer_obj = self->buffer_obj;
access->offset = offset;
access->size = size;
access->access = readonly ? GL_MAP_READ_BIT : (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
return access;
}
PyObject * MGLBuffer_read(MGLBuffer * self, PyObject * args) {
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"II",
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of rangeoffset = %d or size = %d", offset, size);
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
void * map = gl.MapBufferRange(GL_ARRAY_BUFFER, offset, size, GL_MAP_READ_BIT);
if (!map) {
MGLError_Set("cannot map the buffer");
return 0;
}
PyObject * data = PyBytes_FromStringAndSize((const char *)map, size);
gl.UnmapBuffer(GL_ARRAY_BUFFER);
return data;
}
PyObject * MGLBuffer_read_into(MGLBuffer * self, PyObject * args) {
PyObject * data;
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"OII",
&data,
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (size == -1) {
size = self->size - offset;
}
if (offset < 0 || size < 0 || size + offset > self->size) {
MGLError_Set("out of rangeoffset = %d or size = %d", offset, size);
return 0;
}
Py_buffer buffer_view;
int get_buffer = PyObject_GetBuffer(data, &buffer_view, PyBUF_WRITABLE);
if (get_buffer < 0) {
MGLError_Set("the buffer (%s) does not support buffer interface", Py_TYPE(data)->tp_name);
return 0;
}
if (buffer_view.len < size) {
MGLError_Set("the buffer is too small %d < %d", buffer_view.len, size);
PyBuffer_Release(&buffer_view);
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
void * map = gl.MapBufferRange(GL_ARRAY_BUFFER, offset, size, GL_MAP_READ_BIT);
memcpy(buffer_view.buf, map, size);
gl.UnmapBuffer(GL_ARRAY_BUFFER);
PyBuffer_Release(&buffer_view);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_write(MGLBuffer * self, PyObject * args) {
const char * data;
int size;
int offset;
int args_ok = PyArg_ParseTuple(
args,
"y#I",
&data,
&size,
&offset
);
if (!args_ok) {
return 0;
}
if (offset < 0 || size + offset > self->size) {
MGLError_Set("out of range offset = %d or size = %d", offset, size);
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
gl.BufferSubData(GL_ARRAY_BUFFER, (GLintptr)offset, size, data);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_clear(MGLBuffer * self, PyObject * args) {
int size;
int offset;
PyObject * chunk;
int args_ok = PyArg_ParseTuple(
args,
"iiO",
&size,
&offset,
&chunk
);
if (!args_ok) {
return 0;
}
if (size < 0) {
size = self->size - offset;
}
Py_buffer buffer_view;
if (chunk != Py_None) {
int get_buffer = PyObject_GetBuffer(chunk, &buffer_view, PyBUF_SIMPLE);
if (get_buffer < 0) {
MGLError_Set("the chunk (%s) does not support buffer interface", Py_TYPE(chunk)->tp_name);
return 0;
}
if (size % buffer_view.len != 0) {
MGLError_Set("the chunk does not fit the size");
PyBuffer_Release(&buffer_view);
return 0;
}
} else {
buffer_view.len = 0;
buffer_view.buf = 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
char * map = (char *)gl.MapBufferRange(GL_ARRAY_BUFFER, offset, size, GL_MAP_WRITE_BIT);
if (!map) {
MGLError_Set("cannot map the buffer");
return 0;
}
if (buffer_view.len) {
char * src = (char *)buffer_view.buf;
int divisor = buffer_view.len;
for (int i = 0; i < size; ++i) {
map[i] = src[i % divisor];
}
} else {
memset(map + offset, 0, size);
}
gl.UnmapBuffer(GL_ARRAY_BUFFER);
if (chunk != Py_None) {
PyBuffer_Release(&buffer_view);
}
Py_RETURN_NONE;
}
PyObject * MGLBuffer_orphan(MGLBuffer * self) {
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
gl.BufferData(GL_ARRAY_BUFFER, self->size, 0, self->dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_bind_to_uniform_block(MGLBuffer * self, PyObject * args) {
int binding;
int args_ok = PyArg_ParseTuple(
args,
"I",
&binding
);
if (!args_ok) {
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBufferBase(GL_UNIFORM_BUFFER, binding, self->buffer_obj);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_bind_to_storage_buffer(MGLBuffer * self, PyObject * args) {
int binding;
int args_ok = PyArg_ParseTuple(
args,
"I",
&binding
);
if (!args_ok) {
return 0;
}
const GLMethods & gl = self->context->gl;
gl.BindBufferBase(GL_SHADER_STORAGE_BUFFER, binding, self->buffer_obj);
Py_RETURN_NONE;
}
PyObject * MGLBuffer_release(MGLBuffer * self) {
MGLBuffer_Invalidate(self);
Py_RETURN_NONE;
}
PyMethodDef MGLBuffer_tp_methods[] = {
{"access", (PyCFunction)MGLBuffer_access, METH_VARARGS, 0},
{"read", (PyCFunction)MGLBuffer_read, METH_VARARGS, 0},
{"read_into", (PyCFunction)MGLBuffer_read_into, METH_VARARGS, 0},
{"write", (PyCFunction)MGLBuffer_write, METH_VARARGS, 0},
{"clear", (PyCFunction)MGLBuffer_clear, METH_VARARGS, 0},
{"orphan", (PyCFunction)MGLBuffer_orphan, METH_NOARGS, 0},
{"bind_to_uniform_block", (PyCFunction)MGLBuffer_bind_to_uniform_block, METH_VARARGS, 0},
{"bind_to_storage_buffer", (PyCFunction)MGLBuffer_bind_to_storage_buffer, METH_VARARGS, 0},
{"release", (PyCFunction)MGLBuffer_release, METH_NOARGS, 0},
{0},
};
PyObject * MGLBuffer_get_size(MGLBuffer * self, void * closure) {
return PyLong_FromLong(self->size);
}
PyObject * MGLBuffer_get_dynamic(MGLBuffer * self, void * closure) {
return PyBool_FromLong(self->dynamic);
}
MGLContext * MGLBuffer_get_context(MGLBuffer * self, void * closure) {
Py_INCREF(self->context);
return self->context;
}
PyObject * MGLBuffer_get_glo(MGLBuffer * self, void * closure) {
return PyLong_FromLong(self->buffer_obj);
}
PyGetSetDef MGLBuffer_tp_getseters[] = {
{(char *)"size", (getter)MGLBuffer_get_size, 0, 0, 0},
{(char *)"dynamic", (getter)MGLBuffer_get_dynamic, 0, 0, 0},
{(char *)"context", (getter)MGLBuffer_get_context, 0, 0, 0},
{(char *)"glo", (getter)MGLBuffer_get_glo, 0, 0, 0},
{0},
};
int MGLBuffer_tp_as_buffer_get_view(MGLBuffer * self, Py_buffer * view, int flags) {
int access = (flags == PyBUF_SIMPLE) ? GL_MAP_READ_BIT : (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
const GLMethods & gl = self->context->gl;
gl.BindBuffer(GL_ARRAY_BUFFER, self->buffer_obj);
void * map = gl.MapBufferRange(GL_ARRAY_BUFFER, 0, self->size, access);
if (!map) {
PyErr_Format(PyExc_BufferError, "Cannot map buffer");
view->obj = 0;
return -1;
}
view->buf = map;
view->len = self->size;
view->itemsize = 1;
view->format = 0;
view->ndim = 0;
view->shape = 0;
view->strides = 0;
view->suboffsets = 0;
Py_INCREF(self);
view->obj = (PyObject *)self;
return 0;
}
void MGLBuffer_tp_as_buffer_release_view(MGLBuffer * self, Py_buffer * view) {
const GLMethods & gl = self->context->gl;
gl.UnmapBuffer(GL_ARRAY_BUFFER);
}
PyBufferProcs MGLBuffer_tp_as_buffer = {
PyBufferProcs_PADDING
(getbufferproc)MGLBuffer_tp_as_buffer_get_view, // getbufferproc bf_getbuffer
(releasebufferproc)MGLBuffer_tp_as_buffer_release_view, // releasebufferproc bf_releasebuffer
};
PyTypeObject MGLBuffer_Type = {
PyVarObject_HEAD_INIT(0, 0)
"mgl.Buffer", // tp_name
sizeof(MGLBuffer), // tp_basicsize
0, // tp_itemsize
(destructor)MGLBuffer_tp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
&MGLBuffer_tp_as_buffer, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
0, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
MGLBuffer_tp_methods, // tp_methods
0, // tp_members
MGLBuffer_tp_getseters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)MGLBuffer_tp_init, // tp_init
0, // tp_alloc
MGLBuffer_tp_new, // tp_new
};
MGLBuffer * MGLBuffer_New() {
MGLBuffer * self = (MGLBuffer *)MGLBuffer_tp_new(&MGLBuffer_Type, 0, 0);
return self;
}
void MGLBuffer_Invalidate(MGLBuffer * buffer) {
if (Py_TYPE(buffer) == &MGLInvalidObject_Type) {
#ifdef MGL_VERBOSE
printf("MGLBuffer_Invalidate %p already released\n", buffer);
#endif
return;
}
#ifdef MGL_VERBOSE
printf("MGLBuffer_Invalidate %p\n", buffer);
#endif
const GLMethods & gl = buffer->context->gl;
gl.DeleteBuffers(1, (GLuint *)&buffer->buffer_obj);
Py_DECREF(buffer->context);
Py_TYPE(buffer) = &MGLInvalidObject_Type;
Py_DECREF(buffer);
}
| fix buffer bindings | fix buffer bindings
| C++ | mit | cprogrammer1994/ModernGL,cprogrammer1994/ModernGL,cprogrammer1994/ModernGL |
310267a11a036183b5cc4e5e5ca5f46555a1b4e9 | SurfMatcher.hpp | SurfMatcher.hpp | #include <iostream>
#include <stdio.h>
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/xfeatures2d.hpp"
using namespace cv;
using namespace cv::xfeatures2d;
using namespace std;
const int LOOP_NUM = 10;
const int GOOD_PTS_MAX = 50;
const float GOOD_PORTION = 0.15f;
int64 work_begin = 0;
int64 work_end = 0;
static void workBegin()
{
work_begin = getTickCount();
}
static void workEnd()
{
work_end = getTickCount() - work_begin;
}
static double getTime()
{
return work_end /((double)getTickFrequency() )* 1000.;
}
struct SURFDetector
{
Ptr<Feature2D> surf;
SURFDetector(double hessian = 800.0)
{
surf = SURF::create(hessian);
}
template<class T>
void operator()(const T& in, const T& mask, vector<cv::KeyPoint>& pts, T& descriptors, bool useProvided = false)
{
surf->detectAndCompute(in, mask, pts, descriptors, useProvided);
}
};
template<class KPMatcher>
struct SURFMatcher
{
KPMatcher matcher;
template<class T>
void match(const T& in1, const T& in2, vector<cv::DMatch>& matches)
{
matcher.match(in1, in2, matches);
}
};
static Mat drawGoodMatches(
const Mat& img1,
const Mat& img2,
const vector<KeyPoint>& keypoints1,
const vector<KeyPoint>& keypoints2,
vector<DMatch>& matches,
vector<Point2f>& scene_corners_
)
{
//-- Sort matches and preserve top 10% matches
sort(matches.begin(), matches.end());
vector< DMatch > good_matches;
double minDist = matches.front().distance;
double maxDist = matches.back().distance;
const int ptsPairs = min(GOOD_PTS_MAX, (int)(matches.size() * GOOD_PORTION));
for( int i = 0; i < ptsPairs; i++ )
{
good_matches.push_back( matches[i] );
}
cout << "\nMax distance: " << maxDist << endl;
cout << "Min distance: " << minDist << endl;
cout << "Calculating homography using " << ptsPairs << " point pairs." << endl;
// drawing the results
Mat img_matches;
drawMatches( img1, keypoints1, img2, keypoints2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
//-- Localize the object
vector<Point2f> obj;
vector<Point2f> scene;
for( size_t i = 0; i < good_matches.size(); i++ )
{
//-- Get the keypoints from the good matches
obj.push_back( keypoints1[ good_matches[i].queryIdx ].pt );
scene.push_back( keypoints2[ good_matches[i].trainIdx ].pt );
}
//-- Get the corners from the image_1 ( the object to be "detected" )
vector<Point2f> obj_corners(4);
obj_corners[0] = Point(0,0);
obj_corners[1] = Point( img1.cols, 0 );
obj_corners[2] = Point( img1.cols, img1.rows );
obj_corners[3] = Point( 0, img1.rows );
vector<Point2f> scene_corners(4);
Mat H = findHomography( obj, scene );
Mat H2 = findHomography( scene, obj);
perspectiveTransform( obj_corners, scene_corners, H);
//imshow("image1", img1);
//imshow("image2", img2);
Size size(img1.cols,img1.rows);
Mat tempMat = Mat::zeros(size,CV_8UC3);
warpPerspective(img2, tempMat, H2, size);
imshow("temp_image", tempMat);
scene_corners_ = scene_corners;
//-- Draw lines between the corners (the mapped object in the scene - image_2 )
line( img_matches,
scene_corners[0] + Point2f( (float)img1.cols, 0), scene_corners[1] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
line( img_matches,
scene_corners[1] + Point2f( (float)img1.cols, 0), scene_corners[2] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
line( img_matches,
scene_corners[2] + Point2f( (float)img1.cols, 0), scene_corners[3] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
line( img_matches,
scene_corners[3] + Point2f( (float)img1.cols, 0), scene_corners[0] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
return img_matches;
}
static Mat CutGoodArea(
const Mat& img1,
const Mat& img2,
const vector<KeyPoint>& keypoints1,
const vector<KeyPoint>& keypoints2,
vector<DMatch>& matches,
vector<Point2f>& scene_corners_
)
{
//-- Sort matches and preserve top 10% matches
sort(matches.begin(), matches.end());
vector< DMatch > good_matches;
double minDist = matches.front().distance;
double maxDist = matches.back().distance;
const int ptsPairs = min(GOOD_PTS_MAX, (int)(matches.size() * GOOD_PORTION));
for( int i = 0; i < ptsPairs; i++ )
{
good_matches.push_back( matches[i] );
}
cout << "\nMax distance: " << maxDist << endl;
cout << "Min distance: " << minDist << endl;
cout << "Calculating homography using " << ptsPairs << " point pairs." << endl;
// drawing the results
Mat img_matches;
drawMatches( img1, keypoints1, img2, keypoints2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
//-- Localize the object
vector<Point2f> obj;
vector<Point2f> scene;
for( size_t i = 0; i < good_matches.size(); i++ )
{
//-- Get the keypoints from the good matches
obj.push_back( keypoints1[ good_matches[i].queryIdx ].pt );
scene.push_back( keypoints2[ good_matches[i].trainIdx ].pt );
}
//-- Get the corners from the image_1 ( the object to be "detected" )
vector<Point2f> obj_corners(4);
obj_corners[0] = Point(0,0);
obj_corners[1] = Point( img1.cols, 0 );
obj_corners[2] = Point( img1.cols, img1.rows );
obj_corners[3] = Point( 0, img1.rows );
vector<Point2f> scene_corners(4);
Mat H2 = findHomography( scene, obj);
Size size(img1.cols,img1.rows);
Mat imgGoodArea = Mat::zeros(size,CV_8UC3);
warpPerspective(img2, imgGoodArea, H2, size);
imshow("img_GoodArea", imgGoodArea);
return imgGoodArea;
}
Mat SurfMatch(Mat img1, Mat img2)
{
double surf_time = 0.;
//宣告輸入及輸出data
vector<KeyPoint> keypoints1, keypoints2;
vector<DMatch> matches;
UMat _descriptors1, _descriptors2;
Mat descriptors1 = _descriptors1.getMat(ACCESS_RW);
Mat descriptors2 = _descriptors2.getMat(ACCESS_RW);
//instantiate detectors/matchers
SURFDetector surf;
SURFMatcher<BFMatcher> matcher;
//-- start of timing section
for (int i = 0; i <= LOOP_NUM; i++)
{
if(i == 1) workBegin();
//surf(img1.getMat(ACCESS_READ), Mat(), keypoints1, descriptors1);
//surf(img2.getMat(ACCESS_READ), Mat(), keypoints2, descriptors2);
surf(img1, Mat(), keypoints1, descriptors1);
surf(img2, Mat(), keypoints2, descriptors2);
matcher.match(descriptors1, descriptors2, matches);
}
workEnd();
cout << "FOUND " << keypoints1.size() << " keypoints on first image" << endl;
cout << "FOUND " << keypoints2.size() << " keypoints on second image" << endl;
surf_time = getTime();
cout << "SURF run time: " << surf_time / LOOP_NUM << " ms" << endl<<"\n";
vector<Point2f> corner;
//Mat img_matches = drawGoodMatches(img1.getMat(ACCESS_READ), img2.getMat(ACCESS_READ), keypoints1, keypoints2, matches, corner);
//Mat img_matches = drawGoodMatches(img1, img2, keypoints1, keypoints2, matches, corner);
Mat imgIdentifyCard = CutGoodArea(img1, img2, keypoints1, keypoints2, matches, corner);
//-- Show detected matches
//string outpath = "test.jpg";
/*namedWindow("surf matches", 0);
imshow("surf matches", img_matches);
imwrite(outpath, img_matches);*/
return imgIdentifyCard;
}
| #include <iostream>
#include <stdio.h>
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/xfeatures2d.hpp"
using namespace cv;
using namespace cv::xfeatures2d;
using namespace std;
const int LOOP_NUM = 10;
const int GOOD_PTS_MAX = 50;
const float GOOD_PORTION = 0.15f;
int64 work_begin = 0;
int64 work_end = 0;
static void workBegin()
{
work_begin = getTickCount();
}
static void workEnd()
{
work_end = getTickCount() - work_begin;
}
static double getTime()
{
return work_end /((double)getTickFrequency() )* 1000.;
}
struct SURFDetector
{
Ptr<Feature2D> surf;
SURFDetector(double hessian = 800.0)
{
surf = SURF::create(hessian);
}
template<class T>
void operator()(const T& in, const T& mask, vector<cv::KeyPoint>& pts, T& descriptors, bool useProvided = false)
{
surf->detectAndCompute(in, mask, pts, descriptors, useProvided);
}
};
template<class KPMatcher>
struct SURFMatcher
{
KPMatcher matcher;
template<class T>
void match(const T& in1, const T& in2, vector<cv::DMatch>& matches)
{
matcher.match(in1, in2, matches);
}
};
static Mat drawGoodMatches(
const Mat& img1,
const Mat& img2,
const vector<KeyPoint>& keypoints1,
const vector<KeyPoint>& keypoints2,
vector<DMatch>& matches,
vector<Point2f>& scene_corners_
)
{
//-- Sort matches and preserve top 10% matches
sort(matches.begin(), matches.end());
vector< DMatch > good_matches;
good_matches.reserve(matches.size());
double minDist = matches.front().distance;
double maxDist = matches.back().distance;
// const int LOOP_NUM = 10;
// const int GOOD_PTS_MAX = 50;
// const float GOOD_PORTION = 0.15f;
int goodMatchStart = 0;
int goodMatchEnd = matches.size();
//goodMatchEnd = min(goodMatchStart + 30, goodMatchStart + (int)(matches.size() * GOOD_PORTION));
//goodMatchEnd = min(goodMatchEnd, (int)(matches.size()));
cout << "goodMatchEnd = " << goodMatchEnd << endl;
int ptsPairs = goodMatchEnd - goodMatchStart;
double tresholdDist = 0.2 * sqrt(double(img1.size().height * img1.size().height + img1.size().width * img1.size().width));
double deltaY = 0.2 * (double)img1.size().height;
double deltaX = 0.2 * (double)img1.size().width;
for( int i = goodMatchStart; i < goodMatchEnd; i++ )
{
//以相近斜率做特特徵點篩選 失敗
// cout << "i = " << i <<endl;
// vector<double> slope;
// int slopeIndex = 0;
// for(int j = max(i - 1, 0); j <= min((int)matches.size(), i + 1); j++)
// {
// cout << "j= " << j << endl;
// Point2f from = keypoints1[matches[j].queryIdx].pt;
// Point2f to = keypoints2[matches[j].trainIdx].pt;
// slopeIndex++;
// slope.push_back((double)(to.y - from.y) / (double)(to.x - from.x));
// }
// int slopeRange = 5;
// int matchFlag = 0;
// for(int j = 0; j < slopeIndex - 1; j++)
// {
// if(slope[j] - slopeRange > slope[j + 1] || slope[j] + slopeRange < slope[j + 1])
// matchFlag++;
// }
// cout<<"slopeIndex = " << slopeIndex<<endl;
// for(int j= 0; j < slopeIndex; j++)
// cout<<"slope" << j << " = " <<slope[j]<<endl;
// cout<<"match flag = "<<matchFlag<<endl<<endl;
// if(matchFlag == 2)
// {
// Point2f from2 = keypoints1[matches[i].queryIdx].pt;
// Point2f to2 = keypoints2[matches[i].trainIdx].pt;
// cout << "slope = " << (double)(from2.y - to2.y) / (double)(from2.x - to2.x) << endl;
// cout<<"push. i = " << i <<endl;
// cout << "from2 10 = " << keypoints1[matches[10].queryIdx].pt << endl;
// cout << "to2 10 = " << keypoints2[matches[10].queryIdx].pt << endl;
// cout << "from2 26 = " << keypoints1[matches[26].queryIdx].pt << endl;
// cout << "to2 26 = " << keypoints2[matches[26].queryIdx].pt << endl;
// good_matches.push_back( matches[10] );
// good_matches.push_back( matches[26] );
// }
//以距離及XY值變化量做條件的特徵點篩選 失敗
// Point2f from = keypoints1[matches[i].queryIdx].pt;
// Point2f to = keypoints2[matches[i].trainIdx].pt;
// double dist = sqrt((from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y));
// cout << "from.x = " << from.x << ", from.y = " << from.y << endl;
// cout << "to.x = " << to.x << ", to.y = " << to.y << endl;
// cout << "slope = " << (double)(from.y - to.y) / (double)(from.x - to.x) << endl;
// cout << "tresholdDist = " << tresholdDist << endl;
// cout << "deltaY = " << deltaY << endl;
// cout << "dist = " << dist << endl;
// cout << "distance = " << matches[i].distance << endl;
//
// if(dist < tresholdDist && abs(to.y - from.y) < deltaY && abs(to.x - from.x) < deltaX)
// {
// good_matches.push_back( matches[i] );
// cout<<"push. i = " << i <<endl;
// }
good_matches.push_back( matches[i] );
// cout<<"push. i = " << i <<endl;
// cout<<endl;
}
cout << "\nMax distance: " << maxDist << endl;
cout << "Min distance: " << minDist << endl;
cout << "Calculating homography using " << good_matches.size() << " point pairs." << endl;
// drawing the results
Mat img_matches;
drawMatches( img1, keypoints1, img2, keypoints2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
//-- Localize the object
vector<Point2f> obj;
vector<Point2f> scene;
for( size_t i = 0; i < good_matches.size(); i++ )
{
//-- Get the keypoints from the good matches
obj.push_back( keypoints1[ good_matches[i].queryIdx ].pt );
scene.push_back( keypoints2[ good_matches[i].trainIdx ].pt );
}
//-- Get the corners from the image_1 ( the object to be "detected" )
vector<Point2f> obj_corners(4);
obj_corners[0] = Point(0,0);
obj_corners[1] = Point( img1.cols, 0 );
obj_corners[2] = Point( img1.cols, img1.rows );
obj_corners[3] = Point( 0, img1.rows );
vector<Point2f> scene_corners(4);
Mat H = findHomography( obj, scene );
Mat H2 = findHomography( scene, obj);
perspectiveTransform( obj_corners, scene_corners, H);
// for(int index = 0; index < 4; index++)
// {
// cout << "scene_corners[" << index << "] = " << scene_corners[index] << endl;
// cout << "obj_corners[" << index << "] = " << obj_corners[index] << endl;
// }
imshow("image1", img1);//樣本
imshow("image2", img2);//場景
Size size(img1.cols,img1.rows);
Mat tempMat = Mat::zeros(size,CV_8UC3);
warpPerspective(img2, tempMat, H2, size);
imshow("output_image", tempMat);
scene_corners_ = scene_corners;
//-- Draw lines between the corners (the mapped object in the scene - image_2 )
line( img_matches,
scene_corners[0] + Point2f( (float)img1.cols, 0), scene_corners[1] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
line( img_matches,
scene_corners[1] + Point2f( (float)img1.cols, 0), scene_corners[2] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
line( img_matches,
scene_corners[2] + Point2f( (float)img1.cols, 0), scene_corners[3] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
line( img_matches,
scene_corners[3] + Point2f( (float)img1.cols, 0), scene_corners[0] + Point2f( (float)img1.cols, 0),
Scalar( 0, 255, 0), 2, LINE_AA );
resize(img_matches,img_matches,Size(800, 480));
imshow("goodMatch_image", img_matches);
return tempMat;
}
static Mat CutGoodArea(
const Mat& img1,
const Mat& img2,
const vector<KeyPoint>& keypoints1,
const vector<KeyPoint>& keypoints2,
vector<DMatch>& matches,
vector<Point2f>& scene_corners_
)
{
//-- Sort matches and preserve top 10% matches
sort(matches.begin(), matches.end());
vector< DMatch > good_matches;
double minDist = matches.front().distance;
double maxDist = matches.back().distance;
const int ptsPairs = min(GOOD_PTS_MAX, (int)(matches.size() * GOOD_PORTION));
for( int i = 0; i < ptsPairs; i++ )
{
good_matches.push_back( matches[i] );
}
cout << "\nMax distance: " << maxDist << endl;
cout << "Min distance: " << minDist << endl;
cout << "Calculating homography using " << ptsPairs << " point pairs." << endl;
// drawing the results
Mat img_matches;
drawMatches( img1, keypoints1, img2, keypoints2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
//-- Localize the object
vector<Point2f> obj;
vector<Point2f> scene;
for( size_t i = 0; i < good_matches.size(); i++ )
{
//-- Get the keypoints from the good matches
obj.push_back( keypoints1[ good_matches[i].queryIdx ].pt );
scene.push_back( keypoints2[ good_matches[i].trainIdx ].pt );
}
//-- Get the corners from the image_1 ( the object to be "detected" )
vector<Point2f> obj_corners(4);
obj_corners[0] = Point(0,0);
obj_corners[1] = Point( img1.cols, 0 );
obj_corners[2] = Point( img1.cols, img1.rows );
obj_corners[3] = Point( 0, img1.rows );
vector<Point2f> scene_corners(4);
Mat H2 = findHomography( scene, obj);
Size size(img1.cols,img1.rows);
Mat imgGoodArea = Mat::zeros(size,CV_8UC3);
warpPerspective(img2, imgGoodArea, H2, size);
imshow("img_GoodArea", imgGoodArea);
return imgGoodArea;
}
Mat SurfMatch(Mat img1, Mat img2)
{
double surf_time = 0.;
//宣告輸入及輸出data
vector<KeyPoint> keypoints1, keypoints2;
vector<DMatch> matches;
UMat _descriptors1, _descriptors2;
Mat descriptors1 = _descriptors1.getMat(ACCESS_RW);
Mat descriptors2 = _descriptors2.getMat(ACCESS_RW);
//instantiate detectors/matchers
SURFDetector surf;
SURFMatcher<BFMatcher> matcher;
//-- start of timing section
for (int i = 0; i <= LOOP_NUM; i++)
{
if(i == 1) workBegin();
//surf(img1.getMat(ACCESS_READ), Mat(), keypoints1, descriptors1);
//surf(img2.getMat(ACCESS_READ), Mat(), keypoints2, descriptors2);
surf(img1, Mat(), keypoints1, descriptors1);
surf(img2, Mat(), keypoints2, descriptors2);
matcher.match(descriptors1, descriptors2, matches);
}
workEnd();
cout << "FOUND " << keypoints1.size() << " keypoints on first image" << endl;
cout << "FOUND " << keypoints2.size() << " keypoints on second image" << endl;
surf_time = getTime();
cout << "SURF run time: " << surf_time / LOOP_NUM << " ms" << endl<<"\n";
vector<Point2f> corner;
//Mat img_matches = drawGoodMatches(img1.getMat(ACCESS_READ), img2.getMat(ACCESS_READ), keypoints1, keypoints2, matches, corner);
//Mat img_matches = drawGoodMatches(img1, img2, keypoints1, keypoints2, matches, corner);
//Mat imgIdentifyCard = CutGoodArea(img1, img2, keypoints1, keypoints2, matches, corner);
Mat imgIdentifyCard = drawGoodMatches(img1, img2, keypoints1, keypoints2, matches, corner);
//-- Show detected matches
//string outpath = "test.jpg";
/*namedWindow("surf matches", 0);
imshow("surf matches", img_matches);
imwrite(outpath, img_matches);*/
return imgIdentifyCard;
}
| 修改 SurfMatcher.hpp(未採用) -增加特徵點篩選條件 | 修改
SurfMatcher.hpp(未採用)
-增加特徵點篩選條件
| C++ | apache-2.0 | tyson3822/IdentityCardNumberRecognition |
4419164995f2375355aee1a85b4e763985b660a2 | src/CS5490.cpp | src/CS5490.cpp | /******************************************
Author: Tiago Britto Lobão
[email protected]
*/
/*
Purpose: Control an integrated circuit
Cirrus Logic - CS5490
Used to measure electrical quantities
MIT License
******************************************/
#include "CS5490.h"
/******* Init CS5490 *******/
//For Arduino & ESP8622
#if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s)
CS5490::CS5490(float mclk, int rx, int tx){
this->MCLK = mclk;
this->cSerial = new SoftwareSerial(rx,tx);
}
//For ESP32 AND MEGA
#else
CS5490::CS5490(float mclk){
this->MCLK = mclk;
this->cSerial = &Serial2;
}
#endif
void CS5490::begin(int baudRate){
cSerial->begin(baudRate);
}
/**************************************************************/
/* PRIVATE METHODS */
/**************************************************************/
/******* Write a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::write(int page, int address, long value){
uint8_t checksum = 0;
for(int i=0; i<3; i++)
checksum += 0xFF - checksum;
//Select page and address
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (writeByte | (uint8_t)address);
cSerial->write(buffer);
//Send information
for(int i=0; i<3 ; i++){
data[i] = value & 0x000000FF;
cSerial->write(this->data[i]);
value >>= 8;
}
//Calculate and send checksum
buffer = 0xFF - data[0] - data[1] - data[2];
cSerial->write(buffer);
}
/******* Read a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::read(int page, int address){
cSerial->flush();
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (readByte | (uint8_t)address);
cSerial->write(buffer);
//Wait for 3 bytes to arrive
while(cSerial->available() < 3);
for(int i=0; i<3; i++){
data[i] = cSerial->read();
}
}
/******* Give an instruction by the serial communication *******/
void CS5490::instruct(int value){
cSerial->flush();
uint8_t buffer = (instructionByte | (uint8_t)value);
cSerial->write(buffer);
}
/*
Function: toDouble
Transforms a 24 bit number to a double number for easy processing data
Param:
data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490
LSBpow => Exponent specified from datasheet of the less significant bit
MSBoption => Information of most significant bit case. It can be only three values:
MSBnull (1) The MSB is a Don't Care bit
MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion
MSBunsigned (3) The MSB is a positive value, the default case.
*/
double CS5490::toDouble(int LSBpow, int MSBoption){
uint32_t buffer = 0;
double output = 0.0;
bool MSB;
//Concat bytes in a 32 bit word
buffer += this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
switch(MSBoption){
case MSBnull:
this->data[2] &= ~(1 << 7); //Clear MSB
buffer += this->data[2] << 16;
output = (double)buffer;
output /= pow(2,LSBpow);
break;
case MSBsigned:
MSB = data[2] & 0x80;
if(MSB){ //- (2 complement conversion)
buffer = ~buffer;
//Clearing the first 8 bits
for(int i=24; i<32; i++)
buffer &= ~(1 << i);
output = (double)buffer + 1.0;
output /= -pow(2,LSBpow);
}
else{ //+
output = (double)buffer;
output /= (pow(2,LSBpow)-1.0);
}
break;
default:
case MSBunsigned:
output = (double)buffer;
output /= pow(2,LSBpow);
break;
}
return output;
}
/**************************************************************/
/* PUBLIC METHODS - Instructions */
/**************************************************************/
void CS5490::reset(){
this->instruct(1);
}
void CS5490::standby(){
this->instruct(2);
}
void CS5490::wakeUp(){
this->instruct(3);
}
void CS5490::singConv(){
this->instruct(20);
}
void CS5490::contConv(){
this->instruct(21);
}
void CS5490::haltConv(){
this->instruct(24);
}
/**************************************************************/
/* PUBLIC METHODS - Calibration and Configuration */
/**************************************************************/
/* SET */
void CS5490::setBaudRate(long value){
//Calculate the correct binary value
uint32_t hexBR = ceil(value*0.5242880/MCLK);
if (hexBR > 65535) hexBR = 65535;
hexBR += 0x020000;
this->write(0x80,0x07,hexBR);
delay(100); //To avoid bugs from ESP32
//Reset Serial communication from controller
cSerial->end();
cSerial->begin(value);
return;
}
/* GET */
int CS5490::getGainI(){
//Page 16, Address 33
this->read(16,33);
return this->toDouble(22,MSBunsigned);
}
long CS5490::getBaudRate(){
this->read(0,7);
uint32_t buffer = this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
buffer -= 0x020000;
return ( (buffer/0.5242880)*MCLK );
}
/**************************************************************/
/* PUBLIC METHODS - Measurements */
/**************************************************************/
double CS5490::getPeakV(){
//Page 0, Address 36
this->read(0,36);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPeakI(){
//Page 0, Address 37
this->read(0,37);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstI(){
//Page 16, Address 2
this->read(16,2);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstV(){
//Page 16, Address 3
this->read(16,3);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstP(){
//Page 16, Address 4
this->read(16,4);
return this->toDouble(23, MSBsigned);
}
double CS5490::getRmsI(){
//Page 16, Address 6
this->read(16,6);
return this->toDouble(24, MSBunsigned);
}
double CS5490::getRmsV(){
//Page 16, Address 7
this->read(16,7);
return this->toDouble(24, MSBunsigned);
}
double CS5490::getAvgP(){
//Page 16, Address 5
this->read(16,5);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgQ(){
//Page 16, Address 14
this->read(16,14);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgS(){
//Page 16, Address 20
this->read(16,20);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstQ(){
//Page 16, Address 15
this->read(16,15);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPF(){
//Page 16, Address 21
this->read(16,21);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalP(){
//Page 16, Address 29
this->read(16,29);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalS(){
//Page 16, Address 30
this->read(16,30);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalQ(){
//Page 16, Address 31
this->read(16,31);
return this->toDouble(23, MSBsigned);
}
double CS5490::getFreq(){
//Page 16, Address 49
this->read(16,49);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTime(){
//Page 16, Address 61
this->read(16,61);
return this->toDouble(0, MSBunsigned);
}
/**************************************************************/
/* PUBLIC METHODS - Read Register */
/**************************************************************/
long CS5490::readReg(int page, int address){
long value = 0;
this->read(page, address);
for(int i=0; i<3; i++){
value += data[2-i];
value <<= 8;
}
return value;
}
| /******************************************
Author: Tiago Britto Lobão
[email protected]
*/
/*
Purpose: Control an integrated circuit
Cirrus Logic - CS5490
Used to measure electrical quantities
MIT License
******************************************/
#include "CS5490.h"
/******* Init CS5490 *******/
//For Arduino & ESP8622
#if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s)
CS5490::CS5490(float mclk, int rx, int tx){
this->MCLK = mclk;
this->cSerial = new SoftwareSerial(rx,tx);
}
//For ESP32 AND MEGA
#else
CS5490::CS5490(float mclk){
this->MCLK = mclk;
this->cSerial = &Serial2;
}
#endif
void CS5490::begin(int baudRate){
cSerial->begin(baudRate);
delay(10); //Avoid Bugs on Arduino UNO
}
/**************************************************************/
/* PRIVATE METHODS */
/**************************************************************/
/******* Write a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::write(int page, int address, long value){
uint8_t checksum = 0;
for(int i=0; i<3; i++)
checksum += 0xFF - checksum;
//Select page and address
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (writeByte | (uint8_t)address);
cSerial->write(buffer);
//Send information
for(int i=0; i<3 ; i++){
data[i] = value & 0x000000FF;
cSerial->write(this->data[i]);
value >>= 8;
}
//Calculate and send checksum
buffer = 0xFF - data[0] - data[1] - data[2];
cSerial->write(buffer);
}
/******* Read a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::read(int page, int address){
cSerial->flush();
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (readByte | (uint8_t)address);
cSerial->write(buffer);
//Wait for 3 bytes to arrive
while(cSerial->available() < 3);
for(int i=0; i<3; i++){
data[i] = cSerial->read();
}
}
/******* Give an instruction by the serial communication *******/
void CS5490::instruct(int value){
cSerial->flush();
uint8_t buffer = (instructionByte | (uint8_t)value);
cSerial->write(buffer);
}
/*
Function: toDouble
Transforms a 24 bit number to a double number for easy processing data
Param:
data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490
LSBpow => Exponent specified from datasheet of the less significant bit
MSBoption => Information of most significant bit case. It can be only three values:
MSBnull (1) The MSB is a Don't Care bit
MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion
MSBunsigned (3) The MSB is a positive value, the default case.
*/
double CS5490::toDouble(int LSBpow, int MSBoption){
uint32_t buffer = 0;
double output = 0.0;
bool MSB;
//Concat bytes in a 32 bit word
buffer += this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
switch(MSBoption){
case MSBnull:
this->data[2] &= ~(1 << 7); //Clear MSB
buffer += this->data[2] << 16;
output = (double)buffer;
output /= pow(2,LSBpow);
break;
case MSBsigned:
MSB = data[2] & 0x80;
if(MSB){ //- (2 complement conversion)
buffer = ~buffer;
//Clearing the first 8 bits
for(int i=24; i<32; i++)
buffer &= ~(1 << i);
output = (double)buffer + 1.0;
output /= -pow(2,LSBpow);
}
else{ //+
output = (double)buffer;
output /= (pow(2,LSBpow)-1.0);
}
break;
default:
case MSBunsigned:
output = (double)buffer;
output /= pow(2,LSBpow);
break;
}
return output;
}
/**************************************************************/
/* PUBLIC METHODS - Instructions */
/**************************************************************/
void CS5490::reset(){
this->instruct(1);
}
void CS5490::standby(){
this->instruct(2);
}
void CS5490::wakeUp(){
this->instruct(3);
}
void CS5490::singConv(){
this->instruct(20);
}
void CS5490::contConv(){
this->instruct(21);
}
void CS5490::haltConv(){
this->instruct(24);
}
/**************************************************************/
/* PUBLIC METHODS - Calibration and Configuration */
/**************************************************************/
/* SET */
void CS5490::setBaudRate(long value){
//Calculate the correct binary value
uint32_t hexBR = ceil(value*0.5242880/MCLK);
if (hexBR > 65535) hexBR = 65535;
hexBR += 0x020000;
this->write(0x80,0x07,hexBR);
delay(100); //To avoid bugs from ESP32
//Reset Serial communication from controller
cSerial->end();
cSerial->begin(value);
return;
}
/* GET */
int CS5490::getGainI(){
//Page 16, Address 33
this->read(16,33);
return this->toDouble(22,MSBunsigned);
}
long CS5490::getBaudRate(){
this->read(0,7);
uint32_t buffer = this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
buffer -= 0x020000;
return ( (buffer/0.5242880)*MCLK );
}
/**************************************************************/
/* PUBLIC METHODS - Measurements */
/**************************************************************/
double CS5490::getPeakV(){
//Page 0, Address 36
this->read(0,36);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPeakI(){
//Page 0, Address 37
this->read(0,37);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstI(){
//Page 16, Address 2
this->read(16,2);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstV(){
//Page 16, Address 3
this->read(16,3);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstP(){
//Page 16, Address 4
this->read(16,4);
return this->toDouble(23, MSBsigned);
}
double CS5490::getRmsI(){
//Page 16, Address 6
this->read(16,6);
return this->toDouble(24, MSBunsigned);
}
double CS5490::getRmsV(){
//Page 16, Address 7
this->read(16,7);
return this->toDouble(24, MSBunsigned);
}
double CS5490::getAvgP(){
//Page 16, Address 5
this->read(16,5);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgQ(){
//Page 16, Address 14
this->read(16,14);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgS(){
//Page 16, Address 20
this->read(16,20);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstQ(){
//Page 16, Address 15
this->read(16,15);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPF(){
//Page 16, Address 21
this->read(16,21);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalP(){
//Page 16, Address 29
this->read(16,29);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalS(){
//Page 16, Address 30
this->read(16,30);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalQ(){
//Page 16, Address 31
this->read(16,31);
return this->toDouble(23, MSBsigned);
}
double CS5490::getFreq(){
//Page 16, Address 49
this->read(16,49);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTime(){
//Page 16, Address 61
this->read(16,61);
return this->toDouble(0, MSBunsigned);
}
/**************************************************************/
/* PUBLIC METHODS - Read Register */
/**************************************************************/
long CS5490::readReg(int page, int address){
long value = 0;
this->read(page, address);
for(int i=0; i<3; i++){
value += data[2-i];
value <<= 8;
}
return value;
}
| Fix Arduino UNO bug | Fix Arduino UNO bug
- .begin method crashes without a small delay
| C++ | mit | tiagolobao/CS5490 |
e34026519d8505e3e6fcd4f5cd1669c52125eb66 | folly/executors/test/GlobalCPUExecutorTest.cpp | folly/executors/test/GlobalCPUExecutorTest.cpp | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <folly/executors/GlobalExecutor.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>
#include <folly/system/HardwareConcurrency.h>
using namespace folly;
DECLARE_uint32(folly_global_cpu_executor_threads);
TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
gflags::FlagSaver flagsaver;
FLAGS_folly_global_cpu_executor_threads = 100;
auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
folly::getGlobalCPUExecutor().get());
EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}
| /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <folly/executors/GlobalExecutor.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>
DECLARE_uint32(folly_global_cpu_executor_threads);
TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
gflags::FlagSaver flagsaver;
FLAGS_folly_global_cpu_executor_threads = 100;
auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
folly::getGlobalCPUExecutor().get());
EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}
| Remove dead includes in folly/executors | Remove dead includes in folly/executors
Reviewed By: Orvid
Differential Revision: D38385209
fbshipit-source-id: 1d962f7b7f21ef7892727ec5d3ed315dfba06951
| C++ | apache-2.0 | facebook/folly,facebook/folly,facebook/folly,facebook/folly,facebook/folly |
a0b4ee4c51af8dfcb1a478c07d5e7f3af5039a18 | src/Crypto.cpp | src/Crypto.cpp |
#include <libclientserver.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
std::string Crypto::SHA1Pass(const std::string pass, const std::string salt)
{
std::stringstream ss;
unsigned char out[20];
int ret = PKCS5_PBKDF2_HMAC_SHA1(pass.c_str(), 0, (unsigned char *) salt.c_str(), salt.size(), 1000, sizeof(out), out);
if (ret != 1)
abort();
for(size_t i=0;i<sizeof(out);i++)
{
char tmp[3];
sprintf(tmp, "%02X", out[i] & 0xFF);
ss << tmp;
}
return ss.str();
}
|
#include <libclientserver.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
std::string Crypto::SHA1Pass(const std::string pass, const std::string salt)
{
std::stringstream ss;
unsigned char out[20];
int ret = PKCS5_PBKDF2_HMAC_SHA1(pass.c_str(), 0, (unsigned char *) salt.c_str(), salt.size(), 1000, sizeof(out), out);
if (ret != 1)
abort();
for(size_t i=0;i<sizeof(out);i++)
{
char tmp[3];
sprintf(tmp, "%02X", out[i] & 0xFF);
ss << tmp;
}
return ss.str();
}
| Trim WhiteSpace | Trim WhiteSpace
| C++ | mit | mistralol/libclientserver,mistralol/libclientserver |
78008ce35332272d05cc573ffdd27e86e2c8a697 | vision/locate_tags.cc | vision/locate_tags.cc | #include <apriltag/apriltag.h>
#include <apriltag/tag36h11.h>
#include <apriltag/tag36artoolkit.h>
#include <curl/curl.h>
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace cv;
using std::vector;
#define TAG_SIZE 6.5f
int main(int argc, char** argv) {
// Display usage
if (argc < 3) {
printf("Usage: %s <basestation url> [cameras...]\n", argv[0]);
return -1;
}
// Parse arguments
CURL *curl;
curl = curl_easy_init();
if (!curl) {
std::cerr << "Failed to initialize curl" << std::endl;
return -1;
}
curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 200L);
vector<VideoCapture> devices;
vector<int> device_ids;
vector<Mat> device_camera_matrix;
vector<Mat> device_dist_coeffs;
vector<Mat> device_transform_matrix;
for (int i = 2; i < argc; i++) {
int id = atoi(argv[i]);
VideoCapture device(id);
if (!device.isOpened()) {
std::cerr << "Failed to open video capture device " << id << std::endl;
continue;
}
std::ifstream fin;
fin.open(argv[i]);
if (fin.fail()) {
std::cerr << "Failed to open file " << argv[i] << std::endl;
continue;
}
Mat camera_matrix, dist_coeffs, transform_matrix;
std::string line;
// TODO Error checking
while (std::getline(fin, line)) {
std::stringstream line_stream(line);
std::string key, equals;
line_stream >> key >> equals;
if (key == "camera_matrix") {
vector<double> data;
for (int i = 0; i < 9; i++) {
double v;
line_stream >> v;
data.push_back(v);
}
camera_matrix = Mat(data, true).reshape(1,3);
}
else if (key == "dist_coeffs") {
vector<double> data;
for (int i = 0; i < 5; i++) {
double v;
line_stream >> v;
data.push_back(v);
}
dist_coeffs = Mat(data, true).reshape(1,1);
}
else if (key == "transform_matrix"){
vector<double> data;
for (int i = 0; i < 16; i++){
double v;
line_stream >> v;
data.push_back(v);
}
transform_matrix = Mat(data, true).reshape(1,4);
}
else {
std::cerr << "Unrecognized key '" << key << "' in file " << argv[i] << std::endl;
}
}
if (camera_matrix.rows != 3 || camera_matrix.cols != 3) {
std::cerr << "Error reading camera_matrix in file " << argv[i] << std::endl;
continue;
}
if (dist_coeffs.rows != 1 || dist_coeffs.cols != 5) {
std::cerr << "Error reading dist_coeffs in file " << argv[i] << std::endl;
continue;
}
if (transform_matrix.rows != 4 || transform_matrix.cols != 4){
std::cerr << "Error reading transform_matrix in file " << argv[i] << std::endl;
continue;
}
device.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
device.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
device.set(CV_CAP_PROP_FPS, 30);
devices.push_back(device);
device_ids.push_back(id);
device_camera_matrix.push_back(camera_matrix);
device_dist_coeffs.push_back(dist_coeffs);
device_transform_matrix.push_back(transform_matrix);
}
// Initialize detector
apriltag_family_t* tf = tag36h11_create();
tf->black_border = 1;
apriltag_detector_t* td = apriltag_detector_create();
apriltag_detector_add_family(td, tf);
td->quad_decimate = 1.0;
td->quad_sigma = 0.0;
td->nthreads = 4;
td->debug = 0;
td->refine_edges = 1;
td->refine_decode = 0;
td->refine_pose = 0;
int key = 0;
Mat frame, gray;
char postDataBuffer[100];
while (key != 27) { // Quit on escape keypress
for (size_t i = 0; i < devices.size(); i++) {
if (!devices[i].isOpened()) {
continue;
}
devices[i] >> frame;
cvtColor(frame, gray, COLOR_BGR2GRAY);
image_u8_t im = {
.width = gray.cols,
.height = gray.rows,
.stride = gray.cols,
.buf = gray.data
};
zarray_t* detections = apriltag_detector_detect(td, &im);
vector<Point2f> img_points(4);
vector<Point3f> obj_points(4);
Mat rvec(3, 1, CV_64FC1);
Mat tvec(3, 1, CV_64FC1);
for (int j = 0; j < zarray_size(detections); j++) {
// Get the ith detection
apriltag_detection_t *det;
zarray_get(detections, j, &det);
// Draw onto the frame
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[1][0], det->p[1][1]),
Scalar(0, 0xff, 0), 2);
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0, 0, 0xff), 2);
line(frame, Point(det->p[1][0], det->p[1][1]),
Point(det->p[2][0], det->p[2][1]),
Scalar(0xff, 0, 0), 2);
line(frame, Point(det->p[2][0], det->p[2][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0xff, 0, 0), 2);
// Compute transformation using PnP
img_points[0] = Point2f(det->p[0][0], det->p[0][1]);
img_points[1] = Point2f(det->p[1][0], det->p[1][1]);
img_points[2] = Point2f(det->p[2][0], det->p[2][1]);
img_points[3] = Point2f(det->p[3][0], det->p[3][1]);
obj_points[0] = Point3f(-TAG_SIZE * 0.5f, -TAG_SIZE * 0.5f, 0.f);
obj_points[1] = Point3f( TAG_SIZE * 0.5f, -TAG_SIZE * 0.5f, 0.f);
obj_points[2] = Point3f( TAG_SIZE * 0.5f, TAG_SIZE * 0.5f, 0.f);
obj_points[3] = Point3f(-TAG_SIZE * 0.5f, TAG_SIZE * 0.5f, 0.f);
solvePnP(obj_points, img_points, device_camera_matrix[i],
device_dist_coeffs[i], rvec, tvec);
Matx33d r;
Rodrigues(rvec,r);
vector<double> data;
data.push_back(r(0,0));
data.push_back(r(0,1));
data.push_back(r(0,2));
data.push_back(tvec.at<double>(0));
data.push_back(r(1,0));
data.push_back(r(1,1));
data.push_back(r(1,2));
data.push_back(tvec.at<double>(1));
data.push_back(r(2,0));
data.push_back(r(2,1));
data.push_back(r(2,2));
data.push_back(tvec.at<double>(2));
data.push_back(0);
data.push_back(0);
data.push_back(0);
data.push_back(1);
Mat tag2cam = Mat(data,true).reshape(1, 4);
vector<double> data2;
data2.push_back(0);
data2.push_back(0);
data2.push_back(0);
data2.push_back(1);
Mat genout = Mat(data2,true).reshape(1, 4);
Mat tag2orig = tag2cam * device_transform_matrix[i];
Mat tagXYZS = tag2orig * genout;
printf("%zu :: %d :: % 3.3f % 3.3f % 3.3f\n",
i, det->id,
tagXYZS.at<double>(0), tagXYZS.at<double>(1), tagXYZS.at<double>(2));
// Send data to basestation
sprintf(postDataBuffer, "{\"id\":%d,\"x\":%f,\"y\":%f,\"z\":%f}",
det->id, tagXYZS.at<double>(0), tagXYZS.at<double>(1), tagXYZS.at<double>(2));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postDataBuffer);
// TODO Check for error response
curl_easy_perform(curl);
}
zarray_destroy(detections);
imshow(std::to_string(i), frame);
}
key = waitKey(16);
}
curl_easy_cleanup(curl);
}
| #include <apriltag/apriltag.h>
#include <apriltag/tag36h11.h>
#include <apriltag/tag36artoolkit.h>
#include <curl/curl.h>
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace cv;
using std::vector;
#define TAG_SIZE 6.5f
int main(int argc, char** argv) {
// Display usage
if (argc < 3) {
printf("Usage: %s <basestation url> [cameras...]\n", argv[0]);
return -1;
}
// Parse arguments
CURL *curl;
curl = curl_easy_init();
if (!curl) {
std::cerr << "Failed to initialize curl" << std::endl;
return -1;
}
curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 200L);
vector<VideoCapture> devices;
vector<int> device_ids;
vector<Mat> device_camera_matrix;
vector<Mat> device_dist_coeffs;
vector<Mat> device_transform_matrix;
for (int i = 2; i < argc; i++) {
int id = atoi(argv[i]);
VideoCapture device(id);
if (!device.isOpened()) {
std::cerr << "Failed to open video capture device " << id << std::endl;
continue;
}
std::ifstream fin;
fin.open(argv[i]);
if (fin.fail()) {
std::cerr << "Failed to open file " << argv[i] << std::endl;
continue;
}
Mat camera_matrix, dist_coeffs, transform_matrix;
std::string line;
// TODO Error checking
while (std::getline(fin, line)) {
std::stringstream line_stream(line);
std::string key, equals;
line_stream >> key >> equals;
if (key == "camera_matrix") {
vector<double> data;
for (int i = 0; i < 9; i++) {
double v;
line_stream >> v;
data.push_back(v);
}
camera_matrix = Mat(data, true).reshape(1,3);
}
else if (key == "dist_coeffs") {
vector<double> data;
for (int i = 0; i < 5; i++) {
double v;
line_stream >> v;
data.push_back(v);
}
dist_coeffs = Mat(data, true).reshape(1,1);
}
else if (key == "transform_matrix"){
vector<double> data;
for (int i = 0; i < 16; i++){
double v;
line_stream >> v;
data.push_back(v);
}
transform_matrix = Mat(data, true).reshape(1,4);
}
else {
std::cerr << "Unrecognized key '" << key << "' in file " << argv[i] << std::endl;
}
}
if (camera_matrix.rows != 3 || camera_matrix.cols != 3) {
std::cerr << "Error reading camera_matrix in file " << argv[i] << std::endl;
continue;
}
if (dist_coeffs.rows != 1 || dist_coeffs.cols != 5) {
std::cerr << "Error reading dist_coeffs in file " << argv[i] << std::endl;
continue;
}
if (transform_matrix.rows != 4 || transform_matrix.cols != 4){
std::cerr << "Error reading transform_matrix in file " << argv[i] << std::endl;
continue;
}
device.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
device.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
device.set(CV_CAP_PROP_FPS, 30);
devices.push_back(device);
device_ids.push_back(id);
device_camera_matrix.push_back(camera_matrix);
device_dist_coeffs.push_back(dist_coeffs);
device_transform_matrix.push_back(transform_matrix);
}
// Initialize detector
apriltag_family_t* tf = tag36h11_create();
tf->black_border = 1;
apriltag_detector_t* td = apriltag_detector_create();
apriltag_detector_add_family(td, tf);
td->quad_decimate = 1.0;
td->quad_sigma = 0.0;
td->nthreads = 4;
td->debug = 0;
td->refine_edges = 1;
td->refine_decode = 0;
td->refine_pose = 0;
int key = 0;
Mat frame, gray;
char postDataBuffer[100];
while (key != 27) { // Quit on escape keypress
for (size_t i = 0; i < devices.size(); i++) {
if (!devices[i].isOpened()) {
continue;
}
devices[i] >> frame;
cvtColor(frame, gray, COLOR_BGR2GRAY);
image_u8_t im = {
.width = gray.cols,
.height = gray.rows,
.stride = gray.cols,
.buf = gray.data
};
zarray_t* detections = apriltag_detector_detect(td, &im);
vector<Point2f> img_points(4);
vector<Point3f> obj_points(4);
Mat rvec(3, 1, CV_64FC1);
Mat tvec(3, 1, CV_64FC1);
for (int j = 0; j < zarray_size(detections); j++) {
// Get the ith detection
apriltag_detection_t *det;
zarray_get(detections, j, &det);
// Draw onto the frame
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[1][0], det->p[1][1]),
Scalar(0, 0xff, 0), 2);
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0, 0, 0xff), 2);
line(frame, Point(det->p[1][0], det->p[1][1]),
Point(det->p[2][0], det->p[2][1]),
Scalar(0xff, 0, 0), 2);
line(frame, Point(det->p[2][0], det->p[2][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0xff, 0, 0), 2);
// Compute transformation using PnP
img_points[0] = Point2f(det->p[0][0], det->p[0][1]);
img_points[1] = Point2f(det->p[1][0], det->p[1][1]);
img_points[2] = Point2f(det->p[2][0], det->p[2][1]);
img_points[3] = Point2f(det->p[3][0], det->p[3][1]);
obj_points[0] = Point3f(-TAG_SIZE * 0.5f, -TAG_SIZE * 0.5f, 0.f);
obj_points[1] = Point3f( TAG_SIZE * 0.5f, -TAG_SIZE * 0.5f, 0.f);
obj_points[2] = Point3f( TAG_SIZE * 0.5f, TAG_SIZE * 0.5f, 0.f);
obj_points[3] = Point3f(-TAG_SIZE * 0.5f, TAG_SIZE * 0.5f, 0.f);
solvePnP(obj_points, img_points, device_camera_matrix[i],
device_dist_coeffs[i], rvec, tvec);
Matx33d r;
Rodrigues(rvec,r);
vector<double> data;
data.push_back(r(0,0));
data.push_back(r(0,1));
data.push_back(r(0,2));
data.push_back(tvec.at<double>(0));
data.push_back(r(1,0));
data.push_back(r(1,1));
data.push_back(r(1,2));
data.push_back(tvec.at<double>(1));
data.push_back(r(2,0));
data.push_back(r(2,1));
data.push_back(r(2,2));
data.push_back(tvec.at<double>(2));
data.push_back(0);
data.push_back(0);
data.push_back(0);
data.push_back(1);
Mat tag2cam = Mat(data,true).reshape(1, 4);
vector<double> data2;
data2.push_back(0);
data2.push_back(0);
data2.push_back(0);
data2.push_back(1);
Mat genout = Mat(data2,true).reshape(1, 4);
Mat tag2orig = device_transform_matrix[i] * tag2cam;
Mat tagXYZS = tag2orig * genout;
printf("%zu :: %d :: % 3.3f % 3.3f % 3.3f\n",
i, det->id,
tagXYZS.at<double>(0), tagXYZS.at<double>(1), tagXYZS.at<double>(2));
// Send data to basestation
sprintf(postDataBuffer, "{\"id\":%d,\"x\":%f,\"y\":%f,\"z\":%f}",
det->id, tagXYZS.at<double>(0), tagXYZS.at<double>(1), tagXYZS.at<double>(2));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postDataBuffer);
// TODO Check for error response
curl_easy_perform(curl);
}
zarray_destroy(detections);
imshow(std::to_string(i), frame);
}
key = waitKey(16);
}
curl_easy_cleanup(curl);
}
| Fix matrix multiplication order | Fix matrix multiplication order
| C++ | apache-2.0 | cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot |
598b58f1d15703292eee5f3e4603f0563eaace73 | src/JToken.cpp | src/JToken.cpp | //
// Created by qife on 16/1/27.
//
#include "JToken.h"
using namespace JsonCpp;
NodePtrList JToken::ParseJPath(const char *str) const
{
str = JsonUtil::SkipWhiteSpace(str);
NodePtrList list;
if (*str == '$')
{
list.push_back(std::shared_ptr<ActionNode>(new ActionNode(ActionType::RootItem)));
++str;
}
else
{
list.push_back(std::shared_ptr<ActionNode>(new ActionNode(ActionType::RootItem)));
if (!ReadNodeByDotRefer(&str, list))
{
goto error;
}
}
while (*str)
{
switch (*str)
{
case '.':
if (*(str + 1) == '.')
{
str = JsonUtil::SkipWhiteSpace(str, 2);
if (!ReadNodeByDotRefer(&str, list, true))
{
goto error;
}
continue;
}
else
{
str = JsonUtil::SkipWhiteSpace(str, 1);
if (!ReadNodeByDotRefer(&str, list))
{
goto error;
}
continue;
}
case '[':
{
str = JsonUtil::SkipWhiteSpace(str, 1);
auto node = std::shared_ptr<ActionNode>(new ActionNode(ActionType::ArrayBySubscript));
node->actionData.subData = new SubscriptData();
auto data = node->actionData.subData;
if (*str == '*')
{
data->filterType = SubscriptData::All;
}
else if (*str == '?')
{
str = JsonUtil::SkipWhiteSpace(str, 1);
if (*str != '(')
{
goto error;
}
str = JsonUtil::SkipWhiteSpace(str, 1);
Expr::BoolOpType opType = Expr::Exist;
const char *start = str;
const char *last = nullptr;
const char *paren = nullptr;
const char *op = nullptr;
while (*str)
{
switch (*str)
{
case '>':
{
if (opType != Expr::Exist)
{
goto error;
}
op = str;
if (*++str == '=')
{
opType = Expr::GreaterEqual;
++str;
}
else
{
opType = Expr::Greater;
}
continue;
}
case '<':
{
if (opType != Expr::Exist)
{
goto error;
}
op = str;
if (*++str == '=')
{
opType = Expr::LessEqual;
++str;
}
else
{
opType = Expr::Less;
}
continue;
}
case '=':
case '!':
{
if (opType != Expr::Exist)
{
goto error;
}
op = str;
if (*(str + 1) != '=')
{
goto error;
}
opType = *str == '=' ? Expr::Equal : Expr::NotEqual;
str += 2;
continue;
}
case ')':
paren = str;
continue;
case ']':
break;
case ' ':
continue;
default:
last = str;
}
if (last >= paren || op > paren || op > last || !last)
{
goto error;
}
break;
}
if (op)
{
std::string leftExpr(start, op - start);
data->filterData.filter = new Expr::BoolExpression(opType, true);
JsonUtil::GetRePolishExpression(leftExpr.c_str(), data->filterData.filter->leftRePolishExpr);
}
}
}
case ' ':
continue;
default:
goto error;
}
}
return list;
error:
list.clear();
return list;
}
| //
// Created by qife on 16/1/27.
//
#include "JToken.h"
using namespace JsonCpp;
JToken::NodePtrList JToken::ParseJPath(const char *str) const
{
str = JsonUtil::SkipWhiteSpace(str);
NodePtrList list;
if (*str == '$')
{
list.push_back(std::shared_ptr<ActionNode>(new ActionNode(ActionType::RootItem)));
// list.push_back(std::make_shared<ActionNode>(ActionType::RootItem)); // Clion bug
++str;
}
else
{
list.push_back(std::shared_ptr<ActionNode>(new ActionNode(ActionType::RootItem)));
if (!ReadNodeByDotRefer(&str, list))
{
goto error;
}
}
while (*str)
{
switch (*str)
{
case '.':
if (*(str + 1) == '.')
{
str = JsonUtil::SkipWhiteSpace(str, 2);
if (!ReadNodeByDotRefer(&str, list, true))
{
goto error;
}
continue;
}
else
{
str = JsonUtil::SkipWhiteSpace(str, 1);
if (!ReadNodeByDotRefer(&str, list))
{
goto error;
}
continue;
}
case '[':
{
str = JsonUtil::SkipWhiteSpace(str, 1);
auto node = std::shared_ptr<ActionNode>(new ActionNode(ActionType::ArrayBySubscript));
node->actionData.subData = new SubscriptData();
auto data = node->actionData.subData;
if (*str == '*')
{
data->filterType = SubscriptData::All;
}
else if (*str == '?')
{
str = JsonUtil::SkipWhiteSpace(str, 1);
if (*str != '(')
{
goto error;
}
str = JsonUtil::SkipWhiteSpace(str, 1);
Expr::BoolOpType opType = Expr::Exist;
const char *start = str;
const char *last = nullptr;
const char *paren = nullptr;
const char *op = nullptr;
while (*str)
{
switch (*str)
{
case '>':
{
if (opType != Expr::Exist)
{
goto error;
}
op = str;
if (*++str == '=')
{
opType = Expr::GreaterEqual;
++str;
}
else
{
opType = Expr::Greater;
}
continue;
}
case '<':
{
if (opType != Expr::Exist)
{
goto error;
}
op = str;
if (*++str == '=')
{
opType = Expr::LessEqual;
++str;
}
else
{
opType = Expr::Less;
}
continue;
}
case '=':
case '!':
{
if (opType != Expr::Exist)
{
goto error;
}
op = str;
if (*(str + 1) != '=')
{
goto error;
}
opType = *str == '=' ? Expr::Equal : Expr::NotEqual;
str += 2;
continue;
}
case ')':
paren = str;
continue;
case ']':
break;
case ' ':
continue;
default:
last = str;
}
break;
}
if (last >= paren || op > paren || op > last || !last || !*str)
{
goto error;
}
data->filterType = SubscriptData::Filter;
if (op)
{
std::string leftExpr(start, op);
data->filterData.filter = new Expr::BoolExpression(opType, true);
if (!JsonUtil::GetRePolishExpression(leftExpr.c_str(),
data->filterData.filter->leftRePolishExpr))
{
goto error;
}
unsigned int i = opType == Expr::Less || opType == Expr::Greater ? 1 : 2;
std::string rightExpr(op + i, last + 1);
if (!JsonUtil::GetRePolishExpression(rightExpr.c_str(),
*data->filterData.filter->rightRePolishExpr))
{
goto error;
}
}
else
{
std::string expr(start, last + 1);
data->filterData.filter = new Expr::BoolExpression(opType);
if (!JsonUtil::GetRePolishExpression(expr.c_str(), data->filterData.filter->leftRePolishExpr))
{
goto error;
}
}
}
else if (*str == '(')
{
str = JsonUtil::SkipWhiteSpace(str, 1);
const char *start = str;
const char *end = nullptr;
const char *paren = nullptr;
while (*str)
{
switch (*str)
{
case '<':
case '>':
case '=':
case '!':
goto error;
case ')':
paren = str;
continue;
case ' ':
continue;
case ']':
break;
default:
end = str;
}
break;
}
if (end >= paren || !end || !*str)
{
goto error;
}
data->filterType = SubscriptData::Script;
data->filterData.script = new std::queue<Expr::ExprNode>();
std::string expr(start, end + 1);
if (!JsonUtil::GetRePolishExpression(expr.c_str(), *data->filterData.script))
{
goto error;
}
}
else
{
char *numEnd = nullptr;
auto num = (int)std::strtol(str, &numEnd, 0);
if (numEnd)
{
str = JsonUtil::SkipWhiteSpace(numEnd);
if (*str == ',' || *str == ']')
{
data->filterType = SubscriptData::ArrayIndices;
data->filterData.indices = new std::vector<int>();
data->filterData.indices->push_back(num);
if (*str == ',')
{
do
{
numEnd = nullptr;
num = (int)std::strtol(str + 1, &numEnd, 0);
if (!numEnd)
{
goto error;
}
data->filterData.indices->push_back(num);
str = JsonUtil::SkipWhiteSpace(numEnd);
} while (*str == ',');
if (*str != ']')
{
goto error;
}
}
++str;
list.push_back(std::move(node));
continue;
}
}
if (*str == ':')
{
data->filterType = SubscriptData::ArraySlice;
data->filterData.slice = new SliceData(num);
str = JsonUtil::SkipWhiteSpace(str, 1);
if (*str == ':')
{
char *stepEnd = nullptr;
str = JsonUtil::SkipWhiteSpace(str, 1);
auto step = std::strtoul(str, &stepEnd, 0);
if (stepEnd)
{
data->filterData.slice->step = (unsigned int)step;
str = JsonUtil::SkipWhiteSpace(stepEnd);
}
}
else
{
char *strEnd = nullptr;
auto end = std::strtol(str, &strEnd, 0);
if (strEnd)
{
data->filterData.slice->end = (int)end;
str = JsonUtil::SkipWhiteSpace(strEnd);
if (*str == ':')
{
strEnd = nullptr;
auto step = std::strtoul(str, &strEnd, 0);
if (strEnd)
{
data->filterData.slice->step = (unsigned int)step;
str = JsonUtil::SkipWhiteSpace(strEnd);
}
}
}
}
if (*str != ']')
{
goto error;
}
}
else
{
goto error;
}
}
++str;
list.push_back(std::move(node));
continue;
}
case ' ':
continue;
default:
goto error;
}
}
return list;
error:
list.clear();
return list;
}
| complete the parser | complete the parser
| C++ | mit | 3meng/JsonCpp |
3f49160c901571add42855f8bbb577b02c77e53f | src/Mirror.cpp | src/Mirror.cpp |
#include "Mirror.hpp"
#include "tcp/Server.hpp"
#include <onions-common/containers/Cache.hpp>
#include <onions-common/Common.hpp>
#include <onions-common/Log.hpp>
#include <onions-common/Config.hpp>
#include <onions-common/Constants.hpp>
#include <botan/pubkey.h>
#include <thread>
#include <fstream>
#include <iostream>
// definitions for static variables
std::vector<boost::shared_ptr<Session>> Mirror::connections_;
boost::shared_ptr<Session> Mirror::authSession_;
std::shared_ptr<boost::asio::io_service> Mirror::authIO_;
void Mirror::startServer(const std::string& host, ushort port, bool isAuthority)
{
loadCache();
if (isAuthority)
Log::get().notice("Running as authoritative server.");
else
Log::get().notice("Running as normal server.");
// auto mt = std::make_shared<MerkleTree>(Cache::get().getSortedList());
try
{
if (!isAuthority)
subscribeToAuthority();
Server s(host, port, isAuthority);
s.start();
}
catch (boost::exception_detail::clone_impl<
boost::exception_detail::error_info_injector<
boost::system::system_error>> const& ex)
{
Log::get().error(ex.what());
}
}
UInt8Array Mirror::signMerkleRoot(Botan::RSA_PrivateKey* key,
const MerkleTreePtr& mt)
{
static Botan::AutoSeeded_RNG rng;
Botan::PK_Signer signer(*key, "EMSA-PSS(SHA-384)");
auto sig = signer.sign_message(mt->getRoot(), Const::SHA384_LEN, rng);
uint8_t* bin = new uint8_t[sig.size()];
memcpy(bin, sig, sig.size());
return std::make_pair(bin, sig.size());
}
void Mirror::addConnection(const boost::shared_ptr<Session>& session)
{
connections_.push_back(session);
}
void Mirror::broadcastEvent(const std::string& type, const Json::Value& value)
{
Json::Value event;
event["type"] = type;
event["value"] = value;
uint n = 0;
for (auto s : connections_)
{
if (s->isSubscriber())
{
s->asyncWrite(event);
n++;
}
}
Log::get().notice("Broadcasted to " + std::to_string(n) + " subscribers.");
}
void Mirror::loadCache()
{
Log::get().notice("Loading Record cache... ");
std::ifstream cacheFile;
cacheFile.open("/var/lib/tor-onions/cache.json", std::fstream::in);
if (!cacheFile.is_open())
Log::get().error("Cannot open cache!");
// parse cache file into JSON object
Json::Value cacheValue;
Json::Reader reader;
std::string json((std::istreambuf_iterator<char>(cacheFile)),
std::istreambuf_iterator<char>());
if (!reader.parse(json, cacheValue))
{
Log::get().error("Failed to parse cache!");
return;
}
// interpret JSON as Records and load into cache
Log::get().notice("Preparing Records... ");
for (uint n = 0; n < cacheValue.size(); n++)
if (!Cache::add(Common::parseRecord(cacheValue[n])))
Log::get().error("Invalid Record inside cache!");
}
void Mirror::subscribeToAuthority()
{
std::thread t(receiveEvents);
t.detach();
}
void Mirror::receiveEvents()
{
auto addr = Config::getAuthority()[0];
authIO_ = std::make_shared<boost::asio::io_service>();
boost::shared_ptr<Session> session(new Session(*authIO_, 0));
authSession_ = session;
Log::get().notice("Connecting to authority server... ");
using boost::asio::ip::tcp;
tcp::resolver resolver(*authIO_);
tcp::resolver::query query(addr["ip"].asString(), addr["port"].asString());
tcp::resolver::iterator iterator = resolver.resolve(query);
boost::asio::connect(authSession_->getSocket(), iterator);
Log::get().notice("Connected! Subscribing to events...");
authSession_->asyncWrite("subscribe", "");
authIO_->run();
}
|
#include "Mirror.hpp"
#include "tcp/Server.hpp"
#include <onions-common/containers/Cache.hpp>
#include <onions-common/Common.hpp>
#include <onions-common/Log.hpp>
#include <onions-common/Config.hpp>
#include <onions-common/Constants.hpp>
#include <botan/pubkey.h>
#include <thread>
#include <fstream>
#include <iostream>
typedef boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error>> BoostSystemError;
// definitions for static variables
std::vector<boost::shared_ptr<Session>> Mirror::connections_;
boost::shared_ptr<Session> Mirror::authSession_;
std::shared_ptr<boost::asio::io_service> Mirror::authIO_;
void Mirror::startServer(const std::string& host, ushort port, bool isAuthority)
{
loadCache();
if (isAuthority)
Log::get().notice("Running as authoritative server.");
else
Log::get().notice("Running as normal server.");
// auto mt = std::make_shared<MerkleTree>(Cache::get().getSortedList());
try
{
if (!isAuthority)
subscribeToAuthority();
Server s(host, port, isAuthority);
s.start();
}
catch (const BoostSystemError& ex)
{
Log::get().error(ex.what());
}
}
UInt8Array Mirror::signMerkleRoot(Botan::RSA_PrivateKey* key,
const MerkleTreePtr& mt)
{
static Botan::AutoSeeded_RNG rng;
Botan::PK_Signer signer(*key, "EMSA-PSS(SHA-384)");
auto sig = signer.sign_message(mt->getRoot(), Const::SHA384_LEN, rng);
uint8_t* bin = new uint8_t[sig.size()];
memcpy(bin, sig, sig.size());
return std::make_pair(bin, sig.size());
}
void Mirror::addConnection(const boost::shared_ptr<Session>& session)
{
connections_.push_back(session);
}
void Mirror::broadcastEvent(const std::string& type, const Json::Value& value)
{
Json::Value event;
event["type"] = type;
event["value"] = value;
uint n = 0;
for (auto s : connections_)
{
if (s->isSubscriber())
{
s->asyncWrite(event);
n++;
}
}
Log::get().notice("Broadcasted to " + std::to_string(n) + " subscribers.");
}
void Mirror::loadCache()
{
Log::get().notice("Loading Record cache... ");
std::ifstream cacheFile;
cacheFile.open("/var/lib/tor-onions/cache.json", std::fstream::in);
if (!cacheFile.is_open())
Log::get().error("Cannot open cache!");
// parse cache file into JSON object
Json::Value cacheValue;
Json::Reader reader;
std::string json((std::istreambuf_iterator<char>(cacheFile)),
std::istreambuf_iterator<char>());
if (!reader.parse(json, cacheValue))
{
Log::get().error("Failed to parse cache!");
return;
}
// interpret JSON as Records and load into cache
Log::get().notice("Preparing Records... ");
for (uint n = 0; n < cacheValue.size(); n++)
if (!Cache::add(Common::parseRecord(cacheValue[n])))
Log::get().error("Invalid Record inside cache!");
}
void Mirror::subscribeToAuthority()
{
std::thread t(receiveEvents);
t.detach();
}
void Mirror::receiveEvents()
{
const static RECONNECT_DELAY = 10;
while (true) // reestablish lost network connection
{
auto addr = Config::getAuthority()[0];
authIO_ = std::make_shared<boost::asio::io_service>();
boost::shared_ptr<Session> session(new Session(*authIO_, 0));
authSession_ = session;
try
{
// https://stackoverflow.com/questions/15687016/ may be useful later
Log::get().notice("Connecting to authority server... ");
using boost::asio::ip::tcp;
tcp::resolver resolver(*authIO_);
tcp::resolver::query query(addr["ip"].asString(),
addr["port"].asString());
tcp::resolver::iterator iterator = resolver.resolve(query);
boost::asio::connect(authSession_->getSocket(), iterator);
}
catch (const BoostSystemError& ex)
{
Log::get().warn("Connection error, " + std::string(ex.what()));
std::this_thread::sleep_for(std::chrono::seconds(RECONNECT_DELAY));
continue;
}
Log::get().notice("Connected! Subscribing to events...");
authSession_->asyncWrite("subscribe", "");
authIO_->run();
Log::get().warn("Lost connection to authority server.");
std::this_thread::sleep_for(std::chrono::seconds(RECONNECT_DELAY));
}
}
| Fix #66 | Fix #66
This fix reestablishes the connection with the Quorum node if the
connection is lost. I have also introduced a 10-second delay between
reconnect attempts, so as to not overwhelm the Quorum server.
| C++ | bsd-3-clause | Jesse-V/OnioNS-server,Jesse-V/OnioNS-server |
375ef02236b1b2a3b3487f4270bdc46d6b3fb8ef | matrix/test/test-block_mv.cpp | matrix/test/test-block_mv.cpp | #ifdef PROFILER
#include <google/profiler.h>
#endif
#include "eigensolver/block_dense_matrix.h"
using namespace fm;
size_t long_dim = 60 * 1024 * 1024;
size_t repeats = 1;
void test_gemm(eigen::block_multi_vector::ptr mv)
{
bool in_mem = mv->get_block(0)->is_in_mem();
int num_nodes = mv->get_block(0)->get_data().get_num_nodes();
dense_matrix::ptr mat = dense_matrix::create_randu<double>(0, 1,
mv->get_num_cols(), mv->get_block_size(),
matrix_layout_t::L_COL, -1, true);
detail::mem_col_matrix_store::const_ptr B
= detail::mem_col_matrix_store::cast(mat->get_raw_store());
scalar_variable_impl<double> alpha(2);
scalar_variable_impl<double> beta(0);
struct timeval start, end;
#if 0
eigen::block_multi_vector::ptr res0 = eigen::block_multi_vector::create(
long_dim, mv->get_block_size(), mv->get_block_size(),
get_scalar_type<double>(), true);
res0->set_block(0, dense_matrix::create_const<double>(0, long_dim,
mv->get_block_size(), matrix_layout_t::L_COL, num_nodes, in_mem));
res0->set_multiply_blocks(1);
gettimeofday(&start, NULL);
res0 = res0->gemm(*mv, B, alpha, beta);
assert(res0->get_num_blocks() == 1);
dense_matrix::ptr res_mat0 = res0->get_block(0);
res_mat0->materialize_self();
gettimeofday(&end, NULL);
printf("agg materialization takes %.3f seconds\n", time_diff(start, end));
#endif
for (size_t i = 0; i < repeats; i++) {
eigen::block_multi_vector::ptr res1 = eigen::block_multi_vector::create(
long_dim, mv->get_block_size(), mv->get_block_size(),
get_scalar_type<double>(), true);
res1->set_block(0, dense_matrix::create_const<double>(0, long_dim,
mv->get_block_size(), matrix_layout_t::L_COL, num_nodes, in_mem));
res1->set_multiply_blocks(4);
gettimeofday(&start, NULL);
res1 = res1->gemm(*mv, B, alpha, beta);
assert(res1->get_num_blocks() == 1);
dense_matrix::ptr res_mat1 = res1->get_block(0);
res_mat1->materialize_self();
gettimeofday(&end, NULL);
printf("hierarchical materialization takes %.3f seconds\n",
time_diff(start, end));
}
for (size_t i = 0; i < repeats; i++) {
eigen::block_multi_vector::ptr res2 = eigen::block_multi_vector::create(
long_dim, mv->get_block_size(), mv->get_block_size(),
get_scalar_type<double>(), true);
res2->set_block(0, dense_matrix::create_const<double>(0, long_dim,
mv->get_block_size(), matrix_layout_t::L_COL, num_nodes, in_mem));
res2->set_multiply_blocks(mv->get_num_blocks());
gettimeofday(&start, NULL);
res2 = res2->gemm(*mv, B, alpha, beta);
assert(res2->get_num_blocks() == 1);
dense_matrix::ptr res_mat2 = res2->get_block(0);
res_mat2->materialize_self();
gettimeofday(&end, NULL);
printf("flat materialization takes %.3f seconds\n", time_diff(start, end));
}
#if 0
dense_matrix::ptr diff = res_mat1->minus(*res_mat2);
scalar_variable::ptr max_diff = diff->abs()->max();
scalar_variable::ptr max1 = res_mat1->max();
scalar_variable::ptr max2 = res_mat2->max();
printf("max diff: %g, max mat1: %g, max mat2: %g\n",
*(double *) max_diff->get_raw(), *(double *) max1->get_raw(),
*(double *) max2->get_raw());
#endif
}
void test_gemm(bool in_mem, size_t block_size, size_t min_num_blocks,
size_t max_num_blocks, size_t num_cached_blocks)
{
std::vector<dense_matrix::ptr> mats(max_num_blocks);
for (size_t i = 0; i < mats.size(); i++) {
if (i < num_cached_blocks)
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), true);
else
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), in_mem);
}
for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks;
num_blocks *= 2) {
eigen::block_multi_vector::ptr mv = eigen::block_multi_vector::create(
long_dim, num_blocks * block_size, block_size,
get_scalar_type<double>(), in_mem);
printf("gemm on block multi-vector (block size: %ld, #blocks: %ld)\n",
mv->get_block_size(), mv->get_num_blocks());
for (size_t i = 0; i < mv->get_num_blocks(); i++)
mv->set_block(i, mats[i]);
test_gemm(mv);
}
}
void test_MvTransMv(eigen::block_multi_vector::ptr mv1,
eigen::block_multi_vector::ptr mv2)
{
struct timeval start, end;
#if 0
mv1->set_multiply_blocks(1);
gettimeofday(&start, NULL);
fm::dense_matrix::ptr res1 = mv1->MvTransMv(*mv2);
gettimeofday(&end, NULL);
printf("MvTransMv (1 block) takes %.3f seconds\n", time_diff(start, end));
#endif
mv1->set_multiply_blocks(4);
#ifdef PROFILER
ProfilerStart("MvTransMv.4B.prof");
#endif
for (size_t i = 0; i < repeats; i++) {
gettimeofday(&start, NULL);
fm::dense_matrix::ptr res2 = mv1->MvTransMv(*mv2);
gettimeofday(&end, NULL);
printf("MvTransMv (4 blocks) takes %.3f seconds\n", time_diff(start, end));
}
#ifdef PROFILER
ProfilerStop();
#endif
mv1->set_multiply_blocks(mv1->get_num_blocks());
#ifdef PROFILER
ProfilerStart("MvTransMv.all.prof");
#endif
for (size_t i = 0; i < repeats; i++) {
gettimeofday(&start, NULL);
fm::dense_matrix::ptr res3 = mv1->MvTransMv(*mv2);
gettimeofday(&end, NULL);
printf("MvTransMv (all blocks) takes %.3f seconds\n", time_diff(start, end));
}
#ifdef PROFILER
ProfilerStop();
#endif
#if 0
dense_matrix::ptr diff = res2->minus(*res3);
scalar_variable::ptr max_diff = diff->abs()->max();
scalar_variable::ptr max1 = res2->max();
scalar_variable::ptr max2 = res3->max();
printf("max diff: %g, max mat1: %g, max mat2: %g\n",
*(double *) max_diff->get_raw(), *(double *) max1->get_raw(),
*(double *) max2->get_raw());
#endif
}
void test_MvTransMv(bool in_mem, size_t block_size,
size_t min_num_blocks, size_t max_num_blocks, size_t num_cached_blocks)
{
std::vector<dense_matrix::ptr> mats(max_num_blocks);
for (size_t i = 0; i < mats.size(); i++) {
if (i < num_cached_blocks)
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), true);
else
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), in_mem);
}
eigen::block_multi_vector::ptr mv2 = eigen::block_multi_vector::create(
long_dim, block_size, block_size, get_scalar_type<double>(), in_mem);
mv2->set_block(0, dense_matrix::create_randu<double>(0, 1, long_dim,
mv2->get_block_size(), matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), in_mem));
for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks;
num_blocks *= 2) {
eigen::block_multi_vector::ptr mv1 = eigen::block_multi_vector::create(
long_dim, num_blocks * block_size, block_size,
get_scalar_type<double>(), in_mem);
for (size_t i = 0; i < mv1->get_num_blocks(); i++)
mv1->set_block(i, mats[i]);
printf("MvTransMv on block MV (block size: %ld, #blocks: %ld)\n",
block_size, mv1->get_num_blocks());
test_MvTransMv(mv1, mv2);
}
}
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "test conf_file\n");
exit(1);
}
std::string conf_file = argv[1];
config_map::ptr configs = config_map::create(conf_file);
init_flash_matrix(configs);
test_gemm(true, 4, 1, 128, 0);
test_gemm(true, 64, 1, 8, 0);
test_MvTransMv(true, 4, 128, 128, 0);
test_MvTransMv(true, 64, 1, 8, 0);
test_gemm(false, 4, 8, 128, 4);
test_gemm(false, 64, 1, 8, 0);
test_MvTransMv(false, 4, 8, 128, 4);
test_MvTransMv(false, 64, 1, 8, 0);
destroy_flash_matrix();
}
| #ifdef PROFILER
#include <google/profiler.h>
#endif
#include "eigensolver/block_dense_matrix.h"
using namespace fm;
size_t long_dim = 60 * 1024 * 1024;
size_t repeats = 1;
void test_gemm(eigen::block_multi_vector::ptr mv)
{
bool in_mem = mv->get_block(0)->is_in_mem();
int num_nodes = mv->get_block(0)->get_data().get_num_nodes();
dense_matrix::ptr mat = dense_matrix::create_randu<double>(0, 1,
mv->get_num_cols(), mv->get_block_size(),
matrix_layout_t::L_COL, -1, true);
detail::mem_col_matrix_store::const_ptr B
= detail::mem_col_matrix_store::cast(mat->get_raw_store());
scalar_variable_impl<double> alpha(2);
scalar_variable_impl<double> beta(0);
struct timeval start, end;
#if 0
eigen::block_multi_vector::ptr res0 = eigen::block_multi_vector::create(
long_dim, mv->get_block_size(), mv->get_block_size(),
get_scalar_type<double>(), true);
res0->set_block(0, dense_matrix::create_const<double>(0, long_dim,
mv->get_block_size(), matrix_layout_t::L_COL, num_nodes, in_mem));
res0->set_multiply_blocks(1);
gettimeofday(&start, NULL);
res0 = res0->gemm(*mv, B, alpha, beta);
assert(res0->get_num_blocks() == 1);
dense_matrix::ptr res_mat0 = res0->get_block(0);
res_mat0->materialize_self();
gettimeofday(&end, NULL);
printf("agg materialization takes %.3f seconds\n", time_diff(start, end));
#endif
for (size_t i = 0; i < repeats; i++) {
eigen::block_multi_vector::ptr res1 = eigen::block_multi_vector::create(
long_dim, mv->get_block_size(), mv->get_block_size(),
get_scalar_type<double>(), true);
res1->set_block(0, dense_matrix::create_const<double>(0, long_dim,
mv->get_block_size(), matrix_layout_t::L_COL, num_nodes, in_mem));
res1->set_multiply_blocks(4);
gettimeofday(&start, NULL);
res1 = res1->gemm(*mv, B, alpha, beta);
assert(res1->get_num_blocks() == 1);
dense_matrix::ptr res_mat1 = res1->get_block(0);
res_mat1->materialize_self();
gettimeofday(&end, NULL);
printf("hierarchical materialization takes %.3f seconds\n",
time_diff(start, end));
}
for (size_t i = 0; i < repeats; i++) {
eigen::block_multi_vector::ptr res2 = eigen::block_multi_vector::create(
long_dim, mv->get_block_size(), mv->get_block_size(),
get_scalar_type<double>(), true);
res2->set_block(0, dense_matrix::create_const<double>(0, long_dim,
mv->get_block_size(), matrix_layout_t::L_COL, num_nodes, in_mem));
res2->set_multiply_blocks(mv->get_num_blocks());
gettimeofday(&start, NULL);
res2 = res2->gemm(*mv, B, alpha, beta);
assert(res2->get_num_blocks() == 1);
dense_matrix::ptr res_mat2 = res2->get_block(0);
res_mat2->materialize_self();
gettimeofday(&end, NULL);
printf("flat materialization takes %.3f seconds\n", time_diff(start, end));
}
#if 0
dense_matrix::ptr diff = res_mat1->minus(*res_mat2);
scalar_variable::ptr max_diff = diff->abs()->max();
scalar_variable::ptr max1 = res_mat1->max();
scalar_variable::ptr max2 = res_mat2->max();
printf("max diff: %g, max mat1: %g, max mat2: %g\n",
*(double *) max_diff->get_raw(), *(double *) max1->get_raw(),
*(double *) max2->get_raw());
#endif
}
void test_gemm(bool in_mem, size_t block_size, size_t min_num_blocks,
size_t max_num_blocks, size_t num_cached_blocks)
{
std::vector<dense_matrix::ptr> mats(max_num_blocks);
for (size_t i = 0; i < mats.size(); i++) {
if (i < num_cached_blocks)
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), true);
else
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), in_mem);
}
for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks;
num_blocks *= 2) {
eigen::block_multi_vector::ptr mv = eigen::block_multi_vector::create(
long_dim, num_blocks * block_size, block_size,
get_scalar_type<double>(), in_mem);
printf("gemm on block multi-vector (block size: %ld, #blocks: %ld)\n",
mv->get_block_size(), mv->get_num_blocks());
for (size_t i = 0; i < mv->get_num_blocks(); i++)
mv->set_block(i, mats[i]);
test_gemm(mv);
}
}
void test_MvTransMv(eigen::block_multi_vector::ptr mv1,
eigen::block_multi_vector::ptr mv2)
{
struct timeval start, end;
#if 0
mv1->set_multiply_blocks(1);
gettimeofday(&start, NULL);
fm::dense_matrix::ptr res1 = mv1->MvTransMv(*mv2);
gettimeofday(&end, NULL);
printf("MvTransMv (1 block) takes %.3f seconds\n", time_diff(start, end));
#endif
mv1->set_multiply_blocks(4);
#ifdef PROFILER
ProfilerStart("MvTransMv.4B.prof");
#endif
for (size_t i = 0; i < repeats; i++) {
gettimeofday(&start, NULL);
fm::dense_matrix::ptr res2 = mv1->MvTransMv(*mv2);
gettimeofday(&end, NULL);
printf("MvTransMv (4 blocks) takes %.3f seconds\n", time_diff(start, end));
}
#ifdef PROFILER
ProfilerStop();
#endif
mv1->set_multiply_blocks(mv1->get_num_blocks());
#ifdef PROFILER
ProfilerStart("MvTransMv.all.prof");
#endif
for (size_t i = 0; i < repeats; i++) {
gettimeofday(&start, NULL);
fm::dense_matrix::ptr res3 = mv1->MvTransMv(*mv2);
gettimeofday(&end, NULL);
printf("MvTransMv (all blocks) takes %.3f seconds\n", time_diff(start, end));
}
#ifdef PROFILER
ProfilerStop();
#endif
#if 0
dense_matrix::ptr diff = res2->minus(*res3);
scalar_variable::ptr max_diff = diff->abs()->max();
scalar_variable::ptr max1 = res2->max();
scalar_variable::ptr max2 = res3->max();
printf("max diff: %g, max mat1: %g, max mat2: %g\n",
*(double *) max_diff->get_raw(), *(double *) max1->get_raw(),
*(double *) max2->get_raw());
#endif
}
void test_MvTransMv(bool in_mem, size_t block_size,
size_t min_num_blocks, size_t max_num_blocks, size_t num_cached_blocks)
{
std::vector<dense_matrix::ptr> mats(max_num_blocks);
for (size_t i = 0; i < mats.size(); i++) {
if (i < num_cached_blocks)
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), true);
else
mats[i] = dense_matrix::create_randu<double>(0, 1, long_dim,
block_size, matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), in_mem);
}
eigen::block_multi_vector::ptr mv2 = eigen::block_multi_vector::create(
long_dim, block_size, block_size, get_scalar_type<double>(), in_mem);
mv2->set_block(0, dense_matrix::create_randu<double>(0, 1, long_dim,
mv2->get_block_size(), matrix_layout_t::L_COL,
matrix_conf.get_num_nodes(), in_mem));
for (size_t num_blocks = min_num_blocks; num_blocks <= max_num_blocks;
num_blocks *= 2) {
eigen::block_multi_vector::ptr mv1 = eigen::block_multi_vector::create(
long_dim, num_blocks * block_size, block_size,
get_scalar_type<double>(), in_mem);
for (size_t i = 0; i < mv1->get_num_blocks(); i++)
mv1->set_block(i, mats[i]);
printf("MvTransMv on block MV (block size: %ld, #blocks: %ld)\n",
block_size, mv1->get_num_blocks());
test_MvTransMv(mv1, mv2);
}
}
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "test conf_file\n");
exit(1);
}
std::string conf_file = argv[1];
config_map::ptr configs = config_map::create(conf_file);
init_flash_matrix(configs);
test_gemm(true, 4, 1, 128, 0);
test_gemm(true, 64, 1, 8, 0);
test_MvTransMv(true, 4, 1, 128, 0);
test_MvTransMv(true, 64, 1, 8, 0);
test_gemm(false, 4, 8, 128, 4);
test_gemm(false, 64, 1, 8, 0);
test_MvTransMv(false, 4, 8, 128, 4);
test_MvTransMv(false, 64, 1, 8, 0);
destroy_flash_matrix();
}
| fix a minor bug in block MV test. | [Matrix]: fix a minor bug in block MV test.
| C++ | apache-2.0 | icoming/FlashGraph,flashxio/FlashX,icoming/FlashX,icoming/FlashGraph,flashxio/FlashX,zheng-da/FlashX,icoming/FlashX,flashxio/FlashX,icoming/FlashGraph,flashxio/FlashX,zheng-da/FlashX,zheng-da/FlashX,zheng-da/FlashX,icoming/FlashGraph,zheng-da/FlashX,flashxio/FlashX,icoming/FlashGraph,icoming/FlashX,icoming/FlashX,flashxio/FlashX,icoming/FlashX |
6b7dba68fb035e17fab23fabe3d88faea1ded215 | kernel/osl/osl_closures.cpp | kernel/osl/osl_closures.cpp | /*
* Adapted from Open Shading Language with this license:
*
* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
* All Rights Reserved.
*
* Modifications Copyright 2011, Blender Foundation.
*
* 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 Sony Pictures Imageworks 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 <OSL/genclosure.h>
#include <OSL/oslclosure.h>
#include "osl_closures.h"
#include "osl_shader.h"
#include "util_debug.h"
#include "util_math.h"
#include "util_param.h"
#include "kernel_types.h"
#include "kernel_montecarlo.h"
#include "closure/bsdf_util.h"
#include "closure/bsdf_ashikhmin_velvet.h"
#include "closure/bsdf_diffuse.h"
#include "closure/bsdf_microfacet.h"
#include "closure/bsdf_oren_nayar.h"
#include "closure/bsdf_reflection.h"
#include "closure/bsdf_refraction.h"
#include "closure/bsdf_transparent.h"
#include "closure/bsdf_ward.h"
#include "closure/bsdf_westin.h"
CCL_NAMESPACE_BEGIN
using namespace OSL;
/* BSDF class definitions */
BSDF_CLOSURE_CLASS_BEGIN(Diffuse, diffuse, diffuse, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(DiffuseClosure, sc.N),
BSDF_CLOSURE_CLASS_END(Diffuse, diffuse)
BSDF_CLOSURE_CLASS_BEGIN(Translucent, translucent, translucent, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(TranslucentClosure, sc.N),
BSDF_CLOSURE_CLASS_END(Translucent, translucent)
BSDF_CLOSURE_CLASS_BEGIN(OrenNayar, oren_nayar, oren_nayar, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(OrenNayarClosure, sc.N),
CLOSURE_FLOAT_PARAM(OrenNayarClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(OrenNayar, oren_nayar)
BSDF_CLOSURE_CLASS_BEGIN(Reflection, reflection, reflection, LABEL_SINGULAR)
CLOSURE_FLOAT3_PARAM(ReflectionClosure, sc.N),
BSDF_CLOSURE_CLASS_END(Reflection, reflection)
BSDF_CLOSURE_CLASS_BEGIN(Refraction, refraction, refraction, LABEL_SINGULAR)
CLOSURE_FLOAT3_PARAM(RefractionClosure, sc.N),
CLOSURE_FLOAT_PARAM(RefractionClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(Refraction, refraction)
BSDF_CLOSURE_CLASS_BEGIN(WestinBackscatter, westin_backscatter, westin_backscatter, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(WestinBackscatterClosure, sc.N),
CLOSURE_FLOAT_PARAM(WestinBackscatterClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(WestinBackscatter, westin_backscatter)
BSDF_CLOSURE_CLASS_BEGIN(WestinSheen, westin_sheen, westin_sheen, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(WestinSheenClosure, sc.N),
CLOSURE_FLOAT_PARAM(WestinSheenClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(WestinSheen, westin_sheen)
BSDF_CLOSURE_CLASS_BEGIN(Transparent, transparent, transparent, LABEL_SINGULAR)
BSDF_CLOSURE_CLASS_END(Transparent, transparent)
BSDF_CLOSURE_CLASS_BEGIN(AshikhminVelvet, ashikhmin_velvet, ashikhmin_velvet, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(AshikhminVelvetClosure, sc.N),
CLOSURE_FLOAT_PARAM(AshikhminVelvetClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(AshikhminVelvet, ashikhmin_velvet)
BSDF_CLOSURE_CLASS_BEGIN(Ward, ward, ward, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(WardClosure, sc.N),
CLOSURE_FLOAT3_PARAM(WardClosure, sc.T),
CLOSURE_FLOAT_PARAM(WardClosure, sc.data0),
CLOSURE_FLOAT_PARAM(WardClosure, sc.data1),
BSDF_CLOSURE_CLASS_END(Ward, ward)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetGGX, microfacet_ggx, microfacet_ggx, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetGGXClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetGGXClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(MicrofacetGGX, microfacet_ggx)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetBeckmann, microfacet_beckmann, microfacet_beckmann, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetBeckmannClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetBeckmannClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(MicrofacetBeckmann, microfacet_beckmann)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetGGXRefraction, microfacet_ggx_refraction, microfacet_ggx, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetGGXRefractionClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetGGXRefractionClosure, sc.data0),
CLOSURE_FLOAT_PARAM(MicrofacetGGXRefractionClosure, sc.data1),
BSDF_CLOSURE_CLASS_END(MicrofacetGGXRefraction, microfacet_ggx_refraction)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetBeckmannRefraction, microfacet_beckmann_refraction, microfacet_beckmann, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetBeckmannRefractionClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetBeckmannRefractionClosure, sc.data0),
CLOSURE_FLOAT_PARAM(MicrofacetBeckmannRefractionClosure, sc.data1),
BSDF_CLOSURE_CLASS_END(MicrofacetBeckmannRefraction, microfacet_beckmann_refraction)
/* Registration */
static void generic_closure_setup(OSL::RendererServices *, int id, void *data)
{
assert(data);
OSL::ClosurePrimitive *prim = (OSL::ClosurePrimitive *)data;
prim->setup();
}
static bool generic_closure_compare(int id, const void *dataA, const void *dataB)
{
assert(dataA && dataB);
OSL::ClosurePrimitive *primA = (OSL::ClosurePrimitive *)dataA;
OSL::ClosurePrimitive *primB = (OSL::ClosurePrimitive *)dataB;
return primA->mergeable(primB);
}
static void register_closure(OSL::ShadingSystem *ss, const char *name, int id, OSL::ClosureParam *params, OSL::PrepareClosureFunc prepare)
{
ss->register_closure(name, id, params, prepare, generic_closure_setup, generic_closure_compare);
}
void OSLShader::register_closures(OSLShadingSystem *ss_)
{
OSL::ShadingSystem *ss = (OSL::ShadingSystem*)ss_;
int id = 0;
register_closure(ss, "diffuse", id++,
bsdf_diffuse_params(), bsdf_diffuse_prepare);
register_closure(ss, "oren_nayar", id++,
bsdf_oren_nayar_params(), bsdf_oren_nayar_prepare);
register_closure(ss, "translucent", id++,
bsdf_translucent_params(), bsdf_translucent_prepare);
register_closure(ss, "reflection", id++,
bsdf_reflection_params(), bsdf_reflection_prepare);
register_closure(ss, "refraction", id++,
bsdf_refraction_params(), bsdf_refraction_prepare);
register_closure(ss, "transparent", id++,
bsdf_transparent_params(), bsdf_transparent_prepare);
register_closure(ss, "microfacet_ggx", id++,
bsdf_microfacet_ggx_params(), bsdf_microfacet_ggx_prepare);
register_closure(ss, "microfacet_ggx_refraction", id++,
bsdf_microfacet_ggx_refraction_params(), bsdf_microfacet_ggx_refraction_prepare);
register_closure(ss, "microfacet_beckmann", id++,
bsdf_microfacet_beckmann_params(), bsdf_microfacet_beckmann_prepare);
register_closure(ss, "microfacet_beckmann_refraction", id++,
bsdf_microfacet_beckmann_refraction_params(), bsdf_microfacet_beckmann_refraction_prepare);
register_closure(ss, "ward", id++,
bsdf_ward_params(), bsdf_ward_prepare);
register_closure(ss, "ashikhmin_velvet", id++,
bsdf_ashikhmin_velvet_params(), bsdf_ashikhmin_velvet_prepare);
register_closure(ss, "emission", id++,
closure_emission_params(), closure_emission_prepare);
register_closure(ss, "background", id++,
closure_background_params(), closure_background_prepare);
register_closure(ss, "holdout", id++,
closure_holdout_params(), closure_holdout_prepare);
register_closure(ss, "ambient_occlusion", id++,
closure_ambient_occlusion_params(), closure_ambient_occlusion_prepare);
register_closure(ss, "diffuse_ramp", id++,
closure_bsdf_diffuse_ramp_params(), closure_bsdf_diffuse_ramp_prepare);
register_closure(ss, "phong_ramp", id++,
closure_bsdf_phong_ramp_params(), closure_bsdf_phong_ramp_prepare);
register_closure(ss, "diffuse_toon", id++,
closure_bsdf_diffuse_toon_params(), closure_bsdf_diffuse_toon_prepare);
register_closure(ss, "specular_toon", id++,
closure_bsdf_specular_toon_params(), closure_bsdf_specular_toon_prepare);
register_closure(ss, "westin_backscatter", id++,
closure_westin_backscatter_params(), closure_westin_backscatter_prepare);
register_closure(ss, "westin_sheen", id++,
closure_westin_sheen_params(), closure_westin_sheen_prepare);
register_closure(ss, "bssrdf_cubic", id++,
closure_bssrdf_params(), closure_bssrdf_prepare);
}
CCL_NAMESPACE_END
| /*
* Adapted from Open Shading Language with this license:
*
* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
* All Rights Reserved.
*
* Modifications Copyright 2011, Blender Foundation.
*
* 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 Sony Pictures Imageworks 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 <OSL/genclosure.h>
#include <OSL/oslclosure.h>
#include "osl_closures.h"
#include "osl_shader.h"
#include "util_debug.h"
#include "util_math.h"
#include "util_param.h"
#include "kernel_types.h"
#include "kernel_montecarlo.h"
#include "closure/bsdf_util.h"
#include "closure/bsdf_ashikhmin_velvet.h"
#include "closure/bsdf_diffuse.h"
#include "closure/bsdf_microfacet.h"
#include "closure/bsdf_oren_nayar.h"
#include "closure/bsdf_reflection.h"
#include "closure/bsdf_refraction.h"
#include "closure/bsdf_transparent.h"
#include "closure/bsdf_ward.h"
#include "closure/bsdf_westin.h"
CCL_NAMESPACE_BEGIN
using namespace OSL;
/* BSDF class definitions */
BSDF_CLOSURE_CLASS_BEGIN(Diffuse, diffuse, diffuse, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(DiffuseClosure, sc.N),
BSDF_CLOSURE_CLASS_END(Diffuse, diffuse)
BSDF_CLOSURE_CLASS_BEGIN(Translucent, translucent, translucent, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(TranslucentClosure, sc.N),
BSDF_CLOSURE_CLASS_END(Translucent, translucent)
BSDF_CLOSURE_CLASS_BEGIN(OrenNayar, oren_nayar, oren_nayar, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(OrenNayarClosure, sc.N),
CLOSURE_FLOAT_PARAM(OrenNayarClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(OrenNayar, oren_nayar)
BSDF_CLOSURE_CLASS_BEGIN(Reflection, reflection, reflection, LABEL_SINGULAR)
CLOSURE_FLOAT3_PARAM(ReflectionClosure, sc.N),
BSDF_CLOSURE_CLASS_END(Reflection, reflection)
BSDF_CLOSURE_CLASS_BEGIN(Refraction, refraction, refraction, LABEL_SINGULAR)
CLOSURE_FLOAT3_PARAM(RefractionClosure, sc.N),
CLOSURE_FLOAT_PARAM(RefractionClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(Refraction, refraction)
BSDF_CLOSURE_CLASS_BEGIN(WestinBackscatter, westin_backscatter, westin_backscatter, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(WestinBackscatterClosure, sc.N),
CLOSURE_FLOAT_PARAM(WestinBackscatterClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(WestinBackscatter, westin_backscatter)
BSDF_CLOSURE_CLASS_BEGIN(WestinSheen, westin_sheen, westin_sheen, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(WestinSheenClosure, sc.N),
CLOSURE_FLOAT_PARAM(WestinSheenClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(WestinSheen, westin_sheen)
BSDF_CLOSURE_CLASS_BEGIN(Transparent, transparent, transparent, LABEL_SINGULAR)
BSDF_CLOSURE_CLASS_END(Transparent, transparent)
BSDF_CLOSURE_CLASS_BEGIN(AshikhminVelvet, ashikhmin_velvet, ashikhmin_velvet, LABEL_DIFFUSE)
CLOSURE_FLOAT3_PARAM(AshikhminVelvetClosure, sc.N),
CLOSURE_FLOAT_PARAM(AshikhminVelvetClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(AshikhminVelvet, ashikhmin_velvet)
BSDF_CLOSURE_CLASS_BEGIN(Ward, ward, ward, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(WardClosure, sc.N),
CLOSURE_FLOAT3_PARAM(WardClosure, sc.T),
CLOSURE_FLOAT_PARAM(WardClosure, sc.data0),
CLOSURE_FLOAT_PARAM(WardClosure, sc.data1),
BSDF_CLOSURE_CLASS_END(Ward, ward)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetGGX, microfacet_ggx, microfacet_ggx, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetGGXClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetGGXClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(MicrofacetGGX, microfacet_ggx)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetBeckmann, microfacet_beckmann, microfacet_beckmann, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetBeckmannClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetBeckmannClosure, sc.data0),
BSDF_CLOSURE_CLASS_END(MicrofacetBeckmann, microfacet_beckmann)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetGGXRefraction, microfacet_ggx_refraction, microfacet_ggx, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetGGXRefractionClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetGGXRefractionClosure, sc.data0),
CLOSURE_FLOAT_PARAM(MicrofacetGGXRefractionClosure, sc.data1),
BSDF_CLOSURE_CLASS_END(MicrofacetGGXRefraction, microfacet_ggx_refraction)
BSDF_CLOSURE_CLASS_BEGIN(MicrofacetBeckmannRefraction, microfacet_beckmann_refraction, microfacet_beckmann, LABEL_GLOSSY)
CLOSURE_FLOAT3_PARAM(MicrofacetBeckmannRefractionClosure, sc.N),
CLOSURE_FLOAT_PARAM(MicrofacetBeckmannRefractionClosure, sc.data0),
CLOSURE_FLOAT_PARAM(MicrofacetBeckmannRefractionClosure, sc.data1),
BSDF_CLOSURE_CLASS_END(MicrofacetBeckmannRefraction, microfacet_beckmann_refraction)
/* Registration */
static void generic_closure_setup(OSL::RendererServices *, int id, void *data)
{
assert(data);
OSL::ClosurePrimitive *prim = (OSL::ClosurePrimitive *)data;
prim->setup();
}
static bool generic_closure_compare(int id, const void *dataA, const void *dataB)
{
assert(dataA && dataB);
OSL::ClosurePrimitive *primA = (OSL::ClosurePrimitive *)dataA;
OSL::ClosurePrimitive *primB = (OSL::ClosurePrimitive *)dataB;
return primA->mergeable(primB);
}
static void register_closure(OSL::ShadingSystem *ss, const char *name, int id, OSL::ClosureParam *params, OSL::PrepareClosureFunc prepare)
{
ss->register_closure(name, id, params, prepare, generic_closure_setup, generic_closure_compare);
}
void OSLShader::register_closures(OSLShadingSystem *ss_)
{
OSL::ShadingSystem *ss = (OSL::ShadingSystem*)ss_;
int id = 0;
register_closure(ss, "diffuse", id++,
bsdf_diffuse_params(), bsdf_diffuse_prepare);
register_closure(ss, "oren_nayar", id++,
bsdf_oren_nayar_params(), bsdf_oren_nayar_prepare);
register_closure(ss, "translucent", id++,
bsdf_translucent_params(), bsdf_translucent_prepare);
register_closure(ss, "reflection", id++,
bsdf_reflection_params(), bsdf_reflection_prepare);
register_closure(ss, "refraction", id++,
bsdf_refraction_params(), bsdf_refraction_prepare);
register_closure(ss, "transparent", id++,
bsdf_transparent_params(), bsdf_transparent_prepare);
register_closure(ss, "microfacet_ggx", id++,
bsdf_microfacet_ggx_params(), bsdf_microfacet_ggx_prepare);
register_closure(ss, "microfacet_ggx_refraction", id++,
bsdf_microfacet_ggx_refraction_params(), bsdf_microfacet_ggx_refraction_prepare);
register_closure(ss, "microfacet_beckmann", id++,
bsdf_microfacet_beckmann_params(), bsdf_microfacet_beckmann_prepare);
register_closure(ss, "microfacet_beckmann_refraction", id++,
bsdf_microfacet_beckmann_refraction_params(), bsdf_microfacet_beckmann_refraction_prepare);
register_closure(ss, "ward", id++,
bsdf_ward_params(), bsdf_ward_prepare);
register_closure(ss, "ashikhmin_velvet", id++,
bsdf_ashikhmin_velvet_params(), bsdf_ashikhmin_velvet_prepare);
register_closure(ss, "westin_backscatter", id++,
bsdf_westin_backscatter_params(), bsdf_westin_backscatter_prepare);
register_closure(ss, "westin_sheen", id++,
bsdf_westin_sheen_params(), bsdf_westin_sheen_prepare);
register_closure(ss, "emission", id++,
closure_emission_params(), closure_emission_prepare);
register_closure(ss, "background", id++,
closure_background_params(), closure_background_prepare);
register_closure(ss, "holdout", id++,
closure_holdout_params(), closure_holdout_prepare);
register_closure(ss, "ambient_occlusion", id++,
closure_ambient_occlusion_params(), closure_ambient_occlusion_prepare);
register_closure(ss, "diffuse_ramp", id++,
closure_bsdf_diffuse_ramp_params(), closure_bsdf_diffuse_ramp_prepare);
register_closure(ss, "phong_ramp", id++,
closure_bsdf_phong_ramp_params(), closure_bsdf_phong_ramp_prepare);
register_closure(ss, "diffuse_toon", id++,
closure_bsdf_diffuse_toon_params(), closure_bsdf_diffuse_toon_prepare);
register_closure(ss, "specular_toon", id++,
closure_bsdf_specular_toon_params(), closure_bsdf_specular_toon_prepare);
register_closure(ss, "bssrdf_cubic", id++,
closure_bssrdf_params(), closure_bssrdf_prepare);
}
CCL_NAMESPACE_END
| Fix compiler warnings with westin OSL code. | Fix compiler warnings with westin OSL code.
| C++ | apache-2.0 | pyrochlore/cycles,tangent-opensource/coreBlackbird,pyrochlore/cycles,tangent-opensource/coreBlackbird,pyrochlore/cycles,tangent-opensource/coreBlackbird |
527149c67095bb5e29d32c970d0e94b91a8fcd86 | test/std/containers/sequences/array/indexing.pass.cpp | test/std/containers/sequences/array/indexing.pass.cpp | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <array>
// reference operator[] (size_type)
// const_reference operator[] (size_type); // constexpr in C++14
// reference at (size_type)
// const_reference at (size_type); // constexpr in C++14
// Libc++ marks these as noexcept
#include <array>
#include <cassert>
#include "test_macros.h"
// std::array is explicitly allowed to be initialized with A a = { init-list };.
// Disable the missing braces warning for this reason.
#include "disable_missing_braces_warning.h"
#if TEST_STD_VER > 14
constexpr bool check_idx( size_t idx, double val )
{
std::array<double, 3> arr = {1, 2, 3.5};
return arr[idx] == val;
}
#endif
int main(int, char**)
{
{
typedef double T;
typedef std::array<T, 3> C;
C c = {1, 2, 3.5};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::reference, decltype(c[0]));
C::reference r1 = c[0];
assert(r1 == 1);
r1 = 5.5;
assert(c.front() == 5.5);
C::reference r2 = c[2];
assert(r2 == 3.5);
r2 = 7.5;
assert(c.back() == 7.5);
}
{
typedef double T;
typedef std::array<T, 3> C;
const C c = {1, 2, 3.5};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::const_reference, decltype(c[0]));
C::const_reference r1 = c[0];
assert(r1 == 1);
C::const_reference r2 = c[2];
assert(r2 == 3.5);
}
{ // Test operator[] "works" on zero sized arrays
typedef double T;
typedef std::array<T, 0> C;
C c = {};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::reference, decltype(c[0]));
C const& cc = c;
static_assert((std::is_same<decltype(c[0]), T &>::value), "");
static_assert((std::is_same<decltype(cc[0]), const T &>::value), "");
if (c.size() > (0)) { // always false
C::reference r1 = c[0];
C::const_reference r2 = cc[0];
((void)r1);
((void)r2);
}
}
{ // Test operator[] "works" on zero sized arrays
typedef double T;
typedef std::array<const T, 0> C;
C c = {{}};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::reference, decltype(c[0]));
C const& cc = c;
static_assert((std::is_same<decltype(c[0]), const T &>::value), "");
static_assert((std::is_same<decltype(cc[0]), const T &>::value), "");
if (c.size() > (0)) { // always false
C::reference r1 = c[0];
C::const_reference r2 = cc[0];
((void)r1);
((void)r2);
}
}
#if TEST_STD_VER > 11
{
typedef double T;
typedef std::array<T, 3> C;
constexpr C c = {1, 2, 3.5};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::const_reference, decltype(c[0]));
constexpr T t1 = c[0];
static_assert (t1 == 1, "");
constexpr T t2 = c[2];
static_assert (t2 == 3.5, "");
}
#endif
#if TEST_STD_VER > 14
{
static_assert (check_idx(0, 1), "");
static_assert (check_idx(1, 2), "");
static_assert (check_idx(2, 3.5), "");
}
#endif
return 0;
}
| //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <array>
// reference operator[] (size_type)
// const_reference operator[] (size_type); // constexpr in C++14
// reference at (size_type)
// const_reference at (size_type); // constexpr in C++14
// Libc++ marks these as noexcept
#include <array>
#include <cassert>
#include "test_macros.h"
// std::array is explicitly allowed to be initialized with A a = { init-list };.
// Disable the missing braces warning for this reason.
#include "disable_missing_braces_warning.h"
#if TEST_STD_VER > 14
constexpr bool check_idx( size_t idx, double val )
{
std::array<double, 3> arr = {1, 2, 3.5};
return arr[idx] == val;
}
#endif
int main(int, char**)
{
{
typedef double T;
typedef std::array<T, 3> C;
C c = {1, 2, 3.5};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::reference, decltype(c[0]));
C::reference r1 = c[0];
assert(r1 == 1);
r1 = 5.5;
assert(c.front() == 5.5);
C::reference r2 = c[2];
assert(r2 == 3.5);
r2 = 7.5;
assert(c.back() == 7.5);
}
{
typedef double T;
typedef std::array<T, 3> C;
const C c = {1, 2, 3.5};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::const_reference, decltype(c[0]));
C::const_reference r1 = c[0];
assert(r1 == 1);
C::const_reference r2 = c[2];
assert(r2 == 3.5);
}
{ // Test operator[] "works" on zero sized arrays
typedef double T;
typedef std::array<T, 0> C;
C c = {};
C const& cc = c;
LIBCPP_ASSERT_NOEXCEPT(c[0]);
LIBCPP_ASSERT_NOEXCEPT(cc[0]);
ASSERT_SAME_TYPE(C::reference, decltype(c[0]));
ASSERT_SAME_TYPE(C::const_reference, decltype(cc[0]));
if (c.size() > (0)) { // always false
C::reference r1 = c[0];
C::const_reference r2 = cc[0];
((void)r1);
((void)r2);
}
}
{ // Test operator[] "works" on zero sized arrays
typedef double T;
typedef std::array<const T, 0> C;
C c = {{}};
C const& cc = c;
LIBCPP_ASSERT_NOEXCEPT(c[0]);
LIBCPP_ASSERT_NOEXCEPT(cc[0]);
ASSERT_SAME_TYPE(C::reference, decltype(c[0]));
ASSERT_SAME_TYPE(C::const_reference, decltype(cc[0]));
if (c.size() > (0)) { // always false
C::reference r1 = c[0];
C::const_reference r2 = cc[0];
((void)r1);
((void)r2);
}
}
#if TEST_STD_VER > 11
{
typedef double T;
typedef std::array<T, 3> C;
constexpr C c = {1, 2, 3.5};
LIBCPP_ASSERT_NOEXCEPT(c[0]);
ASSERT_SAME_TYPE(C::const_reference, decltype(c[0]));
constexpr T t1 = c[0];
static_assert (t1 == 1, "");
constexpr T t2 = c[2];
static_assert (t2 == 3.5, "");
}
#endif
#if TEST_STD_VER > 14
{
static_assert (check_idx(0, 1), "");
static_assert (check_idx(1, 2), "");
static_assert (check_idx(2, 3.5), "");
}
#endif
return 0;
}
| Update a deque test with more assertions. NFC | Update a deque test with more assertions. NFC
git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@356266 91177308-0d34-0410-b5e6-96231b3b80d8
| C++ | apache-2.0 | llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx |
7644a681de2e76a4db6d26ee8e636bc3e91f5f1e | tools/Jupyter/Kernel.cpp | tools/Jupyter/Kernel.cpp | //------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// FIXME: This file shall contain the decl of cling::Jupyter in a future
// revision!
//#include "cling/Interpreter/Jupyter/Kernel.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <string>
#include <cstring>
// FIXME: should be moved into a Jupyter interp struct that then gets returned
// from create.
int pipeToJupyterFD = -1;
namespace cling {
namespace Jupyter {
struct MIMEDataRef {
const char* m_Data;
const long m_Size;
MIMEDataRef(const std::string& str):
m_Data(str.c_str()), m_Size((long)str.length() + 1) {}
MIMEDataRef(const char* str):
MIMEDataRef(std::string(str)) {}
MIMEDataRef(const char* data, long size):
m_Data(data), m_Size(size) {}
};
/// Push MIME stuff to Jupyter. To be called from user code.
///\param contentDict - dictionary of MIME type versus content. E.g.
/// {{"text/html", {"<div></div>", }}
void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) {
// Pipe sees (all numbers are longs, except for the first:
// - num bytes in a long (sent as a single unsigned char!)
// - num elements of the MIME dictionary; Jupyter selects one to display.
// For each MIME dictionary element:
// - size of MIME type string (including the terminating 0)
// - MIME type as 0-terminated string
// - size of MIME data buffer (including the terminating 0 for
// 0-terminated strings)
// - MIME data buffer
// Write number of dictionary elements (and the size of that number in a
// char)
unsigned char sizeLong = sizeof(long);
write(pipeToJupyterFD, &sizeLong, 1);
long dictSize = contentDict.size();
write(pipeToJupyterFD, &dictSize, sizeof(long));
for (auto iContent: contentDict) {
const std::string& mimeType = iContent.first;
long mimeTypeSize = (long)mimeType.size();
write(pipeToJupyterFD, &mimeTypeSize, sizeof(long));
write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1);
const MIMEDataRef& mimeData = iContent.second;
write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long));
write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size);
}
}
} // namespace Jupyter
} // namespace cling
extern "C" {
///\{
///\name Cling4CTypes
/// The Python compatible view of cling
/// The Interpreter object cast to void*
using TheInterpreter = void ;
/// Create an interpreter object.
TheInterpreter*
cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) {
auto interp = new cling::Interpreter(argc, argv, llvmdir);
pipeToJupyterFD = pipefd;
return interp;
}
/// Destroy the interpreter.
void cling_destroy(TheInterpreter *interpVP) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
delete interp;
}
/// Stringify a cling::Value
static std::string ValueToString(const cling::Value& V) {
std::string valueString;
{
llvm::raw_string_ostream os(valueString);
V.print(os);
}
return valueString;
}
/// Evaluate a string of code. Returns nullptr on failure.
/// Returns a string representation of the expression (can be "") on success.
char* cling_eval(TheInterpreter *interpVP, const char *code) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
cling::Value V;
cling::Interpreter::CompilationResult Res = interp->process(code, &V);
if (Res != cling::Interpreter::kSuccess)
return nullptr;
cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}});
if (!V.isValid())
return strdup("");
return strdup(ValueToString(V).c_str());
}
void cling_eval_free(char* str) {
free(str);
}
/// Code completion interfaces.
/// Start completion of code. Returns a handle to be passed to
/// cling_complete_next() to iterate over the completion options. Returns nulptr
/// if no completions are known.
void* cling_complete_start(const char* code) {
return new int(42);
}
/// Grab the next completion of some code. Returns nullptr if none is left.
const char* cling_complete_next(void* completionHandle) {
int* counter = (int*) completionHandle;
if (++(*counter) > 43) {
delete counter;
return nullptr;
}
return "COMPLETE!";
}
///\}
} // extern "C"
| //------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Axel Naumann <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// FIXME: This file shall contain the decl of cling::Jupyter in a future
// revision!
//#include "cling/Interpreter/Jupyter/Kernel.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <string>
#include <cstring>
#include <unistd.h>
// FIXME: should be moved into a Jupyter interp struct that then gets returned
// from create.
int pipeToJupyterFD = -1;
namespace cling {
namespace Jupyter {
struct MIMEDataRef {
const char* m_Data;
const long m_Size;
MIMEDataRef(const std::string& str):
m_Data(str.c_str()), m_Size((long)str.length() + 1) {}
MIMEDataRef(const char* str):
MIMEDataRef(std::string(str)) {}
MIMEDataRef(const char* data, long size):
m_Data(data), m_Size(size) {}
};
/// Push MIME stuff to Jupyter. To be called from user code.
///\param contentDict - dictionary of MIME type versus content. E.g.
/// {{"text/html", {"<div></div>", }}
void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) {
// Pipe sees (all numbers are longs, except for the first:
// - num bytes in a long (sent as a single unsigned char!)
// - num elements of the MIME dictionary; Jupyter selects one to display.
// For each MIME dictionary element:
// - size of MIME type string (including the terminating 0)
// - MIME type as 0-terminated string
// - size of MIME data buffer (including the terminating 0 for
// 0-terminated strings)
// - MIME data buffer
// Write number of dictionary elements (and the size of that number in a
// char)
unsigned char sizeLong = sizeof(long);
write(pipeToJupyterFD, &sizeLong, 1);
long dictSize = contentDict.size();
write(pipeToJupyterFD, &dictSize, sizeof(long));
for (auto iContent: contentDict) {
const std::string& mimeType = iContent.first;
long mimeTypeSize = (long)mimeType.size();
write(pipeToJupyterFD, &mimeTypeSize, sizeof(long));
write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1);
const MIMEDataRef& mimeData = iContent.second;
write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long));
write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size);
}
}
} // namespace Jupyter
} // namespace cling
extern "C" {
///\{
///\name Cling4CTypes
/// The Python compatible view of cling
/// The Interpreter object cast to void*
using TheInterpreter = void ;
/// Create an interpreter object.
TheInterpreter*
cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) {
auto interp = new cling::Interpreter(argc, argv, llvmdir);
pipeToJupyterFD = pipefd;
return interp;
}
/// Destroy the interpreter.
void cling_destroy(TheInterpreter *interpVP) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
delete interp;
}
/// Stringify a cling::Value
static std::string ValueToString(const cling::Value& V) {
std::string valueString;
{
llvm::raw_string_ostream os(valueString);
V.print(os);
}
return valueString;
}
/// Evaluate a string of code. Returns nullptr on failure.
/// Returns a string representation of the expression (can be "") on success.
char* cling_eval(TheInterpreter *interpVP, const char *code) {
cling::Interpreter *interp = (cling::Interpreter *) interpVP;
cling::Value V;
cling::Interpreter::CompilationResult Res = interp->process(code, &V);
if (Res != cling::Interpreter::kSuccess)
return nullptr;
cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}});
if (!V.isValid())
return strdup("");
return strdup(ValueToString(V).c_str());
}
void cling_eval_free(char* str) {
free(str);
}
/// Code completion interfaces.
/// Start completion of code. Returns a handle to be passed to
/// cling_complete_next() to iterate over the completion options. Returns nulptr
/// if no completions are known.
void* cling_complete_start(const char* code) {
return new int(42);
}
/// Grab the next completion of some code. Returns nullptr if none is left.
const char* cling_complete_next(void* completionHandle) {
int* counter = (int*) completionHandle;
if (++(*counter) > 43) {
delete counter;
return nullptr;
}
return "COMPLETE!";
}
///\}
} // extern "C"
| Add missing #include, reported by 0xACE. | Add missing #include, reported by 0xACE.
| C++ | lgpl-2.1 | root-mirror/cling,karies/cling,root-mirror/cling,root-mirror/cling,marsupial/cling,marsupial/cling,root-mirror/cling,karies/cling,marsupial/cling,root-mirror/cling,karies/cling,karies/cling,marsupial/cling,marsupial/cling,root-mirror/cling,marsupial/cling,karies/cling,karies/cling |
0f2e6424b9366d643a234dd8ee9eaa9ef857408a | chrome/browser/extensions/app_process_apitest.cc | chrome/browser/extensions/app_process_apitest.cc | // Copyright (c) 2010 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 "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class AppApiTest : public ExtensionApiTest {
};
// Simulates a page calling window.open on an URL, and waits for the navigation.
static void WindowOpenHelper(Browser* browser,
RenderViewHost* opener_host,
const GURL& url,
bool newtab_process_should_equal_opener) {
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(
opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');"));
// The above window.open call is not user-initiated, it will create
// a popup window instead of a new tab in current window.
// Now the active tab in last active window should be the new tab.
Browser* last_active_browser = BrowserList::GetLastActive();
EXPECT_TRUE(last_active_browser);
TabContents* newtab = last_active_browser->GetSelectedTabContents();
EXPECT_TRUE(newtab);
if (!newtab->controller().GetLastCommittedEntry() ||
newtab->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&newtab->controller());
EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url());
if (newtab_process_should_equal_opener)
EXPECT_EQ(opener_host->process(), newtab->render_view_host()->process());
else
EXPECT_NE(opener_host->process(), newtab->render_view_host()->process());
}
// Simulates a page navigating itself to an URL, and waits for the navigation.
static void NavigateTabHelper(TabContents* contents, const GURL& url) {
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(), L"",
L"window.addEventListener('unload', function() {"
L" window.domAutomationController.send(true);"
L"}, false);"
L"window.location = '" + UTF8ToWide(url.spec()) + L"';",
&result));
ASSERT_TRUE(result);
if (!contents->controller().GetLastCommittedEntry() ||
contents->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url());
}
IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app, one outside it.
GURL base_url("http://localhost:1337/files/extensions/api_test/app_process/");
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path3/empty.html"));
// The extension should have opened 3 new tabs. Including the original blank
// tab, we now have 4 tabs. Two should be part of the extension app, and
// grouped in the same process.
ASSERT_EQ(4, browser()->tab_count());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// Now let's do the same using window.open. The same should happen.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path2/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path3/empty.html"), false);
// Now let's have these pages navigate, into or out of the extension web
// extent. They should switch processes.
const GURL& app_url(base_url.Resolve("path1/empty.html"));
const GURL& non_app_url(base_url.Resolve("path3/empty.html"));
NavigateTabHelper(browser()->GetTabContentsAt(2), non_app_url);
NavigateTabHelper(browser()->GetTabContentsAt(3), app_url);
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
}
| // Copyright (c) 2010 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 "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class AppApiTest : public ExtensionApiTest {
};
// Simulates a page calling window.open on an URL, and waits for the navigation.
static void WindowOpenHelper(Browser* browser,
RenderViewHost* opener_host,
const GURL& url,
bool newtab_process_should_equal_opener) {
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(
opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');"));
// The above window.open call is not user-initiated, it will create
// a popup window instead of a new tab in current window.
// Now the active tab in last active window should be the new tab.
Browser* last_active_browser = BrowserList::GetLastActive();
EXPECT_TRUE(last_active_browser);
TabContents* newtab = last_active_browser->GetSelectedTabContents();
EXPECT_TRUE(newtab);
if (!newtab->controller().GetLastCommittedEntry() ||
newtab->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&newtab->controller());
EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url());
if (newtab_process_should_equal_opener)
EXPECT_EQ(opener_host->process(), newtab->render_view_host()->process());
else
EXPECT_NE(opener_host->process(), newtab->render_view_host()->process());
}
// Simulates a page navigating itself to an URL, and waits for the navigation.
static void NavigateTabHelper(TabContents* contents, const GURL& url) {
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
contents->render_view_host(), L"",
L"window.addEventListener('unload', function() {"
L" window.domAutomationController.send(true);"
L"}, false);"
L"window.location = '" + UTF8ToWide(url.spec()) + L"';",
&result));
ASSERT_TRUE(result);
if (!contents->controller().GetLastCommittedEntry() ||
contents->controller().GetLastCommittedEntry()->url() != url)
ui_test_utils::WaitForNavigation(&contents->controller());
EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url());
}
#if defined(OS_WIN)
// AppProcess sometimes hangs on Windows
// http://crbug.com/58810
#define MAYBE_AppProcess DISABLED_AppProcess
#else
#define MAYBE_AppProcess AppProcess
#endif
IN_PROC_BROWSER_TEST_F(AppApiTest, MAYBE_AppProcess) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kDisablePopupBlocking);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app_process")));
// Open two tabs in the app, one outside it.
GURL base_url("http://localhost:1337/files/extensions/api_test/app_process/");
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path1/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html"));
browser()->NewTab();
ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path3/empty.html"));
// The extension should have opened 3 new tabs. Including the original blank
// tab, we now have 4 tabs. Two should be part of the extension app, and
// grouped in the same process.
ASSERT_EQ(4, browser()->tab_count());
RenderViewHost* host = browser()->GetTabContentsAt(1)->render_view_host();
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
// Now let's do the same using window.open. The same should happen.
ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
WindowOpenHelper(browser(), host,
base_url.Resolve("path1/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path2/empty.html"), true);
WindowOpenHelper(browser(), host,
base_url.Resolve("path3/empty.html"), false);
// Now let's have these pages navigate, into or out of the extension web
// extent. They should switch processes.
const GURL& app_url(base_url.Resolve("path1/empty.html"));
const GURL& non_app_url(base_url.Resolve("path3/empty.html"));
NavigateTabHelper(browser()->GetTabContentsAt(2), non_app_url);
NavigateTabHelper(browser()->GetTabContentsAt(3), app_url);
EXPECT_NE(host->process(),
browser()->GetTabContentsAt(2)->render_view_host()->process());
EXPECT_EQ(host->process(),
browser()->GetTabContentsAt(3)->render_view_host()->process());
}
| Disable AppApiTest.AppProcess on Windows -- it sometimes hangs | Disable AppApiTest.AppProcess on Windows -- it sometimes hangs
BUG=58810
TEST=none
Review URL: http://codereview.chromium.org/3706004
git-svn-id: http://src.chromium.org/svn/trunk/src@62466 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: bef2a5cc6ecfaaa11342a16b1b8f7d4623317574 | C++ | bsd-3-clause | meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser |
d152ed99c189f6f69c8167b25cb72d54c86afec2 | chrome/browser/tab_contents/web_drag_dest_gtk.cc | chrome/browser/tab_contents/web_drag_dest_gtk.cc | // Copyright (c) 2011 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/tab_contents/web_drag_dest_gtk.h"
#include <string>
#include "base/file_path.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_node_data.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/gtk/bookmarks/bookmark_utils_gtk.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/url_constants.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/net_util.h"
#include "ui/base/dragdrop/gtk_dnd_util.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationNone;
namespace {
// Returns the bookmark target atom, based on the underlying toolkit.
//
// For GTK, bookmark drag data is encoded as pickle and associated with
// ui::CHROME_BOOKMARK_ITEM. See // bookmark_utils::WriteBookmarksToSelection()
// for details.
// For Views, bookmark drag data is encoded in the same format, and
// associated with a custom format. See BookmarkNodeData::Write() for
// details.
GdkAtom GetBookmarkTargetAtom() {
#if defined(TOOLKIT_VIEWS)
return BookmarkNodeData::GetBookmarkCustomFormat();
#else
return ui::GetAtomForTarget(ui::CHROME_BOOKMARK_ITEM);
#endif
}
} // namespace
WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)
: tab_contents_(tab_contents),
tab_(NULL),
widget_(widget),
context_(NULL),
method_factory_(this) {
gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),
NULL, 0,
static_cast<GdkDragAction>(GDK_ACTION_COPY |
GDK_ACTION_LINK |
GDK_ACTION_MOVE));
g_signal_connect(widget, "drag-motion",
G_CALLBACK(OnDragMotionThunk), this);
g_signal_connect(widget, "drag-leave",
G_CALLBACK(OnDragLeaveThunk), this);
g_signal_connect(widget, "drag-drop",
G_CALLBACK(OnDragDropThunk), this);
g_signal_connect(widget, "drag-data-received",
G_CALLBACK(OnDragDataReceivedThunk), this);
// TODO(tony): Need a drag-data-delete handler for moving content out of
// the tab contents. http://crbug.com/38989
destroy_handler_ = g_signal_connect(
widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_);
}
WebDragDestGtk::~WebDragDestGtk() {
if (widget_) {
gtk_drag_dest_unset(widget_);
g_signal_handler_disconnect(widget_, destroy_handler_);
}
}
void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {
if (context_) {
is_drop_target_ = operation != WebDragOperationNone;
gdk_drag_status(context_, gtk_util::WebDragOpToGdkDragAction(operation),
drag_over_time_);
}
}
void WebDragDestGtk::DragLeave() {
tab_contents_->render_view_host()->DragTargetDragLeave();
DCHECK(tab_);
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()) {
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDragLeave(
bookmark_drag_data_);
}
}
gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,
GdkDragContext* context,
gint x, gint y,
guint time) {
if (context_ != context) {
context_ = context;
drop_data_.reset(new WebDropData);
bookmark_drag_data_.Clear();
is_drop_target_ = false;
// text/plain must come before text/uri-list. This is a hack that works in
// conjunction with OnDragDataReceived. Since some file managers populate
// text/plain with file URLs when dragging files, we want to handle
// text/uri-list after text/plain so that the plain text can be cleared if
// it's a file drag.
static int supported_targets[] = {
ui::TEXT_PLAIN,
ui::TEXT_URI_LIST,
ui::TEXT_HTML,
ui::NETSCAPE_URL,
ui::CHROME_NAMED_URL,
// TODO(estade): support image drags?
};
// Add the bookmark target as well.
data_requests_ = arraysize(supported_targets) + 1;
for (size_t i = 0; i < arraysize(supported_targets); ++i) {
gtk_drag_get_data(widget_, context,
ui::GetAtomForTarget(supported_targets[i]),
time);
}
gtk_drag_get_data(widget_, context, GetBookmarkTargetAtom(), time);
} else if (data_requests_ == 0) {
tab_contents_->render_view_host()->
DragTargetDragOver(
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_util::GdkDragActionToWebDragOp(context->actions));
DCHECK(tab_);
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate())
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDragOver(
bookmark_drag_data_);
drag_over_time_ = time;
}
// Pretend we are a drag destination because we don't want to wait for
// the renderer to tell us if we really are or not.
return TRUE;
}
void WebDragDestGtk::OnDragDataReceived(
GtkWidget* sender, GdkDragContext* context, gint x, gint y,
GtkSelectionData* data, guint info, guint time) {
// We might get the data from an old get_data() request that we no longer
// care about.
if (context != context_)
return;
data_requests_--;
// Decode the data.
if (data->data && data->length > 0) {
// If the source can't provide us with valid data for a requested target,
// data->data will be NULL.
if (data->target == ui::GetAtomForTarget(ui::TEXT_PLAIN)) {
guchar* text = gtk_selection_data_get_text(data);
if (text) {
drop_data_->plain_text =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(text)));
g_free(text);
}
} else if (data->target == ui::GetAtomForTarget(ui::TEXT_URI_LIST)) {
gchar** uris = gtk_selection_data_get_uris(data);
if (uris) {
drop_data_->url = GURL();
for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {
// Most file managers populate text/uri-list with file URLs when
// dragging files. To avoid exposing file system paths to web content,
// file URLs are never set as the URL content for the drop.
// TODO(estade): Can the filenames have a non-UTF8 encoding?
GURL url(*uri_iter);
FilePath file_path;
if (url.SchemeIs(chrome::kFileScheme) &&
net::FileURLToFilePath(url, &file_path)) {
drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));
// This is a hack. Some file managers also populate text/plain with
// a file URL when dragging files, so we clear it to avoid exposing
// it to the web content.
drop_data_->plain_text.clear();
} else if (!drop_data_->url.is_valid()) {
// Also set the first non-file URL as the URL content for the drop.
drop_data_->url = url;
}
}
g_strfreev(uris);
}
} else if (data->target == ui::GetAtomForTarget(ui::TEXT_HTML)) {
// TODO(estade): Can the html have a non-UTF8 encoding?
drop_data_->text_html =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),
data->length));
// We leave the base URL empty.
} else if (data->target == ui::GetAtomForTarget(ui::NETSCAPE_URL)) {
std::string netscape_url(reinterpret_cast<char*>(data->data),
data->length);
size_t split = netscape_url.find_first_of('\n');
if (split != std::string::npos) {
drop_data_->url = GURL(netscape_url.substr(0, split));
if (split < netscape_url.size() - 1)
drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));
}
} else if (data->target == ui::GetAtomForTarget(ui::CHROME_NAMED_URL)) {
ui::ExtractNamedURL(data, &drop_data_->url, &drop_data_->url_title);
}
}
// For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source
// doesn't have any data available for us. In this case we try to synthesize a
// URL bookmark.
// Note that bookmark drag data is encoded in the same format for both
// GTK and Views, hence we can share the same logic here.
if (data->target == GetBookmarkTargetAtom()) {
if (data->data && data->length > 0) {
Profile* profile =
Profile::FromBrowserContext(tab_contents_->browser_context());
bookmark_drag_data_.ReadFromVector(
bookmark_utils::GetNodesFromSelection(
NULL, data,
ui::CHROME_BOOKMARK_ITEM,
profile, NULL, NULL));
bookmark_drag_data_.SetOriginatingProfile(profile);
} else {
bookmark_drag_data_.ReadFromTuple(drop_data_->url,
drop_data_->url_title);
}
}
if (data_requests_ == 0) {
// Tell the renderer about the drag.
// |x| and |y| are seemingly arbitrary at this point.
tab_contents_->render_view_host()->
DragTargetDragEnter(*drop_data_.get(),
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_util::GdkDragActionToWebDragOp(context->actions));
if (!tab_) {
tab_ = TabContentsWrapper::GetCurrentWrapperForContents(tab_contents_);
DCHECK(tab_);
}
// This is non-null if tab_contents_ is showing an ExtensionWebUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()) {
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDragEnter(
bookmark_drag_data_);
}
drag_over_time_ = time;
}
}
// The drag has left our widget; forward this information to the renderer.
void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,
guint time) {
// Set |context_| to NULL to make sure we will recognize the next DragMotion
// as an enter.
context_ = NULL;
drop_data_.reset();
// When GTK sends us a drag-drop signal, it is shortly (and synchronously)
// preceded by a drag-leave. The renderer doesn't like getting the signals
// in this order so delay telling it about the drag-leave till we are sure
// we are not getting a drop as well.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));
}
// Called by GTK when the user releases the mouse, executing a drop.
gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,
gint x, gint y, guint time) {
// Cancel that drag leave!
method_factory_.RevokeAll();
tab_contents_->render_view_host()->
DragTargetDrop(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_));
DCHECK(tab_);
// This is non-null if tab_contents_ is showing an ExtensionWebUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate())
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDrop(
bookmark_drag_data_);
// Focus the target browser.
Browser* browser = Browser::GetBrowserForController(
&tab_contents_->controller(), NULL);
if (browser)
browser->window()->Show();
// The second parameter is just an educated guess as to whether or not the
// drag succeeded, but at least we will get the drag-end animation right
// sometimes.
gtk_drag_finish(context, is_drop_target_, FALSE, time);
return TRUE;
}
| // Copyright (c) 2011 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/tab_contents/web_drag_dest_gtk.h"
#include <string>
#include "base/file_path.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_node_data.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/gtk/bookmarks/bookmark_utils_gtk.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/url_constants.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/net_util.h"
#include "ui/base/dragdrop/gtk_dnd_util.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationNone;
namespace {
// Returns the bookmark target atom, based on the underlying toolkit.
//
// For GTK, bookmark drag data is encoded as pickle and associated with
// ui::CHROME_BOOKMARK_ITEM. See // bookmark_utils::WriteBookmarksToSelection()
// for details.
// For Views, bookmark drag data is encoded in the same format, and
// associated with a custom format. See BookmarkNodeData::Write() for
// details.
GdkAtom GetBookmarkTargetAtom() {
#if defined(TOOLKIT_VIEWS)
return BookmarkNodeData::GetBookmarkCustomFormat();
#else
return ui::GetAtomForTarget(ui::CHROME_BOOKMARK_ITEM);
#endif
}
} // namespace
WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)
: tab_contents_(tab_contents),
tab_(NULL),
widget_(widget),
context_(NULL),
method_factory_(this) {
gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),
NULL, 0,
static_cast<GdkDragAction>(GDK_ACTION_COPY |
GDK_ACTION_LINK |
GDK_ACTION_MOVE));
g_signal_connect(widget, "drag-motion",
G_CALLBACK(OnDragMotionThunk), this);
g_signal_connect(widget, "drag-leave",
G_CALLBACK(OnDragLeaveThunk), this);
g_signal_connect(widget, "drag-drop",
G_CALLBACK(OnDragDropThunk), this);
g_signal_connect(widget, "drag-data-received",
G_CALLBACK(OnDragDataReceivedThunk), this);
// TODO(tony): Need a drag-data-delete handler for moving content out of
// the tab contents. http://crbug.com/38989
destroy_handler_ = g_signal_connect(
widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_);
}
WebDragDestGtk::~WebDragDestGtk() {
if (widget_) {
gtk_drag_dest_unset(widget_);
g_signal_handler_disconnect(widget_, destroy_handler_);
}
}
void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {
if (context_) {
is_drop_target_ = operation != WebDragOperationNone;
gdk_drag_status(context_, gtk_util::WebDragOpToGdkDragAction(operation),
drag_over_time_);
}
}
void WebDragDestGtk::DragLeave() {
tab_contents_->render_view_host()->DragTargetDragLeave();
// TODO(thestig) Turn back to DCHECKs after we figure out bug 89388.
CHECK(tab_);
CHECK(tab_->bookmark_tab_helper());
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()) {
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDragLeave(
bookmark_drag_data_);
}
}
gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,
GdkDragContext* context,
gint x, gint y,
guint time) {
if (context_ != context) {
context_ = context;
drop_data_.reset(new WebDropData);
bookmark_drag_data_.Clear();
is_drop_target_ = false;
// text/plain must come before text/uri-list. This is a hack that works in
// conjunction with OnDragDataReceived. Since some file managers populate
// text/plain with file URLs when dragging files, we want to handle
// text/uri-list after text/plain so that the plain text can be cleared if
// it's a file drag.
static int supported_targets[] = {
ui::TEXT_PLAIN,
ui::TEXT_URI_LIST,
ui::TEXT_HTML,
ui::NETSCAPE_URL,
ui::CHROME_NAMED_URL,
// TODO(estade): support image drags?
};
// Add the bookmark target as well.
data_requests_ = arraysize(supported_targets) + 1;
for (size_t i = 0; i < arraysize(supported_targets); ++i) {
gtk_drag_get_data(widget_, context,
ui::GetAtomForTarget(supported_targets[i]),
time);
}
gtk_drag_get_data(widget_, context, GetBookmarkTargetAtom(), time);
} else if (data_requests_ == 0) {
tab_contents_->render_view_host()->
DragTargetDragOver(
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_util::GdkDragActionToWebDragOp(context->actions));
DCHECK(tab_);
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate())
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDragOver(
bookmark_drag_data_);
drag_over_time_ = time;
}
// Pretend we are a drag destination because we don't want to wait for
// the renderer to tell us if we really are or not.
return TRUE;
}
void WebDragDestGtk::OnDragDataReceived(
GtkWidget* sender, GdkDragContext* context, gint x, gint y,
GtkSelectionData* data, guint info, guint time) {
// We might get the data from an old get_data() request that we no longer
// care about.
if (context != context_)
return;
data_requests_--;
// Decode the data.
if (data->data && data->length > 0) {
// If the source can't provide us with valid data for a requested target,
// data->data will be NULL.
if (data->target == ui::GetAtomForTarget(ui::TEXT_PLAIN)) {
guchar* text = gtk_selection_data_get_text(data);
if (text) {
drop_data_->plain_text =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(text)));
g_free(text);
}
} else if (data->target == ui::GetAtomForTarget(ui::TEXT_URI_LIST)) {
gchar** uris = gtk_selection_data_get_uris(data);
if (uris) {
drop_data_->url = GURL();
for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {
// Most file managers populate text/uri-list with file URLs when
// dragging files. To avoid exposing file system paths to web content,
// file URLs are never set as the URL content for the drop.
// TODO(estade): Can the filenames have a non-UTF8 encoding?
GURL url(*uri_iter);
FilePath file_path;
if (url.SchemeIs(chrome::kFileScheme) &&
net::FileURLToFilePath(url, &file_path)) {
drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));
// This is a hack. Some file managers also populate text/plain with
// a file URL when dragging files, so we clear it to avoid exposing
// it to the web content.
drop_data_->plain_text.clear();
} else if (!drop_data_->url.is_valid()) {
// Also set the first non-file URL as the URL content for the drop.
drop_data_->url = url;
}
}
g_strfreev(uris);
}
} else if (data->target == ui::GetAtomForTarget(ui::TEXT_HTML)) {
// TODO(estade): Can the html have a non-UTF8 encoding?
drop_data_->text_html =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),
data->length));
// We leave the base URL empty.
} else if (data->target == ui::GetAtomForTarget(ui::NETSCAPE_URL)) {
std::string netscape_url(reinterpret_cast<char*>(data->data),
data->length);
size_t split = netscape_url.find_first_of('\n');
if (split != std::string::npos) {
drop_data_->url = GURL(netscape_url.substr(0, split));
if (split < netscape_url.size() - 1)
drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));
}
} else if (data->target == ui::GetAtomForTarget(ui::CHROME_NAMED_URL)) {
ui::ExtractNamedURL(data, &drop_data_->url, &drop_data_->url_title);
}
}
// For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source
// doesn't have any data available for us. In this case we try to synthesize a
// URL bookmark.
// Note that bookmark drag data is encoded in the same format for both
// GTK and Views, hence we can share the same logic here.
if (data->target == GetBookmarkTargetAtom()) {
if (data->data && data->length > 0) {
Profile* profile =
Profile::FromBrowserContext(tab_contents_->browser_context());
bookmark_drag_data_.ReadFromVector(
bookmark_utils::GetNodesFromSelection(
NULL, data,
ui::CHROME_BOOKMARK_ITEM,
profile, NULL, NULL));
bookmark_drag_data_.SetOriginatingProfile(profile);
} else {
bookmark_drag_data_.ReadFromTuple(drop_data_->url,
drop_data_->url_title);
}
}
if (data_requests_ == 0) {
// Tell the renderer about the drag.
// |x| and |y| are seemingly arbitrary at this point.
tab_contents_->render_view_host()->
DragTargetDragEnter(*drop_data_.get(),
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_util::GdkDragActionToWebDragOp(context->actions));
if (!tab_) {
tab_ = TabContentsWrapper::GetCurrentWrapperForContents(tab_contents_);
DCHECK(tab_);
}
// This is non-null if tab_contents_ is showing an ExtensionWebUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()) {
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDragEnter(
bookmark_drag_data_);
}
drag_over_time_ = time;
}
}
// The drag has left our widget; forward this information to the renderer.
void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,
guint time) {
// Set |context_| to NULL to make sure we will recognize the next DragMotion
// as an enter.
context_ = NULL;
drop_data_.reset();
// When GTK sends us a drag-drop signal, it is shortly (and synchronously)
// preceded by a drag-leave. The renderer doesn't like getting the signals
// in this order so delay telling it about the drag-leave till we are sure
// we are not getting a drop as well.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));
}
// Called by GTK when the user releases the mouse, executing a drop.
gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,
gint x, gint y, guint time) {
// Cancel that drag leave!
method_factory_.RevokeAll();
tab_contents_->render_view_host()->
DragTargetDrop(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_));
DCHECK(tab_);
// This is non-null if tab_contents_ is showing an ExtensionWebUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_->bookmark_tab_helper()->GetBookmarkDragDelegate())
tab_->bookmark_tab_helper()->GetBookmarkDragDelegate()->OnDrop(
bookmark_drag_data_);
// Focus the target browser.
Browser* browser = Browser::GetBrowserForController(
&tab_contents_->controller(), NULL);
if (browser)
browser->window()->Show();
// The second parameter is just an educated guess as to whether or not the
// drag succeeded, but at least we will get the drag-end animation right
// sometimes.
gtk_drag_finish(context, is_drop_target_, FALSE, time);
return TRUE;
}
| Add some CHECKs to figure out a crash. | Linux: Add some CHECKs to figure out a crash.
BUG=89388
TEST=none
Review URL: http://codereview.chromium.org/7587015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@96325 0039d316-1c4b-4281-b951-d872f2087c98
| C++ | bsd-3-clause | ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,ropik/chromium |
33664db9d9deea2780046e06153124ec3a04bc8a | cint/cling/lib/Interpreter/IncrementalParser.cpp | cint/cling/lib/Interpreter/IncrementalParser.cpp | //------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "IncrementalParser.h"
#include "ASTDumper.h"
#include "ChainedConsumer.h"
#include "DeclExtractor.h"
#include "DynamicLookup.h"
#include "ValuePrinterSynthesizer.h"
#include "cling/Interpreter/CIFactory.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/FileManager.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Parse/Parser.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ASTWriter.h"
#include "llvm/LLVMContext.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_os_ostream.h"
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <sstream>
using namespace clang;
namespace cling {
IncrementalParser::IncrementalParser(Interpreter* interp,
int argc, const char* const *argv,
const char* llvmdir):
m_Interpreter(interp),
m_DynamicLookupEnabled(false),
m_Consumer(0),
m_FirstTopLevelDecl(0),
m_LastTopLevelDecl(0),
m_SyntaxOnly(false)
{
CompilerInstance* CI
= CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer("", "CLING"),
argc, argv, llvmdir);
assert(CI && "CompilerInstance is (null)!");
m_CI.reset(CI);
m_SyntaxOnly = (CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly);
CreateSLocOffsetGenerator();
m_Consumer = dyn_cast<ChainedConsumer>(&CI->getASTConsumer());
assert(m_Consumer && "Expected ChainedConsumer!");
// Add consumers to the ChainedConsumer, which owns them
EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp);
ES->Attach(m_Consumer);
addConsumer(ChainedConsumer::kEvaluateTSynthesizer, ES);
DeclExtractor* DE = new DeclExtractor();
DE->Attach(m_Consumer);
addConsumer(ChainedConsumer::kDeclExtractor, DE);
ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp);
VPS->Attach(m_Consumer);
addConsumer(ChainedConsumer::kValuePrinterSynthesizer, VPS);
addConsumer(ChainedConsumer::kASTDumper, new ASTDumper());
if (!m_SyntaxOnly) {
CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(),
"cling input",
CI->getCodeGenOpts(),
/*Owned by codegen*/ * new llvm::LLVMContext()
);
assert(CG && "No CodeGen?!");
addConsumer(ChainedConsumer::kCodeGenerator, CG);
}
m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema(),
false /*skipFuncBodies*/));
CI->getPreprocessor().EnterMainSourceFile();
// Initialize the parser after we have entered the main source file.
m_Parser->Initialize();
// Perform initialization that occurs after the parser has been initialized
// but before it parses anything. Initializes the consumers too.
CI->getSema().Initialize();
}
// Each input line is contained in separate memory buffer. The SourceManager
// assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry
// for the MemoryBuffer's FileID. That in turn is problem because invalid
// SourceLocations are given to the diagnostics. Thus the diagnostics cannot
// order the overloads, for example
//
// Our work-around is creating a virtual file, which doesn't exist on the disk
// with enormous size (no allocation is done). That file has valid FileEntry
// and so on... We use it for generating valid SourceLocations with valid
// offsets so that it doesn't cause any troubles to the diagnostics.
//
// +---------------------+
// | Main memory buffer |
// +---------------------+
// | Virtual file SLoc |
// | address space |<-----------------+
// | ... |<------------+ |
// | ... | | |
// | ... |<----+ | |
// | ... | | | |
// +~~~~~~~~~~~~~~~~~~~~~+ | | |
// | input_line_1 | ....+.......+..--+
// +---------------------+ | |
// | input_line_2 | ....+.....--+
// +---------------------+ |
// | ... | |
// +---------------------+ |
// | input_line_N | ..--+
// +---------------------+
//
void IncrementalParser::CreateSLocOffsetGenerator() {
SourceManager& SM = getCI()->getSourceManager();
FileManager& FM = SM.getFileManager();
const FileEntry* FE
= FM.getVirtualFile("Interactrive/InputLineIncluder", 1U << 15U, time(0));
m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
assert(!m_VirtualFileID.isInvalid() && "No VirtualFileID created?");
}
IncrementalParser::~IncrementalParser() {
if (GetCodeGenerator()) {
GetCodeGenerator()->ReleaseModule();
}
}
void IncrementalParser::Initialize() {
Compile("", CompilationOptions()); // Consume initialization.
}
IncrementalParser::EParseResult
IncrementalParser::Compile(llvm::StringRef input,
const CompilationOptions& Opts) {
m_Consumer->pushCompilationOpts(Opts);
EParseResult Result = Compile(input);
m_Consumer->popCompilationOpts();
return Result;
}
void IncrementalParser::Parse(llvm::StringRef input,
llvm::SmallVector<DeclGroupRef, 4>& DGRs){
if (!m_SyntaxOnly)
m_Consumer->DisableConsumer(ChainedConsumer::kCodeGenerator);
Parse(input);
for (llvm::SmallVector<ChainedConsumer::DGRInfo, 64>::iterator
I = m_Consumer->DeclsQueue.begin(), E = m_Consumer->DeclsQueue.end();
I != E; ++I) {
DGRs.push_back((*I).D);
}
if (!m_SyntaxOnly)
m_Consumer->EnableConsumer(ChainedConsumer::kCodeGenerator);
}
IncrementalParser::EParseResult
IncrementalParser::Compile(llvm::StringRef input) {
// Just in case when Parse is called, we want to complete the transaction
// coming from parse and then start new one.
m_Consumer->HandleTranslationUnit(getCI()->getASTContext());
// Reset the module builder to clean up global initializers, c'tors, d'tors:
if (GetCodeGenerator()) {
GetCodeGenerator()->Initialize(getCI()->getASTContext());
}
EParseResult Result = Parse(input);
// Check for errors coming from our custom consumers.
DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();
DClient.BeginSourceFile(getCI()->getLangOpts(), &getCI()->getPreprocessor());
m_Consumer->HandleTranslationUnit(getCI()->getASTContext());
DClient.EndSourceFile();
m_CI->getDiagnostics().Reset();
if (!m_SyntaxOnly) {
m_Interpreter->runStaticInitializersOnce();
}
return Result;
}
IncrementalParser::EParseResult
IncrementalParser::Parse(llvm::StringRef input) {
// Add src to the memory buffer, parse it, and add it to
// the AST. Returns the CompilerInstance (and thus the AST).
// Diagnostics are reset for each call of parse: they are only covering
// src.
Preprocessor& PP = m_CI->getPreprocessor();
DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();
PP.enableIncrementalProcessing();
DClient.BeginSourceFile(m_CI->getLangOpts(), &PP);
// Reset the transaction information
getLastTransaction().setBeforeFirstDecl(getCI()->getSema().CurContext);
if (input.size()) {
std::ostringstream source_name;
source_name << "input_line_" << (m_MemoryBuffer.size() + 1);
m_MemoryBuffer.push_back(llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str()));
SourceManager& SM = getCI()->getSourceManager();
// Create SourceLocation, which will allow clang to order the overload
// candidates for example
SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);
NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1);
// Create FileID for the current buffer
FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(),
/*LoadedID*/0,
/*LoadedOffset*/0, NewLoc);
PP.EnterSourceFile(FID, 0, NewLoc);
}
Parser::DeclGroupPtrTy ADecl;
while (!m_Parser->ParseTopLevelDecl(ADecl)) {
// Not end of file.
// If we got a null return and something *was* parsed, ignore it. This
// is due to a top-level semicolon, an action override, or a parse error
// skipping something.
if (ADecl) {
DeclGroupRef DGR = ADecl.getAsVal<DeclGroupRef>();
for (DeclGroupRef::iterator i=DGR.begin(); i< DGR.end(); ++i) {
if (!m_FirstTopLevelDecl)
m_FirstTopLevelDecl = *((*i)->getDeclContext()->decls_begin());
m_LastTopLevelDecl = *i;
}
m_Consumer->HandleTopLevelDecl(DGR);
} // ADecl
};
// Process any TopLevelDecls generated by #pragma weak.
for (llvm::SmallVector<Decl*,2>::iterator
I = getCI()->getSema().WeakTopLevelDecls().begin(),
E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) {
m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
}
getCI()->getSema().PerformPendingInstantiations();
DClient.EndSourceFile();
PP.enableIncrementalProcessing(false);
DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics();
if (Diag.hasErrorOccurred())
return IncrementalParser::kFailed;
else if (Diag.getNumWarnings())
return IncrementalParser::kSuccessWithWarnings;
return IncrementalParser::kSuccess;
}
void IncrementalParser::enableDynamicLookup(bool value) {
m_DynamicLookupEnabled = value;
Sema& S = m_CI->getSema();
if (isDynamicLookupEnabled()) {
assert(!S.ExternalSource && "Already set Sema ExternalSource");
S.ExternalSource = new DynamicIDHandler(&S);
}
else {
delete S.ExternalSource;
S.ExternalSource = 0;
}
}
void IncrementalParser::addConsumer(ChainedConsumer::EConsumerIndex I, ASTConsumer* consumer) {
if (m_Consumer->Exists(I))
return;
m_Consumer->Add(I, consumer);
if (I == ChainedConsumer::kCodeGenerator)
m_Consumer->EnableConsumer(I);
}
CodeGenerator* IncrementalParser::GetCodeGenerator() const {
return
(CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator);
}
} // namespace cling
| //------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "IncrementalParser.h"
#include "ASTDumper.h"
#include "ChainedConsumer.h"
#include "DeclExtractor.h"
#include "DynamicLookup.h"
#include "ValuePrinterSynthesizer.h"
#include "cling/Interpreter/CIFactory.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/FileManager.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Parse/Parser.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ASTWriter.h"
#include "llvm/LLVMContext.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_os_ostream.h"
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <sstream>
using namespace clang;
namespace cling {
IncrementalParser::IncrementalParser(Interpreter* interp,
int argc, const char* const *argv,
const char* llvmdir):
m_Interpreter(interp),
m_DynamicLookupEnabled(false),
m_Consumer(0),
m_FirstTopLevelDecl(0),
m_LastTopLevelDecl(0),
m_SyntaxOnly(false)
{
CompilerInstance* CI
= CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer("", "CLING"),
argc, argv, llvmdir);
assert(CI && "CompilerInstance is (null)!");
m_CI.reset(CI);
m_SyntaxOnly = (CI->getFrontendOpts().ProgramAction == clang::frontend::ParseSyntaxOnly);
CreateSLocOffsetGenerator();
m_Consumer = dyn_cast<ChainedConsumer>(&CI->getASTConsumer());
assert(m_Consumer && "Expected ChainedConsumer!");
// Add consumers to the ChainedConsumer, which owns them
EvaluateTSynthesizer* ES = new EvaluateTSynthesizer(interp);
ES->Attach(m_Consumer);
addConsumer(ChainedConsumer::kEvaluateTSynthesizer, ES);
DeclExtractor* DE = new DeclExtractor();
DE->Attach(m_Consumer);
addConsumer(ChainedConsumer::kDeclExtractor, DE);
ValuePrinterSynthesizer* VPS = new ValuePrinterSynthesizer(interp);
VPS->Attach(m_Consumer);
addConsumer(ChainedConsumer::kValuePrinterSynthesizer, VPS);
addConsumer(ChainedConsumer::kASTDumper, new ASTDumper());
if (!m_SyntaxOnly) {
CodeGenerator* CG = CreateLLVMCodeGen(CI->getDiagnostics(),
"cling input",
CI->getCodeGenOpts(),
/*Owned by codegen*/ * new llvm::LLVMContext()
);
assert(CG && "No CodeGen?!");
addConsumer(ChainedConsumer::kCodeGenerator, CG);
}
m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema(),
false /*skipFuncBodies*/));
CI->getPreprocessor().EnterMainSourceFile();
// Initialize the parser after we have entered the main source file.
m_Parser->Initialize();
// Perform initialization that occurs after the parser has been initialized
// but before it parses anything. Initializes the consumers too.
CI->getSema().Initialize();
}
// Each input line is contained in separate memory buffer. The SourceManager
// assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry
// for the MemoryBuffer's FileID. That in turn is problem because invalid
// SourceLocations are given to the diagnostics. Thus the diagnostics cannot
// order the overloads, for example
//
// Our work-around is creating a virtual file, which doesn't exist on the disk
// with enormous size (no allocation is done). That file has valid FileEntry
// and so on... We use it for generating valid SourceLocations with valid
// offsets so that it doesn't cause any troubles to the diagnostics.
//
// +---------------------+
// | Main memory buffer |
// +---------------------+
// | Virtual file SLoc |
// | address space |<-----------------+
// | ... |<------------+ |
// | ... | | |
// | ... |<----+ | |
// | ... | | | |
// +~~~~~~~~~~~~~~~~~~~~~+ | | |
// | input_line_1 | ....+.......+..--+
// +---------------------+ | |
// | input_line_2 | ....+.....--+
// +---------------------+ |
// | ... | |
// +---------------------+ |
// | input_line_N | ..--+
// +---------------------+
//
void IncrementalParser::CreateSLocOffsetGenerator() {
SourceManager& SM = getCI()->getSourceManager();
FileManager& FM = SM.getFileManager();
const FileEntry* FE
= FM.getVirtualFile("Interactrive/InputLineIncluder", 1U << 15U, time(0));
m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
assert(!m_VirtualFileID.isInvalid() && "No VirtualFileID created?");
}
IncrementalParser::~IncrementalParser() {
if (GetCodeGenerator()) {
GetCodeGenerator()->ReleaseModule();
}
}
void IncrementalParser::Initialize() {
CompilationOptions CO;
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
Compile("", CO); // Consume initialization.
}
IncrementalParser::EParseResult
IncrementalParser::Compile(llvm::StringRef input,
const CompilationOptions& Opts) {
m_Consumer->pushCompilationOpts(Opts);
EParseResult Result = Compile(input);
m_Consumer->popCompilationOpts();
return Result;
}
void IncrementalParser::Parse(llvm::StringRef input,
llvm::SmallVector<DeclGroupRef, 4>& DGRs){
if (!m_SyntaxOnly)
m_Consumer->DisableConsumer(ChainedConsumer::kCodeGenerator);
Parse(input);
for (llvm::SmallVector<ChainedConsumer::DGRInfo, 64>::iterator
I = m_Consumer->DeclsQueue.begin(), E = m_Consumer->DeclsQueue.end();
I != E; ++I) {
DGRs.push_back((*I).D);
}
if (!m_SyntaxOnly)
m_Consumer->EnableConsumer(ChainedConsumer::kCodeGenerator);
}
IncrementalParser::EParseResult
IncrementalParser::Compile(llvm::StringRef input) {
// Just in case when Parse is called, we want to complete the transaction
// coming from parse and then start new one.
m_Consumer->HandleTranslationUnit(getCI()->getASTContext());
// Reset the module builder to clean up global initializers, c'tors, d'tors:
if (GetCodeGenerator()) {
GetCodeGenerator()->Initialize(getCI()->getASTContext());
}
EParseResult Result = Parse(input);
// Check for errors coming from our custom consumers.
DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();
DClient.BeginSourceFile(getCI()->getLangOpts(), &getCI()->getPreprocessor());
m_Consumer->HandleTranslationUnit(getCI()->getASTContext());
DClient.EndSourceFile();
m_CI->getDiagnostics().Reset();
if (!m_SyntaxOnly) {
m_Interpreter->runStaticInitializersOnce();
}
return Result;
}
IncrementalParser::EParseResult
IncrementalParser::Parse(llvm::StringRef input) {
// Add src to the memory buffer, parse it, and add it to
// the AST. Returns the CompilerInstance (and thus the AST).
// Diagnostics are reset for each call of parse: they are only covering
// src.
Preprocessor& PP = m_CI->getPreprocessor();
DiagnosticConsumer& DClient = m_CI->getDiagnosticClient();
PP.enableIncrementalProcessing();
DClient.BeginSourceFile(m_CI->getLangOpts(), &PP);
// Reset the transaction information
getLastTransaction().setBeforeFirstDecl(getCI()->getSema().CurContext);
if (input.size()) {
std::ostringstream source_name;
source_name << "input_line_" << (m_MemoryBuffer.size() + 1);
m_MemoryBuffer.push_back(llvm::MemoryBuffer::getMemBufferCopy(input, source_name.str()));
SourceManager& SM = getCI()->getSourceManager();
// Create SourceLocation, which will allow clang to order the overload
// candidates for example
SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);
NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffer.size() + 1);
// Create FileID for the current buffer
FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffer.back(),
/*LoadedID*/0,
/*LoadedOffset*/0, NewLoc);
PP.EnterSourceFile(FID, 0, NewLoc);
}
Parser::DeclGroupPtrTy ADecl;
while (!m_Parser->ParseTopLevelDecl(ADecl)) {
// Not end of file.
// If we got a null return and something *was* parsed, ignore it. This
// is due to a top-level semicolon, an action override, or a parse error
// skipping something.
if (ADecl) {
DeclGroupRef DGR = ADecl.getAsVal<DeclGroupRef>();
for (DeclGroupRef::iterator i=DGR.begin(); i< DGR.end(); ++i) {
if (!m_FirstTopLevelDecl)
m_FirstTopLevelDecl = *((*i)->getDeclContext()->decls_begin());
m_LastTopLevelDecl = *i;
}
m_Consumer->HandleTopLevelDecl(DGR);
} // ADecl
};
// Process any TopLevelDecls generated by #pragma weak.
for (llvm::SmallVector<Decl*,2>::iterator
I = getCI()->getSema().WeakTopLevelDecls().begin(),
E = getCI()->getSema().WeakTopLevelDecls().end(); I != E; ++I) {
m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
}
getCI()->getSema().PerformPendingInstantiations();
DClient.EndSourceFile();
PP.enableIncrementalProcessing(false);
DiagnosticsEngine& Diag = getCI()->getSema().getDiagnostics();
if (Diag.hasErrorOccurred())
return IncrementalParser::kFailed;
else if (Diag.getNumWarnings())
return IncrementalParser::kSuccessWithWarnings;
return IncrementalParser::kSuccess;
}
void IncrementalParser::enableDynamicLookup(bool value) {
m_DynamicLookupEnabled = value;
Sema& S = m_CI->getSema();
if (isDynamicLookupEnabled()) {
assert(!S.ExternalSource && "Already set Sema ExternalSource");
S.ExternalSource = new DynamicIDHandler(&S);
}
else {
delete S.ExternalSource;
S.ExternalSource = 0;
}
}
void IncrementalParser::addConsumer(ChainedConsumer::EConsumerIndex I, ASTConsumer* consumer) {
if (m_Consumer->Exists(I))
return;
m_Consumer->Add(I, consumer);
if (I == ChainedConsumer::kCodeGenerator)
m_Consumer->EnableConsumer(I);
}
CodeGenerator* IncrementalParser::GetCodeGenerator() const {
return
(CodeGenerator*)m_Consumer->getConsumer(ChainedConsumer::kCodeGenerator);
}
} // namespace cling
| Use better tunned up CompilationOptions. | Use better tunned up CompilationOptions.
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@43751 27541ba8-7e3a-0410-8455-c3a389f83636
| C++ | lgpl-2.1 | olifre/root,sawenzel/root,omazapa/root,lgiommi/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,olifre/root,root-mirror/root,sawenzel/root,lgiommi/root,nilqed/root,tc3t/qoot,Y--/root,gganis/root,buuck/root,davidlt/root,ffurano/root5,dfunke/root,CristinaCristescu/root,krafczyk/root,perovic/root,Duraznos/root,karies/root,veprbl/root,gbitzes/root,zzxuanyuan/root,cxx-hep/root-cern,cxx-hep/root-cern,tc3t/qoot,dfunke/root,abhinavmoudgil95/root,smarinac/root,dfunke/root,beniz/root,agarciamontoro/root,sawenzel/root,tc3t/qoot,buuck/root,zzxuanyuan/root-compressor-dummy,omazapa/root,mkret2/root,0x0all/ROOT,veprbl/root,kirbyherm/root-r-tools,root-mirror/root,abhinavmoudgil95/root,pspe/root,satyarth934/root,mhuwiler/rootauto,karies/root,karies/root,agarciamontoro/root,agarciamontoro/root,mattkretz/root,buuck/root,mhuwiler/rootauto,esakellari/my_root_for_test,sawenzel/root,Y--/root,esakellari/my_root_for_test,abhinavmoudgil95/root,sawenzel/root,lgiommi/root,gbitzes/root,Duraznos/root,abhinavmoudgil95/root,smarinac/root,tc3t/qoot,nilqed/root,Y--/root,olifre/root,arch1tect0r/root,georgtroska/root,krafczyk/root,omazapa/root,simonpf/root,esakellari/my_root_for_test,davidlt/root,CristinaCristescu/root,Duraznos/root,gbitzes/root,smarinac/root,davidlt/root,satyarth934/root,strykejern/TTreeReader,perovic/root,simonpf/root,Duraznos/root,Dr15Jones/root,BerserkerTroll/root,buuck/root,olifre/root,kirbyherm/root-r-tools,pspe/root,esakellari/my_root_for_test,BerserkerTroll/root,karies/root,dfunke/root,jrtomps/root,omazapa/root-old,Dr15Jones/root,georgtroska/root,sbinet/cxx-root,esakellari/my_root_for_test,davidlt/root,pspe/root,vukasinmilosevic/root,zzxuanyuan/root,karies/root,BerserkerTroll/root,gganis/root,CristinaCristescu/root,smarinac/root,bbockelm/root,thomaskeck/root,esakellari/my_root_for_test,gbitzes/root,BerserkerTroll/root,Duraznos/root,ffurano/root5,zzxuanyuan/root,CristinaCristescu/root,satyarth934/root,Duraznos/root,simonpf/root,omazapa/root-old,omazapa/root,mattkretz/root,jrtomps/root,dfunke/root,strykejern/TTreeReader,buuck/root,jrtomps/root,bbockelm/root,krafczyk/root,satyarth934/root,perovic/root,satyarth934/root,perovic/root,krafczyk/root,vukasinmilosevic/root,thomaskeck/root,lgiommi/root,simonpf/root,cxx-hep/root-cern,veprbl/root,mattkretz/root,beniz/root,karies/root,evgeny-boger/root,olifre/root,perovic/root,sawenzel/root,tc3t/qoot,perovic/root,agarciamontoro/root,abhinavmoudgil95/root,omazapa/root,gganis/root,mhuwiler/rootauto,vukasinmilosevic/root,evgeny-boger/root,thomaskeck/root,mkret2/root,alexschlueter/cern-root,dfunke/root,omazapa/root-old,arch1tect0r/root,kirbyherm/root-r-tools,omazapa/root-old,alexschlueter/cern-root,gganis/root,sbinet/cxx-root,omazapa/root,abhinavmoudgil95/root,arch1tect0r/root,0x0all/ROOT,olifre/root,buuck/root,cxx-hep/root-cern,sbinet/cxx-root,arch1tect0r/root,bbockelm/root,veprbl/root,bbockelm/root,abhinavmoudgil95/root,mattkretz/root,simonpf/root,thomaskeck/root,gganis/root,vukasinmilosevic/root,gbitzes/root,esakellari/root,karies/root,mhuwiler/rootauto,evgeny-boger/root,nilqed/root,CristinaCristescu/root,mhuwiler/rootauto,lgiommi/root,gganis/root,perovic/root,tc3t/qoot,agarciamontoro/root,agarciamontoro/root,beniz/root,alexschlueter/cern-root,perovic/root,cxx-hep/root-cern,cxx-hep/root-cern,esakellari/my_root_for_test,georgtroska/root,jrtomps/root,abhinavmoudgil95/root,georgtroska/root,sbinet/cxx-root,BerserkerTroll/root,omazapa/root-old,agarciamontoro/root,BerserkerTroll/root,evgeny-boger/root,Y--/root,esakellari/root,tc3t/qoot,buuck/root,karies/root,zzxuanyuan/root,jrtomps/root,mattkretz/root,sirinath/root,sirinath/root,olifre/root,evgeny-boger/root,satyarth934/root,mhuwiler/rootauto,sbinet/cxx-root,mkret2/root,bbockelm/root,zzxuanyuan/root-compressor-dummy,omazapa/root-old,karies/root,smarinac/root,krafczyk/root,pspe/root,tc3t/qoot,gbitzes/root,vukasinmilosevic/root,mhuwiler/rootauto,davidlt/root,pspe/root,root-mirror/root,veprbl/root,ffurano/root5,lgiommi/root,arch1tect0r/root,beniz/root,CristinaCristescu/root,mattkretz/root,gganis/root,Duraznos/root,0x0all/ROOT,satyarth934/root,Dr15Jones/root,0x0all/ROOT,thomaskeck/root,BerserkerTroll/root,davidlt/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,sirinath/root,gganis/root,smarinac/root,kirbyherm/root-r-tools,zzxuanyuan/root,nilqed/root,gbitzes/root,nilqed/root,mkret2/root,mhuwiler/rootauto,thomaskeck/root,root-mirror/root,jrtomps/root,mkret2/root,jrtomps/root,georgtroska/root,Dr15Jones/root,pspe/root,esakellari/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,Y--/root,root-mirror/root,esakellari/root,sawenzel/root,pspe/root,karies/root,sbinet/cxx-root,Duraznos/root,krafczyk/root,esakellari/root,georgtroska/root,pspe/root,georgtroska/root,nilqed/root,ffurano/root5,alexschlueter/cern-root,simonpf/root,simonpf/root,0x0all/ROOT,vukasinmilosevic/root,dfunke/root,agarciamontoro/root,omazapa/root-old,omazapa/root-old,Duraznos/root,beniz/root,evgeny-boger/root,bbockelm/root,smarinac/root,cxx-hep/root-cern,sirinath/root,Y--/root,Dr15Jones/root,root-mirror/root,mattkretz/root,kirbyherm/root-r-tools,BerserkerTroll/root,mkret2/root,tc3t/qoot,jrtomps/root,simonpf/root,root-mirror/root,krafczyk/root,bbockelm/root,kirbyherm/root-r-tools,gbitzes/root,CristinaCristescu/root,omazapa/root-old,mattkretz/root,smarinac/root,gganis/root,mattkretz/root,davidlt/root,zzxuanyuan/root,zzxuanyuan/root,beniz/root,arch1tect0r/root,alexschlueter/cern-root,sirinath/root,krafczyk/root,mkret2/root,bbockelm/root,ffurano/root5,veprbl/root,esakellari/my_root_for_test,sbinet/cxx-root,tc3t/qoot,veprbl/root,CristinaCristescu/root,0x0all/ROOT,arch1tect0r/root,mhuwiler/rootauto,satyarth934/root,davidlt/root,zzxuanyuan/root,0x0all/ROOT,olifre/root,lgiommi/root,simonpf/root,buuck/root,zzxuanyuan/root-compressor-dummy,vukasinmilosevic/root,jrtomps/root,lgiommi/root,nilqed/root,root-mirror/root,lgiommi/root,georgtroska/root,zzxuanyuan/root-compressor-dummy,Y--/root,strykejern/TTreeReader,thomaskeck/root,simonpf/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,omazapa/root,ffurano/root5,abhinavmoudgil95/root,dfunke/root,omazapa/root,Dr15Jones/root,vukasinmilosevic/root,gganis/root,beniz/root,veprbl/root,thomaskeck/root,esakellari/root,CristinaCristescu/root,omazapa/root,perovic/root,zzxuanyuan/root,mattkretz/root,sirinath/root,dfunke/root,mhuwiler/rootauto,krafczyk/root,Y--/root,Duraznos/root,jrtomps/root,lgiommi/root,krafczyk/root,bbockelm/root,lgiommi/root,esakellari/root,olifre/root,evgeny-boger/root,kirbyherm/root-r-tools,bbockelm/root,Y--/root,satyarth934/root,mkret2/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,sbinet/cxx-root,zzxuanyuan/root,mattkretz/root,perovic/root,perovic/root,evgeny-boger/root,sbinet/cxx-root,georgtroska/root,jrtomps/root,0x0all/ROOT,vukasinmilosevic/root,davidlt/root,gbitzes/root,esakellari/root,smarinac/root,arch1tect0r/root,thomaskeck/root,satyarth934/root,abhinavmoudgil95/root,omazapa/root-old,sawenzel/root,esakellari/root,arch1tect0r/root,vukasinmilosevic/root,sirinath/root,mhuwiler/rootauto,CristinaCristescu/root,veprbl/root,nilqed/root,BerserkerTroll/root,abhinavmoudgil95/root,sirinath/root,sawenzel/root,nilqed/root,karies/root,Y--/root,alexschlueter/cern-root,esakellari/root,dfunke/root,beniz/root,evgeny-boger/root,Duraznos/root,strykejern/TTreeReader,mkret2/root,strykejern/TTreeReader,nilqed/root,omazapa/root,ffurano/root5,bbockelm/root,sirinath/root,smarinac/root,omazapa/root-old,beniz/root,BerserkerTroll/root,gbitzes/root,CristinaCristescu/root,esakellari/my_root_for_test,root-mirror/root,olifre/root,arch1tect0r/root,Dr15Jones/root,zzxuanyuan/root,beniz/root,root-mirror/root,dfunke/root,strykejern/TTreeReader,simonpf/root,davidlt/root,mkret2/root,sirinath/root,cxx-hep/root-cern,georgtroska/root,pspe/root,sawenzel/root,pspe/root,sirinath/root,nilqed/root,agarciamontoro/root,beniz/root,mkret2/root,BerserkerTroll/root,vukasinmilosevic/root,zzxuanyuan/root,thomaskeck/root,omazapa/root,pspe/root,veprbl/root,esakellari/root,gganis/root,strykejern/TTreeReader,georgtroska/root,davidlt/root,sawenzel/root,Y--/root,buuck/root,buuck/root,0x0all/ROOT,krafczyk/root,olifre/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,esakellari/my_root_for_test,veprbl/root,satyarth934/root,root-mirror/root,arch1tect0r/root,alexschlueter/cern-root,buuck/root |
73318cb52f57f6d0dbbb1e21541341513da53b86 | topics/search/poj1330.cc | topics/search/poj1330.cc | #include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main () {
return 0;
}
| #include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
#define N 10100
int par[N];
int n;
int l, r;
vector<int> lv, rv;
int main () {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
::memset(par, 0, sizeof par);
lv.clear();
rv.clear();
cin >> n;
int p, c;
for (int j = 0; j < n-1; j++) {
cin >> p >> c;
par[c] = p;
}
cin >> l >> r;
int li = l, ri = r;
while(li != 0) {
lv.push_back(li);
li = par[li];
}
while(ri != 0) {
rv.push_back(ri);
ri = par[ri];
}
reverse(lv.begin(), lv.end());
reverse(rv.begin(), rv.end());
int prefix = 0;
for (size_t i = 0; i < lv.size() && i < rv.size(); i++) {
if (lv[i] == rv[i]) {
prefix = i;
} else {
break;
}
}
printf("%d\n", lv[prefix]);
}
return 0;
}
| add poj1330 | add poj1330
| C++ | mit | LihuaWu/algorithms |
2619d3560e9f43e15d806bf136122934dfa84c13 | topics/search/poj2253.cc | topics/search/poj2253.cc | #include <math.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define N 210
int n;
int a[N][2];
double dis[N][N];
double res[N];
bool v[N];
int main() {
int cnt = 1;
while (1) {
cin >> n;
if (n == 0) break;
for (int i = 0; i < n; i++) {
cin >> a[i][0] >> a[i][1];
}
for (int i = 0; i < n; i++) {
dis[i][i] = 0;
for (int j = i+1; j < n; j++) {
int diff_x = a[i][0] - a[j][0];
int diff_y = a[i][1] - a[j][1];
dis[i][j] = dis[j][i] = sqrt(diff_x * diff_x + diff_y * diff_y);
}
}
for (int i = 0; i < n; i++) {
res[i] = dis[0][i];
v[i] = false;
}
v[0] = true;
for (int i = 0; i < n-1; i++) {
double minV = 99999999.0;
int p = 0;
for (int j = 0; j < n; j++) {
if (!v[j] && res[j] < minV) {
minV = res[j];
p = j;
}
}
v[p] = true;
for (int k = 0; k < n; k++) {
if (!v[k]) {
double maxV = max(res[p], dis[p][k]);
res[k] = min(res[k], maxV);
}
}
}
printf("Scenario #%d\nFrog Distance = %.3f\n\n", cnt++, res[1]);
}
return 0;
}
| //Tag: search dp dijkstra
#include <math.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define N 210
int n;
int a[N][2];
double dis[N][N];
double res[N];
bool v[N];
int main() {
int cnt = 1;
while (1) {
cin >> n;
if (n == 0) break;
for (int i = 0; i < n; i++) {
cin >> a[i][0] >> a[i][1];
}
for (int i = 0; i < n; i++) {
dis[i][i] = 0;
for (int j = i+1; j < n; j++) {
int diff_x = a[i][0] - a[j][0];
int diff_y = a[i][1] - a[j][1];
dis[i][j] = dis[j][i] = sqrt(diff_x * diff_x + diff_y * diff_y);
}
}
for (int i = 0; i < n; i++) {
res[i] = dis[0][i];
v[i] = false;
}
v[0] = true;
for (int i = 0; i < n-1; i++) {
double minV = 99999999.0;
int p = 0;
for (int j = 0; j < n; j++) {
if (!v[j] && res[j] < minV) {
minV = res[j];
p = j;
}
}
v[p] = true;
for (int k = 0; k < n; k++) {
if (!v[k]) {
double maxV = max(res[p], dis[p][k]);
res[k] = min(res[k], maxV);
}
}
}
printf("Scenario #%d\nFrog Distance = %.3f\n\n", cnt++, res[1]);
}
return 0;
}
| add poj2253 | add poj2253
| C++ | mit | LihuaWu/algorithms |
2d047c3428f16138008dff3354638e32eb0dfd0d | src/mem/packet.hh | src/mem/packet.hh | /*
* Copyright (c) 2006 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Ron Dreslinski
* Steve Reinhardt
* Ali Saidi
*/
/**
* @file
* Declaration of the Packet class.
*/
#ifndef __MEM_PACKET_HH__
#define __MEM_PACKET_HH__
#include <cassert>
#include <list>
#include "mem/request.hh"
#include "sim/host.hh"
#include "sim/root.hh"
struct Packet;
typedef Packet *PacketPtr;
typedef uint8_t* PacketDataPtr;
typedef std::list<PacketPtr> PacketList;
//Coherence Flags
#define NACKED_LINE 1 << 0
#define SATISFIED 1 << 1
#define SHARED_LINE 1 << 2
#define CACHE_LINE_FILL 1 << 3
#define COMPRESSED 1 << 4
#define NO_ALLOCATE 1 << 5
#define SNOOP_COMMIT 1 << 6
//for now. @todo fix later
#define NUM_MEM_CMDS 1 << 11
/**
* A Packet is used to encapsulate a transfer between two objects in
* the memory system (e.g., the L1 and L2 cache). (In contrast, a
* single Request travels all the way from the requester to the
* ultimate destination and back, possibly being conveyed by several
* different Packets along the way.)
*/
class Packet
{
public:
/** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */
uint64_t flags;
private:
/** A pointer to the data being transfered. It can be differnt
* sizes at each level of the heirarchy so it belongs in the
* packet, not request. This may or may not be populated when a
* responder recieves the packet. If not populated it memory
* should be allocated.
*/
PacketDataPtr data;
/** Is the data pointer set to a value that shouldn't be freed
* when the packet is destroyed? */
bool staticData;
/** The data pointer points to a value that should be freed when
* the packet is destroyed. */
bool dynamicData;
/** the data pointer points to an array (thus delete [] ) needs to
* be called on it rather than simply delete.*/
bool arrayData;
/** The address of the request. This address could be virtual or
* physical, depending on the system configuration. */
Addr addr;
/** The size of the request or transfer. */
int size;
/** Device address (e.g., bus ID) of the source of the
* transaction. The source is not responsible for setting this
* field; it is set implicitly by the interconnect when the
* packet is first sent. */
short src;
/** Device address (e.g., bus ID) of the destination of the
* transaction. The special value Broadcast indicates that the
* packet should be routed based on its address. This field is
* initialized in the constructor and is thus always valid
* (unlike * addr, size, and src). */
short dest;
/** Are the 'addr' and 'size' fields valid? */
bool addrSizeValid;
/** Is the 'src' field valid? */
bool srcValid;
public:
/** Used to calculate latencies for each packet.*/
Tick time;
/** The time at which the packet will be fully transmitted */
Tick finishTime;
/** The time at which the first chunk of the packet will be transmitted */
Tick firstWordTime;
/** The special destination address indicating that the packet
* should be routed based on its address. */
static const short Broadcast = -1;
/** A pointer to the original request. */
RequestPtr req;
/** A virtual base opaque structure used to hold coherence-related
* state. A specific subclass would be derived from this to
* carry state specific to a particular coherence protocol. */
class CoherenceState {
public:
virtual ~CoherenceState() {}
};
/** This packet's coherence state. Caches should use
* dynamic_cast<> to cast to the state appropriate for the
* system's coherence protocol. */
CoherenceState *coherence;
/** A virtual base opaque structure used to hold state associated
* with the packet but specific to the sending device (e.g., an
* MSHR). A pointer to this state is returned in the packet's
* response so that the sender can quickly look up the state
* needed to process it. A specific subclass would be derived
* from this to carry state specific to a particular sending
* device. */
class SenderState {
public:
virtual ~SenderState() {}
};
/** This packet's sender state. Devices should use dynamic_cast<>
* to cast to the state appropriate to the sender. */
SenderState *senderState;
private:
/** List of command attributes. */
// If you add a new CommandAttribute, make sure to increase NUM_MEM_CMDS
// as well.
enum CommandAttribute
{
IsRead = 1 << 0,
IsWrite = 1 << 1,
IsPrefetch = 1 << 2,
IsInvalidate = 1 << 3,
IsRequest = 1 << 4,
IsResponse = 1 << 5,
NeedsResponse = 1 << 6,
IsSWPrefetch = 1 << 7,
IsHWPrefetch = 1 << 8,
IsUpgrade = 1 << 9,
HasData = 1 << 10
};
public:
/** List of all commands associated with a packet. */
enum Command
{
InvalidCmd = 0,
ReadReq = IsRead | IsRequest | NeedsResponse,
WriteReq = IsWrite | IsRequest | NeedsResponse | HasData,
WriteReqNoAck = IsWrite | IsRequest | HasData,
ReadResp = IsRead | IsResponse | NeedsResponse | HasData,
WriteResp = IsWrite | IsResponse | NeedsResponse,
Writeback = IsWrite | IsRequest | HasData,
SoftPFReq = IsRead | IsRequest | IsSWPrefetch | NeedsResponse,
HardPFReq = IsRead | IsRequest | IsHWPrefetch | NeedsResponse,
SoftPFResp = IsRead | IsResponse | IsSWPrefetch
| NeedsResponse | HasData,
HardPFResp = IsRead | IsResponse | IsHWPrefetch
| NeedsResponse | HasData,
InvalidateReq = IsInvalidate | IsRequest,
WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest
| HasData | NeedsResponse,
WriteInvalidateResp = IsWrite | IsInvalidate | IsRequest | NeedsResponse
| IsResponse,
UpgradeReq = IsInvalidate | IsRequest | IsUpgrade,
ReadExReq = IsRead | IsInvalidate | IsRequest | NeedsResponse,
ReadExResp = IsRead | IsInvalidate | IsResponse
| NeedsResponse | HasData
};
/** Return the string name of the cmd field (for debugging and
* tracing). */
const std::string &cmdString() const;
/** Reutrn the string to a cmd given by idx. */
const std::string &cmdIdxToString(Command idx);
/** Return the index of this command. */
inline int cmdToIndex() const { return (int) cmd; }
/** The command field of the packet. */
Command cmd;
bool isRead() const { return (cmd & IsRead) != 0; }
bool isWrite() const { return (cmd & IsWrite) != 0; }
bool isRequest() const { return (cmd & IsRequest) != 0; }
bool isResponse() const { return (cmd & IsResponse) != 0; }
bool needsResponse() const { return (cmd & NeedsResponse) != 0; }
bool isInvalidate() const { return (cmd & IsInvalidate) != 0; }
bool hasData() const { return (cmd & HasData) != 0; }
bool isCacheFill() const { return (flags & CACHE_LINE_FILL) != 0; }
bool isNoAllocate() const { return (flags & NO_ALLOCATE) != 0; }
bool isCompressed() const { return (flags & COMPRESSED) != 0; }
bool nic_pkt() { assert("Unimplemented\n" && 0); return false; }
/** Possible results of a packet's request. */
enum Result
{
Success,
BadAddress,
Nacked,
Unknown
};
/** The result of this packet's request. */
Result result;
/** Accessor function that returns the source index of the packet. */
short getSrc() const { assert(srcValid); return src; }
void setSrc(short _src) { src = _src; srcValid = true; }
/** Accessor function that returns the destination index of
the packet. */
short getDest() const { return dest; }
void setDest(short _dest) { dest = _dest; }
Addr getAddr() const { assert(addrSizeValid); return addr; }
int getSize() const { assert(addrSizeValid); return size; }
Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }
void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; }
void cmdOverride(Command newCmd) { cmd = newCmd; }
/** Constructor. Note that a Request object must be constructed
* first, but the Requests's physical address and size fields
* need not be valid. The command and destination addresses
* must be supplied. */
Packet(Request *_req, Command _cmd, short _dest)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr), size(_req->size), dest(_dest),
addrSizeValid(_req->validPaddr),
srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Alternate constructor if you are trying to create a packet with
* a request that is for a whole block, not the address from the req.
* this allows for overriding the size/addr of the req.*/
Packet(Request *_req, Command _cmd, short _dest, int _blkSize)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize),
dest(_dest),
addrSizeValid(_req->validPaddr), srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Destructor. */
~Packet()
{ deleteData(); }
/** Reinitialize packet address and size from the associated
* Request object, and reset other fields that may have been
* modified by a previous transaction. Typically called when a
* statically allocated Request/Packet pair is reused for
* multiple transactions. */
void reinitFromRequest() {
assert(req->validPaddr);
addr = req->paddr;
size = req->size;
time = req->time;
addrSizeValid = true;
result = Unknown;
if (dynamicData) {
deleteData();
dynamicData = false;
arrayData = false;
}
}
/** Take a request packet and modify it in place to be suitable
* for returning as a response to that request. Used for timing
* accesses only. For atomic and functional accesses, the
* request packet is always implicitly passed back *without*
* modifying the destination fields, so this function
* should not be called. */
void makeTimingResponse() {
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
if (isRead())
icmd |= HasData;
if (isWrite())
icmd &= ~HasData;
cmd = (Command)icmd;
dest = src;
srcValid = false;
}
/**
* Take a request packet and modify it in place to be suitable for
* returning as a response to that request.
*/
void makeAtomicResponse()
{
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
if (isRead())
icmd |= HasData;
if (isWrite())
icmd &= ~HasData;
cmd = (Command)icmd;
}
/**
* Take a request packet that has been returned as NACKED and
* modify it so that it can be sent out again. Only packets that
* need a response can be NACKED, so verify that that is true.
*/
void
reinitNacked()
{
assert(needsResponse() && result == Nacked);
dest = Broadcast;
result = Unknown;
}
/**
* Set the data pointer to the following value that should not be
* freed.
*/
template <typename T>
void
dataStatic(T *p)
{
if(dynamicData)
dynamicData = false;
data = (PacketDataPtr)p;
staticData = true;
}
/**
* Set the data pointer to a value that should have delete []
* called on it.
*/
template <typename T>
void
dataDynamicArray(T *p)
{
assert(!staticData && !dynamicData);
data = (PacketDataPtr)p;
dynamicData = true;
arrayData = true;
}
/**
* set the data pointer to a value that should have delete called
* on it.
*/
template <typename T>
void
dataDynamic(T *p)
{
assert(!staticData && !dynamicData);
data = (PacketDataPtr)p;
dynamicData = true;
arrayData = false;
}
/** get a pointer to the data ptr. */
template <typename T>
T*
getPtr()
{
assert(staticData || dynamicData);
return (T*)data;
}
/** return the value of what is pointed to in the packet. */
template <typename T>
T get();
/** set the value in the data pointer to v. */
template <typename T>
void set(T v);
/**
* delete the data pointed to in the data pointer. Ok to call to
* matter how data was allocted.
*/
void deleteData();
/** If there isn't data in the packet, allocate some. */
void allocate();
/** Do the packet modify the same addresses. */
bool intersect(PacketPtr p);
};
/** This function given a functional packet and a timing packet either satisfies
* the timing packet, or updates the timing packet to reflect the updated state
* in the timing packet. It returns if the functional packet should continue to
* traverse the memory hierarchy or not.
*/
bool fixPacket(PacketPtr func, PacketPtr timing);
std::ostream & operator<<(std::ostream &o, const Packet &p);
#endif //__MEM_PACKET_HH
| /*
* Copyright (c) 2006 The Regents of The University of Michigan
* 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 holders 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.
*
* Authors: Ron Dreslinski
* Steve Reinhardt
* Ali Saidi
*/
/**
* @file
* Declaration of the Packet class.
*/
#ifndef __MEM_PACKET_HH__
#define __MEM_PACKET_HH__
#include <cassert>
#include <list>
#include "mem/request.hh"
#include "sim/host.hh"
#include "sim/root.hh"
struct Packet;
typedef Packet *PacketPtr;
typedef uint8_t* PacketDataPtr;
typedef std::list<PacketPtr> PacketList;
//Coherence Flags
#define NACKED_LINE (1 << 0)
#define SATISFIED (1 << 1)
#define SHARED_LINE (1 << 2)
#define CACHE_LINE_FILL (1 << 3)
#define COMPRESSED (1 << 4)
#define NO_ALLOCATE (1 << 5)
#define SNOOP_COMMIT (1 << 6)
//for now. @todo fix later
#define NUM_MEM_CMDS (1 << 11)
/**
* A Packet is used to encapsulate a transfer between two objects in
* the memory system (e.g., the L1 and L2 cache). (In contrast, a
* single Request travels all the way from the requester to the
* ultimate destination and back, possibly being conveyed by several
* different Packets along the way.)
*/
class Packet
{
public:
/** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */
uint64_t flags;
private:
/** A pointer to the data being transfered. It can be differnt
* sizes at each level of the heirarchy so it belongs in the
* packet, not request. This may or may not be populated when a
* responder recieves the packet. If not populated it memory
* should be allocated.
*/
PacketDataPtr data;
/** Is the data pointer set to a value that shouldn't be freed
* when the packet is destroyed? */
bool staticData;
/** The data pointer points to a value that should be freed when
* the packet is destroyed. */
bool dynamicData;
/** the data pointer points to an array (thus delete [] ) needs to
* be called on it rather than simply delete.*/
bool arrayData;
/** The address of the request. This address could be virtual or
* physical, depending on the system configuration. */
Addr addr;
/** The size of the request or transfer. */
int size;
/** Device address (e.g., bus ID) of the source of the
* transaction. The source is not responsible for setting this
* field; it is set implicitly by the interconnect when the
* packet is first sent. */
short src;
/** Device address (e.g., bus ID) of the destination of the
* transaction. The special value Broadcast indicates that the
* packet should be routed based on its address. This field is
* initialized in the constructor and is thus always valid
* (unlike * addr, size, and src). */
short dest;
/** Are the 'addr' and 'size' fields valid? */
bool addrSizeValid;
/** Is the 'src' field valid? */
bool srcValid;
public:
/** Used to calculate latencies for each packet.*/
Tick time;
/** The time at which the packet will be fully transmitted */
Tick finishTime;
/** The time at which the first chunk of the packet will be transmitted */
Tick firstWordTime;
/** The special destination address indicating that the packet
* should be routed based on its address. */
static const short Broadcast = -1;
/** A pointer to the original request. */
RequestPtr req;
/** A virtual base opaque structure used to hold coherence-related
* state. A specific subclass would be derived from this to
* carry state specific to a particular coherence protocol. */
class CoherenceState {
public:
virtual ~CoherenceState() {}
};
/** This packet's coherence state. Caches should use
* dynamic_cast<> to cast to the state appropriate for the
* system's coherence protocol. */
CoherenceState *coherence;
/** A virtual base opaque structure used to hold state associated
* with the packet but specific to the sending device (e.g., an
* MSHR). A pointer to this state is returned in the packet's
* response so that the sender can quickly look up the state
* needed to process it. A specific subclass would be derived
* from this to carry state specific to a particular sending
* device. */
class SenderState {
public:
virtual ~SenderState() {}
};
/** This packet's sender state. Devices should use dynamic_cast<>
* to cast to the state appropriate to the sender. */
SenderState *senderState;
private:
/** List of command attributes. */
// If you add a new CommandAttribute, make sure to increase NUM_MEM_CMDS
// as well.
enum CommandAttribute
{
IsRead = 1 << 0,
IsWrite = 1 << 1,
IsPrefetch = 1 << 2,
IsInvalidate = 1 << 3,
IsRequest = 1 << 4,
IsResponse = 1 << 5,
NeedsResponse = 1 << 6,
IsSWPrefetch = 1 << 7,
IsHWPrefetch = 1 << 8,
IsUpgrade = 1 << 9,
HasData = 1 << 10
};
public:
/** List of all commands associated with a packet. */
enum Command
{
InvalidCmd = 0,
ReadReq = IsRead | IsRequest | NeedsResponse,
WriteReq = IsWrite | IsRequest | NeedsResponse | HasData,
WriteReqNoAck = IsWrite | IsRequest | HasData,
ReadResp = IsRead | IsResponse | NeedsResponse | HasData,
WriteResp = IsWrite | IsResponse | NeedsResponse,
Writeback = IsWrite | IsRequest | HasData,
SoftPFReq = IsRead | IsRequest | IsSWPrefetch | NeedsResponse,
HardPFReq = IsRead | IsRequest | IsHWPrefetch | NeedsResponse,
SoftPFResp = IsRead | IsResponse | IsSWPrefetch
| NeedsResponse | HasData,
HardPFResp = IsRead | IsResponse | IsHWPrefetch
| NeedsResponse | HasData,
InvalidateReq = IsInvalidate | IsRequest,
WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest
| HasData | NeedsResponse,
WriteInvalidateResp = IsWrite | IsInvalidate | IsRequest
| NeedsResponse | IsResponse,
UpgradeReq = IsInvalidate | IsRequest | IsUpgrade,
ReadExReq = IsRead | IsInvalidate | IsRequest | NeedsResponse,
ReadExResp = IsRead | IsInvalidate | IsResponse
| NeedsResponse | HasData
};
/** Return the string name of the cmd field (for debugging and
* tracing). */
const std::string &cmdString() const;
/** Reutrn the string to a cmd given by idx. */
const std::string &cmdIdxToString(Command idx);
/** Return the index of this command. */
inline int cmdToIndex() const { return (int) cmd; }
/** The command field of the packet. */
Command cmd;
bool isRead() const { return (cmd & IsRead) != 0; }
bool isWrite() const { return (cmd & IsWrite) != 0; }
bool isRequest() const { return (cmd & IsRequest) != 0; }
bool isResponse() const { return (cmd & IsResponse) != 0; }
bool needsResponse() const { return (cmd & NeedsResponse) != 0; }
bool isInvalidate() const { return (cmd & IsInvalidate) != 0; }
bool hasData() const { return (cmd & HasData) != 0; }
bool isCacheFill() const { return (flags & CACHE_LINE_FILL) != 0; }
bool isNoAllocate() const { return (flags & NO_ALLOCATE) != 0; }
bool isCompressed() const { return (flags & COMPRESSED) != 0; }
bool nic_pkt() { assert("Unimplemented\n" && 0); return false; }
/** Possible results of a packet's request. */
enum Result
{
Success,
BadAddress,
Nacked,
Unknown
};
/** The result of this packet's request. */
Result result;
/** Accessor function that returns the source index of the packet. */
short getSrc() const { assert(srcValid); return src; }
void setSrc(short _src) { src = _src; srcValid = true; }
/** Accessor function that returns the destination index of
the packet. */
short getDest() const { return dest; }
void setDest(short _dest) { dest = _dest; }
Addr getAddr() const { assert(addrSizeValid); return addr; }
int getSize() const { assert(addrSizeValid); return size; }
Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }
void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; }
void cmdOverride(Command newCmd) { cmd = newCmd; }
/** Constructor. Note that a Request object must be constructed
* first, but the Requests's physical address and size fields
* need not be valid. The command and destination addresses
* must be supplied. */
Packet(Request *_req, Command _cmd, short _dest)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr), size(_req->size), dest(_dest),
addrSizeValid(_req->validPaddr),
srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Alternate constructor if you are trying to create a packet with
* a request that is for a whole block, not the address from the req.
* this allows for overriding the size/addr of the req.*/
Packet(Request *_req, Command _cmd, short _dest, int _blkSize)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize),
dest(_dest),
addrSizeValid(_req->validPaddr), srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Destructor. */
~Packet()
{ deleteData(); }
/** Reinitialize packet address and size from the associated
* Request object, and reset other fields that may have been
* modified by a previous transaction. Typically called when a
* statically allocated Request/Packet pair is reused for
* multiple transactions. */
void reinitFromRequest() {
assert(req->validPaddr);
addr = req->paddr;
size = req->size;
time = req->time;
addrSizeValid = true;
result = Unknown;
if (dynamicData) {
deleteData();
dynamicData = false;
arrayData = false;
}
}
/** Take a request packet and modify it in place to be suitable
* for returning as a response to that request. Used for timing
* accesses only. For atomic and functional accesses, the
* request packet is always implicitly passed back *without*
* modifying the destination fields, so this function
* should not be called. */
void makeTimingResponse() {
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
if (isRead())
icmd |= HasData;
if (isWrite())
icmd &= ~HasData;
cmd = (Command)icmd;
dest = src;
srcValid = false;
}
/**
* Take a request packet and modify it in place to be suitable for
* returning as a response to that request.
*/
void makeAtomicResponse()
{
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
if (isRead())
icmd |= HasData;
if (isWrite())
icmd &= ~HasData;
cmd = (Command)icmd;
}
/**
* Take a request packet that has been returned as NACKED and
* modify it so that it can be sent out again. Only packets that
* need a response can be NACKED, so verify that that is true.
*/
void
reinitNacked()
{
assert(needsResponse() && result == Nacked);
dest = Broadcast;
result = Unknown;
}
/**
* Set the data pointer to the following value that should not be
* freed.
*/
template <typename T>
void
dataStatic(T *p)
{
if(dynamicData)
dynamicData = false;
data = (PacketDataPtr)p;
staticData = true;
}
/**
* Set the data pointer to a value that should have delete []
* called on it.
*/
template <typename T>
void
dataDynamicArray(T *p)
{
assert(!staticData && !dynamicData);
data = (PacketDataPtr)p;
dynamicData = true;
arrayData = true;
}
/**
* set the data pointer to a value that should have delete called
* on it.
*/
template <typename T>
void
dataDynamic(T *p)
{
assert(!staticData && !dynamicData);
data = (PacketDataPtr)p;
dynamicData = true;
arrayData = false;
}
/** get a pointer to the data ptr. */
template <typename T>
T*
getPtr()
{
assert(staticData || dynamicData);
return (T*)data;
}
/** return the value of what is pointed to in the packet. */
template <typename T>
T get();
/** set the value in the data pointer to v. */
template <typename T>
void set(T v);
/**
* delete the data pointed to in the data pointer. Ok to call to
* matter how data was allocted.
*/
void deleteData();
/** If there isn't data in the packet, allocate some. */
void allocate();
/** Do the packet modify the same addresses. */
bool intersect(PacketPtr p);
};
/** This function given a functional packet and a timing packet either satisfies
* the timing packet, or updates the timing packet to reflect the updated state
* in the timing packet. It returns if the functional packet should continue to
* traverse the memory hierarchy or not.
*/
bool fixPacket(PacketPtr func, PacketPtr timing);
std::ostream & operator<<(std::ostream &o, const Packet &p);
#endif //__MEM_PACKET_HH
| Fix formatting that got screwed up when tabs were removed. | Fix formatting that got screwed up when tabs were removed.
| C++ | bsd-3-clause | vovojh/gem5,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,hoangt/tpzsimul.gem5,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,hoangt/tpzsimul.gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,hoangt/tpzsimul.gem5,vovojh/gem5,vovojh/gem5,hoangt/tpzsimul.gem5,pombredanne/http-repo.gem5.org-gem5- |
284de5bc0e777c792c06b8d6ca0d35642beb7269 | include/BinaryTree.hpp | include/BinaryTree.hpp | #include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>* root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
void _deleteElements(Node<T>*);
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
Node<T>*root_();
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
void output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template <typename T>
void BinaryTree<T>::_deleteElements(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
_deleteElements(temp->left);
_deleteElements(temp->right);
delete node;
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
return;
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
if (!temp.root)
throw "error";
show(ost, temp.root, 0);
return ost;
}
| #include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>* root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
void output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template <typename T>
void BinaryTree<T>::_deleteElements(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
_deleteElements(temp->left);
_deleteElements(temp->right);
delete node;
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
return;
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
if (!temp.root)
throw "error";
show(ost, temp.root, 0);
return ost;
}
| Update BinaryTree.hpp | Update BinaryTree.hpp | C++ | mit | rtv22/BinaryTree_S |
a4bd2e6998dbec3e66072ca4827cb75adeb74e3c | include/BinaryTree.hpp | include/BinaryTree.hpp | #include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>* root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
Node<T>*root_();
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
void output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
return;
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& bst)
{
if (!bst.root)
throw "error";
show(ost, bst.root, 0);
return ost;
}
| #include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
std::ostream& operator<<(std::ostream&, const BinarySearchTree<T>&);
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>* root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
Node<T>*root_();
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
void output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
return;
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& bst)
{
if (!bst.root)
throw "error";
show(ost, bst.root, 0);
return ost;
}
| Update BinaryTree.hpp | Update BinaryTree.hpp | C++ | mit | rtv22/BinaryTree_S |
2fdf3d23e6431c0d4f300e62d87977b532967162 | src/PefCMD.cpp | src/PefCMD.cpp | //
// PefCMD.cpp
// J3NI
//
// Created by Neil on 2014-03-14.
// Copyright (c) 2014 Neil. All rights reserved.
//
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <PefCMD.h>
#include <IpmiCommandDefines.h>
using namespace IpmiCommandDefines;
extern std::ofstream log_file;
GetPefCapabCMD::GetPefCapabCMD() : pefCapab_(0x0E)
{
}
void GetPefCapabCMD::setPefCapab(unsigned char pefCap)
{
pefCapab_ = pefCap;
}
unsigned char GetPefCapabCMD::getPefCapab() const
{
return pefCapab_;
}
int GetPefCapabCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Get PEF Capabilities Command" << std::endl;
resp[0] = COMP_CODE_OK;
resp[1] = 0x51;
resp[2] = pefCapab_;
resp[3] = 0x00;
return 4;
}
ArmPefPostponeTimerCMD::ArmPefPostponeTimerCMD() : countdownDuration(0)
{
setTime = time(0);
}
int ArmPefPostponeTimerCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Arm PEF Postpone Timer Command" << std::endl;
time_t t = time(0);
if(req[0] == 0xFE || req[0] == 0x00)
{
countdownDuration = 0;
}
else if(req[0] != 0xFF)
{
countdownDuration = req[0];
setTime = t;
}
unsigned char countdownValue = countdownDuration;
if(req[0] == 0xFF)
{
countdownValue = (t - setTime) % countdownDuration;
}
resp[0] = COMP_CODE_OK;
resp[1] = countdownValue;
return 2;
}
GetPefConfigParamCMD::GetPefConfigParamCMD()
{
unsigned char defaultInProgress = 0x00;
pefConfigMap[0x00] = new ConfigParam(1, &defaultInProgress);
unsigned char defaultControl = 0x01;
pefConfigMap[0x01] = new ConfigParam(1, &defaultControl);
unsigned char defaultActionControl = 0x0E;
pefConfigMap[0x02] = new ConfigParam(1, &defaultActionControl);
unsigned char defaultStartupDelay = 0x00;
pefConfigMap[0x03] = new ConfigParam(1, &defaultStartupDelay);
unsigned char defaultAlertStartupDelay = 0x00;
pefConfigMap[0x04] = new ConfigParam(1, &defaultAlertStartupDelay);
unsigned char eventFilters = 0x00;
pefConfigMap[0x05] = new ConfigParam(1, &eventFilters, true);
}
unsigned char GetPefConfigParamCMD::setMap(unsigned char param,
const unsigned char* paramValue,
int length)
{
unsigned char paramSelector = paramValue[0] & 0x7F;
ConfigParamMap::iterator it = pefConfigMap.find(paramSelector);
if(it == pefConfigMap.end())
{
return PARAM_UNSUPPORTED;
}
ConfigParam* configParam = it->second;
if(configParam->readOnly)
{
return WRITE_TO_READ_ONLY;
}
if((param == 0x00) && (configParam->data[0] != 0x00))
{
return SET_IN_PROGRESS_FAIL;
}
if(configParam->length != length)
{
delete[] configParam->data;
configParam->data = new unsigned char[length];
}
for(int i = 0; i < configParam->length; i++)
{
configParam->data[i] = paramValue[i];
}
return COMP_CODE_OK;
}
int GetPefConfigParamCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Get PEF Configuration Parameters Command" << std::endl;
resp[0] = COMP_CODE_OK;
resp[1] = 0x11;
if((req[0] & 0x80) == 0x80)
return 2;
unsigned char paramSelector = req[0] & 0x7F;
ConfigParamMap::iterator it = pefConfigMap.find(paramSelector);
if(it == pefConfigMap.end())
{
resp[0] = PARAM_UNSUPPORTED;
return 2;
}
ConfigParam* param = it->second;
int i = 0;
for(; i < param->length; i++)
{
resp[2 + i] = param->data[i];
}
return 2 + i;
}
SetPefConfigParamCMD::SetPefConfigParamCMD(GetPefConfigParamCMD* getPefConfigParam)
{
getPefConfigParam_ = getPefConfigParam;
}
int SetPefConfigParamCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Set PEF Configuration Parameters Command" << std::endl;
unsigned char paramSelector = req[0] & 0x7F;
resp[0] = getPefConfigParam_->setMap(paramSelector,
req + 1, reqLength - 1);
return 1;
}
GetLastProcEventIdCMD::GetLastProcEventIdCMD()
: mostRecentId_(NULL), bmcRecordId_(0x0000), swRecordId_(0x0000)
{
timestamp_ = time(0);
mostRecentId_ = &swRecordId_;
}
void GetLastProcEventIdCMD::setBmcRecordId(const unsigned char* recordId, int length)
{
if(length < 2) return;
bmcRecordId_ = recordId[0] | (recordId[1] << 8);
mostRecentId_ = &bmcRecordId_;
timestamp_ = time(0);
}
void GetLastProcEventIdCMD::setSwRecordId(const unsigned char* recordId, int length)
{
if(length < 2) return;
swRecordId_ = recordId[0] | (recordId[1] << 8);
mostRecentId_ = &swRecordId_;
timestamp_ = time(0);
}
uint16_t GetLastProcEventIdCMD::getBmcRecordId() const
{
return bmcRecordId_;
}
uint16_t GetLastProcEventIdCMD::getSwRecordId() const
{
return swRecordId_;
}
int GetLastProcEventIdCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Get Last Proccessed Event Id Command" << std::endl;
resp[0] = COMP_CODE_OK;
resp[1] = timestamp_ & 0x000000FF;
resp[2] = (timestamp_ & 0x0000FF00) >> 8;
resp[3] = (timestamp_ & 0x00FF0000) >> 16;
resp[4] = (timestamp_ & 0xFF000000) >> 24;
resp[5] = *mostRecentId_ & 0x00FF ;
resp[6] = (*mostRecentId_ & 0xFF00) >> 8;
resp[7] = swRecordId_ & 0x00FF ;
resp[8] = (swRecordId_ & 0xFF00) >> 8;
resp[9] = swRecordId_ & 0x00FF ;
resp[10] = (swRecordId_ & 0xFF00) >> 8;
return 11;
}
SetLastProcEventIdCMD::SetLastProcEventIdCMD(GetLastProcEventIdCMD* lastProcEventCmd)
{
lastProcEventCmd_ = lastProcEventCmd;
}
int SetLastProcEventIdCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Set Last Proccessed Event Id Command" << std::endl;
resp[0] = COMP_CODE_OK;
if (reqLength >= 3)
{
if((req[0] & 0x01) == 0x01)
lastProcEventCmd_->setBmcRecordId(req + 1, 2);
else
lastProcEventCmd_->setSwRecordId(req + 1, 2);
}
return 1;
}
| //
// PefCMD.cpp
// J3NI
//
// Created by Neil on 2014-03-14.
// Copyright (c) 2014 Neil. All rights reserved.
//
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <PefCMD.h>
#include <IpmiCommandDefines.h>
using namespace IpmiCommandDefines;
extern std::ofstream log_file;
GetPefCapabCMD::GetPefCapabCMD() : pefCapab_(0x0E)
{
}
void GetPefCapabCMD::setPefCapab(unsigned char pefCap)
{
pefCapab_ = pefCap;
}
unsigned char GetPefCapabCMD::getPefCapab() const
{
return pefCapab_;
}
int GetPefCapabCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Get PEF Capabilities Command" << std::endl;
resp[0] = COMP_CODE_OK;
resp[1] = 0x51;
resp[2] = pefCapab_;
resp[3] = 0x00;
return 4;
}
ArmPefPostponeTimerCMD::ArmPefPostponeTimerCMD() : countdownDuration(0)
{
setTime = time(0);
}
int ArmPefPostponeTimerCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Arm PEF Postpone Timer Command" << std::endl;
time_t t = time(0);
if(req[0] == 0xFE || req[0] == 0x00)
{
countdownDuration = 0;
}
else if(req[0] != 0xFF)
{
countdownDuration = req[0];
setTime = t;
}
unsigned char countdownValue = countdownDuration;
if(req[0] == 0xFF)
{
countdownValue = (t - setTime) % countdownDuration;
}
resp[0] = COMP_CODE_OK;
resp[1] = countdownValue;
return 2;
}
GetPefConfigParamCMD::GetPefConfigParamCMD()
{
unsigned char defaultInProgress = 0x00;
pefConfigMap[0x00] = new ConfigParam(1, &defaultInProgress);
unsigned char defaultControl = 0x01;
pefConfigMap[0x01] = new ConfigParam(1, &defaultControl);
unsigned char defaultActionControl = 0x0E;
pefConfigMap[0x02] = new ConfigParam(1, &defaultActionControl);
unsigned char defaultStartupDelay = 0x00;
pefConfigMap[0x03] = new ConfigParam(1, &defaultStartupDelay);
unsigned char defaultAlertStartupDelay = 0x00;
pefConfigMap[0x04] = new ConfigParam(1, &defaultAlertStartupDelay);
unsigned char eventFilters = 0x00;
pefConfigMap[0x05] = new ConfigParam(1, &eventFilters, true);
unsigned char alertPolicyNum = 0x00;
pefConfigMap[0x08] = new ConfigParam(1, &alertPolicyNum, true);
// Generate or use default GUID?
//pefConfigMap[0x0A] = new ConfigParam[]
}
unsigned char GetPefConfigParamCMD::setMap(unsigned char param,
const unsigned char* paramValue,
int length)
{
unsigned char paramSelector = paramValue[0] & 0x7F;
ConfigParamMap::iterator it = pefConfigMap.find(paramSelector);
if(it == pefConfigMap.end())
{
return PARAM_UNSUPPORTED;
}
ConfigParam* configParam = it->second;
if(configParam->readOnly)
{
return WRITE_TO_READ_ONLY;
}
if((param == 0x00) && (configParam->data[0] != 0x00))
{
return SET_IN_PROGRESS_FAIL;
}
if(configParam->length != length)
{
delete[] configParam->data;
configParam->data = new unsigned char[length];
}
for(int i = 0; i < configParam->length; i++)
{
configParam->data[i] = paramValue[i];
}
return COMP_CODE_OK;
}
int GetPefConfigParamCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Get PEF Configuration Parameters Command" << std::endl;
resp[0] = COMP_CODE_OK;
resp[1] = 0x11;
if((req[0] & 0x80) == 0x80)
return 2;
unsigned char paramSelector = req[0] & 0x7F;
ConfigParamMap::iterator it = pefConfigMap.find(paramSelector);
if(it == pefConfigMap.end())
{
resp[0] = PARAM_UNSUPPORTED;
return 2;
}
ConfigParam* param = it->second;
int i = 0;
for(; i < param->length; i++)
{
resp[2 + i] = param->data[i];
}
return 2 + i;
}
SetPefConfigParamCMD::SetPefConfigParamCMD(GetPefConfigParamCMD* getPefConfigParam)
{
getPefConfigParam_ = getPefConfigParam;
}
int SetPefConfigParamCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Set PEF Configuration Parameters Command" << std::endl;
unsigned char paramSelector = req[0] & 0x7F;
resp[0] = getPefConfigParam_->setMap(paramSelector,
req + 1, reqLength - 1);
return 1;
}
GetLastProcEventIdCMD::GetLastProcEventIdCMD()
: mostRecentId_(NULL), bmcRecordId_(0x0000), swRecordId_(0x0000)
{
timestamp_ = time(0);
mostRecentId_ = &swRecordId_;
}
void GetLastProcEventIdCMD::setBmcRecordId(const unsigned char* recordId, int length)
{
if(length < 2) return;
bmcRecordId_ = recordId[0] | (recordId[1] << 8);
mostRecentId_ = &bmcRecordId_;
timestamp_ = time(0);
}
void GetLastProcEventIdCMD::setSwRecordId(const unsigned char* recordId, int length)
{
if(length < 2) return;
swRecordId_ = recordId[0] | (recordId[1] << 8);
mostRecentId_ = &swRecordId_;
timestamp_ = time(0);
}
uint16_t GetLastProcEventIdCMD::getBmcRecordId() const
{
return bmcRecordId_;
}
uint16_t GetLastProcEventIdCMD::getSwRecordId() const
{
return swRecordId_;
}
int GetLastProcEventIdCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Get Last Proccessed Event Id Command" << std::endl;
resp[0] = COMP_CODE_OK;
resp[1] = timestamp_ & 0x000000FF;
resp[2] = (timestamp_ & 0x0000FF00) >> 8;
resp[3] = (timestamp_ & 0x00FF0000) >> 16;
resp[4] = (timestamp_ & 0xFF000000) >> 24;
resp[5] = *mostRecentId_ & 0x00FF ;
resp[6] = (*mostRecentId_ & 0xFF00) >> 8;
resp[7] = swRecordId_ & 0x00FF ;
resp[8] = (swRecordId_ & 0xFF00) >> 8;
resp[9] = swRecordId_ & 0x00FF ;
resp[10] = (swRecordId_ & 0xFF00) >> 8;
return 11;
}
SetLastProcEventIdCMD::SetLastProcEventIdCMD(GetLastProcEventIdCMD* lastProcEventCmd)
{
lastProcEventCmd_ = lastProcEventCmd;
}
int SetLastProcEventIdCMD::process(const unsigned char* req, int reqLength,
unsigned char* resp)
{
log_file << "Set Last Proccessed Event Id Command" << std::endl;
resp[0] = COMP_CODE_OK;
if (reqLength >= 3)
{
if((req[0] & 0x01) == 0x01)
lastProcEventCmd_->setBmcRecordId(req + 1, 2);
else
lastProcEventCmd_->setSwRecordId(req + 1, 2);
}
return 1;
}
| Add one more supported parameter to PEF | Add one more supported parameter to PEF
| C++ | bsd-3-clause | J3NI/J3NI,J3NI/J3NI,J3NI/J3NI |
50c82fcdfbc17bb13d8c2cfd7b63943d68f5c46c | src/mitm/mitm.hpp | src/mitm/mitm.hpp | /* Copyright (C) 2015 INRA
*
* 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 FR_INRA_MITM_MITM_HPP
#define FR_INRA_MITM_MITM_HPP
#if defined _WIN32 || defined __CYGWIN__
#define MITM_HELPER_DLL_IMPORT __declspec(dllimport)
#define MITM_HELPER_DLL_EXPORT __declspec(dllexport)
#define MITM_HELPER_DLL_LOCAL
#else
#if __GNUC__ >= 4
#define MITM_HELPER_DLL_IMPORT __attribute__ ((visibility ("default")))
#define MITM_HELPER_DLL_EXPORT __attribute__ ((visibility ("default")))
#define MITM_HELPER_DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define MITM_HELPER_DLL_IMPORT
#define MITM_HELPER_DLL_EXPORT
#define MITM_HELPER_DLL_LOCAL
#endif
#endif
#ifdef MITM_DLL
#ifdef libmitm_EXPORTS
#define MITM_API MITM_HELPER_DLL_EXPORT
#else
#define MITM_API MITM_HELPER_DLL_IMPORT
#endif
#define MITM_LOCAL MITM_HELPER_DLL_LOCAL
#define MITM_MODULE MITM_HELPER_DLL_EXPORT
#else
#define MITM_API
#define MITM_LOCAL
#define MITM_MODULE MITM_HELPER_DLL_EXPORT
#endif
#include <stdexcept>
#include <istream>
#include <ostream>
#include <string>
#include <vector>
namespace mitm {
class MITM_API io_error : public std::runtime_error
{
public:
io_error(const char *message, int line);
virtual ~io_error() throw();
std::string message() const;
int line() const;
private:
std::string m_message;
int m_line;
};
#ifdef MITM_REAL_TYPE
typedef MITM_REAL_TYPE real
#else
typedef float real;
#endif
typedef std::ptrdiff_t index;
class MITM_API SimpleState
{
public:
/** Try to initialize the constraints matrix @e A, equalities and costs
* vectors @b and @c.
*
* return 0 if success otherwise -EDOM if m and n are bad or -ENOMEM if
* not enough memory.
*/
int init(index m, index n) noexcept;
index constraints() const noexcept;
index variables() const noexcept;
std::vector<bool> a;
std::vector<int> b;
std::vector<real> c;
};
class MITM_API NegativeCoefficient
{
public:
struct b_bounds {
real lower_bound;
real upper_bound;
};
void init(index m, index n)
{
try {
a.resize(m * n);
b.resize(m);
c.resize(n);
} catch(const std::bad_alloc& e) {
std::vector<int>().swap(a);
std::vector<b_bounds>().swap(b);
std::vector<real>().swap(c);
throw std::runtime_error("not enough memory");
}
}
/// Constraints matrix allows -1, 0 or +1 values.
std::vector<int> a;
/// The lower bound, value and upper bound for the equality or inequality
/// constraint.
std::vector<b_bounds> b;
/// The cost vector.
std::vector<real> c;
};
struct result
{
/// The solution vector.
std::vector<bool> x;
/// Number of loop necessary.
index loop;
};
MITM_API std::istream &operator>>(std::istream &is, SimpleState &s);
MITM_API result
heuristic_algorithm(const SimpleState &s, index limit,
real kappa, real delta, real theta,
const std::string &impl);
MITM_API result
heuristic_algorithm(const NegativeCoefficient& s, index limit,
real kappa, real delta, real theta,
const std::string &impl);
inline int
SimpleState::init(index m, index n) noexcept
{
if (m <= 0 or n <= 0)
return -EDOM;
try {
a.resize(m * n);
b.resize(m);
c.resize(n);
} catch(const std::bad_alloc& e) {
std::vector<bool>().swap(a);
std::vector<int>().swap(b);
std::vector<real>().swap(c);
return -ENOMEM;
}
return 0;
}
inline index
SimpleState::constraints() const noexcept
{
return static_cast<index>(b.size());
}
inline index
SimpleState::variables() const noexcept
{
return static_cast<index>(c.size());
}
}
#endif
| /* Copyright (C) 2015 INRA
*
* 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 FR_INRA_MITM_MITM_HPP
#define FR_INRA_MITM_MITM_HPP
#if defined _WIN32 || defined __CYGWIN__
#define MITM_HELPER_DLL_IMPORT __declspec(dllimport)
#define MITM_HELPER_DLL_EXPORT __declspec(dllexport)
#define MITM_HELPER_DLL_LOCAL
#else
#if __GNUC__ >= 4
#define MITM_HELPER_DLL_IMPORT __attribute__ ((visibility ("default")))
#define MITM_HELPER_DLL_EXPORT __attribute__ ((visibility ("default")))
#define MITM_HELPER_DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define MITM_HELPER_DLL_IMPORT
#define MITM_HELPER_DLL_EXPORT
#define MITM_HELPER_DLL_LOCAL
#endif
#endif
#ifdef MITM_DLL
#ifdef libmitm_EXPORTS
#define MITM_API MITM_HELPER_DLL_EXPORT
#else
#define MITM_API MITM_HELPER_DLL_IMPORT
#endif
#define MITM_LOCAL MITM_HELPER_DLL_LOCAL
#define MITM_MODULE MITM_HELPER_DLL_EXPORT
#else
#define MITM_API
#define MITM_LOCAL
#define MITM_MODULE MITM_HELPER_DLL_EXPORT
#endif
#include <stdexcept>
#include <istream>
#include <ostream>
#include <string>
#include <vector>
namespace mitm {
class MITM_API io_error : public std::runtime_error
{
public:
io_error(const char *message, int line);
virtual ~io_error() throw();
std::string message() const;
int line() const;
private:
std::string m_message;
int m_line;
};
#ifdef MITM_REAL_TYPE
typedef MITM_REAL_TYPE real
#else
typedef float real;
#endif
typedef std::ptrdiff_t index;
class MITM_API SimpleState
{
public:
/** Try to initialize the constraints matrix @e A, equalities and costs
* vectors @b and @c.
*
* return 0 if success otherwise -EDOM if m and n are bad or -ENOMEM if
* not enough memory.
*/
int init(index m, index n) noexcept;
index constraints() const noexcept;
index variables() const noexcept;
std::vector<bool> a;
std::vector<int> b;
std::vector<real> c;
std::size_t size() const noexcept
{
return a.size() * sizeof(bool)
+ b.size() * sizeof(int)
+ c.size() * sizeof(real);
}
template <class T>
friend T& operator<<(T& os, const SimpleState& s)
{
const index m = s.constraints();
const index n = s.variables();
os << "A:\n";
for (index i = 0; i != m; ++i) {
for (index j = 0; j != n; ++j)
os << s.a[i * m + j] << ' ';
os << '\n';
}
os << "b:\n";
for (index i = 0; i != m; ++i)
os << s.b[i] << ' ';
os << '\n';
os << "c:\n";
for (index i = 0; i != n; ++i)
os << s.c[i] << ' ';
os << '\n';
}
};
class MITM_API NegativeCoefficient
{
public:
struct b_bounds {
real lower_bound;
real upper_bound;
};
void init(index m, index n)
{
try {
a.resize(m * n);
b.resize(m);
c.resize(n);
} catch(const std::bad_alloc& e) {
std::vector<int>().swap(a);
std::vector<b_bounds>().swap(b);
std::vector<real>().swap(c);
throw std::runtime_error("not enough memory");
}
}
/// Constraints matrix allows -1, 0 or +1 values.
std::vector<int> a;
/// The lower bound, value and upper bound for the equality or inequality
/// constraint.
std::vector<b_bounds> b;
/// The cost vector.
std::vector<real> c;
};
struct result
{
/// The solution vector.
std::vector<bool> x;
/// Number of loop necessary.
index loop;
};
MITM_API std::istream &operator>>(std::istream &is, SimpleState &s);
MITM_API result
heuristic_algorithm(const SimpleState &s, index limit,
real kappa, real delta, real theta,
const std::string &impl);
MITM_API result
heuristic_algorithm(const NegativeCoefficient& s, index limit,
real kappa, real delta, real theta,
const std::string &impl);
inline int
SimpleState::init(index m, index n) noexcept
{
if (m <= 0 or n <= 0)
return -EDOM;
try {
a.resize(m * n);
b.resize(m);
c.resize(n);
} catch(const std::bad_alloc& e) {
std::vector<bool>().swap(a);
std::vector<int>().swap(b);
std::vector<real>().swap(c);
return -ENOMEM;
}
return 0;
}
inline index
SimpleState::constraints() const noexcept
{
return static_cast<index>(b.size());
}
inline index
SimpleState::variables() const noexcept
{
return static_cast<index>(c.size());
}
}
#endif
| add useful functions | mitm: add useful functions
| C++ | mit | quesnel/mitm |
4628f3f2a03e23b08d07d69039de9485172bc4ce | api/mraa/uart.hpp | api/mraa/uart.hpp | /*
* Author: Brendan Le Foll <[email protected]>
* Contributions: Jon Trulson <[email protected]>
* Contributions: Thomas Ingleby <[email protected]>
* Copyright (c) 2014 - 2015 Intel Corporation.
*
* 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.
*/
#pragma once
#include "uart.h"
#include <stdexcept>
#include <cstring>
namespace mraa
{
/**
* @brief API to UART (enabling only)
*
* This file defines the UART interface for libmraa
*/
class Uart
{
public:
/**
* Uart Constructor, takes a pin number which will map directly to the
* linux uart number, this 'enables' the uart, nothing more
*
* @param uart the index of the uart set to use
*/
Uart(int uart)
{
m_uart = mraa_uart_init(uart);
if (m_uart == NULL) {
throw std::invalid_argument("Error initialising UART");
}
}
/**
* Uart Constructor, takes a string to the path of the serial
* interface that is needed.
*
* @param uart the index of the uart set to use
*/
Uart(std::string path)
{
m_uart = mraa_uart_init_raw(path.c_str());
if (m_uart == NULL) {
throw std::invalid_argument("Error initialising UART");
}
}
/**
* Uart destructor
*/
~Uart()
{
mraa_uart_stop(m_uart);
}
/**
* Get string with tty device path within Linux
* For example. Could point to "/dev/ttyS0"
*
* @return char pointer of device path
*/
std::string
getDevicePath()
{
std::string ret_val(mraa_uart_get_dev_path(m_uart));
return ret_val;
}
/**
* Read bytes from the device into a buffer
*
* @param data buffer pointer
* @param length maximum size of buffer
* @return string of data
*/
std::string
read(int length)
{
char* data = (char*) malloc(sizeof(char) * length);
int v = mraa_uart_read(m_uart, data, (size_t) length);
char* out = (char*) malloc(sizeof(char) * v);
strncpy(out, data, v);
std::string ret(out);
free(data);
free(out);
return ret;
}
/**
* Write bytes in buffer to a device
*
* @param data buffer pointer
* @param length maximum size of buffer
* @return the number of bytes written, or -1 if an error occurred
*/
int
write(std::string data)
{
// this is data.length() not +1 because we want to avoid the '\0' char
return mraa_uart_write(m_uart, data.c_str(), (data.length()));
}
/**
* Check to see if data is available on the device for reading
*
* @param millis number of milliseconds to wait, or 0 to return immediately
* @return true if there is data available to read, false otherwise
*/
bool
dataAvailable(unsigned int millis = 0)
{
if (mraa_uart_data_available(m_uart, millis))
return true;
else
return false;
}
/**
* Flush the outbound data.
* Blocks until complete.
*
* @return Result of operation
*/
mraa_result_t
flush()
{
return mraa_uart_flush(m_uart);
}
/**
* Set the baudrate.
* Takes an int and will attempt to decide what baudrate is
* to be used on the UART hardware.
*
* @param baud unsigned int of baudrate i.e. 9600
* @return Result of operation
*/
mraa_result_t
setBaudRate(unsigned int baud)
{
return mraa_uart_set_baudrate(m_uart, baud);
}
/**
* Set the transfer mode
* For example setting the mode to 8N1 would be
* "dev.setMode(8,MRAA_UART_PARITY_NONE , 1)"
*
* @param bytesize data bits
* @param parity Parity bit setting
* @param stopbits stop bits
* @return Result of operation
*/
mraa_result_t
setMode(int bytesize, mraa_uart_parity_t parity, int stopbits)
{
return mraa_uart_set_mode(m_uart, bytesize, parity, stopbits);
}
/**
* Set the flowcontrol
*
* @param xonxoff XON/XOFF Software flow control.
* @param rtscts RTS/CTS out of band hardware flow control
* @return Result of operation
*/
mraa_result_t
setFlowcontrol(bool xonxoff, bool rtscts)
{
return mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);
}
/**
* Set the timeout for read and write operations
* <= 0 will disable that timeout
*
* @param read read timeout
* @param write write timeout
* @param interchar inbetween char timeout
* @return Result of operation
*/
mraa_result_t
setTimeout(int read, int write, int interchar)
{
return mraa_uart_set_timeout(m_uart, read, write, interchar);
}
private:
mraa_uart_context m_uart;
};
}
| /*
* Author: Brendan Le Foll <[email protected]>
* Contributions: Jon Trulson <[email protected]>
* Contributions: Thomas Ingleby <[email protected]>
* Copyright (c) 2014 - 2015 Intel Corporation.
*
* 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.
*/
#pragma once
#include "uart.h"
#include <stdexcept>
#include <cstring>
namespace mraa
{
/**
* @brief API to UART (enabling only)
*
* This file defines the UART interface for libmraa
*/
class Uart
{
public:
/**
* Uart Constructor, takes a pin number which will map directly to the
* linux uart number, this 'enables' the uart, nothing more
*
* @param uart the index of the uart set to use
*/
Uart(int uart)
{
m_uart = mraa_uart_init(uart);
if (m_uart == NULL) {
throw std::invalid_argument("Error initialising UART");
}
}
/**
* Uart Constructor, takes a string to the path of the serial
* interface that is needed.
*
* @param uart the index of the uart set to use
*/
Uart(std::string path)
{
m_uart = mraa_uart_init_raw(path.c_str());
if (m_uart == NULL) {
throw std::invalid_argument("Error initialising UART");
}
}
/**
* Uart destructor
*/
~Uart()
{
mraa_uart_stop(m_uart);
}
/**
* Get string with tty device path within Linux
* For example. Could point to "/dev/ttyS0"
*
* @return char pointer of device path
*/
std::string
getDevicePath()
{
std::string ret_val(mraa_uart_get_dev_path(m_uart));
return ret_val;
}
/**
* Read bytes from the device into a buffer
*
* @param data buffer pointer
* @param length maximum size of buffer
* @return string of data
*/
std::string
read(int length)
{
char* data = (char*) malloc(sizeof(char) * length);
int v = mraa_uart_read(m_uart, data, (size_t) length);
std::string ret(data, v);
free(data);
return ret;
}
/**
* Write bytes in buffer to a device
*
* @param data buffer pointer
* @param length maximum size of buffer
* @return the number of bytes written, or -1 if an error occurred
*/
int
write(std::string data)
{
// this is data.length() not +1 because we want to avoid the '\0' char
return mraa_uart_write(m_uart, data.c_str(), (data.length()));
}
/**
* Check to see if data is available on the device for reading
*
* @param millis number of milliseconds to wait, or 0 to return immediately
* @return true if there is data available to read, false otherwise
*/
bool
dataAvailable(unsigned int millis = 0)
{
if (mraa_uart_data_available(m_uart, millis))
return true;
else
return false;
}
/**
* Flush the outbound data.
* Blocks until complete.
*
* @return Result of operation
*/
mraa_result_t
flush()
{
return mraa_uart_flush(m_uart);
}
/**
* Set the baudrate.
* Takes an int and will attempt to decide what baudrate is
* to be used on the UART hardware.
*
* @param baud unsigned int of baudrate i.e. 9600
* @return Result of operation
*/
mraa_result_t
setBaudRate(unsigned int baud)
{
return mraa_uart_set_baudrate(m_uart, baud);
}
/**
* Set the transfer mode
* For example setting the mode to 8N1 would be
* "dev.setMode(8,MRAA_UART_PARITY_NONE , 1)"
*
* @param bytesize data bits
* @param parity Parity bit setting
* @param stopbits stop bits
* @return Result of operation
*/
mraa_result_t
setMode(int bytesize, mraa_uart_parity_t parity, int stopbits)
{
return mraa_uart_set_mode(m_uart, bytesize, parity, stopbits);
}
/**
* Set the flowcontrol
*
* @param xonxoff XON/XOFF Software flow control.
* @param rtscts RTS/CTS out of band hardware flow control
* @return Result of operation
*/
mraa_result_t
setFlowcontrol(bool xonxoff, bool rtscts)
{
return mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);
}
/**
* Set the timeout for read and write operations
* <= 0 will disable that timeout
*
* @param read read timeout
* @param write write timeout
* @param interchar inbetween char timeout
* @return Result of operation
*/
mraa_result_t
setTimeout(int read, int write, int interchar)
{
return mraa_uart_set_timeout(m_uart, read, write, interchar);
}
private:
mraa_uart_context m_uart;
};
}
| Use std::string constructor which lets use set a size parameter | uart.hpp: Use std::string constructor which lets use set a size parameter
Signed-off-by: Brendan Le Foll <[email protected]>
| C++ | mit | neuroidss/mraa,malikabhi05/mraa,malikabhi05/mraa,alexandru-elisei/mraa,tripzero/mraa,g-vidal/mraa,smileboywtu/mraa,alexandru-elisei/mraa,neuberfran/mraa,intel-iot-devkit/mraa,ncrastanaren/mraa,intel-iot-devkit/mraa,stefan-andritoiu/mraa-gpio-chardev,petreeftime/mraa,arfoll/mraa,zBMNForks/mraa,tripzero/mraa,g-vidal/mraa,yoyojacky/mraa,alext-mkrs/mraa,neuberfran/mraa,allela-roy/mraa,noahchense/mraa,Kiritoalex/mraa,damcclos/mraa,matt-auld/mraa,sundw2014/mraa,whbruce/mraa,arfoll/mraa,Meirtz/mraa,smileboywtu/mraa,STANAPO/mraa,arfoll/mraa,arfoll/mraa,STANAPO/mraa,Hbrinj/mraa,damcclos/mraa,jontrulson/mraa,yoyojacky/mraa,alext-mkrs/mraa,Pillar1989/mraa,ProfFan/mraa,alext-mkrs/mraa,neuroidss/mraa,mircea/mraa,stefan-andritoiu/mraa,allela-roy/mraa,mircea/mraa,yongli3/mraa,nioinnovation/mraa,KurtE/mraa,SyrianSpock/mraa,pctj101/mraa,anonymouse64/mraa,arfoll/mraa,Hbrinj/mraa,neuberfran/mraa,jontrulson/mraa,sundw2014/mraa,Jon-ICS/mraa,yongli3/mraa,sergev/mraa,stefan-andritoiu/mraa-gpio-chardev,sundw2014/mraa,Jon-ICS/mraa,spitfire88/mraa,ProfFan/mraa,pctj101/mraa,yongli3/mraa,alexandru-elisei/mraa,spitfire88/mraa,arunlee77/mraa,ProfFan/mraa,w4ilun/mraa,tripzero/mraa,noahchense/mraa,sergev/mraa,Hbrinj/mraa,ncrastanaren/mraa,sergev/mraa,andreivasiliu2211/mraa,noahchense/mraa,stefan-andritoiu/mraa,jontrulson/mraa,andreivasiliu2211/mraa,pctj101/mraa,alext-mkrs/mraa,andreivasiliu2211/mraa,malikabhi05/mraa,Pillar1989/mraa,arunlee77/mraa,petreeftime/mraa,smileboywtu/mraa,g-vidal/mraa,anonymouse64/mraa,SyrianSpock/mraa,stefan-andritoiu/mraa-gpio-chardev,matt-auld/mraa,arunlee77/mraa,stefan-andritoiu/mraa,whbruce/mraa,Meirtz/mraa,zBMNForks/mraa,intel-iot-devkit/mraa,spitfire88/mraa,Hbrinj/mraa,Pillar1989/mraa,pctj101/mraa,jontrulson/mraa,alex1818/mraa,arunlee77/mraa,Propanu/mraa,Jon-ICS/mraa,Propanu/mraa,noahchense/mraa,alext-mkrs/mraa,sundw2014/mraa,allela-roy/mraa,w4ilun/mraa,mircea/mraa,Propanu/mraa,ncrastanaren/mraa,jontrulson/mraa,ncrastanaren/mraa,alex1818/mraa,whbruce/mraa,anonymouse64/mraa,whbruce/mraa,malikabhi05/mraa,ncrastanaren/mraa,KurtE/mraa,neuberfran/mraa,petreeftime/mraa,stefan-andritoiu/mraa-gpio-chardev,w4ilun/mraa,zBMNForks/mraa,Kiritoalex/mraa,damcclos/mraa,KurtE/mraa,intel-iot-devkit/mraa,neuroidss/mraa,nioinnovation/mraa,andreivasiliu2211/mraa,ProfFan/mraa,noahchense/mraa,intel-iot-devkit/mraa,sundw2014/mraa,Meirtz/mraa,petreeftime/mraa,KurtE/mraa,spitfire88/mraa,stefan-andritoiu/mraa,g-vidal/mraa,matt-auld/mraa,malikabhi05/mraa,alex1818/mraa,w4ilun/mraa,alexandru-elisei/mraa,nioinnovation/mraa,SyrianSpock/mraa,KurtE/mraa,sergev/mraa,stefan-andritoiu/mraa-gpio-chardev,alexandru-elisei/mraa,yongli3/mraa,yongli3/mraa,neuberfran/mraa,Kiritoalex/mraa,sergev/mraa,Propanu/mraa,pctj101/mraa,stefan-andritoiu/mraa,g-vidal/mraa,STANAPO/mraa,Propanu/mraa,yoyojacky/mraa |
91675a6e670cb4a2b38d242c32a7b3b0eae59936 | tools/swift-reflection-dump/swift-reflection-dump.cpp | tools/swift-reflection-dump/swift-reflection-dump.cpp | //===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//
#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Reflection/ReflectionContext.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Error.h"
#if defined(_WIN32)
#include <io.h>
#else
#include <unistd.h>
#endif
#include <algorithm>
#include <csignal>
#include <iostream>
using llvm::ArrayRef;
using llvm::dyn_cast;
using llvm::StringRef;
using namespace llvm::object;
using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;
enum class ActionType { DumpReflectionSections, DumpTypeLowering };
namespace options {
static llvm::cl::opt<ActionType> Action(
llvm::cl::desc("Mode:"),
llvm::cl::values(
clEnumValN(ActionType::DumpReflectionSections,
"dump-reflection-sections",
"Dump the field reflection section"),
clEnumValN(
ActionType::DumpTypeLowering, "dump-type-lowering",
"Dump the field layout for typeref strings read from stdin")),
llvm::cl::init(ActionType::DumpReflectionSections));
static llvm::cl::list<std::string>
BinaryFilename("binary-filename",
llvm::cl::desc("Filenames of the binary files"),
llvm::cl::OneOrMore);
static llvm::cl::opt<std::string>
Architecture("arch",
llvm::cl::desc("Architecture to inspect in the binary"),
llvm::cl::Required);
} // end namespace options
template <typename T> static T unwrap(llvm::Expected<T> value) {
if (value)
return std::move(value.get());
llvm::errs() << "swift-reflection-test error: " << toString(value.takeError())
<< "\n";
exit(EXIT_FAILURE);
}
static void reportError(std::error_code EC) {
assert(EC);
llvm::errs() << "swift-reflection-test error: " << EC.message() << ".\n";
exit(EXIT_FAILURE);
}
using NativeReflectionContext =
swift::reflection::ReflectionContext<External<RuntimeTarget<sizeof(uintptr_t)>>>;
using ReadBytesResult = swift::remote::MemoryReader::ReadBytesResult;
static uint64_t getSectionAddress(SectionRef S) {
// See COFFObjectFile.cpp for the implementation of
// COFFObjectFile::getSectionAddress. The image base address is added
// to all the addresses of the sections, thus the behavior is slightly different from
// the other platforms.
if (auto C = dyn_cast<COFFObjectFile>(S.getObject()))
return S.getAddress() - C->getImageBase();
return S.getAddress();
}
static bool needToRelocate(SectionRef S) {
if (!getSectionAddress(S))
return false;
if (auto EO = dyn_cast<ELFObjectFileBase>(S.getObject())) {
static const llvm::StringSet<> ELFSectionsList = {
".data", ".rodata", "swift5_protocols", "swift5_protocol_conformances",
"swift5_typeref", "swift5_reflstr", "swift5_assocty", "swift5_replace",
"swift5_type_metadata", "swift5_fieldmd", "swift5_capture", "swift5_builtin"
};
llvm::Expected<llvm::StringRef> NameOrErr = S.getName();
if (!NameOrErr) {
reportError(errorToErrorCode(NameOrErr.takeError()));
return false;
}
return ELFSectionsList.count(*NameOrErr);
}
return true;
}
class Image {
std::vector<char> Memory;
public:
explicit Image(const ObjectFile *O) {
uint64_t VASize = O->getData().size();
for (SectionRef S : O->sections()) {
if (auto SectionAddr = getSectionAddress(S))
VASize = std::max(VASize, SectionAddr + S.getSize());
}
Memory.resize(VASize);
std::memcpy(&Memory[0], O->getData().data(), O->getData().size());
for (SectionRef S : O->sections()) {
if (!needToRelocate(S))
continue;
llvm::Expected<llvm::StringRef> Content = S.getContents();
if (!Content)
reportError(errorToErrorCode(Content.takeError()));
std::memcpy(&Memory[getSectionAddress(S)], Content->data(),
Content->size());
}
}
RemoteAddress getStartAddress() const {
return RemoteAddress((uintptr_t)Memory.data());
}
bool isAddressValid(RemoteAddress Addr, uint64_t Size) const {
return (uintptr_t)Memory.data() <= Addr.getAddressData() &&
Addr.getAddressData() + Size <=
(uintptr_t)Memory.data() + Memory.size();
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) {
if (!isAddressValid(Addr, Size))
return ReadBytesResult(nullptr, [](const void *) {});
return ReadBytesResult((const void *)(Addr.getAddressData()),
[](const void *) {});
}
};
class ObjectMemoryReader : public MemoryReader {
std::vector<Image> Images;
public:
explicit ObjectMemoryReader(
const std::vector<const ObjectFile *> &ObjectFiles) {
for (const ObjectFile *O : ObjectFiles)
Images.emplace_back(O);
}
const std::vector<Image> &getImages() const { return Images; }
bool queryDataLayout(DataLayoutQueryType type, void *inBuffer,
void *outBuffer) override {
switch (type) {
case DLQ_GetPointerSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(void *);
return true;
}
case DLQ_GetSizeSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(size_t);
return true;
}
}
return false;
}
RemoteAddress getSymbolAddress(const std::string &name) override {
return RemoteAddress(nullptr);
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) override {
auto I = std::find_if(Images.begin(), Images.end(), [=](const Image &I) {
return I.isAddressValid(Addr, Size);
});
return I == Images.end() ? ReadBytesResult(nullptr, [](const void *) {})
: I->readBytes(Addr, Size);
}
bool readString(RemoteAddress Addr, std::string &Dest) override {
ReadBytesResult R = readBytes(Addr, 1);
if (!R)
return false;
StringRef Str((const char *)R.get());
Dest.append(Str.begin(), Str.end());
return true;
}
};
static int doDumpReflectionSections(ArrayRef<std::string> BinaryFilenames,
StringRef Arch, ActionType Action,
std::ostream &OS) {
// Note: binaryOrError and objectOrError own the memory for our ObjectFile;
// once they go out of scope, we can no longer do anything.
std::vector<OwningBinary<Binary>> BinaryOwners;
std::vector<std::unique_ptr<ObjectFile>> ObjectOwners;
std::vector<const ObjectFile *> ObjectFiles;
for (const std::string &BinaryFilename : BinaryFilenames) {
auto BinaryOwner = unwrap(createBinary(BinaryFilename));
Binary *BinaryFile = BinaryOwner.getBinary();
// The object file we are doing lookups in -- either the binary itself, or
// a particular slice of a universal binary.
std::unique_ptr<ObjectFile> ObjectOwner;
const ObjectFile *O = dyn_cast<ObjectFile>(BinaryFile);
if (!O) {
auto Universal = cast<MachOUniversalBinary>(BinaryFile);
ObjectOwner = unwrap(Universal->getObjectForArch(Arch));
O = ObjectOwner.get();
}
// Retain the objects that own section memory
BinaryOwners.push_back(std::move(BinaryOwner));
ObjectOwners.push_back(std::move(ObjectOwner));
ObjectFiles.push_back(O);
}
auto Reader = std::make_shared<ObjectMemoryReader>(ObjectFiles);
NativeReflectionContext Context(Reader);
for (const Image &I : Reader->getImages())
Context.addImage(I.getStartAddress());
switch (Action) {
case ActionType::DumpReflectionSections:
// Dump everything
Context.getBuilder().dumpAllSections(OS);
break;
case ActionType::DumpTypeLowering: {
for (std::string Line; std::getline(std::cin, Line);) {
if (Line.empty())
continue;
if (StringRef(Line).startswith("//"))
continue;
Demangle::Demangler Dem;
auto Demangled = Dem.demangleType(Line);
auto *TypeRef =
swift::Demangle::decodeMangledType(Context.getBuilder(), Demangled);
if (TypeRef == nullptr) {
OS << "Invalid typeref: " << Line << "\n";
continue;
}
TypeRef->dump(OS);
auto *TypeInfo =
Context.getBuilder().getTypeConverter().getTypeInfo(TypeRef);
if (TypeInfo == nullptr) {
OS << "Invalid lowering\n";
continue;
}
TypeInfo->dump(OS);
}
break;
}
}
return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) {
PROGRAM_START(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
return doDumpReflectionSections(options::BinaryFilename,
options::Architecture, options::Action,
std::cout);
}
| //===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//
#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Reflection/ReflectionContext.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Error.h"
#if defined(_WIN32)
#include <io.h>
#else
#include <unistd.h>
#endif
#include <algorithm>
#include <csignal>
#include <iostream>
using llvm::ArrayRef;
using llvm::dyn_cast;
using llvm::StringRef;
using namespace llvm::object;
using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;
enum class ActionType { DumpReflectionSections, DumpTypeLowering };
namespace options {
static llvm::cl::opt<ActionType> Action(
llvm::cl::desc("Mode:"),
llvm::cl::values(
clEnumValN(ActionType::DumpReflectionSections,
"dump-reflection-sections",
"Dump the field reflection section"),
clEnumValN(
ActionType::DumpTypeLowering, "dump-type-lowering",
"Dump the field layout for typeref strings read from stdin")),
llvm::cl::init(ActionType::DumpReflectionSections));
static llvm::cl::list<std::string>
BinaryFilename("binary-filename",
llvm::cl::desc("Filenames of the binary files"),
llvm::cl::OneOrMore);
static llvm::cl::opt<std::string>
Architecture("arch",
llvm::cl::desc("Architecture to inspect in the binary"),
llvm::cl::Required);
} // end namespace options
template <typename T> static T unwrap(llvm::Expected<T> value) {
if (value)
return std::move(value.get());
llvm::errs() << "swift-reflection-test error: " << toString(value.takeError())
<< "\n";
exit(EXIT_FAILURE);
}
static void reportError(std::error_code EC) {
assert(EC);
llvm::errs() << "swift-reflection-test error: " << EC.message() << ".\n";
exit(EXIT_FAILURE);
}
using NativeReflectionContext =
swift::reflection::ReflectionContext<External<RuntimeTarget<sizeof(uintptr_t)>>>;
using ReadBytesResult = swift::remote::MemoryReader::ReadBytesResult;
static uint64_t getSectionAddress(SectionRef S) {
// See COFFObjectFile.cpp for the implementation of
// COFFObjectFile::getSectionAddress. The image base address is added
// to all the addresses of the sections, thus the behavior is slightly different from
// the other platforms.
if (auto C = dyn_cast<COFFObjectFile>(S.getObject()))
return S.getAddress() - C->getImageBase();
return S.getAddress();
}
static bool needToRelocate(SectionRef S) {
if (!getSectionAddress(S))
return false;
if (auto EO = dyn_cast<ELFObjectFileBase>(S.getObject())) {
static const llvm::StringSet<> ELFSectionsList = {
".data", ".rodata", "swift5_protocols", "swift5_protocol_conformances",
"swift5_typeref", "swift5_reflstr", "swift5_assocty", "swift5_replace",
"swift5_type_metadata", "swift5_fieldmd", "swift5_capture", "swift5_builtin"
};
llvm::Expected<llvm::StringRef> NameOrErr = S.getName();
if (!NameOrErr) {
reportError(errorToErrorCode(NameOrErr.takeError()));
return false;
}
return ELFSectionsList.count(*NameOrErr);
}
return true;
}
class Image {
std::vector<char> Memory;
public:
explicit Image(const ObjectFile *O) {
uint64_t VASize = O->getData().size();
for (SectionRef S : O->sections()) {
if (auto SectionAddr = getSectionAddress(S))
VASize = std::max(VASize, SectionAddr + S.getSize());
}
Memory.resize(VASize);
std::memcpy(&Memory[0], O->getData().data(), O->getData().size());
for (SectionRef S : O->sections()) {
if (!needToRelocate(S))
continue;
llvm::Expected<llvm::StringRef> Content = S.getContents();
if (!Content)
reportError(errorToErrorCode(Content.takeError()));
std::memcpy(&Memory[getSectionAddress(S)], Content->data(),
Content->size());
}
}
RemoteAddress getStartAddress() const {
return RemoteAddress((uintptr_t)Memory.data());
}
bool isAddressValid(RemoteAddress Addr, uint64_t Size) const {
return (uintptr_t)Memory.data() <= Addr.getAddressData() &&
Addr.getAddressData() + Size <=
(uintptr_t)Memory.data() + Memory.size();
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) {
if (!isAddressValid(Addr, Size))
return ReadBytesResult(nullptr, [](const void *) {});
return ReadBytesResult((const void *)(Addr.getAddressData()),
[](const void *) {});
}
};
class ObjectMemoryReader : public MemoryReader {
std::vector<Image> Images;
public:
explicit ObjectMemoryReader(
const std::vector<const ObjectFile *> &ObjectFiles) {
for (const ObjectFile *O : ObjectFiles)
Images.emplace_back(O);
}
const std::vector<Image> &getImages() const { return Images; }
bool queryDataLayout(DataLayoutQueryType type, void *inBuffer,
void *outBuffer) override {
switch (type) {
case DLQ_GetPointerSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(void *);
return true;
}
case DLQ_GetSizeSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = sizeof(size_t);
return true;
}
}
return false;
}
RemoteAddress getSymbolAddress(const std::string &name) override {
return RemoteAddress(nullptr);
}
ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) override {
auto I = std::find_if(Images.begin(), Images.end(), [=](const Image &I) {
return I.isAddressValid(Addr, Size);
});
return I == Images.end() ? ReadBytesResult(nullptr, [](const void *) {})
: I->readBytes(Addr, Size);
}
bool readString(RemoteAddress Addr, std::string &Dest) override {
ReadBytesResult R = readBytes(Addr, 1);
if (!R)
return false;
StringRef Str((const char *)R.get());
Dest.append(Str.begin(), Str.end());
return true;
}
};
static int doDumpReflectionSections(ArrayRef<std::string> BinaryFilenames,
StringRef Arch, ActionType Action,
std::ostream &OS) {
// Note: binaryOrError and objectOrError own the memory for our ObjectFile;
// once they go out of scope, we can no longer do anything.
std::vector<OwningBinary<Binary>> BinaryOwners;
std::vector<std::unique_ptr<ObjectFile>> ObjectOwners;
std::vector<const ObjectFile *> ObjectFiles;
for (const std::string &BinaryFilename : BinaryFilenames) {
auto BinaryOwner = unwrap(createBinary(BinaryFilename));
Binary *BinaryFile = BinaryOwner.getBinary();
// The object file we are doing lookups in -- either the binary itself, or
// a particular slice of a universal binary.
std::unique_ptr<ObjectFile> ObjectOwner;
const ObjectFile *O = dyn_cast<ObjectFile>(BinaryFile);
if (!O) {
auto Universal = cast<MachOUniversalBinary>(BinaryFile);
ObjectOwner = unwrap(Universal->getMachOObjectForArch(Arch));
O = ObjectOwner.get();
}
// Retain the objects that own section memory
BinaryOwners.push_back(std::move(BinaryOwner));
ObjectOwners.push_back(std::move(ObjectOwner));
ObjectFiles.push_back(O);
}
auto Reader = std::make_shared<ObjectMemoryReader>(ObjectFiles);
NativeReflectionContext Context(Reader);
for (const Image &I : Reader->getImages())
Context.addImage(I.getStartAddress());
switch (Action) {
case ActionType::DumpReflectionSections:
// Dump everything
Context.getBuilder().dumpAllSections(OS);
break;
case ActionType::DumpTypeLowering: {
for (std::string Line; std::getline(std::cin, Line);) {
if (Line.empty())
continue;
if (StringRef(Line).startswith("//"))
continue;
Demangle::Demangler Dem;
auto Demangled = Dem.demangleType(Line);
auto *TypeRef =
swift::Demangle::decodeMangledType(Context.getBuilder(), Demangled);
if (TypeRef == nullptr) {
OS << "Invalid typeref: " << Line << "\n";
continue;
}
TypeRef->dump(OS);
auto *TypeInfo =
Context.getBuilder().getTypeConverter().getTypeInfo(TypeRef);
if (TypeInfo == nullptr) {
OS << "Invalid lowering\n";
continue;
}
TypeInfo->dump(OS);
}
break;
}
}
return EXIT_SUCCESS;
}
int main(int argc, char *argv[]) {
PROGRAM_START(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
return doDumpReflectionSections(options::BinaryFilename,
options::Architecture, options::Action,
std::cout);
}
| Adjust for svn rL372278 | Adjust for svn rL372278
The method MachOUniversalBinary::getObjectForArch had its return type altered. A
new method was added that accomplishes what we want:
MachOUniversalBinary::getMachOObjectForArch.
| C++ | apache-2.0 | parkera/swift,harlanhaskins/swift,jckarter/swift,rudkx/swift,nathawes/swift,benlangmuir/swift,harlanhaskins/swift,aschwaighofer/swift,jmgc/swift,ahoppen/swift,apple/swift,glessard/swift,parkera/swift,jckarter/swift,JGiola/swift,xwu/swift,xwu/swift,atrick/swift,harlanhaskins/swift,glessard/swift,hooman/swift,roambotics/swift,jmgc/swift,apple/swift,stephentyrone/swift,hooman/swift,glessard/swift,aschwaighofer/swift,JGiola/swift,JGiola/swift,airspeedswift/swift,gregomni/swift,CodaFi/swift,harlanhaskins/swift,CodaFi/swift,ahoppen/swift,JGiola/swift,benlangmuir/swift,airspeedswift/swift,apple/swift,allevato/swift,roambotics/swift,rudkx/swift,roambotics/swift,CodaFi/swift,glessard/swift,ahoppen/swift,jckarter/swift,gregomni/swift,JGiola/swift,hooman/swift,harlanhaskins/swift,airspeedswift/swift,aschwaighofer/swift,benlangmuir/swift,nathawes/swift,rudkx/swift,nathawes/swift,aschwaighofer/swift,tkremenek/swift,tkremenek/swift,gregomni/swift,parkera/swift,rudkx/swift,xwu/swift,jmgc/swift,allevato/swift,allevato/swift,benlangmuir/swift,allevato/swift,stephentyrone/swift,aschwaighofer/swift,airspeedswift/swift,CodaFi/swift,roambotics/swift,jmgc/swift,ahoppen/swift,aschwaighofer/swift,tkremenek/swift,harlanhaskins/swift,roambotics/swift,jmgc/swift,jmgc/swift,tkremenek/swift,airspeedswift/swift,atrick/swift,roambotics/swift,jckarter/swift,JGiola/swift,parkera/swift,jckarter/swift,nathawes/swift,apple/swift,ahoppen/swift,stephentyrone/swift,nathawes/swift,parkera/swift,parkera/swift,hooman/swift,atrick/swift,hooman/swift,allevato/swift,atrick/swift,atrick/swift,stephentyrone/swift,parkera/swift,apple/swift,apple/swift,glessard/swift,benlangmuir/swift,CodaFi/swift,allevato/swift,allevato/swift,jmgc/swift,tkremenek/swift,hooman/swift,xwu/swift,xwu/swift,stephentyrone/swift,jckarter/swift,airspeedswift/swift,glessard/swift,gregomni/swift,tkremenek/swift,hooman/swift,xwu/swift,gregomni/swift,rudkx/swift,ahoppen/swift,CodaFi/swift,benlangmuir/swift,atrick/swift,CodaFi/swift,tkremenek/swift,nathawes/swift,stephentyrone/swift,stephentyrone/swift,xwu/swift,harlanhaskins/swift,airspeedswift/swift,nathawes/swift,parkera/swift,jckarter/swift,rudkx/swift,aschwaighofer/swift,gregomni/swift |
ebdc14379338d2efbfcc903027d601cb055da6a2 | Code/Common/itkLightObject.cxx | Code/Common/itkLightObject.cxx | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLightObject.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.
=========================================================================*/
#include "itkLightObject.h"
#include "itkObjectFactory.h"
#include "itkFastMutexLock.h"
#include <list>
#include <memory>
// Better name demanging for gcc
#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 )
#define GCC_USEDEMANGLE
#endif
#ifdef GCC_USEDEMANGLE
#include <cstdlib>
#include <cxxabi.h>
#endif
namespace itk
{
LightObject::Pointer
LightObject::New()
{
Pointer smartPtr;
LightObject *rawPtr = ::itk::ObjectFactory<LightObject>::Create();
if(rawPtr == NULL)
{
rawPtr = new LightObject;
}
smartPtr = rawPtr;
rawPtr->UnRegister();
return smartPtr;
}
LightObject::Pointer
LightObject::CreateAnother() const
{
return LightObject::New();
}
/**
* Delete a itk object. This method should always be used to delete an object
* when the new operator was used to create it. Using the C++ delete method
* will not work with reference counting.
*/
void
LightObject
::Delete()
{
this->UnRegister();
}
/**
* Avoid DLL boundary problems.
*/
#ifdef _WIN32
void*
LightObject
::operator new(size_t n)
{
return new char[n];
}
void*
LightObject
::operator new[](size_t n)
{
return new char[n];
}
void
LightObject
::operator delete(void* m)
{
delete [] (char*)m;
}
void
LightObject
::operator delete[](void* m, size_t)
{
delete [] (char*)m;
}
#endif
/**
* This function will be common to all itk objects. It just calls the
* header/self/trailer virtual print methods, which can be overriden by
* subclasses (any itk object).
*/
void
LightObject
::Print(std::ostream& os, Indent indent) const
{
this->PrintHeader(os, indent);
this->PrintSelf(os, indent.GetNextIndent());
this->PrintTrailer(os, indent);
}
/**
* This method is called when itkExceptionMacro executes. It allows
* the debugger to break on error.
*/
void
LightObject
::BreakOnError()
{
;
}
/**
* Increase the reference count (mark as used by another object).
*/
void
LightObject
::Register() const
{
m_ReferenceCountLock.Lock();
m_ReferenceCount++;
m_ReferenceCountLock.Unlock();
}
/**
* Decrease the reference count (release by another object).
*/
void
LightObject
::UnRegister() const
{
m_ReferenceCountLock.Lock();
m_ReferenceCount--;
m_ReferenceCountLock.Unlock();
// ReferenceCount in now unlocked. We may have a race condition
// to delete the object.
if ( m_ReferenceCount <= 0)
{
delete this;
}
}
/**
* Sets the reference count (use with care)
*/
void
LightObject
::SetReferenceCount(int ref)
{
m_ReferenceCountLock.Lock();
m_ReferenceCount = ref;
m_ReferenceCountLock.Unlock();
if ( m_ReferenceCount <= 0)
{
delete this;
}
}
LightObject
::~LightObject()
{
/**
* warn user if reference counting is on and the object is being referenced
* by another object
*/
if ( m_ReferenceCount > 0)
{
itkExceptionMacro(<< "Trying to delete object with non-zero reference count.");
}
}
/**
* Chaining method to print an object's instance variables, as well as
* its superclasses.
*/
void
LightObject
::PrintSelf(std::ostream& os, Indent indent) const
{
#ifdef GCC_USEDEMANGLE
char const * mangledName = typeid(*this).name();
int status;
char* unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status);
os << indent << "RTTI typeinfo: ";
if(status == 0)
{
os << unmangled;
free(unmangled);
}
else
{
os << mangledName;
}
os << std::endl;
#else
os << indent << "RTTI typeinfo: " << typeid( *this ).name() << std::endl;
#endif
os << indent << "Reference Count: " << m_ReferenceCount << std::endl;
}
/**
* Define a default print header for all objects.
*/
void
LightObject
::PrintHeader(std::ostream& os, Indent indent) const
{
os << indent << this->GetNameOfClass() << " (" << this << ")\n";
}
/**
* Define a default print trailer for all objects.
*/
void
LightObject
::PrintTrailer(std::ostream& itkNotUsed(os), Indent itkNotUsed(indent)) const
{
}
/**
* This operator allows all subclasses of LightObject to be printed via <<.
* It in turn invokes the Print method, which in turn will invoke the
* PrintSelf method that all objects should define, if they have anything
* interesting to print out.
*/
std::ostream&
operator<<(std::ostream& os, const LightObject& o)
{
o.Print(os);
return os;
}
} // end namespace itk
| /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLightObject.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.
=========================================================================*/
#include "itkLightObject.h"
#include "itkObjectFactory.h"
#include "itkFastMutexLock.h"
#include <list>
#include <memory>
#include <exception>
// Better name demanging for gcc
#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 )
#define GCC_USEDEMANGLE
#endif
#ifdef GCC_USEDEMANGLE
#include <cstdlib>
#include <cxxabi.h>
#endif
namespace itk
{
LightObject::Pointer
LightObject::New()
{
Pointer smartPtr;
LightObject *rawPtr = ::itk::ObjectFactory<LightObject>::Create();
if(rawPtr == NULL)
{
rawPtr = new LightObject;
}
smartPtr = rawPtr;
rawPtr->UnRegister();
return smartPtr;
}
LightObject::Pointer
LightObject::CreateAnother() const
{
return LightObject::New();
}
/**
* Delete a itk object. This method should always be used to delete an object
* when the new operator was used to create it. Using the C++ delete method
* will not work with reference counting.
*/
void
LightObject
::Delete()
{
this->UnRegister();
}
/**
* Avoid DLL boundary problems.
*/
#ifdef _WIN32
void*
LightObject
::operator new(size_t n)
{
return new char[n];
}
void*
LightObject
::operator new[](size_t n)
{
return new char[n];
}
void
LightObject
::operator delete(void* m)
{
delete [] (char*)m;
}
void
LightObject
::operator delete[](void* m, size_t)
{
delete [] (char*)m;
}
#endif
/**
* This function will be common to all itk objects. It just calls the
* header/self/trailer virtual print methods, which can be overriden by
* subclasses (any itk object).
*/
void
LightObject
::Print(std::ostream& os, Indent indent) const
{
this->PrintHeader(os, indent);
this->PrintSelf(os, indent.GetNextIndent());
this->PrintTrailer(os, indent);
}
/**
* This method is called when itkExceptionMacro executes. It allows
* the debugger to break on error.
*/
void
LightObject
::BreakOnError()
{
;
}
/**
* Increase the reference count (mark as used by another object).
*/
void
LightObject
::Register() const
{
m_ReferenceCountLock.Lock();
m_ReferenceCount++;
m_ReferenceCountLock.Unlock();
}
/**
* Decrease the reference count (release by another object).
*/
void
LightObject
::UnRegister() const
{
m_ReferenceCountLock.Lock();
m_ReferenceCount--;
m_ReferenceCountLock.Unlock();
// ReferenceCount in now unlocked. We may have a race condition
// to delete the object.
if ( m_ReferenceCount <= 0)
{
delete this;
}
}
/**
* Sets the reference count (use with care)
*/
void
LightObject
::SetReferenceCount(int ref)
{
m_ReferenceCountLock.Lock();
m_ReferenceCount = ref;
m_ReferenceCountLock.Unlock();
if ( m_ReferenceCount <= 0)
{
delete this;
}
}
LightObject
::~LightObject()
{
/**
* warn user if reference counting is on and the object is being referenced
* by another object.
* a call to uncaught_exception is necessary here to avoid throwing an
* exception if one has been thrown already. This is likely to
* happen when a subclass constructor (say B) is throwing an exception: at
* that point, the stack unwinds by calling all superclass destructors back
* to this method (~LightObject): since the ref count is still 1, an
* exception would be thrown again, causing the system to abort()!
*/
if (!std::uncaught_exception() && m_ReferenceCount > 0)
{
itkExceptionMacro(<< "Trying to delete object with non-zero reference count.");
}
}
/**
* Chaining method to print an object's instance variables, as well as
* its superclasses.
*/
void
LightObject
::PrintSelf(std::ostream& os, Indent indent) const
{
#ifdef GCC_USEDEMANGLE
char const * mangledName = typeid(*this).name();
int status;
char* unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status);
os << indent << "RTTI typeinfo: ";
if(status == 0)
{
os << unmangled;
free(unmangled);
}
else
{
os << mangledName;
}
os << std::endl;
#else
os << indent << "RTTI typeinfo: " << typeid( *this ).name() << std::endl;
#endif
os << indent << "Reference Count: " << m_ReferenceCount << std::endl;
}
/**
* Define a default print header for all objects.
*/
void
LightObject
::PrintHeader(std::ostream& os, Indent indent) const
{
os << indent << this->GetNameOfClass() << " (" << this << ")\n";
}
/**
* Define a default print trailer for all objects.
*/
void
LightObject
::PrintTrailer(std::ostream& itkNotUsed(os), Indent itkNotUsed(indent)) const
{
}
/**
* This operator allows all subclasses of LightObject to be printed via <<.
* It in turn invokes the Print method, which in turn will invoke the
* PrintSelf method that all objects should define, if they have anything
* interesting to print out.
*/
std::ostream&
operator<<(std::ostream& os, const LightObject& o)
{
o.Print(os);
return os;
}
} // end namespace itk
| handle the case when subclass constructors would call an exception. This prevents a system abort() | COMP: handle the case when subclass constructors would call an exception. This prevents a system abort()
| C++ | apache-2.0 | hinerm/ITK,LucasGandel/ITK,eile/ITK,LucasGandel/ITK,itkvideo/ITK,jmerkow/ITK,LucHermitte/ITK,hinerm/ITK,malaterre/ITK,biotrump/ITK,stnava/ITK,PlutoniumHeart/ITK,biotrump/ITK,BRAINSia/ITK,hendradarwin/ITK,GEHC-Surgery/ITK,GEHC-Surgery/ITK,msmolens/ITK,jcfr/ITK,itkvideo/ITK,rhgong/itk-with-dom,zachary-williamson/ITK,msmolens/ITK,zachary-williamson/ITK,blowekamp/ITK,jcfr/ITK,fedral/ITK,PlutoniumHeart/ITK,CapeDrew/DITK,daviddoria/itkHoughTransform,hendradarwin/ITK,jmerkow/ITK,BlueBrain/ITK,BRAINSia/ITK,fedral/ITK,biotrump/ITK,fbudin69500/ITK,eile/ITK,spinicist/ITK,fbudin69500/ITK,daviddoria/itkHoughTransform,msmolens/ITK,ajjl/ITK,vfonov/ITK,hendradarwin/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,cpatrick/ITK-RemoteIO,thewtex/ITK,hendradarwin/ITK,InsightSoftwareConsortium/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,CapeDrew/DCMTK-ITK,heimdali/ITK,paulnovo/ITK,wkjeong/ITK,jcfr/ITK,wkjeong/ITK,thewtex/ITK,stnava/ITK,spinicist/ITK,atsnyder/ITK,rhgong/itk-with-dom,ajjl/ITK,hinerm/ITK,blowekamp/ITK,itkvideo/ITK,biotrump/ITK,thewtex/ITK,BlueBrain/ITK,itkvideo/ITK,fuentesdt/InsightToolkit-dev,zachary-williamson/ITK,wkjeong/ITK,BlueBrain/ITK,daviddoria/itkHoughTransform,cpatrick/ITK-RemoteIO,cpatrick/ITK-RemoteIO,wkjeong/ITK,Kitware/ITK,GEHC-Surgery/ITK,daviddoria/itkHoughTransform,BlueBrain/ITK,atsnyder/ITK,biotrump/ITK,CapeDrew/DITK,richardbeare/ITK,LucasGandel/ITK,GEHC-Surgery/ITK,fuentesdt/InsightToolkit-dev,atsnyder/ITK,heimdali/ITK,fuentesdt/InsightToolkit-dev,hjmjohnson/ITK,msmolens/ITK,CapeDrew/DCMTK-ITK,jcfr/ITK,jcfr/ITK,fuentesdt/InsightToolkit-dev,hjmjohnson/ITK,ajjl/ITK,zachary-williamson/ITK,hinerm/ITK,cpatrick/ITK-RemoteIO,biotrump/ITK,heimdali/ITK,CapeDrew/DITK,ajjl/ITK,wkjeong/ITK,jcfr/ITK,GEHC-Surgery/ITK,richardbeare/ITK,vfonov/ITK,spinicist/ITK,vfonov/ITK,hjmjohnson/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DITK,ajjl/ITK,spinicist/ITK,ajjl/ITK,paulnovo/ITK,paulnovo/ITK,spinicist/ITK,CapeDrew/DCMTK-ITK,vfonov/ITK,rhgong/itk-with-dom,zachary-williamson/ITK,LucasGandel/ITK,vfonov/ITK,atsnyder/ITK,Kitware/ITK,jmerkow/ITK,hinerm/ITK,itkvideo/ITK,hinerm/ITK,Kitware/ITK,jcfr/ITK,heimdali/ITK,GEHC-Surgery/ITK,wkjeong/ITK,atsnyder/ITK,BRAINSia/ITK,paulnovo/ITK,biotrump/ITK,heimdali/ITK,malaterre/ITK,hinerm/ITK,GEHC-Surgery/ITK,atsnyder/ITK,CapeDrew/DCMTK-ITK,malaterre/ITK,PlutoniumHeart/ITK,itkvideo/ITK,blowekamp/ITK,eile/ITK,PlutoniumHeart/ITK,hjmjohnson/ITK,thewtex/ITK,CapeDrew/DITK,blowekamp/ITK,heimdali/ITK,fedral/ITK,fedral/ITK,fedral/ITK,itkvideo/ITK,cpatrick/ITK-RemoteIO,msmolens/ITK,InsightSoftwareConsortium/ITK,atsnyder/ITK,eile/ITK,rhgong/itk-with-dom,jmerkow/ITK,ajjl/ITK,paulnovo/ITK,eile/ITK,hjmjohnson/ITK,itkvideo/ITK,atsnyder/ITK,jmerkow/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,fedral/ITK,daviddoria/itkHoughTransform,eile/ITK,vfonov/ITK,CapeDrew/DITK,hinerm/ITK,fbudin69500/ITK,fedral/ITK,malaterre/ITK,hendradarwin/ITK,stnava/ITK,PlutoniumHeart/ITK,eile/ITK,PlutoniumHeart/ITK,cpatrick/ITK-RemoteIO,fuentesdt/InsightToolkit-dev,stnava/ITK,jmerkow/ITK,zachary-williamson/ITK,Kitware/ITK,fbudin69500/ITK,msmolens/ITK,CapeDrew/DCMTK-ITK,blowekamp/ITK,hinerm/ITK,zachary-williamson/ITK,CapeDrew/DCMTK-ITK,zachary-williamson/ITK,eile/ITK,richardbeare/ITK,hendradarwin/ITK,heimdali/ITK,CapeDrew/DCMTK-ITK,thewtex/ITK,Kitware/ITK,eile/ITK,CapeDrew/DCMTK-ITK,fuentesdt/InsightToolkit-dev,LucasGandel/ITK,fbudin69500/ITK,rhgong/itk-with-dom,spinicist/ITK,blowekamp/ITK,rhgong/itk-with-dom,InsightSoftwareConsortium/ITK,biotrump/ITK,fedral/ITK,hendradarwin/ITK,vfonov/ITK,jmerkow/ITK,daviddoria/itkHoughTransform,LucHermitte/ITK,vfonov/ITK,spinicist/ITK,stnava/ITK,BRAINSia/ITK,daviddoria/itkHoughTransform,Kitware/ITK,richardbeare/ITK,fuentesdt/InsightToolkit-dev,hendradarwin/ITK,fbudin69500/ITK,daviddoria/itkHoughTransform,CapeDrew/DCMTK-ITK,BRAINSia/ITK,PlutoniumHeart/ITK,CapeDrew/DITK,LucasGandel/ITK,GEHC-Surgery/ITK,jcfr/ITK,wkjeong/ITK,malaterre/ITK,fuentesdt/InsightToolkit-dev,LucHermitte/ITK,stnava/ITK,thewtex/ITK,paulnovo/ITK,LucasGandel/ITK,LucHermitte/ITK,InsightSoftwareConsortium/ITK,fbudin69500/ITK,vfonov/ITK,spinicist/ITK,wkjeong/ITK,zachary-williamson/ITK,heimdali/ITK,cpatrick/ITK-RemoteIO,Kitware/ITK,paulnovo/ITK,LucHermitte/ITK,atsnyder/ITK,stnava/ITK,LucasGandel/ITK,msmolens/ITK,blowekamp/ITK,jmerkow/ITK,CapeDrew/DITK,richardbeare/ITK,BlueBrain/ITK,ajjl/ITK,BlueBrain/ITK,fbudin69500/ITK,BlueBrain/ITK,richardbeare/ITK,stnava/ITK,fuentesdt/InsightToolkit-dev,malaterre/ITK,stnava/ITK,hjmjohnson/ITK,LucHermitte/ITK,daviddoria/itkHoughTransform,CapeDrew/DITK,thewtex/ITK,malaterre/ITK,BRAINSia/ITK,hjmjohnson/ITK,itkvideo/ITK,blowekamp/ITK,rhgong/itk-with-dom,malaterre/ITK,InsightSoftwareConsortium/ITK,msmolens/ITK,LucHermitte/ITK,paulnovo/ITK,LucHermitte/ITK,spinicist/ITK,rhgong/itk-with-dom,richardbeare/ITK |
d01bdb2d31d28dbda46ba96f03b595f3408bedab | include/eixx/eterm.hpp | include/eixx/eterm.hpp | //----------------------------------------------------------------------------
/// \file eterm.hpp
//----------------------------------------------------------------------------
/// \brief Header file for including marshaling part of eixx.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <[email protected]>
// Created: 2010-09-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
Copyright 2010 Serge Aleynikov <saleyn at gmail dot com>
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.
***** END LICENSE BLOCK *****
*/
#ifndef _EIXX_ETERM_HPP_
#define _EIXX_ETERM_HPP_
#include <eixx/config.h>
#include <eixx/marshal/defaults.hpp>
#include <eixx/marshal/eterm.hpp>
#define EIXX_DECL_ATOM(Atom) static const eixx::atom am_##Atom(#Atom)
#define EIXX_DECL_ATOM_VAL(Atom, Val) static const eixx::atom am_##Atom(#Val)
#define EIXX_DECL_ATOM_VAR(Name, Atom) static const eixx::atom Name(Atom)
namespace eixx {
typedef marshal::eterm<allocator_t> eterm;
typedef marshal::atom atom;
typedef marshal::string<allocator_t> string;
typedef marshal::binary<allocator_t> binary;
typedef marshal::epid<allocator_t> epid;
typedef marshal::port<allocator_t> port;
typedef marshal::ref<allocator_t> ref;
typedef marshal::tuple<allocator_t> tuple;
typedef marshal::list<allocator_t> list;
typedef marshal::map<allocator_t> map;
typedef marshal::trace<allocator_t> trace;
typedef marshal::var var;
typedef marshal::varbind<allocator_t> varbind;
typedef marshal::eterm_pattern_matcher<allocator_t> eterm_pattern_matcher;
typedef marshal::eterm_pattern_action<allocator_t> eterm_pattern_action;
namespace detail {
BOOST_STATIC_ASSERT(sizeof(eterm) == (ALIGNOF_UINT64_T > sizeof(int) ? ALIGNOF_UINT64_T : sizeof(int)) + sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(atom) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(string) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(binary) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(epid) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(port) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(ref) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(tuple) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(list) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(map) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(trace) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(var) == sizeof(uint64_t));
} // namespace detail
} // namespace eixx
#endif
| //----------------------------------------------------------------------------
/// \file eterm.hpp
//----------------------------------------------------------------------------
/// \brief Header file for including marshaling part of eixx.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <[email protected]>
// Created: 2010-09-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
Copyright 2010 Serge Aleynikov <saleyn at gmail dot com>
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.
***** END LICENSE BLOCK *****
*/
#ifndef _EIXX_ETERM_HPP_
#define _EIXX_ETERM_HPP_
#include <eixx/config.h>
#include <eixx/marshal/defaults.hpp>
#include <eixx/marshal/eterm.hpp>
#define EIXX_DECL_ATOM(Atom) static const eixx::atom am_##Atom(#Atom)
#define EIXX_DECL_ATOM_VAL(Atom, Val) static const eixx::atom am_##Atom(Val)
#define EIXX_DECL_ATOM_VAR(Name, Atom) static const eixx::atom Name(Atom)
namespace eixx {
typedef marshal::eterm<allocator_t> eterm;
typedef marshal::atom atom;
typedef marshal::string<allocator_t> string;
typedef marshal::binary<allocator_t> binary;
typedef marshal::epid<allocator_t> epid;
typedef marshal::port<allocator_t> port;
typedef marshal::ref<allocator_t> ref;
typedef marshal::tuple<allocator_t> tuple;
typedef marshal::list<allocator_t> list;
typedef marshal::map<allocator_t> map;
typedef marshal::trace<allocator_t> trace;
typedef marshal::var var;
typedef marshal::varbind<allocator_t> varbind;
typedef marshal::eterm_pattern_matcher<allocator_t> eterm_pattern_matcher;
typedef marshal::eterm_pattern_action<allocator_t> eterm_pattern_action;
namespace detail {
BOOST_STATIC_ASSERT(sizeof(eterm) == (ALIGNOF_UINT64_T > sizeof(int) ? ALIGNOF_UINT64_T : sizeof(int)) + sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(atom) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(string) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(binary) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(epid) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(port) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(ref) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(tuple) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(list) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(map) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(trace) <= sizeof(uint64_t));
BOOST_STATIC_ASSERT(sizeof(var) == sizeof(uint64_t));
} // namespace detail
} // namespace eixx
#endif
| Add declaration of atom macro | Add declaration of atom macro
| C++ | apache-2.0 | saleyn/eixx |
2363f5d0bed01c4681c2fcc304f7d73acc6a873a | src/Vector.hpp | src/Vector.hpp | #ifndef AX_VECTOR_H
#define AX_VECTOR_H
#include <array>
#include <vector>
#include <iostream>
#include "VectorExpression.hpp"
namespace ax
{
// static dimension case
template<typename T_elem, dimension_type I_dim>
class Vector
{
public:
// traits
using tag = vector_tag;
using elem_t = T_elem;
constexpr static dimension_type dim = I_dim;
using container_t = std::array<elem_t, dim>;
using self_type = Vector<elem_t, dim>;
public:
Vector() : values_{{}}{}
~Vector() = default;
Vector(const elem_t d){values_.fill(d);}
Vector(const container_t& v) : values_(v){}
Vector(const self_type& v): values_(v.values_){}
Vector(const std::vector<elem_t>& vec)
{
if(vec.size() < dim) vec.resize(dim, 0e0);
for(std::size_t i(0); i<dim; ++i) values_[i] = vec[i];
}
template<typename ... T_args, typename std::enable_if<
(sizeof...(T_args) == dim) && is_all<elem_t, T_args...>::value
>::type*& = enabler>
Vector(T_args ... args) : values_{{args...}}{}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr)
{
for(std::size_t i(0); i<dim; ++i) (*this)[i] = expr[i];
}
// from dynamic
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr)
{
if(expr.size() != dim)
throw std::invalid_argument("vector size different");
for(std::size_t i(0); i<dim; ++i) (*this)[i] = expr[i];
}
// from static
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
for(auto i(0); i<dim; ++i) (*this)[i] = expr[i];
return *this;
}
// from dynamic
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
if(expr.size() != dim)
throw std::invalid_argument("vector size different");
for(auto i(0); i<dim; ++i) (*this)[i] = expr[i];
return *this;
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
return *this = (*this + expr);
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
if(expr.size() != dim)
throw std::invalid_argument("vector size different");
return *this = (*this + expr);
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
return *this = (*this - expr);
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
if(expr.size() != dim)
throw std::invalid_argument("vector size different");
return *this = (*this - expr);
}
Vector<elem_t, dim>& operator*=(const elem_t& expr)
{
return *this = (*this * expr);
}
Vector<elem_t, dim>& operator/=(const elem_t& expr)
{
return *this = (*this / expr);
}
elem_t const& operator[](const std::size_t i) const
{
#ifdef AX_PARANOIAC
return values_.at(i);
#else
return values_[i];
#endif
}
elem_t& operator[](const std::size_t i)
{
#ifdef AX_PARANOIAC
return values_.at(i);
#else
return values_[i];
#endif
}
elem_t const& at(const std::size_t i) const {return values_.at(i);}
elem_t& at(const std::size_t i) {return values_.at(i);}
private:
container_t values_;
};
}
#endif//AX_VECTOR_H
| #ifndef AX_VECTOR_H
#define AX_VECTOR_H
#include <array>
#include <vector>
#include <iostream>
#include "VectorExpression.hpp"
namespace ax
{
// static dimension case
template<typename T_elem, dimension_type I_dim>
class Vector
{
public:
// traits
using tag = vector_tag;
using elem_t = T_elem;
constexpr static dimension_type dim = I_dim;
using container_t = std::array<elem_t, dim>;
using self_type = Vector<elem_t, dim>;
public:
Vector() : values_{{}}{}
~Vector() = default;
Vector(const elem_t d){values_.fill(d);}
Vector(const container_t& v): values_(v){}
Vector(const self_type& v): values_(v.values_){}
template<typename ... T_args, typename std::enable_if<
(sizeof...(T_args) == dim) && is_all<elem_t, T_args...>::value
>::type*& = enabler>
Vector(T_args ... args) : values_{{args...}}{}
// from static
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr)
{
for(std::size_t i(0); i<dim; ++i) (*this)[i] = expr[i];
}
// from dynamic
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr)
{
if(dimension(expr) != dim)
throw std::invalid_argument("vector size different");
for(std::size_t i(0); i<dim; ++i) (*this)[i] = expr[i];
}
// from static
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
for(auto i(0); i<dim; ++i) (*this)[i] = expr[i];
return *this;
}
// from dynamic
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
if(dimension(expr) != dim)
throw std::invalid_argument("vector size different");
for(auto i(0); i<dim; ++i) (*this)[i] = expr[i];
return *this;
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
return *this = (*this + expr);
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
if(dimension(expr) != dim)
throw std::invalid_argument("vector size different");
return *this = (*this + expr);
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_same_dimension<dim, T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
return *this = (*this - expr);
}
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
if(dimension(expr) != dim)
throw std::invalid_argument("vector size different");
return *this = (*this - expr);
}
Vector<elem_t, dim>& operator*=(const elem_t& expr)
{
return *this = (*this * expr);
}
Vector<elem_t, dim>& operator/=(const elem_t& expr)
{
return *this = (*this / expr);
}
elem_t const& operator[](const std::size_t i) const
{
#ifdef AX_PARANOIAC
return values_.at(i);
#else
return values_[i];
#endif
}
elem_t& operator[](const std::size_t i)
{
#ifdef AX_PARANOIAC
return values_.at(i);
#else
return values_[i];
#endif
}
elem_t const& at(const std::size_t i) const {return values_.at(i);}
elem_t& at(const std::size_t i) {return values_.at(i);}
private:
container_t values_;
};
}
#endif//AX_VECTOR_H
| use dimension(expr) instead of .size() | use dimension(expr) instead of .size()
| C++ | mit | ToruNiina/AX |
81165eb04aca09b619b7371b4b57b9f417c5fce0 | voxblox_ros/src/voxblox_eval.cc | voxblox_ros/src/voxblox_eval.cc | #include <deque>
#include <minkindr_conversions/kindr_msg.h>
#include <minkindr_conversions/kindr_tf.h>
#include <minkindr_conversions/kindr_xml.h>
#include <pcl/conversions.h>
#include <pcl/filters/filter.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_srvs/Empty.h>
#include <tf/transform_listener.h>
#include <visualization_msgs/MarkerArray.h>
#include <voxblox/core/esdf_map.h>
#include <voxblox/core/labeltsdf_map.h>
#include <voxblox/core/occupancy_map.h>
#include <voxblox/core/tsdf_map.h>
#include <voxblox/integrator/esdf_integrator.h>
#include <voxblox/integrator/labeltsdf_integrator.h>
#include <voxblox/integrator/occupancy_integrator.h>
#include <voxblox/integrator/tsdf_integrator.h>
#include <voxblox/io/layer_io.h>
#include <voxblox/io/mesh_ply.h>
#include <voxblox/mesh/mesh_integrator.h>
#include "voxblox_ros/mesh_vis.h"
#include "voxblox_ros/ptcloud_vis.h"
// This binary evaluates a pre-built voxblox map against a provided ground
// truth dataset, provided as pointcloud, and outputs a variety of statistics.
namespace voxblox {
class VoxbloxEvaluator {
public:
VoxbloxEvaluator(const ros::NodeHandle& nh,
const ros::NodeHandle& nh_private);
void evaluate();
void visualize();
bool shouldExit() const { return !visualize_; }
private:
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
// Whether to do the visualizations (involves generating mesh of the TSDF
// layer) and keep alive (for visualization) after finishing the eval.
// Otherwise only outputs the evaluations statistics.
bool visualize_;
// Whether to recolor the voxels by error to the GT before generating a mesh.
bool recolor_by_error_;
// How to color the mesh.
ColorMode color_mode_;
// If visualizing, what TF frame to visualize in.
std::string frame_id_;
// Transformation between the ground truth dataset and the voxblox map.
// The GT is transformed INTO the voxblox coordinate frame.
Transformation T_V_G_;
// Visualization publishers.
ros::Publisher mesh_pub_;
ros::Publisher gt_ptcloud_pub_;
// Core data to compare.
std::shared_ptr<Layer<TsdfVoxel> > tsdf_layer_;
pcl::PointCloud<pcl::PointXYZRGB> gt_ptcloud_;
// Interpolator to get the distance at the exact point in the GT.
Interpolator<TsdfVoxel>::Ptr interpolator_;
// Mesh visualization.
std::shared_ptr<MeshLayer> mesh_layer_;
std::shared_ptr<MeshIntegrator> mesh_integrator_;
};
VoxbloxEvaluator::VoxbloxEvaluator(const ros::NodeHandle& nh,
const ros::NodeHandle& nh_private)
: nh_(nh),
nh_private_(nh_private),
visualize_(true),
recolor_by_error_(false),
frame_id_("world") {
// Load parameters.
nh_private_.param("visualize", visualize_, visualize_);
nh_private_.param("recolor_by_error", recolor_by_error_, recolor_by_error_);
nh_private_.param("frame_id", frame_id_, frame_id_);
// Load transformations.
XmlRpc::XmlRpcValue T_V_G_xml;
if (nh_private_.getParam("T_V_G", T_V_G_xml)) {
kindr::minimal::xmlRpcToKindr(T_V_G_xml, &T_V_G_);
bool invert_static_tranform = false;
nh_private_.param("invert_T_V_G", invert_static_tranform,
invert_static_tranform);
if (invert_static_tranform) {
T_V_G_ = T_V_G_.inverse();
}
}
// Load the actual map and GT.
// Just exit if there's any issues here (this is just an evaluation node,
// after all).
std::string voxblox_file_path, gt_file_path;
CHECK(nh_private_.getParam("voxblox_file_path", voxblox_file_path))
<< "No file path provided for voxblox map! Set the \"voxblox_file_path\" "
"param.";
CHECK(nh_private_.getParam("gt_file_path", gt_file_path))
<< "No file path provided for ground truth pointcloud! Set the "
"\"gt_file_path\" param.";
CHECK(io::LoadLayer<TsdfVoxel>(voxblox_file_path, &tsdf_layer_))
<< "Could not load voxblox map.";
pcl::PLYReader ply_reader;
CHECK_EQ(ply_reader.read(gt_file_path, gt_ptcloud_), 0)
<< "Could not load pointcloud ground truth.";
// Initialize the interpolator.
interpolator_.reset(new Interpolator<TsdfVoxel>(tsdf_layer_.get()));
// If doing visualizations, initialize the publishers.
if (visualize_) {
mesh_pub_ =
nh_private_.advertise<visualization_msgs::MarkerArray>("mesh", 1, true);
gt_ptcloud_pub_ = nh_private_.advertise<pcl::PointCloud<pcl::PointXYZRGB> >(
"gt_ptcloud", 1, true);
std::string color_mode("color");
nh_private_.param("color_mode", color_mode, color_mode);
if (color_mode == "color") {
color_mode_ = ColorMode::kColor;
} else if (color_mode == "height") {
color_mode_ = ColorMode::kHeight;
} else if (color_mode == "normals") {
color_mode_ = ColorMode::kNormals;
} else if (color_mode == "lambert") {
color_mode_ = ColorMode::kLambert;
} else { // Default case is gray.
color_mode_ = ColorMode::kGray;
}
}
std::cout << "Evaluating " << voxblox_file_path << std::endl;
}
void VoxbloxEvaluator::evaluate() {
// First, transform the pointcloud into the correct coordinate frame.
// First, rotate the pointcloud into the world frame.
pcl::transformPointCloud(gt_ptcloud_, gt_ptcloud_,
T_V_G_.getTransformationMatrix());
// Go through each point, use trilateral interpolation to figure out the
// distance at that point.
// This double-counts -- multiple queries to the same voxel will be counted
// separately.
uint64_t total_evaluated_voxels = 0;
uint64_t unknown_voxels = 0;
uint64_t outside_truncation_voxels = 0;
// TODO(helenol): make this dynamic.
double truncation_distance = 2 * tsdf_layer_->voxel_size();
double mse = 0.0;
for (pcl::PointCloud<pcl::PointXYZRGB>::const_iterator it =
gt_ptcloud_.begin();
it != gt_ptcloud_.end(); ++it) {
Point point(it->x, it->y, it->z);
FloatingPoint distance = 0.0;
float weight = 0.0;
bool valid = false;
const float min_weight = 0.01;
const bool interpolate = true;
// We will do multiple lookups -- the first is to determine whether the
// voxel exists.
if (!interpolator_->getNearestDistanceAndWeight(point, &distance,
&weight)) {
unknown_voxels++;
} else if (weight <= min_weight) {
unknown_voxels++;
} else if (distance >= truncation_distance) {
outside_truncation_voxels++;
mse += truncation_distance * truncation_distance;
valid = true;
} else {
// In case this fails, distance is still the nearest neighbor distance.
interpolator_->getDistance(point, &distance, interpolate);
mse += distance * distance;
valid = true;
}
if (valid && visualize_ && recolor_by_error_) {
Layer<TsdfVoxel>::BlockType::Ptr block_ptr =
tsdf_layer_->getBlockPtrByCoordinates(point);
if (block_ptr != nullptr) {
TsdfVoxel& voxel = block_ptr->getVoxelByCoordinates(point);
voxel.color =
grayColorMap(std::fabs(distance) / truncation_distance);
}
}
total_evaluated_voxels++;
}
double rms = sqrt(mse / (total_evaluated_voxels - unknown_voxels));
std::cout << "Finished evaluating.\n"
<< "\nRMS Error: " << rms
<< "\nTotal evaluated: " << total_evaluated_voxels
<< "\nUnknown voxels: " << unknown_voxels << " ("
<< static_cast<double>(unknown_voxels) / total_evaluated_voxels
<< ")\nOutside truncation: " << outside_truncation_voxels << " ("
<< outside_truncation_voxels /
static_cast<double>(total_evaluated_voxels)
<< ")\n";
if (visualize_) {
visualize();
}
}
void VoxbloxEvaluator::visualize() {
// Generate the mesh.
MeshIntegrator::Config mesh_config;
mesh_layer_.reset(new MeshLayer(tsdf_layer_->block_size()));
mesh_integrator_.reset(
new MeshIntegrator(mesh_config, tsdf_layer_.get(), mesh_layer_.get()));
mesh_integrator_->generateWholeMesh();
// Publish mesh.
visualization_msgs::MarkerArray marker_array;
marker_array.markers.resize(1);
fillMarkerWithMesh(mesh_layer_, color_mode_, &marker_array.markers[0]);
mesh_pub_.publish(marker_array);
gt_ptcloud_.header.frame_id = frame_id_;
gt_ptcloud_pub_.publish(gt_ptcloud_);
std::cout << "Finished visualizing.\n";
}
} // namespace voxblox
int main(int argc, char** argv) {
ros::init(argc, argv, "voxblox_node");
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, false);
google::InstallFailureSignalHandler();
ros::NodeHandle nh;
ros::NodeHandle nh_private("~");
voxblox::VoxbloxEvaluator eval(nh, nh_private);
eval.evaluate();
if (!eval.shouldExit()) {
ros::spin();
}
return 0;
}
| #include <deque>
#include <minkindr_conversions/kindr_msg.h>
#include <minkindr_conversions/kindr_tf.h>
#include <minkindr_conversions/kindr_xml.h>
#include <pcl/conversions.h>
#include <pcl/filters/filter.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_srvs/Empty.h>
#include <tf/transform_listener.h>
#include <visualization_msgs/MarkerArray.h>
#include <voxblox/core/esdf_map.h>
#include <voxblox/core/occupancy_map.h>
#include <voxblox/core/tsdf_map.h>
#include <voxblox/integrator/esdf_integrator.h>
#include <voxblox/integrator/occupancy_integrator.h>
#include <voxblox/integrator/tsdf_integrator.h>
#include <voxblox/io/layer_io.h>
#include <voxblox/io/mesh_ply.h>
#include <voxblox/mesh/mesh_integrator.h>
#include "voxblox_ros/mesh_vis.h"
#include "voxblox_ros/ptcloud_vis.h"
// This binary evaluates a pre-built voxblox map against a provided ground
// truth dataset, provided as pointcloud, and outputs a variety of statistics.
namespace voxblox {
class VoxbloxEvaluator {
public:
VoxbloxEvaluator(const ros::NodeHandle& nh,
const ros::NodeHandle& nh_private);
void evaluate();
void visualize();
bool shouldExit() const { return !visualize_; }
private:
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
// Whether to do the visualizations (involves generating mesh of the TSDF
// layer) and keep alive (for visualization) after finishing the eval.
// Otherwise only outputs the evaluations statistics.
bool visualize_;
// Whether to recolor the voxels by error to the GT before generating a mesh.
bool recolor_by_error_;
// How to color the mesh.
ColorMode color_mode_;
// If visualizing, what TF frame to visualize in.
std::string frame_id_;
// Transformation between the ground truth dataset and the voxblox map.
// The GT is transformed INTO the voxblox coordinate frame.
Transformation T_V_G_;
// Visualization publishers.
ros::Publisher mesh_pub_;
ros::Publisher gt_ptcloud_pub_;
// Core data to compare.
std::shared_ptr<Layer<TsdfVoxel> > tsdf_layer_;
pcl::PointCloud<pcl::PointXYZRGB> gt_ptcloud_;
// Interpolator to get the distance at the exact point in the GT.
Interpolator<TsdfVoxel>::Ptr interpolator_;
// Mesh visualization.
std::shared_ptr<MeshLayer> mesh_layer_;
std::shared_ptr<MeshIntegrator> mesh_integrator_;
};
VoxbloxEvaluator::VoxbloxEvaluator(const ros::NodeHandle& nh,
const ros::NodeHandle& nh_private)
: nh_(nh),
nh_private_(nh_private),
visualize_(true),
recolor_by_error_(false),
frame_id_("world") {
// Load parameters.
nh_private_.param("visualize", visualize_, visualize_);
nh_private_.param("recolor_by_error", recolor_by_error_, recolor_by_error_);
nh_private_.param("frame_id", frame_id_, frame_id_);
// Load transformations.
XmlRpc::XmlRpcValue T_V_G_xml;
if (nh_private_.getParam("T_V_G", T_V_G_xml)) {
kindr::minimal::xmlRpcToKindr(T_V_G_xml, &T_V_G_);
bool invert_static_tranform = false;
nh_private_.param("invert_T_V_G", invert_static_tranform,
invert_static_tranform);
if (invert_static_tranform) {
T_V_G_ = T_V_G_.inverse();
}
}
// Load the actual map and GT.
// Just exit if there's any issues here (this is just an evaluation node,
// after all).
std::string voxblox_file_path, gt_file_path;
CHECK(nh_private_.getParam("voxblox_file_path", voxblox_file_path))
<< "No file path provided for voxblox map! Set the \"voxblox_file_path\" "
"param.";
CHECK(nh_private_.getParam("gt_file_path", gt_file_path))
<< "No file path provided for ground truth pointcloud! Set the "
"\"gt_file_path\" param.";
CHECK(io::LoadLayer<TsdfVoxel>(voxblox_file_path, &tsdf_layer_))
<< "Could not load voxblox map.";
pcl::PLYReader ply_reader;
CHECK_EQ(ply_reader.read(gt_file_path, gt_ptcloud_), 0)
<< "Could not load pointcloud ground truth.";
// Initialize the interpolator.
interpolator_.reset(new Interpolator<TsdfVoxel>(tsdf_layer_.get()));
// If doing visualizations, initialize the publishers.
if (visualize_) {
mesh_pub_ =
nh_private_.advertise<visualization_msgs::MarkerArray>("mesh", 1, true);
gt_ptcloud_pub_ = nh_private_.advertise<pcl::PointCloud<pcl::PointXYZRGB> >(
"gt_ptcloud", 1, true);
std::string color_mode("color");
nh_private_.param("color_mode", color_mode, color_mode);
if (color_mode == "color") {
color_mode_ = ColorMode::kColor;
} else if (color_mode == "height") {
color_mode_ = ColorMode::kHeight;
} else if (color_mode == "normals") {
color_mode_ = ColorMode::kNormals;
} else if (color_mode == "lambert") {
color_mode_ = ColorMode::kLambert;
} else { // Default case is gray.
color_mode_ = ColorMode::kGray;
}
}
std::cout << "Evaluating " << voxblox_file_path << std::endl;
}
void VoxbloxEvaluator::evaluate() {
// First, transform the pointcloud into the correct coordinate frame.
// First, rotate the pointcloud into the world frame.
pcl::transformPointCloud(gt_ptcloud_, gt_ptcloud_,
T_V_G_.getTransformationMatrix());
// Go through each point, use trilateral interpolation to figure out the
// distance at that point.
// This double-counts -- multiple queries to the same voxel will be counted
// separately.
uint64_t total_evaluated_voxels = 0;
uint64_t unknown_voxels = 0;
uint64_t outside_truncation_voxels = 0;
// TODO(helenol): make this dynamic.
double truncation_distance = 2 * tsdf_layer_->voxel_size();
double mse = 0.0;
for (pcl::PointCloud<pcl::PointXYZRGB>::const_iterator it =
gt_ptcloud_.begin();
it != gt_ptcloud_.end(); ++it) {
Point point(it->x, it->y, it->z);
FloatingPoint distance = 0.0;
float weight = 0.0;
bool valid = false;
const float min_weight = 0.01;
const bool interpolate = true;
// We will do multiple lookups -- the first is to determine whether the
// voxel exists.
if (!interpolator_->getNearestDistanceAndWeight(point, &distance,
&weight)) {
unknown_voxels++;
} else if (weight <= min_weight) {
unknown_voxels++;
} else if (distance >= truncation_distance) {
outside_truncation_voxels++;
mse += truncation_distance * truncation_distance;
valid = true;
} else {
// In case this fails, distance is still the nearest neighbor distance.
interpolator_->getDistance(point, &distance, interpolate);
mse += distance * distance;
valid = true;
}
if (valid && visualize_ && recolor_by_error_) {
Layer<TsdfVoxel>::BlockType::Ptr block_ptr =
tsdf_layer_->getBlockPtrByCoordinates(point);
if (block_ptr != nullptr) {
TsdfVoxel& voxel = block_ptr->getVoxelByCoordinates(point);
voxel.color =
grayColorMap(std::fabs(distance) / truncation_distance);
}
}
total_evaluated_voxels++;
}
double rms = sqrt(mse / (total_evaluated_voxels - unknown_voxels));
std::cout << "Finished evaluating.\n"
<< "\nRMS Error: " << rms
<< "\nTotal evaluated: " << total_evaluated_voxels
<< "\nUnknown voxels: " << unknown_voxels << " ("
<< static_cast<double>(unknown_voxels) / total_evaluated_voxels
<< ")\nOutside truncation: " << outside_truncation_voxels << " ("
<< outside_truncation_voxels /
static_cast<double>(total_evaluated_voxels)
<< ")\n";
if (visualize_) {
visualize();
}
}
void VoxbloxEvaluator::visualize() {
// Generate the mesh.
MeshIntegrator::Config mesh_config;
mesh_layer_.reset(new MeshLayer(tsdf_layer_->block_size()));
mesh_integrator_.reset(
new MeshIntegrator(mesh_config, tsdf_layer_.get(), mesh_layer_.get()));
mesh_integrator_->generateWholeMesh();
// Publish mesh.
visualization_msgs::MarkerArray marker_array;
marker_array.markers.resize(1);
fillMarkerWithMesh(mesh_layer_, color_mode_, &marker_array.markers[0]);
mesh_pub_.publish(marker_array);
gt_ptcloud_.header.frame_id = frame_id_;
gt_ptcloud_pub_.publish(gt_ptcloud_);
std::cout << "Finished visualizing.\n";
}
} // namespace voxblox
int main(int argc, char** argv) {
ros::init(argc, argv, "voxblox_node");
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, false);
google::InstallFailureSignalHandler();
ros::NodeHandle nh;
ros::NodeHandle nh_private("~");
voxblox::VoxbloxEvaluator eval(nh, nh_private);
eval.evaluate();
if (!eval.shouldExit()) {
ros::spin();
}
return 0;
}
| remove gsm header from voxblox_eval | remove gsm header from voxblox_eval
| C++ | bsd-3-clause | mfehr/voxblox,mfehr/voxblox |
Subsets and Splits