hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
106cc66213980d0299c763ee0a3247c604f64d97 | 7,829 | cc | C++ | src/Modules/Visualization/ShowString.cc | kimjohn1/SCIRun | 62ae6cb632100371831530c755ef0b133fb5c978 | [
"MIT"
] | 92 | 2015-02-09T22:42:11.000Z | 2022-03-25T09:14:50.000Z | src/Modules/Visualization/ShowString.cc | kimjohn1/SCIRun | 62ae6cb632100371831530c755ef0b133fb5c978 | [
"MIT"
] | 1,618 | 2015-01-05T19:39:13.000Z | 2022-03-27T20:28:45.000Z | src/Modules/Visualization/ShowString.cc | kimjohn1/SCIRun | 62ae6cb632100371831530c755ef0b133fb5c978 | [
"MIT"
] | 64 | 2015-02-20T17:51:23.000Z | 2021-11-19T07:08:08.000Z | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/// @todo Documentation Modules/Visualization/ShowString.cc
#include <Modules/Visualization/ShowString.h>
#include <Modules/Visualization/TextBuilder.h>
#include <Core/Datatypes/String.h>
#include <Graphics/Datatypes/GeometryImpl.h>
using namespace SCIRun;
using namespace Modules::Visualization;
using namespace Core::Datatypes;
using namespace Dataflow::Networks;
using namespace Core::Algorithms;
using namespace Core::Algorithms::Visualization;
using namespace Core::Geometry;
using namespace Graphics::Datatypes;
ALGORITHM_PARAMETER_DEF(Visualization, TextRed);
ALGORITHM_PARAMETER_DEF(Visualization, TextGreen);
ALGORITHM_PARAMETER_DEF(Visualization, TextBlue);
ALGORITHM_PARAMETER_DEF(Visualization, TextAlpha);
ALGORITHM_PARAMETER_DEF(Visualization, FontName);
ALGORITHM_PARAMETER_DEF(Visualization, FontSize);
ALGORITHM_PARAMETER_DEF(Visualization, PositionType);
ALGORITHM_PARAMETER_DEF(Visualization, FixedHorizontal);
ALGORITHM_PARAMETER_DEF(Visualization, FixedVertical);
ALGORITHM_PARAMETER_DEF(Visualization, CoordinateHorizontal);
ALGORITHM_PARAMETER_DEF(Visualization, CoordinateVertical);
MODULE_INFO_DEF(ShowString, Visualization, SCIRun)
ShowString::ShowString() : GeometryGeneratingModule(staticInfo_), textBuilder_(makeShared<TextBuilder>())
{
INITIALIZE_PORT(String);
INITIALIZE_PORT(RenderedString);
}
void ShowString::setStateDefaults()
{
auto state = get_state();
state->setValue(Parameters::TextRed, 1.0);
state->setValue(Parameters::TextGreen, 1.0);
state->setValue(Parameters::TextBlue, 1.0);
state->setValue(Parameters::TextAlpha, 1.0);
state->setValue(Parameters::FontSize, 16);
state->setValue(Parameters::FontName, std::string("FreeSansBold"));
state->setValue(Parameters::PositionType, std::string("Preset"));
state->setValue(Parameters::FixedHorizontal, std::string("Left"));
state->setValue(Parameters::FixedVertical, std::string("Top"));
state->setValue(Parameters::CoordinateHorizontal, 0.5);
state->setValue(Parameters::CoordinateVertical, 0.5);
}
void ShowString::execute()
{
auto str = getRequiredInput(String);
if (needToExecute() || needReexecute_)
{
auto geom = buildGeometryObject(str->value());
sendOutput(RenderedString, geom);
needReexecute_ = false;
executedOnce_ = true;
}
}
std::tuple<double, double> ShowString::getTextPosition()
{
auto state = get_state();
auto positionChoice = state->getValue(Parameters::PositionType).toString();
if ("Preset" == positionChoice)
{
double x, y;
auto horizontal = state->getValue(Parameters::FixedHorizontal).toString();
if ("Left" == horizontal)
x = 0.3;
else if ("Center" == horizontal)
x = 1.0;
else // "Right"
x = 1.7;
auto vertical = state->getValue(Parameters::FixedVertical).toString();
if ("Top" == vertical)
y = 1.7;
else if ("Middle" == vertical)
y = 1.0;
else // "Bottom"
y = 0.3;
state->setValue(Parameters::CoordinateHorizontal, x / 2.0);
state->setValue(Parameters::CoordinateVertical, y / 2.0);
return std::make_tuple(x, y);
}
else if ("Coordinates" == positionChoice)
{
return std::make_tuple(2 * state->getValue(Parameters::CoordinateHorizontal).toDouble(),
2 * state->getValue(Parameters::CoordinateVertical).toDouble());
}
else
{
throw "logical error";
}
}
// TODO: clean up duplication here and in ShowColorMap
GeometryBaseHandle ShowString::buildGeometryObject(const std::string& text)
{
std::shared_ptr<spire::VarBuffer> iboBufferSPtr(new spire::VarBuffer(0));
std::shared_ptr<spire::VarBuffer> vboBufferSPtr(new spire::VarBuffer(0));
auto uniqueNodeID = id().id_ + "_showString_" + text;
auto vboName = uniqueNodeID + "VBO";
auto iboName = uniqueNodeID + "IBO";
auto passName = uniqueNodeID + "Pass";
// Construct VBO.
std::string shader = "Shaders/ColorMapLegend";
std::vector<SpireVBO::AttributeData> attribs;
attribs.push_back(SpireVBO::AttributeData("aPos", 3 * sizeof(float)));
attribs.push_back(SpireVBO::AttributeData("aColor", 4 * sizeof(float)));
std::vector<SpireSubPass::Uniform> uniforms;
double xTrans, yTrans;
std::tie(xTrans, yTrans) = getTextPosition();
uniforms.push_back(SpireSubPass::Uniform("uXTranslate", xTrans));
uniforms.push_back(SpireSubPass::Uniform("uYTranslate", yTrans));
SpireVBO geomVBO(vboName, attribs, vboBufferSPtr, 0, BBox(Point{}, Point{}), true);
SpireIBO geomIBO(iboName, SpireIBO::PRIMITIVE::TRIANGLES, sizeof(uint32_t), iboBufferSPtr);
RenderState renState;
renState.set(RenderState::ActionFlags::IS_ON, true);
renState.set(RenderState::ActionFlags::HAS_DATA, true);
SpireText spiretext;
SpireSubPass pass(passName, vboName, iboName, shader,
ColorScheme::COLOR_MAP, renState, RenderType::RENDER_VBO_IBO, geomVBO, geomIBO, spiretext);
// Add all uniforms generated above to the pass.
for (const auto& uniform : uniforms) { pass.addUniform(uniform); }
auto geom(makeShared<GeometryObjectSpire>(*this, "ShowString", false));
geom->ibos().push_back(geomIBO);
geom->vbos().push_back(geomVBO);
geom->passes().push_back(pass);
auto state = get_state();
auto fontSize = state->getValue(Parameters::FontSize).toInt();
auto fontName = state->getValue(Parameters::FontName).toString() + ".ttf";
if (textBuilder_ && textBuilder_->isReady() && textBuilder_->getFontName() != fontName)
{
textBuilder_.reset(new TextBuilder);
}
if (!textBuilder_->initialize(fontSize, fontName))
return geom;
if (textBuilder_->getFaceSize() != fontSize)
textBuilder_->setFaceSize(fontSize);
{
auto r = state->getValue(Parameters::TextRed).toDouble();
auto g = state->getValue(Parameters::TextGreen).toDouble();
auto b = state->getValue(Parameters::TextBlue).toDouble();
auto a = state->getValue(Parameters::TextAlpha).toDouble();
textBuilder_->setColor(r, g, b, a);
}
auto dims = textBuilder_->getStringDims(text);
auto length = std::get<0>(dims) + 20;
auto width = std::get<1>(dims) + 20;
xTrans *= 1 - length / std::get<0>(lastWindowSize_);
yTrans *= 1 - width / std::get<1>(lastWindowSize_);
if (containsDescenderLetter(text))
{
yTrans += 0.02;
}
Vector trans(xTrans, yTrans, 0.0);
textBuilder_->printString(text, trans, Vector(), text, *geom);
return geom;
}
bool ShowString::containsDescenderLetter(const std::string& text)
{
static const std::string descenders("qpygj");
return std::any_of(descenders.begin(), descenders.end(),
[&text](char c) { return text.find(c) != std::string::npos; });
}
| 34.641593 | 105 | 0.730489 | kimjohn1 |
1070e90f63ebb43473dbd60b96fcabe1b2f5d9cb | 20,029 | cpp | C++ | modules/attention_segmentation/src/convertions.cpp | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 17 | 2015-11-16T14:21:10.000Z | 2020-11-09T02:57:33.000Z | modules/attention_segmentation/src/convertions.cpp | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 35 | 2015-07-27T15:04:43.000Z | 2019-08-22T10:52:35.000Z | modules/attention_segmentation/src/convertions.cpp | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 18 | 2015-08-06T09:26:27.000Z | 2020-09-03T01:31:00.000Z | /**
* Copyright (C) 2012
* Ekaterina Potapova
* Automation and Control Institute
* Vienna University of Technology
* Gusshausstraße 25-29
* 1040 Vienna, Austria
* potapova(at)acin.tuwien.ac.at
*
* 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "v4r/attention_segmentation/convertions.h"
namespace v4r
{
#ifndef NOT_USE_PCL
//
void Depth2PointCloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud, pcl::PointIndices::Ptr indices, const cv::Mat depth,
const std::vector<float> cameraParametrs, cv::Mat mask, float th)
{
if( mask.empty() )
{
mask = cv::Mat_<uchar>::ones(depth.size());
}
// check types
assert(mask.type() == CV_8UC1);
assert(depth.type() == CV_32FC1);
assert(mask.size() == depth.size());
float cx, cy, fx, fy;
fx = cameraParametrs.at(0);
fy = cameraParametrs.at(1);
cx = cameraParametrs.at(2);
cy = cameraParametrs.at(3);
cloud->points.clear();
cloud->is_dense = false;
cloud->width = depth.cols;
cloud->height = depth.rows;
cloud->points.reserve(cloud->width * cloud->height);
indices->indices.clear();
for(int i = 0; i < depth.rows; ++i)
{
for(int j = 0; j < depth.cols; ++j)
{
if(mask.at<uchar>(i,j) == 0)
continue;
float z_ir = depth.at<float>(i,j);
if(z_ir < th)
{
pcl::PointXYZRGB point(std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::quiet_NaN());
cloud->points.push_back(point);
continue;
}
float x_ir = ((j - cx) / fx) * z_ir;
float y_ir = ((i - cy) / fy) * z_ir;
pcl::PointXYZRGB point(x_ir,y_ir,z_ir);
cloud->points.push_back(point);
int idx = i*(depth.cols)+j;
indices->indices.push_back(idx);
}
}
cloud->width = cloud->points.size();
cloud->height = 1;
}
//ep:begin: revision at 17-07-2014
void pointCloud_2_depth(cv::Mat &depth, pcl::PointCloud<pcl::PointXYZRGBL>::ConstPtr cloud,
unsigned int width, unsigned int height, pcl::PointIndices::Ptr indices, float th)
{
if( (indices->indices.size()) == 0 )
{
indices->indices.resize(cloud->size());
for(unsigned int i = 0; i < cloud->size(); ++i)
{
indices->indices.at(i) = i;
}
}
// check types
assert( indices->indices.size() <= cloud->size() );
assert( (width*height) == cloud->size() );
assert( cloud->width == width );
assert( cloud->height == height );
depth = cv::Mat_<float>::zeros(height,width);
for(unsigned int i = 0; i < indices->indices.size(); ++i)
{
int idx = indices->indices.at(i);
if(std::isnan(cloud->points.at(idx).x) ||
std::isnan(cloud->points.at(idx).y) ||
std::isnan(cloud->points.at(idx).z))
{
continue;
}
float z_ir = cloud->points.at(idx).z;
if(z_ir < th)
{
continue;
}
int r = idx / width;
int c = idx % width;
depth.at<float>(r,c) = z_ir;
}
}
void pointCloud_2_depth(cv::Mat &depth, pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud,
unsigned int width, unsigned int height, pcl::PointIndices::Ptr indices, float th)
{
if( (indices->indices.size()) == 0 )
{
indices->indices.resize(cloud->size());
for(unsigned int i = 0; i < cloud->size(); ++i)
{
indices->indices.at(i) = i;
}
}
// check types
assert( indices->indices.size() <= cloud->size() );
assert( (width*height) == cloud->size() );
assert( cloud->width == width );
assert( cloud->height == height );
depth = cv::Mat_<float>::zeros(height,width);
for(unsigned int i = 0; i < indices->indices.size(); ++i)
{
int idx = indices->indices.at(i);
if(std::isnan(cloud->points.at(idx).x) ||
std::isnan(cloud->points.at(idx).y) ||
std::isnan(cloud->points.at(idx).z))
{
continue;
}
float z_ir = cloud->points.at(idx).z;
if(z_ir < th)
{
continue;
}
int r = idx / width;
int c = idx % width;
depth.at<float>(r,c) = z_ir;
}
}
void pointCloud_2_rgb(cv::Mat &RGB, pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud_xyzrgb,
unsigned int width, unsigned int height, pcl::PointIndices::Ptr indices)
{
if( (indices->indices.size()) == 0 )
{
indices->indices.resize(cloud_xyzrgb->size());
for(unsigned int i = 0; i < cloud_xyzrgb->size(); ++i)
{
indices->indices.at(i) = i;
}
}
// check types
assert( indices->indices.size() <= cloud_xyzrgb->size() );
assert( (width*height) == cloud_xyzrgb->size() );
assert( cloud_xyzrgb->width == width );
assert( cloud_xyzrgb->height == height );
RGB = cv::Mat::zeros(height,width,CV_8UC3);
for(unsigned int i = 0; i < indices->indices.size(); ++i)
{
int idx = indices->indices.at(i);
int r = idx / width;
int c = idx % width;
RGB.at<uchar>(r,3*c+2) = cloud_xyzrgb->points.at(idx).r;
RGB.at<uchar>(r,3*c+1) = cloud_xyzrgb->points.at(idx).g;
RGB.at<uchar>(r,3*c+0) = cloud_xyzrgb->points.at(idx).b;
}
}
void pointCloud_2_channels(cv::Mat &xchannel, cv::Mat &ychannel, cv::Mat &zchannel, pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud,
unsigned int width, unsigned int height, pcl::PointIndices::Ptr indices, float th)
{
if( (indices->indices.size()) == 0 )
{
indices->indices.resize(cloud->size());
for(unsigned int i = 0; i < cloud->size(); ++i)
{
indices->indices.at(i) = i;
}
}
// check types
assert(indices->indices.size() <= cloud->size());
assert((size_t)(width*height) == cloud->size());
xchannel = cv::Mat_<float>::zeros(height,width);
ychannel = cv::Mat_<float>::zeros(height,width);
zchannel = cv::Mat_<float>::zeros(height,width);
for(unsigned int i = 0; i < indices->indices.size(); ++i)
{
int idx = indices->indices.at(i);
if(std::isnan(cloud->points.at(idx).x) ||
std::isnan(cloud->points.at(idx).y) ||
std::isnan(cloud->points.at(idx).z))
{
continue;
}
float x_ir = cloud->points.at(idx).x;
float y_ir = cloud->points.at(idx).y;
float z_ir = cloud->points.at(idx).z;
if(z_ir < th)
{
continue;
}
int r = idx / width;
int c = idx % width;
xchannel.at<float>(r,c) = x_ir;
ychannel.at<float>(r,c) = y_ir;
zchannel.at<float>(r,c) = z_ir;
}
}
void normals_2_channels(cv::Mat &xnormals, cv::Mat &ynormals, cv::Mat &znormals, pcl::PointCloud<pcl::Normal>::ConstPtr normals,
unsigned int width, unsigned int height, pcl::PointIndices::Ptr indices)
{
// check types
assert(indices->indices.size() == normals->points.size());
xnormals = cv::Mat_<float>::zeros(height,width);
ynormals = cv::Mat_<float>::zeros(height,width);
znormals = cv::Mat_<float>::zeros(height,width);
for(unsigned int i = 0; i < indices->indices.size(); ++i)
{
int idx = indices->indices.at(i);
float x_n = normals->points.at(i).normal[0];
float y_n = normals->points.at(i).normal[1];
float z_n = normals->points.at(i).normal[2];
int r = idx / width;
int c = idx % width;
xnormals.at<float>(r,c) = x_n;
ynormals.at<float>(r,c) = y_n;
znormals.at<float>(r,c) = z_n;
}
}
void pointCloud_2_disparity(cv::Mat &disparity, pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud,
int width, int height, pcl::PointIndices::Ptr indices, float f, float b, float th)
{
if( (indices->indices.size()) == 0 )
{
indices->indices.resize(cloud->size());
for(unsigned int i = 0; i < cloud->size(); ++i)
{
indices->indices.at(i) = i;
}
}
// check types
assert(indices->indices.size() <= cloud->size());
assert((size_t)(width*height) == cloud->size());
cv::Scalar defaultDisparityValue(255);
disparity = cv::Mat(height,width,CV_32FC1,defaultDisparityValue);
for(unsigned int i = 0; i < indices->indices.size(); ++i)
{
int idx = indices->indices.at(i);
if(std::isnan(cloud->points.at(idx).x) ||
std::isnan(cloud->points.at(idx).y) ||
std::isnan(cloud->points.at(idx).z))
{
continue;
}
float z_ir = cloud->points.at(idx).z;
if(z_ir < th)
{
continue;
}
float disp = b*f/z_ir;
if(disp < 0)
{
continue;
}
int r = idx / width;
int c = idx % width;
disparity.at<float>(r,c) = disp;
}
}
//ep:end: revision at 17-07-2014
//
void indices_2_image(cv::Mat &mask, unsigned int width, unsigned int height, pcl::PointIndices::Ptr indices)
{
if( (indices->indices.size()) == 0 )
{
indices->indices.resize(width*height);
for(unsigned int i = 0; i < width*height; ++i)
{
indices->indices.at(i) = i;
}
}
// check types
assert(indices->indices.size() <= (size_t)(width*height));
mask = cv::Mat_<float>::zeros(height,width);
for(unsigned int i = 0; i < indices->indices.size(); ++i)
{
int idx = indices->indices.at(i);
int r = idx / width;
int c = idx % width;
mask.at<float>(r,c) = 255;
}
}
//ep:begin: revision at 17-07-2014
void pointCloudXYZimageRGB_2_cloudXYZRGB(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb,
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz, cv::Mat &RGB, unsigned int width, unsigned int height)
{
// check types
assert( cloud_xyz->height == (unsigned int)RGB.rows );
assert( cloud_xyz->width == (unsigned int)RGB.cols );
assert( cloud_xyz->height == height );
assert( cloud_xyz->width == width );
cloud_xyzrgb->points.resize(cloud_xyz->points.size());
cloud_xyzrgb->width = width;
cloud_xyzrgb->height = height;
for(unsigned int i = 0; i < height; ++i)
{
for(unsigned int j = 0; j < width; ++j)
{
int position = i*width + j;
cloud_xyzrgb->points.at(position).x = cloud_xyz->points.at(position).x;
cloud_xyzrgb->points.at(position).y = cloud_xyz->points.at(position).y;
cloud_xyzrgb->points.at(position).z = cloud_xyz->points.at(position).z;
cloud_xyzrgb->points.at(position).r = RGB.at<uchar>(i,3*j+2);
cloud_xyzrgb->points.at(position).g = RGB.at<uchar>(i,3*j+1);
cloud_xyzrgb->points.at(position).b = RGB.at<uchar>(i,3*j+0);
}
}
}
void depthRGB_2_cloudXYZRGB(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb, const cv::Mat &depth, const cv::Mat &RGB,
const std::vector<float> &cameraParametrs, unsigned int width, unsigned int height, float th)
{
// check types
assert(RGB.type() == CV_8UC3);
assert(depth.type() == CV_32FC1);
assert(RGB.size() == depth.size());
assert( (unsigned int)depth.rows == height );
assert( (unsigned int)depth.cols == width );
float cx, cy, fx, fy;
fx = cameraParametrs.at(0);
fy = cameraParametrs.at(1);
cx = cameraParametrs.at(2);
cy = cameraParametrs.at(3);
cloud_xyzrgb->points.clear();
cloud_xyzrgb->is_dense = false;
cloud_xyzrgb->width = depth.cols;
cloud_xyzrgb->height = depth.rows;
cloud_xyzrgb->points.resize (cloud_xyzrgb->width * cloud_xyzrgb->height);
for(unsigned int i = 0; i < height; ++i)
{
for(unsigned int j = 0; j < width; ++j)
{
float z_ir = depth.at<float>(i,j);
uchar rr = RGB.at<uchar>(i,3*j+2);//(r,3*c+2)
uchar gg = RGB.at<uchar>(i,3*j+1);
uchar bb = RGB.at<uchar>(i,3*j+0);
pcl::PointXYZRGB point;
if(z_ir < th)
{
point.x = std::numeric_limits<float>::quiet_NaN();
point.y = std::numeric_limits<float>::quiet_NaN();
point.z = std::numeric_limits<float>::quiet_NaN();
}
else
{
float x_ir = ((j - cx) / fx) * z_ir;
float y_ir = ((i - cy) / fy) * z_ir;
point.x = x_ir;
point.y = y_ir;
point.z = z_ir;
}
point.r = rr;
point.g = gg;
point.b = bb;
int idx = i*width + j;
cloud_xyzrgb->points.at(idx) = point;
}
}
}
void pointCloudXYZRGB_2_cloudXYZimageRGB(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb,
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz, cv::Mat &RGB, unsigned int width, unsigned int height)
{
assert( height == cloud_xyzrgb->height );
assert( width == cloud_xyzrgb->width );
assert( width*height == cloud_xyzrgb->points.size() );
//cloud_xyz = pcl::PointCloud<pcl::PointXYZ>::Ptr( new pcl::PointCloud<pcl::PointXYZ>() );
cloud_xyz->points.resize(cloud_xyzrgb->points.size());
cloud_xyz->width = width;
cloud_xyz->height = height;
RGB = cv::Mat::zeros(height,width,CV_8UC3);
for (unsigned int i = 0; i < height; i++)
{
for (unsigned int j = 0; j < width; j++)
{
int position = i * width + j;
const pcl::PointXYZRGB pt = cloud_xyzrgb->points.at(position);
cloud_xyz->points.at(position).x = pt.x;
cloud_xyz->points.at(position).y = pt.y;
cloud_xyz->points.at(position).z = pt.z;
RGB.at<uchar>(i,3*j+2) = pt.r;
RGB.at<uchar>(i,3*j+1) = pt.g;
RGB.at<uchar>(i,3*j+0) = pt.b;
}
}
}
void pointCloudXYZimageRGBimageL_2_cloudXYZRGBL(pcl::PointCloud<pcl::PointXYZRGBL>::Ptr cloud_xyzrgbl, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz,
cv::Mat &RGB, cv::Mat &L, unsigned int width, unsigned int height)
{
assert( cloud_xyz->height == (unsigned int)RGB.rows );
assert( cloud_xyz->width == (unsigned int)RGB.cols );
assert( cloud_xyz->height == (unsigned int)L.rows );
assert( cloud_xyz->width == (unsigned int)L.cols );
assert( cloud_xyz->height == height );
assert( cloud_xyz->width == width );
//cloud_xyzrgbl = pcl::PointCloud<pcl::PointXYZRGBL>::Ptr( new pcl::PointCloud<pcl::PointXYZRGBL>() );
cloud_xyzrgbl->points.resize(cloud_xyz->points.size());
cloud_xyzrgbl->width = width;
cloud_xyzrgbl->height = height;
for (unsigned int i = 0; i < height; i++)
{
for (unsigned int j = 0; j < width; j++)
{
int position = i * width + j;
cloud_xyzrgbl->points.at(position).x = cloud_xyz->points.at(position).x;
cloud_xyzrgbl->points.at(position).y = cloud_xyz->points.at(position).y;
cloud_xyzrgbl->points.at(position).z = cloud_xyz->points.at(position).z;
cloud_xyzrgbl->points.at(position).r = RGB.at<uchar>(i,3*j+2);
cloud_xyzrgbl->points.at(position).g = RGB.at<uchar>(i,3*j+1);
cloud_xyzrgbl->points.at(position).b = RGB.at<uchar>(i,3*j+0);
cloud_xyzrgbl->points.at(position).label = L.at<uchar>(i,j);
}
}
}
void pointCloudXYZRGBL_2_cloudXYZimageRGBlableL(pcl::PointCloud<pcl::PointXYZRGBL>::Ptr cloud_xyzrgbl, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz,
cv::Mat &RGB, cv::Mat &L, unsigned int width, unsigned int height)
{
assert( height == cloud_xyzrgbl->height );
assert( width == cloud_xyzrgbl->width );
assert( width*height == cloud_xyzrgbl->points.size() );
//cloud_xyz = pcl::PointCloud<pcl::PointXYZ>::Ptr( new pcl::PointCloud<pcl::PointXYZ>() );
cloud_xyz->points.resize(cloud_xyzrgbl->points.size());
cloud_xyz->width = width;
cloud_xyz->height = height;
RGB = cv::Mat::zeros(height,width,CV_8UC3);
L = cv::Mat::zeros(height,width,CV_8UC1);
for (unsigned int i = 0; i < height; i++)
{
for (unsigned int j = 0; j < width; j++)
{
int position = i * width + j;
const pcl::PointXYZRGBL pt = cloud_xyzrgbl->points.at(position);
cloud_xyz->points.at(position).x = pt.x;
cloud_xyz->points.at(position).y = pt.y;
cloud_xyz->points.at(position).z = pt.z;
RGB.at<uchar>(i,3*j+2) = pt.r;
RGB.at<uchar>(i,3*j+1) = pt.g;
RGB.at<uchar>(i,3*j+0) = pt.b;
L.at<uchar>(i,j) = pt.label;
}
}
}
void pointCloudXYZRGBimageL_2_cloudXYZRGBL(pcl::PointCloud<pcl::PointXYZRGBL>::Ptr cloud_xyzrgbl, pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb,
cv::Mat &L, unsigned int width, unsigned int height)
{
assert( cloud_xyzrgb->height == (unsigned int)L.rows );
assert( cloud_xyzrgb->width == (unsigned int)L.cols );
assert( cloud_xyzrgb->height == height );
assert( cloud_xyzrgb->width == width );
cloud_xyzrgbl->points.resize(cloud_xyzrgb->points.size());
cloud_xyzrgbl->width = width;
cloud_xyzrgbl->height = height;
for (unsigned int i = 0; i < height; i++)
{
for (unsigned int j = 0; j < width; j++)
{
int position = i * width + j;
cloud_xyzrgbl->points.at(position).x = cloud_xyzrgb->points.at(position).x;
cloud_xyzrgbl->points.at(position).y = cloud_xyzrgb->points.at(position).y;
cloud_xyzrgbl->points.at(position).z = cloud_xyzrgb->points.at(position).z;
cloud_xyzrgbl->points.at(position).r = cloud_xyzrgb->points.at(position).r;
cloud_xyzrgbl->points.at(position).g = cloud_xyzrgb->points.at(position).g;
cloud_xyzrgbl->points.at(position).b = cloud_xyzrgb->points.at(position).b;
cloud_xyzrgbl->points.at(position).label = L.at<uchar>(i,j);
}
}
}
void pointCloudXYZRGBL_2_cloudXYZRGBlableL(pcl::PointCloud<pcl::PointXYZRGBL>::Ptr cloud_xyzrgbl, pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb,
cv::Mat &L, unsigned int width, unsigned int height)
{
assert( height == cloud_xyzrgbl->height );
assert( width == cloud_xyzrgbl->width );
assert( width*height == cloud_xyzrgbl->points.size() );
cloud_xyzrgb->points.resize(cloud_xyzrgbl->points.size());
cloud_xyzrgb->width = width;
cloud_xyzrgb->height = height;
L = cv::Mat::zeros(height,width,CV_8UC1);
for (unsigned int i = 0; i < height; i++)
{
for (unsigned int j = 0; j < width; j++)
{
int position = i * width + j;
const pcl::PointXYZRGBL pt = cloud_xyzrgbl->points.at(position);
cloud_xyzrgb->points.at(position).x = pt.x;
cloud_xyzrgb->points.at(position).y = pt.y;
cloud_xyzrgb->points.at(position).z = pt.z;
cloud_xyzrgb->points.at(position).r = pt.r;
cloud_xyzrgb->points.at(position).g = pt.g;
cloud_xyzrgb->points.at(position).b = pt.b;
L.at<uchar>(i,j) = pt.label;
}
}
}
//ep:end: revision at 17-07-2014
//
void binMasksFromClusters(std::vector<cv::Mat> &binMasks, std::vector<pcl::PointIndices::ConstPtr> clusters)
{
binMasks.clear();
binMasks.resize(clusters.size());
for(unsigned int k = 0; k < clusters.size(); ++k)
{
binMasks.at(k) = cv::Mat_<uchar>::zeros(480,640);
for(unsigned int i = 0; i < clusters.at(k)->indices.size(); ++i)
{
int idx = clusters.at(k)->indices.at(i);
int r = idx / 640;
int c = idx % 640;
binMasks.at(k).at<uchar>(r,c) = 255;
}
}
}
#endif
//
void Disparity2Depth(cv::Mat &depth, const cv::Mat disparity, float f, float b)
{
depth = cv::Mat::zeros(disparity.size(),CV_32FC1);
for(int i = 0; i < disparity.rows; ++i)
{
for(int j = 0; j < disparity.cols; ++j)
{
if(disparity.at<float>(i,j) >= 255)
{
continue;
}
float disp = disparity.at<float>(i,j);
float z = b*f/disp;
depth.at<float>(i,j) = z;
}
}
}
void FloatMap2UcharMap(cv::Mat &map_u, const cv::Mat map_f)
{
cv::convertScaleAbs(map_f,map_u,255,0);
}
} //namespace v4r
| 30.028486 | 151 | 0.60692 | ToMadoRe |
107370106c941da471197df74dc396a6fff8cc30 | 2,891 | cpp | C++ | csapex_point_cloud/src/conversion/pointcloud_to_depthimage.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 2 | 2016-09-02T15:33:22.000Z | 2019-05-06T22:09:33.000Z | csapex_point_cloud/src/conversion/pointcloud_to_depthimage.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 1 | 2021-02-14T19:53:30.000Z | 2021-02-14T19:53:30.000Z | csapex_point_cloud/src/conversion/pointcloud_to_depthimage.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 6 | 2016-10-12T00:55:23.000Z | 2021-02-10T17:49:25.000Z |
/// PROJECT
#include <csapex/model/node.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_core_plugins/timestamp_message.h>
#include <csapex_opencv/cv_mat_message.h>
#include <csapex_point_cloud/msg/point_cloud_message.h>
using namespace csapex;
using namespace csapex::connection_types;
namespace csapex
{
class PointCloudToDepthImage : public Node
{
public:
PointCloudToDepthImage()
{
}
void setupParameters(Parameterizable& parameters) override
{
parameters.addParameter(csapex::param::factory::declareRange("scale", 1.0, 1000.0, 1.0, 0.5));
parameters.addParameter(csapex::param::factory::declareBool("fit", false));
}
void setup(csapex::NodeModifier& node_modifier) override
{
input_ = node_modifier.addInput<PointCloudMessage>("PointCloud");
output_ = node_modifier.addOutput<CvMatMessage>("DepthImage");
}
void process() override
{
PointCloudMessage::ConstPtr msg(msg::getMessage<PointCloudMessage>(input_));
boost::apply_visitor(PointCloudMessage::Dispatch<PointCloudToDepthImage>(this, msg), msg->value);
}
template <class PointT>
void inputCloud(typename pcl::PointCloud<PointT>::ConstPtr cloud)
{
unsigned n = cloud->points.size();
apex_assert(cloud->isOrganized());
apex_assert(cloud->width != 0 && cloud->height != 0);
int cols = cloud->width;
int rows = n / cols;
CvMatMessage::Ptr output(new CvMatMessage(enc::depth, cloud->header.frame_id, cloud->header.stamp));
output->value.create(rows, cols, CV_32F);
typename pcl::PointCloud<PointT>::const_iterator pt = cloud->points.begin();
float* data = (float*)output->value.data;
double max_dist = std::numeric_limits<double>::min();
double min_dist = std::numeric_limits<double>::max();
for (unsigned idx = 0; idx < n; ++idx) {
const PointT& p = *pt;
double dist = std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
if (dist != dist)
dist = 0;
*data = dist;
if (dist < min_dist) {
min_dist = dist;
}
if (dist > max_dist) {
max_dist = dist;
}
++data;
++pt;
}
bool fit = readParameter<bool>("fit");
double s = readParameter<double>("scale");
if (fit) {
s = 255.0 / (max_dist - min_dist);
}
output->value = (fit ? (output->value - min_dist) : output->value) * s;
msg::publish(output_, output);
}
private:
Input* input_;
Output* output_;
};
} // namespace csapex
CSAPEX_REGISTER_CLASS(csapex::PointCloudToDepthImage, csapex::Node)
| 28.067961 | 108 | 0.617088 | AdrianZw |
1073f469f8755494b669063ddd5817fddb2c7620 | 3,956 | cpp | C++ | core/model/src/model_math_t.cpp | lkeegan/spatial-model-editor | 5dcb06550607b0a734acddd8b719035b68e35307 | [
"MIT"
] | 4 | 2019-07-18T15:05:09.000Z | 2020-03-14T09:50:07.000Z | core/model/src/model_math_t.cpp | lkeegan/spatial-model-editor | 5dcb06550607b0a734acddd8b719035b68e35307 | [
"MIT"
] | 328 | 2019-06-30T12:03:01.000Z | 2020-10-05T15:56:35.000Z | core/model/src/model_math_t.cpp | lkeegan/spatial-model-editor | 5dcb06550607b0a734acddd8b719035b68e35307 | [
"MIT"
] | 1 | 2019-06-08T22:47:14.000Z | 2019-06-08T22:47:14.000Z | #include "catch_wrapper.hpp"
#include "model_test_utils.hpp"
#include "sme/model.hpp"
#include "sme/model_math.hpp"
#include <QFile>
#include <cmath>
using namespace sme;
using namespace sme::test;
TEST_CASE("SBML math", "[core/model/math][core/model][core][model][math]") {
SECTION("No SBML model, valid expressions") {
model::ModelMath math;
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() == "Empty expression");
math.parse("");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() == "Empty expression");
math.parse("2");
REQUIRE(math.isValid() == true);
REQUIRE(math.getErrorMessage().empty());
REQUIRE(math.eval() == dbl_approx(2));
math.parse("1.1+2.4");
REQUIRE(math.isValid() == true);
REQUIRE(math.getErrorMessage().empty());
REQUIRE(math.eval() == dbl_approx(3.5));
math.parse("cos(0)");
REQUIRE(math.isValid() == true);
REQUIRE(math.getErrorMessage().empty());
REQUIRE(math.eval() == dbl_approx(1));
math.parse("(-2)^2");
REQUIRE(math.isValid() == true);
REQUIRE(math.getErrorMessage().empty());
REQUIRE(math.eval() == dbl_approx(4));
math.parse("(-2)^2");
REQUIRE(math.isValid() == true);
REQUIRE(math.getErrorMessage().empty());
REQUIRE(math.eval() == dbl_approx(4));
model::ModelMath math2;
math2 = std::move(math);
math2.parse("(-2)^2");
REQUIRE(math2.isValid() == true);
}
SECTION("No SBML model, invalid expressions") {
model::ModelMath math;
math.parse("(");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() ==
"Error when parsing input '(' at position 1: syntax error, "
"unexpected end of string");
math.parse("x");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() == "Unknown variable: x");
math.parse("sillyfunction(x)");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() == "Unknown function: sillyfunction");
math.parse("cos(sin(yy))");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() == "Unknown variable: yy");
math.parse("cos(sin(yy)");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() ==
"Error when parsing input 'cos(sin(yy)' at position 11: syntax "
"error, unexpected end of string, expecting ')' or ','");
}
SECTION("SBML model") {
auto model{getExampleModel(Mod::ABtoC)};
auto &funcs = model.getFunctions();
funcs.add("f1");
funcs.addArgument("f1", "x");
funcs.setExpression("f1", "2*x");
model.getFunctions().add("my_func");
funcs.setExpression("my_func", "42");
model.getFunctions().add("my Func!");
auto &math = model.getMath();
std::map<const std::string, std::pair<double, bool>> map;
map["x"] = {1.345, false};
map["y"] = {-0.9, false};
SECTION("Valid expressions") {
math.parse("x");
REQUIRE(math.isValid() == true);
REQUIRE(math.eval(map) == dbl_approx(1.345));
math.parse("x^2 + cos(x)");
REQUIRE(math.isValid() == true);
REQUIRE(math.eval(map) == dbl_approx(1.345 * 1.345 + std::cos(1.345)));
math.parse("x+y");
REQUIRE(math.isValid() == true);
REQUIRE(math.eval(map) == dbl_approx(0.445));
math.parse("f1(x+y)");
REQUIRE(math.isValid() == true);
REQUIRE(math.eval(map) == dbl_approx(0.89));
}
SECTION("Invalid expressions") {
math.parse("x(");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() ==
"Error when parsing input 'x(' at position 2: syntax error, "
"unexpected end of string");
math.parse("zz");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() == "Unknown variable: zz");
math.parse("zz(y)");
REQUIRE(math.isValid() == false);
REQUIRE(math.getErrorMessage() == "Unknown function: zz");
}
}
}
| 36.62963 | 77 | 0.60541 | lkeegan |
1075b208a14f1e7be9140232429ef4b5afe897b8 | 930 | cpp | C++ | LinkedList/palindromell.cpp | riti2409/180DSAProblemsbusted | 4cce47fa61bf2e7cb3b621996e2e327e9ef61ad1 | [
"MIT"
] | 8 | 2021-10-20T02:19:59.000Z | 2022-02-05T16:49:49.000Z | LinkedList/palindromell.cpp | riti2409/180DSAProblemsbusted | 4cce47fa61bf2e7cb3b621996e2e327e9ef61ad1 | [
"MIT"
] | null | null | null | LinkedList/palindromell.cpp | riti2409/180DSAProblemsbusted | 4cce47fa61bf2e7cb3b621996e2e327e9ef61ad1 | [
"MIT"
] | null | null | null | class Solution {
public:
ListNode* reverse(ListNode* head){
ListNode*prev=NULL;
ListNode*curr=head;
ListNode*next;
while(curr!=NULL){
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
return prev;
}
bool isPalindrome(ListNode* head) {
if(head==NULL || head->next==NULL) return true;
ListNode*fast=head;
ListNode*slow=head;
while(fast->next!=NULL && fast->next->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
slow->next=reverse(slow->next);
slow=slow->next;
while(slow!=NULL){
if(head->val!=slow->val){
return false;
}
head=head->next;
slow=slow->next;
}
return true;
}
}; | 25.135135 | 59 | 0.446237 | riti2409 |
1076f1a9d8c7ba961e690f6a0b44e521701554dc | 62,349 | cpp | C++ | cmfe/lib/AST/TypePrinter.cpp | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 115 | 2018-02-01T18:56:44.000Z | 2022-03-21T13:23:00.000Z | cmfe/lib/AST/TypePrinter.cpp | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 27 | 2018-09-17T17:49:49.000Z | 2021-11-03T04:31:51.000Z | cmfe/lib/AST/TypePrinter.cpp | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 55 | 2018-02-01T07:11:49.000Z | 2022-03-04T01:20:23.000Z | //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to print types from Clang's type system.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/Basic/AddressSpaces.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <string>
using namespace clang;
namespace {
/// RAII object that enables printing of the ARC __strong lifetime
/// qualifier.
class IncludeStrongLifetimeRAII {
PrintingPolicy &Policy;
bool Old;
public:
explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
: Policy(Policy), Old(Policy.SuppressStrongLifetime) {
if (!Policy.SuppressLifetimeQualifiers)
Policy.SuppressStrongLifetime = false;
}
~IncludeStrongLifetimeRAII() {
Policy.SuppressStrongLifetime = Old;
}
};
class ParamPolicyRAII {
PrintingPolicy &Policy;
bool Old;
public:
explicit ParamPolicyRAII(PrintingPolicy &Policy)
: Policy(Policy), Old(Policy.SuppressSpecifiers) {
Policy.SuppressSpecifiers = false;
}
~ParamPolicyRAII() {
Policy.SuppressSpecifiers = Old;
}
};
class ElaboratedTypePolicyRAII {
PrintingPolicy &Policy;
bool SuppressTagKeyword;
bool SuppressScope;
public:
explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
SuppressTagKeyword = Policy.SuppressTagKeyword;
SuppressScope = Policy.SuppressScope;
Policy.SuppressTagKeyword = true;
Policy.SuppressScope = true;
}
~ElaboratedTypePolicyRAII() {
Policy.SuppressTagKeyword = SuppressTagKeyword;
Policy.SuppressScope = SuppressScope;
}
};
class TypePrinter {
PrintingPolicy Policy;
unsigned Indentation;
bool HasEmptyPlaceHolder = false;
bool InsideCCAttribute = false;
public:
explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0)
: Policy(Policy), Indentation(Indentation) {}
void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
StringRef PlaceHolder);
void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
void spaceBeforePlaceHolder(raw_ostream &OS);
void printTypeSpec(NamedDecl *D, raw_ostream &OS);
void printBefore(QualType T, raw_ostream &OS);
void printAfter(QualType T, raw_ostream &OS);
void AppendScope(DeclContext *DC, raw_ostream &OS);
void printTag(TagDecl *T, raw_ostream &OS);
void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS);
#define ABSTRACT_TYPE(CLASS, PARENT)
#define TYPE(CLASS, PARENT) \
void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
#include "clang/AST/TypeNodes.def"
private:
void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
};
} // namespace
static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
bool HasRestrictKeyword) {
bool appendSpace = false;
if (TypeQuals & Qualifiers::Const) {
OS << "const";
appendSpace = true;
}
if (TypeQuals & Qualifiers::Volatile) {
if (appendSpace) OS << ' ';
OS << "volatile";
appendSpace = true;
}
if (TypeQuals & Qualifiers::Restrict) {
if (appendSpace) OS << ' ';
if (HasRestrictKeyword) {
OS << "restrict";
} else {
OS << "__restrict";
}
}
}
void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
if (!HasEmptyPlaceHolder)
OS << ' ';
}
static SplitQualType splitAccordingToPolicy(QualType QT,
const PrintingPolicy &Policy) {
if (Policy.PrintCanonicalTypes)
QT = QT.getCanonicalType();
return QT.split();
}
void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
SplitQualType split = splitAccordingToPolicy(t, Policy);
print(split.Ty, split.Quals, OS, PlaceHolder);
}
void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
StringRef PlaceHolder) {
if (!T) {
OS << "NULL TYPE";
return;
}
SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
printBefore(T, Quals, OS);
OS << PlaceHolder;
printAfter(T, Quals, OS);
}
bool TypePrinter::canPrefixQualifiers(const Type *T,
bool &NeedARCStrongQualifier) {
// CanPrefixQualifiers - We prefer to print type qualifiers before the type,
// so that we get "const int" instead of "int const", but we can't do this if
// the type is complex. For example if the type is "int*", we *must* print
// "int * const", printing "const int *" is different. Only do this when the
// type expands to a simple string.
bool CanPrefixQualifiers = false;
NeedARCStrongQualifier = false;
Type::TypeClass TC = T->getTypeClass();
if (const auto *AT = dyn_cast<AutoType>(T))
TC = AT->desugar()->getTypeClass();
if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T))
TC = Subst->getReplacementType()->getTypeClass();
switch (TC) {
case Type::Auto:
case Type::Builtin:
case Type::Complex:
case Type::UnresolvedUsing:
case Type::Typedef:
case Type::TypeOfExpr:
case Type::TypeOf:
case Type::Decltype:
case Type::UnaryTransform:
case Type::Record:
case Type::Enum:
case Type::Elaborated:
case Type::TemplateTypeParm:
case Type::SubstTemplateTypeParmPack:
case Type::DeducedTemplateSpecialization:
case Type::TemplateSpecialization:
case Type::InjectedClassName:
case Type::DependentName:
case Type::DependentTemplateSpecialization:
case Type::ObjCObject:
case Type::ObjCTypeParam:
case Type::ObjCInterface:
case Type::Atomic:
case Type::Pipe:
CanPrefixQualifiers = true;
break;
case Type::ObjCObjectPointer:
CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
break;
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
case Type::DependentSizedArray:
NeedARCStrongQualifier = true;
LLVM_FALLTHROUGH;
case Type::Adjusted:
case Type::Decayed:
case Type::Pointer:
case Type::BlockPointer:
case Type::LValueReference:
case Type::RValueReference:
case Type::MemberPointer:
case Type::DependentAddressSpace:
case Type::DependentVector:
case Type::DependentSizedExtVector:
case Type::Vector:
case Type::ExtVector:
case Type::CMVector:
case Type::CMMatrix:
case Type::DependentCMVector:
case Type::DependentCMMatrix:
case Type::FunctionProto:
case Type::FunctionNoProto:
case Type::Paren:
case Type::Attributed:
case Type::PackExpansion:
case Type::SubstTemplateTypeParm:
CanPrefixQualifiers = false;
break;
}
return CanPrefixQualifiers;
}
void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
SplitQualType Split = splitAccordingToPolicy(T, Policy);
// If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
// at this level.
Qualifiers Quals = Split.Quals;
if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
Quals -= QualType(Subst, 0).getQualifiers();
printBefore(Split.Ty, Quals, OS);
}
/// Prints the part of the type string before an identifier, e.g. for
/// "int foo[10]" it prints "int ".
void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
if (Policy.SuppressSpecifiers && T->isSpecifierType())
return;
SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
// Print qualifiers as appropriate.
bool CanPrefixQualifiers = false;
bool NeedARCStrongQualifier = false;
CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
if (CanPrefixQualifiers && !Quals.empty()) {
if (NeedARCStrongQualifier) {
IncludeStrongLifetimeRAII Strong(Policy);
Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
} else {
Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
}
}
bool hasAfterQuals = false;
if (!CanPrefixQualifiers && !Quals.empty()) {
hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
if (hasAfterQuals)
HasEmptyPlaceHolder = false;
}
switch (T->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, PARENT)
#define TYPE(CLASS, PARENT) case Type::CLASS: \
print##CLASS##Before(cast<CLASS##Type>(T), OS); \
break;
#include "clang/AST/TypeNodes.def"
}
if (hasAfterQuals) {
if (NeedARCStrongQualifier) {
IncludeStrongLifetimeRAII Strong(Policy);
Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
} else {
Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
}
}
}
void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
SplitQualType split = splitAccordingToPolicy(t, Policy);
printAfter(split.Ty, split.Quals, OS);
}
/// Prints the part of the type string after an identifier, e.g. for
/// "int foo[10]" it prints "[10]".
void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
switch (T->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, PARENT)
#define TYPE(CLASS, PARENT) case Type::CLASS: \
print##CLASS##After(cast<CLASS##Type>(T), OS); \
break;
#include "clang/AST/TypeNodes.def"
}
}
void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
OS << T->getName(Policy);
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {}
void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
OS << "_Complex ";
printBefore(T->getElementType(), OS);
}
void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
printAfter(T->getElementType(), OS);
}
void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printBefore(T->getPointeeType(), OS);
// Handle things like 'int (*A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(T->getPointeeType()))
OS << '(';
OS << '*';
}
void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
// Handle things like 'int (*A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(T->getPointeeType()))
OS << ')';
printAfter(T->getPointeeType(), OS);
}
void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
raw_ostream &OS) {
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printBefore(T->getPointeeType(), OS);
OS << '^';
}
void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
raw_ostream &OS) {
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printAfter(T->getPointeeType(), OS);
}
// When printing a reference, the referenced type might also be a reference.
// If so, we want to skip that before printing the inner type.
static QualType skipTopLevelReferences(QualType T) {
if (auto *Ref = T->getAs<ReferenceType>())
return skipTopLevelReferences(Ref->getPointeeTypeAsWritten());
return T;
}
void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
printBefore(Inner, OS);
// Handle things like 'int (&A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(Inner))
OS << '(';
OS << '&';
}
void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
// Handle things like 'int (&A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(Inner))
OS << ')';
printAfter(Inner, OS);
}
void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
printBefore(Inner, OS);
// Handle things like 'int (&&A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(Inner))
OS << '(';
OS << "&&";
}
void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
// Handle things like 'int (&&A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(Inner))
OS << ')';
printAfter(Inner, OS);
}
void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printBefore(T->getPointeeType(), OS);
// Handle things like 'int (Cls::*A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(T->getPointeeType()))
OS << '(';
PrintingPolicy InnerPolicy(Policy);
InnerPolicy.IncludeTagDefinition = false;
TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
OS << "::*";
}
void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
// Handle things like 'int (Cls::*A)[4];' correctly.
// FIXME: this should include vectors, but vectors use attributes I guess.
if (isa<ArrayType>(T->getPointeeType()))
OS << ')';
printAfter(T->getPointeeType(), OS);
}
void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printBefore(T->getElementType(), OS);
}
void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
raw_ostream &OS) {
OS << '[';
if (T->getIndexTypeQualifiers().hasQualifiers()) {
AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
Policy.Restrict);
OS << ' ';
}
if (T->getSizeModifier() == ArrayType::Static)
OS << "static ";
OS << T->getSize().getZExtValue() << ']';
printAfter(T->getElementType(), OS);
}
void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printBefore(T->getElementType(), OS);
}
void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
raw_ostream &OS) {
OS << "[]";
printAfter(T->getElementType(), OS);
}
void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printBefore(T->getElementType(), OS);
}
void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
raw_ostream &OS) {
OS << '[';
if (T->getIndexTypeQualifiers().hasQualifiers()) {
AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
OS << ' ';
}
if (T->getSizeModifier() == VariableArrayType::Static)
OS << "static ";
else if (T->getSizeModifier() == VariableArrayType::Star)
OS << '*';
if (T->getSizeExpr())
T->getSizeExpr()->printPretty(OS, nullptr, Policy);
OS << ']';
printAfter(T->getElementType(), OS);
}
void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) {
// Print the adjusted representation, otherwise the adjustment will be
// invisible.
printBefore(T->getAdjustedType(), OS);
}
void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) {
printAfter(T->getAdjustedType(), OS);
}
void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
// Print as though it's a pointer.
printAdjustedBefore(T, OS);
}
void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
printAdjustedAfter(T, OS);
}
void TypePrinter::printDependentSizedArrayBefore(
const DependentSizedArrayType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
printBefore(T->getElementType(), OS);
}
void TypePrinter::printDependentSizedArrayAfter(
const DependentSizedArrayType *T,
raw_ostream &OS) {
OS << '[';
if (T->getSizeExpr())
T->getSizeExpr()->printPretty(OS, nullptr, Policy);
OS << ']';
printAfter(T->getElementType(), OS);
}
void TypePrinter::printDependentAddressSpaceBefore(
const DependentAddressSpaceType *T, raw_ostream &OS) {
printBefore(T->getPointeeType(), OS);
}
void TypePrinter::printDependentAddressSpaceAfter(
const DependentAddressSpaceType *T, raw_ostream &OS) {
OS << " __attribute__((address_space(";
if (T->getAddrSpaceExpr())
T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy);
OS << ")))";
printAfter(T->getPointeeType(), OS);
}
void TypePrinter::printDependentSizedExtVectorBefore(
const DependentSizedExtVectorType *T,
raw_ostream &OS) {
printBefore(T->getElementType(), OS);
}
void TypePrinter::printDependentSizedExtVectorAfter(
const DependentSizedExtVectorType *T,
raw_ostream &OS) {
OS << " __attribute__((ext_vector_type(";
if (T->getSizeExpr())
T->getSizeExpr()->printPretty(OS, nullptr, Policy);
OS << ")))";
printAfter(T->getElementType(), OS);
}
void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
switch (T->getVectorKind()) {
case VectorType::AltiVecPixel:
OS << "__vector __pixel ";
break;
case VectorType::AltiVecBool:
OS << "__vector __bool ";
printBefore(T->getElementType(), OS);
break;
case VectorType::AltiVecVector:
OS << "__vector ";
printBefore(T->getElementType(), OS);
break;
case VectorType::NeonVector:
OS << "__attribute__((neon_vector_type("
<< T->getNumElements() << "))) ";
printBefore(T->getElementType(), OS);
break;
case VectorType::NeonPolyVector:
OS << "__attribute__((neon_polyvector_type(" <<
T->getNumElements() << "))) ";
printBefore(T->getElementType(), OS);
break;
case VectorType::GenericVector: {
// FIXME: We prefer to print the size directly here, but have no way
// to get the size of the type.
OS << "__attribute__((__vector_size__("
<< T->getNumElements()
<< " * sizeof(";
print(T->getElementType(), OS, StringRef());
OS << ")))) ";
printBefore(T->getElementType(), OS);
break;
}
}
}
void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
printAfter(T->getElementType(), OS);
}
void TypePrinter::printDependentVectorBefore(
const DependentVectorType *T, raw_ostream &OS) {
switch (T->getVectorKind()) {
case VectorType::AltiVecPixel:
OS << "__vector __pixel ";
break;
case VectorType::AltiVecBool:
OS << "__vector __bool ";
printBefore(T->getElementType(), OS);
break;
case VectorType::AltiVecVector:
OS << "__vector ";
printBefore(T->getElementType(), OS);
break;
case VectorType::NeonVector:
OS << "__attribute__((neon_vector_type(";
if (T->getSizeExpr())
T->getSizeExpr()->printPretty(OS, nullptr, Policy);
OS << "))) ";
printBefore(T->getElementType(), OS);
break;
case VectorType::NeonPolyVector:
OS << "__attribute__((neon_polyvector_type(";
if (T->getSizeExpr())
T->getSizeExpr()->printPretty(OS, nullptr, Policy);
OS << "))) ";
printBefore(T->getElementType(), OS);
break;
case VectorType::GenericVector: {
// FIXME: We prefer to print the size directly here, but have no way
// to get the size of the type.
OS << "__attribute__((__vector_size__(";
if (T->getSizeExpr())
T->getSizeExpr()->printPretty(OS, nullptr, Policy);
OS << " * sizeof(";
print(T->getElementType(), OS, StringRef());
OS << ")))) ";
printBefore(T->getElementType(), OS);
break;
}
}
}
void TypePrinter::printDependentVectorAfter(
const DependentVectorType *T, raw_ostream &OS) {
printAfter(T->getElementType(), OS);
}
void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
raw_ostream &OS) {
printBefore(T->getElementType(), OS);
}
void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
printAfter(T->getElementType(), OS);
OS << " __attribute__((ext_vector_type(";
OS << T->getNumElements();
OS << ")))";
}
void TypePrinter::printCMVectorBefore(const CMVectorType *T,
raw_ostream &OS) {
if (T->isReference())
OS << "vector_ref<";
else
OS << "vector<";
printBefore(T->getElementType(), OS);
OS << ',';
OS << T->getNumElements();
OS << '>';
}
void TypePrinter::printCMVectorAfter(const CMVectorType *T,
raw_ostream &OS) {
printAfter(T->getElementType(), OS);
}
void TypePrinter::printDependentCMVectorBefore(const DependentCMVectorType *T,
raw_ostream &OS) {
if (T->isReference())
OS << "vector_ref<";
else
OS << "vector<";
printBefore(T->getElementType(), OS);
OS << ',';
if (T->getSizeExpr())
T->getSizeExpr()->printPretty(OS, 0, Policy);
OS << '>';
}
void TypePrinter::printDependentCMVectorAfter(const DependentCMVectorType *T,
raw_ostream &OS) {
printAfter(T->getElementType(), OS);
}
void TypePrinter::printCMMatrixBefore(const CMMatrixType *T,
raw_ostream &OS) {
if (T->isReference())
OS << "matrix_ref<";
else
OS << "matrix<";
printBefore(T->getElementType(), OS);
OS << ',';
OS << T->getNumRows();
OS << ',';
OS << T->getNumColumns();
OS << '>';
}
void TypePrinter::printCMMatrixAfter(const CMMatrixType *T,
raw_ostream &OS) {
printAfter(T->getElementType(), OS);
}
void TypePrinter::printDependentCMMatrixBefore(const DependentCMMatrixType *T,
raw_ostream &OS) {
if (T->isReference())
OS << "matrix_ref<";
else
OS << "matrix<";
printBefore(T->getElementType(), OS);
OS << ',';
if (T->getNumRowExpr())
T->getNumRowExpr()->printPretty(OS, 0, Policy);
OS << ',';
if (T->getNumColumnExpr())
T->getNumColumnExpr()->printPretty(OS, 0, Policy);
OS << '>';
}
void TypePrinter::printDependentCMMatrixAfter(const DependentCMMatrixType *T,
raw_ostream &OS) {
printAfter(T->getElementType(), OS);
}
void
FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
const PrintingPolicy &Policy)
const {
if (hasDynamicExceptionSpec()) {
OS << " throw(";
if (getExceptionSpecType() == EST_MSAny)
OS << "...";
else
for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
if (I)
OS << ", ";
OS << getExceptionType(I).stream(Policy);
}
OS << ')';
} else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
OS << " noexcept";
// FIXME:Is it useful to print out the expression for a non-dependent
// noexcept specification?
if (isComputedNoexcept(getExceptionSpecType())) {
OS << '(';
if (getNoexceptExpr())
getNoexceptExpr()->printPretty(OS, nullptr, Policy);
OS << ')';
}
}
}
void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
raw_ostream &OS) {
if (T->hasTrailingReturn()) {
OS << "auto ";
if (!HasEmptyPlaceHolder)
OS << '(';
} else {
// If needed for precedence reasons, wrap the inner part in grouping parens.
SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
printBefore(T->getReturnType(), OS);
if (!PrevPHIsEmpty.get())
OS << '(';
}
}
StringRef clang::getParameterABISpelling(ParameterABI ABI) {
switch (ABI) {
case ParameterABI::Ordinary:
llvm_unreachable("asking for spelling of ordinary parameter ABI");
case ParameterABI::SwiftContext:
return "swift_context";
case ParameterABI::SwiftErrorResult:
return "swift_error_result";
case ParameterABI::SwiftIndirectResult:
return "swift_indirect_result";
}
llvm_unreachable("bad parameter ABI kind");
}
void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
raw_ostream &OS) {
// If needed for precedence reasons, wrap the inner part in grouping parens.
if (!HasEmptyPlaceHolder)
OS << ')';
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
OS << '(';
{
ParamPolicyRAII ParamPolicy(Policy);
for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
if (i) OS << ", ";
auto EPI = T->getExtParameterInfo(i);
if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
if (EPI.isNoEscape())
OS << "__attribute__((noescape)) ";
auto ABI = EPI.getABI();
if (ABI != ParameterABI::Ordinary)
OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
print(T->getParamType(i), OS, StringRef());
}
}
if (T->isVariadic()) {
if (T->getNumParams())
OS << ", ";
OS << "...";
} else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
// Do not emit int() if we have a proto, emit 'int(void)'.
OS << "void";
}
OS << ')';
FunctionType::ExtInfo Info = T->getExtInfo();
printFunctionAfter(Info, OS);
if (!T->getTypeQuals().empty())
OS << " " << T->getTypeQuals().getAsString();
switch (T->getRefQualifier()) {
case RQ_None:
break;
case RQ_LValue:
OS << " &";
break;
case RQ_RValue:
OS << " &&";
break;
}
T->printExceptionSpecification(OS, Policy);
if (T->hasTrailingReturn()) {
OS << " -> ";
print(T->getReturnType(), OS, StringRef());
} else
printAfter(T->getReturnType(), OS);
}
void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
raw_ostream &OS) {
if (!InsideCCAttribute) {
switch (Info.getCC()) {
case CC_C:
// The C calling convention is the default on the vast majority of platforms
// we support. If the user wrote it explicitly, it will usually be printed
// while traversing the AttributedType. If the type has been desugared, let
// the canonical spelling be the implicit calling convention.
// FIXME: It would be better to be explicit in certain contexts, such as a
// cdecl function typedef used to declare a member function with the
// Microsoft C++ ABI.
break;
case CC_X86StdCall:
OS << " __attribute__((stdcall))";
break;
case CC_X86FastCall:
OS << " __attribute__((fastcall))";
break;
case CC_X86ThisCall:
OS << " __attribute__((thiscall))";
break;
case CC_X86VectorCall:
OS << " __attribute__((vectorcall))";
break;
case CC_X86Pascal:
OS << " __attribute__((pascal))";
break;
case CC_AAPCS:
OS << " __attribute__((pcs(\"aapcs\")))";
break;
case CC_AAPCS_VFP:
OS << " __attribute__((pcs(\"aapcs-vfp\")))";
break;
case CC_AArch64VectorCall:
OS << "__attribute__((aarch64_vector_pcs))";
break;
case CC_IntelOclBicc:
OS << " __attribute__((intel_ocl_bicc))";
break;
case CC_Win64:
OS << " __attribute__((ms_abi))";
break;
case CC_X86_64SysV:
OS << " __attribute__((sysv_abi))";
break;
case CC_X86RegCall:
OS << " __attribute__((regcall))";
break;
case CC_SpirFunction:
case CC_OpenCLKernel:
// Do nothing. These CCs are not available as attributes.
break;
case CC_Swift:
OS << " __attribute__((swiftcall))";
break;
case CC_PreserveMost:
OS << " __attribute__((preserve_most))";
break;
case CC_PreserveAll:
OS << " __attribute__((preserve_all))";
break;
}
}
if (Info.getNoReturn())
OS << " __attribute__((noreturn))";
if (Info.getProducesResult())
OS << " __attribute__((ns_returns_retained))";
if (Info.getRegParm())
OS << " __attribute__((regparm ("
<< Info.getRegParm() << ")))";
if (Info.getNoCallerSavedRegs())
OS << " __attribute__((no_caller_saved_registers))";
if (Info.getNoCfCheck())
OS << " __attribute__((nocf_check))";
}
void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
raw_ostream &OS) {
// If needed for precedence reasons, wrap the inner part in grouping parens.
SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
printBefore(T->getReturnType(), OS);
if (!PrevPHIsEmpty.get())
OS << '(';
}
void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
raw_ostream &OS) {
// If needed for precedence reasons, wrap the inner part in grouping parens.
if (!HasEmptyPlaceHolder)
OS << ')';
SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
OS << "()";
printFunctionAfter(T->getExtInfo(), OS);
printAfter(T->getReturnType(), OS);
}
void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
// Compute the full nested-name-specifier for this type.
// In C, this will always be empty except when the type
// being printed is anonymous within other Record.
if (!Policy.SuppressScope)
AppendScope(D->getDeclContext(), OS);
IdentifierInfo *II = D->getIdentifier();
OS << II->getName();
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
raw_ostream &OS) {
printTypeSpec(T->getDecl(), OS);
}
void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
raw_ostream &OS) {}
void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
printTypeSpec(T->getDecl(), OS);
}
void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
raw_ostream &OS) {
OS << "typeof ";
if (T->getUnderlyingExpr())
T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
raw_ostream &OS) {}
void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
OS << "typeof(";
print(T->getUnderlyingType(), OS, StringRef());
OS << ')';
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
OS << "decltype(";
if (T->getUnderlyingExpr())
T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
OS << ')';
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
switch (T->getUTTKind()) {
case UnaryTransformType::EnumUnderlyingType:
OS << "__underlying_type(";
print(T->getBaseType(), OS, StringRef());
OS << ')';
spaceBeforePlaceHolder(OS);
return;
}
printBefore(T->getBaseType(), OS);
}
void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
switch (T->getUTTKind()) {
case UnaryTransformType::EnumUnderlyingType:
return;
}
printAfter(T->getBaseType(), OS);
}
void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
// If the type has been deduced, do not print 'auto'.
if (!T->getDeducedType().isNull()) {
printBefore(T->getDeducedType(), OS);
} else {
switch (T->getKeyword()) {
case AutoTypeKeyword::Auto: OS << "auto"; break;
case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
}
spaceBeforePlaceHolder(OS);
}
}
void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
// If the type has been deduced, do not print 'auto'.
if (!T->getDeducedType().isNull())
printAfter(T->getDeducedType(), OS);
}
void TypePrinter::printDeducedTemplateSpecializationBefore(
const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
// If the type has been deduced, print the deduced type.
if (!T->getDeducedType().isNull()) {
printBefore(T->getDeducedType(), OS);
} else {
IncludeStrongLifetimeRAII Strong(Policy);
T->getTemplateName().print(OS, Policy);
spaceBeforePlaceHolder(OS);
}
}
void TypePrinter::printDeducedTemplateSpecializationAfter(
const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
// If the type has been deduced, print the deduced type.
if (!T->getDeducedType().isNull())
printAfter(T->getDeducedType(), OS);
}
void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
OS << "_Atomic(";
print(T->getValueType(), OS, StringRef());
OS << ')';
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {}
void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
if (T->isReadOnly())
OS << "read_only ";
else
OS << "write_only ";
OS << "pipe ";
print(T->getElementType(), OS, StringRef());
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {}
/// Appends the given scope to the end of a string.
void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
if (DC->isTranslationUnit()) return;
if (DC->isFunctionOrMethod()) return;
AppendScope(DC->getParent(), OS);
if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
if (Policy.SuppressUnwrittenScope &&
(NS->isAnonymousNamespace() || NS->isInline()))
return;
if (NS->getIdentifier())
OS << NS->getName() << "::";
else
OS << "(anonymous namespace)::";
} else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
IncludeStrongLifetimeRAII Strong(Policy);
OS << Spec->getIdentifier()->getName();
const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
printTemplateArgumentList(OS, TemplateArgs.asArray(), Policy);
OS << "::";
} else if (const auto *Tag = dyn_cast<TagDecl>(DC)) {
if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
OS << Typedef->getIdentifier()->getName() << "::";
else if (Tag->getIdentifier())
OS << Tag->getIdentifier()->getName() << "::";
else
return;
}
}
void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
if (Policy.IncludeTagDefinition) {
PrintingPolicy SubPolicy = Policy;
SubPolicy.IncludeTagDefinition = false;
D->print(OS, SubPolicy, Indentation);
spaceBeforePlaceHolder(OS);
return;
}
bool HasKindDecoration = false;
// We don't print tags unless this is an elaborated type.
// In C, we just assume every RecordType is an elaborated type.
if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
HasKindDecoration = true;
OS << D->getKindName();
OS << ' ';
}
// Compute the full nested-name-specifier for this type.
// In C, this will always be empty except when the type
// being printed is anonymous within other Record.
if (!Policy.SuppressScope)
AppendScope(D->getDeclContext(), OS);
if (const IdentifierInfo *II = D->getIdentifier())
OS << II->getName();
else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
assert(Typedef->getIdentifier() && "Typedef without identifier?");
OS << Typedef->getIdentifier()->getName();
} else {
// Make an unambiguous representation for anonymous types, e.g.
// (anonymous enum at /usr/include/string.h:120:9)
OS << (Policy.MSVCFormatting ? '`' : '(');
if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
OS << "lambda";
HasKindDecoration = true;
} else {
OS << "anonymous";
}
if (Policy.AnonymousTagLocations) {
// Suppress the redundant tag keyword if we just printed one.
// We don't have to worry about ElaboratedTypes here because you can't
// refer to an anonymous type with one.
if (!HasKindDecoration)
OS << " " << D->getKindName();
PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
D->getLocation());
if (PLoc.isValid()) {
OS << " at ";
StringRef File = PLoc.getFilename();
if (Policy.RemapFilePaths)
OS << Policy.remapPath(File);
else
OS << File;
OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
}
}
OS << (Policy.MSVCFormatting ? '\'' : ')');
}
// If this is a class template specialization, print the template
// arguments.
if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
ArrayRef<TemplateArgument> Args;
if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
const TemplateSpecializationType *TST =
cast<TemplateSpecializationType>(TAW->getType());
Args = TST->template_arguments();
} else {
const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Args = TemplateArgs.asArray();
}
IncludeStrongLifetimeRAII Strong(Policy);
printTemplateArgumentList(OS, Args, Policy);
}
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
printTag(T->getDecl(), OS);
}
void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {}
void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
printTag(T->getDecl(), OS);
}
void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {}
void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
raw_ostream &OS) {
if (IdentifierInfo *Id = T->getIdentifier())
OS << Id->getName();
else
OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
raw_ostream &OS) {}
void TypePrinter::printSubstTemplateTypeParmBefore(
const SubstTemplateTypeParmType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
printBefore(T->getReplacementType(), OS);
}
void TypePrinter::printSubstTemplateTypeParmAfter(
const SubstTemplateTypeParmType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
printAfter(T->getReplacementType(), OS);
}
void TypePrinter::printSubstTemplateTypeParmPackBefore(
const SubstTemplateTypeParmPackType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
}
void TypePrinter::printSubstTemplateTypeParmPackAfter(
const SubstTemplateTypeParmPackType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
}
void TypePrinter::printTemplateSpecializationBefore(
const TemplateSpecializationType *T,
raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
T->getTemplateName().print(OS, Policy);
printTemplateArgumentList(OS, T->template_arguments(), Policy);
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printTemplateSpecializationAfter(
const TemplateSpecializationType *T,
raw_ostream &OS) {}
void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
raw_ostream &OS) {
printTemplateSpecializationBefore(T->getInjectedTST(), OS);
}
void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
raw_ostream &OS) {}
void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
raw_ostream &OS) {
if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) {
TagDecl *OwnedTagDecl = T->getOwnedTagDecl();
assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() &&
"OwnedTagDecl expected to be a declaration for the type");
PrintingPolicy SubPolicy = Policy;
SubPolicy.IncludeTagDefinition = false;
OwnedTagDecl->print(OS, SubPolicy, Indentation);
spaceBeforePlaceHolder(OS);
return;
}
// The tag definition will take care of these.
if (!Policy.IncludeTagDefinition)
{
OS << TypeWithKeyword::getKeywordName(T->getKeyword());
if (T->getKeyword() != ETK_None)
OS << " ";
NestedNameSpecifier *Qualifier = T->getQualifier();
if (Qualifier)
Qualifier->print(OS, Policy);
}
ElaboratedTypePolicyRAII PolicyRAII(Policy);
printBefore(T->getNamedType(), OS);
}
void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
raw_ostream &OS) {
if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
return;
ElaboratedTypePolicyRAII PolicyRAII(Policy);
printAfter(T->getNamedType(), OS);
}
void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
printBefore(T->getInnerType(), OS);
OS << '(';
} else
printBefore(T->getInnerType(), OS);
}
void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
OS << ')';
printAfter(T->getInnerType(), OS);
} else
printAfter(T->getInnerType(), OS);
}
void TypePrinter::printDependentNameBefore(const DependentNameType *T,
raw_ostream &OS) {
OS << TypeWithKeyword::getKeywordName(T->getKeyword());
if (T->getKeyword() != ETK_None)
OS << " ";
T->getQualifier()->print(OS, Policy);
OS << T->getIdentifier()->getName();
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printDependentNameAfter(const DependentNameType *T,
raw_ostream &OS) {}
void TypePrinter::printDependentTemplateSpecializationBefore(
const DependentTemplateSpecializationType *T, raw_ostream &OS) {
IncludeStrongLifetimeRAII Strong(Policy);
OS << TypeWithKeyword::getKeywordName(T->getKeyword());
if (T->getKeyword() != ETK_None)
OS << " ";
if (T->getQualifier())
T->getQualifier()->print(OS, Policy);
OS << T->getIdentifier()->getName();
printTemplateArgumentList(OS, T->template_arguments(), Policy);
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printDependentTemplateSpecializationAfter(
const DependentTemplateSpecializationType *T, raw_ostream &OS) {}
void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
raw_ostream &OS) {
printBefore(T->getPattern(), OS);
}
void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
raw_ostream &OS) {
printAfter(T->getPattern(), OS);
OS << "...";
}
void TypePrinter::printAttributedBefore(const AttributedType *T,
raw_ostream &OS) {
// FIXME: Generate this with TableGen.
// Prefer the macro forms of the GC and ownership qualifiers.
if (T->getAttrKind() == attr::ObjCGC ||
T->getAttrKind() == attr::ObjCOwnership)
return printBefore(T->getEquivalentType(), OS);
if (T->getAttrKind() == attr::ObjCKindOf)
OS << "__kindof ";
printBefore(T->getModifiedType(), OS);
if (T->isMSTypeSpec()) {
switch (T->getAttrKind()) {
default: return;
case attr::Ptr32: OS << " __ptr32"; break;
case attr::Ptr64: OS << " __ptr64"; break;
case attr::SPtr: OS << " __sptr"; break;
case attr::UPtr: OS << " __uptr"; break;
}
spaceBeforePlaceHolder(OS);
}
// Print nullability type specifiers.
if (T->getImmediateNullability()) {
if (T->getAttrKind() == attr::TypeNonNull)
OS << " _Nonnull";
else if (T->getAttrKind() == attr::TypeNullable)
OS << " _Nullable";
else if (T->getAttrKind() == attr::TypeNullUnspecified)
OS << " _Null_unspecified";
else
llvm_unreachable("unhandled nullability");
spaceBeforePlaceHolder(OS);
}
}
void TypePrinter::printAttributedAfter(const AttributedType *T,
raw_ostream &OS) {
// FIXME: Generate this with TableGen.
// Prefer the macro forms of the GC and ownership qualifiers.
if (T->getAttrKind() == attr::ObjCGC ||
T->getAttrKind() == attr::ObjCOwnership)
return printAfter(T->getEquivalentType(), OS);
// If this is a calling convention attribute, don't print the implicit CC from
// the modified type.
SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
printAfter(T->getModifiedType(), OS);
// Some attributes are printed as qualifiers before the type, so we have
// nothing left to do.
if (T->getAttrKind() == attr::ObjCKindOf ||
T->isMSTypeSpec() || T->getImmediateNullability())
return;
// Don't print the inert __unsafe_unretained attribute at all.
if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained)
return;
// Don't print ns_returns_retained unless it had an effect.
if (T->getAttrKind() == attr::NSReturnsRetained &&
!T->getEquivalentType()->castAs<FunctionType>()
->getExtInfo().getProducesResult())
return;
if (T->getAttrKind() == attr::LifetimeBound) {
OS << " [[clang::lifetimebound]]";
return;
}
// The printing of the address_space attribute is handled by the qualifier
// since it is still stored in the qualifier. Return early to prevent printing
// this twice.
if (T->getAttrKind() == attr::AddressSpace)
return;
OS << " __attribute__((";
switch (T->getAttrKind()) {
#define TYPE_ATTR(NAME)
#define DECL_OR_TYPE_ATTR(NAME)
#define ATTR(NAME) case attr::NAME:
#include "clang/Basic/AttrList.inc"
llvm_unreachable("non-type attribute attached to type");
case attr::OpenCLPrivateAddressSpace:
case attr::OpenCLGlobalAddressSpace:
case attr::OpenCLLocalAddressSpace:
case attr::OpenCLConstantAddressSpace:
case attr::OpenCLGenericAddressSpace:
// FIXME: Update printAttributedBefore to print these once we generate
// AttributedType nodes for them.
break;
case attr::LifetimeBound:
case attr::TypeNonNull:
case attr::TypeNullable:
case attr::TypeNullUnspecified:
case attr::ObjCGC:
case attr::ObjCInertUnsafeUnretained:
case attr::ObjCKindOf:
case attr::ObjCOwnership:
case attr::Ptr32:
case attr::Ptr64:
case attr::SPtr:
case attr::UPtr:
case attr::AddressSpace:
llvm_unreachable("This attribute should have been handled already");
case attr::NSReturnsRetained:
OS << "ns_returns_retained";
break;
// FIXME: When Sema learns to form this AttributedType, avoid printing the
// attribute again in printFunctionProtoAfter.
case attr::AnyX86NoCfCheck: OS << "nocf_check"; break;
case attr::CDecl: OS << "cdecl"; break;
case attr::FastCall: OS << "fastcall"; break;
case attr::StdCall: OS << "stdcall"; break;
case attr::ThisCall: OS << "thiscall"; break;
case attr::SwiftCall: OS << "swiftcall"; break;
case attr::VectorCall: OS << "vectorcall"; break;
case attr::Pascal: OS << "pascal"; break;
case attr::MSABI: OS << "ms_abi"; break;
case attr::SysVABI: OS << "sysv_abi"; break;
case attr::RegCall: OS << "regcall"; break;
case attr::Pcs: {
OS << "pcs(";
QualType t = T->getEquivalentType();
while (!t->isFunctionType())
t = t->getPointeeType();
OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
"\"aapcs\"" : "\"aapcs-vfp\"");
OS << ')';
break;
}
case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break;
case attr::IntelOclBicc: OS << "inteloclbicc"; break;
case attr::PreserveMost:
OS << "preserve_most";
break;
case attr::PreserveAll:
OS << "preserve_all";
break;
case attr::NoDeref:
OS << "noderef";
break;
}
OS << "))";
}
void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
raw_ostream &OS) {
OS << T->getDecl()->getName();
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
raw_ostream &OS) {}
void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
raw_ostream &OS) {
OS << T->getDecl()->getName();
if (!T->qual_empty()) {
bool isFirst = true;
OS << '<';
for (const auto *I : T->quals()) {
if (isFirst)
isFirst = false;
else
OS << ',';
OS << I->getName();
}
OS << '>';
}
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
raw_ostream &OS) {}
void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
raw_ostream &OS) {
if (T->qual_empty() && T->isUnspecializedAsWritten() &&
!T->isKindOfTypeAsWritten())
return printBefore(T->getBaseType(), OS);
if (T->isKindOfTypeAsWritten())
OS << "__kindof ";
print(T->getBaseType(), OS, StringRef());
if (T->isSpecializedAsWritten()) {
bool isFirst = true;
OS << '<';
for (auto typeArg : T->getTypeArgsAsWritten()) {
if (isFirst)
isFirst = false;
else
OS << ",";
print(typeArg, OS, StringRef());
}
OS << '>';
}
if (!T->qual_empty()) {
bool isFirst = true;
OS << '<';
for (const auto *I : T->quals()) {
if (isFirst)
isFirst = false;
else
OS << ',';
OS << I->getName();
}
OS << '>';
}
spaceBeforePlaceHolder(OS);
}
void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
raw_ostream &OS) {
if (T->qual_empty() && T->isUnspecializedAsWritten() &&
!T->isKindOfTypeAsWritten())
return printAfter(T->getBaseType(), OS);
}
void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
raw_ostream &OS) {
printBefore(T->getPointeeType(), OS);
// If we need to print the pointer, print it now.
if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
!T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
if (HasEmptyPlaceHolder)
OS << ' ';
OS << '*';
}
}
void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
raw_ostream &OS) {}
static
const TemplateArgument &getArgument(const TemplateArgument &A) { return A; }
static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) {
return A.getArgument();
}
template<typename TA>
static void printTo(raw_ostream &OS, ArrayRef<TA> Args,
const PrintingPolicy &Policy, bool SkipBrackets) {
const char *Comma = Policy.MSVCFormatting ? "," : ", ";
if (!SkipBrackets)
OS << '<';
bool NeedSpace = false;
bool FirstArg = true;
for (const auto &Arg : Args) {
// Print the argument into a string.
SmallString<128> Buf;
llvm::raw_svector_ostream ArgOS(Buf);
const TemplateArgument &Argument = getArgument(Arg);
if (Argument.getKind() == TemplateArgument::Pack) {
if (Argument.pack_size() && !FirstArg)
OS << Comma;
printTo(ArgOS, Argument.getPackAsArray(), Policy, true);
} else {
if (!FirstArg)
OS << Comma;
Argument.print(Policy, ArgOS);
}
StringRef ArgString = ArgOS.str();
// If this is the first argument and its string representation
// begins with the global scope specifier ('::foo'), add a space
// to avoid printing the diagraph '<:'.
if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
OS << ' ';
OS << ArgString;
NeedSpace = (!ArgString.empty() && ArgString.back() == '>');
FirstArg = false;
}
// If the last character of our string is '>', add another space to
// keep the two '>''s separate tokens. We don't *have* to do this in
// C++0x, but it's still good hygiene.
if (NeedSpace)
OS << ' ';
if (!SkipBrackets)
OS << '>';
}
void clang::printTemplateArgumentList(raw_ostream &OS,
const TemplateArgumentListInfo &Args,
const PrintingPolicy &Policy) {
return printTo(OS, Args.arguments(), Policy, false);
}
void clang::printTemplateArgumentList(raw_ostream &OS,
ArrayRef<TemplateArgument> Args,
const PrintingPolicy &Policy) {
printTo(OS, Args, Policy, false);
}
void clang::printTemplateArgumentList(raw_ostream &OS,
ArrayRef<TemplateArgumentLoc> Args,
const PrintingPolicy &Policy) {
printTo(OS, Args, Policy, false);
}
std::string Qualifiers::getAsString() const {
LangOptions LO;
return getAsString(PrintingPolicy(LO));
}
// Appends qualifiers to the given string, separated by spaces. Will
// prefix a space if the string is non-empty. Will not append a final
// space.
std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
SmallString<64> Buf;
llvm::raw_svector_ostream StrOS(Buf);
print(StrOS, Policy);
return StrOS.str();
}
bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
if (getCVRQualifiers())
return false;
if (getAddressSpace() != LangAS::Default)
return false;
if (getObjCGCAttr())
return false;
if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
return false;
return true;
}
// Appends qualifiers to the given string, separated by spaces. Will
// prefix a space if the string is non-empty. Will not append a final
// space.
void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
bool appendSpaceIfNonEmpty) const {
bool addSpace = false;
unsigned quals = getCVRQualifiers();
if (quals) {
AppendTypeQualList(OS, quals, Policy.Restrict);
addSpace = true;
}
if (hasUnaligned()) {
if (addSpace)
OS << ' ';
OS << "__unaligned";
addSpace = true;
}
LangAS addrspace = getAddressSpace();
if (addrspace != LangAS::Default) {
if (addrspace != LangAS::opencl_private) {
if (addSpace)
OS << ' ';
addSpace = true;
switch (addrspace) {
case LangAS::opencl_global:
OS << "__global";
break;
case LangAS::opencl_local:
OS << "__local";
break;
case LangAS::opencl_private:
break;
case LangAS::opencl_constant:
case LangAS::cuda_constant:
OS << "__constant";
break;
case LangAS::opencl_generic:
OS << "__generic";
break;
case LangAS::cuda_device:
OS << "__device";
break;
case LangAS::cuda_shared:
OS << "__shared";
break;
default:
OS << "__attribute__((address_space(";
OS << toTargetAddressSpace(addrspace);
OS << ")))";
}
}
}
if (Qualifiers::GC gc = getObjCGCAttr()) {
if (addSpace)
OS << ' ';
addSpace = true;
if (gc == Qualifiers::Weak)
OS << "__weak";
else
OS << "__strong";
}
if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
if (addSpace)
OS << ' ';
addSpace = true;
}
switch (lifetime) {
case Qualifiers::OCL_None: llvm_unreachable("none but true");
case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
case Qualifiers::OCL_Strong:
if (!Policy.SuppressStrongLifetime)
OS << "__strong";
break;
case Qualifiers::OCL_Weak: OS << "__weak"; break;
case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
}
}
if (appendSpaceIfNonEmpty && addSpace)
OS << ' ';
}
std::string QualType::getAsString() const {
return getAsString(split(), LangOptions());
}
std::string QualType::getAsString(const PrintingPolicy &Policy) const {
std::string S;
getAsStringInternal(S, Policy);
return S;
}
std::string QualType::getAsString(const Type *ty, Qualifiers qs,
const PrintingPolicy &Policy) {
std::string buffer;
getAsStringInternal(ty, qs, buffer, Policy);
return buffer;
}
void QualType::print(raw_ostream &OS, const PrintingPolicy &Policy,
const Twine &PlaceHolder, unsigned Indentation) const {
print(splitAccordingToPolicy(*this, Policy), OS, Policy, PlaceHolder,
Indentation);
}
void QualType::print(const Type *ty, Qualifiers qs,
raw_ostream &OS, const PrintingPolicy &policy,
const Twine &PlaceHolder, unsigned Indentation) {
SmallString<128> PHBuf;
StringRef PH = PlaceHolder.toStringRef(PHBuf);
TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
}
void QualType::getAsStringInternal(std::string &Str,
const PrintingPolicy &Policy) const {
return getAsStringInternal(splitAccordingToPolicy(*this, Policy), Str,
Policy);
}
void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
std::string &buffer,
const PrintingPolicy &policy) {
SmallString<256> Buf;
llvm::raw_svector_ostream StrOS(Buf);
TypePrinter(policy).print(ty, qs, StrOS, buffer);
std::string str = StrOS.str();
buffer.swap(str);
}
| 32.205062 | 82 | 0.63807 | dmitryryintel |
10786f7a915956d6e83da511fac1ece010f98a2a | 2,362 | cpp | C++ | engine/source/gom/source/src/Actor.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 5 | 2019-02-12T07:23:55.000Z | 2020-06-22T15:03:36.000Z | engine/source/gom/source/src/Actor.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | null | null | null | engine/source/gom/source/src/Actor.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 2 | 2019-06-17T05:04:21.000Z | 2020-04-22T09:05:57.000Z | #include "Actor.hpp"
#include "vec3.hpp"
#include "vec2.hpp"
#include "mat4.hpp"
#include "Body_2d_def.hpp"
#include "Body_2d.hpp"
#include "World.hpp"
#include "Physics_manager.hpp"
#include "Projectile.hpp"
#include "Sprite.hpp"
#include "Sprite_atlas.hpp"
#include "Graphics_manager.hpp"
#include "Gameplay_state.hpp"
#include "Animator_controller.hpp"
#include "runtime_memory_allocator.hpp"
#include <cstddef>
//TAKE OUT MAGIC NUMBER 16 ON SPRITE CONSTRUCTOR
//Actor::Actor(const cgm::vec3 & pos, const cgm::mat4 & orientation, const std::string & texture_file, State *pstate, const AABB_2d & aabb, const cgm::vec2 & velocity, bool facing_left)
// : Renderable_game_object(pos, orientation, texture_file), m_pstate(pstate), m_aabb(aabb), m_velocity(velocity), m_facing_left(facing_left) {}
namespace gom {
Actor::Actor(std::size_t object_sz, atlas_n_layer & sprite_data,
physics_2d::Body_2d_def *pbody_def, const gfx::Animator_controller *pcontroller,
bool facing_left) :
Game_object(object_sz, pbody_def->m_position), m_pstate(nullptr), m_velocity(pbody_def->m_linear_velocity), m_facing_left(facing_left)
{
//create sprite component
void *pmem = mem::allocate(sizeof(gfx::Sprite));
if (pmem != nullptr) {
m_psprite = static_cast<gfx::Sprite*>(new (pmem) gfx::Sprite(sprite_data.first, sprite_data.second) );
//add to the graphics manager to be rendered
gfx::g_graphics_mgr.add_sprite_to_render(m_psprite);
}
//create a body2d component
m_pbody_2d = physics_2d::g_physics_mgr.get_world()->create_body_2d(*pbody_def);
m_pbody_2d->set_user_data(static_cast<void*>(this));
//make a copy of the animator controller
pmem = mem::allocate(sizeof(gfx::Animator_controller));
if (pmem != nullptr) {
m_panimator_controller = static_cast<gfx::Animator_controller*>( new (pmem) gfx::Animator_controller(*pcontroller) );
}
}
Actor::~Actor()
{
if (m_pstate != nullptr) {
size_t sz = m_pstate->get_size();
m_pstate->~Gameplay_state();
mem::free(m_pstate, sz);
m_pstate = nullptr;
}
}
void Actor::begin_tile_collision(const physics_2d::AABB_2d & tile_aabb)
{
m_pstate->begin_tile_collision(*this, tile_aabb);
}
void Actor::end_tile_collision(const physics_2d::AABB_2d & tile_aabb)
{
m_pstate->end_tile_collision(*this, tile_aabb);
}
} | 32.356164 | 185 | 0.724809 | mateusgondim |
10791f85ae8e2c6fe3473339e07ca53247fc4fc9 | 2,216 | cpp | C++ | hazelcast/src/hazelcast/client/TypedData.cpp | sbrown-uhd/hazelcast-cpp-client | ce57a508092fa42b9b4b371ae6c2782a21c75515 | [
"Apache-2.0"
] | null | null | null | hazelcast/src/hazelcast/client/TypedData.cpp | sbrown-uhd/hazelcast-cpp-client | ce57a508092fa42b9b4b371ae6c2782a21c75515 | [
"Apache-2.0"
] | null | null | null | hazelcast/src/hazelcast/client/TypedData.cpp | sbrown-uhd/hazelcast-cpp-client | ce57a508092fa42b9b4b371ae6c2782a21c75515 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hazelcast/client/TypedData.h"
#include "hazelcast/client/serialization/pimpl/Data.h"
namespace hazelcast {
namespace client {
TypedData::TypedData() : ss(NULL) {
}
TypedData::TypedData(std::auto_ptr<serialization::pimpl::Data> data,
serialization::pimpl::SerializationService &serializationService) : data(data),
ss(&serializationService) {
}
TypedData::TypedData(const boost::shared_ptr<serialization::pimpl::Data> &data,
serialization::pimpl::SerializationService &serializationService) : data(data),
ss(&serializationService) {
}
TypedData::~TypedData() {}
const serialization::pimpl::ObjectType TypedData::getType() const {
return ss->getObjectType(data.get());
}
const boost::shared_ptr<serialization::pimpl::Data> TypedData::getData() const {
return data;
}
bool operator<(const TypedData &lhs, const TypedData &rhs) {
const serialization::pimpl::Data *lhsData = lhs.getData().get();
const serialization::pimpl::Data *rhsData = rhs.getData().get();
if (lhsData == NULL) {
return true;
}
if (rhsData == NULL) {
return false;
}
return *lhsData < *rhsData;
}
}
}
| 36.933333 | 124 | 0.574007 | sbrown-uhd |
107a5f0d2e59a6cc83a80733e005a74f3f4b7928 | 11,129 | cc | C++ | src/automaton/tests/interop/abi_encoder_test.cc | automaton-network/automaton | 34f6df278dc71d11340084c3487564ab58b04c2e | [
"MIT"
] | 2 | 2018-12-19T18:01:14.000Z | 2019-03-29T12:54:41.000Z | src/automaton/tests/interop/abi_encoder_test.cc | automaton-network/automaton | 34f6df278dc71d11340084c3487564ab58b04c2e | [
"MIT"
] | 3 | 2018-12-20T17:44:31.000Z | 2020-03-25T16:45:04.000Z | src/automaton/tests/interop/abi_encoder_test.cc | automaton-network/automaton | 34f6df278dc71d11340084c3487564ab58b04c2e | [
"MIT"
] | 2 | 2020-03-12T13:33:10.000Z | 2020-03-22T00:48:51.000Z | #include <fstream>
#include <string>
#include <vector>
#include <json.hpp>
#include "automaton/core/interop/ethereum/eth_contract_curl.h"
#include "automaton/core/interop/ethereum/eth_helper_functions.h"
#include "automaton/core/io/io.h"
#include "gtest/gtest.h"
using json = nlohmann::json;
using namespace automaton::core::interop::ethereum; // NOLINT
using automaton::core::io::bin2hex;
using automaton::core::io::hex2bin;
using automaton::core::io::hex2dec;
TEST(encoder, encode_decode_test) {
std::unique_ptr<g3::LogWorker> logworker {g3::LogWorker::createLogWorker()};
auto l_handler = logworker->addDefaultLogger("demo", "./");
g3::initializeLogging(logworker.get());
auto t = get_type("int");
EXPECT_EQ(t.str, "int");
EXPECT_EQ(t.s_type, numerical);
EXPECT_EQ(t.s_array_type, no_array);
EXPECT_EQ(t.array_len, 0);
t = get_type("int[][]");
EXPECT_EQ(t.str, "int[][]");
EXPECT_EQ(t.s_type, numerical);
EXPECT_EQ(t.s_array_type, dynamic);
EXPECT_EQ(t.array_len, 0);
t = get_type("fixed[5]");
EXPECT_EQ(t.str, "fixed[5]");
EXPECT_EQ(t.s_type, numerical);
EXPECT_EQ(t.s_array_type, fixed);
EXPECT_EQ(t.array_len, 5);
t = get_type("bytes32");
EXPECT_EQ(t.str, "bytes32");
EXPECT_EQ(t.s_type, fixed_size_bytes);
EXPECT_EQ(t.s_array_type, no_array);
EXPECT_EQ(t.array_len, 0);
t = get_type("string");
EXPECT_EQ(t.str, "string");
EXPECT_EQ(t.s_type, string);
EXPECT_EQ(t.s_array_type, no_array);
EXPECT_EQ(t.array_len, 0);
t = get_type("string[5][]");
EXPECT_EQ(t.str, "string[5][]");
EXPECT_EQ(t.s_type, string);
EXPECT_EQ(t.s_array_type, dynamic);
EXPECT_EQ(t.array_len, 0);
t = get_type("string[][5]");
EXPECT_EQ(t.str, "string[][5]");
EXPECT_EQ(t.s_type, string);
EXPECT_EQ(t.s_array_type, dynamic);
EXPECT_EQ(t.array_len, 5);
t = get_type("string[4][5]");
EXPECT_EQ(t.str, "string[4][5]");
EXPECT_EQ(t.s_type, string);
EXPECT_EQ(t.s_array_type, dynamic);
EXPECT_EQ(t.array_len, 5);
t = get_type("int[4][5]");
EXPECT_EQ(t.str, "int[4][5]");
EXPECT_EQ(t.s_type, numerical);
EXPECT_EQ(t.s_array_type, fixed);
EXPECT_EQ(t.array_len, 5);
t = extract_array_type("uint256[][]");
EXPECT_EQ(t.str, "uint256[]");
EXPECT_EQ(t.s_type, numerical);
EXPECT_EQ(t.s_array_type, dynamic);
EXPECT_EQ(t.array_len, 0);
t = extract_array_type("string[5][]");
EXPECT_EQ(t.str, "string[5]");
EXPECT_EQ(t.s_type, string);
EXPECT_EQ(t.s_array_type, dynamic);
EXPECT_EQ(t.array_len, 5);
t = extract_array_type("int[][5]");
EXPECT_EQ(t.str, "int[]");
EXPECT_EQ(t.s_type, numerical);
EXPECT_EQ(t.s_array_type, dynamic);
EXPECT_EQ(t.array_len, 0);
t = extract_array_type("int[5][]");
EXPECT_EQ(t.str, "int[5]");
EXPECT_EQ(t.s_type, numerical);
EXPECT_EQ(t.s_array_type, fixed);
EXPECT_EQ(t.array_len, 5);
t = extract_array_type("bytes[]");
EXPECT_EQ(t.str, "bytes");
EXPECT_EQ(t.s_type, dynamic_size_bytes);
EXPECT_EQ(t.s_array_type, no_array);
EXPECT_EQ(t.array_len, 0);
EXPECT_EQ(calculate_offset({"uint256"}), 32);
EXPECT_EQ(calculate_offset({"uint8", "string", "string[][5]", "bool"}), 4 * 32);
EXPECT_EQ(calculate_offset({"fixed[2][3][4]"}), 24 * 32);
EXPECT_EQ(calculate_offset({"string", "bytes"}), 64);
EXPECT_EQ(calculate_offset({"string[]", "uint32"}), 64);
EXPECT_EQ(calculate_offset({"bool[3]", "uint256[7][]"}), 4 * 32);
EXPECT_EQ(calculate_offset({"uint256[][10]"}), 32);
EXPECT_EQ(calculate_offset({"uint256[10]"}), 320);
std::string encoded, decoded, signatures, parameters;
signatures = "[\"bytes\"]";
parameters = "[\"A30B12\"]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"uint\"]";
parameters = "[2]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, "[\"2\"]");
signatures = "[\"uint[][]\",\"string[]\"]";
parameters = "[[[1,2],[3]],[\"one\",\"two\",\"three\"]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, "[[[\"1\",\"2\"],[\"3\"]],[\"one\",\"two\",\"three\"]]");
signatures = "[\"uint[]\",\"string\"]";
parameters = "[[\"1\",\"2\"],\"aaa\"]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"uint\",\"string[2]\"]";
parameters = "[\"15\",[\"aaa\",\"eee\"]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"string[2]\"]";
parameters = "[[\"aaa\",\"eee\"]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"string[][2]\"]";
parameters = "[[[\"aaa\",\"eee\"],[\"ppp\",\"ooo\"]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"string[][2]\",\"uint8[][]\"]";
parameters = "[[[\"aaa\",\"eee\"],[\"ooo\",\"ppp\"]],[[\"7\",\"8\"],[\"5\"]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"string[2][2]\"]";
parameters = "[[[\"aaa\",\"eee\"],[\"ooo\",\"ppp\"]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, "[[[\"aaa\",\"eee\"],[\"ooo\",\"ppp\"]]]");
signatures = "[\"string[][2][]\"]";
parameters = "[[[[\"aaa\"],[\"eee\"]],[[\"ooo\"],[\"ppp\",\"ooo\"]]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"uint256[2]\"]";
parameters = "[[1,2]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, "[[\"1\",\"2\"]]");
signatures = "[\"uint256[3][2]\"]";
parameters = "[[[\"1\",\"2\",\"3\"],[5,6,7]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, "[[[\"1\",\"2\",\"3\"],[\"5\",\"6\",\"7\"]]]");
signatures = "[\"uint256[3][2]\", \"string[][2][]\"]";
parameters = "[[[\"1\",\"2\",\"3\"],[\"5\",\"6\",\"7\"]],[[[\"aaa\"],[\"eee\"]],[[\"ooo\"],[\"ppp\",\"ooo\"]]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"string[][2][]\", \"uint256[3][2]\"]";
parameters = "[[[[\"aaa\"],[\"eee\"]],[[\"ooo\"],[\"ppp\",\"rrr\"]]],[[\"1\",\"2\",\"3\"],[\"5\",\"6\",\"7\"]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"uint256[3][2]\", \"string[2][2][]\"]";
parameters = "[[[\"1\",\"2\",\"3\"],[\"5\",\"6\",\"7\"]],[[[\"aaa\",\"eee\"],[\"ppp\",\"rrr\"]]]]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"address\"]";
parameters = "[\"22D9D6FAB361FAA969D2EFDE420472633CBB7B11\"]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
signatures = "[\"bool\"]";
parameters = "[true]";
encoded = encode(signatures, parameters);
decoded = decode(signatures, encoded);
EXPECT_EQ(decoded, parameters);
// Test contract functions
const char* JSON_FILE = "../contracts/test_contract/build/contracts/test_contract.json";
const char* URL = "127.0.0.1:7545";
const char* CONTRACT_ADDR = "0xCfEB869F69431e42cdB54A4F4f105C19C080A601";
const char* ADDRESS = "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1";
curl_global_init(CURL_GLOBAL_ALL);
using namespace automaton::core::interop::ethereum; // NOLINT
std::fstream fs(JSON_FILE, std::fstream::in);
json j, abi;
if (!fs.is_open()) {
LOG(FATAL) << "No contract json file!";
}
fs >> j;
if (j.find("abi") != j.end()) {
abi = j["abi"].get<json>();
} else {
LOG(FATAL) << "No abi!";
}
std::string abi_string = abi.dump();
eth_contract::register_contract(URL, CONTRACT_ADDR, abi_string);
fs.close();
auto contract = eth_contract::get_contract(CONTRACT_ADDR);
EXPECT_NE(contract, nullptr);
status s = status::ok();
s = contract->call("f1", "[3]");
EXPECT_EQ(s.msg, "[\"259\"]");
s = contract->call("f2", "[3]");
EXPECT_EQ(s.msg, "[[\"0\",\"1\",\"4\"]]");
s = contract->call("f3", "[5,7]");
EXPECT_EQ(s.msg, "[\"7\",\"5\"]");
s = contract->call("f4", "[\"abc\"]");
EXPECT_EQ(s.msg, "[\"cba\"]");
s = contract->call("f5", "");
EXPECT_EQ(s.msg, "[\"ABCDEABCDE\"]");
s = contract->call("f6", "");
EXPECT_EQ(s.msg, "[\"CFEB869F69431E42CDB54A4F4F105C19C080A601\"]");
s = contract->call("f7", "[true]");
EXPECT_EQ(s.msg, "[false]");
s = contract->call("f7", "[false]");
EXPECT_EQ(s.msg, "[true]");
s = contract->call("f8", "[5]");
EXPECT_EQ(s.msg, "[\"-5\"]");
s = contract->call("f8", "[0]");
EXPECT_EQ(s.msg, "[\"0\"]");
s = contract->call("f8", "[\"18446744073709551615\"]");
EXPECT_EQ(s.msg, "[\"-18446744073709551615\"]");
s = contract->call("f8", "[\"518446744073709551615\"]");
EXPECT_EQ(s.msg, "[\"-518446744073709551615\"]");
s = contract->call("f9", "[5]");
EXPECT_EQ(s.msg, "[\"10\"]");
s = contract->call("f10", "[[[2,3],[5,7],[11,13]]]");
EXPECT_EQ(s.msg, "[\"30030\"]");
s = contract->call("f11", "[[[2,3,5],[7,11,13]]]");
EXPECT_EQ(s.msg, "[\"30030\"]");
s = contract->call("f12", "[[1,2,3,4,5]]");
EXPECT_EQ(s.msg, "[\"15\"]");
s = contract->call("f13", "");
EXPECT_EQ(s.msg, "[[[\"0\",\"1\",\"2\"],[\"1\",\"2\",\"3\"]]]");
s = contract->call("f14", "");
EXPECT_EQ(s.msg, "[[[\"0\",\"1\",\"2\"],[\"1\",\"2\",\"3\"]]]");
s = contract->call("f15", "");
EXPECT_EQ(s.msg, "[[[\"0\",\"1\",\"2\"],[\"1\",\"2\",\"3\"]]]");
s = contract->call("f16", "");
EXPECT_EQ(s.msg, "[[[\"0\",\"1\",\"2\"],[\"1\",\"2\",\"3\"]]]");
s = contract->call("f17", "[[[\"0\",\"1\",\"2\"],[\"1\",\"2\",\"3\"]]]");
EXPECT_EQ(s.msg, "[[[\"0\",\"1\"],[\"1\",\"2\"],[\"2\",\"3\"]]]");
s = contract->call("f18", "[[[\"0\",\"1\"],[\"1\",\"2\"],[\"2\",\"3\"]]]");
EXPECT_EQ(s.msg, "[[[\"0\",\"1\",\"2\"],[\"1\",\"2\",\"3\"]]]");
s = contract->call("f19", "[[[\"aa\",\"bb\",\"cc\"],[\"ss\",\"pp\",\"rr\"]]]");
EXPECT_EQ(s.msg, "[[[\"aa\",\"ss\"],[\"bb\",\"pp\"],[\"cc\",\"rr\"]]]");
s = contract->call("f20", "[[[\"aa\",\"ss\"],[\"bb\",\"pp\"],[\"cc\",\"rr\"]]]");
EXPECT_EQ(s.msg, "[[[\"aa\",\"bb\",\"cc\"],[\"ss\",\"pp\",\"rr\"]]]");
s = contract->call("f21",
"[[[\"0\",\"1\",\"2\",\"3\"],[\"4\",\"5\",\"6\",\"7\"]],[[[\"a\",\"ab\"],[\"abc\"]],[[\"b\",\"ba\"],[\"cb\",\"ca\",\"c\"]]]]]"); // NOLINT
EXPECT_EQ(s.msg, "[[[[\"4\",\"5\",\"6\",\"7\"]],[[\"0\",\"1\",\"2\",\"3\"]]],true,[[\"a\",\"ab\"],[\"abc\"],[\"b\",\"ba\"],[\"cb\",\"ca\",\"c\"]]]"); // NOLINT
s = contract->call("f22", "[[[[\"aa\"],[\"ss\"]],[[\"bb\"],[\"pp\"]],[[\"cc\"],[\"rr\"]]]]");
EXPECT_EQ(s.msg, "[[[[\"aa\",\"bb\",\"cc\"],[\"ss\",\"pp\",\"rr\"]]]]");
}
| 34.669782 | 162 | 0.572738 | automaton-network |
107ac452648bfa7b6d7dd997b2314ecf40390d6f | 891 | cpp | C++ | data/dailyCodingProblem972.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | 2 | 2020-09-04T20:56:23.000Z | 2021-06-11T07:42:26.000Z | data/dailyCodingProblem972.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | data/dailyCodingProblem972.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
Given a string with repeated characters, rearrange the string so that no two adjacent
characters are the same. If this is not possible, return None.
For example, given "aaabbc", you could return "ababac". Given "aaab", return None.
*/
string rearrangeNoTwoAdj(string s){
unordered_map<char, int> char_count;
for(char c : s) char_count[c]++;
priority_queue<pair<int, char>> pq;
for(auto it : char_count) pq.push({it.second, it.first});
pair<int, char> prev = {-1, '$'};
string ans;
while(!pq.empty()){
auto t = pq.top();
pq.pop();
ans += t.second;
if(prev.first > 0) pq.push(prev);
(t.first)--;
prev = t;
}
if(ans.length() != s.length())
return "$$";
return ans;
}
// main function
int main(){
cout << rearrangeNoTwoAdj("aaabbc") << "\n";
cout << rearrangeNoTwoAdj("aaab") << "\n";
return 0;
} | 19.8 | 85 | 0.637486 | vidit1999 |
107fc4b66b44d92e397aa1a95acdfa2007b5cc6c | 696 | cpp | C++ | src/rt64lib/private/rt64_common.cpp | Ridge-Racer/RT64 | 20c983ea6875f23063449dd9c31e87e1f6b12fdf | [
"MIT"
] | null | null | null | src/rt64lib/private/rt64_common.cpp | Ridge-Racer/RT64 | 20c983ea6875f23063449dd9c31e87e1f6b12fdf | [
"MIT"
] | null | null | null | src/rt64lib/private/rt64_common.cpp | Ridge-Racer/RT64 | 20c983ea6875f23063449dd9c31e87e1f6b12fdf | [
"MIT"
] | null | null | null | //
// RT64
//
#include "rt64_common.h"
#ifndef RT64_MINIMAL
namespace nv_helpers_dx12
{
ID3D12DescriptorHeap* CreateDescriptorHeap(ID3D12Device* device, uint32_t count, D3D12_DESCRIPTOR_HEAP_TYPE type, bool shaderVisible) {
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.NumDescriptors = count;
desc.Type = type;
desc.Flags = shaderVisible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
ID3D12DescriptorHeap* pHeap;
D3D12_CHECK(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&pHeap)));
return pHeap;
}
}
#endif
namespace RT64 {
std::string GlobalLastError;
};
DLLEXPORT const char *RT64_GetLastError() {
return RT64::GlobalLastError.c_str();
} | 24 | 136 | 0.780172 | Ridge-Racer |
108089c02f264c5e026a26f721739850094a0de1 | 1,536 | hpp | C++ | castle-crawl/src/game-coordinator.hpp | Biyorne/learningcpp | bcf963990800ed939fa4cc1b30fadccaf098155b | [
"MIT"
] | null | null | null | castle-crawl/src/game-coordinator.hpp | Biyorne/learningcpp | bcf963990800ed939fa4cc1b30fadccaf098155b | [
"MIT"
] | null | null | null | castle-crawl/src/game-coordinator.hpp | Biyorne/learningcpp | bcf963990800ed939fa4cc1b30fadccaf098155b | [
"MIT"
] | null | null | null | #ifndef CASTLECRAWL_GAMECOORDINATOR_HPP_INCLUDED
#define CASTLECRAWL_GAMECOORDINATOR_HPP_INCLUDED
//
// game-coordinator.hpp
//
#include "animation-player.hpp"
#include "board.hpp"
#include "context.hpp"
#include "keys.hpp"
#include "maps.hpp"
#include "player-piece.hpp"
#include "popup-manager.hpp"
#include "random.hpp"
#include "resources.hpp"
#include "settings.hpp"
#include "sound-player.hpp"
#include "state-machine.hpp"
#include "tile-image.hpp"
#include <memory>
#include <string>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/System/Clock.hpp>
namespace castlecrawl
{
class GameCoordinator
{
public:
GameCoordinator();
void run(const GameConfig & config);
protected:
void initializeSubsystems(const GameConfig & config);
void openWindow();
void handleEvents();
void update(const float elapsedTimeSec);
void draw();
protected:
sf::RenderWindow m_window;
// subsystems
Maps m_maps;
Media m_media;
Board m_board;
Layout m_layout;
GameInPlay m_game;
GameConfig m_config;
StateMachine m_stateMachine;
PopupManager m_popupManager;
util::Random m_random;
util::SoundPlayer m_soundPlayer;
util::AnimationPlayer m_animationPlayer;
// subsystems reference wrapper
Context m_context;
};
} // namespace castlecrawl
#endif // CASTLECRAWL_GAMECOORDINATOR_HPP_INCLUDED
| 23.272727 | 61 | 0.685547 | Biyorne |
1080f8af35ddc9c69953f48f79aa560094477ae8 | 5,227 | hpp | C++ | include/DynPDT.hpp | kamp78/dynpdt | 5ecdb043b3185f3adcdc6e084786608f01547bcc | [
"MIT"
] | null | null | null | include/DynPDT.hpp | kamp78/dynpdt | 5ecdb043b3185f3adcdc6e084786608f01547bcc | [
"MIT"
] | null | null | null | include/DynPDT.hpp | kamp78/dynpdt | 5ecdb043b3185f3adcdc6e084786608f01547bcc | [
"MIT"
] | null | null | null | #ifndef DYNPDT_DYNPDT_HPP
#define DYNPDT_DYNPDT_HPP
#include "SimpleBonsai.hpp"
#include "LabelPool_Plain.hpp"
#include "LabelPool_BitMap.hpp"
namespace dynpdt {
struct Setting {
uint64_t num_keys = 0;
double load_factor = 0.0;
uint64_t fixed_len = 0; // of node labels
uint8_t width_1st = 0;
void show_stat(std::ostream& os) const {
using std::endl;
os << "Show statistics of Setting" << endl;
os << " - num_keys:\t" << num_keys << endl;
os << " - load_factor:\t" << load_factor << endl;
os << " - fixed_len:\t" << fixed_len << endl;
os << " - width_1st:\t" << static_cast<uint32_t>(width_1st) << endl;
}
};
template<typename _LabelPoolType>
class DynPDT {
public:
using LabelPoolType = _LabelPoolType;
using ValueType = typename _LabelPoolType::ValueType;
static constexpr uint8_t kAdjustAlphabet = 3; // heuristic
static constexpr uint8_t kLabelMax = UINT8_MAX - kAdjustAlphabet;
static constexpr uint64_t kStepSymbol = UINT8_MAX; // <UINT8_MAX, 0>
static std::string name() {
std::ostringstream oss;
oss << "DynPDT_" << LabelPoolType::name().substr(std::strlen("LabelPool_"));
return oss.str();
}
DynPDT(Setting setting) : setting_(setting) {
if (!is_power2(setting_.fixed_len)) {
std::cerr << "ERROR: fixed_len must be a power of 2." << std::endl;
exit(1);
}
trie_ = std::make_unique<SimpleBonsai>(setting_.num_keys / setting_.load_factor,
(setting_.fixed_len << 8) - kAdjustAlphabet,
setting_.width_1st);
label_pool_ = std::make_unique<LabelPoolType>(trie_->num_slots());
table_.fill(UINT8_MAX);
}
~DynPDT() {}
const ValueType* find(const std::string& key) const {
return find_(key);
}
ValueType* update(const std::string& key) {
return update_(key);
}
uint64_t num_keys() const {
return num_keys_;
}
uint64_t num_steps() const {
return num_steps_;
}
uint8_t num_chars() const {
return num_chars_;
}
const SimpleBonsai* get_trie() const {
return trie_.get();
}
void show_stat(std::ostream& os) const {
using std::endl;
setting_.show_stat(os);
os << "Show statistics of " << name() << endl;
os << " - num_keys:\t" << num_keys() << endl;
os << " - num_steps:\t" << num_steps() << endl;
os << " - num_chars:\t" << static_cast<uint32_t>(num_chars()) << endl;
trie_->show_stat(os);
label_pool_->show_stat(os);
}
DynPDT(const DynPDT&) = delete;
DynPDT& operator=(const DynPDT&) = delete;
private:
const Setting setting_;
uint64_t num_keys_ = 0;
uint64_t num_steps_ = 0;
// code table to avoid overflow
std::array<uint8_t, 256> table_;
uint8_t num_chars_ = 0;
std::unique_ptr<SimpleBonsai> trie_;
std::unique_ptr<LabelPoolType> label_pool_;
const ValueType* find_(CharRange key) const {
assert(key.begin != key.end);
auto node_id = trie_->get_root();
while (key.begin != key.end) {
uint64_t num_match = 0;
auto value_ptr = label_pool_->compare_and_get(node_id, key, num_match);
if (value_ptr) {
return value_ptr;
}
key.begin += num_match;
// Follow step nodes
while (setting_.fixed_len <= num_match) {
if (!trie_->get_child(node_id, kStepSymbol)) {
return nullptr;
}
num_match -= setting_.fixed_len;
}
if (table_[*key.begin] == UINT8_MAX) {
// Useless character
return nullptr;
}
if (!trie_->get_child(node_id, make_symbol_(*key.begin++, num_match))) {
return nullptr;
}
}
return label_pool_->compare_and_get(node_id, key);
}
ValueType* update_(CharRange key) {
assert(key.begin != key.end);
auto node_id = trie_->get_root();
if (num_keys_ == 0) {
// First insert
++num_keys_;
return label_pool_->append(node_id, key);
}
while (key.begin != key.end) {
uint64_t num_match = 0;
auto value_ptr = label_pool_->compare_and_get(node_id, key, num_match);
if (value_ptr) {
return value_ptr;
}
key.begin += num_match;
while (setting_.fixed_len <= num_match) {
if (trie_->add_child(node_id, kStepSymbol)) {
++num_steps_;
}
num_match -= setting_.fixed_len;
}
if (table_[*key.begin] == UINT8_MAX) {
// Update table
table_[*key.begin] = num_chars_++;
if (kLabelMax < num_chars_) {
std::cerr << "ERROR: kLabelMax < alphabet_count_" << std::endl;
exit(1);
}
}
if (trie_->add_child(node_id, make_symbol_(*key.begin++, num_match))) {
++num_keys_;
return label_pool_->append(node_id, key);
}
}
auto value_ptr = label_pool_->compare_and_get(node_id, key);
if (value_ptr) {
return value_ptr;
}
++num_keys_;
return label_pool_->append(node_id, key);
}
uint64_t make_symbol_(uint8_t label, uint64_t offset) const {
const auto symbol = static_cast<uint64_t>(table_[label]) | (offset << 8);
assert(symbol != kStepSymbol);
return symbol;
}
};
} // namespace - dynpdt
#endif // DYNPDT_DYNPDT_HPP
| 25.748768 | 87 | 0.616223 | kamp78 |
1081364e434d72176856ce2745b3f4e78289a2f6 | 32,131 | cpp | C++ | Plugins/Rename/Rename.cpp | GideonCrawle/unified | 2a310e0012badfcc9675bd8c8554613b5354e21a | [
"MIT"
] | null | null | null | Plugins/Rename/Rename.cpp | GideonCrawle/unified | 2a310e0012badfcc9675bd8c8554613b5354e21a | [
"MIT"
] | null | null | null | Plugins/Rename/Rename.cpp | GideonCrawle/unified | 2a310e0012badfcc9675bd8c8554613b5354e21a | [
"MIT"
] | null | null | null | #include "Rename.hpp"
#include <sstream>
#include <regex>
#include <string>
#include <random>
#include <algorithm>
#include "API/CAppManager.hpp"
#include "API/CServerExoApp.hpp"
#include "API/CNetLayer.hpp"
#include "API/CNetLayerPlayerInfo.hpp"
#include "API/Constants.hpp"
#include "API/Globals.hpp"
#include "API/CNWSPlayer.hpp"
#include "API/CNWSCreature.hpp"
#include "API/CServerExoAppInternal.hpp"
#include "API/CExoLinkedListInternal.hpp"
#include "API/CExoString.hpp"
#include "API/CLastUpdateObject.hpp"
#include "API/CExoLinkedList.hpp"
#include "API/CExoLinkedListNode.hpp"
#include "API/CNWSCreatureStats.hpp"
#include "API/Functions.hpp"
#include "Services/Config/Config.hpp"
#include "Services/Messaging/Messaging.hpp"
using namespace NWNXLib;
using namespace NWNXLib::API;
static Hooking::FunctionHook* m_SendServerToPlayerPopUpGUIPanelHook;
static Hooking::FunctionHook* m_SendServerToPlayerPlayModuleCharacterListResponseHook;
static Rename::Rename* g_plugin;
//Constants for Player Name states.
const int NWNX_RENAME_PLAYERNAME_DEFAULT = 0;
const int NWNX_RENAME_PLAYERNAME_OBFUSCATE = 1;
const int NWNX_RENAME_PLAYERNAME_OVERRIDE = 2;
const int NWNX_RENAME_PLAYERNAME_ANONYMOUS = 3;
NWNX_PLUGIN_ENTRY Plugin* PluginLoad(Services::ProxyServiceList* services)
{
g_plugin = new Rename::Rename(services);
return g_plugin;
}
namespace Rename {
Rename::Rename(Services::ProxyServiceList* services)
: Plugin(services)
{
#define REGISTER(func) \
GetServices()->m_events->RegisterEvent(#func, std::bind(&Rename::func, this, std::placeholders::_1))
REGISTER(SetPCNameOverride);
REGISTER(GetPCNameOverride);
REGISTER(ClearPCNameOverride);
#undef REGISTER
m_RenameOnModuleCharList = GetServices()->m_config->Get<int32_t>("ON_MODULE_CHAR_LIST", 0);
m_RenameOnPlayerList = GetServices()->m_config->Get<bool>("ON_PLAYER_LIST", true);
m_RenameAllowDM = GetServices()->m_config->Get<bool>("ALLOW_DM", false);
m_RenameAnonymousPlayerName = GetServices()->m_config->Get<std::string>("ANONYMOUS_NAME", "Someone");
m_RenameOverwriteDisplayName = GetServices()->m_config->Get<bool>("OVERWRITE_DISPLAY_NAME", false);
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage31WriteGameObjUpdate_UpdateObjectEP10CNWSPlayerP10CNWSObjectP17CLastUpdateObjectjj,
int32_t, CNWSMessage *, CNWSPlayer *, CNWSObject *, CLastUpdateObject *, uint32_t, uint32_t>(
&WriteGameObjUpdate_UpdateObjectHook);
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage41SendServerToPlayerExamineGui_CreatureDataEP10CNWSPlayerj,
int32_t, CNWSMessage *, CNWSPlayer *, ObjectID>(&SendServerToPlayerExamineGui_CreatureDataHook);
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage28SendServerToPlayerChat_PartyEjj10CExoString,
int32_t, CNWSMessage*, PlayerID, ObjectID, CExoString*>(&SendServerToPlayerChatHook);
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage28SendServerToPlayerChat_ShoutEjj10CExoString,
int32_t, CNWSMessage*, PlayerID, ObjectID, CExoString*>(&SendServerToPlayerChatHook);
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage27SendServerToPlayerChat_TellEjj10CExoString,
int32_t, CNWSMessage*, PlayerID, ObjectID, CExoString*>(&SendServerToPlayerChatHook);
// TODO: When shared hooks are executed by exclusive hooks we can use a shared hook for this instead and simplify
// For now we perform the functionality of the HideClassesOnCharList Tweak for convenience
if (m_RenameOnModuleCharList > 0)
{
if (m_RenameOnModuleCharList == 1)
LOG_INFO("Renaming PCs in the module character listing.");
else if (m_RenameOnModuleCharList == 2)
LOG_INFO("Renaming PCs and hiding classes in the module character listing.");
else if (m_RenameOnModuleCharList == 3)
LOG_INFO("Hiding classes in the module character listing via the Rename plugin.");
m_SendServerToPlayerPlayModuleCharacterListResponseHook = GetServices()->m_hooks->RequestExclusiveHook
<Functions::_ZN11CNWSMessage49SendServerToPlayerPlayModuleCharacterListResponseEjji, int32_t, CNWSMessage *, PlayerID, ObjectID, int32_t>
(&SendServerToPlayerPlayModuleCharacterListResponseHook);
}
if (m_RenameOnPlayerList)
{
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage32SendServerToPlayerPlayerList_AllEP10CNWSPlayer,
int32_t, CNWSMessage*, CNWSPlayer*>(&SendServerToPlayerPlayerList_AllHook);
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage32SendServerToPlayerPlayerList_AddEjP10CNWSPlayer,
int32_t, CNWSMessage*, PlayerID, CNWSPlayer*>(&SendServerToPlayerPlayerList_AddHook);
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage35SendServerToPlayerPlayerList_DeleteEjP10CNWSPlayer,
int32_t, CNWSMessage*, PlayerID, CNWSPlayer*>(&SendServerToPlayerPlayerList_DeleteHook);
}
else
LOG_INFO("Not renaming PCs in the player list.");
if (m_RenameAllowDM)
{
GetServices()->m_hooks->RequestSharedHook<Functions::_ZN11CNWSMessage46SendServerToPlayerDungeonMasterUpdatePartyListEj,
int32_t, CNWSMessage*, PlayerID>(&SendServerToPlayerDungeonMasterUpdatePartyListHook);
LOG_INFO("DMs will be included with rename logic.");
}
// TODO: When shared hooks are executed by exclusive hooks change this to HandlePlayerToServerParty
m_SendServerToPlayerPopUpGUIPanelHook = GetServices()->m_hooks->RequestExclusiveHook
<Functions::_ZN11CNWSMessage31SendServerToPlayerPopUpGUIPanelEjiiii10CExoString, int32_t, CNWSMessage*, ObjectID, int32_t, int32_t, int32_t, int32_t, CExoString*>
(&SendServerToPlayerPopUpGUIPanelHook);
}
Rename::~Rename()
{
}
CNWSPlayer *Rename::player(ObjectID playerId)
{
if (playerId == Constants::OBJECT_INVALID)
{
LOG_NOTICE("NWNX_Rename function called on OBJECT_INVALID");
return nullptr;
}
auto *pPlayer = Globals::AppManager()->m_pServerExoApp->GetClientObjectByObjectId(playerId);
if (!pPlayer)
{
LOG_NOTICE("NWNX_Rename function called on non-player object %x", playerId);
}
return pPlayer;
}
void Rename::SetOrRestorePlayerName(bool before, CNWSPlayer *targetPlayer, CNWSPlayer *observerPlayer, bool playerList)
{
if (targetPlayer == nullptr || observerPlayer == nullptr)
return;
auto *targetCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(targetPlayer->m_oidNWSObject);
auto *observerCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(observerPlayer->m_oidNWSObject);
ObjectID observerOid;
if (observerCreature == nullptr)
observerOid = Constants::OBJECT_INVALID;
else
observerOid = observerPlayer->m_oidNWSObject;
// There's a moment when a player is just logging in that pStats doesn't exist yet.
if (targetCreature == nullptr || targetCreature->m_pStats == nullptr || (!g_plugin->m_RenameAllowDM &&
(targetCreature->m_pStats->GetIsDM() ||
targetCreature->m_nAssociateType == 7 ||
targetCreature->m_nAssociateType == 8)) ||
(observerCreature != nullptr && (observerCreature->m_pStats == nullptr || (!g_plugin->m_RenameAllowDM &&
(observerCreature->m_pStats->GetIsDM() ||
observerCreature->m_nAssociateType == 7 ||
observerCreature->m_nAssociateType == 8)))))
{
return;
}
if (before)
SetPlayerNameAsObservedBy(targetCreature, observerOid, playerList);
else
RestorePlayerName(targetCreature, playerList);
}
void Rename::SetPlayerNameAsObservedBy(CNWSCreature *targetCreature, ObjectID observerOid, bool playerList)
{
auto targetOid = targetCreature->m_idSelf;
if (!g_plugin->m_RenamePlayerNames.count(targetOid))
return;
if (g_plugin->m_RenamePlayerNames[targetOid].count(observerOid))
{
auto displayName = std::get<0>(g_plugin->m_RenamePlayerNames[targetOid][observerOid]);
auto overrideName = std::get<1>(g_plugin->m_RenamePlayerNames[targetOid][observerOid]);
if (playerList)
{
targetCreature->m_pStats->m_lsFirstName = g_plugin->ContainString(overrideName.CStr());
targetCreature->m_pStats->m_lsLastName = g_plugin->ContainString("");
}
targetCreature->m_sDisplayName = displayName;
LOG_DEBUG("Observer %x will see %x as %s due to personal override", observerOid, targetOid, overrideName.m_sString);
}
else if (g_plugin->m_RenamePlayerNames[targetOid].count(Constants::OBJECT_INVALID))
{
auto displayName = std::get<0>(g_plugin->m_RenamePlayerNames[targetOid][Constants::OBJECT_INVALID]);
auto overrideName = std::get<1>(g_plugin->m_RenamePlayerNames[targetOid][Constants::OBJECT_INVALID]);
if (playerList)
{
targetCreature->m_pStats->m_lsFirstName = g_plugin->ContainString(overrideName.CStr());
targetCreature->m_pStats->m_lsLastName = g_plugin->ContainString("");
}
targetCreature->m_sDisplayName = displayName;
LOG_DEBUG("Observer %x will see %x as %s due to global override", observerOid, targetOid, overrideName.m_sString);
}
}
void Rename::RestorePlayerName(CNWSCreature *targetCreature, bool playerList)
{
if (g_plugin->m_RenameOriginalNames.count(targetCreature->m_idSelf))
{
auto lsFirstName = std::get<1>(g_plugin->m_RenameOriginalNames[targetCreature->m_idSelf]);
auto lsLastName = std::get<2>(g_plugin->m_RenameOriginalNames[targetCreature->m_idSelf]);
if (playerList)
{
targetCreature->m_pStats->m_lsFirstName = lsFirstName;
targetCreature->m_pStats->m_lsLastName = lsLastName;
}
if (g_plugin->m_RenameOverwriteDisplayName &&
g_plugin->m_RenamePlayerNames[targetCreature->m_idSelf].count(Constants::OBJECT_INVALID))
{
targetCreature->m_sDisplayName = std::get<0>(g_plugin->m_RenamePlayerNames[targetCreature->m_idSelf][Constants::OBJECT_INVALID]);
}
else
{
targetCreature->m_sDisplayName = "";
}
}
}
void Rename::WriteGameObjUpdate_UpdateObjectHook(
bool before,
CNWSMessage*,
CNWSPlayer *observerPlayer,
CNWSObject *targetObject,
CLastUpdateObject*,
uint32_t,
uint32_t)
{
auto *targetPlayer = Globals::AppManager()->m_pServerExoApp->GetClientObjectByObjectId(targetObject->m_idSelf);
SetOrRestorePlayerName(before, targetPlayer, observerPlayer);
}
void Rename::SendServerToPlayerExamineGui_CreatureDataHook(
bool before,
CNWSMessage*,
CNWSPlayer *observerPlayer,
ObjectID targetOid)
{
auto *targetPlayer = Globals::AppManager()->m_pServerExoApp->GetClientObjectByObjectId(targetOid);
SetOrRestorePlayerName(before, targetPlayer, observerPlayer);
}
// This can't work on per target basis as the player logging in hasn't selected their PC yet but it
// will still work for a global override. We also handle the hide classes tweak until exclusive
// hooks call shared hooks
int32_t Rename::SendServerToPlayerPlayModuleCharacterListResponseHook(
CNWSMessage *thisPtr,
PlayerID observerPlayerId,
ObjectID targetOid,
int32_t add)
{
auto *targetPlayer = Globals::AppManager()->m_pServerExoApp->GetClientObjectByObjectId(targetOid);
auto *observerClient = Globals::AppManager()->m_pServerExoApp->GetClientObjectByPlayerId(observerPlayerId, 0);
auto *observerPlayer = static_cast<CNWSPlayer *>(observerClient);
if (g_plugin->m_RenameOnModuleCharList == 1 || g_plugin->m_RenameOnModuleCharList == 2)
{
SetOrRestorePlayerName(true, targetPlayer, observerPlayer);
}
int32_t retVal = -1;
if (g_plugin->m_RenameOnModuleCharList >= 2)
{
thisPtr->CreateWriteMessage(sizeof(observerPlayerId), observerPlayerId, true);
thisPtr->WriteBOOL(add);
thisPtr->WriteDWORD(targetOid, 32);
if (add)
{
auto *targetCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(targetOid);
if (targetCreature)
{
thisPtr->WriteCExoLocStringServer(targetCreature->GetFirstName(), targetCreature->GetGender());
thisPtr->WriteCExoLocStringServer(targetCreature->GetLastName(), targetCreature->GetGender());
uint16_t portraitId = targetCreature->GetPortraitId();
thisPtr->WriteWORD(portraitId, 16);
if (portraitId >= 0xFFFE)
{
thisPtr->WriteCResRef(targetCreature->GetPortrait(), 16);
}
thisPtr->WriteBYTE(0, 8);
}
else
{
retVal = 0;
}
}
uint8_t *message;
uint32_t size;
if (!thisPtr->GetWriteMessage(&message, &size))
{
retVal = 0;
}
if (retVal != 0)
retVal = thisPtr->SendServerToPlayerMessage(observerPlayerId, 0x31, 0x03, message, size);
}
else
{
retVal = m_SendServerToPlayerPlayModuleCharacterListResponseHook->CallOriginal<int32_t>(thisPtr, observerPlayerId, targetOid, add);
}
if (g_plugin->m_RenameOnModuleCharList == 1 || g_plugin->m_RenameOnModuleCharList == 2)
{
SetOrRestorePlayerName(false, targetPlayer, observerPlayer);
}
return retVal;
}
void Rename::SendServerToPlayerChatHook(
bool before,
CNWSMessage*,
PlayerID observerPlayerId,
ObjectID targetOid,
CExoString*)
{
auto *targetPlayer = Globals::AppManager()->m_pServerExoApp->GetClientObjectByObjectId(targetOid);
auto *observerClient = Globals::AppManager()->m_pServerExoApp->GetClientObjectByPlayerId(observerPlayerId, 0);
auto *observerPlayer = static_cast<CNWSPlayer*>(observerClient);
SetOrRestorePlayerName(before, targetPlayer, observerPlayer);
}
void Rename::SendServerToPlayerDungeonMasterUpdatePartyListHook(
bool before,
CNWSMessage*,
PlayerID observerPlayerId)
{
g_plugin->GlobalNameChange(before, observerPlayerId, Constants::PLAYERID_ALL_PLAYERS);
}
void Rename::SendServerToPlayerPlayerList_AllHook(
bool before,
CNWSMessage*,
CNWSPlayer *observerPlayer)
{
g_plugin->GlobalNameChange(before, observerPlayer->m_nPlayerID, Constants::PLAYERID_ALL_PLAYERS);
}
void Rename::SendServerToPlayerPlayerList_AddHook(
bool before,
CNWSMessage*,
PlayerID observerPlayerId,
CNWSPlayer *targetPlayer)
{
if (!g_plugin->m_RenameAllowDM && observerPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS)
return;
if (!before)
{
g_plugin->m_RenameAddedToPlayerList.insert(targetPlayer->m_oidNWSObject);
}
g_plugin->GlobalNameChange(before, observerPlayerId, targetPlayer->m_nPlayerID);
}
void Rename::SendServerToPlayerPlayerList_DeleteHook(
bool before,
CNWSMessage*,
PlayerID observerPlayerId,
CNWSPlayer *targetPlayer)
{
if (!g_plugin->m_RenameAllowDM && observerPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS)
return;
if (before)
{
g_plugin->m_RenameAddedToPlayerList.erase(targetPlayer->m_oidNWSObject);
}
}
int32_t Rename::SendServerToPlayerPopUpGUIPanelHook(
CNWSMessage *pMessage,
ObjectID observerOid,
int32_t nGuiPanel,
int32_t bGUIOption1,
int32_t bGUIOption2,
int32_t nStringReference,
CExoString *p_sStringReference)
{
if (nGuiPanel == 1) // Party invite popup
{
auto *server = Globals::AppManager()->m_pServerExoApp;
auto *observerCreature = server->GetCreatureByGameObjectID(observerOid);
auto targetOid = observerCreature->m_oidInvitedToPartyBy;
if (g_plugin->m_RenamePlayerNames.count(targetOid) && g_plugin->m_RenamePlayerNames[targetOid].count(observerOid))
{
*p_sStringReference = std::get<0>(g_plugin->m_RenamePlayerNames[targetOid][observerOid]);
}
else if (g_plugin->m_RenamePlayerNames.count(targetOid) &&
g_plugin->m_RenamePlayerNames[targetOid].count(Constants::OBJECT_INVALID))
{
*p_sStringReference = std::get<0>(g_plugin->m_RenamePlayerNames[targetOid][Constants::OBJECT_INVALID]);
}
}
return m_SendServerToPlayerPopUpGUIPanelHook->CallOriginal<int32_t>(pMessage, observerOid, nGuiPanel, bGUIOption1,
bGUIOption2, nStringReference, p_sStringReference);
}
void Rename::GlobalNameChange(
bool before,
PlayerID observerPlayerId,
PlayerID targetPlayerId)
{
auto *server = Globals::AppManager()->m_pServerExoApp;
auto *playerList = server->m_pcExoAppInternal->m_pNWSPlayerList->m_pcExoLinkedListInternal;
std::vector<PlayerID> observersToNotify;
std::vector<PlayerID> targetsToNotify;
if (observerPlayerId == Constants::PLAYERID_ALL_PLAYERS || observerPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS)
{
for (auto *head = playerList->pHead; head; head = head->pNext)
{
auto *observerPlayer = static_cast<CNWSPlayer *>(static_cast<CNWSClient *>(head->pObject));
if ((observerPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS &&
observerPlayer->m_nCharacterType == Constants::CharacterType::DM) ||
(observerPlayerId == Constants::PLAYERID_ALL_PLAYERS &&
observerPlayer->m_nCharacterType != Constants::CharacterType::DM))
{
observersToNotify.emplace_back(observerPlayer->m_nPlayerID);
}
}
}
else
{
observersToNotify.emplace_back(observerPlayerId);
}
if (targetPlayerId == Constants::PLAYERID_ALL_PLAYERS || targetPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS)
{
for (auto *head = playerList->pHead; head; head = head->pNext)
{
auto *targetPlayer = static_cast<CNWSPlayer *>(static_cast<CNWSClient *>(head->pObject));
if ((targetPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS &&
targetPlayer->m_nCharacterType == Constants::CharacterType::DM) ||
(targetPlayerId == Constants::PLAYERID_ALL_PLAYERS &&
targetPlayer->m_nCharacterType != Constants::CharacterType::DM))
{
targetsToNotify.emplace_back(targetPlayer->m_nPlayerID);
}
}
}
else
{
targetsToNotify.emplace_back(targetPlayerId);
}
auto *pNetLayer = server->GetNetLayer();
for (auto &observerPid : observersToNotify)
{
for (auto &targetPid : targetsToNotify)
{
auto *targetPlayer = static_cast<CNWSPlayer*>(server->GetClientObjectByPlayerId(targetPid, 0));
auto targetOid = targetPlayer->m_oidNWSObject;
auto *targetCreature = server->GetCreatureByGameObjectID(targetOid);
if (targetCreature && g_plugin->m_RenamePlayerNames.count(targetOid) &&
g_plugin->m_RenamePlayerNames[targetOid].count(Constants::OBJECT_INVALID))
{
auto playerNameOverrideState = std::get<2>(g_plugin->m_RenamePlayerNames[targetOid][Constants::OBJECT_INVALID]);
if (playerNameOverrideState)
{
auto playerInfo = pNetLayer->GetPlayerInfo(targetPid);
if (!before)
{
playerInfo->m_sPlayerName = std::get<0>(g_plugin->m_RenameOriginalNames[targetOid]);
}
else
{
switch (playerNameOverrideState)
{
case NWNX_RENAME_PLAYERNAME_OBFUSCATE:
playerInfo->m_sPlayerName = CExoString(GenerateRandomPlayerName(7).c_str());
break;
case NWNX_RENAME_PLAYERNAME_OVERRIDE:
playerInfo->m_sPlayerName = std::get<1>(g_plugin->m_RenamePlayerNames[targetOid][Constants::OBJECT_INVALID]);
break;
case NWNX_RENAME_PLAYERNAME_ANONYMOUS:
playerInfo->m_sPlayerName = CExoString(m_RenameAnonymousPlayerName.c_str());
break;
default:
playerInfo->m_sPlayerName = std::get<0>(g_plugin->m_RenameOriginalNames[targetOid]);
}
}
}
}
auto *observerPlayer = static_cast<CNWSPlayer*>(server->GetClientObjectByPlayerId(observerPid, 0));
SetOrRestorePlayerName(before, targetPlayer, observerPlayer, true);
}
}
}
CExoLocString Rename::ContainString(const std::string& str)
{
CExoLocString locStr;
locStr.AddString(0,CExoString(str.c_str()),0);
return locStr;
}
std::string Rename::GenerateRandomPlayerName(size_t length)
{
static std::mt19937 rngEngine(std::random_device{}());
static const std::string charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::uniform_int_distribution<int> distribution(0, charSet.length() - 1);
std::string randomPlayername;
randomPlayername.reserve(length+1);
for (size_t i = 0; i < length; ++i)
{
randomPlayername += charSet[distribution(rngEngine)];
}
return randomPlayername;
}
void Rename::SendNameUpdate(CNWSCreature *targetCreature, PlayerID observerPlayerId)
{
std::vector<PlayerID> playersToNotify;
auto *server = Globals::AppManager()->m_pServerExoApp;
if (observerPlayerId == Constants::PLAYERID_ALL_CLIENTS)
{
auto *playerList = server->m_pcExoAppInternal->m_pNWSPlayerList->m_pcExoLinkedListInternal;
for (auto *head = playerList->pHead; head; head = head->pNext)
{
auto *client = static_cast<CNWSClient*>(head->pObject);
if (client)
playersToNotify.emplace_back(client->m_nPlayerID);
}
}
else
{
playersToNotify.emplace_back(observerPlayerId);
}
auto *message = static_cast<CNWSMessage*>(server->GetNWSMessage());
for (auto &pid : playersToNotify)
{
bool success = false;
auto *observerPlayerObject = static_cast<CNWSPlayer*>(server->GetClientObjectByPlayerId(pid, 0));
if (observerPlayerObject == nullptr)
continue;
auto targets = g_plugin->m_RenamePlayerNames[targetCreature->m_idSelf];
// If the update is to all clients but the observer has a personal override of the target's name then skip
if (observerPlayerId == Constants::PLAYERID_ALL_CLIENTS && targets.count(observerPlayerObject->m_oidNWSObject))
continue;
if (g_plugin->m_RenameAllowDM || observerPlayerObject->m_nCharacterType != Constants::CharacterType::DM)
{
// Write a message notifying an object update.
message->CreateWriteMessage(0x400, pid, 1);
// We don't need one for our update.
// However, the appearance update is contingent on receiving a pointer which isn't nullptr.
auto *lastUpdateObj = reinterpret_cast<CLastUpdateObject*>(0xDEADBEEF);
message->WriteGameObjUpdate_UpdateObject(observerPlayerObject, targetCreature, lastUpdateObj, 0, 0x400);
uint8_t *data = nullptr;
uint32_t size = 0;
if (message->GetWriteMessage(&data, &size) && size)
{
message->SendServerToPlayerMessage(pid, 5, 1, data, size);
success = true;
}
if (m_RenameOnPlayerList)
message->SendServerToPlayerPlayerList_All(observerPlayerObject);
}
LOG_DEBUG("%s sending name update message for observer (PlayerID): '0x%08x', target (ObjectID): '0x%08x'.",
success ? "Succeeded" : "Failed", pid, targetCreature->m_idSelf);
}
}
ArgumentStack Rename::SetPCNameOverride(ArgumentStack&& args)
{
auto targetOid = Services::Events::ExtractArgument<ObjectID>(args);
if (auto *targetPlayer = player(targetOid))
{
auto *server = Globals::AppManager()->m_pServerExoApp;
auto *targetCreature = server->GetCreatureByGameObjectID(targetOid);
if (targetCreature == nullptr)
{
LOG_ERROR("No creature object found for Player ID '0x%08x', oidNWSObject '%x'", targetPlayer->m_nPlayerID, targetOid);
return Services::Events::Arguments();
}
const auto newName = Services::Events::ExtractArgument<std::string>(args);
const auto sPrefix = Services::Events::ExtractArgument<std::string>(args);
const auto sSuffix = Services::Events::ExtractArgument<std::string>(args);
auto bPlayerNameState = Services::Events::ExtractArgument<int>(args);
const auto observerOid = Services::Events::ExtractArgument<ObjectID>(args);
if (bPlayerNameState != NWNX_RENAME_PLAYERNAME_DEFAULT && observerOid != Constants::OBJECT_INVALID)
{
LOG_WARNING("You can not override or obfuscate a player name per target. Falling back to DEFAULT.");
bPlayerNameState = NWNX_RENAME_PLAYERNAME_DEFAULT;
}
if (bPlayerNameState != NWNX_RENAME_PLAYERNAME_DEFAULT && !m_RenameOnPlayerList)
{
LOG_WARNING("You can not override the community name with NWNX_RENAME_ON_PLAYER_LIST set to false.");
bPlayerNameState = NWNX_RENAME_PLAYERNAME_DEFAULT;
}
const auto observerPlayerId =
observerOid == Constants::OBJECT_INVALID ? Constants::PLAYERID_ALL_CLIENTS
: server->GetPlayerIDByGameObjectID(observerOid);
if (observerPlayerId == Constants::PLAYERID_INVALIDID)
{
LOG_ERROR("The target observer '0x%08x' is not a valid player.", observerPlayerId);
return Services::Events::Arguments();
}
std::string fullDisplayName = sPrefix + newName + sSuffix; //put together the floaty/chat/hover name
fullDisplayName = std::regex_replace(fullDisplayName, std::regex("^ +| +$|( ) +"), "$1"); //remove trailing and leading spaces
// Store our override values
m_RenamePlayerNames[targetOid][observerOid] = std::make_tuple(CExoString(fullDisplayName.c_str()),
CExoString(newName.c_str()), bPlayerNameState);
// Store the original values
auto *pPlayerInfo = server->GetNetLayer()->GetPlayerInfo(targetPlayer->m_nPlayerID);
m_RenameOriginalNames[targetOid] = std::make_tuple(
pPlayerInfo->m_sPlayerName,
targetCreature->m_pStats->m_lsFirstName,
targetCreature->m_pStats->m_lsLastName);
// If we've ran this before the PC has even been added to the other clients' player list then there's
// nothing else we need to do, the hooks will take care of doing the renames. If we don't skip this
// then the SendServerToPlayerPlayerList_All in the SendNameUpdate below runs before the server has even ran a
// SendServerToPlayerPlayerList_Add and weird things happen(tm)
auto &v = m_RenameAddedToPlayerList;
if (m_RenameOnPlayerList && v.find(targetPlayer->m_oidNWSObject) == v.end())
{
return Services::Events::Arguments();
}
SendNameUpdate(targetCreature, observerPlayerId);
}
return Services::Events::Arguments();
}
ArgumentStack Rename::GetPCNameOverride(ArgumentStack &&args)
{
auto targetOid = Services::Events::ExtractArgument<ObjectID>(args);
std::string retVal;
if (auto *targetPlayer = player(targetOid))
{
auto *targetCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(targetOid);
if (!targetCreature)
{
LOG_ERROR("No creature object found for Player %x, oidNWSObject %x", targetPlayer->m_nPlayerID, targetOid);
return Services::Events::Arguments();
}
auto observerOid = Services::Events::ExtractArgument<ObjectID>(args);
if(m_RenamePlayerNames[targetOid].find(observerOid) != m_RenamePlayerNames[targetOid].end())
retVal = std::get<0>(m_RenamePlayerNames[targetOid][observerOid]).CStr();
else if(m_RenamePlayerNames[targetOid].find(Constants::OBJECT_INVALID) != m_RenamePlayerNames[targetOid].end())
retVal = std::get<0>(m_RenamePlayerNames[targetOid][Constants::OBJECT_INVALID]).CStr();
}
return Services::Events::Arguments(retVal);
}
ArgumentStack Rename::ClearPCNameOverride(ArgumentStack &&args)
{
auto playerOid = Services::Events::ExtractArgument<ObjectID>(args);
auto observerOid = Services::Events::ExtractArgument<ObjectID>(args);
bool bClearAll = Services::Events::ExtractArgument<int32_t>(args);
auto *server = Globals::AppManager()->m_pServerExoApp;
const auto observerPlayerId =
observerOid == Constants::OBJECT_INVALID ? Constants::PLAYERID_ALL_CLIENTS
: server->GetPlayerIDByGameObjectID(observerOid);
if (observerPlayerId == Constants::PLAYERID_INVALIDID)
{
LOG_ERROR("The target observer '0x%08x' is not a valid player.", observerPlayerId);
return Services::Events::Arguments();
}
//clears global override for target PC
if (observerOid == Constants::OBJECT_INVALID && !bClearAll)
{
auto *targetCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(playerOid);
m_RenamePlayerNames[playerOid].erase(Constants::OBJECT_INVALID);
SendNameUpdate(targetCreature, Constants::PLAYERID_ALL_CLIENTS);
}
// clears global override and all personal overrides for that target PC
else if (observerOid == Constants::OBJECT_INVALID)
{
auto *targetCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(playerOid);
m_RenamePlayerNames.erase(playerOid);
SendNameUpdate(targetCreature, Constants::PLAYERID_ALL_CLIENTS);
}
// clears all personal overrides for the observer for any targets
else if (playerOid == Constants::OBJECT_INVALID)
{
for (auto tgt = m_RenamePlayerNames.cbegin(), next_tgt = tgt; tgt != m_RenamePlayerNames.cend(); tgt = next_tgt)
{
++next_tgt;
if (m_RenamePlayerNames[tgt->first].erase(observerOid))
{
auto *targetCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(tgt->first);
if (targetCreature)
SendNameUpdate(targetCreature, observerPlayerId);
}
}
}
// clears personal override for that observer for target oPC
else
{
auto *targetCreature = Globals::AppManager()->m_pServerExoApp->GetCreatureByGameObjectID(playerOid);
m_RenamePlayerNames[playerOid].erase(observerOid);
SendNameUpdate(targetCreature, observerPlayerId);
}
return Services::Events::Arguments();
}
}
| 43.954856 | 170 | 0.669385 | GideonCrawle |
10816f47c2a8ec6f56032fccf80bcd9e7d5649ba | 3,062 | cpp | C++ | compiler/moco-tf/src/Canonicalization/PadCanonicalizer.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/moco-tf/src/Canonicalization/PadCanonicalizer.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/moco-tf/src/Canonicalization/PadCanonicalizer.cpp | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PadCanonicalizer.h"
#include <moco/IR/TFDialect.h>
#include "loco/Service/TypeInference.h"
#include <stdex/Memory.h>
namespace
{
bool canonicalize_pad(loco::Graph *graph, moco::TFPad *node)
{
/**
* @note This will replace TFPad node with Canonical TensorConstantPad
*
* Before
* input --- TFPad -- C
* paddings --/
* After
* paddings ------- TFPad --
* /
* input ----------- TensorConstantPad -- C
* ConstGen --------/
* Where
* input : input of TFPad
* paddings : paddings of TFPad. it becomes TensorConstantPad's attribute.
* C : a node that uses TFPad as an input. TFPad is disconnected from C.
* ConstGen : constant value of Pad. TFPad has zero value by default.
*/
auto pad_node = graph->nodes()->create<loco::TensorConstantPad>();
auto constant_node = graph->nodes()->create<loco::ConstGen>();
auto input_node = node->input();
// TODO: support other dtype.
assert(loco::dtype_get(input_node) == loco::DataType::FLOAT32);
constant_node->dtype(loco::DataType::FLOAT32);
// TODO: constant node changes to scalar when it is implemented.
constant_node->shape({1});
constant_node->size<loco::DataType::FLOAT32>(1);
constant_node->at<loco::DataType::FLOAT32>(0) = 0.0f;
auto const_paddings_node = dynamic_cast<loco::ConstGen *>(node->paddings());
// TODO: support S64 type.
assert(const_paddings_node->dtype() == loco::DataType::S32);
assert(const_paddings_node->rank() == 2);
assert(const_paddings_node->dim(1).value() == 2);
auto padding = pad_node->padding();
uint32_t padding_rank = const_paddings_node->dim(0).value();
padding->rank(padding_rank);
for (uint32_t i = 0; i < padding_rank; i++)
{
padding->front(i) = const_paddings_node->at<loco::DataType::S32>(i << 1);
padding->back(i) = const_paddings_node->at<loco::DataType::S32>((i << 1) + 1);
}
// update connections
pad_node->input(input_node);
pad_node->constant(constant_node);
// replace node
replace(node).with(pad_node);
return true;
}
} // namespace
namespace moco
{
namespace tf
{
bool PadCanonicalizer::transform(TFPad *node) const
{
return canonicalize_pad(node->graph(), node);
}
} // namespace tf
} // namespace moco
| 30.316832 | 92 | 0.643044 | wateret |
1083834ea7c86c67df16cb6493f39dd9144f26f0 | 1,127 | cc | C++ | aslam_cv_common/test/test-hash-id.cc | shuhannod/aslam_cv2 | 4dd48916b9e5b9d5aa56e28894a04d4a25a87348 | [
"Apache-2.0"
] | 3 | 2019-09-16T02:11:58.000Z | 2020-03-20T22:49:32.000Z | aslam_cv_common/test/test-hash-id.cc | shuhannod/aslam_cv2 | 4dd48916b9e5b9d5aa56e28894a04d4a25a87348 | [
"Apache-2.0"
] | null | null | null | aslam_cv_common/test/test-hash-id.cc | shuhannod/aslam_cv2 | 4dd48916b9e5b9d5aa56e28894a04d4a25a87348 | [
"Apache-2.0"
] | 3 | 2019-07-04T00:47:45.000Z | 2019-10-17T02:22:11.000Z | #include <algorithm>
#include <unordered_set>
#include <gtest/gtest.h>
#include <aslam/common/entrypoint.h>
#include <aslam/common/hash-id.h>
using namespace aslam;
TEST(HashIdTest, Different) {
HashId a(HashId::random()), b(HashId::random());
EXPECT_NE(a, b);
}
TEST(HashIdTest, Validity) {
HashId a, b;
EXPECT_FALSE(a.isValid());
EXPECT_FALSE(b.isValid());
EXPECT_EQ(a,b);
a.randomize();
EXPECT_TRUE(a.isValid());
}
TEST(HashIdTest, String) {
HashId a(HashId::random()), b(HashId::random());
std::string as(a.hexString()), bs(b.hexString());
EXPECT_NE(as, bs);
EXPECT_EQ(as.length(), 32u);
EXPECT_EQ(bs.length(), 32u);
}
TEST(HashIdTest, Deserialize) {
HashId a;
std::string as(a.hexString());
HashId b;
EXPECT_TRUE(b.fromHexString(as));
EXPECT_EQ(a, b);
}
TEST(HashIdTest, StdHash) {
std::unordered_set<HashId> hashes;
HashId needle(HashId::random());
hashes.insert(needle);
hashes.insert(HashId::random());
std::unordered_set<HashId>::iterator found = hashes.find(needle);
EXPECT_TRUE(found != hashes.end());
EXPECT_EQ(*found, needle);
}
ASLAM_UNITTEST_ENTRYPOINT
| 21.673077 | 67 | 0.687666 | shuhannod |
1088be6841bce3d3a0624d4bfb5a6edfc47edc50 | 104 | cpp | C++ | ShipEditorSimulation/Pool.cpp | timdecode/GraphSimulation | 7dec48ea9d2e094bab0825cde44c93fe83d1a92c | [
"MIT"
] | 1 | 2018-09-05T21:01:29.000Z | 2018-09-05T21:01:29.000Z | ShipEditorSimulation/Pool.cpp | timdecode/GraphSimulation | 7dec48ea9d2e094bab0825cde44c93fe83d1a92c | [
"MIT"
] | null | null | null | ShipEditorSimulation/Pool.cpp | timdecode/GraphSimulation | 7dec48ea9d2e094bab0825cde44c93fe83d1a92c | [
"MIT"
] | null | null | null | // Copyright 2016 Timothy Davison, all rights reserved.
#include "RegionGrowing.h"
#include "Pool.h"
| 14.857143 | 55 | 0.740385 | timdecode |
1089607571bba3f5291fa7ee90fcab2cc793f19d | 11,569 | hh | C++ | src/base/remote_gdb.hh | zinob15/gem5 | fb2946e314ea9e63c7696ee8023150ed13956582 | [
"BSD-3-Clause"
] | 1 | 2021-10-11T18:06:53.000Z | 2021-10-11T18:06:53.000Z | src/base/remote_gdb.hh | zinob15/gem5 | fb2946e314ea9e63c7696ee8023150ed13956582 | [
"BSD-3-Clause"
] | 1 | 2022-01-31T13:15:08.000Z | 2022-01-31T13:15:08.000Z | src/base/remote_gdb.hh | zinob15/gem5 | fb2946e314ea9e63c7696ee8023150ed13956582 | [
"BSD-3-Clause"
] | 1 | 2021-11-08T18:50:43.000Z | 2021-11-08T18:50:43.000Z | /*
* Copyright (c) 2018 ARM Limited
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright 2015 LabWare
* Copyright 2014 Google, Inc.
* Copyright (c) 2002-2005 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.
*/
#ifndef __REMOTE_GDB_HH__
#define __REMOTE_GDB_HH__
#include <sys/signal.h>
#include <cstdint>
#include <exception>
#include <map>
#include <string>
#include <vector>
#include "arch/pcstate.hh"
#include "base/cprintf.hh"
#include "base/pollevent.hh"
#include "base/socket.hh"
#include "base/types.hh"
#include "cpu/pc_event.hh"
#include "sim/debug.hh"
#include "sim/eventq.hh"
/*
* This file implements a client for the GDB remote serial protocol as
* described in this official documentation:
*
* https://sourceware.org/gdb/current/onlinedocs/gdb/Remote-Protocol.html
*/
namespace gem5
{
class System;
class ThreadContext;
class BaseRemoteGDB;
class HardBreakpoint;
/**
* Concrete subclasses of this abstract class represent how the
* register values are transmitted on the wire. Usually each
* architecture should define one subclass, but there can be more
* if there is more than one possible wire format. For example,
* ARM defines both AArch32GdbRegCache and AArch64GdbRegCache.
*/
class BaseGdbRegCache
{
public:
/**
* Return the pointer to the raw bytes buffer containing the
* register values. Each byte of this buffer is literally
* encoded as two hex digits in the g or G RSP packet.
*
* @ingroup api_remote_gdb
*/
virtual char *data() const = 0;
/**
* Return the size of the raw buffer, in bytes
* (i.e., half of the number of digits in the g/G packet).
*
* @ingroup api_remote_gdb
*/
virtual size_t size() const = 0;
/**
* Fill the raw buffer from the registers in the ThreadContext.
*
* @ingroup api_remote_gdb
*/
virtual void getRegs(ThreadContext*) = 0;
/**
* Set the ThreadContext's registers from the values
* in the raw buffer.
*
* @ingroup api_remote_gdb
*/
virtual void setRegs(ThreadContext*) const = 0;
/**
* Return the name to use in places like DPRINTF.
* Having each concrete superclass redefine this member
* is useful in situations where the class of the regCache
* can change on the fly.
*
* @ingroup api_remote_gdb
*/
virtual const std::string name() const = 0;
/**
* @ingroup api_remote_gdb
*/
BaseGdbRegCache(BaseRemoteGDB *g) : gdb(g)
{}
virtual ~BaseGdbRegCache()
{}
protected:
BaseRemoteGDB *gdb;
};
class BaseRemoteGDB
{
friend class HardBreakpoint;
public:
/**
* @ingroup api_remote_gdb
* @{
*/
/**
* Interface to other parts of the simulator.
*/
BaseRemoteGDB(System *system, int _port);
virtual ~BaseRemoteGDB();
std::string name();
void listen();
void connect();
int port() const;
void attach(int fd);
void detach();
bool isAttached() { return attached; }
void addThreadContext(ThreadContext *_tc);
void replaceThreadContext(ThreadContext *_tc);
bool selectThreadContext(ContextID id);
bool trap(ContextID id, int type);
/** @} */ // end of api_remote_gdb
template <class GDBStub, class ...Args>
static BaseRemoteGDB *
build(Args... args)
{
int port = getRemoteGDBPort();
if (port)
return new GDBStub(args..., port);
else
return nullptr;
}
private:
/*
* Connection to the external GDB.
*/
void incomingData(int revent);
void connectWrapper(int revent) { connect(); }
template <void (BaseRemoteGDB::*F)(int revent)>
class SocketEvent : public PollEvent
{
protected:
BaseRemoteGDB *gdb;
public:
SocketEvent(BaseRemoteGDB *gdb, int fd, int e) :
PollEvent(fd, e), gdb(gdb)
{}
void process(int revent) { (gdb->*F)(revent); }
};
typedef SocketEvent<&BaseRemoteGDB::connectWrapper> ConnectEvent;
typedef SocketEvent<&BaseRemoteGDB::incomingData> DataEvent;
friend ConnectEvent;
friend DataEvent;
ConnectEvent *connectEvent;
DataEvent *dataEvent;
ListenSocket listener;
int _port;
// The socket commands come in through.
int fd;
// Transfer data to/from GDB.
uint8_t getbyte();
void putbyte(uint8_t b);
void recv(std::vector<char> &bp);
void send(const char *data);
void send(const std::string &data) { send(data.c_str()); }
template <typename ...Args>
void
send(const char *format, const Args &...args)
{
send(csprintf(format, args...));
}
/*
* Simulator side debugger state.
*/
bool active = false;
bool attached = false;
bool threadSwitching = false;
System *sys;
std::map<ContextID, ThreadContext *> threads;
ThreadContext *tc = nullptr;
BaseGdbRegCache *regCachePtr = nullptr;
class TrapEvent : public Event
{
protected:
int _type;
ContextID _id;
BaseRemoteGDB *gdb;
public:
TrapEvent(BaseRemoteGDB *g) : gdb(g)
{}
void type(int t) { _type = t; }
void id(ContextID id) { _id = id; }
void process() { gdb->trap(_id, _type); }
} trapEvent;
/*
* The interface to the simulated system.
*/
// Machine memory.
bool read(Addr addr, size_t size, char *data);
bool write(Addr addr, size_t size, const char *data);
template <class T> T read(Addr addr);
template <class T> void write(Addr addr, T data);
// Single step.
void singleStep();
EventWrapper<BaseRemoteGDB, &BaseRemoteGDB::singleStep> singleStepEvent;
void clearSingleStep();
void setSingleStep();
/// Schedule an event which will be triggered "delta" instructions later.
void scheduleInstCommitEvent(Event *ev, int delta);
/// Deschedule an instruction count based event.
void descheduleInstCommitEvent(Event *ev);
// Breakpoints.
void insertSoftBreak(Addr addr, size_t len);
void removeSoftBreak(Addr addr, size_t len);
void insertHardBreak(Addr addr, size_t len);
void removeHardBreak(Addr addr, size_t len);
/*
* GDB commands.
*/
struct GdbCommand
{
public:
struct Context
{
const GdbCommand *cmd;
char cmdByte;
int type;
char *data;
int len;
};
typedef bool (BaseRemoteGDB::*Func)(Context &ctx);
const char * const name;
const Func func;
GdbCommand(const char *_name, Func _func) : name(_name), func(_func) {}
};
static std::map<char, GdbCommand> commandMap;
bool cmdUnsupported(GdbCommand::Context &ctx);
bool cmdSignal(GdbCommand::Context &ctx);
bool cmdCont(GdbCommand::Context &ctx);
bool cmdAsyncCont(GdbCommand::Context &ctx);
bool cmdDetach(GdbCommand::Context &ctx);
bool cmdRegR(GdbCommand::Context &ctx);
bool cmdRegW(GdbCommand::Context &ctx);
bool cmdSetThread(GdbCommand::Context &ctx);
bool cmdMemR(GdbCommand::Context &ctx);
bool cmdMemW(GdbCommand::Context &ctx);
bool cmdQueryVar(GdbCommand::Context &ctx);
bool cmdStep(GdbCommand::Context &ctx);
bool cmdAsyncStep(GdbCommand::Context &ctx);
bool cmdClrHwBkpt(GdbCommand::Context &ctx);
bool cmdSetHwBkpt(GdbCommand::Context &ctx);
bool cmdDumpPageTable(GdbCommand::Context &ctx);
struct QuerySetCommand
{
struct Context
{
const std::string &name;
std::vector<std::string> args;
Context(const std::string &_name) : name(_name) {}
};
using Func = void (BaseRemoteGDB::*)(Context &ctx);
const char * const argSep;
const Func func;
QuerySetCommand(Func _func, const char *_argSep=nullptr) :
argSep(_argSep), func(_func)
{}
};
static std::map<std::string, QuerySetCommand> queryMap;
void queryC(QuerySetCommand::Context &ctx);
void querySupported(QuerySetCommand::Context &ctx);
void queryXfer(QuerySetCommand::Context &ctx);
size_t threadInfoIdx = 0;
void queryFThreadInfo(QuerySetCommand::Context &ctx);
void querySThreadInfo(QuerySetCommand::Context &ctx);
protected:
ThreadContext *context() { return tc; }
System *system() { return sys; }
void encodeBinaryData(const std::string &unencoded,
std::string &encoded) const;
void encodeXferResponse(const std::string &unencoded,
std::string &encoded, size_t offset, size_t unencoded_length) const;
// To be implemented by subclasses.
virtual bool checkBpLen(size_t len);
virtual BaseGdbRegCache *gdbRegs() = 0;
virtual bool acc(Addr addr, size_t len) = 0;
virtual std::vector<std::string> availableFeatures() const;
/**
* Get an XML target description.
*
* @param[in] annex the XML filename
* @param[out] output set to the decoded XML
* @return true if the given annex was found
*/
virtual bool getXferFeaturesRead(const std::string &annex,
std::string &output);
};
template <class T>
inline T
BaseRemoteGDB::read(Addr addr)
{
T temp;
read(addr, sizeof(T), (char *)&temp);
return temp;
}
template <class T>
inline void
BaseRemoteGDB::write(Addr addr, T data)
{
write(addr, sizeof(T), (const char *)&data);
}
} // namespace gem5
#endif /* __REMOTE_GDB_H__ */
| 27.545238 | 79 | 0.665485 | zinob15 |
c80935789299c12c90ec7b8c5af1211d58c42842 | 10,674 | cpp | C++ | Tests/NumLib/LocalToGlobalIndexMap.cpp | hosseinsotudeh/ogs | 214afcb00af23e4393168a846c7ee8ce4f13e489 | [
"BSD-4-Clause"
] | null | null | null | Tests/NumLib/LocalToGlobalIndexMap.cpp | hosseinsotudeh/ogs | 214afcb00af23e4393168a846c7ee8ce4f13e489 | [
"BSD-4-Clause"
] | null | null | null | Tests/NumLib/LocalToGlobalIndexMap.cpp | hosseinsotudeh/ogs | 214afcb00af23e4393168a846c7ee8ce4f13e489 | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "NumLib/DOF/LocalToGlobalIndexMap.h"
#include "MeshLib/MeshGenerators/MeshGenerator.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/MeshSearch/NodeSearch.h"
#include "MeshLib/MeshSubset.h"
class NumLibLocalToGlobalIndexMapTest : public ::testing::Test
{
public:
NumLibLocalToGlobalIndexMapTest()
{
mesh.reset(MeshLib::MeshGenerator::generateLineMesh(1.0, mesh_size));
nodesSubset =
std::make_unique<MeshLib::MeshSubset>(*mesh, mesh->getNodes());
// Add two components both based on the same nodesSubset.
components.emplace_back(*nodesSubset);
components.emplace_back(*nodesSubset);
}
protected:
static std::size_t const mesh_size = 9;
std::unique_ptr<MeshLib::Mesh const> mesh;
std::unique_ptr<MeshLib::MeshSubset const> nodesSubset;
//data component 0 and 1 are assigned to all nodes in the mesh
static int const comp0_id = 0;
static int const comp1_id = 1;
std::vector<MeshLib::MeshSubset> components;
std::unique_ptr<NumLib::LocalToGlobalIndexMap const> dof_map;
};
#ifndef USE_PETSC
TEST_F(NumLibLocalToGlobalIndexMapTest, NumberOfRowsByComponent)
#else
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_NumberOfRowsByComponent)
#endif
{
// need to store the size because the components will be moved into the
// DOF-table.
std::size_t components_size = components.size();
dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(components), NumLib::ComponentOrder::BY_COMPONENT);
// There must be as many rows as nodes in the input times the number of
// components.
ASSERT_EQ(mesh->getNumberOfNodes() * components_size, dof_map->dofSizeWithGhosts());
}
#ifndef USE_PETSC
TEST_F(NumLibLocalToGlobalIndexMapTest, NumberOfRowsByLocation)
#else
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_NumberOfRowsByLocation)
#endif
{
// need to store the size because the components will be moved into the
// DOF-table.
std::size_t components_size = components.size();
dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(components), NumLib::ComponentOrder::BY_LOCATION);
// There must be as many rows as nodes in the input times the number of
// components.
ASSERT_EQ(mesh->getNumberOfNodes() * components_size, dof_map->dofSizeWithGhosts());
}
#ifndef USE_PETSC
TEST_F(NumLibLocalToGlobalIndexMapTest, SubsetByComponent)
#else
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_SubsetByComponent)
#endif
{
dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(components), NumLib::ComponentOrder::BY_COMPONENT);
// Select some elements from the full mesh.
std::array<std::size_t, 3> const ids = {{ 0, 5, 8 }};
std::vector<MeshLib::Element*> some_elements;
for (std::size_t id : ids)
some_elements.push_back(mesh->getElement(id)->clone());
auto boundary_mesh =
MeshLib::createMeshFromElementSelection("boundary_mesh", some_elements);
MeshLib::MeshSubset selected_component(*boundary_mesh,
boundary_mesh->getNodes());
auto dof_map_subset = std::unique_ptr<NumLib::LocalToGlobalIndexMap>{
dof_map->deriveBoundaryConstrainedMap(1, // variable id
{0}, // component id
std::move(selected_component))};
// There must be as many rows as nodes in the input times the number of
// components.
ASSERT_EQ(boundary_mesh->getNodes().size(),
dof_map_subset->dofSizeWithGhosts());
}
#ifndef USE_PETSC
TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponents)
#else
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponents)
#endif
{
// test 2 variables (1st variable with 1 component, 2nd variable with 2 components)
components.emplace_back(*nodesSubset);
std::vector<int> vec_var_n_components{1, 2};
dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(components),
vec_var_n_components,
NumLib::ComponentOrder::BY_COMPONENT);
ASSERT_EQ(30, dof_map->dofSizeWithGhosts());
ASSERT_EQ(3, dof_map->getNumberOfComponents());
ASSERT_EQ(2u, dof_map->getNumberOfVariables());
ASSERT_EQ(1, dof_map->getNumberOfVariableComponents(0));
ASSERT_EQ(2, dof_map->getNumberOfVariableComponents(1));
MeshLib::Location l_node0(mesh->getID(), MeshLib::MeshItemType::Node, 0);
ASSERT_EQ(0, dof_map->getGlobalIndex(l_node0, 0, 0));
ASSERT_EQ(10, dof_map->getGlobalIndex(l_node0, 1, 0));
ASSERT_EQ(20, dof_map->getGlobalIndex(l_node0, 1, 1));
}
#ifndef USE_PETSC
TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponents2)
#else
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponents2)
#endif
{
// test 2 variables (1st variable with 2 component, 2nd variable with 1 components)
components.emplace_back(*nodesSubset);
std::vector<int> vec_var_n_components{2, 1};
dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(components),
vec_var_n_components,
NumLib::ComponentOrder::BY_COMPONENT);
ASSERT_EQ(30, dof_map->dofSizeWithGhosts());
ASSERT_EQ(3, dof_map->getNumberOfComponents());
ASSERT_EQ(2u, dof_map->getNumberOfVariables());
ASSERT_EQ(2, dof_map->getNumberOfVariableComponents(0));
ASSERT_EQ(1, dof_map->getNumberOfVariableComponents(1));
MeshLib::Location l_node0(mesh->getID(), MeshLib::MeshItemType::Node, 0);
ASSERT_EQ(0, dof_map->getGlobalIndex(l_node0, 0, 0));
ASSERT_EQ(10, dof_map->getGlobalIndex(l_node0, 0, 1));
ASSERT_EQ(20, dof_map->getGlobalIndex(l_node0, 1, 0));
}
#ifndef USE_PETSC
TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponentsHeterogeneousElements)
#else
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponentsHeterogeneousElements)
#endif
{
// test 2 variables
// - 1st variable with 2 components for all nodes, elements
// - 2nd variable with 1 component for nodes of element id 1
std::vector<MeshLib::Node*> var2_nodes{const_cast<MeshLib::Node*>(mesh->getNode(1)), const_cast<MeshLib::Node*>(mesh->getNode(2))};
MeshLib::MeshSubset var2_subset{*mesh, var2_nodes};
components.emplace_back(var2_subset);
std::vector<int> vec_var_n_components{2, 1};
std::vector<std::vector<MeshLib::Element*>const*> vec_var_elements;
vec_var_elements.push_back(&mesh->getElements());
std::vector<MeshLib::Element*> var2_elements{const_cast<MeshLib::Element*>(mesh->getElement(1))};
vec_var_elements.push_back(&var2_elements);
dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(components),
vec_var_n_components,
vec_var_elements,
NumLib::ComponentOrder::BY_COMPONENT);
ASSERT_EQ(22u, dof_map->dofSizeWithGhosts());
ASSERT_EQ(3, dof_map->getNumberOfComponents());
ASSERT_EQ(2u, dof_map->getNumberOfVariables());
ASSERT_EQ(2, dof_map->getNumberOfVariableComponents(0));
ASSERT_EQ(1, dof_map->getNumberOfVariableComponents(1));
MeshLib::Location l_node0(mesh->getID(), MeshLib::MeshItemType::Node, 0);
ASSERT_EQ(0, dof_map->getGlobalIndex(l_node0, 0, 0));
ASSERT_EQ(10, dof_map->getGlobalIndex(l_node0, 0, 1));
ASSERT_EQ(std::numeric_limits<GlobalIndexType>::max(), dof_map->getGlobalIndex(l_node0, 1, 0));
MeshLib::Location l_node1(mesh->getID(), MeshLib::MeshItemType::Node, 1);
ASSERT_EQ(1, dof_map->getGlobalIndex(l_node1, 0, 0));
ASSERT_EQ(11, dof_map->getGlobalIndex(l_node1, 0, 1));
ASSERT_EQ(20, dof_map->getGlobalIndex(l_node1, 1, 0));
auto ele0_c0_indices = (*dof_map)(0, 0);
ASSERT_EQ(2u, ele0_c0_indices.rows.size());
auto ele0_c2_indices = (*dof_map)(0, 2);
ASSERT_EQ(0u, ele0_c2_indices.rows.size());
auto ele1_c2_indices = (*dof_map)(1, 2);
ASSERT_EQ(2u, ele1_c2_indices.rows.size());
}
#ifndef USE_PETSC
TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponentsHeterogeneousWithinElement)
#else
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponentsHeterogeneousWithinElement)
#endif
{
// test 2 variables
// - 1st variable with 2 components for all nodes, elements
// - 2nd variable with 1 component for 1st node of element id 1
std::vector<MeshLib::Node*> var2_nodes{const_cast<MeshLib::Node*>(mesh->getNode(1))};
MeshLib::MeshSubset var2_subset = {*mesh, var2_nodes};
components.emplace_back(var2_subset);
std::vector<int> vec_var_n_components{2, 1};
std::vector<std::vector<MeshLib::Element*>const*> vec_var_elements;
vec_var_elements.push_back(&mesh->getElements());
std::vector<MeshLib::Element*> var2_elements{const_cast<MeshLib::Element*>(mesh->getElement(1))};
vec_var_elements.push_back(&var2_elements);
dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(components),
vec_var_n_components,
vec_var_elements,
NumLib::ComponentOrder::BY_COMPONENT);
ASSERT_EQ(21u, dof_map->dofSizeWithGhosts());
ASSERT_EQ(3, dof_map->getNumberOfComponents());
ASSERT_EQ(2u, dof_map->getNumberOfVariables());
ASSERT_EQ(2, dof_map->getNumberOfVariableComponents(0));
ASSERT_EQ(1, dof_map->getNumberOfVariableComponents(1));
MeshLib::Location l_node0(mesh->getID(), MeshLib::MeshItemType::Node, 0);
ASSERT_EQ(0, dof_map->getGlobalIndex(l_node0, 0, 0));
ASSERT_EQ(10, dof_map->getGlobalIndex(l_node0, 0, 1));
ASSERT_EQ(std::numeric_limits<GlobalIndexType>::max(), dof_map->getGlobalIndex(l_node0, 1, 0));
MeshLib::Location l_node1(mesh->getID(), MeshLib::MeshItemType::Node, 1);
ASSERT_EQ(1, dof_map->getGlobalIndex(l_node1, 0, 0));
ASSERT_EQ(11, dof_map->getGlobalIndex(l_node1, 0, 1));
ASSERT_EQ(20, dof_map->getGlobalIndex(l_node1, 1, 0));
auto ele0_c0_indices = (*dof_map)(0, 0);
ASSERT_EQ(2u, ele0_c0_indices.rows.size());
auto ele0_c2_indices = (*dof_map)(0, 2);
ASSERT_EQ(0u, ele0_c2_indices.rows.size());
auto ele1_c2_indices = (*dof_map)(1, 2);
ASSERT_EQ(1u, ele1_c2_indices.rows.size());
ASSERT_EQ(20u, ele1_c2_indices.rows[0]);
}
| 38.121429 | 135 | 0.719974 | hosseinsotudeh |
c810c8e43f2259753f488137169fb82a19380b5f | 22,229 | cpp | C++ | src/navier_stokes/StaggeredStokesBlockFactorizationPreconditioner.cpp | kkeonho/IBAMR | 50d5c37d8f2952abc21f05ab224f22003d23d6e7 | [
"BSD-3-Clause"
] | 264 | 2015-01-04T12:11:02.000Z | 2022-03-31T13:10:37.000Z | src/navier_stokes/StaggeredStokesBlockFactorizationPreconditioner.cpp | kkeonho/IBAMR | 50d5c37d8f2952abc21f05ab224f22003d23d6e7 | [
"BSD-3-Clause"
] | 1,057 | 2015-04-27T04:27:57.000Z | 2022-03-31T13:14:59.000Z | src/navier_stokes/StaggeredStokesBlockFactorizationPreconditioner.cpp | drwells/IBAMR | 0ceda3873405a35da4888c99e7d2b24d132f9071 | [
"BSD-3-Clause"
] | 126 | 2015-02-13T15:36:02.000Z | 2022-03-27T21:59:50.000Z | // ---------------------------------------------------------------------
//
// Copyright (c) 2014 - 2020 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------
/////////////////////////////// INCLUDES /////////////////////////////////////
#include "ibamr/StaggeredStokesBlockFactorizationPreconditioner.h"
#include "ibamr/StaggeredStokesBlockPreconditioner.h"
#include "ibamr/ibamr_utilities.h"
#include "ibtk/CellNoCornersFillPattern.h"
#include "ibtk/GeneralSolver.h"
#include "ibtk/HierarchyGhostCellInterpolation.h"
#include "ibtk/HierarchyMathOps.h"
#include "ibtk/LinearSolver.h"
#include "ibtk/PoissonSolver.h"
#include "CellVariable.h"
#include "HierarchyDataOpsReal.h"
#include "IntVector.h"
#include "MultiblockDataTranslator.h"
#include "PatchHierarchy.h"
#include "PatchLevel.h"
#include "PoissonSpecifications.h"
#include "SAMRAIVectorReal.h"
#include "SideVariable.h"
#include "Variable.h"
#include "VariableContext.h"
#include "VariableDatabase.h"
#include "VariableFillPattern.h"
#include "tbox/Database.h"
#include "tbox/MathUtilities.h"
#include "tbox/Pointer.h"
#include "tbox/Timer.h"
#include "tbox/TimerManager.h"
#include "tbox/Utilities.h"
#include <ostream>
#include <string>
#include "ibamr/namespaces.h" // IWYU pragma: keep
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
namespace
{
// Number of ghosts cells used for each variable quantity.
static const int CELLG = 1;
static const int SIDEG = 1;
// Types of refining and coarsening to perform prior to setting coarse-fine
// boundary and physical boundary ghost cell values.
static const std::string DATA_REFINE_TYPE = "NONE";
static const bool USE_CF_INTERPOLATION = true;
static const std::string DATA_COARSEN_TYPE = "CUBIC_COARSEN";
// Type of extrapolation to use at physical boundaries.
static const std::string BDRY_EXTRAP_TYPE = "LINEAR";
// Whether to enforce consistent interpolated values at Type 2 coarse-fine
// interface ghost cells.
static const bool CONSISTENT_TYPE_2_BDRY = false;
// Timers.
static Timer* t_solve_system;
static Timer* t_initialize_solver_state;
static Timer* t_deallocate_solver_state;
} // namespace
/////////////////////////////// PUBLIC ///////////////////////////////////////
StaggeredStokesBlockFactorizationPreconditioner::StaggeredStokesBlockFactorizationPreconditioner(
const std::string& object_name,
Pointer<Database> input_db,
const std::string& /*default_options_prefix*/)
: StaggeredStokesBlockPreconditioner(/*needs_velocity_solver*/ true,
/*needs_pressure_solver*/ true)
{
GeneralSolver::init(object_name, /*homogeneous_bc*/ true);
// Present implementation requires zero initial guess and can perform only
// one iteration.
d_initial_guess_nonzero = false;
d_max_iterations = 1;
// Read in the factorization type.
if (input_db->keyExists("factorization_type"))
{
std::string factorization_type_string = input_db->getString("factorization_type");
if (factorization_type_string == "LOWER_TRIANGULAR")
{
d_factorization_type = LOWER_TRIANGULAR;
}
else if (factorization_type_string == "UPPER_TRIANGULAR")
{
d_factorization_type = UPPER_TRIANGULAR;
}
else if (factorization_type_string == "SYMMETRIC")
{
d_factorization_type = SYMMETRIC;
}
else if (factorization_type_string == "DIAGONAL")
{
d_factorization_type = DIAGONAL;
}
else
{
TBOX_ERROR("unsupported factorization type: " << factorization_type_string << "\n");
}
}
// Setup variables.
VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
Pointer<VariableContext> context = var_db->getContext(d_object_name + "::CONTEXT");
const std::string U_var_name = d_object_name + "::U";
d_U_var = var_db->getVariable(U_var_name);
if (d_U_var)
{
d_F_U_mod_idx = var_db->mapVariableAndContextToIndex(d_U_var, context);
}
else
{
d_U_var = new SideVariable<NDIM, double>(U_var_name);
d_F_U_mod_idx = var_db->registerVariableAndContext(d_U_var, context, IntVector<NDIM>(SIDEG));
}
#if !defined(NDEBUG)
TBOX_ASSERT(d_F_U_mod_idx >= 0);
#endif
const std::string P_var_name = d_object_name + "::P";
d_P_var = var_db->getVariable(P_var_name);
if (d_P_var)
{
d_P_scratch_idx = var_db->mapVariableAndContextToIndex(d_P_var, context);
}
else
{
d_P_var = new CellVariable<NDIM, double>(P_var_name);
d_P_scratch_idx = var_db->registerVariableAndContext(d_P_var, context, IntVector<NDIM>(CELLG));
d_F_P_mod_idx = var_db->registerClonedPatchDataIndex(d_P_var, d_P_scratch_idx);
}
#if !defined(NDEBUG)
TBOX_ASSERT(d_P_scratch_idx >= 0);
TBOX_ASSERT(d_F_P_mod_idx >= 0);
#endif
// Setup Timers.
IBAMR_DO_ONCE(t_solve_system = TimerManager::getManager()->getTimer(
"IBAMR::StaggeredStokesBlockFactorizationPreconditioner::solveSystem("
")");
t_initialize_solver_state =
TimerManager::getManager()->getTimer("IBAMR::StaggeredStokesBlockFactorizationPreconditioner::"
"initializeSolverState()");
t_deallocate_solver_state =
TimerManager::getManager()->getTimer("IBAMR::StaggeredStokesBlockFactorizationPreconditioner::"
"deallocateSolverState("
")"););
return;
} // StaggeredStokesBlockFactorizationPreconditioner
StaggeredStokesBlockFactorizationPreconditioner::~StaggeredStokesBlockFactorizationPreconditioner()
{
deallocateSolverState();
return;
} // ~StaggeredStokesBlockFactorizationPreconditioner
void
StaggeredStokesBlockFactorizationPreconditioner::setFactorizationType(FactorizationType factorization_type)
{
d_factorization_type = factorization_type;
return;
}
bool
StaggeredStokesBlockFactorizationPreconditioner::solveSystem(SAMRAIVectorReal<NDIM, double>& x,
SAMRAIVectorReal<NDIM, double>& b)
{
IBAMR_TIMER_START(t_solve_system);
// Initialize the solver (if necessary).
const bool deallocate_at_completion = !d_is_initialized;
if (!d_is_initialized) initializeSolverState(x, b);
// Get the vector components.
const int F_U_idx = b.getComponentDescriptorIndex(0);
const int F_P_idx = b.getComponentDescriptorIndex(1);
const Pointer<Variable<NDIM> >& F_U_var = b.getComponentVariable(0);
const Pointer<Variable<NDIM> >& F_P_var = b.getComponentVariable(1);
Pointer<SideVariable<NDIM, double> > F_U_sc_var = F_U_var;
Pointer<CellVariable<NDIM, double> > F_P_cc_var = F_P_var;
const int U_idx = x.getComponentDescriptorIndex(0);
const int P_idx = x.getComponentDescriptorIndex(1);
const Pointer<Variable<NDIM> >& U_var = x.getComponentVariable(0);
const Pointer<Variable<NDIM> >& P_var = x.getComponentVariable(1);
Pointer<SideVariable<NDIM, double> > U_sc_var = U_var;
Pointer<CellVariable<NDIM, double> > P_cc_var = P_var;
// Setup the component solver vectors.
Pointer<SAMRAIVectorReal<NDIM, double> > F_U_vec;
F_U_vec = new SAMRAIVectorReal<NDIM, double>(d_object_name + "::F_U", d_hierarchy, d_coarsest_ln, d_finest_ln);
F_U_vec->addComponent(F_U_sc_var, F_U_idx, d_velocity_wgt_idx, d_velocity_data_ops);
Pointer<SAMRAIVectorReal<NDIM, double> > F_U_mod_vec;
F_U_mod_vec =
new SAMRAIVectorReal<NDIM, double>(d_object_name + "::F_U_mod", d_hierarchy, d_coarsest_ln, d_finest_ln);
F_U_mod_vec->addComponent(d_U_var, d_F_U_mod_idx, d_velocity_wgt_idx, d_velocity_data_ops);
Pointer<SAMRAIVectorReal<NDIM, double> > U_vec;
U_vec = new SAMRAIVectorReal<NDIM, double>(d_object_name + "::U", d_hierarchy, d_coarsest_ln, d_finest_ln);
U_vec->addComponent(U_sc_var, U_idx, d_velocity_wgt_idx, d_velocity_data_ops);
Pointer<SAMRAIVectorReal<NDIM, double> > F_P_vec;
F_P_vec = new SAMRAIVectorReal<NDIM, double>(d_object_name + "::F_P", d_hierarchy, d_coarsest_ln, d_finest_ln);
F_P_vec->addComponent(F_P_cc_var, F_P_idx, d_pressure_wgt_idx, d_pressure_data_ops);
Pointer<SAMRAIVectorReal<NDIM, double> > F_P_mod_vec;
F_P_mod_vec =
new SAMRAIVectorReal<NDIM, double>(d_object_name + "::F_P_mod", d_hierarchy, d_coarsest_ln, d_finest_ln);
F_P_mod_vec->addComponent(d_P_var, d_F_P_mod_idx, d_pressure_wgt_idx, d_pressure_data_ops);
Pointer<SAMRAIVectorReal<NDIM, double> > P_vec;
P_vec = new SAMRAIVectorReal<NDIM, double>(d_object_name + "::P", d_hierarchy, d_coarsest_ln, d_finest_ln);
P_vec->addComponent(P_cc_var, P_idx, d_pressure_wgt_idx, d_pressure_data_ops);
// Setup the interpolation transaction information.
Pointer<VariableFillPattern<NDIM> > fill_pattern = new CellNoCornersFillPattern(CELLG, false, false, true);
using InterpolationTransactionComponent = HierarchyGhostCellInterpolation::InterpolationTransactionComponent;
InterpolationTransactionComponent P_transaction_comp(P_idx,
DATA_REFINE_TYPE,
USE_CF_INTERPOLATION,
DATA_COARSEN_TYPE,
BDRY_EXTRAP_TYPE,
CONSISTENT_TYPE_2_BDRY,
d_P_bc_coef,
fill_pattern);
InterpolationTransactionComponent P_scratch_transaction_comp(d_P_scratch_idx,
DATA_REFINE_TYPE,
USE_CF_INTERPOLATION,
DATA_COARSEN_TYPE,
BDRY_EXTRAP_TYPE,
CONSISTENT_TYPE_2_BDRY,
d_P_bc_coef,
fill_pattern);
// Allocate scratch data.
for (int ln = d_coarsest_ln; ln <= d_finest_ln; ++ln)
{
Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);
level->allocatePatchData(d_F_U_mod_idx);
level->allocatePatchData(d_P_scratch_idx);
level->allocatePatchData(d_F_P_mod_idx);
}
// Apply one of the approximate block-factorization preconditioners.
switch (d_factorization_type)
{
case UPPER_TRIANGULAR:
solvePressureSubsystem(*P_vec, *F_P_vec, /*initial_guess_nonzero*/ false);
d_P_bdry_fill_op->resetTransactionComponent(P_transaction_comp);
d_hier_math_ops->grad(d_F_U_mod_idx,
F_U_sc_var,
/*cf_bdry_synch*/ true,
-1.0,
P_idx,
P_cc_var,
d_P_bdry_fill_op,
d_pressure_solver->getSolutionTime(),
1.0,
F_U_idx,
F_U_sc_var);
d_P_bdry_fill_op->resetTransactionComponent(P_scratch_transaction_comp);
solveVelocitySubsystem(*U_vec,
*F_U_mod_vec,
/*initial_guess_nonzero*/ false);
break;
case LOWER_TRIANGULAR:
solveVelocitySubsystem(*U_vec, *F_U_vec, /*initial_guess_nonzero*/ false);
d_hier_math_ops->div(d_F_P_mod_idx,
F_P_cc_var,
1.0,
U_idx,
U_sc_var,
d_no_fill_op,
d_velocity_solver->getSolutionTime(),
/*cf_bdry_synch*/ true,
1.0,
F_P_idx,
F_P_cc_var);
solvePressureSubsystem(*P_vec,
*F_P_mod_vec,
/*initial_guess_nonzero*/ false);
break;
case SYMMETRIC:
solveVelocitySubsystem(*U_vec, *F_U_vec, /*initial_guess_nonzero*/ false);
d_hier_math_ops->div(d_F_P_mod_idx,
F_P_cc_var,
1.0,
U_idx,
U_sc_var,
d_no_fill_op,
d_velocity_solver->getSolutionTime(),
/*cf_bdry_synch*/ true,
1.0,
F_P_idx,
F_P_cc_var);
solvePressureSubsystem(*P_vec,
*F_P_mod_vec,
/*initial_guess_nonzero*/ false);
d_P_bdry_fill_op->resetTransactionComponent(P_transaction_comp);
d_hier_math_ops->grad(d_F_U_mod_idx,
F_U_sc_var,
/*cf_bdry_synch*/ true,
-1.0,
P_idx,
P_cc_var,
d_P_bdry_fill_op,
d_pressure_solver->getSolutionTime(),
1.0,
F_U_idx,
F_U_sc_var);
d_P_bdry_fill_op->resetTransactionComponent(P_scratch_transaction_comp);
solveVelocitySubsystem(*U_vec,
*F_U_mod_vec,
/*initial_guess_nonzero*/ true);
break;
case DIAGONAL:
solveVelocitySubsystem(*U_vec, *F_U_vec, /*initial_guess_nonzero*/ false);
solvePressureSubsystem(*P_vec, *F_P_vec, /*initial_guess_nonzero*/ false);
break;
default:
TBOX_ERROR("unsupported block factorization type\n");
}
// Account for nullspace vectors.
correctNullspace(U_vec, P_vec);
// Deallocate scratch data.
for (int ln = d_coarsest_ln; ln <= d_finest_ln; ++ln)
{
Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);
level->deallocatePatchData(d_F_U_mod_idx);
level->deallocatePatchData(d_P_scratch_idx);
level->deallocatePatchData(d_F_P_mod_idx);
}
// Deallocate the solver (if necessary).
if (deallocate_at_completion) deallocateSolverState();
IBAMR_TIMER_STOP(t_solve_system);
return true;
}
void
StaggeredStokesBlockFactorizationPreconditioner::initializeSolverState(const SAMRAIVectorReal<NDIM, double>& x,
const SAMRAIVectorReal<NDIM, double>& b)
{
IBAMR_TIMER_START(t_initialize_solver_state);
if (d_is_initialized) deallocateSolverState();
// Parent class initialization.
StaggeredStokesBlockPreconditioner::initializeSolverState(x, b);
// Setup hierarchy operators.
Pointer<VariableFillPattern<NDIM> > fill_pattern = new CellNoCornersFillPattern(CELLG, false, false, true);
using InterpolationTransactionComponent = HierarchyGhostCellInterpolation::InterpolationTransactionComponent;
InterpolationTransactionComponent P_scratch_component(d_P_scratch_idx,
DATA_REFINE_TYPE,
USE_CF_INTERPOLATION,
DATA_COARSEN_TYPE,
BDRY_EXTRAP_TYPE,
CONSISTENT_TYPE_2_BDRY,
d_P_bc_coef,
fill_pattern);
d_P_bdry_fill_op = new HierarchyGhostCellInterpolation();
d_P_bdry_fill_op->setHomogeneousBc(true);
d_P_bdry_fill_op->initializeOperatorState(P_scratch_component, d_hierarchy);
d_is_initialized = true;
IBAMR_TIMER_STOP(t_initialize_solver_state);
return;
} // initializeSolverState
void
StaggeredStokesBlockFactorizationPreconditioner::deallocateSolverState()
{
if (!d_is_initialized) return;
IBAMR_TIMER_START(t_deallocate_solver_state);
// Parent class deallocation.
StaggeredStokesBlockPreconditioner::deallocateSolverState();
// Deallocate hierarchy operators.
d_P_bdry_fill_op.setNull();
d_is_initialized = false;
IBAMR_TIMER_STOP(t_deallocate_solver_state);
return;
} // deallocateSolverState
void
StaggeredStokesBlockFactorizationPreconditioner::setInitialGuessNonzero(bool initial_guess_nonzero)
{
if (initial_guess_nonzero)
{
TBOX_ERROR(d_object_name + "::setInitialGuessNonzero()\n"
<< " class "
"IBAMR::StaggeredStokesBlockFactorizationPreconditioner "
"requires a "
"zero initial guess"
<< std::endl);
}
return;
} // setInitialGuessNonzero
void
StaggeredStokesBlockFactorizationPreconditioner::setMaxIterations(int max_iterations)
{
if (max_iterations != 1)
{
TBOX_ERROR(d_object_name + "::setMaxIterations()\n"
<< " class "
"IBAMR::StaggeredStokesBlockFactorizationPreconditioner only "
"performs a single iteration"
<< std::endl);
}
return;
} // setMaxIterations
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
void
StaggeredStokesBlockFactorizationPreconditioner::solvePressureSubsystem(SAMRAIVectorReal<NDIM, double>& P_vec,
SAMRAIVectorReal<NDIM, double>& F_P_vec,
const bool initial_guess_nonzero)
{
// Get the vector components.
const int P_idx = P_vec.getComponentDescriptorIndex(0);
const int F_P_idx = F_P_vec.getComponentDescriptorIndex(0);
Pointer<SAMRAIVectorReal<NDIM, double> > P_scratch_vec;
P_scratch_vec =
new SAMRAIVectorReal<NDIM, double>(d_object_name + "::P_scratch", d_hierarchy, d_coarsest_ln, d_finest_ln);
P_scratch_vec->addComponent(d_P_var, d_P_scratch_idx, d_pressure_wgt_idx, d_pressure_data_ops);
// Solve the pressure sub-problem by applying inv(S^) to F_P, in which
// S^ is the approximate Schur complement.
//
// The Schur complement S is
//
// S = D inv(rho/dt - K*mu*L) G
//
// We obtain S^ by assuming that
//
// D inv(rho/dt - K*mu*L) G ~ L_p inv(rho/dt - K*mu*L_p)
//
// in which L_p = D*G.
//
// We treat two cases:
//
// (i) rho/dt = 0.
//
// In this case,
//
// inv(S^) = inv(L_p inv(-K*mu*L_p)) = -K*mu
//
// so that
//
// P := -K*mu*F_P
//
// (ii) rho/dt != 0.
//
// In this case, we make the further approximation that
//
// L_p ~ rho L_rho = rho (D (1/rho) G)
//
// so that
//
// inv(S^) = (1/dt) inv(L_rho) - K*mu
//
// and
//
// P := [(1/dt) inv(L_rho) - K*mu] F_P
//
// NOTE: d_U_problem_coefs.getCConstant() == rho/dt
// d_U_problem_coefs.getDConstant() == -K*mu
//
// in which K depends on the form of the time stepping scheme.
const bool steady_state =
d_U_problem_coefs.cIsZero() ||
(d_U_problem_coefs.cIsConstant() && MathUtilities<double>::equalEps(d_U_problem_coefs.getCConstant(), 0.0));
if (steady_state)
{
d_pressure_data_ops->scale(P_idx, d_U_problem_coefs.getDConstant(), F_P_idx);
}
else
{
d_pressure_solver->setHomogeneousBc(true);
auto p_pressure_solver = dynamic_cast<LinearSolver*>(d_pressure_solver.getPointer());
if (p_pressure_solver) p_pressure_solver->setInitialGuessNonzero(initial_guess_nonzero);
d_pressure_solver->solveSystem(*P_scratch_vec,
F_P_vec); // P_scratch_idx := -inv(L_rho)*F_P
d_pressure_data_ops->linearSum(
P_idx, -1.0 / getDt(), d_P_scratch_idx, d_U_problem_coefs.getDConstant(), F_P_idx);
}
return;
}
void
StaggeredStokesBlockFactorizationPreconditioner::solveVelocitySubsystem(SAMRAIVectorReal<NDIM, double>& U_vec,
SAMRAIVectorReal<NDIM, double>& F_U_vec,
const bool initial_guess_nonzero)
{
// Solve the velocity sub-problem.
//
// U := inv(rho/dt - K*mu*L) * F_U
//
// No special treatment is needed for the steady-state case.
d_velocity_solver->setHomogeneousBc(true);
auto p_velocity_solver = dynamic_cast<LinearSolver*>(d_velocity_solver.getPointer());
if (p_velocity_solver) p_velocity_solver->setInitialGuessNonzero(initial_guess_nonzero);
d_velocity_solver->solveSystem(U_vec, F_U_vec);
return;
}
//////////////////////////////////////////////////////////////////////////////
} // namespace IBAMR
//////////////////////////////////////////////////////////////////////////////
| 39.836918 | 117 | 0.586531 | kkeonho |
c81174fe2da7990dfd340c6fae2a403c36b93d47 | 1,921 | cpp | C++ | gameboy_core/ios/Classes/gb/game_boy.cpp | momo5502/game-man | 296c1bfdde98541e5cc29507309e8903f1bc20a6 | [
"MIT"
] | 5 | 2022-01-03T21:20:15.000Z | 2022-01-05T11:58:35.000Z | gameboy_core/ios/Classes/gb/game_boy.cpp | momo5502/game-man | 296c1bfdde98541e5cc29507309e8903f1bc20a6 | [
"MIT"
] | null | null | null | gameboy_core/ios/Classes/gb/game_boy.cpp | momo5502/game-man | 296c1bfdde98541e5cc29507309e8903f1bc20a6 | [
"MIT"
] | null | null | null | #include "std_include.hpp"
#include "game_boy.hpp"
game_boy::game_boy(joypad* joypad, display* display)
: joypad_(joypad)
, display_(display)
, input_(this)
, cpu_(this)
, mmu_(this)
, gpu_(this)
{
}
game_boy::~game_boy()
{
this->off_ = true;
}
void game_boy::serialize(utils::binary_buffer& buffer)
{
this->cpu_.serialize(buffer);
this->mmu_.serialize(buffer);
this->gpu_.serialize(buffer);
}
void game_boy::run()
{
this->off_ = false;
while (!this->off_ && this->frame())
{
while (this->paused_)
{
if (this->off_ || !this->get_display()->is_on())
{
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
}
void game_boy::skip_bios()
{
this->cpu_.skip_bios();
}
void game_boy::turn_off()
{
this->off_ = true;
}
void game_boy::pause()
{
this->paused_ = true;
}
void game_boy::resume()
{
this->paused_ = false;
}
bool game_boy::is_paused() const
{
return this->paused_;
}
bool game_boy::frame()
{
const uint32_t end_tick = this->cpu_.registers.m + 17556;
const auto start = std::chrono::high_resolution_clock::now();
while (this->cpu_.registers.m < end_tick)
{
if (!this->cpu_.execute())
{
return false;
}
}
const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - start);
const auto frame_delay = 15ms / this->speed_scale_;
if (delta < frame_delay)
{
std::this_thread::sleep_for(frame_delay - delta);
}
return true;
}
void game_boy::load_rom(std::vector<uint8_t> data)
{
if (data.size() < sizeof(gb_rom))
{
throw std::runtime_error("Invalid rom");
}
auto* rom = reinterpret_cast<const gb_rom*>(data.data());
std::string rom_name(rom->title, 16);
while (!rom_name.empty() && !rom_name.back()) rom_name.pop_back();
this->display_->set_title(std::move(rom_name));
this->gpu_.set_is_color_gb(false);
this->mmu_.load_rom(std::move(data));
}
| 17.463636 | 74 | 0.665799 | momo5502 |
c815542decfce80dde10af976a3a4229608c7f7e | 98,025 | hpp | C++ | MyFish/Pods/Realm/include/core/realm/impl/transact_log.hpp | aidudu/MyFish | b2cc6c82c67c535016d6dad601452c172823fb4f | [
"MIT"
] | 10 | 2016-05-12T02:01:49.000Z | 2020-04-18T10:21:50.000Z | MyFish/Pods/Realm/include/core/realm/impl/transact_log.hpp | aidudu/MyFish | b2cc6c82c67c535016d6dad601452c172823fb4f | [
"MIT"
] | 1 | 2018-10-18T20:30:01.000Z | 2018-10-18T20:30:01.000Z | MyFish/Pods/Realm/include/core/realm/impl/transact_log.hpp | aidudu/MyFish | b2cc6c82c67c535016d6dad601452c172823fb4f | [
"MIT"
] | 13 | 2016-03-29T02:00:33.000Z | 2020-10-27T16:26:35.000Z | /*************************************************************************
*
* Copyright 2016 Realm 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.
*
**************************************************************************/
#ifndef REALM_IMPL_TRANSACT_LOG_HPP
#define REALM_IMPL_TRANSACT_LOG_HPP
#include <stdexcept>
#include <realm/string_data.hpp>
#include <realm/data_type.hpp>
#include <realm/binary_data.hpp>
#include <realm/olddatetime.hpp>
#include <realm/mixed.hpp>
#include <realm/util/safe_int_ops.hpp>
#include <realm/util/buffer.hpp>
#include <realm/util/string_buffer.hpp>
#include <realm/util/tuple.hpp>
#include <realm/impl/input_stream.hpp>
#include <realm/group.hpp>
#include <realm/descriptor.hpp>
namespace realm {
namespace _impl {
/// Transaction log instruction encoding
enum Instruction {
instr_InsertGroupLevelTable = 1,
instr_EraseGroupLevelTable = 2, // Remove columnless table from group
instr_RenameGroupLevelTable = 3,
instr_MoveGroupLevelTable = 45,
instr_SelectTable = 4,
instr_SetInt = 5,
instr_SetIntUnique = 31,
instr_SetBool = 6,
instr_SetFloat = 7,
instr_SetDouble = 8,
instr_SetString = 9,
instr_SetStringUnique = 32,
instr_SetBinary = 10,
instr_SetOldDateTime = 11,
instr_SetTimestamp = 48,
instr_SetTable = 12,
instr_SetMixed = 13,
instr_SetLink = 14,
instr_NullifyLink = 15, // Set link to null due to target being erased
instr_SetNull = 16,
instr_InsertSubstring = 43, // FIXME: Reenumerate
instr_EraseFromString = 44, // FIXME: Reenumerate
instr_InsertEmptyRows = 17,
instr_EraseRows = 18, // Remove (multiple) rows
instr_SwapRows = 19,
instr_ChangeLinkTargets = 47, // Replace links pointing to row A with links to row B
instr_ClearTable = 20, // Remove all rows in selected table
instr_OptimizeTable = 21,
instr_SelectDescriptor = 22, // Select descriptor from currently selected root table
instr_InsertColumn = 23, // Insert new non-nullable column into to selected descriptor (nullable is instr_InsertNullableColumn)
instr_InsertLinkColumn = 24, // do, but for a link-type column
instr_InsertNullableColumn = 25, // Insert nullable column
instr_EraseColumn = 26, // Remove column from selected descriptor
instr_EraseLinkColumn = 27, // Remove link-type column from selected descriptor
instr_RenameColumn = 28, // Rename column in selected descriptor
instr_MoveColumn = 46, // Move column in selected descriptor // FIXME: Reenumerate
instr_AddSearchIndex = 29, // Add a search index to a column
instr_RemoveSearchIndex = 30, // Remove a search index from a column
instr_SetLinkType = 33, // Strong/weak
instr_SelectLinkList = 34,
instr_LinkListSet = 35, // Assign to link list entry
instr_LinkListInsert = 36, // Insert entry into link list
instr_LinkListMove = 37, // Move an entry within a link list
instr_LinkListSwap = 38, // Swap two entries within a link list
instr_LinkListErase = 39, // Remove an entry from a link list
instr_LinkListNullify = 40, // Remove an entry from a link list due to linked row being erased
instr_LinkListClear = 41, // Ramove all entries from a link list
instr_LinkListSetAll = 42, // Assign to link list entry
};
class TransactLogStream {
public:
/// Ensure contiguous free space in the transaction log
/// buffer. This method must update `out_free_begin`
/// and `out_free_end` such that they refer to a chunk
/// of free space whose size is at least \a n.
///
/// \param n The required amount of contiguous free space. Must be
/// small (probably not greater than 1024)
/// \param n Must be small (probably not greater than 1024)
virtual void transact_log_reserve(size_t size, char** out_free_begin, char** out_free_end) = 0;
/// Copy the specified data into the transaction log buffer. This
/// function should be called only when the specified data does
/// not fit inside the chunk of free space currently referred to
/// by `out_free_begin` and `out_free_end`.
///
/// This method must update `out_begin` and
/// `out_end` such that, upon return, they still
/// refer to a (possibly empty) chunk of free space.
virtual void transact_log_append(const char* data, size_t size, char** out_free_begin, char** out_free_end) = 0;
};
class TransactLogBufferStream: public TransactLogStream {
public:
void transact_log_reserve(size_t size, char** out_free_begin, char** out_free_end) override;
void transact_log_append(const char* data, size_t size, char** out_free_begin, char** out_free_end) override;
const char* transact_log_data() const;
util::Buffer<char> m_buffer;
};
// LCOV_EXCL_START (because the NullInstructionObserver is trivial)
class NullInstructionObserver {
public:
/// The following methods are also those that TransactLogParser expects
/// to find on the `InstructionHandler`.
// No selection needed:
bool select_table(size_t, size_t, const size_t*) { return true; }
bool select_descriptor(size_t, const size_t*) { return true; }
bool select_link_list(size_t, size_t, size_t) { return true; }
bool insert_group_level_table(size_t, size_t, StringData) { return true; }
bool erase_group_level_table(size_t, size_t) { return true; }
bool rename_group_level_table(size_t, StringData) { return true; }
bool move_group_level_table(size_t, size_t) { return true; }
// Must have table selected:
bool insert_empty_rows(size_t, size_t, size_t, bool) { return true; }
bool erase_rows(size_t, size_t, size_t, bool) { return true; }
bool swap_rows(size_t, size_t) { return true; }
bool change_link_targets(size_t, size_t) { return true; }
bool clear_table() { return true; }
bool set_int(size_t, size_t, int_fast64_t) { return true; }
bool set_int_unique(size_t, size_t, size_t, int_fast64_t) { return true; }
bool set_bool(size_t, size_t, bool) { return true; }
bool set_float(size_t, size_t, float) { return true; }
bool set_double(size_t, size_t, double) { return true; }
bool set_string(size_t, size_t, StringData) { return true; }
bool set_string_unique(size_t, size_t, size_t, StringData) { return true; }
bool set_binary(size_t, size_t, BinaryData) { return true; }
bool set_olddatetime(size_t, size_t, OldDateTime) { return true; }
bool set_timestamp(size_t, size_t, Timestamp) { return true; }
bool set_table(size_t, size_t) { return true; }
bool set_mixed(size_t, size_t, const Mixed&) { return true; }
bool set_link(size_t, size_t, size_t, size_t) { return true; }
bool set_null(size_t, size_t) { return true; }
bool nullify_link(size_t, size_t, size_t) { return true; }
bool insert_substring(size_t, size_t, size_t, StringData) { return true; }
bool erase_substring(size_t, size_t, size_t, size_t) { return true; }
bool optimize_table() { return true; }
// Must have descriptor selected:
bool insert_link_column(size_t, DataType, StringData, size_t, size_t) { return true; }
bool insert_column(size_t, DataType, StringData, bool) { return true; }
bool erase_link_column(size_t, size_t, size_t) { return true; }
bool erase_column(size_t) { return true; }
bool rename_column(size_t, StringData) { return true; }
bool move_column(size_t, size_t) { return true; }
bool add_search_index(size_t) { return true; }
bool remove_search_index(size_t) { return true; }
bool set_link_type(size_t, LinkType) { return true; }
// Must have linklist selected:
bool link_list_set(size_t, size_t) { return true; }
bool link_list_insert(size_t, size_t) { return true; }
bool link_list_move(size_t, size_t) { return true; }
bool link_list_swap(size_t, size_t) { return true; }
bool link_list_erase(size_t) { return true; }
bool link_list_nullify(size_t) { return true; }
bool link_list_clear(size_t) { return true; }
void parse_complete() {}
};
// LCOV_EXCL_STOP (NullInstructionObserver)
/// See TransactLogConvenientEncoder for information about the meaning of the
/// arguments of each of the functions in this class.
class TransactLogEncoder {
public:
/// The following methods are also those that TransactLogParser expects
/// to find on the `InstructionHandler`.
// No selection needed:
bool select_table(size_t group_level_ndx, size_t levels, const size_t* path);
bool select_descriptor(size_t levels, const size_t* path);
bool select_link_list(size_t col_ndx, size_t row_ndx, size_t link_target_group_level_ndx);
bool insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name);
bool erase_group_level_table(size_t table_ndx, size_t num_tables);
bool rename_group_level_table(size_t table_ndx, StringData new_name);
bool move_group_level_table(size_t from_table_ndx, size_t to_table_ndx);
/// Must have table selected.
bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows,
bool unordered);
bool erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool unordered);
bool swap_rows(size_t row_ndx_1, size_t row_ndx_2);
bool change_link_targets(size_t row_ndx, size_t new_row_ndx);
bool clear_table();
bool set_int(size_t col_ndx, size_t row_ndx, int_fast64_t);
bool set_int_unique(size_t col_ndx, size_t row_ndx, size_t prior_num_rows, int_fast64_t);
bool set_bool(size_t col_ndx, size_t row_ndx, bool);
bool set_float(size_t col_ndx, size_t row_ndx, float);
bool set_double(size_t col_ndx, size_t row_ndx, double);
bool set_string(size_t col_ndx, size_t row_ndx, StringData);
bool set_string_unique(size_t col_ndx, size_t row_ndx, size_t prior_num_rows, StringData);
bool set_binary(size_t col_ndx, size_t row_ndx, BinaryData);
bool set_olddatetime(size_t col_ndx, size_t row_ndx, OldDateTime);
bool set_timestamp(size_t col_ndx, size_t row_ndx, Timestamp);
bool set_table(size_t col_ndx, size_t row_ndx);
bool set_mixed(size_t col_ndx, size_t row_ndx, const Mixed&);
bool set_link(size_t col_ndx, size_t row_ndx, size_t, size_t target_group_level_ndx);
bool set_null(size_t col_ndx, size_t row_ndx);
bool nullify_link(size_t col_ndx, size_t row_ndx, size_t target_group_level_ndx);
bool insert_substring(size_t col_ndx, size_t row_ndx, size_t pos, StringData);
bool erase_substring(size_t col_ndx, size_t row_ndx, size_t pos, size_t size);
bool optimize_table();
// Must have descriptor selected:
bool insert_link_column(size_t col_ndx, DataType, StringData name, size_t link_target_table_ndx, size_t backlink_col_ndx);
bool insert_column(size_t col_ndx, DataType, StringData name, bool nullable = false);
bool erase_link_column(size_t col_ndx, size_t link_target_table_ndx, size_t backlink_col_ndx);
bool erase_column(size_t col_ndx);
bool rename_column(size_t col_ndx, StringData new_name);
bool move_column(size_t col_ndx_1, size_t col_ndx_2);
bool add_search_index(size_t col_ndx);
bool remove_search_index(size_t col_ndx);
bool set_link_type(size_t col_ndx, LinkType);
// Must have linklist selected:
bool link_list_set(size_t link_ndx, size_t value);
bool link_list_set_all(const IntegerColumn& values);
bool link_list_insert(size_t link_ndx, size_t value);
bool link_list_move(size_t from_link_ndx, size_t to_link_ndx);
bool link_list_swap(size_t link1_ndx, size_t link2_ndx);
bool link_list_erase(size_t link_ndx);
bool link_list_nullify(size_t link_ndx);
bool link_list_clear(size_t old_list_size);
/// End of methods expected by parser.
TransactLogEncoder(TransactLogStream& out_stream);
void set_buffer(char* new_free_begin, char* new_free_end);
char* write_position() const { return m_transact_log_free_begin; }
private:
// Make sure this is in agreement with the actual integer encoding
// scheme (see encode_int()).
static const int max_enc_bytes_per_int = 10;
static const int max_enc_bytes_per_double = sizeof (double);
static const int max_enc_bytes_per_num = max_enc_bytes_per_int <
max_enc_bytes_per_double ? max_enc_bytes_per_double : max_enc_bytes_per_int;
TransactLogStream& m_stream;
// These two delimit a contiguous region of free space in a
// transaction log buffer following the last written data. It may
// be empty.
char* m_transact_log_free_begin = 0;
char* m_transact_log_free_end = 0;
char* reserve(size_t size);
/// \param ptr Must be in the range [m_transact_log_free_begin, m_transact_log_free_end]
void advance(char* ptr) noexcept;
template<class L>
void append_simple_instr(Instruction, const util::Tuple<L>& numbers);
template<class L>
void append_string_instr(Instruction, const util::Tuple<L>& numbers, StringData);
template<class L>
void append_mixed_instr(Instruction, const util::Tuple<L>& numbers, const Mixed&);
template<class L, class I>
bool append_variable_size_instr(Instruction instr, const util::Tuple<L>& numbers,
I var_begin, I var_end);
template<class T>
static char* encode_int(char*, T value);
static char* encode_bool(char*, bool value);
static char* encode_float(char*, float value);
static char* encode_double(char*, double value);
template<class>
struct EncodeNumber;
};
class TransactLogConvenientEncoder {
public:
void insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name);
void erase_group_level_table(size_t table_ndx, size_t num_tables);
void rename_group_level_table(size_t table_ndx, StringData new_name);
void move_group_level_table(size_t from_table_ndx, size_t to_table_ndx);
void insert_column(const Descriptor&, size_t col_ndx, DataType type, StringData name,
LinkTargetInfo& link, bool nullable = false);
void erase_column(const Descriptor&, size_t col_ndx);
void rename_column(const Descriptor&, size_t col_ndx, StringData name);
void move_column(const Descriptor&, size_t from, size_t to);
void set_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value);
void set_int_unique(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value);
void set_bool(const Table*, size_t col_ndx, size_t ndx, bool value);
void set_float(const Table*, size_t col_ndx, size_t ndx, float value);
void set_double(const Table*, size_t col_ndx, size_t ndx, double value);
void set_string(const Table*, size_t col_ndx, size_t ndx, StringData value);
void set_string_unique(const Table*, size_t col_ndx, size_t ndx, StringData value);
void set_binary(const Table*, size_t col_ndx, size_t ndx, BinaryData value);
void set_olddatetime(const Table*, size_t col_ndx, size_t ndx, OldDateTime value);
void set_timestamp(const Table*, size_t col_ndx, size_t ndx, Timestamp value);
void set_table(const Table*, size_t col_ndx, size_t ndx);
void set_mixed(const Table*, size_t col_ndx, size_t ndx, const Mixed& value);
void set_link(const Table*, size_t col_ndx, size_t ndx, size_t value);
void set_null(const Table*, size_t col_ndx, size_t ndx);
void set_link_list(const LinkView&, const IntegerColumn& values);
void insert_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, StringData);
void erase_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, size_t size);
/// \param prior_num_rows The number of rows in the table prior to the
/// modification.
void insert_empty_rows(const Table*, size_t row_ndx, size_t num_rows_to_insert,
size_t prior_num_rows);
/// \param prior_num_rows The number of rows in the table prior to the
/// modification.
void erase_rows(const Table*, size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool is_move_last_over);
void swap_rows(const Table*, size_t row_ndx_1, size_t row_ndx_2);
void change_link_targets(const Table*, size_t row_ndx, size_t new_row_ndx);
void add_search_index(const Table*, size_t col_ndx);
void remove_search_index(const Table*, size_t col_ndx);
void set_link_type(const Table*, size_t col_ndx, LinkType);
void clear_table(const Table*);
void optimize_table(const Table*);
void link_list_set(const LinkView&, size_t link_ndx, size_t value);
void link_list_insert(const LinkView&, size_t link_ndx, size_t value);
void link_list_move(const LinkView&, size_t from_link_ndx, size_t to_link_ndx);
void link_list_swap(const LinkView&, size_t link_ndx_1, size_t link_ndx_2);
void link_list_erase(const LinkView&, size_t link_ndx);
void link_list_clear(const LinkView&);
//@{
/// Implicit nullifications due to removal of target row. This is redundant
/// information from the point of view of replication, as the removal of the
/// target row will reproduce the implicit nullifications in the target
/// Realm anyway. The purpose of this instruction is to allow observers
/// (reactor pattern) to be explicitly notified about the implicit
/// nullifications.
void nullify_link(const Table*, size_t col_ndx, size_t ndx);
void link_list_nullify(const LinkView&, size_t link_ndx);
//@}
void on_table_destroyed(const Table*) noexcept;
void on_spec_destroyed(const Spec*) noexcept;
void on_link_list_destroyed(const LinkView&) noexcept;
protected:
TransactLogConvenientEncoder(TransactLogStream& encoder);
void reset_selection_caches() noexcept;
void set_buffer(char* new_free_begin, char* new_free_end) { m_encoder.set_buffer(new_free_begin, new_free_end); }
char* write_position() const { return m_encoder.write_position(); }
private:
TransactLogEncoder m_encoder;
// These are mutable because they are caches.
mutable util::Buffer<size_t> m_subtab_path_buf;
mutable const Table* m_selected_table;
mutable const Spec* m_selected_spec;
// Has to be atomic to support concurrent reset when a linklist
// is unselected. This can happen on a different thread. In case
// of races, setting of a new value must win.
mutable std::atomic<const LinkView*> m_selected_link_list;
void unselect_all() noexcept;
void select_table(const Table*); // unselects descriptor and link list
void select_desc(const Descriptor&); // unselects link list
void select_link_list(const LinkView&); // unselects descriptor
void record_subtable_path(const Table&, size_t*& out_begin, size_t*& out_end);
void do_select_table(const Table*);
void do_select_desc(const Descriptor&);
void do_select_link_list(const LinkView&);
friend class TransactReverser;
};
class TransactLogParser {
public:
class BadTransactLog; // Exception
TransactLogParser();
~TransactLogParser() noexcept;
/// See `TransactLogEncoder` for a list of methods that the `InstructionHandler` must define.
/// parse() promises that the path passed by reference to
/// InstructionHandler::select_descriptor() will remain valid
/// during subsequent calls to all descriptor modifying functions.
template<class InstructionHandler>
void parse(InputStream&, InstructionHandler&);
template<class InstructionHandler>
void parse(NoCopyInputStream&, InstructionHandler&);
private:
util::Buffer<char> m_input_buffer;
// The input stream is assumed to consist of chunks of memory organised such that
// every instruction resides in a single chunk only.
NoCopyInputStream* m_input;
// pointer into transaction log, each instruction is parsed from m_input_begin and onwards.
// Each instruction are assumed to be contiguous in memory.
const char* m_input_begin;
// pointer to one past current instruction log chunk. If m_input_begin reaches m_input_end,
// a call to next_input_buffer will move m_input_begin and m_input_end to a new chunk of
// memory. Setting m_input_end to 0 disables this check, and is used if it is already known
// that all of the instructions are in memory.
const char* m_input_end;
util::StringBuffer m_string_buffer;
static const int m_max_levels = 1024;
util::Buffer<size_t> m_path;
REALM_NORETURN void parser_error() const;
template<class InstructionHandler>
void parse_one(InstructionHandler&);
bool has_next() noexcept;
template<class T>
T read_int();
void read_bytes(char* data, size_t size);
BinaryData read_buffer(util::StringBuffer&, size_t size);
bool read_bool();
float read_float();
double read_double();
StringData read_string(util::StringBuffer&);
BinaryData read_binary(util::StringBuffer&);
Timestamp read_timestamp();
void read_mixed(Mixed*);
// Advance m_input_begin and m_input_end to reflect the next block of instructions
// Returns false if no more input was available
bool next_input_buffer();
// return true if input was available
bool read_char(char&); // throws
bool is_valid_data_type(int type);
bool is_valid_link_type(int type);
};
class TransactLogParser::BadTransactLog: public std::exception {
public:
const char* what() const noexcept override
{
return "Bad transaction log";
}
};
/// Implementation:
inline void TransactLogBufferStream::transact_log_reserve(size_t n, char** inout_new_begin, char** out_new_end)
{
char* data = m_buffer.data();
REALM_ASSERT(*inout_new_begin >= data);
REALM_ASSERT(*inout_new_begin <= (data + m_buffer.size()));
size_t size = *inout_new_begin - data;
m_buffer.reserve_extra(size, n);
data = m_buffer.data(); // May have changed
*inout_new_begin = data + size;
*out_new_end = data + m_buffer.size();
}
inline void TransactLogBufferStream::transact_log_append(const char* data, size_t size, char** out_new_begin, char** out_new_end)
{
transact_log_reserve(size, out_new_begin, out_new_end);
*out_new_begin = std::copy(data, data + size, *out_new_begin);
}
inline const char* TransactLogBufferStream::transact_log_data() const
{
return m_buffer.data();
}
inline TransactLogEncoder::TransactLogEncoder(TransactLogStream& stream):
m_stream(stream)
{
}
inline void TransactLogEncoder::set_buffer(char* free_begin, char* free_end)
{
REALM_ASSERT(free_begin <= free_end);
m_transact_log_free_begin = free_begin;
m_transact_log_free_end = free_end;
}
inline void TransactLogConvenientEncoder::reset_selection_caches() noexcept
{
unselect_all();
}
inline char* TransactLogEncoder::reserve(size_t n)
{
if (size_t(m_transact_log_free_end - m_transact_log_free_begin) < n) {
m_stream.transact_log_reserve(n, &m_transact_log_free_begin, &m_transact_log_free_end);
}
return m_transact_log_free_begin;
}
inline void TransactLogEncoder::advance(char* ptr) noexcept
{
REALM_ASSERT_DEBUG(m_transact_log_free_begin <= ptr);
REALM_ASSERT_DEBUG(ptr <= m_transact_log_free_end);
m_transact_log_free_begin = ptr;
}
// The integer encoding is platform independent. Also, it does not
// depend on the type of the specified integer. Integers of any type
// can be encoded as long as the specified buffer is large enough (see
// below). The decoding does not have to use the same type. Decoding
// will fail if, and only if the encoded value falls outside the range
// of the requested destination type.
//
// The encoding uses one or more bytes. It never uses more than 8 bits
// per byte. The last byte in the sequence is the first one that has
// its 8th bit set to zero.
//
// Consider a particular non-negative value V. Let W be the number of
// bits needed to encode V using the trivial binary encoding of
// integers. The total number of bytes produced is then
// ceil((W+1)/7). The first byte holds the 7 least significant bits of
// V. The last byte holds at most 6 bits of V including the most
// significant one. The value of the first bit of the last byte is
// always 2**((N-1)*7) where N is the total number of bytes.
//
// A negative value W is encoded by setting the sign bit to one and
// then encoding the positive result of -(W+1) as described above. The
// advantage of this representation is that it converts small negative
// values to small positive values which require a small number of
// bytes. This would not have been true for 2's complements
// representation, for example. The sign bit is always stored as the
// 7th bit of the last byte.
//
// value bits value + sign max bytes
// --------------------------------------------------
// int8_t 7 8 2
// uint8_t 8 9 2
// int16_t 15 16 3
// uint16_t 16 17 3
// int32_t 31 32 5
// uint32_t 32 33 5
// int64_t 63 64 10
// uint64_t 64 65 10
//
template<class T>
char* TransactLogEncoder::encode_int(char* ptr, T value)
{
static_assert(std::numeric_limits<T>::is_integer, "Integer required");
bool negative = util::is_negative(value);
if (negative) {
// The following conversion is guaranteed by C++11 to never
// overflow (contrast this with "-value" which indeed could
// overflow). See C99+TC3 section 6.2.6.2 paragraph 2.
REALM_DIAG_PUSH();
REALM_DIAG_IGNORE_UNSIGNED_MINUS();
value = -(value + 1);
REALM_DIAG_POP();
}
// At this point 'value' is always a positive number. Also, small
// negative numbers have been converted to small positive numbers.
REALM_ASSERT(!util::is_negative(value));
// One sign bit plus number of value bits
const int num_bits = 1 + std::numeric_limits<T>::digits;
// Only the first 7 bits are available per byte. Had it not been
// for the fact that maximum guaranteed bit width of a char is 8,
// this value could have been increased to 15 (one less than the
// number of value bits in 'unsigned').
const int bits_per_byte = 7;
const int max_bytes = (num_bits + (bits_per_byte-1)) / bits_per_byte;
static_assert(max_bytes <= max_enc_bytes_per_int, "Bad max_enc_bytes_per_int");
// An explicit constant maximum number of iterations is specified
// in the hope that it will help the optimizer (to do loop
// unrolling, for example).
typedef unsigned char uchar;
for (int i=0; i<max_bytes; ++i) {
if (value >> (bits_per_byte-1) == 0)
break;
*reinterpret_cast<uchar*>(ptr) =
uchar((1U<<bits_per_byte) | unsigned(value & ((1U<<bits_per_byte)-1)));
++ptr;
value >>= bits_per_byte;
}
*reinterpret_cast<uchar*>(ptr) =
uchar(negative ? (1U<<(bits_per_byte-1)) | unsigned(value) : value);
return ++ptr;
}
inline char* TransactLogEncoder::encode_bool(char* ptr, bool value)
{
// A `char` is the smallest element that the encoder/decoder can process. So we encode the bool
// in a char. If we called encode_int<bool> it would end up as a char too, but we would get
// Various warnings about arithmetic on non-arithmetic type.
return encode_int<char>(ptr, value);
}
inline char* TransactLogEncoder::encode_float(char* ptr, float value)
{
static_assert(std::numeric_limits<float>::is_iec559 &&
sizeof (float) * std::numeric_limits<unsigned char>::digits == 32,
"Unsupported 'float' representation");
const char* val_ptr = reinterpret_cast<char*>(&value);
return std::copy(val_ptr, val_ptr + sizeof value, ptr);
}
inline char* TransactLogEncoder::encode_double(char* ptr, double value)
{
static_assert(std::numeric_limits<double>::is_iec559 &&
sizeof (double) * std::numeric_limits<unsigned char>::digits == 64,
"Unsupported 'double' representation");
const char* val_ptr = reinterpret_cast<char*>(&value);
return std::copy(val_ptr, val_ptr + sizeof value, ptr);
}
template<class T>
struct TransactLogEncoder::EncodeNumber {
void operator()(T value, char** ptr)
{
auto value_2 = value + 0; // Perform integral promotion
*ptr = encode_int(*ptr, value_2);
}
};
template<>
struct TransactLogEncoder::EncodeNumber<bool> {
void operator()(bool value, char** ptr)
{
*ptr = encode_bool(*ptr, value);
}
};
template<>
struct TransactLogEncoder::EncodeNumber<float> {
void operator()(float value, char** ptr)
{
*ptr = encode_float(*ptr, value);
}
};
template<>
struct TransactLogEncoder::EncodeNumber<double> {
void operator()(double value, char** ptr)
{
*ptr = encode_double(*ptr, value);
}
};
template<class L>
void TransactLogEncoder::append_simple_instr(Instruction instr, const util::Tuple<L>& numbers)
{
size_t num_numbers = util::TypeCount<L>::value;
size_t max_required_bytes = 1 + max_enc_bytes_per_num * num_numbers;
char* ptr = reserve(max_required_bytes); // Throws
*ptr++ = char(instr);
util::for_each<EncodeNumber>(numbers, &ptr);
advance(ptr);
}
template<class L>
void TransactLogEncoder::append_string_instr(Instruction instr, const util::Tuple<L>& numbers,
StringData string)
{
size_t num_numbers = util::TypeCount<L>::value + 1;
size_t max_required_bytes = 1 + max_enc_bytes_per_num * num_numbers + string.size();
char* ptr = reserve(max_required_bytes); // Throws
*ptr++ = char(instr);
util::for_each<EncodeNumber>(append(numbers, string.size()), &ptr);
ptr = std::copy(string.data(), string.data() + string.size(), ptr);
advance(ptr);
}
template<class L>
void TransactLogEncoder::append_mixed_instr(Instruction instr, const util::Tuple<L>& numbers,
const Mixed& value)
{
DataType type = value.get_type();
auto numbers_2 = append(numbers, type);
switch (type) {
case type_Int:
append_simple_instr(instr, append(numbers_2, value.get_int())); // Throws
return;
case type_Bool:
append_simple_instr(instr, append(numbers_2, value.get_bool())); // Throws
return;
case type_Float:
append_simple_instr(instr, append(numbers_2, value.get_float())); // Throws
return;
case type_Double:
append_simple_instr(instr, append(numbers_2, value.get_double())); // Throws
return;
case type_OldDateTime: {
auto value_2 = value.get_olddatetime().get_olddatetime();
append_simple_instr(instr, append(numbers_2, value_2)); // Throws
return;
}
case type_String: {
append_string_instr(instr, numbers_2, value.get_string()); // Throws
return;
}
case type_Binary: {
BinaryData value_2 = value.get_binary();
StringData value_3(value_2.data(), value_2.size());
append_string_instr(instr, numbers_2, value_3); // Throws
return;
}
case type_Timestamp: {
Timestamp ts= value.get_timestamp();
int64_t seconds = ts.get_seconds();
int32_t nano_seconds = ts.get_nanoseconds();
auto numbers_3 = append(numbers_2, seconds);
append_simple_instr(instr, append(numbers_3, nano_seconds)); // Throws
return;
}
case type_Table:
append_simple_instr(instr, numbers_2); // Throws
return;
case type_Mixed:
// Mixed in mixed is not possible
REALM_ASSERT_RELEASE(false);
case type_Link:
case type_LinkList:
// FIXME: Need to handle new link types here.
REALM_ASSERT_RELEASE(false);
}
REALM_ASSERT_RELEASE(false);
}
template<class L, class I>
bool TransactLogEncoder::append_variable_size_instr(Instruction instr,
const util::Tuple<L>& numbers,
I var_begin, I var_end)
{
// Space is reserved in chunks to avoid excessive over allocation.
#ifdef REALM_DEBUG
const int max_numbers_per_chunk = 2; // Increase the chance of chunking in debug mode
#else
const int max_numbers_per_chunk = 8;
#endif
size_t num_numbers = util::TypeCount<L>::value + max_numbers_per_chunk;
size_t max_required_bytes = 1 + max_enc_bytes_per_num * num_numbers;
char* ptr = reserve(max_required_bytes); // Throws
*ptr++ = char(instr);
util::for_each<EncodeNumber>(numbers, &ptr);
I i = var_begin;
while (var_end - i > max_numbers_per_chunk) {
for (int j = 0; j < max_numbers_per_chunk; ++j)
ptr = encode_int(ptr, *i++);
advance(ptr);
size_t max_required_bytes_2 = max_enc_bytes_per_num * max_numbers_per_chunk;
ptr = reserve(max_required_bytes_2); // Throws
}
while (i != var_end)
ptr = encode_int(ptr, *i++);
advance(ptr);
return true;
}
inline void TransactLogConvenientEncoder::unselect_all() noexcept
{
m_selected_table = nullptr;
m_selected_spec = nullptr;
// no race with on_link_list_destroyed since both are setting to nullptr
m_selected_link_list = nullptr;
}
inline void TransactLogConvenientEncoder::select_table(const Table* table)
{
if (table != m_selected_table)
do_select_table(table); // Throws
m_selected_spec = nullptr;
// no race with on_link_list_destroyed since both are setting to nullptr
m_selected_link_list = nullptr;
}
inline void TransactLogConvenientEncoder::select_desc(const Descriptor& desc)
{
typedef _impl::DescriptorFriend df;
if (&df::get_spec(desc) != m_selected_spec)
do_select_desc(desc); // Throws
// no race with on_link_list_destroyed since both are setting to nullptr
m_selected_link_list = nullptr;
}
inline void TransactLogConvenientEncoder::select_link_list(const LinkView& list)
{
// A race between this and a call to on_link_list_destroyed() must
// end up with m_selected_link_list pointing to the list argument given
// here. We assume that the list given to on_link_list_destroyed() can
// *never* be the same as the list argument given here. We resolve the
// race by a) always updating m_selected_link_list in do_select_link_list()
// and b) only atomically and conditionally updating it in
// on_link_list_destroyed().
if (&list != m_selected_link_list) {
do_select_link_list(list); // Throws
}
m_selected_spec = nullptr;
}
inline bool TransactLogEncoder::insert_group_level_table(size_t table_ndx, size_t prior_num_tables,
StringData name)
{
append_string_instr(instr_InsertGroupLevelTable, util::tuple(table_ndx, prior_num_tables),
name); // Throws
return true;
}
inline void TransactLogConvenientEncoder::insert_group_level_table(size_t table_ndx,
size_t prior_num_tables,
StringData name)
{
unselect_all();
m_encoder.insert_group_level_table(table_ndx, prior_num_tables, name); // Throws
}
inline bool TransactLogEncoder::erase_group_level_table(size_t table_ndx, size_t prior_num_tables)
{
append_simple_instr(instr_EraseGroupLevelTable, util::tuple(table_ndx, prior_num_tables)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::erase_group_level_table(size_t table_ndx, size_t prior_num_tables)
{
unselect_all();
m_encoder.erase_group_level_table(table_ndx, prior_num_tables); // Throws
}
inline bool TransactLogEncoder::rename_group_level_table(size_t table_ndx, StringData new_name)
{
append_string_instr(instr_RenameGroupLevelTable, util::tuple(table_ndx), new_name); // Throws
return true;
}
inline void TransactLogConvenientEncoder::rename_group_level_table(size_t table_ndx,
StringData new_name)
{
unselect_all();
m_encoder.rename_group_level_table(table_ndx, new_name); // Throws
}
inline bool TransactLogEncoder::move_group_level_table(size_t from_table_ndx, size_t to_table_ndx)
{
REALM_ASSERT(from_table_ndx != to_table_ndx);
append_simple_instr(instr_MoveGroupLevelTable, util::tuple(from_table_ndx, to_table_ndx));
return true;
}
inline void TransactLogConvenientEncoder::move_group_level_table(size_t from_table_ndx, size_t to_table_ndx)
{
unselect_all();
m_encoder.move_group_level_table(from_table_ndx, to_table_ndx);
}
inline bool TransactLogEncoder::insert_column(size_t col_ndx, DataType type, StringData name,
bool nullable)
{
Instruction instr = (nullable ? instr_InsertNullableColumn : instr_InsertColumn);
append_string_instr(instr, util::tuple(col_ndx, type), name); // Throws
return true;
}
inline bool TransactLogEncoder::insert_link_column(size_t col_ndx, DataType type, StringData name,
size_t link_target_table_ndx,
size_t backlink_col_ndx)
{
REALM_ASSERT(_impl::TableFriend::is_link_type(ColumnType(type)));
append_string_instr(instr_InsertLinkColumn, util::tuple(col_ndx, type, link_target_table_ndx,
backlink_col_ndx), name); // Throws
return true;
}
inline void TransactLogConvenientEncoder::insert_column(const Descriptor& desc, size_t col_ndx,
DataType type,
StringData name,
LinkTargetInfo& link,
bool nullable)
{
select_desc(desc); // Throws
if (link.is_valid()) {
typedef _impl::TableFriend tf;
typedef _impl::DescriptorFriend df;
size_t target_table_ndx = link.m_target_table->get_index_in_group();
const Table& origin_table = df::get_root_table(desc);
REALM_ASSERT(origin_table.is_group_level());
const Spec& target_spec = tf::get_spec(*(link.m_target_table));
size_t origin_table_ndx = origin_table.get_index_in_group();
size_t backlink_col_ndx = target_spec.find_backlink_column(origin_table_ndx, col_ndx);
REALM_ASSERT_3(backlink_col_ndx, ==, link.m_backlink_col_ndx);
m_encoder.insert_link_column(col_ndx, type, name, target_table_ndx, backlink_col_ndx); // Throws
}
else {
m_encoder.insert_column(col_ndx, type, name, nullable); // Throws
}
}
inline bool TransactLogEncoder::erase_column(size_t col_ndx)
{
append_simple_instr(instr_EraseColumn, util::tuple(col_ndx)); // Throws
return true;
}
inline bool TransactLogEncoder::erase_link_column(size_t col_ndx, size_t link_target_table_ndx,
size_t backlink_col_ndx)
{
append_simple_instr(instr_EraseLinkColumn, util::tuple(col_ndx, link_target_table_ndx,
backlink_col_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::erase_column(const Descriptor& desc, size_t col_ndx)
{
select_desc(desc); // Throws
DataType type = desc.get_column_type(col_ndx);
typedef _impl::TableFriend tf;
if (!tf::is_link_type(ColumnType(type))) {
m_encoder.erase_column(col_ndx); // Throws
}
else { // it's a link column:
REALM_ASSERT(desc.is_root());
typedef _impl::DescriptorFriend df;
const Table& origin_table = df::get_root_table(desc);
REALM_ASSERT(origin_table.is_group_level());
const Table& target_table = *tf::get_link_target_table_accessor(origin_table, col_ndx);
size_t target_table_ndx = target_table.get_index_in_group();
const Spec& target_spec = tf::get_spec(target_table);
size_t origin_table_ndx = origin_table.get_index_in_group();
size_t backlink_col_ndx = target_spec.find_backlink_column(origin_table_ndx, col_ndx);
m_encoder.erase_link_column(col_ndx, target_table_ndx, backlink_col_ndx); // Throws
}
}
inline bool TransactLogEncoder::rename_column(size_t col_ndx, StringData new_name)
{
append_string_instr(instr_RenameColumn, util::tuple(col_ndx), new_name); // Throws
return true;
}
inline void TransactLogConvenientEncoder::rename_column(const Descriptor& desc, size_t col_ndx,
StringData name)
{
select_desc(desc); // Throws
m_encoder.rename_column(col_ndx, name); // Throws
}
inline bool TransactLogEncoder::move_column(size_t from, size_t to)
{
append_simple_instr(instr_MoveColumn, util::tuple(from, to)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::move_column(const Descriptor& desc, size_t from, size_t to)
{
select_desc(desc); // Throws
m_encoder.move_column(from, to);
}
inline bool TransactLogEncoder::set_int(size_t col_ndx, size_t ndx, int_fast64_t value)
{
append_simple_instr(instr_SetInt, util::tuple(col_ndx, ndx, value)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_int(const Table* t, size_t col_ndx,
size_t ndx, int_fast64_t value)
{
select_table(t); // Throws
m_encoder.set_int(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_int_unique(size_t col_ndx, size_t ndx, size_t prior_num_rows, int_fast64_t value)
{
append_simple_instr(instr_SetIntUnique, util::tuple(col_ndx, ndx, prior_num_rows, value));
return true;
}
inline void TransactLogConvenientEncoder::set_int_unique(const Table* t, size_t col_ndx,
size_t ndx, int_fast64_t value)
{
select_table(t); // Throws
m_encoder.set_int_unique(col_ndx, ndx, t->size(), value); // Throws
}
inline bool TransactLogEncoder::set_bool(size_t col_ndx, size_t ndx, bool value)
{
append_simple_instr(instr_SetBool, util::tuple(col_ndx, ndx, value)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_bool(const Table* t, size_t col_ndx,
size_t ndx, bool value)
{
select_table(t); // Throws
m_encoder.set_bool(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_float(size_t col_ndx, size_t ndx, float value)
{
append_simple_instr(instr_SetFloat, util::tuple(col_ndx, ndx, value)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_float(const Table* t, size_t col_ndx,
size_t ndx, float value)
{
select_table(t); // Throws
m_encoder.set_float(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_double(size_t col_ndx, size_t ndx, double value)
{
append_simple_instr(instr_SetDouble, util::tuple(col_ndx, ndx, value)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_double(const Table* t, size_t col_ndx,
size_t ndx, double value)
{
select_table(t); // Throws
m_encoder.set_double(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_string(size_t col_ndx, size_t ndx, StringData value)
{
if (value.is_null()) {
set_null(col_ndx, ndx); // Throws
}
else {
append_string_instr(instr_SetString, util::tuple(col_ndx, ndx), value); // Throws
}
return true;
}
inline void TransactLogConvenientEncoder::set_string(const Table* t, size_t col_ndx,
size_t ndx, StringData value)
{
select_table(t); // Throws
m_encoder.set_string(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_string_unique(size_t col_ndx, size_t ndx, size_t prior_num_rows, StringData value)
{
if (value.is_null()) {
// FIXME: This loses SetUnique information.
set_null(col_ndx, ndx); // Throws
}
else {
append_string_instr(instr_SetStringUnique, util::tuple(col_ndx, ndx, prior_num_rows), value); // Throws
}
return true;
}
inline void TransactLogConvenientEncoder::set_string_unique(const Table* t, size_t col_ndx,
size_t ndx, StringData value)
{
select_table(t); // Throws
m_encoder.set_string_unique(col_ndx, ndx, t->size(), value); // Throws
}
inline bool TransactLogEncoder::set_binary(size_t col_ndx, size_t row_ndx, BinaryData value)
{
if (value.is_null()) {
set_null(col_ndx, row_ndx); // Throws
}
else {
StringData value_2(value.data(), value.size());
append_string_instr(instr_SetBinary, util::tuple(col_ndx, row_ndx), value_2); // Throws
}
return true;
}
inline void TransactLogConvenientEncoder::set_binary(const Table* t, size_t col_ndx,
size_t ndx, BinaryData value)
{
select_table(t); // Throws
m_encoder.set_binary(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_olddatetime(size_t col_ndx, size_t ndx, OldDateTime value)
{
append_simple_instr(instr_SetOldDateTime, util::tuple(col_ndx, ndx,
value.get_olddatetime())); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_olddatetime(const Table* t, size_t col_ndx,
size_t ndx, OldDateTime value)
{
select_table(t); // Throws
m_encoder.set_olddatetime(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_timestamp(size_t col_ndx, size_t ndx, Timestamp value)
{
append_simple_instr(instr_SetTimestamp, util::tuple(col_ndx, ndx,
value.get_seconds(), value.get_nanoseconds())); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_timestamp(const Table* t, size_t col_ndx, size_t ndx, Timestamp value)
{
select_table(t); // Throws
m_encoder.set_timestamp(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_table(size_t col_ndx, size_t ndx)
{
append_simple_instr(instr_SetTable, util::tuple(col_ndx, ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_table(const Table* t, size_t col_ndx,
size_t ndx)
{
select_table(t); // Throws
m_encoder.set_table(col_ndx, ndx); // Throws
}
inline bool TransactLogEncoder::set_mixed(size_t col_ndx, size_t ndx, const Mixed& value)
{
append_mixed_instr(instr_SetMixed, util::tuple(col_ndx, ndx), value); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_mixed(const Table* t, size_t col_ndx,
size_t ndx, const Mixed& value)
{
select_table(t); // Throws
m_encoder.set_mixed(col_ndx, ndx, value); // Throws
}
inline bool TransactLogEncoder::set_link(size_t col_ndx, size_t ndx,
size_t value, size_t target_group_level_ndx)
{
// Map `realm::npos` to zero, and `n` to `n+1`, where `n` is a target row
// index.
size_t value_2 = size_t(1) + value;
append_simple_instr(instr_SetLink, util::tuple(col_ndx, ndx, value_2,
target_group_level_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_link(const Table* t, size_t col_ndx,
size_t ndx, size_t value)
{
select_table(t); // Throws
size_t target_group_level_ndx = t->get_descriptor()->get_column_link_target(col_ndx);
m_encoder.set_link(col_ndx, ndx, value, target_group_level_ndx); // Throws
}
inline bool TransactLogEncoder::set_null(size_t col_ndx, size_t ndx)
{
append_simple_instr(instr_SetNull, util::tuple(col_ndx, ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_null(const Table* t, size_t col_ndx,
size_t row_ndx)
{
select_table(t); // Throws
m_encoder.set_null(col_ndx, row_ndx); // Throws
}
inline bool TransactLogEncoder::nullify_link(size_t col_ndx, size_t ndx,
size_t target_group_level_ndx)
{
append_simple_instr(instr_NullifyLink, util::tuple(col_ndx, ndx,
target_group_level_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::nullify_link(const Table* t, size_t col_ndx, size_t ndx)
{
select_table(t); // Throws
size_t target_group_level_ndx = t->get_descriptor()->get_column_link_target(col_ndx);
m_encoder.nullify_link(col_ndx, ndx, target_group_level_ndx); // Throws
}
inline bool TransactLogEncoder::insert_substring(size_t col_ndx, size_t row_ndx, size_t pos,
StringData value)
{
append_string_instr(instr_InsertSubstring, util::tuple(col_ndx, row_ndx, pos),
value); // Throws
return true;
}
inline void TransactLogConvenientEncoder::insert_substring(const Table* t, size_t col_ndx,
size_t row_ndx, size_t pos,
StringData value)
{
if (value.size() > 0) {
select_table(t); // Throws
m_encoder.insert_substring(col_ndx, row_ndx, pos, value); // Throws
}
}
inline bool TransactLogEncoder::erase_substring(size_t col_ndx, size_t row_ndx, size_t pos,
size_t size)
{
append_simple_instr(instr_EraseFromString, util::tuple(col_ndx, row_ndx, pos, size)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::erase_substring(const Table* t, size_t col_ndx,
size_t row_ndx, size_t pos,
size_t size)
{
if (size > 0) {
select_table(t); // Throws
m_encoder.erase_substring(col_ndx, row_ndx, pos, size); // Throws
}
}
inline bool TransactLogEncoder::insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert,
size_t prior_num_rows, bool unordered)
{
append_simple_instr(instr_InsertEmptyRows, util::tuple(row_ndx, num_rows_to_insert,
prior_num_rows, unordered)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::insert_empty_rows(const Table* t, size_t row_ndx,
size_t num_rows_to_insert,
size_t prior_num_rows)
{
select_table(t); // Throws
bool unordered = false;
m_encoder.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows,
unordered); // Throws
}
inline bool TransactLogEncoder::erase_rows(size_t row_ndx, size_t num_rows_to_erase,
size_t prior_num_rows, bool unordered)
{
append_simple_instr(instr_EraseRows, util::tuple(row_ndx, num_rows_to_erase, prior_num_rows,
unordered)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::erase_rows(const Table* t, size_t row_ndx,
size_t num_rows_to_erase,
size_t prior_num_rows,
bool is_move_last_over)
{
select_table(t); // Throws
bool unordered = is_move_last_over;
m_encoder.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, unordered); // Throws
}
inline bool TransactLogEncoder::swap_rows(size_t row_ndx_1, size_t row_ndx_2)
{
append_simple_instr(instr_SwapRows, util::tuple(row_ndx_1, row_ndx_2)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::swap_rows(const Table* t, size_t row_ndx_1, size_t row_ndx_2)
{
REALM_ASSERT(row_ndx_1 < row_ndx_2);
select_table(t); // Throws
m_encoder.swap_rows(row_ndx_1, row_ndx_2);
}
inline bool TransactLogEncoder::change_link_targets(size_t row_ndx, size_t new_row_ndx)
{
append_simple_instr(instr_ChangeLinkTargets, util::tuple(row_ndx, new_row_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::change_link_targets(const Table* t, size_t row_ndx,
size_t new_row_ndx)
{
select_table(t); // Throws
m_encoder.change_link_targets(row_ndx, new_row_ndx);
}
inline bool TransactLogEncoder::add_search_index(size_t col_ndx)
{
append_simple_instr(instr_AddSearchIndex, util::tuple(col_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::add_search_index(const Table* t, size_t col_ndx)
{
select_table(t); // Throws
m_encoder.add_search_index(col_ndx); // Throws
}
inline bool TransactLogEncoder::remove_search_index(size_t col_ndx)
{
append_simple_instr(instr_RemoveSearchIndex, util::tuple(col_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::remove_search_index(const Table* t, size_t col_ndx)
{
select_table(t); // Throws
m_encoder.remove_search_index(col_ndx); // Throws
}
inline bool TransactLogEncoder::set_link_type(size_t col_ndx, LinkType link_type)
{
append_simple_instr(instr_SetLinkType, util::tuple(col_ndx, int(link_type))); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_link_type(const Table* t, size_t col_ndx, LinkType link_type)
{
select_table(t); // Throws
m_encoder.set_link_type(col_ndx, link_type); // Throws
}
inline bool TransactLogEncoder::clear_table()
{
append_simple_instr(instr_ClearTable, util::tuple()); // Throws
return true;
}
inline void TransactLogConvenientEncoder::clear_table(const Table* t)
{
select_table(t); // Throws
m_encoder.clear_table(); // Throws
}
inline bool TransactLogEncoder::optimize_table()
{
append_simple_instr(instr_OptimizeTable, util::tuple()); // Throws
return true;
}
inline void TransactLogConvenientEncoder::optimize_table(const Table* t)
{
select_table(t); // Throws
m_encoder.optimize_table(); // Throws
}
inline bool TransactLogEncoder::link_list_set(size_t link_ndx, size_t value)
{
append_simple_instr(instr_LinkListSet, util::tuple(link_ndx, value)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::link_list_set(const LinkView& list, size_t link_ndx,
size_t value)
{
select_link_list(list); // Throws
m_encoder.link_list_set(link_ndx, value); // Throws
}
inline bool TransactLogEncoder::link_list_nullify(size_t link_ndx)
{
append_simple_instr(instr_LinkListNullify, util::tuple(link_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::link_list_nullify(const LinkView& list, size_t link_ndx)
{
select_link_list(list); // Throws
m_encoder.link_list_nullify(link_ndx); // Throws
}
inline bool TransactLogEncoder::link_list_set_all(const IntegerColumn& values)
{
struct iter {
iter(const IntegerColumn& iter_values, size_t ndx): m_values(&iter_values), m_ndx(ndx) {}
const IntegerColumn* m_values;
size_t m_ndx;
bool operator==(const iter& i) const { return m_ndx == i.m_ndx; }
bool operator!=(const iter& i) const { return m_ndx != i.m_ndx; }
size_t operator-(const iter& i) const { return m_ndx - i.m_ndx; }
int_fast64_t operator*() const { return m_values->get(m_ndx); }
iter& operator++() { ++m_ndx; return *this; }
iter operator++(int) { iter i = *this; ++m_ndx; return i; }
};
size_t num_values = values.size();
append_variable_size_instr(instr_LinkListSetAll, util::tuple(num_values),
iter(values, 0), iter(values, num_values)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::set_link_list(const LinkView& list, const IntegerColumn& values)
{
select_link_list(list); // Throws
m_encoder.link_list_set_all(values); // Throws
}
inline bool TransactLogEncoder::link_list_insert(size_t link_ndx, size_t value)
{
append_simple_instr(instr_LinkListInsert, util::tuple(link_ndx, value)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::link_list_insert(const LinkView& list, size_t link_ndx,
size_t value)
{
select_link_list(list); // Throws
m_encoder.link_list_insert(link_ndx, value); // Throws
}
inline bool TransactLogEncoder::link_list_move(size_t from_link_ndx, size_t to_link_ndx)
{
REALM_ASSERT(from_link_ndx != to_link_ndx);
append_simple_instr(instr_LinkListMove, util::tuple(from_link_ndx, to_link_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::link_list_move(const LinkView& list, size_t from_link_ndx,
size_t to_link_ndx)
{
select_link_list(list); // Throws
m_encoder.link_list_move(from_link_ndx, to_link_ndx); // Throws
}
inline bool TransactLogEncoder::link_list_swap(size_t link1_ndx, size_t link2_ndx)
{
append_simple_instr(instr_LinkListSwap, util::tuple(link1_ndx, link2_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::link_list_swap(const LinkView& list, size_t link1_ndx,
size_t link2_ndx)
{
select_link_list(list); // Throws
m_encoder.link_list_swap(link1_ndx, link2_ndx); // Throws
}
inline bool TransactLogEncoder::link_list_erase(size_t link_ndx)
{
append_simple_instr(instr_LinkListErase, util::tuple(link_ndx)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::link_list_erase(const LinkView& list, size_t link_ndx)
{
select_link_list(list); // Throws
m_encoder.link_list_erase(link_ndx); // Throws
}
inline bool TransactLogEncoder::link_list_clear(size_t old_list_size)
{
append_simple_instr(instr_LinkListClear, util::tuple(old_list_size)); // Throws
return true;
}
inline void TransactLogConvenientEncoder::on_table_destroyed(const Table* t) noexcept
{
if (m_selected_table == t)
m_selected_table = nullptr;
}
inline void TransactLogConvenientEncoder::on_spec_destroyed(const Spec* s) noexcept
{
if (m_selected_spec == s)
m_selected_spec = nullptr;
}
inline void TransactLogConvenientEncoder::on_link_list_destroyed(const LinkView& list) noexcept
{
const LinkView* lw_ptr = &list;
// atomically clear m_selected_link_list iff it already points to 'list':
// (lw_ptr will be modified if the swap fails, but we ignore that)
m_selected_link_list.compare_exchange_strong(lw_ptr, nullptr,
std::memory_order_relaxed,
std::memory_order_relaxed);
}
inline TransactLogParser::TransactLogParser():
m_input_buffer(1024) // Throws
{
}
inline TransactLogParser::~TransactLogParser() noexcept
{
}
template<class InstructionHandler>
void TransactLogParser::parse(NoCopyInputStream& in, InstructionHandler& handler)
{
m_input = ∈
m_input_begin = m_input_end = nullptr;
while (has_next())
parse_one(handler); // Throws
}
template<class InstructionHandler>
void TransactLogParser::parse(InputStream& in, InstructionHandler& handler)
{
NoCopyInputStreamAdaptor in_2(in, m_input_buffer.data(), m_input_buffer.size());
parse(in_2, handler); // Throws
}
inline bool TransactLogParser::has_next() noexcept
{
return m_input_begin != m_input_end || next_input_buffer();
}
template<class InstructionHandler>
void TransactLogParser::parse_one(InstructionHandler& handler)
{
char instr;
if (!read_char(instr))
parser_error();
// std::cerr << "parsing " << util::promote(instr) << " @ " << std::hex << long(m_input_begin) << std::dec << "\n";
switch (Instruction(instr)) {
case instr_SetInt: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
// FIXME: Don't depend on the existence of int64_t,
// but don't allow values to use more than 64 bits
// either.
int_fast64_t value = read_int<int64_t>(); // Throws
if (!handler.set_int(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetIntUnique: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
size_t prior_num_rows = read_int<size_t>(); // Throws
// FIXME: Don't depend on the existence of int64_t,
// but don't allow values to use more than 64 bits
// either.
int_fast64_t value = read_int<int64_t>(); // Throws
if (!handler.set_int_unique(col_ndx, row_ndx, prior_num_rows, value)) // Throws
parser_error();
return;
}
case instr_SetBool: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
bool value = read_bool(); // Throws
if (!handler.set_bool(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetFloat: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
float value = read_float(); // Throws
if (!handler.set_float(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetDouble: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
double value = read_double(); // Throws
if (!handler.set_double(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetString: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
StringData value = read_string(m_string_buffer); // Throws
if (!handler.set_string(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetStringUnique: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
size_t prior_num_rows = read_int<size_t>(); // Throws
StringData value = read_string(m_string_buffer); // Throws
if (!handler.set_string_unique(col_ndx, row_ndx, prior_num_rows, value)) // Throws
parser_error();
return;
}
case instr_SetBinary: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
BinaryData value = read_binary(m_string_buffer); // Throws
if (!handler.set_binary(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetOldDateTime: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
int_fast64_t value = read_int<int_fast64_t>(); // Throws
if (!handler.set_olddatetime(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetTimestamp: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
int64_t seconds = read_int<int64_t>(); // Throws
int32_t nanoseconds = read_int<int32_t>(); // Throws
Timestamp value = Timestamp(seconds, nanoseconds);
if (!handler.set_timestamp(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetTable: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
if (!handler.set_table(col_ndx, row_ndx)) // Throws
parser_error();
return;
}
case instr_SetMixed: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
Mixed value;
read_mixed(&value); // Throws
if (!handler.set_mixed(col_ndx, row_ndx, value)) // Throws
parser_error();
return;
}
case instr_SetLink: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
size_t value = read_int<size_t>(); // Throws
// Map zero to realm::npos, and `n+1` to `n`, where `n` is a target row index.
size_t target_row_ndx = size_t(value - 1);
size_t target_group_level_ndx = read_int<size_t>(); // Throws
if (!handler.set_link(col_ndx, row_ndx, target_row_ndx, target_group_level_ndx)) // Throws
parser_error();
return;
}
case instr_SetNull: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
if (!handler.set_null(col_ndx, row_ndx)) // Throws
parser_error();
return;
}
case instr_NullifyLink: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
size_t target_group_level_ndx = read_int<size_t>(); // Throws
if (!handler.nullify_link(col_ndx, row_ndx, target_group_level_ndx)) // Throws
parser_error();
return;
}
case instr_InsertSubstring: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
size_t pos = read_int<size_t>(); // Throws
StringData value = read_string(m_string_buffer); // Throws
if (!handler.insert_substring(col_ndx, row_ndx, pos, value)) // Throws
parser_error();
return;
}
case instr_EraseFromString: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
size_t pos = read_int<size_t>(); // Throws
size_t size = read_int<size_t>(); // Throws
if (!handler.erase_substring(col_ndx, row_ndx, pos, size)) // Throws
parser_error();
return;
}
case instr_InsertEmptyRows: {
size_t row_ndx = read_int<size_t>(); // Throws
size_t num_rows_to_insert = read_int<size_t>(); // Throws
size_t prior_num_rows = read_int<size_t>(); // Throws
bool unordered = read_bool(); // Throws
if (!handler.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows,
unordered)) // Throws
parser_error();
return;
}
case instr_EraseRows: {
size_t row_ndx = read_int<size_t>(); // Throws
size_t num_rows_to_erase = read_int<size_t>(); // Throws
size_t prior_num_rows = read_int<size_t>(); // Throws
bool unordered = read_bool(); // Throws
if (!handler.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows,
unordered)) // Throws
parser_error();
return;
}
case instr_SwapRows: {
size_t row_ndx_1 = read_int<size_t>(); // Throws
size_t row_ndx_2 = read_int<size_t>(); // Throws
if (!handler.swap_rows(row_ndx_1, row_ndx_2)) // Throws
parser_error();
return;
}
case instr_ChangeLinkTargets: {
size_t row_ndx = read_int<size_t>(); // Throws
size_t new_row_ndx = read_int<size_t>(); // Throws
if (!handler.change_link_targets(row_ndx, new_row_ndx)) // Throws
parser_error();
return;
}
case instr_SelectTable: {
int levels = read_int<int>(); // Throws
if (levels < 0 || levels > m_max_levels)
parser_error();
m_path.reserve(0, 2*levels); // Throws
size_t* path = m_path.data();
size_t group_level_ndx = read_int<size_t>(); // Throws
for (int i = 0; i != levels; ++i) {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
path[2*i + 0] = col_ndx;
path[2*i + 1] = row_ndx;
}
if (!handler.select_table(group_level_ndx, levels, path)) // Throws
parser_error();
return;
}
case instr_ClearTable: {
if (!handler.clear_table()) // Throws
parser_error();
return;
}
case instr_LinkListSet: {
size_t link_ndx = read_int<size_t>(); // Throws
size_t value = read_int<size_t>(); // Throws
if (!handler.link_list_set(link_ndx, value)) // Throws
parser_error();
return;
}
case instr_LinkListSetAll: {
// todo, log that it's a SetAll we're doing
size_t size = read_int<size_t>(); // Throws
for (size_t i = 0; i < size; i++) {
size_t link = read_int<size_t>(); // Throws
if (!handler.link_list_set(i, link)) // Throws
parser_error();
}
return;
}
case instr_LinkListInsert: {
size_t link_ndx = read_int<size_t>(); // Throws
size_t value = read_int<size_t>(); // Throws
if (!handler.link_list_insert(link_ndx, value)) // Throws
parser_error();
return;
}
case instr_LinkListMove: {
size_t from_link_ndx = read_int<size_t>(); // Throws
size_t to_link_ndx = read_int<size_t>(); // Throws
if (!handler.link_list_move(from_link_ndx, to_link_ndx)) // Throws
parser_error();
return;
}
case instr_LinkListSwap: {
size_t link1_ndx = read_int<size_t>(); // Throws
size_t link2_ndx = read_int<size_t>(); // Throws
if (!handler.link_list_swap(link1_ndx, link2_ndx)) // Throws
parser_error();
return;
}
case instr_LinkListErase: {
size_t link_ndx = read_int<size_t>(); // Throws
if (!handler.link_list_erase(link_ndx)) // Throws
parser_error();
return;
}
case instr_LinkListNullify: {
size_t link_ndx = read_int<size_t>(); // Throws
if (!handler.link_list_nullify(link_ndx)) // Throws
parser_error();
return;
}
case instr_LinkListClear: {
size_t old_list_size = read_int<size_t>(); // Throws
if (!handler.link_list_clear(old_list_size)) // Throws
parser_error();
return;
}
case instr_SelectLinkList: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t row_ndx = read_int<size_t>(); // Throws
size_t target_group_level_ndx = read_int<size_t>(); // Throws
if (!handler.select_link_list(col_ndx, row_ndx, target_group_level_ndx)) // Throws
parser_error();
return;
}
case instr_AddSearchIndex: {
size_t col_ndx = read_int<size_t>(); // Throws
if (!handler.add_search_index(col_ndx)) // Throws
parser_error();
return;
}
case instr_RemoveSearchIndex: {
size_t col_ndx = read_int<size_t>(); // Throws
if (!handler.remove_search_index(col_ndx)) // Throws
parser_error();
return;
}
case instr_SetLinkType: {
size_t col_ndx = read_int<size_t>(); // Throws
int link_type = read_int<int>(); // Throws
if (!is_valid_link_type(link_type))
parser_error();
if (!handler.set_link_type(col_ndx, LinkType(link_type))) // Throws
parser_error();
return;
}
case instr_InsertColumn:
case instr_InsertNullableColumn: {
size_t col_ndx = read_int<size_t>(); // Throws
int type = read_int<int>(); // Throws
if (!is_valid_data_type(type))
parser_error();
if (REALM_UNLIKELY(type == type_Link || type == type_LinkList))
parser_error();
StringData name = read_string(m_string_buffer); // Throws
bool nullable = (Instruction(instr) == instr_InsertNullableColumn);
if (REALM_UNLIKELY(nullable && (type == type_Table || type == type_Mixed))) {
// Nullability not supported for Table and Mixed columns.
parser_error();
}
if (!handler.insert_column(col_ndx, DataType(type), name, nullable)) // Throws
parser_error();
return;
}
case instr_InsertLinkColumn: {
size_t col_ndx = read_int<size_t>(); // Throws
int type = read_int<int>(); // Throws
if (!is_valid_data_type(type))
parser_error();
if (REALM_UNLIKELY(type != type_Link && type != type_LinkList))
parser_error();
size_t link_target_table_ndx = read_int<size_t>(); // Throws
size_t backlink_col_ndx = read_int<size_t>(); // Throws
StringData name = read_string(m_string_buffer); // Throws
if (!handler.insert_link_column(col_ndx, DataType(type), name,
link_target_table_ndx, backlink_col_ndx)) // Throws
parser_error();
return;
}
case instr_EraseColumn: {
size_t col_ndx = read_int<size_t>(); // Throws
if (!handler.erase_column(col_ndx)) // Throws
parser_error();
return;
}
case instr_EraseLinkColumn: {
size_t col_ndx = read_int<size_t>(); // Throws
size_t link_target_table_ndx = read_int<size_t>(); // Throws
size_t backlink_col_ndx = read_int<size_t>(); // Throws
if (!handler.erase_link_column(col_ndx, link_target_table_ndx,
backlink_col_ndx)) // Throws
parser_error();
return;
}
case instr_RenameColumn: {
size_t col_ndx = read_int<size_t>(); // Throws
StringData name = read_string(m_string_buffer); // Throws
if (!handler.rename_column(col_ndx, name)) // Throws
parser_error();
return;
}
case instr_MoveColumn: {
size_t col_ndx_1 = read_int<size_t>(); // Throws
size_t col_ndx_2 = read_int<size_t>(); // Throws
if (!handler.move_column(col_ndx_1, col_ndx_2)) // Throws
parser_error();
return;
}
case instr_SelectDescriptor: {
int levels = read_int<int>(); // Throws
if (levels < 0 || levels > m_max_levels)
parser_error();
m_path.reserve(0, levels); // Throws
size_t* path = m_path.data();
for (int i = 0; i != levels; ++i) {
size_t col_ndx = read_int<size_t>(); // Throws
path[i] = col_ndx;
}
if (!handler.select_descriptor(levels, path)) // Throws
parser_error();
return;
}
case instr_InsertGroupLevelTable: {
size_t table_ndx = read_int<size_t>(); // Throws
size_t num_tables = read_int<size_t>(); // Throws
StringData name = read_string(m_string_buffer); // Throws
if (!handler.insert_group_level_table(table_ndx, num_tables, name)) // Throws
parser_error();
return;
}
case instr_EraseGroupLevelTable: {
size_t table_ndx = read_int<size_t>(); // Throws
size_t prior_num_tables = read_int<size_t>(); // Throws
if (!handler.erase_group_level_table(table_ndx, prior_num_tables)) // Throws
parser_error();
return;
}
case instr_RenameGroupLevelTable: {
size_t table_ndx = read_int<size_t>(); // Throws
StringData new_name = read_string(m_string_buffer); // Throws
if (!handler.rename_group_level_table(table_ndx, new_name)) // Throws
parser_error();
return;
}
case instr_MoveGroupLevelTable: {
size_t from_table_ndx = read_int<size_t>(); // Throws
size_t to_table_ndx = read_int<size_t>(); // Throws
if (!handler.move_group_level_table(from_table_ndx, to_table_ndx)) // Throws
parser_error();
return;
}
case instr_OptimizeTable: {
if (!handler.optimize_table()) // Throws
parser_error();
return;
}
}
throw BadTransactLog();
}
template<class T>
T TransactLogParser::read_int()
{
T value = 0;
int part = 0;
const int max_bytes = (std::numeric_limits<T>::digits+1+6)/7;
for (int i = 0; i != max_bytes; ++i) {
char c;
if (!read_char(c))
goto bad_transact_log;
part = static_cast<unsigned char>(c);
if (0xFF < part)
goto bad_transact_log; // Only the first 8 bits may be used in each byte
if ((part & 0x80) == 0) {
T p = part & 0x3F;
if (util::int_shift_left_with_overflow_detect(p, i*7))
goto bad_transact_log;
value |= p;
break;
}
if (i == max_bytes-1)
goto bad_transact_log; // Too many bytes
value |= T(part & 0x7F) << (i*7);
}
if (part & 0x40) {
// The real value is negative. Because 'value' is positive at
// this point, the following negation is guaranteed by C++11
// to never overflow. See C99+TC3 section 6.2.6.2 paragraph 2.
REALM_DIAG_PUSH();
REALM_DIAG_IGNORE_UNSIGNED_MINUS();
value = -value;
REALM_DIAG_POP();
if (util::int_subtract_with_overflow_detect(value, 1))
goto bad_transact_log;
}
return value;
bad_transact_log:
throw BadTransactLog();
}
inline void TransactLogParser::read_bytes(char* data, size_t size)
{
for (;;) {
const size_t avail = m_input_end - m_input_begin;
if (size <= avail)
break;
const char* to = m_input_begin + avail;
std::copy(m_input_begin, to, data);
if (!next_input_buffer())
throw BadTransactLog();
data += avail;
size -= avail;
}
const char* to = m_input_begin + size;
std::copy(m_input_begin, to, data);
m_input_begin = to;
}
inline BinaryData TransactLogParser::read_buffer(util::StringBuffer& buf, size_t size)
{
const size_t avail = m_input_end - m_input_begin;
if (avail >= size) {
m_input_begin += size;
return BinaryData(m_input_begin - size, size);
}
buf.clear();
buf.resize(size); // Throws
read_bytes(buf.data(), size);
return BinaryData(buf.data(), size);
}
inline bool TransactLogParser::read_bool()
{
return read_int<char>();
}
inline float TransactLogParser::read_float()
{
static_assert(std::numeric_limits<float>::is_iec559 &&
sizeof (float) * std::numeric_limits<unsigned char>::digits == 32,
"Unsupported 'float' representation");
float value;
read_bytes(reinterpret_cast<char*>(&value), sizeof value); // Throws
return value;
}
inline double TransactLogParser::read_double()
{
static_assert(std::numeric_limits<double>::is_iec559 &&
sizeof (double) * std::numeric_limits<unsigned char>::digits == 64,
"Unsupported 'double' representation");
double value;
read_bytes(reinterpret_cast<char*>(&value), sizeof value); // Throws
return value;
}
inline StringData TransactLogParser::read_string(util::StringBuffer& buf)
{
size_t size = read_int<size_t>(); // Throws
if (size > Table::max_string_size)
parser_error();
BinaryData buffer = read_buffer(buf, size);
return StringData{buffer.data(), size};
}
inline Timestamp TransactLogParser::read_timestamp()
{
REALM_ASSERT(false);
return Timestamp(null{});
}
inline BinaryData TransactLogParser::read_binary(util::StringBuffer& buf)
{
size_t size = read_int<size_t>(); // Throws
if (size > Table::max_binary_size)
parser_error();
return read_buffer(buf, size);
}
inline void TransactLogParser::read_mixed(Mixed* mixed)
{
DataType type = DataType(read_int<int>()); // Throws
switch (type) {
case type_Int: {
// FIXME: Don't depend on the existence of
// int64_t, but don't allow values to use more
// than 64 bits either.
int_fast64_t value = read_int<int64_t>(); // Throws
mixed->set_int(value);
return;
}
case type_Bool: {
bool value = read_bool(); // Throws
mixed->set_bool(value);
return;
}
case type_Float: {
float value = read_float(); // Throws
mixed->set_float(value);
return;
}
case type_Double: {
double value = read_double(); // Throws
mixed->set_double(value);
return;
}
case type_OldDateTime: {
int_fast64_t value = read_int<int_fast64_t>(); // Throws
mixed->set_olddatetime(value);
return;
}
case type_Timestamp: {
Timestamp value = read_timestamp(); // Throws
mixed->set_timestamp(value);
return;
}
case type_String: {
StringData value = read_string(m_string_buffer); // Throws
mixed->set_string(value);
return;
}
case type_Binary: {
BinaryData value = read_binary(m_string_buffer); // Throws
mixed->set_binary(value);
return;
}
case type_Table: {
*mixed = Mixed::subtable_tag();
return;
}
case type_Mixed:
break;
case type_Link:
case type_LinkList:
// FIXME: Need to handle new link types here
break;
}
throw BadTransactLog();
}
inline bool TransactLogParser::next_input_buffer()
{
size_t sz = m_input->next_block(m_input_begin, m_input_end);
if (sz == 0)
return false;
else
return true;
}
inline bool TransactLogParser::read_char(char& c)
{
if (m_input_begin == m_input_end && !next_input_buffer())
return false;
c = *m_input_begin++;
return true;
}
inline bool TransactLogParser::is_valid_data_type(int type)
{
switch (DataType(type)) {
case type_Int:
case type_Bool:
case type_Float:
case type_Double:
case type_String:
case type_Binary:
case type_OldDateTime:
case type_Timestamp:
case type_Table:
case type_Mixed:
case type_Link:
case type_LinkList:
return true;
}
return false;
}
inline bool TransactLogParser::is_valid_link_type(int type)
{
switch (LinkType(type)) {
case link_Strong:
case link_Weak:
return true;
}
return false;
}
class TransactReverser {
public:
bool select_table(size_t group_level_ndx, size_t levels, const size_t* path)
{
sync_table();
m_encoder.select_table(group_level_ndx, levels, path);
m_pending_ts_instr = get_inst();
return true;
}
bool select_descriptor(size_t levels, const size_t* path)
{
sync_descriptor();
m_encoder.select_descriptor(levels, path);
m_pending_ds_instr = get_inst();
return true;
}
bool insert_group_level_table(size_t table_ndx, size_t num_tables, StringData)
{
sync_table();
m_encoder.erase_group_level_table(table_ndx, num_tables + 1);
append_instruction();
return true;
}
bool erase_group_level_table(size_t table_ndx, size_t num_tables)
{
sync_table();
m_encoder.insert_group_level_table(table_ndx, num_tables - 1, "");
append_instruction();
return true;
}
bool rename_group_level_table(size_t, StringData)
{
sync_table();
return true;
}
bool move_group_level_table(size_t from_table_ndx, size_t to_table_ndx)
{
sync_table();
m_encoder.move_group_level_table(to_table_ndx, from_table_ndx);
append_instruction();
return true;
}
bool optimize_table()
{
return true; // No-op
}
bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows,
bool unordered)
{
size_t num_rows_to_erase = num_rows_to_insert;
size_t prior_num_rows_2 = prior_num_rows + num_rows_to_insert;
m_encoder.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows_2, unordered); // Throws
append_instruction();
return true;
}
bool erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool unordered)
{
size_t num_rows_to_insert = num_rows_to_erase;
// Number of rows in table after removal, but before inverse insertion
size_t prior_num_rows_2 = prior_num_rows - num_rows_to_erase;
m_encoder.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows_2,
unordered); // Throws
append_instruction();
return true;
}
bool swap_rows(size_t row_ndx_1, size_t row_ndx_2)
{
m_encoder.swap_rows(row_ndx_1, row_ndx_2);
append_instruction();
return true;
}
bool change_link_targets(size_t row_ndx, size_t new_row_ndx)
{
static_cast<void>(row_ndx);
static_cast<void>(new_row_ndx);
// There is no instruction we can generate here to change back.
return true;
}
bool set_int(size_t col_ndx, size_t row_ndx, int_fast64_t value)
{
m_encoder.set_int(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_int_unique(size_t col_ndx, size_t row_ndx, size_t prior_num_rows, int_fast64_t value)
{
m_encoder.set_int_unique(col_ndx, row_ndx, prior_num_rows, value);
append_instruction();
return true;
}
bool set_bool(size_t col_ndx, size_t row_ndx, bool value)
{
m_encoder.set_bool(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_float(size_t col_ndx, size_t row_ndx, float value)
{
m_encoder.set_float(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_double(size_t col_ndx, size_t row_ndx, double value)
{
m_encoder.set_double(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_string(size_t col_ndx, size_t row_ndx, StringData value)
{
m_encoder.set_string(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_string_unique(size_t col_ndx, size_t row_ndx, size_t prior_num_rows, StringData value)
{
m_encoder.set_string_unique(col_ndx, row_ndx, prior_num_rows, value);
append_instruction();
return true;
}
bool set_binary(size_t col_ndx, size_t row_ndx, BinaryData value)
{
m_encoder.set_binary(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_olddatetime(size_t col_ndx, size_t row_ndx, OldDateTime value)
{
m_encoder.set_olddatetime(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_timestamp(size_t col_ndx, size_t row_ndx, Timestamp value)
{
m_encoder.set_timestamp(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_table(size_t col_ndx, size_t row_ndx)
{
m_encoder.set_table(col_ndx, row_ndx);
append_instruction();
return true;
}
bool set_mixed(size_t col_ndx, size_t row_ndx, const Mixed& value)
{
m_encoder.set_mixed(col_ndx, row_ndx, value);
append_instruction();
return true;
}
bool set_null(size_t col_ndx, size_t row_ndx)
{
m_encoder.set_null(col_ndx, row_ndx);
append_instruction();
return true;
}
bool set_link(size_t col_ndx, size_t row_ndx, size_t value, size_t target_group_level_ndx)
{
m_encoder.set_link(col_ndx, row_ndx, value, target_group_level_ndx);
append_instruction();
return true;
}
bool insert_substring(size_t, size_t, size_t, StringData)
{
return true; // No-op
}
bool erase_substring(size_t, size_t, size_t, size_t)
{
return true; // No-op
}
bool clear_table()
{
m_encoder.insert_empty_rows(0, 0, 0, true); // FIXME: Explain what is going on here (Finn).
append_instruction();
return true;
}
bool add_search_index(size_t)
{
return true; // No-op
}
bool remove_search_index(size_t)
{
return true; // No-op
}
bool set_link_type(size_t, LinkType)
{
return true; // No-op
}
bool insert_link_column(size_t col_idx, DataType, StringData,
size_t target_table_idx, size_t backlink_col_ndx)
{
m_encoder.erase_link_column(col_idx, target_table_idx, backlink_col_ndx);
append_instruction();
return true;
}
bool erase_link_column(size_t col_idx, size_t target_table_idx,
size_t backlink_col_idx)
{
DataType type = type_Link; // The real type of the column doesn't matter here,
// but the encoder asserts that it's actually a link type.
m_encoder.insert_link_column(col_idx, type, "", target_table_idx, backlink_col_idx);
append_instruction();
return true;
}
bool insert_column(size_t col_idx, DataType, StringData, bool)
{
m_encoder.erase_column(col_idx);
append_instruction();
return true;
}
bool erase_column(size_t col_idx)
{
m_encoder.insert_column(col_idx, DataType(), "");
append_instruction();
return true;
}
bool rename_column(size_t, StringData)
{
return true; // No-op
}
bool move_column(size_t col_ndx_1, size_t col_ndx_2)
{
m_encoder.move_column(col_ndx_2, col_ndx_1);
append_instruction();
return true;
}
bool select_link_list(size_t col_ndx, size_t row_ndx, size_t link_target_group_level_ndx)
{
sync_linkview();
m_encoder.select_link_list(col_ndx, row_ndx, link_target_group_level_ndx);
m_pending_lv_instr = get_inst();
return true;
}
bool link_list_set(size_t row, size_t value)
{
m_encoder.link_list_set(row, value);
append_instruction();
return true;
}
bool link_list_insert(size_t link_ndx, size_t)
{
m_encoder.link_list_erase(link_ndx);
append_instruction();
return true;
}
bool link_list_move(size_t from_link_ndx, size_t to_link_ndx)
{
m_encoder.link_list_move(from_link_ndx, to_link_ndx);
append_instruction();
return true;
}
bool link_list_swap(size_t link1_ndx, size_t link2_ndx)
{
m_encoder.link_list_swap(link1_ndx, link2_ndx);
append_instruction();
return true;
}
bool link_list_erase(size_t link_ndx)
{
m_encoder.link_list_insert(link_ndx, 0);
append_instruction();
return true;
}
bool link_list_clear(size_t old_list_size)
{
// Append in reverse order because the reversed log is itself applied
// in reverse, and this way it generates all back-insertions rather than
// all front-insertions
for (size_t i = old_list_size; i > 0; --i) {
m_encoder.link_list_insert(i - 1, 0);
append_instruction();
}
return true;
}
bool nullify_link(size_t col_ndx, size_t row_ndx, size_t target_group_level_ndx)
{
size_t value = 0;
// FIXME: Is zero this right value to pass here, or should
// TransactReverser::nullify_link() also have taken a
// `target_group_level_ndx` argument.
m_encoder.set_link(col_ndx, row_ndx, value, target_group_level_ndx);
append_instruction();
return true;
}
bool link_list_nullify(size_t link_ndx)
{
m_encoder.link_list_insert(link_ndx, 0);
append_instruction();
return true;
}
private:
_impl::TransactLogBufferStream m_buffer;
_impl::TransactLogEncoder m_encoder{m_buffer};
struct Instr { size_t begin; size_t end; };
std::vector<Instr> m_instructions;
size_t current_instr_start = 0;
Instr m_pending_ts_instr{0, 0};
Instr m_pending_ds_instr{0, 0};
Instr m_pending_lv_instr{0, 0};
Instr get_inst()
{
Instr instr;
instr.begin = current_instr_start;
current_instr_start = transact_log_size();
instr.end = current_instr_start;
return instr;
}
size_t transact_log_size() const
{
REALM_ASSERT_3(m_encoder.write_position(), >=, m_buffer.transact_log_data());
return m_encoder.write_position() - m_buffer.transact_log_data();
}
void append_instruction()
{
m_instructions.push_back(get_inst());
}
void append_instruction(Instr instr)
{
m_instructions.push_back(instr);
}
void sync_select(Instr& pending_instr)
{
if (pending_instr.begin != pending_instr.end) {
append_instruction(pending_instr);
pending_instr = {0, 0};
}
}
void sync_linkview()
{
sync_select(m_pending_lv_instr);
}
void sync_descriptor()
{
sync_linkview();
sync_select(m_pending_ds_instr);
}
void sync_table()
{
sync_descriptor();
sync_select(m_pending_ts_instr);
}
friend class ReversedNoCopyInputStream;
};
class ReversedNoCopyInputStream: public NoCopyInputStream {
public:
ReversedNoCopyInputStream(TransactReverser& reverser):
m_instr_order(reverser.m_instructions)
{
// push any pending select_table or select_descriptor into the buffer
reverser.sync_table();
m_buffer = reverser.m_buffer.transact_log_data();
m_current = m_instr_order.size();
}
size_t next_block(const char*& begin, const char*& end) override
{
if (m_current != 0) {
m_current--;
begin = m_buffer + m_instr_order[m_current].begin;
end = m_buffer + m_instr_order[m_current].end;
return end-begin;
}
return 0;
}
private:
const char* m_buffer;
std::vector<TransactReverser::Instr>& m_instr_order;
size_t m_current;
};
} // namespace _impl
} // namespace realm
#endif // REALM_IMPL_TRANSACT_LOG_HPP
| 37.144752 | 140 | 0.641857 | aidudu |
c819c251ef201a40de037e129c7af31f4a818911 | 14,077 | cpp | C++ | flinter/linkage/linkage_worker.cpp | yiyuanzhong/flinter | c52655ea5f8e48244fdb59bdf34b915faee57a6e | [
"Apache-2.0"
] | 29 | 2016-01-29T09:31:09.000Z | 2021-07-11T12:00:31.000Z | flinter/linkage/linkage_worker.cpp | yiyuanzhong/flinter | c52655ea5f8e48244fdb59bdf34b915faee57a6e | [
"Apache-2.0"
] | 2 | 2015-03-30T09:59:51.000Z | 2017-03-13T09:35:18.000Z | flinter/linkage/linkage_worker.cpp | yiyuanzhong/flinter | c52655ea5f8e48244fdb59bdf34b915faee57a6e | [
"Apache-2.0"
] | 17 | 2015-03-28T09:24:53.000Z | 2021-08-07T10:09:10.000Z | /* Copyright 2014 yiyuanzhong@gmail.com (Yiyuan Zhong)
*
* 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 "flinter/linkage/linkage_worker.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <list>
#include <stdexcept>
#include "flinter/linkage/interface.h"
#include "flinter/linkage/linkage_base.h"
#include "flinter/linkage/linkage_peer.h"
#include "flinter/thread/mutex.h"
#include "flinter/thread/mutex_locker.h"
#include "flinter/logger.h"
#include "flinter/safeio.h"
#include "flinter/utility.h"
#include "config.h"
#if HAVE_EV_H
#include <ev.h>
namespace flinter {
struct LinkageWorker::client_t {
LinkageBase *linkage;
struct ev_io ev_io_r;
struct ev_io ev_io_w;
bool auto_release;
bool running_r;
bool running_w;
int fd;
}; // struct LinkageWorker::client_t
struct LinkageWorker::timer_t {
struct ev_timer ev_timer;
Runnable *runnable;
bool auto_release;
}; // struct LinkageWorker::timer_t
class LinkageWorker::HealthTimer : public Runnable {
public:
HealthTimer(LinkageWorker *worker) : _worker(worker) {}
virtual ~HealthTimer() {}
protected:
virtual bool Run()
{
return _worker->OnHealthCheck(get_monotonic_timestamp());
}
private:
LinkageWorker *_worker;
}; // class LinkageWorker::HealthTimer
LinkageWorker::LinkageWorker() : _loop(ev_loop_new(0))
, _quit(false)
, _running_thread_id(0)
, _async(new struct ev_async)
, _mutex(new Mutex)
{
if (!_loop) {
throw std::runtime_error("LinkageWorker: failed to initialize loop.");
}
ev_async_init(_async, command_cb);
ev_async_start(_loop, _async);
ev_set_userdata(_loop, this);
}
LinkageWorker::~LinkageWorker()
{
ev_async_stop(_loop, _async);
ev_loop_destroy(_loop);
delete _mutex;
delete _async;
}
void LinkageWorker::command_cb(struct ev_loop *loop, struct ev_async * /*w*/, int /*revents*/)
{
LinkageWorker *worker = reinterpret_cast<LinkageWorker *>(ev_userdata(loop));
worker->OnCommand();
}
void LinkageWorker::readable_cb(struct ev_loop *loop, struct ev_io *w, int /*revents*/)
{
LinkageWorker *worker = reinterpret_cast<LinkageWorker *>(ev_userdata(loop));
unsigned char *p = reinterpret_cast<unsigned char *>(w);
p -= offsetof(struct client_t, ev_io_r);
struct client_t *client = reinterpret_cast<struct client_t *>(p);
worker->OnReadable(client);
}
void LinkageWorker::writable_cb(struct ev_loop *loop, struct ev_io *w, int /*revents*/)
{
LinkageWorker *worker = reinterpret_cast<LinkageWorker *>(ev_userdata(loop));
unsigned char *p = reinterpret_cast<unsigned char *>(w);
p -= offsetof(struct client_t, ev_io_w);
struct client_t *client = reinterpret_cast<struct client_t *>(p);
worker->OnWritable(client);
}
void LinkageWorker::timer_cb(struct ev_loop *loop, struct ev_timer *w, int /*revents*/)
{
LinkageWorker *worker = reinterpret_cast<LinkageWorker *>(ev_userdata(loop));
unsigned char *p = reinterpret_cast<unsigned char *>(w);
p -= offsetof(struct timer_t, ev_timer);
struct timer_t *timer = reinterpret_cast<struct timer_t *>(p);
worker->OnTimer(timer);
}
void LinkageWorker::OnTimer(struct timer_t *timer)
{
if (!timer->runnable->Run()) {
DoRelease(timer, true);
}
}
bool LinkageWorker::RegisterTimer(int64_t interval,
Runnable *runnable,
bool auto_release)
{
return RegisterTimer(interval, interval, runnable, auto_release);
}
bool LinkageWorker::RegisterTimer(int64_t after,
int64_t repeat,
Runnable *runnable,
bool auto_release)
{
if (after < 0 || repeat <= 0 || !runnable) {
return false;
}
double r = static_cast<double>(repeat) / 1000000000;
double a = static_cast<double>(after) / 1000000000;
struct timer_t *timer = new struct timer_t;
struct ev_timer *t = &timer->ev_timer;
timer->auto_release = auto_release;
timer->runnable = runnable;
_timers.insert(timer);
ev_timer_init(t, timer_cb, a, r);
ev_timer_start(_loop, &timer->ev_timer);
return true;
}
bool LinkageWorker::Run()
{
if (!OnInitialize()) {
CLOG.Error("Linkage: failed to initialize.");
throw std::runtime_error("Linkage: failed to initialize.");
}
HealthTimer *health = new HealthTimer(this);
if (!RegisterTimer(1000000000LL, health, true)) {
delete health;
CLOG.Error("Linkage: failed to register timers.");
throw std::runtime_error("Linkage: failed to register timers.");
}
_running_thread_id = get_current_thread_id();
LOG(VERBOSE) << "Linkage: enter event loop [" << _running_thread_id << "]";
while (!_quit) {
if (!ev_run(_loop, 0)) {
CLOG.Error("Linkage: ev_run() returned false.");
throw std::runtime_error("Linkage: ev_run() returned false.");
}
}
LOG(VERBOSE) << "Linkage: leave event loop [" << _running_thread_id << "]";
_running_thread_id = 0;
OnShutdown();
for (events_t::iterator p = _events.begin(); p != _events.end(); ++p) {
DoRelease(p->second, false);
}
for (timers_t::iterator p = _timers.begin(); p != _timers.end(); ++p) {
DoRelease(*p, false);
}
_events.clear();
_timers.clear();
return true;
}
bool LinkageWorker::Shutdown()
{
return SendCommand(NULL);
}
bool LinkageWorker::SendCommand(Runnable *command)
{
MutexLocker locker(_mutex);
_commands.push_back(command);
locker.Unlock();
ev_async_send(_loop, _async);
return true;
}
void LinkageWorker::OnCommand()
{
std::list<Runnable *> q;
MutexLocker locker(_mutex);
q.swap(_commands);
locker.Unlock();
for (std::list<Runnable *>::iterator p = q.begin(); p != q.end(); ++p) {
Runnable *command = *p;
if (!command) {
ev_break(_loop, EVBREAK_ALL);
_quit = true;
return;
}
if (!command->Run()) {
break;
}
}
for (std::list<Runnable *>::iterator p = q.begin(); p != q.end(); ++p) {
delete *p;
}
}
bool LinkageWorker::Attach(LinkageBase *linkage,
int fd,
bool read_now,
bool write_now,
bool auto_release)
{
if (!linkage) {
return false;
} else if (_events.find(linkage) != _events.end()) {
return true;
}
struct client_t *client = new struct client_t;
struct ev_io *ev_io_r = &client->ev_io_r;
struct ev_io *ev_io_w = &client->ev_io_w;
ev_io_init(ev_io_r, readable_cb, fd, EV_READ);
ev_io_init(ev_io_w, writable_cb, fd, EV_WRITE);
client->auto_release = auto_release;
client->linkage = linkage;
client->running_r = read_now;
client->running_w = write_now;
client->fd = fd;
CLOG.Verbose("Linkage: attached %p:%p:%d:%d", this, linkage, fd, auto_release);
_events.insert(std::make_pair(linkage, client));
if (read_now) {
ev_io_start(_loop, &client->ev_io_r);
}
if (write_now) {
ev_io_start(_loop, &client->ev_io_w);
}
return true;
}
bool LinkageWorker::Detach(LinkageBase *linkage)
{
if (!linkage) {
return false;
}
events_t::iterator p = _events.find(linkage);
if (p == _events.end()) {
return true;
}
struct client_t *client = p->second;
if (client->running_r) {
ev_io_stop(_loop, &client->ev_io_r);
}
if (client->running_w) {
ev_io_stop(_loop, &client->ev_io_w);
}
CLOG.Verbose("Linkage: detached %p:%p", this, linkage);
_events.erase(p);
delete client;
return true;
}
void LinkageWorker::OnReadable(struct client_t *client)
{
CLOG.Verbose("LinkageWorker: OnReadable(%p)", client->linkage);
int ret = client->linkage->OnReadable(this);
if (ret < 0) {
OnError(client, true, errno);
} else if (ret == 0) {
OnDisconnected(client);
}
}
void LinkageWorker::OnWritable(struct client_t *client)
{
CLOG.Verbose("LinkageWorker: OnWritable(%p)", client->linkage);
int ret = client->linkage->OnWritable(this);
if (ret < 0) {
OnError(client, false, errno);
} else if (ret == 0) {
OnDisconnected(client);
}
}
void LinkageWorker::OnError(struct client_t *client, bool reading_or_writing, int errnum)
{
client->linkage->OnError(reading_or_writing, errnum);
DoRelease(client, true);
}
void LinkageWorker::OnDisconnected(struct client_t *client)
{
DoRelease(client, true);
}
void LinkageWorker::DoRelease(struct client_t *client, bool erase_container)
{
if (client->running_r) {
ev_io_stop(_loop, &client->ev_io_r);
}
if (client->running_w) {
ev_io_stop(_loop, &client->ev_io_w);
}
if (erase_container) {
events_t::iterator p = _events.find(client->linkage);
assert(p != _events.end());
assert(client == p->second);
_events.erase(p);
}
// TODO(yiyuanzhong): dangerous, crash might occur.
//
// It was originally designed that users should never use the pointer
// `linkage` after OnDisconnected() is called, which is correct if
// users are within the same thread as LinkageWorker. However if
// they call SendCommand() from another thread, which adds a job
// referring to the pointer, the job might be executed after the
// pointer has been released.
//
// There're two possible fixes, one is to eliminate all jobs referring
// the pointer before releasing it, simple as it sounds, there's no
// way I can tell jobs from each other, unless I design a different
// command queue.
//
// Another way is to defer releasing linkages, which requires additional
// variables and memory can be held longer than usual. Also if you're
// debugging you might find it inconvenient.
//
// I'm still thinking about it.
client->linkage->OnDisconnected();
if (client->auto_release) {
CLOG.Verbose("Linkage: closed linkage [%p], auto released.", client->linkage);
delete client->linkage;
} else {
CLOG.Verbose("Linkage: closed linkage [%p], not released.", client->linkage);
}
delete client;
}
void LinkageWorker::DoRelease(struct timer_t *timer, bool erase_container)
{
ev_timer_stop(_loop, &timer->ev_timer);
if (timer->auto_release) {
CLOG.Verbose("Linkage: stopped timer [%p], auto released.", timer->runnable);
delete timer->runnable;
} else {
CLOG.Verbose("Linkage: stopped timer [%p], not released.", timer->runnable);
}
delete timer;
if (erase_container) {
_timers.erase(timer);
}
}
bool LinkageWorker::SetWanna(LinkageBase *linkage, bool wanna_read, bool wanna_write)
{
events_t::iterator p = _events.find(linkage);
if (p == _events.end()) {
return false;
}
struct client_t *client = p->second;
if (wanna_read != client->running_r) {
client->running_r = wanna_read;
if (wanna_read) {
ev_io_start(_loop, &client->ev_io_r);
} else {
ev_io_stop(_loop, &client->ev_io_r);
}
}
if (wanna_write != client->running_w) {
client->running_w = wanna_write;
if (wanna_write) {
ev_io_start(_loop, &client->ev_io_w);
} else {
ev_io_stop(_loop, &client->ev_io_w);
}
}
return true;
}
bool LinkageWorker::SetWannaRead(LinkageBase *linkage, bool wanna)
{
events_t::iterator p = _events.find(linkage);
if (p == _events.end()) {
return false;
}
struct client_t *client = p->second;
if (wanna == client->running_r) {
return true;
}
if (wanna) {
ev_io_start(_loop, &client->ev_io_r);
} else {
ev_io_stop(_loop, &client->ev_io_r);
}
client->running_r = wanna;
return true;
}
bool LinkageWorker::SetWannaWrite(LinkageBase *linkage, bool wanna)
{
events_t::iterator p = _events.find(linkage);
if (p == _events.end()) {
return false;
}
struct client_t *client = p->second;
if (wanna == client->running_w) {
return true;
}
if (wanna) {
ev_io_start(_loop, &client->ev_io_w);
} else {
ev_io_stop(_loop, &client->ev_io_w);
}
client->running_w = wanna;
return true;
}
bool LinkageWorker::OnInitialize()
{
return true;
}
void LinkageWorker::OnShutdown()
{
// Intended left blank.
}
bool LinkageWorker::OnHealthCheck(int64_t now)
{
std::list<struct client_t *> drops;
for (events_t::iterator p = _events.begin(); p != _events.end(); ++p) {
struct client_t *client = p->second;
LinkageBase *linkage = client->linkage;
if (!linkage->Cleanup(now)) {
drops.push_back(client);
}
}
for (std::list<struct client_t *>::iterator p = drops.begin();
p != drops.end(); ++p) {
struct client_t *client = *p;
CLOG.Verbose("Linkage: disconnect timed out connection: fd = %d",
client->fd);
DoRelease(client, true);
}
return true;
}
} // namespace flinter
#endif // HAVE_EV_H
| 27.281008 | 94 | 0.624281 | yiyuanzhong |
c81b062864945c16921507bd55ccc183064da6ba | 10,057 | cpp | C++ | beelzebub/arc/x86/src/djinn.arc.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 32 | 2015-09-02T22:56:22.000Z | 2021-02-24T17:15:50.000Z | beelzebub/arc/x86/src/djinn.arc.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 30 | 2015-04-26T18:35:07.000Z | 2021-06-06T09:57:02.000Z | beelzebub/arc/x86/src/djinn.arc.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 11 | 2015-09-03T20:47:41.000Z | 2021-06-25T17:00:01.000Z | /*
Copyright (c) 2018 Alexandru-Mihai Maftei. All rights reserved.
Developed by: Alexandru-Mihai Maftei
aka Vercas
http://vercas.com | https://github.com/vercas/Beelzebub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal with 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:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of Alexandru-Mihai Maftei, Vercas, nor the names of
its contributors may be used to endorse or promote products derived from
this Software without specific prior written permission.
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
CONTRIBUTORS 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
WITH THE SOFTWARE.
---
You may also find the text of this license in "LICENSE.md", along with a more
thorough explanation regarding other files.
*/
#include "djinn.arc.hpp"
#include "utils/port.parse.hpp"
#include "system/serial_ports.hpp"
#include "system/io_ports.hpp"
#include <math.h>
using namespace Beelzebub;
using namespace Beelzebub::Utils;
using namespace Beelzebub::Synchronization;
using namespace Beelzebub::System;
ManagedSerialPort * DjinnPort = nullptr;
__hot __unsanitized DJINN_SEND_RES DjinnSendPacketThroughSerialPort(void const * packet, size_t size);
__hot __unsanitized DJINN_POLL_RES DjinnPollPacketFromSerialPort(void * buffer, size_t capacity, size_t * len);
__hot __unsanitized DJINN_SEND_RES DjinnSendPacketThroughSerialPortBase64(void const * packet, size_t size);
__hot __unsanitized DJINN_POLL_RES DjinnPollPacketFromSerialPortBase64(void * buffer, size_t capacity, size_t * len);
__unsanitized Handle Beelzebub::InitializeDebuggerInterface(DjinnInterfaces iface)
{
bool b64 = false;
switch (iface)
{
case DjinnInterfaces::COM1Base64:
b64 = true;
[[fallthrough]];
case DjinnInterfaces::COM1:
DjinnPort = &COM1;
break;
case DjinnInterfaces::COM2Base64:
b64 = true;
[[fallthrough]];
case DjinnInterfaces::COM2:
DjinnPort = &COM2;
break;
case DjinnInterfaces::COM3Base64:
b64 = true;
[[fallthrough]];
case DjinnInterfaces::COM3:
DjinnPort = &COM3;
break;
case DjinnInterfaces::COM4Base64:
b64 = true;
[[fallthrough]];
case DjinnInterfaces::COM4:
DjinnPort = &COM4;
break;
default:
return HandleResult::NotImplemented;
}
DjinnInitData id {};
if (DjinnPort != nullptr)
{
if (b64)
{
id.Sender = &DjinnSendPacketThroughSerialPortBase64;
id.Poller = &DjinnPollPacketFromSerialPortBase64;
id.PacketMaxSize = 1024; // Arbitrary number, it doesn't matter.
}
else
{
id.Sender = &DjinnSendPacketThroughSerialPort;
id.Poller = &DjinnPollPacketFromSerialPort;
id.PacketMaxSize = DjinnPort->QueueSize - 1;
}
}
else
return HandleResult::Failed;
DJINN_INIT_RES res = DjinnInitialize(&id);
if (res != DJINN_INIT_SUCCESS)
return HandleResult::Failed;
return HandleResult::Okay;
}
/*******************
Serial Ports
*******************/
DJINN_SEND_RES DjinnSendPacketThroughSerialPort(void const * packet, size_t size)
{
if (size > 0xFF)
return DJINN_SEND_PACKET_SIZE_OOR;
LockGuard<SmpLock> lg { DjinnPort->WriteLock };
if unlikely(DjinnPort->OutputCount >= DjinnPort->QueueSize && !DjinnPort->CanWrite())
return DJINN_SEND_AWAIT;
Io::Out8(DjinnPort->BasePort, (uint8_t)size);
DjinnPort->OutputCount++;
for (size_t i = 0, j; i < size; i += j)
{
while unlikely(DjinnPort->OutputCount >= DjinnPort->QueueSize && !DjinnPort->CanWrite())
DO_NOTHING();
j = Minimum(DjinnPort->QueueSize - DjinnPort->OutputCount, size - i);
Io::Out8n(DjinnPort->BasePort, (uint8_t const *)packet + i, j);
DjinnPort->OutputCount += j;
}
return DJINN_SEND_SUCCESS;
}
DJINN_POLL_RES DjinnPollPacketFromSerialPort(void * buffer, size_t capacity, size_t * len)
{
if (!DjinnPort->CanRead())
return DJINN_POLL_NOTHING;
uint8_t const sz = Io::In8(DjinnPort->BasePort);
if (sz > capacity)
return DJINN_POLL_PACKET_SIZE_OOR;
*len = sz;
uint8_t i = 0;
do
{
while (!DjinnPort->CanRead()) DO_NOTHING();
((uint8_t *)buffer)[i] = Io::In8(DjinnPort->BasePort);
} while (++i < sz);
return DJINN_POLL_SUCCESS;
}
/**************************************
Serial Ports w/ Base64 Encoding
**************************************/
static uint8_t const Base64Chars[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static __unsanitized void WriteByte(uint8_t const val)
{
while (DjinnPort->OutputCount >= DjinnPort->QueueSize
&& !DjinnPort->CanWrite()) ;
Io::Out8(DjinnPort->BasePort, val);
++DjinnPort->OutputCount;
}
DJINN_SEND_RES DjinnSendPacketThroughSerialPortBase64(void const * packet, size_t size)
{
if unlikely(DjinnPort->OutputCount >= DjinnPort->QueueSize && !DjinnPort->CanWrite())
return DJINN_SEND_AWAIT;
uint8_t const * in = reinterpret_cast<uint8_t const *>(packet);
uint8_t const * const end = in + size;
LockGuard<SmpLock> lg { DjinnPort->WriteLock };
for (/* nothing */; end - in >= 3; in += 3)
{
WriteByte(Base64Chars[in[0] >> 2]);
WriteByte(Base64Chars[((in[0] & 0x03) << 4) | (in[1] >> 4)]);
WriteByte(Base64Chars[((in[1] & 0x0f) << 2) | (in[2] >> 6)]);
WriteByte(Base64Chars[in[2] & 0x3f]);
}
if (end > in)
{
WriteByte(Base64Chars[in[0] >> 2]);
if (end - in == 1)
{
WriteByte(Base64Chars[(in[0] & 0x03) << 4]);
WriteByte('=');
}
else
{
WriteByte(Base64Chars[((in[0] & 0x03) << 4) | (in[1] >> 4)]);
WriteByte(Base64Chars[(in[1] & 0x0f) << 2]);
}
WriteByte('=');
}
WriteByte('\n'); // When using PTY-backed serial ports, this should flush nicely.
return DJINN_SEND_SUCCESS;
}
static uint32_t const Base64Values[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 63, 62, 62, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 63,
0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
DJINN_POLL_RES DjinnPollPacketFromSerialPortBase64(void * buffer, size_t capacity, size_t * len)
{
if (!DjinnPort->CanRead())
return DJINN_POLL_NOTHING;
uint8_t temp[4];
size_t i = 0;
int j;
request_chars:
j = 0;
do
{
while (!DjinnPort->CanRead()) DO_NOTHING();
temp[j] = Io::In8(DjinnPort->BasePort);
} while (temp[j] != '\n' && ++j < 4);
if (j == 0)
{
// K being 0 means a newline was read into the first slot of the buffer.
// Also this packet has no padding.
*len = i;
return DJINN_POLL_SUCCESS;
}
// j has to be 4 here, otherwise the base64 data isn't encoded properly.
if (temp[2] == '=')
{
// This means there's two padding sextets, so just one byte.
if ((*len = i + 1) > capacity)
return DJINN_POLL_PACKET_SIZE_OOR;
uint32_t const n = Base64Values[temp[0]] << 18 | Base64Values[temp[1]] << 12;
reinterpret_cast<uint8_t *>(buffer)[i ] = n >> 16;
}
else if (temp[3] == '=')
{
// This means there's just one padding sextet, so two bytes.
if ((*len = i + 2) > capacity)
return DJINN_POLL_PACKET_SIZE_OOR;
uint32_t const n = Base64Values[temp[0]] << 18 | Base64Values[temp[1]] << 12
| Base64Values[temp[2]] << 6;
reinterpret_cast<uint8_t *>(buffer)[i++] = n >> 16;
reinterpret_cast<uint8_t *>(buffer)[i ] = n >> 8 & 0xFF;
}
else
{
if (i + 3 > capacity)
{
*len = i + 3;
return DJINN_POLL_PACKET_SIZE_OOR;
}
uint32_t const n = Base64Values[temp[0]] << 18 | Base64Values[temp[1]] << 12
| Base64Values[temp[2]] << 6 | Base64Values[temp[3]];
reinterpret_cast<uint8_t *>(buffer)[i++] = n >> 16;
reinterpret_cast<uint8_t *>(buffer)[i++] = n >> 8 & 0xFF;
reinterpret_cast<uint8_t *>(buffer)[i++] = n & 0xFF;
goto request_chars;
}
// Reaching this point means padding sextets have been read and the end of
// the packet follows.
while (!DjinnPort->CanRead()) DO_NOTHING();
Io::In8(DjinnPort->BasePort); // Result is discarded for now.
return DJINN_POLL_SUCCESS;
}
| 30.661585 | 117 | 0.615691 | vercas |
c81d4fac2f9504aba74f0121100f9f7073ce5a75 | 1,114 | cpp | C++ | src/lib/utils/mem_ops.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | 1 | 2018-01-07T03:42:28.000Z | 2018-01-07T03:42:28.000Z | src/lib/utils/mem_ops.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | null | null | null | src/lib/utils/mem_ops.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | null | null | null | /*
* Memory Scrubbing
* (C) 2012,2015,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/mem_ops.h>
#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
#define NOMINMAX 1
#include <windows.h>
#endif
namespace Botan {
void secure_scrub_memory(void* ptr, size_t n)
{
#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
::RtlSecureZeroMemory(ptr, n);
#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)
/*
Call memset through a static volatile pointer, which the compiler
should not elide. This construct should be safe in conforming
compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and
Clang 3.8 both create code that saves the memset address in the
data segment and uncondtionally loads and jumps to that address.
*/
static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset;
(memset_ptr)(ptr, 0, n);
#else
volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);
for(size_t i = 0; i != n; ++i)
p[i] = 0;
#endif
}
}
| 27.85 | 94 | 0.722621 | reneme |
c81d84f952c06ed98cc22444f9d57d2b036f83d6 | 3,406 | hpp | C++ | include/bits/decor/select.hpp | vashman/range_layer | 056b6ee805a92187021b686960bc7d9766ab478b | [
"BSL-1.0"
] | null | null | null | include/bits/decor/select.hpp | vashman/range_layer | 056b6ee805a92187021b686960bc7d9766ab478b | [
"BSL-1.0"
] | null | null | null | include/bits/decor/select.hpp | vashman/range_layer | 056b6ee805a92187021b686960bc7d9766ab478b | [
"BSL-1.0"
] | null | null | null | //
// Copyright Sundeep S. Sangha 2015 - 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef RANGE_LAYER_SELECT_RANGE_HPP
#define RANGE_LAYER_SELECT_RANGE_HPP
#include <tuple>
#include "base_decor.hpp"
namespace range_layer {
namespace bits {
/*===========================================================
range_element_type
===========================================================*/
template <typename T, std::size_t I>
struct range_element_type {
using type = typename std::tuple_element<I, T>::type;
};
/*===========================================================
range_element_type
===========================================================*/
template <std::size_t I>
struct range_element_type <void, I> {
using type = void;
};
/*===========================================================
select
===========================================================*/
template <typename Range, std::size_t I>
class select
: public bits::base_decor<Range, select<Range, I>>
{
using base_t = bits::base_decor<Range, select<Range, I>>;
public:
using read_type
= typename range_element_type
< typename range_trait::read_type<Range>::type
, I
>::type;
using write_type
= typename range_element_type
< typename range_trait::write_type<Range>::type
, I
>::type;
/*===========================================================
ctor
===========================================================*/
select (
Range _range
)
: base_t {_range}
{}
/*===========================================================
copy ctor
===========================================================*/
select (select const &) = default;
/*===========================================================
move ctor
===========================================================*/
select (select &&) = default;
/*===========================================================
move assignment operator
===========================================================*/
select & operator = (select &&) = default;
/*===========================================================
copy assignment operator
===========================================================*/
select & operator = (select const &) = default;
/*===========================================================
dtor
===========================================================*/
~select () = default;
/*===========================================================
operator *
===========================================================*/
auto
operator * (
) -> decltype(std::get<I>(*this->range)) {
using std::get;
return get<I>(*this->range);
}
/*===========================================================
operator =
===========================================================*/
template <typename T>
void
operator = (
T const & _var
){
using std::get;
get<I>(this->range) = _var;
}
using base_t::size;
using base_t::position;
using base_t::save;
using base_t::operator ==;
using base_t::erase;
using base_t::erase_all;
using base_t::shrink;
using base_t::insert;
using base_t::expand;
using base_t::disable;
}; //select--------------------------------------------------
} //bits-----------------------------------------------------
} //range layer----------------------------------------------
#endif
| 26.2 | 61 | 0.389313 | vashman |
c820cee12f73821d255fcc217074988befbeeeb5 | 2,739 | hpp | C++ | ql/models/marketmodels/historicalratesanalysis.hpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 76 | 2017-06-28T21:24:38.000Z | 2021-12-19T18:07:37.000Z | ql/models/marketmodels/historicalratesanalysis.hpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 2 | 2017-07-05T09:20:13.000Z | 2019-10-31T12:06:51.000Z | ql/models/marketmodels/historicalratesanalysis.hpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 34 | 2017-07-02T14:49:21.000Z | 2021-11-26T15:32:04.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2007 Ferdinando Ametrano
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file historicalratesanalysis.hpp
\brief Statistical analysis of historical rates
*/
#ifndef quantlib_historical_rates_analysis_hpp
#define quantlib_historical_rates_analysis_hpp
#include <ql/math/statistics/sequencestatistics.hpp>
#include <ql/time/date.hpp>
namespace QuantLib {
class InterestRateIndex;
void historicalRatesAnalysis(
SequenceStatistics& statistics,
std::vector<Date>& skippedDates,
std::vector<std::string>& skippedDatesErrorMessage,
const Date& startDate,
const Date& endDate,
const Period& step,
const std::vector<std::shared_ptr<InterestRateIndex> >& indexes);
//! %Historical rate analysis class
class HistoricalRatesAnalysis {
public:
HistoricalRatesAnalysis(
const std::shared_ptr<SequenceStatistics>& stats,
const Date& startDate,
const Date& endDate,
const Period& step,
const std::vector<std::shared_ptr<InterestRateIndex> >& indexes);
const std::vector<Date>& skippedDates() const;
const std::vector<std::string>& skippedDatesErrorMessage() const;
const std::shared_ptr<SequenceStatistics>& stats() const;
private:
// calculated data
std::shared_ptr<SequenceStatistics> stats_;
std::vector<Date> skippedDates_;
std::vector<std::string> skippedDatesErrorMessage_;
};
// inline
inline const std::vector<Date>&
HistoricalRatesAnalysis::skippedDates() const {
return skippedDates_;
}
inline const std::vector<std::string>&
HistoricalRatesAnalysis::skippedDatesErrorMessage() const {
return skippedDatesErrorMessage_;
}
inline const std::shared_ptr<SequenceStatistics>&
HistoricalRatesAnalysis::stats() const {
return stats_;
}
}
#endif
| 33.402439 | 81 | 0.682731 | haozhangphd |
c82144220807594eed0894a47269f00319a46bf7 | 486 | cpp | C++ | other/la/blas/level1.cpp | MTang23/AMS562-lecture-notes | 0d49d584e43eff7283aebbf468b14c3f86f75d0d | [
"MIT"
] | 2 | 2020-09-09T01:37:46.000Z | 2021-11-30T19:21:42.000Z | other/la/blas/level1.cpp | MTang23/AMS562-lecture-notes | 0d49d584e43eff7283aebbf468b14c3f86f75d0d | [
"MIT"
] | 2 | 2021-08-30T13:47:12.000Z | 2021-09-10T16:54:18.000Z | other/la/blas/level1.cpp | MTang23/AMS562-lecture-notes | 0d49d584e43eff7283aebbf468b14c3f86f75d0d | [
"MIT"
] | 4 | 2019-12-01T17:33:13.000Z | 2022-02-27T00:53:48.000Z | #include <cblas.h>
#include <vector>
#include <iostream>
int main() {
std::vector<double> x(10), y(10);
for (int i = 0; i < 10; ++i)
x[i] = i + 1;
// copy x to y, then y = [1, 2, ... 10]
cblas_dcopy(10, x.data(), 1, y.data(), 1);
for (int i = 0; i < 10; ++i)
std::cout << y[i] << ' ';
std::cout << '\n';
// axpy y = 2*x+y
cblas_daxpy(10, 2.0, x.data(), 1, y.data(), 1);
// nrm2 ||y||_2 = sqrt(sum(y_i^2))
double nrm2 = cblas_dnrm2(10, y.data(), 1);
}
| 20.25 | 49 | 0.489712 | MTang23 |
c823738c43f76f2428c04c3a96ae2b9c2453939d | 420 | cpp | C++ | tools/level_editor/src/objects/items/ThreeDObject.cpp | filipwasil/fillwave | 65f5eeebf8ca4a8ce2d25293874b051c2a4c0550 | [
"MIT"
] | 27 | 2015-09-26T23:29:48.000Z | 2021-03-06T08:54:46.000Z | tools/level_editor/src/objects/items/ThreeDObject.cpp | filipwasil/fillwave | 65f5eeebf8ca4a8ce2d25293874b051c2a4c0550 | [
"MIT"
] | 83 | 2015-09-28T22:20:16.000Z | 2018-05-16T13:25:28.000Z | tools/level_editor/src/objects/items/ThreeDObject.cpp | filipwasil/fillwave | 65f5eeebf8ca4a8ce2d25293874b051c2a4c0550 | [
"MIT"
] | 8 | 2015-11-03T22:29:29.000Z | 2018-11-17T08:49:07.000Z | #include "ThreeDObject.h"
namespace objects {
ThreeDObject::ThreeDObject(IItem* parent, QString name, QByteArray id, std::unique_ptr<Model> model)
: BaseItem(parent, name, id)
, mModel(std::move(model)) {
init();
}
void ThreeDObject::init() {
BaseItem::init();
//TODO:add to model and scene, node controler should take the model and add him to scene
//TODO: MVC for inspector, emit signal modelUpdated
}
} | 26.25 | 100 | 0.716667 | filipwasil |
c82650f6932e6f20124a3c843bb81126f1773ae3 | 2,589 | cpp | C++ | modules/task_3/vizgalov_a_dijkstra/main.cpp | orcyyy/pp_2020_autumn_engineer-1 | 14cb1248b8b765a02eaa4c73f06807c250545491 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/vizgalov_a_dijkstra/main.cpp | orcyyy/pp_2020_autumn_engineer-1 | 14cb1248b8b765a02eaa4c73f06807c250545491 | [
"BSD-3-Clause"
] | 1 | 2020-12-27T20:31:37.000Z | 2020-12-27T20:31:37.000Z | modules/task_3/vizgalov_a_dijkstra/main.cpp | schelyanskovan/pp_2020_autumn_engineer | 2bacf7ccaf3c638044c41068565a693ac4fae828 | [
"BSD-3-Clause"
] | 1 | 2021-03-29T10:15:47.000Z | 2021-03-29T10:15:47.000Z | // Copyright 2020 Vizgalov Anton
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include "./dijkstra.h"
TEST(Dijkstra, Dijkstra_Generate_Random) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
ASSERT_NO_THROW(generateRandomGraph(100));
}
}
TEST(Dijkstra, Dijkstra_Sequential_100) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
std::vector<int> graph = generateRandomGraph(100);
double t0 = MPI_Wtime();
ASSERT_NO_THROW(dijkstraSequential(graph, 0));
double t1 = MPI_Wtime();
std::cout << "\nSequential time (graph size 100): " << (t1 - t0) << "\n" << std::endl;
}
}
TEST(Dijkstra, Dijkstra_Sequential_1000) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
std::vector<int> graph = generateRandomGraph(1000);
double t0 = MPI_Wtime();
ASSERT_NO_THROW(dijkstraSequential(graph, 0));
double t1 = MPI_Wtime();
std::cout << "\nSequential time (graph size 1000): " << (t1 - t0) << "\n" << std::endl;
}
}
TEST(Dijkstra, Dijkstra_Parallel_100) {
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (size < 2 || size > 100) return;
std::vector<int> graph = generateRandomGraph(100);
double t0 = MPI_Wtime();
ASSERT_NO_THROW(dijkstraParallel(graph, 0));
double t1 = MPI_Wtime();
if (rank == 0) {
std::cout << "\nParallel time (graph size 100): " << (t1 - t0) << "\n" << std::endl;
}
}
TEST(Dijkstra, Dijkstra_Parallel_1000) {
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (size < 2 || size > 1000) return;
std::vector<int> graph = generateRandomGraph(1000);
double t0 = MPI_Wtime();
ASSERT_NO_THROW(dijkstraParallel(graph, 0));
double t1 = MPI_Wtime();
if (rank == 0) {
std::cout << "\nParallel time (graph size 1000): " << (t1 - t0) << "\n" << std::endl;
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 26.151515 | 95 | 0.633449 | orcyyy |
c8266040dd5a025d4a2303aae679d45a5d7b04d9 | 16,687 | cpp | C++ | test/index/test_index.cpp | DecodeGenetics/graphtyper | f9edcf4cf040197f57e208ff6f910e5a2875f692 | [
"MIT"
] | 122 | 2017-06-09T18:05:57.000Z | 2022-03-27T20:22:22.000Z | test/index/test_index.cpp | DecodeGenetics/graphtyper | f9edcf4cf040197f57e208ff6f910e5a2875f692 | [
"MIT"
] | 79 | 2017-06-12T06:35:06.000Z | 2022-03-30T16:01:11.000Z | test/index/test_index.cpp | DecodeGenetics/graphtyper | f9edcf4cf040197f57e208ff6f910e5a2875f692 | [
"MIT"
] | 14 | 2017-06-22T13:02:21.000Z | 2022-03-26T01:45:02.000Z | #include <climits>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string>
#include <graphtyper/graph/constructor.hpp>
#include <graphtyper/graph/graph_serialization.hpp>
#include <graphtyper/index/indexer.hpp>
#include <graphtyper/index/ph_index.hpp>
#include <graphtyper/utilities/type_conversions.hpp>
#include "../help_functions.hpp" // create_test_graph
#include <catch.hpp>
TEST_CASE("Test index chr1")
{
gyper::print_log(gyper::log_severity::debug, "[", __HERE__, "] Test index chr1");
using namespace gyper;
create_test_graph("/test/data/reference/index_test.fa", "/test/data/reference/index_test.vcf.gz", "chr1", true);
std::stringstream my_graph;
my_graph << gyper_SOURCE_DIRECTORY << "/test/data/graphs/index_test_chr1.grf";
REQUIRE(graph.size() > 0);
// All reference kmers are present in the graph
{
std::vector<char> ref = graph.get_all_ref();
REQUIRE(ref == gyper::to_vec("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCTTTGGA"));
}
gyper::PHIndex ph_index = gyper::index_graph(my_graph.str());
REQUIRE(ph_index.check());
// Test one var kmer are present in the graph
{
std::vector<char> ref = graph.get_first_var();
REQUIRE(ref == gyper::to_vec("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTGCCCAGGTTTCCCCAGGTTTCCCCTTTGGA"));
}
// All kmers should be have the correct count
{
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG")).size() == 3);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCTT")).size() == 1);
REQUIRE(ph_index.get(to_uint64("TTCCCCAGGTTTCCCCAGGTTTCCCCTTTGGA")).size() == 1);
REQUIRE(ph_index.get(to_uint64("GGTTTCCCCAGGTTTCCCCAGGTTTGCCCAGG")).size() == 1);
}
// All kmers should have the correct starting index
{
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[0].start_index == 1);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[1].start_index == 11);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[2].start_index == 21);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCTT"))[0].start_index == 31);
REQUIRE(ph_index.get(to_uint64("GGTTTCCCCAGGTTTCCCCAGGTTTGCCCAGG"))[0].start_index == 12);
}
// All kmers should have the correct end index
{
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[0].end_index == 32);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[1].end_index == 42);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[2].end_index == 52);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCTT"))[0].end_index == 62);
REQUIRE(ph_index.get(to_uint64("GGTTTCCCCAGGTTTCCCCAGGTTTGCCCAGG"))[0].end_index == 43);
}
// Correct variant id
{
// AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCTTTGGA
// chr1 37 rs1 C G 0 . .
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[0].variant_id == INVALID_ID);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[1].variant_id == 0);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAG"))[2].variant_id == 0);
REQUIRE(ph_index.get(to_uint64("AGGTTTCCCCAGGTTTCCCCAGGTTTCCCCTT"))[0].variant_id == 0);
REQUIRE(ph_index.get(to_uint64("GGTTTCCCCAGGTTTCCCCAGGTTTGCCCAGG"))[0].variant_id == 1);
}
}
TEST_CASE("Test index chr2")
{
gyper::print_log(gyper::log_severity::debug, "[", __HERE__, "] Test index chr2");
using namespace gyper;
create_test_graph("/test/data/reference/index_test.fa", "/test/data/reference/index_test.vcf.gz", "chr2", true);
std::stringstream my_graph;
my_graph << gyper_SOURCE_DIRECTORY << "/test/data/graphs/index_test_chr2.grf";
REQUIRE(graph.size() > 0);
// The reference is present in the graph
{
std::vector<char> ref = graph.get_all_ref();
REQUIRE(ref == gyper::to_vec("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTGGACCC"));
}
gyper::PHIndex ph_index = gyper::index_graph(graph);
REQUIRE(ph_index.check());
// All kmers should be have the correct count
{
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC")).size() == 4);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTGG")).size() == 1);
REQUIRE(ph_index.get(to_uint64("CACCAGGTTTCCCCAGGTTTCCCCAGGTTTCC")).size() == 2);
REQUIRE(ph_index.get(to_uint64("CCACAGGTTTCCCCAGGTTTCCCCAGGTTTCC")).size() == 2);
REQUIRE(ph_index.get(to_uint64("CAACAGGTTTCCCCAGGTTTCCCCAGGTTTCC")).size() == 2);
}
// All kmers should have the correct starting index
{
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[0].start_index == 1);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[1].start_index == 1);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[2].start_index == 11);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[3].start_index == 21);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTGG"))[0].start_index == 31);
}
// All kmers should have the correct end index
{
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[0].end_index == 32);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[1].end_index == 32);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[2].end_index == 42);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[3].end_index == 52);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTGG"))[0].end_index == 62);
}
// Correct variant id and num
{
using gyper::INVALID_ID;
using gyper::to_uint64;
// CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCCCCAGGTTTGGACCC
// chr2 2 rs2 C A 0 . .
// chr2 3 rs3 C A 0 . .
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[0].variant_id == 0);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[1].variant_id == 2);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[2].variant_id == INVALID_ID);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTCC"))[3].variant_id == INVALID_ID);
REQUIRE(ph_index.get(to_uint64("CCCCAGGTTTCCCCAGGTTTCCCCAGGTTTGG"))[0].variant_id == INVALID_ID);
}
}
TEST_CASE("Test index chr3")
{
gyper::print_log(gyper::log_severity::debug, __HERE__, " Test index chr3");
// AAAACAAAATAAAACAAAATAAAAGAAAACAAAATAAAACAAAATAAAAGAAAACATTATAAAACA
// chr3 31 rs4 A G,GA
using namespace gyper;
create_test_graph("/test/data/reference/index_test.fa", "/test/data/reference/index_test.vcf.gz", "chr3", true);
std::stringstream my_graph;
my_graph << gyper_SOURCE_DIRECTORY << "/test/data/graphs/index_test_chr3.grf";
REQUIRE(graph.size() > 0);
gyper::PHIndex ph_index = gyper::index_graph(my_graph.str());
REQUIRE(ph_index.check());
// All reference kmers are present in the graph
{
std::vector<char> ref = graph.get_all_ref();
REQUIRE(ref == gyper::to_vec("AAAACAAAATAAAACAAAATAAAAGAAAACAAAATAAAACAAAATAAAAGAAAACATTATAAAACA"));
}
// Kmer that starts at zero is has matches positions with the next one (although this is not a real alignmment)
{
// kmer ref
std::vector<gyper::KmerLabel> labels0 = ph_index.get(gyper::to_uint64("AAAACAAAATAAAACAAAATAAAAGAAAACAA"));
REQUIRE(labels0.size() == 1);
REQUIRE(labels0[0].start_index == 1);
REQUIRE(labels0[0].end_index == 32);
// kmer 1
std::vector<gyper::KmerLabel> labels1 = ph_index.get(gyper::to_uint64("AAAACAAAATAAAACAAAATAAAAGAAAACGA"));
REQUIRE(labels1.size() == 2);
REQUIRE(labels1[0].start_index == 1);
REQUIRE(labels1[0].end_index == gyper::SPECIAL_START);
REQUIRE(labels1[0].variant_id == 2);
REQUIRE(labels1[1].start_index == 1);
REQUIRE(labels1[1].end_index == 32);
REQUIRE(labels1[1].variant_id == 1);
// kmer 2
std::vector<gyper::KmerLabel> labels2 = ph_index.get(gyper::to_uint64("AAAATAAAACAAAATAAAAGAAAACATTATAA"));
REQUIRE(labels2.size() == 2);
REQUIRE(labels2[0].start_index == 31);
REQUIRE(labels2[0].end_index == 62);
REQUIRE(labels2[0].variant_id == 0);
REQUIRE(labels2[1].start_index == gyper::SPECIAL_START);
REQUIRE(labels2[1].end_index == 62);
REQUIRE(labels2[1].variant_id == 2);
// kmer 3
std::vector<gyper::KmerLabel> labels3 = ph_index.get(gyper::to_uint64("AAATAAAACAAAATAAAAGAAAACATTATAAA"));
REQUIRE(labels3.size() == 1);
REQUIRE(labels3[0].start_index == 32);
REQUIRE(labels3[0].end_index == 63);
REQUIRE(labels3[0].variant_id == -1);
}
}
TEST_CASE("Test index chr4")
{
gyper::print_log(gyper::log_severity::debug, __HERE__, " Test index chr4");
using namespace gyper;
create_test_graph("/test/data/reference/index_test.fa", "/test/data/reference/index_test.vcf.gz", "chr4", true);
REQUIRE(graph.size() > 0);
// The reference is present in the graph
{
std::vector<char> ref = graph.get_all_ref();
REQUIRE(ref == gyper::to_vec("AAAACAAAATAAAACAAAATAAAAGAAAACAAAATAAAACAAAATAANNNNNNNNNNNNNNNNNNN"));
}
gyper::PHIndex ph_index = gyper::index_graph(graph);
REQUIRE(ph_index.check());
// kmer ref
{
std::vector<gyper::KmerLabel> labels0 = ph_index.get(to_uint64("AAAACAAAATAAAACAAAATAAAAGAAAACAA", 0));
REQUIRE(labels0.size() == 1);
REQUIRE(labels0[0].start_index == 1);
REQUIRE(labels0[0].end_index == 32);
REQUIRE(labels0[0].variant_id == 0);
std::vector<gyper::KmerLabel> labels1 = ph_index.get(to_uint64("ATAACAAAATAAAACAAAATAAAAGAAAACAA", 0));
REQUIRE(labels1.size() == 1);
REQUIRE(labels1[0].start_index == 1);
REQUIRE(labels1[0].end_index == 32);
REQUIRE(labels1[0].variant_id == 1);
}
}
TEST_CASE("Test index chr5")
{
gyper::print_log(gyper::log_severity::debug, __HERE__, " Test index chr5");
using namespace gyper;
// 70A 70C 70G 70T
// chr5 70A70C SVTYPE=DEL,SVSIZE=70
create_test_graph("/test/data/reference/index_test.fa", "/test/data/reference/index_test.vcf.gz", "chr5", true);
std::stringstream my_graph;
my_graph << gyper_SOURCE_DIRECTORY << "/test/data/graphs/index_test_chr5.grf";
REQUIRE(graph.size() > 0);
PHIndex ph_index = gyper::index_graph(my_graph.str());
REQUIRE(ph_index.check());
// All reference kmers are present in the graph
{
std::vector<char> ref = graph.get_all_ref();
REQUIRE(ref == gyper::to_vec("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
"GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"
"TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"));
}
// k-mer that starts at zero is has matches positions with the next one (although this is not a real alignmment)
{
// kmer ref
std::vector<KmerLabel> labels0 = ph_index.get(to_uint64("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 0));
REQUIRE(labels0.size() == 40);
std::vector<KmerLabel> labels1 = ph_index.get(to_uint64("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG", 0));
REQUIRE(labels1.size() == 1);
REQUIRE(labels1[0].start_index == 40);
REQUIRE(labels1[0].end_index == gyper::SPECIAL_START);
std::vector<KmerLabel> labels2 = ph_index.get(to_uint64("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGG", 0));
REQUIRE(labels2.size() == 1);
REQUIRE(labels2[0].start_index == 41);
REQUIRE(labels2[0].end_index == gyper::SPECIAL_START + 1);
std::vector<KmerLabel> labels3 = ph_index.get(to_uint64("AGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels3.size() == 1);
REQUIRE(labels3[0].start_index == 70);
REQUIRE(labels3[0].end_index == gyper::SPECIAL_START + 30);
std::vector<KmerLabel> labels4 = ph_index.get(to_uint64("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels4.size() == 2 * (71 - K)); // 78
// There should be strictly one starting at gyper::SPECIAL_START
{
unsigned found_count = 0;
for (auto const & label : labels4)
found_count += (label.start_index == gyper::SPECIAL_START + 1);
REQUIRE(found_count == 1);
}
std::vector<KmerLabel> labels6 = ph_index.get(to_uint64("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT", 0));
REQUIRE(labels6.size() == 2 * (71 - K)); // 78
}
}
/*
TEST_CASE("Test index chr6")
{
using namespace gyper;
std::stringstream my_graph;
my_graph << gyper_SOURCE_DIRECTORY << "/test/data/graphs/index_test_chr6.grf";
gyper::load_graph(my_graph.str().c_str());
REQUIRE(graph.size() > 0);
gyper::index_graph(my_graph.str());
REQUIRE(gyper::index.check());
// All reference kmers are present in the graph
{
std::vector<char> ref = graph.get_all_ref();
REQUIRE(ref == gyper::to_vec(
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
"GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"
"TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"
));
}
{
// kmer ref
std::vector<gyper::KmerLabel> labels0 = gyper::index.get(gyper::to_uint64("CGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels0.size() == 3);
REQUIRE(labels0[0].start_index >= gyper::SPECIAL_START);
REQUIRE(labels0[0].end_index >= gyper::SPECIAL_START);
REQUIRE(labels0[1].start_index == 139);
REQUIRE(labels0[1].end_index == 170);
REQUIRE(labels0[2].start_index >= gyper::SPECIAL_START);
REQUIRE(labels0[2].end_index >= gyper::SPECIAL_START);
}
}
*/
TEST_CASE("Test index chr9 with anti event")
{
using namespace gyper;
std::stringstream my_graph;
my_graph << gyper_SOURCE_DIRECTORY << "/test/data/graphs/index_test_chr9.grf";
gyper::load_graph(my_graph.str().c_str());
REQUIRE(graph.size() > 0);
gyper::PHIndex ph_index = gyper::index_graph(my_graph.str());
REQUIRE(ph_index.check());
std::vector<gyper::KmerLabel> labels = ph_index.get(gyper::to_uint64("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels.size() == 36);
labels = ph_index.get(gyper::to_uint64("GGGGGAGTGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels.size() == 1);
REQUIRE(labels[0].variant_id == 3); // insertion
labels = ph_index.get(gyper::to_uint64("GGGGGGGTGGGGGGGGGGGGGGGGGGGGGGGG", 0));
for (auto const & label : labels)
{
bool const is_either = label.variant_id == 0 || label.variant_id == 2;
REQUIRE(is_either);
}
REQUIRE(labels.size() == 2);
REQUIRE(labels[0].variant_id != labels[1].variant_id);
labels = ph_index.get(gyper::to_uint64("AGGGGGGTGGGGGGGGGGGGGGGGGGGGGGGG", 0));
for (auto const & label : labels)
{
bool const is_either = label.variant_id == 0 || label.variant_id == 2;
std::cerr << __HERE__ << " " << label.to_string() << "\n";
}
REQUIRE(labels.size() == 2);
REQUIRE(labels[0].variant_id != labels[1].variant_id);
labels = ph_index.get(gyper::to_uint64("AGGGGAGTGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels.size() == 0);
}
TEST_CASE("Test index chr10 with parity event")
{
using namespace gyper;
std::stringstream my_graph;
my_graph << gyper_SOURCE_DIRECTORY << "/test/data/graphs/index_test_chr10.grf";
gyper::load_graph(my_graph.str().c_str());
REQUIRE(graph.size() > 0);
gyper::PHIndex ph_index = gyper::index_graph(my_graph.str());
REQUIRE(ph_index.check());
ph_index.print();
std::vector<gyper::KmerLabel> labels = ph_index.get(gyper::to_uint64("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels.size() == 36);
labels = ph_index.get(gyper::to_uint64("GGGGGAGTGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels.size() == 1);
REQUIRE(labels[0].variant_id == 3); // insertion
labels = ph_index.get(gyper::to_uint64("GGGGGGGTGGGGGGGGGGGGGGGGGGGGGGGG", 0));
for (auto const & label : labels)
{
bool const is_either = label.variant_id == 0 || label.variant_id == 2;
REQUIRE(is_either);
}
REQUIRE(labels.size() == 2);
REQUIRE(labels[0].variant_id != labels[1].variant_id);
labels = ph_index.get(gyper::to_uint64("AGGGGGGTGGGGGGGGGGGGGGGGGGGGGGGG", 0));
REQUIRE(labels.size() == 2);
labels = ph_index.get(gyper::to_uint64("AGGGGGAGTGGGGGGGGGGGGGGGGGGGGGGG", 0));
for (auto const & label : labels)
{
bool const is_either = label.variant_id == 1 || label.variant_id == 3;
REQUIRE(is_either);
}
REQUIRE(labels.size() == 2);
REQUIRE(labels[0].variant_id != labels[1].variant_id);
}
| 37.498876 | 118 | 0.710134 | DecodeGenetics |
c826865cfd74ffb5fa2d4c297f5f957d3a8d5db1 | 1,221 | cpp | C++ | src/kits/media/MediaClientDefs.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | 3 | 2018-05-21T15:32:32.000Z | 2019-03-21T13:34:55.000Z | src/kits/media/MediaClientDefs.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/kits/media/MediaClientDefs.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
* Copyright 2015, Dario Casalinuovo. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#include <MediaClient.h>
#include <MediaConnection.h>
#include <kits/debug/Debug.h>
media_client_id
media_client::Id() const
{
return node.node;
}
media_connection_id
media_connection::Id() const
{
return id;
}
media_connection_kind
media_connection::Kind() const
{
return kind;
}
bool media_connection::IsInput() const
{
return Kind() == B_MEDIA_INPUT;
}
bool media_connection::IsOutput() const
{
return Kind() == B_MEDIA_OUTPUT;
}
media_input
media_connection::MediaInput() const
{
media_input input;
input.node = client.node;
input.source = source;
input.destination = destination;
input.format = format;
return input;
}
media_output
media_connection::MediaOutput() const
{
media_output output;
output.node = client.node;
output.source = source;
output.destination = destination;
output.format = format;
return output;
}
const media_source&
media_connection::Source() const
{
return source;
}
const media_destination&
media_connection::Destination() const
{
return destination;
}
media_node
media_connection::RemoteNode() const
{
return remote_client.node;
}
| 13.875 | 58 | 0.747748 | stasinek |
c82a00726c77d8638ed7c7eae0a5d7b9ccf0e475 | 1,006 | cpp | C++ | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/RestoreTour.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/RestoreTour.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/RestoreTour.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | #include "./INCLUDE/Segment.h"
#include "./INCLUDE/LKH.h"
/*
* The RestoreTour function is used to undo a series of moves. The function
* restores the tour from SwapStack, the stack of 2-opt moves. A bad sequence
* of moves is undone by unstacking the 2-opt moves and making the inverse
* 2-opt moves in this reversed sequence.
*/
void LKH::LKHAlg::RestoreTour()
{
Node *t1, *t2, *t3, *t4;
/* Loop as long as the stack is not empty */
while (Swaps > OldSwaps) {
/* Undo topmost 2-opt move */
Swaps--;
t1 = SwapStack[Swaps].t1;
t2 = SwapStack[Swaps].t2;
t3 = SwapStack[Swaps].t3;
t4 = SwapStack[Swaps].t4;
Swap1(t3, t2, t1);
Swaps--;
/* Make edges (t1,t2) and (t2,t3) excludable again */
t1->OldPredExcluded = t1->OldSucExcluded = 0;
t2->OldPredExcluded = t2->OldSucExcluded = 0;
t3->OldPredExcluded = t3->OldSucExcluded = 0;
t4->OldPredExcluded = t4->OldSucExcluded = 0;
}
}
| 31.4375 | 78 | 0.610338 | BaiChunhui-9803 |
c82ada9c718d4ba753f956c213ed671f356570de | 43,370 | cpp | C++ | drishti/clipobject.cpp | shouhengli/drishti | 46558d12adcc1d365b7e2125d28190e3be2181c3 | [
"MIT"
] | null | null | null | drishti/clipobject.cpp | shouhengli/drishti | 46558d12adcc1d365b7e2125d28190e3be2181c3 | [
"MIT"
] | null | null | null | drishti/clipobject.cpp | shouhengli/drishti | 46558d12adcc1d365b7e2125d28190e3be2181c3 | [
"MIT"
] | null | null | null | #include "global.h"
#include "staticfunctions.h"
#include "clipobject.h"
#include "volumeinformation.h"
#include "captiondialog.h"
#include "dcolordialog.h"
#include "propertyeditor.h"
#include "enums.h"
#include "matrix.h"
#include <QFileDialog>
//------------------------------------------------------------------
ClipObjectUndo::ClipObjectUndo() { clear(); }
ClipObjectUndo::~ClipObjectUndo() { clear(); }
void
ClipObjectUndo::clear()
{
m_pos.clear();
m_rot.clear();
m_index = -1;
}
void
ClipObjectUndo::clearTop()
{
if (m_index == m_pos.count()-1)
return;
while(m_index < m_pos.count()-1)
m_pos.removeLast();
while(m_index < m_rot.count()-1)
m_rot.removeLast();
}
void
ClipObjectUndo::append(Vec p, Quaternion r)
{
clearTop();
m_pos << p;
m_rot << r;
m_index = m_pos.count()-1;
}
void ClipObjectUndo::redo() { m_index = qMin(m_index+1, m_pos.count()-1); }
void ClipObjectUndo::undo() { m_index = qMax(m_index-1, 0); }
Vec
ClipObjectUndo::pos()
{
Vec p = Vec(0,0,0);
if (m_index >= 0 && m_index < m_pos.count())
p = m_pos[m_index];
return p;
}
Quaternion
ClipObjectUndo::rot()
{
Quaternion r = Quaternion(Vec(1,0,0), 0);
if (m_index >= 0 && m_index < m_pos.count())
r = m_rot[m_index];
return r;
}
//------------------------------------------------------------------
int ClipObject::tfset() { return m_tfset; }
void ClipObject::setTFset(int tf) { m_tfset = tf; }
bool ClipObject::viewportGrabbed() { return m_viewportGrabbed; }
void ClipObject::setViewportGrabbed(bool v) { m_viewportGrabbed = v; }
QVector4D ClipObject::viewport() { return m_viewport; }
void ClipObject::setViewport(QVector4D v) { m_viewport = v; }
bool ClipObject::viewportType() { return m_viewportType; }
void ClipObject::setViewportType(bool v) { m_viewportType = v; }
float ClipObject::viewportScale() { return m_viewportScale; }
void ClipObject::setViewportScale(float v) { m_viewportScale = v; }
int ClipObject::thickness() { return m_thickness; }
void ClipObject::setThickness(int v) { m_thickness = v; }
float ClipObject::opmod() { return m_opmod; }
void ClipObject::setOpmod(float v) { m_opmod = v; }
bool ClipObject::showSlice() { return m_showSlice; }
void ClipObject::setShowSlice(bool b) { m_showSlice = b; }
bool ClipObject::showThickness() { return m_showThickness; }
void ClipObject::setShowThickness(bool b) { m_showThickness = b; }
bool ClipObject::showOtherSlice() { return m_showOtherSlice; }
void ClipObject::setShowOtherSlice(bool b) { m_showOtherSlice = b; }
bool ClipObject::apply() { return m_apply; }
void ClipObject::setApply(bool b) { m_apply = b; }
void ClipObject::setActive(bool a) { m_active = a; }
float ClipObject::size() { return m_size; }
bool ClipObject::flip() { return m_applyFlip; }
void ClipObject::setFlip(bool v) { m_applyFlip = v; }
float ClipObject::stereo() { return m_stereo; }
void ClipObject::setStereo(float v) { m_stereo = v; }
float ClipObject::opacity() { return m_opacity; }
void ClipObject::setOpacity(float v) { m_applyOpacity = true; m_opacity = v; }
Vec ClipObject::color() { return m_color; }
void ClipObject::setColor(Vec color) { m_color = color; }
bool ClipObject::solidColor() { return m_solidColor; }
void ClipObject::setSolidColor(bool sc) { m_solidColor = sc; }
float ClipObject::scale1() { return m_scale1; }
float ClipObject::scale2() { return m_scale2; }
float ClipObject::tscale1() { return m_tscale1; }
float ClipObject::tscale2() { return m_tscale2; }
void ClipObject::setScale1(float v) { m_scale1 = v; }
void ClipObject::setScale2(float v) { m_scale2 = v; }
QString ClipObject::captionText() { return m_captionText; }
QFont ClipObject::captionFont() { return m_captionFont; }
QColor ClipObject::captionColor() { return m_captionColor; }
QColor ClipObject::captionHaloColor() { return m_captionHaloColor; }
QString ClipObject::imageName() { return m_imageName; }
int ClipObject::imageFrame() { return m_imageFrame; }
void ClipObject::setImage(QString v, int n) { loadImage(v, n); }
int ClipObject::moveAxis() { return m_moveAxis; }
void ClipObject::setMoveAxis(int type) { m_moveAxis = type; }
bool ClipObject::mopClip() { return m_mopClip; }
bool ClipObject::reorientCamera() { return m_reorientCamera; }
bool ClipObject::saveSliceImage() { return m_saveSliceImage; }
bool ClipObject::resliceVolume() { return m_resliceVolume; }
int ClipObject::resliceSubsample() { return m_resliceSubsample; }
int ClipObject::resliceTag() { return m_resliceTag; }
void ClipObject::setGridX(int g) { m_gridX = g; }
void ClipObject::setGridY(int g) { m_gridY = g; }
int ClipObject::gridX() { return m_gridX; }
int ClipObject::gridY() { return m_gridY; }
ClipObject::ClipObject()
{
m_undo.clear();
m_mopClip = false;
m_reorientCamera = false;
m_saveSliceImage = false;
m_resliceVolume = false;
m_resliceSubsample = 1;
m_resliceTag = -1;
m_solidColor = false;
m_show = true;
m_displaylist = 0;
m_moveAxis = MoveAll;
m_color = Vec(0.8,0.7,0.9);
m_opacity = 1;
m_active = false;
m_stereo = 1;
m_tfset = -1; // i.e. do not texture clipplane
m_viewport = QVector4D(-1,-1,-1,-1);
m_viewportType = true;
m_viewportScale = 1.0f;
m_viewportGrabbed = false;
m_thickness = 0;
m_showSlice = true;
m_showThickness = true;
m_showOtherSlice = true;
m_apply = true;
m_opmod = 1.0;
m_applyOpacity = true;
m_applyFlip = false;
m_scale1 = 1.0;
m_scale2 = 1.0;
m_tscale1 = 1.0;
m_tscale2 = 1.0;
m_position = Vec(0,0,0);
m_quaternion = Quaternion(Vec(0,0,1), 0);
m_tang = Vec(0,0,1);
m_xaxis = Vec(1,0,0);
m_yaxis = Vec(0,1,0);
m_textureWidth = 0;
m_textureHeight = 0;
m_imagePresent = false;
m_imageName.clear();
m_imageFrame = 0;
m_captionPresent = false;
m_captionText.clear();
m_captionFont = QFont("Helvetica", 48);
m_captionColor = Qt::white;
m_captionHaloColor = Qt::white;
m_gridX = m_gridY = 0;
Matrix::identity(m_xform);
glGenTextures(1, &m_imageTex);
}
ClipObject::~ClipObject()
{
if (m_displaylist)
glDeleteLists(m_displaylist, 1);
glDeleteTextures(1, &m_imageTex);
m_undo.clear();
}
void
ClipObject::clearCaption()
{
m_captionPresent = false;
m_captionText.clear();
m_captionFont = QFont("Helvetica", 48);
m_captionColor = Qt::white;
m_captionHaloColor = Qt::white;
}
void
ClipObject::setCaption(QString ct, QFont cf,
QColor cc, QColor chc)
{
bool doit = false;
if (m_captionText != ct) doit = true;
if (m_captionFont != cf) doit = true;
if (m_captionColor != cc) doit = true;
if (m_captionHaloColor != chc) doit = true;
if (doit)
loadCaption(ct, cf, cc, chc);
}
void
ClipObject::loadCaption()
{
CaptionDialog cd(0,
m_captionText,
m_captionFont,
m_captionColor,
m_captionHaloColor);
cd.hideOpacity(true);
cd.move(QCursor::pos());
if (cd.exec() != QDialog::Accepted)
return;
loadCaption(cd.text(),
cd.font(),
cd.color(),
cd.haloColor());
}
void
ClipObject::loadCaption(QString ct, QFont cf,
QColor cc, QColor chc)
{
m_captionText = ct;
m_captionFont = cf;
m_captionColor = cc;
m_captionHaloColor = chc;
if (m_captionText.isEmpty())
{
m_captionPresent = false;
return;
}
QFontMetrics metric(m_captionFont);
int mde = metric.descent();
int fht = metric.height();
int fwd = metric.width(m_captionText)+2;
//-------------------
QImage bImage = QImage(fwd, fht, QImage::Format_ARGB32);
bImage.fill(0);
{
QPainter bpainter(&bImage);
// we have image as ARGB, but we want RGBA
// so switch red and blue colors here itself
QColor penColor(m_captionHaloColor.blue(),
m_captionHaloColor.green(),
m_captionHaloColor.red());
// do not use alpha(),
// opacity will be modulated using clip-plane's opacity parameter
bpainter.setPen(penColor);
bpainter.setFont(m_captionFont);
bpainter.drawText(1, fht-mde, m_captionText);
uchar *dbits = new uchar[4*fht*fwd];
uchar *bits = bImage.bits();
memcpy(dbits, bits, 4*fht*fwd);
for(int i=2; i<fht-2; i++)
for(int j=2; j<fwd-2; j++)
{
for (int k=0; k<4; k++)
{
int sum = 0;
for(int i0=-2; i0<=2; i0++)
for(int j0=-2; j0<=2; j0++)
sum += dbits[4*((i+i0)*fwd+(j+j0)) + k];
bits[4*(i*fwd+j) + k] = sum/25;
}
}
delete [] dbits;
}
//-------------------
QImage cImage = QImage(fwd, fht, QImage::Format_ARGB32);
cImage.fill(0);
QPainter cpainter(&cImage);
// first draw the halo image
cpainter.drawImage(0, 0, bImage);
// we have image as ARGB, but we want RGBA
// so switch red and blue colors here itself
QColor penColor(m_captionColor.blue(),
m_captionColor.green(),
m_captionColor.red());
// do not use alpha(),
// opacity will be modulated using clip-plane's opacity parameter
cpainter.setPen(penColor);
cpainter.setFont(m_captionFont);
cpainter.drawText(1, fht-mde, m_captionText);
m_textureWidth = fwd;
m_textureHeight = fht;
unsigned char *image = new unsigned char[4*m_textureWidth*m_textureHeight];
memcpy(image, cImage.bits(), 4*m_textureWidth*m_textureHeight);
if (m_imageTex)
glDeleteTextures(1, &m_imageTex);
glGenTextures(1, &m_imageTex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, m_imageTex);
glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,
0,
4,
m_textureWidth,
m_textureHeight,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image);
glDisable(GL_TEXTURE_RECTANGLE_ARB);
delete [] image;
clearImage();
m_captionPresent = true;
}
void
ClipObject::clearImage()
{
m_imagePresent = false;
m_imageName.clear();
m_imageFrame = 0;
}
void
ClipObject::loadImage()
{
QString imgFile = QFileDialog::getOpenFileName(0,
QString("Load image to map on the clip plane"),
Global::previousDirectory(),
"Image Files (*.png *.tif *.bmp *.jpg *.gif)");
if (imgFile.isEmpty())
return;
QFileInfo f(imgFile);
if (f.exists() == false)
return;
Global::setPreviousDirectory(f.absolutePath());
VolumeInformation pvlInfo = VolumeInformation::volumeInformation();
QFileInfo fileInfo(pvlInfo.pvlFile);
imgFile = fileInfo.absoluteDir().relativeFilePath(imgFile);
loadImage(imgFile, 0);
}
void
ClipObject::loadImage(QString imgFile, int imgFrame)
{
if (m_imageName == imgFile && m_imageFrame == imgFrame)
return;
m_imageName = imgFile;
m_imageFrame = imgFrame;
if (m_imageName.isEmpty())
{
m_imageFrame = 0;
m_imagePresent = false;
return;
}
//----------------
// file is assumed to be relative to .pvl.nc file
// get the absolute path
VolumeInformation pvlInfo = VolumeInformation::volumeInformation();
QFileInfo fileInfo(pvlInfo.pvlFile);
QString absoluteImageFile = QFileInfo(fileInfo.absolutePath(),
m_imageName).absoluteFilePath();
//----------------
QFileInfo f(absoluteImageFile);
if (f.exists() == false)
{
m_textureHeight = m_textureWidth = 10;
m_imagePresent = true;
clearCaption();
return;
}
QMovie movie(absoluteImageFile);
movie.setCacheMode(QMovie::CacheAll);
movie.start();
movie.setPaused(true);
movie.jumpToFrame(0);
if (movie.jumpToFrame(m_imageFrame) == false)
movie.jumpToFrame(0);
QImage mapImage(movie.currentImage());
m_textureHeight = mapImage.height();
m_textureWidth = mapImage.width();
int nbytes = mapImage.byteCount();
int rgb = nbytes/(m_textureWidth*m_textureHeight);
unsigned char *image = new unsigned char[rgb*m_textureWidth*m_textureHeight];
memcpy(image, mapImage.bits(), rgb*m_textureWidth*m_textureHeight);
GLuint fmt;
if (rgb == 1) fmt = GL_LUMINANCE;
else if (rgb == 2) fmt = GL_LUMINANCE_ALPHA;
else if (rgb == 3) fmt = GL_RGB;
else if (rgb == 4) fmt = GL_BGRA;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, m_imageTex);
glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,
0,
rgb,
m_textureWidth,
m_textureHeight,
0,
fmt,
GL_UNSIGNED_BYTE,
image);
glDisable(GL_TEXTURE_RECTANGLE_ARB);
delete [] image;
clearCaption();
m_imagePresent = true;
}
void
ClipObject::translate(Vec trans)
{
m_position += trans;
m_undo.append(m_position, m_quaternion);
}
Vec ClipObject::position() { return m_position; }
Quaternion ClipObject::orientation() { return m_quaternion; }
void ClipObject::setPosition(Vec pos)
{
m_position = pos;
m_undo.append(m_position, m_quaternion);
}
void
ClipObject::setOrientation(Quaternion q)
{
m_quaternion = q;
m_tang = m_quaternion.rotate(Vec(0,0,1));
m_xaxis = m_quaternion.rotate(Vec(1,0,0));
m_yaxis = m_quaternion.rotate(Vec(0,1,0));
m_undo.append(m_position, m_quaternion);
}
void
ClipObject::rotate(Vec axis, float angle)
{
Quaternion q(axis, DEG2RAD(angle));
m_quaternion = q*m_quaternion;
m_tang = m_quaternion.rotate(Vec(0,0,1));
m_xaxis = m_quaternion.rotate(Vec(1,0,0));
m_yaxis = m_quaternion.rotate(Vec(0,1,0));
m_undo.append(m_position, m_quaternion);
}
void ClipObject::normalize()
{
Vec pt = m_position;
pt = Vec((int)pt.x, (int)pt.y, (int)pt.z);
m_position = pt;
m_undo.append(m_position, m_quaternion);
}
void
ClipObject::draw(QGLViewer *viewer,
bool backToFront, float widgetSize)
{
m_size = widgetSize;
computeTscale();
if (!m_show)
return;
if (m_imagePresent ||
m_captionPresent ||
(m_gridX > 0 && m_gridY > 0) )
{
if (m_gridX > 0 && m_gridY > 0)
drawGrid();
if (m_imagePresent || m_captionPresent)
drawCaptionImage();
if (m_active) drawLines(viewer, backToFront);
}
else
drawLines(viewer, backToFront);
}
void
ClipObject::drawGrid()
{
float s1 = m_tscale1;
float s2 = m_tscale2;
glColor4f(m_color.x*m_opacity,
m_color.y*m_opacity,
m_color.z*m_opacity,
m_opacity);
Vec tang = m_tang;
Vec xaxis = m_xaxis;
Vec yaxis = m_yaxis;
tang = Matrix::rotateVec(m_xform, tang);
xaxis = Matrix::rotateVec(m_xform, xaxis);
yaxis = Matrix::rotateVec(m_xform, yaxis);
Vec voxelScaling = Global::voxelScaling();
Vec opt = VECPRODUCT(m_position, voxelScaling);
opt = Matrix::xformVec(m_xform, opt);
Vec c0, c1, c2, c3;
c0 = opt - s1*xaxis + s2*yaxis;
c1 = opt - s1*xaxis - s2*yaxis;
c2 = opt + s1*xaxis - s2*yaxis;
c3 = opt + s1*xaxis + s2*yaxis;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Global::boxTexture());
glEnable(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0, 1.0);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3fv(c0);
glTexCoord2f(0, m_gridY); glVertex3fv(c1);
glTexCoord2f(m_gridX, m_gridY); glVertex3fv(c2);
glTexCoord2f(m_gridX, 0); glVertex3fv(c3);
glEnd();
glPolygonOffset(0.0, 0.0);
glDisable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_TEXTURE_2D);
}
void
ClipObject::drawCaptionImage()
{
glLineWidth(1);
float s1 = m_tscale1;
float s2 = m_tscale2;
glColor4f(0, 0, 0, m_opacity);
if (m_applyOpacity)
glColor4f(m_opacity,
m_opacity,
m_opacity,
m_opacity);
else
glColor4f(1,1,1,1);
if (m_applyFlip)
{
s2 = -s2;
}
Vec tang = m_tang;
Vec xaxis = m_xaxis;
Vec yaxis = m_yaxis;
tang = Matrix::rotateVec(m_xform, tang);
xaxis = Matrix::rotateVec(m_xform, xaxis);
yaxis = Matrix::rotateVec(m_xform, yaxis);
Vec voxelScaling = Global::voxelScaling();
Vec opt = VECPRODUCT(m_position, voxelScaling);
opt = Matrix::xformVec(m_xform, opt);
Vec c0, c1, c2, c3;
c0 = opt - s1*xaxis + s2*yaxis;
c1 = opt - s1*xaxis - s2*yaxis;
c2 = opt + s1*xaxis - s2*yaxis;
c3 = opt + s1*xaxis + s2*yaxis;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, m_imageTex);
glTexEnvf(GL_TEXTURE_ENV,
GL_TEXTURE_ENV_MODE,
GL_MODULATE);
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0, 1.0);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3fv(c0);
glTexCoord2f(0, m_textureHeight); glVertex3fv(c1);
glTexCoord2f(m_textureWidth, m_textureHeight); glVertex3fv(c2);
glTexCoord2f(m_textureWidth, 0); glVertex3fv(c3);
glEnd();
glPolygonOffset(0.0, 0.0);
glDisable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_TEXTURE_RECTANGLE_ARB);
}
//#define DRAWTHICKNESS() \
// { \
// float aspectRatio = m_viewport.z()/m_viewport.w(); \
// float cdist = 2*viewer->sceneRadius()/m_viewportScale; \
// float fov = viewer->camera()->fieldOfView(); \
// float yn = (cdist-m_thickness)*tan(fov*0.5); \
// float yf = (cdist+m_thickness)*tan(fov*0.5); \
// if (!m_viewportType) \
// { \
// yf = yn = cdist*tan(fov*0.5); \
// } \
// float xn = yn*aspectRatio; \
// float xf = yf*aspectRatio; \
// \
// glBegin(GL_LINE_STRIP); \
// glVertex3fv(opt - xn*xaxis - yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt - xn*xaxis + yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt + xn*xaxis + yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt + xn*xaxis - yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt - xn*xaxis - yn*yaxis + m_thickness*tang); \
// glEnd(); \
// glBegin(GL_LINE_STRIP); \
// glVertex3fv(opt - xf*xaxis - yf*yaxis - m_thickness*tang); \
// glVertex3fv(opt - xf*xaxis + yf*yaxis - m_thickness*tang); \
// glVertex3fv(opt + xf*xaxis + yf*yaxis - m_thickness*tang); \
// glVertex3fv(opt + xf*xaxis - yf*yaxis - m_thickness*tang); \
// glVertex3fv(opt - xf*xaxis - yf*yaxis - m_thickness*tang); \
// glEnd(); \
// \
// glBegin(GL_LINES); \
// glVertex3fv(opt - xn*xaxis - yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt - xf*xaxis - yf*yaxis - m_thickness*tang); \
// glVertex3fv(opt - xn*xaxis + yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt - xf*xaxis + yf*yaxis - m_thickness*tang); \
// glVertex3fv(opt + xn*xaxis + yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt + xf*xaxis + yf*yaxis - m_thickness*tang); \
// glVertex3fv(opt + xn*xaxis - yn*yaxis + m_thickness*tang); \
// glVertex3fv(opt + xf*xaxis - yf*yaxis - m_thickness*tang); \
// glEnd(); \
// }
#define DRAWTHICKNESS() \
{ \
float aspectRatio = m_viewport.z()/m_viewport.w(); \
float cdist = 2*viewer->sceneRadius()/m_viewportScale; \
float fov = viewer->camera()->fieldOfView(); \
float yn = cdist*tan(fov*0.5); \
float yf = (cdist+2*m_thickness)*tan(fov*0.5); \
if (!m_viewportType) \
{ \
yf = yn = cdist*tan(fov*0.5); \
} \
float xn = yn*aspectRatio; \
float xf = yf*aspectRatio; \
\
glBegin(GL_LINE_STRIP); \
glVertex3fv(opt - xn*xaxis - yn*yaxis); \
glVertex3fv(opt - xn*xaxis + yn*yaxis); \
glVertex3fv(opt + xn*xaxis + yn*yaxis); \
glVertex3fv(opt + xn*xaxis - yn*yaxis); \
glVertex3fv(opt - xn*xaxis - yn*yaxis); \
glEnd(); \
glBegin(GL_LINE_STRIP); \
glVertex3fv(opt - xf*xaxis - yf*yaxis - 2*m_thickness*tang); \
glVertex3fv(opt - xf*xaxis + yf*yaxis - 2*m_thickness*tang); \
glVertex3fv(opt + xf*xaxis + yf*yaxis - 2*m_thickness*tang); \
glVertex3fv(opt + xf*xaxis - yf*yaxis - 2*m_thickness*tang); \
glVertex3fv(opt - xf*xaxis - yf*yaxis - 2*m_thickness*tang); \
glEnd(); \
\
glBegin(GL_LINES); \
glVertex3fv(opt - xn*xaxis - yn*yaxis); \
glVertex3fv(opt - xf*xaxis - yf*yaxis - 2*m_thickness*tang); \
glVertex3fv(opt - xn*xaxis + yn*yaxis); \
glVertex3fv(opt - xf*xaxis + yf*yaxis - 2*m_thickness*tang); \
glVertex3fv(opt + xn*xaxis + yn*yaxis); \
glVertex3fv(opt + xf*xaxis + yf*yaxis - 2*m_thickness*tang); \
glVertex3fv(opt + xn*xaxis - yn*yaxis); \
glVertex3fv(opt + xf*xaxis - yf*yaxis - 2*m_thickness*tang); \
glEnd(); \
}
#define DRAWCLIPWIDGET() \
{ \
if (!m_solidColor) \
{ \
glColor3f(m_color.x, m_color.y, m_color.z); \
glBegin(GL_LINE_STRIP); \
glVertex3fv(opt - s1*xaxis - s2*yaxis); \
glVertex3fv(opt - s1*xaxis + s2*yaxis); \
glVertex3fv(opt + s1*xaxis + s2*yaxis); \
glVertex3fv(opt + s1*xaxis - s2*yaxis); \
glVertex3fv(opt - s1*xaxis - s2*yaxis); \
glEnd(); \
} \
else \
{ \
glColor4f(m_color.x*m_opacity, \
m_color.y*m_opacity, \
m_color.z*m_opacity, \
m_opacity); \
glBegin(GL_QUADS); \
glVertex3fv(opt - s1*xaxis - s2*yaxis); \
glVertex3fv(opt - s1*xaxis + s2*yaxis); \
glVertex3fv(opt + s1*xaxis + s2*yaxis); \
glVertex3fv(opt + s1*xaxis - s2*yaxis); \
glEnd(); \
} \
}
void
ClipObject::drawLines(QGLViewer *viewer,
bool backToFront)
{
bool noimage = !m_imagePresent && !m_captionPresent;
bool quad = noimage && m_active;
glEnable(GL_BLEND);
// glEnable(GL_LINE_SMOOTH);
// glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
Vec voxelScaling = Global::voxelScaling();
Vec opt = VECPRODUCT(m_position, voxelScaling);
opt = Matrix::xformVec(m_xform, opt);
float r = m_size;
float s1 = m_tscale1;
float s2 = m_tscale2;
Vec tang = m_tang;
Vec xaxis = m_xaxis;
Vec yaxis = m_yaxis;
tang = Matrix::rotateVec(m_xform, tang);
xaxis = Matrix::rotateVec(m_xform, xaxis);
yaxis = Matrix::rotateVec(m_xform, yaxis);
if (backToFront)
{
if (m_active)
glLineWidth(3);
else
glLineWidth(1);
glColor3f(m_color.x, m_color.y, m_color.z);
if (m_thickness > 0 && m_showThickness)
DRAWTHICKNESS()
else
DRAWCLIPWIDGET()
}
glLineWidth(1);
if (!m_solidColor || m_active)
{
Vec c0, ca, cb, c1;
c0 = opt + s1*xaxis;
ca = opt - 0.2*s2*yaxis;
c1 = opt - s1*xaxis;
cb = opt + 0.2*s2*yaxis;
glColor4f(m_opacity, 0.5*m_opacity, 0, m_opacity);
if (quad &&
m_moveAxis >= MoveX0 &&
m_moveAxis <= MoveX1) glBegin(GL_QUADS);
else glBegin(GL_LINE_STRIP);
glVertex3fv(c0);
glVertex3fv(ca);
glVertex3fv(c1);
glVertex3fv(cb);
if (!(quad && m_moveAxis == MoveZ)) glVertex3fv(c0);
glEnd();
c0 = opt + s2*yaxis;
ca = opt - 0.2*s1*xaxis;
c1 = opt - s2*yaxis;
cb = opt + 0.2*s1*xaxis;
glColor4f(0.5*m_opacity, m_opacity, 0, m_opacity);
if (quad &&
m_moveAxis >= MoveY0 &&
m_moveAxis <= MoveY1) glBegin(GL_QUADS);
else glBegin(GL_LINE_STRIP);
glVertex3fv(c0);
glVertex3fv(ca);
glVertex3fv(c1);
glVertex3fv(cb);
if (!quad) glVertex3fv(c0);
glEnd();
c0 = opt + r*tang;
Vec cax = opt - 0.2*s1*xaxis;
Vec cbx = opt + 0.2*s1*xaxis;
Vec cay = opt - 0.2*s2*yaxis;
Vec cby = opt + 0.2*s2*yaxis;
glColor4f(0, 0.5*m_opacity, m_opacity, m_opacity);
if (quad && m_moveAxis == MoveZ) glBegin(GL_TRIANGLES);
else glBegin(GL_LINE_STRIP);
glVertex3fv(c0);
glVertex3fv(cax);
glVertex3fv(cay);
glVertex3fv(c0);
glVertex3fv(cay);
glVertex3fv(cbx);
glVertex3fv(c0);
glVertex3fv(cbx);
glVertex3fv(cby);
glVertex3fv(c0);
glVertex3fv(cby);
glVertex3fv(cax);
if (!(quad && m_moveAxis == MoveZ)) glVertex3fv(c0);
glEnd();
}
// glDisable(GL_LINE_SMOOTH);
if (!backToFront)
{
if (m_active)
glLineWidth(3);
else
glLineWidth(1);
glColor3f(m_color.x, m_color.y, m_color.z);
if (m_thickness > 0 && m_showThickness)
DRAWTHICKNESS()
else
DRAWCLIPWIDGET()
}
if (!m_solidColor || m_active)
{
glEnable(GL_POINT_SPRITE);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, Global::spriteTexture());
glTexEnvf( GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE );
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_POINT_SMOOTH);
if (m_active)
{
glColor3f(1,0,0);
glPointSize(25);
}
else
{
glColor3f(m_color.x, m_color.y, m_color.z);
glPointSize(20);
}
glBegin(GL_POINTS);
glVertex3fv(opt);
glEnd();
glPointSize(1);
glDisable(GL_POINT_SPRITE);
glActiveTexture(GL_TEXTURE0);
glDisable(GL_TEXTURE_2D);
glDisable(GL_POINT_SMOOTH);
}
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
}
void
ClipObject::postdraw(QGLViewer *viewer,
int x, int y,
bool grabsMouse)
{
if (!grabsMouse)
return;
// glEnable(GL_LINE_SMOOTH);
// glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // blend on top
glDisable(GL_DEPTH_TEST);
viewer->startScreenCoordinatesSystem();
Vec voxelScaling = Global::voxelScaling();
if (grabsMouse)
{
VolumeInformation pvlInfo = VolumeInformation::volumeInformation();
QString str;
str = QString("clip : %1 %2 %3").\
arg(m_position.x).\
arg(m_position.y).\
arg(m_position.z);
QFont font = QFont();
QFontMetrics metric(font);
int ht = metric.height();
int wd = metric.width(str);
x += 10;
StaticFunctions::renderText(x+2, y, str, font, Qt::black, Qt::white);
}
glEnable(GL_DEPTH_TEST);
viewer->stopScreenCoordinatesSystem();
}
void
ClipObject::applyUndo()
{
m_undo.undo();
undoParameters();
}
void
ClipObject::applyRedo()
{
m_undo.redo();
undoParameters();
}
void
ClipObject::undoParameters()
{
m_position = m_undo.pos();
m_quaternion = m_undo.rot();
m_tang = m_quaternion.rotate(Vec(0,0,1));
m_xaxis = m_quaternion.rotate(Vec(1,0,0));
m_yaxis = m_quaternion.rotate(Vec(0,1,0));
}
bool
ClipObject::keyPressEvent(QKeyEvent *event)
{
m_mopClip = false;
m_reorientCamera = false;
m_saveSliceImage = false;
m_resliceVolume = false;
if (event->key() == Qt::Key_F)
{
m_applyFlip = !m_applyFlip;
return true;
}
else if (event->key() == Qt::Key_O)
{
m_applyOpacity = !m_applyOpacity;
return true;
}
else if (event->key() == Qt::Key_Z &&
(event->modifiers() & Qt::ControlModifier ||
event->modifiers() & Qt::MetaModifier) )
{
applyUndo();
return true;
}
else if (event->key() == Qt::Key_Y &&
(event->modifiers() & Qt::ControlModifier ||
event->modifiers() & Qt::MetaModifier) )
{
applyRedo();
return true;
}
else if (event->key() == Qt::Key_Space)
{
return commandEditor();
}
return false;
}
bool
ClipObject::processCommand(QString cmd)
{
bool ok;
cmd = cmd.toLower();
QStringList list = cmd.split(" ", QString::SkipEmptyParts);
if (list[0] == "mop")
{
if (list.size() == 2 && list[1] == "clip")
{
m_mopClip = true;
return true;
}
else
return false;
}
else if (list[0] == "tfset")
{
int tf = 1000;
if (list.size() == 2) tf = qMax(0, list[1].toInt());
m_tfset = tf;
return true;
}
else if (list[0] == "reorientcamera")
{
m_reorientCamera = true;
return true;
}
else if (list[0] == "color")
{
QColor dcolor = QColor::fromRgbF(m_color.x,
m_color.y,
m_color.z);
QColor color = DColorDialog::getColor(dcolor);
if (color.isValid())
{
float r = color.redF();
float g = color.greenF();
float b = color.blueF();
m_color = Vec(r,g,b);
}
}
else if (list[0] == "solidcolor")
{
if (list.size() == 2 &&
list[1] == "no")
m_solidColor = false;
else
m_solidColor = true;
return true;
}
else if (list[0] == "savesliceimage")
{
m_resliceSubsample = 1;
m_saveSliceImage = true;
if (list.size() == 2) m_resliceSubsample = qMax(1, list[1].toInt(&ok));
return true;
}
else if (list[0] == "reslice")
{
m_resliceSubsample = 1;
m_resliceTag = -1;
m_resliceVolume = true;
if (list.size() > 1) m_resliceSubsample = qMax(1, list[1].toInt(&ok));
if (list.size() > 2) m_resliceTag = list[2].toInt(&ok);
return true;
}
else if (list[0] == "grid")
{
if (list.size() == 1)
{
m_gridX = m_gridY = 10;
}
else if (list.size() == 2 && list[1] == "no")
{
m_gridX = m_gridY = 0;
}
else if (list.size() == 3)
{
m_gridX = list[1].toInt();
m_gridY = list[2].toInt();
}
return true;
}
else if (list[0] == "image")
{
if (list.size() == 2 &&
list[1] == "no")
clearImage();
else
loadImage();
return true;
}
else if (list[0] == "imageframe")
{
if (list.size() == 2)
{
int frm = list[1].toInt(&ok);
if (frm >= 0)
{
loadImage(m_imageName, frm);
}
else
QMessageBox::information(0, "Error",
"ImageFrame not changed. Positive values required");
}
else
QMessageBox::information(0, "Error",
"Please specify ImageFrame number for the clipplane");
return true;
}
else if (list[0] == "caption")
{
if (list.count() == 2 &&
list[1] == "no")
clearCaption();
else
loadCaption();
return true;
}
else if (list[0] == "vscale" ||
list[0] == "scale")
{
if (list.size() > 1)
{
float scl1, scl2;
if (list.size() == 2)
{
scl1 = list[1].toFloat(&ok);
scl2 = scl1;
}
else
{
scl1 = list[1].toFloat(&ok);
scl2 = list[2].toFloat(&ok);
}
if (list[0] == "scale")
{
m_scale1 = -qAbs(scl1);
m_scale2 = -qAbs(scl2);
}
else
{
m_scale1 = scl1;
m_scale2 = scl2;
}
}
else
QMessageBox::information(0, "Error",
"Please specify both scalings for the clipplane");
return true;
}
else if (list[0] == "opacity")
{
if (list.size() == 2)
{
float scl = list[1].toFloat(&ok);
if (scl >= 0 && scl <= 1)
{
m_opacity = scl;
m_opacity = qMax(0.02f, qMin(1.0f, m_opacity));
}
else
QMessageBox::information(0, "Error",
"Opacity not changed. Value between 0 and 1 required");
}
else
QMessageBox::information(0, "Error",
"Please specify opacity for the clipplane");
return true;
}
else if (list[0] == "translate" ||
list[0] == "translatex" ||
list[0] == "translatey" ||
list[0] == "translatez" ||
list[0] == "move" ||
list[0] == "movex" ||
list[0] == "movey" ||
list[0] == "movez")
{
Vec pos;
float x=0,y=0,z=0;
if (list[0] == "translate" || list[0] == "move")
{
if (list.size() > 1) x = list[1].toFloat(&ok);
if (list.size() > 2) y = list[2].toFloat(&ok);
if (list.size() > 3) z = list[3].toFloat(&ok);
pos = Vec(x,y,z);
}
else
{
float v=0;
if (list.size() > 1) v = list[1].toFloat(&ok);
if (list[0] == "translatex" || list[0] == "movex")
pos = Vec(v,0,0);
else if (list[0] == "translatey" || list[0] == "movey")
pos = Vec(0,v,0);
else if (list[0] == "translatez" || list[0] == "movez")
pos = Vec(0,0,v);
}
if (list[0].contains("move"))
{
Vec cpos = position();
pos = pos + cpos;
}
setPosition(pos);
return true;
}
else if (list[0] == "rotatea" ||
list[0] == "rotateb" ||
list[0] == "rotatec")
{
float angle = 0;
if (list.size() > 1)
{
angle = list[1].toFloat(&ok);
if (list[0] == "rotatea") rotate(m_xaxis, angle);
if (list[0] == "rotateb") rotate(m_yaxis, angle);
if (list[0] == "rotatec") rotate(m_tang, angle);
}
else
{
QMessageBox::information(0, "", "No angle specified");
}
return true;
}
else if (list[0] == "movea" ||
list[0] == "moveb" ||
list[0] == "movec")
{
float shift = 0;
if (list.size() > 1)
{
shift = list[1].toFloat(&ok);
if (list[0] == "movea") translate(shift*m_xaxis);
if (list[0] == "moveb") translate(shift*m_yaxis);
if (list[0] == "movec") translate(shift*m_tang);
}
else
{
QMessageBox::information(0, "", "No distance specified");
}
return true;
}
else if (list[0] == "rotate" ||
list[0] == "rotatex" ||
list[0] == "rotatey" ||
list[0] == "rotatez" ||
list[0] == "addrotation" ||
list[0] == "addrotationx" ||
list[0] == "addrotationy" ||
list[0] == "addrotationz")
{
Quaternion rot;
float x=0,y=0,z=0,a=0;
if (list[0] == "rotate" || list[0] == "addrotation")
{
if (list.size() > 1) x = list[1].toFloat(&ok);
if (list.size() > 2) y = list[2].toFloat(&ok);
if (list.size() > 3) z = list[3].toFloat(&ok);
if (list.size() > 4) a = list[4].toFloat(&ok);
rot = Quaternion(Vec(x,y,z), DEG2RAD(a));
}
else
{
float a=0;
if (list.size() > 1) a = list[1].toFloat(&ok);
if (list[0] == "rotatex" || list[0] == "addrotationx")
rot = Quaternion(Vec(1,0,0), DEG2RAD(a));
else if (list[0] == "rotatey" || list[0] == "addrotationy")
rot = Quaternion(Vec(0,1,0), DEG2RAD(a));
else if (list[0] == "rotatez" || list[0] == "addrotationz")
rot = Quaternion(Vec(0,0,1), DEG2RAD(a));
}
if (list[0].contains("addrotation"))
{
Quaternion orot = orientation();
rot = rot*orot;
}
setOrientation(rot);
return true;
}
else
QMessageBox::information(0, "Error",
QString("Cannot understand the command : ") +
cmd);
return false;
}
void
ClipObject::computeTscale()
{
float s1, s2;
s1 = s2 = 1.0;
if (m_imagePresent || m_captionPresent)
{
if (m_textureHeight > m_textureWidth)
s1 = (float)m_textureWidth/(float)m_textureHeight;
else
s2 = (float)m_textureHeight/(float)m_textureWidth;
}
if (m_scale1 > 0 && m_scale2 > 0)
{ // scale according to widget size
s1*=m_size;
s2*=m_size;
}
// otherwise do no scale according to widget size
// negative scale value means take the absolute
// grid size values
s1*=qAbs(m_scale1);
s2*=qAbs(m_scale2);
m_tscale1 = s1;
m_tscale2 = s2;
}
bool
ClipObject::commandEditor()
{
PropertyEditor propertyEditor;
QMap<QString, QVariantList> plist;
QVariantList vlist;
vlist.clear();
plist["command"] = vlist;
vlist.clear();
vlist << QVariant("double");
vlist << QVariant(m_opacity);
vlist << QVariant(0.0);
vlist << QVariant(1.0);
vlist << QVariant(0.1); // singlestep
vlist << QVariant(1); // decimals
plist["opacity"] = vlist;
vlist.clear();
vlist << QVariant("color");
Vec pcolor = m_color;
QColor dcolor = QColor::fromRgbF(pcolor.x,
pcolor.y,
pcolor.z);
vlist << dcolor;
plist["color"] = vlist;
vlist.clear();
vlist << QVariant("checkbox");
vlist << QVariant(m_apply);
plist["apply clipping"] = vlist;
vlist.clear();
vlist << QVariant("int");
vlist << QVariant(m_tfset);
vlist << QVariant(-1);
vlist << QVariant(15);
plist["tfset"] = vlist;
vlist.clear();
vlist << QVariant("int");
vlist << QVariant(m_thickness);
vlist << QVariant(0);
vlist << QVariant(200);
plist["thickness"] = vlist;
vlist.clear();
vlist << QVariant("int");
vlist << QVariant(m_opmod);
vlist << QVariant(1);
vlist << QVariant(10);
plist["opmod"] = vlist;
vlist.clear();
vlist << QVariant("checkbox");
vlist << QVariant(m_solidColor);
plist["solid color"] = vlist;
vlist.clear();
vlist << QVariant("checkbox");
vlist << QVariant(m_showSlice);
plist["show slice"] = vlist;
vlist.clear();
vlist << QVariant("checkbox");
vlist << QVariant(m_showThickness);
plist["show thickness"] = vlist;
vlist.clear();
vlist << QVariant("combobox");
if (m_viewportType)
vlist << QVariant(1);
else
vlist << QVariant(0);
vlist << QVariant("orthographic");
vlist << QVariant("perspective");
plist["camera type"] = vlist;
vlist.clear();
vlist << QVariant("double");
vlist << QVariant(m_stereo);
vlist << QVariant(0.0);
vlist << QVariant(1.0);
vlist << QVariant(0.1); // singlestep
vlist << QVariant(1); // decimals
plist["stereo"] = vlist;
vlist.clear();
vlist << QVariant("checkbox");
vlist << QVariant(m_showOtherSlice);
plist["show other slice"] = vlist;
QString vpstr = QString("%1 %2 %3 %4").\
arg(m_viewport.x()).\
arg(m_viewport.y()).\
arg(m_viewport.z()).\
arg(m_viewport.w());
vlist.clear();
vlist << QVariant("string");
vlist << QVariant(vpstr);
plist["viewport"] = vlist;
vlist.clear();
vlist << QVariant("double");
vlist << QVariant(m_viewportScale);
vlist << QVariant(0.5);
vlist << QVariant(30.0);
vlist << QVariant(0.1); // singlestep
vlist << QVariant(1); // decimals
plist["viewport scale"] = vlist;
vlist.clear();
QFile helpFile(":/clipobject.help");
if (helpFile.open(QFile::ReadOnly))
{
QTextStream in(&helpFile);
QString line = in.readLine();
while (!line.isNull())
{
if (line == "#begin")
{
QString keyword = in.readLine();
QString helptext;
line = in.readLine();
while (!line.isNull())
{
helptext += line;
helptext += "\n";
line = in.readLine();
if (line == "#end") break;
}
vlist << keyword << helptext;
}
line = in.readLine();
}
}
plist["commandhelp"] = vlist;
//---------------------
vlist.clear();
QString mesg;
if (m_scale1 < 0 || m_scale2 < 0)
mesg += QString("scales : %1 %2\n").arg(-m_scale1).arg(-m_scale2);
else
mesg += QString("vscales : %1 %2\n").arg(m_scale1).arg(m_scale2);
mesg += QString("opacity : %1\n").arg(m_opacity);
mesg += QString("position : %1 %2 %3\n"). \
arg(m_position.x).arg(m_position.y).arg(m_position.z);
Quaternion q = orientation();
Vec axis;
qreal angle;
q.getAxisAngle(axis, angle);
mesg += QString("rotation : %1 %2 %3 : %4\n"). \
arg(axis.x).arg(axis.y).arg(axis.z).arg(RAD2DEG(angle));
mesg += QString("Red axis : %1 %2 %3\n"). \
arg(m_xaxis.x).arg(m_xaxis.y).arg(m_xaxis.z);
mesg += QString("Green axis : %1 %2 %3\n"). \
arg(m_yaxis.x).arg(m_yaxis.y).arg(m_yaxis.z);
mesg += QString("Blue axis : %1 %2 %3\n"). \
arg(m_tang.x).arg(m_tang.y).arg(m_tang.z);
vlist << mesg;
plist["message"] = vlist;
//---------------------
QStringList keys;
keys << "apply clipping";
keys << "solid color";
keys << "show slice";
keys << "show thickness";
keys << "show other slice";
keys << "gap";
keys << "color";
keys << "opacity";
keys << "gap";
keys << "viewport";
keys << "tfset";
keys << "opmod";
keys << "thickness";
keys << "viewport scale";
keys << "camera type";
keys << "stereo";
keys << "gap";
keys << "command";
keys << "commandhelp";
keys << "message";
propertyEditor.set("Clip Plane Dialog", plist, keys);
QMap<QString, QPair<QVariant, bool> > vmap;
if (propertyEditor.exec() == QDialog::Accepted)
vmap = propertyEditor.get();
else
return true;
keys = vmap.keys();
for(int ik=0; ik<keys.count(); ik++)
{
QPair<QVariant, bool> pair = vmap.value(keys[ik]);
if (pair.second)
{
if (keys[ik] == "color")
{
QColor color = pair.first.value<QColor>();
float r = color.redF();
float g = color.greenF();
float b = color.blueF();
m_color = Vec(r,g,b);
}
else if (keys[ik] == "opacity")
m_opacity = pair.first.toDouble();
else if (keys[ik] == "solid color")
m_solidColor = pair.first.toBool();
else if (keys[ik] == "apply clipping")
m_apply = pair.first.toBool();
else if (keys[ik] == "show slice")
m_showSlice = pair.first.toBool();
else if (keys[ik] == "show thickness")
m_showThickness = pair.first.toBool();
else if (keys[ik] == "show other slice")
m_showOtherSlice = pair.first.toBool();
else if (keys[ik] == "tfset")
m_tfset = pair.first.toInt();
else if (keys[ik] == "thickness")
m_thickness = pair.first.toInt();
else if (keys[ik] == "viewport scale")
m_viewportScale = pair.first.toDouble();
else if (keys[ik] == "camera type")
m_viewportType = (pair.first.toInt() == 1);
else if (keys[ik] == "stereo")
m_stereo = pair.first.toDouble();
else if (keys[ik] == "opmod")
m_opmod = pair.first.toInt();
else if (keys[ik] == "viewport")
{
vpstr = pair.first.toString();
QStringList list = vpstr.split(" ", QString::SkipEmptyParts);
if (list.count() == 4)
{
float x = list[0].toFloat();
float y = list[1].toFloat();
float z = list[2].toFloat();
float w = list[3].toFloat();
if (x < 0.0f || x > 1.0f ||
y < 0.0f || y > 1.0f ||
z < 0.0f || z > 1.0f ||
w < 0.0f || w > 1.0f)
QMessageBox::information(0, "",
QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3 %4").\
arg(x).arg(y).arg(z).arg(w));
else
m_viewport = QVector4D(x,y,z,w);
}
else if (list.count() == 3)
{
float x = list[0].toFloat();
float y = list[1].toFloat();
float z = list[2].toFloat();
if (x < 0.0f || x > 1.0f ||
y < 0.0f || y > 1.0f ||
z < 0.0f || z > 1.0f)
QMessageBox::information(0, "",
QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3").\
arg(x).arg(y).arg(z));
else
m_viewport = QVector4D(x,y,z,z);
}
else if (list.count() == 2)
{
float x = list[0].toFloat();
float y = list[1].toFloat();
if (x < 0.0f || x > 1.0f ||
y < 0.0f || y > 1.0f)
QMessageBox::information(0, "",
QString("Values for viewport must be between 0.0 and 1.0 : %1 %2").\
arg(x).arg(y));
else
m_viewport = QVector4D(x,y,0.5,0.5);
}
else
{
QMessageBox::information(0, "", "Switching off the viewport");
m_viewport = QVector4D(-1,-1,-1,-1);
}
}
}
}
QString cmd = propertyEditor.getCommandString();
if (!cmd.isEmpty())
return processCommand(cmd);
else
return true;
// if (propertyEditor.exec() == QDialog::Accepted)
// {
// QString cmd = propertyEditor.getCommandString();
// if (!cmd.isEmpty())
// return processCommand(cmd);
// }
// else
// return true;
}
| 25.496767 | 82 | 0.607033 | shouhengli |
c82b7b12cbb69b99e703af602b997cddb160a6c9 | 2,641 | hpp | C++ | OREData/ored/marketdata/fxtriangulation.hpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | null | null | null | OREData/ored/marketdata/fxtriangulation.hpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | null | null | null | OREData/ored/marketdata/fxtriangulation.hpp | PiotrSiejda/Engine | 8360b5de32408f2a37da5ac3ca7b4e913bf67e9f | [
"BSD-3-Clause"
] | 1 | 2022-02-07T02:04:10.000Z | 2022-02-07T02:04:10.000Z | /*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file marketdata/fxtriangulation.hpp
\brief Intelligent FX price repository
\ingroup marketdata
*/
#pragma once
#include <map>
#include <ql/handle.hpp>
#include <ql/quote.hpp>
#include <ql/types.hpp>
namespace ore {
namespace data {
using QuantLib::Quote;
using QuantLib::Handle;
//! Intelligent FX price repository
/*! FX Triangulation is an intelligent price repository that will attempt to calculate FX spot values
*
* As quotes for currency pairs are added to the repository they are stored in an internal map
* If the repository is asked for the FX spot price for a given pair it will attempt the following:
* 1) Look in the map for the pair
* 2) Look for the reverse quote (EURUSD -> USDEUR), if found it will return an inverse quote.
* 3) Look through the map and attempt to find a bridging pair (e.g EURUSD and EURJPY for USDJPY)
* and return the required composite quote.
*
* In cases (2) and (3) the constructed quote is then stored in the map so subsequent calls will hit (1).
*
* The constructed quotes all reference the original quotes which are added by the addQuote() method
* and so if these original quotes change in the future, the constructed quotes will reflect the new
* value
*
* \ingroup marketdata
*/
class FXTriangulation {
public:
//! Default ctor, once built the repo is empty
FXTriangulation() {}
//! Add a quote to the repo
void addQuote(const std::string& pair, const Handle<Quote>& spot) { map_[pair] = spot; }
//! Get a quote from the repo, this will follow the algorithm described above
Handle<Quote> getQuote(const std::string&) const;
//! Get all quotes currently stored in the triangulation
const std::map<std::string, Handle<Quote>>& quotes() const { return map_; }
private:
mutable std::map<std::string, Handle<Quote>> map_;
};
} // namespace data
} // namespace ore
| 36.178082 | 106 | 0.736842 | PiotrSiejda |
c82f177184b0c2f5911a6b8f2dcc9c0e98ae86a4 | 9,584 | cpp | C++ | Dependencies/crossguid/src/guid.cpp | solidajenjo/CyberPimpEngine | da4fc5d22bc7c52a45794ea73e2bac903d893178 | [
"MIT"
] | null | null | null | Dependencies/crossguid/src/guid.cpp | solidajenjo/CyberPimpEngine | da4fc5d22bc7c52a45794ea73e2bac903d893178 | [
"MIT"
] | null | null | null | Dependencies/crossguid/src/guid.cpp | solidajenjo/CyberPimpEngine | da4fc5d22bc7c52a45794ea73e2bac903d893178 | [
"MIT"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2014 Graeme Hill (http://graemehill.ca)
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 <cstring>
#include "crossguid/include/crossguid/guid.hpp"
#ifdef GUID_LIBUUID
#include <uuid/uuid.h>
#endif
#ifdef GUID_CFUUID
#include <CoreFoundation/CFUUID.h>
#endif
#include <objbase.h>
#ifdef GUID_ANDROID
#include <jni.h>
#include <cassert>
#endif
BEGIN_XG_NAMESPACE
#ifdef GUID_ANDROID
AndroidGuidInfo androidInfo;
AndroidGuidInfo AndroidGuidInfo::fromJniEnv(JNIEnv *env)
{
AndroidGuidInfo info;
info.env = env;
auto localUuidClass = env->FindClass("java/util/UUID");
info.uuidClass = (jclass)env->NewGlobalRef(localUuidClass);
env->DeleteLocalRef(localUuidClass);
info.newGuidMethod = env->GetStaticMethodID(
info.uuidClass, "randomUUID", "()Ljava/util/UUID;");
info.mostSignificantBitsMethod = env->GetMethodID(
info.uuidClass, "getMostSignificantBits", "()J");
info.leastSignificantBitsMethod = env->GetMethodID(
info.uuidClass, "getLeastSignificantBits", "()J");
info.initThreadId = std::this_thread::get_id();
return info;
}
void initJni(JNIEnv *env)
{
androidInfo = AndroidGuidInfo::fromJniEnv(env);
}
#endif
// overload << so that it's easy to convert to a string
std::ostream &operator<<(std::ostream &s, const Guid &guid)
{
std::ios_base::fmtflags f(s.flags()); // politely don't leave the ostream in hex mode
s << std::hex << std::setfill('0')
<< std::setw(2) << (int)guid._bytes[0]
<< std::setw(2) << (int)guid._bytes[1]
<< std::setw(2) << (int)guid._bytes[2]
<< std::setw(2) << (int)guid._bytes[3]
<< "-"
<< std::setw(2) << (int)guid._bytes[4]
<< std::setw(2) << (int)guid._bytes[5]
<< "-"
<< std::setw(2) << (int)guid._bytes[6]
<< std::setw(2) << (int)guid._bytes[7]
<< "-"
<< std::setw(2) << (int)guid._bytes[8]
<< std::setw(2) << (int)guid._bytes[9]
<< "-"
<< std::setw(2) << (int)guid._bytes[10]
<< std::setw(2) << (int)guid._bytes[11]
<< std::setw(2) << (int)guid._bytes[12]
<< std::setw(2) << (int)guid._bytes[13]
<< std::setw(2) << (int)guid._bytes[14]
<< std::setw(2) << (int)guid._bytes[15];
s.flags(f);
return s;
}
bool operator<(const xg::Guid &lhs, const xg::Guid &rhs)
{
return lhs.bytes() < rhs.bytes();
}
bool Guid::isValid() const
{
xg::Guid empty;
return *this != empty;
}
// convert to string using std::snprintf() and std::string
std::string Guid::str() const
{
char one[10], two[6], three[6], four[6], five[14];
snprintf(one, 10, "%02x%02x%02x%02x",
_bytes[0], _bytes[1], _bytes[2], _bytes[3]);
snprintf(two, 6, "%02x%02x",
_bytes[4], _bytes[5]);
snprintf(three, 6, "%02x%02x",
_bytes[6], _bytes[7]);
snprintf(four, 6, "%02x%02x",
_bytes[8], _bytes[9]);
snprintf(five, 14, "%02x%02x%02x%02x%02x%02x",
_bytes[10], _bytes[11], _bytes[12], _bytes[13], _bytes[14], _bytes[15]);
const std::string sep("-");
std::string out(one);
out += sep + two;
out += sep + three;
out += sep + four;
out += sep + five;
return out;
}
// conversion operator for std::string
Guid::operator std::string() const
{
return str();
}
// Access underlying bytes
const std::array<unsigned char, 16>& Guid::bytes() const
{
return _bytes;
}
// create a guid from vector of bytes
Guid::Guid(const std::array<unsigned char, 16> &bytes) : _bytes(bytes)
{ }
// create a guid from array of bytes
Guid::Guid(const unsigned char *bytes)
{
std::copy(bytes, bytes + 16, std::begin(_bytes));
}
// converts a single hex char to a number (0 - 15)
unsigned char hexDigitToChar(char ch)
{
// 0-9
if (ch > 47 && ch < 58)
return ch - 48;
// a-f
if (ch > 96 && ch < 103)
return ch - 87;
// A-F
if (ch > 64 && ch < 71)
return ch - 55;
return 0;
}
bool isValidHexChar(char ch)
{
// 0-9
if (ch > 47 && ch < 58)
return true;
// a-f
if (ch > 96 && ch < 103)
return true;
// A-F
if (ch > 64 && ch < 71)
return true;
return false;
}
// converts the two hexadecimal characters to an unsigned char (a byte)
unsigned char hexPairToChar(char a, char b)
{
return hexDigitToChar(a) * 16 + hexDigitToChar(b);
}
// create a guid from string
Guid::Guid(const std::string &fromString)
{
char charOne = '\0';
char charTwo = '\0';
bool lookingForFirstChar = true;
unsigned nextByte = 0;
for (const char &ch : fromString)
{
if (ch == '-')
continue;
if (nextByte >= 16 || !isValidHexChar(ch))
{
// Invalid string so bail
zeroify();
return;
}
if (lookingForFirstChar)
{
charOne = ch;
lookingForFirstChar = false;
}
else
{
charTwo = ch;
auto byte = hexPairToChar(charOne, charTwo);
_bytes[nextByte++] = byte;
lookingForFirstChar = true;
}
}
// if there were fewer than 16 bytes in the string then guid is bad
if (nextByte < 16)
{
zeroify();
return;
}
}
// create empty guid
Guid::Guid() : _bytes{ {0} }
{ }
// copy constructor
Guid::Guid(const Guid &other) : _bytes(other._bytes)
{ }
// set all bytes to zero
void Guid::zeroify()
{
std::fill(_bytes.begin(), _bytes.end(), static_cast<unsigned char>(0));
}
// overload assignment operator
Guid &Guid::operator=(const Guid &other)
{
Guid(other).swap(*this);
return *this;
}
// overload equality operator
bool Guid::operator==(const Guid &other) const
{
return _bytes == other._bytes;
}
// overload inequality operator
bool Guid::operator!=(const Guid &other) const
{
return !((*this) == other);
}
// member swap function
void Guid::swap(Guid &other)
{
_bytes.swap(other._bytes);
}
// This is the linux friendly implementation, but it could work on other
// systems that have libuuid available
#ifdef GUID_LIBUUID
Guid newGuid()
{
uuid_t id;
uuid_generate(id);
return id;
}
#endif
// this is the mac and ios version
#ifdef GUID_CFUUID
Guid newGuid()
{
auto newId = CFUUIDCreate(NULL);
auto bytes = CFUUIDGetUUIDBytes(newId);
CFRelease(newId);
std::array<unsigned char, 16> byteArray =
{{
bytes.byte0,
bytes.byte1,
bytes.byte2,
bytes.byte3,
bytes.byte4,
bytes.byte5,
bytes.byte6,
bytes.byte7,
bytes.byte8,
bytes.byte9,
bytes.byte10,
bytes.byte11,
bytes.byte12,
bytes.byte13,
bytes.byte14,
bytes.byte15
}};
return byteArray;
}
#endif
// obviously this is the windows version
Guid newGuid()
{
GUID newId;
CoCreateGuid(&newId);
std::array<unsigned char, 16> bytes =
{
(unsigned char)((newId.Data1 >> 24) & 0xFF),
(unsigned char)((newId.Data1 >> 16) & 0xFF),
(unsigned char)((newId.Data1 >> 8) & 0xFF),
(unsigned char)((newId.Data1) & 0xff),
(unsigned char)((newId.Data2 >> 8) & 0xFF),
(unsigned char)((newId.Data2) & 0xff),
(unsigned char)((newId.Data3 >> 8) & 0xFF),
(unsigned char)((newId.Data3) & 0xFF),
(unsigned char)newId.Data4[0],
(unsigned char)newId.Data4[1],
(unsigned char)newId.Data4[2],
(unsigned char)newId.Data4[3],
(unsigned char)newId.Data4[4],
(unsigned char)newId.Data4[5],
(unsigned char)newId.Data4[6],
(unsigned char)newId.Data4[7]
};
return bytes;
}
// android version that uses a call to a java api
#ifdef GUID_ANDROID
Guid newGuid(JNIEnv *env)
{
assert(env != androidInfo.env || std::this_thread::get_id() == androidInfo.initThreadId);
jobject javaUuid = env->CallStaticObjectMethod(
androidInfo.uuidClass, androidInfo.newGuidMethod);
jlong mostSignificant = env->CallLongMethod(javaUuid,
androidInfo.mostSignificantBitsMethod);
jlong leastSignificant = env->CallLongMethod(javaUuid,
androidInfo.leastSignificantBitsMethod);
std::array<unsigned char, 16> bytes =
{
(unsigned char)((mostSignificant >> 56) & 0xFF),
(unsigned char)((mostSignificant >> 48) & 0xFF),
(unsigned char)((mostSignificant >> 40) & 0xFF),
(unsigned char)((mostSignificant >> 32) & 0xFF),
(unsigned char)((mostSignificant >> 24) & 0xFF),
(unsigned char)((mostSignificant >> 16) & 0xFF),
(unsigned char)((mostSignificant >> 8) & 0xFF),
(unsigned char)((mostSignificant) & 0xFF),
(unsigned char)((leastSignificant >> 56) & 0xFF),
(unsigned char)((leastSignificant >> 48) & 0xFF),
(unsigned char)((leastSignificant >> 40) & 0xFF),
(unsigned char)((leastSignificant >> 32) & 0xFF),
(unsigned char)((leastSignificant >> 24) & 0xFF),
(unsigned char)((leastSignificant >> 16) & 0xFF),
(unsigned char)((leastSignificant >> 8) & 0xFF),
(unsigned char)((leastSignificant) & 0xFF)
};
env->DeleteLocalRef(javaUuid);
return bytes;
}
Guid newGuid()
{
return newGuid(androidInfo.env);
}
#endif
END_XG_NAMESPACE
// Specialization for std::swap<Guid>() --
// call member swap function of lhs, passing rhs
namespace std
{
template <>
void swap(xg::Guid &lhs, xg::Guid &rhs)
{
lhs.swap(rhs);
}
}
| 23.262136 | 90 | 0.675814 | solidajenjo |
c833061537004d21b1d7abfe6ca66315b946f6ab | 2,733 | cc | C++ | src/sycl/plugin-Validation/CountValidator.cc | lauracappelli/pixeltrack-standalone | 1a8286f1712e8693796503328e300d52c0c73e61 | [
"Apache-2.0"
] | null | null | null | src/sycl/plugin-Validation/CountValidator.cc | lauracappelli/pixeltrack-standalone | 1a8286f1712e8693796503328e300d52c0c73e61 | [
"Apache-2.0"
] | null | null | null | src/sycl/plugin-Validation/CountValidator.cc | lauracappelli/pixeltrack-standalone | 1a8286f1712e8693796503328e300d52c0c73e61 | [
"Apache-2.0"
] | null | null | null | #include "SYCLCore/Product.h"
#include "SYCLCore/ScopedContext.h"
#include "SYCLDataFormats/SiPixelClustersCUDA.h"
#include "SYCLDataFormats/SiPixelDigisCUDA.h"
#include "DataFormats/DigiClusterCount.h"
#include "DataFormats/TrackCount.h"
#include "DataFormats/VertexCount.h"
#include "Framework/EventSetup.h"
#include "Framework/Event.h"
#include "Framework/PluginFactory.h"
#include "Framework/EDProducer.h"
#include <atomic>
#include <iostream>
#include <mutex>
#include <sstream>
namespace {
std::atomic<int> allEvents = 0;
std::atomic<int> goodEvents = 0;
} // namespace
class CountValidator : public edm::EDProducer {
public:
explicit CountValidator(edm::ProductRegistry& reg);
private:
void produce(edm::Event& iEvent, const edm::EventSetup& iSetup) override;
void endJob() override;
edm::EDGetTokenT<DigiClusterCount> digiClusterCountToken_;
edm::EDGetTokenT<cms::sycltools::Product<SiPixelDigisCUDA>> digiToken_;
edm::EDGetTokenT<cms::sycltools::Product<SiPixelClustersCUDA>> clusterToken_;
};
CountValidator::CountValidator(edm::ProductRegistry& reg)
: digiClusterCountToken_(reg.consumes<DigiClusterCount>()),
digiToken_(reg.consumes<cms::sycltools::Product<SiPixelDigisCUDA>>()),
clusterToken_(reg.consumes<cms::sycltools::Product<SiPixelClustersCUDA>>()) {}
void CountValidator::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) {
std::stringstream ss;
bool ok = true;
ss << "Event " << iEvent.eventID() << " ";
{
auto const& pdigis = iEvent.get(digiToken_);
cms::sycltools::ScopedContextProduce ctx{pdigis};
auto const& count = iEvent.get(digiClusterCountToken_);
auto const& digis = ctx.get(iEvent, digiToken_);
auto const& clusters = ctx.get(iEvent, clusterToken_);
if (digis.nModules() != count.nModules()) {
ss << "\n N(modules) is " << digis.nModules() << " expected " << count.nModules();
ok = false;
}
if (digis.nDigis() != count.nDigis()) {
ss << "\n N(digis) is " << digis.nDigis() << " expected " << count.nDigis();
ok = false;
}
if (clusters.nClusters() != count.nClusters()) {
ss << "\n N(clusters) is " << clusters.nClusters() << " expected " << count.nClusters();
ok = false;
}
}
++allEvents;
if (ok) {
++goodEvents;
} else {
std::cout << ss.str() << std::endl;
}
}
void CountValidator::endJob() {
if (allEvents == goodEvents) {
std::cout << "CountValidator: all " << allEvents << " events passed validation\n";
} else {
std::cout << "CountValidator: " << (allEvents - goodEvents) << " events failed validation (see details above)\n";
throw std::runtime_error("CountValidator failed");
}
}
DEFINE_FWK_MODULE(CountValidator);
| 31.413793 | 117 | 0.683132 | lauracappelli |
c8375a4d91e53b3a94a6cdbfe9ddf77653ba0c9f | 3,465 | cpp | C++ | src/import/MultiFormatReader.cpp | The-audafoss-crew/audafoss | e9ea301028272da918c2e94e3298fa5d4fec4c14 | [
"CC-BY-3.0"
] | 393 | 2021-07-04T20:27:15.000Z | 2021-09-21T10:44:47.000Z | src/import/MultiFormatReader.cpp | The-audafoss-crew/audafoss | e9ea301028272da918c2e94e3298fa5d4fec4c14 | [
"CC-BY-3.0"
] | 41 | 2021-07-05T17:31:57.000Z | 2021-09-14T03:51:01.000Z | src/import/MultiFormatReader.cpp | The-audafoss-crew/audafoss | e9ea301028272da918c2e94e3298fa5d4fec4c14 | [
"CC-BY-3.0"
] | 32 | 2021-07-05T12:34:57.000Z | 2021-08-15T21:18:54.000Z | /**********************************************************************
Audacium: A Digital Audio Editor
MultiFormatReader.cpp
Philipp Sibler
******************************************************************//**
\class MultiFormatReader
\brief MultiFormatReader reads raw audio files in different formats and
machine endianness representations.
*//*******************************************************************/
#include "MultiFormatReader.h"
#include <exception>
#include <stdexcept>
#include <cstring>
#include <stdint.h>
#include <cstdio>
#include <wx/defs.h>
MachineEndianness::MachineEndianness()
{
if (wxBYTE_ORDER == wxLITTLE_ENDIAN)
{
mFlag = MachineEndianness::Little;
}
else
{
mFlag = MachineEndianness::Big;
}
}
MultiFormatReader::MultiFormatReader(const char* filename)
: mpFid(NULL)
{
mpFid = fopen(filename, "rb");
if (mpFid == NULL)
{
throw std::runtime_error("Error opening file");
}
}
MultiFormatReader::~MultiFormatReader()
{
if (mpFid != NULL)
{
fclose(mpFid);
}
}
void MultiFormatReader::Reset()
{
if (mpFid != NULL)
{
rewind(mpFid);
}
}
size_t MultiFormatReader::ReadSamples(void* buffer, size_t len,
MultiFormatReader::FormatT format,
MachineEndianness::EndiannessT end)
{
return ReadSamples(buffer, len, 1, format, end);
}
size_t MultiFormatReader::ReadSamples(void* buffer, size_t len, size_t stride,
MultiFormatReader::FormatT format,
MachineEndianness::EndiannessT end)
{
bool swapflag = (mEnd.Which() != end);
size_t actRead=0;
switch(format)
{
case Int8:
case Uint8:
actRead = Read(buffer, 1, len, stride);
break;
case Int16:
case Uint16:
actRead = Read(buffer, 2, len, stride);
if(swapflag) SwapBytes(buffer, 2, len);
break;
case Int32:
case Uint32:
case Float:
actRead = Read(buffer, 4, len, stride);
if(swapflag) SwapBytes(buffer, 4, len);
break;
case Double:
actRead = Read(buffer, 8, len, stride);
if(swapflag) SwapBytes(buffer, 8, len);
break;
default:
break;
}
return actRead;
}
size_t MultiFormatReader::Read(void* buffer, size_t size, size_t len, size_t stride)
{
size_t actRead = 0;
uint8_t* pWork = (uint8_t*) buffer;
if (stride > 1)
{
// There are gaps between consecutive samples,
// so do a scattered read
for (size_t n = 0; n < len; n++)
{
actRead += fread(&(pWork[n*size]), size, 1, mpFid);
// FIXME: TRAP_ERR fseek return in MultiFormatReader unchecked.
fseek(mpFid, (stride - 1) * size, SEEK_CUR);
}
}
else
{
// Just do a linear read
actRead = fread(buffer, size, len, mpFid);
}
return actRead;
}
void MultiFormatReader::SwapBytes(void* buffer, size_t size, size_t len)
{
uint8_t* pResBuffer = (uint8_t*) buffer;
uint8_t* pCurBuffer;
if (size > 8)
{
throw std::runtime_error("SwapBytes Exception: Format width exceeding 8 bytes.");
}
for (size_t i = 0; i < len; i++)
{
pCurBuffer = &(pResBuffer[i*size]);
memcpy(mSwapBuffer, &(pCurBuffer[0]), size);
for (size_t n = 0; n < size; n++)
{
pCurBuffer[n] = mSwapBuffer[size - n - 1];
}
}
}
| 21.93038 | 87 | 0.559596 | The-audafoss-crew |
c8377e40ccb5033b12e7ad8b89fcc22ed83230dd | 1,049 | cpp | C++ | HDUOJ/6674/math.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | HDUOJ/6674/math.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | HDUOJ/6674/math.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> mp; vector<int> vec;
int bitSum(int num) {
int ret = 0;
while (num > 0) {
ret += num % 10;
num /= 10;
}
return ret;
}
void factorize(int num) {
for (int i = 1; i * i <= num; i++) {
if (num % i != 0)
continue;
mp[i]++;
if (i * i != num)
mp[num / i]++;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int caseNum; cin >> caseNum;
while (caseNum--) {
mp.clear(); vec.clear();
int num; cin >> num;
factorize(num); factorize(bitSum(num));
for (const auto & p : mp)
if (p.second == 2)
vec.push_back(p.first);
sort(vec.begin(), vec.end());
int siz = vec.size();
cout << siz << '\n';
cout << vec[0];
for (int i = 1; i < siz; i++)
cout << ' ' << vec[i];
cout << '\n';
}
return 0;
} | 22.319149 | 48 | 0.419447 | codgician |
c838e79e53765085afe99d2cf7e6c8d52edf7237 | 7,502 | cpp | C++ | CubeEngine/EngineSrc/Scene/OctreeScene.cpp | tangziwen/Cube-Engine | c79b878dcc7e2e382f4463ca63519627d6220afd | [
"MIT"
] | 360 | 2015-01-26T08:15:01.000Z | 2021-07-11T16:30:58.000Z | CubeEngine/EngineSrc/Scene/OctreeScene.cpp | tangziwen/Cube-Engine | c79b878dcc7e2e382f4463ca63519627d6220afd | [
"MIT"
] | 6 | 2015-03-09T09:15:07.000Z | 2020-07-06T01:34:00.000Z | CubeEngine/EngineSrc/Scene/OctreeScene.cpp | tangziwen/CubeMiniGame | 90bffa66d4beba5fddc39fc642a8fb36703cf32d | [
"MIT"
] | 41 | 2015-03-10T03:17:46.000Z | 2021-07-13T06:26:26.000Z | #include "OctreeScene.h"
#include "../Interface/Drawable3D.h"
#include <algorithm>
#include "../base/Camera.h"
#include <cassert>
#include "3D/Primitive/CubePrimitive.h"
#include "Base/TAssert.h"
#define MAX_DEEP 5
namespace tzw {
static int g_nodeIndex = 0;
void OctreeNode::genId()
{
m_index = g_nodeIndex;
g_nodeIndex += 1;
TAssert(g_nodeIndex >=0, "error");
}
OctreeNode::OctreeNode()
{
for(int i =0;i<8;i++)
{
m_child[i] = nullptr;
}
genId();
}
OctreeScene::OctreeScene(): m_root(nullptr)
{
}
void OctreeScene::init(AABB range)
{
m_root = new OctreeNode();
m_root->aabb = range;
m_nodeList.push_back(m_root);
subDivide(m_root,1);
}
void OctreeScene::subDivide(OctreeNode *node, int level)
{
if(level> MAX_DEEP) {return;}
auto subAABBList = node->aabb.split8();
for(int i =0;i<8;i++)
{
auto child = new OctreeNode();
m_nodeList.push_back(child);
child->aabb = subAABBList[i];
node->m_child[i] = child;
subDivide(child,level + 1 );
}
}
std::vector<Drawable3D *> &OctreeScene::getVisibleList()
{
return m_visibleList;
}
bool OctreeScene::isInOctree(Drawable3D * obj)
{
return m_objSet.find(obj) != m_objSet.end();
}
OctreeNode* OctreeScene::getNodeByIndex(int index)
{
return m_nodeList[index];
}
void OctreeScene::addObj(Drawable3D *obj)
{
auto result = addObj_R(m_root,obj);
if(result)
{
m_objSet.insert(obj);
}else
{
//printf("can't add Object\n");
//assert(0);
}
}
bool OctreeScene::addObj_R(OctreeNode *node, Drawable3D *obj)
{
if(node->aabb.isCanCotain(obj->getAABB()))
{
if(!node->m_child[0])//terminal node
{
node->m_drawlist.push_back(obj);
obj->setOctNodeIndex(node->m_index);
return true;
}else {
for(int i =0;i<8;i++)
{
if(addObj_R(node->m_child[i],obj))
{
return true;
}
}
// the children can containt that ,so we only can put it in parent.
node->m_drawlist.push_back(obj);
obj->setOctNodeIndex(node->m_index);
return true;
}
}
return false;
}
void OctreeScene::removeObj(Drawable3D *obj)
{
removeObj_R(m_root,obj);
{
auto iter = m_objMap.find(obj);
if (iter != m_objMap.end())
{
m_objMap.erase(iter);
}
}
{
auto iter = m_objSet.find(obj);
if (iter != m_objSet.end())
{
m_objSet.erase(iter);
}
}
}
bool OctreeScene::removeObj_R(OctreeNode *node, Drawable3D *obj)
{
auto result = std::find(node->m_drawlist.begin(),node->m_drawlist.end(),obj);
if(result != node->m_drawlist.end())
{
node->m_drawlist.erase(result);
return true;
}else
{
if(!node->m_child[0]) return false;//terminal node.
for(int i =0;i<8;i++)
{
if(removeObj_R(node->m_child[i],obj))
{
return true;
}
}
return false;
}
}
bool OctreeScene::hitByRay_R(OctreeNode *node, const Ray &ray, vec3 &hitPoint)
{
vec3 result;
if(ray.intersectAABB(node->aabb,nullptr,result))
{
//check self
for(int i =0;i<node->m_drawlist.size();i++)
{
Drawable3D * obj = node->m_drawlist[i];
if(ray.intersectAABB(obj->getAABB(),nullptr,hitPoint))
{
return true;
}
}
//check sub
if(!node->m_child[0]) return false; // is terminal
for(int i = 0;i<8;i++)
{
if(hitByRay_R(node->m_child[i],ray,hitPoint))
{
return true;
}
}
return false;
}else
{
return false;
}
}
void OctreeScene::updateObj(Drawable3D *obj)
{
if(obj->getOctNodeIndex() >= 0)
{
auto node = getNodeByIndex(obj->getOctNodeIndex());
if(node->aabb.isCanCotain(obj->getAABB()))// no need to update;
{
return;
}
}
removeObj(obj);
addObj(obj);
}
bool OctreeScene::hitByRay(const Ray &ray, vec3 &hitPoint)
{
return hitByRay_R(m_root,ray,hitPoint);
}
void OctreeScene::cullingByCamera(Camera *camera, uint32_t renderStageFlag)
{
//clear visible List;
m_visibleList.clear();
cullingByCameraExtraFlag(camera, static_cast<uint32_t>(DrawableFlag::Drawable), renderStageFlag, m_visibleList);
}
void OctreeScene::cullingByCameraExtraFlag(Camera* camera, uint32_t drawableFlag, uint32_t renderStageFlag, std::vector<Drawable3D*>& resultList)
{
cullingByCameraFlag_R(m_root,camera, drawableFlag, renderStageFlag, resultList);
//auto test = [camera](const AABB& targetAABB){return !camera->isOutOfFrustum(targetAABB);};
//cullingImp_R(m_root,flags, &resultList,test);
}
void OctreeScene::getRange(std::vector<Drawable3D *> *list, uint32_t drawableFlag, uint32_t renderStageFlag, AABB aabb)
{
auto test = [&aabb](const AABB& targetAABB){vec3 noNeedVar; return aabb.isIntersect(targetAABB, noNeedVar);};
cullingImp_R(m_root,drawableFlag, renderStageFlag, list,test);
}
int OctreeScene::getAmount()
{
return getAmount_R(m_root);
}
int OctreeScene::getAmount_R(OctreeNode *node)
{
int the_size = node->m_drawlist.size();
if(!node->m_child[0]) return the_size;
for(int i =0;i<8;i++)
{
the_size += getAmount_R(node->m_child[i]);
}
return the_size;
}
static Camera * currentCamera = nullptr;
static int compare(const void * a, const void * b)
{
auto nodeA = (OctreeNode *)a;
auto nodeB = (OctreeNode *)b;
auto vA = nodeA->aabb.centre() - currentCamera->getPos();
auto vB = nodeB->aabb.centre() - currentCamera->getPos();
auto distA = fabs(vA.x) + fabs(vA.y) + fabs(vA.z);
auto distB = fabs(vB.x) + fabs(vB.y) + fabs(vB.z);
if(distA > distB)
{
return 1;
}
else if(fabs(distA - distB) < 0.00001)
{
return 0;
}else
{
return -1;
}
}
void OctreeScene::cullingByCameraFlag_R(OctreeNode* node, Camera* camera, uint32_t itemFlags, uint32_t renderStageFlag, std::vector<Drawable3D*>& resultList)
{
if(!camera->isOutOfFrustum(node->aabb))
{
for(int i=0;i<node->m_drawlist.size();i++)
{
Drawable3D * obj = node->m_drawlist[i];
if(!camera->isOutOfFrustum(obj->getAABB()))
{
if((obj->getDrawableFlag() & itemFlags) && (obj->getRenderStageFlag() & renderStageFlag))
{
resultList.push_back (obj);
}
}
}
if(!node->m_child[0]) return;//terminal node return directly
for(int i=0;i<8;i++)
{
cullingByCameraFlag_R(node->m_child[i],camera, itemFlags, renderStageFlag, resultList);
}
}
}
void OctreeScene::cullingImp_R(OctreeNode *node, uint32_t itemFlags, uint32_t renderStageFlag, std::vector<Drawable3D *> *list, const std::function<bool(const AABB&)>& testFunc)
{
if(testFunc(node->aabb))
{
//put self
for(auto drawObj : node->m_drawlist)
{
if((drawObj->getDrawableFlag() & itemFlags) && (drawObj->getRenderStageFlag() & renderStageFlag))
{
if(testFunc(drawObj->getAABB()))
{
list->push_back(drawObj);
}
}
}
//check sub
if(!node->m_child[0]) return;
for(int i =0;i<8;i++)
{
cullingImp_R(node->m_child[i], itemFlags, renderStageFlag, list, testFunc);
}
}
}
} // namespace tzw
| 24.278317 | 177 | 0.599573 | tangziwen |
c83a2442a7f35ab3791b047d5d6b5f076a5fbfd3 | 2,309 | cpp | C++ | src/structure/map_generation/mapCell.cpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | 18 | 2016-05-26T18:11:31.000Z | 2022-02-10T20:00:52.000Z | src/structure/map_generation/mapCell.cpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | null | null | null | src/structure/map_generation/mapCell.cpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | 2 | 2016-06-30T15:20:01.000Z | 2020-08-27T18:28:33.000Z | /// @file mapCell.cpp
/// @author Enrico Fraccaroli
/// @date Jan 06 2017
/// @copyright
/// Copyright (c) 2017 Enrico Fraccaroli <enrico.fraccaroli@gmail.com>
/// Permission is hereby granted, free of charge, to any person obtaining a
/// copy of this software and associated documentation files (the "Software"),
/// to deal in the Software without restriction, including without limitation
/// the rights to use, copy, modify, merge, publish, distribute, sublicense,
/// and/or sell copies of the Software, and to permit persons to whom the
/// Software is furnished to do so, subject to the following conditions:
/// The above copyright notice and this permission notice shall be included
/// in all copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
/// DEALINGS IN THE SOFTWARE.
#include "mapCell.hpp"
#include "logger.hpp"
MapCell::MapCell() :
room(),
coordinates(),
terrain(),
neighbours(),
flags(),
liquidContent()
{
// Nothing to do.
}
bool MapCell::addNeighbour(const Direction & direction,
MapCell * mapCell)
{
if (mapCell == nullptr)
{
return false;
}
return neighbours.insert(std::make_pair(direction, mapCell)).second;
}
MapCell * MapCell::findLowestNearbyCell()
{
MapCell * selectedCell = this;
for (auto neighbour : neighbours)
{
if (neighbour.second->coordinates.z < selectedCell->coordinates.z)
{
selectedCell = neighbour.second;
}
}
return selectedCell;
}
std::string MapCell::getTile() const
{
if (liquidContent.first != nullptr)
{
return "w";
}
if (HasFlag(flags, RoomFlags::SpawnTree))
{
return "t";
}
return terrain->symbol;
}
bool MapCell::operator==(const MapCell & other) const
{
return (coordinates == other.coordinates);
}
| 30.381579 | 79 | 0.67735 | Galfurian |
c83ca41a3955a9ed16a737513eccec82f1802028 | 25,182 | cpp | C++ | libraries/blockchain/market_engine.cpp | dacsunlimited/dacplay | 91e354c951cf137617f2593c895e009866923bed | [
"Unlicense"
] | 20 | 2015-03-30T23:41:06.000Z | 2017-03-30T02:20:14.000Z | libraries/blockchain/market_engine.cpp | dacsunlimited/dacplay | 91e354c951cf137617f2593c895e009866923bed | [
"Unlicense"
] | 112 | 2015-01-01T13:45:59.000Z | 2015-08-05T09:16:10.000Z | libraries/blockchain/market_engine.cpp | dacsunlimited/dacplay | 91e354c951cf137617f2593c895e009866923bed | [
"Unlicense"
] | 5 | 2015-06-06T08:09:50.000Z | 2017-12-13T07:34:15.000Z | #include <bts/blockchain/exceptions.hpp>
#include <bts/blockchain/market_engine.hpp>
#include <fc/real128.hpp>
#include <algorithm>
namespace bts { namespace blockchain { namespace detail {
#define MARKET_ENGINE_PASS_PROCESS_MARGIN_CALLS 0
#define MARKET_ENGINE_PASS_PROCESS_EXPIRED_COVERS 1
#define MARKET_ENGINE_PASS_PROCESS_ASK_ORDERS 2
#define MARKET_ENGINE_PASS_COUNT 3
market_engine::market_engine( const pending_chain_state_ptr ps, const chain_database_impl& cdi )
:_pending_state(ps),_db_impl(cdi)
{
_pending_state = std::make_shared<pending_chain_state>( ps );
_prior_state = ps;
//_eval_state._pending_state = _pending_state;
}
bool market_engine::execute( asset_id_type quote_id, asset_id_type base_id, const fc::time_point_sec timestamp )
{
try
{
_quote_id = quote_id;
_base_id = base_id;
oasset_record quote_asset = _pending_state->get_asset_record( _quote_id );
oasset_record base_asset = _pending_state->get_asset_record( _base_id );
FC_ASSERT( quote_asset.valid() && base_asset.valid() );
FC_ASSERT( !quote_asset->flag_is_active( asset_record::halted_markets ) );
FC_ASSERT( !base_asset->flag_is_active( asset_record::halted_markets ) );
// The order book is sorted from low to high price. So to get the last item (highest bid),
// we need to go to the first item in the next market class and then back up one
const price current_pair = price( 0, quote_id, base_id );
const price next_pair = (base_id+1 == quote_id) ? price( 0, quote_id+1, 0 ) : price( 0, quote_id, base_id+1 );
_bid_itr = _db_impl._bid_db.lower_bound( market_index_key( next_pair ) );
_ask_itr = _db_impl._ask_db.lower_bound( market_index_key( price( 0, quote_id, base_id ) ) );
int last_orders_filled = -1;
asset trading_volume(0, base_id);
price opening_price, closing_price, highest_price, lowest_price;
if( !_ask_itr.valid() ) _ask_itr = _db_impl._ask_db.begin();
//
// following logic depends on the internals of cached_level_map class.
// if lower_bound() argument is past the end of the collection,
// then result will point to end() which has valid() == false
//
// so we need to decrement the returned iterator, but
// decrement operator may be undefined for end(), so we
// special-case the result.
//
// one day we should write a greatest_element_below() method
// for our DB class to implement the logic we're doing
// directly here
//
// decrementing begin() OTOH is well-defined and returns
// end() which is invalid, thus overflow of --itr here is
// ok as long as we check valid() later
//
if( _bid_itr.valid() ) --_bid_itr;
else _bid_itr = _db_impl._bid_db.last();
// Market issued assets cannot match until the first time there is a median feed; assume feed price base id 0
if( quote_asset->is_market_issued() && base_asset->id == 0 )
{
_feed_price = _db_impl.self->get_active_feed_price( _quote_id );
const omarket_status market_stat = _pending_state->get_market_status( _quote_id, _base_id );
if( (!market_stat.valid() || !market_stat->last_valid_feed_price.valid()) && !_feed_price.valid() )
FC_CAPTURE_AND_THROW( insufficient_feeds, (quote_id)(base_id) );
}
/*
if( _feed_price.valid() )
_short_at_limit_itr = std::set< pair<price,market_index_key> >::reverse_iterator(
_db_impl._short_limit_index.lower_bound(
std::make_pair( *_feed_price, market_index_key( current_pair ))
));
*/
_current_bid.reset();
for( _current_pass=0; _current_pass<MARKET_ENGINE_PASS_COUNT; _current_pass++ )
{
_current_ask.reset();
while( true )
{
if( (!_current_bid.valid()) || (_current_bid->get_balance().amount <= 0) )
{
ilog("getting next bid");
get_next_bid();
if( (!_current_bid.valid()) )
{
ilog("market engine terminating due to no more bids");
break;
}
idump( (_current_bid) );
}
if( (!_current_ask.valid()) || (_current_ask->get_balance().amount <= 0) )
{
ilog("getting next ask");
get_next_ask();
if( (!_current_ask.valid()) )
{
ilog("market engine terminating due to no more asks");
break;
}
idump( (_current_ask) );
}
// Make sure that at least one order was matched every time we enter the loop
FC_ASSERT( _orders_filled != last_orders_filled, "We appear caught in an order matching loop!" );
last_orders_filled = _orders_filled;
// Initialize the market transaction
market_transaction mtrx;
mtrx.bid_owner = _current_bid->get_owner();
mtrx.ask_owner = _current_ask->get_owner();
if( _feed_price )
{
mtrx.bid_price = _current_bid->get_price( *_feed_price );
mtrx.ask_price = _current_ask->get_price( *_feed_price );
}
else
{
mtrx.bid_price = _current_bid->get_price();
mtrx.ask_price = _current_ask->get_price();
}
mtrx.bid_type = _current_bid->type;
mtrx.ask_type = _current_ask->type;
if( mtrx.bid_price < mtrx.ask_price )
{
wlog( "bid_price ${b} < ask_price ${a}; exit market loop", ("b",mtrx.bid_price)("a",mtrx.ask_price) );
break;
}
if( _current_ask->type == ask_order && _current_bid->type == bid_order )
{
const asset bid_quantity_xts = _current_bid->get_quantity( _feed_price ? *_feed_price : price() );
const asset ask_quantity_xts = _current_ask->get_quantity( _feed_price ? *_feed_price : price() );
const asset quantity_xts = std::min( bid_quantity_xts, ask_quantity_xts );
// Everyone gets the price they asked for
mtrx.ask_received = quantity_xts * mtrx.ask_price;
mtrx.bid_paid = quantity_xts * mtrx.bid_price;
mtrx.ask_paid = quantity_xts;
mtrx.bid_received = quantity_xts;
// Handle rounding errors
if( quantity_xts == bid_quantity_xts )
mtrx.bid_paid = _current_bid->get_balance();
if( quantity_xts == ask_quantity_xts )
mtrx.ask_paid = _current_ask->get_balance();
mtrx.quote_fees = mtrx.bid_paid - mtrx.ask_received;
pay_current_bid( mtrx, *base_asset, *quote_asset );
pay_current_ask( mtrx, *base_asset, *quote_asset );
}
push_market_transaction( mtrx );
quote_asset->collected_fees += mtrx.quote_fees.amount;
base_asset->collected_fees += mtrx.base_fees.amount;
if( mtrx.ask_received.asset_id == 0 )
trading_volume += mtrx.ask_received;
else if( mtrx.bid_received.asset_id == 0 )
trading_volume += mtrx.bid_received;
if( opening_price == price() )
opening_price = mtrx.bid_price;
closing_price = mtrx.bid_price;
//
// Remark: only prices of matched orders are used to update market history
//
// Because of prioritization, we need the second comparison
// in the following if statements. Ask-side orders are
// only sorted by price within a single pass.
//
if( highest_price == price() || highest_price < mtrx.bid_price)
highest_price = mtrx.bid_price;
// TODO check here: store lowest ask price or lowest bid price?
if( lowest_price == price() || lowest_price > mtrx.ask_price)
lowest_price = mtrx.ask_price;
}
}
// update any fees collected
_pending_state->store_asset_record( *quote_asset );
_pending_state->store_asset_record( *base_asset );
// Update market status and market history
{
omarket_status market_stat = _pending_state->get_market_status( _quote_id, _base_id );
if( !market_stat.valid() ) market_stat = market_status( _quote_id, _base_id );
market_stat->last_error.reset();
_pending_state->store_market_status( *market_stat );
// Remark: only prices of matched orders be updated to market history
update_market_history( trading_volume, highest_price, lowest_price, opening_price, closing_price, timestamp );
}
//_eval_state.update_delegate_votes();
_pending_state->apply_changes();
return true;
}
catch( const fc::exception& e )
{
wlog( "error executing market ${quote} / ${base}\n ${e}", ("quote",quote_id)("base",base_id)("e",e.to_detail_string()) );
omarket_status market_stat = _prior_state->get_market_status( _quote_id, _base_id );
if( !market_stat.valid() ) market_stat = market_status( _quote_id, _base_id );
market_stat->last_error = e;
_prior_state->store_market_status( *market_stat );
}
return false;
} // execute(...)
void market_engine::push_market_transaction( const market_transaction& mtrx )
{ try {
// If not an automatic market cancel
if( mtrx.ask_paid.amount != 0
|| mtrx.ask_received.amount != 0
|| mtrx.bid_received.asset_id != 0
|| mtrx.bid_paid.amount != 0 )
{
FC_ASSERT( mtrx.bid_paid.amount >= 0 );
FC_ASSERT( mtrx.ask_paid.amount >= 0 );
FC_ASSERT( mtrx.bid_received.amount >= 0 );
FC_ASSERT( mtrx.ask_received.amount>= 0 );
FC_ASSERT( mtrx.bid_paid >= mtrx.ask_received );
FC_ASSERT( mtrx.ask_paid >= mtrx.bid_received );
FC_ASSERT( mtrx.quote_fees.amount >= 0 );
FC_ASSERT( mtrx.base_fees.amount >= 0 );
}
_market_transactions.push_back(mtrx);
} FC_CAPTURE_AND_RETHROW( (mtrx) ) }
void market_engine::pay_current_bid( market_transaction& mtrx, asset_record& base_asset, asset_record& quote_asset )
{ try {
FC_ASSERT( _current_bid->type == bid_order );
FC_ASSERT( mtrx.bid_type == bid_order );
_current_bid->state.balance -= mtrx.bid_paid.amount;
FC_ASSERT( _current_bid->state.balance >= 0 );
FC_ASSERT( base_asset.address_is_whitelisted( mtrx.bid_owner ) );
auto bid_payout = _pending_state->get_balance_record(
withdraw_condition( withdraw_with_signature(mtrx.bid_owner), _base_id ).get_address() );
if( !bid_payout )
bid_payout = balance_record( mtrx.bid_owner, asset(0,_base_id), 0 );
share_type issuer_fee = 0;
if( base_asset.market_fee_rate > 0 )
{
FC_ASSERT( base_asset.market_fee_rate <= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE );
issuer_fee = mtrx.bid_received.amount * base_asset.market_fee_rate;
issuer_fee /= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE;
}
mtrx.base_fees.amount += issuer_fee;
mtrx.bid_received.amount -= issuer_fee;
bid_payout->balance += mtrx.bid_received.amount;
bid_payout->last_update = _pending_state->now();
bid_payout->deposit_date = _pending_state->now();
_pending_state->store_balance_record( *bid_payout );
// if the balance is less than 1 XTS then it gets collected as fees.
if( (_current_bid->get_quote_quantity() * mtrx.bid_price).amount == 0 )
{
mtrx.quote_fees.amount += _current_bid->state.balance;
_current_bid->state.balance = 0;
}
_pending_state->store_bid_record( _current_bid->market_index, _current_bid->state );
} FC_CAPTURE_AND_RETHROW( (mtrx) ) }
void market_engine::pay_current_ask( market_transaction& mtrx, asset_record& base_asset, asset_record& quote_asset )
{ try {
FC_ASSERT( _current_ask->type == ask_order );
FC_ASSERT( mtrx.ask_type == ask_order );
_current_ask->state.balance -= mtrx.ask_paid.amount;
FC_ASSERT( _current_ask->state.balance >= 0, "balance: ${b}", ("b",_current_ask->state.balance) );
FC_ASSERT( quote_asset.address_is_whitelisted( mtrx.ask_owner ) );
auto ask_balance_address = withdraw_condition( withdraw_with_signature(mtrx.ask_owner), _quote_id ).get_address();
auto ask_payout = _pending_state->get_balance_record( ask_balance_address );
if( !ask_payout )
ask_payout = balance_record( mtrx.ask_owner, asset(0,_quote_id), 0 );
share_type issuer_fee = 0;
if( quote_asset.market_fee_rate > 0 )
{
FC_ASSERT( quote_asset.market_fee_rate <= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE );
issuer_fee = mtrx.ask_received.amount * quote_asset.market_fee_rate;
issuer_fee /= BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE;
}
mtrx.quote_fees.amount += issuer_fee;
mtrx.ask_received.amount -= issuer_fee;
ask_payout->balance += mtrx.ask_received.amount;
ask_payout->last_update = _pending_state->now();
ask_payout->deposit_date = _pending_state->now();
_pending_state->store_balance_record( *ask_payout );
// if the balance is less than 1 XTS * PRICE < .001 USD XTS goes to fees
if( (_current_ask->get_quantity() * mtrx.ask_price).amount == 0 )
{
mtrx.base_fees.amount += _current_ask->state.balance;
_current_ask->state.balance = 0;
}
_pending_state->store_ask_record( _current_ask->market_index, _current_ask->state );
} FC_CAPTURE_AND_RETHROW( (mtrx) ) } // pay_current_ask
/**
* if there are bids above feed price, take the max of the two
* if there are shorts at the feed take the next short
* if there are bids with prices above the limit of the current short they should take priority
* - shorts need to be ordered by limit first, then interest rate *WHEN* the limit is
* lower than the feed price.
*/
bool market_engine::get_next_bid()
{ try {
if( _current_bid && _current_bid->get_quantity().amount > 0 )
return _current_bid.valid();
++_orders_filled;
_current_bid.reset();
optional<market_order> bid;
if( _bid_itr.valid() )
{
market_order abs_bid( bid_order, _bid_itr.key(), _bid_itr.value() );
if( abs_bid.get_price().quote_asset_id == _quote_id && abs_bid.get_price().base_asset_id == _base_id )
{
bid = abs_bid;
}
}
if( !_feed_price )
{
_current_bid = bid;
--_bid_itr;
return _current_bid.valid();
}
/*
// if bids are less than feed price, then we can consider shorts
if( !bid || (bid->get_price(*_feed_price) < *_feed_price) )
{
// first consider shorts at the feed price
if( _short_at_feed_itr != _db_impl._shorts_at_feed.rend() )
{
// if we skipped past the range for our market, note that we reached the end
if( _short_at_feed_itr->order_price.quote_asset_id != _quote_id ||
_short_at_feed_itr->order_price.base_asset_id != _base_id )
{
_short_at_feed_itr = _db_impl._shorts_at_feed.rend();
}
else // fetch the order
{
optional<order_record> oshort = _pending_state->get_short_record( *_short_at_feed_itr );
FC_ASSERT( oshort.valid() );
bid = market_order( short_order, *_short_at_feed_itr, *oshort );
_current_bid = bid;
++_short_at_feed_itr;
return _current_bid.valid();
}
}
else
{
wlog( "feed at short itr is null" );
}
// if we have a short with a limit below the feed
if( _short_at_limit_itr != _db_impl._short_limit_index.rend() )
{
//wdump((*_short_at_limit_itr) );
if( _short_at_limit_itr->first.quote_asset_id != _quote_id ||
_short_at_limit_itr->first.base_asset_id != _base_id )
{
_short_at_limit_itr = _db_impl._short_limit_index.rend();
}
else
{
// if the limit price is better than a current bid
if( !bid || (_short_at_limit_itr->first > bid->get_price(*_feed_price)) )
{
// then the short is game.
optional<order_record> oshort = _pending_state->get_short_record( _short_at_limit_itr->second );
FC_ASSERT( oshort );
bid = market_order( short_order, _short_at_limit_itr->second, *oshort );
_current_bid = bid;
++_short_at_limit_itr;
return _current_bid.valid();
}
}
}
// then consider shorts by limit
}
*/
if( bid )
{
_current_bid = bid;
switch( uint8_t(bid->type) )
{
case bid_order:
--_bid_itr;
break;
default:
FC_ASSERT( false, "Unknown Bid Type" );
}
}
return _current_bid.valid();
} FC_CAPTURE_AND_RETHROW() }
bool market_engine::get_next_ask()
{ try {
if( _current_ask && _current_ask->state.balance > 0 )
return _current_ask.valid();
_current_ask.reset();
++_orders_filled;
switch( _current_pass )
{
case MARKET_ENGINE_PASS_PROCESS_ASK_ORDERS:
return get_next_ask_order();
default:
FC_ASSERT( false, "_current_pass value is unknown" );
}
return false;
} FC_CAPTURE_AND_RETHROW()
}
bool market_engine::get_next_ask_order()
{
/**
* Process asks.
*/
if( !_ask_itr.valid() )
return false;
market_order abs_ask = market_order( ask_order, _ask_itr.key(), _ask_itr.value() );
if( (abs_ask.get_price().quote_asset_id != _quote_id) || (abs_ask.get_price().base_asset_id != _base_id) )
return false;
_current_ask = abs_ask;
++_ask_itr;
return true;
}
/**
* This method should not affect market execution or validation and
* is for historical purposes only.
*/
void market_engine::update_market_history( const asset& trading_volume,
const price& highest_price,
const price& lowest_price,
const price& opening_price,
const price& closing_price,
const fc::time_point_sec timestamp )
{
// Remark: only prices of matched orders be updated to market history
if( trading_volume.amount > 0 )
{
market_history_key key(_quote_id, _base_id, market_history_key::each_block, _db_impl._head_block_header.timestamp);
market_history_record new_record(highest_price,
lowest_price,
opening_price,
closing_price,
trading_volume.amount);
//LevelDB iterators are dumb and don't support proper past-the-end semantics.
auto last_key_itr = _db_impl._market_history_db.lower_bound(key);
if( !last_key_itr.valid() )
last_key_itr = _db_impl._market_history_db.last();
else
--last_key_itr;
key.timestamp = timestamp;
//Unless the previous record for this market is the same as ours...
// TODO check here: the previous commit checks for volume and prices change here,
// I replaced them with key comparison, but looks odd as well.
// maybe need to remove the judgements at all? since volume info is
// always needed to be updated to market history,
// even if prices and volumes are same to last block.
if( (!(last_key_itr.valid()
&& last_key_itr.key() == key)) )
{
//...add a new entry to the history table.
_pending_state->market_history[key] = new_record;
}
fc::time_point_sec start_of_this_hour = timestamp - (timestamp.sec_since_epoch() % (60*60));
market_history_key old_key(_quote_id, _base_id, market_history_key::each_hour, start_of_this_hour);
if( auto opt = _db_impl._market_history_db.fetch_optional(old_key) )
{
auto old_record = *opt;
old_record.volume += new_record.volume;
old_record.closing_price = new_record.closing_price;
if( new_record.highest_bid > old_record.highest_bid || new_record.lowest_ask < old_record.lowest_ask )
{
old_record.highest_bid = std::max(new_record.highest_bid, old_record.highest_bid);
old_record.lowest_ask = std::min(new_record.lowest_ask, old_record.lowest_ask);
}
// always update old data since volume changed
_pending_state->market_history[old_key] = old_record;
}
else
_pending_state->market_history[old_key] = new_record;
fc::time_point_sec start_of_this_day = timestamp - (timestamp.sec_since_epoch() % (60*60*24));
old_key = market_history_key(_quote_id, _base_id, market_history_key::each_day, start_of_this_day);
if( auto opt = _db_impl._market_history_db.fetch_optional(old_key) )
{
auto old_record = *opt;
old_record.volume += new_record.volume;
old_record.closing_price = new_record.closing_price;
if( new_record.highest_bid > old_record.highest_bid || new_record.lowest_ask < old_record.lowest_ask )
{
old_record.highest_bid = std::max(new_record.highest_bid, old_record.highest_bid);
old_record.lowest_ask = std::min(new_record.lowest_ask, old_record.lowest_ask);
}
// always update old data since volume changed
_pending_state->market_history[old_key] = old_record;
}
else
_pending_state->market_history[old_key] = new_record;
}
}
asset market_engine::get_interest_paid(const asset& total_amount_paid, const price& apr, uint32_t age_seconds)
{
// TOTAL_PAID = DELTA_PRINCIPLE + DELTA_PRINCIPLE * APR * PERCENT_OF_YEAR
// DELTA_PRINCIPLE = TOTAL_PAID / (1 + APR*PERCENT_OF_YEAR)
// INTEREST_PAID = TOTAL_PAID - DELTA_PRINCIPLE
fc::real128 total_paid( total_amount_paid.amount );
fc::real128 apr_n( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) * apr).amount );
fc::real128 apr_d( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) ).amount );
fc::real128 iapr = apr_n / apr_d;
fc::real128 age_sec(age_seconds);
fc::real128 sec_per_year(365 * 24 * 60 * 60);
fc::real128 percent_of_year = age_sec / sec_per_year;
fc::real128 delta_principle = total_paid / ( fc::real128(1) + iapr * percent_of_year );
fc::real128 interest_paid = total_paid - delta_principle;
return asset( interest_paid.to_uint64(), total_amount_paid.asset_id );
}
asset market_engine::get_interest_owed(const asset& principle, const price& apr, uint32_t age_seconds)
{
// INTEREST_OWED = TOTAL_PRINCIPLE * APR * PERCENT_OF_YEAR
fc::real128 total_principle( principle.amount );
fc::real128 apr_n( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) * apr).amount );
fc::real128 apr_d( (asset( BTS_BLOCKCHAIN_MAX_SHARES, apr.base_asset_id ) ).amount );
fc::real128 iapr = apr_n / apr_d;
fc::real128 age_sec(age_seconds);
fc::real128 sec_per_year(365 * 24 * 60 * 60);
fc::real128 percent_of_year = age_sec / sec_per_year;
fc::real128 interest_owed = total_principle * iapr * percent_of_year;
return asset( interest_owed.to_uint64(), principle.asset_id );
}
} } } // end namespace bts::blockchain::detail
| 42.75382 | 129 | 0.599396 | dacsunlimited |
c83cc9d2c7defdfc6ce9001efb4d6a872a8693f3 | 2,312 | cpp | C++ | lib/Runtime/Library/JavascriptSimdUint8x16.cpp | satheeshravi/ChakraCore | 3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5 | [
"MIT"
] | 1 | 2021-11-07T18:56:21.000Z | 2021-11-07T18:56:21.000Z | lib/Runtime/Library/JavascriptSimdUint8x16.cpp | MaxMood96/ChakraCore | 9d9fea268ce1ae6c00873fd966a6a2be048f3455 | [
"MIT"
] | null | null | null | lib/Runtime/Library/JavascriptSimdUint8x16.cpp | MaxMood96/ChakraCore | 9d9fea268ce1ae6c00873fd966a6a2be048f3455 | [
"MIT"
] | 1 | 2021-09-04T23:26:57.000Z | 2021-09-04T23:26:57.000Z | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeLibraryPch.h"
namespace Js
{
JavascriptSIMDUint8x16::JavascriptSIMDUint8x16(SIMDValue *val, StaticType *type) : JavascriptSIMDType(val, type)
{
Assert(type->GetTypeId() == TypeIds_SIMDUint8x16);
}
JavascriptSIMDUint8x16* JavascriptSIMDUint8x16::New(SIMDValue *val, ScriptContext* requestContext)
{
return (JavascriptSIMDUint8x16 *)AllocatorNew(Recycler, requestContext->GetRecycler(), JavascriptSIMDUint8x16, val, requestContext->GetLibrary()->GetSIMDUint8x16TypeStatic());
}
bool JavascriptSIMDUint8x16::Is(Var instance)
{
return JavascriptOperators::GetTypeId(instance) == TypeIds_SIMDUint8x16;
}
JavascriptSIMDUint8x16* JavascriptSIMDUint8x16::FromVar(Var aValue)
{
Assert(aValue);
AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptSIMDUint8x16'");
return reinterpret_cast<JavascriptSIMDUint8x16 *>(aValue);
}
Var JavascriptSIMDUint8x16::CallToLocaleString(RecyclableObject& obj, ScriptContext& requestContext, SIMDValue simdValue,
const Var* args, uint numArgs, CallInfo callInfo)
{
char16 *typeString = _u("SIMD.Uint8x16(");
return JavascriptSIMDObject::FromVar(&obj)->ToLocaleString<uint8, 16>(args, numArgs, typeString,
simdValue.u8, &callInfo, &requestContext);
}
RecyclableObject * JavascriptSIMDUint8x16::CloneToScriptContext(ScriptContext* requestContext)
{
return JavascriptSIMDUint8x16::New(&value, requestContext);
}
const char16* JavascriptSIMDUint8x16::GetFullBuiltinName(char16** aBuffer, const char16* name)
{
Assert(aBuffer && *aBuffer);
swprintf_s(*aBuffer, SIMD_STRING_BUFFER_MAX, _u("SIMD.Uint8x16.%s"), name);
return *aBuffer;
}
Var JavascriptSIMDUint8x16::Copy(ScriptContext* requestContext)
{
return JavascriptSIMDUint8x16::New(&this->value, requestContext);
}
}
| 39.862069 | 183 | 0.651817 | satheeshravi |
c83d4c60f8f57461b4773c8648aa5dfa7dbb9dcb | 103 | hpp | C++ | include/vpp/util/span.hpp | nyorain/vpp | ccffafa0b59baa633df779274d7743f169d61c06 | [
"BSL-1.0"
] | 308 | 2016-02-23T11:59:20.000Z | 2022-03-14T18:40:24.000Z | include/vpp/util/span.hpp | nyorain/vpp | ccffafa0b59baa633df779274d7743f169d61c06 | [
"BSL-1.0"
] | 11 | 2017-01-21T17:33:13.000Z | 2020-08-17T10:33:42.000Z | include/vpp/util/span.hpp | nyorain/vpp | ccffafa0b59baa633df779274d7743f169d61c06 | [
"BSL-1.0"
] | 11 | 2016-02-23T10:35:08.000Z | 2021-12-18T16:15:39.000Z | #pragma once
#include <vpp/fwd.hpp>
#include <vkpp/span.hpp>
namespace vpp {
// using nytl::Span;
}
| 11.444444 | 24 | 0.669903 | nyorain |
c83ddcd9a1023b540706630f941b58e1fae0e4a1 | 839 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/metaparse/v1/cpp98/impl/sequence_impl.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | ReactNativeFrontend/ios/Pods/boost/boost/metaparse/v1/cpp98/impl/sequence_impl.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | ReactNativeFrontend/ios/Pods/boost/boost/metaparse/v1/cpp98/impl/sequence_impl.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | #ifndef BOOST_METAPARSE_V1_CPP98_IMPL_SEQUENCE_IMPL_HPP
#define BOOST_METAPARSE_V1_CPP98_IMPL_SEQUENCE_IMPL_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/metaparse/v1/impl/apply_parser.hpp>
#include <boost/metaparse/v1/accept.hpp>
#include <boost/mpl/deque.hpp>
#include <boost/mpl/fold.hpp>
namespace boost
{
namespace metaparse
{
namespace v1
{
namespace impl
{
template <class Ps, class S, class Pos>
struct sequence_impl :
boost::mpl::fold<
Ps,
accept<boost::mpl::deque<>, S, Pos>,
apply_parser
>
{};
}
}
}
}
#endif
| 22.078947 | 61 | 0.646007 | Harshitha91 |
c8405e9329e11cd8f3c2af2e59d6c59b29fab7c3 | 5,779 | hpp | C++ | AqooleEngine/src/main/cpp/boost/boost/geometry/strategy/cartesian/side_robust.hpp | kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine- | 72c8f34b6b6d507319069e681ff8c5008337b7c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | AqooleEngine/src/main/cpp/boost/boost/geometry/strategy/cartesian/side_robust.hpp | kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine- | 72c8f34b6b6d507319069e681ff8c5008337b7c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | AqooleEngine/src/main/cpp/boost/boost/geometry/strategy/cartesian/side_robust.hpp | kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine- | 72c8f34b6b6d507319069e681ff8c5008337b7c6 | [
"Apache-2.0",
"MIT"
] | null | null | null | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.
// Contributed and/or modified by Tinko Bartels,
// as part of Google Summer of Code 2019 program.
// This file was modified by Oracle on 2021.
// Modifications copyright (c) 2021, Oracle and/or its affiliates.
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_ROBUST_HPP
#define BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_ROBUST_HPP
#include <boost/geometry/core/config.hpp>
#include <boost/geometry/strategy/cartesian/side_non_robust.hpp>
#include <boost/geometry/strategies/side.hpp>
#include <boost/geometry/util/select_most_precise.hpp>
#include <boost/geometry/util/select_calculation_type.hpp>
#include <boost/geometry/util/precise_math.hpp>
#include <boost/geometry/util/math.hpp>
namespace boost { namespace geometry
{
namespace strategy { namespace side
{
struct epsilon_equals_policy
{
public:
template <typename Policy, typename T1, typename T2>
static bool apply(T1 const& a, T2 const& b, Policy const& policy)
{
return boost::geometry::math::detail::equals_by_policy(a, b, policy);
}
};
struct fp_equals_policy
{
public:
template <typename Policy, typename T1, typename T2>
static bool apply(T1 const& a, T2 const& b, Policy const&)
{
return a == b;
}
};
/*!
\brief Adaptive precision predicate to check at which side of a segment a point lies:
left of segment (>0), right of segment (< 0), on segment (0).
\ingroup strategies
\tparam CalculationType \tparam_calculation (numeric_limits<ct>::epsilon() and numeric_limits<ct>::digits must be supported for calculation type ct)
\tparam Robustness std::size_t value from 0 (fastest) to 3 (default, guarantees correct results).
\details This predicate determines at which side of a segment a point lies using an algorithm that is adapted from orient2d as described in "Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates" by Jonathan Richard Shewchuk ( https://dl.acm.org/citation.cfm?doid=237218.237337 ). More information and copies of the paper can also be found at https://www.cs.cmu.edu/~quake/robust.html . It is designed to be adaptive in the sense that it should be fast for inputs that lead to correct results with plain float operations but robust for inputs that require higher precision arithmetics.
*/
template
<
typename CalculationType = void,
typename EqualsPolicy = epsilon_equals_policy,
std::size_t Robustness = 3
>
struct side_robust
{
template <typename CT>
struct epsilon_policy
{
using Policy = boost::geometry::math::detail::equals_factor_policy<CT>;
epsilon_policy() {}
template <typename Type>
epsilon_policy(Type const& a, Type const& b, Type const& c, Type const& d)
: m_policy(a, b, c, d)
{}
Policy m_policy;
public:
template <typename T1, typename T2>
bool apply(T1 a, T2 b) const
{
return EqualsPolicy::apply(a, b, m_policy);
}
};
public:
typedef cartesian_tag cs_tag;
//! \brief Computes the sign of the CCW triangle p1, p2, p
template
<
typename PromotedType,
typename P1,
typename P2,
typename P,
typename EpsPolicyInternal,
std::enable_if_t<std::is_fundamental<PromotedType>::value, int> = 0
>
static inline PromotedType side_value(P1 const& p1,
P2 const& p2,
P const& p,
EpsPolicyInternal& eps_policy)
{
using vec2d = ::boost::geometry::detail::precise_math::vec2d<PromotedType>;
vec2d pa;
pa.x = get<0>(p1);
pa.y = get<1>(p1);
vec2d pb;
pb.x = get<0>(p2);
pb.y = get<1>(p2);
vec2d pc;
pc.x = get<0>(p);
pc.y = get<1>(p);
return ::boost::geometry::detail::precise_math::orient2d
<PromotedType, Robustness>(pa, pb, pc, eps_policy);
}
template
<
typename PromotedType,
typename P1,
typename P2,
typename P,
typename EpsPolicyInternal,
std::enable_if_t<!std::is_fundamental<PromotedType>::value, int> = 0
>
static inline auto side_value(P1 const& p1, P2 const& p2, P const& p,
EpsPolicyInternal&)
{
return side_non_robust<>::apply(p1, p2, p);
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
template
<
typename P1,
typename P2,
typename P
>
static inline int apply(P1 const& p1, P2 const& p2, P const& p)
{
using coordinate_type = typename select_calculation_type_alt
<
CalculationType,
P1,
P2,
P
>::type;
using promoted_type = typename select_most_precise
<
coordinate_type,
double
>::type;
epsilon_policy<promoted_type> epsp;
promoted_type sv = side_value<promoted_type>(p1, p2, p, epsp);
promoted_type const zero = promoted_type();
return epsp.apply(sv, zero) ? 0
: sv > zero ? 1
: -1;
}
#endif
};
}} // namespace strategy::side
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_ROBUST_HPP
| 31.069892 | 613 | 0.64596 | kodai731 |
c840ed385ca7bb408ee42bb8d459aaff55f661cb | 8,531 | cpp | C++ | src/paraminspector.cpp | Sirithang/eitri | 8f72061c52e0b2b95ed9ff0695c3c3b718200769 | [
"MIT"
] | 4 | 2015-06-10T04:05:19.000Z | 2018-01-13T14:10:55.000Z | src/paraminspector.cpp | Sirithang/eitri | 8f72061c52e0b2b95ed9ff0695c3c3b718200769 | [
"MIT"
] | null | null | null | src/paraminspector.cpp | Sirithang/eitri | 8f72061c52e0b2b95ed9ff0695c3c3b718200769 | [
"MIT"
] | 1 | 2019-03-11T19:22:13.000Z | 2019-03-11T19:22:13.000Z | #include "paraminspector.h"
#include "graphcanvas.h"
#include "eitri.h"
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>
#include <QColorDialog>
#include <QFrame>
#include <QLineEdit>
//---helper func
void setButtonToColor(QPushButton* button, QColor color)
{
QString s("background: #"
+ QString(color.red() < 16? "0" : "") + QString::number(color.red(),16)
+ QString(color.green() < 16? "0" : "") + QString::number(color.green(),16)
+ QString(color.blue() < 16? "0" : "") + QString::number(color.blue(),16) + ";");
button->setStyleSheet(s);
button->update();
}
//----------
ParamInspector::ParamInspector(QWidget *parent) :
QWidget(parent)
{
layout = new QVBoxLayout();
setLayout(layout);
}
void ParamInspector::setGraphItem(NodeBox *b)
{
while(_instanciated.count() > 0)
{
delete _instanciated.back();
_instanciated.removeLast();
}
_opBox = b;
if(b)
{
eitri_NodeInstance* inst = &b->owner->g->nodes[b->op];
eitri_Node* op = &eitri_gOpsDB.ops[b->owner->g->nodes[b->op].operation];
QHBoxLayout* hlayout;
QLabel* l;
if(op->size == -1)
{
hlayout = new QHBoxLayout();
l = new QLabel();
l->setText("Size : ");
l->setToolTip("Size of the image. W == H at the moment");
hlayout->addWidget(l);
QSpinBox* sizeSpin = new QSpinBox();
sizeSpin->setMinimum(1);
sizeSpin->setMaximum(8192);
sizeSpin->setKeyboardTracking(false);
sizeSpin->setValue(inst->_cachedResult.w);
hlayout->addWidget(sizeSpin);
connect(sizeSpin, SIGNAL(valueChanged(int)), this, SLOT(handleImgResize(int)));
QFrame* line = new QFrame();
line->setObjectName(QString::fromUtf8("line"));
line->setGeometry(QRect(320, 150, 118, 3));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
layout->addLayout(hlayout);
layout->addWidget(line);
_instanciated.append(sizeSpin);
_instanciated.append(hlayout);
_instanciated.append(l);
_instanciated.append(line);
}
if(inst->isOutput)
{
eitri_GraphOutput* output = &b->owner->g->outputs[inst->isOutput-1];
hlayout = new QHBoxLayout();
l = new QLabel();
l->setText("Output Name : ");
l->setToolTip("output name for query from C lib");
hlayout->addWidget(l);
QLineEdit* lineInput = new QLineEdit();
lineInput->setMaxLength(255);
lineInput->setText(output->name);
hlayout->addWidget(lineInput);
connect(lineInput, SIGNAL(editingFinished()), this, SLOT(handleRenaming()));
QFrame* line = new QFrame();
line->setObjectName(QString::fromUtf8("line"));
line->setGeometry(QRect(320, 150, 118, 3));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
layout->addLayout(hlayout);
layout->addWidget(line);
_instanciated.append(hlayout);
_instanciated.append(lineInput);
_instanciated.append(l);
_instanciated.append(line);
}
for(int i = 0; i < op->paramsCount; ++i)
{
hlayout = new QHBoxLayout();
l = new QLabel();
l->setText(op->params[i].name);
l->setToolTip(op->params[i].tip);
hlayout->addWidget(l);
switch(op->params[i].type)
{
case EITRI_PARAM_FLOAT:
{
QDoubleSpinBox* spinbox = new QDoubleSpinBox();
spinbox->setProperty("paramIdx", i);
spinbox->setMaximum(FLT_MAX);
spinbox->setKeyboardTracking(false);
spinbox->setValue(inst->paramsValues[i].fParam);
hlayout->addWidget(spinbox),
_instanciated.push_back(spinbox);
connect(spinbox, SIGNAL(valueChanged(double)), this, SLOT(handleSpinBoxf(double)));
}
break;
case EITRI_PARAM_INT:
{
QSpinBox* spinbox = new QSpinBox();
spinbox->setProperty("paramIdx", i);
spinbox->setMaximum(INT_MAX);
spinbox->setKeyboardTracking(false);
spinbox->setValue(inst->paramsValues[i].iParam);
hlayout->addWidget(spinbox),
_instanciated.push_back(spinbox);
connect(spinbox, SIGNAL(valueChanged(int)), this, SLOT(handleSpinBox(int)));
QPushButton* b = new QPushButton("rand");
b->setProperty("linkedSpin", (int)(spinbox));
hlayout->addWidget(b);
_instanciated.push_back(b);
connect(b, SIGNAL(clicked()), this, SLOT(randValue()));
}
break;
case EITRI_PARAM_COLOR:
{
QPushButton* button = new QPushButton();
button->setProperty("paramIdx", i);
QColor c(inst->paramsValues[i].colParam.r
,inst->paramsValues[i].colParam.g
,inst->paramsValues[i].colParam.b
,inst->paramsValues[i].colParam.a);
setButtonToColor(button, c);
hlayout->addWidget(button);
_instanciated.push_back(button);
connect(button, SIGNAL(clicked()), this, SLOT(handleColorButton()));
}
break;
default:
break;
}
layout->addLayout(hlayout);
_instanciated.append(hlayout);
_instanciated.append(l);
}
}
}
void ParamInspector::handleSpinBox(int i)
{
QSpinBox* s = (QSpinBox*)QObject::sender();
if(s)
{
QVariant v = s->property("paramIdx");
if(v.isValid())
{
_opBox->owner->g->nodes[_opBox->op].paramsValues[v.toInt()].iParam = i;
_opBox->owner->g->nodes[_opBox->op].isDirty = 1;
_opBox->updatePreview();
}
}
}
void ParamInspector::handleSpinBoxf(double d)
{
QSpinBox* s = (QSpinBox*)QObject::sender();
if(s)
{
QVariant v = s->property("paramIdx");
if(v.isValid())
{
_opBox->owner->g->nodes[_opBox->op].paramsValues[v.toInt()].fParam = d;
_opBox->owner->g->nodes[_opBox->op].isDirty = 1;
_opBox->updatePreview();
}
}
}
void ParamInspector::randValue()
{
QSpinBox* s = (QSpinBox*)QObject::sender();
if(s)
{
QVariant v = s->property("linkedSpin");
if(v.isValid())
{
QSpinBox* b = (QSpinBox*)v.toInt();
b->setValue(qrand());
}
}
}
void ParamInspector::handleTextBox(QString s)
{
}
void ParamInspector::handleColorButton()
{
QPushButton* button = (QPushButton*)QObject::sender();
if(button)
{
QVariant v = button->property("paramIdx");
if(v.isValid())
{
QColor color = QColorDialog::getColor();
setButtonToColor(button, color);
eitri_Color* c = &_opBox->owner->g->nodes[_opBox->op].paramsValues[v.toInt()].colParam;
c->r = color.red();
c->g = color.green();
c->b = color.blue();
c->a = color.alpha();
_opBox->owner->g->nodes[_opBox->op].isDirty = 1;
}
}
}
void ParamInspector::handleImgResize(int i)
{
eitri_resizeNode(_opBox->owner->g, _opBox->op, i);
_opBox->owner->g->nodes[_opBox->op].isDirty = 1;
_opBox->updatePreview();
}
void ParamInspector::handleRenaming()
{
QLineEdit* line = (QLineEdit*)QObject::sender();
eitri_NodeInstance* inst = &_opBox->owner->g->nodes[_opBox->op];
strncpy(_opBox->owner->g->outputs[inst->isOutput-1].name, (const char*)line->text().toLocal8Bit().constData(), line->text().length()+1);
_opBox->updatePreview();
}
| 27.519355 | 140 | 0.527957 | Sirithang |
c842092c7791498068c09bca3c014f49a0e1077f | 10,459 | cpp | C++ | src/ini_parser.cpp | Erwan28250/ini_parser | f9534e931a28daa52729e0049db3d2dfdc4af880 | [
"MIT"
] | null | null | null | src/ini_parser.cpp | Erwan28250/ini_parser | f9534e931a28daa52729e0049db3d2dfdc4af880 | [
"MIT"
] | null | null | null | src/ini_parser.cpp | Erwan28250/ini_parser | f9534e931a28daa52729e0049db3d2dfdc4af880 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2022 Erwan Saclier de la Bâtie
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 "ini_parser.h"
#include <fstream>
#include <sstream>
const std::string ini_parser::m_nullString = std::string();
ini_parser::ini_parser() :
m_isFile(false),
m_isParsed(false)
{}
ini_parser::ini_parser(const char* iniFile, bool isFile) :
m_iniFile(iniFile),
m_isFile(isFile),
m_isParsed(false)
{
parse();
}
ini_parser::ini_parser(const std::string& iniFile, bool isFile) :
m_iniFile(iniFile),
m_isFile(isFile),
m_isParsed(false)
{
parse();
}
ini_parser::~ini_parser()
{}
void ini_parser::parse()
{
// Check if the m_iniFile is a file path or a file data.
if (m_isFile)
parseFile();
else
parseData();
}
void ini_parser::parseFile()
{
// Parsing the m_iniFile file.
if (m_iniFile.empty())
return;
// Opening the ini file.
std::ifstream file(m_iniFile);
if (file.is_open())
{
std::string currentSection;
std::string line;
while (std::getline(file, line))
parseLine(line, currentSection);
parsingSuccess();
}
}
void ini_parser::parseData()
{
// Parsing the m_iniFile as ini data.
if (m_iniFile.empty())
return;
// Streaming the string.
std::istringstream data(m_iniFile);
std::string currentSection;
std::string line;
while (std::getline(data, line))
parseLine(line, currentSection);
parsingSuccess();
}
void ini_parser::parseLine(const std::string& line, std::string& currentSection)
{
// Parsing a single line of a ini file.
if (line.size() == 0)
return;
// Create a copy of the line and removing the first spaces.
std::string copyLine = line;
removeFirstSpaces(copyLine);
// Retrieve the section name.
if (copyLine.at(0) == '#')
return;
else if (copyLine.at(0) == '[')
{
size_t pos = copyLine.find_first_of(']');
if (pos < copyLine.size())
{
currentSection.clear();
currentSection.append(
std::next(copyLine.cbegin(), 1),
std::next(copyLine.cbegin(), pos));
removeSpaces(currentSection);
}
}
// Retrieve the parameters and values
else
{
/*
Allow parameters to be attach to any sections.
This can be usefull if to use the library
has a simple config file.
*/
size_t pos = copyLine.find_first_of('=');
if (pos < copyLine.size() && pos > 0)
{
std::string paramName;
std::string valueName;
paramName.append(
copyLine.cbegin(),
std::next(copyLine.cbegin(), pos));
size_t valueEndPos = copyLine.find_first_of('#');
std::string::const_iterator valueIt;
if (valueEndPos < copyLine.size())
valueIt = std::next(copyLine.cbegin(), valueEndPos);
else
valueIt = copyLine.cend();
if (pos+1 < copyLine.size())
valueName.append(
std::next(copyLine.cbegin(), pos+1),
valueIt);
removeSpaces(paramName);
removeSpaces(valueName);
setValue(currentSection, paramName, valueName);
}
}
}
void ini_parser::setValue(const char* section, const char* parameters, const char* value)
{
setValue(std::string(section), std::string(parameters), std::string(value));
}
void ini_parser::setValue(const std::string& section, const std::string& parameters, const std::string& value)
{
// Setting the value of the parameters of the section (section).
Section* pSection = nullptr;
// Find existing section.
for (std::vector<Section>::iterator it = m_sections.begin();
it != m_sections.end();
it++)
{
if (it->name == section)
{
pSection = &(*it);
break;
}
}
// If no section found, create a new one.
if (pSection == nullptr)
{
Section sec = {};
sec.name = section;
m_sections.push_back(sec);
pSection = &m_sections.at(m_sections.size()-1);
}
Parameter *pParam = nullptr;
// Find existing parameters
/*for (size_t i = 0; i < pSection->params.size(); i++)
{
if (pSection->params.at(i).name == parameters)
{
pParam = &pSection->params.at(i);
break;
}
}*/
for (std::vector<Parameter>::iterator it = pSection->params.begin();
it != pSection->params.end();
it++)
{
if (it->name == parameters)
{
pParam = &(*it);
break;
}
}
// If no parameters found, create a new one.
if (pParam == nullptr)
{
ini_parser::Parameter param = {};
param.name = parameters;
pSection->params.push_back(param);
pParam = &pSection->params.at(pSection->params.size()-1);
}
// Set the value of the parameters.
pParam->value = value;
}
void ini_parser::removeParameters(const char* section, const char* parameters)
{
removeParameters(std::string(section), std::string(parameters));
}
void ini_parser::removeParameters(const std::string& section, const std::string& parameters)
{
// Removing a parameters of a given section.
Section* pSection = nullptr;
// Find the section.
for (std::vector<Section>::iterator it = m_sections.begin();
it != m_sections.end();
it++)
{
if (it->name == section)
{
pSection = &(*it);
break;
}
}
// Remove the parameters from the section.
for (std::vector<Parameter>::const_iterator it = pSection->params.cbegin();
it != pSection->params.cend();
it++)
{
if (it->name == parameters)
{
pSection->params.erase(it);
break;
}
}
}
void ini_parser::removeSection(const char* section)
{
removeSection(std::string(section));
}
void ini_parser::removeSection(const std::string& section)
{
// Removing a section.
for (std::vector<Section>::const_iterator it = m_sections.cbegin();
it != m_sections.cend();
it++)
{
if (it->name == section)
{
m_sections.erase(it);
break;
}
}
}
void ini_parser::parsingSuccess()
{
m_isParsed = true;
}
void ini_parser::removeSpaces(std::string& value)
{
// Removing the first and the last spaces from a string.
// Removing the first spaces.
removeFirstSpaces(value);
// Removing the last spaces.
for (std::string::const_reverse_iterator rit = value.crbegin();
rit != value.crend();
rit++)
{
if (*rit == ' ')
value.erase((rit+1).base());
else
break;
}
}
void ini_parser::removeFirstSpaces(std::string& value)
{
// Removing only the first spaces from a string.
while (value.size() > 0)
{
if (value.at(0) == ' ')
value.erase(0, 1);
else
break;
}
}
const std::string& ini_parser::iniFile() const
{
return m_iniFile;
}
bool ini_parser::isFile() const
{
return m_isFile;
}
bool ini_parser::isParsed() const
{
return m_isParsed;
}
const char* ini_parser::getValue(const char* section, const char* parameters, bool* isExist) const
{
return getValue(std::string(section), std::string(parameters), isExist).c_str();
}
const std::string& ini_parser::getValue(const std::string& section, const std::string& parameters, bool* isExist) const
{
// Return the value of the parameters (parameters) of the section (section).
// Find section.
const Section* pSection = nullptr;
for (std::vector<Section>::const_iterator it = m_sections.cbegin();
it != m_sections.cend();
it++)
{
if (it->name == section)
{
pSection = &(*it);
break;
}
}
if (pSection == nullptr)
{
if (isExist)
*isExist = false;
return m_nullString;
}
// Find parameters
const Parameter* pParameters = nullptr;
for (std::vector<Parameter>::const_iterator it = pSection->params.cbegin();
it != pSection->params.cend();
it++)
{
if (it->name == parameters)
{
pParameters = &(*it);
break;
}
}
if (pParameters == nullptr)
{
if (isExist)
*isExist = false;
return m_nullString;
}
if (isExist)
*isExist = true;
return pParameters->value;
}
const char* ini_parser::getValue(const char* parameters, bool* isExist) const
{
return getValue(std::string(parameters), isExist).c_str();
}
const std::string& ini_parser::getValue(const std::string& parameters, bool* isExist) const
{
return getValue(std::string(), parameters, isExist);
}
void ini_parser::setIniFile(const char* iniFile, bool isFile)
{
m_iniFile = iniFile;
m_isFile = isFile;
m_isParsed = false;
m_sections.clear();
parse();
}
void ini_parser::setIniFile(const std::string& iniFile, bool isFile)
{
m_iniFile = iniFile;
m_isFile = isFile;
m_isParsed = false;
m_sections.clear();
parse();
} | 25.263285 | 119 | 0.592982 | Erwan28250 |
c8437bca6d8e7f4911beb853c9b98623a266cf36 | 1,723 | cpp | C++ | lib/soc/m4/stm32l4/peripherals/WWDG.cpp | msemegen/CML | f37e20f0add711c743b69607d39aa5ab0680cf7e | [
"MIT"
] | 23 | 2020-07-16T21:52:38.000Z | 2022-03-13T18:24:16.000Z | lib/soc/m4/stm32l4/peripherals/WWDG.cpp | msemegen/CML | f37e20f0add711c743b69607d39aa5ab0680cf7e | [
"MIT"
] | 16 | 2019-12-28T01:14:44.000Z | 2021-04-15T14:40:07.000Z | lib/soc/m4/stm32l4/peripherals/WWDG.cpp | msemegen/CML | f37e20f0add711c743b69607d39aa5ab0680cf7e | [
"MIT"
] | 5 | 2020-07-17T17:48:50.000Z | 2022-03-25T16:06:52.000Z | /*
* Name: WWDG.cpp
*
* Copyright (c) Mateusz Semegen and contributors. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for details.
*/
#ifdef STM32L4
// this
#include <soc/m4/stm32l4/peripherals/WWDG.hpp>
// cml
#include <cml/bit_flag.hpp>
#include <cml/debug/assertion.hpp>
// soc
#include <soc/Interrupt_guard.hpp>
namespace {
using namespace soc::m4::stm32l4::peripherals;
uint16_t reload = 0;
bool created = false;
WWDG::Early_wakeup_callback callback;
} // namespace
extern "C" {
#define WWDG_T ((WWDG_TypeDef*)WWDG_BASE)
void WWDG_IRQHandler()
{
if (nullptr != callback.function)
{
callback.function(callback.p_user_data);
}
}
} // extern C
namespace soc {
namespace m4 {
namespace stm32l4 {
namespace peripherals {
using namespace cml;
WWDG::WWDG()
{
cml_assert(false == created);
created = true;
}
void WWDG::enable(Prescaler a_prescaler, uint16_t a_reload, uint16_t a_window, uint16_t a_irq_priority)
{
WWDG_T->CR = (WWDG_CR_WDGA | a_reload);
WWDG_T->CFR = static_cast<uint32_t>(a_prescaler) | a_window;
NVIC_SetPriority(WWDG_IRQn, a_irq_priority);
NVIC_EnableIRQ(WWDG_IRQn);
}
void WWDG::register_early_wakeup_callback(const Early_wakeup_callback& a_callback)
{
Interrupt_guard gaurd;
callback = a_callback;
bit_flag::set(&(WWDG_T->CFR), WWDG_CFR_EWI);
}
void WWDG::unregister_early_wakeup_callback()
{
Interrupt_guard guard;
bit_flag::clear(&(WWDG_T->CFR), WWDG_CFR_EWI);
callback = { nullptr, nullptr };
}
void WWDG::feed()
{
WWDG_T->CR = reload;
}
} // namespace peripherals
} // namespace stm32l4
} // namespace m4
} // namespace soc
#endif // STM32L4 | 18.329787 | 103 | 0.703424 | msemegen |
c844860023ddf357b9293691cb2b0b5963be1658 | 5,985 | cpp | C++ | src/plugProjectOgawaU/ogSceneSMenuItem.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 33 | 2021-12-08T11:10:59.000Z | 2022-03-26T19:59:37.000Z | src/plugProjectOgawaU/ogSceneSMenuItem.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 6 | 2021-12-22T17:54:31.000Z | 2022-01-07T21:43:18.000Z | src/plugProjectOgawaU/ogSceneSMenuItem.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 2 | 2022-01-04T06:00:49.000Z | 2022-01-26T07:27:28.000Z | #include "types.h"
/*
Generated from dpostproc
.section .rodata # 0x804732E0 - 0x8049E220
.global lbl_8048E550
lbl_8048E550:
.4byte 0x534D656E
.4byte 0x75497465
.4byte 0x6D207363
.4byte 0x7265656E
.4byte 0x00000000
.global lbl_8048E564
lbl_8048E564:
.4byte 0x7265735F
.4byte 0x735F6D65
.4byte 0x6E755F69
.4byte 0x74656D2E
.4byte 0x737A7300
.section .data, "wa" # 0x8049E220 - 0x804EFC20
.global lbl_804D8778
lbl_804D8778:
.4byte lbl_80313FE8
.4byte lbl_80313FE8
.4byte lbl_80313FE8
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FE8
.4byte lbl_80313FE8
.4byte lbl_80313FEC
.4byte lbl_80313FE8
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FE8
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FE8
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FEC
.4byte lbl_80313FE8
.global __vt__Q32og9newScreen9SMenuItem
__vt__Q32og9newScreen9SMenuItem:
.4byte 0
.4byte 0
.4byte getSceneType__Q32og9newScreen9SMenuItemFv
.4byte getOwnerID__Q32og9newScreen9SMenuItemFv
.4byte getMemberID__Q32og9newScreen9SMenuItemFv
.4byte isUseBackupSceneInfo__Q32og9newScreen9SMenuItemFv
.4byte isDrawInDemo__Q26Screen9SceneBaseCFv
.4byte getResName__Q32og9newScreen9SMenuItemCFv
.4byte doCreateObj__Q32og9newScreen9SMenuItemFP10JKRArchive
.4byte
doUserCallBackFunc__Q32og9newScreen9SMenuItemFPQ28Resource10MgrCommand .4byte
setPort__Q26Screen9SceneBaseFR8Graphics .4byte
doUpdateActive__Q32og9newScreen9SMenuItemFv .4byte
doConfirmSetScene__Q32og9newScreen9SMenuItemFRQ26Screen11SetSceneArg .4byte
doConfirmStartScene__Q26Screen9SceneBaseFPQ26Screen13StartSceneArg .4byte
doConfirmEndScene__Q26Screen9SceneBaseFRPQ26Screen11EndSceneArg .4byte
doStart__Q26Screen9SceneBaseFPQ26Screen13StartSceneArg .4byte
doEnd__Q26Screen9SceneBaseFPQ26Screen11EndSceneArg .4byte
setDefaultDispMember__Q26Screen9SceneBaseFv .4byte
doSetBackupScene__Q32og9newScreen9SMenuItemFRQ26Screen11SetSceneArg .4byte
doGetFinishState__Q32og9newScreen14SceneSMenuBaseFv
*/
namespace og {
namespace newScreen {
/*
* --INFO--
* Address: 80313F4C
* Size: 000050
*/
SMenuItem::SMenuItem(void)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r3
bl __ct__Q26Screen9SceneBaseFv
lis r4, __vt__Q32og9newScreen14SceneSMenuBase@ha
lis r3, __vt__Q32og9newScreen9SMenuItem@ha
addi r0, r4, __vt__Q32og9newScreen14SceneSMenuBase@l
li r4, 1
stw r0, 0(r31)
addi r0, r3, __vt__Q32og9newScreen9SMenuItem@l
mr r3, r31
stw r4, 0x220(r31)
stw r0, 0(r31)
lwz r31, 0xc(r1)
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: ........
* Size: 000084
*/
SMenuItem::~SMenuItem(void)
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: 80313F9C
* Size: 000068
*/
void SMenuItem::doConfirmSetScene(Screen::SetSceneArg&)
{
/*
stwu r1, -0x10(r1)
mflr r0
mr r3, r4
stw r0, 0x14(r1)
stw r31, 0xc(r1)
li r31, 0
lwz r12, 0(r4)
lwz r12, 8(r12)
mtctr r12
bctrl
addi r0, r3, -10000
cmplwi r0, 0x1b
bgt lbl_80313FEC
lis r3, lbl_804D8778@ha
slwi r0, r0, 2
addi r3, r3, lbl_804D8778@l
lwzx r0, r3, r0
mtctr r0
bctr
.global lbl_80313FE8
lbl_80313FE8:
li r31, 1
.global lbl_80313FEC
lbl_80313FEC:
lwz r0, 0x14(r1)
mr r3, r31
lwz r31, 0xc(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 80314004
* Size: 00000C
*/
void SMenuItem::doSetBackupScene(Screen::SetSceneArg&)
{
/*
li r0, 0
stb r0, 9(r4)
blr
*/
}
/*
* --INFO--
* Address: 80314010
* Size: 000004
*/
void SMenuItem::doUserCallBackFunc(Resource::MgrCommand*) { }
/*
* --INFO--
* Address: 80314014
* Size: 000060
*/
void SMenuItem::doCreateObj(JKRArchive*)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r4
stw r30, 8(r1)
mr r30, r3
li r3, 0xd4
bl __nw__FUl
or. r4, r3, r3
beq lbl_80314050
lis r4, lbl_8048E550@ha
addi r4, r4, lbl_8048E550@l
bl __ct__Q32og9newScreen12ObjSMenuItemFPCc
mr r4, r3
lbl_80314050:
mr r3, r30
mr r5, r31
bl registObj__Q26Screen9SceneBaseFPQ26Screen7ObjBaseP10JKRArchive
lwz r0, 0x14(r1)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 80314074
* Size: 000004
*/
void SMenuItem::doUpdateActive(void) { }
/*
* --INFO--
* Address: 80314078
* Size: 00000C
*/
void SMenuItem::getResName() const
{
/*
lis r3, lbl_8048E564@ha
addi r3, r3, lbl_8048E564@l
blr
*/
}
/*
* --INFO--
* Address: 80314084
* Size: 000008
*/
u32 SMenuItem::getSceneType(void) { return 0x271C; }
/*
* --INFO--
* Address: 8031408C
* Size: 00000C
*/
void SMenuItem::getOwnerID(void)
{
/*
lis r3, 0x004F4741@ha
addi r3, r3, 0x004F4741@l
blr
*/
}
/*
* --INFO--
* Address: 80314098
* Size: 000014
*/
void SMenuItem::getMemberID(void)
{
/*
lis r4, 0x4954454D@ha
lis r3, 0x00534D5F@ha
addi r4, r4, 0x4954454D@l
addi r3, r3, 0x00534D5F@l
blr
*/
}
/*
* --INFO--
* Address: 803140AC
* Size: 000008
*/
u32 SMenuItem::isUseBackupSceneInfo(void) { return 0x1; }
} // namespace newScreen
} // namespace og
| 20.637931 | 80 | 0.647619 | projectPiki |
c84808cfac1f4ecd63b78488b5f8f8efe62b79a7 | 1,360 | cpp | C++ | openicc/oyjl/oyjl-args-qml/src/utils.cpp | oyranos-cms/oyranos | 43d16a5a457bc3b8b66feabfe992f2a665723faa | [
"BSD-3-Clause"
] | 15 | 2015-03-06T07:21:55.000Z | 2021-12-31T02:07:10.000Z | openicc/oyjl/oyjl-args-qml/src/utils.cpp | oyranos-cms/oyranos | 43d16a5a457bc3b8b66feabfe992f2a665723faa | [
"BSD-3-Clause"
] | 64 | 2015-02-09T11:07:32.000Z | 2022-03-26T13:03:05.000Z | openicc/oyjl/oyjl-args-qml/src/utils.cpp | oyranos-cms/oyranos | 43d16a5a457bc3b8b66feabfe992f2a665723faa | [
"BSD-3-Clause"
] | 7 | 2015-05-23T23:17:04.000Z | 2021-06-24T13:27:30.000Z | /** @file utils.cpp
*
* Oyjl JSON QML is a graphical renderer of UI files.
*
* @par Copyright:
* 2018 (C) Kai-Uwe Behrmann
* All Rights reserved.
*
* @par License:
* MIT <http://www.opensource.org/licenses/mit-license.php>
* @since 2018/02/26
*
* logging and helpers
*/
#include "include/utils.h"
#include <QDateTime>
#include <QObject>
#include <QTextStream>
#if defined(Q_OS_ANDROID)
#include <android/log.h>
#endif
void app_log( QString log_text )
{
QTextStream s(stderr);
s << "oyjl-args-qml("<< QDateTime::currentDateTime().toString("hh:mm:ss.zzz") <<"): "
<< log_text << endl;
#if defined(Q_OS_ANDROID)
__android_log_print(ANDROID_LOG_INFO, "oyjl-args-qml", "%s", log_text.toLocal8Bit().data() );
#endif
}
void app_log( QString file, QString func, QString log_text )
{
QString t(file);
int len = t.lastIndexOf('/');
if(len > 0)
t.remove( 0, len+1 );
t += " " + func;
QTextStream s(stderr);
s << t << " " << QDateTime::currentDateTime().toString("hh:mm:ss.zzz") << " "
<< log_text << endl;
#if defined(Q_OS_ANDROID)
__android_log_print(ANDROID_LOG_INFO, t.toLocal8Bit().data(), "%s", log_text.toLocal8Bit().data() );
#endif
}
int appIsBigEndian ()
{ union { unsigned short u16; unsigned char c; } test = { .u16 = 1 }; return !test.c; }
| 25.185185 | 104 | 0.622059 | oyranos-cms |
c84a127c1f0dc3d83ea406232d4c3d9d58291fcd | 16,922 | cpp | C++ | src/cloud_scene.cpp | JakubLukas/LumixCloudSystem | 42a8cbffb54c12fec8e5bd130fcbf83b133bccb0 | [
"MIT"
] | 4 | 2017-02-21T05:00:43.000Z | 2020-10-26T20:01:08.000Z | src/cloud_scene.cpp | JakubLukas/LumixCloudSystem | 42a8cbffb54c12fec8e5bd130fcbf83b133bccb0 | [
"MIT"
] | 1 | 2020-10-13T00:50:39.000Z | 2020-10-13T00:50:39.000Z | src/cloud_scene.cpp | JakubLukas/LumixCloudSystem | 42a8cbffb54c12fec8e5bd130fcbf83b133bccb0 | [
"MIT"
] | null | null | null | #include "cloud_scene.h"
#include "engine/universe/universe.h"
#include "engine/iallocator.h"
#include "engine/associative_array.h"
#include "engine/property_register.h"
#include "engine/serializer.h"
#include "engine/blob.h"
#include "engine/engine.h"
#include "engine/resource.h"
#include "engine/resource_manager_base.h"
#include "engine/resource_manager.h"
#include "engine/vec.h"
#include "engine/path.h"
#include "renderer/render_scene.h"
#include "renderer/material.h"
#include "renderer/shader.h"
#include "engine/crc32.h"
#include "simulation/simulation.h"
#include "render/renderer.h"
#include "renderer/pipeline.h"
#include "engine/lua_wrapper.h"
namespace Lumix
{
static const ComponentType CLOUD_TYPE = PropertyRegister::getComponentType("cloud");
static const ResourceType MATERIAL_TYPE("material");
struct Cloud
{
Entity entity;
Vec3 cellSpace;
CldSim::Simulation simulation;
CldSim::CloudRenderer renderer;
Material* material = nullptr;
bool isSimulating = false;
float timescale = 1.0f;
};
struct BaseVertex //TODO
{
float x, y, z;
u32 rgba;
float u;
float v;
};
struct CloudSceneImpl LUMIX_FINAL : public CloudScene
{
enum class Version
{
CLOUDS = 0,
LATEST
};
CloudSceneImpl(CloudSystem& system, Engine& engine, Universe& universe, IAllocator& allocator)
: m_system(system)
, m_engine(engine)
, m_universe(universe)
, m_allocator(allocator)
, m_clouds(allocator)
{
//m_universe.entityTransformed().bind<NavigationSceneImpl, &NavigationSceneImpl::onEntityMoved>(this);
universe.registerComponentType(CLOUD_TYPE, this, &CloudSceneImpl::serializeCloud, &CloudSceneImpl::deserializeCloud);
createCloudBuffers();
m_cloud_matrix_uniform = bgfx::createUniform("u_cloudMatrix", bgfx::UniformType::Mat4);
}
~CloudSceneImpl()
{
bgfx::destroyUniform(m_cloud_matrix_uniform);
bgfx::destroyVertexBuffer(m_particle_vertex_buffer);
bgfx::destroyIndexBuffer(m_particle_index_buffer);
auto* manager = m_engine.getResourceManager().get(MATERIAL_TYPE);
for(Cloud& cloud : m_clouds)
{
if(cloud.material != nullptr)
manager->unload(*cloud.material);
}
}
void clear() override
{
auto* manager = m_engine.getResourceManager().get(MATERIAL_TYPE);
for(Cloud& cloud : m_clouds)
{
if(cloud.material != nullptr)
manager->unload(*cloud.material);
}
m_clouds.clear();
};
ComponentHandle createComponent(ComponentType type, Entity entity) override
{
if(type == CLOUD_TYPE)
{
Cloud& cloud = m_clouds.insert(entity);
cloud.entity = entity;
cloud.cellSpace = Vec3(10, 10, 10);
cloud.simulation.Setup(30, 10, 30);
cloud.renderer.Setup(30, 10, 30);
ComponentHandle cmp = { entity.index };
m_universe.addComponent(entity, type, this, cmp);
return cmp;
}
return INVALID_COMPONENT;
};
void destroyComponent(ComponentHandle component, ComponentType type) override
{
if(type == CLOUD_TYPE)
{
Entity entity = { component.index };
m_clouds.erase(entity);
m_universe.destroyComponent(entity, type, this, component);
}
else
{
ASSERT(false);
}
};
ComponentHandle getComponent(Entity entity, ComponentType type) override
{
if(type == CLOUD_TYPE)
{
if (m_clouds.find(entity) < 0)
return INVALID_COMPONENT;
return{ entity.index };
}
return INVALID_COMPONENT;
}
int getVersion() const override { return (int)Version::LATEST; }
IPlugin& getPlugin() const override { return m_system; };
Universe& getUniverse() override { return m_universe; }
void startGame() override { } //TODO
void stopGame() override { } //TODO
void debugDraw()
{
auto render_scene = static_cast<RenderScene*>(m_universe.getScene(crc32("renderer")));
if(!render_scene) return;
Entity camera = m_universe.getFirstEntity();
do
{
if(strcmp(m_universe.getEntityName(camera), "editor_camera") == 0)
break;
camera = m_universe.getNextEntity(camera);
}
while(isValid(camera));
Vec3 dir = m_universe.getRotation(camera).rotate(Vec3(0, 0, 1));
Vec3 pos;
for (const Cloud& cloud : m_clouds)
{
CldSim::uint size =
cloud.simulation.GetWidth()
* cloud.simulation.GetHeight()
* cloud.simulation.GetLength();
for(CldSim::uint i = 0; i < size; ++i)
{
const auto& p = cloud.renderer.GetParticles()[i];
pos.x = p.position.x;
pos.y = p.position.y;
pos.z = p.position.z;
u32 color =
(u32(p.color.a * 0xff) << 24)
+ (u32(p.color.r * 0xff) << 16)
+ (u32(p.color.g * 0xff) << 8)
+ (u32(p.color.b * 0xff));
render_scene->addDebugPoint(pos, color, 0);
}
}
}
void update(float time_delta, bool paused) override
{
if(paused)
return;
for(Cloud& cloud : m_clouds)
{
if(cloud.isSimulating)
{
cloud.simulation.Update(time_delta * cloud.timescale);
cloud.renderer.CalcParticleColors(cloud.simulation.GetCloudSpace());
}
}
}
void serialize(OutputBlob& serializer) override
{
int count = m_clouds.size();
serializer.write(count);
for(const Cloud& cloud : m_clouds)
{
serializer.write(cloud.entity);
serializer.write(cloud.cellSpace);
serializer.write(Vec3((float)cloud.simulation.GetWidth(), (float)cloud.simulation.GetHeight(), (float)cloud.simulation.GetLength()));
const Material* material = cloud.material;
serializer.writeString(material ? material->getPath().c_str() : "");
serializer.write(cloud.timescale);
}
};
void deserialize(InputBlob& serializer) override
{
ResourceManager manager = m_engine.getResourceManager();
auto material_manager = manager.get(MATERIAL_TYPE);
int count = 0;
serializer.read(count);
m_clouds.reserve(count);
for(int i = 0; i < count; ++i)
{
Entity entity;
serializer.read(entity);
Cloud& cloud = m_clouds.insert(entity);
cloud.entity = entity;
serializer.read(cloud.cellSpace);
Vec3 dimension;
serializer.read(dimension);
cloud.simulation.Setup((CldSim::uint)dimension.x, (CldSim::uint)dimension.y, (CldSim::uint)dimension.z);
cloud.renderer.Setup((CldSim::uint)dimension.x, (CldSim::uint)dimension.y, (CldSim::uint)dimension.z);
char path[MAX_PATH_LENGTH];
serializer.readString(path, lengthOf(path));
if(path[0] != '\0')
cloud.material = static_cast<Material*>(material_manager->load(Path(path)));
serializer.read(cloud.timescale);
ComponentHandle cmp = { entity.index };
m_universe.addComponent(cloud.entity, CLOUD_TYPE, this, cmp);
}
};
void serializeCloud(ISerializer& serializer, ComponentHandle cmp)
{
Cloud& cloud = m_clouds[{cmp.index}];
serializer.write("cellSpace", cloud.cellSpace);
serializer.write("size", Vec3((float)cloud.simulation.GetWidth(), (float)cloud.simulation.GetHeight(), (float)cloud.simulation.GetLength()));
const Material* material = cloud.material;
serializer.write("material", material ? material->getPath().c_str() : "");
serializer.write("timescale", cloud.timescale);
}
void deserializeCloud(IDeserializer& serializer, Entity entity, int)
{
ResourceManagerBase* material_manager = m_engine.getResourceManager().get(MATERIAL_TYPE);
Cloud& cloud = m_clouds.insert(entity);
cloud.entity = entity;
serializer.read(&cloud.cellSpace);
Vec3 dimension;
serializer.read(&dimension);
cloud.simulation.Setup((CldSim::uint)dimension.x, (CldSim::uint)dimension.y, (CldSim::uint)dimension.z);
cloud.renderer.Setup((CldSim::uint)dimension.x, (CldSim::uint)dimension.y, (CldSim::uint)dimension.z);
char path[MAX_PATH_LENGTH];
serializer.read(path, lengthOf(path));
if(path[0] != '\0')
cloud.material = static_cast<Material*>(material_manager->load(Path(path)));
serializer.read(&cloud.timescale);
ComponentHandle cmp = { cloud.entity.index };
m_universe.addComponent(cloud.entity, CLOUD_TYPE, this, cmp);
}
void setCloudSize(ComponentHandle cmp, const Vec3& size) override
{
Entity entity = { cmp.index };
Cloud& cloud = m_clouds[entity];
cloud.simulation.Clear();
cloud.simulation.Setup((CldSim::uint)size.x, (CldSim::uint)size.y, (CldSim::uint)size.z);
cloud.renderer.Clear();
cloud.renderer.Setup((CldSim::uint)size.x, (CldSim::uint)size.y, (CldSim::uint)size.z);
}
Vec3 getCloudSize(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return Vec3(
(float)m_clouds[entity].simulation.GetWidth(),
(float)m_clouds[entity].simulation.GetHeight(),
(float)m_clouds[entity].simulation.GetLength());
}
void setCloudCellSpace(ComponentHandle cmp, const Vec3& count) override
{
Entity entity = { cmp.index };
m_clouds[entity].cellSpace.x = count.x;
m_clouds[entity].cellSpace.y = count.y;
m_clouds[entity].cellSpace.z = count.z;
}
Vec3 getCloudCellSpace(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
Vec3 count(
m_clouds[entity].cellSpace.x,
m_clouds[entity].cellSpace.y,
m_clouds[entity].cellSpace.z);
return count;
}
void setCloudHumidityProbability(ComponentHandle cmp, const float value) override
{
Entity entity = { cmp.index };
m_clouds[entity].simulation.SetHumidityProbability(value);
}
float getCloudHumidityProbability(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].simulation.GetHumidityProbability();
}
void setCloudActiveProbability(ComponentHandle cmp, const float value) override
{
Entity entity = { cmp.index };
m_clouds[entity].simulation.SetActiveProbability(value);
}
float getCloudActiveProbability(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].simulation.GetActiveProbability();
}
void setCloudExtinctionProbability(ComponentHandle cmp, const float value) override
{
Entity entity = { cmp.index };
m_clouds[entity].simulation.SetExtinctionProbability(value);
}
float getCloudExtinctionProbability(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].simulation.GetExtinctionProbability();
}
void setCloudExtinctionTime(ComponentHandle cmp, const float value) override
{
Entity entity = { cmp.index };
m_clouds[entity].simulation.SetExtinctionTime(value);
}
float getCloudExtinctionTime(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].simulation.GetExtinctionTime();
}
void setViewSamplesCount(ComponentHandle cmp, const int count) override
{
Entity entity = { cmp.index };
m_clouds[entity].renderer.SetViewSamplesCount(count);
}
int getViewSamplesCount(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].renderer.GetViewSamplesCount();
}
void setLightSamplesCount(ComponentHandle cmp, const int count) override
{
Entity entity = { cmp.index };
m_clouds[entity].renderer.SetLightSamplesCount(count);
}
int getLightSamplesCount(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].renderer.GetLightSamplesCount();
}
void setSunPosition(ComponentHandle cmp, const Vec3& pos) override
{
Entity entity = { cmp.index };
m_clouds[entity].renderer.SetSunPosition({ pos.x, pos.y, pos.z });
}
Vec3 getSunPosition(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
CldSim::Vec3 pos = m_clouds[entity].renderer.GetSunPosition();
return Vec3(pos.x, pos.y, pos.z);
}
void setSunColor(ComponentHandle cmp, const Vec4& color) override
{
Entity entity = { cmp.index };
m_clouds[entity].renderer.SetSunColor({ color.w, color.x, color.y, color.z });
}
Vec4 getSunColor(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
CldSim::Color col = m_clouds[entity].renderer.GetSunColor();
return Vec4(col.r, col.g, col.b, col.a);
}
void setShadeColor(ComponentHandle cmp, const Vec4& color) override
{
Entity entity = { cmp.index };
m_clouds[entity].renderer.SetShadeColor({ color.w, color.x, color.y, color.z });
}
Vec4 getShadeColor(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
CldSim::Color col = m_clouds[entity].renderer.GetShadeColor();
return Vec4(col.r, col.g, col.b, col.a);
}
void setCloudMaterialPath(ComponentHandle cmp, const Path& path) override
{
Entity entity = { cmp.index };
auto* manager = m_engine.getResourceManager().get(MATERIAL_TYPE);
Material* material = m_clouds[entity].material;
if(material != nullptr)
manager->unload(*material);
m_clouds[entity].material = static_cast<Material*>(manager->load(path));
}
Path getCloudMaterialPath(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
Cloud& cloud = m_clouds[entity];
if (cloud.material == nullptr)
return Path("");
return cloud.material->getPath();
}
void restartSimulation(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].simulation.Restart();
}
void setIsSimulating(ComponentHandle cmp, const bool isSimulating) override
{
Entity entity = { cmp.index };
m_clouds[entity].isSimulating = isSimulating;
}
bool getIsSimulating(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].isSimulating;
}
void setSimulationTimescale(ComponentHandle cmp, const float timescale) override
{
Entity entity = { cmp.index };
m_clouds[entity].timescale = timescale;
}
float getSimulationTimescale(ComponentHandle cmp) override
{
Entity entity = { cmp.index };
return m_clouds[entity].timescale;
}
void createCloudBuffers() //TODO
{
const BaseVertex vertices[] = {
{ -1, -1, 1, 0xffffffff, 0, 0 },
{ -1, 1, 1, 0xffffffff, 0, 1 },
{ 1, 1, 1, 0xffffffff, 1, 1 },
{ 1, -1, 1, 0xffffffff, 1, 0 },
};
bgfx::VertexDecl m_base_vertex_decl;
m_base_vertex_decl.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
.end();
const bgfx::Memory* vertex_mem = bgfx::copy(vertices, sizeof(vertices));
m_particle_vertex_buffer = bgfx::createVertexBuffer(vertex_mem, m_base_vertex_decl);
const u16 indices[] = { 0, 1, 2, 0, 2, 3 };
const bgfx::Memory* index_mem = bgfx::copy(indices, sizeof(indices));
m_particle_index_buffer = bgfx::createIndexBuffer(index_mem);
}
void renderClouds(Pipeline* pipeline)
{
for(const Cloud& cloud : m_clouds)
{
Material* material = cloud.material;
if(material == nullptr)
continue;//TODO
Matrix mtx = m_universe.getMatrix(cloud.entity);
struct Instance
{
Vec4 pos;
Vec4 color;
};
int count =
cloud.simulation.GetWidth()
* cloud.simulation.GetHeight()
* cloud.simulation.GetLength();
const CldSim::CloudRenderer::Particle* particle = cloud.renderer.GetParticles();
const bgfx::InstanceDataBuffer* instance_buffer = bgfx::allocInstanceDataBuffer(count, sizeof(Instance));
Instance* instance = (Instance*)instance_buffer->data;
for(int i = 0, c = count; i < c; ++i)
{
instance->pos = Vec4(particle->position.x, particle->position.y, particle->position.z, 1.0f);
instance->color = Vec4(particle->color.r, particle->color.g, particle->color.b, particle->color.a);
++instance;
++particle;
}
bgfx::setUniform(m_cloud_matrix_uniform, &mtx);
pipeline->render(m_particle_vertex_buffer, m_particle_index_buffer, *instance_buffer, count, *material);
}
}
IAllocator& m_allocator;
Universe& m_universe;
CloudSystem& m_system;
Engine& m_engine;
AssociativeArray<Entity, Cloud> m_clouds;
bgfx::VertexBufferHandle m_particle_vertex_buffer; //TODO
bgfx::IndexBufferHandle m_particle_index_buffer; //TODO
bgfx::UniformHandle m_cloud_matrix_uniform;
};
CloudScene* CloudScene::createInstance(CloudSystem& system,
Engine& engine,
Universe& universe,
class IAllocator& allocator)
{
return LUMIX_NEW(allocator, CloudSceneImpl)(system, engine, universe, allocator);
}
void CloudScene::destroyInstance(CloudScene* scene)
{
LUMIX_DELETE(static_cast<CloudSceneImpl*>(scene)->m_allocator, scene);
}
void CloudScene::registerLuaAPI(lua_State* L)
{
auto registerCFunction = [L](const char* name, lua_CFunction function)
{
lua_pushcfunction(L, function);
lua_setglobal(L, name);
};
#define REGISTER_FUNCTION(name) \
do {\
auto f = &LuaWrapper::wrapMethod<CloudSceneImpl, decltype(&CloudSceneImpl::name), &CloudSceneImpl::name>; \
registerCFunction(#name, f); \
} while(false) \
REGISTER_FUNCTION(renderClouds);
#undef REGISTER_FUNCTION
}
} // namespace Lumix
| 27.0752 | 144 | 0.698322 | JakubLukas |
c84c3ed67f1c9b0a60038280b30f437d53cd1850 | 2,370 | cpp | C++ | SherbertEngine Project/SherbertEngine/Pass.cpp | JDSherbert/Sherbert-Engine | e7a22035b077c78fc324b3ae3cb33a4fe1a5487d | [
"MIT"
] | 1 | 2022-02-22T18:27:00.000Z | 2022-02-22T18:27:00.000Z | SherbertEngine Project/SherbertEngine/Pass.cpp | JDSherbert/Sherbert-Engine | e7a22035b077c78fc324b3ae3cb33a4fe1a5487d | [
"MIT"
] | null | null | null | SherbertEngine Project/SherbertEngine/Pass.cpp | JDSherbert/Sherbert-Engine | e7a22035b077c78fc324b3ae3cb33a4fe1a5487d | [
"MIT"
] | null | null | null | #include "Pass.h"
#include "RenderGraphCompileException.h"
#include "RenderTarget.h"
#include "DepthStencil.h"
#include <sstream>
#include "SherbertENgine_Utilities.h"
#include "Sink.h"
#include "Source.h"
namespace n_SherbRendergraphpass
{
Pass::Pass( std::string name ) noexcept
:
name( std::move( name ) )
{}
void Pass::Reset() noxnd
{}
const std::string& Pass::GetName() const noexcept
{
return name;
}
void Pass::Finalize()
{
for( auto& in : sinks )
{
in->PostLinkValidate();
}
for( auto& out : sources )
{
out->PostLinkValidate();
}
}
Pass::~Pass()
{}
const std::vector<std::unique_ptr<Sink>>& Pass::GetSinks() const
{
return sinks;
}
Source& Pass::GetSource( const std::string& name ) const
{
for( auto& src : sources )
{
if( src->GetName() == name )
{
return *src;
}
}
std::ostringstream oss;
oss << "Output named [" << name << "] not found in pass: " << GetName();
throw RGC_EXCEPTION( oss.str() );
}
Sink& Pass::GetSink( const std::string& registeredName ) const
{
for( auto& si : sinks )
{
if( si->GetRegisteredName() == registeredName )
{
return *si;
}
}
std::ostringstream oss;
oss << "Input named [" << registeredName << "] not found in pass: " << GetName();
throw RGC_EXCEPTION( oss.str() );
}
void Pass::RegisterSink( std::unique_ptr<Sink> sink )
{
// check for overlap of input names
for( auto& si : sinks )
{
if( si->GetRegisteredName() == sink->GetRegisteredName() )
{
throw RGC_EXCEPTION( "Registered input overlaps with existing: " + sink->GetRegisteredName() );
}
}
sinks.push_back( std::move( sink ) );
}
void Pass::RegisterSource( std::unique_ptr<Source> source )
{
// check for overlap of output names
for( auto& src : sources )
{
if( src->GetName() == source->GetName() )
{
throw RGC_EXCEPTION( "Registered output overlaps with existing: " + source->GetName() );
}
}
sources.push_back( std::move( source ) );
}
void Pass::SetSinkLinkage( const std::string& registeredName,const std::string& target )
{
auto& sink = GetSink( registeredName );
auto targetSplit = SplitString( target,"." );
if( targetSplit.size() != 2u )
{
throw RGC_EXCEPTION( "Input target has incorrect format" );
}
sink.SetTarget( std::move( targetSplit[0] ),std::move( targetSplit[1] ) );
}
}
| 20.789474 | 99 | 0.631646 | JDSherbert |
c84f7c4de90997f8e7a9ce448769a26f0cf21116 | 3,089 | hpp | C++ | tracy/common/TracySocket.hpp | MacdaraTwomey/KeepTime | eacfecbaf9a401a87c5c8df09a6d2a2c4d24c3d5 | [
"MIT"
] | 19 | 2020-02-11T19:57:41.000Z | 2022-02-20T14:11:33.000Z | tracy/common/TracySocket.hpp | MacdaraTwomey/KeepTime | eacfecbaf9a401a87c5c8df09a6d2a2c4d24c3d5 | [
"MIT"
] | null | null | null | tracy/common/TracySocket.hpp | MacdaraTwomey/KeepTime | eacfecbaf9a401a87c5c8df09a6d2a2c4d24c3d5 | [
"MIT"
] | 5 | 2019-11-05T17:38:33.000Z | 2022-03-04T12:49:58.000Z | #ifndef __TRACYSOCKET_HPP__
#define __TRACYSOCKET_HPP__
#include <atomic>
#include <stdint.h>
#include "TracyForceInline.hpp"
struct addrinfo;
struct sockaddr;
namespace tracy
{
#ifdef _WIN32
void InitWinSock();
#endif
class Socket
{
public:
Socket();
Socket( int sock );
~Socket();
bool Connect( const char* addr, int port );
void Close();
int Send( const void* buf, int len );
int GetSendBufSize();
bool Read( void* buf, int len, int timeout );
template<typename ShouldExit>
bool Read( void* buf, int len, int timeout, ShouldExit exitCb )
{
auto cbuf = (char*)buf;
while( len > 0 )
{
if( exitCb() ) return false;
if( !ReadImpl( cbuf, len, timeout ) ) return false;
}
return true;
}
bool ReadRaw( void* buf, int len, int timeout );
bool HasData();
bool IsValid() const;
Socket( const Socket& ) = delete;
Socket( Socket&& ) = delete;
Socket& operator=( const Socket& ) = delete;
Socket& operator=( Socket&& ) = delete;
private:
int RecvBuffered( void* buf, int len, int timeout );
int Recv( void* buf, int len, int timeout );
bool ReadImpl( char*& buf, int& len, int timeout );
char* m_buf;
char* m_bufPtr;
std::atomic<int> m_sock;
int m_bufLeft;
struct addrinfo *m_res;
struct addrinfo *m_ptr;
int m_connSock;
};
class ListenSocket
{
public:
ListenSocket();
~ListenSocket();
bool Listen( int port, int backlog );
Socket* Accept();
void Close();
ListenSocket( const ListenSocket& ) = delete;
ListenSocket( ListenSocket&& ) = delete;
ListenSocket& operator=( const ListenSocket& ) = delete;
ListenSocket& operator=( ListenSocket&& ) = delete;
private:
int m_sock;
};
class UdpBroadcast
{
public:
UdpBroadcast();
~UdpBroadcast();
bool Open( const char* addr, int port );
void Close();
int Send( int port, const void* data, int len );
UdpBroadcast( const UdpBroadcast& ) = delete;
UdpBroadcast( UdpBroadcast&& ) = delete;
UdpBroadcast& operator=( const UdpBroadcast& ) = delete;
UdpBroadcast& operator=( UdpBroadcast&& ) = delete;
private:
int m_sock;
};
class IpAddress
{
public:
IpAddress();
~IpAddress();
void Set( const struct sockaddr& addr );
uint32_t GetNumber() const { return m_number; }
const char* GetText() const { return m_text; }
IpAddress( const IpAddress& ) = delete;
IpAddress( IpAddress&& ) = delete;
IpAddress& operator=( const IpAddress& ) = delete;
IpAddress& operator=( IpAddress&& ) = delete;
private:
uint32_t m_number;
char m_text[17];
};
class UdpListen
{
public:
UdpListen();
~UdpListen();
bool Listen( int port );
void Close();
const char* Read( size_t& len, IpAddress& addr );
UdpListen( const UdpListen& ) = delete;
UdpListen( UdpListen&& ) = delete;
UdpListen& operator=( const UdpListen& ) = delete;
UdpListen& operator=( UdpListen&& ) = delete;
private:
int m_sock;
};
}
#endif
| 20.058442 | 67 | 0.626416 | MacdaraTwomey |
c8518e8b006549f430517d66945e12d3e771e7fe | 1,609 | cpp | C++ | src/Screens/ShowOrientationScreen.cpp | underscoredotspace/watchy-revolution | 9403314a47e53565e36172c37a75d9622657c51f | [
"MIT"
] | null | null | null | src/Screens/ShowOrientationScreen.cpp | underscoredotspace/watchy-revolution | 9403314a47e53565e36172c37a75d9622657c51f | [
"MIT"
] | null | null | null | src/Screens/ShowOrientationScreen.cpp | underscoredotspace/watchy-revolution | 9403314a47e53565e36172c37a75d9622657c51f | [
"MIT"
] | null | null | null | #include "ShowOrientationScreen.h"
#include "OptimaLTStd12pt7b.h"
#include "Watchy.h"
void ShowOrientationScreen::showMe() {
Watchy::display.fillScreen(bgColor);
Watchy::display.setCursor(0,0);
Accel acc;
if (Watchy::sensor.getAccel(acc)) {
Watchy::display.printf("\n X: %d", acc.x);
Watchy::display.printf("\n Y: %d", acc.y);
Watchy::display.printf("\n Z: %d", acc.z);
} else {
Watchy::display.print("\ncan't get accel");
}
Watchy::display.printf("\ndirection\n");
uint8_t direction = Watchy::sensor.getDirection();
switch (direction) {
case DIRECTION_DISP_DOWN:
Watchy::display.print("down");
break;
case DIRECTION_DISP_UP:
Watchy::display.print("up");
break;
case DIRECTION_BOTTOM_EDGE:
Watchy::display.print("bottom");
break;
case DIRECTION_TOP_EDGE:
Watchy::display.print("top");
break;
case DIRECTION_RIGHT_EDGE:
Watchy::display.print("right");
break;
case DIRECTION_LEFT_EDGE:
Watchy::display.print("left");
break;
default:
Watchy::display.printf("%d ???", direction);
break;
}
Watchy::display.printf("\npress back to exit");
Watchy::display.display(true);
}
void ShowOrientationScreen::show() {
Watchy::display.fillScreen(bgColor);
Watchy::display.setFont(OptimaLTStd12pt7b);
showing = true;
while (showing) {
showMe();
auto timeout = millis() + 200;
while (millis() < timeout) {
Watchy::pollButtonsAndDispatch();
yield();
}
}
}
void ShowOrientationScreen::back() {
showing = false;
Screen::back();
} | 25.539683 | 52 | 0.640771 | underscoredotspace |
c85315372dc02dd2d409a8e214ea587101241a43 | 224 | hpp | C++ | RuneFramework/vendor/glm/glm/mat3x2.hpp | IvanNSBS/Rune-Engine | b0e42b143f85da44381a498a9935355083429be4 | [
"MIT"
] | 6,097 | 2015-01-03T02:11:03.000Z | 2022-03-31T03:29:58.000Z | RuneFramework/vendor/glm/glm/mat3x2.hpp | IvanNSBS/Rune-Engine | b0e42b143f85da44381a498a9935355083429be4 | [
"MIT"
] | 1,340 | 2017-08-29T15:28:41.000Z | 2022-03-31T23:45:51.000Z | RuneFramework/vendor/glm/glm/mat3x2.hpp | IvanNSBS/Rune-Engine | b0e42b143f85da44381a498a9935355083429be4 | [
"MIT"
] | 2,057 | 2015-01-03T00:07:34.000Z | 2022-03-31T22:49:17.000Z | /// @ref core
/// @file glm/mat3x2.hpp
#pragma once
#include "./ext/matrix_double3x2.hpp"
#include "./ext/matrix_double3x2_precision.hpp"
#include "./ext/matrix_float3x2.hpp"
#include "./ext/matrix_float3x2_precision.hpp"
| 22.4 | 47 | 0.745536 | IvanNSBS |
c8545b568dfb334eead1802acd50651402b756df | 53,946 | cpp | C++ | test/examples/code/3rdparty/assimp/detail/LWOLoader.cpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | test/examples/code/3rdparty/assimp/detail/LWOLoader.cpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | test/examples/code/3rdparty/assimp/detail/LWOLoader.cpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
---------------------------------------------------------------------------
*/
/** @file LWOLoader.cpp
* @brief Implementation of the LWO importer class
*/
#include "ph.hpp"
#ifndef ASSIMP_BUILD_NO_LWO_IMPORTER
// internal headers
#include "LWOLoader.h"
#include "StringComparison.h"
#include "SGSpatialSort.h"
#include "ByteSwapper.h"
#include "ProcessHelper.h"
#include "ConvertToLHProcess.h"
#include <assimp/IOSystem.hpp>
using namespace Assimp;
static const aiImporterDesc desc = {
"LightWave/Modo Object Importer",
"",
"",
"http://www.newtek.com/lightwave.html\nhttp://www.luxology.com/modo/",
aiImporterFlags_SupportTextFlavour,
0,
0,
0,
0,
"lwo lxo"
};
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
LWOImporter::LWOImporter()
: mIsLWO2(),
mIsLXOB(),
mLayers(),
mCurLayer(),
mTags(),
mMapping(),
mSurfaces(),
mFileBuffer(),
fileSize(),
pScene(),
configSpeedFlag(),
configLayerIndex(),
hasNamedLayer()
{}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
LWOImporter::~LWOImporter()
{}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool LWOImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
{
const std::string extension = GetExtension(pFile);
if (extension == "lwo" || extension == "lxo") {
return true;
}
// if check for extension is not enough, check for the magic tokens
if (!extension.length() || checkSig) {
uint32_t tokens[3];
tokens[0] = AI_LWO_FOURCC_LWOB;
tokens[1] = AI_LWO_FOURCC_LWO2;
tokens[2] = AI_LWO_FOURCC_LXOB;
return CheckMagicToken(pIOHandler,pFile,tokens,3,8);
}
return false;
}
// ------------------------------------------------------------------------------------------------
// Setup configuration properties
void LWOImporter::SetupProperties(const Importer* pImp)
{
configSpeedFlag = ( 0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0) ? true : false);
configLayerIndex = pImp->GetPropertyInteger (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,UINT_MAX);
configLayerName = pImp->GetPropertyString (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,"");
}
// ------------------------------------------------------------------------------------------------
// Get list of file extensions
const aiImporterDesc* LWOImporter::GetInfo () const
{
return &desc;
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void LWOImporter::InternReadFile( const std::string& pFile,
aiScene* pScene,
IOSystem* pIOHandler)
{
std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
// Check whether we can read from the file
if( file.get() == NULL)
throw DeadlyImportError( "Failed to open LWO file " + pFile + ".");
if((this->fileSize = (unsigned int)file->FileSize()) < 12)
throw DeadlyImportError("LWO: The file is too small to contain the IFF header");
// Allocate storage and copy the contents of the file to a memory buffer
std::vector< uint8_t > mBuffer(fileSize);
file->Read( &mBuffer[0], 1, fileSize);
this->pScene = pScene;
// Determine the type of the file
uint32_t fileType;
const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
if (sz)throw DeadlyImportError(sz);
mFileBuffer = &mBuffer[0] + 12;
fileSize -= 12;
// Initialize some members with their default values
hasNamedLayer = false;
// Create temporary storage on the stack but store pointers to it in the class
// instance. Therefore everything will be destructed properly if an exception
// is thrown and we needn't take care of that.
LayerList _mLayers;
SurfaceList _mSurfaces;
TagList _mTags;
TagMappingTable _mMapping;
mLayers = &_mLayers;
mTags = &_mTags;
mMapping = &_mMapping;
mSurfaces = &_mSurfaces;
// Allocate a default layer (layer indices are 1-based from now)
mLayers->push_back(Layer());
mCurLayer = &mLayers->back();
mCurLayer->mName = "<LWODefault>";
mCurLayer->mIndex = -1;
// old lightwave file format (prior to v6)
if (AI_LWO_FOURCC_LWOB == fileType) {
DefaultLogger::get()->info("LWO file format: LWOB (<= LightWave 5.5)");
mIsLWO2 = false;
mIsLXOB = false;
LoadLWOBFile();
}
// New lightwave format
else if (AI_LWO_FOURCC_LWO2 == fileType) {
mIsLXOB = false;
DefaultLogger::get()->info("LWO file format: LWO2 (>= LightWave 6)");
}
// MODO file format
else if (AI_LWO_FOURCC_LXOB == fileType) {
mIsLXOB = true;
DefaultLogger::get()->info("LWO file format: LXOB (Modo)");
}
// we don't know this format
else
{
char szBuff[5];
szBuff[0] = (char)(fileType >> 24u);
szBuff[1] = (char)(fileType >> 16u);
szBuff[2] = (char)(fileType >> 8u);
szBuff[3] = (char)(fileType);
szBuff[4] = '\0';
throw DeadlyImportError(std::string("Unknown LWO sub format: ") + szBuff);
}
if (AI_LWO_FOURCC_LWOB != fileType) {
mIsLWO2 = true;
LoadLWO2File();
// The newer lightwave format allows the user to configure the
// loader that just one layer is used. If this is the case
// we need to check now whether the requested layer has been found.
if (UINT_MAX != configLayerIndex) {
unsigned int layerCount = 0;
for(std::list<LWO::Layer>::iterator itLayers=mLayers->begin(); itLayers!=mLayers->end(); ++itLayers)
if (!itLayers->skip)
layerCount++;
if (layerCount!=2)
throw DeadlyImportError("LWO2: The requested layer was not found");
}
if (configLayerName.length() && !hasNamedLayer) {
throw DeadlyImportError("LWO2: Unable to find the requested layer: "
+ configLayerName);
}
}
// now, as we have loaded all data, we can resolve cross-referenced tags and clips
ResolveTags();
ResolveClips();
// now process all layers and build meshes and nodes
std::vector<aiMesh*> apcMeshes;
std::map<uint16_t, aiNode*> apcNodes;
apcMeshes.reserve(mLayers->size()*std::min(((unsigned int)mSurfaces->size()/2u), 1u));
unsigned int iDefaultSurface = UINT_MAX; // index of the default surface
for (LWO::Layer &layer : *mLayers) {
if (layer.skip)
continue;
// I don't know whether there could be dummy layers, but it would be possible
const unsigned int meshStart = (unsigned int)apcMeshes.size();
if (!layer.mFaces.empty() && !layer.mTempPoints.empty()) {
// now sort all faces by the surfaces assigned to them
std::vector<SortedRep> pSorted(mSurfaces->size()+1);
unsigned int i = 0;
for (FaceList::iterator it = layer.mFaces.begin(), end = layer.mFaces.end();it != end;++it,++i) {
// Check whether we support this face's type
if ((*it).type != AI_LWO_FACE && (*it).type != AI_LWO_PTCH &&
(*it).type != AI_LWO_BONE && (*it).type != AI_LWO_SUBD) {
continue;
}
unsigned int idx = (*it).surfaceIndex;
if (idx >= mTags->size())
{
DefaultLogger::get()->warn("LWO: Invalid face surface index");
idx = UINT_MAX;
}
if(UINT_MAX == idx || UINT_MAX == (idx = _mMapping[idx])) {
if (UINT_MAX == iDefaultSurface) {
iDefaultSurface = (unsigned int)mSurfaces->size();
mSurfaces->push_back(LWO::Surface());
LWO::Surface& surf = mSurfaces->back();
surf.mColor.r = surf.mColor.g = surf.mColor.b = 0.6f;
surf.mName = "LWODefaultSurface";
}
idx = iDefaultSurface;
}
pSorted[idx].push_back(i);
}
if (UINT_MAX == iDefaultSurface) {
pSorted.erase(pSorted.end()-1);
}
for (unsigned int p = 0,i = 0;i < mSurfaces->size();++i) {
SortedRep& sorted = pSorted[i];
if (sorted.empty())
continue;
// generate the mesh
aiMesh* mesh = new aiMesh();
apcMeshes.push_back(mesh);
mesh->mNumFaces = (unsigned int)sorted.size();
// count the number of vertices
SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
for (;it != end;++it) {
mesh->mNumVertices += layer.mFaces[*it].mNumIndices;
}
aiVector3D *nrm = NULL, * pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
mesh->mMaterialIndex = i;
// find out which vertex color channels and which texture coordinate
// channels are really required by the material attached to this mesh
unsigned int vUVChannelIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS];
unsigned int vVColorIndices[AI_MAX_NUMBER_OF_COLOR_SETS];
#ifdef ASSIMP_BUILD_DEBUG
for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui ) {
vUVChannelIndices[mui] = UINT_MAX;
}
for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui ) {
vVColorIndices[mui] = UINT_MAX;
}
#endif
FindUVChannels(_mSurfaces[i],sorted,layer,vUVChannelIndices);
FindVCChannels(_mSurfaces[i],sorted,layer,vVColorIndices);
// allocate storage for UV and CV channels
aiVector3D* pvUV[AI_MAX_NUMBER_OF_TEXTURECOORDS];
for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui ) {
if (UINT_MAX == vUVChannelIndices[mui]) {
break;
}
pvUV[mui] = mesh->mTextureCoords[mui] = new aiVector3D[mesh->mNumVertices];
// LightWave doesn't support more than 2 UV components (?)
mesh->mNumUVComponents[0] = 2;
}
if (layer.mNormals.name.length())
nrm = mesh->mNormals = new aiVector3D[mesh->mNumVertices];
aiColor4D* pvVC[AI_MAX_NUMBER_OF_COLOR_SETS];
for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui) {
if (UINT_MAX == vVColorIndices[mui]) {
break;
}
pvVC[mui] = mesh->mColors[mui] = new aiColor4D[mesh->mNumVertices];
}
// we would not need this extra array, but the code is much cleaner if we use it
std::vector<unsigned int>& smoothingGroups = layer.mPointReferrers;
smoothingGroups.erase (smoothingGroups.begin(),smoothingGroups.end());
smoothingGroups.resize(mesh->mNumFaces,0);
// now convert all faces
unsigned int vert = 0;
std::vector<unsigned int>::iterator outIt = smoothingGroups.begin();
for (it = sorted.begin(); it != end;++it,++outIt) {
const LWO::Face& face = layer.mFaces[*it];
*outIt = face.smoothGroup;
// copy all vertices
for (unsigned int q = 0; q < face.mNumIndices;++q,++vert) {
unsigned int idx = face.mIndices[q];
*pv++ = layer.mTempPoints[idx] /*- layer.mPivot*/;
// process UV coordinates
for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_TEXTURECOORDS;++w) {
if (UINT_MAX == vUVChannelIndices[w]) {
break;
}
aiVector3D*& pp = pvUV[w];
const aiVector2D& src = ((aiVector2D*)&layer.mUVChannels[vUVChannelIndices[w]].rawData[0])[idx];
pp->x = src.x;
pp->y = src.y;
pp++;
}
// process normals (MODO extension)
if (nrm) {
*nrm = ((aiVector3D*)&layer.mNormals.rawData[0])[idx];
nrm->z *= -1.f;
++nrm;
}
// process vertex colors
for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_COLOR_SETS;++w) {
if (UINT_MAX == vVColorIndices[w]) {
break;
}
*pvVC[w] = ((aiColor4D*)&layer.mVColorChannels[vVColorIndices[w]].rawData[0])[idx];
// If a RGB color map is explicitly requested delete the
// alpha channel - it could theoretically be != 1.
if(_mSurfaces[i].mVCMapType == AI_LWO_RGB)
pvVC[w]->a = 1.f;
pvVC[w]++;
}
#if 0
// process vertex weights. We can't properly reconstruct the whole skeleton for now,
// but we can create dummy bones for all weight channels which we have.
for (unsigned int w = 0; w < layer.mWeightChannels.size();++w)
{
}
#endif
face.mIndices[q] = vert;
}
pf->mIndices = face.mIndices;
pf->mNumIndices = face.mNumIndices;
unsigned int** p = (unsigned int**)&face.mIndices;*p = NULL; // HACK: make sure it won't be deleted
pf++;
}
if (!mesh->mNormals) {
// Compute normal vectors for the mesh - we can't use our GenSmoothNormal-
// Step here since it wouldn't handle smoothing groups correctly for LWO.
// So we use a separate implementation.
ComputeNormals(mesh,smoothingGroups,_mSurfaces[i]);
}
else DefaultLogger::get()->debug("LWO2: No need to compute normals, they're already there");
++p;
}
}
// Generate nodes to render the mesh. Store the source layer in the mParent member of the nodes
unsigned int num = apcMeshes.size() - meshStart;
if (layer.mName != "<LWODefault>" || num > 0) {
aiNode* pcNode = new aiNode();
apcNodes[layer.mIndex] = pcNode;
pcNode->mName.Set(layer.mName);
pcNode->mParent = (aiNode*)&layer;
pcNode->mNumMeshes = num;
if (pcNode->mNumMeshes) {
pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
for (unsigned int p = 0; p < pcNode->mNumMeshes;++p)
pcNode->mMeshes[p] = p + meshStart;
}
}
}
if (apcNodes.empty() || apcMeshes.empty())
throw DeadlyImportError("LWO: No meshes loaded");
// The RemoveRedundantMaterials step will clean this up later
pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = (unsigned int)mSurfaces->size()];
for (unsigned int mat = 0; mat < pScene->mNumMaterials;++mat) {
aiMaterial* pcMat = new aiMaterial();
pScene->mMaterials[mat] = pcMat;
ConvertMaterial((*mSurfaces)[mat],pcMat);
}
// copy the meshes to the output structure
pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = (unsigned int)apcMeshes.size() ];
::memcpy(pScene->mMeshes,&apcMeshes[0],pScene->mNumMeshes*sizeof(void*));
// generate the final node graph
GenerateNodeGraph(apcNodes);
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::ComputeNormals(aiMesh* mesh, const std::vector<unsigned int>& smoothingGroups,
const LWO::Surface& surface)
{
// Allocate output storage
mesh->mNormals = new aiVector3D[mesh->mNumVertices];
// First generate per-face normals
aiVector3D* out;
std::vector<aiVector3D> faceNormals;
// ... in some cases that's already enough
if (!surface.mMaximumSmoothAngle)
out = mesh->mNormals;
else {
faceNormals.resize(mesh->mNumVertices);
out = &faceNormals[0];
}
aiFace* begin = mesh->mFaces, *const end = mesh->mFaces+mesh->mNumFaces;
for (; begin != end; ++begin) {
aiFace& face = *begin;
if(face.mNumIndices < 3) {
continue;
}
// LWO doc: "the normal is defined as the cross product of the first and last edges"
aiVector3D* pV1 = mesh->mVertices + face.mIndices[0];
aiVector3D* pV2 = mesh->mVertices + face.mIndices[1];
aiVector3D* pV3 = mesh->mVertices + face.mIndices[face.mNumIndices-1];
aiVector3D vNor = ((*pV2 - *pV1) ^(*pV3 - *pV1)).Normalize();
for (unsigned int i = 0; i < face.mNumIndices;++i)
out[face.mIndices[i]] = vNor;
}
if (!surface.mMaximumSmoothAngle)return;
const float posEpsilon = ComputePositionEpsilon(mesh);
// Now generate the spatial sort tree
SGSpatialSort sSort;
std::vector<unsigned int>::const_iterator it = smoothingGroups.begin();
for( begin = mesh->mFaces; begin != end; ++begin, ++it)
{
aiFace& face = *begin;
for (unsigned int i = 0; i < face.mNumIndices;++i)
{
unsigned int tt = face.mIndices[i];
sSort.Add(mesh->mVertices[tt],tt,*it);
}
}
// Sort everything - this takes O(nlogn) time
sSort.Prepare();
std::vector<unsigned int> poResult;
poResult.reserve(20);
// Generate vertex normals. We have O(logn) for the binary lookup, which we need
// for n elements, thus the EXPECTED complexity is O(nlogn)
if (surface.mMaximumSmoothAngle < 3.f && !configSpeedFlag) {
const float fLimit = std::cos(surface.mMaximumSmoothAngle);
for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it) {
const aiFace& face = *begin;
unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
for (; beginIdx != endIdx; ++beginIdx)
{
unsigned int idx = *beginIdx;
sSort.FindPositions(mesh->mVertices[idx],*it,posEpsilon,poResult,true);
std::vector<unsigned int>::const_iterator a, end = poResult.end();
aiVector3D vNormals;
for (a = poResult.begin();a != end;++a) {
const aiVector3D& v = faceNormals[*a];
if (v * faceNormals[idx] < fLimit)
continue;
vNormals += v;
}
mesh->mNormals[idx] = vNormals.Normalize();
}
}
}
// faster code path in case there is no smooth angle
else {
std::vector<bool> vertexDone(mesh->mNumVertices,false);
for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it) {
const aiFace& face = *begin;
unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
for (; beginIdx != endIdx; ++beginIdx)
{
unsigned int idx = *beginIdx;
if (vertexDone[idx])
continue;
sSort.FindPositions(mesh->mVertices[idx],*it,posEpsilon,poResult,true);
std::vector<unsigned int>::const_iterator a, end = poResult.end();
aiVector3D vNormals;
for (a = poResult.begin();a != end;++a) {
const aiVector3D& v = faceNormals[*a];
vNormals += v;
}
vNormals.Normalize();
for (a = poResult.begin();a != end;++a) {
mesh->mNormals[*a] = vNormals;
vertexDone[*a] = true;
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::GenerateNodeGraph(std::map<uint16_t,aiNode*>& apcNodes)
{
// now generate the final nodegraph - generate a root node and attach children
aiNode* root = pScene->mRootNode = new aiNode();
root->mName.Set("<LWORoot>");
//Set parent of all children, inserting pivots
//std::cout << "Set parent of all children" << std::endl;
std::map<uint16_t, aiNode*> mapPivot;
for (std::map<uint16_t,aiNode*>::iterator itapcNodes = apcNodes.begin(); itapcNodes != apcNodes.end(); ++itapcNodes) {
//Get the parent index
LWO::Layer* nodeLayer = (LWO::Layer*)(itapcNodes->second->mParent);
uint16_t parentIndex = nodeLayer->mParent;
//Create pivot node, store it into the pivot map, and set the parent as the pivot
aiNode* pivotNode = new aiNode();
pivotNode->mName.Set("Pivot-"+std::string(itapcNodes->second->mName.data));
mapPivot[-(itapcNodes->first+2)] = pivotNode;
itapcNodes->second->mParent = pivotNode;
//Look for the parent node to attach the pivot to
if (apcNodes.find(parentIndex) != apcNodes.end()) {
pivotNode->mParent = apcNodes[parentIndex];
} else {
//If not, attach to the root node
pivotNode->mParent = root;
}
//Set the node and the pivot node transformation
itapcNodes->second->mTransformation.a4 = -nodeLayer->mPivot.x;
itapcNodes->second->mTransformation.b4 = -nodeLayer->mPivot.y;
itapcNodes->second->mTransformation.c4 = -nodeLayer->mPivot.z;
pivotNode->mTransformation.a4 = nodeLayer->mPivot.x;
pivotNode->mTransformation.b4 = nodeLayer->mPivot.y;
pivotNode->mTransformation.c4 = nodeLayer->mPivot.z;
}
//Merge pivot map into node map
//std::cout << "Merge pivot map into node map" << std::endl;
for (std::map<uint16_t, aiNode*>::iterator itMapPivot = mapPivot.begin(); itMapPivot != mapPivot.end(); ++itMapPivot) {
apcNodes[itMapPivot->first] = itMapPivot->second;
}
//Set children of all parents
apcNodes[-1] = root;
for (std::map<uint16_t,aiNode*>::iterator itMapParentNodes = apcNodes.begin(); itMapParentNodes != apcNodes.end(); ++itMapParentNodes) {
for (std::map<uint16_t,aiNode*>::iterator itMapChildNodes = apcNodes.begin(); itMapChildNodes != apcNodes.end(); ++itMapChildNodes) {
if ((itMapParentNodes->first != itMapChildNodes->first) && (itMapParentNodes->second == itMapChildNodes->second->mParent)) {
++(itMapParentNodes->second->mNumChildren);
}
}
if (itMapParentNodes->second->mNumChildren) {
itMapParentNodes->second->mChildren = new aiNode* [ itMapParentNodes->second->mNumChildren ];
uint16_t p = 0;
for (std::map<uint16_t,aiNode*>::iterator itMapChildNodes = apcNodes.begin(); itMapChildNodes != apcNodes.end(); ++itMapChildNodes) {
if ((itMapParentNodes->first != itMapChildNodes->first) && (itMapParentNodes->second == itMapChildNodes->second->mParent)) {
itMapParentNodes->second->mChildren[p++] = itMapChildNodes->second;
}
}
}
}
if (!pScene->mRootNode->mNumChildren)
throw DeadlyImportError("LWO: Unable to build a valid node graph");
// Remove a single root node with no meshes assigned to it ...
if (1 == pScene->mRootNode->mNumChildren) {
aiNode* pc = pScene->mRootNode->mChildren[0];
pc->mParent = pScene->mRootNode->mChildren[0] = NULL;
delete pScene->mRootNode;
pScene->mRootNode = pc;
}
// convert the whole stuff to RH with CCW winding
MakeLeftHandedProcess maker;
maker.Execute(pScene);
FlipWindingOrderProcess flipper;
flipper.Execute(pScene);
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::ResolveTags()
{
// --- this function is used for both LWO2 and LWOB
mMapping->resize(mTags->size(), UINT_MAX);
for (unsigned int a = 0; a < mTags->size();++a) {
const std::string& c = (*mTags)[a];
for (unsigned int i = 0; i < mSurfaces->size();++i) {
const std::string& d = (*mSurfaces)[i].mName;
if (!ASSIMP_stricmp(c,d)) {
(*mMapping)[a] = i;
break;
}
}
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::ResolveClips()
{
for( unsigned int i = 0; i < mClips.size();++i) {
Clip& clip = mClips[i];
if (Clip::REF == clip.type) {
if (clip.clipRef >= mClips.size()) {
DefaultLogger::get()->error("LWO2: Clip referrer index is out of range");
clip.clipRef = 0;
}
Clip& dest = mClips[clip.clipRef];
if (Clip::REF == dest.type) {
DefaultLogger::get()->error("LWO2: Clip references another clip reference");
clip.type = Clip::UNSUPPORTED;
}
else {
clip.path = dest.path;
clip.type = dest.type;
}
}
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::AdjustTexturePath(std::string& out)
{
// --- this function is used for both LWO2 and LWOB
if (!mIsLWO2 && ::strstr(out.c_str(), "(sequence)")) {
// remove the (sequence) and append 000
DefaultLogger::get()->info("LWOB: Sequence of animated texture found. It will be ignored");
out = out.substr(0,out.length()-10) + "000";
}
// format: drive:path/file - we just need to insert a slash after the drive
std::string::size_type n = out.find_first_of(':');
if (std::string::npos != n) {
out.insert(n+1,"/");
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::LoadLWOTags(unsigned int size)
{
// --- this function is used for both LWO2 and LWOB
const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
const char* const szEnd = szLast+size;
while (szCur < szEnd)
{
if (!(*szCur))
{
const size_t len = (size_t)(szCur-szLast);
// FIX: skip empty-sized tags
if (len)
mTags->push_back(std::string(szLast,len));
szCur += (len&0x1 ? 1 : 2);
szLast = szCur;
}
szCur++;
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::LoadLWOPoints(unsigned int length)
{
// --- this function is used for both LWO2 and LWOB but for
// LWO2 we need to allocate 25% more storage - it could be we'll
// need to duplicate some points later.
const size_t vertexLen = 12;
if ((length % vertexLen) != 0)
{
throw DeadlyImportError( "LWO2: Points chunk length is not multiple of vertexLen (12)");
}
unsigned int regularSize = (unsigned int)mCurLayer->mTempPoints.size() + length / 12;
if (mIsLWO2)
{
mCurLayer->mTempPoints.reserve ( regularSize + (regularSize>>2u) );
mCurLayer->mTempPoints.resize ( regularSize );
// initialize all point referrers with the default values
mCurLayer->mPointReferrers.reserve ( regularSize + (regularSize>>2u) );
mCurLayer->mPointReferrers.resize ( regularSize, UINT_MAX );
}
else mCurLayer->mTempPoints.resize( regularSize );
// perform endianness conversions
#ifndef AI_BUILD_BIG_ENDIAN
for (unsigned int i = 0; i < length>>2;++i)
ByteSwap::Swap4( mFileBuffer + (i << 2));
#endif
::memcpy(&mCurLayer->mTempPoints[0],mFileBuffer,length);
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::LoadLWO2Polygons(unsigned int length)
{
LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length);
const uint32_t type = GetU4();
// Determine the type of the polygons
switch (type)
{
// read unsupported stuff too (although we wont process it)
case AI_LWO_MBAL:
DefaultLogger::get()->warn("LWO2: Encountered unsupported primitive chunk (METABALL)");
break;
case AI_LWO_CURV:
DefaultLogger::get()->warn("LWO2: Encountered unsupported primitive chunk (SPLINE)");;
break;
// These are ok with no restrictions
case AI_LWO_PTCH:
case AI_LWO_FACE:
case AI_LWO_BONE:
case AI_LWO_SUBD:
break;
default:
// hm!? wtf is this? ok ...
DefaultLogger::get()->error("LWO2: Ignoring unknown polygon type.");
break;
}
// first find out how many faces and vertices we'll finally need
uint16_t* cursor= (uint16_t*)mFileBuffer;
unsigned int iNumFaces = 0,iNumVertices = 0;
CountVertsAndFacesLWO2(iNumVertices,iNumFaces,cursor,end);
// allocate the output array and copy face indices
if (iNumFaces)
{
cursor = (uint16_t*)mFileBuffer;
mCurLayer->mFaces.resize(iNumFaces,LWO::Face(type));
FaceList::iterator it = mCurLayer->mFaces.begin();
CopyFaceIndicesLWO2(it,cursor,end);
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::CountVertsAndFacesLWO2(unsigned int& verts, unsigned int& faces,
uint16_t*& cursor, const uint16_t* const end, unsigned int max)
{
while (cursor < end && max--)
{
uint16_t numIndices;
::memcpy(&numIndices, cursor++, 2);
AI_LSWAP2(numIndices);
numIndices &= 0x03FF;
verts += numIndices;
++faces;
for(uint16_t i = 0; i < numIndices; i++)
{
ReadVSizedIntLWO2((uint8_t*&)cursor);
}
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::CopyFaceIndicesLWO2(FaceList::iterator& it,
uint16_t*& cursor,
const uint16_t* const end)
{
while (cursor < end)
{
LWO::Face& face = *it++;
uint16_t numIndices;
::memcpy(&numIndices, cursor++, 2);
AI_LSWAP2(numIndices);
face.mNumIndices = numIndices & 0x03FF;
if(face.mNumIndices) /* byte swapping has already been done */
{
face.mIndices = new unsigned int[face.mNumIndices];
for(unsigned int i = 0; i < face.mNumIndices; i++)
{
face.mIndices[i] = ReadVSizedIntLWO2((uint8_t*&)cursor) + mCurLayer->mPointIDXOfs;
if(face.mIndices[i] > mCurLayer->mTempPoints.size())
{
DefaultLogger::get()->warn("LWO2: Failure evaluating face record, index is out of range");
face.mIndices[i] = (unsigned int)mCurLayer->mTempPoints.size()-1;
}
}
}
else throw DeadlyImportError("LWO2: Encountered invalid face record with zero indices");
}
}
// ------------------------------------------------------------------------------------------------
void LWOImporter::LoadLWO2PolygonTags(unsigned int length)
{
LE_NCONST uint8_t* const end = mFileBuffer+length;
AI_LWO_VALIDATE_CHUNK_LENGTH(length,PTAG,4);
uint32_t type = GetU4();
if (type != AI_LWO_SURF && type != AI_LWO_SMGP)
return;
while (mFileBuffer < end)
{
unsigned int i = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
unsigned int j = GetU2();
if (i >= mCurLayer->mFaces.size()) {
DefaultLogger::get()->warn("LWO2: face index in PTAG is out of range");
continue;
}
switch (type) {
case AI_LWO_SURF:
mCurLayer->mFaces[i].surfaceIndex = j;
break;
case AI_LWO_SMGP: /* is that really used? */
mCurLayer->mFaces[i].smoothGroup = j;
break;
};
}
}
// ------------------------------------------------------------------------------------------------
template <class T>
VMapEntry* FindEntry(std::vector< T >& list,const std::string& name, bool perPoly)
{
for (auto & elem : list) {
if (elem.name == name) {
if (!perPoly) {
DefaultLogger::get()->warn("LWO2: Found two VMAP sections with equal names");
}
return &elem;
}
}
list.push_back( T() );
VMapEntry* p = &list.back();
p->name = name;
return p;
}
// ------------------------------------------------------------------------------------------------
template <class T>
inline void CreateNewEntry(T& chan, unsigned int srcIdx)
{
if (!chan.name.length())
return;
chan.abAssigned[srcIdx] = true;
chan.abAssigned.resize(chan.abAssigned.size()+1,false);
for (unsigned int a = 0; a < chan.dims;++a)
chan.rawData.push_back(chan.rawData[srcIdx*chan.dims+a]);
}
// ------------------------------------------------------------------------------------------------
template <class T>
inline void CreateNewEntry(std::vector< T >& list, unsigned int srcIdx)
{
for (auto &elem : list) {
CreateNewEntry( elem, srcIdx );
}
}
// ------------------------------------------------------------------------------------------------
inline void LWOImporter::DoRecursiveVMAPAssignment(VMapEntry* base, unsigned int numRead,
unsigned int idx, float* data)
{
ai_assert(NULL != data);
LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
unsigned int i;
if (idx >= base->abAssigned.size()) {
throw DeadlyImportError("Bad index");
}
base->abAssigned[idx] = true;
for (i = 0; i < numRead;++i) {
base->rawData[idx*base->dims+i]= data[i];
}
if (UINT_MAX != (i = refList[idx])) {
DoRecursiveVMAPAssignment(base,numRead,i,data);
}
}
// ------------------------------------------------------------------------------------------------
inline void AddToSingleLinkedList(ReferrerList& refList, unsigned int srcIdx, unsigned int destIdx)
{
if(UINT_MAX == refList[srcIdx]) {
refList[srcIdx] = destIdx;
return;
}
AddToSingleLinkedList(refList,refList[srcIdx],destIdx);
}
// ------------------------------------------------------------------------------------------------
// Load LWO2 vertex map
void LWOImporter::LoadLWO2VertexMap(unsigned int length, bool perPoly)
{
LE_NCONST uint8_t* const end = mFileBuffer+length;
AI_LWO_VALIDATE_CHUNK_LENGTH(length,VMAP,6);
unsigned int type = GetU4();
unsigned int dims = GetU2();
VMapEntry* base;
// read the name of the vertex map
std::string name;
GetS0(name,length);
switch (type)
{
case AI_LWO_TXUV:
if (dims != 2) {
DefaultLogger::get()->warn("LWO2: Skipping UV channel \'"
+ name + "\' with !2 components");
return;
}
base = FindEntry(mCurLayer->mUVChannels,name,perPoly);
break;
case AI_LWO_WGHT:
case AI_LWO_MNVW:
if (dims != 1) {
DefaultLogger::get()->warn("LWO2: Skipping Weight Channel \'"
+ name + "\' with !1 components");
return;
}
base = FindEntry((type == AI_LWO_WGHT ? mCurLayer->mWeightChannels
: mCurLayer->mSWeightChannels),name,perPoly);
break;
case AI_LWO_RGB:
case AI_LWO_RGBA:
if (dims != 3 && dims != 4) {
DefaultLogger::get()->warn("LWO2: Skipping Color Map \'"
+ name + "\' with a dimension > 4 or < 3");
return;
}
base = FindEntry(mCurLayer->mVColorChannels,name,perPoly);
break;
case AI_LWO_MODO_NORM:
/* This is a non-standard extension chunk used by Luxology's MODO.
* It stores per-vertex normals. This VMAP exists just once, has
* 3 dimensions and is btw extremely beautiful.
*/
if (name != "vert_normals" || dims != 3 || mCurLayer->mNormals.name.length())
return;
DefaultLogger::get()->info("Processing non-standard extension: MODO VMAP.NORM.vert_normals");
mCurLayer->mNormals.name = name;
base = & mCurLayer->mNormals;
break;
case AI_LWO_PICK: /* these VMAPs are just silently dropped */
case AI_LWO_MORF:
case AI_LWO_SPOT:
return;
default:
if (name == "APS.Level") {
// XXX handle this (seems to be subdivision-related).
}
DefaultLogger::get()->warn("LWO2: Skipping unknown VMAP/VMAD channel \'" + name + "\'");
return;
};
base->Allocate((unsigned int)mCurLayer->mTempPoints.size());
// now read all entries in the map
type = std::min(dims,base->dims);
const unsigned int diff = (dims - type)<<2u;
LWO::FaceList& list = mCurLayer->mFaces;
LWO::PointList& pointList = mCurLayer->mTempPoints;
LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
float temp[4];
const unsigned int numPoints = (unsigned int)pointList.size();
const unsigned int numFaces = (unsigned int)list.size();
while (mFileBuffer < end) {
unsigned int idx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mPointIDXOfs;
if (idx >= numPoints) {
DefaultLogger::get()->warn("LWO2: Failure evaluating VMAP/VMAD entry \'" + name + "\', vertex index is out of range");
mFileBuffer += base->dims<<2u;
continue;
}
if (perPoly) {
unsigned int polyIdx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
if (base->abAssigned[idx]) {
// we have already a VMAP entry for this vertex - thus
// we need to duplicate the corresponding polygon.
if (polyIdx >= numFaces) {
DefaultLogger::get()->warn("LWO2: Failure evaluating VMAD entry \'" + name + "\', polygon index is out of range");
mFileBuffer += base->dims<<2u;
continue;
}
LWO::Face& src = list[polyIdx];
// generate a new unique vertex for the corresponding index - but only
// if we can find the index in the face
bool had = false;
for (unsigned int i = 0; i < src.mNumIndices;++i) {
unsigned int srcIdx = src.mIndices[i], tmp = idx;
do {
if (tmp == srcIdx)
break;
}
while ((tmp = refList[tmp]) != UINT_MAX);
if (tmp == UINT_MAX) {
continue;
}
had = true;
refList.resize(refList.size()+1, UINT_MAX);
idx = (unsigned int)pointList.size();
src.mIndices[i] = (unsigned int)pointList.size();
// store the index of the new vertex in the old vertex
// so we get a single linked list we can traverse in
// only one direction
AddToSingleLinkedList(refList,srcIdx,src.mIndices[i]);
pointList.push_back(pointList[srcIdx]);
CreateNewEntry(mCurLayer->mVColorChannels, srcIdx );
CreateNewEntry(mCurLayer->mUVChannels, srcIdx );
CreateNewEntry(mCurLayer->mWeightChannels, srcIdx );
CreateNewEntry(mCurLayer->mSWeightChannels, srcIdx );
CreateNewEntry(mCurLayer->mNormals, srcIdx );
}
if (!had) {
DefaultLogger::get()->warn("LWO2: Failure evaluating VMAD entry \'" + name + "\', vertex index wasn't found in that polygon");
ai_assert(had);
}
}
}
for (unsigned int l = 0; l < type;++l)
temp[l] = GetF4();
DoRecursiveVMAPAssignment(base,type,idx, temp);
mFileBuffer += diff;
}
}
// ------------------------------------------------------------------------------------------------
// Load LWO2 clip
void LWOImporter::LoadLWO2Clip(unsigned int length)
{
AI_LWO_VALIDATE_CHUNK_LENGTH(length,CLIP,10);
mClips.push_back(LWO::Clip());
LWO::Clip& clip = mClips.back();
// first - get the index of the clip
clip.idx = GetU4();
IFF::SubChunkHeader head = IFF::LoadSubChunk(mFileBuffer);
switch (head.type)
{
case AI_LWO_STIL:
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,STIL,1);
// "Normal" texture
GetS0(clip.path,head.length);
clip.type = Clip::STILL;
break;
case AI_LWO_ISEQ:
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,ISEQ,16);
// Image sequence. We'll later take the first.
{
uint8_t digits = GetU1(); mFileBuffer++;
int16_t offset = GetU2(); mFileBuffer+=4;
int16_t start = GetU2(); mFileBuffer+=4;
std::string s;
std::ostringstream ss;
GetS0(s,head.length);
head.length -= (uint16_t)s.length()+1;
ss << s;
ss << std::setw(digits) << offset + start;
GetS0(s,head.length);
ss << s;
clip.path = ss.str();
clip.type = Clip::SEQ;
}
break;
case AI_LWO_STCC:
DefaultLogger::get()->warn("LWO2: Color shifted images are not supported");
break;
case AI_LWO_ANIM:
DefaultLogger::get()->warn("LWO2: Animated textures are not supported");
break;
case AI_LWO_XREF:
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,XREF,4);
// Just a cross-reference to another CLIp
clip.type = Clip::REF;
clip.clipRef = GetU4();
break;
case AI_LWO_NEGA:
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,NEGA,2);
clip.negate = (0 != GetU2());
break;
default:
DefaultLogger::get()->warn("LWO2: Encountered unknown CLIP subchunk");
}
}
// ------------------------------------------------------------------------------------------------
// Load envelope description
void LWOImporter::LoadLWO2Envelope(unsigned int length)
{
LE_NCONST uint8_t* const end = mFileBuffer + length;
AI_LWO_VALIDATE_CHUNK_LENGTH(length,ENVL,4);
mEnvelopes.push_back(LWO::Envelope());
LWO::Envelope& envelope = mEnvelopes.back();
// Get the index of the envelope
envelope.index = ReadVSizedIntLWO2(mFileBuffer);
// It looks like there might be an extra U4 right after the index,
// at least in modo (LXOB) files: we'll ignore it if it's zero,
// otherwise it represents the start of a subchunk, so we backtrack.
if (mIsLXOB)
{
uint32_t extra = GetU4();
if (extra)
{
mFileBuffer -= 4;
}
}
// ... and read all subchunks
while (true)
{
if (mFileBuffer + 6 >= end)break;
LE_NCONST IFF::SubChunkHeader head = IFF::LoadSubChunk(mFileBuffer);
if (mFileBuffer + head.length > end)
throw DeadlyImportError("LWO2: Invalid envelope chunk length");
uint8_t* const next = mFileBuffer+head.length;
switch (head.type)
{
// Type & representation of the envelope
case AI_LWO_TYPE:
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,TYPE,2);
mFileBuffer++; // skip user format
// Determine type of envelope
envelope.type = (LWO::EnvelopeType)*mFileBuffer;
++mFileBuffer;
break;
// precondition
case AI_LWO_PRE:
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,PRE,2);
envelope.pre = (LWO::PrePostBehaviour)GetU2();
break;
// postcondition
case AI_LWO_POST:
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,POST,2);
envelope.post = (LWO::PrePostBehaviour)GetU2();
break;
// keyframe
case AI_LWO_KEY:
{
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,KEY,8);
envelope.keys.push_back(LWO::Key());
LWO::Key& key = envelope.keys.back();
key.time = GetF4();
key.value = GetF4();
break;
}
// interval interpolation
case AI_LWO_SPAN:
{
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,SPAN,4);
if (envelope.keys.size()<2)
DefaultLogger::get()->warn("LWO2: Unexpected SPAN chunk");
else {
LWO::Key& key = envelope.keys.back();
switch (GetU4())
{
case AI_LWO_STEP:
key.inter = LWO::IT_STEP;break;
case AI_LWO_LINE:
key.inter = LWO::IT_LINE;break;
case AI_LWO_TCB:
key.inter = LWO::IT_TCB;break;
case AI_LWO_HERM:
key.inter = LWO::IT_HERM;break;
case AI_LWO_BEZI:
key.inter = LWO::IT_BEZI;break;
case AI_LWO_BEZ2:
key.inter = LWO::IT_BEZ2;break;
default:
DefaultLogger::get()->warn("LWO2: Unknown interval interpolation mode");
};
// todo ... read params
}
break;
}
default:
DefaultLogger::get()->warn("LWO2: Encountered unknown ENVL subchunk");
}
// regardless how much we did actually read, go to the next chunk
mFileBuffer = next;
}
}
// ------------------------------------------------------------------------------------------------
// Load file - master function
void LWOImporter::LoadLWO2File()
{
bool skip = false;
LE_NCONST uint8_t* const end = mFileBuffer + fileSize;
while (true)
{
if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break;
const IFF::ChunkHeader head = IFF::LoadChunk(mFileBuffer);
if (mFileBuffer + head.length > end)
{
throw DeadlyImportError("LWO2: Chunk length points behind the file");
break;
}
uint8_t* const next = mFileBuffer+head.length;
unsigned int iUnnamed = 0;
if(!head.length) {
mFileBuffer = next;
continue;
}
switch (head.type)
{
// new layer
case AI_LWO_LAYR:
{
// add a new layer to the list ....
mLayers->push_back ( LWO::Layer() );
LWO::Layer& layer = mLayers->back();
mCurLayer = &layer;
AI_LWO_VALIDATE_CHUNK_LENGTH(head.length,LAYR,16);
// layer index.
layer.mIndex = GetU2();
// Continue loading this layer or ignore it? Check the layer index property
if (UINT_MAX != configLayerIndex && (configLayerIndex-1) != layer.mIndex) {
skip = true;
}
else skip = false;
// pivot point
mFileBuffer += 2; /* unknown */
mCurLayer->mPivot.x = GetF4();
mCurLayer->mPivot.y = GetF4();
mCurLayer->mPivot.z = GetF4();
GetS0(layer.mName,head.length-16);
// if the name is empty, generate a default name
if (layer.mName.empty()) {
char buffer[128]; // should be sufficiently large
::ai_snprintf(buffer, 128, "Layer_%i", iUnnamed++);
layer.mName = buffer;
}
// load this layer or ignore it? Check the layer name property
if (configLayerName.length() && configLayerName != layer.mName) {
skip = true;
}
else hasNamedLayer = true;
// optional: parent of this layer
if (mFileBuffer + 2 <= next)
layer.mParent = GetU2();
else layer.mParent = -1;
// Set layer skip parameter
layer.skip = skip;
break;
}
// vertex list
case AI_LWO_PNTS:
{
if (skip)
break;
unsigned int old = (unsigned int)mCurLayer->mTempPoints.size();
LoadLWOPoints(head.length);
mCurLayer->mPointIDXOfs = old;
break;
}
// vertex tags
case AI_LWO_VMAD:
if (mCurLayer->mFaces.empty())
{
DefaultLogger::get()->warn("LWO2: Unexpected VMAD chunk");
break;
}
// --- intentionally no break here
case AI_LWO_VMAP:
{
if (skip)
break;
if (mCurLayer->mTempPoints.empty())
DefaultLogger::get()->warn("LWO2: Unexpected VMAP chunk");
else LoadLWO2VertexMap(head.length,head.type == AI_LWO_VMAD);
break;
}
// face list
case AI_LWO_POLS:
{
if (skip)
break;
unsigned int old = (unsigned int)mCurLayer->mFaces.size();
LoadLWO2Polygons(head.length);
mCurLayer->mFaceIDXOfs = old;
break;
}
// polygon tags
case AI_LWO_PTAG:
{
if (skip)
break;
if (mCurLayer->mFaces.empty())
DefaultLogger::get()->warn("LWO2: Unexpected PTAG");
else LoadLWO2PolygonTags(head.length);
break;
}
// list of tags
case AI_LWO_TAGS:
{
if (!mTags->empty())
DefaultLogger::get()->warn("LWO2: SRFS chunk encountered twice");
else LoadLWOTags(head.length);
break;
}
// surface chunk
case AI_LWO_SURF:
{
LoadLWO2Surface(head.length);
break;
}
// clip chunk
case AI_LWO_CLIP:
{
LoadLWO2Clip(head.length);
break;
}
// envelope chunk
case AI_LWO_ENVL:
{
LoadLWO2Envelope(head.length);
break;
}
}
mFileBuffer = next;
}
}
#endif // !! ASSIMP_BUILD_NO_LWO_IMPORTER
| 36.54878 | 146 | 0.528306 | maikebing |
c856fe947589d7709e9114760b5dee39312e1abf | 942 | cpp | C++ | Challenge-2021-08/03_subsets_II.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-08/03_subsets_II.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-08/03_subsets_II.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | #include "../header.h"
class Solution {
vector<int> temp;
vector<vector<int>> res;
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
int total = 1 << n; // n <= 10
for (int mask = 0; mask < total; ++mask) {
temp.clear();
bool flag = true;
for (int i = 0; i < n; ++i) {
if (mask & (1 << i)) {
// the previous is not pick this time
// actually it's a duplicate this round
if (i > 0 && nums[i] == nums[i-1] && ((mask >> (i-1)) & 1) == 0) {
flag = false;
break;
}
temp.push_back(nums[i]);
}
}
if (flag) {
res.push_back(temp);
}
}
return res;
}
}; | 30.387097 | 86 | 0.381104 | qiufengyu |
c8578edc0e09188fb1cc224df4794f9b3731131b | 5,386 | cpp | C++ | src/io/frontend_io/unvmf_io_handler.cpp | hsungyang/poseidonos | 0f523b36ccf0d70726364395ea96ac6ae3b845c3 | [
"BSD-3-Clause"
] | 38 | 2021-04-06T03:20:55.000Z | 2022-03-02T09:33:28.000Z | src/io/frontend_io/unvmf_io_handler.cpp | gye-ul/poseidonos | bce8fe2cd1f36ede8647446ecc4cf8a9749e6918 | [
"BSD-3-Clause"
] | 19 | 2021-04-08T02:27:44.000Z | 2022-03-23T00:59:04.000Z | src/io/frontend_io/unvmf_io_handler.cpp | gye-ul/poseidonos | bce8fe2cd1f36ede8647446ecc4cf8a9749e6918 | [
"BSD-3-Clause"
] | 28 | 2021-04-08T04:39:18.000Z | 2022-03-24T05:56:00.000Z | /*
* BSD LICENSE
* Copyright (c) 2021 Samsung Electronics Corporation
* 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 Samsung Electronics Corporation 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 "src/volume/volume_manager.h"
#include "src/event_scheduler/io_completer.h"
#include "src/io/frontend_io/unvmf_io_handler.h"
#include <vector>
#include "spdk/pos.h"
#include "src/include/pos_event_id.hpp"
#include "src/include/branch_prediction.h"
#include "src/io/frontend_io/aio.h"
#include "src/bio/ubio.h"
#include "src/logger/logger.h"
#include "src/event_scheduler/event.h"
#include "src/event_scheduler/event_scheduler.h"
#include "src/spdk_wrapper/event_framework_api.h"
#include "src/qos/qos_manager.h"
#include "src/io/frontend_io/aio_submission_adapter.h"
using namespace pos;
using namespace std;
void
UNVMfCompleteHandler(void)
{
try
{
AIO aio;
aio.CompleteIOs();
EventFrameworkApiSingleton::Instance()->CompleteEvents();
}
catch (...)
{
POS_EVENT_ID eventId = POS_EVENT_ID::SCHEDAPI_COMPLETION_POLLING_FAIL;
POS_TRACE_ERROR(static_cast<int>(eventId),
"Fail to poll ibof completion");
}
}
int
UNVMfSubmitHandler(struct pos_io* io)
{
try
{
if (unlikely(nullptr == io))
{
POS_EVENT_ID eventId = POS_EVENT_ID::SCHEDAPI_NULL_COMMAND;
POS_TRACE_ERROR(static_cast<int>(eventId),
"Command from bdev is empty");
throw eventId;
}
if (io->ioType > IO_TYPE::ADMIN)
{
AIO aio;
aio.SubmitAsyncAdmin(*io);
return POS_IO_STATUS_SUCCESS;
}
switch (io->ioType)
{
case IO_TYPE::READ:
case IO_TYPE::WRITE:
{
if (unlikely(1 != io->iovcnt))
{
POS_EVENT_ID eventId = POS_EVENT_ID::SCHEDAPI_WRONG_BUFFER;
POS_TRACE_ERROR(static_cast<int>(eventId),
"Single IO command should have a continuous buffer");
throw eventId;
}
break;
}
case IO_TYPE::FLUSH:
{
AIO aio;
aio.SubmitAsyncIO(*io);
return POS_IO_STATUS_SUCCESS;
}
break;
default:
{
POS_EVENT_ID eventId = POS_EVENT_ID::BLKHDLR_WRONG_IO_DIRECTION;
POS_TRACE_ERROR(eventId, "Wrong IO direction (only read/write types are suppoered)");
throw eventId;
break;
}
}
QosManager* qosManager = QosManagerSingleton::Instance();
IVolumeManager* volumeManager
= VolumeServiceSingleton::Instance()->GetVolumeManager(io->array_id);
if (unlikely(static_cast<int>(POS_EVENT_ID::SUCCESS) != volumeManager->IncreasePendingIOCountIfNotZero(io->volume_id)))
{
AIO aio;
VolumeIoSmartPtr volumeIo = aio.CreateVolumeIo(*io);
IoCompleter ioCompleter(volumeIo);
ioCompleter.CompleteUbioWithoutRecovery(IOErrorType::VOLUME_UMOUNTED, true);
return POS_IO_STATUS_SUCCESS;
}
if (true == qosManager->IsFeQosEnabled())
{
AioSubmissionAdapter aioSubmission;
qosManager->HandlePosIoSubmission(&aioSubmission, io);
}
else
{
AIO aio;
aio.SubmitAsyncIO(*io);
}
}
catch (...)
{
POS_EVENT_ID eventId = POS_EVENT_ID::SCHEDAPI_SUBMISSION_FAIL;
POS_TRACE_ERROR(static_cast<int>(eventId),
"Fail to submit ibof IO");
if (nullptr != io && nullptr != io->complete_cb)
{
io->complete_cb(io, POS_IO_STATUS_FAIL);
}
}
return POS_IO_STATUS_SUCCESS;
}
| 34.305732 | 127 | 0.630524 | hsungyang |
c8586c1a94963d672798450f73fa3184979e0da4 | 1,424 | hpp | C++ | src/CardCanvas/AlarmPanelCardCanvas.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | 2 | 2020-10-23T19:53:56.000Z | 2020-11-06T08:59:48.000Z | src/CardCanvas/AlarmPanelCardCanvas.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | src/CardCanvas/AlarmPanelCardCanvas.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | #ifndef __ALARMPANELCARDCANVAS_H__
#define __ALARMPANELCARDCANVAS_H__
#include "CardCanvas.hpp"
#include <Canvas/ImageCanvas.hpp>
#include <Canvas/TextCanvas.hpp>
#include <Canvas/NumberPadCanvas.hpp>
#include "LovelaceConfig/AlarmPanelCardConfig.hpp"
#include "HomeAssistant/Components/AlarmControlPanel.hpp"
#include <list>
class AlarmPanelCardCanvas : public CardCanvas {
public:
AlarmPanelCardCanvas(Canvas * canvas, uint16_t id, HomeAssistantManager * hass, AlarmPanelCardConfig * cardConfig, LcdTheme * theme);
virtual ~AlarmPanelCardCanvas();
static constexpr int MAX_STATE_BUTTONS = 3;
static constexpr int MAX_CODE_SIZE = 10;
virtual const char * getCardTitle();
virtual const char * getCardIcon();
virtual void update();
protected:
uint32_t prevTime = 0;
bool iconState = false;
uint8_t code[MAX_CODE_SIZE];
int8_t codeIndex = 0;
NumberPadCanvas * numPadCanvas;
TextCanvas * codeCanvas;
TextCanvas * stateChangeButtonCanvas[MAX_STATE_BUTTONS];
ImageCanvas * stateCanvas;
ImageCanvas * passwordVisibilityToggleButton;
bool passwordVisible = false;
uint8_t numStateButtons = 0;
AlarmPanelCardConfig * cardConfig;
AlarmControlPanel * entity;
std::list<string> states;
void setCodeString();
};
#endif // __ALARMPANELCARDCANVAS_H__ | 35.6 | 141 | 0.707865 | RobinSinghNanda |
c859a157c7f49e0b6967e486a0e93c0fcd4b708b | 1,369 | cpp | C++ | src/layers/reductions/layer_reduction.cpp | ilveroluca/eddl | 02e37c0dfb674468495f4d0ae3c159de3b2d3cc0 | [
"MIT"
] | null | null | null | src/layers/reductions/layer_reduction.cpp | ilveroluca/eddl | 02e37c0dfb674468495f4d0ae3c159de3b2d3cc0 | [
"MIT"
] | null | null | null | src/layers/reductions/layer_reduction.cpp | ilveroluca/eddl | 02e37c0dfb674468495f4d0ae3c159de3b2d3cc0 | [
"MIT"
] | null | null | null | /*
* EDDL Library - European Distributed Deep Learning Library.
* Version: 0.6
* copyright (c) 2020, Universidad Politécnica de Valencia (UPV), PRHLT Research Centre
* Date: April 2020
* Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es)
* All rights reserved
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include "eddl/layers/reductions/layer_reductions.h"
using namespace std;
ReductionLayer::ReductionLayer(string name, int dev, int mem) : Layer(name, dev, mem) {
binary=0;
}
void ReductionLayer::mem_delta(){
if(this->delta == nullptr) {
// Reserve parent's delta
parent[0]->mem_delta();
RD->ID = parent[0]->delta;
delta = Tensor::zeros(RD->O->shape, RD->O->device);
RD->D = delta;
if(this->verbosity_level >= 2) {
std::cout << "Booked delta for: " + this->name << std::endl;
}
}
}
void ReductionLayer::addchild(Layer *l) {
child.push_back(l);
lout++;
}
void ReductionLayer::addparent(Layer *l) {
parent.push_back(l);
lin++;
}
string ReductionLayer::plot(int c) {
string s;
if (c) s = name + " [label=" + "\"" + name + "\",style=filled,fontsize=12,fillcolor=bisque4,shape=box]";
else s = name + " [label=" + "\"" + name + "\",style=filled,fontsize=12,fillcolor=White,shape=box]";
return s;
}
| 22.816667 | 108 | 0.623083 | ilveroluca |
c85d86987fb543faa3254b804a2e7fd72d09acd4 | 1,927 | cpp | C++ | src/lsm6_imu.cpp | agv-polsl/minimu | 2ec1abeb5fad2f0ba20e435879576bb7d71267af | [
"MIT"
] | null | null | null | src/lsm6_imu.cpp | agv-polsl/minimu | 2ec1abeb5fad2f0ba20e435879576bb7d71267af | [
"MIT"
] | 15 | 2020-04-19T12:46:38.000Z | 2020-09-08T12:00:06.000Z | src/lsm6_imu.cpp | agv-polsl/minimu | 2ec1abeb5fad2f0ba20e435879576bb7d71267af | [
"MIT"
] | 1 | 2020-09-08T14:20:35.000Z | 2020-09-08T14:20:35.000Z | #include "minimu/lsm6_imu.h"
namespace minimu {
Lsm6_imu::Lsm6_imu(const uint8_t adapter_nr, const sa0_state device_mode)
: Minimu_i2c_device<lsm6_regs_addr, lsm6_id>{adapter_nr, device_mode} {
default_setup();
}
point3d Lsm6_imu::read_3d_burst(lsm6_regs_addr start_addr, double scale) {
constexpr size_t num_of_bytes_in_3d_point = 6;
auto bytes_block = read_bytes_block(start_addr, num_of_bytes_in_3d_point);
return {scale * merge_bytes(bytes_block[1], bytes_block[0]),
scale * merge_bytes(bytes_block[3], bytes_block[2]),
scale * merge_bytes(bytes_block[5], bytes_block[4])};
}
static double mg_to_mps2(double acc_in_mg) {
constexpr double earth_g = 9.80665;
return acc_in_mg * earth_g / 1000.0;
}
static double mdps_to_dps(double gyro_in_mdps) { return gyro_in_mdps / 1000.0; }
point3d Lsm6_imu::read_gyro() {
auto gyror = read_3d_burst(lsm6_regs_addr::outx_l_g, gyro_scale);
return {mdps_to_dps(gyror.x), mdps_to_dps(gyror.y), mdps_to_dps(gyror.z)};
}
point3d Lsm6_imu::read_acc() {
auto accr = read_3d_burst(lsm6_regs_addr::outx_l_xl, acc_scale);
return {mg_to_mps2(accr.x), mg_to_mps2(accr.y), mg_to_mps2(accr.z)};
}
void Lsm6_imu::default_setup() {
set_acc_rate_and_scale();
set_gyro_rate_and_scale();
set_auto_increment();
}
void Lsm6_imu::set_acc_rate_and_scale() {
const std::byte set_default_rate{0b10000000};
const double default_scale = 0.061;
write(lsm6_regs_addr::ctrl1_xl, set_default_rate);
acc_scale = default_scale;
}
void Lsm6_imu::set_gyro_rate_and_scale() {
const std::byte set_default_rate{0b10000000};
const double default_scale = 8.75;
write(lsm6_regs_addr::ctrl2_g, set_default_rate);
gyro_scale = default_scale;
}
void Lsm6_imu::set_auto_increment() {
const std::byte set_auto_inc{0b00000100};
write(lsm6_regs_addr::ctrl3_c, set_auto_inc);
}
} // namespace minimu
| 30.109375 | 80 | 0.736378 | agv-polsl |
c85e5173312b5f3477fd296fdc15bd5e90fa9f88 | 3,109 | cpp | C++ | core/src/bind/hotkey/clipboard.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 731 | 2020-05-07T06:22:59.000Z | 2022-03-31T16:36:03.000Z | core/src/bind/hotkey/clipboard.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 67 | 2020-07-20T19:46:42.000Z | 2022-03-31T15:34:47.000Z | core/src/bind/hotkey/clipboard.cpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 15 | 2021-01-29T04:49:11.000Z | 2022-03-04T22:16:31.000Z | #include "bind/hotkey/clipboard.hpp"
#include <windows.h>
#include "key/char_logger.hpp"
#include "mode.hpp"
#include "key/ntype_logger.hpp"
#include "util/def.hpp"
#include "bind/emu/edi_change_mode.hpp"
#include "bind/mode/change_mode.hpp"
#include "io/keybrd.hpp"
#include "io/mouse.hpp"
#include "key/key_absorber.hpp"
#if defined(DEBUG)
#include <iostream>
#endif
namespace vind
{
//HotkeyCopy
HotkeyCopy::HotkeyCopy()
: BindedFuncCreator("hotkey_copy")
{}
void HotkeyCopy::sprocess() {
mouse::release(KEYCODE_MOUSE_LEFT) ;
//there are cases in which not editable.
//thus, not use Message Copy
keybrd::pushup(KEYCODE_LCTRL, KEYCODE_C) ;
}
void HotkeyCopy::sprocess(NTypeLogger& parent_lgr) {
if(!parent_lgr.is_long_pressing()) {
sprocess() ;
}
}
void HotkeyCopy::sprocess(const CharLogger& UNUSED(parent_lgr)) {
sprocess() ;
}
//HotkeyPaste
HotkeyPaste::HotkeyPaste()
: BindedFuncCreator("hotkey_paste")
{}
void HotkeyPaste::sprocess() {
mouse::release(KEYCODE_MOUSE_LEFT) ;
//not selecting at paste.
keybrd::pushup(KEYCODE_LCTRL, KEYCODE_V) ;
}
void HotkeyPaste::sprocess(NTypeLogger& parent_lgr) {
if(!parent_lgr.is_long_pressing()) {
sprocess() ;
}
}
void HotkeyPaste::sprocess(const CharLogger& UNUSED(parent_lgr)) {
sprocess() ;
}
//HotkeyCut
HotkeyCut::HotkeyCut()
: BindedFuncCreator("hotkey_cut")
{}
void HotkeyCut::sprocess() {
mouse::release(KEYCODE_MOUSE_LEFT) ;
keybrd::pushup(KEYCODE_LCTRL, KEYCODE_X) ;
}
void HotkeyCut::sprocess(NTypeLogger& parent_lgr) {
if(!parent_lgr.is_long_pressing()) {
sprocess() ;
}
}
void HotkeyCut::sprocess(const CharLogger& UNUSED(parent_lgr)) {
sprocess() ;
}
//HotkeyDelete
HotkeyDelete::HotkeyDelete()
: BindedFuncCreator("hotkey_delete")
{}
void HotkeyDelete::sprocess() {
mouse::release(KEYCODE_MOUSE_LEFT) ;
//selecting->cut
//unselecting->delete
keybrd::pushup(KEYCODE_LCTRL, KEYCODE_C) ;
keybrd::pushup(KEYCODE_DELETE) ;
}
void HotkeyDelete::sprocess(NTypeLogger& parent_lgr) {
if(!parent_lgr.is_long_pressing()) {
sprocess() ;
}
}
void HotkeyDelete::sprocess(const CharLogger& UNUSED(parent_lgr)) {
sprocess() ;
}
//HotkeyBackspace
HotkeyBackspace::HotkeyBackspace()
: BindedFuncCreator("hotkey_backspace")
{}
void HotkeyBackspace::sprocess() {
mouse::release(KEYCODE_MOUSE_LEFT) ;
//selecting->cut
//unselecting->delete
keybrd::pushup(KEYCODE_LCTRL, KEYCODE_C) ;
keybrd::pushup(KEYCODE_BKSPACE) ;
}
void HotkeyBackspace::sprocess(NTypeLogger& parent_lgr) {
if(!parent_lgr.is_long_pressing()) {
sprocess() ;
}
}
void HotkeyBackspace::sprocess(const CharLogger& UNUSED(parent_lgr)) {
sprocess() ;
}
}
| 24.674603 | 74 | 0.62496 | pit-ray |
c8603f1d5f07e9c96c16fe832d53d2c466648886 | 8,257 | cpp | C++ | src/FullSystem/Residuals.cpp | danielecolautti/DSO-Server | 34968398f9834c9177ca373d9a3b3d2e13c2ee86 | [
"Apache-2.0"
] | null | null | null | src/FullSystem/Residuals.cpp | danielecolautti/DSO-Server | 34968398f9834c9177ca373d9a3b3d2e13c2ee86 | [
"Apache-2.0"
] | null | null | null | src/FullSystem/Residuals.cpp | danielecolautti/DSO-Server | 34968398f9834c9177ca373d9a3b3d2e13c2ee86 | [
"Apache-2.0"
] | null | null | null | /**
* This file is part of DSO.
*
* Copyright 2016 Technical University of Munich and Intel.
* Developed by Jakob Engel <engelj at in dot tum dot de>,
* for more information see <http://vision.in.tum.de/dso>.
* If you use this code, please cite the respective publications as
* listed on the above website.
*
* DSO 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 3 of the License, or
* (at your option) any later version.
*
* DSO 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 DSO. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* KFBuffer.cpp
*
* Created on: Jan 7, 2014
* Author: engelj
*/
#include "FullSystem/FullSystem.h"
#include "stdio.h"
#include "util/globalFuncs.h"
#include <Eigen/LU>
#include <algorithm>
#include "IOWrapper/ImageDisplay.h"
#include "util/globalCalib.h"
#include <Eigen/SVD>
#include <Eigen/Eigenvalues>
#include "FullSystem/ResidualProjections.h"
#include "OptimizationBackend/EnergyFunctional.h"
#include "OptimizationBackend/EnergyFunctionalStructs.h"
#include "FullSystem/HessianBlocks.h"
namespace dso
{
int PointFrameResidual::instanceCounter = 0;
long runningResID=0;
PointFrameResidual::PointFrameResidual(){assert(false); instanceCounter++;}
PointFrameResidual::~PointFrameResidual(){assert(efResidual==0); instanceCounter--; delete J;}
PointFrameResidual::PointFrameResidual(PointHessian* point_, FrameHessian* host_, FrameHessian* target_) :
point(point_),
host(host_),
target(target_)
{
efResidual=0;
instanceCounter++;
resetOOB();
J = new RawResidualJacobian();
assert(((long)J)%16==0);
isNew=true;
}
double PointFrameResidual::linearize(CalibHessian* HCalib)
{
state_NewEnergyWithOutlier=-1;
if(state_state == ResState::OOB)
{ state_NewState = ResState::OOB; return state_energy; }
FrameFramePrecalc* precalc = &(host->targetPrecalc[target->idx]);
float energyLeft=0;
const Eigen::Vector3f* dIl = target->dI;
//const float* const Il = target->I;
const Mat33f &PRE_KRKiTll = precalc->PRE_KRKiTll;
const Vec3f &PRE_KtTll = precalc->PRE_KtTll;
const Mat33f &PRE_RTll_0 = precalc->PRE_RTll_0;
const Vec3f &PRE_tTll_0 = precalc->PRE_tTll_0;
const float * const color = point->color;
const float * const weights = point->weights;
Vec2f affLL = precalc->PRE_aff_mode;
float b0 = precalc->PRE_b0_mode;
Vec6f d_xi_x, d_xi_y;
Vec4f d_C_x, d_C_y;
float d_d_x, d_d_y;
{
float drescale, u, v, new_idepth;
float Ku, Kv;
Vec3f KliP;
if(!projectPoint(point->u, point->v, point->idepth_zero_scaled, 0, 0,HCalib,
PRE_RTll_0,PRE_tTll_0, drescale, u, v, Ku, Kv, KliP, new_idepth))
{ state_NewState = ResState::OOB; return state_energy; }
centerProjectedTo = Vec3f(Ku, Kv, new_idepth);
// diff d_idepth
d_d_x = drescale * (PRE_tTll_0[0]-PRE_tTll_0[2]*u)*SCALE_IDEPTH*HCalib->fxl();
d_d_y = drescale * (PRE_tTll_0[1]-PRE_tTll_0[2]*v)*SCALE_IDEPTH*HCalib->fyl();
// diff calib
d_C_x[2] = drescale*(PRE_RTll_0(2,0)*u-PRE_RTll_0(0,0));
d_C_x[3] = HCalib->fxl() * drescale*(PRE_RTll_0(2,1)*u-PRE_RTll_0(0,1)) * HCalib->fyli();
d_C_x[0] = KliP[0]*d_C_x[2];
d_C_x[1] = KliP[1]*d_C_x[3];
d_C_y[2] = HCalib->fyl() * drescale*(PRE_RTll_0(2,0)*v-PRE_RTll_0(1,0)) * HCalib->fxli();
d_C_y[3] = drescale*(PRE_RTll_0(2,1)*v-PRE_RTll_0(1,1));
d_C_y[0] = KliP[0]*d_C_y[2];
d_C_y[1] = KliP[1]*d_C_y[3];
d_C_x[0] = (d_C_x[0]+u)*SCALE_F;
d_C_x[1] *= SCALE_F;
d_C_x[2] = (d_C_x[2]+1)*SCALE_C;
d_C_x[3] *= SCALE_C;
d_C_y[0] *= SCALE_F;
d_C_y[1] = (d_C_y[1]+v)*SCALE_F;
d_C_y[2] *= SCALE_C;
d_C_y[3] = (d_C_y[3]+1)*SCALE_C;
d_xi_x[0] = new_idepth*HCalib->fxl();
d_xi_x[1] = 0;
d_xi_x[2] = -new_idepth*u*HCalib->fxl();
d_xi_x[3] = -u*v*HCalib->fxl();
d_xi_x[4] = (1+u*u)*HCalib->fxl();
d_xi_x[5] = -v*HCalib->fxl();
d_xi_y[0] = 0;
d_xi_y[1] = new_idepth*HCalib->fyl();
d_xi_y[2] = -new_idepth*v*HCalib->fyl();
d_xi_y[3] = -(1+v*v)*HCalib->fyl();
d_xi_y[4] = u*v*HCalib->fyl();
d_xi_y[5] = u*HCalib->fyl();
}
{
J->Jpdxi[0] = d_xi_x;
J->Jpdxi[1] = d_xi_y;
J->Jpdc[0] = d_C_x;
J->Jpdc[1] = d_C_y;
J->Jpdd[0] = d_d_x;
J->Jpdd[1] = d_d_y;
}
float JIdxJIdx_00=0, JIdxJIdx_11=0, JIdxJIdx_10=0;
float JabJIdx_00=0, JabJIdx_01=0, JabJIdx_10=0, JabJIdx_11=0;
float JabJab_00=0, JabJab_01=0, JabJab_11=0;
float wJI2_sum = 0;
for(int idx=0;idx<patternNum;idx++)
{
float Ku, Kv;
if(!projectPoint(point->u+patternP[idx][0], point->v+patternP[idx][1], point->idepth_scaled, PRE_KRKiTll, PRE_KtTll, Ku, Kv))
{ state_NewState = ResState::OOB; return state_energy; }
projectedTo[idx][0] = Ku;
projectedTo[idx][1] = Kv;
Vec3f hitColor = (getInterpolatedElement33(dIl, Ku, Kv, wG[0]));
float residual = hitColor[0] - (float)(affLL[0] * color[idx] + affLL[1]);
float drdA = (color[idx]-b0);
if(!std::isfinite((float)hitColor[0]))
{ state_NewState = ResState::OOB; return state_energy; }
float w = sqrtf(setting_outlierTHSumComponent / (setting_outlierTHSumComponent + hitColor.tail<2>().squaredNorm()));
w = 0.5f*(w + weights[idx]);
float hw = fabsf(residual) < setting_huberTH ? 1 : setting_huberTH / fabsf(residual);
energyLeft += w*w*hw *residual*residual*(2-hw);
{
if(hw < 1) hw = sqrtf(hw);
hw = hw*w;
hitColor[1]*=hw;
hitColor[2]*=hw;
J->resF[idx] = residual*hw;
J->JIdx[0][idx] = hitColor[1];
J->JIdx[1][idx] = hitColor[2];
J->JabF[0][idx] = drdA*hw;
J->JabF[1][idx] = hw;
JIdxJIdx_00+=hitColor[1]*hitColor[1];
JIdxJIdx_11+=hitColor[2]*hitColor[2];
JIdxJIdx_10+=hitColor[1]*hitColor[2];
JabJIdx_00+= drdA*hw * hitColor[1];
JabJIdx_01+= drdA*hw * hitColor[2];
JabJIdx_10+= hw * hitColor[1];
JabJIdx_11+= hw * hitColor[2];
JabJab_00+= drdA*drdA*hw*hw;
JabJab_01+= drdA*hw*hw;
JabJab_11+= hw*hw;
wJI2_sum += hw*hw*(hitColor[1]*hitColor[1]+hitColor[2]*hitColor[2]);
if(setting_affineOptModeA < 0) J->JabF[0][idx]=0;
if(setting_affineOptModeB < 0) J->JabF[1][idx]=0;
}
}
J->JIdx2(0,0) = JIdxJIdx_00;
J->JIdx2(0,1) = JIdxJIdx_10;
J->JIdx2(1,0) = JIdxJIdx_10;
J->JIdx2(1,1) = JIdxJIdx_11;
J->JabJIdx(0,0) = JabJIdx_00;
J->JabJIdx(0,1) = JabJIdx_01;
J->JabJIdx(1,0) = JabJIdx_10;
J->JabJIdx(1,1) = JabJIdx_11;
J->Jab2(0,0) = JabJab_00;
J->Jab2(0,1) = JabJab_01;
J->Jab2(1,0) = JabJab_01;
J->Jab2(1,1) = JabJab_11;
state_NewEnergyWithOutlier = energyLeft;
if(energyLeft > std::max<float>(host->frameEnergyTH, target->frameEnergyTH) || wJI2_sum < 2)
{
energyLeft = std::max<float>(host->frameEnergyTH, target->frameEnergyTH);
state_NewState = ResState::OUTLIER;
}
else
{
state_NewState = ResState::IN;
}
state_NewEnergy = energyLeft;
return energyLeft;
}
void PointFrameResidual::debugPlot()
{
if(state_state==ResState::OOB) return;
Vec3b cT = Vec3b(0,0,0);
if(freeDebugParam5==0)
{
float rT = 20*sqrt(state_energy/9);
if(rT<0) rT=0; if(rT>255)rT=255;
cT = Vec3b(0,255-rT,rT);
}
else
{
if(state_state == ResState::IN) cT = Vec3b(255,0,0);
else if(state_state == ResState::OOB) cT = Vec3b(255,255,0);
else if(state_state == ResState::OUTLIER) cT = Vec3b(0,0,255);
else cT = Vec3b(255,255,255);
}
for(int i=0;i<patternNum;i++)
{
if((projectedTo[i][0] > 2 && projectedTo[i][1] > 2 && projectedTo[i][0] < wG[0]-3 && projectedTo[i][1] < hG[0]-3 ))
target->debugImage->setPixel1((float)projectedTo[i][0], (float)projectedTo[i][1],cT);
}
}
void PointFrameResidual::applyRes(bool copyJacobians)
{
if(copyJacobians)
{
if(state_state == ResState::OOB)
{
assert(!efResidual->isActiveAndIsGoodNEW);
return; // can never go back from OOB
}
if(state_NewState == ResState::IN)// && )
{
efResidual->isActiveAndIsGoodNEW=true;
efResidual->takeDataF();
}
else
{
efResidual->isActiveAndIsGoodNEW=false;
}
}
setState(state_NewState);
state_energy = state_NewEnergy;
}
}
| 25.021212 | 127 | 0.672884 | danielecolautti |
c86579f5f0c690af1eb201a088dea19a608e2f03 | 13,511 | cpp | C++ | openEAR-0.1.0/src/semaineEmmaSender.cpp | trimlab/Voice-Emotion-Detection | c7272dd2f70e2d4b8eee304e68578494d7ef624c | [
"MIT"
] | null | null | null | openEAR-0.1.0/src/semaineEmmaSender.cpp | trimlab/Voice-Emotion-Detection | c7272dd2f70e2d4b8eee304e68578494d7ef624c | [
"MIT"
] | null | null | null | openEAR-0.1.0/src/semaineEmmaSender.cpp | trimlab/Voice-Emotion-Detection | c7272dd2f70e2d4b8eee304e68578494d7ef624c | [
"MIT"
] | null | null | null | /*F******************************************************************************
*
* openSMILE - open Speech and Music Interpretation by Large-space Extraction
* the open-source Munich Audio Feature Extraction Toolkit
* Copyright (C) 2008-2009 Florian Eyben, Martin Woellmer, Bjoern Schuller
*
*
* Institute for Human-Machine Communication
* Technische Universitaet Muenchen (TUM)
* D-80333 Munich, Germany
*
*
* If you use openSMILE or any code from openSMILE in your research work,
* you are kindly asked to acknowledge the use of openSMILE in your publications.
* See the file CITING.txt for details.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
******************************************************************************E*/
/* openSMILE component:
the SEMAINE Emma message sender for openSMILE
*/
#include <semaineEmmaSender.hpp>
//#include <math.h>
#define MODULE "cSemaineEmmaSender"
#ifdef HAVE_SEMAINEAPI
SMILECOMPONENT_STATICS(cSemaineEmmaSender)
SMILECOMPONENT_REGCOMP(cSemaineEmmaSender)
{
SMILECOMPONENT_REGCOMP_INIT
scname = COMPONENT_NAME_CSEMAINEEMMASENDER;
sdescription = COMPONENT_DESCRIPTION_CSEMAINEEMMASENDER;
// configure your component's configType:
SMILECOMPONENT_CREATE_CONFIGTYPE
//ct->setField("reader", "dataMemory interface configuration (i.e. what slot to read from)", sconfman->getTypeObj("cDataReader"), NO_ARRAY, DONT_FREE);
ct->setField("dummy","nothing",0);
SMILECOMPONENT_IFNOTREGAGAIN( {} )
SMILECOMPONENT_MAKEINFO(cSemaineEmmaSender);
}
SMILECOMPONENT_CREATE(cSemaineEmmaSender)
//-----
cSemaineEmmaSender::cSemaineEmmaSender(const char *_name) :
cSmileComponent(_name)
{
// initialisation code...
}
/*
void cSemaineEmmaSender::mySetEnvironment()
{
}
int cSemaineEmmaSender::myConfigureInstance()
{
return 1;
}
int cSemaineEmmaSender::myFinaliseInstance()
{
return 1;
}
*/
// get smileTime from _msg, convert to semaine time by getting current time from smile and semaine and observing the difference
long long cSemaineEmmaSender::smileTimeToSemaineTime( double smileTime )
{
smileTime *= 1000.0;
if (meta != NULL) {
long long smit = (long long)round(getSmileTime()*1000.0);
return (long long)round(smileTime) + (meta->getTime() - smit);
} else {
SMILE_IWRN(3,"warning, no meta component found, times sent are SMILE times and NOT semaine times!");
return (long long)round(smileTime);
}
return 0;
}
// send an XML document and delete it afterwards
void cSemaineEmmaSender::sendDocument( DOMDocument * document )
{
// Now send it
if ((meta != NULL)&&(meta->isSystemReady())) {
emmaSender->sendXML(document, meta->getTime());
}
delete document;
/*
else {
emmaSender->sendXML(document, 0.0);
}*/
}
void cSemaineEmmaSender::sendArousalC( cComponentMessage *_msg )
{
char strtmp[50];
sprintf(strtmp,"%.2f",_msg->floatData[0]);
std::string aroStr(strtmp);
sprintf(strtmp,"%ld",smileTimeToSemaineTime(_msg->userTime1));
std::string startTm(strtmp);
sprintf(strtmp,"%ld",(long long)round((_msg->userTime2 - _msg->userTime1)*1000.0));
std::string duration(strtmp);
// Create and fill a simple EMMA EmotionML document
DOMDocument * document = XMLTool::newDocument(EMMA::E_EMMA, EMMA::namespaceURI, EMMA::version);
DOMElement * interpretation = XMLTool::appendChildElement(document->getDocumentElement(), EMMA::E_INTERPRETATION);
XMLTool::setAttribute(interpretation, EMMA::A_OFFSET_TO_START, startTm);
XMLTool::setAttribute(interpretation, EMMA::A_DURATION, duration);
XMLTool::setPrefix(interpretation, "emma");
DOMElement * emotion = XMLTool::appendChildElement(interpretation, EmotionML::E_EMOTION, EmotionML::namespaceURI);
XMLTool::setPrefix(emotion, "emotion");
DOMElement * dimensions = XMLTool::appendChildElement(emotion, EmotionML::E_DIMENSIONS, EmotionML::namespaceURI);
XMLTool::setAttribute(dimensions, EmotionML::A_SET, "valenceArousalPotency");
XMLTool::setPrefix(dimensions, "emotion");
DOMElement * arousal = XMLTool::appendChildElement(dimensions, EmotionML::E_AROUSAL, EmotionML::namespaceURI);
XMLTool::setAttribute(arousal, EmotionML::A_VALUE, aroStr);
XMLTool::setPrefix(arousal, "emotion");
sendDocument(document);
}
void cSemaineEmmaSender::sendValenceC( cComponentMessage *_msg )
{
char strtmp[50];
sprintf(strtmp,"%.2f",_msg->floatData[0]);
std::string valStr(strtmp);
sprintf(strtmp,"%ld",smileTimeToSemaineTime(_msg->userTime1));
std::string startTm(strtmp);
sprintf(strtmp,"%ld",(long long)round((_msg->userTime2 - _msg->userTime1)*1000.0));
std::string duration(strtmp);
// Create and fill a simple EMMA EmotionML document
DOMDocument * document = XMLTool::newDocument(EMMA::E_EMMA, EMMA::namespaceURI, EMMA::version);
DOMElement * interpretation = XMLTool::appendChildElement(document->getDocumentElement(), EMMA::E_INTERPRETATION);
XMLTool::setAttribute(interpretation, EMMA::A_OFFSET_TO_START, startTm);
XMLTool::setAttribute(interpretation, EMMA::A_DURATION, duration);
XMLTool::setPrefix(interpretation, "emma");
DOMElement * emotion = XMLTool::appendChildElement(interpretation, EmotionML::E_EMOTION, EmotionML::namespaceURI);
XMLTool::setPrefix(emotion, "emotion");
DOMElement * dimensions = XMLTool::appendChildElement(emotion, EmotionML::E_DIMENSIONS, EmotionML::namespaceURI);
XMLTool::setAttribute(dimensions, EmotionML::A_SET, "valenceArousalPotency");
XMLTool::setPrefix(dimensions, "emotion");
DOMElement * valence = XMLTool::appendChildElement(dimensions, EmotionML::E_VALENCE, EmotionML::namespaceURI);
XMLTool::setAttribute(valence, EmotionML::A_VALUE, valStr);
XMLTool::setPrefix(valence, "emotion");
// Now send it
sendDocument(document);
}
void cSemaineEmmaSender::sendInterestC( cComponentMessage *_msg )
{
char strtmp[50];
sprintf(strtmp,"%.2f",_msg->floatData[0]);
std::string interestStr(strtmp);
// Create and fill a simple EMMA EmotionML document
DOMDocument * document = XMLTool::newDocument(EMMA::E_EMMA, EMMA::namespaceURI, EMMA::version);
sprintf(strtmp,"%ld",smileTimeToSemaineTime(_msg->userTime1));
std::string startTm(strtmp);
sprintf(strtmp,"%ld",(long long)round((_msg->userTime2 - _msg->userTime1)*1000.0));
std::string duration(strtmp);
DOMElement * oneof = XMLTool::appendChildElement(document->getDocumentElement(), EMMA::E_ONEOF);
XMLTool::setAttribute(oneof, EMMA::A_OFFSET_TO_START, startTm);
XMLTool::setAttribute(oneof, EMMA::A_DURATION, duration);
XMLTool::setPrefix(oneof, "emma");
DOMElement * interpretation0 = XMLTool::appendChildElement(oneof, EMMA::E_INTERPRETATION);
sprintf(strtmp,"%.3f",((double*)(_msg->custData))[0]);
std::string conf0(strtmp);
XMLTool::setAttribute(interpretation0, EMMA::A_CONFIDENCE, conf0);
XMLTool::setPrefix(interpretation0, "emma");
DOMElement * emotion0 = XMLTool::appendChildElement(interpretation0, EmotionML::E_EMOTION, EmotionML::namespaceURI);
XMLTool::setPrefix(emotion0, "emotion");
DOMElement * category0 = XMLTool::appendChildElement(emotion0, EmotionML::E_CATEGORY, EmotionML::namespaceURI);
XMLTool::setAttribute(category0, EmotionML::A_SET, "interestLevels");
XMLTool::setAttribute(category0, EmotionML::A_NAME, "bored");
XMLTool::setPrefix(category0, "emotion");
DOMElement * interpretation1 = XMLTool::appendChildElement(oneof, EMMA::E_INTERPRETATION);
sprintf(strtmp,"%.3f",((double*)(_msg->custData))[1]);
std::string conf1(strtmp);
XMLTool::setAttribute(interpretation1, EMMA::A_CONFIDENCE, conf1);
XMLTool::setPrefix(interpretation1, "emma");
DOMElement * emotion1 = XMLTool::appendChildElement(interpretation1, EmotionML::E_EMOTION, EmotionML::namespaceURI);
XMLTool::setPrefix(emotion1, "emotion");
DOMElement * category1 = XMLTool::appendChildElement(emotion1, EmotionML::E_CATEGORY, EmotionML::namespaceURI);
XMLTool::setAttribute(category1, EmotionML::A_SET, "interestLevels");
XMLTool::setAttribute(category1, EmotionML::A_NAME, "neutral");
XMLTool::setPrefix(category1, "emotion");
DOMElement * interpretation2 = XMLTool::appendChildElement(oneof, EMMA::E_INTERPRETATION);
sprintf(strtmp,"%.3f",((double*)(_msg->custData))[2]);
std::string conf2(strtmp);
XMLTool::setAttribute(interpretation2, EMMA::A_CONFIDENCE, conf2);
XMLTool::setPrefix(interpretation2, "emma");
DOMElement * emotion2 = XMLTool::appendChildElement(interpretation2, EmotionML::E_EMOTION, EmotionML::namespaceURI);
XMLTool::setPrefix(emotion2, "emotion");
DOMElement * category2 = XMLTool::appendChildElement(emotion2, EmotionML::E_CATEGORY, EmotionML::namespaceURI);
XMLTool::setAttribute(category2, EmotionML::A_SET, "interestLevels");
XMLTool::setAttribute(category2, EmotionML::A_NAME, "interested");
XMLTool::setPrefix(category2, "emotion");
// Now send it
sendDocument(document);
}
// start = 1: speaking status changed to start, start = 0: status changed to stop
void cSemaineEmmaSender::sendSpeakingStatus( cComponentMessage *_msg, int start )
{
const char *strtmp = "stop";
if (start) strtmp = "start";
std::string statusStr(strtmp);
char strtmp2[50];
sprintf(strtmp2,"%ld",smileTimeToSemaineTime(_msg->userTime1));
std::string startTm(strtmp2);
// Create and fill a simple EMMA EmotionML document
DOMDocument * document = XMLTool::newDocument(EMMA::E_EMMA, EMMA::namespaceURI, EMMA::version);
DOMElement * interpretation = XMLTool::appendChildElement(document->getDocumentElement(), EMMA::E_INTERPRETATION);
XMLTool::setAttribute(interpretation, EMMA::A_OFFSET_TO_START, startTm);
XMLTool::setAttribute(interpretation, EMMA::A_DURATION, "0");
XMLTool::setPrefix(interpretation, "emma");
DOMElement * speaking = XMLTool::appendChildElement(interpretation, SemaineML::E_SPEAKING, SemaineML::namespaceURI);
XMLTool::setAttribute(speaking, SemaineML::A_STATUS_CHANGE, strtmp);
XMLTool::setPrefix(speaking, "semaine");
// Now send it
sendDocument(document);
}
#include <kwsjKresult.h>
void cSemaineEmmaSender::sendKeywords( cComponentMessage *_msg )
{
char strtmp[50];
sprintf(strtmp,"%.2f",_msg->floatData[0]);
std::string valStr(strtmp);
long long startTime = smileTimeToSemaineTime(_msg->userTime1);
sprintf(strtmp,"%ld",startTime);
std::string startTm(strtmp);
sprintf(strtmp,"%ld",(long long)round((_msg->userTime2 - _msg->userTime1)*1000.0));
std::string duration(strtmp);
// Create and fill a simple EMMA EmotionML document
DOMDocument * document = XMLTool::newDocument(EMMA::E_EMMA, EMMA::namespaceURI, EMMA::version);
DOMElement * sequence = XMLTool::appendChildElement(document->getDocumentElement(), EMMA::E_SEQUENCE);
XMLTool::setAttribute(sequence, EMMA::A_OFFSET_TO_START, startTm);
XMLTool::setAttribute(sequence, EMMA::A_DURATION, duration);
XMLTool::setPrefix(sequence, "emma");
int i;
Kresult *k = (Kresult *)(_msg->custData);
for (i=0; i<k->numOfKw; i++) {
DOMElement * interpretation = XMLTool::appendChildElement(sequence, EMMA::E_INTERPRETATION);
sprintf(strtmp,"%ld",startTime + (long long)round((k->kwStartTime[i])*1000.0));
std::string offs(strtmp);
sprintf(strtmp,"%s",k->keyword[i]);
std::string keyword(strtmp);
sprintf(strtmp,"%.3f",k->kwConf[i]);
std::string confidence(strtmp);
XMLTool::setAttribute(interpretation, EMMA::A_OFFSET_TO_START, offs);
XMLTool::setAttribute(interpretation, EMMA::A_TOKENS, keyword);
XMLTool::setAttribute(interpretation, EMMA::A_CONFIDENCE, confidence);
XMLTool::setPrefix(interpretation, "emma");
}
// Now send it
sendDocument(document);
}
int cSemaineEmmaSender::processComponentMessage( cComponentMessage *_msg )
{
if (isMessageType(_msg,"classificationResult")) {
// determine origin by message's user-defined name, which can be set in the config file
SMILE_IDBG(3,"received 'classificationResult' message");
if (!strcmp(_msg->msgname,"arousal")) sendArousalC(_msg);
if (!strcmp(_msg->msgname,"valence")) sendValenceC(_msg);
if (!strcmp(_msg->msgname,"interest")) sendInterestC(_msg);
return 1; // message was processed
}
else if (isMessageType(_msg,"asrKeywordOutput")) {
SMILE_IDBG(3,"received 'asrKeywordOutput' message");
sendKeywords(_msg);
return 1; // message was processed
}
else if (isMessageType(_msg,"turnSpeakingStatus")) {
SMILE_IDBG(3,"received 'turnSpeakingStatus' message");
sendSpeakingStatus(_msg, _msg->intData[0]);
return 1; // message was processed
}
return 0; // if message was not processed
}
int cSemaineEmmaSender::myTick(long long t)
{
// return 1; // tick did succeed!
return 0; // tick did not succeed, i.e. nothing was processed or there was nothing to process
}
cSemaineEmmaSender::~cSemaineEmmaSender()
{
// cleanup code...
}
#endif //HAVE_SEMAINEAPI
| 36.814714 | 153 | 0.735253 | trimlab |
c8695aa9b61aed42bfba5bfff680886bd68e6231 | 2,411 | cpp | C++ | Abacus.cpp | south37/topcoder | 9edee3f723189ccdbecb1cbc5c186a99f392e6dd | [
"MIT"
] | null | null | null | Abacus.cpp | south37/topcoder | 9edee3f723189ccdbecb1cbc5c186a99f392e6dd | [
"MIT"
] | null | null | null | Abacus.cpp | south37/topcoder | 9edee3f723189ccdbecb1cbc5c186a99f392e6dd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#define N 6
#define M 12
class Abacus {
public:
std::vector <std::string> add(std::vector <std::string> original, int val) {
int c = changeToLong(original) + val;
std::vector <std::string> result(6, "oooooooooooo");
changeToVector(result, c);
return result;
}
int changeToLong(std::vector <std::string>& original) {
int result = 0;
for(int i = 0; i < N; ++i) {
result *= 10;
int pos = position(original[i]);
result += pos;
}
return result;
}
void changeToVector(std::vector<std::string>& result, int input) {
for(int i = 0; i < N; ++i) {
int n = (input % 10);
changeFromPosition(result[N-1-i], n);
input /= 10;
}
}
int position(const std::string& s) {
for(int i = 0; i < M; ++i) {
if (s[i] == '-') {
return 9 - i;
}
}
return 0;
}
void changeFromPosition(std::string& result, int pos) {
// 0 -> 9
// 9 -> 0
// So, 9 - pos;
int start = 9 - pos;
int end = start + 3;
for (int i = start; i < end; ++i) {
result[i] = '-';
}
}
};
int main(int argc, char** argv) {
Abacus a0;
std::vector<std::string> input0 = {"ooo---oooooo", "---ooooooooo", "---ooooooooo", "---ooooooooo", "oo---ooooooo", "---ooooooooo"};
// std::cout << a0.position("ooo---oooooo") << std::endl;
// std::cout << a0.position("o---oooooooo") << std::endl;
// std::cout << a0.position("---ooooooooo") << std::endl;
// std::cout << a0.position("oooooooo---o") << std::endl;
// std::cout << a0.position("ooooooooo---") << std::endl;
// std::cout << a0.changeToLong(input0) << std::endl;
// std::cout << a0.changeFromPosition(0) << std::endl;
// std::cout << a0.changeFromPosition(3) << std::endl;
// std::string i = "oooooooooooo";
// a0.changeFromPosition(i, 9);
// std::cout << i << std::endl;
// std::vector <std::string> result(6, "oooooooooooo");
// for(auto s : result) {
// std::cout << s << std::endl;
// }
// a0.changeToVector(result, 699984);
// for(auto s : result) {
// std::cout << s << std::endl;
// }
for(auto s : a0.add(input0, 5)) {
std::cout << s << std::endl;
}
}
| 30.518987 | 135 | 0.491083 | south37 |
c86aa93d2153b2b8dccc9022319c3a2dc8900ade | 962 | cpp | C++ | src/vcpkg/buildenvironment.cpp | autoantwort/vcpkg-tool | fb3475040d256bc0d744fa72a20b0a9d103d48b3 | [
"MIT"
] | null | null | null | src/vcpkg/buildenvironment.cpp | autoantwort/vcpkg-tool | fb3475040d256bc0d744fa72a20b0a9d103d48b3 | [
"MIT"
] | null | null | null | src/vcpkg/buildenvironment.cpp | autoantwort/vcpkg-tool | fb3475040d256bc0d744fa72a20b0a9d103d48b3 | [
"MIT"
] | null | null | null | #include <vcpkg/buildenvironment.h>
#include <vcpkg/tools.h>
#include <vcpkg/triplet.h>
#include <vcpkg/vcpkgpaths.h>
namespace vcpkg
{
System::Command make_cmake_cmd(const VcpkgPaths& paths,
const fs::path& cmake_script,
std::vector<System::CMakeVariable>&& pass_variables)
{
auto local_variables = std::move(pass_variables);
local_variables.emplace_back("VCPKG_ROOT_DIR", paths.root);
local_variables.emplace_back("PACKAGES_DIR", paths.packages);
local_variables.emplace_back("BUILDTREES_DIR", paths.buildtrees);
local_variables.emplace_back("_VCPKG_INSTALLED_DIR", paths.installed);
local_variables.emplace_back("DOWNLOADS", paths.downloads);
local_variables.emplace_back("VCPKG_MANIFEST_INSTALL", "OFF");
return System::make_basic_cmake_cmd(paths.get_tool_exe(Tools::CMAKE), cmake_script, local_variables);
}
}
| 43.727273 | 109 | 0.689189 | autoantwort |
c86d975e9b89e79c786522a62419a71c386e11a4 | 3,106 | cpp | C++ | test/focus-cycle.cpp | 8l/swm | dfa4ba130ff39aa0bf96b991bca34fba086b333b | [
"BSD-2-Clause"
] | null | null | null | test/focus-cycle.cpp | 8l/swm | dfa4ba130ff39aa0bf96b991bca34fba086b333b | [
"BSD-2-Clause"
] | null | null | null | test/focus-cycle.cpp | 8l/swm | dfa4ba130ff39aa0bf96b991bca34fba086b333b | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <vector>
#include <UnitTest++.h>
#include "model/focus-cycle.h"
#include "logging/logging.h"
#include "logging/stream.h"
const int last_window = 9;
StreamLog log(std::cerr);
struct FocusCycleFixture
{
FocusCycle cycle;
std::vector<Window> windows;
FocusCycleFixture() :
cycle(&log)
{
for (int win = 0; win < last_window + 1; win++)
{
windows.push_back(win);
}
cycle.update_window_list(windows);
}
};
SUITE(FocusModelSuite)
{
/**
* Ensures that FocusCycle.get_next returns the correct value in cases when
* it doesn't wrap around.
*/
TEST_FIXTURE(FocusCycleFixture, test_gets_windows)
{
// It starts at the first window, but get_next() doesn't return it, so
// we have to start at the second window.
for (int win = 1; win < last_window + 1; win++)
{
CHECK_EQUAL(cycle.get_next(), win);
}
}
/**
* Ensures that FocusCycle.get_prev returns the correct value in cases when
* it doesn't wrap around.
*/
TEST_FIXTURE(FocusCycleFixture, test_gets_windows_reverse)
{
cycle.set_focus(last_window);
// It starts at the first window, but get_next() doesn't return it, so
// we have to start at the second window.
for (int win = last_window - 1; win >= 0; win--)
{
CHECK_EQUAL(cycle.get_prev(), win);
}
}
/**
* This ensures that the FocusCycle wraps around when it gets past the
* last window.
*/
TEST_FIXTURE(FocusCycleFixture, test_wraparound)
{
for (int win = 1; win < last_window + 1; win++)
{
cycle.get_next();
}
CHECK_EQUAL(cycle.get_next(), 0);
}
/**
* This ensures that the FocusCycle wraps around when it gets past the
* first window (cycling backwards)
*/
TEST_FIXTURE(FocusCycleFixture, test_wraparound_reverse)
{
cycle.set_focus(last_window);
for (int win = last_window - 1; win >= 0; win--)
{
cycle.get_prev();
}
CHECK_EQUAL(cycle.get_prev(), last_window);
}
/**
* This ensures that setting the focus to a valid window causes the window
* after it to be returned by get_next.
*/
TEST_FIXTURE(FocusCycleFixture, test_set_focus)
{
// As before, setting the focus means that the window *after* the current
// focus will be returned by get_next
cycle.set_focus(5);
for (int win = 6; win < last_window; win++)
{
CHECK_EQUAL(cycle.get_next(), win);
}
}
/**
* This ensures that setting the focus to an invalid window does nothing.
*/
TEST_FIXTURE(FocusCycleFixture, test_set_invalid)
{
// As before, setting the focus means that the window *after* the current
// focus will be returned by get_next
cycle.set_focus(100);
CHECK_EQUAL(cycle.get_next(), 1);
}
}
int main()
{
return UnitTest::RunAllTests();
}
| 25.669421 | 81 | 0.594656 | 8l |
c86de741c299f5cfe6e3f3665c39031dce01f69e | 37,829 | hpp | C++ | src/ocl/jit_gen9_common_conv_kernel.hpp | uyongw/mkl-dnn | 5588edb4f12b7ddd4b25ca857acde64066fbd699 | [
"Apache-2.0"
] | 1 | 2018-04-13T01:38:53.000Z | 2018-04-13T01:38:53.000Z | src/ocl/jit_gen9_common_conv_kernel.hpp | uyongw/mkl-dnn | 5588edb4f12b7ddd4b25ca857acde64066fbd699 | [
"Apache-2.0"
] | null | null | null | src/ocl/jit_gen9_common_conv_kernel.hpp | uyongw/mkl-dnn | 5588edb4f12b7ddd4b25ca857acde64066fbd699 | [
"Apache-2.0"
] | 2 | 2021-06-29T13:24:31.000Z | 2021-06-30T12:07:02.000Z | /*******************************************************************************
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef JIT_GEN9_COMMON_CONV_KERNEL_HPP
#define JIT_GEN9_COMMON_CONV_KERNEL_HPP
#include "common/c_types_map.hpp"
#include "ocl/jit_primitive_conf.hpp"
namespace mkldnn {
namespace impl {
namespace ocl {
using namespace mkldnn::impl::format_tag;
struct jit_gen9_common_conv_fwd_kernel {
jit_gen9_common_conv_fwd_kernel(jit_conv_conf_t ajcp) : jcp(ajcp){};
~jit_gen9_common_conv_fwd_kernel(){};
static status_t init_conf(jit_conv_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_t &src_md,
const memory_desc_t &weights_md, const memory_desc_t &dst_md,
const memory_desc_t &bias_md, const primitive_attr_t &attr) {
const memory_desc_wrapper src_mdw(&src_md);
const memory_desc_wrapper weights_mdw(&weights_md);
const memory_desc_wrapper dst_mdw(&dst_md);
const memory_desc_wrapper bias_mdw(&bias_md);
set_default_conf(jcp, cd, src_md, weights_md, dst_md, attr);
const bool is_dw_16g = (jcp.is_depthwise && jcp.ngroups % 16 == 0);
const bool is_1stconv = jcp.ic == 3;
const bool is_16ic = jcp.ic % 16 == 0;
const bool is_16oc = jcp.oc % 16 == 0;
const bool use_16mb_unroll = !(jcp.mb == 1 || jcp.mb % 16 != 0)
&& !is_1stconv
&& ((is_16ic && is_16oc) || is_dw_16g)
&& IMPLICATION(src_mdw.data_type() == data_type::f16,
jcp.mb % 32 == 0)
&& IMPLICATION(src_mdw.data_type() == data_type::f16
&& jcp.is_depthwise,
jcp.ngroups % 32 == 0);
const bool is_32oc = true
&& IMPLICATION(src_mdw.data_type() == data_type::f16,
jcp.oc % 32 == 0);
jcp.mb_block = 1;
jcp.oc_block = 1;
jcp.ic_block = 1;
jcp.od_block = 1;
jcp.oh_block = 1;
jcp.ow_block = 1;
jcp.ver = ver_ref;
if (use_16mb_unroll)
jcp.ver = ver_16mb16c;
else if ((is_16oc && is_16ic) || is_dw_16g)
jcp.ver = ver_8ow16c;
else if (is_1stconv && is_16oc && is_32oc)
jcp.ver = ver_1stconv;
else
jcp.ver = ver_ref;
status_t status = status::success;
jcp.ocb = 1;
jcp.src_data_type = src_mdw.data_type();
switch (jcp.ver) {
case ver_16mb16c:
jcp.mb_block = 16;
if (src_mdw.data_type() == mkldnn_f32
|| src_mdw.data_type() == mkldnn_f16) {
if (src_mdw.data_type() == mkldnn_f16 && jcp.mb % 32 != 0) {
jcp.mb_block = (jcp.ver == ver_1stconv && jcp.mb % 16 == 0)
? 16
: 1;
jcp.oc_block = 16;
jcp.ic_block = (jcp.ver == ver_1stconv) ? 1 : 16;
jcp.ow_block = 8;
jcp.oh_block = 1;
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = jcp.ngroups * jcp.oc;
jcp.gws_d[1] = utils::div_up(jcp.oh, jcp.oh_block)
* utils::div_up(jcp.ow, jcp.ow_block) * jcp.od;
jcp.gws_d[2] = jcp.mb;
} else {
jcp.oc_block = 16;
jcp.ic_block = 16;
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = jcp.oc * jcp.ngroups;
jcp.gws_d[1] = jcp.oh * jcp.ow * jcp.od;
jcp.gws_d[2] = (src_mdw.data_type() == mkldnn_f16
&& !jcp.is_depthwise)
? jcp.mb / (jcp.mb_block * 2)
: jcp.mb / (jcp.mb_block * 1);
}
} else {
jcp.oc_block = utils::one_of(src_mdw.data_type(), mkldnn_s8,
mkldnn_u8)
? 32
: 16;
jcp.ic_block = utils::one_of(src_mdw.data_type(), mkldnn_s8,
mkldnn_u8)
? 32
: 16;
jcp.mb_block = 32;
jcp.sub_group_size = 8;
if (jcp.kw == 1) {
jcp.slm_ic = 2;
} else {
jcp.slm_ic = 1;
}
if (jcp.oc == 64) {
jcp.lws_d[0] = 2 * 8;
jcp.lws_d[1] = 8;
} else if (jcp.oc % 128 == 0) {
jcp.lws_d[0] = 4 * 8;
jcp.lws_d[1] = 4;
} else {
jcp.lws_d[0] = utils::max_div(jcp.oc, 4) * 8;
jcp.lws_d[1] = utils::max_div(jcp.ow, 4);
}
jcp.lws_d[2] = 1;
jcp.gws_d[0] = (jcp.oc / jcp.oc_block) * 8;
jcp.gws_d[1] = jcp.oh * utils::rnd_up(jcp.ow, jcp.lws_d[1]);
jcp.gws_d[2] = jcp.mb / (jcp.mb_block * 1);
}
jcp.wht_slm_size = jcp.slm_ic * jcp.ic_block * (jcp.lws_d[0] / 8)
* jcp.oc_block * jcp.kw;
if (jcp.kw == 1)
jcp.src_slm_size = jcp.slm_ic * jcp.ic_block
* (jcp.lws_d[1] + jcp.kw - 1) * jcp.mb_block;
else
jcp.src_slm_size = jcp.slm_ic * jcp.ic_block
* (jcp.stride_w * (jcp.lws_d[1] - 1) + jcp.kw)
* jcp.mb_block;
#ifdef DEBUG_PRINT
printf("LWS = %ld\n", jcp.lws_d[0] * jcp.lws_d[2] * jcp.lws_d[1]);
fflush(0);
printf("USE SLM %ld KB\n",
utils::div_up(jcp.wht_slm_size + jcp.src_slm_size, 1024));
fflush(0);
printf("LWS GWS: (%ld %ld %ld) (%ld %ld %ld)\n", jcp.lws_d[0],
jcp.lws_d[1], jcp.lws_d[2], jcp.gws_d[0], jcp.gws_d[1],
jcp.gws_d[2]);
#endif
break;
case ver_1stconv:
if (src_mdw.data_type() == mkldnn_f16) {
jcp.mb_block = jcp.mb % 16 == 0 ? 16 : 1;
jcp.oc_block = 16;
jcp.ic_block = 16;
jcp.ow_block = 8;
jcp.oh_block = 1;
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = (jcp.oc / 2) * jcp.ngroups;
jcp.gws_d[1] = utils::div_up(jcp.oh, jcp.oh_block)
* utils::div_up(jcp.ow, jcp.ow_block) * jcp.od;
jcp.gws_d[2] = jcp.mb % 2 == 0 ? jcp.mb / 2
: jcp.mb; // unroll mb by 2
break;
} else if (utils::one_of(
src_mdw.data_type(), mkldnn_s8, mkldnn_u8)) {
jcp.mb_block = 32;
jcp.oc_block = 32;
jcp.ic_block = 32;
jcp.slm_ic = 1;
jcp.sub_group_size = 8;
jcp.lws_d[0] = 2 * 8;
jcp.lws_d[1] = utils::max_div(jcp.ow, 16);
jcp.lws_d[2] = 1;
jcp.gws_d[0] = (jcp.oc / jcp.oc_block) * 8;
jcp.gws_d[1] = jcp.oh * jcp.ow;
jcp.gws_d[2] = jcp.mb / jcp.mb_block;
jcp.wht_slm_size = jcp.ic_block * (jcp.lws_d[0] / 8)
* jcp.oc_block * jcp.kw;
jcp.src_slm_size = jcp.ic_block
* (jcp.stride_w * (jcp.lws_d[1] - 1) + jcp.kw)
* jcp.mb_block;
#ifdef DEBUG_PRINT
printf("1st: LWS = %ld\n",
jcp.lws_d[0] * jcp.lws_d[2] * jcp.lws_d[1]);
fflush(0);
printf("1st: USE SLM %ld KB\n",
utils::div_up(
jcp.wht_slm_size + jcp.src_slm_size, 1024));
fflush(0);
printf("1st: LWS GWS: (%ld %ld %ld) (%ld %ld %ld)\n",
jcp.lws_d[0], jcp.lws_d[1], jcp.lws_d[2], jcp.gws_d[0],
jcp.gws_d[1], jcp.gws_d[2]);
printf("SRC_SP_GROUP=%ld\n",
jcp.stride_w * (jcp.lws_d[1] - 1) + jcp.kw);
#endif
break;
}
case ver_8ow16c:
switch (src_mdw.data_type()) {
case data_type::f32:
jcp.mb_block
= (jcp.ver == ver_1stconv && jcp.mb % 16 == 0) ? 16 : 1;
jcp.oc_block = 16;
jcp.ic_block = (jcp.ver == ver_1stconv) ? 1 : 16;
if (jcp.is_depthwise) {
jcp.ow_block = utils::max_div(jcp.ow, 8);
} else {
jcp.ow_block = (jcp.ver == ver_1stconv)
? 8
: nstl::max(8, utils::max_div(jcp.ow, 16));
}
jcp.oh_block = 1;
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
if (jcp.is_depthwise) {
jcp.ocb = jcp.ngroups;
} else {
jcp.ocb = 128;
while (jcp.ocb > 16) {
if (jcp.oc % jcp.ocb == 0)
break;
else
jcp.ocb /= 2;
}
}
jcp.gws_d[0] = jcp.ocb;
jcp.gws_d[1] = utils::div_up(jcp.oh, jcp.oh_block)
* utils::div_up(jcp.ow, jcp.ow_block) * jcp.od;
if (jcp.is_depthwise) {
jcp.gws_d[2] = jcp.mb * (jcp.ngroups / jcp.ocb);
} else {
jcp.gws_d[2] = jcp.mb * (jcp.oc / jcp.ocb) * jcp.ngroups;
}
break;
case data_type::f16:
jcp.mb_block
= (jcp.ver == ver_1stconv && jcp.mb % 16 == 0) ? 16 : 1;
jcp.oc_block = 16;
jcp.ic_block = (jcp.ver == ver_1stconv) ? 1 : 16;
if (jcp.is_depthwise) {
jcp.ow_block = utils::max_div(jcp.ow, 8);
} else {
jcp.ow_block = (jcp.ver == ver_1stconv)
? 8
: nstl::max(8, utils::max_div(jcp.ow, 16));
}
jcp.oh_block = 1;
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.ocb = 128;
if (jcp.is_depthwise) {
jcp.ocb = jcp.ngroups;
} else {
while (jcp.ocb > 16) {
if (jcp.oc % jcp.ocb == 0)
break;
else
jcp.ocb /= 2;
}
}
jcp.gws_d[0] = jcp.ocb;
jcp.gws_d[1] = utils::div_up(jcp.oh, jcp.oh_block)
* utils::div_up(jcp.ow, jcp.ow_block) * jcp.od;
if (jcp.is_depthwise) {
jcp.gws_d[2] = jcp.mb * (jcp.ngroups / jcp.ocb);
} else {
jcp.gws_d[2] = jcp.mb * (jcp.oc / jcp.ocb) * jcp.ngroups;
}
break;
default: return status::unimplemented;
}
break;
case ver_ref:
jcp.mb_block = 1;
jcp.oc_block = 1;
jcp.ic_block = 1;
jcp.oh_block = 1;
jcp.ow_block = 1;
jcp.sub_group_size = 1;
jcp.lws_d[0] = 1;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = jcp.ow * jcp.oh * jcp.od;
jcp.gws_d[1] = jcp.oc * jcp.ngroups;
jcp.gws_d[2] = jcp.mb;
break;
default: status = status::unimplemented;
}
jcp.with_bias = cd.bias_desc.format_kind != format_kind::undef;
format_tag_t src_tag, dst_tag, wei_tag;
switch (jcp.ver) {
case ver_ref:
src_tag = (jcp.ndims == 5) ? ncdhw : nchw;
dst_tag = (jcp.ndims == 5) ? ncdhw : nchw;
wei_tag = (jcp.ndims == 5) ? (jcp.with_groups) ? goidhw : oidhw
: (jcp.with_groups) ? goihw : oihw;
break;
case ver_1stconv:
if (utils::one_of(src_mdw.data_type(), mkldnn_u8, mkldnn_s8)) {
src_tag = (jcp.ndims == 5) ? ncdhw : chwn;
dst_tag = jcp.mb % 16 == 0
? (jcp.ndims == 5) ? ncdhw : NChw32n32c
: (jcp.ndims == 5) ? ncdhw : nChw16c;
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? goidhw : oidhw
: (jcp.with_groups) ? gOhwi32o : Ohwi32o;
} else {
src_tag = (jcp.ndims == 5) ? ncdhw : nchw;
dst_tag = jcp.mb % 16 == 0
? (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c
: (jcp.ndims == 5) ? nCdhw16c : nChw16c;
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gOdhwi16o : Odhwi16o
: (jcp.with_groups) ? gOhwi16o : Ohwi16o;
}
break;
case ver_16mb16c:
if (utils::one_of(src_mdw.data_type(), mkldnn_f16)) {
if (jcp.mb % 32 == 0) {
src_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
dst_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
if (jcp.is_depthwise) {
wei_tag = (jcp.ndims == 5) ? Goidhw16g : Goihw16g;
} else {
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gOIdhw8i16o2i
: OIdhw8i16o2i
: (jcp.with_groups) ? gOIhw8i16o2i
: OIhw8i16o2i;
}
} else {
src_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
dst_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gIOdhw16i16o : IOdhw16i16o
: (jcp.with_groups) ? gIOhw16i16o : IOhw16i16o;
}
} else if (utils::one_of(
src_mdw.data_type(), mkldnn_u8, mkldnn_s8)) {
src_tag = (jcp.ndims == 5) ? ncdhw : NChw32n32c;
dst_tag = (jcp.ndims == 5) ? ncdhw : NChw32n32c;
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gOidhw16o : Oidhw16o
: (jcp.with_groups) ? gOIhw4o8i8o4i : OIhw4o8i8o4i;
} else {
src_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
dst_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
if (jcp.is_depthwise) {
wei_tag = (jcp.ndims == 5) ? Goidhw16g : Goihw16g;
} else {
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gIOdhw16i16o : IOdhw16i16o
: (jcp.with_groups) ? gIOhw16i16o : IOhw16i16o;
}
}
break;
case ver_8ow16c:
src_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
dst_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
if (jcp.is_depthwise) {
wei_tag = (jcp.ndims == 5) ? Goidhw16g : Goihw16g;
} else {
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gOIdhw16i16o : OIdhw16i16o
: (jcp.with_groups) ? gOIhw16i16o : OIhw16i16o;
}
break;
default: status = status::unimplemented;
}
if (status != status::success)
return status;
jcp.src_tag = src_tag;
jcp.wei_tag = wei_tag;
jcp.dst_tag = dst_tag;
jcp.is_nchw = utils::one_of(src_tag, nchw, ncdhw);
jcp.is_nhwc = utils::one_of(src_tag, nhwc, ndhwc);
return status;
};
static status_t init_const_def(ocl_jit_t &jit, const jit_conv_conf_t &jcp) {
jit.define_int("IS_DW", jcp.is_depthwise);
jit.define_int("FWD_DATA", 1);
jit.define_int("G", jcp.ngroups);
jit.define_int("MB", jcp.mb);
jit.define_int("IC", jcp.ic_without_padding);
jit.define_int("ID", jcp.id);
jit.define_int("IH", jcp.ih);
jit.define_int("IW", jcp.iw);
jit.define_int("OC", jcp.oc_without_padding);
jit.define_int("OD", jcp.od);
jit.define_int("OH", jcp.oh);
jit.define_int("OW", jcp.ow);
jit.define_int("KD", jcp.kd);
jit.define_int("KH", jcp.kh);
jit.define_int("KW", jcp.kw);
jit.define_int("SD", jcp.stride_d);
jit.define_int("SH", jcp.stride_h);
jit.define_int("SW", jcp.stride_w);
jit.define_int("PD", jcp.f_pad);
jit.define_int("PH", jcp.t_pad);
jit.define_int("PW", jcp.l_pad);
jit.define_int("DD", jcp.dilate_d);
jit.define_int("DH", jcp.dilate_h);
jit.define_int("DW", jcp.dilate_w);
jit.define_int("OW_PADDED", utils::rnd_up(jcp.ow, 4));
jit.define_int("OC_PADDED", jcp.oc);
jit.define_int("OCB", jcp.ocb);
jit.define_int("MB_BLOCK", jcp.mb_block);
jit.define_int("OH_BLOCK", jcp.oh_block);
jit.define_int("OW_BLOCK", jcp.ow_block);
jit.define_int("OW_LAST", utils::rnd_dn(jcp.ow, jcp.ow_block));
jit.define_int("OWB", utils::div_up(jcp.ow, jcp.ow_block));
jit.define_int("OHB", utils::div_up(jcp.oh, jcp.oh_block));
jit.define_int("WITH_BIAS", jcp.with_bias);
jit.define_int("WITH_RELU", jcp.with_relu);
jit.define_int("WITH_SUM", jcp.with_sum);
jit.define_int("WITH_SUM_RELU", jcp.with_sum_relu);
jit.define_int("SUM_SCALE", jcp.sum_scale == 1.0);
jit.define_int("SUB_GROUP_SIZE", jcp.sub_group_size);
jit.define_int("OC_BLOCK", jcp.oc_block);
jit.define_int("IC_BLOCK", jcp.ic_block);
jit.define_int("OC_GROUP", jcp.lws_d[0] / 8);
jit.define_int("MB_GROUP", 1);
jit.define_int("SP_GROUP", jcp.lws_d[1]);
if (jcp.kw == 1)
jit.define_int("SRC_SP_GROUP", jcp.lws_d[1] + jcp.kw - 1);
else
jit.define_int(
"SRC_SP_GROUP", jcp.stride_w * (jcp.lws_d[1] - 1) + jcp.kw);
jit.define_int("SLM_IC", jcp.slm_ic);
const int use_fast_path = 1 && jcp.scale_idx_mult == 0
&& jcp.ngroups == 1 && !jcp.with_bias;
jit.define_int("USE_FAST_PATH", use_fast_path);
jit.define_int("SCALE_IDX_MULT", jcp.scale_idx_mult);
jit.define_int("RMODE", jcp.rmode);
jit.set_data_type(jcp.src_data_type);
switch (jcp.ver) {
case ver_ref: jit.define_int("VER_REF", 1); break;
case ver_16mb16c: jit.define_int("VER_16MB16C", 1); break;
case ver_1stconv:
case ver_8ow16c: jit.define_int("VER_8OW16C", 1); break;
default: break;
}
jit.define_int("LWS_0", jcp.lws_d[0]);
jit.define_int("LWS_1", jcp.lws_d[1]);
jit.define_int("LWS_2", jcp.lws_d[2]);
if (jcp.is_nchw)
jit.define_int("NCHW", 1);
else if (jcp.is_nhwc)
jit.define_int("NHWC", 1);
jit.add_option("-Dcl_intel_subgroup_matrix_multiply_accumulate");
jit.add_option("-Dcl_intel_subgroups_char");
#ifdef DEBUG_PRINT
printf("OPT:\n%s\n", jit.get_options());
#endif
return status::success;
}
jit_conv_conf_t jcp;
};
struct jit_gen9_common_conv_bwd_data_kernel {
jit_gen9_common_conv_bwd_data_kernel(jit_conv_conf_t ajcp) : jcp(ajcp){};
~jit_gen9_common_conv_bwd_data_kernel(){};
static status_t init_conf(jit_conv_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_t &diff_src_md,
const memory_desc_t &weights_md, const memory_desc_t &diff_dst_md,
const primitive_attr_t &attr) {
const memory_desc_wrapper src_mdw(&diff_src_md);
const memory_desc_wrapper weights_mdw(&weights_md);
const memory_desc_wrapper dst_mdw(&diff_dst_md);
set_default_conf(jcp, cd, diff_src_md, weights_md, diff_dst_md, attr);
const bool is_dw_16g = (jcp.is_depthwise && jcp.ngroups % 16 == 0);
const bool is_1stconv = jcp.ic == 3;
const bool is_16ic = jcp.ic % 16 == 0;
const bool is_16oc = jcp.oc % 16 == 0;
const bool use_16mb_unroll = true
&& !(jcp.mb == 1 || jcp.mb % 16 != 0)
&& !is_1stconv && ((is_16ic && is_16oc) || is_dw_16g);
jcp.mb_block = 1;
jcp.oc_block = 1;
jcp.ic_block = 1;
jcp.od_block = 1;
jcp.oh_block = 1;
jcp.ow_block = 1;
jcp.ver = ver_ref;
if (use_16mb_unroll)
jcp.ver = ver_16mb16c;
if (jcp.mb % 16 != 0 && ((is_16oc && is_16ic) || is_dw_16g))
jcp.ver = ver_8ow16c;
if (is_1stconv && is_16oc)
jcp.ver = ver_1stconv;
status_t status = status::success;
switch (jcp.ver) {
case ver_16mb16c:
jcp.mb_block = 16;
jcp.oc_block = 16;
jcp.ic_block = 16;
jcp.od_block = 1;
jcp.ih_block = 1;
jcp.iw_block = 1;
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = jcp.ic * jcp.ngroups;
jcp.gws_d[1] = jcp.ih * jcp.iw * jcp.id;
jcp.gws_d[2] = jcp.mb / 16;
break;
case ver_8ow16c:
jcp.mb_block = 1;
jcp.oc_block = 16;
jcp.ic_block = 16;
jcp.od_block = 1;
jcp.ih_block = 1;
jcp.iw_block = 1;
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = jcp.ic * jcp.ngroups;
jcp.gws_d[1] = jcp.ih * jcp.iw * jcp.id;
jcp.gws_d[2] = utils::div_up(jcp.mb, 16);
break;
case ver_1stconv:
case ver_ref:
jcp.mb_block = 1;
jcp.oc_block = 1;
jcp.ic_block = 1;
jcp.od_block = 1;
jcp.ih_block = 1;
jcp.iw_block = 1;
jcp.sub_group_size = 1;
jcp.lws_d[0] = 1;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = jcp.iw / jcp.iw_block;
jcp.gws_d[1] = (jcp.ih / jcp.ih_block) * jcp.id;
jcp.gws_d[2] = utils::rnd_up(jcp.ic, jcp.sub_group_size) * jcp.mb
* jcp.ngroups;
break;
default: status = status::unimplemented;
}
jcp.with_bias = cd.bias_desc.format_kind != format_kind::undef;
format_tag_t src_tag, dst_tag, wei_tag;
switch (jcp.ver) {
case ver_1stconv:
case ver_ref:
src_tag = (jcp.ndims == 5) ? ncdhw : nchw;
dst_tag = (jcp.ndims == 5) ? ncdhw : nchw;
wei_tag = (jcp.ndims == 5) ? (jcp.with_groups) ? goidhw : oidhw
: (jcp.with_groups) ? goihw : oihw;
break;
case ver_16mb16c:
src_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
dst_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
if (jcp.is_depthwise) {
wei_tag = (jcp.ndims == 5) ? Goidhw16g : Goihw16g;
} else {
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gOIdhw16o16i : OIdhw16o16i
: (jcp.with_groups) ? gOIhw16o16i : OIhw16o16i;
}
break;
case ver_8ow16c:
src_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
dst_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
if (jcp.is_depthwise) {
wei_tag = (jcp.ndims == 5) ? Goidhw16g : Goihw16g;
} else {
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gOIdhw16o16i : OIdhw16o16i
: (jcp.with_groups) ? gOIhw16o16i : OIhw16o16i;
}
break;
default: status = status::unimplemented;
}
if (status != status::success)
return status;
jcp.src_tag = src_tag;
jcp.wei_tag = wei_tag;
jcp.dst_tag = dst_tag;
jcp.is_nchw = utils::one_of(src_tag, nchw, ncdhw);
jcp.is_nhwc = utils::one_of(src_tag, nhwc, ndhwc);
return status::success;
};
static status_t init_const_def(ocl_jit_t &jit, const jit_conv_conf_t &jcp) {
jit.define_int("IS_DW", jcp.is_depthwise);
jit.define_int("BWD_DATA", 1);
jit.define_int("G", jcp.ngroups);
jit.define_int("MB", jcp.mb);
jit.define_int("IC", jcp.ic_without_padding);
jit.define_int("ID", jcp.id);
jit.define_int("IH", jcp.ih);
jit.define_int("IW", jcp.iw);
jit.define_int("OC", jcp.oc_without_padding);
jit.define_int("OD", jcp.od);
jit.define_int("OH", jcp.oh);
jit.define_int("OW", jcp.ow);
jit.define_int("KD", jcp.kd);
jit.define_int("KH", jcp.kh);
jit.define_int("KW", jcp.kw);
jit.define_int("SD", jcp.stride_d);
jit.define_int("SH", jcp.stride_h);
jit.define_int("SW", jcp.stride_w);
jit.define_int("PD", jcp.f_pad);
jit.define_int("PH", jcp.t_pad);
jit.define_int("PW", jcp.l_pad);
jit.define_int("DD", jcp.dilate_d);
jit.define_int("DH", jcp.dilate_h);
jit.define_int("DW", jcp.dilate_w);
jit.define_int("OC_PADDED", jcp.oc);
jit.define_int("MB_BLOCK", jcp.mb_block);
jit.define_int("MB_LAST", utils::rnd_dn(jcp.mb, 16));
jit.define_int("IH_BLOCK", jcp.ih_block);
jit.define_int("IW_BLOCK", jcp.iw_block);
jit.define_int("IW_LAST", utils::rnd_dn(jcp.iw, jcp.iw_block));
jit.define_int("WITH_BIAS", jcp.with_bias);
jit.define_int("WITH_RELU", jcp.with_relu);
jit.define_int("WITH_SUM", jcp.with_sum);
jit.define_int("WITH_SUM_RELU", jcp.with_sum_relu);
jit.define_int("SUM_SCALE", jcp.sum_scale == 1.0);
jit.define_int("SUB_GROUP_SIZE", jcp.sub_group_size);
jit.define_int("OC_BLOCK", jcp.oc_block);
jit.define_int("IC_BLOCK", jcp.ic_block);
jit.define_int("LWS_0", jcp.lws_d[0]);
jit.define_int("LWS_1", jcp.lws_d[1]);
jit.define_int("LWS_2", jcp.lws_d[2]);
switch (jcp.ver) {
case ver_1stconv:
case ver_ref: jit.define_int("VER_REF", 1); break;
case ver_16mb16c: jit.define_int("VER_16MB16C", 1); break;
case ver_8ow16c: jit.define_int("VER_8OW16C", 1); break;
default: break;
}
return status::success;
}
jit_conv_conf_t jcp;
};
struct jit_gen9_common_conv_bwd_weights_kernel {
jit_gen9_common_conv_bwd_weights_kernel(jit_conv_conf_t ajcp) : jcp(ajcp){};
~jit_gen9_common_conv_bwd_weights_kernel(){};
static status_t init_conf(jit_conv_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_t &src_md,
const memory_desc_t &diff_weights_md,
const memory_desc_t &diff_bias_md, const memory_desc_t &diff_dst_md,
const primitive_attr_t &attr) {
const memory_desc_wrapper src_mdw(&src_md);
const memory_desc_wrapper weights_mdw(&diff_weights_md);
const memory_desc_wrapper dst_mdw(&diff_dst_md);
const memory_desc_wrapper bias_mdw(&diff_bias_md);
set_default_conf(jcp, cd, src_md, diff_weights_md, diff_dst_md, attr);
const bool is_dw_16g = (jcp.is_depthwise && jcp.ngroups % 16 == 0);
const bool is_1stconv = jcp.ic == 3;
const bool is_16ic = jcp.ic % 16 == 0;
const bool is_16oc = jcp.oc % 16 == 0;
const bool use_16mb_unroll = true && !(jcp.mb == 1 || jcp.mb % 16 != 0)
&& !is_1stconv && ((is_16ic && is_16oc) || is_dw_16g);
jcp.mb_block = 1;
jcp.oc_block = 1;
jcp.ic_block = 1;
jcp.od_block = 1;
jcp.oh_block = 1;
jcp.ow_block = 1;
jcp.oh_chunk = 1;
jcp.mb_chunk = 1;
jcp.ver = ver_ref;
if (use_16mb_unroll)
jcp.ver = ver_16mb16c;
if (jcp.mb % 16 != 0 && ((is_16oc && is_16ic) || is_dw_16g)
&& (jcp.iw >= jcp.stride_w * 8))
jcp.ver = ver_8ow16c;
if (is_1stconv && is_16oc)
jcp.ver = ver_1stconv;
status_t status = status::success;
switch (jcp.ver) {
case ver_1stconv:
case ver_8ow16c:
jcp.mb_block = 1;
jcp.oc_block = 16;
jcp.ic_block = jcp.ver == ver_8ow16c ? 16 : 1;
jcp.ow_block = 8;
if (jcp.kd * jcp.kh * jcp.kw
* ((jcp.ic * jcp.oc * jcp.ngroups) / 256)
>= 1024) {
jcp.oh_chunk = 1;
jcp.mb_chunk = nstl::min(jcp.mb, utils::max_div(jcp.mb, 4));
} else {
jcp.mb_chunk = jcp.mb;
jcp.oh_chunk = 1;
}
jcp.nchunk = jcp.oh_chunk * jcp.mb_chunk;
jcp.oh_block
= utils::div_up(jcp.od * jcp.oh * jcp.ow, jcp.oh_chunk);
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
if (jcp.is_depthwise) {
jcp.gws_d[0] = jcp.ngroups;
} else {
jcp.gws_d[0] = jcp.ver == ver_8ow16c
? jcp.oc * (jcp.ic / 16) * jcp.ngroups
: jcp.oc * jcp.ngroups;
}
jcp.gws_d[1] = jcp.kh * jcp.kw * jcp.kd;
jcp.gws_d[2] = jcp.nchunk;
break;
case ver_16mb16c:
jcp.mb_block = 16;
jcp.oc_block = 16;
jcp.ic_block = 16;
jcp.ow_block = 1;
if (jcp.kd * jcp.kh * jcp.kw
* ((jcp.ic * jcp.oc * jcp.ngroups) / 256)
>= 1024) {
jcp.oh_chunk = 1;
jcp.mb_chunk = nstl::min(jcp.mb / 16, 2);
} else if (jcp.kd * jcp.kh * jcp.kw
* ((jcp.ic * jcp.oc * jcp.ngroups) / 256)
>= 256) {
jcp.oh_chunk = nstl::min(jcp.od * jcp.oh * jcp.ow, 4);
jcp.mb_chunk = jcp.mb / 16;
} else {
jcp.mb_chunk = jcp.mb / 16;
jcp.oh_chunk = nstl::min(jcp.od * jcp.oh * jcp.ow, 32);
}
jcp.nchunk = jcp.oh_chunk * jcp.mb_chunk;
jcp.oh_block
= utils::div_up(jcp.od * jcp.oh * jcp.ow, jcp.oh_chunk);
jcp.sub_group_size = 16;
jcp.lws_d[0] = 16;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
if (jcp.is_depthwise) {
jcp.gws_d[0] = jcp.ngroups;
} else {
jcp.gws_d[0] = jcp.oc * (jcp.ic / 16) * jcp.ngroups;
}
jcp.gws_d[1] = jcp.kh * jcp.kw * jcp.kd;
jcp.gws_d[2] = jcp.nchunk;
break;
case ver_ref:
jcp.sub_group_size = 1;
jcp.lws_d[0] = 1;
jcp.lws_d[1] = 1;
jcp.lws_d[2] = 1;
jcp.gws_d[0] = jcp.kw;
jcp.gws_d[1] = jcp.kh * jcp.kd;
jcp.gws_d[2] = jcp.ic * jcp.oc * jcp.ngroups;
break;
default: status = status::unimplemented;
}
jcp.with_bias = cd.diff_bias_desc.format_kind != format_kind::undef;
format_tag_t src_tag, dst_tag, wei_tag;
switch (jcp.ver) {
case ver_ref:
src_tag = (jcp.ndims == 5) ? ncdhw : nchw;
dst_tag = (jcp.ndims == 5) ? ncdhw : nchw;
wei_tag = (jcp.ndims == 5) ? (jcp.with_groups) ? goidhw : oidhw
: (jcp.with_groups) ? goihw : oihw;
break;
case ver_1stconv:
assert(!jcp.is_depthwise);
src_tag = (jcp.ndims == 5) ? ncdhw : nchw;
dst_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gOdhwi16o : Odhwi16o
: (jcp.with_groups) ? gOhwi16o : Ohwi16o;
break;
case ver_16mb16c:
src_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
dst_tag = (jcp.ndims == 5) ? NCdhw16n16c : NChw16n16c;
if (jcp.is_depthwise) {
wei_tag = (jcp.ndims == 5) ? Goidhw16g : Goihw16g;
} else {
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gIOdhw16i16o : IOdhw16i16o
: (jcp.with_groups) ? gIOhw16i16o : IOhw16i16o;
}
break;
case ver_8ow16c:
src_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
dst_tag = (jcp.ndims == 5) ? nCdhw16c : nChw16c;
if (jcp.is_depthwise) {
wei_tag = (jcp.ndims == 5) ? Goidhw16g : Goihw16g;
} else {
wei_tag = (jcp.ndims == 5)
? (jcp.with_groups) ? gIOdhw16i16o : IOdhw16i16o
: (jcp.with_groups) ? gIOhw16i16o : IOhw16i16o;
}
break;
default: status = status::unimplemented;
}
if (status != status::success)
return status;
jcp.src_tag = src_tag;
jcp.wei_tag = wei_tag;
jcp.dst_tag = dst_tag;
return status::success;
};
static status_t init_const_def(ocl_jit_t &jit, const jit_conv_conf_t &jcp) {
jit.define_int("IS_DW", jcp.is_depthwise);
jit.define_int("BWD_WEIGHTS", 1);
jit.define_int("G", jcp.ngroups);
jit.define_int("MB", jcp.mb);
jit.define_int("IC", jcp.ic_without_padding);
jit.define_int("ID", jcp.id);
jit.define_int("IH", jcp.ih);
jit.define_int("IW", jcp.iw);
jit.define_int("OC", jcp.oc_without_padding);
jit.define_int("OD", jcp.od);
jit.define_int("OH", jcp.oh);
jit.define_int("OW", jcp.ow);
jit.define_int("KD", jcp.kd);
jit.define_int("KH", jcp.kh);
jit.define_int("KW", jcp.kw);
jit.define_int("SD", jcp.stride_d);
jit.define_int("SH", jcp.stride_h);
jit.define_int("SW", jcp.stride_w);
jit.define_int("PD", jcp.f_pad);
jit.define_int("PH", jcp.t_pad);
jit.define_int("PW", jcp.l_pad);
jit.define_int("DD", jcp.dilate_d);
jit.define_int("DH", jcp.dilate_h);
jit.define_int("DW", jcp.dilate_w);
jit.define_int("OC_PADDED", jcp.oc);
jit.define_int("OH_BLOCK", jcp.oh_block);
jit.define_int("WITH_BIAS", jcp.with_bias);
jit.define_int("WITH_RELU", jcp.with_relu);
jit.define_int("WITH_SUM", jcp.with_sum);
jit.define_int("WITH_SUM_RELU", jcp.with_sum_relu);
jit.define_int("SUM_SCALE", jcp.sum_scale == 1.0);
jit.define_int("SUB_GROUP_SIZE", jcp.sub_group_size);
jit.define_int("MB_BLOCK", jcp.mb_block);
jit.define_int("OC_BLOCK", jcp.oc_block);
jit.define_int("IC_BLOCK", jcp.ic_block);
jit.define_int("NCHUNK", jcp.nchunk);
jit.define_int("OH_CHUNK", jcp.oh_chunk);
jit.define_int("MB_CHUNK", jcp.mb_chunk);
jit.define_int("OW_BLOCK", jcp.ow_block);
jit.define_int("OW_LAST", utils::rnd_dn(jcp.ow, jcp.ow_block));
jit.define_int("LWS_0", jcp.lws_d[0]);
jit.define_int("LWS_1", jcp.lws_d[1]);
jit.define_int("LWS_2", jcp.lws_d[2]);
switch (jcp.ver) {
case ver_ref: jit.define_int("VER_REF", 1); break;
case ver_16mb16c: jit.define_int("VER_16MB16C", 1); break;
case ver_1stconv:
case ver_8ow16c: jit.define_int("VER_8OW16C", 1); break;
default: break;
}
return status::success;
}
jit_conv_conf_t jcp;
};
} // namespace ocl
} // namespace impl
} // namespace mkldnn
#endif
| 39.736345 | 80 | 0.486214 | uyongw |
c86fa9294611c85f7f6f0cc2435d0f86cbcd02ff | 1,075 | hpp | C++ | src/GameState/PhysicalObject/Player.hpp | Heaven31415/SpaceShooter | 385e43aa2deb8720c1b0a23834ad31de97fd25eb | [
"Zlib"
] | null | null | null | src/GameState/PhysicalObject/Player.hpp | Heaven31415/SpaceShooter | 385e43aa2deb8720c1b0a23834ad31de97fd25eb | [
"Zlib"
] | null | null | null | src/GameState/PhysicalObject/Player.hpp | Heaven31415/SpaceShooter | 385e43aa2deb8720c1b0a23834ad31de97fd25eb | [
"Zlib"
] | null | null | null | #pragma once
#include "Weapons\LaserFactory.hpp"
#include "../PhysicalObject.hpp"
#include "../../Common/Context.hpp"
#include "../../Common/Observer.hpp"
class World;
class Player : public PhysicalObject
{
public:
enum class Frame
{
Straight,
Left,
Right
};
enum class Weapon
{
Laser,
};
Player(Context& context, World& world, LaserFactory& laserFactory);
virtual void collision(PhysicalObject* object) override;
void onEnemyKilled(PhysicalObject* object); // callback
void setGraphicsFrame(Player::Frame frame);
void addWeapon(Player::Weapon weapon);
std::size_t getWeaponCount();
bool canAddWeapon();
private:
LaserFactory& m_laserFactory;
const GraphicsFrames m_frames;
const std::size_t m_maxWeaponCount;
}; | 29.861111 | 107 | 0.512558 | Heaven31415 |
c87016a61baadf2a9cb74fbd2a002c384803322d | 809 | hpp | C++ | include/lug/Graphics/Builder/Scene.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 275 | 2016-10-08T15:33:17.000Z | 2022-03-30T06:11:56.000Z | include/lug/Graphics/Builder/Scene.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 24 | 2016-09-29T20:51:20.000Z | 2018-05-09T21:41:36.000Z | include/lug/Graphics/Builder/Scene.hpp | Lugdunum3D/Lugdunum3D | b6d6907d034fdba1ffc278b96598eba1d860f0d4 | [
"MIT"
] | 37 | 2017-02-25T05:03:48.000Z | 2021-05-10T19:06:29.000Z | #pragma once
#include <vector>
#include <string>
#include <lug/Graphics/Resource.hpp>
#include <lug/Graphics/Scene/Scene.hpp>
namespace lug {
namespace Graphics {
class Renderer;
namespace Builder {
class LUG_GRAPHICS_API Scene {
public:
explicit Scene(Renderer& renderer);
Scene(const Scene&) = delete;
Scene(Scene&&) = delete;
Scene& operator=(const Scene&) = delete;
Scene& operator=(Scene&&) = delete;
~Scene() = default;
/**
* @brief Sets the name.
* @param[in] name The name of the scene.
*/
void setName(const std::string& name);
Resource::SharedPtr<lug::Graphics::Scene::Scene> build();
protected:
Renderer& _renderer;
std::string _name;
};
#include <lug/Graphics/Builder/Scene.inl>
} // Builder
} // Graphics
} // lug
| 16.854167 | 61 | 0.647713 | Lugdunum3D |
c87418f9015157295076a8c57c6a644028956a46 | 17,341 | cpp | C++ | src/pgen/mignone_advection.cpp | kahoooo/athena-public | 583aee106677cba7fa5ea4e3689e2cfb81796e25 | [
"BSD-3-Clause"
] | 174 | 2016-11-30T01:20:14.000Z | 2022-02-22T16:23:55.000Z | src/pgen/mignone_advection.cpp | kahoooo/athena-public | 583aee106677cba7fa5ea4e3689e2cfb81796e25 | [
"BSD-3-Clause"
] | 74 | 2017-01-30T22:37:33.000Z | 2021-05-10T17:20:33.000Z | src/pgen/mignone_advection.cpp | kahoooo/athena-public | 583aee106677cba7fa5ea4e3689e2cfb81796e25 | [
"BSD-3-Clause"
] | 126 | 2016-12-08T14:03:22.000Z | 2022-03-31T06:01:59.000Z | //========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file mignone_advection.cpp
//! \brief 1D passive scalar advection tests in curvilinear coordinates from:
//! Mignone, A. (2014). High-order conservative reconstruction schemes for finite volume
//! methods in cylindrical and spherical coordinates. Journal of Computational Physics,
//! 270, 784-814.
//========================================================================================
// C++ headers
#include <algorithm> // min, max
#include <iostream> // endl
#include <sstream> // stringstream
#include <stdexcept> // runtime_error
#include <string> // c_str()
// Athena++ headers
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../coordinates/coordinates.hpp"
#include "../eos/eos.hpp"
#include "../field/field.hpp"
#include "../globals.hpp"
#include "../hydro/hydro.hpp"
#include "../mesh/mesh.hpp"
#include "../parameter_input.hpp"
#include "../scalars/scalars.hpp"
#include "../utils/gl_quadrature.hpp"
// Parameters which define initial solution -- made global so that they can be shared
namespace {
constexpr int N_gl = 12;
constexpr Real d0 = 1.0;
constexpr bool use_gl_quadrature = true;
Real (*IntegrandInitial)(Real x1);
Real (*IntegrandFinal)(Real x1);
Real a_width, b_center, alpha;
Real iso_cs;
int m_coord;
Real t_final;
int iprob;
// pointwise analytic initial condition for Gaussian bell curve
Real InitialGaussianProfile(Real x1);
// pointwise analytic exact solution at any t >=0 for a linear x1 velocity profile
Real FinalGaussianProfile(Real x1);
Real InitialGaussianCylindricalIntegrand(Real x1);
Real FinalGaussianCylindricalIntegrand(Real x1);
Real InitialGaussianSphericalIntegrand(Real x1);
Real FinalGaussianSphericalIntegrand(Real x1);
Real InitialCosineProfile(Real x2);
Real FinalCosineProfile(Real x2);
Real InitialCosineSphericalIntegrand(Real x2);
Real FinalCosineSphericalIntegrand(Real x2);
} // namespace
//========================================================================================
//! \fn void Mesh::InitUserMeshData(ParameterInput *pin)
//========================================================================================
void Mesh::InitUserMeshData(ParameterInput *pin) {
// read and initialize global parameters
iso_cs = pin->GetReal("hydro", "iso_sound_speed");
// initial condition; see Mignone (2014) section 5.1.1
alpha = pin->GetOrAddReal("problem", "alpha", 1.0);
a_width = pin->GetOrAddReal("problem", "a_width", 10.0);
b_center = pin->GetOrAddReal("problem", "b_center", 0.0);
t_final = pin->GetOrAddReal("time", "tlim", 1.0);
iprob = pin->GetInteger("problem", "iprob");
if (std::strcmp(COORDINATE_SYSTEM, "cartesian") == 0) {
if (iprob == 1) {
m_coord = 0;
IntegrandInitial = &InitialGaussianProfile;
IntegrandFinal = &FinalGaussianProfile;
} else if (iprob == 2) {
IntegrandInitial = &InitialCosineProfile;
IntegrandFinal = &FinalCosineProfile;
}
} else if (std::strcmp(COORDINATE_SYSTEM, "cylindrical") == 0) {
if (iprob == 1) {
m_coord = 1;
IntegrandInitial = &InitialGaussianCylindricalIntegrand;
IntegrandFinal = &FinalGaussianCylindricalIntegrand;
} else if (iprob == 2) {
// iprob=2 is for spherical-polar coordinates only
}
} else { // if (std::strcmp(COORDINATE_SYSTEM, "spherical_polar") == 0)
if (iprob == 1) {
m_coord = 2;
IntegrandInitial = &InitialGaussianSphericalIntegrand;
IntegrandFinal = &FinalGaussianSphericalIntegrand;
} else if (iprob == 2) {
IntegrandInitial = &InitialCosineSphericalIntegrand;
IntegrandFinal = &FinalCosineSphericalIntegrand;
}
}
// Restrict to: 1) no-MHD 2) isothermal EOS only 3) hydro/active=background
// TODO(felker): add explicit user-safety checks for these conditions
return;
}
//========================================================================================
//! \fn void Mesh::UserWorkAfterLoop(ParameterInput *pin)
//========================================================================================
void Mesh::UserWorkAfterLoop(ParameterInput *pin) {
if (!pin->GetOrAddBoolean("problem", "compute_error", false)) return;
if (NSCALARS > 0) { // TODO(felker): error-out at compile time if NSCALARS < 1
// Initialize errors to zero
// (temp. workaround for zero-length array prohibition from ISO C++; replace with
// dynamically-sized arrays)
Real l1_err[(NSCALARS > 0 ? NSCALARS : 1)]{},
max_err[(NSCALARS > 0 ? NSCALARS : 1)]{};
Real total_vol = 0.0;
MeshBlock *pmb = my_blocks(0);
AthenaArray<Real> vol(pmb->ncells1);
// recalculate initial condition from ProblemGenerator on final Mesh configuration:
// (may have changed due to AMR)
for (int b=0; b<nblocal; ++b) {
pmb = my_blocks(b);
int il = pmb->is, iu = pmb->ie, jl = pmb->js, ju = pmb->je,
kl = pmb->ks, ku = pmb->ke;
// only interested in error of the evolved passive scalar profiles
constexpr int scalar_norm = NSCALARS > 0 ? NSCALARS : 1.0;
for (int n=0; n<NSCALARS; ++n) {
for (int k=kl; k<=ku; k++) {
for (int j=jl; j<=ju; j++) {
pmb->pcoord->CellVolume(k, j, il, iu, vol);
for (int i=il; i<=iu; i++) {
Real cell_ave;
if (iprob == 1) {
if (use_gl_quadrature) {
Real xl, xu;
xl = pmb->pcoord->x1f(i);
xu = pmb->pcoord->x1f(i+1);
// GL implementation returns total integral, not ave. Divide by delta_r
Real cell_quad = GaussLegendre::integrate(N_gl, IntegrandFinal, xl, xu);
cell_ave = cell_quad/vol(i);
// assuming that the Gaussian profile is 1D in radial coordinate to pull
// out 2x integrals from the triple volume integral
if (std::strcmp(COORDINATE_SYSTEM, "cartesian") == 0 || // dy*dz
std::strcmp(COORDINATE_SYSTEM, "cylindrical") == 0) { // dz*dphi
cell_ave *= pmb->pcoord->dx2f(j);
cell_ave *= pmb->pcoord->dx3f(k);
} else { // if (std::strcmp(COORDINATE_SYSTEM, "spherical_polar") == 0)
// sin(theta)*dtheta*dphi
cell_ave *= std::cos(pmb->pcoord->x2f(j)) -
std::cos(pmb->pcoord->x2f(j+1));
cell_ave *= pmb->pcoord->dx3f(k);
}
} else {
// Use standard midpoint approximation with cell-centered coords:
cell_ave = FinalGaussianProfile(pmb->pcoord->x1v(i));
}
} else if (iprob == 2) {
if (use_gl_quadrature) {
Real xl, xu;
xl = pmb->pcoord->x2f(j);
xu = pmb->pcoord->x2f(j+1);
Real cell_quad = GaussLegendre::integrate(N_gl, IntegrandFinal, xl, xu);
cell_ave = cell_quad*pmb->pcoord->dx3f(k)/vol(i);
cell_ave *= ONE_3RD*(SQR(pmb->pcoord->x1f(i+1))*pmb->pcoord->x1f(i+1)
- SQR(pmb->pcoord->x1f(i))*pmb->pcoord->x1f(i));
} else {
cell_ave = FinalCosineProfile(pmb->pcoord->x2v(j));
}
} // end if iprob == 2
Real sol = 1.0/scalar_norm*cell_ave;
Real abs_diff = std::abs(sol - pmb->pscalars->s(n,k,j,i));
l1_err[n] += abs_diff*vol(i);
max_err[n] = std::max(abs_diff, max_err[n]);
total_vol += vol(i);
}
}
}
}
}
#ifdef MPI_PARALLEL
if (Globals::my_rank == 0) {
MPI_Reduce(MPI_IN_PLACE, &l1_err, NSCALARS, MPI_ATHENA_REAL, MPI_SUM, 0,
MPI_COMM_WORLD);
MPI_Reduce(MPI_IN_PLACE, &total_vol, 1, MPI_ATHENA_REAL, MPI_SUM, 0,
MPI_COMM_WORLD);
MPI_Reduce(MPI_IN_PLACE, &max_err, NSCALARS, MPI_ATHENA_REAL, MPI_MAX, 0,
MPI_COMM_WORLD);
} else {
MPI_Reduce(&l1_err, &l1_err, NSCALARS, MPI_ATHENA_REAL, MPI_SUM, 0,
MPI_COMM_WORLD);
MPI_Reduce(&total_vol, &total_vol, 1, MPI_ATHENA_REAL, MPI_SUM, 0,
MPI_COMM_WORLD);
MPI_Reduce(&max_err, &max_err, NSCALARS, MPI_ATHENA_REAL, MPI_MAX, 0,
MPI_COMM_WORLD);
}
#endif
// only the root process outputs the data
if (Globals::my_rank == 0) {
// normalize errors by total domain volume
for (int i=0; i<NSCALARS; ++i) l1_err[i] = l1_err[i]/total_vol;
// open output file and write out errors
std::stringstream msg;
std::string fname;
if (iprob == 1) {
fname.assign("mignone_radial-errors.dat");
} else {
fname.assign("mignone_meridional-errors.dat");
}
FILE *pfile;
// The file exists -- reopen the file in append mode
if ((pfile = std::fopen(fname.c_str(), "r")) != nullptr) {
if ((pfile = std::freopen(fname.c_str(), "a", pfile)) == nullptr) {
msg << "### FATAL ERROR in function Mesh::UserWorkAfterLoop"
<< std::endl << "Error output file could not be opened" <<std::endl;
ATHENA_ERROR(msg);
}
// The file does not exist -- open the file in write mode and add headers
} else {
if ((pfile = std::fopen(fname.c_str(), "w")) == nullptr) {
msg << "### FATAL ERROR in function Mesh::UserWorkAfterLoop"
<< std::endl << "Error output file could not be opened" <<std::endl;
ATHENA_ERROR(msg);
}
std::fprintf(pfile, "# Nx1 Nx2 Nx3 Ncycle ");
for (int n=0; n<NSCALARS; ++n)
std::fprintf(pfile, "s%d_L1 ", n);
for (int n=0; n<NSCALARS; ++n)
std::fprintf(pfile, "s%d_max ", n);
std::fprintf(pfile, "\n");
}
// write errors
std::fprintf(pfile, "%d %d", mesh_size.nx1, mesh_size.nx2);
std::fprintf(pfile, " %d %d", mesh_size.nx3, ncycle);
for (int n=0; n<NSCALARS; ++n)
std::fprintf(pfile, " %e", l1_err[n]);
for (int n=0; n<NSCALARS; ++n)
std::fprintf(pfile, " %e", max_err[n]);
std::fprintf(pfile, "\n");
std::fclose(pfile);
}
} // if NSCALARS > 0
return;
}
//========================================================================================
//! \fn void MeshBlock::ProblemGenerator(ParameterInput *pin)
//========================================================================================
void MeshBlock::ProblemGenerator(ParameterInput *pin) {
AthenaArray<Real> vol(ncells1);
// initialize conserved variables
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je; j++) {
pcoord->CellVolume(k, j, is, ie, vol);
for (int i=is; i<=ie; i++) {
// background fluid:
phydro->u(IDN,k,j,i) = d0;
phydro->u(IM3,k,j,i) = 0.0;
// assuming isothermal EOS:
// phydro->u(IEN,k,j,i) =
Real cell_ave;
//--- iprob=1
if (iprob == 1) {
// Note: GL quadrature is only ever used for the passive scalar profile (even
// though it would be straightforward to compute the analytic integral for the
// specific Gaussian profile) for generality with any initial condition
Real xl, xu;
xl = pcoord->x1f(i);
xu = pcoord->x1f(i+1);
phydro->u(IM2,k,j,i) = 0.0;
// The cell-averaged linear velocity profile is always computed from the
// analytic integral expression:
if (std::strcmp(COORDINATE_SYSTEM, "cartesian") == 0 || // dy*dz
std::strcmp(COORDINATE_SYSTEM, "cylindrical") == 0) { // dz*dphi
phydro->u(IM1,k,j,i) =
d0*alpha*ONE_3RD*(pcoord->x1f(i+1)*SQR(pcoord->x1f(i+1)) -
pcoord->x1f(i)*SQR(pcoord->x1f(i)));
phydro->u(IM1,k,j,i) *= pcoord->dx2f(j)*pcoord->dx3f(k)/vol(i);
} else { // if (std::strcmp(COORDINATE_SYSTEM, "spherical_polar") == 0)
// sin(theta)*dtheta*dphi
phydro->u(IM1,k,j,i) =
d0*alpha*0.25*(SQR(SQR(pcoord->x1f(i+1))) - SQR(SQR(pcoord->x1f(i))));
phydro->u(IM1,k,j,i) *= pcoord->dx3f(k)/vol(i);
phydro->u(IM1,k,j,i) *= std::cos(pcoord->x2f(j)) - std::cos(pcoord->x2f(j+1));
}
// vs. midpoint approximation for intiialization of linear velocity profile:
// phydro->u(IM1,k,j,i) = d0*alpha*pcoord->x1v(i);
if (use_gl_quadrature) {
// Use Gauss-Legendre quadrature rules to compute cell-averaged passive scalar
// initial condition based on the pointwise analytic formula
// GL implementation returns total integral, not average. Divide by delta_r
Real cell_quad = GaussLegendre::integrate(N_gl, IntegrandInitial, xl, xu);
cell_ave = cell_quad/vol(i);
// assume that the Gaussian profile is 1D in radial coordinate to pull
// out 2x integrals from the triple volume integral
if (std::strcmp(COORDINATE_SYSTEM, "cartesian") == 0 || // dy*dz
std::strcmp(COORDINATE_SYSTEM, "cylindrical") == 0) { // dz*dphi
cell_ave *= pcoord->dx2f(j);
cell_ave *= pcoord->dx3f(k);
} else { // if (std::strcmp(COORDINATE_SYSTEM, "spherical_polar") == 0)
// sin(theta)*dtheta*dphi
cell_ave *= std::cos(pcoord->x2f(j)) - std::cos(pcoord->x2f(j+1));
cell_ave *= pcoord->dx3f(k);
}
} else {
// Use standard midpoint approximation with cell centered coords:
cell_ave = InitialGaussianProfile(pcoord->x1v(i));
}
} else if (iprob == 2) {
Real xl, xu;
xl = pcoord->x2f(j);
xu = pcoord->x2f(j+1);
phydro->u(IM1,k,j,i) = 0.0;
// exact integral of cell-averaged linear velocity profile:
phydro->u(IM2,k,j,i) =
d0*alpha*(std::sin(xu) - xu*std::cos(xu)
- (std::sin(xl) - xl*std::cos(xl)));
phydro->u(IM2,k,j,i) *= pcoord->dx3f(k)/vol(i);
phydro->u(IM2,k,j,i) *= 0.25*(SQR(SQR(pcoord->x1f(i+1)))
- SQR(SQR(pcoord->x1f(i))));
// vs. midpoint approximation for intiialization of linear velocity profile:
// (note, Mignone assumes r=1 for the 1D variant of this problem; need to scale
// v_theta with radius in this 2D variant)
// phydro->u(IM2,k,j,i) = d0*alpha*pcoord->x2v(j)*pcoord->x1f(i);
if (use_gl_quadrature) {
Real cell_quad = GaussLegendre::integrate(N_gl, IntegrandInitial, xl, xu);
cell_ave = cell_quad*pcoord->dx3f(k)/vol(i);
cell_ave *= ONE_3RD*(SQR(pcoord->x1f(i+1))*pcoord->x1f(i+1)
- SQR(pcoord->x1f(i))*pcoord->x1f(i));
} else {
cell_ave = InitialCosineProfile(pcoord->x2v(j));
}
} // end if iprob == 2
// uniformly fill all scalars to have equal concentration
constexpr int scalar_norm = NSCALARS > 0 ? NSCALARS : 1.0;
if (NSCALARS > 0) {
for (int n=0; n<NSCALARS; ++n) {
pscalars->s(n,k,j,i) = 1.0/scalar_norm*cell_ave*d0;
}
}
}
}
}
return;
}
namespace {
Real InitialGaussianProfile(Real x1) {
return std::exp(-SQR(a_width)*SQR(x1 - b_center)); // Mignone eq 73
}
Real FinalGaussianProfile(Real x1) {
// hardcoding t=t_final to maintain compatiblity with GL quadrature routines
Real x_initial = x1*std::exp(-alpha*t_final);
Real q_initial = InitialGaussianProfile(x_initial);
Real amp = std::exp(-(m_coord + 1)*alpha*t_final);
return amp*q_initial; // Mignone eq 72
}
Real InitialCosineProfile(Real x2) {
Real shift_x2 = x2 - b_center;
if (std::abs(shift_x2) < PI/a_width) {
return SQR(0.5 + 0.5*std::cos(a_width*shift_x2)); // Mignone eq 77
} else {
return 0.0;
}
}
Real FinalCosineProfile(Real x2) {
Real x2_initial = x2*std::exp(-alpha*t_final);
Real q_initial = InitialCosineProfile(x2_initial);
Real amp = std::exp(-alpha*t_final)*std::sin(x2_initial)/sin(x2);
return amp*q_initial; // Mignone eq 76
}
Real InitialGaussianCylindricalIntegrand(Real x1) {
return x1*InitialGaussianProfile(x1);
}
Real FinalGaussianCylindricalIntegrand(Real x1) {
return x1*FinalGaussianProfile(x1);
}
Real InitialGaussianSphericalIntegrand(Real x1) {
return SQR(x1)*InitialGaussianProfile(x1);
}
Real FinalGaussianSphericalIntegrand(Real x1) {
return SQR(x1)*FinalGaussianProfile(x1);
}
Real InitialCosineSphericalIntegrand(Real x2) {
return std::sin(x2)*InitialCosineProfile(x2);
}
Real FinalCosineSphericalIntegrand(Real x2) {
return std::sin(x2)*FinalCosineProfile(x2);
}
} // namespace
| 40.995272 | 90 | 0.56427 | kahoooo |
c877fa444a3a164676cc295c9b060dd8da7b2770 | 6,040 | cpp | C++ | C45/contin.cpp | everyday-solution/ESolutions.C45 | 3285440e0b5812820c85f318c5d50585a7cee288 | [
"MIT"
] | null | null | null | C45/contin.cpp | everyday-solution/ESolutions.C45 | 3285440e0b5812820c85f318c5d50585a7cee288 | [
"MIT"
] | null | null | null | C45/contin.cpp | everyday-solution/ESolutions.C45 | 3285440e0b5812820c85f318c5d50585a7cee288 | [
"MIT"
] | null | null | null | /*************************************************************************/
/* */
/* Evaluation of a test on a continuous valued attribute */
/* ----------------------------------------------------- */
/* */
/*************************************************************************/
#ifndef __CONTIN_CPP__
#define __CONTIN_CPP__
#include "buildex.i"
#include "header.h"
#include "info.h"
#include "contin.h"
#include "build.h"
#include "sort.h"
#include "trees.h"
/*************************************************************************/
/* */
/* Continuous attributes are treated as if they have possible values */
/* 0 (unknown), 1 (less than cut), 2(greater than cut) */
/* This routine finds the best cut for items Fp through Lp and sets */
/* Info[], Gain[] and Bar[] */
/* */
/*************************************************************************/
void EvalContinuousAtt(Attribute Att, ItemNo Fp, ItemNo Lp)
{
ItemNo i = 0, BestI = 0, Xp = 0, Tries = 0;
ItemCount Items = 0, KnownItems = 0, LowItems = 0, MinSplit = 0;
ClassNo c = 0;
float AvGain = 0.0, Val = 0.0, BestVal = 0.0, BaseInfo = 0.0, ThreshCost = 0.0;
Verbosity(2)
{
StringCbPrintf(szBuffer, cbDest, "\tAtt %s", AttName[Att]);
SendOutput (szBuffer);
}
Verbosity(3)
{
StringCbPrintf(szBuffer, cbDest, "\n");
SendOutput (szBuffer);
}
ResetFreq(2);
/* Omit and count unknown values */
Items = CountItems(Fp, Lp);
Xp = Fp;
ForEach(i, Fp, Lp)
{
if ( CVal(Item[i],Att) == UNKNOWN )
{
Freq[ 0 ][ Class(Item[i]) ] += Weight[i];
Swap(Xp, i);
Xp++;
}
}
ValFreq[0] = 0;
ForEach(c, 0, MaxClass)
{
ValFreq[0] += Freq[0][c];
}
KnownItems = Items - ValFreq[0];
UnknownRate[Att] = 1.0 - KnownItems / Items;
/* Special case when very few known values */
if ( KnownItems < 2 * MINOBJS )
{
Verbosity(2)
{
StringCbPrintf(szBuffer, cbDest, "\tinsufficient cases with known values\n");
SendOutput (szBuffer);
}
Gain[Att] = -Epsilon;
Info[Att] = 0.0;
return;
}
Quicksort(Xp, Lp, Att, Swap);
/* Count base values and determine base information */
ForEach(i, Xp, Lp)
{
Freq[ 2 ][ Class(Item[i]) ] += Weight[i];
SplitGain[i] = -Epsilon;
SplitInfo[i] = 0;
}
BaseInfo = TotalInfo(Freq[2], 0, MaxClass) / KnownItems;
/* Try possible cuts between items i and i+1, and determine the
information and gain of the split in each case. We have to be wary
of splitting a small number of items off one end, as we can always
split off a single item, but this has little predictive power. */
MinSplit = 0.10 * KnownItems / (MaxClass + 1);
if ( MinSplit <= MINOBJS ) MinSplit = MINOBJS;
else
if ( MinSplit > 25 ) MinSplit = 25;
LowItems = 0;
ForEach(i, Xp, Lp - 1)
{
c = Class(Item[i]);
LowItems += Weight[i];
Freq[1][c] += Weight[i];
Freq[2][c] -= Weight[i];
if ( LowItems < MinSplit ) continue;
else
if ( LowItems > KnownItems - MinSplit ) break;
if ( CVal(Item[i],Att) < CVal(Item[i+1],Att) - 1E-5 )
{
ValFreq[1] = LowItems;
ValFreq[2] = KnownItems - LowItems;
SplitGain[i] = ComputeGain(BaseInfo, UnknownRate[Att], 2, KnownItems);
SplitInfo[i] = TotalInfo(ValFreq, 0, 2) / Items;
AvGain += SplitGain[i];
Tries++;
Verbosity(3)
{ StringCbPrintf(szBuffer, cbDest, "\t\tCut at %.3f (gain %.3f, val %.3f):",
( CVal(Item[i],Att) + CVal(Item[i+1],Att) ) / 2,
SplitGain[i],
Worth(SplitInfo[i], SplitGain[i], Epsilon));
PrintDistribution(Att, 2, true);
SendOutput (szBuffer);
}
}
}
/* Find the best attribute according to the given criterion */
ThreshCost = Log(Tries) / Items;
BestVal = 0;
BestI = None;
ForEach(i, Xp, Lp - 1)
{
if ( (Val = SplitGain[i] - ThreshCost) > BestVal )
{
BestI = i;
BestVal = Val;
}
}
/* If a test on the attribute is able to make a gain,
set the best break point, gain and information */
if ( BestI == None )
{
Gain[Att] = -Epsilon;
Info[Att] = 0.0;
Verbosity(2)
{
StringCbPrintf(szBuffer, cbDest, "\tno gain\n");
SendOutput (szBuffer);
}
}
else
{
Bar[Att] = (CVal(Item[BestI],Att) + CVal(Item[BestI+1],Att)) / 2;
Gain[Att] = BestVal;
Info[Att] = SplitInfo[BestI];
Verbosity(2)
{
StringCbPrintf(szBuffer, cbDest, "\tcut=%.3f, inf %.3f, gain %.3f\n",
Bar[Att], Info[Att], Gain[Att]);
SendOutput (szBuffer);
}
}
}
/*************************************************************************/
/* */
/* Change a leaf into a test on a continuous attribute */
/* */
/*************************************************************************/
void ContinTest(Tree Node, Attribute Att)
{
float Thresh = 0.0;
Sprout(Node, 2);
Thresh = GreatestValueBelow(Att, Bar[Att]);
Node->NodeType = ThreshContin;
Node->Tested = Att;
Node->Cut =
Node->Lower =
Node->Upper = Thresh;
Node->Errors = 0;
}
/*************************************************************************/
/* */
/* Return the greatest value of attribute Att below threshold t */
/* */
/*************************************************************************/
float GreatestValueBelow(Attribute Att, float t)
{
ItemNo i = 0.0;
float v = 0.0, Best = 0.0;
Boolean NotYet = true;
ForEach(i, 0, MaxItem)
{
v = CVal(Item[i], Att);
if ( v != UNKNOWN && v <= t && ( NotYet || v > Best ) )
{
Best = v;
NotYet = false;
}
}
return Best;
}
#endif //__CONTIN_CPP__ | 25.166667 | 85 | 0.480629 | everyday-solution |
c87ab1bf12e789acfe15bfc687f2743a06515c8e | 12,253 | cpp | C++ | dpnp/backend/kernels/dpnp_krnl_manipulation.cpp | antonwolfy/dpnp | 7595c82a41bf5ab34cdefb3b5a9631f2365ac69a | [
"BSD-2-Clause"
] | null | null | null | dpnp/backend/kernels/dpnp_krnl_manipulation.cpp | antonwolfy/dpnp | 7595c82a41bf5ab34cdefb3b5a9631f2365ac69a | [
"BSD-2-Clause"
] | null | null | null | dpnp/backend/kernels/dpnp_krnl_manipulation.cpp | antonwolfy/dpnp | 7595c82a41bf5ab34cdefb3b5a9631f2365ac69a | [
"BSD-2-Clause"
] | null | null | null | //*****************************************************************************
// Copyright (c) 2016-2020, Intel Corporation
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//*****************************************************************************
#include <cmath>
#include <iostream>
#include <vector>
#include <dpnp_iface.hpp>
#include "dpnp_fptr.hpp"
#include "dpnp_utils.hpp"
#include "dpnpc_memory_adapter.hpp"
#include "queue_sycl.hpp"
template <typename _DataType>
class dpnp_repeat_c_kernel;
template <typename _DataType>
DPCTLSyclEventRef dpnp_repeat_c(DPCTLSyclQueueRef q_ref,
const void* array1_in,
void* result1,
const size_t repeats,
const size_t size,
const DPCTLEventVectorRef dep_event_vec_ref)
{
// avoid warning unused variable
(void)dep_event_vec_ref;
DPCTLSyclEventRef event_ref = nullptr;
if (!array1_in || !result1)
{
return event_ref;
}
if (!size || !repeats)
{
return event_ref;
}
sycl::queue q = *(reinterpret_cast<sycl::queue*>(q_ref));
sycl::event event;
DPNPC_ptr_adapter<_DataType> input1_ptr(q_ref,array1_in, size);
const _DataType* array_in = input1_ptr.get_ptr();
_DataType* result = reinterpret_cast<_DataType*>(result1);
sycl::range<2> gws(size, repeats);
auto kernel_parallel_for_func = [=](sycl::id<2> global_id) {
size_t idx1 = global_id[0];
size_t idx2 = global_id[1];
result[(idx1 * repeats) + idx2] = array_in[idx1];
};
auto kernel_func = [&](sycl::handler& cgh) {
cgh.parallel_for<class dpnp_repeat_c_kernel<_DataType>>(gws, kernel_parallel_for_func);
};
event = q.submit(kernel_func);
event.wait();
return event_ref;
}
template <typename _DataType>
void dpnp_repeat_c(const void* array1_in, void* result1, const size_t repeats, const size_t size)
{
DPCTLSyclQueueRef q_ref = reinterpret_cast<DPCTLSyclQueueRef>(&DPNP_QUEUE);
DPCTLEventVectorRef dep_event_vec_ref = nullptr;
DPCTLSyclEventRef event_ref = dpnp_repeat_c<_DataType>(q_ref,
array1_in,
result1,
repeats,
size,
dep_event_vec_ref);
DPCTLEvent_WaitAndThrow(event_ref);
}
template <typename _DataType>
void (*dpnp_repeat_default_c)(const void*, void*, const size_t, const size_t) = dpnp_repeat_c<_DataType>;
template <typename _DataType>
DPCTLSyclEventRef (*dpnp_repeat_ext_c)(DPCTLSyclQueueRef,
const void*,
void*,
const size_t,
const size_t,
const DPCTLEventVectorRef) = dpnp_repeat_c<_DataType>;
template <typename _KernelNameSpecialization>
class dpnp_elemwise_transpose_c_kernel;
template <typename _DataType>
DPCTLSyclEventRef dpnp_elemwise_transpose_c(DPCTLSyclQueueRef q_ref,
void* array1_in,
const shape_elem_type* input_shape,
const shape_elem_type* result_shape,
const shape_elem_type* permute_axes,
size_t ndim,
void* result1,
size_t size,
const DPCTLEventVectorRef dep_event_vec_ref)
{
// avoid warning unused variable
(void)dep_event_vec_ref;
DPCTLSyclEventRef event_ref = nullptr;
if (!size)
{
return event_ref;
}
sycl::queue q = *(reinterpret_cast<sycl::queue*>(q_ref));
sycl::event event;
DPNPC_ptr_adapter<_DataType> input1_ptr(q_ref,array1_in, size);
_DataType* array1 = input1_ptr.get_ptr();
_DataType* result = reinterpret_cast<_DataType*>(result1);
shape_elem_type* input_offset_shape =
reinterpret_cast<shape_elem_type*>(sycl::malloc_shared(ndim * sizeof(shape_elem_type), q));
get_shape_offsets_inkernel(input_shape, ndim, input_offset_shape);
shape_elem_type* temp_result_offset_shape =
reinterpret_cast<shape_elem_type*>(sycl::malloc_shared(ndim * sizeof(shape_elem_type), q));
get_shape_offsets_inkernel(result_shape, ndim, temp_result_offset_shape);
shape_elem_type* result_offset_shape =
reinterpret_cast<shape_elem_type*>(sycl::malloc_shared(ndim * sizeof(shape_elem_type), q));
for (size_t axis = 0; axis < ndim; ++axis)
{
result_offset_shape[permute_axes[axis]] = temp_result_offset_shape[axis];
}
sycl::range<1> gws(size);
auto kernel_parallel_for_func = [=](sycl::id<1> global_id) {
const size_t idx = global_id[0];
size_t output_index = 0;
size_t reminder = idx;
for (size_t axis = 0; axis < ndim; ++axis)
{
/* reconstruct [x][y][z] from given linear idx */
size_t xyz_id = reminder / input_offset_shape[axis];
reminder = reminder % input_offset_shape[axis];
/* calculate destination index based on reconstructed [x][y][z] */
output_index += (xyz_id * result_offset_shape[axis]);
}
result[output_index] = array1[idx];
};
auto kernel_func = [&](sycl::handler& cgh) {
cgh.parallel_for<class dpnp_elemwise_transpose_c_kernel<_DataType>>(gws, kernel_parallel_for_func);
};
event = q.submit(kernel_func);
event.wait();
sycl::free(input_offset_shape, q);
sycl::free(temp_result_offset_shape, q);
sycl::free(result_offset_shape, q);
return event_ref;
}
template <typename _DataType>
void dpnp_elemwise_transpose_c(void* array1_in,
const shape_elem_type* input_shape,
const shape_elem_type* result_shape,
const shape_elem_type* permute_axes,
size_t ndim,
void* result1,
size_t size)
{
DPCTLSyclQueueRef q_ref = reinterpret_cast<DPCTLSyclQueueRef>(&DPNP_QUEUE);
DPCTLEventVectorRef dep_event_vec_ref = nullptr;
DPCTLSyclEventRef event_ref = dpnp_elemwise_transpose_c<_DataType>(q_ref,
array1_in,
input_shape,
result_shape,
permute_axes,
ndim,
result1,
size,
dep_event_vec_ref);
DPCTLEvent_WaitAndThrow(event_ref);
}
template <typename _DataType>
void (*dpnp_elemwise_transpose_default_c)(void*,
const shape_elem_type*,
const shape_elem_type*,
const shape_elem_type*,
size_t,
void*,
size_t) = dpnp_elemwise_transpose_c<_DataType>;
template <typename _DataType>
DPCTLSyclEventRef (*dpnp_elemwise_transpose_ext_c)(DPCTLSyclQueueRef,
void*,
const shape_elem_type*,
const shape_elem_type*,
const shape_elem_type*,
size_t,
void*,
size_t,
const DPCTLEventVectorRef) = dpnp_elemwise_transpose_c<_DataType>;
void func_map_init_manipulation(func_map_t& fmap)
{
fmap[DPNPFuncName::DPNP_FN_REPEAT][eft_INT][eft_INT] = {eft_INT, (void*)dpnp_repeat_default_c<int32_t>};
fmap[DPNPFuncName::DPNP_FN_REPEAT][eft_LNG][eft_LNG] = {eft_LNG, (void*)dpnp_repeat_default_c<int64_t>};
fmap[DPNPFuncName::DPNP_FN_REPEAT][eft_FLT][eft_FLT] = {eft_FLT, (void*)dpnp_repeat_default_c<float>};
fmap[DPNPFuncName::DPNP_FN_REPEAT][eft_DBL][eft_DBL] = {eft_DBL, (void*)dpnp_repeat_default_c<double>};
fmap[DPNPFuncName::DPNP_FN_REPEAT_EXT][eft_INT][eft_INT] = {eft_INT, (void*)dpnp_repeat_ext_c<int32_t>};
fmap[DPNPFuncName::DPNP_FN_REPEAT_EXT][eft_LNG][eft_LNG] = {eft_LNG, (void*)dpnp_repeat_ext_c<int64_t>};
fmap[DPNPFuncName::DPNP_FN_REPEAT_EXT][eft_FLT][eft_FLT] = {eft_FLT, (void*)dpnp_repeat_ext_c<float>};
fmap[DPNPFuncName::DPNP_FN_REPEAT_EXT][eft_DBL][eft_DBL] = {eft_DBL, (void*)dpnp_repeat_ext_c<double>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE][eft_INT][eft_INT] = {eft_INT,
(void*)dpnp_elemwise_transpose_default_c<int32_t>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE][eft_LNG][eft_LNG] = {eft_LNG,
(void*)dpnp_elemwise_transpose_default_c<int64_t>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE][eft_FLT][eft_FLT] = {eft_FLT,
(void*)dpnp_elemwise_transpose_default_c<float>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE][eft_DBL][eft_DBL] = {eft_DBL,
(void*)dpnp_elemwise_transpose_default_c<double>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE_EXT][eft_INT][eft_INT] = {eft_INT,
(void*)dpnp_elemwise_transpose_ext_c<int32_t>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE_EXT][eft_LNG][eft_LNG] = {eft_LNG,
(void*)dpnp_elemwise_transpose_ext_c<int64_t>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE_EXT][eft_FLT][eft_FLT] = {eft_FLT,
(void*)dpnp_elemwise_transpose_ext_c<float>};
fmap[DPNPFuncName::DPNP_FN_TRANSPOSE_EXT][eft_DBL][eft_DBL] = {eft_DBL,
(void*)dpnp_elemwise_transpose_ext_c<double>};
return;
}
| 45.720149 | 117 | 0.558149 | antonwolfy |
c87b9e09c7f32121e12d52365d377923ae6efe53 | 5,238 | cpp | C++ | tests/Unit/Time/StepChoosers/Test_PreventRapidIncrease.cpp | Ambrou/spectre | a819ebbcca607d8af9683db3683bea14bf4ac23c | [
"MIT"
] | null | null | null | tests/Unit/Time/StepChoosers/Test_PreventRapidIncrease.cpp | Ambrou/spectre | a819ebbcca607d8af9683db3683bea14bf4ac23c | [
"MIT"
] | null | null | null | tests/Unit/Time/StepChoosers/Test_PreventRapidIncrease.cpp | Ambrou/spectre | a819ebbcca607d8af9683db3683bea14bf4ac23c | [
"MIT"
] | 1 | 2019-01-03T21:47:04.000Z | 2019-01-03T21:47:04.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <limits>
#include <memory>
#include <utility>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataBox/Tag.hpp"
#include "Framework/TestCreation.hpp"
#include "Framework/TestHelpers.hpp"
#include "Parallel/GlobalCache.hpp"
#include "Parallel/RegisterDerivedClassesWithCharm.hpp"
#include "Time/History.hpp"
#include "Time/Slab.hpp"
#include "Time/StepChoosers/PreventRapidIncrease.hpp"
#include "Time/StepChoosers/StepChooser.hpp"
#include "Time/Tags.hpp"
#include "Time/Time.hpp"
#include "Time/TimeStepId.hpp"
#include "Utilities/StdHelpers.hpp"
#include "Utilities/TMPL.hpp"
// IWYU pragma: no_include <pup.h>
// IWYU pragma: no_include "Utilities/Rational.hpp"
namespace {
using Frac = Time::rational_t;
using StepChooserType =
StepChooser<tmpl::list<StepChoosers::Registrars::PreventRapidIncrease>>;
using PreventRapidIncrease = StepChoosers::PreventRapidIncrease<>;
struct Metavariables {
using component_list = tmpl::list<>;
};
void check_case(const Frac& expected_frac,
const std::vector<Frac>& times) noexcept {
CAPTURE(times);
CAPTURE(expected_frac);
const PreventRapidIncrease relax{};
const std::unique_ptr<StepChooserType> relax_base =
std::make_unique<PreventRapidIncrease>(relax);
const Parallel::GlobalCache<Metavariables> cache{};
const Slab slab(0.25, 1.5);
const double expected = expected_frac == -1
? std::numeric_limits<double>::infinity()
: (expected_frac * slab.duration()).value();
for (const auto& direction : {1, -1}) {
CAPTURE(direction);
const auto make_time_id =
[&direction, &slab, ×](const size_t i) noexcept {
Frac frac = -direction * times[i];
int64_t slab_number = 0;
Slab time_slab = slab;
while (frac > 1) {
time_slab = time_slab.advance();
frac -= 1;
slab_number += direction;
}
while (frac < 0) {
time_slab = time_slab.retreat();
frac += 1;
slab_number -= direction;
}
return TimeStepId(direction > 0, slab_number, Time(time_slab, frac));
};
// Silly type. The step chooser should not care.
struct Tag : db::SimpleTag {
using type = std::nullptr_t;
};
using history_tag = Tags::HistoryEvolvedVariables<Tag>;
typename history_tag::type lts_history{};
typename history_tag::type gts_history{};
const auto make_gts_time_id =
[&direction, &make_time_id](const size_t i) noexcept {
const double time = make_time_id(i).substep_time().value();
const double next_time =
i > 0 ? make_time_id(i - 1).substep_time().value() : time + direction;
const Slab gts_slab(std::min(time, next_time), std::max(time, next_time));
return TimeStepId(direction > 0, -static_cast<int64_t>(i),
direction > 0 ? gts_slab.start() : gts_slab.end());
};
for (size_t i = 1; i < times.size(); ++i) {
lts_history.insert_initial(make_time_id(i), nullptr, nullptr);
gts_history.insert_initial(make_gts_time_id(i), nullptr, nullptr);
}
const auto check = [&cache, &expected, &relax, &relax_base](
const auto& box, const Time& current_time) noexcept {
const auto& history = db::get<history_tag>(box);
const double current_step =
history.size() > 0 ? abs(current_time - history.back()).value()
: std::numeric_limits<double>::infinity();
CHECK(relax(history, current_step, cache) == expected);
CHECK(relax_base->desired_step(current_step, box, cache) == expected);
CHECK(serialize_and_deserialize(relax)(history, current_step, cache) ==
expected);
CHECK(serialize_and_deserialize(relax_base)
->desired_step(current_step, box, cache) == expected);
};
{
CAPTURE(lts_history);
check(db::create<db::AddSimpleTags<history_tag>>(std::move(lts_history)),
make_time_id(0).substep_time());
}
{
CAPTURE(gts_history);
check(db::create<db::AddSimpleTags<history_tag>>(std::move(gts_history)),
make_gts_time_id(0).substep_time());
}
}
}
} // namespace
SPECTRE_TEST_CASE("Unit.Time.StepChoosers.PreventRapidIncrease",
"[Unit][Time]") {
Parallel::register_derived_classes_with_charm<StepChooserType>();
// -1 indicates no expected restriction
check_case(-1, {0});
check_case(-1, {{2, 5}});
check_case(-1, {0, {2, 5}});
check_case(-1, {{1, 5}, {2, 5}, {3, 5}});
check_case(-1, {{4, 5}, {5, 5}, {6, 5}});
check_case({1, 5}, {{4, 5}, {5, 5}, {7, 5}});
check_case({2, 5}, {{3, 5}, {5, 5}, {6, 5}});
check_case(-1, {{1, 5}, {2, 5}, {3, 5}, {4, 5}});
check_case({2, 5}, {{0, 5}, {2, 5}, {3, 5}, {4, 5}});
check_case({1, 20}, {{1, 5}, {1, 4}, {3, 5}, {4, 5}});
// Cause roundoff errors
check_case(-1, {{1, 3}, {2, 3}, {3, 3}});
TestHelpers::test_factory_creation<StepChooserType>("PreventRapidIncrease");
}
| 33.793548 | 80 | 0.641084 | Ambrou |
c8810fb05be038ac190400a166720131d636b6f9 | 4,560 | cpp | C++ | src/NovelRT.Interop/DotNet/NrtRuntimeService.cpp | chococookies131/NovelRT | 1e9b72abf53391a9d86f7fd3e171599e820de2a2 | [
"MIT"
] | null | null | null | src/NovelRT.Interop/DotNet/NrtRuntimeService.cpp | chococookies131/NovelRT | 1e9b72abf53391a9d86f7fd3e171599e820de2a2 | [
"MIT"
] | null | null | null | src/NovelRT.Interop/DotNet/NrtRuntimeService.cpp | chococookies131/NovelRT | 1e9b72abf53391a9d86f7fd3e171599e820de2a2 | [
"MIT"
] | null | null | null | // Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root for more information.
#include <NovelRT.Interop/NrtInteropErrorHandlingInternal.h>
#include <NovelRT.Interop/NrtInteropUtils.h>
#include <NovelRT.Interop/DotNet/NrtRuntimeService.h>
#include <NovelRT.h>
#include <list>
using namespace NovelRT;
std::list<std::shared_ptr<Ink::InkService>> _inkServiceCollection;
#ifdef __cplusplus
extern "C" {
#endif
NrtRuntimeService Nrt_RuntimeService_create() {
NovelRT::DotNet::RuntimeService* service = new NovelRT::DotNet::RuntimeService();
return reinterpret_cast<NrtRuntimeService&>(service);
}
NrtResult Nrt_RuntimeService_destroy(NrtRuntimeService service) {
if (service == nullptr) {
Nrt_setErrMsgIsNullptrInternal();
return NRT_FAILURE_NULLPTR_PROVIDED;
}
NovelRT::DotNet::RuntimeService* cService = reinterpret_cast<NovelRT::DotNet::RuntimeService*>(service);
cService->~RuntimeService();
return NRT_SUCCESS;
}
NrtResult Nrt_RuntimeService_initialise(NrtRuntimeService service) {
if (service == nullptr) {
Nrt_setErrMsgIsNullptrInternal();
return NRT_FAILURE_NULLPTR_PROVIDED;
}
NovelRT::DotNet::RuntimeService* cService = reinterpret_cast<NovelRT::DotNet::RuntimeService*>(service);
try
{
cService->initialise();
}
catch (const Exceptions::InitialisationFailureException)
{
Nrt_setErrMsgIsInitialisationFailureInternal();
return NRT_FAILURE_INITIALISATION_FAILURE;
}
catch (const Exceptions::FunctionNotFoundException)
{
Nrt_setErrMsgIsFunctionNotFoundInternal();
return NRT_FAILURE_FUNCTION_NOT_FOUND;
}
return NRT_SUCCESS;
}
NrtResult Nrt_RuntimeService_tearDown(NrtRuntimeService service) {
if (service == nullptr) {
Nrt_setErrMsgIsNullptrInternal();
return NRT_FAILURE_NULLPTR_PROVIDED;
}
NovelRT::DotNet::RuntimeService* cService = reinterpret_cast<NovelRT::DotNet::RuntimeService*>(service);
cService->tearDown();
return NRT_SUCCESS;
}
NrtResult Nrt_RuntimeService_freeObject(NrtRuntimeService service, intptr_t obj) {
if (service == nullptr) {
Nrt_setErrMsgIsNullptrInternal();
return NRT_FAILURE_NULLPTR_PROVIDED;
}
NovelRT::DotNet::RuntimeService* cService = reinterpret_cast<NovelRT::DotNet::RuntimeService*>(service);
try{
cService->freeObject(obj);
} catch (const Exceptions::InitialisationFailureException) {
Nrt_setErrMsgIsInitialisationFailureInternal();
return NRT_FAILURE_INITIALISATION_FAILURE;
} catch (const Exceptions::FunctionNotFoundException) {
Nrt_setErrMsgIsFunctionNotFoundInternal();
return NRT_FAILURE_FUNCTION_NOT_FOUND;
}
return NRT_SUCCESS;
}
NrtResult Nrt_RuntimeService_freeString(NrtRuntimeService service, const char* str) {
if (service == nullptr || str == nullptr) {
Nrt_setErrMsgIsNullptrInternal();
return NRT_FAILURE_NULLPTR_PROVIDED;
}
NovelRT::DotNet::RuntimeService* cService = reinterpret_cast<NovelRT::DotNet::RuntimeService*>(service);
try
{
cService->freeString(str);
}
catch (const Exceptions::InitialisationFailureException)
{
Nrt_setErrMsgIsInitialisationFailureInternal();
return NRT_FAILURE_INITIALISATION_FAILURE;
}
catch (const Exceptions::FunctionNotFoundException)
{
Nrt_setErrMsgIsFunctionNotFoundInternal();
return NRT_FAILURE_FUNCTION_NOT_FOUND;
}
return NRT_SUCCESS;
}
NrtResult Nrt_RuntimeService_getInkService(NrtRuntimeService service, NrtInkService* outputInkService) {
if (service == nullptr || outputInkService == nullptr) {
Nrt_setErrMsgIsNullptrInternal();
return NRT_FAILURE_NULLPTR_PROVIDED;
}
NovelRT::DotNet::RuntimeService* cService = reinterpret_cast<NovelRT::DotNet::RuntimeService*>(service);
std::shared_ptr<Ink::InkService> inkServicePtr;
try{
inkServicePtr = cService->getInkService();
} catch (const Exceptions::InitialisationFailureException) {
Nrt_setErrMsgIsInitialisationFailureInternal();
return NRT_FAILURE_INITIALISATION_FAILURE;
} catch (const Exceptions::FunctionNotFoundException) {
Nrt_setErrMsgIsFunctionNotFoundInternal();
return NRT_FAILURE_FUNCTION_NOT_FOUND;
}
_inkServiceCollection.push_back(inkServicePtr);
*outputInkService = reinterpret_cast<NrtInkService>(inkServicePtr.get());
return NRT_SUCCESS;
}
#ifdef __cplusplus
}
#endif
| 31.888112 | 141 | 0.745175 | chococookies131 |
c8815f45a9da1dc0e19958879c39e4ad05810e1c | 56,801 | cpp | C++ | Source/VoxelGraphEditor/Private/VoxelGraphEditorToolkit.cpp | SolarStormInteractive/VoxelPlugin | b0b8a1838262227fa586fbcb1b46a6184cdf1e8c | [
"MIT"
] | null | null | null | Source/VoxelGraphEditor/Private/VoxelGraphEditorToolkit.cpp | SolarStormInteractive/VoxelPlugin | b0b8a1838262227fa586fbcb1b46a6184cdf1e8c | [
"MIT"
] | null | null | null | Source/VoxelGraphEditor/Private/VoxelGraphEditorToolkit.cpp | SolarStormInteractive/VoxelPlugin | b0b8a1838262227fa586fbcb1b46a6184cdf1e8c | [
"MIT"
] | null | null | null | // Copyright 2020 Phyronnaz
#include "VoxelGraphEditorToolkit.h"
#include "VoxelGraphEditorUtilities.h"
#include "VoxelGraphGenerator.h"
#include "VoxelGraphShortcuts.h"
#include "VoxelGraphPreviewSettings.h"
#include "VoxelGraphImportExposedVariablesValues.h"
#include "VoxelGraphSchema.h"
#include "VoxelNodes/VoxelGraphMacro.h"
#include "VoxelNodes/VoxelLocalVariables.h"
#include "VoxelGraphEditorCommands.h"
#include "VoxelGraphNodes/VoxelGraphNode_Root.h"
#include "VoxelGraphNodes/VoxelGraphNode.h"
#include "VoxelGraphNodes/SVoxelGraphNode.h"
#include "VoxelGraphNodes/VoxelGraphNode_Knot.h"
#include "VoxelMessages.h"
#include "VoxelDebugGraphUtils.h"
#include "VoxelEditorModule.h"
#include "SVoxelPalette.h"
#include "Preview/SVoxelGraphPreview.h"
#include "Preview/SVoxelGraphPreviewViewport.h"
#include "Preview/VoxelGraphPreview.h"
#include "IDetailsView.h"
#include "PropertyEditorModule.h"
#include "Modules/ModuleManager.h"
#include "ScopedTransaction.h"
#include "Misc/MessageDialog.h"
#include "HAL/PlatformApplicationMisc.h"
#include "Editor.h"
#include "EditorStyleSet.h"
#include "GraphEditorActions.h"
#include "GraphEditor.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "Framework/Commands/GenericCommands.h"
#include "Widgets/Docking/SDockTab.h"
#include "Widgets/Layout/SScaleBox.h"
#include "EdGraph/EdGraph.h"
#include "EdGraphUtilities.h"
#include "AdvancedPreviewScene.h"
#include "MessageLogModule.h"
#include "IMessageLogListing.h"
#include "Logging/TokenizedMessage.h"
const FName FVoxelGraphEditorToolkit::GraphCanvasTabId(TEXT("VoxelGraphEditor_GraphCanvas"));
const FName FVoxelGraphEditorToolkit::DebugGraphCanvasTabId(TEXT("VoxelGraphEditor_DebugGraphCanvas"));
const FName FVoxelGraphEditorToolkit::PropertiesTabId(TEXT("VoxelGraphEditor_Properties"));
const FName FVoxelGraphEditorToolkit::ShortcutsTabId(TEXT("VoxelGraphEditor_Shortcuts"));
const FName FVoxelGraphEditorToolkit::PreviewSettingsTabId(TEXT("VoxelGraphEditor_PreviewSettings"));
const FName FVoxelGraphEditorToolkit::PaletteTabId(TEXT("VoxelGraphEditor_Palette"));
const FName FVoxelGraphEditorToolkit::PreviewTabId(TEXT("VoxelGraphEditor_Preview"));
const FName FVoxelGraphEditorToolkit::PreviewViewportTabId(TEXT("VoxelGraphEditor_PreviewViewport"));
const FName FVoxelGraphEditorToolkit::MessagesTabId(TEXT("VoxelGraphEditor_Messages"));
FVoxelGraphEditorToolkit::FVoxelGraphEditorToolkit()
{
}
FVoxelGraphEditorToolkit::~FVoxelGraphEditorToolkit()
{
GEditor->UnregisterForUndo(this);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::RegisterTabSpawners(const TSharedRef<class FTabManager>& InTabManager)
{
WorkspaceMenuCategory = InTabManager->AddLocalWorkspaceMenuCategory(VOXEL_LOCTEXT("Voxel Editor"));
auto WorkspaceMenuCategoryRef = WorkspaceMenuCategory.ToSharedRef();
FAssetEditorToolkit::RegisterTabSpawners(InTabManager);
InTabManager->RegisterTabSpawner(GraphCanvasTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_GraphCanvas))
.SetDisplayName(VOXEL_LOCTEXT("Main Graph"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "GraphEditor.EventGraph_16x"));
InTabManager->RegisterTabSpawner(DebugGraphCanvasTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_DebugGraphCanvas))
.SetDisplayName(VOXEL_LOCTEXT("Debug Graph"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "GraphEditor.EventGraph_16x"));
InTabManager->RegisterTabSpawner(PropertiesTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_Properties))
.SetDisplayName(VOXEL_LOCTEXT("Details"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.Tabs.Details"));
InTabManager->RegisterTabSpawner(ShortcutsTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_Shortcuts))
.SetDisplayName(VOXEL_LOCTEXT("Shortcuts"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.Tabs.Details"));
InTabManager->RegisterTabSpawner(PreviewSettingsTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_PreviewSettings))
.SetDisplayName(VOXEL_LOCTEXT("Preview Settings"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.Tabs.Details"));
InTabManager->RegisterTabSpawner(PaletteTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_Palette))
.SetDisplayName(VOXEL_LOCTEXT("Palette"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "Kismet.Tabs.Palette"));
InTabManager->RegisterTabSpawner(PreviewTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_Preview))
.SetDisplayName(VOXEL_LOCTEXT("Preview"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.Tabs.Viewports"));
InTabManager->RegisterTabSpawner(PreviewViewportTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_PreviewViewport))
.SetDisplayName(VOXEL_LOCTEXT("3D Preview"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "LevelEditor.Tabs.Viewports"));
InTabManager->RegisterTabSpawner(MessagesTabId, FOnSpawnTab::CreateSP(this, &FVoxelGraphEditorToolkit::SpawnTab_Messages))
.SetDisplayName(VOXEL_LOCTEXT("Messages"))
.SetGroup(WorkspaceMenuCategoryRef)
.SetIcon(FSlateIcon(FEditorStyle::GetStyleSetName(), "MessageLog.TabIcon"));
}
void FVoxelGraphEditorToolkit::UnregisterTabSpawners(const TSharedRef<class FTabManager>& InTabManager)
{
FAssetEditorToolkit::UnregisterTabSpawners(InTabManager);
InTabManager->UnregisterTabSpawner(GraphCanvasTabId);
InTabManager->UnregisterTabSpawner(DebugGraphCanvasTabId);
InTabManager->UnregisterTabSpawner(PropertiesTabId);
InTabManager->UnregisterTabSpawner(ShortcutsTabId);
InTabManager->UnregisterTabSpawner(PreviewSettingsTabId);
InTabManager->UnregisterTabSpawner(PaletteTabId);
InTabManager->UnregisterTabSpawner(PreviewTabId);
InTabManager->UnregisterTabSpawner(PreviewViewportTabId);
InTabManager->UnregisterTabSpawner(MessagesTabId);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::InitVoxelEditor(const EToolkitMode::Type Mode, const TSharedPtr< class IToolkitHost >& InitToolkitHost, UObject* ObjectToEdit)
{
FVoxelMessages::Info("You can view and edit Voxel Graphs, but running them requires Voxel Plugin Pro");
WorldGenerator = CastChecked<UVoxelGraphGenerator>(ObjectToEdit);
if (!ensureAlways(WorldGenerator->VoxelGraph && WorldGenerator->VoxelDebugGraph))
{
FAssetEditorToolkit::InitAssetEditor(
Mode,
InitToolkitHost,
TEXT("VoxelGraphEditorApp"),
FTabManager::NewLayout("Standalone_VoxelGraphEditor_Crash")->AddArea(FTabManager::NewPrimaryArea()),
false,
false,
ObjectToEdit,
false);
return;
}
// Support undo/redo
WorldGenerator->SetFlags(RF_Transactional);
GEditor->RegisterForUndo(this);
FGraphEditorCommands::Register();
FVoxelGraphEditorCommands::Register();
BindGraphCommands();
CreateInternalWidgets();
const TSharedRef<FTabManager::FLayout> StandaloneDefaultLayout = FTabManager::NewLayout("Standalone_VoxelGraphEditor_Layout_v8")
->AddArea
(
FTabManager::NewPrimaryArea() ->SetOrientation(Orient_Vertical)
->Split
(
FTabManager::NewStack()
->SetSizeCoefficient(0.1f)
->SetHideTabWell( true )
->AddTab(GetToolbarTabId(), ETabState::OpenedTab)
)
->Split
(
FTabManager::NewSplitter() ->SetOrientation(Orient_Horizontal) ->SetSizeCoefficient(0.9f)
->Split
(
FTabManager::NewSplitter() ->SetOrientation(Orient_Vertical) ->SetSizeCoefficient(0.2f)
->Split
(
FTabManager::NewStack()
->AddTab( PaletteTabId, ETabState::ClosedTab )
->AddTab( PreviewSettingsTabId, ETabState::OpenedTab)
)
->Split
(
FTabManager::NewStack()
->AddTab( ShortcutsTabId, ETabState::OpenedTab )
->AddTab( PropertiesTabId, ETabState::OpenedTab )
)
)
->Split
(
FTabManager::NewSplitter() ->SetOrientation( Orient_Vertical )
->SetSizeCoefficient(0.7f)
->Split
(
FTabManager::NewStack()
->SetSizeCoefficient(0.8f)
->SetHideTabWell( true )
->AddTab( GraphCanvasTabId, ETabState::OpenedTab )
->AddTab( DebugGraphCanvasTabId, ETabState::ClosedTab )
)
->Split
(
FTabManager::NewStack()
->SetSizeCoefficient(0.2f)
->AddTab( MessagesTabId, ETabState::OpenedTab )
)
)
->Split
(
FTabManager::NewSplitter() ->SetOrientation(Orient_Vertical)
->SetSizeCoefficient(0.3f)
->Split
(
FTabManager::NewStack()
->SetHideTabWell( true )
->AddTab( PreviewTabId, ETabState::OpenedTab )
)
->Split
(
FTabManager::NewStack()
->SetHideTabWell( true )
->AddTab( PreviewViewportTabId, ETabState::OpenedTab )
)
)
)
);
const bool bCreateDefaultStandaloneMenu = true;
const bool bCreateDefaultToolbar = true;
FAssetEditorToolkit::InitAssetEditor(Mode, InitToolkitHost, TEXT("VoxelGraphEditorApp"), StandaloneDefaultLayout, bCreateDefaultStandaloneMenu, bCreateDefaultToolbar, ObjectToEdit, false);
ExtendToolbar();
ExtendMenu();
RegenerateMenusAndToolbars();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::CreateInternalWidgets()
{
VoxelGraphEditor = CreateGraphEditorWidget(false);
VoxelDebugGraphEditor = CreateGraphEditorWidget(true);
FDetailsViewArgs Args;
Args.bHideSelectionTip = true;
Args.NotifyHook = this;
FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
VoxelProperties = PropertyModule.CreateDetailView(Args);
VoxelProperties->SetObject(WorldGenerator);
ShortcutsProperties = PropertyModule.CreateDetailView(Args);
ShortcutsProperties->SetObject(GetMutableDefault<UVoxelGraphShortcuts>());
if (!WorldGenerator->PreviewSettings)
{
WorldGenerator->PreviewSettings = NewObject<UVoxelGraphPreviewSettings>(WorldGenerator);
WorldGenerator->PreviewSettings->Graph = WorldGenerator;
}
// Needed for undo/redo
WorldGenerator->PreviewSettings->SetFlags(RF_Transactional);
PreviewSettings = PropertyModule.CreateDetailView(Args);
PreviewSettings->SetObject(WorldGenerator->PreviewSettings);
// Must be created before PreviewViewport
PreviewScene = MakeShareable(new FAdvancedPreviewScene(FPreviewScene::ConstructionValues()));
Palette = SNew(SVoxelPalette);
Preview = SNew(SVoxelGraphPreview).PreviewSettings(WorldGenerator->PreviewSettings);
PreviewViewport = SNew(SVoxelGraphPreviewViewport).VoxelGraphEditorToolkit(SharedThis(this));
PreviewHandler = MakeShared<FVoxelGraphPreview>(WorldGenerator, Preview, PreviewViewport, PreviewScene);
Preview->SetTexture(WorldGenerator->GetPreviewTexture());
// Messages panel
FMessageLogModule& MessageLogModule = FModuleManager::LoadModuleChecked<FMessageLogModule>("MessageLog");
FMessageLogInitializationOptions LogOptions;
LogOptions.bShowPages = false;
LogOptions.bShowFilters = true;
LogOptions.bAllowClear = false;
LogOptions.MaxPageCount = 1;
MessagesListing = MessageLogModule.CreateLogListing("VoxelGraphEditorErrors", LogOptions);
MessagesWidget = MessageLogModule.CreateLogListingWidget(MessagesListing.ToSharedRef());
}
void FVoxelGraphEditorToolkit::FillToolbar(FToolBarBuilder& ToolbarBuilder)
{
ToolbarBuilder.BeginSection("Toolbar");
auto& Commands = FVoxelGraphEditorCommands::Get();
ToolbarBuilder.AddToolBarButton(Commands.CompileToCpp);
ToolbarBuilder.AddSeparator();
ToolbarBuilder.AddToolBarButton(Commands.ToggleAutomaticPreview);
ToolbarBuilder.AddToolBarButton(Commands.UpdatePreview);
ToolbarBuilder.AddSeparator();
ToolbarBuilder.AddToolBarButton(Commands.ClearNodesMessages);
ToolbarBuilder.AddSeparator();
ToolbarBuilder.AddToolBarButton(Commands.ShowAxisDependencies);
ToolbarBuilder.AddSeparator();
ToolbarBuilder.AddToolBarButton(Commands.ShowStats);
ToolbarBuilder.AddToolBarButton(Commands.ShowValues);
ToolbarBuilder.EndSection();
}
void FVoxelGraphEditorToolkit::ExtendToolbar()
{
TSharedPtr<FExtender> ToolbarExtender = MakeShareable(new FExtender);
ToolbarExtender->AddToolBarExtension(
"Asset",
EExtensionHook::After,
GetToolkitCommands(),
FToolBarExtensionDelegate::CreateRaw(this, &FVoxelGraphEditorToolkit::FillToolbar)
);
AddToolbarExtender(ToolbarExtender);
}
void FVoxelGraphEditorToolkit::FillVoxelMenu(FMenuBuilder& MenuBuilder)
{
auto& Commands = FVoxelGraphEditorCommands::Get();
MenuBuilder.AddMenuEntry(Commands.ImportExposedVariablesValues);
MenuBuilder.AddMenuEntry(Commands.RecreateNodes);
}
void FVoxelGraphEditorToolkit::AddEditorMenus(FMenuBarBuilder& MenuBarBuilder)
{
MenuBarBuilder.AddPullDownMenu(
VOXEL_LOCTEXT("Voxel"),
VOXEL_LOCTEXT("Open the Voxel menu"),
FNewMenuDelegate::CreateRaw(this, &FVoxelGraphEditorToolkit::FillVoxelMenu),
"Voxel");
}
void FVoxelGraphEditorToolkit::ExtendMenu()
{
TSharedPtr<FExtender> MenuExtender = MakeShareable(new FExtender);
MenuExtender->AddMenuBarExtension(
"Edit",
EExtensionHook::After,
GetToolkitCommands(),
FMenuBarExtensionDelegate::CreateRaw(this, &FVoxelGraphEditorToolkit::AddEditorMenus));
AddMenuExtender(MenuExtender);
}
void FVoxelGraphEditorToolkit::BindGraphCommands()
{
auto& Commands = FVoxelGraphEditorCommands::Get();
ToolkitCommands->MapAction(
Commands.CompileToCpp,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CompileToCpp));
ToolkitCommands->MapAction(
Commands.RecreateNodes,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::RecreateNodes));
ToolkitCommands->MapAction(
Commands.ToggleAutomaticPreview,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::ToggleAutomaticPreview),
FCanExecuteAction(),
FIsActionChecked::CreateSP(this, &FVoxelGraphEditorToolkit::IsToggleAutomaticPreviewChecked));
ToolkitCommands->MapAction(
Commands.UpdatePreview,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::UpdatePreview, EVoxelGraphPreviewFlags::UpdateAll | EVoxelGraphPreviewFlags::ManualPreview));
ToolkitCommands->MapAction(
Commands.UpdateVoxelWorlds,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::UpdateVoxelWorlds));
ToolkitCommands->MapAction(
Commands.ClearNodesMessages,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::ClearNodesMessages));
ToolkitCommands->MapAction(
Commands.ShowAxisDependencies,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::ShowAxisDependencies));
ToolkitCommands->MapAction(
Commands.ShowStats,
FExecuteAction::CreateWeakLambda(WorldGenerator, [=]()
{
WorldGenerator->PreviewSettings->bShowStats = !WorldGenerator->PreviewSettings->bShowStats;
UpdatePreview(EVoxelGraphPreviewFlags::UpdateTextures);
}),
FCanExecuteAction(),
FIsActionChecked::CreateWeakLambda(WorldGenerator, [=]() { return WorldGenerator->PreviewSettings->bShowStats; }));
ToolkitCommands->MapAction(
Commands.ShowValues,
FExecuteAction::CreateWeakLambda(WorldGenerator, [=]()
{
WorldGenerator->PreviewSettings->bShowValues = !WorldGenerator->PreviewSettings->bShowValues;
UpdatePreview(EVoxelGraphPreviewFlags::UpdateTextures);
}),
FCanExecuteAction(),
FIsActionChecked::CreateWeakLambda(WorldGenerator, [=]() { return WorldGenerator->PreviewSettings->bShowValues; }));
ToolkitCommands->MapAction(
Commands.ImportExposedVariablesValues,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::ImportExposedVariablesValues));
ToolkitCommands->MapAction(
FGenericCommands::Get().Undo,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::UndoGraphAction));
ToolkitCommands->MapAction(
FGenericCommands::Get().Redo,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::RedoGraphAction));
}
TSharedRef<SGraphEditor> FVoxelGraphEditorToolkit::CreateGraphEditorWidget(bool bDebug)
{
if (!GraphEditorCommands.IsValid())
{
GraphEditorCommands = MakeShareable(new FUICommandList);
GraphEditorCommands->MapAction(FVoxelGraphEditorCommands::Get().AddInput,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::AddInput),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanAddInput));
GraphEditorCommands->MapAction(FVoxelGraphEditorCommands::Get().DeleteInput,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::DeleteInput),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanDeleteInput));
GraphEditorCommands->MapAction(FVoxelGraphEditorCommands::Get().TogglePinPreview,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnTogglePinPreview));
GraphEditorCommands->MapAction(FVoxelGraphEditorCommands::Get().SplitPin,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnSplitPin));
GraphEditorCommands->MapAction(FVoxelGraphEditorCommands::Get().CombinePin,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnCombinePin));
// Graph Editor Commands
GraphEditorCommands->MapAction(FGraphEditorCommands::Get().CreateComment,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnCreateComment)
);
// Editing commands
GraphEditorCommands->MapAction(FGenericCommands::Get().SelectAll,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::SelectAllNodes),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanSelectAllNodes)
);
GraphEditorCommands->MapAction(FGenericCommands::Get().Delete,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::DeleteSelectedNodes),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanDeleteNodes)
);
GraphEditorCommands->MapAction(FGenericCommands::Get().Copy,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CopySelectedNodes),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanCopyNodes)
);
GraphEditorCommands->MapAction(FGenericCommands::Get().Cut,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CutSelectedNodes),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanCutNodes)
);
GraphEditorCommands->MapAction(FGenericCommands::Get().Paste,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::PasteNodes),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanPasteNodes)
);
GraphEditorCommands->MapAction(FGenericCommands::Get().Duplicate,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::DuplicateNodes),
FCanExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::CanDuplicateNodes)
);
GraphEditorCommands->MapAction( FVoxelGraphEditorCommands::Get().SelectLocalVariableDeclaration,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnSelectLocalVariableDeclaration)
);
GraphEditorCommands->MapAction( FVoxelGraphEditorCommands::Get().SelectLocalVariableUsages,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnSelectLocalVariableUsages)
);
GraphEditorCommands->MapAction( FVoxelGraphEditorCommands::Get().ConvertRerouteToVariables,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnConvertRerouteToVariables)
);
GraphEditorCommands->MapAction( FVoxelGraphEditorCommands::Get().ConvertVariablesToReroute,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::OnConvertVariablesToReroute)
);
GraphEditorCommands->MapAction( FVoxelGraphEditorCommands::Get().ReconstructNode,
FExecuteAction::CreateSP(this, &FVoxelGraphEditorToolkit::ReconstructNode)
);
// Alignment Commands
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().AlignNodesTop,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnAlignTop )
);
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().AlignNodesMiddle,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnAlignMiddle )
);
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().AlignNodesBottom,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnAlignBottom )
);
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().AlignNodesLeft,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnAlignLeft )
);
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().AlignNodesCenter,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnAlignCenter )
);
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().AlignNodesRight,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnAlignRight )
);
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().StraightenConnections,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnStraightenConnections )
);
// Distribution Commands
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().DistributeNodesHorizontally,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnDistributeNodesH )
);
GraphEditorCommands->MapAction( FGraphEditorCommands::Get().DistributeNodesVertically,
FExecuteAction::CreateSP( this, &FVoxelGraphEditorToolkit::OnDistributeNodesV )
);
}
if (bDebug)
{
FGraphAppearanceInfo AppearanceInfo;
AppearanceInfo.CornerText = VOXEL_LOCTEXT("VOXEL DEBUG");
return SNew(SGraphEditor)
.IsEditable(true)
.Appearance(AppearanceInfo)
.GraphToEdit(WorldGenerator->VoxelDebugGraph)
.AutoExpandActionMenu(false)
.ShowGraphStateOverlay(false);
}
else
{
FGraphAppearanceInfo AppearanceInfo;
AppearanceInfo.CornerText = VOXEL_LOCTEXT("VOXEL");
SGraphEditor::FGraphEditorEvents InEvents;
InEvents.OnSelectionChanged = SGraphEditor::FOnSelectionChanged::CreateSP(this, &FVoxelGraphEditorToolkit::OnSelectedNodesChanged);
InEvents.OnTextCommitted = FOnNodeTextCommitted::CreateSP(this, &FVoxelGraphEditorToolkit::OnNodeTitleCommitted);
InEvents.OnNodeDoubleClicked = FSingleNodeEvent::CreateSP(this, &FVoxelGraphEditorToolkit::OnNodeDoubleClicked);
InEvents.OnSpawnNodeByShortcut = SGraphEditor::FOnSpawnNodeByShortcut::CreateSP(this, &FVoxelGraphEditorToolkit::OnSpawnGraphNodeByShortcut);
return SNew(SGraphEditor)
.AdditionalCommands(GraphEditorCommands)
.IsEditable(true)
.Appearance(AppearanceInfo)
.GraphToEdit(WorldGenerator->VoxelGraph)
.GraphEvents(InEvents)
.AutoExpandActionMenu(false)
.ShowGraphStateOverlay(false);
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
bool FVoxelGraphEditorToolkit::GetBoundsForSelectedNodes(class FSlateRect& Rect, float Padding)
{
return VoxelGraphEditor->GetBoundsForSelectedNodes(Rect, Padding);
}
int32 FVoxelGraphEditorToolkit::GetNumberOfSelectedNodes() const
{
return VoxelGraphEditor->GetSelectedNodes().Num();
}
FGraphPanelSelectionSet FVoxelGraphEditorToolkit::GetSelectedNodes() const
{
return VoxelGraphEditor->GetSelectedNodes();
}
void FVoxelGraphEditorToolkit::SelectNodesAndZoomToFit(const TArray<UEdGraphNode*>& Nodes)
{
if (Nodes.Num() > 0)
{
VoxelGraphEditor->ClearSelectionSet();
for (auto& Node : Nodes)
{
VoxelGraphEditor->SetNodeSelection(Node, true);
}
VoxelGraphEditor->ZoomToFit(true);
}
}
void FVoxelGraphEditorToolkit::RefreshNodesMessages()
{
for (auto* Node : WorldGenerator->VoxelGraph->Nodes)
{
if (Node->IsA<UVoxelGraphNode>() && !Node->IsA<UVoxelGraphNode_Knot>())
{
TSharedPtr<SGraphNode> Widget = Node->DEPRECATED_NodeWidget.Pin();
if (Widget.IsValid())
{
static_cast<SVoxelGraphNode*>(Widget.Get())->RefreshErrorInfo();
}
}
}
}
void FVoxelGraphEditorToolkit::TriggerUpdatePreview(EVoxelGraphPreviewFlags Flags)
{
if (WorldGenerator->bAutomaticPreview || EnumHasAnyFlags(Flags, EVoxelGraphPreviewFlags::ManualPreview))
{
bUpdatePreviewOnNextTick = true;
NextPreviewFlags |= Flags;
}
}
FAdvancedPreviewScene* FVoxelGraphEditorToolkit::GetPreviewScene() const
{
return PreviewScene.Get();
}
void FVoxelGraphEditorToolkit::DebugNodes(const TSet<FVoxelCompilationNode*>& Nodes)
{
}
inline EMessageSeverity::Type VoxelMessageTypeToMessageSeverity(EVoxelGraphNodeMessageType Type)
{
switch (Type)
{
default: ensure(false);
case EVoxelGraphNodeMessageType::Info:
return EMessageSeverity::Info;
case EVoxelGraphNodeMessageType::Warning:
return EMessageSeverity::Warning;
case EVoxelGraphNodeMessageType::Error:
return EMessageSeverity::Error;
}
}
void FVoxelGraphEditorToolkit::AddMessages(const TArray<FVoxelGraphMessage>& Messages)
{
CurrentMessages.Append(Messages);
TArray<TSharedRef<FTokenizedMessage>> ListingMessages;
for (auto& Message : Messages)
{
TSharedRef<FTokenizedMessage> ListingMessage = FTokenizedMessage::Create(VoxelMessageTypeToMessageSeverity(Message.Type));
if (Message.Node.IsValid())
{
ListingMessage->AddToken(FActionToken::Create(
Message.Node->GetTitle(),
Message.Node->GetTitle(),
FOnActionTokenExecuted::CreateSP(
this,
&FVoxelGraphEditorToolkit::SelectNodeAndZoomToFit,
Message.Node)
));
}
ListingMessage->AddToken(FTextToken::Create(FText::FromString(Message.Message)));
ListingMessages.Add(ListingMessage);
}
MessagesListing->AddMessages(ListingMessages, false);
}
void FVoxelGraphEditorToolkit::ClearMessages(bool bClearAll, EVoxelGraphNodeMessageType MessagesToClear)
{
MessagesListing->ClearMessages();
if (bClearAll)
{
CurrentMessages.Reset();
}
else
{
TArray<FVoxelGraphMessage> Copy = CurrentMessages;
Copy.RemoveAll([&](auto& Message) { return Message.Type == MessagesToClear; });
CurrentMessages.Reset();
AddMessages(Copy);
}
}
void FVoxelGraphEditorToolkit::SaveAsset_Execute()
{
if (WorldGenerator->bCompileToCppOnSave)
{
}
// Make sure to save AFTER compile to cpp to avoid dirtying it again
FAssetEditorToolkit::SaveAsset_Execute();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::AddReferencedObjects(FReferenceCollector& Collector)
{
Collector.AddReferencedObject(WorldGenerator);
if (PreviewHandler.IsValid())
{
PreviewHandler->AddReferencedObjects(Collector);
}
}
void FVoxelGraphEditorToolkit::PostUndo(bool bSuccess)
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->ClearSelectionSet();
VoxelGraphEditor->NotifyGraphChanged();
}
TriggerUpdatePreview(EVoxelGraphPreviewFlags::UpdateAll);
}
void FVoxelGraphEditorToolkit::NotifyPostChange(const FPropertyChangedEvent& PropertyChangedEvent, class UProperty* PropertyThatChanged)
{
if (VoxelGraphEditor.IsValid() && PropertyChangedEvent.ChangeType != EPropertyChangeType::Interactive)
{
VoxelGraphEditor->NotifyGraphChanged();
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::Tick(float DeltaTime)
{
if (bUpdatePreviewOnNextTick)
{
UpdatePreview(NextPreviewFlags);
bUpdatePreviewOnNextTick = false;
NextPreviewFlags = EVoxelGraphPreviewFlags::None;
}
}
TStatId FVoxelGraphEditorToolkit::GetStatId() const
{
RETURN_QUICK_DECLARE_CYCLE_STAT(FVoxelGraphEditorToolkit, STATGROUP_Tickables);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_GraphCanvas(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == GraphCanvasTabId);
auto Tab = SNew(SDockTab)
.Label(VOXEL_LOCTEXT("Main Graph"));
GraphTab = Tab;
GraphTab->SetContent(VoxelGraphEditor.ToSharedRef());
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_DebugGraphCanvas(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == DebugGraphCanvasTabId);
auto Tab = SNew(SDockTab)
.Label(VOXEL_LOCTEXT("Debug Graph"));
DebugGraphTab = Tab;
DebugGraphTab->SetContent(VoxelDebugGraphEditor.ToSharedRef());
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_Properties(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == PropertiesTabId);
auto Tab =
SNew(SDockTab)
.Icon(FEditorStyle::GetBrush("LevelEditor.Tabs.Details"))
.Label(VOXEL_LOCTEXT("Details"))
[
VoxelProperties.ToSharedRef()
];
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_Shortcuts(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == ShortcutsTabId);
auto Tab =
SNew(SDockTab)
.Icon(FEditorStyle::GetBrush("LevelEditor.Tabs.Details"))
.Label(VOXEL_LOCTEXT("Shortcuts"))
[
ShortcutsProperties.ToSharedRef()
];
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_PreviewSettings(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == PreviewSettingsTabId);
auto Tab =
SNew(SDockTab)
.Icon(FEditorStyle::GetBrush("LevelEditor.Tabs.Details"))
.Label(VOXEL_LOCTEXT("Preview Settings"))
[
PreviewSettings.ToSharedRef()
];
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_Palette(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == PaletteTabId);
auto Tab =
SNew(SDockTab)
.Icon(FEditorStyle::GetBrush("Kismet.Tabs.Palette"))
.Label(VOXEL_LOCTEXT("Palette"))
[
Palette.ToSharedRef()
];
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_Preview(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == PreviewTabId);
auto Tab =
SNew(SDockTab)
.Icon(FEditorStyle::GetBrush("LevelEditor.Tabs.Viewports"))
.Label(VOXEL_LOCTEXT("Preview"))
[
// Do the scaling here to make math easier
SNew(SScaleBox)
.Stretch(EStretch::ScaleToFit)
[
Preview.ToSharedRef()
]
];
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_PreviewViewport(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == PreviewViewportTabId);
auto Tab =
SNew(SDockTab)
.Icon(FEditorStyle::GetBrush("LevelEditor.Tabs.Viewports"))
.Label(VOXEL_LOCTEXT("3D Preview"))
[
PreviewViewport.ToSharedRef()
];
return Tab;
}
TSharedRef<SDockTab> FVoxelGraphEditorToolkit::SpawnTab_Messages(const FSpawnTabArgs& Args)
{
check(Args.GetTabId() == MessagesTabId);
auto Tab =
SNew(SDockTab)
.Icon(FEditorStyle::GetBrush("MessageLog.TabIcon"))
.Label(VOXEL_LOCTEXT("Messages"))
[
MessagesWidget.ToSharedRef()
];
return Tab;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::OnSelectedNodesChanged(const TSet<class UObject*>& NewSelection)
{
TArray<UObject*> Selection;
if (NewSelection.Num())
{
for (auto* Object : NewSelection)
{
if (Cast<UVoxelGraphNode_Root>(Object) || Cast<UVoxelGraphMacroInputOutputNode>(Object))
{
Selection.Add(WorldGenerator);
}
else if (UVoxelGraphNode* GraphNode = Cast<UVoxelGraphNode>(Object))
{
Selection.Add(GraphNode->VoxelNode);
}
else
{
Selection.Add(Object);
}
}
}
else
{
Selection.Add(WorldGenerator);
}
VoxelProperties->SetObjects(Selection);
}
void FVoxelGraphEditorToolkit::OnNodeTitleCommitted(const FText& NewText, ETextCommit::Type CommitInfo, UEdGraphNode* NodeBeingChanged)
{
if (NodeBeingChanged)
{
const FScopedTransaction Transaction(VOXEL_LOCTEXT("Rename Node"));
NodeBeingChanged->Modify();
NodeBeingChanged->OnRenameNode(NewText.ToString());
}
}
void FVoxelGraphEditorToolkit::OnNodeDoubleClicked(UEdGraphNode* Node)
{
if (Node->CanJumpToDefinition())
{
Node->JumpToDefinition();
}
}
FReply FVoxelGraphEditorToolkit::OnSpawnGraphNodeByShortcut(FInputChord InChord, const FVector2D& InPosition)
{
auto* Ptr = GetDefault<UVoxelGraphShortcuts>()->Shortcuts.FindByPredicate([&](auto& Key) { return Key.IsSameAs(InChord); });
UClass* ClassToSpawn = Ptr ? Ptr->Class : nullptr;
if (ClassToSpawn)
{
FVoxelGraphSchemaAction_NewNode Action(FText(), FText(), FText(), 0);
Action.VoxelNodeClass = ClassToSpawn;
Action.PerformAction(WorldGenerator->VoxelGraph, nullptr, InPosition);
}
return FReply::Handled();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::AddInput()
{
const FGraphPanelSelectionSet SelectedNodes = GetSelectedNodes();
// Iterator used but should only contain one node
for (auto* SelectedNode : SelectedNodes)
{
if (auto* Node = Cast<UVoxelGraphNode>(SelectedNode))
{
Node->AddInputPin();
break;
}
}
}
bool FVoxelGraphEditorToolkit::CanAddInput() const
{
return GetSelectedNodes().Num() == 1;
}
void FVoxelGraphEditorToolkit::DeleteInput()
{
UEdGraphPin* SelectedPin = VoxelGraphEditor->GetGraphPinForMenu();
UVoxelGraphNode* SelectedNode = Cast<UVoxelGraphNode>(SelectedPin->GetOwningNode());
if (SelectedNode && SelectedNode == SelectedPin->GetOwningNode())
{
SelectedNode->RemoveInputPin(SelectedPin);
}
}
bool FVoxelGraphEditorToolkit::CanDeleteInput() const
{
return true;
}
void FVoxelGraphEditorToolkit::OnCreateComment()
{
FVoxelGraphSchemaAction_NewComment CommentAction;
CommentAction.PerformAction(WorldGenerator->VoxelGraph, NULL, VoxelGraphEditor->GetPasteLocation());
}
void FVoxelGraphEditorToolkit::OnTogglePinPreview()
{
UEdGraphPin* SelectedPin = VoxelGraphEditor->GetGraphPinForMenu();
UVoxelGraphNode* SelectedNode = Cast<UVoxelGraphNode>(SelectedPin->GetOwningNode());
UVoxelGraphNode* GraphNodeToPreview = Cast<UVoxelGraphNode>(SelectedNode);
if (GraphNodeToPreview && GraphNodeToPreview->VoxelNode)
{
const bool bIsPreviewing = SelectedPin->bIsDiffing;
if (WorldGenerator->PreviewedPin.Get())
{
ensure(!bIsPreviewing || SelectedPin == WorldGenerator->PreviewedPin.Get());
ensure(WorldGenerator->PreviewedPin.Get()->bIsDiffing);
WorldGenerator->PreviewedPin.Get()->bIsDiffing = false;
WorldGenerator->PreviewedPin.SetPin(nullptr);
}
ensure(!SelectedPin->bIsDiffing);
if (!bIsPreviewing)
{
SelectedPin->bIsDiffing = true;
WorldGenerator->PreviewedPin.SetPin(SelectedPin);
}
VoxelGraphEditor->NotifyGraphChanged();
}
UpdatePreview(EVoxelGraphPreviewFlags::UpdateAll | EVoxelGraphPreviewFlags::ManualPreview);
}
void FVoxelGraphEditorToolkit::OnSplitPin()
{
UEdGraphPin* SelectedPin = VoxelGraphEditor->GetGraphPinForMenu();
UVoxelGraphNode* SelectedNode = Cast<UVoxelGraphNode>(SelectedPin->GetOwningNode());
SelectedNode->TrySplitPin(*SelectedPin, false);
}
void FVoxelGraphEditorToolkit::OnCombinePin()
{
UEdGraphPin* SelectedPin = VoxelGraphEditor->GetGraphPinForMenu();
UVoxelGraphNode* SelectedNode = Cast<UVoxelGraphNode>(SelectedPin->GetOwningNode());
SelectedNode->TryCombinePin(*SelectedPin, false);
}
void FVoxelGraphEditorToolkit::SelectAllNodes()
{
VoxelGraphEditor->SelectAllNodes();
}
void FVoxelGraphEditorToolkit::DeleteSelectedNodes()
{
const FScopedTransaction Transaction(VOXEL_LOCTEXT("Delete Selected Voxel Node"));
VoxelGraphEditor->GetCurrentGraph()->Modify();
const FGraphPanelSelectionSet SelectedNodes = GetSelectedNodes();
VoxelGraphEditor->ClearSelectionSet();
for (auto* Object : SelectedNodes)
{
UEdGraphNode* Node = CastChecked<UEdGraphNode>(Object);
if (Node->CanUserDeleteNode())
{
if (UVoxelGraphNode* VoxelGraphNode = Cast<UVoxelGraphNode>(Node))
{
UVoxelNode* VoxelNode = VoxelGraphNode->VoxelNode;
if (VoxelNode)
{
VoxelNode->Modify();
VoxelNode->MarkPendingKill();
}
auto* PreviewedPin = WorldGenerator->PreviewedPin.Get();
if (PreviewedPin && PreviewedPin->GetOwningNode() == VoxelGraphNode)
{
// Clear previewed pin if we delete the owning node
WorldGenerator->PreviewedPin = {};
// Clear since we're not previewing it anymore
PreviewedPin->bIsDiffing = false;
}
FBlueprintEditorUtils::RemoveNode(NULL, VoxelGraphNode, true);
// Make sure Voxel is updated to match graph
WorldGenerator->CompileVoxelNodesFromGraphNodes();
// Remove this node from the list of all VoxelNodes
WorldGenerator->AllNodes.Remove(VoxelNode);
WorldGenerator->MarkPackageDirty();
}
else
{
FBlueprintEditorUtils::RemoveNode(NULL, Node, true);
}
}
}
}
bool FVoxelGraphEditorToolkit::CanDeleteNodes() const
{
const FGraphPanelSelectionSet SelectedNodes = GetSelectedNodes();
if (SelectedNodes.Num() == 1)
{
for (auto* Node : SelectedNodes)
{
UVoxelGraphNode* GraphNode = Cast<UVoxelGraphNode>(Node);
if (GraphNode && !GraphNode->CanUserDeleteNode())
{
return false;
}
}
}
return SelectedNodes.Num() > 0;
}
void FVoxelGraphEditorToolkit::DeleteSelectedDuplicatableNodes()
{
// Cache off the old selection
const FGraphPanelSelectionSet OldSelectedNodes = GetSelectedNodes();
// Clear the selection and only select the nodes that can be duplicated
FGraphPanelSelectionSet RemainingNodes;
VoxelGraphEditor->ClearSelectionSet();
for (auto* SelectedNode : OldSelectedNodes)
{
UEdGraphNode* Node = Cast<UEdGraphNode>(SelectedNode);
if (Node && Node->CanDuplicateNode())
{
VoxelGraphEditor->SetNodeSelection(Node, true);
}
else
{
RemainingNodes.Add(Node);
}
}
// Delete the duplicable nodes
DeleteSelectedNodes();
// Reselect whatever's left from the original selection after the deletion
VoxelGraphEditor->ClearSelectionSet();
for (auto* RemainingNode : RemainingNodes)
{
if (UEdGraphNode* Node = Cast<UEdGraphNode>(RemainingNode))
{
VoxelGraphEditor->SetNodeSelection(Node, true);
}
}
}
void FVoxelGraphEditorToolkit::CutSelectedNodes()
{
CopySelectedNodes();
// Cut should only delete nodes that can be duplicated
DeleteSelectedDuplicatableNodes();
}
bool FVoxelGraphEditorToolkit::CanCutNodes() const
{
return CanCopyNodes() && CanDeleteNodes();
}
void FVoxelGraphEditorToolkit::CopySelectedNodes()
{
// Export the selected nodes and place the text on the clipboard
FGraphPanelSelectionSet SelectedNodes;
{
FGraphPanelSelectionSet AllSelectedNodes = GetSelectedNodes();
for (auto* SelectedNode : AllSelectedNodes)
{
auto* Node = Cast<UEdGraphNode>(SelectedNode);
if (Node && Node->CanDuplicateNode())
{
SelectedNodes.Add(Node);
}
}
}
FString ExportedText;
for (auto It = SelectedNodes.CreateIterator(); It; ++It)
{
CastChecked<UEdGraphNode>(*It)->PrepareForCopying();
}
FEdGraphUtilities::ExportNodesToText(SelectedNodes, /*out*/ ExportedText);
FPlatformApplicationMisc::ClipboardCopy(*ExportedText);
// Make sure the voxel graph remains the owner of the copied nodes
for (auto It = SelectedNodes.CreateIterator(); It; ++It)
{
if (auto* Node = Cast<UVoxelGraphNode>(*It))
{
Node->PostCopyNode();
}
}
}
bool FVoxelGraphEditorToolkit::CanCopyNodes() const
{
// If any of the nodes can be duplicated then we should allow copying
const FGraphPanelSelectionSet SelectedNodes = GetSelectedNodes();
for (auto* SelectedNode : SelectedNodes)
{
UEdGraphNode* Node = Cast<UEdGraphNode>(SelectedNode);
if (Node && Node->CanDuplicateNode())
{
return true;
}
}
return false;
}
void FVoxelGraphEditorToolkit::PasteNodes()
{
PasteNodesHere(VoxelGraphEditor->GetPasteLocation());
}
void FVoxelGraphEditorToolkit::PasteNodesHere(const FVector2D& Location)
{
// Undo/Redo support
const FScopedTransaction Transaction(VOXEL_LOCTEXT("Paste Voxel Node"));
WorldGenerator->VoxelGraph->Modify();
WorldGenerator->Modify();
// Clear the selection set (newly pasted stuff will be selected)
VoxelGraphEditor->ClearSelectionSet();
// Grab the text to paste from the clipboard.
FString TextToImport;
FPlatformApplicationMisc::ClipboardPaste(TextToImport);
// Import the nodes
TSet<UEdGraphNode*> PastedNodes;
FEdGraphUtilities::ImportNodesFromText(WorldGenerator->VoxelGraph, TextToImport, /*out*/ PastedNodes);
//Average position of nodes so we can move them while still maintaining relative distances to each other
FVector2D AvgNodePosition(0.0f, 0.0f);
for (auto* Node : PastedNodes)
{
AvgNodePosition.X += Node->NodePosX;
AvgNodePosition.Y += Node->NodePosY;
}
if (PastedNodes.Num() > 0)
{
float InvNumNodes = 1.0f / float(PastedNodes.Num());
AvgNodePosition.X *= InvNumNodes;
AvgNodePosition.Y *= InvNumNodes;
}
TArray<UVoxelNode*> PastedVoxelNodes;
for (auto* Node : PastedNodes)
{
if (UVoxelGraphNode* VoxelGraphNode = Cast<UVoxelGraphNode>(Node))
{
if (auto* VoxelNode = VoxelGraphNode->VoxelNode)
{
PastedVoxelNodes.Add(VoxelNode);
WorldGenerator->AllNodes.Add(VoxelNode);
VoxelNode->Graph = WorldGenerator;
}
// Combine pins if possible
// This cannot destroy any link
// Else combined pins are all expanded on copy
VoxelGraphNode->CombineAll();
}
// Select the newly pasted stuff
VoxelGraphEditor->SetNodeSelection(Node, true);
Node->NodePosX = (Node->NodePosX - AvgNodePosition.X) + Location.X;
Node->NodePosY = (Node->NodePosY - AvgNodePosition.Y) + Location.Y;
Node->SnapToGrid(SNodePanel::GetSnapGridSize());
// Give new node a different Guid from the old one
Node->CreateNewGuid();
}
// Force new pasted VoxelNodes to have same connections as graph nodes
WorldGenerator->CompileVoxelNodesFromGraphNodes();
// Post copy for local variables
for (auto* Node : PastedVoxelNodes)
{
Node->PostCopyNode(PastedVoxelNodes);
}
// Update UI
VoxelGraphEditor->NotifyGraphChanged();
WorldGenerator->PostEditChange();
WorldGenerator->MarkPackageDirty();
}
bool FVoxelGraphEditorToolkit::CanPasteNodes() const
{
FString ClipboardContent;
FPlatformApplicationMisc::ClipboardPaste(ClipboardContent);
return FEdGraphUtilities::CanImportNodesFromText(WorldGenerator->VoxelGraph, ClipboardContent);
}
void FVoxelGraphEditorToolkit::DuplicateNodes()
{
// Copy and paste current selection
CopySelectedNodes();
PasteNodes();
}
bool FVoxelGraphEditorToolkit::CanDuplicateNodes() const
{
return CanCopyNodes();
}
void FVoxelGraphEditorToolkit::OnAlignTop()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnAlignTop();
}
}
void FVoxelGraphEditorToolkit::OnAlignMiddle()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnAlignMiddle();
}
}
void FVoxelGraphEditorToolkit::OnAlignBottom()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnAlignBottom();
}
}
void FVoxelGraphEditorToolkit::OnAlignLeft()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnAlignLeft();
}
}
void FVoxelGraphEditorToolkit::OnAlignCenter()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnAlignCenter();
}
}
void FVoxelGraphEditorToolkit::OnAlignRight()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnAlignRight();
}
}
void FVoxelGraphEditorToolkit::OnStraightenConnections()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnStraightenConnections();
}
}
void FVoxelGraphEditorToolkit::OnDistributeNodesH()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnDistributeNodesH();
}
}
void FVoxelGraphEditorToolkit::OnDistributeNodesV()
{
if (VoxelGraphEditor.IsValid())
{
VoxelGraphEditor->OnDistributeNodesV();
}
}
void FVoxelGraphEditorToolkit::OnSelectLocalVariableDeclaration()
{
const FGraphPanelSelectionSet SelectedNodes = VoxelGraphEditor->GetSelectedNodes();
if (SelectedNodes.Num() == 1)
{
VoxelGraphEditor->ClearSelectionSet();
for (FGraphPanelSelectionSet::TConstIterator NodeIt(SelectedNodes); NodeIt; ++NodeIt)
{
UVoxelGraphNode* GraphNode = Cast<UVoxelGraphNode>(*NodeIt);
if (GraphNode)
{
UVoxelNode* CurrentSelectedNoe = GraphNode->VoxelNode;
UVoxelLocalVariableUsage* Usage = Cast<UVoxelLocalVariableUsage>(CurrentSelectedNoe);
if (Usage && Usage->Declaration)
{
UEdGraphNode* DeclarationGraphNode = Usage->Declaration->GraphNode;
if (DeclarationGraphNode)
{
VoxelGraphEditor->SetNodeSelection(DeclarationGraphNode, true);
}
}
}
}
VoxelGraphEditor->ZoomToFit(true);
}
}
void FVoxelGraphEditorToolkit::OnSelectLocalVariableUsages()
{
const FGraphPanelSelectionSet SelectedNodes = VoxelGraphEditor->GetSelectedNodes();
if (SelectedNodes.Num() == 1)
{
bool bZoom = false;
VoxelGraphEditor->ClearSelectionSet();
for (FGraphPanelSelectionSet::TConstIterator NodeIt(SelectedNodes); NodeIt; ++NodeIt)
{
UVoxelGraphNode* GraphNode = Cast<UVoxelGraphNode>(*NodeIt);
if (GraphNode)
{
UVoxelNode* CurrentSelectedNode = GraphNode->VoxelNode;
UVoxelLocalVariableDeclaration* Declaration = Cast<UVoxelLocalVariableDeclaration>(CurrentSelectedNode);
for (UVoxelNode* Node : WorldGenerator->AllNodes)
{
auto* Usage = Cast<UVoxelLocalVariableUsage>(Node);
if (Usage && Usage->Declaration == Declaration)
{
UEdGraphNode* UsageGraphNode = Usage->GraphNode;
if (UsageGraphNode)
{
bZoom = true;
VoxelGraphEditor->SetNodeSelection(UsageGraphNode, true);
}
}
}
}
}
if (bZoom)
{
VoxelGraphEditor->ZoomToFit(true);
}
}
}
void FVoxelGraphEditorToolkit::OnConvertRerouteToVariables()
{
const FGraphPanelSelectionSet SelectedNodes = VoxelGraphEditor->GetSelectedNodes();
if (SelectedNodes.Num() == 1)
{
VoxelGraphEditor->ClearSelectionSet();
for (FGraphPanelSelectionSet::TConstIterator NodeIt(SelectedNodes); NodeIt; ++NodeIt)
{
UVoxelGraphNode_Knot* GraphNode = Cast<UVoxelGraphNode_Knot>(*NodeIt);
if (GraphNode)
{
UEdGraph* Graph = GraphNode->GetGraph();
const FScopedTransaction Transaction(VOXEL_LOCTEXT("Convert reroute to local variables"));
Graph->Modify();
const TArray<UEdGraphPin*>& InputPins = GraphNode->GetInputPin()->LinkedTo;
TArray<UEdGraphPin*> OutputPins = GraphNode->GetOutputPin()->LinkedTo;
OutputPins.Sort([](UEdGraphPin& A, UEdGraphPin& B) { return A.GetOwningNode()->NodePosY < B.GetOwningNode()->NodePosY; });
TArray<UVoxelLocalVariableUsage*> Usages;
int UsageIndex = -OutputPins.Num() / 2;
for (auto* OutputPin : OutputPins)
{
auto* Usage = WorldGenerator->ConstructNewNode<UVoxelLocalVariableUsage>(FVector2D(GraphNode->NodePosX + 50, GraphNode->NodePosY + 50 * UsageIndex));
Usages.Add(Usage);
UsageIndex++;
}
// Spawn declaration AFTER usages so that it gets renamed
auto* Declaration = WorldGenerator->ConstructNewNode<UVoxelLocalVariableDeclaration>(FVector2D(GraphNode->NodePosX - 50, GraphNode->NodePosY));
Declaration->SetCategory(FVoxelPinCategory::FromString(GraphNode->GetInputPin()->PinType.PinCategory));
Declaration->GraphNode->ReconstructNode();
check(Declaration->GraphNode->Pins.Num() == 1);
UEdGraphPin* DeclarationInputPin = Declaration->GraphNode->Pins[0];
check(DeclarationInputPin->Direction == EEdGraphPinDirection::EGPD_Input)
for (auto* InputPin : InputPins)
{
InputPin->MakeLinkTo(DeclarationInputPin);
}
for (int32 Index = 0; Index < OutputPins.Num() ; Index++)
{
auto* Usage = Usages[Index];
Usage->Declaration = Declaration;
Usage->DeclarationGuid = Declaration->VariableGuid;
Usage->GraphNode->ReconstructNode();
Usage->GraphNode->GetAllPins()[0]->MakeLinkTo(OutputPins[Index]); // usage node has a single pin
}
GraphNode->DestroyNode();
}
}
}
}
void FVoxelGraphEditorToolkit::OnConvertVariablesToReroute()
{
const FGraphPanelSelectionSet SelectedNodes = VoxelGraphEditor->GetSelectedNodes();
if (SelectedNodes.Num() == 1)
{
for (FGraphPanelSelectionSet::TConstIterator NodeIt(SelectedNodes); NodeIt; ++NodeIt)
{
UVoxelGraphNode* GraphNode = Cast<UVoxelGraphNode>(*NodeIt);
if (GraphNode)
{
UEdGraph* Graph = GraphNode->GetGraph();
const FScopedTransaction Transaction(VOXEL_LOCTEXT("Convert local variables to reroute"));
Graph->Modify();
UVoxelNode* CurrentSelectedNode = GraphNode->VoxelNode;
UVoxelLocalVariableDeclaration* Declaration = Cast<UVoxelLocalVariableDeclaration>(CurrentSelectedNode);
if (!Declaration)
{
UVoxelLocalVariableUsage* Usage = Cast<UVoxelLocalVariableUsage>(CurrentSelectedNode);
if (Usage)
{
Declaration = Usage->Declaration;
}
}
if (!Declaration)
{
return;
}
UEdGraphNode* DeclarationGraphNode = Declaration->GraphNode;
FGraphNodeCreator<UVoxelGraphNode_Knot> KnotNodeCreator(*Graph);
UVoxelGraphNode_Knot* KnotNode = KnotNodeCreator.CreateNode();
KnotNodeCreator.Finalize();
KnotNode->NodePosX = DeclarationGraphNode->NodePosX + 50;
KnotNode->NodePosY = DeclarationGraphNode->NodePosY;
for (UEdGraphPin* Pin : DeclarationGraphNode->GetAllPins())
{
if (Pin->Direction == EEdGraphPinDirection::EGPD_Input)
{
for (UEdGraphPin* InputPin : Pin->LinkedTo)
{
KnotNode->GetInputPin()->MakeLinkTo(InputPin);
}
}
if (Pin->Direction == EEdGraphPinDirection::EGPD_Output)
{
for (UEdGraphPin* OutputPin : Pin->LinkedTo)
{
KnotNode->GetOutputPin()->MakeLinkTo(OutputPin);
}
}
}
DeclarationGraphNode->DestroyNode();
for(UVoxelNode* Node : WorldGenerator->AllNodes)
{
auto* Usage = Cast<UVoxelLocalVariableUsage>(Node);
if (Usage && Usage->Declaration == Declaration)
{
UEdGraphNode* UsageGraphNode = Usage->GraphNode;
if (UsageGraphNode)
{
UEdGraphPin* Pin = Usage->GraphNode->GetAllPins()[0]; // usage node has a single pin
for (UEdGraphPin* OutputPin : Pin->LinkedTo)
{
KnotNode->GetOutputPin()->MakeLinkTo(OutputPin);
}
UsageGraphNode->DestroyNode();
}
}
}
KnotNode->PropagatePinType();
}
}
}
}
void FVoxelGraphEditorToolkit::ReconstructNode()
{
const FGraphPanelSelectionSet SelectedNodes = VoxelGraphEditor->GetSelectedNodes();
for(auto& Object : SelectedNodes)
{
if (auto* Node = Cast<UVoxelGraphNode>(Object))
{
Node->ReconstructNode();
}
}
WorldGenerator->CompileVoxelNodesFromGraphNodes();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::RecreateNodes()
{
for (int32 I = 0; I < 4; I++) // Hack to make sure they are really recreated
{
TArray<UVoxelGraphNode*> AllNodes;
VoxelGraphEditor->GetCurrentGraph()->GetNodesOfClass<UVoxelGraphNode>(AllNodes);
for (auto* Node : AllNodes)
{
Node->ReconstructNode();
}
WorldGenerator->CompileVoxelNodesFromGraphNodes();
GraphTab->ClearContent();
VoxelGraphEditor = CreateGraphEditorWidget(false);
GraphTab->SetContent(VoxelGraphEditor.ToSharedRef());
}
ClearNodesMessages();
}
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::CompileToCpp()
{
FVoxelMessages::Info("Compiling graphs to C++ requires Voxel Plugin Pro");
}
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::ToggleAutomaticPreview()
{
WorldGenerator->Modify();
WorldGenerator->bAutomaticPreview = !WorldGenerator->bAutomaticPreview;
}
bool FVoxelGraphEditorToolkit::IsToggleAutomaticPreviewChecked() const
{
return WorldGenerator->bAutomaticPreview;
}
void FVoxelGraphEditorToolkit::UpdatePreview(EVoxelGraphPreviewFlags Flags)
{
PreviewHandler->Update(Flags);
if (EnumHasAnyFlags(Flags, EVoxelGraphPreviewFlags::ManualPreview))
{
FVoxelMessages::Info("You can view and edit Voxel Graphs, but running and previewing them requires Voxel Plugin Pro");
}
}
void FVoxelGraphEditorToolkit::UpdateVoxelWorlds()
{
IVoxelEditorModule* VoxelEditorModule = &FModuleManager::LoadModuleChecked<IVoxelEditorModule>("VoxelEditor");
VoxelEditorModule->RefreshVoxelWorlds(WorldGenerator);
}
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::ClearNodesMessages()
{
FVoxelGraphErrorReporter::ClearNodesMessages(WorldGenerator);
ClearMessages(true, EVoxelGraphNodeMessageType::Info);
}
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::ShowAxisDependencies()
{
FVoxelGraphErrorReporter::ClearNodesMessages(WorldGenerator);
}
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::ImportExposedVariablesValues()
{
FVoxelGraphImportExposedVariablesValues::Import(WorldGenerator);
VoxelGraphEditor->NotifyGraphChanged();
}
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::UndoGraphAction()
{
GEditor->UndoTransaction();
}
void FVoxelGraphEditorToolkit::RedoGraphAction()
{
// Clear selection, to avoid holding refs to nodes that go away
VoxelGraphEditor->ClearSelectionSet();
GEditor->RedoTransaction();
}
///////////////////////////////////////////////////////////////////////////////
void FVoxelGraphEditorToolkit::SelectNodeAndZoomToFit(TWeakObjectPtr<const UVoxelNode> Node)
{
if (Node.IsValid() && Node->Graph)
{
if (Node->Graph == WorldGenerator)
{
SelectNodesAndZoomToFit({ Node->GraphNode });
}
else
{
#if ENGINE_MINOR_VERSION < 24
if (ensure(FAssetEditorManager::Get().OpenEditorForAsset(Node->Graph)))
#else
if (ensure(GEditor->GetEditorSubsystem<UAssetEditorSubsystem>()->OpenEditorForAsset(Node->Graph)))
#endif
{
auto NewEditor = FVoxelGraphEditorUtilities::GetIVoxelEditorForGraph(Node->Graph->VoxelGraph);
if (ensure(NewEditor.IsValid()))
{
NewEditor->SelectNodesAndZoomToFit({ Node->GraphNode });
}
}
}
}
} | 32.383694 | 190 | 0.706678 | SolarStormInteractive |
c8842edb55f427acc1ab99f1f35fad7930b7b61c | 2,548 | hpp | C++ | include/System/DefaultBinder_BinderState.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/DefaultBinder_BinderState.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/DefaultBinder_BinderState.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.DefaultBinder
#include "System/DefaultBinder.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: System
namespace System {
// Size: 0x1D
#pragma pack(push, 1)
// Autogenerated type: System.DefaultBinder/BinderState
class DefaultBinder::BinderState : public ::Il2CppObject {
public:
// System.Int32[] m_argsMap
// Size: 0x8
// Offset: 0x10
::Array<int>* m_argsMap;
// Field size check
static_assert(sizeof(::Array<int>*) == 0x8);
// System.Int32 m_originalSize
// Size: 0x4
// Offset: 0x18
int m_originalSize;
// Field size check
static_assert(sizeof(int) == 0x4);
// System.Boolean m_isParamArray
// Size: 0x1
// Offset: 0x1C
bool m_isParamArray;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: BinderState
BinderState(::Array<int>* m_argsMap_ = {}, int m_originalSize_ = {}, bool m_isParamArray_ = {}) noexcept : m_argsMap{m_argsMap_}, m_originalSize{m_originalSize_}, m_isParamArray{m_isParamArray_} {}
// System.Void .ctor(System.Int32[] argsMap, System.Int32 originalSize, System.Boolean isParamArray)
// Offset: 0x1AEB1D8
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static DefaultBinder::BinderState* New_ctor(::Array<int>* argsMap, int originalSize, bool isParamArray) {
static auto ___internal__logger = ::Logger::get().WithContext("System::DefaultBinder::BinderState::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<DefaultBinder::BinderState*, creationType>(argsMap, originalSize, isParamArray)));
}
}; // System.DefaultBinder/BinderState
#pragma pack(pop)
static check_size<sizeof(DefaultBinder::BinderState), 28 + sizeof(bool)> __System_DefaultBinder_BinderStateSizeCheck;
static_assert(sizeof(DefaultBinder::BinderState) == 0x1D);
}
DEFINE_IL2CPP_ARG_TYPE(System::DefaultBinder::BinderState*, "System", "DefaultBinder/BinderState");
| 47.185185 | 202 | 0.69741 | darknight1050 |
c888d8434dbe6267c3226793419b3fb3fcfc39e3 | 3,125 | cpp | C++ | Linked List/Sorting a LL.cpp | hidayat7z/Data-Structures-and-Algorithms | b78fc9c09b55f6ce9e92edeb48b5069792c4341b | [
"MIT"
] | 22 | 2020-09-13T15:12:50.000Z | 2021-01-29T08:29:57.000Z | Linked List/Sorting a LL.cpp | hidayat7z/Data-Structures-and-Algorithms | b78fc9c09b55f6ce9e92edeb48b5069792c4341b | [
"MIT"
] | null | null | null | Linked List/Sorting a LL.cpp | hidayat7z/Data-Structures-and-Algorithms | b78fc9c09b55f6ce9e92edeb48b5069792c4341b | [
"MIT"
] | 6 | 2020-09-13T15:34:38.000Z | 2021-01-29T08:30:01.000Z | #include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *start1= NULL;
struct node *createList(struct node*,int);
void display(struct node*);
struct node *swap(struct node*, struct node*);
struct node *sort(int);
int main()
{
int n,i,val;
printf("Enter the no. of elements of you want in the list: ");
scanf("%d",&n);
printf("Enter the elements of the list--\n");
i=0;
while(i<n)
{
scanf("%d",&val);
start1=createList(start1,val);
i++;
}
display(start1);
printf("\n\n");
start1=sort(n);
display(start1);
}
struct node* createList(struct node *start,int val)
{
struct node *nN,*temp;
nN=(struct node*)malloc(sizeof(struct node));
nN->data=val;
nN->next=NULL;
if(start==NULL)
start=nN;
else
{
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=nN;
}
return start;
}
struct node* sort(int n)
{
struct node *t;
int i=0,j=0,c=0;
while(i<n)
{
c=0; //Optimised Bubble Sort
t=start1;
while(t->next!=NULL)
{
if(t->data > (t->next)->data)
{
c++;
start1=swap(t,t->next);
}
else
{
t=t->next;
}
j++; //to count no. of times the loop runs
display(start1);
}
if(c==0)
break;
i++;
}
printf("\n\n[[Loop ran %d times...]]\n\n",j);
return start1;
}
struct node *swap(struct node *temp1,struct node *temp2)
{
struct node *prevt1,*prevt2,*temp3;
if(temp1==start1)
{
temp1=start1;
}
else
{
prevt1=start1;
while(prevt1->next!=temp1)
{
prevt1=prevt1->next;
}
prevt2=start1;
while(prevt2->next!=temp2)
{
prevt2=prevt2->next;
}
}
if(temp1==start1) //if head node and some other node
{
if(temp1->next==temp2) //adjacent nodes
{
temp1->next=temp2->next;
temp2->next=temp1;
start1=temp2;
}
else
{
start1=start1->next;
temp1->next=temp2->next;
prevt2->next=temp1;
temp2->next=start1;
start1=temp2;
}
}
else if(temp1!= start1 && temp2->next==NULL) //if last node and some other node
{
if(temp1->next==temp2) //adjacent nodes
{
prevt1->next=temp1->next;
temp2->next=temp1;
temp1->next=NULL;
}
else //works for last and first node as well
{
prevt1->next=temp1->next;
prevt2->next=temp1;
temp1->next=NULL;
temp2->next=prevt1->next;
prevt1->next=temp2;
}
}
else
{
if(temp1->next==temp2) //adjacent nodes
{
prevt1->next=temp2;
temp1->next=temp2->next;
temp2->next=temp1;
}
else
{
prevt1->next=temp1->next;
temp1->next=temp2->next;
prevt2->next=temp1;
temp2->next=prevt1->next;
prevt1->next=temp2;
}
}
return start1;
}
void display(struct node *start)
{
struct node *temp;
if(start==NULL)
printf("EMPTY LIST.\n");
else
{
temp=start;
while(temp!=NULL)
{
printf("%d \t",temp->data);
temp=temp->next;
}
printf("\n");
}
}
| 15.625 | 83 | 0.55008 | hidayat7z |
c889ab8f1ce62c843c8327d8a7d1e33e95100dfa | 176 | cpp | C++ | src/core/utils/build/external_template.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | 4 | 2018-09-11T14:27:57.000Z | 2019-12-16T21:06:26.000Z | src/core/utils/build/external_template.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | null | null | null | src/core/utils/build/external_template.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | 2 | 2018-06-11T14:15:30.000Z | 2019-01-09T12:23:35.000Z | #include "precompiled.h"
template class djnnstl::basic_string<char>;
template class djnn::map<djnn::string, djnn::CoreProcess*>;
template class djnn::vector<djnn::Coupling*>;
| 29.333333 | 59 | 0.767045 | lii-enac |
c8913671a099e4122e485136541322089eb68915 | 729 | cpp | C++ | LeetCode/search-BST.cpp | abusomani/DS-Algo | b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba | [
"Unlicense"
] | null | null | null | LeetCode/search-BST.cpp | abusomani/DS-Algo | b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba | [
"Unlicense"
] | null | null | null | LeetCode/search-BST.cpp | abusomani/DS-Algo | b81b592b4ccb6c1c8a1c5275f1411ba4e91977ba | [
"Unlicense"
] | null | null | null | //Sometimes I feel like giving up, then I remember I have a lot of motherfuckers to prove wrong!
//@BEGIN OF SOURCE CODE ( By Abhishek Somani)
#include <bits/stdc++.h>
using namespace std;
// Definition for a binary tree node.
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
TreeNode *searchBST(TreeNode *root, int val)
{
if (root)
{
if (root->val == val)
return root;
else if (root->val > val)
return searchBST(root->left, val);
else
return searchBST(root->right, val);
}
return NULL;
}
}; | 23.516129 | 96 | 0.565158 | abusomani |
c891a4a6ebd43d3530ea74f4aec70387ce79630e | 8,244 | cpp | C++ | extensions/openpower-pels/pldm_interface.cpp | Alpana07/phosphor-logging | 1be39849bd974c2f7df7fa932edcd7f71a2c6d59 | [
"Apache-2.0"
] | 5 | 2017-12-01T19:34:13.000Z | 2020-12-29T10:50:32.000Z | extensions/openpower-pels/pldm_interface.cpp | Alpana07/phosphor-logging | 1be39849bd974c2f7df7fa932edcd7f71a2c6d59 | [
"Apache-2.0"
] | 26 | 2017-02-02T08:20:10.000Z | 2021-11-16T18:28:44.000Z | extensions/openpower-pels/pldm_interface.cpp | Alpana07/phosphor-logging | 1be39849bd974c2f7df7fa932edcd7f71a2c6d59 | [
"Apache-2.0"
] | 28 | 2016-07-20T16:46:54.000Z | 2022-03-16T11:20:03.000Z | /**
* Copyright © 2019 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "pldm_interface.hpp"
#include <libpldm/base.h>
#include <libpldm/file_io.h>
#include <systemd/sd-bus.h>
#include <unistd.h>
#include <fstream>
#include <phosphor-logging/log.hpp>
namespace openpower::pels
{
namespace service
{
constexpr auto pldm = "xyz.openbmc_project.PLDM";
}
namespace object_path
{
constexpr auto pldm = "/xyz/openbmc_project/pldm";
}
namespace interface
{
constexpr auto pldm_requester = "xyz.openbmc_project.PLDM.Requester";
}
using namespace phosphor::logging;
using namespace sdeventplus;
using namespace sdeventplus::source;
constexpr auto eidPath = "/usr/share/pldm/host_eid";
constexpr mctp_eid_t defaultEIDValue = 9;
constexpr uint16_t pelFileType = 0;
PLDMInterface::~PLDMInterface()
{
sd_bus_unref(_bus);
closeFD();
}
void PLDMInterface::closeFD()
{
if (_fd >= 0)
{
close(_fd);
_fd = -1;
}
}
void PLDMInterface::readEID()
{
_eid = defaultEIDValue;
std::ifstream eidFile{eidPath};
if (!eidFile.good())
{
log<level::ERR>("Could not open host EID file");
}
else
{
std::string eid;
eidFile >> eid;
if (!eid.empty())
{
_eid = atoi(eid.c_str());
}
else
{
log<level::ERR>("EID file was empty");
}
}
}
void PLDMInterface::open()
{
_fd = pldm_open();
if (_fd < 0)
{
auto e = errno;
log<level::ERR>("pldm_open failed", entry("ERRNO=%d", e),
entry("RC=%d\n", _fd));
throw std::exception{};
}
}
void PLDMInterface::instanceIDCallback(sd_bus_message* msg)
{
if (!_inProgress)
{
// A cancelCmd was run, just return
log<level::INFO>(
"A command was canceled while waiting for the instance ID");
return;
}
bool failed = false;
auto rc = sd_bus_message_get_errno(msg);
if (rc)
{
log<level::ERR>("GetInstanceId D-Bus method failed",
entry("ERRNO=%d", rc));
failed = true;
}
else
{
uint8_t id;
rc = sd_bus_message_read_basic(msg, 'y', &id);
if (rc < 0)
{
log<level::ERR>("Could not read instance ID out of message",
entry("ERROR=%d", rc));
failed = true;
}
else
{
_instanceID = id;
}
}
if (failed)
{
_inProgress = false;
callResponseFunc(ResponseStatus::failure);
}
else
{
startCommand();
}
}
int iidCallback(sd_bus_message* msg, void* data, sd_bus_error* /*err*/)
{
auto* interface = static_cast<PLDMInterface*>(data);
interface->instanceIDCallback(msg);
return 0;
}
void PLDMInterface::startCommand()
{
try
{
closeFD();
open();
registerReceiveCallback();
doSend();
_receiveTimer.restartOnce(_receiveTimeout);
}
catch (const std::exception& e)
{
cleanupCmd();
callResponseFunc(ResponseStatus::failure);
}
}
void PLDMInterface::startReadInstanceID()
{
auto rc = sd_bus_call_method_async(
_bus, NULL, service::pldm, object_path::pldm, interface::pldm_requester,
"GetInstanceId", iidCallback, this, "y", _eid);
if (rc < 0)
{
log<level::ERR>("Error calling sd_bus_call_method_async",
entry("RC=%d", rc), entry("MSG=%s", strerror(-rc)));
throw std::exception{};
}
}
CmdStatus PLDMInterface::sendNewLogCmd(uint32_t id, uint32_t size)
{
_pelID = id;
_pelSize = size;
_inProgress = true;
try
{
// Kick off the async call to get the instance ID if
// necessary, otherwise start the command itself.
if (!_instanceID)
{
startReadInstanceID();
}
else
{
startCommand();
}
}
catch (const std::exception& e)
{
_inProgress = false;
return CmdStatus::failure;
}
return CmdStatus::success;
}
void PLDMInterface::registerReceiveCallback()
{
_source = std::make_unique<IO>(
_event, _fd, EPOLLIN,
std::bind(std::mem_fn(&PLDMInterface::receive), this,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3));
}
void PLDMInterface::doSend()
{
std::array<uint8_t, sizeof(pldm_msg_hdr) + sizeof(pelFileType) +
sizeof(_pelID) + sizeof(uint64_t)>
requestMsg;
auto request = reinterpret_cast<pldm_msg*>(requestMsg.data());
auto rc = encode_new_file_req(*_instanceID, pelFileType, _pelID, _pelSize,
request);
if (rc != PLDM_SUCCESS)
{
log<level::ERR>("encode_new_file_req failed", entry("RC=%d", rc));
throw std::exception{};
}
rc = pldm_send(_eid, _fd, requestMsg.data(), requestMsg.size());
if (rc < 0)
{
auto e = errno;
log<level::ERR>("pldm_send failed", entry("RC=%d", rc),
entry("ERRNO=%d", e));
throw std::exception{};
}
}
void PLDMInterface::receive(IO& /*io*/, int fd, uint32_t revents)
{
if (!(revents & EPOLLIN))
{
return;
}
uint8_t* responseMsg = nullptr;
size_t responseSize = 0;
ResponseStatus status = ResponseStatus::success;
auto rc = pldm_recv(_eid, fd, *_instanceID, &responseMsg, &responseSize);
if (rc < 0)
{
if (rc == PLDM_REQUESTER_INSTANCE_ID_MISMATCH)
{
// We got a response to someone else's message. Ignore it.
return;
}
else if (rc == PLDM_REQUESTER_NOT_RESP_MSG)
{
// Due to the MCTP loopback, we may get notified of the message
// we just sent.
return;
}
auto e = errno;
log<level::ERR>("pldm_recv failed", entry("RC=%d", rc),
entry("ERRNO=%d", e));
status = ResponseStatus::failure;
responseMsg = nullptr;
}
cleanupCmd();
// Can't use this instance ID anymore.
_instanceID = std::nullopt;
if (status == ResponseStatus::success)
{
uint8_t completionCode = 0;
auto response = reinterpret_cast<pldm_msg*>(responseMsg);
auto decodeRC = decode_new_file_resp(response, PLDM_NEW_FILE_RESP_BYTES,
&completionCode);
if (decodeRC < 0)
{
log<level::ERR>("decode_new_file_resp failed",
entry("RC=%d", decodeRC));
status = ResponseStatus::failure;
}
else
{
if (completionCode != PLDM_SUCCESS)
{
log<level::ERR>("Bad PLDM completion code",
entry("COMPLETION_CODE=%d", completionCode));
status = ResponseStatus::failure;
}
}
}
callResponseFunc(status);
if (responseMsg)
{
free(responseMsg);
}
}
void PLDMInterface::receiveTimerExpired()
{
log<level::ERR>("Timed out waiting for PLDM response");
// Cleanup, but keep the instance ID because the host didn't
// respond so we can still use it.
cleanupCmd();
callResponseFunc(ResponseStatus::failure);
}
void PLDMInterface::cancelCmd()
{
_instanceID = std::nullopt;
cleanupCmd();
}
void PLDMInterface::cleanupCmd()
{
_inProgress = false;
_source.reset();
if (_receiveTimer.isEnabled())
{
_receiveTimer.setEnabled(false);
}
closeFD();
}
} // namespace openpower::pels
| 22.963788 | 80 | 0.574842 | Alpana07 |
c89241cd3ffc7e58eaa6ca180033c710a644f2e4 | 3,641 | cpp | C++ | examples/rgb2hsv.cpp | Bensuo/visioncpp | 8b4233809fbc9f0ad2ee59ec8dfe6de078e44777 | [
"Apache-2.0"
] | 156 | 2016-09-15T13:05:21.000Z | 2022-03-04T01:41:39.000Z | examples/rgb2hsv.cpp | Bensuo/visioncpp | 8b4233809fbc9f0ad2ee59ec8dfe6de078e44777 | [
"Apache-2.0"
] | 24 | 2016-09-20T11:25:23.000Z | 2022-02-01T02:20:27.000Z | examples/rgb2hsv.cpp | Bensuo/visioncpp | 8b4233809fbc9f0ad2ee59ec8dfe6de078e44777 | [
"Apache-2.0"
] | 58 | 2016-09-15T14:08:28.000Z | 2022-02-28T04:55:55.000Z | // This file is part of VisionCpp, a lightweight C++ template library
// for computer vision and image processing.
//
// Copyright (C) 2016 Codeplay Software Limited. All Rights Reserved.
//
// Contact: visioncpp@codeplay.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.
/// \file rgb2hsv.cc
///
/// -------Example--------
/// RGB -> HSV
/// \brief this example convert an RGB pixel to HSV
// include VisionCpp
#include <visioncpp.hpp>
int main(int argc, char *argv[]) {
if (argc < 4) {
std::cout << "You need to provide 3 uchar values" << std::endl;
std::cout << "example>: ./example_rgb2hsv 100 13 145" << std::endl;
return -1;
}
// where VisionCpp will run.
auto dev = visioncpp::make_device<visioncpp::backend::sycl,
visioncpp::device::cpu>();
// create a host container for input data
std::shared_ptr<unsigned char> in_rgb(
new unsigned char[3], [](unsigned char *dataMem) { delete[] dataMem; });
in_rgb.get()[0] = atoi(argv[1]);
in_rgb.get()[1] = atoi(argv[2]);
in_rgb.get()[2] = atoi(argv[3]);
// create a host container for output data
std::shared_ptr<unsigned char> out_hsv(
new unsigned char[3], [](unsigned char *dataMem) { delete[] dataMem; });
// exiting this scope will sync data
{
// definition of the VisionCpp pipeline:
// create terminal nodes - a leaf node ( data node ) of the expression tree.
// terminal struct takes 4 arguments
// 1st template parameter specifies the data U8 (unsigned char) C3 (three
// channels)
// 2nd: the number of columns in the storage
// 3rd: the number of rows in the storage
// 4th: the underlying storage type - currently only Buffer2D supported
auto data =
visioncpp::terminal<visioncpp::pixel::U8C3, 1, 1,
visioncpp::memory_type::Buffer2D>(in_rgb.get());
auto data_out =
visioncpp::terminal<visioncpp::pixel::U8C3, 1, 1,
visioncpp::memory_type::Buffer2D>(out_hsv.get());
// unsigned char -> float RGB storage conversion
auto node = visioncpp::point_operation<visioncpp::OP_U8C3ToF32C3>(data);
// float RGB to float HSV conversion
auto node2 = visioncpp::point_operation<visioncpp::OP_RGBToHSV>(node);
// helper node that allows display of HSV
// for unsigned char: V <- 255*V, S <- 255*S, H <- H/2 ( to fit in range of
// 0..255 )
auto node3 = visioncpp::point_operation<visioncpp::OP_HSVToU8C3>(node2);
// assign operation that writes output of the pipe to output terminal node
auto pipe = visioncpp::assign(data_out, node3);
// execute the pipeline
// 1st template parameter defines if VisionCpp back-end fuses the expression
// 2nd & 3rd shared memory sizes ( column, row )
// 4th & 5th local work group size ( column , row )
visioncpp::execute<visioncpp::policy::Fuse, 1, 1, 1, 1>(pipe, dev);
}
printf("RGB: %u %u %u \nHSV: %u %u %u \n", in_rgb.get()[0], in_rgb.get()[1],
in_rgb.get()[2], out_hsv.get()[0], out_hsv.get()[1], out_hsv.get()[2]);
return 0;
}
| 39.150538 | 80 | 0.650096 | Bensuo |
c89881ac919d7a172dcf68afd9e39961f89368ac | 9,654 | cpp | C++ | src/peco/task/impl/loopimpl.cpp | littlepush/libpeco | c0ca92ddb7a70cd8183ade1ee0ec57fd534e280e | [
"MIT"
] | 1 | 2020-04-14T06:31:56.000Z | 2020-04-14T06:31:56.000Z | src/peco/task/impl/loopimpl.cpp | littlepush/libpeco | c0ca92ddb7a70cd8183ade1ee0ec57fd534e280e | [
"MIT"
] | null | null | null | src/peco/task/impl/loopimpl.cpp | littlepush/libpeco | c0ca92ddb7a70cd8183ade1ee0ec57fd534e280e | [
"MIT"
] | null | null | null | /*
loopimpl.cpp
libpeco
2022-02-12
Push Chen
*/
/*
MIT License
Copyright (c) 2019 Push Chen
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 "peco/task/impl/loopimpl.hxx"
namespace peco {
/**
* @brief Default C'str
*/
loopimpl::loopimpl() {
}
/**
* @brief Singleton loopimpl
*/
loopimpl& loopimpl::shared() {
thread_local static loopimpl s_impl;
return s_impl;
}
/**
* @brief Tell if current loop is running
*/
bool loopimpl::is_running() const {
return running_;
}
/**
* @brief Entrypoint
*/
void loopimpl::main() {
// Invoke base init(which is platform-related)
this->init(
[=](long fd) {
auto id_list = this->timed_list_.search_all(fd);
// erase task related with this fd
this->timed_list_.erase(fd);
for (const auto& tid : id_list) {
auto ptrt = basic_task::fetch(tid);
if (ptrt) {
ptrt->get_task()->signal = kWaitingSignalBroken;
ptrt->get_task()->next_fire_time = TASK_TIME_NOW();
// Run this task in next loop
this->timed_list_.insert(ptrt, nullptr);
}
}
},
[=](long fd, EventType event_type) {
auto id_list = this->timed_list_.search(fd, event_type);
for (const auto& tid: id_list) {
auto ptrt = basic_task::fetch(tid);
this->timed_list_.erase(ptrt, fd, event_type);
if (ptrt) {
ptrt->get_task()->signal = kWaitingSignalReceived;
ptrt->get_task()->next_fire_time = TASK_TIME_NOW();
// Run this task in next loop
this->timed_list_.insert(ptrt, nullptr);
}
}
});
running_ = true;
begin_time_ = TASK_TIME_NOW();
while (basic_task::cache_size() > 0) {
while (this->timed_list_.size() > 0 && TASK_TIME_NOW() >= this->timed_list_.nearest_time()) {
auto result = this->timed_list_.fetch();
if (result.on_time) {
result.on_time();
}
auto ptrt = basic_task::fetch(result.tid);
// Switch to the task
ptrt->swap_to_task();
if (ptrt->status() == kTaskStatusStopped) {
ptrt->destroy_task();
} else if (ptrt->status() == kTaskStatusPending) {
this->timed_list_.insert(ptrt, nullptr);
}
}
// after all timed task's executing, if there is no
// cached task, stop the loop
if (basic_task::cache_size() == 0) break;
// Someone stop the loop, should cancel all task
if (!running_) {
// Mark all task to be cancelled
basic_task::foreach([=](std::shared_ptr<basic_task> ptrt) {
this->cancel(ptrt);
});
continue;
}
auto idle_gap = (this->timed_list_.size() > 0 ?
(this->timed_list_.nearest_time() - TASK_TIME_NOW()) :
PECO_TIME_MS(1000));
if (idle_gap.count() < 0) continue;
// wait fd event until idle_gap
this->wait(idle_gap);
}
// force to stop if we break from last while loop
this->stop();
}
/**
* @brief Exit with given code
*/
void loopimpl::exit(int code) {
exit_code_ = code;
running_ = false;
this->stop();
}
/**
* @brief Get the load average of current loop
*/
double loopimpl::load_average() const {
return 1.0 - ((double)this->get_wait_time() / (double)(TASK_TIME_NOW() - begin_time_).count());
}
/**
* @brief Get the exit code
*/
int loopimpl::exit_code() const {
return exit_code_;
}
/**
* @brief Just add a task to the timed list
*/
void loopimpl::add_task(std::shared_ptr<basic_task> ptrt) {
if (ptrt == nullptr) return;
assert(ptrt->status() != kTaskStatusStopped);
ptrt->get_task()->status = kTaskStatusPaused;
this->timed_list_.insert(ptrt, nullptr);
}
/**
* @brief Yield a task
*/
void loopimpl::yield_task(std::shared_ptr<basic_task> ptrt) {
if (ptrt == nullptr) return;
// only running task can be holded
assert(ptrt->task_id() == basic_task::running_task()->task_id());
ptrt->get_task()->next_fire_time = TASK_TIME_NOW();
ptrt->get_task()->status = kTaskStatusPaused;
this->timed_list_.insert(ptrt, nullptr);
basic_task::swap_to_main();
}
/**
* @brief Hold the task, put the task into never-check list
*/
void loopimpl::hold_task(std::shared_ptr<basic_task> ptrt) {
if (ptrt == nullptr) return;
// only running task can be holded
assert(ptrt->task_id() == basic_task::running_task()->task_id());
// This task will only remain in basic task's cache,
// unless someone keep the task_id and wakeup it.
ptrt->get_task()->signal = kWaitingSignalNothing;
// if the task has already been marked as canceled,
// just return, not allowed to be holded.
if (ptrt->get_task()->cancelled) {
ptrt->get_task()->signal = kWaitingSignalBroken;
return;
}
ptrt->get_task()->status = kTaskStatusPaused;
basic_task::swap_to_main();
}
/**
* @brief Hold the task, wait until timedout
* if waked up before timedout, the signal will be received
*/
void loopimpl::hold_task_for(std::shared_ptr<basic_task> ptrt, duration_t timedout) {
if (ptrt == nullptr) return;
// only running task can be holded
assert(ptrt->task_id() == basic_task::running_task()->task_id());
ptrt->get_task()->signal = kWaitingSignalNothing;
// if the task has already been marked as canceled,
// just return, not allowed to be holded.
if (ptrt->get_task()->cancelled) {
ptrt->get_task()->signal = kWaitingSignalBroken;
return;
}
ptrt->get_task()->next_fire_time = (TASK_TIME_NOW() + timedout);
ptrt->get_task()->status = kTaskStatusPaused;
this->timed_list_.insert(ptrt, nullptr);
basic_task::swap_to_main();
}
/**
* @brief brief
*/
void loopimpl::wakeup_task(std::shared_ptr<basic_task> ptrt, WaitingSignal signal) {
if (ptrt == nullptr) return;
// Make the given task validate again
assert(
(!basic_task::running_task()) ||
(ptrt->task_id() != basic_task::running_task()->task_id())
);
ptrt->get_task()->signal = signal;
if (this->timed_list_.has(ptrt)) {
this->timed_list_.replace_time(ptrt, TASK_TIME_NOW());
} else {
this->timed_list_.insert(ptrt, nullptr);
}
}
/**
* @brief Monitor the fd for reading event and put the task into
* timed list with a timedout handler
*/
void loopimpl::wait_for_reading(long fd, std::shared_ptr<basic_task> ptrt, duration_t timedout) {
if (ptrt == nullptr) return;
// if the task has already been marked as canceled,
// just return, not allowed to be holded.
if (ptrt->get_task()->cancelled) {
ptrt->get_task()->signal = kWaitingSignalBroken;
return;
}
ptrt->get_task()->signal = kWaitingSignalNothing;
ptrt->get_task()->status = kTaskStatusPaused;
ptrt->get_task()->next_fire_time = (TASK_TIME_NOW() + timedout);
this->timed_list_.insert(ptrt, [=]() {
this->timed_list_.erase(ptrt, fd);
this->del_read_event(fd);
if (ptrt->get_task()->cancelled) {
ptrt->get_task()->signal = kWaitingSignalBroken;
}
}, fd, kEventTypeRead);
this->add_read_event(fd);
basic_task::swap_to_main();
}
/**
* @brief Monitor the fd for writing buffer and put the task into
* timed list with a timedout handler
*/
void loopimpl::wait_for_writing(long fd, std::shared_ptr<basic_task> ptrt, duration_t timedout) {
if (ptrt == nullptr) return;
// if the task has already been marked as canceled,
// just return, not allowed to be holded.
if (ptrt->get_task()->cancelled) {
ptrt->get_task()->signal = kWaitingSignalBroken;
return;
}
ptrt->get_task()->signal = kWaitingSignalNothing;
ptrt->get_task()->status = kTaskStatusPaused;
ptrt->get_task()->next_fire_time = (TASK_TIME_NOW() + timedout);
this->timed_list_.insert(ptrt, [=]() {
this->timed_list_.erase(ptrt, fd);
this->del_write_event(fd);
if (ptrt->get_task()->cancelled) {
ptrt->get_task()->signal = kWaitingSignalBroken;
}
}, fd, kEventTypeWrite);
this->add_write_event(fd);
basic_task::swap_to_main();
}
/**
* @brief Cancel a repeatable or delay task
* If a task is running, will wakeup and set the status to cancel
*/
void loopimpl::cancel(std::shared_ptr<basic_task> ptrt) {
if (ptrt == nullptr) return;
// The task is already been marked as cancelled, do nothing
if (ptrt->get_task()->cancelled) return;
ptrt->get_task()->cancelled = true;
// Cancel self
if (basic_task::running_task() == ptrt) {
// Means the task is not in the timed_list and not holding
// we dont need to do anything
return;
}
// The task is just been holded, force to wakeup
if (!this->timed_list_.has(ptrt)) {
this->wakeup_task(ptrt, kWaitingSignalBroken);
} else {
// Mark the task's next fire time to now, force all pending
// event to be timedout
this->timed_list_.replace_time(ptrt, TASK_TIME_NOW());
}
}
} // namespace peco
| 30.647619 | 97 | 0.672985 | littlepush |
c89c334baa1f7025bf4ac08852dc2cd7505e1d7f | 444 | cc | C++ | networking/packet_handlers/unknown_packet_handler.cc | RikoOphorst/Tremble | 650fa53402f9c6114642e0cc8515b2ed517d40d6 | [
"MIT"
] | 1 | 2021-10-17T06:41:46.000Z | 2021-10-17T06:41:46.000Z | networking/packet_handlers/unknown_packet_handler.cc | RikoOphorst/Tremble | 650fa53402f9c6114642e0cc8515b2ed517d40d6 | [
"MIT"
] | null | null | null | networking/packet_handlers/unknown_packet_handler.cc | RikoOphorst/Tremble | 650fa53402f9c6114642e0cc8515b2ed517d40d6 | [
"MIT"
] | null | null | null | //#include "unknown_packet_handler.h"
//#include <iostream>
//
//using namespace networking;
//
//UnknownPacketHandler::UnknownPacketHandler(NetworkController & net_controller) : IPacketHandler(net_controller)
//{
//}
//
//UnknownPacketHandler::~UnknownPacketHandler()
//{
//}
//
//void UnknownPacketHandler::Handle(int packet_id, RakNet::Packet* packet)
//{
// std::cout << "Received unknown packet id: " << packet_id << "." << std::endl;
//}
| 24.666667 | 113 | 0.707207 | RikoOphorst |
c8a3fe8757fd21ba2c56f472f3a0a54a86a4fefd | 1,219 | cpp | C++ | source/SoloFeature.cpp | rammid1189/STAR | 75461e7e1a4a315e6dde87c85317e3f67e8d7a98 | [
"MIT"
] | 1 | 2020-04-29T12:37:20.000Z | 2020-04-29T12:37:20.000Z | source/SoloFeature.cpp | alexey0308/STAR | eb9b28f869ba82cdfcc45c6f76c53513e25f1fcc | [
"MIT"
] | null | null | null | source/SoloFeature.cpp | alexey0308/STAR | eb9b28f869ba82cdfcc45c6f76c53513e25f1fcc | [
"MIT"
] | null | null | null | #include "SoloFeature.h"
#include "streamFuns.h"
#include "ErrorWarning.h"
SoloFeature::SoloFeature(int32 feTy, Parameters &Pin, Transcriptome &inTrans, SoloReadBarcode *readBarSumIn, SoloFeature **soloFeatAll)
:featureType(feTy), P(Pin), Trans(inTrans), soloFeatAll(soloFeatAll), pSolo(P.pSolo), readBarSum(readBarSumIn)
{
readFeatSum = new SoloReadFeature(featureType,P,-1);
readFeatAll = new SoloReadFeature*[P.runThreadN];
if (pSolo.type==0)
return;
outputPrefix=P.outFileNamePrefix+pSolo.outFileNames[0];
outputPrefix += SoloFeatureTypes::Names[featureType] +'/';
if (mkdir(outputPrefix.c_str(),P.runDirPerm)!=0 && errno!=EEXIST) {//create directory
ostringstream errOut;
errOut << "EXITING because of fatal OUTPUT FILE error: could not create Solo output directory"<<outputPrefix<<"\n";
errOut << "SOLUTION: check the path and permisssions";
exitWithError(errOut.str(),std::cerr, P.inOut->logMain, EXIT_CODE_PARAMETER, P);
};
if (featureType==SoloFeatureTypes::Transcript3p) {//for now - open output file
streamTranscriptsOut = &ofstrOpen(outputPrefix+"transcriptCbUmiIndexDistance.txt",ERROR_OUT, P);
};
};
| 43.535714 | 135 | 0.707957 | rammid1189 |
c8a6c5d326cd4726e9f91cbe381d4dda1c4d47e8 | 3,020 | cpp | C++ | alignmut/restable.cpp | sferanchuk/tbev | 71e62ae093719aa0e0de4708e87e589129b44f96 | [
"MIT"
] | null | null | null | alignmut/restable.cpp | sferanchuk/tbev | 71e62ae093719aa0e0de4708e87e589129b44f96 | [
"MIT"
] | null | null | null | alignmut/restable.cpp | sferanchuk/tbev | 71e62ae093719aa0e0de4708e87e589129b44f96 | [
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <set>
#include <map>
using namespace std;
int main( int argc, char **argv )
{
vector< vector< string > > table;
vector<int> mut;
vector< string > ids;
vector< map<string,int> > other;
vector<int> lcvec;
int fcnt = 1;
do
{
char nbuf[32];
sprintf( nbuf, "res_%d.xml", fcnt );
fcnt++;
FILE *ifile = fopen( nbuf, "rt" );
if ( !ifile ) break;
const int nkeys = 7;
const char *key[] = { "<Pos>", "<SPos>", "<Letter>", "<Percent>", "<LCount>", "<Other>", "<Ids>" };
char buf[4096];
int lc = 0;
while ( fgets( buf, 4096, ifile ) )
{
if ( !strstr( buf, "<Line>" ) ) continue;
vector<string> fields;
for ( int kc = 0; kc < nkeys; kc++ )
{
char *v = strstr( buf, key[kc] ) + strlen( key[kc] );
fields.push_back( string( v, 0, strcspn( v, "<" ) ) );
}
if ( table.size() <= lc )
{
table.resize( lc + 1 );
ids.resize( lc + 1 );
other.resize( lc + 1 );
lcvec.resize( lc + 1, 0 );
table[lc].push_back( fields[0] );
table[lc].push_back( fields[1] );
table[lc].push_back( fields[2] );
}
table[lc].push_back( fields[3] );
if ( mut.size() <= lc ) mut.resize( lc + 1, 0 );
int lcount = atoi( fields[4].data() );
if ( lcount == 0 ) mut[ lc ] = 10;
else mut[lc] += int( lcount * ( 100 - atof( fields[3].data() ) ) * 0.01 + 0.3 );
ids[lc].append( fields[6] );
char nbuf[256];
strcpy( nbuf, fields[5].data() );
for ( char *p = strtok( nbuf, " \t" ); p; p = strtok( 0, " \t" ) )
{
string clet = p;
double f = atof( strtok( 0, " \t" ) );
other[lc][ clet ] += f * lcount * 0.01 + 0.4;
}
lcvec[lc] += lcount;
lc++;
}
}
while ( 1 );
printf( "<html><body><table>" );
for ( int lc = 0; lc < table.size(); lc++ )
{
printf( "<tr>" );
for ( int fc = 0; fc < table[lc].size(); fc++ ) printf( "<td>%s", table[lc][fc].data() );
char symb[4] = ".";
if ( mut[lc] == 0 ) strcpy( symb, "*" );
else if ( mut[lc] < 3 ) sprintf( symb, "%d", mut[lc] );
printf( "<td>%s<td>", symb );
multimap<int,string> rother;
for ( map<string,int>::iterator it = other[lc].begin(); it != other[lc].end(); it++ ) rother.insert( pair<int,string>( it->second, it->first ) );
for ( multimap<int,string>::reverse_iterator it = rother.rbegin(); it != rother.rend(); it++ ) printf( "%s %d; ", it->second.data(), it->first );
printf( "<td>" );
set<string> cids;
char buf[4096];
strcpy( buf, ids[lc].data() );
set<string> sids;
for ( char *p = strtok( buf, " " ); p; p = strtok( 0, " " ) ) sids.insert( p );
int ocnt = 0;
for ( set<string>::iterator it = sids.begin(); it != sids.end() && ocnt < 3; it++, ocnt++ )
{
vector<string> idi;
char nbuf[256];
strcpy( nbuf, it->data() );
for ( char *p = strtok( nbuf, "|" ); p; p = strtok( 0, "|" ) ) idi.push_back( p );
printf( "%s ", idi.back().data() );
}
printf( "\n" );
}
printf( "</table></body></html>" );
return 0;
}
| 29.320388 | 147 | 0.527152 | sferanchuk |
c8a709c0f8f841becae522a2b9d2e2fec7be4345 | 5,900 | cpp | C++ | c-src/Fl_Paged_DeviceC.cpp | ericu/fltkhs | 3ca521ca30d51a84f8ec87938932f2ce5af8a7c0 | [
"MIT"
] | 222 | 2015-01-11T19:01:16.000Z | 2022-03-25T14:47:26.000Z | c-src/Fl_Paged_DeviceC.cpp | ericu/fltkhs | 3ca521ca30d51a84f8ec87938932f2ce5af8a7c0 | [
"MIT"
] | 143 | 2015-01-13T19:08:33.000Z | 2021-10-10T20:43:46.000Z | c-src/Fl_Paged_DeviceC.cpp | ericu/fltkhs | 3ca521ca30d51a84f8ec87938932f2ce5af8a7c0 | [
"MIT"
] | 36 | 2015-01-14T15:30:18.000Z | 2021-08-11T13:04:28.000Z | #include "Fl_Paged_DeviceC.h"
#ifdef __cplusplus
EXPORT {
#endif
FL_EXPORT_C(void,Fl_Paged_Device_set_current)(fl_Paged_Device paged_device){
return (static_cast<Fl_Paged_Device*>(paged_device))->set_current();
}
FL_EXPORT_C(fl_Surface_Device,Fl_Paged_Device_surface)(){
return (fl_Surface_Device)Fl_Surface_Device::surface();
}
FL_EXPORT_C(int,Fl_Paged_Device_start_job)(fl_Paged_Device paged_device,int pagecount){
return (static_cast<Fl_Paged_Device*>(paged_device))->start_job(pagecount);
}
FL_EXPORT_C(int,Fl_Paged_Device_start_job_with_frompage)(fl_Paged_Device paged_device,int pagecount,int* frompage){
return (static_cast<Fl_Paged_Device*>(paged_device))->start_job(pagecount,frompage);
}
FL_EXPORT_C(int,Fl_Paged_Device_start_job_with_topage)(fl_Paged_Device paged_device,int pagecount,int* topage){
return (static_cast<Fl_Paged_Device*>(paged_device))->start_job(pagecount,NULL,topage);
}
FL_EXPORT_C(int,Fl_Paged_Device_start_job_with_frompage_topage)(fl_Paged_Device paged_device,int pagecount,int* frompage,int* topage){
return (static_cast<Fl_Paged_Device*>(paged_device))->start_job(pagecount,frompage,topage);
}
FL_EXPORT_C(int,Fl_Paged_Device_start_page)(fl_Paged_Device paged_device){
return (static_cast<Fl_Paged_Device*>(paged_device))->start_page();
}
FL_EXPORT_C(int,Fl_Paged_Device_printable_rect)(fl_Paged_Device paged_device,int* w,int* h){
return (static_cast<Fl_Paged_Device*>(paged_device))->printable_rect(w,h);
}
FL_EXPORT_C(void,Fl_Paged_Device_margins)(fl_Paged_Device paged_device,int* left,int* top,int* right,int* bottom){
(static_cast<Fl_Paged_Device*>(paged_device))->margins(left,top,right,bottom);
}
FL_EXPORT_C(void,Fl_Paged_Device_origin)(fl_Paged_Device paged_device,int* x,int* y){
(static_cast<Fl_Paged_Device*>(paged_device))->origin(x,y);
}
FL_EXPORT_C(void,Fl_Paged_Device_scale)(fl_Paged_Device paged_device,float scale_x){
(static_cast<Fl_Paged_Device*>(paged_device))->scale(scale_x);
}
FL_EXPORT_C(void,Fl_Paged_Device_scale_with_scaly_y)(fl_Paged_Device paged_device,float scale_x,float scale_y){
(static_cast<Fl_Paged_Device*>(paged_device))->scale(scale_x,scale_y);
}
FL_EXPORT_C(void,Fl_Paged_Device_rotate)(fl_Paged_Device paged_device,float angle){
(static_cast<Fl_Paged_Device*>(paged_device))->rotate(angle);
}
FL_EXPORT_C(void,Fl_Paged_Device_translate)(fl_Paged_Device paged_device,int x,int y){
(static_cast<Fl_Paged_Device*>(paged_device))->translate(x,y);
}
FL_EXPORT_C(void,Fl_Paged_Device_untranslate)(fl_Paged_Device paged_device){
(static_cast<Fl_Paged_Device*>(paged_device))->untranslate();
}
FL_EXPORT_C(void,Fl_Paged_Device_print_widget)(fl_Paged_Device paged_device,fl_Widget widget){
(static_cast<Fl_Paged_Device*>(paged_device))->print_widget(static_cast<Fl_Widget*>(widget));
}
FL_EXPORT_C(void,Fl_Paged_Device_print_widget_with_delta_x)(fl_Paged_Device paged_device,fl_Widget widget,int delta_x){
(static_cast<Fl_Paged_Device*>(paged_device))->print_widget(static_cast<Fl_Widget*>(widget),delta_x);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_widget_with_delta_y)(fl_Paged_Device paged_device,fl_Widget widget,int delta_y){
(static_cast<Fl_Paged_Device*>(paged_device))->print_widget(static_cast<Fl_Widget*>(widget),0,delta_y);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_widget_with_delta_x_delta_y)(fl_Paged_Device paged_device,fl_Widget widget,int delta_x,int delta_y){
(static_cast<Fl_Paged_Device*>(paged_device))->print_widget(static_cast<Fl_Widget*>(widget),delta_x,delta_y);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window)(fl_Paged_Device paged_device,fl_Window win){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window(static_cast<Fl_Window*>(win));
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window_with_x_offset)(fl_Paged_Device paged_device,fl_Window win,int x_offset){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window(static_cast<Fl_Window*>(win),x_offset);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window_with_y_offset)(fl_Paged_Device paged_device,fl_Window win,int y_offset){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window(static_cast<Fl_Window*>(win),y_offset);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window_with_x_offset_y_offset)(fl_Paged_Device paged_device,fl_Window win,int x_offset,int y_offset){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window(static_cast<Fl_Window*>(win),x_offset,y_offset);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window_part)(fl_Paged_Device paged_device,fl_Window win,int x,int y,int w,int h){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window_part(static_cast<Fl_Window*>(win),x,y,w,h);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window_part_with_delta_x)(fl_Paged_Device paged_device,fl_Window win,int x,int y,int w,int h,int delta_x){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window_part(static_cast<Fl_Window*>(win),x,y,w,h,delta_x);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window_part_with_delta_y)(fl_Paged_Device paged_device,fl_Window win,int x,int y,int w,int h,int delta_y){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window_part(static_cast<Fl_Window*>(win),x,y,w,h,0,delta_y);
}
FL_EXPORT_C(void,Fl_Paged_Device_print_window_part_with_delta_xy)(fl_Paged_Device paged_device,fl_Window win,int x,int y,int w,int h,int delta_x,int delta_y){
(static_cast<Fl_Paged_Device*>(paged_device))->print_window_part(static_cast<Fl_Window*>(win),x,y,w,h,delta_x,delta_y);
}
FL_EXPORT_C(int,Fl_Paged_Device_end_page)(fl_Paged_Device paged_device){
return (static_cast<Fl_Paged_Device*>(paged_device))->end_page();
}
FL_EXPORT_C(void,Fl_Paged_Device_end_job)(fl_Paged_Device paged_device){
(static_cast<Fl_Paged_Device*>(paged_device))->end_job();
}
#ifdef __cplusplus
}
#endif
| 62.105263 | 160 | 0.80322 | ericu |
c8a7b8d8387e470634834f5a8a8b65415c370361 | 1,598 | hpp | C++ | source/boost/simd/arch/common/generic/function/genmask.hpp | chronos38/low_latency_demo | de0d0d3dcebff23ba77c06c6c368b9d1c3d2c648 | [
"MIT"
] | 3 | 2017-11-18T18:23:16.000Z | 2019-02-15T12:41:24.000Z | include/boost/simd/arch/common/generic/function/genmask.hpp | dendisuhubdy/boost.simd | 7630b1c1ffbd0300c100885b89ff78c2d579a24c | [
"BSL-1.0"
] | null | null | null | include/boost/simd/arch/common/generic/function/genmask.hpp | dendisuhubdy/boost.simd | 7630b1c1ffbd0300c100885b89ff78c2d579a24c | [
"BSL-1.0"
] | 1 | 2019-04-11T20:18:39.000Z | 2019-04-11T20:18:39.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_GENMASK_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_GENMASK_HPP_INCLUDED
#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/meta/as_arithmetic.hpp>
#include <boost/simd/constant/allbits.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/config.hpp>
namespace boost { namespace simd { namespace ext
{
namespace bd = boost::dispatch;
namespace bs = boost::simd;
// -----------------------------------------------------------------------------------------------
// re-targeted genmask for other types
BOOST_DISPATCH_OVERLOAD ( genmask_
, (typename A0, typename Target)
, bd::cpu_
, bd::scalar_< bd::unspecified_<A0> >
, bd::target_< bd::generic_<bd::unspecified_<Target> > >
)
{
using result_t = typename Target::type;
BOOST_FORCEINLINE result_t operator()( A0 const& a0, Target const& ) const BOOST_NOEXCEPT
{
return (a0!=0) ? Allbits<result_t>() : Zero<result_t>();
}
};
} } }
#endif
| 36.318182 | 100 | 0.539424 | chronos38 |
c8a8725ed614bcf63b701b3d956082746cd92963 | 8,394 | cpp | C++ | src/behaviortree/nodes/composites/parallel.cpp | zja147/behaviac | 2e9c53c8368cf451139d50db01276e3f9da78733 | [
"BSD-3-Clause"
] | null | null | null | src/behaviortree/nodes/composites/parallel.cpp | zja147/behaviac | 2e9c53c8368cf451139d50db01276e3f9da78733 | [
"BSD-3-Clause"
] | null | null | null | src/behaviortree/nodes/composites/parallel.cpp | zja147/behaviac | 2e9c53c8368cf451139d50db01276e3f9da78733 | [
"BSD-3-Clause"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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 "behaviac/common/base.h"
#include "behaviac/behaviortree/nodes/composites/parallel.h"
#include "behaviac/htn/planner.h"
#include "behaviac/htn/plannertask.h"
namespace behaviac {
Parallel::Parallel() : m_failPolicy(FAIL_ON_ONE), m_succeedPolicy(SUCCEED_ON_ALL), m_exitPolicy(EXIT_NONE), m_childFinishPolicy(CHILDFINISH_LOOP)
{}
Parallel::~Parallel()
{}
#if BEHAVIAC_USE_HTN
bool Parallel::decompose(BehaviorNode* node, PlannerTaskComplex* seqTask, int depth, Planner* planner) {
bool bOk = false;
Parallel* parallel = (Parallel*)node;// as Parallel;
int childCount = parallel->GetChildrenCount();
int i = 0;
for (; i < childCount; ++i) {
BehaviorNode* childNode = (BehaviorNode*)parallel->GetChild(i);
PlannerTask* childTask = planner->decomposeNode(childNode, depth);
if (childTask == NULL) {
break;
}
seqTask->AddChild(childTask);
}
if (i == childCount) {
bOk = true;
}
return bOk;
}
#endif
bool Parallel::IsValid(Agent* pAgent, BehaviorTask* pTask) const {
if (!Parallel::DynamicCast(pTask->GetNode())) {
return false;
}
return super::IsValid(pAgent, pTask);
}
BehaviorTask* Parallel::createTask() const {
ParallelTask* pTask = BEHAVIAC_NEW ParallelTask();
return pTask;
}
bool Parallel::IsManagingChildrenAsSubTrees() const {
return true;
}
EBTStatus Parallel::ParallelUpdate(Agent* pAgent, behaviac::vector<BehaviorTask*> children) {
bool sawSuccess = false;
bool sawFail = false;
bool sawRunning = false;
bool sawAllFails = true;
bool sawAllSuccess = true;
bool bLoop = (this->m_childFinishPolicy == CHILDFINISH_LOOP);
// go through all m_children
for (uint32_t i = 0; i < children.size(); ++i) {
BehaviorTask* pChild = children[i];
EBTStatus treeStatus = pChild->GetStatus();
if (bLoop || (treeStatus == BT_RUNNING || treeStatus == BT_INVALID)) {
EBTStatus status = pChild->exec(pAgent);
if (status == BT_FAILURE) {
sawFail = true;
sawAllSuccess = false;
} else if (status == BT_SUCCESS) {
sawSuccess = true;
sawAllFails = false;
} else if (status == BT_RUNNING) {
sawRunning = true;
sawAllFails = false;
sawAllSuccess = false;
}
} else if (treeStatus == BT_SUCCESS) {
sawSuccess = true;
sawAllFails = false;
} else {
BEHAVIAC_ASSERT(treeStatus == BT_FAILURE);
sawFail = true;
sawAllSuccess = false;
}
}
EBTStatus result = sawRunning ? BT_RUNNING : BT_FAILURE;
if ((this->m_failPolicy == FAIL_ON_ALL && sawAllFails) ||
(this->m_failPolicy == FAIL_ON_ONE && sawFail)) {
result = BT_FAILURE;
} else if ((this->m_succeedPolicy == SUCCEED_ON_ALL && sawAllSuccess) ||
(this->m_succeedPolicy == SUCCEED_ON_ONE && sawSuccess)) {
result = BT_SUCCESS;
}
if (this->m_exitPolicy == EXIT_ABORT_RUNNINGSIBLINGS && (result == BT_FAILURE || result == BT_SUCCESS)) {
for (uint32_t i = 0; i < children.size(); ++i) {
BehaviorTask* pChild = children[i];
//BEHAVIAC_ASSERT(BehaviorTreeTask.DynamicCast(pChild));
EBTStatus treeStatus = pChild->GetStatus();
if (treeStatus == BT_RUNNING) {
pChild->abort(pAgent);
}
}
}
return result;
}
void Parallel::load(int version, const char* agentType, const properties_t& properties) {
super::load(version, agentType, properties);
for (propertie_const_iterator_t it = properties.begin(); it != properties.end(); ++it) {
const property_t& p = (*it);
if (StringUtils::StringEqual(p.name, "FailurePolicy")) {
if (StringUtils::StringEqual(p.value, "FAIL_ON_ONE")) {
this->m_failPolicy = FAIL_ON_ONE;
} else if (StringUtils::StringEqual(p.value, "FAIL_ON_ALL")) {
this->m_failPolicy = FAIL_ON_ALL;
} else {
BEHAVIAC_ASSERT(0);
}
} else if (StringUtils::StringEqual(p.name, "SuccessPolicy")) {
if (StringUtils::StringEqual(p.value, "SUCCEED_ON_ONE")) {
this->m_succeedPolicy = SUCCEED_ON_ONE;
} else if (StringUtils::StringEqual(p.value, "SUCCEED_ON_ALL")) {
this->m_succeedPolicy = SUCCEED_ON_ALL;
} else {
BEHAVIAC_ASSERT(0);
}
} else if (StringUtils::StringEqual(p.name, "ExitPolicy")) {
if (StringUtils::StringEqual(p.value, "EXIT_NONE")) {
this->m_exitPolicy = EXIT_NONE;
} else if (StringUtils::StringEqual(p.value, "EXIT_ABORT_RUNNINGSIBLINGS")) {
this->m_exitPolicy = EXIT_ABORT_RUNNINGSIBLINGS;
} else {
BEHAVIAC_ASSERT(0);
}
} else if (StringUtils::StringEqual(p.name, "ChildFinishPolicy")) {
if (StringUtils::StringEqual(p.value, "CHILDFINISH_ONCE")) {
this->m_childFinishPolicy = CHILDFINISH_ONCE;
} else if (StringUtils::StringEqual(p.value, "CHILDFINISH_LOOP")) {
this->m_childFinishPolicy = CHILDFINISH_LOOP;
} else {
BEHAVIAC_ASSERT(0);
}
} else {
//BEHAVIAC_ASSERT(0);
}
}
}
ParallelTask::ParallelTask() : CompositeTask() {
}
ParallelTask::~ParallelTask() {
for (BehaviorTasks_t::iterator it = this->m_children.begin(); it != this->m_children.end(); ++it) {
BEHAVIAC_DELETE(*it);
}
this->m_children.clear();
}
void ParallelTask::Init(const BehaviorNode* node) {
super::Init(node);
}
void ParallelTask::copyto(BehaviorTask* target) const {
super::copyto(target);
}
void ParallelTask::save(IIONode* node) const {
super::save(node);
}
void ParallelTask::load(IIONode* node) {
super::load(node);
}
bool ParallelTask::onenter(Agent* pAgent) {
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_ASSERT(this->m_activeChildIndex == CompositeTask::InvalidChildIndex);
return true;
}
void ParallelTask::onexit(Agent* pAgent, EBTStatus s) {
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(s);
}
EBTStatus ParallelTask::update_current(Agent* pAgent, EBTStatus childStatus) {
EBTStatus s = this->update(pAgent, childStatus);
return s;
}
EBTStatus ParallelTask::update(Agent* pAgent, EBTStatus childStatus) {
BEHAVIAC_UNUSED_VAR(childStatus);
Parallel* node = (Parallel*)this->m_node;
EBTStatus result = node->ParallelUpdate(pAgent, this->m_children);
return result;
}
}
| 33.846774 | 149 | 0.560043 | zja147 |
c8aa61a07552b8493e57baacb0ae1efd9abb1537 | 4,469 | cpp | C++ | src/hip/SELF_Model.cpp | FluidNumerics/self-fluids | 98293579cd438e51d45ea136eecb930ff54c3f25 | [
"BSD-3-Clause"
] | 1 | 2018-07-22T15:03:31.000Z | 2018-07-22T15:03:31.000Z | src/hip/SELF_Model.cpp | FluidNumerics/self-fluids | 98293579cd438e51d45ea136eecb930ff54c3f25 | [
"BSD-3-Clause"
] | 15 | 2018-05-30T14:51:15.000Z | 2018-07-13T06:06:00.000Z | src/hip/SELF_Model.cpp | FluidNumerics/SELF-Fluids | 98293579cd438e51d45ea136eecb930ff54c3f25 | [
"BSD-3-Clause"
] | null | null | null | #include <hip/hip_runtime.h>
#include "SELF_HIP_Macros.h"
__global__ void UpdateSolution_Model1D_gpu(real *solution, real *dSdt, real dt, int N, int nVar){
size_t iVar = blockIdx.x;
size_t iEl = blockIdx.y;
size_t i = threadIdx.x;
solution[SC_1D_INDEX(i,iVar,iEl,N,nVar)] += dt*dSdt[SC_1D_INDEX(i,iVar,iEl,N,nVar)];
}
extern "C"
{
void UpdateSolution_Model1D_gpu_wrapper(real **solution, real **dSdt, real dt, int N, int nVar, int nEl)
{
UpdateSolution_Model1D_gpu<<<dim3(nVar,nEl,1), dim3(N+1,1,1), 0, 0>>>(*solution, *dSdt, dt, N, nVar);
}
}
__global__ void UpdateGRK3_Model1D_gpu(real *grk3, real *solution, real *dSdt, real rk3_a, real rk3_g, real dt, int N, int nVar){
size_t iVar = blockIdx.x;
size_t iEl = blockIdx.y;
size_t i = threadIdx.x;
grk3[SC_1D_INDEX(i,iVar,iEl,N,nVar)] = rk3_a*grk3[SC_1D_INDEX(i,iVar,iEl,N,nVar)] + dSdt[SC_1D_INDEX(i,iVar,iEl,N,nVar)];
solution[SC_1D_INDEX(i,iVar,iEl,N,nVar)] += rk3_g*dt*grk3[SC_1D_INDEX(i,iVar,iEl,N,nVar)];
}
extern "C"
{
void UpdateGRK3_Model1D_gpu_wrapper(real **grk3, real **solution, real **dSdt, real rk3_a, real rk3_g, real dt, int N, int nVar, int nEl)
{
UpdateGRK3_Model1D_gpu<<<dim3(nVar,nEl,1), dim3(N+1,1,1), 0, 0>>>(*grk3, *solution, *dSdt, rk3_a, rk3_g, dt, N, nVar);
}
}
__global__ void CalculateDSDt_Model1D_gpu(real *fluxDivergence, real *source, real *dSdt, int N, int nVar){
size_t iVar = blockIdx.x;
size_t iEl = blockIdx.y;
size_t i = threadIdx.x;
dSdt[SC_1D_INDEX(i,iVar,iEl,N,nVar)] = source[SC_1D_INDEX(i,iVar,iEl,N,nVar)]-
fluxDivergence[SC_1D_INDEX(i,iVar,iEl,N,nVar)];
}
extern "C"
{
void CalculateDSDt_Model1D_gpu_wrapper(real **fluxDivergence, real **source, real **dSdt, int N, int nVar, int nEl)
{
CalculateDSDt_Model1D_gpu<<<dim3(nVar,nEl,1), dim3(N+1,1,1), 0, 0>>>(*fluxDivergence, *source, *dSdt, N, nVar);
}
}
__global__ void UpdateGRK3_Model2D_gpu(real *grk3, real *solution, real *dSdt, real rk3_a, real rk3_g, real dt, int N, int nVar){
size_t iVar = blockIdx.x;
size_t iEl = blockIdx.y;
size_t i = threadIdx.x;
size_t j = threadIdx.y;
grk3[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)] = rk3_a*grk3[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)] + dSdt[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)];
solution[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)] += rk3_g*dt*grk3[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)];
}
extern "C"
{
void UpdateGRK3_Model2D_gpu_wrapper(real **grk3, real **solution, real **dSdt, real rk3_a, real rk3_g, real dt, int N, int nVar, int nEl)
{
UpdateGRK3_Model2D_gpu<<<dim3(nVar,nEl,1), dim3(N+1,N+1,1), 0, 0>>>(*grk3, *solution, *dSdt, rk3_a, rk3_g, dt, N, nVar);
}
}
__global__ void UpdateSolution_Model2D_gpu(real *solution, real *dSdt, real dt, int N, int nVar){
size_t iVar = blockIdx.x;
size_t iEl = blockIdx.y;
size_t i = threadIdx.x;
size_t j = threadIdx.y;
solution[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)] += dt*dSdt[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)];
}
extern "C"
{
void UpdateSolution_Model2D_gpu_wrapper(real **solution, real **dSdt, real dt, int N, int nVar, int nEl)
{
UpdateSolution_Model2D_gpu<<<dim3(nVar,nEl,1), dim3(N+1,N+1,1), 0, 0>>>(*solution, *dSdt, dt, N, nVar);
}
}
__global__ void CalculateDSDt_Model2D_gpu(real *fluxDivergence, real *source, real *dSdt, int N, int nVar){
size_t iVar = blockIdx.x;
size_t iEl = blockIdx.y;
size_t i = threadIdx.x;
size_t j = threadIdx.y;
dSdt[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)] = source[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)]-
fluxDivergence[SC_2D_INDEX(i,j,iVar,iEl,N,nVar)];
}
extern "C"
{
void CalculateDSDt_Model2D_gpu_wrapper(real **fluxDivergence, real **source, real **dSdt, int N, int nVar, int nEl)
{
CalculateDSDt_Model2D_gpu<<<dim3(nVar,nEl,1), dim3(N+1,N+1,1), 0, 0>>>(*fluxDivergence, *source, *dSdt, N, nVar);
}
}
__global__ void CalculateDSDt_Model3D_gpu(real *fluxDivergence, real *source, real *dSdt, int N, int nVar){
size_t iVar = blockIdx.x;
size_t iEl = blockIdx.y;
size_t i = threadIdx.x;
size_t j = threadIdx.y;
size_t k = threadIdx.z;
dSdt[SC_3D_INDEX(i,j,k,iVar,iEl,N,nVar)] = source[SC_3D_INDEX(i,j,k,iVar,iEl,N,nVar)]-
fluxDivergence[SC_3D_INDEX(i,j,k,iVar,iEl,N,nVar)];
}
extern "C"
{
void CalculateDSDt_Model3D_gpu_wrapper(real **fluxDivergence, real **source, real **dSdt, int N, int nVar, int nEl)
{
CalculateDSDt_Model3D_gpu<<<dim3(nVar,nEl,1), dim3(N+1,N+1,N+1), 0, 0>>>(*fluxDivergence, *source, *dSdt, N, nVar);
}
}
| 32.151079 | 139 | 0.68606 | FluidNumerics |
c8aad589036ab57563a3fb0389b1f6ffe6b35595 | 13,524 | hpp | C++ | src/noise/quantum_error.hpp | jakelishman/qiskit-aer | 7512ecede820e0d2bc7ad7b6704bcf06a861ca3a | [
"Apache-2.0"
] | 313 | 2018-12-19T09:19:12.000Z | 2022-03-21T18:15:41.000Z | src/noise/quantum_error.hpp | jakelishman/qiskit-aer | 7512ecede820e0d2bc7ad7b6704bcf06a861ca3a | [
"Apache-2.0"
] | 933 | 2018-12-21T02:56:49.000Z | 2022-03-30T01:19:54.000Z | src/noise/quantum_error.hpp | jakelishman/qiskit-aer | 7512ecede820e0d2bc7ad7b6704bcf06a861ca3a | [
"Apache-2.0"
] | 313 | 2018-12-19T14:52:55.000Z | 2022-02-28T20:20:14.000Z | /**
* This code is part of Qiskit.
*
* (C) Copyright IBM 2018, 2019.
*
* This code is licensed under the Apache License, Version 2.0. You may
* obtain a copy of this license in the LICENSE.txt file in the root directory
* of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
*
* Any modifications or derivative works of this code must retain this
* copyright notice, and modified files need to carry a notice indicating
* that they have been altered from the originals.
*/
#ifndef _aer_noise_quantum_error_hpp_
#define _aer_noise_quantum_error_hpp_
#include "framework/opset.hpp"
#include "simulators/superoperator/superoperator_state.hpp"
#include "framework/noise_utils.hpp"
namespace AER {
namespace Noise {
//=========================================================================
// Quantum Error class
//=========================================================================
// Quantum error class that can model any error that is expressed as a
// qobj instruction acting on qubits.
class QuantumError {
public:
// Methods for sampling
enum class Method {circuit, superop, kraus};
// Alias for return type
using NoiseOps = std::vector<Operations::Op>;
//-----------------------------------------------------------------------
// Sampling method
//-----------------------------------------------------------------------
// Sample a noisy implementation of op
NoiseOps sample_noise(const reg_t &qubits,
RngEngine &rng,
Method method = Method::circuit) const;
// Return the opset for the quantum error
const Operations::OpSet& opset() const {return opset_;}
// Return the superoperator matrix representation of the error.
// If the error cannot be converted to a superoperator an error
// will be raised.
const cmatrix_t& superoperator() const;
// Return the canonical Kraus representation of the error.
// If the error cannot be converted to a Kraus an error
// will be raised.
const std::vector<cmatrix_t>& kraus() const;
//-----------------------------------------------------------------------
// Initialization
//-----------------------------------------------------------------------
// Load a QuantumError object from a JSON Error object
void load_from_json(const json_t &js);
// Sets the sub-circuits and probabilities to be sampled from.
// The length of the circuits vector and probability vector must be equal.
void set_circuits(const std::vector<NoiseOps> &circuits,
const rvector_t &probs);
// Construct a quantum error from a set of Kraus matrices
// This will factor out any identity or unitary Kraus operators into
// non-kraus subcircuits.
void set_from_kraus(const std::vector<cmatrix_t> &mats);
// Compute the superoperator representation of the quantum error
void compute_superoperator();
// Compute canonical Kraus representation of the quantum error
void compute_kraus();
//-----------------------------------------------------------------------
// Utility
//-----------------------------------------------------------------------
// Set number of qubits or memory bits for error
inline void set_num_qubits(uint_t num_qubits) {num_qubits_ = num_qubits;}
// Get number of qubits or memory bits for error
inline uint_t get_num_qubits() const {return num_qubits_;}
// Set the sampled errors to be applied after the original operation
inline void set_errors_after() {errors_after_op_ = true;}
// Set the sampled errors to be applied before the original operation
inline void set_errors_before() {errors_after_op_ = false;}
// Returns true if the errors are to be applied after the operation
inline bool errors_after() const {return errors_after_op_;}
// Set threshold for checking probabilities and matrices
void set_threshold(double);
protected:
// Number of qubits sthe error applies to
uint_t num_qubits_ = 0;
// Probabilities, first entry is no-error (identity)
rvector_t probabilities_;
// List of unitary error matrices
std::vector<NoiseOps> circuits_;
// List of OpTypes contained in error circuits
Operations::OpSet opset_;
// threshold for validating if matrices are unitary
double threshold_ = 1e-10;
// Superoperator matrix representation of the error
cmatrix_t superoperator_;
std::vector<cmatrix_t> canonical_kraus_;
// flag for where errors should be applied relative to the sampled op
bool errors_after_op_ = true;
};
//-------------------------------------------------------------------------
// Implementation: Mixed unitary error subclass
//-------------------------------------------------------------------------
QuantumError::NoiseOps QuantumError::sample_noise(const reg_t &qubits,
RngEngine &rng,
Method method) const {
if (qubits.size() < get_num_qubits()) {
std::stringstream msg;
msg << "QuantumError: qubits size (" << qubits.size() << ")";
msg << " < error qubits (" << get_num_qubits() << ").";
throw std::invalid_argument(msg.str());
}
switch (method) {
case Method::superop: {
// Truncate qubits to size of the actual error
reg_t op_qubits = qubits;
op_qubits.resize(get_num_qubits());
auto op = Operations::make_superop(op_qubits, superoperator());
return NoiseOps({op});
}
case Method::kraus: {
// Truncate qubits to size of the actual error
reg_t op_qubits = qubits;
op_qubits.resize(get_num_qubits());
auto op = Operations::make_kraus(op_qubits, kraus());
return NoiseOps({op});
}
default: {
auto r = rng.rand_int(probabilities_);
// Check for invalid arguments
if (r + 1 > circuits_.size()) {
throw std::invalid_argument(
"QuantumError: probability outcome (" + std::to_string(r) + ")"
" is greater than number of circuits (" + std::to_string(circuits_.size()) + ")."
);
}
NoiseOps noise_ops = circuits_[r];
// Add qubits to noise op commands;
for (auto &op : noise_ops) {
// Update qubits based on position in qubits list
for (auto &qubit: op.qubits) {
qubit = qubits[qubit];
}
}
return noise_ops;
}
}
}
void QuantumError::set_threshold(double threshold) {
threshold_ = std::abs(threshold);
}
void QuantumError::set_circuits(const std::vector<NoiseOps> &circuits,
const rvector_t &probs) {
if (probs.size() != circuits.size()) {
throw std::invalid_argument(
"QuantumError: invalid input, number of circuits (" +
std::to_string(circuits.size()) + ") and number of probabilities (" +
std::to_string(probs.size()) + ") are not equal."
);
}
// Check probability vector
double total = 0.;
bool probs_valid = true;
uint_t num_qubits = 0;
for (const auto &p : probs) {
probs_valid &= !(p < 0 || p > 1);
total += p;
}
if (!probs_valid || std::abs(total - 1.0) > threshold_) {
throw std::invalid_argument("QuantumError: invalid probability vector total (" +
std::to_string(total) + "!= 1)");
}
// Reset OpSet
opset_ = Operations::OpSet();
// Add elements with non-zero probability
for (size_t j=0; j < probs.size(); j++ ) {
if (probs[j] > threshold_) {
probabilities_.push_back(probs[j]);
circuits_.push_back(circuits[j]);
for (const auto &op: circuits[j]) {
// Check max qubit size
for (const auto &qubit : op.qubits) {
num_qubits = std::max(num_qubits, qubit + 1);
}
// Record op in opset
opset_.insert(op);
}
}
}
set_num_qubits(num_qubits);
}
void QuantumError::set_from_kraus(const std::vector<cmatrix_t> &mats) {
// Check input isn't empty
if (mats.empty())
throw std::invalid_argument("QuantumError: Kraus channel input is empty.");
// Check input is a CPTP map
if (Utils::is_cptp_kraus(mats, threshold_) == false)
throw std::invalid_argument("QuantumError: Kraus channel input is not a CPTP map.");
// Get number of qubits from first Kraus operator
size_t mat_dim = mats[0].GetRows();
auto num_qubits = static_cast<unsigned>(std::log2(mat_dim));
set_num_qubits(num_qubits);
if (mat_dim != 1ULL << num_qubits)
throw std::invalid_argument("QuantumError: Kraus channel input is a multi-qubit channel.");
// Check if each matrix is a:
// - scaled identity matrix
// - scaled non-identity unitary matrix
// - a non-unitary Kraus operator
// Probabilities
double p_unitary = 0.; // total probability of all unitary ops
rvector_t probs = {0.}; // initialize with probability of Identity
// Matrices
std::vector<cmatrix_t> unitaries; // non-identity unitaries
std::vector<cmatrix_t> kraus; // non-unitary Kraus matrices
for (const auto &mat : mats) {
if (!Utils::is_square(mat) && !Utils::is_diagonal(mat)) {
throw std::invalid_argument("Error matrix is not square or diagonal.");
}
// Get the value of the first non-zero diagonal element of mat * dagger(mat) for rescaling
double p = 0.;
for (size_t i=0; i < mat.GetColumns(); i ++) {
for (size_t j=0; j < mat.GetRows(); j ++) {
p += std::real(std::abs(mat(j, i) * std::conj(mat(j, i)) ));
}
if (p > threshold_)
break;
}
if (p > 0) {
// Rescale mat by probability
cmatrix_t tmp = (1 / std::sqrt(p)) * mat;
// Check if rescaled matrix is an identity
if (Utils::is_identity(tmp, threshold_) || Utils::is_diagonal_identity(tmp, threshold_)) {
// Add to identity probability
probs[0] += p;
p_unitary += p;
}
// Check if rescaled matrix is a unitary
else if (Utils::is_unitary(tmp, threshold_)) {
unitaries.push_back(tmp);
probs.push_back(p); // add probability for unitary
p_unitary += p;
} else {
// Original matrix is non-unitary so add original matrix to Kraus ops
kraus.push_back(mat);
}
}
}
// Create noise circuits:
std::vector<NoiseOps> circuits;
// Add identity
Operations::Op iden;
iden.name = "id";
iden.qubits = reg_t({0});
iden.type = Operations::OpType::gate;
circuits.push_back({iden});
// Create n-qubit argument {0, ... , n-1}
// for indexing remaining errors operators
reg_t error_qubits(num_qubits);
std::iota(error_qubits.begin(), error_qubits.end(), 0);
for (size_t j=1; j < probs.size(); j++) {
auto op = Operations::make_unitary(error_qubits, unitaries[j - 1]);
circuits.push_back({op});
}
// Add Kraus
// Probability of non-unitary Kraus error is 1 - p_total
double p_kraus = 1.0 - p_unitary;
if (std::abs(p_kraus) > threshold_) {
// Rescale Kraus operators by probability
Utils::scalar_multiply_inplace(kraus, complex_t(1. / std::sqrt(p_kraus), 0.0));
// Check rescaled Kraus map is still CPTP
if (Utils::is_cptp_kraus(kraus, threshold_) == false) {
throw std::invalid_argument("QuantumError: Rescaled non-unitary Kraus channel is not a CPTP map.");
}
// Add Kraus error subcircuit
auto op = Operations::make_kraus(error_qubits, kraus);
circuits.push_back({op});
// Add kraus error prob
probs.push_back(p_kraus);
}
// Add the circuits
set_circuits(circuits, probs);
}
const cmatrix_t& QuantumError::superoperator() const {
// Check the superoperator is actually computed
// If not raise an exception
if (superoperator_.empty()) {
throw std::runtime_error("QuantumError: superoperator is empty.");
}
return superoperator_;
}
const std::vector<cmatrix_t>& QuantumError::kraus() const {
// Check the canonical Kraus method is actually computed
// If not raise an exception
if (canonical_kraus_.empty()) {
throw std::runtime_error("QuantumError: Kraus is empty.");
}
return canonical_kraus_;
}
void QuantumError::compute_superoperator() {
// Initialize superoperator matrix to correct size
size_t dim = 1ULL << (2 * get_num_qubits());
superoperator_.initialize(dim, dim);
// We use the superoperator simulator state to do this
QubitSuperoperator::State<> superop;
for (size_t j=0; j<circuits_.size(); j++ ){
// Initialize identity superoperator
superop.initialize_qreg(get_num_qubits());
// Apply each gate in the circuit
// We don't need output data or RNG for this
ExperimentResult data;
RngEngine rng;
superop.apply_ops(circuits_[j].cbegin(), circuits_[j].cend(), data, rng);
superoperator_ += probabilities_[j] * superop.move_to_matrix();
}
}
void QuantumError::compute_kraus() {
// Check superoperator representation is computed
if (superoperator_.empty()) {
compute_superoperator();
}
// Conver to Kraus
size_t dim = 1 << get_num_qubits();
canonical_kraus_ = Utils::superop2kraus(superoperator_, dim);
}
void QuantumError::load_from_json(const json_t &js) {
rvector_t probs;
JSON::get_value(probs, "probabilities", js);
std::vector<NoiseOps> circuits;
JSON::get_value(circuits, "instructions", js);
set_circuits(circuits, probs);
}
//-------------------------------------------------------------------------
} // end namespace Noise
//-------------------------------------------------------------------------
} // end namespace AER
//-------------------------------------------------------------------------
#endif | 34.237975 | 105 | 0.619269 | jakelishman |
c8af7dd0b1e8bab893d6944622d50f80760346d3 | 4,239 | hpp | C++ | engine/executor/include/model.hpp | huggingface/neural-compressor | aaad4c357a86914ffa583753c9a26d949838a2a5 | [
"Apache-2.0"
] | 52 | 2020-08-04T04:31:48.000Z | 2020-11-29T02:34:32.000Z | engine/executor/include/model.hpp | intel/lp-opt-tool | 130eefa3586b38df6c0ff78cc8807ae273f6a63f | [
"Apache-2.0"
] | null | null | null | engine/executor/include/model.hpp | intel/lp-opt-tool | 130eefa3586b38df6c0ff78cc8807ae273f6a63f | [
"Apache-2.0"
] | 7 | 2020-08-21T01:08:55.000Z | 2020-11-29T03:36:55.000Z | // Copyright (c) 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ENGINE_EXECUTOR_INCLUDE_MODEL_HPP_
#define ENGINE_EXECUTOR_INCLUDE_MODEL_HPP_
#include <stdio.h>
#include <algorithm>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "common.hpp"
#include "glog/logging.h"
#include "memory_allocator.hpp"
#include "operator.hpp"
#include "operator_registry.hpp"
#include "tensor.hpp"
namespace executor {
/**
* @brief Connects Operator%s together into a directed acyclic graph (DAG)
* specified by a ModelConfig.
*
*/
class Model {
public:
explicit Model(const ModelConfig& conf, const string& weight_root);
explicit Model(const string& conf_file, const string& weight_root);
virtual ~Model() {}
void Init(const ModelConfig& conf);
vector<Tensor>& Forward(vector<Tensor>& input_data); // NOLINT
void SetInput(const vector<OperatorConfig*>& conf, const int operator_id, const int tensor_id,
map<string, int>* tensor_name_to_idx);
void SetOutput(const vector<OperatorConfig*>& conf, const int operator_id, const int tensor_id,
map<string, int>* tensor_name_to_idx);
inline const string& name() const { return name_; }
inline const vector<string>& operator_names() const { return operator_names_; }
inline const vector<string>& tensor_names() const { return tensor_names_; }
inline const vector<shared_ptr<Operator> >& operators() const { return operators_; }
inline const vector<Tensor*>& tensors() const { return tensors_; }
inline int num_inputs() const { return model_input_tensors_.size(); }
inline int num_outputs() const { return model_output_tensors_.size(); }
inline const vector<TensorConfig*>& input_configs() const { return model_input_configs_; }
inline vector<Tensor>& output_tensors() {
LOG(INFO) << "Output tensor size is " << model_output_tensors_.size();
for (int i = 0; i < model_output_tensors_.size(); ++i) {
output_tensors_[i].set_dtype(model_output_tensors_[i]->dtype());
auto data_buffer = model_output_tensors_[i]->data();
auto size = model_output_tensors_[i]->size();
// copy the data from memory to an output buffer
if (size > output_tensors_[i].size() ||
output_tensors_[i].size() < size * type2bytes[output_tensors_[i].dtype()]) {
free(output_tensors_[i].mutable_data());
void* out_buffer = malloc(size * type2bytes[output_tensors_[i].dtype()]);
output_tensors_[i].set_data(out_buffer);
output_tensors_[i].set_shape(model_output_tensors_[i]->shape());
memcpy(out_buffer, data_buffer, size * type2bytes[output_tensors_[i].dtype()]);
} else {
void* out_buffer = output_tensors_[i].mutable_data();
memcpy(out_buffer, data_buffer, size * type2bytes[output_tensors_[i].dtype()]);
}
}
for (auto& tensor_ptr : model_output_tensors_) tensor_ptr->unref_data();
// MemoryAllocator::get().AliveBuffer();
return output_tensors_;
}
protected:
string name_;
string weight_root_;
vector<shared_ptr<Operator> > operators_;
vector<string> operator_names_;
map<string, int> operator_name_index_;
vector<Tensor*> tensors_;
vector<string> tensor_names_;
map<string, int> tensor_name_index_;
/// input output weight vecs stores the vectors of each operator.
vector<vector<Tensor*> > input_vecs_;
vector<vector<Tensor*> > output_vecs_;
vector<Tensor*> model_input_tensors_;
vector<TensorConfig*> model_input_configs_;
vector<Tensor*> model_output_tensors_;
vector<Tensor> output_tensors_;
};
} // namespace executor
#endif // ENGINE_EXECUTOR_INCLUDE_MODEL_HPP_
| 36.543103 | 97 | 0.718802 | huggingface |
c8b34ae4f19227892a1c611ff7a2191a9f9185dd | 3,932 | hpp | C++ | openstudiocore/src/utilities/core/Application.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/utilities/core/Application.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/utilities/core/Application.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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
**********************************************************************/
#ifndef UTILITIES_CORE_APPLICATION_HPP
#define UTILITIES_CORE_APPLICATION_HPP
#include <utilities/UtilitiesAPI.hpp>
#include <utilities/core/Singleton.hpp>
#include <QtGui/QApplication>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
namespace openstudio{
/** Singleton application wide configuration management.
*/
class UTILITIES_API ApplicationSingleton
{
friend class Singleton<ApplicationSingleton>;
public:
/// get the QApplication, if no QApplication has been set this will create a default one
QCoreApplication* application(bool gui=true);
/// set the QApplication, this should be done before calling application(),
/// no op if it has already been set. Returns true if set succeeded.
bool setApplication(QCoreApplication *qApplication);
/// get the QWidget wrapper around SketchUp window
/// initialized by call to application, only implemented for windows
QWidget* sketchUpWidget();
/// Process pending Qt events
/// returns true if some work was done
bool processEvents();
bool processEvents(int maxTime);
/// Check if application has given setting
bool hasSetting(const std::string& key);
/// Remove setting
void removeSetting(const std::string& key);
/// Check if the application is headless
bool isDefaultInstance();
/// Get the value of setting as given type, be careful when using getSettingValueAsBool
/// you must first check if the optional is set and then check its value
boost::optional<bool> getSettingValueAsBool(const std::string& key);
boost::optional<int> getSettingValueAsInt(const std::string& key);
boost::optional<double> getSettingValueAsDouble(const std::string& key);
boost::optional<std::string> getSettingValueAsString(const std::string& key);
/// Set application value to given value
void setSettingValue(const std::string& key, bool value);
void setSettingValue(const std::string& key, int value);
void setSettingValue(const std::string& key, double value);
void setSettingValue(const std::string& key, const std::string& value);
~ApplicationSingleton();
private:
/// private constructor
ApplicationSingleton();
/// QApplication handle
QCoreApplication* m_qApplication;
/// QWidget wrapper around SketchUp window
QWidget* m_sketchUpWidget;
bool defaultInstance;
};
typedef openstudio::Singleton<ApplicationSingleton> Application;
#if _WIN32 || _MSC_VER
/// Explicitly instantiate and export ApplicationSingleton Singleton template instance
/// so that the same instance is shared between the DLL's that link to Utilities.dll
UTILITIES_TEMPLATE_EXT template class UTILITIES_API openstudio::Singleton<ApplicationSingleton>;
#endif
} // openstudio
#endif // UTILITIES_CORE_APPLICATION_HPP
| 36.747664 | 99 | 0.694557 | ORNL-BTRIC |
c8b3cd5099a8215296f3b9eea9112369767dbda9 | 1,895 | cc | C++ | faster_tokenizers/faster_tokenizers/src/normalizers/unicode.cc | Beacontownfc/PaddleNLP | cec1caf485f2552a678a1d56a182d399106eeff3 | [
"Apache-2.0"
] | null | null | null | faster_tokenizers/faster_tokenizers/src/normalizers/unicode.cc | Beacontownfc/PaddleNLP | cec1caf485f2552a678a1d56a182d399106eeff3 | [
"Apache-2.0"
] | null | null | null | faster_tokenizers/faster_tokenizers/src/normalizers/unicode.cc | Beacontownfc/PaddleNLP | cec1caf485f2552a678a1d56a182d399106eeff3 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <algorithm>
#include <codecvt>
#include <locale>
#include <string>
#include "normalizers/unicode.h"
#include "unicode/edits.h"
#include "unicode/errorcode.h"
#include "unicode/normalizer2.h"
#include "unicode/utypes.h"
namespace tokenizers {
namespace normalizers {
void NFCNormalizer::operator()(NormalizedString* input) const { input->NFC(); }
void NFKCNormalizer::operator()(NormalizedString* input) const {
input->NFKC();
}
void NFDNormalizer::operator()(NormalizedString* input) const { input->NFD(); }
void NFKDNormalizer::operator()(NormalizedString* input) const {
input->NFKD();
}
void NmtNormalizer::operator()(NormalizedString* input) const {
input->FilterChar([](char32_t ch) -> bool {
if ((ch >= 0x0001 && ch <= 0x0008) || (ch == 0x000B) ||
(ch >= 0x000E && ch <= 0x001F) || (ch == 0x007F) || (ch == 0x008F) ||
(ch == 0x009F)) {
return false;
}
return true;
});
input->MapChar([](char32_t ch) -> char32_t {
if ((ch == 0x0009) || (ch == 0x000A) || (ch == 0x000C) || (ch == 0x000D) ||
(ch == 0x1680) || (ch >= 0x200B && ch <= 0x200F) || (ch == 0x2028) ||
(ch == 0x2029) || (ch == 0x2581) || (ch == 0xFEFF) || (ch == 0xFFFD)) {
return ' ';
}
return ch;
});
}
} // normalizers
} // tokenizers
| 30.564516 | 79 | 0.658575 | Beacontownfc |
c8b5f499b86355b2f06d18af2b58493871a28c6a | 20,032 | cpp | C++ | XBoxController_UART/LynxStructure.cpp | Kjelland/lynxLib | d3e8c6f9df19d258438451aec14a0a6cfc49bf1e | [
"Apache-2.0"
] | null | null | null | XBoxController_UART/LynxStructure.cpp | Kjelland/lynxLib | d3e8c6f9df19d258438451aec14a0a6cfc49bf1e | [
"Apache-2.0"
] | null | null | null | XBoxController_UART/LynxStructure.cpp | Kjelland/lynxLib | d3e8c6f9df19d258438451aec14a0a6cfc49bf1e | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------- Version 1.2.0.3 ----------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------
#include"LynxStructure.h"
// #include <exception>
// #include <iostream>
namespace LynxStructureSpace
{
//----------------------------------------------- LynxStructure ------------------------------------------------------------
void LynxStructure::init(const StructDefinition* structDefinition, LynxID _lynxID)
{
this->lynxID = _lynxID;
switch (structDefinition->structMode)
{
case LynxStructureSpace::eStructureMode:
int tempSize;
for (int i = 0; i < structDefinition->size; i++)
{
tempSize = checkLocalSize(structDefinition->structItems[i].dataType);
if (tempSize > this->indexingSize)
{
this->indexingSize = tempSize;
}
}
break;
case LynxStructureSpace::eArrayMode:
if (structDefinition->size <= 0)
{
return;
}
this->indexingSize = checkLocalSize(structDefinition->structItems[0].dataType);
break;
default:
return;
}
if (data)
{
delete[] data;
}
data = new char[structDefinition->size*this->indexingSize];
this->_structDefinition = structDefinition;
// _structName = structDefinition->structName;
this->clear();
}
int LynxStructure::toBuffer(char *dataBuffer, SendMode sendMode, int subindex)
{
if (sendMode >= eSendModeEndOfList)
return -3;
if ((sendMode == eSingleVariable) && ((subindex < 0) || (subindex >= this->_structDefinition->size)))
{
return -4;
}
int index = 0;
// Write ID
dataBuffer[index] = char(this->lynxID.deviceID);
index++;
dataBuffer[index] = char(this->lynxID.structTypeID);
index++;
dataBuffer[index] = char(this->lynxID.structInstanceID);
index++;
int tempIndex;
if (sendMode == eAllVariables)
tempIndex = 0;
else if (sendMode == eSingleVariable)
tempIndex = subindex + 1;
else
return -1;
dataBuffer[index] = char(tempIndex & 0xFF);
index++;
dataBuffer[index] = char((tempIndex >> 8) & 0xFF);
index++;
int tempSize;
// Write data
if (sendMode == eAllVariables)
{
for (int i = 0; i < this->_structDefinition->size; i++)
{
tempSize = writeVarToBuffer(dataBuffer, index, i);
if (tempSize > 0)
index += tempSize;
else
return -1;
}
}
else if(sendMode == eSingleVariable)
{
tempSize = writeVarToBuffer(dataBuffer, index, subindex);
if (tempSize > 0)
index += tempSize;
else
return -1;
}
else
{
return -5;
}
// Check data
char checksum = 0;
for (int i = 0; i < index; i++)
{
checksum += dataBuffer[i];
}
dataBuffer[index] = checksum;
return (index + 1);
}
int LynxStructure::fromBuffer(const char *dataBuffer)
{
int lynxIndex = (int(dataBuffer[LYNX_ID_BYTES]) & int(0xFF)) | ((int(dataBuffer[LYNX_ID_BYTES + 1]) & int(0xFF)) << 8);
int index = LYNX_ID_BYTES + LYNX_INDEXER_BYTES;
int tempSize;
if (lynxIndex == 0) // Copy all data
{
// Check data
char remoteChecksum = dataBuffer[index + _structDefinition->transferSize];
char localChecksum = 0;
for (int i = 0; i < (index + _structDefinition->transferSize); i++)
{
localChecksum += dataBuffer[i];
}
if (localChecksum != remoteChecksum)
{
return -2; // Return error code -2 if checksum is wrong
}
// Copy data
for (int i = 0; i < this->_structDefinition->size; i++)
{
tempSize = writeVarFromBuffer(dataBuffer, index, i);
if (tempSize > 0)
index += tempSize;
else
return tempSize;
}
}
else if (lynxIndex > 0) // Copy specific item
{
if (lynxIndex > this->_structDefinition->size)
{
return -1;
}
// Check data
int transferSize = checkTransferSize(_structDefinition->structItems[lynxIndex].dataType);
char remoteChecksum = dataBuffer[index + transferSize];
char localChecksum = 0;
for (int i = 0; i < (index + transferSize); i++)
{
localChecksum += dataBuffer[i];
}
if (localChecksum != remoteChecksum)
{
return -2; // Return error code -2 if checksum is wrong
}
tempSize = writeVarFromBuffer(dataBuffer, index, lynxIndex - 1);
if (tempSize > 0)
index += tempSize;
else
return tempSize;
}
return tempSize;
}
void LynxStructure::clear()
{
for (int i = 0; i < this->_structDefinition->size*this->indexingSize; i++)
{
data[i] = 0;
}
}
// Returns the size of the datapackage in bytes (not including identifiers and checksum)
//int LynxStructure::getTransferSize()
//{
// int tempSize = 0;
// for (int i = 0; i < this->_structDefinition->size; i++)
// {
// if (_structDefinition->structItems[i].dataType == eEndOfList)
// break;
// tempSize += checkTransferSize(_structDefinition->structItems[i].dataType);
// }
// return 0;
//}
// Returns the size of the datapackage in bytes (not including identifiers and checksum)
int LynxStructure::getTransferSize()
{
return (this->_structDefinition->transferSize + LYNX_ID_BYTES + LYNX_INDEXER_BYTES + LYNX_CHECKSUM_BYTES);
}
bool LynxStructure::dataChanged()
{
bool temp = this->_dataChanged;
this->_dataChanged = false;
return temp;
}
int LynxStructure::checkLocalSize(LynxDataType dataType)
{
int temp = 0;
switch (dataType)
{
case eInt8:
temp = sizeof(int8_t);
break;
case eUint8:
temp = sizeof(uint8_t);
break;
case eInt16:
temp = sizeof(int16_t);
break;
case eUint16:
temp = sizeof(uint16_t);
break;
case eInt32:
temp = sizeof(int32_t);
break;
case eUint32:
temp = sizeof(uint32_t);
break;
case eInt64:
temp = sizeof(int64_t);
break;
case eUint64:
temp = sizeof(uint64_t);
break;
case eFloat:
temp = sizeof(float);
break;
case eDouble:
temp = sizeof(double);
break;
case eIQ:
temp = sizeof(uint32_t);
break;
default:
temp = 0;
break;
}
return temp;
}
int LynxStructure::checkTransferSize(LynxDataType dataType)
{
int temp = 0;
switch (dataType)
{
case eInt8:
temp = 1;
break;
case eUint8:
temp = 1;
break;
case eInt16:
temp = 2;
break;
case eUint16:
temp = 2;
break;
case eInt32:
temp = 4;
break;
case eUint32:
temp = 4;
break;
case eInt64:
temp = 8;
break;
case eUint64:
temp = 8;
break;
case eFloat:
temp = 4;
break;
case eDouble:
temp = 8;
break;
case eIQ:
temp = 4;
break;
default:
temp = -1;
break;
}
return temp;
}
int LynxStructure::writeVarToBuffer(char * dataBuffer, int bufferIndex, int lynxIndex)
{
if ((bufferIndex < 0) || (lynxIndex < 0) || (lynxIndex >= this->_structDefinition->size))
return -1;
int tempTransferSize;
int index = bufferIndex;
switch (this->_structDefinition->structMode)
{
case LynxStructureSpace::eStructureMode:
tempTransferSize = checkTransferSize(this->_structDefinition->structItems[lynxIndex].dataType);
break;
case LynxStructureSpace::eArrayMode:
tempTransferSize = checkTransferSize(this->_structDefinition->structItems[0].dataType);
break;
default:
return -1;
}
switch (tempTransferSize)
{
case 1:
dataBuffer[index] = char(getData<uint8_t>(lynxIndex));
index++;
break;
case 2:
{
uint16_t temp = getData<uint16_t>(lynxIndex);
for (int n = 0; n < 2; n++)
{
dataBuffer[index] = char((temp >> (n * 8)) & 0xFF);
index++;
}
}
break;
case 4:
{
uint32_t temp = getData<uint32_t>(lynxIndex);
for (int n = 0; n < 4; n++)
{
dataBuffer[index] = char((temp >> (n * 8)) & 0xFF);
index++;
}
}
break;
case 8:
{
uint64_t temp = getData<uint64_t>(lynxIndex);
for (int n = 0; n < 8; n++)
{
dataBuffer[index] = char((temp >> (n * 8)) & 0xFF);
index++;
}
}
break;
default:
return -1;
}
return tempTransferSize;
}
int LynxStructure::writeVarFromBuffer(const char * dataBuffer, int bufferIndex, int lynxIndex)
{
int tempTransferSize;
int index = bufferIndex;
// Read data
switch (this->_structDefinition->structMode)
{
case LynxStructureSpace::eStructureMode:
tempTransferSize = checkTransferSize(this->_structDefinition->structItems[lynxIndex].dataType);
break;
case LynxStructureSpace::eArrayMode:
tempTransferSize = checkTransferSize(this->_structDefinition->structItems[0].dataType);
break;
default:
return -1;
}
switch (tempTransferSize)
{
case 1:
setData<uint8_t>(lynxIndex, uint8_t(dataBuffer[index]));
index++;
break;
case 2:
{
uint16_t temp = 0;
for (int n = 0; n < 2; n++)
{
temp |= ((uint16_t(dataBuffer[index]) << (n * 8)) & (uint16_t(0xFF) << (n * 8)));
index++;
}
setData<uint16_t>(lynxIndex, temp);
}
break;
case 4:
{
uint32_t temp = 0;
for (int n = 0; n < 4; n++)
{
temp |= ((uint32_t(dataBuffer[index]) << (n * 8)) & (uint32_t(0xFF) << (n * 8)));
index++;
}
setData<uint32_t>(lynxIndex, temp);
}
break;
case 8:
{
uint64_t temp = 0;
for (int n = 0; n < 4; n++)
{
temp |= ((uint64_t(dataBuffer[index]) << (n * 8)) & (uint64_t(0xFF) << (n * 8)));
index++;
}
setData<uint64_t>(lynxIndex, temp);
}
break;
default:
return -1;
}
return tempTransferSize;
}
int LynxStructure::getOffset(int target)
{
if ((this->_structDefinition->size == 0) || (target >= this->_structDefinition->size))
{
return -1;
}
return (target * this->indexingSize);
}
//----------------------------------------------- LynxHandler ------------------------------------------------------------
void LynxHandler::init(int nStructs)
{
// deviceID = _deviceID;
if (nStructs > 0)
{
if (_structures)
{
delete[] _structures;
}
_structures = new LynxStructure[nStructs];
_size = 0;
_reservedSize = nStructs;
}
}
LynxID LynxHandler::addStructure(uint8_t _structType, uint8_t _structInstance, const StructDefinition* _structDefinition)
{
if (_structDefinition->size <= 0)
{
return LynxID();
}
_size++;
if (_size > _reservedSize )
{
_reservedSize++;
LynxStructure* tempStructs = new LynxStructure[_reservedSize];
if (this->_structures)
{
for (int i = 0; i < _reservedSize - 1; i++)
{
// StructDefinition temp = { this->_structures[i].structName(), }
tempStructs[i].init(_structures[i].structDefinition(), _structures[i].lynxID);
}
delete[] _structures;
}
_structures = tempStructs;
tempStructs = LYNX_NULL;
}
LynxID tempID = LynxID( this->_deviceInfo.deviceID, _structType, _structInstance );
_structures[_size - 1].init(_structDefinition, tempID);
return tempID;
}
int LynxHandler::scanRequest(char* dataBuffer)
{
int index = 0;
dataBuffer[index] = char(LYNX_INTERNAL_DATAGRAM);
index++;
dataBuffer[index] = char(eLynxRequest);
index++;
dataBuffer[index] = char(eRqDeviceInfo);
index++;
for (int i = 0; i < 20; i++)
{
if ((this->_deviceInfo.deviceName[i] == '\0') || (i == 19))
{
dataBuffer[index] = '\0';
index++;
break;
}
dataBuffer[index] = this->_deviceInfo.deviceName[i];
index++;
}
dataBuffer[index] = char(this->_deviceInfo.deviceID);
index++;
char tempVersion[4] = LYNX_VERSION;
for (int i = 0; i < 4; i++)
{
dataBuffer[index] = tempVersion[i];
index++;
}
char checksum = 0;
for (int i = 0; i < index; i++)
{
checksum += dataBuffer[i];
}
dataBuffer[index] = checksum;
index++;
return index;
}
int LynxHandler::copyData(LynxID source, LynxID target)
{
if (source.structTypeID != target.structTypeID)
return -2;
int sourceIndex = indexFromID(source);
if (sourceIndex < 0)
return -1;
int targetIndex = indexFromID(target);
if (targetIndex < 0)
return -1;
int copySize = _structures[targetIndex].getSize()*_structures[targetIndex].getIndexingSize();
char* sourcePointer = (char*)(_structures[sourceIndex].getDataPointer());
char* targetPointer = (char*)(_structures[targetIndex].getDataPointer());
for (int i = 0; i < copySize; i++)
{
targetPointer[i] = sourcePointer[i];
}
return 0;
}
int LynxHandler::toBuffer(LynxID _lynxID, char * dataBuffer, SendMode sendMode, int subIndex)
{
int index = this->indexFromID(_lynxID);
if (index >= 0)
{
return this->_structures[index].toBuffer(dataBuffer, sendMode, subIndex);
}
return -1;
}
int LynxHandler::fromBuffer(const char * dataBuffer, LynxIpAddress ipAddress)
{
if (dataBuffer[0] == char(LYNX_INTERNAL_DATAGRAM))
{
return handleInternalDatagram(dataBuffer, ipAddress);
}
else
{
return datagramFromBuffer(dataBuffer);
}
}
bool LynxHandler::dataChanged(LynxID _lynxID)
{
int index = indexFromID(_lynxID);
if (index < 0)
{
return false;
}
return this->_structures[index].dataChanged();
}
int LynxHandler::getTranferSize(LynxID _lynxID)
{
int index = indexFromID(_lynxID);
return this->_structures[index].getTransferSize();
}
int LynxHandler::newScanResponses()
{
int temp = 0;
for (int i = 0; i < _availableDevices.getSize(); i++)
{
if (_availableDevices.at(i).newDevice)
{
temp++;
}
}
return temp;
}
LynxDeviceInfo LynxHandler::getScanResponse()
{
LynxDeviceInfo temp = LynxDeviceInfo();
for (int i = 0; i < _availableDevices.getSize(); i++)
{
if (_availableDevices.at(i).newDevice)
{
temp = _availableDevices.at(i);
_availableDevices.at(i).newDevice = false;
break;
}
}
return temp;
//LynxDeviceInfo temp = LynxDeviceInfo();
//if (_availableDevices.getSize() > 0)
//{
// temp = _availableDevices.at(0);
// _availableDevices.removeItem(0);
//}
//return temp;
}
int LynxHandler::sendScanResponse(char* dataBuffer)
{
_newScanRequest = false;
int index = 0;
dataBuffer[index] = LYNX_INTERNAL_DATAGRAM;
index++;
dataBuffer[index] = eLynxResponse;
index++;
dataBuffer[index] = eRqDeviceInfo;
index++;
for (int i = 0; i < 20; i++)
{
if ((this->_deviceInfo.deviceName[i] == '\0') || (i == 19))
{
dataBuffer[index] = '\0';
index++;
break;
}
dataBuffer[index] = this->_deviceInfo.deviceName[i];
index++;
}
dataBuffer[index] = char(this->_deviceInfo.deviceID);
index++;
char tempVersion[4] = LYNX_VERSION;
for (int i = 0; i < 4; i++)
{
dataBuffer[index] = tempVersion[i];
index++;
}
char checksum = 0;
for (int i = 0; i < index; i++)
{
checksum += dataBuffer[i];
}
dataBuffer[index] = checksum;
index++;
return index;
}
int LynxHandler::indexFromID(LynxID _lynxID)
{
for (int i = 0; i < this->_size; i++)
{
if ((this->_structures[i].lynxID.structTypeID == _lynxID.structTypeID)
&& (this->_structures[i].lynxID.structInstanceID == _lynxID.structInstanceID))
{
return i;
}
}
return -1;
}
int LynxHandler::handleInternalDatagram(const char * dataBuffer, LynxIpAddress ipAddress)
{
switch (StandardStructIDs(dataBuffer[1]))
{
case LynxStructureSpace::eLynxRequest:
{
return this->handleRequest(dataBuffer, ipAddress);
}
case LynxStructureSpace::eLynxResponse:
{
return this->handleResponse(dataBuffer, ipAddress);
}
default:
return -1;
}
}
int LynxHandler::handleRequest(const char * dataBuffer, LynxIpAddress ipAddress)
{
if (dataBuffer[2] == eRqDeviceInfo)
{
LynxDeviceInfo tempInfo = receiveScanResponse(dataBuffer, ipAddress);
int index = checkAvailableDevices(tempInfo);
if (index >= 0)
{
_newScanRequest = true;
return 0;
}
}
return -1;
}
int LynxHandler::handleResponse(const char * dataBuffer, LynxIpAddress ipAddress)
{
if (dataBuffer[2] == eRqDeviceInfo)
{
LynxDeviceInfo tempInfo = receiveScanResponse(dataBuffer, ipAddress);
int deviceIndex = checkAvailableDevices(tempInfo);
return deviceIndex;
}
return -1;
}
// Checks for matching device in list.
// If match is found: updates info and returns the index of device.
// If match is not found: device is added to the list and the index is returned.
// If failure: returns -1
int LynxHandler::checkAvailableDevices(LynxDeviceInfo& lynxDevice)
{
lynxDevice.newDevice = true;
for (int i = 0; i < this->_availableDevices.getSize(); i++)
{
char* temp = _availableDevices.at(i).deviceName;
for (int j = 0; j < 20; j++)
{
if (temp[j] != lynxDevice.deviceName[j])
break;
if (temp[j] == '\0') // Device is already in list, update info and return
{
_availableDevices.at(i) = lynxDevice;
return i;
}
}
}
int index = this->_availableDevices.appendItem(lynxDevice); // Device is not in list, add it
if (index >= 0)
{
return index;
}
return -1;
}
LynxDeviceInfo LynxHandler::receiveScanResponse(const char * dataBuffer, LynxIpAddress ipAddress)
{
LynxDeviceInfo response;
int index = 3;
for (int i = 0; i < 20; i++)
{
if ((dataBuffer[index] == '\0') || (i == 19))
{
response.deviceName[i] = '\0';
index ++;
break;
}
response.deviceName[i] = dataBuffer[index];
index++;
}
response.deviceID = uint8_t(dataBuffer[index]);
index++;
for (int i = 0; i < 4; i++)
{
response.lynxVersion[i] = dataBuffer[index];
index++;
}
response.ipAddress = ipAddress;
char checksum = 0;
for (int i = 0; i < index; i++)
{
checksum += dataBuffer[i];
}
if (checksum == dataBuffer[index])
{
return response;
}
return LynxDeviceInfo();
}
int LynxHandler::datagramFromBuffer(const char * dataBuffer)
{
LynxID tempID;
tempID.deviceID = uint8_t(dataBuffer[0]);
tempID.structTypeID = uint8_t(dataBuffer[1]);
tempID.structInstanceID = uint8_t(dataBuffer[2]);
int index = this->indexFromID(tempID);
if (index >= 0)
{
this->_structures[index].lynxID = tempID;
return this->_structures[index].fromBuffer(dataBuffer);
}
return -1;
}
StructDefinition::StructDefinition(const char _structName[], const LynxStructMode _structMode, const StructItem * _structItems, int _size)
: structName(_structName), structMode(_structMode), structItems(_structItems)
{
if (_structMode == eArrayMode)
{
size = _size;
transferSize = _size * LynxStructure::checkTransferSize(_structItems[0].dataType);
}
else if (_size > 0)
{
transferSize = 0;
size = _size;
for (int i = 0; i < size; i++)
{
transferSize += LynxStructure::checkTransferSize(_structItems[i].dataType);
}
}
else
{
transferSize = 0;
for (int i = 0; i < 256; i++)
{
if (_structItems[i].dataType == eEndOfList)
{
size = i;
return;
}
transferSize += LynxStructure::checkTransferSize(_structItems[i].dataType);
}
transferSize = 0;
size = 0;
}
}
}
| 21.632829 | 140 | 0.586911 | Kjelland |
c8b725ef7e1bf610a9eb04257b0cc95177250cb1 | 2,020 | hpp | C++ | ysu/core_test/fakes/websocket_client.hpp | lik2129/ysu_coin | 47e40ed5d4000fc59566099929bd08a9ae16a4c1 | [
"BSD-3-Clause"
] | null | null | null | ysu/core_test/fakes/websocket_client.hpp | lik2129/ysu_coin | 47e40ed5d4000fc59566099929bd08a9ae16a4c1 | [
"BSD-3-Clause"
] | null | null | null | ysu/core_test/fakes/websocket_client.hpp | lik2129/ysu_coin | 47e40ed5d4000fc59566099929bd08a9ae16a4c1 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <ysu/boost/asio/connect.hpp>
#include <ysu/boost/asio/ip/tcp.hpp>
#include <ysu/boost/beast/core.hpp>
#include <ysu/boost/beast/websocket.hpp>
#include <ysu/node/websocket.hpp>
#include <chrono>
using namespace std::chrono_literals;
namespace
{
// Creates its own io context
class fake_websocket_client
{
public:
fake_websocket_client (unsigned port) :
socket (std::make_shared<boost::beast::websocket::stream<boost::asio::ip::tcp::socket>> (ioc))
{
std::string const host = "::1";
boost::asio::ip::tcp::resolver resolver{ ioc };
auto const results = resolver.resolve (host, std::to_string (port));
boost::asio::connect (socket->next_layer (), results.begin (), results.end ());
socket->handshake (host, "/");
socket->text (true);
}
~fake_websocket_client ()
{
if (socket->is_open ())
{
socket->async_close (boost::beast::websocket::close_code::normal, [socket = this->socket](boost::beast::error_code const & ec) {
// A synchronous close usually hangs in tests when the server's io_context stops looping
// An async_close solves this problem
});
}
}
void send_message (std::string const & message_a)
{
socket->write (boost::asio::buffer (message_a));
}
void await_ack ()
{
debug_assert (socket->is_open ());
boost::beast::flat_buffer buffer;
socket->read (buffer);
}
boost::optional<std::string> get_response (std::chrono::seconds const deadline = 5s)
{
debug_assert (deadline > 0s);
boost::optional<std::string> result;
auto buffer (std::make_shared<boost::beast::flat_buffer> ());
socket->async_read (*buffer, [&result, &buffer, socket = this->socket](boost::beast::error_code const & ec, std::size_t const /*n*/) {
if (!ec)
{
std::ostringstream res;
res << beast_buffers (buffer->data ());
result = res.str ();
}
});
ioc.run_one_for (deadline);
return result;
}
private:
boost::asio::io_context ioc;
std::shared_ptr<boost::beast::websocket::stream<boost::asio::ip::tcp::socket>> socket;
};
}
| 26.933333 | 136 | 0.682178 | lik2129 |
c8bab8baf9ef025c36c65a426b2fec85107f75db | 5,451 | cpp | C++ | core/block_validation.cpp | tradingsecret/beam_wallet | abfe5dbb6c2fe325839887271150ae8e996e100f | [
"Apache-2.0"
] | 631 | 2018-11-10T05:56:05.000Z | 2022-03-30T13:21:00.000Z | core/block_validation.cpp | tradingsecret/beam_wallet | abfe5dbb6c2fe325839887271150ae8e996e100f | [
"Apache-2.0"
] | 1,824 | 2018-11-08T11:32:58.000Z | 2022-03-28T12:33:03.000Z | core/block_validation.cpp | tradingsecret/beam_wallet | abfe5dbb6c2fe325839887271150ae8e996e100f | [
"Apache-2.0"
] | 216 | 2018-11-12T08:07:21.000Z | 2022-03-08T20:50:19.000Z | // Copyright 2018 The Beam Team
//
// 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 "block_crypt.h"
namespace beam
{
/////////////
// Transaction
TxBase::Context::Params::Params()
{
ZeroObject(*this);
m_nVerifiers = 1;
}
void TxBase::Context::Reset()
{
m_Sigma = Zero;
m_Stats.Reset();
m_Height.Reset();
m_iVerifier = 0;
}
bool TxBase::Context::ShouldVerify(uint32_t& iV) const
{
if (iV)
{
iV--;
return false;
}
iV = m_Params.m_nVerifiers - 1;
return true;
}
bool TxBase::Context::ShouldAbort() const
{
return m_Params.m_pAbort && *m_Params.m_pAbort;
}
bool TxBase::Context::HandleElementHeight(const HeightRange& hr)
{
m_Height.Intersect(hr); // shrink permitted range. For blocks have no effect, since the range must already consist of a single height
return !m_Height.IsEmpty();
}
bool TxBase::Context::Merge(const Context& x)
{
if (!HandleElementHeight(x.m_Height))
return false;
m_Sigma += x.m_Sigma;
m_Stats += x.m_Stats;
return true;
}
bool TxBase::Context::ValidateAndSummarize(const TxBase& txb, IReader&& r)
{
if (m_Height.IsEmpty())
return false;
const Rules& rules = Rules::get(); // alias
auto iFork = rules.FindFork(m_Height.m_Min);
std::setmin(m_Height.m_Max, rules.get_ForkMaxHeightSafe(iFork)); // mixed versions are not allowed!
assert(!m_Height.IsEmpty());
ECC::Mode::Scope scope(ECC::Mode::Fast);
m_Sigma = -m_Sigma;
assert(m_Params.m_nVerifiers);
uint32_t iV = m_iVerifier;
// Inputs
r.Reset();
ECC::Point::Native pt;
for (const Input* pPrev = NULL; r.m_pUtxoIn; pPrev = r.m_pUtxoIn, r.NextUtxoIn())
{
if (ShouldAbort())
return false;
if (ShouldVerify(iV))
{
if (pPrev && (*pPrev > *r.m_pUtxoIn))
return false;
// make sure no redundant outputs
for (; r.m_pUtxoOut; r.NextUtxoOut())
{
int n = CmpInOut(*r.m_pUtxoIn, *r.m_pUtxoOut);
if (n < 0)
break;
if (!n)
return false; // duplicate!
}
if (!pt.Import(r.m_pUtxoIn->m_Commitment))
return false;
r.m_pUtxoIn->AddStats(m_Stats);
m_Sigma += pt;
}
}
m_Sigma = -m_Sigma;
// Outputs
r.Reset();
for (const Output* pPrev = NULL; r.m_pUtxoOut; pPrev = r.m_pUtxoOut, r.NextUtxoOut())
{
if (ShouldAbort())
return false;
if (ShouldVerify(iV))
{
if (pPrev && (*pPrev > *r.m_pUtxoOut))
{
// in case of unsigned outputs sometimes order of outputs may look incorrect (duplicated commitment, part of signatures removed)
if (!m_Params.m_bAllowUnsignedOutputs || (pPrev->m_Commitment != r.m_pUtxoOut->m_Commitment))
return false;
}
bool bSigned = r.m_pUtxoOut->m_pConfidential || r.m_pUtxoOut->m_pPublic;
if (bSigned)
{
if (!r.m_pUtxoOut->IsValid(m_Height.m_Min, pt))
return false;
}
else
{
// unsigned output
if (!m_Params.m_bAllowUnsignedOutputs)
return false;
if (!pt.Import(r.m_pUtxoOut->m_Commitment))
return false;
}
r.m_pUtxoOut->AddStats(m_Stats);
m_Sigma += pt;
}
}
for (const TxKernel* pPrev = NULL; r.m_pKernel; pPrev = r.m_pKernel, r.NextKernel())
{
if (ShouldAbort())
return false;
if (ShouldVerify(iV))
{
if (pPrev && ((*pPrev) > (*r.m_pKernel)))
return false; // wrong order
if (!r.m_pKernel->IsValid(m_Height.m_Min, m_Sigma))
return false;
HeightRange hr = r.m_pKernel->m_Height;
if (iFork >= 2)
{
if (!hr.IsEmpty() && (hr.m_Max - hr.m_Min > rules.MaxKernelValidityDH))
hr.m_Max = hr.m_Min + rules.MaxKernelValidityDH;
}
if (!HandleElementHeight(hr))
return false;
r.m_pKernel->AddStats(m_Stats);
}
}
if (ShouldVerify(iV) && !(txb.m_Offset.m_Value == Zero))
m_Sigma += ECC::Context::get().G * txb.m_Offset;
assert(!m_Height.IsEmpty());
return true;
}
bool TxBase::Context::IsValidTransaction()
{
if (m_Stats.m_Coinbase != Zero)
return false; // regular transactions should not produce coinbase outputs, only the miner should do this.
AmountBig::AddTo(m_Sigma, m_Stats.m_Fee);
return m_Sigma == Zero;
}
bool TxBase::Context::IsValidBlock()
{
AmountBig::Type subsTotal, subsLocked;
Rules::get_Emission(subsTotal, m_Height);
m_Sigma = -m_Sigma;
AmountBig::AddTo(m_Sigma, subsTotal);
if (!(m_Sigma == Zero))
return false;
if (!m_Params.m_bAllowUnsignedOutputs)
{
// Subsidy is bounded by num of blocks multiplied by coinbase emission
// There must at least some unspent coinbase UTXOs wrt maturity settings
if (m_Height.m_Max - m_Height.m_Min < Rules::get().Maturity.Coinbase)
subsLocked = subsTotal;
else
{
HeightRange hr;
hr.m_Min = m_Height.m_Max - Rules::get().Maturity.Coinbase;
hr.m_Max = m_Height.m_Max;
Rules::get_Emission(subsLocked, hr);
}
if (m_Stats.m_Coinbase < subsLocked)
return false;
}
return true;
}
} // namespace beam
| 22.903361 | 135 | 0.657127 | tradingsecret |
c8c21fb2930622d349c6c3314126de7657e6c43d | 6,160 | hpp | C++ | sdk/storage/azure-storage-blobs/inc/azure/storage/blobs/blob_batch_client.hpp | lordgamez/azure-sdk-for-cpp | 78e34a218926ac43fb06d54190b6c746eeb63692 | [
"MIT"
] | null | null | null | sdk/storage/azure-storage-blobs/inc/azure/storage/blobs/blob_batch_client.hpp | lordgamez/azure-sdk-for-cpp | 78e34a218926ac43fb06d54190b6c746eeb63692 | [
"MIT"
] | null | null | null | sdk/storage/azure-storage-blobs/inc/azure/storage/blobs/blob_batch_client.hpp | lordgamez/azure-sdk-for-cpp | 78e34a218926ac43fb06d54190b6c746eeb63692 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#pragma once
#include "azure/storage/blobs/blob_service_client.hpp"
namespace Azure { namespace Storage { namespace Blobs {
/**
* @brief A BlobBatch allows you to batch multiple Azure Storage operations in a single request
* via BlobBatchClient.SubmitBatch.
*/
class BlobBatch {
public:
/**
* @brief Marks the specified blob or snapshot for deletion.
*
* @param
* containerName The name of the container containing the blob to delete.
* @param blobName
* The name of the blob to delete.
* @param options Optional parameters to execute this
* function.
* @return An index of this operation result in
* SubmitBlobBatchResult.DeleteBlobResults, after this batch is submitted via
* BlobBatchClient.SubmitBatch.
*/
int32_t DeleteBlob(
const std::string& containerName,
const std::string& blobName,
const DeleteBlobOptions& options = DeleteBlobOptions());
/**
* @brief Sets the tier on a blob.
*
* @param containerName The name of the
* container containing the blob to set the tier of.
* @param blobName The name of the blob
* to set the tier of.
* @param Tier Indicates the tier to be set on the blob.
*
* @param options Optional parameters to execute this function.
* @return An index of this
* operation result in SubmitBlobBatchResult.SetBlobAccessTierResults, after this batch is
* submitted via BlobBatchClient.SubmitBatch.
*/
int32_t SetBlobAccessTier(
const std::string& containerName,
const std::string& blobName,
Models::AccessTier Tier,
const SetBlobAccessTierOptions& options = SetBlobAccessTierOptions());
private:
friend class BlobBatchClient;
struct DeleteBlobSubRequest
{
std::string ContainerName;
std::string BlobName;
DeleteBlobOptions Options;
};
struct SetBlobAccessTierSubRequest
{
std::string ContainerName;
std::string BlobName;
Models::AccessTier Tier = Models::AccessTier::Unknown;
SetBlobAccessTierOptions Options;
};
std::vector<DeleteBlobSubRequest> m_deleteBlobSubRequests;
std::vector<SetBlobAccessTierSubRequest> m_setBlobAccessTierSubRequests;
};
struct SubmitBlobBatchResult
{
std::vector<Azure::Core::Response<Models::DeleteBlobResult>> DeleteBlobResults;
std::vector<Azure::Core::Response<Models::SetBlobAccessTierResult>> SetBlobAccessTierResults;
};
/**
* @brief The BlobBatchClient allows you to batch multiple Azure Storage operations in a
* single request.
*/
class BlobBatchClient {
public:
/**
* @brief Initialize a new instance of BlobBatchClient.
*
* @param connectionString A connection string includes the authentication information required
* for your application to access data in an Azure Storage account at runtime.
* @param options Optional client options that define the transport pipeline policies for
* authentication, retries, etc., that are applied to every request and subrequest.
* @return A new BlobBatchClient instance.
*/
static BlobBatchClient CreateFromConnectionString(
const std::string& connectionString,
const BlobBatchClientOptions& options = BlobBatchClientOptions());
/**
* @brief Initialize a new instance of BlobBatchClient.
*
* @param serviceUri A uri referencing the blob that includes the name of the account.
* @param credential The shared key credential used to sign requests.
* @param options Optional client options that define the transport pipeline policies for
* authentication, retries, etc., that are applied to every request and subrequest.
*/
explicit BlobBatchClient(
const std::string& serviceUri,
std::shared_ptr<SharedKeyCredential> credential,
const BlobBatchClientOptions& options = BlobBatchClientOptions());
/**
* @brief Initialize a new instance of BlobBatchClient.
*
* @param serviceUri A uri referencing the blob that includes the name of the account.
* @param credential The token credential used to sign requests.
* @param options Optional client options that define the transport pipeline policies for
* authentication, retries, etc., that are applied to every request and subrequest.
*/
explicit BlobBatchClient(
const std::string& serviceUri,
std::shared_ptr<Core::TokenCredential> credential,
const BlobBatchClientOptions& options = BlobBatchClientOptions());
/**
* @brief Initialize a new instance of BlobBatchClient.
*
* @param serviceUri A uri referencing the blob that includes the name of the account, and
* possibly also a SAS token.
* @param options Optional client options that define the transport pipeline policies for
* authentication, retries, etc., that are applied to every request and subrequest.
*/
explicit BlobBatchClient(
const std::string& serviceUri,
const BlobBatchClientOptions& options = BlobBatchClientOptions());
/**
* @brief Creates a new BlobBatch to collect sub-operations that can be submitted
* together via SubmitBatch.
*
* @return A new instance of BlobBatch.
*/
static BlobBatch CreateBatch() { return BlobBatch(); }
/**
* @brief Submit a BlobBatch of sub-operations.
*
* @param batch A BlobBatch
* of sub-operations.
* @param options Optional parameters to execute this function.
*
* @return A SubmitBlobBatchResult on successful submitting.
*/
Azure::Core::Response<SubmitBlobBatchResult> SubmitBatch(
const BlobBatch& batch,
const SubmitBlobBatchOptions& options = SubmitBlobBatchOptions()) const;
protected:
Azure::Core::Http::Url m_serviceUrl;
std::shared_ptr<Azure::Core::Http::HttpPipeline> m_pipeline;
std::shared_ptr<Azure::Core::Http::HttpPipeline> m_subRequestPipeline;
};
}}} // namespace Azure::Storage::Blobs
| 36.886228 | 99 | 0.700649 | lordgamez |
c8c4ee498faa938663c0243da7df485212965077 | 25,372 | cpp | C++ | project/src/common/Graphics.cpp | delahee/lime | c4bc1ff140fa27c12f580fa3b518721e2a8266f2 | [
"MIT"
] | 1 | 2020-09-16T15:18:39.000Z | 2020-09-16T15:18:39.000Z | openfl_lime/src/common/Graphics.cpp | wannaphong/flappy | bc4630ca9120463c57c1d756c39c60a6dc509940 | [
"MIT"
] | 1 | 2020-11-17T00:58:59.000Z | 2020-11-17T00:58:59.000Z | openfl_lime/src/common/Graphics.cpp | wannaphong/flappy | bc4630ca9120463c57c1d756c39c60a6dc509940 | [
"MIT"
] | null | null | null | #include <Graphics.h>
#include "renderer/common/Surface.h"
#include <Display.h>
namespace lime
{
void Graphics::OnChanged()
{
mVersion++;
if (mOwner && !(mOwner->mDirtyFlags & dirtExtent))
mOwner->DirtyExtent();
}
// TODO: invlidate/cache extents (do for whole lot at once)
Graphics::Graphics(DisplayObject *inOwner,bool inInitRef) : Object(inInitRef)
{
mRotation0 = 0;
mCursor = UserPoint(0,0);
mHardwareData = 0;
mPathData = new GraphicsPath;
mBuiltHardware = 0;
mTileJob.mIsTileJob = true;
mMeasuredJobs = 0;
mVersion = 0;
mOwner = inOwner;
}
Graphics::~Graphics()
{
mOwner = 0;
clear();
mPathData->DecRef();
}
void Graphics::clear()
{
mFillJob.clear();
mLineJob.clear();
mTileJob.clear();
// clear jobs
for(int i=0;i<mJobs.size();i++)
mJobs[i].clear();
mJobs.resize(0);
if (mHardwareData)
{
delete mHardwareData;
mHardwareData = 0;
}
mPathData->clear();
mExtent0 = Extent2DF();
mRotation0 = 0;
mBuiltHardware = 0;
mMeasuredJobs = 0;
mCursor = UserPoint(0,0);
OnChanged();
}
int Graphics::Version() const
{
int result = mVersion;
for(int i=0;i<mJobs.size();i++)
result += mJobs[i].Version();
return result;
}
#define SIN45 0.70710678118654752440084436210485
#define TAN22 0.4142135623730950488016887242097
void Graphics::drawEllipse(float x, float y, float width, float height)
{
x += width/2;
y += height/2;
float w = width*0.5;
float w_ = w*SIN45;
float cw_ = w*TAN22;
float h = height*0.5;
float h_ = h*SIN45;
float ch_ = h*TAN22;
Flush();
mPathData->moveTo(x+w,y);
mPathData->curveTo(x+w, y+ch_, x+w_, y+h_);
mPathData->curveTo(x+cw_,y+h, x, y+h);
mPathData->curveTo(x-cw_,y+h, x-w_, y+h_);
mPathData->curveTo(x-w, y+ch_, x-w, y);
mPathData->curveTo(x-w, y-ch_, x-w_, y-h_);
mPathData->curveTo(x-cw_,y-h, x, y-h);
mPathData->curveTo(x+cw_,y-h, x+w_, y-h_);
mPathData->curveTo(x+w, y-ch_, x+w, y);
Flush();
OnChanged();
}
/*
< ------------ w ----->
< -------- w_ ----->
< ------ cw_ ----->
< --- lw --->
c --------------+
222 | x
2 |
p
c 1 .. ry
1 .
1 ..|
| - rx --
|
|
*/
void Graphics::drawRoundRect(float x,float y,float width,float height,float rx,float ry)
{
rx *= 0.5;
ry *= 0.5;
float w = width*0.5;
x+=w;
if (rx>w) rx = w;
float lw = w - rx;
float w_ = lw + rx*SIN45;
float cw_ = lw + rx*TAN22;
float h = height*0.5;
y+=h;
if (ry>h) ry = h;
float lh = h - ry;
float h_ = lh + ry*SIN45;
float ch_ = lh + ry*TAN22;
Flush();
mPathData->moveTo(x+w,y+lh);
mPathData->curveTo(x+w, y+ch_, x+w_, y+h_);
mPathData->curveTo(x+cw_,y+h, x+lw, y+h);
mPathData->lineTo(x-lw, y+h);
mPathData->curveTo(x-cw_,y+h, x-w_, y+h_);
mPathData->curveTo(x-w, y+ch_, x-w, y+lh);
mPathData->lineTo( x-w, y-lh);
mPathData->curveTo(x-w, y-ch_, x-w_, y-h_);
mPathData->curveTo(x-cw_,y-h, x-lw, y-h);
mPathData->lineTo(x+lw, y-h);
mPathData->curveTo(x+cw_,y-h, x+w_, y-h_);
mPathData->curveTo(x+w, y-ch_, x+w, y-lh);
mPathData->lineTo(x+w, y+lh);
Flush();
OnChanged();
}
void Graphics::drawPath(const QuickVec<uint8> &inCommands, const QuickVec<float> &inData,
WindingRule inWinding )
{
int n = inCommands.size();
if (n==0 || inData.size()<2)
return;
const UserPoint *point = (UserPoint *)&inData[0];
const UserPoint *last = point + inData.size()/2;
if ( (mFillJob.mFill && mFillJob.mCommand0==mPathData->commands.size()) ||
(mLineJob.mStroke && mLineJob.mCommand0==mPathData->commands.size()) )
mPathData->initPosition(mCursor);
for(int i=0;i<n && point<last;i++)
{
switch(inCommands[i])
{
case pcWideMoveTo:
point++;
if (point==last) break;
case pcMoveTo:
mPathData->moveTo(point->x,point->y);
mCursor = *point++;
break;
case pcWideLineTo:
point++;
if (point==last) break;
case pcLineTo:
mPathData->lineTo(point->x,point->y);
mCursor = *point++;
break;
case pcCurveTo:
if (point+1==last) break;
mPathData->curveTo(point->x,point->y,point[1].x,point[1].y);
mCursor = point[1];
point += 2;
}
}
OnChanged();
}
void Graphics::drawGraphicsDatum(IGraphicsData *inData)
{
switch(inData->GetType())
{
case gdtUnknown: break;
case gdtTrianglePath: break;
case gdtPath:
{
GraphicsPath *path = inData->AsPath();
drawPath(path->commands, path->data, path->winding);
break;
}
case gdtEndFill:
endFill();
break;
case gdtSolidFill:
case gdtGradientFill:
case gdtBitmapFill:
{
IGraphicsFill *fill = inData->AsIFill();
if (fill->isSolidStyle())
{
Flush(false,true);
endTiles();
if (mFillJob.mFill)
mFillJob.mFill->DecRef();
mFillJob.mFill = fill;
mFillJob.mFill->IncRef();
if (mFillJob.mCommand0 == mPathData->commands.size())
mPathData->initPosition(mCursor);
}
else if (mLineJob.mStroke)
{
Flush(true,false);
mLineJob.mStroke = mLineJob.mStroke->CloneWithFill(fill);
}
}
break;
case gdtStroke:
{
Flush(true,false);
if (mLineJob.mStroke)
{
mLineJob.mStroke->DecRef();
mLineJob.mStroke = 0;
}
GraphicsStroke *stroke = inData->AsStroke();
if (stroke->thickness>=0 && stroke->fill)
{
mLineJob.mStroke = stroke;
mLineJob.mStroke->IncRef();
if (mLineJob.mCommand0 == mPathData->commands.size())
mPathData->initPosition(mCursor);
}
}
break;
}
OnChanged();
}
void Graphics::drawGraphicsData(IGraphicsData **graphicsData,int inN)
{
for(int i=0;i<inN;i++)
drawGraphicsDatum(graphicsData[i]);
OnChanged();
}
void Graphics::beginFill(unsigned int color, float alpha)
{
Flush(false,true,true);
endTiles();
if (mFillJob.mFill)
mFillJob.mFill->DecRef();
mFillJob.mFill = new GraphicsSolidFill(color,alpha);
mFillJob.mFill->IncRef();
if (mFillJob.mCommand0 == mPathData->commands.size())
mPathData->initPosition(mCursor);
}
void Graphics::endFill()
{
Flush(true,true);
if (mFillJob.mFill)
{
mFillJob.mFill->DecRef();
mFillJob.mFill = 0;
}
}
void Graphics::beginBitmapFill(Surface *bitmapData, const Matrix &inMatrix,
bool inRepeat, bool inSmooth)
{
Flush(false,true,true);
endTiles();
if (mFillJob.mFill)
mFillJob.mFill->DecRef();
mFillJob.mFill = new GraphicsBitmapFill(bitmapData,inMatrix,inRepeat,inSmooth);
mFillJob.mFill->IncRef();
if (mFillJob.mCommand0 == mPathData->commands.size())
mPathData->initPosition(mCursor);
}
void Graphics::endTiles()
{
if (mTileJob.mFill)
{
mTileJob.mFill->DecRef();
mTileJob.mFill = 0;
OnChanged();
}
}
void Graphics::beginTiles(Surface *bitmapData,bool inSmooth,int inBlendMode)
{
endFill();
lineStyle(-1);
Flush();
if (mTileJob.mFill)
mTileJob.mFill->DecRef();
mTileJob.mFill = new GraphicsBitmapFill(bitmapData,Matrix(),false,inSmooth);
mTileJob.mFill->IncRef();
mPathData->elementBlendMode(inBlendMode);
}
void Graphics::lineStyle(double thickness, unsigned int color, double alpha,
bool pixelHinting, StrokeScaleMode scaleMode,
StrokeCaps caps,
StrokeJoints joints, double miterLimit)
{
Flush(true,false,true);
endTiles();
if (mLineJob.mStroke)
{
mLineJob.mStroke->DecRef();
mLineJob.mStroke = 0;
}
if (thickness>=0)
{
IGraphicsFill *solid = new GraphicsSolidFill(color,alpha);
mLineJob.mStroke = new GraphicsStroke(solid,thickness,pixelHinting,
scaleMode,caps,joints,miterLimit);
mLineJob.mStroke->IncRef();
if (mLineJob.mCommand0 == mPathData->commands.size())
mPathData->initPosition(mCursor);
}
}
void Graphics::lineTo(float x, float y)
{
if ( (mFillJob.mFill && mFillJob.mCommand0==mPathData->commands.size()) ||
(mLineJob.mStroke && mLineJob.mCommand0==mPathData->commands.size()) )
mPathData->initPosition(mCursor);
mPathData->lineTo(x,y);
mCursor = UserPoint(x,y);
OnChanged();
}
void Graphics::moveTo(float x, float y)
{
mPathData->moveTo(x,y);
mCursor = UserPoint(x,y);
OnChanged();
}
void Graphics::curveTo(float cx, float cy, float x, float y)
{
if ( (mFillJob.mFill && mFillJob.mCommand0==mPathData->commands.size()) ||
(mLineJob.mStroke && mLineJob.mCommand0==mPathData->commands.size()) )
mPathData->initPosition(mCursor);
if ( (fabs(mCursor.x-cx)<0.00001 && fabs(mCursor.y-cy)<0.00001) ||
(fabs(x-cx)<0.00001 && fabs(y-cy)<0.00001) )
{
mPathData->lineTo(x,y);
}
else
mPathData->curveTo(cx,cy,x,y);
mCursor = UserPoint(x,y);
OnChanged();
}
void Graphics::arcTo(float cx, float cy, float x, float y)
{
if ( (mFillJob.mFill && mFillJob.mCommand0==mPathData->commands.size()) ||
(mLineJob.mStroke && mLineJob.mCommand0==mPathData->commands.size()) )
mPathData->initPosition(mCursor);
mPathData->arcTo(cx,cy,x,y);
mCursor = UserPoint(x,y);
OnChanged();
}
void Graphics::tile(float x, float y, const Rect &inTileRect,float *inTrans,float *inRGBA)
{
mPathData->tile(x,y,inTileRect,inTrans,inRGBA);
}
void Graphics::drawPoints(QuickVec<float> inXYs, QuickVec<int> inRGBAs, unsigned int inDefaultRGBA,
double inSize)
{
endFill();
lineStyle(-1);
Flush();
GraphicsJob job;
job.mCommand0 = mPathData->commands.size();
job.mCommandCount = 1;
job.mData0 = mPathData->data.size();
job.mIsPointJob = true;
mPathData->drawPoints(inXYs,inRGBAs);
job.mDataCount = mPathData->data.size() - job.mData0;
if (mPathData->commands[job.mCommand0]==pcPointsXY)
{
job.mFill = new GraphicsSolidFill(inDefaultRGBA&0xffffff,(inDefaultRGBA>>24)/255.0);
job.mFill->IncRef();
}
if (inSize>0)
{
job.mStroke = new GraphicsStroke(0,inSize);
job.mStroke->IncRef();
}
mJobs.push_back(job);
}
void Graphics::drawTriangles(const QuickVec<float> &inXYs,
const QuickVec<int> &inIndices,
const QuickVec<float> &inUVT, int inCull,
const QuickVec<int> &inColours,
int blendMode)
{
Flush( );
if (!mFillJob.mFill)
{
beginFill (0, 0);
}
IGraphicsFill *fill = mFillJob.mFill;
GraphicsTrianglePath *path = new GraphicsTrianglePath(inXYs,
inIndices, inUVT, inCull, inColours, blendMode );
GraphicsJob job;
path->IncRef();
if (!fill || !fill->AsBitmapFill())
path->mUVT.resize(0);
job.mFill = fill ? fill->IncRef() : 0;
job.mStroke = mLineJob.mStroke ? mLineJob.mStroke->IncRef() : 0;
job.mTriangles = path;
mJobs.push_back(job);
}
// This routine converts a list of "GraphicsPaths" (mItems) into a list
// of LineData and SolidData.
// The items intermix fill-styles and line-stypes with move/draw/triangle
// geometry data - this routine separates them out.
void Graphics::Flush(bool inLine, bool inFill, bool inTile)
{
int n = mPathData->commands.size();
int d = mPathData->data.size();
bool wasFilled = false;
if (inTile)
{
if (mTileJob.mFill && mTileJob.mCommand0 <n)
{
mTileJob.mFill->IncRef();
mTileJob.mDataCount = d-mTileJob.mData0;
mTileJob.mCommandCount = n-mTileJob.mCommand0;
mTileJob.mIsTileJob = true;
mJobs.push_back(mTileJob);
}
}
// Do fill first, so lines go over top.
if (inFill)
{
if (mFillJob.mFill && mFillJob.mCommand0 <n)
{
mFillJob.mFill->IncRef();
mFillJob.mCommandCount = n-mFillJob.mCommand0;
mFillJob.mDataCount = d-mFillJob.mData0;
wasFilled = true;
// Move the fill job up the list so it is "below" lines that start at the same
// (or later) data point
int pos = mJobs.size()-1;
while(pos>=0)
{
if (mJobs[pos].mData0 < mFillJob.mData0)
break;
pos--;
}
pos++;
if (pos==mJobs.size())
{
mJobs.push_back(mFillJob);
}
else
{
mJobs.InsertAt(0,mFillJob);
}
mFillJob.mCommand0 = n;
mFillJob.mData0 = d;
}
}
if (inLine)
{
if (mLineJob.mStroke && mLineJob.mCommand0 <n-1)
{
mLineJob.mStroke->IncRef();
// Add closing segment...
if (wasFilled)
{
mPathData->closeLine(mLineJob.mCommand0,mLineJob.mData0);
n = mPathData->commands.size();
d = mPathData->data.size();
}
mLineJob.mCommandCount = n-mLineJob.mCommand0;
mLineJob.mDataCount = d-mLineJob.mData0;
mJobs.push_back(mLineJob);
}
mLineJob.mCommand0 = n;
mLineJob.mData0 = d;
}
if (inTile)
{
mTileJob.mCommand0 = n;
mTileJob.mData0 = d;
}
if (inFill)
{
mFillJob.mCommand0 = n;
mFillJob.mData0 = d;
}
}
Extent2DF Graphics::GetSoftwareExtent(const Transform &inTransform, bool inIncludeStroke)
{
Extent2DF result;
Flush();
for(int i=0;i<mJobs.size();i++)
{
GraphicsJob &job = mJobs[i];
if (!job.mSoftwareRenderer)
job.mSoftwareRenderer = Renderer::CreateSoftware(job,*mPathData);
job.mSoftwareRenderer->GetExtent(inTransform,result,inIncludeStroke);
}
return result;
}
const Extent2DF &Graphics::GetExtent0(double inRotation)
{
if ( mMeasuredJobs<mJobs.size() || inRotation!=mRotation0)
{
Transform trans;
Matrix m;
trans.mMatrix = &m;
if (inRotation)
m.Rotate(inRotation);
mExtent0 = GetSoftwareExtent(trans,true);
mRotation0 = inRotation;
mMeasuredJobs = mJobs.size();
}
return mExtent0;
}
bool Graphics::Render( const RenderTarget &inTarget, const RenderState &inState )
{
Flush();
#ifdef LIME_DIRECTFB
for(int i=0;i<mJobs.size();i++)
{
GraphicsJob &job = mJobs[i];
if (!job.mHardwareRenderer /*&& !job.mSoftwareRenderer*/)
job.mHardwareRenderer = Renderer::CreateHardware(job,*mPathData,*inTarget.mHardware);
//if (!job.mSoftwareRenderer)
//job.mSoftwareRenderer = Renderer::CreateSoftware(job,*mPathData);
if (inState.mPhase==rpHitTest)
{
if (job.mHardwareRenderer && job.mSoftwareRenderer->Hits(inState))
{
return true;
}
/*else if (job.mSoftwareRenderer && job.mSoftwareRenderer->Hits(inState))
{
return true;
}*/
}
else
{
if (job.mHardwareRenderer)
job.mHardwareRenderer->Render(inTarget,inState);
//else
//job.mSoftwareRenderer->Render(inTarget,inState);
}
}
#else
if (inTarget.IsHardware())
{
if (!mHardwareData)
mHardwareData = new HardwareData();
else if (!mHardwareData->isScaleOk(inState))
{
mHardwareData->clear();
mBuiltHardware = 0;
}
while(mBuiltHardware<mJobs.size())
{
BuildHardwareJob(mJobs[mBuiltHardware++],*mPathData,*mHardwareData,*inTarget.mHardware,inState);
}
if (mHardwareData && !mHardwareData->mElements.empty())
{
if (inState.mPhase==rpHitTest)
return inTarget.mHardware->Hits(inState,*mHardwareData);
else
inTarget.mHardware->Render(inState,*mHardwareData);
}
}
else
{
for(int i=0;i<mJobs.size();i++)
{
GraphicsJob &job = mJobs[i];
if (!job.mSoftwareRenderer)
job.mSoftwareRenderer = Renderer::CreateSoftware(job,*mPathData);
if (inState.mPhase==rpHitTest)
{
if (job.mSoftwareRenderer->Hits(inState))
return true;
}
else
job.mSoftwareRenderer->Render(inTarget,inState);
}
}
#endif
return false;
}
// --- RenderState -------------------------------------------------------------------
void GraphicsJob::clear()
{
if (mStroke) mStroke->DecRef();
if (mFill) mFill->DecRef();
if (mTriangles) mTriangles->DecRef();
if (mSoftwareRenderer) mSoftwareRenderer->Destroy();
bool was_tile = mIsTileJob;
memset(this,0,sizeof(GraphicsJob));
mIsTileJob = was_tile;
}
// --- RenderState -------------------------------------------------------------------
ColorTransform sgIdentityColourTransform;
RenderState::RenderState(Surface *inSurface,int inAA)
{
mTransform.mAAFactor = inAA;
mMask = 0;
mPhase = rpRender;
mAlpha_LUT = 0;
mC0_LUT = 0;
mC1_LUT = 0;
mC2_LUT = 0;
mColourTransform = &sgIdentityColourTransform;
mRoundSizeToPOW2 = false;
mHitResult = 0;
mRecurse = true;
mTargetOffset = ImagePoint(0,0);
if (inSurface)
{
mClipRect = Rect(inSurface->Width(),inSurface->Height());
}
else
mClipRect = Rect(0,0);
}
void RenderState::CombineColourTransform(const RenderState &inState,
const ColorTransform *inObjTrans,
ColorTransform *inBuf)
{
mAlpha_LUT = mColourTransform->IsIdentityAlpha() ? 0 : mColourTransform->GetAlphaLUT();
if (inObjTrans->IsIdentity())
{
mColourTransform = inState.mColourTransform;
mAlpha_LUT = inState.mAlpha_LUT;
mC0_LUT = inState.mC0_LUT;
mC1_LUT = inState.mC1_LUT;
mC2_LUT = inState.mC2_LUT;
return;
}
mColourTransform = inBuf;
inBuf->Combine(*(inState.mColourTransform),*inObjTrans);
if (mColourTransform->IsIdentityColour())
{
mC0_LUT = 0;
mC1_LUT = 0;
mC2_LUT = 0;
}
else
{
mC0_LUT = mColourTransform->GetC0LUT();
mC1_LUT = mColourTransform->GetC1LUT();
mC2_LUT = mColourTransform->GetC2LUT();
}
if (mColourTransform->IsIdentityAlpha())
mAlpha_LUT = 0;
else
mAlpha_LUT = mColourTransform->GetAlphaLUT();
}
// --- RenderTarget -------------------------------------------------------------------
RenderTarget::RenderTarget(const Rect &inRect,PixelFormat inFormat,uint8 *inPtr, int inStride)
{
mRect = inRect;
mPixelFormat = inFormat;
mSoftPtr = inPtr;
mSoftStride = inStride;
mHardware = 0;
}
RenderTarget::RenderTarget(const Rect &inRect,HardwareContext *inContext)
{
mRect = inRect;
mPixelFormat = pfHardware;
mSoftPtr = 0;
mSoftStride = 0;
mHardware = inContext;
}
RenderTarget::RenderTarget() : mRect(0,0)
{
mPixelFormat = pfAlpha;
mSoftPtr = 0;
mSoftStride = 0;
mHardware = 0;
}
RenderTarget RenderTarget::ClipRect(const Rect &inRect) const
{
RenderTarget result = *this;
result.mRect = result.mRect.Intersect(inRect);
return result;
}
void RenderTarget::Clear(uint32 inColour, const Rect &inRect) const
{
if (IsHardware())
{
mHardware->Clear(inColour,&inRect);
return;
}
if (mPixelFormat==pfAlpha)
{
int val = inColour>>24;
for(int y=inRect.y;y<inRect.y1();y++)
{
uint8 *alpha = (uint8 *)Row(y) + inRect.x;
memset(alpha,val,inRect.w);
}
}
else
{
ARGB rgb(inColour);
if ( mPixelFormat&pfSwapRB)
rgb.SwapRB();
if (!(mPixelFormat & pfHasAlpha))
rgb.a = 255;
for(int y=inRect.y;y<inRect.y1();y++)
{
int *ptr = (int *)Row(y) + inRect.x;
for(int x=0;x<inRect.w;x++)
*ptr++ = rgb.ival;
}
}
}
// --- GraphicsBitmapFill -------------------------------------------------------------------
GraphicsBitmapFill::GraphicsBitmapFill(Surface *inBitmapData,
const Matrix &inMatrix, bool inRepeat, bool inSmooth) : bitmapData(inBitmapData),
matrix(inMatrix), repeat(inRepeat), smooth(inSmooth)
{
if (bitmapData)
bitmapData->IncRef();
}
GraphicsBitmapFill::~GraphicsBitmapFill()
{
if (bitmapData)
bitmapData->DecRef();
}
int GraphicsBitmapFill::Version() const
{
return bitmapData->Version();
}
// --- GraphicsStroke -------------------------------------------------------------------
GraphicsStroke::GraphicsStroke(IGraphicsFill *inFill, double inThickness,
bool inPixelHinting, StrokeScaleMode inScaleMode,
StrokeCaps inCaps,
StrokeJoints inJoints, double inMiterLimit)
: fill(inFill), thickness(inThickness), pixelHinting(inPixelHinting),
scaleMode(inScaleMode), caps(inCaps), joints(inJoints), miterLimit(inMiterLimit)
{
if (fill)
fill->IncRef();
}
GraphicsStroke::~GraphicsStroke()
{
if (fill)
fill->DecRef();
}
GraphicsStroke *GraphicsStroke::CloneWithFill(IGraphicsFill *inFill)
{
if (mRefCount < 2)
{
inFill->IncRef();
if (fill)
fill->DecRef();
fill = inFill;
return this;
}
GraphicsStroke *clone = new GraphicsStroke(inFill,thickness,pixelHinting,scaleMode,caps,joints,miterLimit);
DecRef();
clone->IncRef();
return clone;
}
// --- Gradient ---------------------------------------------------------------------
static void GetLinearLookups(int **outToLinear, int **outFromLinear)
{
static int *to = 0;
static int *from = 0;
if (!to)
{
double a = 0.055;
to = new int[256];
from = new int[4096];
for(int i=0;i<4096;i++)
{
double t = i / 4095.0;
from[i] = 255.0 * (t<=0.0031308 ? t*12.92 : (a+1)*pow(t,1/2.4)-a) + 0.5;
}
for(int i=0;i<256;i++)
{
double t = i / 255.0;
to[i] = 4095.0 * ( t<=0.04045 ? t/12.92 : pow( (t+a)/(1+a), 2.4 ) ) + 0.5;
}
}
*outToLinear = to;
*outFromLinear = from;
}
void GraphicsGradientFill::FillArray(ARGB *outColours, bool inSwap)
{
int *ToLinear = 0;
int *FromLinear = 0;
if (interpolationMethod==imLinearRGB)
GetLinearLookups(&ToLinear,&FromLinear);
bool reflect = spreadMethod==smReflect;
int n = mStops.size();
if (n==0)
memset(outColours,0,sizeof(ARGB)*(reflect?512:256));
else
{
int i;
int last = mStops[0].mPos;
if (last>255) last = 255;
for(i=0;i<=last;i++)
outColours[i] = mStops[0].mARGB;
for(int k=0;k<n-1;k++)
{
ARGB c0 = mStops[k].mARGB;
int p0 = mStops[k].mPos;
int p1 = mStops[k+1].mPos;
int diff = p1 - p0;
if (diff>0)
{
if (p0<0) p0 = 0;
if (p1>256) p1 = 256;
int da = mStops[k+1].mARGB.a - c0.a;
if (ToLinear)
{
int dc0 = ToLinear[mStops[k+1].mARGB.c0] - ToLinear[c0.c0];
int dc1 = ToLinear[mStops[k+1].mARGB.c1] - ToLinear[c0.c1];
int dc2 = ToLinear[mStops[k+1].mARGB.c2] - ToLinear[c0.c2];
for(i=p0;i<p1;i++)
{
outColours[i].c1= FromLinear[ ToLinear[c0.c1] + dc1*(i-p0)/diff];
if (inSwap)
{
outColours[i].c2= FromLinear[ ToLinear[c0.c0] + dc0*(i-p0)/diff];
outColours[i].c0= FromLinear[ ToLinear[c0.c2] + dc2*(i-p0)/diff];
}
else
{
outColours[i].c0= FromLinear[ ToLinear[c0.c0] + dc0*(i-p0)/diff];
outColours[i].c2= FromLinear[ ToLinear[c0.c2] + dc2*(i-p0)/diff];
}
outColours[i].a = FromLinear[ ToLinear[c0.a] + da*(i-p0)/diff];
}
}
else
{
int dc0 = mStops[k+1].mARGB.c0 - c0.c0;
int dc1 = mStops[k+1].mARGB.c1 - c0.c1;
int dc2 = mStops[k+1].mARGB.c2 - c0.c2;
for(i=p0;i<p1;i++)
{
outColours[i].c1 = c0.c1 + dc1*(i-p0)/diff;
if (inSwap)
{
outColours[i].c2 = c0.c0 + dc0*(i-p0)/diff;
outColours[i].c0 = c0.c2 + dc2*(i-p0)/diff;
}
else
{
outColours[i].c0 = c0.c0 + dc0*(i-p0)/diff;
outColours[i].c2 = c0.c2 + dc2*(i-p0)/diff;
}
outColours[i].a = c0.a + da*(i-p0)/diff;
}
}
}
}
for(;i<256;i++)
outColours[i] = mStops[n-1].mARGB;
if (reflect)
{
for(;i<512;i++)
outColours[i] = outColours[511-i];
}
}
}
// --- Helper ----------------------------------------
int UpToPower2(int inX)
{
int result = 1;
while(result<inX) result<<=1;
return result;
}
}
| 24.704966 | 110 | 0.563377 | delahee |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.