hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
41edfaea15becfca33eff1e5d2f51a984559b920 | 9,449 | cpp | C++ | VSRootAnalysis/VSRHistogram1D.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSRootAnalysis/VSRHistogram1D.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSRootAnalysis/VSRHistogram1D.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
#include <iostream>
#include <algorithm>
#include <sstream>
// ----------------------------------------------------------------------------
// ChiLA Includes
// ----------------------------------------------------------------------------
#include <WhippleCams.h>
#include <VSSimpleHist.hpp>
// ----------------------------------------------------------------------------
// ROOT Includes
// ----------------------------------------------------------------------------
#include <TEllipse.h>
#include <TPaletteAxis.h>
#include <TH2F.h>
#include <TStyle.h>
#include <TBox.h>
#include <TGaxis.h>
#include <TPaveText.h>
#include <TVectorT.h>
// ----------------------------------------------------------------------------
// Local Includes
// ----------------------------------------------------------------------------
#include "VSRHistogram1D.hpp"
using namespace std;
using namespace VERITAS;
// ============================================================================
// Factory Methods
// ============================================================================
VSRHistogram1D* VSRHistogram1D::create(TVectorT<double>& v,
double min, double max)
{
const unsigned nrow = v.GetNrows();
VSRHistogram1D* hist;
if(min != max)
hist = new VSRHistogram1D(nrow, min, max);
else
hist = new VSRHistogram1D(nrow, 0, (double)nrow);
for(unsigned irow = 0; irow < nrow; irow++)
hist->set(irow,v[irow]);
return hist;
}
VSRHistogram1D* VSRHistogram1D::create(TVectorT<double>& v,
TVectorT<double>& var,
double min, double max)
{
const unsigned nrow = v.GetNrows();
VSRHistogram1D* hist;
if(min != max)
hist = new VSRHistogram1D(nrow, min, max);
else
hist = new VSRHistogram1D(nrow, 0, (double)nrow);
for(unsigned irow = 0; irow < nrow; irow++)
{
hist->set(irow,v[irow]);
hist->setError(irow,sqrt(var[irow]));
}
return hist;
}
VSRHistogram1D* VSRHistogram1D::create(VERITAS::VSNSpace& nspace)
{
VERITAS::VSNSpace nspace_proj = nspace;
std::set< unsigned > dims;
dims.insert(0);
nspace_proj.project(dims);
VSRHistogram1D* hist =
new VSRHistogram1D(nspace_proj.space().axes[0].nbin,
nspace_proj.space().axes[0].lo_bound,
nspace_proj.space().axes[0].hi_bound);
VERITAS::VSNSpace::Cell c(1);
for(c.i[0]=0; c.i[0]<nspace.space().axes[0].nbin; c.i[0]++)
{
VERITAS::VSNSpace::Weight w = -1; // initialize any value
nspace_proj.getWeight(c,w);
if(std::isfinite(w))
hist->set(c.i[0],w);
}
return hist;
}
// ============================================================================
// Constructors
// ============================================================================
VSRHistogram1D::VSRHistogram1D():
m_title(), m_nBins(), m_loX(), m_hiX(), m_binWidth()
{
m_hist.reset(new TH1F("","",100,0.0,1.0));
m_hist->SetDirectory(0);
}
VSRHistogram1D::VSRHistogram1D(unsigned nbins, double lo, double hi,
const std::string& title):
m_title(title), m_nBins(nbins), m_loX(lo), m_hiX(hi), m_binWidth()
{
m_binWidth = (m_hiX-m_loX)/(double)m_nBins;
m_hist.reset(new TH1F(title.c_str(),title.c_str(),nbins,lo,hi));
m_hist->SetDirectory(0);
}
VSRHistogram1D::~VSRHistogram1D()
{
}
void VSRHistogram1D::dump()
{
for(unsigned ibin = 0; ibin < getNBins(); ibin++)
{
std::cout << std::setw(20) << getX(ibin)
<< std::setw(20) << get(ibin)
<< std::setw(20) << getError(ibin)
<< std::endl;
}
}
void VSRHistogram1D::draw()
{
m_hist->SetMarkerStyle(m_options.markerStyle);
m_hist->SetMarkerColor(m_options.markerColor);
m_hist->SetLineStyle(m_options.lineStyle);
m_hist->SetLineColor(m_options.lineColor);
m_hist->SetLineWidth(m_options.lineWidth);
m_hist->SetFillColor(m_options.fillColor);
std::string drawOptions = "SAME"; // Forces not to redraw axes!
if(m_options.showErrors) drawOptions += "E";
else drawOptions += "HIST";
drawOptions += m_options.drawOptions;
m_hist->Draw(drawOptions.c_str());
}
VSRHistogram1D* VSRHistogram1D::clone() const
{
VSRHistogram1D* hist = new VSRHistogram1D(*this);
return hist;
}
double VSRHistogram1D::getIntegral()
{
double bin_size = (m_hiX-m_loX)/(double)m_nBins;
double sum = 0;
for(unsigned ibin = 0; ibin < getNBins(); ibin++)
sum += this->get(ibin)*bin_size;
return sum;
}
TH1F* VSRHistogram1D::getHistogram() { return m_hist.get(); }
void VSRHistogram1D::initialize(unsigned n, double lo, double hi)
{
m_hist.reset(new TH1F(m_title.c_str(),
m_title.c_str(),
n,lo,hi));
m_hist->SetDirectory(0);
}
VSRHistogram1D::VSRHistogram1D(const VSRHistogram1D& hist)
{
*this = hist;
}
VSRHistogram1D& VSRHistogram1D::operator=(const VSRHistogram1D & hist)
{
m_hist.reset( (TH1F*)hist.m_hist->Clone() );
m_hist->SetDirectory(0);
m_title = hist.m_title;
m_nBins = hist.m_nBins;
m_loX = hist.m_loX;
m_hiX = hist.m_hiX;
return *this;
}
void VSRHistogram1D::subtract(VSRHistogram1D* hist, double weight)
{
m_hist->Sumw2();
hist->getHistogram()->Sumw2();
m_hist->Add(hist->getHistogram(),-weight);
}
VSRHistogram1D VSRHistogram1D::operator-(const VSRHistogram1D & hist) const
{
return VSRHistogram1D(*this) -= hist;
}
VSRHistogram1D& VSRHistogram1D::operator-=(const VSRHistogram1D & hist)
{
m_hist->Add(hist.m_hist.get(),-1.0);
return *this;
}
VSRHistogram1D VSRHistogram1D::operator/(const VSRHistogram1D & hist) const
{
return VSRHistogram1D(*this) /= hist;
}
VSRHistogram1D& VSRHistogram1D::operator/=(const VSRHistogram1D & hist)
{
for(unsigned ibin = 0; ibin < getNBins(); ibin++)
{
if(hist.get(ibin) == 0 || get(ibin) == 0)
{
set(ibin,0);
setError(ibin,0);
}
else
{
double x = get(ibin);
double xerr = getError(ibin);
double y = hist.get(ibin);
double yerr = hist.getError(ibin);
double err = x/y*sqrt(pow(xerr/x,2) + pow(yerr/y,2));
set(ibin,x/y);
setError(ibin,err);
}
}
return *this;
}
void VSRHistogram1D::fill(double x, double w)
{
m_hist->Fill(x,w);
}
void VSRHistogram1D::fillBin(unsigned ibin, double w)
{
set(ibin,w+get(ibin));
}
void VSRHistogram1D::rebin(unsigned ngroup)
{
m_hist->Rebin(ngroup);
}
void VSRHistogram1D::set(unsigned ibin, double x)
{
m_hist->SetBinContent(ibin+1,x);
}
void VSRHistogram1D::setError(unsigned ibin, double err)
{
m_hist->SetBinError(ibin+1,err);
}
double VSRHistogram1D::getX(unsigned ibin) const
{
return m_hist->GetBinCenter(ibin+1);
}
double VSRHistogram1D::get(unsigned ibin) const
{
return m_hist->GetBinContent(ibin+1);
}
double VSRHistogram1D::getError(unsigned ibin) const
{
return m_hist->GetBinError(ibin+1);
}
double VSRHistogram1D::getSum()
{
double sum = 0;
for(int i = 1; i <= m_hist->GetNbinsX(); i++)
sum += m_hist->GetBinContent(i);
return sum;
}
double VSRHistogram1D::getRMS()
{
return m_hist->GetRMS();
}
void VSRHistogram1D::fit(string fname)
{
m_hist->Fit(fname.c_str(),"N","E");
}
void VSRHistogram1D::fit(string fname, double lo, double hi)
{
m_hist->Fit(fname.c_str(),"N","E",lo,hi);
}
void VSRHistogram1D::normalize()
{
double sum = getSum();
if(sum == 0)
return;
for(int i = 1; i <= m_hist->GetNbinsX(); i++)
{
double content = m_hist->GetBinContent(i);;
double err = m_hist->GetBinError(i);
m_hist->SetBinContent(i,content/sum);
m_hist->SetBinError(i,err/sum);
}
}
void VSRHistogram1D::normalizeMax()
{
double max = m_hist->GetMaximum();
for(int i = 1; i <= m_hist->GetNbinsX(); i++)
{
set(i-1,get(i-1)/max);
setError(i-1,getError(i-1)/max);
}
}
void VSRHistogram1D::transform(const std::string& transform)
{
for(int i = m_hist->GetNbinsX(); i >= 1; i--)
{
double content = m_hist->GetBinContent(i);;
double err = m_hist->GetBinError(i);
if(transform == "sq")
{
content = std::pow(content,2);
err = 2*err;
}
m_hist->SetBinContent(i,content);
m_hist->SetBinError(i,err);
}
}
void VSRHistogram1D::cumulative(const std::string& lr)
{
double sum = 0;
double sum_var = 0;
if(lr == "r")
{
for(int i = m_hist->GetNbinsX(); i >= 1; i--)
{
double content = m_hist->GetBinContent(i);;
double err = m_hist->GetBinError(i);
sum += content;
sum_var += err*err;
m_hist->SetBinContent(i,sum);
m_hist->SetBinError(i,sqrt(sum_var));
}
}
else
{
for(int i = 1; i <= m_hist->GetNbinsX(); i++)
{
double content = m_hist->GetBinContent(i);;
double err = m_hist->GetBinError(i);
sum += content;
sum_var += err*err;
m_hist->SetBinContent(i,sum);
m_hist->SetBinError(i,sqrt(sum_var));
}
}
}
void VSRHistogram1D::multiply(double x)
{
for(int i = 1; i <= m_hist->GetNbinsX(); i++)
{
double content = m_hist->GetBinContent(i);;
double err = m_hist->GetBinError(i);
m_hist->SetBinContent(i,content*x);
m_hist->SetBinError(i,err*x);
}
}
void VSRHistogram1D::print()
{
for(int ibin = 1; ibin <= m_hist->GetNbinsX(); ibin++)
{
double content = m_hist->GetBinContent(ibin);;
double err = m_hist->GetBinError(ibin);
double x = m_hist->GetBinCenter(ibin);
std::cout << x << " " << content << " " << err << std::endl;
}
}
| 22.077103 | 79 | 0.585459 | [
"transform"
] |
41ee61585d71fc39d20856b90972bc2696fcc157 | 5,760 | cc | C++ | caffe2/mkl/operators/spatial_batch_norm_op.cc | shigengtian/caffe2 | e19489d6acd17fea8ca98cd8e4b5b680e23a93c5 | [
"Apache-2.0"
] | 1 | 2018-03-26T13:25:03.000Z | 2018-03-26T13:25:03.000Z | caffe2/mkl/operators/spatial_batch_norm_op.cc | shigengtian/caffe2 | e19489d6acd17fea8ca98cd8e4b5b680e23a93c5 | [
"Apache-2.0"
] | null | null | null | caffe2/mkl/operators/spatial_batch_norm_op.cc | shigengtian/caffe2 | e19489d6acd17fea8ca98cd8e4b5b680e23a93c5 | [
"Apache-2.0"
] | 1 | 2018-12-20T09:14:48.000Z | 2018-12-20T09:14:48.000Z | #include "caffe2/operators/spatial_batch_norm_op.h"
#include <math.h>
#include "caffe2/mkl/mkl_utils.h"
#ifdef CAFFE2_HAS_MKL_DNN
namespace caffe2 {
namespace mkl {
template <typename T>
class MKLBNOp final : public SpatialBNOp<MKLContext> {
public:
MKLBNOp(const OperatorDef& operator_def, Workspace* ws)
: SpatialBNOp<MKLContext>(operator_def, ws) {
OPERATOR_NEEDS_FEATURE(
order_ == StorageOrder::NCHW, "Only NCHW order supported.");
OPERATOR_NEEDS_FEATURE(
operator_def.input(0) != operator_def.output(0),
"Inplace BN not supported");
}
bool RunOnDevice() {
auto& X = OperatorBase::Input<MKLMemory<float>>(INPUT);
auto& scale = OperatorBase::Input<MKLMemory<float>>(SCALE);
auto& bias = OperatorBase::Input<MKLMemory<float>>(BIAS);
MKLMemory<float>* Y = OperatorBase::Output<MKLMemory<float>>(OUTPUT);
// anded with is_test_-1 to avoid uninitialized access in case of testing
MKLMemory<float>* running_mean =
OperatorBase::Output<MKLMemory<float>>(RUNNING_MEAN & (is_test_ - 1));
MKLMemory<float>* running_var =
OperatorBase::Output<MKLMemory<float>>(RUNNING_VAR & (is_test_ - 1));
MKLMemory<float>* saved_mean =
OperatorBase::Output<MKLMemory<float>>(SAVED_MEAN & (is_test_ - 1));
MKLMemory<float>* saved_var =
OperatorBase::Output<MKLMemory<float>>(SAVED_INV_VAR & (is_test_ - 1));
// current code supports only NCHW -
// have to look for MKL related changes for NHWC later
const int N = X.dim32(0);
const int C = (order_ == StorageOrder::NCHW ? X.dim32(1) : X.dim32(3));
const int H = (order_ == StorageOrder::NCHW ? X.dim32(2) : X.dim32(1));
const int W = (order_ == StorageOrder::NCHW ? X.dim32(3) : X.dim32(2));
DCHECK_EQ(scale.ndim(), 1);
DCHECK_EQ(bias.ndim(), 1);
DCHECK_EQ(scale.dim32(0), C);
DCHECK_EQ(bias.dim32(0), C);
bool dims_changed;
CHECK_INPUT_DIMS(X, dims_changed);
if (dims_changed || FLAGS_caffe2_mkl_memonger_in_use) {
// Create main primitive.
if (is_test_) {
primitive_.Reset(
dnnBatchNormalizationCreateForward_v2<T>,
nullptr,
X.layout(),
epsilon_,
dnnUseInputMeanVariance | dnnUseScaleShift);
} else {
primitive_.Reset(
dnnBatchNormalizationCreateForward_v2<T>,
nullptr,
X.layout(),
epsilon_,
dnnUseScaleShift);
// using scale dims as it is also of size C
saved_mean->Reset(scale.dims(), primitive_, dnnResourceMean);
saved_var->Reset(scale.dims(), primitive_, dnnResourceVariance);
running_mean->Reset(scale.dims(), primitive_, dnnResourceMean);
running_var->Reset(scale.dims(), primitive_, dnnResourceVariance);
running_mean_buf = (T*)running_mean->buffer();
running_var_buf = (T*)running_var->buffer();
}
Y->Reset(X.dims(), primitive_, dnnResourceDst);
buffer_.Reset(X.dims(), primitive_, dnnResourceDst, true);
scale_bias_layout_.Reset(primitive_, dnnResourceScaleShift);
scale_bias_buffer_ =
caffe2::make_unique<MKLWorkspace<float>>(scale_bias_layout_);
// fill scale and bias into a single buffer
scale_buf = (T*)scale.buffer();
bias_buf = (T*)bias.buffer();
for (int i = 0; i < C; i++) {
scale_bias_buffer_->buffer()[i] = scale_buf[i];
scale_bias_buffer_->buffer()[C + i] = bias_buf[i];
}
}
// Try to share from the output: this allows us to avoid unnecessary copy
// operations, if the output is already allocated and is having the same
// layout as the buffer has.
bool shared = buffer_.ShareFrom(*Y);
resources_[dnnResourceSrc] = X.buffer();
resources_[dnnResourceDst] = buffer_.buffer();
resources_[dnnResourceScaleShift] = scale_bias_buffer_->buffer();
if (is_test_) {
auto& est_mean = OperatorBase::Input<MKLMemory<float>>(EST_MEAN);
auto& est_var = OperatorBase::Input<MKLMemory<float>>(EST_VAR);
resources_[dnnResourceMean] = est_mean.buffer();
resources_[dnnResourceVariance] = est_var.buffer();
} else {
resources_[dnnResourceMean] = saved_mean->buffer();
resources_[dnnResourceVariance] = saved_var->buffer();
}
MKLDNN_SAFE_CALL(mkl::dnnExecute<float>(primitive_, resources_));
if (!is_test_) {
// compute running mean and variance
saved_mean_buf = (T*)saved_mean->buffer();
saved_var_buf = (T*)saved_var->buffer();
for (int i = 0; i < C; i++) {
running_mean_buf[i] = running_mean_buf[i] * momentum_ +
saved_mean_buf[i] * (1. - momentum_);
running_var_buf[i] = running_var_buf[i] * momentum_ +
saved_var_buf[i] * (1. - momentum_);
saved_var_buf[i] = (1 / sqrt(saved_var_buf[i] + epsilon_));
}
}
buffer_.CopyTo(Y, primitive_, dnnResourceDst);
if (FLAGS_caffe2_mkl_memonger_in_use && !shared) {
buffer_.Reset();
}
return true;
}
private:
vector<TIndex> cached_input_dims_;
LayoutWrapper<T> scale_bias_layout_;
LayoutWrapper<T> saved_mean_layout_;
LayoutWrapper<T> saved_var_layout_;
LayoutWrapper<T> running_mean_layout_;
LayoutWrapper<T> running_var_layout_;
std::unique_ptr<MKLWorkspace<T>> scale_bias_buffer_;
T* scale_buf = nullptr;
T* bias_buf = nullptr;
T* saved_mean_buf = nullptr;
T* saved_var_buf = nullptr;
T* running_mean_buf = nullptr;
T* running_var_buf = nullptr;
PrimitiveWrapper<T> primitive_;
MKLMemory<T> buffer_;
void* resources_[dnnResourceNumber] = {0};
};
} // namespace mkl
REGISTER_MKL_OPERATOR(SpatialBN, mkl::MKLBNOp<float>);
} // namespace caffe2
#endif // CAFFE2_HAS_MKL_DNN
| 36 | 79 | 0.663021 | [
"vector"
] |
41ef58037f88ea4a18014ba0a863b9381d20d8bc | 1,196 | cpp | C++ | framework/sphere.cpp | TheChosenHobbit/DE_RayTracer | 3f89764f5fa1c769b4fea9b30d30daccd66e5abb | [
"MIT"
] | null | null | null | framework/sphere.cpp | TheChosenHobbit/DE_RayTracer | 3f89764f5fa1c769b4fea9b30d30daccd66e5abb | [
"MIT"
] | null | null | null | framework/sphere.cpp | TheChosenHobbit/DE_RayTracer | 3f89764f5fa1c769b4fea9b30d30daccd66e5abb | [
"MIT"
] | null | null | null | #include "sphere.hpp"
#include <cmath>
#include <glm/glm.hpp>
#include <glm/gtx/intersect.hpp>
#include "material.hpp"
Sphere::Sphere():
Shape({"Sphere"},{Material{}}),
center_{0,0,0},
radius_{0}{ std::cout << "Sphere::Constructor" << std::endl; }
Sphere::Sphere(std::string const& name, Material const& material, glm::vec3 const& center, float radius):
Shape({name},{material}),
center_{center},
radius_{radius}{ std::cout << "Sphere::Constructor" << std::endl; }
Sphere::~Sphere(){ std::cout << "Sphere::Destructor" << std::endl; }
float Sphere::area() const {
return 4*M_PI*radius_;
}
float Sphere::volume() const {
return 4/3*M_PI*radius_*radius_*radius_;
}
glm::vec3 Sphere::getCenter() const {
return center_;
}
float Sphere::getRadius() const {
return radius_;
}
std::ostream& Sphere::print(std::ostream& os) const{
Shape::print(os);
os << "Center: " << center_.x << ", " << center_.y << ", " << center_.z << std::endl;
os << "Radius: " << radius_ << std::endl;
return os;
}
bool Sphere::intersect (Ray const& ray, float& distance) const{
auto v = glm::normalize(ray.direction);
return glm::intersectRaySphere(ray.origin, v, center_, radius_*radius_, distance);
}
| 26 | 105 | 0.665552 | [
"shape"
] |
41eff9dacc3a14294d7f0eb3a7068e49b258c26c | 1,859 | cpp | C++ | src/search_engine/relja_retrival/util/tests/test_slow_construction.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 43 | 2017-07-06T23:44:39.000Z | 2022-03-25T06:53:29.000Z | src/search_engine/relja_retrival/util/tests/test_slow_construction.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 2 | 2018-11-09T03:52:14.000Z | 2020-03-25T14:08:33.000Z | src/search_engine/relja_retrival/util/tests/test_slow_construction.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 9 | 2017-07-27T10:55:55.000Z | 2020-12-15T13:42:43.000Z | /*
==== Author:
Relja Arandjelovic (relja@robots.ox.ac.uk)
Visual Geometry Group,
Department of Engineering Science
University of Oxford
==== Copyright:
The library belongs to Relja Arandjelovic and the University of Oxford.
No usage or redistribution is allowed without explicit permission.
*/
#include "slow_construction.h"
#include <iostream>
#include <unistd.h>
#include <boost/lambda/construct.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
class timedConstr {
public:
timedConstr(int val) : val_(val) {
sleep(val);
}
int getVal(){ return val_; }
private:
int val_;
};
int main(){
boost::function<timedConstr*()> xConstructor= boost::lambda::bind( boost::lambda::new_ptr<timedConstr>(), boost::lambda::make_const(2) );
if (true) {
std::cout<<"First\n";
slowConstruction<timedConstr> slowCons(new timedConstr(0), xConstructor, true);
double dt= 0.1;
for (double t=0; t<3; t+=dt){
std::cout<<t<<" "<<slowCons.getObject()->getVal()<<"\n";
usleep(dt * 1000 * 1000);
}
}
if (true) {
std::cout<<"First\n";
sequentialConstructions consQueue;
slowConstruction<timedConstr> slowCons(new timedConstr(0), xConstructor, true, &consQueue);
slowConstruction<timedConstr> slowCons2(new timedConstr(0), xConstructor, true, &consQueue);
consQueue.start();
double dt= 0.1;
for (double t=0; t<5; t+=dt){
std::cout<<t<<" "<<slowCons.getObject()->getVal()<<" "<<slowCons2.getObject()->getVal()<<"\n";
usleep(dt * 1000 * 1000);
}
}
if (true) {
std::cout<<"Second\n";
slowConstruction<timedConstr> slowCons(new timedConstr(0), xConstructor, true);
}
return 0;
}
| 25.819444 | 141 | 0.608392 | [
"geometry"
] |
41f893f8bd5a9abbe454b28f14f3fa403b2b2859 | 229,491 | cpp | C++ | res/default_font.cpp | covscript/covscript-imgui | edc88c6abcc7269b715e86d421f8f3e272c13f72 | [
"Apache-2.0"
] | 4 | 2018-02-27T01:24:36.000Z | 2019-07-27T12:28:40.000Z | res/default_font.cpp | covscript/covscript-imgui | edc88c6abcc7269b715e86d421f8f3e272c13f72 | [
"Apache-2.0"
] | 2 | 2018-02-27T19:30:26.000Z | 2018-12-15T23:04:01.000Z | res/default_font.cpp | covscript/covscript-imgui | edc88c6abcc7269b715e86d421f8f3e272c13f72 | [
"Apache-2.0"
] | 1 | 2021-04-25T12:46:10.000Z | 2021-04-25T12:46:10.000Z | // File: '.\SourceSansPro.otf' (256288 bytes)
// Exported using binary_to_compressed_c.cpp
static const char default_font_compressed_data_base85[218275+1] =
"7])#######0w(T-'/###S07+>*<MM'Ql#v#]uhv7?fBe,A%&v#2E*##HYMT9$)amPW?(##c(D>#^ebd=M07R*KAuu#Yi,F%b5Oj9@U9Ks(6^2#Q6+4#OPTx9Yf8Y8;c0=#[p$,#BF_v9"
">gLjMfNb$#61a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$Xwgb$:(_%M-DKvdZ)s+Dp(A8e"
"m2VSeo&SS.t@xoew^:5fjCHYG$ftlf$*RMg?)<R*G4qig.+TMh<QCX(fXmfhYM')j_A#s$<Kf`j^A:;muwjf(R%<8n(0(<-OWd;#+3Jp$]gL_$Sdv;#x>]p$/LQc$Yv;<#w]4q$+<xu-"
"GPr*MJF;r$-iWX%Rm]]t4jouuD$/>G3`:Z#B[7W$#%Vf:=Fn8%J04T%C3cf(A_Np%C3Km&0qN`<MQGj'QJ(N()75R*,wCg(VH(H)XTaxFYD@d)D)<a*<d&F..vW&+HY4Z,C#'F.7(2W-"
"'wq/1rdk&#BW)w$8uF#%&-C'#*b?0%>:'B%umt&#<^;<%4f=>%?)>6#T$###u4T;-2LE/15xL$#XMrTC7JZ1F9anMN4DY.Dg0J.#*xCEHVle%#L&l?-XUJr/-Sl##0,GuuhOcs/#####"
"$####naLbrefj)#";
namespace imgui_cs {
const char *get_default_font_data()
{
return default_font_compressed_data_base85;
}
} | 146.172611 | 147 | 0.642827 | [
"cad",
"3d"
] |
51029bc9d8c0a1b7e63657d116d22d274b0d26c1 | 8,614 | cpp | C++ | components/rollkit/src/routes/pair_setup.cpp | NeilBetham/rollk | e82026397c892b5f0d3b53891d5efa51d941fd9d | [
"MIT"
] | 4 | 2018-06-12T21:48:01.000Z | 2021-04-01T15:18:50.000Z | components/rollkit/src/routes/pair_setup.cpp | NeilBetham/rollk | e82026397c892b5f0d3b53891d5efa51d941fd9d | [
"MIT"
] | null | null | null | components/rollkit/src/routes/pair_setup.cpp | NeilBetham/rollk | e82026397c892b5f0d3b53891d5efa51d941fd9d | [
"MIT"
] | 1 | 2018-08-18T13:05:31.000Z | 2018-08-18T13:05:31.000Z | #include "rollkit/routes/pair_setup.hpp"
#include <vector>
#include <esp_log.h>
#include "srp.hpp"
#include "rollkit/cryptor.hpp"
#include "rollkit/hkdf.hpp"
#include "rollkit/ed25519.hpp"
#include "rollkit/key_storage.hpp"
#include "rollkit/pairing_manager.hpp"
using namespace std;
namespace rollkit {
namespace routes {
void PairSetup::handle_request(Request& request, interfaces::IApp& app) {
auto req_tlvs = TLV::decode(request.get_body());
auto state_tlv = req_tlvs.find(HAP_TLV_TYPE_STATE);
if(state_tlv) {
uint8_t hap_state = (uint8_t)state_tlv->get_value()[0];
ESP_LOGD("pair-setup", "Got state from client: M%u", hap_state);
_setup_stage = (PairState)(hap_state - 1);
}
ESP_LOGD("pair-setup", "Got %u TLVs from client", req_tlvs.get().size());
switch(_setup_stage) {
case PairState::M0 : handle_m1(request, req_tlvs, app); break;
case PairState::M2 : handle_m3(request, req_tlvs); break;
case PairState::M4 : handle_m5(request, req_tlvs, app); break;
default : break;
}
}
void PairSetup::handle_m1(Request& request, TLVs& tlvs, interfaces::IApp& app) {
ESP_LOGI("pair-setup", "Handling M1");
auto hap_method = tlvs.find(HAP_TLV_TYPE_METHOD);
ESP_LOGD("pair-setup", "Pairing setup code: `%s`", app.get_setup_code().c_str());
// Check we are receiving the correct setup params
if(hap_method && (hap_method->get_value()[0] != HAP_TLV_METHOD_PAIR_SETUP) && (hap_method->get_value()[0] != HAP_TLV_METHOD_PAIR_SETUP_WITH_AUTH)) {
ESP_LOGE("pair-setup", "Client requesting unsupported pair setup: %d", hap_method->get_value()[0]);
reset();
request.get_session().close();
return;
}
// Check if we are pairing with another controller
if(_pair_in_progress) {
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x02}).serialize();
resp += TLV(HAP_TLV_TYPE_ERROR, {HAP_TLV_ERROR_BUSY}).serialize();
request.get_session().send(200, resp, "application/pairing+tlv8");
return;
}
_pair_in_progress = true;
_pairing_session = request.get_session().get_identifier();
request.get_session().register_event_listener(this);
// Check if a controller is paired already
PairingManager pm;
if(pm.get_pairing_count() > 0) {
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x02}).serialize();
resp += TLV(HAP_TLV_TYPE_ERROR, {HAP_TLV_ERROR_UNAVAILABLE}).serialize();
request.get_session().send(200, resp, "application/pairing+tlv8");
reset();
return;
}
// Setup SRP info
_srp_user = SRP::User::fromPassword(_srp_math, "Pair-Setup", app.get_setup_code());
_srp_verifier = SRP::Verifier(_srp_math, _srp_user);
// Generate challenge
auto challenge = _srp_verifier.get_challenge();
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x02}).serialize();
resp += TLV(HAP_TLV_TYPE_PUB_KEY, challenge.get_B().export_raw()).serialize();
resp += TLV(HAP_TLV_TYPE_SALT, challenge.get_salt().export_raw()).serialize();
// Send TVLs to client
ESP_LOGD("pair-setup", "Sending TLV response to client");
request.get_session().send(200, resp, "application/pairing+tlv8");
// Set PairState
_setup_stage = PairState::M2;
}
void PairSetup::handle_m3(Request& request, TLVs& tlvs) {
ESP_LOGI("pair-setup", "Handling M3");
// Pull the PubKey and proof from the TLVs
auto ios_pub_key = tlvs.find(HAP_TLV_TYPE_PUB_KEY);
auto ios_proof = tlvs.find(HAP_TLV_TYPE_PROOF);
if(!ios_pub_key || !ios_proof) {
ESP_LOGE("pair-setup", "iOS Device didn't send proper M3 TLVs");
reset();
request.get_session().close();
return;
}
BigNum pub_key = BigNum::from_raw(ios_pub_key->get_value());
BigNum proof = BigNum::from_raw(ios_proof->get_value());
// Update the verifier with the pub key and proof and see if they checkout
bool verified = _srp_verifier.verify(pub_key, proof);
if(!verified) {
ESP_LOGE("pair-setup", "iOS Device failed authentication");
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x04}).serialize();
resp += TLV(HAP_TLV_TYPE_ERROR, {HAP_TLV_ERROR_AUTH}).serialize();
request.get_session().send(200, resp, "application/pairing+tlv8");
reset();
return;
}
// Send Proof to client
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x04}).serialize();
resp += TLV(HAP_TLV_TYPE_PROOF, _srp_verifier.get_client_proof().export_raw()).serialize();
request.get_session().send(200, resp, "application/pairing+tlv8");
// Set PairState
_setup_stage = PairState::M4;
}
void PairSetup::handle_m5(Request& request, TLVs& tlvs, interfaces::IApp& app) {
ESP_LOGI("pair-setup", "Handling M5");
// Get the encrypted TLV
auto encrypted_tlv = tlvs.find(HAP_TLV_TYPE_ENCRYPTED_DATA);
if(!encrypted_tlv) {
ESP_LOGE("pair-setup", "No encrypted TLV found");
reset();
request.get_session().close();
return;
}
// Decrypt TLV
auto srp_shared_secret = _srp_verifier.get_shared_secret().export_raw();
string session_key = hkdf_sha512(
srp_shared_secret,
"Pair-Setup-Encrypt-Salt",
"Pair-Setup-Encrypt-Info",
crypto_aead_chacha20poly1305_IETF_KEYBYTES
);
Cryptor cryptor(session_key, "PS-Msg05");
auto decrypted_tlv = cryptor.decrypt(encrypted_tlv->get_value());
if(!decrypted_tlv) {
ESP_LOGE("pair-setup", "Failed to authenticate encrypted tlv");
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x06}).serialize();
resp += TLV(HAP_TLV_TYPE_ERROR, {HAP_TLV_ERROR_AUTH}).serialize();
request.get_session().send(200, resp, "application/pairing+tlv8");
reset();
return;
}
// Parse the sub TLV
auto sub_tlvs = TLV::decode(*decrypted_tlv);
auto id_tlv = sub_tlvs.find(HAP_TLV_TYPE_IDENTIFIER);
auto public_key_tlv = sub_tlvs.find(HAP_TLV_TYPE_PUB_KEY);
auto signature_tlv = sub_tlvs.find(HAP_TLV_TYPE_SIGNATURE);
if(!id_tlv | !public_key_tlv | !signature_tlv) {
ESP_LOGE("pair-setup", "Failed to get required sub TLVs");
reset();
request.get_session().close();
return;
}
// Generate iosdevice_x
auto iosdevice_x = hkdf_sha512(
srp_shared_secret,
"Pair-Setup-Controller-Sign-Salt",
"Pair-Setup-Controller-Sign-Info",
32
);
// Build iOSDeviceInfo
string iosdevice_info = iosdevice_x + id_tlv->get_value() + public_key_tlv->get_value();
// Verify Signature
if(!verify_ed25519(signature_tlv->get_value(), iosdevice_info, public_key_tlv->get_value())) {
ESP_LOGE("pair-setup", "Failed to verify signature");
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x06}).serialize();
resp += TLV(HAP_TLV_TYPE_ERROR, {HAP_TLV_ERROR_AUTH}).serialize();
request.get_session().send(200, resp, "application/pairing+tlv8");
reset();
return;
}
ESP_LOGI("pair-setup", "iOS Signature verified");
// Save the pairing
Pairing pairing(id_tlv->get_value(), public_key_tlv->get_value());
PairingManager pm;
if(!pm.add_pairing(pairing)) {
ESP_LOGE("pair-setup", "Failed save pairing");
string resp;
resp += TLV(HAP_TLV_TYPE_STATE, {0x06}).serialize();
resp += TLV(HAP_TLV_TYPE_ERROR, {HAP_TLV_ERROR_MAX_PEERS}).serialize();
request.get_session().send(200, resp, "application/pairing+tlv8");
reset();
return;
}
// Generate accessory_x
auto accessory_x = hkdf_sha512(
srp_shared_secret,
"Pair-Setup-Accessory-Sign-Salt",
"Pair-Setup-Accessory-Sign-Info",
32
);
// Build AccessoryInfo
string accessory_info = accessory_x + app.get_device_id() + get_public_key();
// Sign the accessory_info
auto signature = sign_ed25519(accessory_info, get_private_key());
// Build TLV to send back to client
string resp;
resp += TLV(HAP_TLV_TYPE_IDENTIFIER, app.get_device_id()).serialize();
resp += TLV(HAP_TLV_TYPE_PUB_KEY, get_public_key()).serialize();
resp += TLV(HAP_TLV_TYPE_SIGNATURE, signature).serialize();
// Encrypt TLV and send
cryptor.set_nonce("PS-Msg06");
auto encrypted_data = cryptor.encrypt(resp);
string wrapper_resp;
wrapper_resp += TLV(HAP_TLV_TYPE_STATE, {0x06}).serialize();
wrapper_resp += TLV(HAP_TLV_TYPE_ENCRYPTED_DATA, encrypted_data).serialize();
request.get_session().send(200, wrapper_resp, "application/pairing+tlv8");
// Set PairState
_setup_stage = PairState::M6;
_pair_in_progress = false;
_pairing_session = NULL;
}
void PairSetup::session_closed(void* session_id) {
if(_pair_in_progress == false) { return; }
ESP_LOGI("pair-setup", "Session %p closed; canceling in progress pairing", session_id);
if(_pairing_session == session_id) {
_pair_in_progress = false;
_pairing_session = NULL;
}
}
} // namespace routes
} // namespace rollkit
| 33.387597 | 150 | 0.707337 | [
"vector"
] |
eedd50ebb8aeea15aaf962d4380f48395b4ffa0e | 15,315 | hpp | C++ | include/boost/gil/image_processing/diffusion.hpp | harsh-4/gil | 6da59cc3351e5657275d3a536e0b6e7a1b6ac738 | [
"BSL-1.0"
] | 153 | 2015-02-03T06:03:54.000Z | 2022-03-20T15:06:34.000Z | include/boost/gil/image_processing/diffusion.hpp | harsh-4/gil | 6da59cc3351e5657275d3a536e0b6e7a1b6ac738 | [
"BSL-1.0"
] | 429 | 2015-03-22T09:49:04.000Z | 2022-03-28T08:32:08.000Z | include/boost/gil/image_processing/diffusion.hpp | harsh-4/gil | 6da59cc3351e5657275d3a536e0b6e7a1b6ac738 | [
"BSL-1.0"
] | 215 | 2015-03-15T09:20:51.000Z | 2022-03-30T12:40:07.000Z | //
// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>
// Copyright 2021 Pranam Lashkari <plashkari628@gmail.com>
//
// Use, modification and distribution are 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_GIL_IMAGE_PROCESSING_DIFFUSION_HPP
#define BOOST_GIL_IMAGE_PROCESSING_DIFFUSION_HPP
#include "boost/gil/detail/math.hpp"
#include <boost/gil/algorithm.hpp>
#include <boost/gil/color_base_algorithm.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/image_view.hpp>
#include <boost/gil/image_view_factory.hpp>
#include <boost/gil/pixel.hpp>
#include <boost/gil/point.hpp>
#include <boost/gil/typedefs.hpp>
#include <functional>
#include <numeric>
#include <vector>
namespace boost { namespace gil {
namespace conductivity {
struct perona_malik_conductivity
{
double kappa;
template <typename Pixel>
Pixel operator()(Pixel input)
{
using channel_type = typename channel_type<Pixel>::type;
// C++11 doesn't seem to capture members
static_transform(input, input, [this](channel_type value) {
value /= kappa;
return std::exp(-std::abs(value));
});
return input;
}
};
struct gaussian_conductivity
{
double kappa;
template <typename Pixel>
Pixel operator()(Pixel input)
{
using channel_type = typename channel_type<Pixel>::type;
// C++11 doesn't seem to capture members
static_transform(input, input, [this](channel_type value) {
value /= kappa;
return std::exp(-value * value);
});
return input;
}
};
struct wide_regions_conductivity
{
double kappa;
template <typename Pixel>
Pixel operator()(Pixel input)
{
using channel_type = typename channel_type<Pixel>::type;
// C++11 doesn't seem to capture members
static_transform(input, input, [this](channel_type value) {
value /= kappa;
return 1.0 / (1.0 + value * value);
});
return input;
}
};
struct more_wide_regions_conductivity
{
double kappa;
template <typename Pixel>
Pixel operator()(Pixel input)
{
using channel_type = typename channel_type<Pixel>::type;
// C++11 doesn't seem to capture members
static_transform(input, input, [this](channel_type value) {
value /= kappa;
return 1.0 / std::sqrt((1.0 + value * value));
});
return input;
}
};
} // namespace diffusion
/**
\brief contains discrete approximations of 2D Laplacian operator
*/
namespace laplace_function {
// The functions assume clockwise enumeration of stencil points, as such
// NW North NE 0 1 2 (-1, -1) (0, -1) (+1, -1)
// West East ===> 7 3 ===> (-1, 0) (+1, 0)
// SW South SE 6 5 4 (-1, +1) (0, +1) (+1, +1)
/**
\brief This function makes sure all Laplace functions enumerate
values in the same order and direction.
The first element is difference North West direction, second in North,
and so on in clockwise manner. Leave element as zero if it is not
to be computed.
*/
inline std::array<gil::point_t, 8> get_directed_offsets()
{
return {point_t{-1, -1}, point_t{0, -1}, point_t{+1, -1}, point_t{+1, 0},
point_t{+1, +1}, point_t{0, +1}, point_t{-1, +1}, point_t{-1, 0}};
}
template <typename PixelType>
using stencil_type = std::array<PixelType, 8>;
/**
\brief 5 point stencil approximation of Laplacian
Only main 4 directions are non-zero, the rest are zero
*/
struct stencil_5points
{
double delta_t = 0.25;
template <typename SubImageView>
stencil_type<typename SubImageView::value_type> compute_laplace(SubImageView view,
point_t origin)
{
auto current = view(origin);
stencil_type<typename SubImageView::value_type> stencil;
using channel_type = typename channel_type<typename SubImageView::value_type>::type;
std::array<gil::point_t, 8> offsets(get_directed_offsets());
typename SubImageView::value_type zero_pixel;
static_fill(zero_pixel, 0);
for (std::size_t index = 0; index < offsets.size(); ++index)
{
if (index % 2 != 0)
{
static_transform(view(origin.x + offsets[index].x, origin.y + offsets[index].y),
current, stencil[index], std::minus<channel_type>{});
}
else
{
stencil[index] = zero_pixel;
}
}
return stencil;
}
template <typename Pixel>
Pixel reduce(const stencil_type<Pixel>& stencil)
{
auto first = stencil.begin();
auto last = stencil.end();
using channel_type = typename channel_type<Pixel>::type;
auto result = []() {
Pixel zero_pixel;
static_fill(zero_pixel, channel_type(0));
return zero_pixel;
}();
for (std::size_t index : {1u, 3u, 5u, 7u})
{
static_transform(result, stencil[index], result, std::plus<channel_type>{});
}
Pixel delta_t_pixel;
static_fill(delta_t_pixel, delta_t);
static_transform(result, delta_t_pixel, result, std::multiplies<channel_type>{});
return result;
}
};
/**
\brief 9 point stencil approximation of Laplacian
This is full 8 way approximation, though diagonal
elements are halved during reduction.
*/
struct stencil_9points_standard
{
double delta_t = 0.125;
template <typename SubImageView>
stencil_type<typename SubImageView::value_type> compute_laplace(SubImageView view,
point_t origin)
{
stencil_type<typename SubImageView::value_type> stencil;
auto out = stencil.begin();
auto current = view(origin);
using channel_type = typename channel_type<typename SubImageView::value_type>::type;
std::array<gil::point_t, 8> offsets(get_directed_offsets());
for (auto offset : offsets)
{
static_transform(view(origin.x + offset.x, origin.y + offset.y), current, *out++,
std::minus<channel_type>{});
}
return stencil;
}
template <typename Pixel>
Pixel reduce(const stencil_type<Pixel>& stencil)
{
using channel_type = typename channel_type<Pixel>::type;
auto result = []() {
Pixel zero_pixel;
static_fill(zero_pixel, channel_type(0));
return zero_pixel;
}();
for (std::size_t index : {1u, 3u, 5u, 7u})
{
static_transform(result, stencil[index], result, std::plus<channel_type>{});
}
for (std::size_t index : {0u, 2u, 4u, 6u})
{
Pixel half_pixel;
static_fill(half_pixel, channel_type(1 / 2.0));
static_transform(stencil[index], half_pixel, half_pixel,
std::multiplies<channel_type>{});
static_transform(result, half_pixel, result, std::plus<channel_type>{});
}
Pixel delta_t_pixel;
static_fill(delta_t_pixel, delta_t);
static_transform(result, delta_t_pixel, result, std::multiplies<channel_type>{});
return result;
}
};
} // namespace laplace_function
namespace brightness_function {
using laplace_function::stencil_type;
struct identity
{
template <typename Pixel>
stencil_type<Pixel> operator()(const stencil_type<Pixel>& stencil)
{
return stencil;
}
};
// TODO: Figure out how to implement color gradient brightness, as it
// seems to need dx and dy using sobel or scharr kernels
struct rgb_luminance
{
using pixel_type = rgb32f_pixel_t;
stencil_type<pixel_type> operator()(const stencil_type<pixel_type>& stencil)
{
stencil_type<pixel_type> output;
std::transform(stencil.begin(), stencil.end(), output.begin(), [](const pixel_type& pixel) {
float32_t luminance = 0.2126f * pixel[0] + 0.7152f * pixel[1] + 0.0722f * pixel[2];
pixel_type result_pixel;
static_fill(result_pixel, luminance);
return result_pixel;
});
return output;
}
};
} // namespace brightness_function
enum class matlab_connectivity
{
minimal,
maximal
};
enum class matlab_conduction_method
{
exponential,
quadratic
};
template <typename InputView, typename OutputView>
void classic_anisotropic_diffusion(const InputView& input, const OutputView& output,
unsigned int num_iter, double kappa)
{
anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},
brightness_function::identity{},
conductivity::perona_malik_conductivity{kappa});
}
template <typename InputView, typename OutputView>
void matlab_anisotropic_diffusion(const InputView& input, const OutputView& output,
unsigned int num_iter, double kappa,
matlab_connectivity connectivity,
matlab_conduction_method conduction_method)
{
if (connectivity == matlab_connectivity::minimal)
{
if (conduction_method == matlab_conduction_method::exponential)
{
anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},
brightness_function::identity{},
conductivity::gaussian_conductivity{kappa});
}
else if (conduction_method == matlab_conduction_method::quadratic)
{
anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},
brightness_function::identity{},
conductivity::gaussian_conductivity{kappa});
}
else
{
throw std::logic_error("unhandled conduction method found");
}
}
else if (connectivity == matlab_connectivity::maximal)
{
if (conduction_method == matlab_conduction_method::exponential)
{
anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},
brightness_function::identity{},
conductivity::gaussian_conductivity{kappa});
}
else if (conduction_method == matlab_conduction_method::quadratic)
{
anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_5points{},
brightness_function::identity{},
conductivity::gaussian_conductivity{kappa});
}
else
{
throw std::logic_error("unhandled conduction method found");
}
}
else
{
throw std::logic_error("unhandled connectivity found");
}
}
template <typename InputView, typename OutputView>
void default_anisotropic_diffusion(const InputView& input, const OutputView& output,
unsigned int num_iter, double kappa)
{
anisotropic_diffusion(input, output, num_iter, laplace_function::stencil_9points_standard{},
brightness_function::identity{}, conductivity::gaussian_conductivity{kappa});
}
/// \brief Performs diffusion according to Perona-Malik equation
///
/// WARNING: Output channel type must be floating point,
/// otherwise there will be loss in accuracy which most
/// probably will lead to incorrect results (input will be unchanged).
/// Anisotropic diffusion is a smoothing algorithm that respects
/// edge boundaries and can work as an edge detector if suitable
/// iteration count is set and grayscale image view is used
/// as an input
template <typename InputView, typename OutputView,
typename LaplaceStrategy = laplace_function::stencil_9points_standard,
typename BrightnessFunction = brightness_function::identity,
typename DiffusivityFunction = conductivity::gaussian_conductivity>
void anisotropic_diffusion(const InputView& input, const OutputView& output, unsigned int num_iter,
LaplaceStrategy laplace, BrightnessFunction brightness,
DiffusivityFunction diffusivity)
{
using input_pixel_type = typename InputView::value_type;
using pixel_type = typename OutputView::value_type;
using channel_type = typename channel_type<pixel_type>::type;
using computation_image = image<pixel_type>;
const auto width = input.width();
const auto height = input.height();
const point_t dims(width, height);
const auto zero_pixel = []() {
pixel_type pixel;
static_fill(pixel, static_cast<channel_type>(0));
return pixel;
}();
computation_image result_image(width + 2, height + 2, zero_pixel);
auto result = view(result_image);
computation_image scratch_result_image(width + 2, height + 2, zero_pixel);
auto scratch_result = view(scratch_result_image);
transform_pixels(input, subimage_view(result, 1, 1, width, height),
[](const input_pixel_type& pixel) {
pixel_type converted;
for (std::size_t i = 0; i < num_channels<pixel_type>{}; ++i)
{
converted[i] = pixel[i];
}
return converted;
});
for (unsigned int iteration = 0; iteration < num_iter; ++iteration)
{
for (std::ptrdiff_t relative_y = 0; relative_y < height; ++relative_y)
{
for (std::ptrdiff_t relative_x = 0; relative_x < width; ++relative_x)
{
auto x = relative_x + 1;
auto y = relative_y + 1;
auto stencil = laplace.compute_laplace(result, point_t(x, y));
auto brightness_stencil = brightness(stencil);
laplace_function::stencil_type<pixel_type> diffusivity_stencil;
std::transform(brightness_stencil.begin(), brightness_stencil.end(),
diffusivity_stencil.begin(), diffusivity);
laplace_function::stencil_type<pixel_type> product_stencil;
std::transform(stencil.begin(), stencil.end(), diffusivity_stencil.begin(),
product_stencil.begin(), [](pixel_type lhs, pixel_type rhs) {
static_transform(lhs, rhs, lhs, std::multiplies<channel_type>{});
return lhs;
});
static_transform(result(x, y), laplace.reduce(product_stencil),
scratch_result(x, y), std::plus<channel_type>{});
}
}
using std::swap;
swap(result, scratch_result);
}
copy_pixels(subimage_view(result, 1, 1, width, height), output);
}
}} // namespace boost::gil
#endif
| 35.699301 | 103 | 0.612733 | [
"vector",
"transform"
] |
eee09ffced0c0327056de73890c07472928e0e5b | 5,596 | cpp | C++ | src/Render2.cpp | jacksonwb/nibbler | 59053e9eb4c71c9eb5183ab9d2d6b057199a256d | [
"MIT"
] | null | null | null | src/Render2.cpp | jacksonwb/nibbler | 59053e9eb4c71c9eb5183ab9d2d6b057199a256d | [
"MIT"
] | null | null | null | src/Render2.cpp | jacksonwb/nibbler | 59053e9eb4c71c9eb5183ab9d2d6b057199a256d | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Render2.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbeall <jbeall@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/30 13:45:31 by jbeall #+# #+# */
/* Updated: 2019/06/13 19:51:25 by jbeall ### ########.fr */
/* */
/* ************************************************************************** */
#include "Render2.hpp"
void Render::init(void) {
SDL_DisplayMode DM;
double scale = 1;
if(SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cout << "SDL Initialization Error" << std::endl;
return;
}
SDL_GetCurrentDisplayMode(0, &DM);
if (DM.w > 2560)
scale = 1.5;
win = SDL_CreateWindow("nibbler", 100, 100, (game.map_width + 1) * RATIO * scale, (game.map_height + 2) * RATIO * scale, SDL_WINDOW_SHOWN);
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
destroy();
exit(EXIT_FAILURE);
}
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr){
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
destroy();
exit(EXIT_FAILURE);
}
TTF_Init();
font = TTF_OpenFont("fnt/slkscr.ttf", 36);
if (!font) {
std::cout << "Error: font not found" << std::endl;
destroy();
exit(EXIT_FAILURE);
}
SDL_RenderSetScale(ren, scale, scale);
};
char Render::getInput(void) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT)
return 'q';
if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_ESCAPE)
return 'q';
if (e.key.keysym.sym == SDLK_q)
return 'q';
if (e.key.keysym.sym == SDLK_w || e.key.keysym.sym == SDLK_UP)
return 'w';
if (e.key.keysym.sym == SDLK_s || e.key.keysym.sym == SDLK_DOWN)
return 's';
if (e.key.keysym.sym == SDLK_a || e.key.keysym.sym == SDLK_LEFT)
return 'a';
if (e.key.keysym.sym == SDLK_d || e.key.keysym.sym == SDLK_RIGHT)
return 'd';
if (e.key.keysym.sym == SDLK_SPACE)
return ' ';
if (e.key.keysym.sym == SDLK_1)
return '1';
if (e.key.keysym.sym == SDLK_3)
return '3';
}
}
return 'e';
}
void Render::destroy(void) {
delete this;
}
void Render::drawWindow(void) {
SDL_Rect board;
board.x = RATIO;
board.y = RATIO;
board.h = RATIO * game.map_height - 1 * RATIO;
board.w = RATIO * game.map_width - 1 * RATIO;
SDL_SetRenderDrawColor(ren, 255, 255, 255, 255 );
SDL_RenderFillRect(ren, &board);
}
bool Render::isHeadChar(char c) {
if (c == H_U || c == H_D || c == H_L || c == H_R)
return true;
return false;
}
void Render::drawGame(void) {
SDL_Rect piece;
piece.w = RATIO;
piece.h = RATIO;
for (int i = 0; i <= game.map_height; i++) {
for (int j = 0; j <= game.map_width; j++) {
if (game.ar[j][i]) {
switch (game.ar[j][i]) {
case (FOOD_CHAR):
SDL_SetRenderDrawColor(ren, 83, 126, 252, 99);
break;
default:
if (isHeadChar(game.ar[j][i]))
SDL_SetRenderDrawColor(ren, 148, 57, 235, 92);
else
SDL_SetRenderDrawColor(ren, 152, 105, 255, 100);
break;
}
piece.x = j * RATIO;
piece.y = game.map_height * RATIO - i * RATIO;
SDL_RenderFillRect(ren, &piece);
}
}
}
}
void Render::drawGameOver(void) {
SDL_Color textColor = {0, 0, 0, 255};
SDL_Surface *gameOverSurface = TTF_RenderText_Blended(font, "Game Over", textColor);
SDL_Texture *text = SDL_CreateTextureFromSurface(ren, gameOverSurface);
SDL_Rect renderQuad = {(int)game.map_width / 2 * RATIO - 100, (int)game.map_height / 2 * RATIO, gameOverSurface->w, gameOverSurface->h};
SDL_RenderCopy(ren, text, NULL, &renderQuad);
SDL_FreeSurface(gameOverSurface);
SDL_DestroyTexture(text);
}
void Render::drawScore(void) {
std::string score_txt = std::string("Score: " + std::to_string(game.score));
SDL_Color textColor = {255, 255, 255, 255};
SDL_Surface *gameOverSurface = TTF_RenderText_Blended(font, score_txt.c_str(), textColor);
SDL_Texture *text = SDL_CreateTextureFromSurface(ren, gameOverSurface);
SDL_Rect renderQuad = {20, (int)game.map_height * RATIO + 2, gameOverSurface->w, gameOverSurface->h};
SDL_RenderCopy(ren, text, NULL, &renderQuad);
SDL_FreeSurface(gameOverSurface);
SDL_DestroyTexture(text);
}
void Render::drawPause(void) {
SDL_Color textColor = {0, 0, 0, 255};
SDL_Surface *gameOverSurface = TTF_RenderText_Blended(font, "Pause", textColor);
SDL_Texture *text = SDL_CreateTextureFromSurface(ren, gameOverSurface);
SDL_Rect renderQuad = {(int)game.map_width / 2 * RATIO - 50, (int)game.map_height / 2 * RATIO, gameOverSurface->w, gameOverSurface->h};
SDL_RenderCopy(ren, text, NULL, &renderQuad);
SDL_FreeSurface(gameOverSurface);
SDL_DestroyTexture(text);
}
void Render::render(void) {
SDL_SetRenderDrawColor(ren, 0, 0, 0, 0);
SDL_RenderClear(ren);
drawWindow();
drawGame();
drawScore();
if (game.game_over)
drawGameOver();
if (game.paused && !game.game_over)
drawPause();
SDL_RenderPresent(ren);
};
Render::~Render() {
if (win)
SDL_DestroyWindow(win);
if (font)
TTF_CloseFont(font);
if (ren)
SDL_DestroyRenderer(ren);
TTF_Quit();
SDL_Quit();
};
| 30.917127 | 140 | 0.574518 | [
"render"
] |
eee62c9adebcf5f60e2a13eccfea5b3da385ec84 | 4,110 | cpp | C++ | WLMatrix/src/wlmatrix/tasks/NewMessageTask.cpp | aeoncl/wlmatrix | da936eaec37f06f0e379c6009962dc69bfe07eb3 | [
"MIT"
] | null | null | null | WLMatrix/src/wlmatrix/tasks/NewMessageTask.cpp | aeoncl/wlmatrix | da936eaec37f06f0e379c6009962dc69bfe07eb3 | [
"MIT"
] | null | null | null | WLMatrix/src/wlmatrix/tasks/NewMessageTask.cpp | aeoncl/wlmatrix | da936eaec37f06f0e379c6009962dc69bfe07eb3 | [
"MIT"
] | null | null | null | #pragma once
#include "NewMessageTask.h"
#include "MatrixEvent.h"
#include <thread>
#include "MSNPRNG.h"
#include "MSNUtils.h"
#include "UUID.h"
#include "SwitchboardDataRepository.h"
#include "SwitchboardRepository.h"
#include "SharedThreadPool.h"
#include "MatrixUtils.h"
using namespace wlmatrix;
std::vector<std::string> NewMessageTask::execute(SyncResponse response, std::shared_ptr<ClientInfo> clientInfo, bool initial)
{
auto &sbDataRepo = SwitchboardDataRepository::getInstance();
auto &sbRepo = SwitchboardRepository::getInstance();
auto directEvent = clientInfo->getDirectEvent();
auto joinedRooms = response.getJoinedRooms();
std::string token = clientInfo->getMatrixToken();
std::vector<std::string> out;
for (auto room : joinedRooms)
{
auto currents = room.getEventsForType<MatrixEvent>("m.room.message");
for (int i = 0; i < currents.size(); i++)
{
auto current = currents[i];
if (current.getSender() == clientInfo->getMatrixId())
{
currents.erase(currents.begin() + i);
}
}
if (!currents.empty())
{
if (initial)
{
//OIMs
}
else
{
//new msgs
auto maybeFoundSb = sbRepo.getSwitchboardForRoomId(room.getId());
if (maybeFoundSb.has_value())
{
auto foundSb = maybeFoundSb.value();
SharedThreadPool::getInstance().getThreadPool()->push_task([foundSb, room]
{ foundSb->onNewMatrixData(room); });
//current
}
else
{
auto sbPendingDataExists = sbDataRepo.hasSwitchboard(room.getId());
if (!sbPendingDataExists)
{
// If it's a DM room, figure out wether it's the room that has access to the user entry
std::string invitePassport = MSNUtils::getMSNPassportNameForRoomId(room.getId());
if (directEvent.isRoomDirect(room.getId()))
{
auto directUserId = directEvent.getUserIdForRoomId(room.getId()).value();
auto maybeTargetRoomForContactEntry = MatrixUtils::findDMRoomForUser(directUserId, response, directEvent, clientInfo);
if (maybeTargetRoomForContactEntry.has_value())
{
if (room.getId() == maybeTargetRoomForContactEntry.value())
{
invitePassport = MSNUtils::getMSNPassportNameForUserId(directUserId);
}
}
}
std::string inviteName = invitePassport;
// Create switchboard creation request payload
sbDataRepo.registerSwitchboard(room.getId());
MSNPRNG rngCommand;
UUID uuid = UUID::generateFromString(room.getId());
rngCommand.setAddress("127.0.0.1:1864"); //this will be dynamic
rngCommand.setInvitePassport(invitePassport);
rngCommand.setInviteName(inviteName); //todo get display name
rngCommand.setSessionId(uuid.getLeastSignificantBytes() + uuid.getMostSignificantBytes());
//rngCommand.setTicket(MSNUtils::getMSNPassportNameForRoomId(room.getId(), false));
rngCommand.setTicket(room.getId()+";"+invitePassport); //include & verify token in ticket
out.push_back(rngCommand.serialize());
}
sbDataRepo.addDataToSwitchboard(room.getId(), response);
}
};
}
}
return out;
};
| 41.938776 | 146 | 0.522384 | [
"vector"
] |
eee8581022b1437585b124bfca6c3cd7bdb527c2 | 24,561 | cpp | C++ | deployed/Il2CppOutputProject/Source/il2cppOutput/Il2CppComCallableWrappers0.cpp | PaulDixon/HelloWorld | f73f1eb2f972b3bc03420727e3c383ff63041af9 | [
"MIT"
] | 1 | 2019-09-14T04:39:37.000Z | 2019-09-14T04:39:37.000Z | deployed/Il2CppOutputProject/Source/il2cppOutput/Il2CppComCallableWrappers0.cpp | PaulDixon/HelloWorld | f73f1eb2f972b3bc03420727e3c383ff63041af9 | [
"MIT"
] | null | null | null | deployed/Il2CppOutputProject/Source/il2cppOutput/Il2CppComCallableWrappers0.cpp | PaulDixon/HelloWorld | f73f1eb2f972b3bc03420727e3c383ff63041af9 | [
"MIT"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "vm/CachedCCWBase.h"
#include "il2cpp-object-internals.h"
template <typename R>
struct VirtFuncInvoker0
{
typedef R (*Func)(void*, const RuntimeMethod*);
static inline R Invoke (Il2CppMethodSlot slot, RuntimeObject* obj)
{
const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj);
return ((Func)invokeData.methodPtr)(obj, invokeData.method);
}
};
// System.Runtime.InteropServices.ManagedErrorInfo
struct ManagedErrorInfo_t1050660351;
// System.String
struct String_t;
// System.Exception
struct Exception_t;
// System.Security.Cryptography.RandomNumberGenerator
struct RandomNumberGenerator_t386037858;
extern RuntimeClass* String_t_il2cpp_TypeInfo_var;
extern const uint32_t IErrorInfo_GetGUID_m1050404947_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetGUID_m3937943306_MetadataUsageId;
extern const uint32_t IErrorInfo_GetSource_m3515283667_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetSource_m2789699263_MetadataUsageId;
extern const uint32_t IErrorInfo_GetDescription_m348776341_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetDescription_m2290622299_MetadataUsageId;
extern const uint32_t IErrorInfo_GetHelpFile_m1121637497_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetHelpFile_m3537687028_MetadataUsageId;
extern const uint32_t IErrorInfo_GetHelpContext_m1611286652_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetHelpContext_m2376875466_MetadataUsageId;
struct Guid_t ;
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
// System.Runtime.InteropServices.IErrorInfo
struct NOVTABLE IErrorInfo_t3055706115 : Il2CppIUnknown
{
static const Il2CppGuid IID;
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetGUID_m1050404947(Guid_t * ___pGuid0, int32_t* comReturnValue) = 0;
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetSource_m3515283667(Il2CppChar** ___pBstrSource0, int32_t* comReturnValue) = 0;
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetDescription_m348776341(Il2CppChar** ___pbstrDescription0, int32_t* comReturnValue) = 0;
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetHelpFile_m1121637497(Il2CppChar** ___pBstrHelpFile0, int32_t* comReturnValue) = 0;
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetHelpContext_m1611286652(uint32_t* ___pdwHelpContext0, int32_t* comReturnValue) = 0;
};
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef STRING_T_H
#define STRING_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::m_stringLength
int32_t ___m_stringLength_0;
// System.Char System.String::m_firstChar
Il2CppChar ___m_firstChar_1;
public:
inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); }
inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; }
inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; }
inline void set_m_stringLength_0(int32_t value)
{
___m_stringLength_0 = value;
}
inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); }
inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; }
inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; }
inline void set_m_firstChar_1(Il2CppChar value)
{
___m_firstChar_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_5;
public:
inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); }
inline String_t* get_Empty_5() const { return ___Empty_5; }
inline String_t** get_address_of_Empty_5() { return &___Empty_5; }
inline void set_Empty_5(String_t* value)
{
___Empty_5 = value;
Il2CppCodeGenWriteBarrier((&___Empty_5), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STRING_T_H
#ifndef MANAGEDERRORINFO_T1050660351_H
#define MANAGEDERRORINFO_T1050660351_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.InteropServices.ManagedErrorInfo
struct ManagedErrorInfo_t1050660351 : public RuntimeObject
{
public:
// System.Exception System.Runtime.InteropServices.ManagedErrorInfo::m_Exception
Exception_t * ___m_Exception_0;
public:
inline static int32_t get_offset_of_m_Exception_0() { return static_cast<int32_t>(offsetof(ManagedErrorInfo_t1050660351, ___m_Exception_0)); }
inline Exception_t * get_m_Exception_0() const { return ___m_Exception_0; }
inline Exception_t ** get_address_of_m_Exception_0() { return &___m_Exception_0; }
inline void set_m_Exception_0(Exception_t * value)
{
___m_Exception_0 = value;
Il2CppCodeGenWriteBarrier((&___m_Exception_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MANAGEDERRORINFO_T1050660351_H
#ifndef UINT32_T2560061978_H
#define UINT32_T2560061978_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UInt32
struct UInt32_t2560061978
{
public:
// System.UInt32 System.UInt32::m_value
uint32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt32_t2560061978, ___m_value_0)); }
inline uint32_t get_m_value_0() const { return ___m_value_0; }
inline uint32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(uint32_t value)
{
___m_value_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UINT32_T2560061978_H
#ifndef GUID_T_H
#define GUID_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Guid
struct Guid_t
{
public:
// System.Int32 System.Guid::_a
int32_t ____a_4;
// System.Int16 System.Guid::_b
int16_t ____b_5;
// System.Int16 System.Guid::_c
int16_t ____c_6;
// System.Byte System.Guid::_d
uint8_t ____d_7;
// System.Byte System.Guid::_e
uint8_t ____e_8;
// System.Byte System.Guid::_f
uint8_t ____f_9;
// System.Byte System.Guid::_g
uint8_t ____g_10;
// System.Byte System.Guid::_h
uint8_t ____h_11;
// System.Byte System.Guid::_i
uint8_t ____i_12;
// System.Byte System.Guid::_j
uint8_t ____j_13;
// System.Byte System.Guid::_k
uint8_t ____k_14;
public:
inline static int32_t get_offset_of__a_4() { return static_cast<int32_t>(offsetof(Guid_t, ____a_4)); }
inline int32_t get__a_4() const { return ____a_4; }
inline int32_t* get_address_of__a_4() { return &____a_4; }
inline void set__a_4(int32_t value)
{
____a_4 = value;
}
inline static int32_t get_offset_of__b_5() { return static_cast<int32_t>(offsetof(Guid_t, ____b_5)); }
inline int16_t get__b_5() const { return ____b_5; }
inline int16_t* get_address_of__b_5() { return &____b_5; }
inline void set__b_5(int16_t value)
{
____b_5 = value;
}
inline static int32_t get_offset_of__c_6() { return static_cast<int32_t>(offsetof(Guid_t, ____c_6)); }
inline int16_t get__c_6() const { return ____c_6; }
inline int16_t* get_address_of__c_6() { return &____c_6; }
inline void set__c_6(int16_t value)
{
____c_6 = value;
}
inline static int32_t get_offset_of__d_7() { return static_cast<int32_t>(offsetof(Guid_t, ____d_7)); }
inline uint8_t get__d_7() const { return ____d_7; }
inline uint8_t* get_address_of__d_7() { return &____d_7; }
inline void set__d_7(uint8_t value)
{
____d_7 = value;
}
inline static int32_t get_offset_of__e_8() { return static_cast<int32_t>(offsetof(Guid_t, ____e_8)); }
inline uint8_t get__e_8() const { return ____e_8; }
inline uint8_t* get_address_of__e_8() { return &____e_8; }
inline void set__e_8(uint8_t value)
{
____e_8 = value;
}
inline static int32_t get_offset_of__f_9() { return static_cast<int32_t>(offsetof(Guid_t, ____f_9)); }
inline uint8_t get__f_9() const { return ____f_9; }
inline uint8_t* get_address_of__f_9() { return &____f_9; }
inline void set__f_9(uint8_t value)
{
____f_9 = value;
}
inline static int32_t get_offset_of__g_10() { return static_cast<int32_t>(offsetof(Guid_t, ____g_10)); }
inline uint8_t get__g_10() const { return ____g_10; }
inline uint8_t* get_address_of__g_10() { return &____g_10; }
inline void set__g_10(uint8_t value)
{
____g_10 = value;
}
inline static int32_t get_offset_of__h_11() { return static_cast<int32_t>(offsetof(Guid_t, ____h_11)); }
inline uint8_t get__h_11() const { return ____h_11; }
inline uint8_t* get_address_of__h_11() { return &____h_11; }
inline void set__h_11(uint8_t value)
{
____h_11 = value;
}
inline static int32_t get_offset_of__i_12() { return static_cast<int32_t>(offsetof(Guid_t, ____i_12)); }
inline uint8_t get__i_12() const { return ____i_12; }
inline uint8_t* get_address_of__i_12() { return &____i_12; }
inline void set__i_12(uint8_t value)
{
____i_12 = value;
}
inline static int32_t get_offset_of__j_13() { return static_cast<int32_t>(offsetof(Guid_t, ____j_13)); }
inline uint8_t get__j_13() const { return ____j_13; }
inline uint8_t* get_address_of__j_13() { return &____j_13; }
inline void set__j_13(uint8_t value)
{
____j_13 = value;
}
inline static int32_t get_offset_of__k_14() { return static_cast<int32_t>(offsetof(Guid_t, ____k_14)); }
inline uint8_t get__k_14() const { return ____k_14; }
inline uint8_t* get_address_of__k_14() { return &____k_14; }
inline void set__k_14(uint8_t value)
{
____k_14 = value;
}
};
struct Guid_t_StaticFields
{
public:
// System.Object System.Guid::_rngAccess
RuntimeObject * ____rngAccess_0;
// System.Security.Cryptography.RandomNumberGenerator System.Guid::_rng
RandomNumberGenerator_t386037858 * ____rng_1;
// System.Security.Cryptography.RandomNumberGenerator System.Guid::_fastRng
RandomNumberGenerator_t386037858 * ____fastRng_2;
// System.Guid System.Guid::Empty
Guid_t ___Empty_3;
public:
inline static int32_t get_offset_of__rngAccess_0() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____rngAccess_0)); }
inline RuntimeObject * get__rngAccess_0() const { return ____rngAccess_0; }
inline RuntimeObject ** get_address_of__rngAccess_0() { return &____rngAccess_0; }
inline void set__rngAccess_0(RuntimeObject * value)
{
____rngAccess_0 = value;
Il2CppCodeGenWriteBarrier((&____rngAccess_0), value);
}
inline static int32_t get_offset_of__rng_1() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____rng_1)); }
inline RandomNumberGenerator_t386037858 * get__rng_1() const { return ____rng_1; }
inline RandomNumberGenerator_t386037858 ** get_address_of__rng_1() { return &____rng_1; }
inline void set__rng_1(RandomNumberGenerator_t386037858 * value)
{
____rng_1 = value;
Il2CppCodeGenWriteBarrier((&____rng_1), value);
}
inline static int32_t get_offset_of__fastRng_2() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ____fastRng_2)); }
inline RandomNumberGenerator_t386037858 * get__fastRng_2() const { return ____fastRng_2; }
inline RandomNumberGenerator_t386037858 ** get_address_of__fastRng_2() { return &____fastRng_2; }
inline void set__fastRng_2(RandomNumberGenerator_t386037858 * value)
{
____fastRng_2 = value;
Il2CppCodeGenWriteBarrier((&____fastRng_2), value);
}
inline static int32_t get_offset_of_Empty_3() { return static_cast<int32_t>(offsetof(Guid_t_StaticFields, ___Empty_3)); }
inline Guid_t get_Empty_3() const { return ___Empty_3; }
inline Guid_t * get_address_of_Empty_3() { return &___Empty_3; }
inline void set_Empty_3(Guid_t value)
{
___Empty_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // GUID_T_H
// System.Int32 System.Runtime.InteropServices.ManagedErrorInfo::GetGUID(System.Guid&)
extern "C" int32_t ManagedErrorInfo_GetGUID_m3937943306 (ManagedErrorInfo_t1050660351 * __this, Guid_t * ___guid0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Runtime.InteropServices.ManagedErrorInfo::GetSource(System.String&)
extern "C" int32_t ManagedErrorInfo_GetSource_m2789699263 (ManagedErrorInfo_t1050660351 * __this, String_t** ___source0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Runtime.InteropServices.ManagedErrorInfo::GetDescription(System.String&)
extern "C" int32_t ManagedErrorInfo_GetDescription_m2290622299 (ManagedErrorInfo_t1050660351 * __this, String_t** ___description0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Runtime.InteropServices.ManagedErrorInfo::GetHelpFile(System.String&)
extern "C" int32_t ManagedErrorInfo_GetHelpFile_m3537687028 (ManagedErrorInfo_t1050660351 * __this, String_t** ___helpFile0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Runtime.InteropServices.ManagedErrorInfo::GetHelpContext(System.UInt32&)
extern "C" int32_t ManagedErrorInfo_GetHelpContext_m2376875466 (ManagedErrorInfo_t1050660351 * __this, uint32_t* ___helpContext0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
// COM Callable Wrapper for System.Runtime.InteropServices.ManagedErrorInfo
struct ManagedErrorInfo_t1050660351_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<ManagedErrorInfo_t1050660351_ComCallableWrapper>, IErrorInfo_t3055706115
{
inline ManagedErrorInfo_t1050660351_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<ManagedErrorInfo_t1050660351_ComCallableWrapper>(obj) {}
virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE
{
if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0
|| ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0)
{
*object = GetIdentity();
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIManagedObjectHolder*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &IErrorInfo_t3055706115::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<IErrorInfo_t3055706115*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0)
{
*object = static_cast<Il2CppIMarshal*>(this);
AddRefImpl();
return IL2CPP_S_OK;
}
*object = NULL;
return IL2CPP_E_NOINTERFACE;
}
virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE
{
return AddRefImpl();
}
virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE
{
return ReleaseImpl();
}
virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE
{
*iidCount = 0;
*iids = NULL;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetGUID_m1050404947(Guid_t * ___guid0, int32_t* comReturnValue) IL2CPP_OVERRIDE
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (IErrorInfo_GetGUID_m1050404947_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetGUID_m3937943306_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
il2cpp_native_wrapper_vm_thread_attacher _vmThreadHelper;
// Marshaling of parameter '___guid0' to managed representation
Guid_t ____guid0_empty;
memset(&____guid0_empty, 0, sizeof(____guid0_empty));
// Managed method invocation
int32_t returnValue;
try
{
ManagedErrorInfo_t1050660351 * __thisValue = (ManagedErrorInfo_t1050660351 *)GetManagedObjectInline();
returnValue = ManagedErrorInfo_GetGUID_m3937943306(__thisValue, (&____guid0_empty), NULL);
}
catch (const Il2CppExceptionWrapper& ex)
{
*comReturnValue = 0;
String_t* exceptionStr = NULL;
try
{
exceptionStr = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, ex.ex);
}
catch (const Il2CppExceptionWrapper&)
{
exceptionStr = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->get_Empty_5();
}
il2cpp_codegen_store_exception_info(ex.ex, exceptionStr);
return ex.ex->hresult;
}
// Marshaling of parameter '___guid0' back from managed representation
*___guid0 = ____guid0_empty;
*comReturnValue = returnValue;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetSource_m3515283667(Il2CppChar** ___source0, int32_t* comReturnValue) IL2CPP_OVERRIDE
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (IErrorInfo_GetSource_m3515283667_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetSource_m2789699263_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
il2cpp_native_wrapper_vm_thread_attacher _vmThreadHelper;
// Marshaling of parameter '___source0' to managed representation
String_t* ____source0_empty = NULL;
// Managed method invocation
int32_t returnValue;
try
{
ManagedErrorInfo_t1050660351 * __thisValue = (ManagedErrorInfo_t1050660351 *)GetManagedObjectInline();
returnValue = ManagedErrorInfo_GetSource_m2789699263(__thisValue, (&____source0_empty), NULL);
}
catch (const Il2CppExceptionWrapper& ex)
{
*comReturnValue = 0;
String_t* exceptionStr = NULL;
try
{
exceptionStr = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, ex.ex);
}
catch (const Il2CppExceptionWrapper&)
{
exceptionStr = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->get_Empty_5();
}
il2cpp_codegen_store_exception_info(ex.ex, exceptionStr);
return ex.ex->hresult;
}
// Marshaling of parameter '___source0' back from managed representation
*___source0 = il2cpp_codegen_marshal_bstring(____source0_empty);
*comReturnValue = returnValue;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetDescription_m348776341(Il2CppChar** ___description0, int32_t* comReturnValue) IL2CPP_OVERRIDE
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (IErrorInfo_GetDescription_m348776341_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetDescription_m2290622299_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
il2cpp_native_wrapper_vm_thread_attacher _vmThreadHelper;
// Marshaling of parameter '___description0' to managed representation
String_t* ____description0_empty = NULL;
// Managed method invocation
int32_t returnValue;
try
{
ManagedErrorInfo_t1050660351 * __thisValue = (ManagedErrorInfo_t1050660351 *)GetManagedObjectInline();
returnValue = ManagedErrorInfo_GetDescription_m2290622299(__thisValue, (&____description0_empty), NULL);
}
catch (const Il2CppExceptionWrapper& ex)
{
*comReturnValue = 0;
String_t* exceptionStr = NULL;
try
{
exceptionStr = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, ex.ex);
}
catch (const Il2CppExceptionWrapper&)
{
exceptionStr = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->get_Empty_5();
}
il2cpp_codegen_store_exception_info(ex.ex, exceptionStr);
return ex.ex->hresult;
}
// Marshaling of parameter '___description0' back from managed representation
*___description0 = il2cpp_codegen_marshal_bstring(____description0_empty);
*comReturnValue = returnValue;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetHelpFile_m1121637497(Il2CppChar** ___helpFile0, int32_t* comReturnValue) IL2CPP_OVERRIDE
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (IErrorInfo_GetHelpFile_m1121637497_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetHelpFile_m3537687028_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
il2cpp_native_wrapper_vm_thread_attacher _vmThreadHelper;
// Marshaling of parameter '___helpFile0' to managed representation
String_t* ____helpFile0_empty = NULL;
// Managed method invocation
int32_t returnValue;
try
{
ManagedErrorInfo_t1050660351 * __thisValue = (ManagedErrorInfo_t1050660351 *)GetManagedObjectInline();
returnValue = ManagedErrorInfo_GetHelpFile_m3537687028(__thisValue, (&____helpFile0_empty), NULL);
}
catch (const Il2CppExceptionWrapper& ex)
{
*comReturnValue = 0;
String_t* exceptionStr = NULL;
try
{
exceptionStr = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, ex.ex);
}
catch (const Il2CppExceptionWrapper&)
{
exceptionStr = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->get_Empty_5();
}
il2cpp_codegen_store_exception_info(ex.ex, exceptionStr);
return ex.ex->hresult;
}
// Marshaling of parameter '___helpFile0' back from managed representation
*___helpFile0 = il2cpp_codegen_marshal_bstring(____helpFile0_empty);
*comReturnValue = returnValue;
return IL2CPP_S_OK;
}
virtual il2cpp_hresult_t STDCALL IErrorInfo_GetHelpContext_m1611286652(uint32_t* ___helpContext0, int32_t* comReturnValue) IL2CPP_OVERRIDE
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (IErrorInfo_GetHelpContext_m1611286652_CCW_ManagedErrorInfo_t1050660351_ComCallableWrapper_ManagedErrorInfo_GetHelpContext_m2376875466_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
il2cpp_native_wrapper_vm_thread_attacher _vmThreadHelper;
// Marshaling of parameter '___helpContext0' to managed representation
uint32_t ____helpContext0_empty = 0;
// Managed method invocation
int32_t returnValue;
try
{
ManagedErrorInfo_t1050660351 * __thisValue = (ManagedErrorInfo_t1050660351 *)GetManagedObjectInline();
returnValue = ManagedErrorInfo_GetHelpContext_m2376875466(__thisValue, (&____helpContext0_empty), NULL);
}
catch (const Il2CppExceptionWrapper& ex)
{
*comReturnValue = 0;
String_t* exceptionStr = NULL;
try
{
exceptionStr = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, ex.ex);
}
catch (const Il2CppExceptionWrapper&)
{
exceptionStr = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->get_Empty_5();
}
il2cpp_codegen_store_exception_info(ex.ex, exceptionStr);
return ex.ex->hresult;
}
// Marshaling of parameter '___helpContext0' back from managed representation
*___helpContext0 = ____helpContext0_empty;
*comReturnValue = returnValue;
return IL2CPP_S_OK;
}
};
extern "C" Il2CppIUnknown* CreateComCallableWrapperFor_ManagedErrorInfo_t1050660351(RuntimeObject* obj)
{
void* memory = il2cpp::utils::Memory::Malloc(sizeof(ManagedErrorInfo_t1050660351_ComCallableWrapper));
if (memory == NULL)
{
il2cpp_codegen_raise_out_of_memory_exception();
}
return static_cast<Il2CppIManagedObjectHolder*>(new(memory) ManagedErrorInfo_t1050660351_ComCallableWrapper(obj));
}
| 35.544139 | 188 | 0.794878 | [
"object"
] |
eee90894ad5b667903b0e1b6791d0a1db50dd645 | 6,366 | cpp | C++ | src/third_party/skia/tests/GrPathUtilsTest.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 3 | 2019-10-14T06:36:32.000Z | 2021-02-20T10:55:14.000Z | src/third_party/skia/tests/GrPathUtilsTest.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 1 | 2021-03-15T17:26:39.000Z | 2021-03-16T17:59:26.000Z | src/third_party/skia/tests/GrPathUtilsTest.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 1 | 2021-06-06T21:31:52.000Z | 2021-06-06T21:31:52.000Z | /*
* Copyright 2020 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/utils/SkRandom.h"
#include "src/core/SkGeometry.h"
#include "src/gpu/geometry/GrPathUtils.h"
#include "tests/Test.h"
static bool is_linear(SkPoint p0, SkPoint p1, SkPoint p2) {
return SkScalarNearlyZero((p0 - p1).cross(p2 - p1));
}
static bool is_linear(const SkPoint p[4]) {
return is_linear(p[0],p[1],p[2]) && is_linear(p[0],p[2],p[3]) && is_linear(p[1],p[2],p[3]);
}
static void check_cubic_convex_180(skiatest::Reporter* r, const SkPoint p[4]) {
bool areCusps = false;
float inflectT[2], convex180T[2];
if (int inflectN = SkFindCubicInflections(p, inflectT)) {
// The curve has inflections. findCubicConvex180Chops should return the inflection
// points.
int convex180N = GrPathUtils::findCubicConvex180Chops(p, convex180T, &areCusps);
REPORTER_ASSERT(r, inflectN == convex180N);
if (!areCusps) {
REPORTER_ASSERT(r, inflectN == 1 ||
fabsf(inflectT[0] - inflectT[1]) >= SK_ScalarNearlyZero);
}
for (int i = 0; i < convex180N; ++i) {
REPORTER_ASSERT(r, SkScalarNearlyEqual(inflectT[i], convex180T[i]));
}
} else {
float totalRotation = SkMeasureNonInflectCubicRotation(p);
int convex180N = GrPathUtils::findCubicConvex180Chops(p, convex180T, &areCusps);
SkPoint chops[10];
SkChopCubicAt(p, chops, convex180T, convex180N);
float radsSum = 0;
for (int i = 0; i <= convex180N; ++i) {
float rads = SkMeasureNonInflectCubicRotation(chops + i*3);
SkASSERT(rads < SK_ScalarPI + SK_ScalarNearlyZero);
radsSum += rads;
}
if (totalRotation < SK_ScalarPI - SK_ScalarNearlyZero) {
// The curve should never chop if rotation is <180 degrees.
REPORTER_ASSERT(r, convex180N == 0);
} else if (!is_linear(p)) {
REPORTER_ASSERT(r, SkScalarNearlyEqual(radsSum, totalRotation));
if (totalRotation > SK_ScalarPI + SK_ScalarNearlyZero) {
REPORTER_ASSERT(r, convex180N == 1);
// This works because cusps take the "inflection" path above, so we don't get
// non-lilnear curves that lose rotation when chopped.
REPORTER_ASSERT(r, SkScalarNearlyEqual(
SkMeasureNonInflectCubicRotation(chops), SK_ScalarPI));
REPORTER_ASSERT(r, SkScalarNearlyEqual(
SkMeasureNonInflectCubicRotation(chops + 3), totalRotation - SK_ScalarPI));
}
REPORTER_ASSERT(r, !areCusps);
} else {
REPORTER_ASSERT(r, areCusps);
}
}
}
DEF_TEST(GrPathUtils_findCubicConvex180Chops, r) {
// Test all combinations of corners from the square [0,0,1,1]. This covers every cubic type as
// well as a wide variety of special cases for cusps, lines, loops, and inflections.
for (int i = 0; i < (1 << 8); ++i) {
SkPoint p[4] = {SkPoint::Make((i>>0)&1, (i>>1)&1),
SkPoint::Make((i>>2)&1, (i>>3)&1),
SkPoint::Make((i>>4)&1, (i>>5)&1),
SkPoint::Make((i>>6)&1, (i>>7)&1)};
check_cubic_convex_180(r, p);
}
{
// This cubic has a convex-180 chop at T=1-"epsilon"
static const uint32_t hexPts[] = {0x3ee0ac74, 0x3f1e061a, 0x3e0fc408, 0x3f457230,
0x3f42ac7c, 0x3f70d76c, 0x3f4e6520, 0x3f6acafa};
SkPoint p[4];
memcpy(p, hexPts, sizeof(p));
check_cubic_convex_180(r, p);
}
// Now test an exact quadratic.
SkPoint quad[4] = {{0,0}, {2,2}, {4,2}, {6,0}};
float T[2];
REPORTER_ASSERT(r, GrPathUtils::findCubicConvex180Chops(quad, T) == 0);
// Now test that cusps and near-cusps get flagged as cusps.
SkPoint cusp[4] = {{0,0}, {1,1}, {1,0}, {0,1}};
bool areCusps = false;
REPORTER_ASSERT(r, GrPathUtils::findCubicConvex180Chops(cusp, T, &areCusps) == 1);
REPORTER_ASSERT(r, areCusps == true);
// Find the height of the right side of "cusp" at which the distance between its inflection
// points is kEpsilon (in parametric space).
constexpr static double kEpsilon = 1.0 / (1 << 11);
constexpr static double kEpsilonSquared = kEpsilon * kEpsilon;
double h = (1 - kEpsilonSquared) / (3 * kEpsilonSquared + 1);
double dy = (1 - h) / 2;
cusp[1].fY = (float)(1 - dy);
cusp[2].fY = (float)(0 + dy);
REPORTER_ASSERT(r, SkFindCubicInflections(cusp, T) == 2);
REPORTER_ASSERT(r, SkScalarNearlyEqual(T[1] - T[0], (float)kEpsilon, (float)kEpsilonSquared));
// Ensure two inflection points barely more than kEpsilon apart do not get flagged as cusps.
cusp[1].fY = (float)(1 - 1.1 * dy);
cusp[2].fY = (float)(0 + 1.1 * dy);
areCusps = false;
REPORTER_ASSERT(r, GrPathUtils::findCubicConvex180Chops(cusp, T, &areCusps) == 2);
REPORTER_ASSERT(r, areCusps == false);
// Ensure two inflection points barely less than kEpsilon apart do get flagged as cusps.
cusp[1].fY = (float)(1 - .9 * dy);
cusp[2].fY = (float)(0 + .9 * dy);
areCusps = false;
REPORTER_ASSERT(r, GrPathUtils::findCubicConvex180Chops(cusp, T, &areCusps) == 1);
REPORTER_ASSERT(r, areCusps == true);
}
DEF_TEST(GrPathUtils_convertToCubic, r) {
SkPoint cubic[4];
GrPathUtils::convertLineToCubic({0,0}, {3,6}, cubic);
REPORTER_ASSERT(r, cubic[0] == SkPoint::Make(0,0));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[1].fX, 1));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[1].fY, 2));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[2].fX, 2));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[2].fY, 4));
REPORTER_ASSERT(r, cubic[3] == SkPoint::Make(3,6));
SkPoint quad[3] = {{0,0}, {3,3}, {6,0}};
GrPathUtils::convertQuadToCubic(quad, cubic);
REPORTER_ASSERT(r, cubic[0] == SkPoint::Make(0,0));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[1].fX, 2));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[1].fY, 2));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[2].fX, 4));
REPORTER_ASSERT(r, SkScalarNearlyEqual(cubic[2].fY, 2));
REPORTER_ASSERT(r, cubic[3] == SkPoint::Make(6,0));
}
| 44.208333 | 98 | 0.621583 | [
"geometry"
] |
eee9da09cd5b7a204d4b9e3288916c9ad2e92138 | 9,407 | cpp | C++ | src/edyn/collision/broadphase_main.cpp | dvir/edyn | 3693937160663319fb9c0789f3b279a650ad2219 | [
"MIT"
] | null | null | null | src/edyn/collision/broadphase_main.cpp | dvir/edyn | 3693937160663319fb9c0789f3b279a650ad2219 | [
"MIT"
] | null | null | null | src/edyn/collision/broadphase_main.cpp | dvir/edyn | 3693937160663319fb9c0789f3b279a650ad2219 | [
"MIT"
] | null | null | null | #include "edyn/collision/broadphase_main.hpp"
#include "edyn/collision/tree_node.hpp"
#include "edyn/comp/aabb.hpp"
#include "edyn/comp/island.hpp"
#include "edyn/comp/tree_resident.hpp"
#include "edyn/collision/contact_manifold.hpp"
#include "edyn/collision/contact_manifold_map.hpp"
#include "edyn/util/constraint_util.hpp"
#include "edyn/collision/tree_view.hpp"
#include "edyn/comp/tag.hpp"
#include "edyn/parallel/parallel_for.hpp"
#include "edyn/context/settings.hpp"
#include <entt/entity/registry.hpp>
namespace edyn {
broadphase_main::broadphase_main(entt::registry ®istry)
: m_registry(®istry)
{
// Add tree nodes for islands (which have a `tree_view`) and for static and
// kinematic entities.
registry.on_construct<tree_view>().connect<&broadphase_main::on_construct_tree_view>(*this);
registry.on_construct<static_tag>().connect<&broadphase_main::on_construct_static_kinematic_tag>(*this);
registry.on_construct<kinematic_tag>().connect<&broadphase_main::on_construct_static_kinematic_tag>(*this);
registry.on_destroy<tree_resident>().connect<&broadphase_main::on_destroy_tree_resident>(*this);
}
void broadphase_main::on_construct_tree_view(entt::registry ®istry, entt::entity entity) {
EDYN_ASSERT(registry.any_of<island>(entity));
auto &view = registry.get<tree_view>(entity);
auto id = m_island_tree.create(view.root_aabb(), entity);
registry.emplace<tree_resident>(entity, id, true);
}
void broadphase_main::on_construct_static_kinematic_tag(entt::registry ®istry, entt::entity entity) {
if (!registry.any_of<AABB>(entity)) return;
auto &aabb = registry.get<AABB>(entity);
auto id = m_np_tree.create(aabb, entity);
registry.emplace<tree_resident>(entity, id, false);
}
void broadphase_main::on_destroy_tree_resident(entt::registry ®istry, entt::entity entity) {
auto &node = registry.get<tree_resident>(entity);
if (node.procedural) {
m_island_tree.destroy(node.id);
} else {
m_np_tree.destroy(node.id);
}
}
void broadphase_main::update() {
// Update island AABBs in tree (ignore sleeping islands).
auto exclude_sleeping = entt::exclude_t<sleeping_tag>{};
auto tree_view_resident_view = m_registry->view<tree_view, tree_resident>(exclude_sleeping);
tree_view_resident_view.each([&] (tree_view &tree_view, tree_resident &node) {
m_island_tree.move(node.id, tree_view.root_aabb());
});
// Update kinematic AABBs in tree.
// TODO: only do this for kinematic entities that had their AABB updated.
auto kinematic_aabb_node_view = m_registry->view<tree_resident, AABB, kinematic_tag>();
kinematic_aabb_node_view.each([&] (tree_resident &node, AABB &aabb) {
m_np_tree.move(node.id, aabb);
});
// Search for island pairs with intersecting AABBs, i.e. the AABB of the root
// node of their trees intersect.
auto tree_view_not_sleeping_view = m_registry->view<tree_view>(exclude_sleeping);
std::vector<entt::entity> awake_island_entities;
for (auto entity : tree_view_not_sleeping_view) {
awake_island_entities.push_back(entity);
}
if (awake_island_entities.empty()) {
return;
}
const auto aabb_view = m_registry->view<AABB>();
const auto tree_view_view = m_registry->view<tree_view>();
const auto multi_resident_view = m_registry->view<multi_island_resident>();
if (awake_island_entities.size() > 1) {
m_pair_results.resize(awake_island_entities.size());
parallel_for(size_t{0}, awake_island_entities.size(), [&] (size_t index) {
auto island_entityA = awake_island_entities[index];
m_pair_results[index] = find_intersecting_islands(island_entityA, aabb_view, multi_resident_view, tree_view_view);
});
auto &manifold_map = m_registry->ctx().at<contact_manifold_map>();
for (auto &results : m_pair_results) {
for (auto &pair : results) {
if (!manifold_map.contains(pair)) {
make_contact_manifold(*m_registry, pair.first, pair.second, m_separation_threshold);
}
}
}
m_pair_results.clear();
} else {
for (auto island_entityA : awake_island_entities) {
auto pairs = find_intersecting_islands(island_entityA, aabb_view, multi_resident_view, tree_view_view);
for (auto &pair : pairs) {
make_contact_manifold(*m_registry, pair.first, pair.second, m_separation_threshold);
}
}
}
}
entity_pair_vector broadphase_main::find_intersecting_islands(entt::entity island_entityA,
const aabb_view_t &aabb_view,
const multi_resident_view_t &resident_view,
const tree_view_view_t &tree_view_view) const {
auto tree_viewA = tree_view_view.get<tree_view>(island_entityA);
auto island_aabb = tree_viewA.root_aabb().inset(m_aabb_offset);
entity_pair_vector results;
// Query the dynamic tree to find other islands whose AABB intersects the
// current island's AABB.
m_island_tree.query(island_aabb, [&] (tree_node_id_t idB) {
auto island_entityB = m_island_tree.get_node(idB).entity;
if (island_entityA == island_entityB) {
return;
}
// Look for AABB intersections between entities from different islands
// and create manifolds.
auto &tree_viewB = tree_view_view.get<tree_view>(island_entityB);
auto pairs = intersect_islands(tree_viewA, tree_viewB, aabb_view);
results.insert(results.end(), pairs.begin(), pairs.end());
});
// Query the non-procedural dynamic tree to find static and kinematic
// entities that are intersecting this island.
m_np_tree.query(island_aabb, [&] (tree_node_id_t id_np) {
auto np_entity = m_np_tree.get_node(id_np).entity;
// Only proceed if the non-procedural entity is not in the island,
// because if it is already in, collisions are handled in the
// island worker.
auto &resident = resident_view.get<multi_island_resident>(np_entity);
if (resident.island_entities.contains(island_entityA)) {
return;
}
auto pairs = intersect_island_np(tree_viewA, np_entity, aabb_view);
results.insert(results.end(), pairs.begin(), pairs.end());
});
return results;
}
entity_pair_vector broadphase_main::intersect_islands(const tree_view &tree_viewA, const tree_view &tree_viewB,
const aabb_view_t &aabb_view) const {
// Query one tree for each node of the other tree. Pick the smaller tree
// for the iteration and use the bigger one for the query.
if (tree_viewA.size() < tree_viewB.size()) {
return intersect_islands_a(tree_viewA, tree_viewB, aabb_view);
} else {
return intersect_islands_a(tree_viewB, tree_viewA, aabb_view);
}
}
entity_pair_vector broadphase_main::intersect_islands_a(const tree_view &tree_viewA, const tree_view &tree_viewB,
const aabb_view_t &aabb_view) const {
entity_pair_vector results;
auto &manifold_map = m_registry->ctx().at<contact_manifold_map>();
// `tree_viewA` is iterated and for each node an AABB query is performed in
// `tree_viewB`, thus for better performance `tree_viewA` should be smaller
// than `tree_viewB`.
tree_viewA.each([&] (const tree_view::tree_node &nodeA) {
auto entityA = nodeA.entity;
auto aabbA = aabb_view.get<AABB>(entityA).inset(m_aabb_offset);
tree_viewB.query(aabbA, [&] (tree_node_id_t idB) {
auto entityB = tree_viewB.get_node(idB).entity;
if (should_collide(entityA, entityB) && !manifold_map.contains(entityA, entityB)) {
auto &aabbB = aabb_view.get<AABB>(entityB);
if (intersect(aabbA, aabbB)) {
results.emplace_back(entityA, entityB);
}
}
});
});
return results;
}
entity_pair_vector broadphase_main::intersect_island_np(const tree_view &island_tree, entt::entity np_entity,
const aabb_view_t &aabb_view) const {
auto np_aabb = aabb_view.get<AABB>(np_entity).inset(m_aabb_offset);
entity_pair_vector results;
auto &manifold_map = m_registry->ctx().at<contact_manifold_map>();
island_tree.query(np_aabb, [&] (tree_node_id_t idA) {
auto entity = island_tree.get_node(idA).entity;
if (should_collide(entity, np_entity) && !manifold_map.contains(entity, np_entity)) {
auto &aabb = aabb_view.get<AABB>(entity);
if (intersect(aabb, np_aabb)) {
results.emplace_back(entity, np_entity);
}
}
});
return results;
}
bool broadphase_main::should_collide(entt::entity first, entt::entity second) const {
// Entities should never be equal because they should come from
// different islands at this point.
EDYN_ASSERT(first != second);
auto &settings = m_registry->ctx().at<edyn::settings>();
return (*settings.should_collide_func)(*m_registry, first, second);
}
}
| 40.9 | 126 | 0.669927 | [
"vector"
] |
eef7401ba7cc753df6a7d1e3a0b2368889e32ab1 | 1,144 | cpp | C++ | windows/pw6e.official/CPlusPlus/Chapter10/AnalogClock/AnalogClock/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:18:08.000Z | 2016-11-23T08:18:08.000Z | windows/pw6e.official/CPlusPlus/Chapter10/AnalogClock/AnalogClock/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | null | null | null | windows/pw6e.official/CPlusPlus/Chapter10/AnalogClock/AnalogClock/MainPage.xaml.cpp | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:17:34.000Z | 2016-11-23T08:17:34.000Z | //
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h" // includes Windows.h
#include "MainPage.xaml.h"
using namespace AnalogClock;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
MainPage::MainPage()
{
InitializeComponent();
CompositionTarget::Rendering += ref new EventHandler<Object^>(this, &MainPage::OnCompositionTargetRendering);
}
void MainPage::OnCompositionTargetRendering(Object^ sender, Object^ args)
{
SYSTEMTIME dt;
GetLocalTime(&dt);
rotateSecond->Angle = 6 * (dt.wSecond + dt.wMilliseconds / 1000.0);
rotateMinute->Angle = 6 * dt.wMinute + rotateSecond->Angle / 60;
rotateHour->Angle = 30 * (dt.wHour % 12) + rotateMinute->Angle / 12;
}
| 31.777778 | 114 | 0.702797 | [
"object"
] |
eef7445d0a696450ba890296ecdacbc67aae56b4 | 1,324 | cpp | C++ | aws-cpp-sdk-ram/source/model/GetResourceSharesResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2021-12-06T20:36:35.000Z | 2021-12-06T20:36:35.000Z | aws-cpp-sdk-ram/source/model/GetResourceSharesResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ram/source/model/GetResourceSharesResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ram/model/GetResourceSharesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::RAM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetResourceSharesResult::GetResourceSharesResult()
{
}
GetResourceSharesResult::GetResourceSharesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
GetResourceSharesResult& GetResourceSharesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("resourceShares"))
{
Array<JsonView> resourceSharesJsonList = jsonValue.GetArray("resourceShares");
for(unsigned resourceSharesIndex = 0; resourceSharesIndex < resourceSharesJsonList.GetLength(); ++resourceSharesIndex)
{
m_resourceShares.push_back(resourceSharesJsonList[resourceSharesIndex].AsObject());
}
}
if(jsonValue.ValueExists("nextToken"))
{
m_nextToken = jsonValue.GetString("nextToken");
}
return *this;
}
| 26.48 | 122 | 0.762085 | [
"model"
] |
eef9e78dbb0e1765b057be3608df932ef9ea55b1 | 82,640 | cpp | C++ | nertc_sdk_node/nertc_node_engine.cpp | nmgwddj/node-nertc-sdk | 555aff158ddfa46205a316b7cd74bec814ce25df | [
"MIT"
] | 1 | 2021-09-11T08:07:53.000Z | 2021-09-11T08:07:53.000Z | nertc_sdk_node/nertc_node_engine.cpp | nmgwddj/node-nertc-sdk | 555aff158ddfa46205a316b7cd74bec814ce25df | [
"MIT"
] | null | null | null | nertc_sdk_node/nertc_node_engine.cpp | nmgwddj/node-nertc-sdk | 555aff158ddfa46205a316b7cd74bec814ce25df | [
"MIT"
] | 4 | 2021-11-04T10:48:32.000Z | 2022-03-15T06:10:50.000Z | #include "nertc_node_engine.h"
#include "nertc_node_engine_helper.h"
#include "nertc_node_video_frame_provider.h"
#ifdef WIN32
#include "../shared/util/string_util.h"
using namespace nertc_electron_util;
#endif
namespace nertc_node
{
DEFINE_CLASS(NertcNodeEngine);
NertcNodeEngine::NertcNodeEngine(Isolate *isolate)
{
isolate_ = isolate;
rtc_engine_ = (nertc::IRtcEngineEx *)createNERtcEngine();
#ifdef WIN32
_windows_helper = new WindowsHelpers();
window_capture_helper_.reset(new WindowCaptureHelper());
screen_capture_helper_.reset(new ScreenCaptureHelper());
#endif
}
NertcNodeEngine::~NertcNodeEngine()
{
if (rtc_engine_)
{
destroyNERtcEngine((void *&)rtc_engine_);
_adm = nullptr;
_vdm = nullptr;
rtc_engine_ = nullptr;
}
#ifdef WIN32
if (_windows_helper)
{
delete _windows_helper;
_windows_helper = nullptr;
}
#endif
}
// void NertcNodeEngine::InitModule(Local<Object> &module)
void NertcNodeEngine::InitModule(Local<Object> &exports,
Local<Value> &module,
Local<Context> &context)
{
BEGIN_OBJECT_INIT_EX(NertcNodeEngine, New, 5)
SET_PROTOTYPE(initialize)
SET_PROTOTYPE(release)
SET_PROTOTYPE(setChannelProfile)
SET_PROTOTYPE(joinChannel)
SET_PROTOTYPE(leaveChannel)
SET_PROTOTYPE(enableLocalAudio)
SET_PROTOTYPE(enableLocalVideo)
SET_PROTOTYPE(subscribeRemoteVideoStream)
SET_PROTOTYPE(setupVideoCanvas)
SET_PROTOTYPE(onVideoFrame)
SET_PROTOTYPE(onEvent)
// 3.9
SET_PROTOTYPE(setClientRole)
SET_PROTOTYPE(setupSubStreamVideoCanvas)
SET_PROTOTYPE(subscribeRemoteVideoSubStream)
SET_PROTOTYPE(setMixedAudioFrameParameters)
SET_PROTOTYPE(setExternalAudioSource)
SET_PROTOTYPE(pushExternalAudioFrame)
// 4.0
SET_PROTOTYPE(sendSEIMsg)
SET_PROTOTYPE(sendSEIMsgEx)
SET_PROTOTYPE(setExternalAudioRender)
SET_PROTOTYPE(pullExternalAudioFrame)
// 4.1.1
SET_PROTOTYPE(setAudioEffectPreset)
SET_PROTOTYPE(setVoiceBeautifierPreset)
SET_PROTOTYPE(setLocalVoicePitch)
SET_PROTOTYPE(setLocalVoiceEqualization)
// 4.1.110
SET_PROTOTYPE(setRemoteHighPriorityAudioStream);
SET_PROTOTYPE(subscribeRemoteAudioSubStream);
SET_PROTOTYPE(enableLocalAudioStream);
SET_PROTOTYPE(enableLoopbackRecording);
SET_PROTOTYPE(adjustLoopbackRecordingSignalVolume);
SET_PROTOTYPE(adjustUserPlaybackSignalVolume);
// 4.1.112
SET_PROTOTYPE(checkNECastAudioDriver);
SET_PROTOTYPE(getConnectionState)
SET_PROTOTYPE(muteLocalAudioStream)
SET_PROTOTYPE(setAudioProfile)
SET_PROTOTYPE(subscribeRemoteAudioStream)
SET_PROTOTYPE(setVideoConfig)
SET_PROTOTYPE(enableDualStreamMode)
SET_PROTOTYPE(setLocalVideoMirrorMode)
SET_PROTOTYPE(startVideoPreview)
SET_PROTOTYPE(stopVideoPreview)
SET_PROTOTYPE(muteLocalVideoStream)
SET_PROTOTYPE(setParameters)
SET_PROTOTYPE(setRecordingAudioFrameParameters)
SET_PROTOTYPE(setPlaybackAudioFrameParameters)
SET_PROTOTYPE(startAudioDump)
SET_PROTOTYPE(stopAudioDump)
SET_PROTOTYPE(startAudioMixing)
SET_PROTOTYPE(stopAudioMixing)
SET_PROTOTYPE(pauseAudioMixing)
SET_PROTOTYPE(resumeAudioMixing)
SET_PROTOTYPE(setAudioMixingSendVolume)
SET_PROTOTYPE(getAudioMixingSendVolume)
SET_PROTOTYPE(setAudioMixingPlaybackVolume)
SET_PROTOTYPE(getAudioMixingPlaybackVolume)
SET_PROTOTYPE(getAudioMixingDuration)
SET_PROTOTYPE(getAudioMixingCurrentPosition)
SET_PROTOTYPE(setAudioMixingPosition)
SET_PROTOTYPE(playEffect)
SET_PROTOTYPE(stopEffect)
SET_PROTOTYPE(stopAllEffects)
SET_PROTOTYPE(pauseEffect)
SET_PROTOTYPE(resumeEffect)
SET_PROTOTYPE(pauseAllEffects)
SET_PROTOTYPE(resumeAllEffects)
SET_PROTOTYPE(setEffectSendVolume)
SET_PROTOTYPE(getEffectSendVolume)
SET_PROTOTYPE(setEffectPlaybackVolume)
SET_PROTOTYPE(getEffectPlaybackVolume)
SET_PROTOTYPE(enableEarback)
SET_PROTOTYPE(setEarbackVolume)
SET_PROTOTYPE(onStatsObserver)
SET_PROTOTYPE(enableAudioVolumeIndication)
SET_PROTOTYPE(startScreenCaptureByScreenRect)
SET_PROTOTYPE(startScreenCaptureByDisplayId)
SET_PROTOTYPE(startScreenCaptureByWindowId)
SET_PROTOTYPE(updateScreenCaptureRegion)
SET_PROTOTYPE(stopScreenCapture)
SET_PROTOTYPE(pauseScreenCapture)
SET_PROTOTYPE(resumeScreenCapture)
SET_PROTOTYPE(setExternalVideoSource)
SET_PROTOTYPE(pushExternalVideoFrame)
SET_PROTOTYPE(getVersion)
SET_PROTOTYPE(getErrorDescription)
SET_PROTOTYPE(uploadSdkInfo)
SET_PROTOTYPE(addLiveStreamTask)
SET_PROTOTYPE(updateLiveStreamTask)
SET_PROTOTYPE(removeLiveStreamTask)
SET_PROTOTYPE(enumerateRecordDevices)
SET_PROTOTYPE(setRecordDevice)
SET_PROTOTYPE(getRecordDevice)
SET_PROTOTYPE(enumeratePlayoutDevices)
SET_PROTOTYPE(setPlayoutDevice)
SET_PROTOTYPE(getPlayoutDevice)
SET_PROTOTYPE(setRecordDeviceVolume)
SET_PROTOTYPE(getRecordDeviceVolume)
SET_PROTOTYPE(setPlayoutDeviceVolume)
SET_PROTOTYPE(getPlayoutDeviceVolume)
SET_PROTOTYPE(setPlayoutDeviceMute)
SET_PROTOTYPE(getPlayoutDeviceMute)
SET_PROTOTYPE(setRecordDeviceMute)
SET_PROTOTYPE(getRecordDeviceMute)
SET_PROTOTYPE(adjustRecordingSignalVolume)
SET_PROTOTYPE(adjustPlaybackSignalVolume)
SET_PROTOTYPE(startRecordDeviceTest)
SET_PROTOTYPE(stopRecordDeviceTest)
SET_PROTOTYPE(startPlayoutDeviceTest)
SET_PROTOTYPE(stopPlayoutDeviceTest)
SET_PROTOTYPE(startAudioDeviceLoopbackTest)
SET_PROTOTYPE(stopAudioDeviceLoopbackTest)
SET_PROTOTYPE(enumerateCaptureDevices)
SET_PROTOTYPE(setDevice)
SET_PROTOTYPE(getDevice)
SET_PROTOTYPE(enumerateScreenCaptureSourceInfo)
SET_PROTOTYPE(startSystemAudioLoopbackCapture)
SET_PROTOTYPE(stopSystemAudioLoopbackCapture)
SET_PROTOTYPE(setSystemAudioLoopbackCaptureVolume)
END_OBJECT_INIT_EX(NertcNodeEngine)
}
void NertcNodeEngine::New(const FunctionCallbackInfo<Value> &args)
{
Isolate *isolate = args.GetIsolate();
if (args.IsConstructCall())
{
NertcNodeEngine *engine = new NertcNodeEngine(isolate);
engine->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
else
{
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Context> context = isolate->GetCurrentContext();
Local<Object> instance = cons->NewInstance(context).ToLocalChecked();
args.GetReturnValue().Set(instance);
}
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, initialize)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1; bool log_ret = false;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcEngineContext context;
context.video_use_exnternal_render = true;
context.video_prefer_hw_decoder = false;
context.video_prefer_hw_encoder = false;
context.log_level = nertc::kNERtcLogLevelInfo;
context.log_file_max_size_KBytes = 20 * 1024;
context.event_handler = NertcNodeEventHandler::GetInstance();
UTF8String app_key, log_dir_path;
if (nim_napi_get_object_value_utf8string(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), "app_key", app_key) == napi_ok)
{
context.app_key = (const char *)app_key.get();
}
if (nim_napi_get_object_value_utf8string(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), "log_dir_path", log_dir_path) == napi_ok)
{
context.log_dir_path = (const char *)log_dir_path.get();
}
uint32_t logLevel = 3, log_file_max_size_KBytes = 20 * 1024;
if (nim_napi_get_object_value_uint32(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), "log_level", logLevel) == napi_ok)
{
context.log_level = (nertc::NERtcLogLevel)logLevel;
}
if (nim_napi_get_object_value_uint32(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), "log_file_max_size_KBytes", log_file_max_size_KBytes) == napi_ok)
{
context.log_file_max_size_KBytes = log_file_max_size_KBytes;
}
ret = instance->rtc_engine_->initialize(context);
if (ret == 0)
{
instance->rtc_engine_->queryInterface(nertc::kNERtcIIDAudioDeviceManager, (void **)&instance->_adm);
instance->rtc_engine_->queryInterface(nertc::kNERtcIIDVideoDeviceManager, (void **)&instance->_vdm);
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, release)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
do
{
CHECK_NATIVE_THIS(instance);
instance->rtc_engine_->release(true);
if (instance->rtc_engine_)
{
destroyNERtcEngine((void *&)instance->rtc_engine_);
instance->_adm = nullptr;
instance->_vdm = nullptr;
instance->rtc_engine_ = nullptr;
}
NertcNodeEventHandler::GetInstance()->RemoveAll();
NertcNodeRtcMediaStatsHandler::GetInstance()->RemoveAll();
} while (false);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setChannelProfile)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t profile;
GET_ARGS_VALUE(isolate, 0, uint32, profile)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setChannelProfile((nertc::NERtcChannelProfileType)profile);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, joinChannel)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint64_t uid;
UTF8String token, channel_name;
GET_ARGS_VALUE(isolate, 0, utf8string, token)
GET_ARGS_VALUE(isolate, 1, utf8string, channel_name)
GET_ARGS_VALUE(isolate, 2, uint64, uid)
if (status != napi_ok || channel_name.length() == 0)
{
break;
}
ret = instance->rtc_engine_->joinChannel(token.length() == 0 ? "" : token.get(), channel_name.get(), uid);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, leaveChannel)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->leaveChannel();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enableLocalAudio)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enabled;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->enableLocalAudio(enabled);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enableLocalVideo)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enabled;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->enableLocalVideo(enabled);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, subscribeRemoteVideoStream)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint64_t uid;
bool sub;
uint32_t type;
GET_ARGS_VALUE(isolate, 0, uint64, uid)
GET_ARGS_VALUE(isolate, 1, uint32, type)
GET_ARGS_VALUE(isolate, 2, bool, sub)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->subscribeRemoteVideoStream(uid, (nertc::NERtcRemoteVideoStreamType)type, sub);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setLocalVideoMirrorMode)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t mode;
GET_ARGS_VALUE(isolate, 0, uint32, mode)
if (status != napi_ok)
{
break;
}
NodeVideoFrameTransporter *pTransporter = getNodeVideoFrameTransporter();
if (pTransporter)
{
pTransporter->setLocalVideoMirrorMode(mode);
ret = 0;
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setupVideoCanvas)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint64_t uid;
bool enable;
GET_ARGS_VALUE(isolate, 0, uint64, uid)
GET_ARGS_VALUE(isolate, 1, bool, enable)
if (status != napi_ok)
{
break;
}
nertc::NERtcVideoCanvas canvas;
canvas.cb = enable ? NodeVideoFrameTransporter::onFrameDataCallback : nullptr;
canvas.user_data = enable ? (void*)(new nertc::uid_t(uid)) : nullptr;
canvas.window = nullptr;
if (uid == 0)
ret = instance->rtc_engine_->setupLocalVideoCanvas(&canvas);
else
ret = instance->rtc_engine_->setupRemoteVideoCanvas(uid, &canvas);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, onVideoFrame)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
NodeVideoFrameTransporter *pTransporter = getNodeVideoFrameTransporter();
if (pTransporter)
{
ret = pTransporter->initialize(isolate, args);
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, onEvent)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
UTF8String eventName;
GET_ARGS_VALUE(isolate, 0, utf8string, eventName)
if (status != napi_ok || eventName.length() == 0)
{
break;
}
ASSEMBLE_REG_CALLBACK(1, NertcNodeEventHandler, eventName.toUtf8String())
} while (false);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getConnectionState)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->getConnectionState();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), (int)ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, muteLocalAudioStream)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enabled;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->muteLocalAudioStream(enabled);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setAudioProfile)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t profile, scenario;
GET_ARGS_VALUE(isolate, 0, uint32, profile)
GET_ARGS_VALUE(isolate, 1, uint32, scenario)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setAudioProfile((nertc::NERtcAudioProfileType)profile, (nertc::NERtcAudioScenarioType)scenario);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, subscribeRemoteAudioStream)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint64_t uid;
bool enable;
GET_ARGS_VALUE(isolate, 0, uint64, uid)
GET_ARGS_VALUE(isolate, 1, bool, enable)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->subscribeRemoteAudioStream(uid, enable);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setVideoConfig)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcVideoConfig config = {};
status = nertc_video_config_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), config);
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setVideoConfig(config);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enableDualStreamMode)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enable;
GET_ARGS_VALUE(isolate, 0, bool, enable)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->enableDualStreamMode(enable);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startVideoPreview)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->startVideoPreview();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopVideoPreview)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->stopVideoPreview();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, muteLocalVideoStream)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enabled;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->muteLocalVideoStream(enabled);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setParameters)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
UTF8String para;
GET_ARGS_VALUE(isolate, 0, utf8string, para)
if (status != napi_ok || para.length() == 0)
{
break;
}
ret = instance->rtc_engine_->setParameters(para.get());
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setRecordingAudioFrameParameters)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcAudioFrameRequestFormat config = {};
status = nertc_audio_frame_rf_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), config);
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setRecordingAudioFrameParameters(&config);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setPlaybackAudioFrameParameters)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcAudioFrameRequestFormat config = {};
status = nertc_audio_frame_rf_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), config);
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setPlaybackAudioFrameParameters(&config);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startAudioDump)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->startAudioDump();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopAudioDump)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->stopAudioDump();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startAudioMixing)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcCreateAudioMixingOption config = {};
status = nertc_audio_mixing_option_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), config);
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->startAudioMixing(&config);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopAudioMixing)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->stopAudioMixing();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, pauseAudioMixing)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->pauseAudioMixing();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, resumeAudioMixing)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->resumeAudioMixing();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setAudioMixingSendVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t param;
GET_ARGS_VALUE(isolate, 0, uint32, param)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setAudioMixingSendVolume(param);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getAudioMixingSendVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
uint32_t volume = 0;
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->getAudioMixingSendVolume(&volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? volume : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setAudioMixingPlaybackVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t param;
GET_ARGS_VALUE(isolate, 0, uint32, param)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setAudioMixingPlaybackVolume(param);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getAudioMixingPlaybackVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
uint32_t volume = 0;
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->getAudioMixingPlaybackVolume(&volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? volume : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getAudioMixingDuration)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
uint64_t dur = 0;
int ret = 0;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->getAudioMixingDuration(&dur);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? dur : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getAudioMixingCurrentPosition)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
uint64_t volume = 0;
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->getAudioMixingCurrentPosition(&volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? volume : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setAudioMixingPosition)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint64_t param;
GET_ARGS_VALUE(isolate, 0, uint64, param)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setAudioMixingPosition(param);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, playEffect)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
auto objs = args[1]->ToObject(isolate->GetCurrentContext()).ToLocalChecked().As<Array>();
nertc::NERtcCreateAudioEffectOption *config = new nertc::NERtcCreateAudioEffectOption[objs->Length()];
status = nertc_audio_effect_option_obj_to_struct(isolate, args[1]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), config);
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->playEffect(effect_id, config);
delete[] config;
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopEffect)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->stopEffect(effect_id);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopAllEffects)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->stopAllEffects();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, pauseEffect)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->pauseEffect(effect_id);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, resumeEffect)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->resumeEffect(effect_id);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, pauseAllEffects)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->pauseAllEffects();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, resumeAllEffects)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->resumeAllEffects();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setEffectSendVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id, volume;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
GET_ARGS_VALUE(isolate, 1, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setEffectSendVolume(effect_id, volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getEffectSendVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
uint32_t volume = 0;
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->getEffectSendVolume(effect_id, &volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? volume : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setEffectPlaybackVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id, volume;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
GET_ARGS_VALUE(isolate, 1, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setEffectPlaybackVolume(effect_id, volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getEffectPlaybackVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
uint32_t ret = 0, vol = 0;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t effect_id;
GET_ARGS_VALUE(isolate, 0, uint32, effect_id)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->getEffectPlaybackVolume(effect_id, &vol);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? vol : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enableEarback)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t volume;
bool enabled;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
GET_ARGS_VALUE(isolate, 1, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->enableEarback(enabled, volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setEarbackVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t volume;
GET_ARGS_VALUE(isolate, 0, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setEarbackVolume(volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, onStatsObserver)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
do
{
CHECK_NATIVE_THIS(instance);
instance->rtc_engine_->setStatsObserver(NertcNodeRtcMediaStatsHandler::GetInstance());
auto status = napi_ok;
UTF8String eventName;
bool enable;
GET_ARGS_VALUE(isolate, 0, utf8string, eventName)
GET_ARGS_VALUE(isolate, 1, bool, enable)
if (status != napi_ok || eventName.length() == 0)
{
break;
}
if (!enable)
{
auto sz = NertcNodeRtcMediaStatsHandler::GetInstance()->RemoveEventHandler(eventName.toUtf8String());
if (sz == 0)
{
instance->rtc_engine_->setStatsObserver(nullptr);
}
}
else
{
ASSEMBLE_REG_CALLBACK(2, NertcNodeRtcMediaStatsHandler, eventName.toUtf8String())
}
} while (false);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enableAudioVolumeIndication)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint64_t interval;
bool enabled;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
GET_ARGS_VALUE(isolate, 1, uint64, interval)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->enableAudioVolumeIndication(enabled, interval);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startScreenCaptureByScreenRect)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcRectangle screen_rect = {}, region_rect = {};
nertc::NERtcScreenCaptureParameters param = {};
status = nertc_rectangle_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), screen_rect);
if (status != napi_ok) break;
status = nertc_rectangle_obj_to_struct(isolate, args[1]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), region_rect);
if (status != napi_ok) break;
status = nertc_screen_capture_params_obj_to_struct(isolate, args[2]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), param);
if (status == napi_ok)
{
ret = instance->rtc_engine_->startScreenCaptureByScreenRect(screen_rect, region_rect, param);
if (param.excluded_window_list != nullptr)
{
delete[] param.excluded_window_list;
param.excluded_window_list = nullptr;
}
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startScreenCaptureByDisplayId)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
int64_t display;
nertc::NERtcRectangle region_rect = {};
nertc::NERtcScreenCaptureParameters param = {};
GET_ARGS_VALUE(isolate, 0, int64, display)
status = nertc_rectangle_obj_to_struct(isolate, args[1]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), region_rect);
if (status != napi_ok) break;
status = nertc_screen_capture_params_obj_to_struct(isolate, args[2]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), param);
if (status == napi_ok)
{
#ifdef WIN32
RECT rc = instance->_windows_helper->getCachedRect(display);
if (rc.bottom == 0 && rc.left == 0 && rc.right == 0 && rc.top == 0)
{
WindowsHelpers::CaptureTargetInfoList list;
instance->_windows_helper->getCaptureWindowList(&list, 1);
for (auto w : list)
{
if (std::to_string(display) == w.display_id)
{
rc = w.rc;
instance->_windows_helper->updateCachedInfos(display, rc);
break;
}
}
}
if (rc.bottom != 0 || rc.left != 0 || rc.right != 0 || rc.top != 0)
{
nertc::NERtcRectangle screen_rect = {};
screen_rect.x = rc.left;
screen_rect.y = rc.top;
screen_rect.width = rc.right - rc.left;
screen_rect.height = rc.bottom - rc.top;
ret = instance->rtc_engine_->startScreenCaptureByScreenRect(screen_rect, region_rect, param);
}
else
{
ret = -100;
}
#else
ret = instance->rtc_engine_->startScreenCaptureByDisplayId(display, region_rect, param);
#endif
if (param.excluded_window_list != nullptr)
{
delete[] param.excluded_window_list;
param.excluded_window_list = nullptr;
}
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startScreenCaptureByWindowId)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
int32_t windowid;
nertc::NERtcRectangle region_rect = {};
nertc::NERtcScreenCaptureParameters param = {};
GET_ARGS_VALUE(isolate, 0, int32, windowid)
status = nertc_rectangle_obj_to_struct(isolate, args[1]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), region_rect);
if (status != napi_ok) break;
status = nertc_screen_capture_params_obj_to_struct(isolate, args[2]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), param);
if (status == napi_ok)
{
#ifdef WIN32
ret = instance->rtc_engine_->startScreenCaptureByWindowId(reinterpret_cast<void *>(windowid), region_rect, param);
#else
ret = instance->rtc_engine_->startScreenCaptureByWindowId(reinterpret_cast<void *>(&windowid), region_rect, param);
#endif
if (param.excluded_window_list != nullptr)
{
delete[] param.excluded_window_list;
param.excluded_window_list = nullptr;
}
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, updateScreenCaptureRegion)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcRectangle region_rect = {};
status = nertc_rectangle_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), region_rect);
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->updateScreenCaptureRegion(region_rect);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopScreenCapture)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->stopScreenCapture();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, pauseScreenCapture)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->pauseScreenCapture();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, resumeScreenCapture)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->resumeScreenCapture();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setExternalVideoSource)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enabled;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setExternalVideoSource(enabled);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, pushExternalVideoFrame)
{
//TODO(litianyi)
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getVersion)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
std::string ret;
do
{
CHECK_NATIVE_THIS(instance);
int32_t build;
ret = (std::string)instance->rtc_engine_->getVersion(&build);
} while (false);
args.GetReturnValue().Set(String::NewFromUtf8(args.GetIsolate(), ret.c_str(), NewStringType::kNormal).ToLocalChecked());
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getErrorDescription)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
std::string ret;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
int32_t error;
GET_ARGS_VALUE(isolate, 0, int32, error)
ret = (std::string)instance->rtc_engine_->getErrorDescription(error);
} while (false);
args.GetReturnValue().Set(String::NewFromUtf8(args.GetIsolate(), ret.c_str(), NewStringType::kNormal).ToLocalChecked());
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, uploadSdkInfo)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
do
{
CHECK_NATIVE_THIS(instance);
instance->rtc_engine_->uploadSdkInfo();
} while (false);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, addLiveStreamTask)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcLiveStreamTaskInfo info = {0};
status = nertc_ls_task_info_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), info);
if (status == napi_ok)
{
memset(info.extraInfo, 0, kNERtcMacSEIBufferLength);
// info.config = {0};
ret = instance->rtc_engine_->addLiveStreamTask(info);
if (info.layout.users)
{
delete[] info.layout.users;
info.layout.users = nullptr;
};
if (info.layout.bg_image)
{
delete info.layout.bg_image;
info.layout.bg_image = nullptr;
}
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, updateLiveStreamTask)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
nertc::NERtcLiveStreamTaskInfo info = {};
status = nertc_ls_task_info_obj_to_struct(isolate, args[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked(), info);
if (status == napi_ok)
{
ret = instance->rtc_engine_->updateLiveStreamTask(info);
if (info.layout.users)
{
delete[] info.layout.users;
info.layout.users = nullptr;
};
if (info.layout.bg_image)
{
delete info.layout.bg_image;
info.layout.bg_image = nullptr;
}
}
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, removeLiveStreamTask)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
UTF8String task_id;
GET_ARGS_VALUE(isolate, 0, utf8string, task_id)
if (status != napi_ok || task_id.length() == 0)
{
break;
}
ret = instance->rtc_engine_->removeLiveStreamTask(task_id.get());
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enumerateRecordDevices)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
Local<Array> arr = Array::New(isolate);;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto devices = instance->_adm->enumerateRecordDevices();
if (devices != nullptr)
{
size_t count = devices->getCount();
for (size_t i = 0; i < count; i++)
{
nertc::NERtcDeviceInfo info;
Local<Object> obj = Object::New(isolate);;
if (devices->getDeviceInfo(i, &info) == 0)
{
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "device_id"), nim_napi_new_utf8string(isolate, (char *)info.device_id));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "device_name"), nim_napi_new_utf8string(isolate, (char *)info.device_name));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "transport_type"), nim_napi_new_uint32(isolate, info.transport_type));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "suspected_unavailable"), nim_napi_new_bool(isolate, info.suspected_unavailable));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "system_default_device"), nim_napi_new_bool(isolate, info.system_default_device));
arr->Set(isolate->GetCurrentContext(), i, obj);
}
}
devices->destroy();
}
} while (false);
args.GetReturnValue().Set(arr);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setRecordDevice)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
UTF8String device;
GET_ARGS_VALUE(isolate, 0, utf8string, device)
if (status != napi_ok || device.length() == 0)
{
break;
}
ret = instance->_adm->setRecordDevice(device.get());
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getRecordDevice)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
char id[256]; int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
ret = instance->_adm->getRecordDevice(id);
} while (false);
args.GetReturnValue().Set(String::NewFromUtf8(args.GetIsolate(), ret== 0 ? (char*)id : "", NewStringType::kNormal).ToLocalChecked());
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enumeratePlayoutDevices)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
Local<Array> arr = Array::New(isolate);
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto devices = instance->_adm->enumeratePlayoutDevices();
if (devices != nullptr)
{
size_t count = devices->getCount();
for (size_t i = 0; i < count; i++)
{
nertc::NERtcDeviceInfo info;
Local<Object> obj = Object::New(isolate);;
if (devices->getDeviceInfo(i, &info) == 0)
{
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "device_id"), nim_napi_new_utf8string(isolate, (char *)info.device_id));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "device_name"), nim_napi_new_utf8string(isolate, (char *)info.device_name));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "transport_type"), nim_napi_new_uint32(isolate, info.transport_type));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "suspected_unavailable"), nim_napi_new_bool(isolate, info.suspected_unavailable));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "system_default_device"), nim_napi_new_bool(isolate, info.system_default_device));
arr->Set(isolate->GetCurrentContext(), i, obj);
}
}
devices->destroy();
}
} while (false);
args.GetReturnValue().Set(arr);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setPlayoutDevice)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
UTF8String device;
GET_ARGS_VALUE(isolate, 0, utf8string, device)
if (status != napi_ok || device.length() == 0)
{
break;
}
ret = instance->_adm->setPlayoutDevice(device.get());
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getPlayoutDevice)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
char id[256]; int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
ret = instance->_adm->getPlayoutDevice(id);
} while (false);
args.GetReturnValue().Set(String::NewFromUtf8(args.GetIsolate(), ret== 0 ? (char*)id : "", NewStringType::kNormal).ToLocalChecked());
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setRecordDeviceVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
uint32_t volume;
GET_ARGS_VALUE(isolate, 0, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->setRecordDeviceVolume(volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getRecordDeviceVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
uint32_t volume = 0;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
ret = instance->_adm->getRecordDeviceVolume(&volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? volume : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setPlayoutDeviceVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
uint32_t volume;
GET_ARGS_VALUE(isolate, 0, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->setPlayoutDeviceVolume(volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getPlayoutDeviceVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
uint32_t volume = 0;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
ret = instance->_adm->getPlayoutDeviceVolume(&volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret == 0 ? volume : ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setPlayoutDeviceMute)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
bool mute;
GET_ARGS_VALUE(isolate, 0, bool, mute)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->setPlayoutDeviceMute(mute);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getPlayoutDeviceMute)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
bool ret = false;
do
{
CHECK_NATIVE_ADM_THIS(instance);
instance->_adm->getPlayoutDeviceMute(&ret);
} while (false);
args.GetReturnValue().Set(Boolean::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setRecordDeviceMute)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
bool mute;
GET_ARGS_VALUE(isolate, 0, bool, mute)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->setRecordDeviceMute(mute);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getRecordDeviceMute)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
bool ret = false;
do
{
CHECK_NATIVE_ADM_THIS(instance);
instance->_adm->getRecordDeviceMute(&ret);
} while (false);
args.GetReturnValue().Set(Boolean::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, adjustRecordingSignalVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
uint32_t volume;
GET_ARGS_VALUE(isolate, 0, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->adjustRecordingSignalVolume(volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, adjustPlaybackSignalVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
uint32_t volume;
GET_ARGS_VALUE(isolate, 0, uint32, volume)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->adjustPlaybackSignalVolume(volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startRecordDeviceTest)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
uint64_t interval;
GET_ARGS_VALUE(isolate, 0, uint64, interval)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->startRecordDeviceTest(interval);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopRecordDeviceTest)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
ret = instance->_adm->stopRecordDeviceTest();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startPlayoutDeviceTest)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
UTF8String path;
GET_ARGS_VALUE(isolate, 0, utf8string, path)
if (status != napi_ok || path.length() == 0)
{
break;
}
ret = instance->_adm->startPlayoutDeviceTest(path.get());
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopPlayoutDeviceTest)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
ret = instance->_adm->stopPlayoutDeviceTest();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startAudioDeviceLoopbackTest)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
uint64_t interval;
GET_ARGS_VALUE(isolate, 0, uint64, interval)
if (status != napi_ok)
{
break;
}
ret = instance->_adm->startAudioDeviceLoopbackTest(interval);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopAudioDeviceLoopbackTest)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
ret = instance->_adm->stopAudioDeviceLoopbackTest();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enumerateCaptureDevices)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
Local<Array> arr = Array::New(isolate);
do
{
CHECK_NATIVE_VDM_THIS(instance);
auto devices = instance->_vdm->enumerateCaptureDevices();
if (devices != nullptr)
{
size_t count = devices->getCount();
for (size_t i = 0; i < count; i++)
{
nertc::NERtcDeviceInfo info;
if (devices->getDeviceInfo(i, &info) == 0)
{
Local<Object> obj = Object::New(isolate);
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "device_id"), nim_napi_new_utf8string(isolate, (const char*)info.device_id));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "device_name"), nim_napi_new_utf8string(isolate, (const char*)info.device_name));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "transport_type"), nim_napi_new_uint32(isolate, info.transport_type));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "suspected_unavailable"), nim_napi_new_bool(isolate, info.suspected_unavailable));
obj->Set(isolate->GetCurrentContext(), nim_napi_new_utf8string(isolate, "system_default_device"), nim_napi_new_bool(isolate, info.system_default_device));
arr->Set(isolate->GetCurrentContext(), i, obj);
}
}
devices->destroy();
}
} while (false);
args.GetReturnValue().Set(arr);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setDevice)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_VDM_THIS(instance);
auto status = napi_ok;
UTF8String device;
GET_ARGS_VALUE(isolate, 0, utf8string, device)
if (status != napi_ok || device.length() == 0)
{
break;
}
ret = instance->_vdm->setDevice(device.get());
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, getDevice)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
char id[256]; int ret = -1;
do
{
CHECK_NATIVE_VDM_THIS(instance);
ret = instance->_vdm->getDevice(id);
} while (false);
args.GetReturnValue().Set(String::NewFromUtf8(args.GetIsolate(), ret== 0 ? (char*)id : "", NewStringType::kNormal).ToLocalChecked());
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setClientRole)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t role;
GET_ARGS_VALUE(isolate, 0, uint32, role)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setClientRole((nertc::NERtcClientRole)role);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setupSubStreamVideoCanvas)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint64_t uid;
bool enable;
GET_ARGS_VALUE(isolate, 0, uint64, uid)
GET_ARGS_VALUE(isolate, 1, bool, enable)
if (status != napi_ok)
{
break;
}
nertc::NERtcVideoCanvas canvas;
canvas.cb = enable ? NodeVideoFrameTransporter::onSubstreamFrameDataCallback : nullptr;
canvas.user_data = enable ? (void*)(new nertc::uid_t(uid)) : nullptr;
canvas.window = nullptr;
if (uid == 0)
ret = instance->rtc_engine_->setupLocalSubStreamVideoCanvas(&canvas);
else
ret = instance->rtc_engine_->setupRemoteSubStreamVideoCanvas(uid, &canvas);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, subscribeRemoteVideoSubStream)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_VDM_THIS(instance);
auto status = napi_ok;
bool sub;
nertc::uid_t uid;
GET_ARGS_VALUE(isolate, 0, uint64, uid)
GET_ARGS_VALUE(isolate, 1, bool, sub)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->subscribeRemoteVideoSubStream(uid, sub);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setMixedAudioFrameParameters)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_VDM_THIS(instance);
auto status = napi_ok;
int samp;
GET_ARGS_VALUE(isolate, 0, int32, samp)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setMixedAudioFrameParameters(samp);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setExternalAudioSource)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_VDM_THIS(instance);
auto status = napi_ok;
bool enabled;
int samp, chan;
GET_ARGS_VALUE(isolate, 0, bool, enabled)
GET_ARGS_VALUE(isolate, 1, int32, samp)
GET_ARGS_VALUE(isolate, 2, int32, chan)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setExternalAudioSource(enabled, samp, chan);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, pushExternalAudioFrame)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_VDM_THIS(instance);
// TODO(litianyi)
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, sendSEIMsg)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
if (!args[0]->IsArrayBuffer())
break;
auto buffer = args[0].As<ArrayBuffer>();
ret = instance->rtc_engine_->sendSEIMsg(
static_cast<const char*>(buffer->GetContents().Data()),
buffer->GetContents().ByteLength());
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, sendSEIMsgEx)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
if (!args[0]->IsArrayBuffer())
break;
auto buffer = args[0].As<ArrayBuffer>();
int32_t type;
GET_ARGS_VALUE(isolate, 1, int32, type)
ret = instance->rtc_engine_->sendSEIMsg(
static_cast<const char*>(buffer->GetContents().Data()),
buffer->GetContents().ByteLength(),
static_cast<nertc::NERtcStreamChannelType>(type));
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setExternalAudioRender)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enable;
int sample_rate = 0;
int channels = 0;
GET_ARGS_VALUE(isolate, 0, bool, enable)
GET_ARGS_VALUE(isolate, 1, int32, sample_rate)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 2, int32, channels)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->setExternalAudioRender(enable, sample_rate, channels);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, pullExternalAudioFrame)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
int length = 0;
GET_ARGS_VALUE(isolate, 0, int32, length)
if (status != napi_ok)
break;
ASSEMBLE_BASE_CALLBACK(1);
auto shared_data = std::make_shared<unsigned char>(length);
ret = instance->rtc_engine_->pullExternalAudioFrame(shared_data.get(), length);
NertcNodeEventHandler::GetInstance()->onPullExternalAudioFrame(bcb, shared_data, length);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setAudioEffectPreset)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
int32_t type;
GET_ARGS_VALUE(isolate, 0, int32, type)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setAudioEffectPreset(static_cast<nertc::NERtcVoiceChangerType>(type));
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setVoiceBeautifierPreset)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
int32_t type;
GET_ARGS_VALUE(isolate, 0, int32, type)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setVoiceBeautifierPreset(static_cast<nertc::NERtcVoiceBeautifierType>(type));
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setLocalVoicePitch)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
double pitch;
GET_ARGS_VALUE(isolate, 0, double, pitch)
if (status != napi_ok)
{
break;
}
ret = instance->rtc_engine_->setLocalVoicePitch(pitch);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setLocalVoiceEqualization)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
int32_t band_frequency;
int32_t band_gain;
GET_ARGS_VALUE(isolate, 0, int32, band_frequency)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 1, int32, band_gain)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->setLocalVoiceEqualization(
static_cast<nertc::NERtcVoiceEqualizationBand>(band_frequency),
band_gain);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setRemoteHighPriorityAudioStream)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enable = false;
uint64_t uid = 0;
int32_t stream_type;
GET_ARGS_VALUE(isolate, 0, bool, enable)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 1, uint64, uid)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 2, int32, stream_type)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->setRemoteHighPriorityAudioStream(enable, uid,
static_cast<nertc::NERtcAudioStreamType>(stream_type));
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, subscribeRemoteAudioSubStream)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_ADM_THIS(instance);
auto status = napi_ok;
uint64_t uid = 0;
bool subscribe = false;
GET_ARGS_VALUE(isolate, 0, uint64, uid)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 1, bool, subscribe)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->subscribeRemoteAudioSubStream(uid, subscribe);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enableLocalAudioStream)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enable = false;
int32_t stream_type;
GET_ARGS_VALUE(isolate, 0, bool, enable)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 1, int32, stream_type)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->enableLocalAudioStream(enable, static_cast<nertc::NERtcAudioStreamType>(stream_type));
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enableLoopbackRecording)
{
CHECK_API_FUNC(NertcNodeEngine, 2)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enable = false;
UTF8String device_name;
GET_ARGS_VALUE(isolate, 0, bool, enable)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 1, utf8string, device_name)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->enableLoopbackRecording(enable,
device_name.length() > 0 ? device_name.toUtf8String().c_str() : nullptr
);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, adjustLoopbackRecordingSignalVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
uint32_t volume = 0;
GET_ARGS_VALUE(isolate, 0, uint32, volume)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->adjustLoopbackRecordingSignalVolume(volume);
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, adjustUserPlaybackSignalVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 3)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
bool enable = false;
uint32_t volume = 0;
uint64_t uid = 0;
int32_t stream_type;
GET_ARGS_VALUE(isolate, 0, uint64, uid)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 1, uint32, volume)
if (status != napi_ok)
break;
GET_ARGS_VALUE(isolate, 2, int32, stream_type)
if (status != napi_ok)
break;
ret = instance->rtc_engine_->adjustUserPlaybackSignalVolume(uid, volume,
static_cast<nertc::NERtcAudioStreamType>(stream_type));
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, checkNECastAudioDriver)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
ret = instance->rtc_engine_->checkNECastAudioDriver();
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, enumerateScreenCaptureSourceInfo)
{
CHECK_API_FUNC(NertcNodeEngine, 4)
Local<Array> arr = Array::New(isolate);
#ifdef WIN32
do
{
CHECK_NATIVE_THIS(instance);
auto status = napi_ok;
int thumbWidth, thumbHeight, iconWidth, iconHeight;
GET_ARGS_VALUE(isolate, 0, int32, thumbWidth)
GET_ARGS_VALUE(isolate, 1, int32, thumbHeight)
GET_ARGS_VALUE(isolate, 2, int32, iconWidth)
GET_ARGS_VALUE(isolate, 3, int32, iconHeight)
if (status != napi_ok)
{
break;
}
WindowsHelpers::CaptureTargetInfoList list;
instance->_windows_helper->getCaptureWindowList(&list);
uint32_t i = 0;
bool captureScreenRet = instance->screen_capture_helper_->InitScreen();
if (captureScreenRet)
{
uint32_t vx = GetSystemMetrics(SM_XVIRTUALSCREEN);
uint32_t vy = GetSystemMetrics(SM_YVIRTUALSCREEN);
for (auto w : list)
{
if (w.type != 1)
continue;
Local<Object> obj = Object::New(isolate);
int32_t sid = reinterpret_cast<int32_t>(w.id);
nim_napi_set_object_value_int32(isolate, obj, "sourceId", sid);
nim_napi_set_object_value_utf8string(isolate, obj, "sourceName", UTF16ToUTF8(w.title));
nim_napi_set_object_value_int32(isolate, obj, "type", w.type);
nim_napi_set_object_value_int32(isolate, obj, "left", w.rc.left);
nim_napi_set_object_value_int32(isolate, obj, "top", w.rc.top);
nim_napi_set_object_value_int32(isolate, obj, "right", w.rc.right);
nim_napi_set_object_value_int32(isolate, obj, "bottom", w.rc.bottom);
nim_napi_set_object_value_utf8string(isolate, obj, "displayId", w.display_id);
instance->_windows_helper->updateCachedInfos(sid, w.rc);
int left = w.rc.left - vx;
int top = w.rc.top - vy;
int sWidth = w.rc.right - w.rc.left;
int sHeight = w.rc.bottom - w.rc.top;
if (instance->screen_capture_helper_->CaptureScreenRect(left, top, sWidth, sHeight, thumbWidth, thumbHeight))
{
int size = GetRGBASize(thumbWidth, thumbHeight);
uint8_t *data = RGBAToBGRA(instance->screen_capture_helper_->GetData(), size);
Local<v8::Object> thumb = Object::New(isolate);
nim_napi_set_object_value_int32(isolate, thumb, "length", size);
nim_napi_set_object_value_int32(isolate, thumb, "width", thumbWidth);
nim_napi_set_object_value_int32(isolate, thumb, "height", thumbHeight);
Local<v8::ArrayBuffer> buff = v8::ArrayBuffer::New(isolate, data, size);
Local<v8::Uint8Array> dataarray = v8::Uint8Array::New(buff, 0, size);
Local<Value> propName = String::NewFromUtf8(isolate, "buffer", NewStringType::kInternalized).ToLocalChecked();
thumb->Set(isolate->GetCurrentContext(), propName, dataarray);
Local<Value> thumbKey = String::NewFromUtf8(isolate, "thumbBGRA", NewStringType::kInternalized).ToLocalChecked();
obj->Set(isolate->GetCurrentContext(), thumbKey, thumb);
}
arr->Set(isolate->GetCurrentContext(), i++, obj);
}
instance->screen_capture_helper_->UnintScreen();
}
for (auto w : list)
{
if (w.type != 2) continue;
Local<Object> obj = Object::New(isolate);
nim_napi_set_object_value_int32(isolate, obj, "sourceId", reinterpret_cast<int32_t>(w.id));
nim_napi_set_object_value_utf8string(isolate, obj, "sourceName", UTF16ToUTF8(w.title));
nim_napi_set_object_value_int32(isolate, obj, "type", w.type);
nim_napi_set_object_value_bool(isolate, obj, "isMinimizeWindow", w.isMinimizeWindow);
if (!w.isMinimizeWindow)
{
if (instance->window_capture_helper_->CaptureWindow(w.id) && instance->window_capture_helper_->Zoom(thumbWidth, thumbHeight))
{
int size = GetRGBASize(thumbWidth, thumbHeight);
uint8_t *data = RGBAToBGRA(instance->window_capture_helper_->GetData(), size);
Local<v8::Object> thumb = Object::New(isolate);
nim_napi_set_object_value_int32(isolate, thumb, "length", size);
nim_napi_set_object_value_int32(isolate, thumb, "width", thumbWidth);
nim_napi_set_object_value_int32(isolate, thumb, "height", thumbHeight);
Local<v8::ArrayBuffer> buff = v8::ArrayBuffer::New(isolate, data, size);
Local<v8::Uint8Array> dataarray = v8::Uint8Array::New(buff, 0, size);
Local<Value> propName = String::NewFromUtf8(isolate, "buffer", NewStringType::kInternalized).ToLocalChecked();
thumb->Set(isolate->GetCurrentContext(), propName, dataarray);
Local<Value> thumbKey = String::NewFromUtf8(isolate, "thumbBGRA", NewStringType::kInternalized).ToLocalChecked();
obj->Set(isolate->GetCurrentContext(), thumbKey, thumb);
} else {
int iconSize = 0;
uint8_t *rgba = GetWindowsIconRGBA(w.id, &thumbWidth, &thumbHeight, &iconSize);
if (rgba != NULL)
{
uint8_t *data = RGBAToBGRA((void *)rgba, iconSize);
free(rgba);
rgba = nullptr;
Local<v8::Object> icon = Object::New(isolate);
nim_napi_set_object_value_int32(isolate, icon, "length", iconSize);
nim_napi_set_object_value_int32(isolate, icon, "width", thumbWidth);
nim_napi_set_object_value_int32(isolate, icon, "height", thumbHeight);
Local<v8::ArrayBuffer> buff = v8::ArrayBuffer::New(isolate, data, iconSize);
Local<v8::Uint8Array> dataarray = v8::Uint8Array::New(buff, 0, iconSize);
Local<Value> propName = String::NewFromUtf8(isolate, "buffer", NewStringType::kInternalized).ToLocalChecked();
icon->Set(isolate->GetCurrentContext(), propName, dataarray);
Local<Value> thumbKey = String::NewFromUtf8(isolate, "thumbBGRA", NewStringType::kInternalized).ToLocalChecked();
obj->Set(isolate->GetCurrentContext(), thumbKey, icon);
}
}
}
int iconSize = 0;
uint8_t *rgba = GetWindowsIconRGBA(w.id, &iconWidth, &iconHeight, &iconSize);
if (rgba != NULL)
{
uint8_t *data = RGBAToBGRA((void *)rgba, iconSize);
free(rgba);
rgba = nullptr;
Local<v8::Object> icon = Object::New(isolate);
nim_napi_set_object_value_int32(isolate, icon, "length", iconSize);
nim_napi_set_object_value_int32(isolate, icon, "width", iconWidth);
nim_napi_set_object_value_int32(isolate, icon, "height", iconHeight);
Local<v8::ArrayBuffer> buff = v8::ArrayBuffer::New(isolate, data, iconSize);
Local<v8::Uint8Array> dataarray = v8::Uint8Array::New(buff, 0, iconSize);
Local<Value> propName = String::NewFromUtf8(isolate, "buffer", NewStringType::kInternalized).ToLocalChecked();
icon->Set(isolate->GetCurrentContext(), propName, dataarray);
Local<Value> thumbKey = String::NewFromUtf8(isolate, "iconBGRA", NewStringType::kInternalized).ToLocalChecked();
obj->Set(isolate->GetCurrentContext(), thumbKey, icon);
}
arr->Set(isolate->GetCurrentContext(), i++, obj);
}
instance->window_capture_helper_->Cleanup();
} while (false);
#endif
args.GetReturnValue().Set(arr);
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, startSystemAudioLoopbackCapture)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
#ifdef WIN32
// ret = instance->rtc_engine_->startSystemAudioLoopbackCapture();
#endif
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, stopSystemAudioLoopbackCapture)
{
CHECK_API_FUNC(NertcNodeEngine, 0)
int ret = -1;
do
{
CHECK_NATIVE_THIS(instance);
#ifdef WIN32
// ret = instance->rtc_engine_->stopSystemAudioLoopbackCapture();
#endif
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
NIM_SDK_NODE_API_DEF(NertcNodeEngine, setSystemAudioLoopbackCaptureVolume)
{
CHECK_API_FUNC(NertcNodeEngine, 1)
int ret = -1;
do
{
auto status = napi_ok;
uint32_t vol;
GET_ARGS_VALUE(isolate, 0, uint32, vol)
if (status != napi_ok)
{
break;
}
#ifdef WIN32
// ret = instance->rtc_engine_->setSystemAudioLoopbackCaptureVolume(vol);
#endif
} while (false);
args.GetReturnValue().Set(Integer::New(args.GetIsolate(), ret));
}
} | 32.664032 | 185 | 0.637379 | [
"object"
] |
eefe0394984d82457ef0dce769d579f276d961a9 | 6,119 | cc | C++ | content/browser/device_monitor_mac.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | 2 | 2020-06-10T07:15:26.000Z | 2020-12-13T19:44:12.000Z | content/browser/device_monitor_mac.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | content/browser/device_monitor_mac.cc | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/device_monitor_mac.h"
#include <IOKit/audio/IOAudioDefines.h>
#include <IOKit/usb/IOUSBLib.h>
#include "base/logging.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/mac/scoped_ioobject.h"
namespace content {
namespace {
const io_name_t kServices[] = {
kIOFirstPublishNotification,
kIOTerminatedNotification,
};
CFMutableDictionaryRef CreateMatchingDictionaryForUSBDevices(
SInt32 interface_class_code, SInt32 interface_subclass_code) {
CFMutableDictionaryRef matching_dictionary =
IOServiceMatching(kIOUSBInterfaceClassName);
base::mac::ScopedCFTypeRef<CFNumberRef> number_ref(CFNumberCreate(
kCFAllocatorDefault, kCFNumberSInt32Type, &interface_class_code));
DCHECK(number_ref);
CFDictionaryAddValue(matching_dictionary, CFSTR(kUSBInterfaceClass),
number_ref);
number_ref.reset(CFNumberCreate(kCFAllocatorDefault,
kCFNumberSInt32Type,
&interface_subclass_code));
DCHECK(number_ref);
CFDictionaryAddValue(matching_dictionary, CFSTR(kUSBInterfaceSubClass),
number_ref);
return matching_dictionary;
}
void RegisterCallbackToIOService(IONotificationPortRef port,
const io_name_t type,
CFMutableDictionaryRef dictionary,
IOServiceMatchingCallback callback,
void* context,
io_iterator_t* service) {
kern_return_t err = IOServiceAddMatchingNotification(port,
type,
dictionary,
callback,
context,
service);
if (err) {
NOTREACHED() << "Failed to register the IO matched notification for type "
<< type;
return;
}
DCHECK(*service);
// Iterate over set of matching devices to access already-present devices
// and to arm the notification.
for (base::mac::ScopedIOObject<io_service_t> object(IOIteratorNext(*service));
object;
object.reset(IOIteratorNext(*service))) {};
}
} // namespace
DeviceMonitorMac::DeviceMonitorMac() {
// Add the notification port to the run loop.
notification_port_ = IONotificationPortCreate(kIOMasterPortDefault);
DCHECK(notification_port_);
RegisterAudioServices();
RegisterVideoServices();
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notification_port_),
kCFRunLoopCommonModes);
}
DeviceMonitorMac::~DeviceMonitorMac() {
// Stop the notifications and free the objects.
for (size_t i = 0; i < notification_iterators_.size(); ++i) {
IOObjectRelease(*notification_iterators_[i]);
}
notification_iterators_.clear();
// Remove the notification port from the message runloop.
CFRunLoopRemoveSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notification_port_),
kCFRunLoopCommonModes);
// Destroy the notification port allocated by IONotificationPortCreate.
IONotificationPortDestroy(notification_port_);
}
void DeviceMonitorMac::RegisterAudioServices() {
CFMutableDictionaryRef dictionary =
IOServiceMatching(kIOAudioDeviceClassName);
RegisterServices(dictionary, &AudioDeviceCallback);
}
void DeviceMonitorMac::RegisterVideoServices() {
CFMutableDictionaryRef dictionary = CreateMatchingDictionaryForUSBDevices(
kUSBVideoInterfaceClass, kUSBVideoControlSubClass);
RegisterServices(dictionary, &VideoDeviceCallback);
}
void DeviceMonitorMac::RegisterServices(CFMutableDictionaryRef dictionary,
IOServiceMatchingCallback callback) {
// Add callback to the service.
for (size_t i = 0; i < arraysize(kServices); ++i) {
// |dictionary| comes in with a reference count as 1. Since each call to
// IOServiceAddMatchingNotification consumes one reference, we need to
// retain |arraysize(kServices) -1| additional dictionary references.
if (i < (arraysize(kServices) - 1))
CFRetain(dictionary);
// Register callback to each service.
io_iterator_t service;
RegisterCallbackToIOService(notification_port_,
kServices[i],
dictionary,
callback,
this,
&service);
// Store the pointer of the object to release the memory when shutting
// down the services.
notification_iterators_.push_back(&service);
}
}
void DeviceMonitorMac::AudioDeviceCallback(void *context,
io_iterator_t iterator) {
for (base::mac::ScopedIOObject<io_service_t> object(IOIteratorNext(iterator));
object;
object.reset(IOIteratorNext(iterator))) {
if (context) {
reinterpret_cast<DeviceMonitorMac*>(context)->NotifyDeviceChanged(
base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE);
}
}
}
void DeviceMonitorMac::VideoDeviceCallback(void *context,
io_iterator_t iterator) {
for (base::mac::ScopedIOObject<io_service_t> object(IOIteratorNext(iterator));
object;
object.reset(IOIteratorNext(iterator))) {
if (context) {
reinterpret_cast<DeviceMonitorMac*>(context)->NotifyDeviceChanged(
base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE);
}
}
}
void DeviceMonitorMac::NotifyDeviceChanged(
base::SystemMonitor::DeviceType type) {
// TODO(xians): Remove the global variable for SystemMonitor.
base::SystemMonitor::Get()->ProcessDevicesChanged(type);
}
} // namespace content
| 36.422619 | 80 | 0.652067 | [
"object"
] |
e101ef90c7f8c7731baaf8c6d77e2868659a7d9c | 14,048 | cpp | C++ | src/zpm_cart.cpp | mlpeck/zernike | 553a956417c34847b80a179a3f6922d71120061d | [
"MIT"
] | 4 | 2019-05-15T09:28:48.000Z | 2021-06-16T17:28:29.000Z | src/zpm_cart.cpp | mlpeck/zernike | 553a956417c34847b80a179a3f6922d71120061d | [
"MIT"
] | null | null | null | src/zpm_cart.cpp | mlpeck/zernike | 553a956417c34847b80a179a3f6922d71120061d | [
"MIT"
] | 1 | 2019-01-17T13:30:49.000Z | 2019-01-17T13:30:49.000Z | //
// Copyright (C) 2021 Michael Peck <mpeck1 -at- ix.netcom.com>
//
// License: MIT <https://opensource.org/licenses/MIT>
//
// [[Rcpp::depends(RcppArmadillo)]]
# include <RcppArmadillo.h>
# include <Rcpp.h>
using namespace Rcpp;
using namespace arma;
/*****************
*
* Convert a matrix of Zernike polynomial values
* from unit scaled to unit variance (orthonormal scaling).
* Columns must be in ISO/ANSI sequence.
* Only check performed is on number of columns.
*
*****************/
//' Normalize matrix of Zernike polynomial values.
//'
//' Convert a matrix of Zernike polynomial values from
//' unit scaled to unit variance aka orthonormal form.
//'
//' @param uzpm matrix of Zernike polynomial values
//' @param maxorder the maximum radial order.
//'
//' @return matrix in orthonormal form.
//'
//' @details
//' This is intended only for ISO/ANSI ordered matrices. The
//' only check performed is that the number of columns in the
//' matrix matches the expected number given by the argument
//' `maxorder`.
//' This is called by [gradzpm_cart()] and [zpm_cart()]
//' if `unit_variance` is set to `true` in the respective
//' function calls.
//' @md
// [[Rcpp::export]]
NumericMatrix norm_zpm(NumericMatrix& uzpm, const int& maxorder = 12) {
int ncol = uzpm.cols();
int n, m, mp, j=0;
double zmult;
if (ncol != (maxorder+1)*(maxorder+2)/2) stop("Matrix is wrong size for entered order");
for (n=0; n<=maxorder; n++) {
for (m=0; m<=n; m++) {
mp = n - 2*m;
zmult = std::sqrt(n+1.0);
if (mp != 0) {
zmult *= sqrt(2.0);
}
uzpm(_, j) = zmult * uzpm(_, j);
++j;
}
}
return uzpm;
}
/********************
Fill matrixes with:
unit scaled Zernikes in cartesian coordinates
x and y directional derivatives
Note: This returns ZP values in ISO?ANSI ordering with sine terms on
the "left" side of the pyramid.
Source:
Anderson, T.B. (2018) Optics Express 26, #5, 18878
URL: https://doi.org/10.1364/OE.26.018878 (open access)
********************/
//' Zernike polynomials and cartesian gradients
//'
//' Calculate Zernike polynomial values and Cartesian gradients in
//' ISO/ANSI sequence for a set of Cartesian coordinates.
//'
//' @param x a vector of x coordinates for points on a unit disk.
//' @param y a vector of y coordinates.
//' @param maxorder the maximum radial polynomial order (defaults to 12).
//' @param unit_variance logical: return with orthonormal scaling? (default `false`)
//' @param return_zpm logical: return Zernike polynomial matrix? (default `true`)
//'
//' @return a named list with the matrices `zm` (optional but returned by default), `dzdx`, `dzdy`.
//'
//' @references
//' Anderson, T.B. (2018) Optics Express 26, #5, 18878
//' <https://doi.org/10.1364/OE.26.018878> (open access)
//'
//' @details
//' Uses the recurrence relations in the above publication to calculate Zernike
//' polynomial values and their directional derivatives in Cartesian coordinates. These are
//' known to be both efficient and numerically stable.
//'
//' Columns are in ISO/ANSI sequence: for each radial order n >= 0 the azimuthal orders m are sequenced
//' m = {-n, -(n-2), ..., (n-2), n}, with sine components for negative m and cosine for positive m. Note this
//' is the opposite ordering from the extended Fringe set and the ordering of aberrations is quite different.
//' For example the two components of trefoil are in the 7th and 10th column while coma is in
//' columns 8 and 9 (or 7 and 8 with 0-indexing). Note also that except for tilt and coma-like aberrations
//' (m=1) non-axisymmetric aberrations will be separated.
//'
//' All three matrices will have the same dimensions on return. Columns 0 and 1 of `dzdx` will be all 0,
//' while columns 0 and 2 of `dzdy` are 0.
//'
//' @seealso [zpm()] uses the same recurrence relations for polar coordinates and extended
//' Fringe set ordering, which is the more common indexing scheme for optical design/testing
//' software.
//' @seealso [zpm_cart()] calculates and returns the Zernike polynomial values only.
//'
//' @examples
//' rho <- seq(0.2, 1., length=5)
//' theta <- seq(0, 1.6*pi, length=5)
//' rt <- expand.grid(theta, rho)
//' x <- c(0, rt[,2]*cos(rt[,1]))
//' y <- c(0, rt[,2]*sin(rt[,1]))
//' gzpm <- gradzpm_cart(x, y)
//'
//' @md
// [[Rcpp::export]]
List gradzpm_cart(const NumericVector& x, const NumericVector& y, const int& maxorder = 12,
const bool& unit_variance = false, const bool& return_zpm = true) {
int n, m;
int ncol = (maxorder+1)*(maxorder+2)/2;
unsigned int nrow = x.size();
int j;
bool n_even;
NumericMatrix zm(nrow, ncol), dzdx(nrow, ncol), dzdy(nrow, ncol);
//do some rudimentary error checking
if (x.size() != y.size()) stop("Numeric vectors must be same length");
if (maxorder < 1) stop("maxorder must be >= 1");
// good enough
// starting values for recursions
zm(_, 0) = rep(1.0, nrow);
zm(_, 1) = y;
zm(_, 2) = x;
dzdx(_, 0) = rep(0.0, nrow);
dzdx(_, 1) = rep(0.0, nrow);
dzdx(_, 2) = rep(1.0, nrow);
dzdy(_, 0) = rep(0.0, nrow);
dzdy(_, 1) = rep(1.0, nrow);
dzdy(_, 2) = rep(0.0, nrow);
j = 3;
n_even = true;
for (n=2; n <= maxorder; n++) {
// fill in m=0
m=0;
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-1);
dzdx(_, j) = (double) n * zm(_, j-n);
dzdy(_, j) = (double) n * zm(_, j-1);
++j;
for (m=1; m < n/2; m++) {
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - y*zm(_, j-2*m) - zm(_, j-2*n);
dzdx(_, j) = (double) n*zm(_, j-n) + (double) n*zm(_, j-n-1) + dzdx(_, j-2*n);
dzdy(_, j) = (double) n*zm(_, j-2*m-1) - (double) n*zm(_, j-2*m) + dzdy(_, j-2*n);
++j;
}
if (n_even) {
zm(_, j) = 2.*x*zm(_, j-n) + 2.*y*zm(_, j-n-1) - zm(_, j-2*n);
dzdx(_, j) = 2.*(double) n*zm(_, j-n) + dzdx(_, j-2*n);
dzdy(_, j) = 2.*(double) n*zm(_, j-2*m-1) + dzdy(_, j-2*n);
++m;
++j;
} else {
zm(_, j) = y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - y*zm(_, j-2*m) - zm(_, j-2*n);
dzdx(_, j) = (double) n*zm(_, j-n-1) + dzdx(_, j-2*n);
dzdy(_, j) = (double) n*(zm(_, j-2*m-1) - zm(_, j-2*m)) + dzdy(_, j-2*n);
++m;
++j;
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - zm(_, j-2*n);
dzdx(_, j) = (double) n*(zm(_, j-n) + zm(_, j-n-1)) + dzdx(_, j-2*n);
dzdy(_, j) = (double) n*zm(_, j-2*m-1) + dzdy(_, j-2*n);
++m;
++j;
}
for (m=m; m<n; m++) {
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - y*zm(_, j-2*m) - zm(_, j-2*n);
dzdx(_, j) = (double) n*zm(_, j-n) + (double) n*zm(_, j-n-1) + dzdx(_, j-2*n);
dzdy(_, j) = (double) n*zm(_, j-2*m-1) - (double) n*zm(_, j-2*m) + dzdy(_, j-2*n);
++j;
}
// m = n
zm(_, j) = x*zm(_, j-n-1) - y*zm(_, j-2*n);
dzdx(_, j) = (double) n * zm(_, j-n-1);
dzdy(_, j) = (double) -n * zm(_, j-2*n);
++j;
n_even = !n_even;
}
//orthonormalize if requested
if (unit_variance) {
zm = norm_zpm(zm, maxorder);
dzdx = norm_zpm(dzdx, maxorder);
dzdy = norm_zpm(dzdy, maxorder);
}
if (return_zpm) {
return List::create(Named("zm") = zm, Named("dzdx") = dzdx, Named("dzdy") = dzdy);
} else {
return List::create(Named("dzdx") = dzdx, Named("dzdy") = dzdy);
}
}
/*****************
* Fill matrix of Zernike polynomial values in cartesian coordinates.
*
* This is just the above code with all references to directional
* derivatives removed.
*****************/
//' Zernike polynomials
//'
//' Calculate Zernike polynomial values in
//' ISO/ANSI sequence for a set of Cartesian coordinates.
//'
//' @param x a vector of x coordinates for points on a unit disk.
//' @param y a vector of y coordinates.
//' @param maxorder the maximum radial polynomial order (defaults to 12).
//' @param unit_variance logical: return with orthonormal scaling? (default `false`)
//'
//' @return a matrix of Zernike polynomial values evaluated at the input
//' Cartesian coordinates and all radial and azimuthal orders from
//' 0 through `maxorder`.
//'
//' @details This is the same algorithm and essentially the same code as [gradzpm_cart()]
//' except directional derivatives aren't calculated.
//'
//' @examples
//' ##illustrates difference in smoothed wavefront from using zpm_cart with ISO sequence of same order
//' require(zernike)
//' fpath <- file.path(find.package(package="zernike"), "psidata")
//' files <- scan(file.path(fpath, "files.txt"), what="character")
//' for (i in 1:length(files)) files[i] <- file.path(fpath, files[i])
//'
//' ## load the images into an array
//'
//' images <- load.images(files)
//'
//' ## parameters for this run
//'
//' source(file.path(fpath, "parameters.txt"))
//'
//' ## phase shifts
//'
//' phases <- wrap((0:(dim(images)[3]-1))/frames.per.cycle*2*pi)
//' phases <- switch(ps.dir, ccw = -phases, cw = phases, phases)
//'
//' ## target SA coefficients for numerical null.
//'
//' sa.t <- sconic(diam,roc,lambda=wavelength)
//' zopt <- psfit_options()
//' zopt$satarget <- sa.t
//' psfit <- psifit(images, phases, psialg="ls", options=zopt)
//'
//' ## get back the raw wavefront
//'
//' wf.raw <- qpuw(psfit$phi, psfit$mod)
//'
//' ## This will tell wf_net to use zpm_cart instead
//'
//' zopt$isoseq <- TRUE
//' ifit <- wf_net(wf.raw, cp = psfit$cp, options=zopt)
//'
//' ## plotn does a direct comparison
//'
//' plotn(psfit, ifit, wftype="smooth", qt=c(0,1))
//'
//' @md
// [[Rcpp::export]]
NumericMatrix zpm_cart(const NumericVector& x, const NumericVector& y, const int& maxorder = 12,
const bool& unit_variance = true) {
int n, m;
int ncol = (maxorder+1)*(maxorder+2)/2;
unsigned int nrow = x.size();
int j;
bool n_even;
NumericMatrix zm(nrow, ncol);
CharacterVector cnames(ncol);
//do some rudimentary error checking
if (x.size() != y.size()) stop("Numeric vectors must be same length");
if (maxorder < 1) stop("maxorder must be >= 1");
// good enough
// starting values for recursions
zm(_, 0) = rep(1.0, nrow);
zm(_, 1) = y;
zm(_, 2) = x;
j = 3;
n_even = true;
for (n=2; n <= maxorder; n++) {
// fill in m=0
m=0;
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-1);
++j;
for (m=1; m < n/2; m++) {
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - y*zm(_, j-2*m) - zm(_, j-2*n);
++j;
}
if (n_even) {
zm(_, j) = 2.*x*zm(_, j-n) + 2.*y*zm(_, j-n-1) - zm(_, j-2*n);
++m;
++j;
} else {
zm(_, j) = y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - y*zm(_, j-2*m) - zm(_, j-2*n);
++m;
++j;
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - zm(_, j-2*n);
++m;
++j;
}
for (m=m; m<n; m++) {
zm(_, j) = x*zm(_, j-n) + y*zm(_, j-2*m-1) + x*zm(_, j-n-1) - y*zm(_, j-2*m) - zm(_, j-2*n);
++j;
}
// m = n
zm(_, j) = x*zm(_, j-n-1) - y*zm(_, j-2*n);
++j;
n_even = !n_even;
}
//orthonormalize if requested
if (unit_variance) {
zm = norm_zpm(zm, maxorder);
}
// add column names
for (j=0; j<ncol; j++) {
cnames(j) = "Z" + std::to_string(j);
}
colnames(zm) = cnames;
return zm;
}
/*****************
*
* Approximate Zernike Annular polynomials by numerically orthogonalizing
* sub-matrixes for each m separately using thin QR decomposition.
*
******************/
//' Zernike Annular polynomials
//'
//' Calculate approximate Zernike Annular polynomial values in
//' ISO/ANSI sequence for a set of Cartesian coordinates.
//'
//' @param x a vector of x coordinates for points on a unit disk.
//' @param y a vector of y coordinates.
//' @param maxorder the maximum radial polynomial order (defaults to 12).
//'
//' @return a matrix of approximate Zernike Annular polynomial values evaluated at the input
//' Cartesian coordinates and all radial and azimuthal orders from
//' 0 through `maxorder`.
//'
//' @details Uses QR decomposition applied separately to each azimuthal order m to orthogonalize a matrix
//' of Zernike polynomials. This closely approximates annular Zernikes for a large enough set of coordinates.
//'
//' Note the coordinates must be uniformly spaced for this to produce the intended values.
//' @md
// [[Rcpp::export]]
mat zapm_cart(const NumericVector& x, const NumericVector& y, const int& maxorder=12) {
uword nrow=x.size();
int ncol = (maxorder+1)*(maxorder+2)/2;
uword i, j, m, nj;
double zpnorm = std::sqrt((double) nrow);
mat zm(nrow, ncol), annzm(nrow, ncol);
//do some rudimentary error checking
if (x.size() != y.size()) stop("Numeric vectors must be same length");
if (maxorder < 1) stop("maxorder must be >= 1");
// good enough
zm = as<arma::mat>(zpm_cart(x, y, maxorder));
// for each azimuthal index m find the column indexes
// of the zp matrix having that value of m. That
// subset is what we need to orthogonalize.
// Note this is done separately for "sine" and "cosine" components.
for (m=0; m<maxorder-1; m++) {
nj = (maxorder-m)/2 + 1;
uvec jsin(nj);
uvec jcos(nj);
mat Q(nrow, nj);
mat R(nj, nj);
vec sgn(nj);
for (i=0; i<nj; i++) {
jsin(i) = ((m + 2*i)*(m + 2*i) + 2*(m + 2*i) - m) / 2;
jcos(i) = jsin(i) + m;
}
qr_econ(Q, R, zm.cols(jsin));
sgn = sign(R.diag());
annzm.cols(jsin) = zpnorm * Q * diagmat(sgn);
if (m > 0) {
qr_econ(Q, R, zm.cols(jcos));
sgn = sign(R.diag());
annzm.cols(jcos) = zpnorm * Q * diagmat(sgn);
}
}
// Two highest orders only have one term
for (m=maxorder-1; m<=maxorder; m++) {
j = (m*m + m)/2;
annzm.col(j) = zm.col(j) * zpnorm / norm(zm.col(j));
j = j+m;
annzm.col(j) = zm.col(j) * zpnorm / norm(zm.col(j));
}
return annzm;
}
| 30.739606 | 111 | 0.580154 | [
"vector"
] |
e1091f558834463e17990199774f6c6c55d72c64 | 13,166 | cpp | C++ | Box2D/Collision/Shapes/b2PolygonShape.cpp | ilektron/box2dpp | e0a02af2ce2a95c128875d55178ad207fb8860d4 | [
"Zlib"
] | 1 | 2020-12-09T21:56:26.000Z | 2020-12-09T21:56:26.000Z | Box2D/Collision/Shapes/b2PolygonShape.cpp | ilektron/box2d11 | e0a02af2ce2a95c128875d55178ad207fb8860d4 | [
"Zlib"
] | null | null | null | Box2D/Collision/Shapes/b2PolygonShape.cpp | ilektron/box2d11 | e0a02af2ce2a95c128875d55178ad207fb8860d4 | [
"Zlib"
] | 1 | 2019-03-27T08:03:54.000Z | 2019-03-27T08:03:54.000Z | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
#include <new>
using namespace box2d;
b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const
{
void* mem = allocator->Allocate(sizeof(b2PolygonShape));
auto clone = new (mem) b2PolygonShape;
*clone = *this;
return clone;
}
void b2PolygonShape::SetAsBox(float hx, float hy)
{
m_vertices = {{{-hx, -hy}},
{{hx, -hy}},
{{hx, hy}},
{{-hx, hy}}};
m_normals = {{{0.0f, -1.0f}},
{{1.0f, 0.0f}},
{{0.0f, 1.0f}},
{{-1.0f, 0.0f}}};
m_centroid = {{0.0f, 0.0f}};
}
void b2PolygonShape::SetAsBox(float hx, float hy, const b2Vec<float, 2>& center, float angle)
{
SetAsBox(hx, hy);
m_centroid = center;
b2Transform xf;
xf.p = center;
xf.q.Set(angle);
// Transform vertices and normals.
for (std::size_t i = 0; i < m_vertices.size(); ++i)
{
m_vertices[i] = b2Mul(xf, m_vertices[i]);
m_normals[i] = b2Mul(xf.q, m_normals[i]);
}
}
int32_t b2PolygonShape::GetChildCount() const
{
return 1;
}
static b2Vec<float, 2> ComputeCentroid(const std::vector<b2Vec<float, 2>>& vs)
{
b2Assert(vs.size() >= 3);
b2Vec<float, 2> c{{0.0f, 0.0f}};
float area = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
b2Vec<float, 2> pRef{{0.0f, 0.0f}};
#if 0
// This code would put the reference point inside the polygon.
for (int32_t i = 0; i < count; ++i)
{
pRef += vs[i];
}
pRef *= 1.0f / count;
#endif
const float inv3 = 1.0f / 3.0f;
for (std::size_t i = 0; i < vs.size(); ++i)
{
// Triangle vertices.
b2Vec<float, 2> p1 = pRef;
b2Vec<float, 2> p2 = vs[i];
b2Vec<float, 2> p3 = i + 1 < vs.size() ? vs[i + 1] : vs[0];
b2Vec<float, 2> e1 = p2 - p1;
b2Vec<float, 2> e2 = p3 - p1;
float D = b2Cross(e1, e2);
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
c += triangleArea * inv3 * (p1 + p2 + p3);
}
// Centroid
b2Assert(area > EPSILON);
c *= 1.0f / area;
return c;
}
void b2PolygonShape::Set(const b2Vec<float, 2>* vertices, int32_t count)
{
b2Assert(3 <= count && count <= MAX_POLYGON_VERTICES);
if (count < 3)
{
SetAsBox(1.0f, 1.0f);
return;
}
int32_t n = b2Min(count, MAX_POLYGON_VERTICES);
// Perform welding and copy vertices into local buffer.
// b2Vec<float, 2> ps[MAX_POLYGON_VERTICES];
std::array<b2Vec<float, 2>, MAX_POLYGON_VERTICES> ps;
int32_t tempCount = 0;
for (int32_t i = 0; i < n; ++i)
{
b2Vec<float, 2> v = vertices[i];
bool unique = true;
for (int32_t j = 0; j < tempCount; ++j)
{
if (b2DistanceSquared(v, ps[j]) < 0.5f * LINEAR_SLOP)
{
unique = false;
break;
}
}
if (unique)
{
ps[tempCount++] = v;
}
}
n = tempCount;
if (n < 3)
{
// Polygon is degenerate.
b2Assert(false);
SetAsBox(1.0f, 1.0f);
return;
}
// Create the convex hull using the Gift wrapping algorithm
// http://en.wikipedia.org/wiki/Gift_wrapping_algorithm
// Find the right most point on the hull
int32_t i0 = 0;
float x0 = ps[0][b2VecX];
for (int32_t i = 1; i < n; ++i)
{
float x = ps[i][b2VecX];
if (x > x0 || (x == x0 && ps[i][b2VecY] < ps[i0][b2VecY]))
{
i0 = i;
x0 = x;
}
}
int32_t hull[MAX_POLYGON_VERTICES];
int32_t m = 0;
int32_t ih = i0;
for (;;)
{
hull[m] = ih;
int32_t ie = 0;
for (int32_t j = 1; j < n; ++j)
{
if (ie == ih)
{
ie = j;
continue;
}
b2Vec<float, 2> r = ps[ie] - ps[hull[m]];
b2Vec<float, 2> v = ps[j] - ps[hull[m]];
float c = b2Cross(r, v);
if (c < 0.0f)
{
ie = j;
}
// Collinearity check
if (c == 0.0f && v.LengthSquared() > r.LengthSquared())
{
ie = j;
}
}
++m;
ih = ie;
if (ie == i0)
{
break;
}
}
if (m < 3)
{
// Polygon is degenerate.
b2Assert(false);
SetAsBox(1.0f, 1.0f);
return;
}
m_vertices.clear();
m_normals.clear();
// Copy vertices.
for (int32_t i = 0; i < m; ++i)
{
m_vertices.push_back(ps[hull[i]]);
}
// Compute normals. Ensure the edges have non-zero length.
for (int32_t i = 0; i < m; ++i)
{
int32_t i1 = i;
int32_t i2 = i + 1 < m ? i + 1 : 0;
b2Vec<float, 2> edge = m_vertices[i2] - m_vertices[i1];
b2Assert(edge.LengthSquared() > EPSILON * EPSILON);
m_normals.push_back(b2Cross(edge, 1.0f));
m_normals[i].Normalize();
}
// Compute the polygon centroid.
m_centroid = ComputeCentroid(m_vertices);
}
bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec<float, 2>& p) const
{
b2Vec<float, 2> pLocal = b2MulT(xf.q, p - xf.p);
for (std::size_t i = 0; i < m_normals.size(); ++i)
{
auto dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
if (dot > 0.0f)
{
return false;
}
}
return true;
}
bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& xf, int32_t childIndex) const
{
B2_NOT_USED(childIndex);
// Put the ray into the polygon's frame of reference.
b2Vec<float, 2> p1 = b2MulT(xf.q, input.p1 - xf.p);
b2Vec<float, 2> p2 = b2MulT(xf.q, input.p2 - xf.p);
b2Vec<float, 2> d = p2 - p1;
float lower = 0.0f, upper = input.maxFraction;
int32_t index = -1;
for (std::size_t i = 0; i < m_normals.size(); ++i)
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
float denominator = b2Dot(m_normals[i], d);
if (denominator == 0.0f)
{
if (numerator < 0.0f)
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if (denominator < 0.0f && numerator < lower * denominator)
{
// Increase lower.
// The segment enters this half-space.
lower = numerator / denominator;
index = i;
}
else if (denominator > 0.0f && numerator < upper * denominator)
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator / denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
// if (upper < lower - EPSILON)
if (upper < lower)
{
return false;
}
}
b2Assert(0.0f <= lower && lower <= input.maxFraction);
if (index >= 0)
{
output->fraction = lower;
output->normal = b2Mul(xf.q, m_normals[index]);
return true;
}
return false;
}
void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32_t childIndex) const
{
B2_NOT_USED(childIndex);
b2Vec<float, 2> lower = b2Mul(xf, m_vertices[0]);
b2Vec<float, 2> upper = lower;
for (const auto& vertex : m_vertices)
{
auto v = b2Mul(xf, vertex);
lower = b2Min(lower, v);
upper = b2Max(upper, v);
}
b2Vec<float, 2> r{{GetRadius(), GetRadius()}};
aabb->lowerBound = lower - r;
aabb->upperBound = upper + r;
}
void b2PolygonShape::ComputeMass(b2MassData* massData, float density) const
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid[b2VecX] = (1/mass) * rho * int(x * dA)
// centroid[b2VecY] = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
b2Assert(m_vertices.size() >= 3);
b2Vec<float, 2> center;
center = {{0.0f, 0.0f}};
float area = 0.0f;
float I = 0.0f;
// s is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
b2Vec<float, 2> s{{0.0f, 0.0f}};
// This code would put the reference point inside the polygon.
for (const auto& vertex : m_vertices)
{
s += vertex;
}
s *= 1.0f / m_vertices.size();
const float k_inv3 = 1.0f / 3.0f;
for (std::size_t i = 0; i < m_vertices.size(); ++i)
{
// Triangle vertices.
b2Vec<float, 2> e1 = m_vertices[i] - s;
b2Vec<float, 2> e2 = i + 1 < m_vertices.size() ? m_vertices[i + 1] - s : m_vertices[0] - s;
float D = b2Cross(e1, e2);
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * (e1 + e2);
float ex1 = e1[b2VecX], ey1 = e1[b2VecY];
float ex2 = e2[b2VecX], ey2 = e2[b2VecY];
float intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
float inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
I += (0.25f * k_inv3 * D) * (intx2 + inty2);
}
// Total mass
massData->mass = density * area;
// Center of mass
b2Assert(area > EPSILON);
center *= 1.0f / area;
massData->center = center + s;
// Inertia tensor relative to the local origin (point s).
massData->I = density * I;
// Shift to center of mass then to original body origin.
massData->I +=
massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
}
bool b2PolygonShape::Validate() const
{
for (std::size_t i = 0; i < m_vertices.size(); ++i)
{
auto i1 = i;
auto i2 = i < m_vertices.size() - 1 ? i1 + 1 : 0;
b2Vec<float, 2> p = m_vertices[i1];
b2Vec<float, 2> e = m_vertices[i2] - p;
for (std::size_t j = 0; j < m_vertices.size(); ++j)
{
if (j == i1 || j == i2)
{
continue;
}
b2Vec<float, 2> v = m_vertices[j] - p;
float c = b2Cross(e, v);
if (c < 0.0f)
{
return false;
}
}
}
return true;
}
| 28.253219 | 100 | 0.514659 | [
"vector",
"transform"
] |
e1122d8de6c38dc81fc0c6071c90facc7008817a | 4,349 | cpp | C++ | lib/Partitioner/PartitionerUtils.cpp | petecoup/glow | 517f4de85e4d67c93d08f9802faffae1dc6c42bd | [
"Apache-2.0"
] | null | null | null | lib/Partitioner/PartitionerUtils.cpp | petecoup/glow | 517f4de85e4d67c93d08f9802faffae1dc6c42bd | [
"Apache-2.0"
] | null | null | null | lib/Partitioner/PartitionerUtils.cpp | petecoup/glow | 517f4de85e4d67c93d08f9802faffae1dc6c42bd | [
"Apache-2.0"
] | null | null | null |
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "glow/Partitioner/PartitionerUtils.h"
#include <set>
namespace glow {
/// Given \p nodes, return a list of nodes who are not in this set but use any
/// node in this set.
std::vector<Node *> getOutUsers(const std::set<Node *> &nodes) {
std::vector<Node *> ret;
for (std::set<Node *>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
Node *cur = *it;
for (auto &U : cur->getUsers()) {
if (nodes.count(U.getUser())) {
continue;
}
ret.push_back(U.getUser());
}
}
return ret;
}
/// Given \p nodes, return a list of nodes who are not in this set but use only
/// the nodes in this set or constant.
std::vector<Node *>
getOutUsersWithOnePredecessor(const std::set<Node *> &nodes) {
std::vector<Node *> ret;
for (std::set<Node *>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
Node *cur = *it;
for (auto &U : cur->getUsers()) {
Node *user = U.getUser();
if (nodes.count(user)) {
continue;
}
bool flag = true;
for (int i = 0, e = user->getNumInputs(); i < e; i++) {
Node *in = user->getNthInput(i).getNode();
if (llvm::isa<Storage>(in) || nodes.count(in)) {
continue;
}
flag = false;
break;
}
if (flag) {
ret.push_back(user);
}
}
}
return ret;
}
GraphMemInfo getGraphMemInfo(const std::set<Node *> &nodes) {
GraphMemInfo ret;
std::set<Node *> nSet;
for (std::set<Node *>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
Node *cur = *it;
// For Save onde, the only required memory is for output.
if (auto *SN = llvm::dyn_cast<SaveNode>(cur)) {
Storage *out = llvm::dyn_cast<Storage>(SN->getOutput().getNode());
ret.outMemSize += out->getType()->getSizeInBytes();
continue;
}
// Check the inputs of each node in this subgraph and decide if it
// contributes to the memory usage:
for (int i = 0, e = cur->getNumInputs(); i < e; i++) {
Node *node = cur->getNthInput(i).getNode();
if (nodes.count(node) || nSet.count(node)) {
// This input belongs to this subgraph or it has been considered
// already, nothing to do.
continue;
}
nSet.insert(node);
Storage *in = llvm::dyn_cast<Storage>(node);
if (in) {
uint64_t size = in->getType()->getSizeInBytes();
if (node->getKind() == Kinded::Kind::ConstantKind) {
// Constant.
ret.constMemSize += size;
} else {
// PlaceHolder for Input.
ret.inMemSize += size;
}
} else {
// In this case, this input is neither a storage type node nor belongs
// to this subgraph. Therefore, when creating paritions, we need to add
// a PlaceHolder for the data from outside.
for (auto &U : node->getUsers()) {
if (U.getUser() == cur) {
ret.inMemSize += node->getType(0)->getSizeInBytes();
break;
}
}
}
}
// Check the outputs of each node in this subgraph and decide if it
// contributes to the memory usage. Although at the stage, the output may
// not be a storage node, after real partitioning, a Save node will be added
// to hold the output:
for (int i = 0, e = cur->getNumResults(); i < e; i++) {
for (auto &U : cur->getNthResult(i).getNode()->getUsers()) {
Node *node = U.getUser();
if (nodes.count(node) || nSet.count(node)) {
// The output belongs to this subgraph, nothing needs to do.
continue;
}
nSet.insert(node);
ret.outMemSize += cur->getType(i)->getSizeInBytes();
}
}
}
return ret;
}
} // namespace glow
| 33.198473 | 80 | 0.589331 | [
"vector"
] |
e115ab1e7fc69a640caca634cf6a671647b8b799 | 6,165 | hpp | C++ | include/mango/math/vector512_uint32x16.hpp | JessyDL/mango | 8db9632fb2e81ba0a13129d3d19019688fab7bd1 | [
"Zlib"
] | 2 | 2020-06-28T19:06:09.000Z | 2020-07-01T16:31:49.000Z | include/mango/math/vector512_uint32x16.hpp | JessyDL/mango | 8db9632fb2e81ba0a13129d3d19019688fab7bd1 | [
"Zlib"
] | null | null | null | include/mango/math/vector512_uint32x16.hpp | JessyDL/mango | 8db9632fb2e81ba0a13129d3d19019688fab7bd1 | [
"Zlib"
] | 1 | 2020-06-28T15:19:27.000Z | 2020-06-28T15:19:27.000Z | /*
MANGO Multimedia Development Platform
Copyright (C) 2012-2019 Twilight Finland 3D Oy Ltd. All rights reserved.
*/
#pragma once
#include "vector.hpp"
namespace mango
{
template <>
struct Vector<u32, 16>
{
using VectorType = simd::u32x16;
using ScalarType = u32;
enum { VectorSize = 16 };
VectorType m;
ScalarType& operator [] (size_t index)
{
assert(index < VectorSize);
return data()[index];
}
ScalarType operator [] (size_t index) const
{
assert(index < VectorSize);
return data()[index];
}
ScalarType* data()
{
return reinterpret_cast<ScalarType *>(this);
}
const ScalarType* data() const
{
return reinterpret_cast<const ScalarType *>(this);
}
explicit Vector() {}
Vector(u32 s)
: m(simd::u32x16_set(s))
{
}
Vector(u32 s0, u32 s1, u32 s2, u32 s3, u32 s4, u32 s5, u32 s6, u32 s7,
u32 s8, u32 s9, u32 s10, u32 s11, u32 s12, u32 s13, u32 s14, u32 s15)
: m(simd::u32x16_set(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15))
{
}
Vector(simd::u32x16 v)
: m(v)
{
}
template <typename T, int I>
Vector& operator = (const ScalarAccessor<ScalarType, T, I>& accessor)
{
*this = ScalarType(accessor);
return *this;
}
Vector& operator = (const Vector& v)
{
m = v.m;
return *this;
}
Vector& operator = (simd::u32x16 v)
{
m = v;
return *this;
}
Vector& operator = (u32 s)
{
m = simd::u32x16_set(s);
return *this;
}
operator simd::u32x16 () const
{
return m;
}
#ifdef int512_is_hardware_vector
operator simd::u32x16::vector () const
{
return m.data;
}
#endif
};
static inline const Vector<u32, 16> operator + (Vector<u32, 16> v)
{
return v;
}
static inline Vector<u32, 16> operator - (Vector<u32, 16> v)
{
return simd::sub(simd::u32x16_zero(), v);
}
static inline Vector<u32, 16>& operator += (Vector<u32, 16>& a, Vector<u32, 16> b)
{
a = simd::add(a, b);
return a;
}
static inline Vector<u32, 16>& operator -= (Vector<u32, 16>& a, Vector<u32, 16> b)
{
a = simd::sub(a, b);
return a;
}
static inline Vector<u32, 16> operator + (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::add(a, b);
}
static inline Vector<u32, 16> operator - (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::sub(a, b);
}
static inline Vector<u32, 16> unpacklo(Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::unpacklo(a, b);
}
static inline Vector<u32, 16> unpackhi(Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::unpackhi(a, b);
}
static inline Vector<u32, 16> min(Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::min(a, b);
}
static inline Vector<u32, 16> max(Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::max(a, b);
}
static inline Vector<u32, 16> clamp(Vector<u32, 16> a, Vector<u32, 16> low, Vector<u32, 16> high)
{
return simd::clamp(a, low, high);
}
// ------------------------------------------------------------------
// bitwise operators
// ------------------------------------------------------------------
static inline Vector<u32, 16> nand(Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::bitwise_nand(a, b);
}
static inline Vector<u32, 16> operator & (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::bitwise_and(a, b);
}
static inline Vector<u32, 16> operator | (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::bitwise_or(a, b);
}
static inline Vector<u32, 16> operator ^ (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::bitwise_xor(a, b);
}
static inline Vector<u32, 16> operator ~ (Vector<u32, 16> a)
{
return simd::bitwise_not(a);
}
// ------------------------------------------------------------------
// compare / select
// ------------------------------------------------------------------
static inline mask32x16 operator > (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::compare_gt(a, b);
}
static inline mask32x16 operator < (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::compare_gt(b, a);
}
static inline mask32x16 operator == (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::compare_eq(a, b);
}
static inline mask32x16 operator >= (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::compare_ge(a, b);
}
static inline mask32x16 operator <= (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::compare_le(b, a);
}
static inline mask32x16 operator != (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::compare_neq(a, b);
}
static inline Vector<u32, 16> select(mask32x16 mask, Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::select(mask, a, b);
}
// ------------------------------------------------------------------
// shift
// ------------------------------------------------------------------
static inline Vector<u32, 16> operator << (Vector<u32, 16> a, int b)
{
return simd::sll(a, b);
}
static inline Vector<u32, 16> operator >> (Vector<u32, 16> a, int b)
{
return simd::srl(a, b);
}
static inline Vector<u32, 16> operator << (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::sll(a, b);
}
static inline Vector<u32, 16> operator >> (Vector<u32, 16> a, Vector<u32, 16> b)
{
return simd::srl(a, b);
}
} // namespace mango
| 24.759036 | 103 | 0.489538 | [
"vector",
"3d"
] |
e11745bcffa2c1a1f3e07e5ed8080855a7cbe081 | 1,997 | cpp | C++ | source/game_data.cpp | nabijaczleweli/apoSimpleSmart | e80893206705fce832fb40dd89cf40e9106d8e05 | [
"MIT"
] | null | null | null | source/game_data.cpp | nabijaczleweli/apoSimpleSmart | e80893206705fce832fb40dd89cf40e9106d8e05 | [
"MIT"
] | null | null | null | source/game_data.cpp | nabijaczleweli/apoSimpleSmart | e80893206705fce832fb40dd89cf40e9106d8e05 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2016 nabijaczleweli
// 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 "game_data.hpp"
#include <fstream>
#include "cereal/cereal.hpp"
#include "cereal/types/vector.hpp"
#include "cereal/archives/json.hpp"
#include "rust_helpers.hpp"
using namespace std;
template <class Archive>
void serialize(Archive & archive, high_data & hd) {
archive(hd.name, hd.score, hd.level);
}
template <class Archive>
void serialize(Archive & archive, game_data & gd) {
archive(gd.name, gd.highscore);
}
game_data load_game_data_from_file(const std::string & filename) {
game_data res;
res.name = username();
try {
ifstream ifs(filename);
cereal::JSONInputArchive archive(ifs);
archive(res);
} catch(cereal::RapidJSONException &) {}
return res;
}
void save_game_data_to_file(const game_data & input_gd, const std::string & filename) {
ofstream ofs(filename);
cereal::JSONOutputArchive archive(ofs);
archive(input_gd);
}
| 30.257576 | 87 | 0.754632 | [
"vector"
] |
e11bea5670c541ae9781953fad64fdeaa1a75edc | 12,089 | cpp | C++ | StartPP/DibGlSurface.cpp | tchv71/StartPP2 | bb5a297865da3fc295058f6e301944fc279948dc | [
"MIT"
] | null | null | null | StartPP/DibGlSurface.cpp | tchv71/StartPP2 | bb5a297865da3fc295058f6e301944fc279948dc | [
"MIT"
] | 1 | 2016-08-06T12:33:16.000Z | 2017-01-13T12:54:55.000Z | StartPP/DibGlSurface.cpp | tchv71/StartPP2 | bb5a297865da3fc295058f6e301944fc279948dc | [
"MIT"
] | 1 | 2020-09-22T15:42:57.000Z | 2020-09-22T15:42:57.000Z | #include "stdafx.h"
#include "DibGlSurface.h"
#include <wx/image.h>
#include <wx/bitmap.h>
#include <wx/glcanvas.h>
#include <wx/dcgraph.h>
#include <wx/dcprint.h>
#if defined(__WXWIN__) && wxUSE_ENH_METAFILE
#include "wx/msw/enhmeta.h"
#endif
#ifdef __WXMSW__
#include "GL/gl.h"
#endif
#ifdef __WXMAC__
#include <OpenGL/OpenGL.h>
#include <OpenGL/CGLTypes.h>
#include <OpenGL/CGLCurrent.h>
#include <OpenGL/gl.h>
#endif
#ifdef __WXGTK__
#define GL_GLEXT_PROTOTYPES 1
//#include "GL/glut.h"
#include <gtk/gtk.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "GL/gl.h"
#include "GL/glext.h"
#endif
CDibGlSurface::CDibGlSurface(const wxSize& size, CDC*pDC) : m_size(size)
#ifdef __WXMSW__
,hDC(nullptr),hMemDC(nullptr),hglRC(nullptr),hBm(nullptr),hBmOld(nullptr),lpBits(nullptr)
#endif
#ifdef __WXGTK__
//, PBDC(0)
, m_pixmap(0)
, m_PBRC(0)
, m_pm(0)
#endif
{
#ifdef __WXMSW__
CDC::TempHDC tempDC(*pDC);
hDC = tempDC.GetHDC();
#endif
InitializeGlobal();
}
CDibGlSurface::~CDibGlSurface()
{
CleanUp();
}
#ifdef __WXMSW__
void CDibGlSurface::InitializeGlobal()
{
hMemDC = CreateCompatibleDC(hDC);
hBm = CreateDIBSurface();
hBmOld = HBITMAP(SelectObject(hMemDC, hBm));
if (!PrepareDIBSurface())
wxMessageBox(_T("The pixel format of the memory DC is not set properly"));
hglRC = wglCreateContext(hMemDC);
wglMakeCurrent(hMemDC, hglRC);
}
//***********************************************************************
// Function: CDibGlSurface::CleanUp
//
//**********************************************************************
void CDibGlSurface::CleanUp()
{
if (hglRC)
{
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(hglRC);
}
//DeleteObject(hPal);
hBm = HBITMAP(SelectObject(hMemDC, hBmOld));
DeleteObject(hBm);
DeleteDC(hMemDC);
}
#define WIDTHBYTES(bits) (((bits) + 31)/32 * 4)
//***********************************************************************
// Function: CreateDIBSurface
//
// Purpose: reates a DIB section as the drawing surface for gl calls
//
// Parameters:
//
// Returns:
// HBITMAP
//
//**********************************************************************
HBITMAP CDibGlSurface::CreateDIBSurface()
{
BYTE biInfo[sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)];
BITMAPINFO* pbi = reinterpret_cast<BITMAPINFO *>(biInfo);
ZeroMemory(pbi, sizeof(BITMAPINFO));
if (!hDC)
return nullptr;
pbi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbi->bmiHeader.biWidth = m_size.GetWidth();
pbi->bmiHeader.biHeight = m_size.GetHeight();
pbi->bmiHeader.biPlanes = 1;
pbi->bmiHeader.biBitCount = WORD(GetDeviceCaps(hDC, PLANES) * GetDeviceCaps(hDC, BITSPIXEL));
pbi->bmiHeader.biCompression = BI_RGB;
pbi->bmiHeader.biSizeImage = WIDTHBYTES(DWORD(pbi->bmiHeader.biWidth) *pbi->bmiHeader.biBitCount) *
pbi->bmiHeader.biHeight;
return CreateDIBSection(hDC, pbi, DIB_RGB_COLORS, &lpBits, nullptr, DWORD(0));
}
//***********************************************************************
// Function: CDibGlSurface::PrepareDIBSurface
//
// Purpose: Selects the DIB section into a memory DC and sets the pixel
// format of the memory DC. A palette is created if the app is
// running on a 8 bit device.
//
// Parameters:
// void
//
// Returns:
// BOOL
//
//**********************************************************************
BOOL CDibGlSurface::PrepareDIBSurface(void) const
{
static PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
1, // version number
PFD_DRAW_TO_WINDOW | PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL | PFD_SUPPORT_GDI,
PFD_TYPE_RGBA,
// RGBA type
24, // 24-bit color depth
0, 0, 0, 0, 0, 0, // color bits ignored
0, // no alpha buffer
0, // shift bit ignored
0, // no accumulation buffer
0, 0, 0, 0, // accum bits ignored
32, // 32-bit z-buffer
0, // no stencil buffer
0, // no auxiliary buffer
PFD_MAIN_PLANE, // main layer
0, // reserved
0, 0, 0 // layer masks ignored
};
BOOL bRet = TRUE;
int nIndex;
pfd.cColorBits = byte(GetDeviceCaps(hDC, PLANES) * GetDeviceCaps(hDC, BITSPIXEL));
nIndex = ChoosePixelFormat(hMemDC, &pfd);
if (!nIndex)
bRet = FALSE;
DescribePixelFormat(hMemDC, nIndex, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (!SetPixelFormat(hMemDC, nIndex, &pfd))
bRet = FALSE;
// if (bRet && pfd.dwFlags & PFD_NEED_PALETTE)
// CreateRGBPalette();
return bRet;
}
#endif
#if defined(__WXMSW__) || defined(__WXGTK__) || defined (__WXMAC__)
void CDibGlSurface::DoDraw(wxDC* pDC, wxRect rectPrint)
{
wxSize sizeSave = m_size;
m_size.x = (m_size.x / 2 + 1) * 2;
BYTE* pixels = new BYTE[3 * m_size.GetWidth()*m_size.GetHeight()];
memset(pixels, 127, 3 * m_size.GetWidth()*m_size.GetHeight());
BYTE* pPix = pixels;
for (int i = 0; i < m_size.GetHeight(); i++)
{
glReadPixels(0, m_size.GetHeight() - i - 1, m_size.GetWidth(), 1, GL_RGB, GL_UNSIGNED_BYTE, pPix);
pPix += m_size.GetWidth() * 3;
}
wxImage img(m_size.GetWidth(), m_size.GetHeight(), pixels, NULL, false);
wxBitmap bmp(img);
m_size = sizeSave;
#if 0
wxMemoryDC memDC;
memDC.SelectObjectAsSource(bmp);
pDC->StretchBlit(rectPrint.GetPosition(), rectPrint.GetSize(), &memDC, wxPoint(0, 0), m_size);
#else
// Намного лучше качество интерполяции
if (dynamic_cast<wxMemoryDC*>(pDC))
{
wxGCDC gc(*dynamic_cast<wxMemoryDC*>(pDC));
gc.GetGraphicsContext()->DrawBitmap(bmp,rectPrint.x, rectPrint.y, rectPrint.width, rectPrint.height);
}
else if (dynamic_cast<wxPrinterDC*>(pDC))
{
wxGCDC gc(*dynamic_cast<wxPrinterDC*>(pDC));
gc.GetGraphicsContext()->DrawBitmap(bmp,rectPrint.x, rectPrint.y, rectPrint.width, rectPrint.height);
}
#if defined(__WXWIN__) && wxUSE_ENH_METAFILE
else if (dynamic_cast<wxEnhMetaFileDC*>(pDC))
{
wxGCDC gc(*dynamic_cast<wxEnhMetaFileDC*>(pDC));
gc.GetGraphicsContext()->DrawBitmap(bmp, rectPrint.x, rectPrint.y, rectPrint.width, rectPrint.height);
}
#endif
#endif
}
#endif
#ifdef __WXQT__
void CDibGlSurface::InitializeGlobal()
{
}
void CDibGlSurface::CleanUp()
{
}
#endif
#ifdef __WXGTK__
void CDibGlSurface::InitializeGlobal()
{
#if 0
Display *dpy = (Display*)wxGetDisplay();
int scrnum = DefaultScreen( dpy );
GLXContext FBRC = glXGetCurrentContext();
GLXDrawable FBDC = glXGetCurrentDrawable();
if (dpy == NULL)
{
throw "unable to get device context";
}
if (!FBDC)
{
throw "unable to get render context";
}
int attrib[] =
{
GLX_DOUBLEBUFFER, False,
//GLX_RED_SIZE, 8,
//GLX_GREEN_SIZE, 8,
//GLX_BLUE_SIZE, 8,
//GLX_ALPHA_SIZE, 8,
//GLX_STENCIL_SIZE, 0,
//GLX_DEPTH_SIZE, 16,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
None
};
int PBattrib[] =
{
GLX_PBUFFER_WIDTH, m_size.GetWidth(),
GLX_PBUFFER_HEIGHT, m_size.GetHeight(),
GLX_LARGEST_PBUFFER, False,
None
};
// choose a pixel format that meets our minimum requirements
int count = 0;
GLXFBConfig *config = glXChooseFBConfig(dpy, scrnum, attrib, &count);
if(config == NULL || count == 0)
{
throw "no fitting pbuffer pixel format found";
}
GLXPbuffer _PBDC = glXCreatePbuffer(dpy, config[0], PBattrib);
GLXContext _PBRC = glXCreateNewContext(dpy, config[0], GLX_RGBA_TYPE, NULL, true);
PBDC = _PBDC;
m_PBRC = _PBRC;
XFree(config);
Bool bRes = glXMakeCurrent(dpy, _PBDC, _PBRC);
const unsigned char* str = glGetString(GL_VENDOR);
return;
int framebuffer_width = m_size.GetWidth();
int framebuffer_height = m_size.GetHeight();
GLuint m_framebuffer1;
GLuint m_colorRenderbuffer1;
GLuint m_depthRenderbuffer;
glGenFramebuffers(1, &m_framebuffer1);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer1);
glGenRenderbuffers(1, &m_colorRenderbuffer1);
glBindRenderbuffer(GL_RENDERBUFFER, m_colorRenderbuffer1);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, framebuffer_width, framebuffer_height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_colorRenderbuffer1);
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_colorRenderbuffer1);
glGenRenderbuffers(1, &m_depthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_depthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, framebuffer_width, framebuffer_height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthRenderbuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_depthRenderbuffer);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
printf("Failed to make complete framebuffer object %x\n",status);
else
printf("Success, finally did it!");
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_framebuffer1);
#else
dis=(Display*)wxGetDisplay();
int scrnum = DefaultScreen( dis );
//d=glXGetCurrentDrawable();
Drawable d=gdk_x11_window_get_xid(gdk_get_default_root_window());
int w = m_size.GetWidth();
int h = m_size.GetHeight();
m_pixmap=XCreatePixmap(dis, d, w, h, 24);
int attribList[] =
{
GLX_RGBA,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24,
None
};
XVisualInfo *vis=glXChooseVisual(dis, scrnum, attribList);
m_pm = glXCreateGLXPixmap(dis, vis, m_pixmap);
m_PBRC = glXCreateContext(dis, vis, NULL, True);
glXMakeCurrent(dis, m_pm, m_PBRC);
XFree(vis);
#ifndef NDEBUG
/*const unsigned char* str =*/ glGetString(GL_VENDOR);
#endif
#endif
}
void CDibGlSurface::CleanUp()
{
glXMakeCurrent(dis,0,NULL);
glXDestroyContext(dis,m_PBRC);
glXDestroyGLXPixmap(dis,m_pm);
XFreePixmap(dis,m_pixmap);
}
#endif
#ifdef __WXMAC__
void CDibGlSurface::InitializeGlobal()
{
CGLPixelFormatAttribute attributes[4] =
{
kCGLPFAAccelerated, // no software rendering
kCGLPFAOpenGLProfile, // core profile with the version stated below
(CGLPixelFormatAttribute) kCGLOGLPVersion_Legacy,
(CGLPixelFormatAttribute) 0
};
CGLPixelFormatObj pix;
CGLError errorCode;
GLint num; // stores the number of possible pixel formats
errorCode = CGLChoosePixelFormat( attributes, &pix, &num );
// add error checking here
errorCode = CGLCreateContext( pix, NULL, &context ); // second parameter can be another context for object sharing
// add error checking here
CGLDestroyPixelFormat( pix );
errorCode = CGLSetCurrentContext( context );
// add error checking here
//const unsigned char* str = glGetString(GL_VENDOR);
int framebuffer_width = m_size.GetWidth();
int framebuffer_height = m_size.GetHeight();
glGenFramebuffers(1, &m_framebuffer1);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer1);
glGenRenderbuffers(1, &m_colorRenderbuffer1);
glBindRenderbuffer(GL_RENDERBUFFER, m_colorRenderbuffer1);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, framebuffer_width, framebuffer_height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_colorRenderbuffer1);
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_colorRenderbuffer1);
glGenRenderbuffers(1, &m_depthRenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_depthRenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, framebuffer_width, framebuffer_height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthRenderbuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_depthRenderbuffer);
#ifndef NDEBUG
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
wxASSERT (status == GL_FRAMEBUFFER_COMPLETE);
#endif
// glDrawBuffer(GL_COLOR_ATTACHMENT0);
// glReadBuffer(GL_COLOR_ATTACHMENT0);
// glBindFramebuffer(GL_READ_FRAMEBUFFER, m_framebuffer1);
}
void CDibGlSurface::CleanUp()
{
glBindFramebuffer(GL_FRAMEBUFFER,0);
glDeleteRenderbuffers(1,&m_depthRenderbuffer);
glDeleteRenderbuffers(1,&m_colorRenderbuffer1);
glDeleteFramebuffers(1,&m_framebuffer1);
CGLSetCurrentContext( NULL );
CGLDestroyContext( context );
}
#endif
| 28.377934 | 115 | 0.719332 | [
"render",
"object"
] |
e124f6e8f588be08951971c171df92bcb26029da | 43,614 | cpp | C++ | sortSVEperf.cpp | berenger-eu/arm-sve-sort | 6369f22ec204f93b62b13c29028bd90b219dbec2 | [
"MIT"
] | null | null | null | sortSVEperf.cpp | berenger-eu/arm-sve-sort | 6369f22ec204f93b62b13c29028bd90b219dbec2 | [
"MIT"
] | null | null | null | sortSVEperf.cpp | berenger-eu/arm-sve-sort | 6369f22ec204f93b62b13c29028bd90b219dbec2 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////
/// By berenger.bramas@inria.fr 2020.
/// Licence is MIT.
/// Comes without any warranty.
///
/// Code to test the performance of the different sorts
/// and partitioning schemes.
///
/// Please refer to the README to know how to build
/// and to have more information about the functions.
///
//////////////////////////////////////////////////////////
#if defined(_OPENMP)
#include <omp.h>
#endif
#include <iostream>
#include <algorithm>
#include <chrono>
#include <cassert>
#include <stdexcept>
#include <climits>
#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <string.h>
#include <array>
#include <vector>
#include "sortSVE.hpp"
#include "sortSVEkv.hpp"
#include "sortSVE512.hpp"
#include "sortSVEkv512.hpp"
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
class dtimer {
using double_second_time = std::chrono::duration<double, std::ratio<1, 1>>;
std::chrono::high_resolution_clock::time_point
m_start; ///< m_start time (start)
std::chrono::high_resolution_clock::time_point m_end; ///< stop time (stop)
std::chrono::nanoseconds m_cumulate; ///< the m_cumulate time
public:
/// Constructor
dtimer() { start(); }
/// Copy constructor
dtimer(const dtimer& other) = delete;
/// Copies an other timer
dtimer& operator=(const dtimer& other) = delete;
/// Move constructor
dtimer(dtimer&& other) = delete;
/// Copies an other timer
dtimer& operator=(dtimer&& other) = delete;
/** Rest all the values, and apply start */
void reset() {
m_start = std::chrono::high_resolution_clock::time_point();
m_end = std::chrono::high_resolution_clock::time_point();
m_cumulate = std::chrono::nanoseconds();
start();
}
/** Start the timer */
void start() {
m_start = std::chrono::high_resolution_clock::now();
}
/** Stop the current timer */
void stop() {
m_end = std::chrono::high_resolution_clock::now();
m_cumulate += std::chrono::duration_cast<std::chrono::nanoseconds>(m_end - m_start);
}
/** Return the elapsed time between start and stop (in second) */
double getElapsed() const {
return std::chrono::duration_cast<double_second_time>(
std::chrono::duration_cast<std::chrono::nanoseconds>(m_end - m_start)).count();
}
/** Return the total counted time */
double getCumulated() const {
return std::chrono::duration_cast<double_second_time>(m_cumulate).count();
}
/** End the current counter (stop) and return the elapsed time */
double stopAndGetElapsed() {
stop();
return getElapsed();
}
};
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
/// Init functions
////////////////////////////////////////////////////////////
#include <iostream>
#include <memory>
#include <cstdlib>
template <class NumType>
void assertNotSorted(const NumType array[], const size_t size, const std::string log){
for(size_t idx = 1 ; idx < size ; ++idx){
if(array[idx-1] > array[idx]){
std::cout << "assertNotSorted -- Array is not sorted\n"
"assertNotSorted -- - at pos " << idx << "\n"
"assertNotSorted -- - log " << log << std::endl;
}
}
}
template <class NumType>
void assertNotPartitioned(const NumType array[], const size_t size, const NumType pivot,
const size_t limite, const std::string log){
for(size_t idx = 0 ; idx < limite ; ++idx){
if(array[idx] > pivot){
std::cout << "assertNotPartitioned -- Array is not partitioned\n"
"assertNotPartitioned -- - at pos " << idx << "\n"
"assertNotPartitioned -- - log " << log << std::endl;
}
}
for(size_t idx = limite ; idx < size ; ++idx){
if(array[idx] <= pivot){
std::cout << "assertNotPartitioned -- Array is not partitioned\n"
"assertNotPartitioned -- - at pos " << idx << "\n"
"assertNotPartitioned -- - log " << log << std::endl;
}
}
}
template <class NumType>
void assertNotEqual(const NumType array1[], const NumType array2[],
const int size, const std::string log){
for(int idx = 0 ; idx < size ; ++idx){
if(array1[idx] != array2[idx]){
std::cout << "assertNotEqual -- Array is not equal\n"
"assertNotEqual -- - at pos " << idx << "\n"
"assertNotEqual -- - array1 " << array1[idx] << "\n"
"assertNotEqual -- - array2 " << array2[idx] << "\n"
"assertNotEqual -- - log " << log << std::endl;
}
}
}
template <class NumType>
void createRandVecInc(NumType array[], const int size, const NumType starValue = 0){
if(size){
array[0] = starValue + rand()/(RAND_MAX/5);
for(int idx = 1 ; idx < size ; ++idx){
array[idx] = (rand()/(RAND_MAX/5)) + array[idx-1];
}
}
}
template <class NumType>
void createRandVec(NumType array[], const size_t size){
for(size_t idx = 0 ; idx < size ; ++idx){
array[idx] = NumType(drand48()*double(size));
}
}
// To ensure vec is used and to kill extra optimization
template <class NumType>
void useVec(NumType array[], const size_t size){
double all = 0;
for(size_t idx = 0 ; idx < size ; ++idx){
all += double(array[idx]) * 0.000000000001;
}
// This will never happen!
if(all == std::numeric_limits<double>::max()){
std::cout << "The impossible happens!!" << std::endl;
exit(99);
}
}
template <class NumType>
void useVec(std::pair<NumType,NumType> array[], const size_t size){
double all = 0;
for(size_t idx = 0 ; idx < size ; ++idx){
all += double(array[idx].first) * 0.000000000001;
}
// This will never happen!
if(all == std::numeric_limits<double>::max()){
std::cout << "The impossible happens!!" << std::endl;
exit(99);
}
}
////////////////////////////////////////////////////////////
/// Timing functions
////////////////////////////////////////////////////////////
#include <fstream>
const size_t GlobalMaxSize = 3L*1024L*1024L*1024L;
template <class NumType>
void timeAll(std::ostream& fres){
const size_t MaxSize = GlobalMaxSize;//10*1024*1024*1024;262144*8;//
const int NbLoops = 5;
fres << "#size\tstdsort\tstdsortnlogn\tsortSVE\tsortSVEnlogn\tsortSVEspeed";
if(svcntb() == 512/8){
fres << "\tsortSVE512\tsortSVE512nlogn\tsortSVE512speed";
}
fres << "\n";
for(size_t currentSize = 64 ; currentSize <= MaxSize ; currentSize *= 8 ){
std::unique_ptr<NumType[]> array(new NumType[currentSize]);
std::cout << "currentSize " << currentSize << std::endl;
double allTimes[3][3] = {{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. }};
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
std::cout << " idxLoop " << idxLoop << std::endl;
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
dtimer timer;
std::sort(&array[0], &array[currentSize], [&](const NumType& v1, const NumType& v2){
return v1 < v2;
});
timer.stop();
std::cout << " std::sort " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 0;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
dtimer timer;
SortSVE::Sort<NumType, size_t>(array.get(), currentSize);
timer.stop();
std::cout << " SortSVE " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 1;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
if(svcntb() == 512/8){
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
dtimer timer;
SortSVE512::Sort<NumType, size_t>(array.get(), currentSize);
timer.stop();
std::cout << " SortSVE512 " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 2;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
}
std::cout << currentSize << ",\"stdsort\"," << allTimes[0][0] << "," << allTimes[0][1] << "," << allTimes[0][2] << "\n";
std::cout << currentSize << ",\"sortSVE\"," << allTimes[1][0] << "," << allTimes[1][1] << "," << allTimes[1][2] << "\n";
if(svcntb() == 512/8){
std::cout << currentSize << ",\"sortSVE512\"," << allTimes[2][0] << "," << allTimes[2][1] << "," << allTimes[2][2] << "\n";
}
fres << currentSize << "\t"
<< allTimes[0][2] << "\t" << allTimes[0][2]/(currentSize*std::log(currentSize)) << "\t"
<< allTimes[1][2] << "\t" << allTimes[1][2]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0][2]/allTimes[1][2];
if(svcntb() == 512/8){
fres << "\t" << allTimes[2][2] << "\t" << allTimes[2][2]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0][2]/allTimes[2][2];
}
fres << "\n";
}
}
template <class NumType>
void timeAll_pair(std::ostream& fres){
const size_t MaxSize = GlobalMaxSize;//10*1024*1024*1024;262144*8;//
const int NbLoops = 5;
fres << "#size\tstdsort\tstdsortnlogn\tsortSVE\tsortSVEnlogn\tsortSVEspeed\tsortSVEpair\tsortSVEpairnlogn\tsortSVEpairspeed";
if(svcntb() == 512/8){
fres << "\tsortSVE512\tsortSVE512nlogn\tsortSVE512speed";
}
fres << "\n";
for(size_t currentSize = 64 ; currentSize <= MaxSize ; currentSize *= 8 ){
std::cout << "currentSize " << currentSize << std::endl;
double allTimes[4][3] = {{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. }};
{
std::unique_ptr<NumType[]> array(new NumType[currentSize]);
std::unique_ptr<NumType[]> values(new NumType[currentSize]());
std::unique_ptr<std::pair<NumType,NumType>[]> arrayPair(new std::pair<NumType,NumType>[currentSize]());
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
std::cout << " idxLoop " << idxLoop << std::endl;
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
for(size_t idxItem = 0 ; idxItem < currentSize ; ++idxItem){
arrayPair[idxItem].first = array[idxItem];
}
dtimer timer;
std::sort(&arrayPair[0], &arrayPair[currentSize], [&](const std::pair<NumType,NumType>& v1, const std::pair<NumType,NumType>& v2){
return v1.first < v2.first;
});
timer.stop();
std::cout << " std::sort " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 0;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
dtimer timer;
SortSVEkv::Sort<NumType, size_t>(array.get(), values.get(), currentSize);
timer.stop();
std::cout << " sortSVE " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 1;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
for(size_t idxItem = 0 ; idxItem < currentSize ; ++idxItem){
arrayPair[idxItem].first = array[idxItem];
}
dtimer timer;
SortSVEkv::Sort<std::pair<NumType,NumType>, size_t>(arrayPair.get(), currentSize);
timer.stop();
std::cout << " sortSVE " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 2;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
if(svcntb() == 512/8){
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
dtimer timer;
SortSVEkv512::Sort<NumType, size_t>(array.get(), values.get(), currentSize);
timer.stop();
std::cout << " sortSVE512 " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 3;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
}
}
std::cout << currentSize << ",\"stdsort\"," << allTimes[0][0] << "," << allTimes[0][1] << "," << allTimes[0][2] << "\n";
std::cout << currentSize << ",\"sortSVE\"," << allTimes[1][0] << "," << allTimes[1][1] << "," << allTimes[1][2] << "\n";
std::cout << currentSize << ",\"sortSVEpair\"," << allTimes[2][0] << "," << allTimes[2][1] << "," << allTimes[2][2] << "\n";
if(svcntb() == 512/8){
std::cout << currentSize << ",\"sortSVE512\"," << allTimes[3][0] << "," << allTimes[3][1] << "," << allTimes[3][2] << "\n";
}
fres << currentSize << "\t"
<< allTimes[0][2] << "\t" << allTimes[0][2]/(currentSize*std::log(currentSize)) << "\t"
<< allTimes[1][2] << "\t" << allTimes[1][2]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0][2]/allTimes[1][2] << "\t"
<< allTimes[2][2] << "\t" << allTimes[2][2]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0][2]/allTimes[2][2];
if(svcntb() == 512/8){
fres << "\t" << allTimes[3][2] << "\t" << allTimes[3][2]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0][2]/allTimes[3][2];
}
fres << "\n";
}
}
#if defined(_OPENMP)
std::vector<int> GetNbThreadsToTest(){
std::vector<int> nbThreads;
const int maxThreads = omp_get_max_threads();
for(int idx = 1 ; idx <= maxThreads ; idx *= 2){
nbThreads.push_back(idx);
}
if(((maxThreads-1)&maxThreads) != 0){
nbThreads.push_back(maxThreads);
}
return nbThreads;
}
template <class NumType>
void timeAllOmp(std::ostream& fres, const std::string prefix){
const size_t MaxSize = GlobalMaxSize;//10*1024*1024*1024;262144*8;//
const int NbLoops = 5;
const auto nbThreadsToTest = GetNbThreadsToTest();
int nbSize=0;
for(size_t currentSize = 512 ; currentSize <= MaxSize ; currentSize *= 8){
nbSize += 1;
}
const bool full = false;
const int nbAlgo = (svcntb() == 512/8 ? (full?2:1) : 1);
std::vector<double> allTimes(3*nbAlgo*nbThreadsToTest.size()*nbSize);
auto access = [&](int idxSize, int idxThread, int idxType, int res) -> int{
assert(idxSize < nbSize);
assert(idxType < nbAlgo);
assert(res < 3);
assert(idxThread < nbThreadsToTest.size());
assert((((idxSize*nbThreadsToTest.size())+idxThread)*nbAlgo+idxType)*3+res < allTimes.size());
return (((idxSize*nbThreadsToTest.size())+idxThread)*nbAlgo+idxType)*3+res;
};
for(int idxThread = 0; idxThread < nbThreadsToTest.size() ; ++idxThread){
const int nbThreads = nbThreadsToTest[idxThread];
omp_set_num_threads(nbThreads);
int idxSize = 0;
for(size_t currentSize = 512 ; currentSize <= MaxSize ; currentSize *= 8 , idxSize += 1){
std::unique_ptr<NumType[]> array(new NumType[currentSize]);
std::cout << "currentSize " << currentSize << std::endl;
for(int idxType = 0 ; idxType < nbAlgo ; ++idxType){
allTimes[access(idxSize, idxThread, idxType, 0)] = std::numeric_limits<double>::max();
allTimes[access(idxSize, idxThread, idxType, 1)] = std::numeric_limits<double>::min();
allTimes[access(idxSize, idxThread, idxType, 2)] = 0;
}
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
std::cout << " idxLoop " << idxLoop << std::endl;
int idxType = 0;
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
dtimer timer;
SortSVE::SortOmpPartition<NumType, size_t>(array.get(), currentSize);
timer.stop();
std::cout << " SortOmpPartition " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
allTimes[access(idxSize, idxThread, idxType, 0)] = std::min(allTimes[access(idxSize, idxThread, idxType, 0)], timer.getElapsed());
allTimes[access(idxSize, idxThread, idxType, 1)] = std::max(allTimes[access(idxSize, idxThread, idxType, 1)], timer.getElapsed());
allTimes[access(idxSize, idxThread, idxType, 2)] += timer.getElapsed()/double(NbLoops);
idxType += 1;
}
if(svcntb() == 512/8){
if(full){
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
dtimer timer;
SortSVE512::SortOmpPartition<NumType, size_t>(array.get(), currentSize);
timer.stop();
std::cout << " SortOmpPartition512 " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
allTimes[access(idxSize, idxThread, idxType, 0)] = std::min(allTimes[access(idxSize, idxThread, idxType, 0)], timer.getElapsed());
allTimes[access(idxSize, idxThread, idxType, 1)] = std::max(allTimes[access(idxSize, idxThread, idxType, 1)], timer.getElapsed());
allTimes[access(idxSize, idxThread, idxType, 2)] += timer.getElapsed()/double(NbLoops);
idxType += 1;
}
}
}
}
}
const char* labelsfull[8] = {"SortOmpPartition","SortOmpPartition512"};
const char* labelsnotfull[1] = {"SortOmpPartition"};
const char** labels = (full ? labelsfull : labelsnotfull);
fres << "#size";
for(const int nbThreads : nbThreadsToTest){
for(int idxlabel = 0 ; idxlabel < nbAlgo ; ++idxlabel){
fres << "\t" << labels[idxlabel] << nbThreads << "min";
fres << "\t" << labels[idxlabel] << nbThreads << "max";
fres << "\t" << labels[idxlabel] << nbThreads << "avg";
fres << "\t" << labels[idxlabel] << nbThreads << "avgnlogn";
fres << "\t" << labels[idxlabel] << nbThreads << "eff";
}
}
fres << "\n";
int idxSize = 0;
for(size_t currentSize = 512 ; currentSize <= MaxSize ; currentSize *= 8 , idxSize += 1){
fres << currentSize;
for(int idxThread = 0; idxThread < nbThreadsToTest.size() ; ++idxThread){
for(int idxlabel = 0 ; idxlabel < nbAlgo ; ++idxlabel){
for(int idxres = 0 ; idxres < 3 ; ++idxres){
fres << "\t" << allTimes[access(idxSize, idxThread, idxlabel, idxres)];
}
fres << "\t" << (allTimes[access(idxSize, idxThread, idxlabel, 2)]
/(currentSize*std::log(currentSize)));
fres << "\t" << (allTimes[access(idxSize, 0, idxlabel, 2)])
/(allTimes[access(idxSize, idxThread, idxlabel, 2)]);
}
}
fres << "\n";
}
}
#endif
template <class NumType>
void timeSmall(std::ostream& fres){
const size_t MaxSizeV2 = 16*(svcntb()/sizeof(NumType));
const int NbLoops = 2000;
std::unique_ptr<NumType[]> array(new NumType[MaxSizeV2*NbLoops]);
double allTimes[3] = {0};
fres << "#size\tstdsort\tstdsortlogn\tsortSVE\tsortSVElogn\tsortSVEspeed";
if(svcntb() == 512/8){
fres << "\tsortSVE512\tsortSVE512nlogn\tsortSVE512speed";
}
fres << "\n";
for(size_t currentSize = 2 ; currentSize <= MaxSizeV2 ; currentSize++ ){
std::cout << "currentSize " << currentSize << std::endl;
std::cout << " std::sort " << std::endl;
{
srand48((long int)(currentSize));
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
createRandVec(&array[idxLoop*currentSize], currentSize);
}
}
{
dtimer timer;
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
std::sort(&array[idxLoop*currentSize], &array[(idxLoop+1)*currentSize], [&](const NumType& v1, const NumType& v2){
return v1 < v2;
});
}
timer.stop();
std::cout << " std::sort " << timer.getElapsed() << std::endl;
const int idxType = 0;
allTimes[idxType] = timer.getElapsed()/double(NbLoops);
}
std::cout << " newqsSVEbitfull " << std::endl;
{
srand48((long int)(currentSize));
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
createRandVec(&array[idxLoop*currentSize], currentSize);
}
}
{
dtimer timer;
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
SortSVE::SmallSort16V(&array[idxLoop*currentSize], currentSize);
}
timer.stop();
std::cout << " sortSVE " << timer.getElapsed() << std::endl;
const int idxType = 1;
allTimes[idxType] = timer.getElapsed()/double(NbLoops);
}
{
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
}
}
if(svcntb() == 512/8){
std::cout << " newqsSVEbitfull512 " << std::endl;
{
srand48((long int)(currentSize));
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
createRandVec(&array[idxLoop*currentSize], currentSize);
}
}
{
dtimer timer;
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
SortSVE512::SmallSort16V(&array[idxLoop*currentSize], currentSize);
}
timer.stop();
std::cout << " sortSVE512 " << timer.getElapsed() << std::endl;
const int idxType = 2;
allTimes[idxType] = timer.getElapsed()/double(NbLoops);
}
{
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
}
}
}
fres << currentSize << "\t" << allTimes[0] << "\t" <<
allTimes[0]/(currentSize*std::log(currentSize)) << "\t" << allTimes[1] << "\t" <<
allTimes[1]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0]/allTimes[1];
if(svcntb() == 512/8){
fres << "\t" << allTimes[2] << "\t" << allTimes[2]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0]/allTimes[2];
}
fres << "\n";
}
}
template <class NumType>
void timeSmall_pair(std::ostream& fres){
const size_t MaxSizeV2 = 16*(svcntb()/sizeof(NumType));
const int NbLoops = 2000;
std::unique_ptr<NumType[]> array(new NumType[MaxSizeV2*NbLoops]);
std::unique_ptr<NumType[]> indexes(new NumType[MaxSizeV2*NbLoops]());
std::unique_ptr<std::pair<NumType,NumType>[]> arrayPair(new std::pair<NumType,NumType>[MaxSizeV2*NbLoops]());
double allTimes[4] = {0};
fres << "#size\tstdsort\tstdsortlogn\tsortSVE\tsortSVElogn\tsortSVEspeed\tsortSVEpair\tsortSVEpairlogn\ttsortSVEpairspeed";
if(svcntb() == 512/8){
fres << "\tsortSVE512\tsortSVE512nlogn\tsortSVE512speed";
}
fres << "\n";
for(size_t currentSize = 2 ; currentSize <= MaxSizeV2 ; currentSize++ ){
std::cout << "currentSize " << currentSize << std::endl;
std::cout << " std::sort " << std::endl;
{
srand48((long int)(currentSize));
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
createRandVec(&array[idxLoop*currentSize], currentSize);
for(size_t idxItem = 0 ; idxItem < currentSize ; ++idxItem){
arrayPair[idxLoop*currentSize+idxItem].first = array[idxLoop*currentSize+idxItem];
}
}
}
{
dtimer timer;
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
std::sort(&arrayPair[idxLoop*currentSize], &arrayPair[(idxLoop+1)*currentSize], [&](const std::pair<NumType,NumType>& v1, const std::pair<NumType,NumType>& v2){
return v1.first < v2.first;
});
}
timer.stop();
std::cout << " std::sort " << timer.getElapsed() << std::endl;
const int idxType = 0;
allTimes[idxType] = timer.getElapsed()/double(NbLoops);
}
std::cout << " sortSVE " << std::endl;
{
srand48((long int)(currentSize));
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
createRandVec(&array[idxLoop*currentSize], currentSize);
}
}
{
dtimer timer;
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
SortSVEkv::SmallSort16V(&array[idxLoop*currentSize], &indexes[idxLoop*currentSize], currentSize);
}
timer.stop();
std::cout << " sortSVE " << timer.getElapsed() << std::endl;
const int idxType = 1;
allTimes[idxType] = timer.getElapsed()/double(NbLoops);
}
{
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
}
}
std::cout << " sortSVEpair " << std::endl;
{
srand48((long int)(currentSize));
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
createRandVec(&array[idxLoop*currentSize], currentSize);
for(size_t idxItem = 0 ; idxItem < currentSize ; ++idxItem){
arrayPair[idxLoop*currentSize+idxItem].first = array[idxLoop*currentSize+idxItem];
}
}
}
{
dtimer timer;
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
SortSVEkv::SmallSort16V(&arrayPair[idxLoop*currentSize], currentSize);
}
timer.stop();
std::cout << " sortSVEpair " << timer.getElapsed() << std::endl;
const int idxType = 2;
allTimes[idxType] = timer.getElapsed()/double(NbLoops);
}
if(svcntb() == 512/8){
std::cout << " sortSVE512 " << std::endl;
{
srand48((long int)(currentSize));
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
createRandVec(&array[idxLoop*currentSize], currentSize);
}
}
{
dtimer timer;
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
SortSVEkv512::SmallSort16V(&array[idxLoop*currentSize], &indexes[idxLoop*currentSize], currentSize);
}
timer.stop();
std::cout << " sortSVE512 " << timer.getElapsed() << std::endl;
const int idxType = 3;
allTimes[idxType] = timer.getElapsed()/double(NbLoops);
}
{
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
useVec(&array[idxLoop*currentSize], currentSize);
}
}
}
fres << currentSize << "\t" << allTimes[0] << "\t" <<
allTimes[0]/(currentSize*std::log(currentSize)) << "\t" << allTimes[1] << "\t" <<
allTimes[1]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0]/allTimes[1] << "\t" << allTimes[2] << "\t" <<
allTimes[2]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0]/allTimes[2];
if(svcntb() == 512/8){
fres <<"\t" << allTimes[3] << "\t" <<
allTimes[3]/(currentSize*std::log(currentSize)) << "\t" << allTimes[0]/allTimes[3];
}
fres << "\n";
}
}
template <class NumType>
void timePartitionAll(std::ostream& fres){
const size_t MaxSize = GlobalMaxSize;//10*1024*1024*1024;
const int NbLoops = 20;
fres << "#size\tstdpart\tstdpartn\tpartitionSVE\tpartitionSVEn\tpartitionSVEspeed";
fres << "\n";
for(size_t currentSize = 64 ; currentSize <= MaxSize ; currentSize *= 8 ){
std::cout << "currentSize " << currentSize << std::endl;
std::unique_ptr<NumType[]> array(new NumType[currentSize]);
double allTimes[2][3] = {{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. }};
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
std::cout << " idxLoop " << idxLoop << std::endl;
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
const NumType pivot = array[(idxLoop*currentSize/NbLoops)];
dtimer timer;
std::partition(&array[0], &array[currentSize], [&](const NumType& v){
return v < pivot;
});
timer.stop();
std::cout << " std::partition " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 0;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
const NumType pivot = array[(idxLoop*currentSize/NbLoops)];
dtimer timer;
SortSVE::PartitionSVE<size_t>(array.get(), 0, currentSize-1, pivot);
timer.stop();
std::cout << " partitionSVE " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 1;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
}
std::cout << currentSize << ",\"stdpartion\"," << allTimes[0][0] << "," << allTimes[0][1] << "," << allTimes[0][2] << "\n";
std::cout << currentSize << ",\"partitionSVE\"," << allTimes[1][0] << "," << allTimes[1][1] << "," << allTimes[1][2] << "\n";
fres << currentSize << "\t"
<< allTimes[0][2] << "\t" << allTimes[0][2]/(currentSize) << "\t"
<< allTimes[1][2] << "\t" << allTimes[1][2]/(currentSize) << "\t" << allTimes[0][2]/allTimes[1][2] << "\n";
}
}
template <class NumType>
void timePartitionAll_pair(std::ostream& fres){
const size_t MaxSize = GlobalMaxSize;//10*1024*1024*1024;
const int NbLoops = 20;
fres << "#size\tstdpart\tstdpartn\tpartitionSVE\tpartitionSVEn\tpartitionSVEspeed\tpartitionSVEpair\tpartitionSVEpairn\tpartitionSVEpairspeed";
if(svcntb() == 512/8){
fres << "\tpartitionSVE512\tpartitionSVEn512\tpartitionSVEspeed512";
}
fres << "\n";
for(size_t currentSize = 64 ; currentSize <= MaxSize ; currentSize *= 8 ){
std::cout << "currentSize " << currentSize << std::endl;
double allTimes[4][3] = {{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. },
{ std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), 0. }};
{
std::unique_ptr<NumType[]> array(new NumType[currentSize]);
std::unique_ptr<NumType[]> values(new NumType[currentSize]());
std::unique_ptr<std::pair<NumType,NumType>[]> arrayPair(new std::pair<NumType,NumType>[currentSize]());
for(int idxLoop = 0 ; idxLoop < NbLoops ; ++idxLoop){
std::cout << " idxLoop " << idxLoop << std::endl;
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
for(size_t idxItem = 0 ; idxItem < currentSize ; ++idxItem){
arrayPair[idxItem].first = array[idxItem];
}
const NumType pivot = array[(idxLoop*currentSize/NbLoops)];
dtimer timer;
std::partition(&arrayPair[0], &arrayPair[currentSize], [&](const std::pair<NumType,NumType>& v){
return v.first < pivot;
});
timer.stop();
std::cout << " std::partition " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 0;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
const NumType pivot = array[(idxLoop*currentSize/NbLoops)];
dtimer timer;
SortSVEkv::PartitionSVE<size_t>(array.get(), values.get(), 0, currentSize-1, pivot);
timer.stop();
std::cout << " partitionSVE " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 1;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
{
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
for(size_t idxItem = 0 ; idxItem < currentSize ; ++idxItem){
arrayPair[idxItem].first = array[idxItem];
}
const NumType pivot = array[(idxLoop*currentSize/NbLoops)];
dtimer timer;
SortSVEkv::PartitionSVE<size_t>(arrayPair.get(), 0, currentSize-1, pivot);
timer.stop();
std::cout << " partitionSVE " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 2;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
if(svcntb() == 512/8){
srand48((long int)(idxLoop));
createRandVec(array.get(), currentSize);
const NumType pivot = array[(idxLoop*currentSize/NbLoops)];
dtimer timer;
SortSVEkv512::PartitionSVE<size_t>(array.get(), values.get(), 0, currentSize-1, pivot);
timer.stop();
std::cout << " partitionSVE512 " << timer.getElapsed() << std::endl;
useVec(array.get(), currentSize);
const int idxType = 3;
allTimes[idxType][0] = std::min(allTimes[idxType][0], timer.getElapsed());
allTimes[idxType][1] = std::max(allTimes[idxType][1], timer.getElapsed());
allTimes[idxType][2] += timer.getElapsed()/double(NbLoops);
}
}
}
std::cout << currentSize << ",\"stdpartion\"," << allTimes[0][0] << "," << allTimes[0][1] << "," << allTimes[0][2] << "\n";
std::cout << currentSize << ",\"partitionSVEV2\"," << allTimes[1][0] << "," << allTimes[1][1] << "," << allTimes[1][2] << "\n";
std::cout << currentSize << ",\"partitionSVEV2pair\"," << allTimes[1][0] << "," << allTimes[1][1] << "," << allTimes[1][2] << "\n";
if(svcntb() == 512/8){
std::cout << currentSize << ",\"partitionSVEV2512\"," << allTimes[3][0] << "," << allTimes[3][1] << "," << allTimes[3][2] << "\n";
}
fres << currentSize << "\t"
<< allTimes[0][2] << "\t" << allTimes[0][2]/(currentSize) << "\t"
<< allTimes[1][2] << "\t" << allTimes[1][2]/(currentSize) << "\t" << allTimes[0][2]/allTimes[1][2] << "\t"
<< allTimes[2][2] << "\t" << allTimes[2][2]/(currentSize) << "\t" << allTimes[0][2]/allTimes[2][2];
if(svcntb() == 512/8){
fres << "\t" << allTimes[3][2] << "\t" << allTimes[3][2]/(currentSize) << "\t" << allTimes[0][2]/allTimes[3][2];
}
fres << "\n";
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
int main(int argc, char** argv){
if(argc == 2 && strcmp(argv[1], "seq") == 0){
{
std::ofstream fres("smallres-int.data");
timeSmall<int>(fres);
}
{
std::ofstream fres("smallres-double.data");
timeSmall<double>(fres);
}
{
std::ofstream fres("smallres-pair-int.data");
timeSmall_pair<int>(fres);
}
{
std::ofstream fres("partitions-int.data");
timePartitionAll<int>(fres);
}
{
std::ofstream fres("partitions-double.data");
timePartitionAll<double>(fres);
}
{
std::ofstream fres("partitions-pair-int.data");
timePartitionAll_pair<int>(fres);
}
{
std::ofstream fres("res-int.data");
timeAll<int>(fres);
}
{
std::ofstream fres("res-double.data");
timeAll<double>(fres);
}
{
std::ofstream fres("res-pair-int.data");
timeAll_pair<int>(fres);
}
}
#if defined(_OPENMP)
else if(argc == 2 && strcmp(argv[1], "par") == 0){
{
std::ofstream fres("res-int-openmp.data");
timeAllOmp<int>(fres, "max-threads");
}
{
std::ofstream fres("res-double-openmp.data");
timeAllOmp<double>(fres, "max-threads");
}
}
else{
std::cout << "Command should be: " << argv[0] << "[seq|par]\n";
}
#else
else{
std::cout << "OpenMP not found, command should be: " << argv[0] << "[seq]\n";
}
#endif
return 0;
}
| 44.143725 | 220 | 0.504494 | [
"vector"
] |
e1274e772a05dc701a85f020e5e1e001b5695e57 | 1,645 | cpp | C++ | src/xtd.forms/src/xtd/forms/animation.cpp | BaderEddineOuaich/xtd | 6f28634c7949a541d183879d2de18d824ec3c8b1 | [
"MIT"
] | 1 | 2022-02-25T16:53:06.000Z | 2022-02-25T16:53:06.000Z | src/xtd.forms/src/xtd/forms/animation.cpp | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | src/xtd.forms/src/xtd/forms/animation.cpp | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | #include <cmath>
#include "../../../include/xtd/forms/animation.h"
using namespace std;
using namespace xtd;
using namespace xtd::diagnostics;
using namespace xtd::forms;
animation::animation() {
double_buffered(true);
set_can_focus(false);
data_->frames_timer.tick += {*this, &animation::on_frames_timer_tick};
}
drawing::size animation::default_size() const {
return {200, 100};
}
int64_t animation::elapsed_milliseconds() const {
return data_->stopwatch.elapsed_nanoseconds();
}
int32_t animation::frame_counter() const {
return data_->frame_counter;
}
int32_t animation::frames_per_second() const {
return data_->frames_per_second;
}
animation& animation::frames_per_second(int32_t value) {
if (data_->frames_per_second != value) {
data_->frames_per_second = value;
if (!data_->frames_per_second) data_->frames_timer.interval_milliseconds(std::numeric_limits<int32_t>::max());
else data_->frames_timer.interval_milliseconds(static_cast<int32_t>(ceil(1000.0 / data_->frames_per_second)));
}
return *this;
}
bool animation::is_running() const {
return data_->frames_timer.enabled();
}
void animation::start() {
data_->frames_timer.enabled(data_->frames_per_second);
}
void animation::stop() {
data_->frames_timer.enabled(false);
}
void animation::on_updated(const animation_updated_event_args& e) {
updated(*this, e);
}
void animation::on_frames_timer_tick(object& timer, const event_args& e) {
++data_->frame_counter;
on_updated(animation_updated_event_args(data_->frame_counter, data_->stopwatch.elapsed_milliseconds()));
invalidate();
data_->stopwatch = stopwatch::start_new();
}
| 26.532258 | 114 | 0.74772 | [
"object"
] |
e12d4b80ed58e13d39c02c0b3be579725bb348e3 | 278 | hpp | C++ | include/awl/cursor/object_unique_ptr.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/cursor/object_unique_ptr.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | include/awl/cursor/object_unique_ptr.hpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | #ifndef AWL_CURSOR_OBJECT_UNIQUE_PTR_HPP_INCLUDED
#define AWL_CURSOR_OBJECT_UNIQUE_PTR_HPP_INCLUDED
#include <awl/cursor/object_fwd.hpp>
#include <fcppt/unique_ptr_impl.hpp>
namespace awl::cursor
{
using object_unique_ptr = fcppt::unique_ptr<awl::cursor::object>;
}
#endif
| 18.533333 | 65 | 0.820144 | [
"object"
] |
e135f1cd3a2cfc0bad5c113f8d592cff3033e86c | 2,254 | cpp | C++ | cxx/test/test_min_cut.cpp | EQt/graphidx | 9716488cf29f6235072fc920fa1a473bf88e954f | [
"MIT"
] | 4 | 2020-04-03T15:18:30.000Z | 2022-01-06T15:22:48.000Z | cxx/test/test_min_cut.cpp | EQt/graphidx | 9716488cf29f6235072fc920fa1a473bf88e954f | [
"MIT"
] | null | null | null | cxx/test/test_min_cut.cpp | EQt/graphidx | 9716488cf29f6235072fc920fa1a473bf88e954f | [
"MIT"
] | null | null | null | #ifdef HAVE_LEMON
#include <doctest/doctest.h>
#include <iostream>
#include <set>
#include <lemon/throws.hpp>
#include <graphidx/min_cut.hpp>
#ifdef RESTORE_NDEBUG
# define NDEBUG
# undef RESTORE_NDEBUG
#endif
std::set<size_t>
to_set(const std::vector<bool> &v)
{
std::set<size_t> s;
for (size_t i = 0; i < v.size(); i++)
if (v[i])
s.insert(i);
return s;
}
TEST_CASE("min_cut")
{
SUBCASE("wiki1")
{
/*
->(3)\
/10 | \5
(0) |15 >v(2)
\5 v /10
\>(1)
https://en.wikipedia.org/wiki/Maximum_flow_problem#/media/File:MFP1.jpg
*/
const size_t n = 4;
std::vector<IArc<int>> arcs {
{0, 1}, // 5
{0, 3}, // 10
{1, 2}, // 10
{3, 1}, // 15
{3, 2}, // 5
};
double capacities[] = {5, 10, 10, 15, 5};
auto above = min_cut(n, arcs, capacities, 0, 2);
REQUIRE(to_set(above) == std::set<size_t>({0}));
}
SUBCASE("chengw1005")
{
// http://chengw1005.blogspot.com/2015/11/graph-network-flow-problems.html
std::vector<std::tuple<int, int, double>> warcs = {
{0, 2, 13},
{0, 1, 16},
{1, 2, 10},
{1, 3, 12},
{2, 1, 4},
{2, 4, 14},
{3, 2, 9},
{3, 5, 20},
{4, 3, 7},
{4, 5, 4}
};
const int source = 0, target = 5;
const size_t n = 6;
const auto above = min_cut(n, warcs, source, target);
REQUIRE(to_set(above) == std::set<size_t>({0, 1, 2, 4}));
}
SUBCASE("chengw1005:permuted")
{
// http://chengw1005.blogspot.com/2015/11/graph-network-flow-problems.html
std::vector<std::tuple<int, int, double>> warcs = {
{0, 2, 13},
{2, 4, 14},
{1, 2, 10},
{1, 3, 12},
{0, 1, 16},
{2, 1, 4},
{3, 2, 9},
{3, 5, 20},
{4, 3, 7},
{4, 5, 4}
};
const int source = 0, target = 5;
const size_t n = 6;
REQUIRE_THROWS_AS(min_cut(n, warcs, source, target), lemon_assert);
}
}
#endif
| 23.978723 | 82 | 0.440106 | [
"vector"
] |
e1374fee5300e65476e96df91de96663f34bc04f | 48,514 | cpp | C++ | src/tests/test-blas3.cpp | YaccConstructor/clSPARSE | 66b141d69006977cfbe7c34500adff01cf6b4057 | [
"Apache-2.0"
] | null | null | null | src/tests/test-blas3.cpp | YaccConstructor/clSPARSE | 66b141d69006977cfbe7c34500adff01cf6b4057 | [
"Apache-2.0"
] | null | null | null | src/tests/test-blas3.cpp | YaccConstructor/clSPARSE | 66b141d69006977cfbe7c34500adff01cf6b4057 | [
"Apache-2.0"
] | 1 | 2020-10-17T14:02:30.000Z | 2020-10-17T14:02:30.000Z | /* ************************************************************************
* Copyright 2015 Advanced Micro Devices, 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.
* ************************************************************************ */
#if defined(_WIN32)
#define NOMINMAX
#endif
#include <gtest/gtest.h>
#include <vector>
#include <string>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include "resources/clsparse_environment.h"
#include "resources/csr_matrix_environment.h"
#include "resources/sparse_matrix_environment.h"
#include "resources/sparse_bool_matrix_environment.h"
#include "resources/sparse_matrix_fill.hpp"
#include "resources/matrix_utils.h"
//boost ublas
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/operation_sparse.hpp>
//#define _DEBUG_SpMxSpM_ 1 // For debugging where errors are occuring
const float SPGEMM_PREC_ERROR = 0.2f;
const float SPGEMM_REL_ERROR = 0.001f;
clsparseControl ClSparseEnvironment::control = NULL;
cl_command_queue ClSparseEnvironment::queue = NULL;
cl_context ClSparseEnvironment::context = NULL;
static cl_bool explicit_zeroes = true;
namespace po = boost::program_options;
namespace uBLAS = boost::numeric::ublas;
//number of columns in dense B matrix;
cl_int B_num_cols;
cl_double B_values;
template <typename T>
clsparseStatus generateSpGemmResult(clsparseCsrMatrix &sparseMatC)
{
using SPER = CSRSparseEnvironment;
using CLSE = ClSparseEnvironment;
if (typeid(T) == typeid(float))
{
return clsparseScsrSpGemm(&SPER::csrSMatrix, &SPER::csrSMatrix, &sparseMatC, CLSE::control);
}
/*
else if (typeid(T) == typeid(double))
{
return clsparseDcsrSpGemm(SPER::csrSMatrix, SPER::csrSMatrix, sparseMatC, CLSE::control);
}*/
return clsparseSuccess;
} // end
#ifdef TEST_LONG
template <typename T>
clsparseStatus generateSpGemmResult_long(clsparseCsrMatrix &sparseMatC)
{
using SPER = CSRSparseEnvironment;
using CLSE = ClSparseEnvironment;
if (typeid(T) == typeid(float))
{
return clsparseScsrSpGemm(&SPER::csrSMatrixA, &SPER::csrSMatrixB, &sparseMatC, CLSE::control);
}
/*
else if (typeid(T) == typeid(double))
{
return clsparseDcsrSpGemm(SPER::csrSMatrix, SPER::csrSMatrix, sparseMatC, CLSE::control);
}*/
return clsparseSuccess;
} // end
#endif
template <typename T>
class TestCSRSpGeMM : public ::testing::Test
{
using SPER = CSRSparseEnvironment;
using CLSE = ClSparseEnvironment;
public:
void SetUp()
{
clsparseInitCsrMatrix(&csrMatrixC);
}
void TearDown()
{
::clReleaseMemObject(csrMatrixC.values);
::clReleaseMemObject(csrMatrixC.col_indices);
::clReleaseMemObject(csrMatrixC.row_pointer);
clsparseInitCsrMatrix(&csrMatrixC);
} // end
void checkrow_pointer(std::vector<clsparseIdx_t> &amdRowPtr)
{
for (clsparseIdx_t i = 0; i < amdRowPtr.size(); i++)
{
//ASSERT_EQ(amdRowPtr[i], this->C.index1_data()[i]);
//EXPECT_EQ(amdRowPtr[i], this->C.index1_data()[i]);
if (amdRowPtr[i] != this->C.index1_data()[i])
{
this->brow_pointerMisFlag = true;
break;
}
}
} // end
void checkInDense(std::vector<clsparseIdx_t> &amdRowPtr, std::vector<clsparseIdx_t> &amdcol_indices, std::vector<T> &amdVals)
{
uBLAS::mapped_matrix<T> sparseDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);
uBLAS::mapped_matrix<T> boostDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);
// boost sparse_prod cancels out zeros and hence reports more accurately non-zeros
// In clSPARSE, spGeMM produces more non-zeros, and considers some zeros as nonzeros.
// Therefore converting to dense and verifying the output in dense format
// Convert CSR to Dense
for (clsparseIdx_t i = 0; i < amdRowPtr.size() - 1; i++)
{
// i corresponds to row index
for (clsparseIdx_t j = amdRowPtr[i]; j < amdRowPtr[i + 1]; j++)
sparseDense(i, amdcol_indices[j]) = amdVals[j];
}
for (clsparseIdx_t i = 0; i < this->C.index1_data().size() - 1; i++)
{
for (clsparseIdx_t j = this->C.index1_data()[i]; j < this->C.index1_data()[i + 1]; j++)
boostDense(i, this->C.index2_data()[j]) = this->C.value_data()[j];
}
bool brelativeErrorFlag = false;
bool babsErrorFlag = false;
for (clsparseIdx_t i = 0; i < csrMatrixC.num_rows; i++)
{
for (clsparseIdx_t j = 0; j < csrMatrixC.num_cols; j++)
{
//ASSERT_EQ(boostDense(i, j), sparseDense(i, j));
#ifdef _DEBUG_SpMxSpM_
ASSERT_NEAR(boostDense(i, j), sparseDense(i, j), SPGEMM_PREC_ERROR);
#else
if (fabs(boostDense(i, j) - sparseDense(i, j)) > SPGEMM_PREC_ERROR)
{
babsErrorFlag = true;
SCOPED_TRACE("Absolute Error Fail");
break;
}
#endif
}
}
// Relative Error
for (clsparseIdx_t i = 0; i < csrMatrixC.num_rows; i++)
{
for (clsparseIdx_t j = 0; j < csrMatrixC.num_cols; j++)
{
float diff = fabs(boostDense(i, j) - sparseDense(i, j));
float ratio = diff / boostDense(i, j);
#ifdef _DEBUG_SpMxSpM_
// ratio is less than or almost equal to SPGEMM_REL_ERROR
EXPECT_PRED_FORMAT2(::testing::FloatLE, ratio, SPGEMM_REL_ERROR);
#else
if (diff / boostDense(i, j) > SPGEMM_REL_ERROR)
{
brelativeErrorFlag = true;
SCOPED_TRACE("Relative Error Fail");
break;
}
#endif
}
} //
#ifndef _DEBUG_SpMxSpM_
if (brelativeErrorFlag)
{
ASSERT_FALSE(babsErrorFlag);
}
if (babsErrorFlag)
{
ASSERT_FALSE(brelativeErrorFlag);
}
#endif
} // end
typedef typename uBLAS::compressed_matrix<T, uBLAS::row_major, 0, uBLAS::unbounded_array<size_t>> uBlasCSRM;
uBlasCSRM C;
bool brow_pointerMisFlag;
clsparseCsrMatrix csrMatrixC;
}; // End of class TestCSRSpGeMM
//typedef ::testing::Types<float, double> SPGEMMTYPES;
typedef ::testing::Types<float> SPGEMMTYPES;
TYPED_TEST_CASE(TestCSRSpGeMM, SPGEMMTYPES);
// C = A * A; // Square matrices are only supported
TYPED_TEST(TestCSRSpGeMM, square)
{
using SPER = CSRSparseEnvironment;
using CLSE = ClSparseEnvironment;
typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<clsparseIdx_t>> uBlasCSRM;
clsparseEnableAsync(CLSE::control, true);
#ifdef TEST_LONG
clsparseStatus status = generateSpGemmResult_long<TypeParam>(this->csrMatrixC);
#else
clsparseStatus status = generateSpGemmResult<TypeParam>(this->csrMatrixC);
#endif
EXPECT_EQ(clsparseSuccess, status);
clsparseEventResult sparseEvent = clsparseGetEvent(CLSE::control);
EXPECT_EQ(clsparseSuccess, sparseEvent.status);
cl::Event event(sparseEvent.event);
event.wait();
//std::cout << "nrows =" << (this->csrMatrixC).num_rows << std::endl;
//std::cout << "nnz =" << (this->csrMatrixC).num_nonzeros << std::endl;
std::vector<clsparseIdx_t> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
std::vector<clsparseIdx_t> resultcol_indices((this->csrMatrixC).num_nonzeros); // Col Indices
std::vector<TypeParam> resultVals((this->csrMatrixC).num_nonzeros); // Values
this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
(this->C).complete_index1_data();
cl_int cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.values, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(TypeParam),
resultVals.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.col_indices, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(clsparseIdx_t), resultcol_indices.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.row_pointer, CL_TRUE, 0,
((this->csrMatrixC).num_rows + 1) * sizeof(clsparseIdx_t), resultRowPtr.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
std::cout << "Done with GPU" << std::endl;
#ifdef TEST_LONG
// Generate referencee result from ublas
if (typeid(TypeParam) == typeid(float))
{
this->C = uBLAS::sparse_prod(SPER::ublasSCsrA, SPER::ublasSCsrB, this->C);
}
#else
if (typeid(TypeParam) == typeid(float))
{
this->C = uBLAS::sparse_prod(SPER::ublasSCsr, SPER::ublasSCsr, this->C);
}
#endif
/*
if (typeid(TypeParam) == typeid(double))
{
this->C = uBLAS::sparse_prod(SPER::ublasDCsr, SPER::ublasDCsr, this->C);;
}*/
/*
for (int i = 0; i < resultRowPtr.size(); i++)
{
ASSERT_EQ(resultRowPtr[i], this->C.index1_data()[i]);
}*/
this->brow_pointerMisFlag = false;
this->checkrow_pointer(resultRowPtr);
//if (::testing::Test::HasFailure())
if (this->brow_pointerMisFlag == true)
{
// Check the values in Dense format
this->checkInDense(resultRowPtr, resultcol_indices, resultVals);
}
else
{
/* Check Col Indices */
for (clsparseIdx_t i = 0; i < resultcol_indices.size(); i++)
{
ASSERT_EQ(resultcol_indices[i], this->C.index2_data()[i]);
}
/* Check Values */
for (clsparseIdx_t i = 0; i < resultVals.size(); i++)
{
//TODO: how to define the tolerance
ASSERT_NEAR(resultVals[i], this->C.value_data()[i], 0.1);
}
ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());
//Rest of the col_indices should be zero
for (size_t i = resultcol_indices.size(); i < this->C.index2_data().size(); i++)
{
ASSERT_EQ(0, this->C.index2_data()[i]);
}
// Rest of the values should be zero
for (size_t i = resultVals.size(); i < this->C.value_data().size(); i++)
{
ASSERT_EQ(0, this->C.value_data()[i]);
}
}
} //end TestCSRSpGeMM: square
// C = A * A; // A is filled with random powers of 2
TYPED_TEST(TestCSRSpGeMM, Powersof2)
{
using SPER = CSRSparseEnvironment;
using CLSE = ClSparseEnvironment;
typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<clsparseIdx_t>> uBlasCSRM;
clsparseEnableAsync(CLSE::control, true);
clsparse_matrix_fill<float> objFillVals(42, -14, 14);
std::vector<float> tmpArray;
tmpArray.resize(SPER::csrSMatrix.num_nonzeros);
//objFillVals.fillMtxTwoPowers(tmpArray.data(), tmpArray.size());
objFillVals.fillMtxOnes(tmpArray.data(), tmpArray.size());
// Fill ublas scr with the same matrix values
for (size_t i = 0; i < tmpArray.size(); i++)
{
SPER::ublasSCsr.value_data()[i] = tmpArray[i];
}
// Copy host to the device
cl_int cl_status = clEnqueueWriteBuffer(CLSE::queue, SPER::csrSMatrix.values, CL_TRUE, 0, sizeof(float) * tmpArray.size(),
tmpArray.data(), 0, nullptr, nullptr);
EXPECT_EQ(CL_SUCCESS, cl_status);
tmpArray.clear();
clsparseStatus status = generateSpGemmResult<TypeParam>(this->csrMatrixC);
EXPECT_EQ(clsparseSuccess, status);
clsparseEventResult sparseEvent = clsparseGetEvent(CLSE::control);
EXPECT_EQ(clsparseSuccess, sparseEvent.status);
cl::Event event(sparseEvent.event);
event.wait();
std::vector<clsparseIdx_t> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
std::vector<clsparseIdx_t> resultcol_indices((this->csrMatrixC).num_nonzeros); // Col Indices
std::vector<TypeParam> resultVals((this->csrMatrixC).num_nonzeros); // Values
this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
(this->C).complete_index1_data();
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.values, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(TypeParam),
resultVals.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.col_indices, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(clsparseIdx_t), resultcol_indices.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.row_pointer, CL_TRUE, 0,
((this->csrMatrixC).num_rows + 1) * sizeof(clsparseIdx_t), resultRowPtr.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
std::cout << "Done with GPU" << std::endl;
if (typeid(TypeParam) == typeid(float))
{
this->C = uBLAS::sparse_prod(SPER::ublasSCsr, SPER::ublasSCsr, this->C);
}
this->brow_pointerMisFlag = false;
this->checkrow_pointer(resultRowPtr);
//if (::testing::Test::HasFailure())
if (this->brow_pointerMisFlag == true)
{
// Check the values in Dense format
this->checkInDense(resultRowPtr, resultcol_indices, resultVals);
}
else
{
/* Check Col Indices */
for (clsparseIdx_t i = 0; i < resultcol_indices.size(); i++)
{
ASSERT_EQ(resultcol_indices[i], this->C.index2_data()[i]);
}
/* Check Values */
for (clsparseIdx_t i = 0; i < resultVals.size(); i++)
{
//TODO: how to define the tolerance
ASSERT_NEAR(resultVals[i], this->C.value_data()[i], 0.0);
}
ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());
//Rest of the col_indices should be zero
for (clsparseIdx_t i = resultcol_indices.size(); i < this->C.index2_data().size(); i++)
{
ASSERT_EQ(0, this->C.index2_data()[i]);
}
// Rest of the values should be zero
for (clsparseIdx_t i = resultVals.size(); i < this->C.value_data().size(); i++)
{
ASSERT_EQ(0, this->C.value_data()[i]);
}
}
} //end TestCSRSpGeMM: Powersof2
clsparseStatus generateBoolSpGemmResult(clsparseBoolCsrMatrix &sparseMatC)
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
return clsparseBoolScsrSpGemm(&CSRBoolE::csrSMatrix, &CSRBoolE::csrSMatrix, &sparseMatC, CLSE::control);
} // end
class TestCSRBoolSpGeMM : public ::testing::Test
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
public:
void SetUp()
{
clsparseInitBoolCsrMatrix(&csrMatrixC);
}
void TearDown()
{
::clReleaseMemObject(csrMatrixC.col_indices);
::clReleaseMemObject(csrMatrixC.row_pointer);
clsparseInitBoolCsrMatrix(&csrMatrixC);
} // end
void checkrow_pointer(std::vector<clsparseIdx_t> &amdRowPtr)
{
for (clsparseIdx_t i = 0; i < amdRowPtr.size(); i++)
{
//ASSERT_EQ(amdRowPtr[i], this->C.index1_data()[i]);
//EXPECT_EQ(amdRowPtr[i], this->C.index1_data()[i]);
if (amdRowPtr[i] != this->C.index1_data()[i])
{
this->brow_pointerMisFlag = true;
break;
}
}
} // end
void checkInDense(std::vector<clsparseIdx_t> &amdRowPtr, std::vector<clsparseIdx_t> &amdcol_indices)
{
uBLAS::mapped_matrix<int> sparseDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);
uBLAS::mapped_matrix<int> boostDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);
// boost sparse_prod cancels out zeros and hence reports more accurately non-zeros
// In clSPARSE, spGeMM produces more non-zeros, and considers some zeros as nonzeros.
// Therefore converting to dense and verifying the output in dense format
// Convert CSR to Dense
for (clsparseIdx_t i = 0; i < amdRowPtr.size() - 1; i++)
{
// i corresponds to row index
for (clsparseIdx_t j = amdRowPtr[i]; j < amdRowPtr[i + 1]; j++) {
std::cout << "sp " << i << " " << amdcol_indices[j] << std::endl;
sparseDense(i, amdcol_indices[j]) = 1;
}
}
for (clsparseIdx_t i = 0; i < this->C.index1_data().size() - 1; i++)
{
for (clsparseIdx_t j = this->C.index1_data()[i]; j < this->C.index1_data()[i + 1]; j++) {
std::cout << "den " << i << " " << this->C.index2_data()[j] << std::endl;
boostDense(i, this->C.index2_data()[j]) = 1;
}
}
bool brelativeErrorFlag = false;
bool babsErrorFlag = false;
for (clsparseIdx_t i = 0; i < csrMatrixC.num_rows; i++)
{
for (clsparseIdx_t j = 0; j < csrMatrixC.num_cols; j++)
{
//ASSERT_EQ(boostDense(i, j), sparseDense(i, j));
#ifdef _DEBUG_SpMxSpM_
ASSERT_NEAR(boostDense(i, j), sparseDense(i, j), SPGEMM_PREC_ERROR);
#else
if (sparseDense(i, j) xor (abs(boostDense(i, j)) > SPGEMM_PREC_ERROR))
{
std::cout << "ERROR IN " << i << " " << j << " VALUES " << sparseDense(i, j) << " " << (abs(boostDense(i, j)) > SPGEMM_PREC_ERROR) << std::endl;
babsErrorFlag = true;
SCOPED_TRACE("Absolute Error Fail");
// break;
}
#endif
}
}
// Relative Error
for (clsparseIdx_t i = 0; i < csrMatrixC.num_rows; i++)
{
for (clsparseIdx_t j = 0; j < csrMatrixC.num_cols; j++)
{
float diff = fabs(boostDense(i, j) - sparseDense(i, j));
float ratio = diff / boostDense(i, j);
#ifdef _DEBUG_SpMxSpM_
// ratio is less than or almost equal to SPGEMM_REL_ERROR
EXPECT_PRED_FORMAT2(::testing::FloatLE, ratio, SPGEMM_REL_ERROR);
#else
if (diff / boostDense(i, j) > SPGEMM_REL_ERROR)
{
brelativeErrorFlag = true;
SCOPED_TRACE("Relative Error Fail");
break;
}
#endif
}
} //
#ifndef _DEBUG_SpMxSpM_
if (brelativeErrorFlag)
{
ASSERT_FALSE(babsErrorFlag);
}
if (babsErrorFlag)
{
ASSERT_FALSE(brelativeErrorFlag);
}
#endif
} // end
typedef typename uBLAS::compressed_matrix<int, uBLAS::row_major, 0, uBLAS::unbounded_array<size_t>> uBlasCSRM;
uBlasCSRM C;
bool brow_pointerMisFlag;
clsparseBoolCsrMatrix csrMatrixC;
}; // End of class TestCSRBoolSpGeMM
// //typedef ::testing::Types<float, double> SPGEMMTYPES;
// typedef ::testing::Types<float> SPGEMMTYPES;
// TYPED_TEST_CASE(TestCSRSpGeMM, SPGEMMTYPES);
// // C = A * A; // Square matrices are only supported
TEST_F(TestCSRBoolSpGeMM, square)
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<clsparseIdx_t>> uBlasCSRM;
clsparseEnableAsync(CLSE::control, true);
clsparseStatus status = generateBoolSpGemmResult(this->csrMatrixC);
EXPECT_EQ(clsparseSuccess, status);
clsparseEventResult sparseEvent = clsparseGetEvent(CLSE::control);
EXPECT_EQ(clsparseSuccess, sparseEvent.status);
cl::Event event(sparseEvent.event);
event.wait();
//std::cout << "nrows =" << (this->csrMatrixC).num_rows << std::endl;
//std::cout << "nnz =" << (this->csrMatrixC).num_nonzeros << std::endl;
std::vector<clsparseIdx_t> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
std::vector<clsparseIdx_t> resultcol_indices((this->csrMatrixC).num_nonzeros); // Col Indices
this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
(this->C).complete_index1_data();
cl_int cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.col_indices, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(clsparseIdx_t), resultcol_indices.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.row_pointer, CL_TRUE, 0,
((this->csrMatrixC).num_rows + 1) * sizeof(clsparseIdx_t), resultRowPtr.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
std::cout << "Done with GPU" << std::endl;
this->C = uBLAS::sparse_prod(CSRBoolE::ublasSCsr, CSRBoolE::ublasSCsr, this->C);
this->brow_pointerMisFlag = false;
this->checkrow_pointer(resultRowPtr);
//if (::testing::Test::HasFailure())
if (this->brow_pointerMisFlag == true)
{
// Check the values in Dense format
this->checkInDense(resultRowPtr, resultcol_indices);
}
else
{
/* Check Col Indices */
for (clsparseIdx_t i = 0; i < resultcol_indices.size(); i++)
{
ASSERT_EQ(resultcol_indices[i], this->C.index2_data()[i]);
}
ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());
//Rest of the col_indices should be zero
for (size_t i = resultcol_indices.size(); i < this->C.index2_data().size(); i++)
{
ASSERT_EQ(0, this->C.index2_data()[i]);
}
}
} //end TestCSRBoolSpGeMM: square
// C = A * A; // A is filled with random powers of 2
TEST_F(TestCSRBoolSpGeMM, Powersof2)
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<clsparseIdx_t> > uBlasCSRM;
clsparseEnableAsync(CLSE::control, true);
clsparse_matrix_fill<float> objFillVals(42, -14, 14);
std::vector<float> tmpArray;
tmpArray.resize(CSRBoolE::csrSMatrix.num_nonzeros);
//objFillVals.fillMtxTwoPowers(tmpArray.data(), tmpArray.size());
objFillVals.fillMtxOnes(tmpArray.data(), tmpArray.size());
// Fill ublas scr with the same matrix values
for (size_t i = 0; i < tmpArray.size(); i++)
{
CSRBoolE::ublasSCsr.value_data()[i] = tmpArray[i];
}
tmpArray.clear();
clsparseStatus status = generateBoolSpGemmResult(this->csrMatrixC);
EXPECT_EQ(clsparseSuccess, status);
clsparseEventResult sparseEvent = clsparseGetEvent( CLSE::control );
EXPECT_EQ( clsparseSuccess, sparseEvent.status );
cl::Event event(sparseEvent.event);
event.wait( );
std::vector<clsparseIdx_t> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
std::vector<clsparseIdx_t> resultcol_indices((this->csrMatrixC).num_nonzeros); // Col Indices
this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
(this->C).complete_index1_data();
cl_int cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.col_indices, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(clsparseIdx_t), resultcol_indices.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.row_pointer, CL_TRUE, 0,
((this->csrMatrixC).num_rows + 1) * sizeof(clsparseIdx_t), resultRowPtr.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
std::cout << "Done with GPU" << std::endl;
this->C = uBLAS::sparse_prod(CSRBoolE::ublasSCsr, CSRBoolE::ublasSCsr, this->C);
this->brow_pointerMisFlag = false;
this->checkrow_pointer(resultRowPtr);
//if (::testing::Test::HasFailure())
if (this->brow_pointerMisFlag == true)
{
// Check the values in Dense format
this->checkInDense(resultRowPtr, resultcol_indices);
}
else
{
/* Check Col Indices */
for (clsparseIdx_t i = 0; i < resultcol_indices.size(); i++)
{
ASSERT_EQ(resultcol_indices[i], this->C.index2_data()[i]);
}
ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());
//Rest of the col_indices should be zero
for (clsparseIdx_t i = resultcol_indices.size(); i < this->C.index2_data().size(); i++)
{
ASSERT_EQ(0, this->C.index2_data()[i]);
}
}
}//end TestCSRBoolSpGeMM: Powersof2
clsparseStatus generateBoolElemAddResult(clsparseBoolCsrMatrix &sparseMatC)
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
return clsparseBoolScsrElemAdd(&CSRBoolE::csrSMatrix, &CSRBoolE::csrSMatrix, &sparseMatC, CLSE::control);
} // end
class TestCSRBoolElemAdd : public ::testing::Test
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
public:
typedef typename uBLAS::compressed_matrix<int, uBLAS::row_major, 0, uBLAS::unbounded_array<size_t>> uBlasCSRM;
uBlasCSRM C;
bool brow_pointerMisFlag;
clsparseBoolCsrMatrix csrMatrixC;
void SetUp()
{
clsparseInitBoolCsrMatrix(&csrMatrixC);
}
void TearDown()
{
::clReleaseMemObject(csrMatrixC.col_indices);
::clReleaseMemObject(csrMatrixC.row_pointer);
clsparseInitBoolCsrMatrix(&csrMatrixC);
} // end
void checkrow_pointer(std::vector<clsparseIdx_t> &amdRowPtr)
{
for (clsparseIdx_t i = 0; i < amdRowPtr.size(); i++)
{
//ASSERT_EQ(amdRowPtr[i], this->C.index1_data()[i]);
//EXPECT_EQ(amdRowPtr[i], this->C.index1_data()[i]);
if (amdRowPtr[i] != this->C.index1_data()[i])
{
this->brow_pointerMisFlag = true;
break;
}
}
} // end
void cpuElemAdd(uBlasCSRM A, uBlasCSRM B, uBlasCSRM &C)
{
std::vector<int> row_ptr_C;
std::vector<int> cols_C;
row_ptr_C.push_back(0);
for (int i = 1; i < A.index1_data().size(); i++)
{
int start_A = A.index1_data()[i - 1];
int end_A = A.index1_data()[i];
int start_B = B.index1_data()[i - 1];
int end_B = B.index1_data()[i];
std::cout << "INDICES " << start_A << " " << start_B << " " << end_A << " " << end_B << std::endl;
std::vector<int> dst;
std::merge(
A.index2_data().begin() + start_A,
A.index2_data().begin() + end_A,
B.index2_data().begin() + start_B,
B.index2_data().begin() + end_B,
std::back_inserter(dst)
);
dst.erase(std::unique(dst.begin(), dst.end()), dst.end());
row_ptr_C.push_back(row_ptr_C[i - 1] + dst.size());
cols_C.insert(cols_C.end(), dst.begin(), dst.end());
dst.clear();
}
for (int r = 0; r < row_ptr_C.size(); r++) {
for (int j = row_ptr_C[r]; j < row_ptr_C[r + 1]; j++) {
std::cout << "INSERT " << r << " " << cols_C[j] << std::endl;
C.insert_element(r, cols_C[j], 1);
}
}
}
void checkInDense(std::vector<clsparseIdx_t> &amdRowPtr, std::vector<clsparseIdx_t> &amdcol_indices)
{
uBLAS::mapped_matrix<int> sparseDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);
uBLAS::mapped_matrix<int> boostDense(csrMatrixC.num_rows, csrMatrixC.num_cols, 0);
// Convert CSR to Dense
for (clsparseIdx_t i = 0; i < amdRowPtr.size() - 1; i++)
{
// i corresponds to row index
for (clsparseIdx_t j = amdRowPtr[i]; j < amdRowPtr[i + 1]; j++) {
std::cout << "sp " << i << " " << amdcol_indices[j] << std::endl;
sparseDense(i, amdcol_indices[j]) = 1;
}
}
for (clsparseIdx_t i = 0; i < this->C.index1_data().size() - 1; i++)
{
for (clsparseIdx_t j = this->C.index1_data()[i]; j < this->C.index1_data()[i + 1]; j++) {
std::cout << "den " << i << " " << this->C.index2_data()[j] << std::endl;
boostDense(i, this->C.index2_data()[j]) = 1;
}
}
bool brelativeErrorFlag = false;
bool babsErrorFlag = false;
for (clsparseIdx_t i = 0; i < csrMatrixC.num_rows; i++)
{
for (clsparseIdx_t j = 0; j < csrMatrixC.num_cols; j++)
{
//ASSERT_EQ(boostDense(i, j), sparseDense(i, j));
#ifdef _DEBUG_SpMxSpM_
ASSERT_NEAR(boostDense(i, j), sparseDense(i, j), SPGEMM_PREC_ERROR);
#else
if (sparseDense(i, j) xor (abs(boostDense(i, j)) > SPGEMM_PREC_ERROR))
{
std::cout << "ERROR IN " << i << " " << j << " VALUES " << sparseDense(i, j) << " " << (abs(boostDense(i, j)) > SPGEMM_PREC_ERROR) << std::endl;
babsErrorFlag = true;
SCOPED_TRACE("Absolute Error Fail");
// break;
}
#endif
}
}
// Relative Error
for (clsparseIdx_t i = 0; i < csrMatrixC.num_rows; i++)
{
for (clsparseIdx_t j = 0; j < csrMatrixC.num_cols; j++)
{
float diff = fabs(boostDense(i, j) - sparseDense(i, j));
float ratio = diff / boostDense(i, j);
#ifdef _DEBUG_SpMxSpM_
// ratio is less than or almost equal to SPGEMM_REL_ERROR
EXPECT_PRED_FORMAT2(::testing::FloatLE, ratio, SPGEMM_REL_ERROR);
#else
if (diff / boostDense(i, j) > SPGEMM_REL_ERROR)
{
brelativeErrorFlag = true;
SCOPED_TRACE("Relative Error Fail");
break;
}
#endif
}
} //
#ifndef _DEBUG_SpMxSpM_
if (brelativeErrorFlag)
{
ASSERT_FALSE(babsErrorFlag);
}
if (babsErrorFlag)
{
ASSERT_FALSE(brelativeErrorFlag);
}
#endif
} // end
}; // End of class TestCSRBoolElemAdd
// //typedef ::testing::Types<float, double> SPGEMMTYPES;
// typedef ::testing::Types<float> SPGEMMTYPES;
// TYPED_TEST_CASE(TestCSRSpGeMM, SPGEMMTYPES);
// // C = A * A; // Square matrices are only supported
TEST_F(TestCSRBoolElemAdd, square)
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<clsparseIdx_t>> uBlasCSRM;
clsparseEnableAsync(CLSE::control, true);
clsparseStatus status = generateBoolElemAddResult(this->csrMatrixC);
EXPECT_EQ(clsparseSuccess, status);
clsparseEventResult sparseEvent = clsparseGetEvent(CLSE::control);
EXPECT_EQ(clsparseSuccess, sparseEvent.status);
cl::Event event(sparseEvent.event);
event.wait();
//std::cout << "nrows =" << (this->csrMatrixC).num_rows << std::endl;
//std::cout << "nnz =" << (this->csrMatrixC).num_nonzeros << std::endl;
std::vector<clsparseIdx_t> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
std::vector<clsparseIdx_t> resultcol_indices((this->csrMatrixC).num_nonzeros); // Col Indices
this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
(this->C).complete_index1_data();
cl_int cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.col_indices, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(clsparseIdx_t), resultcol_indices.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.row_pointer, CL_TRUE, 0,
((this->csrMatrixC).num_rows + 1) * sizeof(clsparseIdx_t), resultRowPtr.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
std::cout << "Done with GPU" << std::endl;
// this->C = uBLAS::sparse_prod(CSRBoolE::ublasSCsr, CSRBoolE::ublasSCsr, this->C);
cpuElemAdd(CSRBoolE::ublasSCsr, CSRBoolE::ublasSCsr, this->C);
this->brow_pointerMisFlag = false;
this->checkrow_pointer(resultRowPtr);
//if (::testing::Test::HasFailure())
if (this->brow_pointerMisFlag == true)
{
// Check the values in Dense format
this->checkInDense(resultRowPtr, resultcol_indices);
}
else
{
/* Check Col Indices */
for (clsparseIdx_t i = 0; i < resultcol_indices.size(); i++)
{
ASSERT_EQ(resultcol_indices[i], this->C.index2_data()[i]);
}
ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());
//Rest of the col_indices should be zero
for (size_t i = resultcol_indices.size(); i < this->C.index2_data().size(); i++)
{
ASSERT_EQ(0, this->C.index2_data()[i]);
}
}
} //end TestCSRBoolElemAdd: square
// C = A * A; // A is filled with random powers of 2
TEST_F(TestCSRBoolElemAdd, Powersof2)
{
using CSRBoolE = CSRSparseBoolEnvironment;
using CLSE = ClSparseEnvironment;
typedef typename uBLAS::compressed_matrix<float, uBLAS::row_major, 0, uBLAS::unbounded_array<clsparseIdx_t> > uBlasCSRM;
clsparseEnableAsync(CLSE::control, true);
clsparse_matrix_fill<float> objFillVals(42, -14, 14);
std::vector<float> tmpArray;
tmpArray.resize(CSRBoolE::csrSMatrix.num_nonzeros);
//objFillVals.fillMtxTwoPowers(tmpArray.data(), tmpArray.size());
objFillVals.fillMtxOnes(tmpArray.data(), tmpArray.size());
// Fill ublas scr with the same matrix values
for (size_t i = 0; i < tmpArray.size(); i++)
{
CSRBoolE::ublasSCsr.value_data()[i] = tmpArray[i];
}
tmpArray.clear();
clsparseStatus status = generateBoolElemAddResult(this->csrMatrixC);
EXPECT_EQ(clsparseSuccess, status);
clsparseEventResult sparseEvent = clsparseGetEvent( CLSE::control );
EXPECT_EQ( clsparseSuccess, sparseEvent.status );
cl::Event event(sparseEvent.event);
event.wait( );
std::vector<clsparseIdx_t> resultRowPtr((this->csrMatrixC).num_rows + 1); // Get row ptr of Output CSR matrix
std::vector<clsparseIdx_t> resultcol_indices((this->csrMatrixC).num_nonzeros); // Col Indices
this->C = uBlasCSRM((this->csrMatrixC).num_rows, (this->csrMatrixC).num_cols, (this->csrMatrixC).num_nonzeros);
(this->C).complete_index1_data();
cl_int cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.col_indices, CL_TRUE, 0,
(this->csrMatrixC).num_nonzeros * sizeof(clsparseIdx_t), resultcol_indices.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
cl_status = clEnqueueReadBuffer(CLSE::queue,
this->csrMatrixC.row_pointer, CL_TRUE, 0,
((this->csrMatrixC).num_rows + 1) * sizeof(clsparseIdx_t), resultRowPtr.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
std::cout << "Done with GPU" << std::endl;
// this->C = uBLAS::sparse_prod(CSRBoolE::ublasSCsr, CSRBoolE::ublasSCsr, this->C);
cpuElemAdd(CSRBoolE::ublasSCsr, CSRBoolE::ublasSCsr, this->C);
this->brow_pointerMisFlag = false;
this->checkrow_pointer(resultRowPtr);
//if (::testing::Test::HasFailure())
if (this->brow_pointerMisFlag == true)
{
// Check the values in Dense format
this->checkInDense(resultRowPtr, resultcol_indices);
}
else
{
/* Check Col Indices */
for (clsparseIdx_t i = 0; i < resultcol_indices.size(); i++)
{
ASSERT_EQ(resultcol_indices[i], this->C.index2_data()[i]);
}
ASSERT_EQ(resultRowPtr.size(), this->C.index1_data().size());
//Rest of the col_indices should be zero
for (clsparseIdx_t i = resultcol_indices.size(); i < this->C.index2_data().size(); i++)
{
ASSERT_EQ(0, this->C.index2_data()[i]);
}
}
}//end TestCSRBoolElemAdd: Powersof2
template <typename T>
clsparseStatus generateResult(cldenseMatrix &matB, clsparseScalar &alpha,
cldenseMatrix &matC, clsparseScalar &beta)
{
using CSRE = CSREnvironment;
using CLSE = ClSparseEnvironment;
if (typeid(T) == typeid(float))
{
return clsparseScsrmm(&alpha, &CSRE::csrSMatrix, &matB,
&beta, &matC, CLSE::control);
}
if (typeid(T) == typeid(double))
{
return clsparseDcsrmm(&alpha, &CSRE::csrDMatrix, &matB,
&beta, &matC, CLSE::control);
}
return clsparseSuccess;
}
template <typename T>
class TestCSRMM : public ::testing::Test
{
using CSRE = CSREnvironment;
using CLSE = ClSparseEnvironment;
public:
void SetUp()
{
// alpha and beta scalars are not yet supported in generating reference result;
alpha = T(CSRE::alpha);
beta = T(CSRE::beta);
B = uBLASDenseM(CSRE::n_cols, B_num_cols, T(B_values));
C = uBLASDenseM(CSRE::n_rows, B_num_cols, T(0));
cl_int status;
cldenseInitMatrix(&deviceMatB);
deviceMatB.values = clCreateBuffer(CLSE::context,
CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
B.data().size() * sizeof(T), B.data().begin(), &status);
deviceMatB.num_rows = B.size1();
deviceMatB.num_cols = B.size2();
deviceMatB.lead_dim = std::min(B.size1(), B.size2());
ASSERT_EQ(CL_SUCCESS, status);
cldenseInitMatrix(&deviceMatC);
deviceMatC.values = clCreateBuffer(CLSE::context,
CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
C.data().size() * sizeof(T), C.data().begin(), &status);
deviceMatC.num_rows = C.size1();
deviceMatC.num_cols = C.size2();
deviceMatC.lead_dim = std::min(C.size1(), C.size2());
ASSERT_EQ(CL_SUCCESS, status);
clsparseInitScalar(&gAlpha);
gAlpha.value = clCreateBuffer(CLSE::context,
CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(T), &alpha, &status);
ASSERT_EQ(CL_SUCCESS, status);
clsparseInitScalar(&gBeta);
gBeta.value = clCreateBuffer(CLSE::context,
CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(T), &beta, &status);
ASSERT_EQ(CL_SUCCESS, status);
}
void TearDown()
{
::clReleaseMemObject(gAlpha.value);
::clReleaseMemObject(gBeta.value);
clsparseInitScalar(&gAlpha);
clsparseInitScalar(&gBeta);
::clReleaseMemObject(deviceMatB.values);
::clReleaseMemObject(deviceMatC.values);
cldenseInitMatrix(&deviceMatB);
cldenseInitMatrix(&deviceMatC);
}
typedef typename uBLAS::matrix<T, uBLAS::row_major, uBLAS::unbounded_array<T>> uBLASDenseM;
uBLASDenseM B;
uBLASDenseM C;
cldenseMatrix deviceMatB;
cldenseMatrix deviceMatC;
T alpha;
T beta;
clsparseScalar gAlpha;
clsparseScalar gBeta;
};
typedef ::testing::Types<float, double> TYPES;
//typedef ::testing::Types<float> TYPES;
TYPED_TEST_CASE(TestCSRMM, TYPES);
// This test may give you false failure result due to multiplication order.
TYPED_TEST(TestCSRMM, multiply)
{
using CSRE = CSREnvironment;
using CLSE = ClSparseEnvironment;
clsparseEnableAsync(CLSE::control, true);
//control object is global and it is updated here;
clsparseStatus status =
generateResult<TypeParam>(this->deviceMatB, this->gAlpha,
this->deviceMatC, this->gBeta);
EXPECT_EQ(clsparseSuccess, status);
clsparseEventResult sparseEvent = clsparseGetEvent(CLSE::control);
EXPECT_EQ(clsparseSuccess, sparseEvent.status);
cl::Event event(sparseEvent.event);
event.wait();
std::vector<TypeParam> result(this->C.data().size());
cl_int cl_status = clEnqueueReadBuffer(CLSE::queue,
this->deviceMatC.values, CL_TRUE, 0,
result.size() * sizeof(TypeParam),
result.data(), 0, NULL, NULL);
EXPECT_EQ(CL_SUCCESS, cl_status);
// Generate referencee result;
if (typeid(TypeParam) == typeid(float))
{
this->C = uBLAS::sparse_prod(CSRE::ublasSCsr, this->B, this->C, false);
}
if (typeid(TypeParam) == typeid(double))
{
this->C = uBLAS::sparse_prod(CSRE::ublasDCsr, this->B, this->C, false);
}
if (typeid(TypeParam) == typeid(float))
for (clsparseIdx_t l = 0; l < std::min(this->C.size1(), this->C.size2()); l++)
for (clsparseIdx_t i = 0; i < this->C.data().size(); i++)
{
ASSERT_NEAR(this->C.data()[i], result[i], 5e-3);
}
if (typeid(TypeParam) == typeid(double))
for (clsparseIdx_t l = 0; l < std::min(this->C.size1(), this->C.size2()); l++)
for (clsparseIdx_t i = 0; i < this->C.data().size(); i++)
{
ASSERT_NEAR(this->C.data()[i], result[i], 5e-10);
};
}
int main(int argc, char *argv[])
{
using CLSE = ClSparseEnvironment;
using CSRE = CSREnvironment;
using SPER = CSRSparseEnvironment;
using CSRBoolE = CSRSparseBoolEnvironment;
//pass path to matrix as an argument, We can switch to boost po later
std::string path;
std::string function;
double alpha;
double beta;
std::string platform;
cl_platform_type pID;
cl_uint dID;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce this message.")
("path,p", po::value(&path)->required(), "Path to matrix in mtx format.")
("function,f", po::value<std::string>(&function)->default_value("SpMdM"), "Sparse functions to test. Options: SpMdM, SpMSpM, All")
("platform,l", po::value(&platform)->default_value("AMD"),
"OpenCL platform: AMD, NVIDIA or INTEL.")
("device,d", po::value(&dID)->default_value(0),
"Device id within platform.")
("alpha,a", po::value(&alpha)->default_value(1.0),
"Alpha parameter for eq: \n\ty = alpha * M * x + beta * y")
("beta,b", po::value(&beta)->default_value(0.0),
"Beta parameter for eq: \n\ty = alpha * M * x + beta * y")
("cols,c", po::value(&B_num_cols)->default_value(8),
"Number of columns in B matrix while calculating sp_A * d_B = d_C")
("vals,v", po::value(&B_values)->default_value(1.0),
"Initial value of B columns")
("no_zeroes,z", po::bool_switch()->default_value(false),
"Disable reading explicit zeroes from the input matrix market file.");
// Parse the command line options, ignore unrecognized options and collect them into a vector of strings
// Googletest itself accepts command line flags that we wish to pass further on
po::variables_map vm;
po::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
try
{
po::store(parsed, vm);
if (vm.count("help"))
{
std::cout << desc << std::endl;
return 0;
}
po::notify(vm);
}
catch (po::error &error)
{
std::cerr << "Parsing command line options..." << std::endl;
std::cerr << "Error: " << error.what() << std::endl;
std::cerr << desc << std::endl;
return false;
}
std::vector<std::string> to_pass_further = po::collect_unrecognized(parsed.options, po::include_positional);
//check platform
if (vm.count("platform"))
{
if ("AMD" == platform)
{
pID = AMD;
}
else if ("NVIDIA" == platform)
{
pID = NVIDIA;
}
else if ("INTEL" == platform)
{
pID = INTEL;
}
else
{
std::cout << "The platform option is missing or is ill defined!\n";
std::cout << "Given [" << platform << "]" << std::endl;
platform = "AMD";
pID = AMD;
std::cout << "Setting [" << platform << "] as default" << std::endl;
}
}
if (vm["no_zeroes"].as<bool>())
explicit_zeroes = false;
if (boost::iequals(function, "SpMdM"))
{
std::cout << "SpMdM Testing \n";
::testing::GTEST_FLAG(filter) = "*TestCSRMM*";
//::testing::GTEST_FLAG(list_tests) = true;
::testing::InitGoogleTest(&argc, argv);
//order does matter!
::testing::AddGlobalTestEnvironment(new CLSE(pID, dID));
::testing::AddGlobalTestEnvironment(new CSRE(path, alpha, beta,
CLSE::queue, CLSE::context, explicit_zeroes));
}
else if (boost::iequals(function, "SpMSpM"))
{
std::cout << "SpMSpM Testing \n";
::testing::GTEST_FLAG(filter) = "*TestCSRSpGeMM*";
//::testing::GTEST_FLAG(list_tests) = true;
::testing::InitGoogleTest(&argc, argv);
::testing::AddGlobalTestEnvironment(new CLSE(pID, dID));
::testing::AddGlobalTestEnvironment(new SPER(path, CLSE::queue, CLSE::context, explicit_zeroes));
}
else if (boost::iequals(function, "Bool"))
{
std::cout << "Bool operations testing \n";
::testing::GTEST_FLAG(filter) = "*TestCSRBool*";
//::testing::GTEST_FLAG(list_tests) = true;
::testing::InitGoogleTest(&argc, argv);
::testing::AddGlobalTestEnvironment(new CLSE(pID, dID));
::testing::AddGlobalTestEnvironment(new CSRBoolE(path, CLSE::queue, CLSE::context, explicit_zeroes));
}
else if (boost::iequals(function, "All"))
{
::testing::InitGoogleTest(&argc, argv);
//order does matter!
::testing::AddGlobalTestEnvironment(new CLSE(pID, dID));
::testing::AddGlobalTestEnvironment(new CSRE(path, alpha, beta,
CLSE::queue, CLSE::context, explicit_zeroes));
::testing::AddGlobalTestEnvironment(new SPER(path, CLSE::queue, CLSE::context, explicit_zeroes));
::testing::AddGlobalTestEnvironment(new CSRBoolE(path, CLSE::queue, CLSE::context, explicit_zeroes));
}
else
{
std::cerr << " unknown Level3 function" << std::endl;
return -1;
}
return RUN_ALL_TESTS();
} // end
| 35.489393 | 164 | 0.600981 | [
"object",
"vector"
] |
e137c348ec6c75790b35462234f749e344e27ea9 | 2,414 | cpp | C++ | UVa/11947 - Cancer or Scorpio.cpp | 2019331099-Rabbi/Online-Judges-Problems-Solution | b42fe9bcc18bbe4ebeaf1af1df30883dd438acd2 | [
"MIT"
] | null | null | null | UVa/11947 - Cancer or Scorpio.cpp | 2019331099-Rabbi/Online-Judges-Problems-Solution | b42fe9bcc18bbe4ebeaf1af1df30883dd438acd2 | [
"MIT"
] | null | null | null | UVa/11947 - Cancer or Scorpio.cpp | 2019331099-Rabbi/Online-Judges-Problems-Solution | b42fe9bcc18bbe4ebeaf1af1df30883dd438acd2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define endl '\n'
#define sz 280
#define RUN_FAST ios::sync_with_stdio(false);
using namespace std;
vector <vector <string>> zods(13, vector <string>(32));
int day[]={0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
void preset()
{
int i;
string s="aquarius";
for (i=21; i<32; i++) zods[1][i]=s;
for (i=1; i<20; i++) zods[2][i]=s;
s="pisces";
for (i=20; i<32; i++) zods[2][i]=s;
for (i=1; i<21; i++) zods[3][i]=s;
s="aries";
for (i=21; i<32; i++) zods[3][i]=s;
for (i=1; i<21; i++) zods[4][i]=s;
s="taurus";
for (i=21; i<32; i++) zods[4][i]=s;
for (i=1; i<22; i++) zods[5][i]=s;
s="gemini";
for (i=22; i<32; i++) zods[5][i]=s;
for (i=1; i<22; i++) zods[6][i]=s;
s="cancer";
for (i=22; i<32; i++) zods[6][i]=s;
for (i=1; i<23; i++) zods[7][i]=s;
s="leo";
for (i=23; i<32; i++) zods[7][i]=s;
for (i=1; i<22; i++) zods[8][i]=s;
s="virgo";
for (i=22; i<32; i++) zods[8][i]=s;
for (i=1; i<24; i++) zods[9][i]=s;
s="libra";
for (i=24; i<32; i++) zods[9][i]=s;
for (i=1; i<24; i++) zods[10][i]=s;
s="scorpio";
for (i=24; i<32; i++) zods[10][i]=s;
for (i=1; i<23; i++) zods[11][i]=s;
s="sagittarius";
for (i=23; i<32; i++) zods[11][i]=s;
for (i=1; i<23; i++) zods[12][i]=s;
s="capricorn";
for (i=23; i<32; i++) zods[12][i]=s;
for (i=1; i<21; i++) zods[1][i]=s;
}
bool isleap(int y)
{
return ((!(y%4) && y%100) || !(y%400));
}
int main()
{
RUN_FAST; cin.tie(nullptr);
preset();
int T, t, d, m, y, i;
string s, tmps;
cin >> T;
for (t=1; t<=T; t++) {
cin >> s;
tmps="";
tmps+=s[0], tmps+=s[1];
m=stoi(tmps);
tmps="";
tmps+=s[2], tmps+=s[3];
d=stoi(tmps);
tmps="";
tmps+=s[4], tmps+=s[5], tmps+=s[6], tmps+=s[7];
y=stoi(tmps);
day[2]=28;
if (isleap(y)) day[2]=29;
for (i=0; i<sz; i++) {
d++;
if (d>day[m]) {
d=1, m++;
if (m>12) {
m=1, y++;
day[2]=isleap(y)?29:28;
}
}
}
cout << t << ' ';
if (m<10) cout << '0';
cout << m << '/';
if (d<10) cout << '0';
cout << d << '/';
cout << y << ' ' << zods[m][d] << endl;
}
return 0;
}
| 24.886598 | 62 | 0.405965 | [
"vector"
] |
e14370423247069cec777276af5250412243437a | 13,981 | cpp | C++ | source/code/programs/examples/glut/worms/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/programs/examples/glut/worms/main.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/programs/examples/glut/worms/main.cpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #if 0
From jallen@cs.hmc.edu Fri Feb 17 00:49:59 1995
Received: from giraffe.asd.sgi.com by hoot.asd.sgi.com via SMTP (940816.SGI.8.6.9/940406.SGI.AUTO)
for <mjk@hoot.asd.sgi.com> id AAA13591; Fri, 17 Feb 1995 00:49:33 -0800
Received: from sgi.sgi.com by giraffe.asd.sgi.com via SMTP (920330.SGI/920502.SGI)
for mjk@hoot.asd.sgi.com id AA09774; Fri, 17 Feb 95 00:52:30 -0800
Received: from cs.hmc.edu by sgi.sgi.com via SMTP (950215.405.SGI.8.6.10/910110.SGI)
for <mjk@sgi.com> id AAA06439; Fri, 17 Feb 1995 00:52:28 -0800
Received: by cs.hmc.edu (5.0/SMI-SVR4)
id AA13309; Fri, 17 Feb 1995 00:52:10 -0800
Date: Fri, 17 Feb 1995 00:52:10 -0800
From: jallen@cs.hmc.edu (Jeff R. Allen)
Message-Id: <9502170852.AA13309@cs.hmc.edu>
To: nate@cs.hmc.edu (Nathan Tuck), mjk@sgi.sgi.com, hadas@cs.hmc.edu
Subject: Re: GLUT demos
In-Reply-To: <9502100805.AA08487@cs.hmc.edu>
References: <9502100805.AA08487@cs.hmc.edu>
Reply-To: Jeff Allen <jeff@hmc.edu>
Content-Length: 12851
Status: RO
Below is a program I wrote for the Graphics class at Harvey Mudd. As
the comments explain, I am currently working on a version in 3D with
lighting, and a pre-programmed camera flight-path. I also added a
checker-board-type-thing for the worms to crawl around on, so that
there is some reference for the viewer.
For now, here is the program.
--
Jeff R. Allen | Senior CS major | Support your local
(fnord) | South 351d, x4940 | unicyclist!
------------------------- begin worms.c -------------------------
#endif
/* worms.c -- demos OpenGL in 2D using the GLUT interface to the
underlying window system.
Compile with: [g]cc -O3 -o worms worms.c -lm -lGLU -lglut -lXmu -lX11 -lGL
This is a fun little demo that actually makes very little use of
OpenGL and GLUT. It generates a bunch of worms and animates them as
they crawl around your screen. When you click in the screen with
the left mouse button, the worms converge on the spot for a while,
then go back to their business. The animation is incredibly simple:
we erase the tail, then draw a new head, repeatedly. It is so
simple, actually, we don't even need double-buffering!
The behavior of the worms can be controlled via the compile-time
constants below. Enterprising indiviuals wil want to add GLUT menus
to control these constants at run time. This is left as an exercise
to the reader. The only thing that can currently be controlled is
wether or not the worms are filled. Use the right button to get a popup
menu.
A future version of this program will make more use of OpenGL by
rendering 3d worms crawling in 3-space (or possibly just around on
a plane) and it will allow the user to manipulate the viewpoint
using the mouse. This will require double-buffering and less
optimal updates.
This program is Copyright 1995 by Jeff R. Allen <jeff@hmc.edu>.
Permission is hereby granted to use and modify this code freely,
provided it is not sold or redistibuted in any way for profit. This
is copyrighted material, and is NOT in the Public Domain.
$Id: worms.c,v 1.2 1995/02/17 03:29:59 jallen Exp $
*/
#include <math.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <string.h>
#include <GL/glut.h>
#ifdef WIN32
#define drand48() (((float) rand())/((float) RAND_MAX))
#define srand48(x) (srand((x)))
#endif
/* Some <math.h> files do not define M_PI... */
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
/* operational constants */
#define RADIAN .0174532
#define CIRCLE_POINTS 25
#define SIDETOLERANCE .01
#define INITH 500
#define INITW 500
/* worm options */
#define SEGMENTS 20
#define SEG_RADIUS 0.01
#define STEPSIZE 0.01
#define MAXTURN (20 * RADIAN) /* in radians */
#define MAXWORMS 400
#define INITWORMS 40
#define MARKTICKS 100
typedef struct worm_s {
float dir; /* direction in radians */
float segx[SEGMENTS]; /* location of segments. */
float segy[SEGMENTS];
GLfloat *color; /* pointer to the RGB color of the worm */
int head; /* which elt of seg[xy] is currently head */
/* the tail is always (head+1 % SEGMENTS) */
} worm_t;
/* colors available for worms... this is a huge mess because I
originally brought these colors in from rgb.txt as integers,
but they have to be normalized into floats. And C is stupid
and truncates them unless I add the annoying .0's
*/
const GLfloat colors[][3] = {
{ 255.0/255.0, 0.0/255.0, 0.0/255.0},
{ 238.0/255.0, 0.0/255.0, 0.0/255.0},
{ 205.0/255.0, 0.0/255.0, 0.0/255.0},
{ 0.0/255.0, 255.0/255.0, 0.0/255.0},
{ 0.0/255.0, 238.0/255.0, 0.0/255.0},
{ 0.0/255.0, 205.0/255.0, 0.0/255.0},
{ 0.0/255.0, 0.0/255.0, 255.0/255.0},
{ 0.0/255.0, 0.0/255.0, 238.0/255.0},
{ 0.0/255.0, 0.0/255.0, 205.0/255.0},
{ 255.0/255.0, 255.0/255.0, 0.0/255.0},
{ 238.0/255.0, 238.0/255.0, 0.0/255.0},
{ 205.0/255.0, 205.0/255.0, 0.0/255.0},
{ 0.0/255.0, 255.0/255.0, 255.0/255.0},
{ 0.0/255.0, 238.0/255.0, 238.0/255.0},
{ 0.0/255.0, 205.0/255.0, 205.0/255.0},
{ 255.0/255.0, 0.0/255.0, 255.0/255.0},
{ 238.0/255.0, 0.0/255.0, 238.0/255.0},
{ 205.0/255.0, 0.0/255.0, 205.0/255.0},
};
#define COLORS 18
/* define's for the menu item numbers */
#define MENU_NULL 0
#define MENU_FILLED 1
#define MENU_UNFILLED 2
#define MENU_QUIT 3
/* flag to determine how to draw worms; set by popup menu -- starts out
filled in
*/
int filled = 1;
/* the global worm array */
worm_t worms[MAXWORMS];
int curworms = 0;
/* global window extent variables */
GLfloat gleft = -1.0, gright = 1.0, gtop = 1.0, gbottom = -1.0;
GLint wsize, hsize;
/* globals for marking */
float markx, marky;
int marktime;
/* prototypes */
void mydisplay(void);
void drawCircle(float x0, float y0, float radius)
{
int i;
float angle;
/* a table of offsets for a circle (used in drawCircle) */
static float circlex[CIRCLE_POINTS];
static float circley[CIRCLE_POINTS];
static int inited = 0;
if (! inited) {
for (i = 0; i < CIRCLE_POINTS; i++) {
angle = 2.0 * M_PI * i / CIRCLE_POINTS;
circlex[i] = cos(angle);
circley[i] = sin(angle);
}
inited++;
};
if (filled)
glBegin(GL_POLYGON);
else
glBegin(GL_LINE_LOOP);
for(i = 0; i < CIRCLE_POINTS; i++)
glVertex2f((radius * circlex[i]) + x0, (radius * circley[i]) + y0);
glEnd();
return;
}
void drawWorm(worm_t *theworm)
{
int i;
glColor3fv(theworm->color);
for (i = 0; i < SEGMENTS; i++)
drawCircle(theworm->segx[i], theworm->segy[i], SEG_RADIUS);
return;
}
void myinit(void)
{
int i, j, thecolor;
float thedir;
srand48(time(NULL));
curworms = INITWORMS;
for (j = 0; j < curworms; j++) {
/* divide the circle up into a number of pieces, and send one worm
each direction.
*/
worms[j].dir = ((2.0 * M_PI) / curworms) * j;
thedir = worms[j].dir;
worms[j].segx[0] = 0.0;
worms[j].segy[0] = 0.0;
for (i = 1; i < SEGMENTS; i++) {
worms[j].segx[i] = worms[j].segx[i-1] + (STEPSIZE * cos(thedir));
worms[j].segy[i] = worms[j].segx[i-1] + (STEPSIZE * sin(thedir));
};
worms[j].head = (SEGMENTS - 1);
/* make this worm one of the predefined colors */
thecolor = (int) COLORS * drand48();
worms[j].color = (GLfloat *) colors[thecolor];
};
/* now that they are all set, draw them as though they have just been
uncovered
*/
mydisplay();
}
/* this routine is called after the coordinates are changed to make sure
worms outside the window come back into view right away. (This behavior
is arbitrary, but they are my worms, and they'll do what I please!)
*/
void warpWorms(void)
{
int j, head;
for (j = 0; j < curworms; j++) {
head = worms[j].head;
if (worms[j].segx[head] < gleft)
worms[j].segx[head] = gleft;
if (worms[j].segx[head] > gright)
worms[j].segx[head] = gright;
if (worms[j].segx[head] > gtop)
worms[j].segx[head] = gtop;
if (worms[j].segx[head] < gbottom)
worms[j].segx[head] = gbottom;
}
}
/* a bunch of extra hoopla goes on here to change the Global coordinate
space at teh same rate that the window itself changes. This give the
worms more space to play in when the window gets bigger, and vice versa.
The alternative would be to end up with big worms when the window gets
big, and that looks silly.
*/
void myreshape (GLsizei w, GLsizei h)
{
float ratiow = (float) w/INITW;
float ratioh = (float) h/INITH;
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gleft = -1 * ratiow;
gright = 1 * ratiow;
gbottom = -1 * ratioh;
gtop = 1 * ratioh;
gluOrtho2D(gleft, gright, gbottom, gtop);
warpWorms();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
wsize = w; hsize = h;
return;
}
/* given a pointer to a worm, this routine will decide on the next
place to put a head and will advance the head pointer
*/
void updateWorm(worm_t *theworm)
{
int newhead;
float prevx, prevy;
float newh = -1, newv = -1;
float num, denom;
/* make an easy to reference local copy of head, and update it in
the worm structure. The new head replaces the old tail.
*/
newhead = (theworm->head + 1) % SEGMENTS;
prevx = theworm->segx[theworm->head];
prevy = theworm->segy[theworm->head];
/* if there is a mark, home in on it. After this, we still allow
the random adjustment so that the worms play around a bit on the
way to the mark.
*/
if (marktime) {
num = marky - prevy;
denom = markx - prevx;
theworm->dir = atan2(num,denom);
};
/* make a bit of a turn: between -MAXTURN and MAXTURN degrees change
to dir (actualy theworm->dir is in radians for later use with
cosf().
*/
theworm->dir += (MAXTURN - (2 * MAXTURN * (float) drand48()));
theworm->segx[newhead] = prevx + (STEPSIZE * cos(theworm->dir));
theworm->segy[newhead] = prevy + (STEPSIZE * sin(theworm->dir));
/* if we are at an edge, change direction so that we are heading away
from the edge in question. There might be a problem here handling
corner cases, but I have never seen a worm get stuck, so what the
heck...
*/
if (theworm->segx[newhead] <= gleft)
theworm->dir = 0;
if (theworm->segx[newhead] >= gright)
theworm->dir = (180 * RADIAN);
if (theworm->segy[newhead] >= gtop)
theworm->dir = (270 * RADIAN);
if (theworm->segy[newhead] <= gbottom)
theworm->dir = (90 * RADIAN);
if ((newv >= 0) || (newh >= 0)) {
newh = (newh<0) ? 0 : newh;
newv = (newv<0) ? 0 : newv;
};
/* update the permanent copy of the new head index */
theworm->head = newhead;
}
/* updates the worms -- drawing takes place here, which may actually
be a bad idea. It will probably be better to update the internal
state only here, then post a redisplay using GLUT.
*/
void myidle (void)
{
int i, tail;
if (marktime)
marktime--;
for (i = 0; i < curworms; i++) {
/* first find tail */
tail = (worms[i].head + 1) % SEGMENTS;
/* erase tail */
glColor3f(0.0, 0.0, 0.0);
drawCircle(worms[i].segx[tail], worms[i].segy[tail], SEG_RADIUS);
/* update head segment position and head pointer */
updateWorm(&worms[i]);
/* draw head */
glColor3fv(worms[i].color);
drawCircle(worms[i].segx[worms[i].head], worms[i].segy[worms[i].head],
SEG_RADIUS);
};
glFlush();
return;
}
/* redraws the worms from scratch -- called after a window gets obscured */
void mydisplay(void)
{
int i;
#ifndef WORMS_EAT_BACKGROUND
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
#endif
for (i = 0; i < curworms; i++)
drawWorm(&worms[i]);
glFlush();
return;
}
/* this routine gets called when the mouse is clicked. The incoming
coordinates are in screen coordinates relative to the upper-left corner
of the window, and oriented according to X, not to GL. So, here we
convert the given coordinates into worm-world coordinates, and set the
mark.
*/
void markSpot(int x, int y)
{
/* map into the corridinate space I am using */
markx = (float)((x - wsize/2)*(gright - gleft)/wsize);
marky = -(float)((y - hsize/2)*(gtop - gbottom)/hsize);
marktime = MARKTICKS;
}
void handleMouse(int btn, int state, int x, int y)
{
switch (btn) {
case (GLUT_LEFT_BUTTON):
if (state == GLUT_UP)
markSpot(x,y);
break;
default:
/* do nothing */
break;
}
return;
}
void menuSelect(int value)
{
switch (value) {
case MENU_FILLED:
filled = 1;
break;
case MENU_UNFILLED:
filled = 0;
break;
case MENU_QUIT:
exit(0);
break;
case MENU_NULL:
return;
default:
break;
};
glutPostRedisplay();
return;
}
void visibility(int status)
{
if (status == GLUT_VISIBLE)
glutIdleFunc(myidle);
else
glutIdleFunc(NULL);
}
/* this is where GLUT is initialized, and the whole thing starts up.
All animation and redisplay happens via the callbacks registered below.
*/
int main(int argc, char **argv)
{
int fillmenu = 0;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(INITW, INITH);
glutCreateWindow("Worms");
myinit();
glutDisplayFunc(mydisplay);
glutVisibilityFunc(visibility);
glutReshapeFunc(myreshape);
glutMouseFunc(handleMouse);
/* popup menu, courtsey of GLUT */
fillmenu = glutCreateMenu(menuSelect);
glutAddMenuEntry("Filled", MENU_FILLED);
glutAddMenuEntry("Unfilled", MENU_UNFILLED);
glutCreateMenu(menuSelect);
glutAddMenuEntry(" WORMS", MENU_NULL);
glutAddSubMenu("Drawing Mode", fillmenu);
glutAddMenuEntry("Quit", MENU_QUIT);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
return 0;
}
| 26.938343 | 98 | 0.645519 | [
"3d"
] |
e14919265b6e680de159d1cbdc67ac464e2d5295 | 2,494 | hxx | C++ | odb-examples-2.4.0/schema/custom/employee.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-examples-2.4.0/schema/custom/employee.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-examples-2.4.0/schema/custom/employee.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | // file : schema/custom/employee.hxx
// copyright : not copyrighted - public domain
#ifndef EMPLOYEE_HXX
#define EMPLOYEE_HXX
#include <vector>
#include <string>
#include <odb/core.hxx>
// Include TR1 <memory> header in a compiler-specific fashion. Fall back
// on the Boost implementation if the compiler does not support TR1.
//
#include <odb/tr1/memory.hxx>
using std::tr1::shared_ptr;
typedef std::vector<std::string> degrees;
#pragma db value
class name
{
public:
name (const std::string& first, const std::string& last)
: first_ (first), last_ (last)
{
}
const std::string&
first () const
{
return first_;
}
const std::string&
last () const
{
return last_;
}
private:
friend class odb::access;
#pragma db type("VARCHAR(255)") column("first_name")
std::string first_;
#pragma db type("VARCHAR(255)") column("last_name")
std::string last_;
};
#pragma db object table("Employer")
class employer
{
public:
employer (const std::string& name)
: name_ (name)
{
}
const std::string&
name () const
{
return name_;
}
private:
friend class odb::access;
employer () {}
#pragma db id type("VARCHAR(255)") column("name")
std::string name_;
};
#pragma db object table("Employee")
class employee
{
public:
typedef ::employer employer_type;
employee (unsigned long id,
const std::string& first,
const std::string& last,
shared_ptr<employer_type> employer)
: id_ (id), name_ (first, last), employer_ (employer)
{
}
// Name.
//
typedef ::name name_type;
const name_type&
name () const
{
return name_;
}
// Degrees.
//
typedef ::degrees degrees_type;
const degrees_type&
degrees () const
{
return degrees_;
}
degrees_type&
degrees ()
{
return degrees_;
}
// Employer.
//
shared_ptr<employer_type>
employer () const
{
return employer_;
}
void
employer (shared_ptr<employer_type> employer)
{
employer_ = employer;
}
private:
friend class odb::access;
employee (): name_ ("", "") {}
#pragma db id type("INTEGER") column("ssn")
unsigned long id_;
#pragma db column("") // No column prefix.
name_type name_;
#pragma db unordered table("EmployeeDegree") id_column("ssn") \
value_type("VARCHAR(255)") value_column("degree")
degrees_type degrees_;
#pragma db not_null column("employer")
shared_ptr<employer_type> employer_;
};
#endif // EMPLOYEE_HXX
| 16.626667 | 72 | 0.646351 | [
"object",
"vector"
] |
e14c384aba8f2f727188ca166d47da219666a7d1 | 52,363 | cc | C++ | chrome/browser/ui/global_media_controls/media_notification_service_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/ui/global_media_controls/media_notification_service_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/ui/global_media_controls/media_notification_service_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/global_media_controls/media_notification_service.h"
#include <memory>
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/unguessable_token.h"
#include "build/build_config.h"
#include "chrome/browser/media/router/chrome_media_router_factory.h"
#include "chrome/browser/media/router/media_router_feature.h"
#include "chrome/browser/ui/global_media_controls/cast_media_notification_producer.h"
#include "chrome/browser/ui/global_media_controls/media_dialog_delegate.h"
#include "chrome/browser/ui/global_media_controls/media_notification_service_observer.h"
#include "chrome/browser/ui/global_media_controls/media_session_notification_producer.h"
#include "chrome/browser/ui/global_media_controls/overlay_media_notification.h"
#include "chrome/browser/ui/global_media_controls/test_helper.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/media_message_center/media_notification_item.h"
#include "components/media_message_center/media_notification_util.h"
#include "components/media_message_center/media_session_notification_item.h"
#include "components/media_router/browser/presentation/start_presentation_context.h"
#include "components/media_router/browser/test/mock_media_router.h"
#include "content/public/browser/media_session.h"
#include "content/public/test/browser_task_environment.h"
#include "media/base/media_switches.h"
#include "services/media_session/public/mojom/audio_focus.mojom.h"
#include "services/media_session/public/mojom/media_session.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using media_router::MediaRoute;
using media_session::mojom::AudioFocusRequestState;
using media_session::mojom::AudioFocusRequestStatePtr;
using media_session::mojom::MediaSessionInfo;
using media_session::mojom::MediaSessionInfoPtr;
using testing::_;
using testing::AtLeast;
using testing::Expectation;
using testing::Return;
namespace {
class MockMediaNotificationServiceObserver
: public MediaNotificationServiceObserver {
public:
MockMediaNotificationServiceObserver() = default;
MockMediaNotificationServiceObserver(
const MockMediaNotificationServiceObserver&) = delete;
MockMediaNotificationServiceObserver& operator=(
const MockMediaNotificationServiceObserver&) = delete;
~MockMediaNotificationServiceObserver() override = default;
// MediaNotificationServiceObserver implementation.
MOCK_METHOD(void, OnNotificationListChanged, ());
MOCK_METHOD(void, OnMediaDialogOpened, ());
MOCK_METHOD(void, OnMediaDialogClosed, ());
};
class MockOverlayMediaNotification : public OverlayMediaNotification {
public:
MockOverlayMediaNotification() = default;
MockOverlayMediaNotification(const MockOverlayMediaNotification&) = delete;
MockOverlayMediaNotification& operator=(const MockOverlayMediaNotification&) =
delete;
~MockOverlayMediaNotification() override = default;
OverlayMediaNotificationsManager* manager() { return manager_; }
// MockOverlayMediaNotification implementation.
void SetManager(OverlayMediaNotificationsManager* manager) {
manager_ = manager;
SetManagerProxy(manager);
}
MOCK_METHOD0(ShowNotification, void());
MOCK_METHOD0(CloseNotification, void());
// Use a proxy so we can add expectations on it while also storing the
// manager for future use.
MOCK_METHOD1(SetManagerProxy,
void(OverlayMediaNotificationsManager* manager));
private:
OverlayMediaNotificationsManager* manager_ = nullptr;
};
class MockWebContentsPresentationManager
: public media_router::WebContentsPresentationManager {
public:
void NotifyMediaRoutesChanged(
const std::vector<media_router::MediaRoute>& routes) {
for (auto& observer : observers_) {
observer.OnMediaRoutesChanged(routes);
}
}
void AddObserver(media_router::WebContentsPresentationManager::Observer*
observer) override {
observers_.AddObserver(observer);
}
void RemoveObserver(media_router::WebContentsPresentationManager::Observer*
observer) override {
observers_.RemoveObserver(observer);
}
MOCK_CONST_METHOD0(HasDefaultPresentationRequest, bool());
MOCK_CONST_METHOD0(GetDefaultPresentationRequest,
const content::PresentationRequest&());
MOCK_METHOD3(OnPresentationResponse,
void(const content::PresentationRequest&,
media_router::mojom::RoutePresentationConnectionPtr,
const media_router::RouteRequestResult&));
MOCK_METHOD0(GetMediaRoutes, std::vector<media_router::MediaRoute>());
base::WeakPtr<WebContentsPresentationManager> GetWeakPtr() override {
return weak_factory_.GetWeakPtr();
}
private:
base::ObserverList<media_router::WebContentsPresentationManager::Observer>
observers_;
base::WeakPtrFactory<MockWebContentsPresentationManager> weak_factory_{this};
};
} // anonymous namespace
class MediaNotificationServiceTest : public ChromeRenderViewHostTestHarness {
public:
MediaNotificationServiceTest()
: ChromeRenderViewHostTestHarness(
base::test::TaskEnvironment::TimeSource::MOCK_TIME,
base::test::TaskEnvironment::MainThreadType::UI) {}
~MediaNotificationServiceTest() override = default;
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
media_router::ChromeMediaRouterFactory::GetInstance()->SetTestingFactory(
profile(), base::BindRepeating(&media_router::MockMediaRouter::Create));
service_ = std::make_unique<MediaNotificationService>(profile(), false);
service_->AddObserver(&observer_);
}
void TearDown() override {
service_.reset();
ChromeRenderViewHostTestHarness::TearDown();
}
protected:
void AdvanceClockMilliseconds(int milliseconds) {
task_environment()->FastForwardBy(
base::TimeDelta::FromMilliseconds(milliseconds));
}
void AdvanceClockMinutes(int minutes) {
AdvanceClockMilliseconds(1000 * 60 * minutes);
}
base::UnguessableToken SimulatePlayingControllableMedia() {
return SimulatePlayingControllableMedia(base::UnguessableToken::Create());
}
base::UnguessableToken SimulatePlayingControllableMedia(
base::UnguessableToken id) {
SimulateFocusGained(id, true);
SimulateNecessaryMetadata(id);
return id;
}
base::UnguessableToken SimulatePlayingControllableMediaForWebContents(
content::WebContents* contents) {
content::MediaSession::Get(contents);
auto id = content::MediaSession::GetRequestIdFromWebContents(contents);
SimulatePlayingControllableMedia(id);
return id;
}
AudioFocusRequestStatePtr CreateFocusRequest(const base::UnguessableToken& id,
bool controllable) {
MediaSessionInfoPtr session_info(MediaSessionInfo::New());
session_info->is_controllable = controllable;
AudioFocusRequestStatePtr focus(AudioFocusRequestState::New());
focus->request_id = id;
focus->session_info = std::move(session_info);
return focus;
}
void SimulateFocusGained(const base::UnguessableToken& id,
bool controllable) {
service_->media_session_notification_producer_->OnFocusGained(
CreateFocusRequest(id, controllable));
}
void SimulateFocusLost(const base::UnguessableToken& id) {
AudioFocusRequestStatePtr focus(AudioFocusRequestState::New());
focus->request_id = id;
service_->media_session_notification_producer_->OnFocusLost(
std::move(focus));
}
void SimulateNecessaryMetadata(const base::UnguessableToken& id) {
// In order for the MediaNotificationItem to tell the
// MediaNotificationService to show a media session, that session needs
// a title and artist. Typically this would happen through the media session
// service, but since the service doesn't run for this test, we'll manually
// grab the MediaNotificationItem from the MediaNotificationService and
// set the metadata.
auto item_itr = sessions().find(id.ToString());
ASSERT_NE(sessions().end(), item_itr);
media_session::MediaMetadata metadata;
metadata.title = u"title";
metadata.artist = u"artist";
item_itr->second.item()->MediaSessionMetadataChanged(std::move(metadata));
}
void SimulateHasArtwork(const base::UnguessableToken& id) {
auto item_itr = sessions().find(id.ToString());
ASSERT_NE(sessions().end(), item_itr);
SkBitmap image;
image.allocN32Pixels(10, 10);
image.eraseColor(SK_ColorMAGENTA);
item_itr->second.item()->MediaControllerImageChanged(
media_session::mojom::MediaSessionImageType::kArtwork, image);
}
void SimulateHasNoArtwork(const base::UnguessableToken& id) {
auto item_itr = sessions().find(id.ToString());
ASSERT_NE(sessions().end(), item_itr);
item_itr->second.item()->MediaControllerImageChanged(
media_session::mojom::MediaSessionImageType::kArtwork, SkBitmap());
}
void SimulateReceivedAudioFocusRequests(
std::vector<AudioFocusRequestStatePtr> requests) {
service_->media_session_notification_producer_
->OnReceivedAudioFocusRequests(std::move(requests));
}
bool IsSessionFrozen(const base::UnguessableToken& id) const {
auto item_itr = sessions().find(id.ToString());
EXPECT_NE(sessions().end(), item_itr);
return item_itr->second.item()->frozen();
}
bool IsSessionInactive(const base::UnguessableToken& id) const {
return base::Contains(
service_->media_session_notification_producer_->inactive_session_ids_,
id.ToString());
}
bool HasActiveNotifications() const {
return service_->HasActiveNotifications();
}
bool HasFrozenNotifications() const {
return service_->HasFrozenNotifications();
}
bool HasOpenDialog() const { return service_->HasOpenDialog(); }
void SimulateDialogOpened(MockMediaDialogDelegate* delegate) {
delegate->Open(service_.get());
}
void SimulateDialogOpenedForPresentationRequest(
MockMediaDialogDelegate* delegate,
content::WebContents* content) {
delegate->OpenForWebContents(service_.get(), content);
}
void SimulateTabClosed(const base::UnguessableToken& id) {
// When a tab is closing, audio focus will be lost before the WebContents is
// destroyed, so to simulate closer to reality we will also simulate audio
// focus lost here.
SimulateFocusLost(id);
// Now, close the tab. The session may have been destroyed with
// |SimulateFocusLost()| above.
auto item_itr = sessions().find(id.ToString());
if (item_itr != sessions().end())
item_itr->second.WebContentsDestroyed();
}
void SimulatePlaybackStateChanged(const base::UnguessableToken& id,
bool playing) {
MediaSessionInfoPtr session_info(MediaSessionInfo::New());
session_info->is_controllable = true;
session_info->playback_state =
playing ? media_session::mojom::MediaPlaybackState::kPlaying
: media_session::mojom::MediaPlaybackState::kPaused;
auto item_itr = sessions().find(id.ToString());
EXPECT_NE(sessions().end(), item_itr);
item_itr->second.MediaSessionInfoChanged(std::move(session_info));
}
void SimulateMediaSeeked(const base::UnguessableToken& id) {
auto item_itr = sessions().find(id.ToString());
EXPECT_NE(sessions().end(), item_itr);
item_itr->second.MediaSessionPositionChanged(base::nullopt);
}
void SimulateNotificationClicked(const base::UnguessableToken& id) {
service_->media_session_notification_producer_->OnContainerClicked(
id.ToString());
}
void SimulateDismissButtonClicked(const base::UnguessableToken& id) {
service_->media_session_notification_producer_->OnContainerDismissed(
id.ToString());
}
// Simulates the media notification of the given |id| being dragged out of the
// given dialog.
MockOverlayMediaNotification* SimulateNotificationDraggedOut(
const base::UnguessableToken& id,
MockMediaDialogDelegate* dialog_delegate) {
const gfx::Rect dragged_out_bounds(0, 1, 2, 3);
auto overlay_notification_unique =
std::make_unique<MockOverlayMediaNotification>();
MockOverlayMediaNotification* overlay_notification =
overlay_notification_unique.get();
// When the notification is dragged out, the dialog should be asked to
// remove the notification and return an overlay version of it.
EXPECT_CALL(*dialog_delegate,
PopOutProxy(id.ToString(), dragged_out_bounds))
.WillOnce(Return(overlay_notification_unique.release()));
// Then, that overlay notification should receive a manager and be shown.
Expectation set_manager =
EXPECT_CALL(*overlay_notification, SetManagerProxy(_));
EXPECT_CALL(*overlay_notification, ShowNotification()).After(set_manager);
// Fire the drag out.
service_->media_session_notification_producer_->OnContainerDraggedOut(
id.ToString(), dragged_out_bounds);
testing::Mock::VerifyAndClearExpectations(dialog_delegate);
testing::Mock::VerifyAndClearExpectations(overlay_notification);
return overlay_notification;
}
void ExpectHistogramCountRecorded(int count, int size) {
histogram_tester_.ExpectBucketCount(
media_message_center::kCountHistogramName, count, size);
}
void ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason reason,
int count) {
histogram_tester_.ExpectBucketCount(
"Media.GlobalMediaControls.DismissReason", reason, count);
}
void ExpectHistogramInteractionDelayAfterPause(base::TimeDelta time,
int count) {
histogram_tester_.ExpectTimeBucketCount(
"Media.GlobalMediaControls.InteractionDelayAfterPause", time, count);
}
void ExpectEmptyInteractionHistogram() {
histogram_tester_.ExpectTotalCount(
"Media.GlobalMediaControls.InteractionDelayAfterPause", 0);
}
void SimulateMediaRoutesUpdate(
const std::vector<media_router::MediaRoute>& routes) {
service_->cast_notification_producer_->OnRoutesUpdated(routes, {});
}
MediaSessionNotificationProducer::Session* GetSession(
const base::UnguessableToken& id) {
return service_->media_session_notification_producer_->GetSession(
id.ToString());
}
MockMediaNotificationServiceObserver& observer() { return observer_; }
MediaNotificationService* service() { return service_.get(); }
std::map<std::string, MediaSessionNotificationProducer::Session>& sessions()
const {
return service_->media_session_notification_producer_->sessions_;
}
private:
MockMediaNotificationServiceObserver observer_;
std::unique_ptr<MediaNotificationService> service_;
base::HistogramTester histogram_tester_;
};
// This class enables the features for starting/stopping cast sessions from
// the Zenith dialog.
// Also, it sets up the MockWebContentsPresentationManager as a test instance
// that's used by the MediaNotificationService to get MediaRoute updates.
class MediaNotificationServiceCastTest : public MediaNotificationServiceTest {
public:
void SetUp() override {
feature_list_.InitAndEnableFeature(
media_router::kGlobalMediaControlsCastStartStop);
presentation_manager_ =
std::make_unique<MockWebContentsPresentationManager>();
media_router::WebContentsPresentationManager::SetTestInstance(
presentation_manager_.get());
MediaNotificationServiceTest::SetUp();
}
void TearDown() override {
media_router::WebContentsPresentationManager::SetTestInstance(nullptr);
MediaNotificationServiceTest::TearDown();
}
media_router::MediaRoute CreateMediaRoute(
media_router::MediaRoute::Id route_id) {
media_router::MediaRoute media_route(route_id,
media_router::MediaSource("source_id"),
"sink_id", "description", true, true);
media_route.set_controller_type(
media_router::RouteControllerType::kGeneric);
return media_route;
}
// Simulate a supplementalNotification for |web_contents()|.
std::string SimulateSupplementalNotification() {
auto presentation_request = content::PresentationRequest(
main_rfh()->GetGlobalFrameRoutingId(),
{GURL("http://example.com"), GURL("http://example2.com")},
url::Origin::Create(GURL("http://google.com")));
auto start_presentation_context =
GetStartPresentationContext(presentation_request);
// Create a PresentationRequestNotificationItem.
service()->OnStartPresentationContextCreated(
std::move(start_presentation_context));
auto notification_id = GetSupplementalNotification()->id();
EXPECT_FALSE(notification_id.empty());
auto item =
service()
->presentation_request_notification_producer_->GetNotificationItem(
notification_id);
EXPECT_TRUE(item);
auto* pr_item =
static_cast<PresentationRequestNotificationItem*>(item.get());
EXPECT_EQ(pr_item->context()->presentation_request(), presentation_request);
return notification_id;
}
void SetMediaRoutesManagedByPresentationManager(
std::vector<media_router::MediaRoute> routes) {
ON_CALL(*presentation_manager_, GetMediaRoutes())
.WillByDefault(Return(routes));
}
base::WeakPtr<PresentationRequestNotificationItem>
GetSupplementalNotification() {
return service()
->presentation_request_notification_producer_->GetNotificationItem();
}
MOCK_METHOD3(RequestSuccess,
void(const blink::mojom::PresentationInfo&,
media_router::mojom::RoutePresentationConnectionPtr,
const MediaRoute&));
MOCK_METHOD1(RequestError,
void(const blink::mojom::PresentationError& error));
private:
std::unique_ptr<media_router::StartPresentationContext>
GetStartPresentationContext(
content::PresentationRequest presentation_request) {
return std::make_unique<media_router::StartPresentationContext>(
presentation_request,
base::BindOnce(&MediaNotificationServiceCastTest::RequestSuccess,
base::Unretained(this)),
base::BindOnce(&MediaNotificationServiceCastTest::RequestError,
base::Unretained(this)));
}
std::unique_ptr<MockWebContentsPresentationManager> presentation_manager_;
base::test::ScopedFeatureList feature_list_;
};
TEST_F(MediaNotificationServiceTest, ShowControllableOnGainAndHideOnLoss) {
// Simulate a new active, controllable media session.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_FALSE(HasActiveNotifications());
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_FALSE(IsSessionFrozen(id));
EXPECT_TRUE(HasActiveNotifications());
// Ensure that the observer was notified of the new notification.
testing::Mock::VerifyAndClearExpectations(&observer());
// Simulate opening a MediaDialogView.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
EXPECT_CALL(observer(), OnMediaDialogOpened());
EXPECT_FALSE(HasOpenDialog());
SimulateDialogOpened(&dialog_delegate);
// Ensure that the session was shown.
ExpectHistogramCountRecorded(1, 1);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// Ensure that the observer was notified of the dialog opening.
EXPECT_TRUE(HasOpenDialog());
testing::Mock::VerifyAndClearExpectations(&observer());
// Simulate the active session ending.
EXPECT_CALL(dialog_delegate, HideMediaSession(id.ToString())).Times(0);
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_FALSE(HasFrozenNotifications());
SimulateFocusLost(id);
// Ensure that the session was frozen and not hidden.
EXPECT_TRUE(IsSessionFrozen(id));
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// Ensure that the observer was notification of the frozen notification.
EXPECT_TRUE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
service()->ShowNotification(id.ToString());
// Once the freeze timer fires, we should hide the media session.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_CALL(dialog_delegate, HideMediaSession(id.ToString()));
AdvanceClockMilliseconds(2500);
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest, DoesNotShowUncontrollableSession) {
base::UnguessableToken id = base::UnguessableToken::Create();
// When focus is gained, we should not show an active session.
EXPECT_FALSE(HasActiveNotifications());
SimulateFocusGained(id, false);
SimulateNecessaryMetadata(id);
EXPECT_FALSE(HasActiveNotifications());
// When focus is lost, we should not have a frozen session.
SimulateFocusLost(id);
EXPECT_FALSE(HasFrozenNotifications());
// When focus is regained, we should still not have an active session.
SimulateFocusGained(id, false);
EXPECT_FALSE(HasActiveNotifications());
}
TEST_F(MediaNotificationServiceTest,
DoesNotShowControllableSessionThatBecomesUncontrollable) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Lose focus so the item freezes.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// After 1s, the item should still be frozen.
AdvanceClockMilliseconds(1000);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// If the item regains focus but is not controllable, it should not become
// active.
SimulateFocusGained(id, false);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// And the frozen timer should still fire after the initial 2.5 seconds is
// finished.
AdvanceClockMilliseconds(1400);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
AdvanceClockMilliseconds(200);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
}
TEST_F(MediaNotificationServiceTest, ShowsAllInitialControllableSessions) {
base::UnguessableToken controllable1_id = base::UnguessableToken::Create();
base::UnguessableToken uncontrollable_id = base::UnguessableToken::Create();
base::UnguessableToken controllable2_id = base::UnguessableToken::Create();
std::vector<AudioFocusRequestStatePtr> requests;
requests.push_back(CreateFocusRequest(controllable1_id, true));
requests.push_back(CreateFocusRequest(uncontrollable_id, false));
requests.push_back(CreateFocusRequest(controllable2_id, true));
EXPECT_FALSE(HasActiveNotifications());
// Having controllable sessions should count as active.
SimulateReceivedAudioFocusRequests(std::move(requests));
SimulateNecessaryMetadata(controllable1_id);
SimulateNecessaryMetadata(uncontrollable_id);
SimulateNecessaryMetadata(controllable2_id);
EXPECT_TRUE(HasActiveNotifications());
// If we open a dialog, it should be told to show the controllable sessions,
// but not the uncontrollable one.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate,
ShowMediaSession(controllable1_id.ToString(), _));
EXPECT_CALL(dialog_delegate,
ShowMediaSession(uncontrollable_id.ToString(), _))
.Times(0);
EXPECT_CALL(dialog_delegate,
ShowMediaSession(controllable2_id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Ensure that we properly recorded the number of active sessions shown.
ExpectHistogramCountRecorded(2, 1);
}
TEST_F(MediaNotificationServiceTest, HideAfterTimeoutAndActiveAgainOnPlay) {
// First, start an active session.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, stop playing media so the session is frozen, but not yet hidden.
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kMediaSessionStopped, 0);
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kMediaSessionStopped, 0);
// If the time hasn't elapsed yet, the session should still be frozen.
AdvanceClockMilliseconds(2400);
EXPECT_TRUE(HasFrozenNotifications());
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kMediaSessionStopped, 0);
// Once the time is elapsed, the session should be hidden.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
AdvanceClockMilliseconds(200);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kMediaSessionStopped, 1);
// If media starts playing again, we should show and enable the button.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest,
BecomesActiveIfMediaStartsPlayingWithinTimeout) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, stop playing media so the session is frozen, but hasn't been hidden
// yet.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// If the time hasn't elapsed yet, we should still not be hidden.
AdvanceClockMilliseconds(2400);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// If media starts playing again, we should become active again.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest, NewMediaSessionWhileDialogOpen) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
ExpectHistogramCountRecorded(1, 1);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// Then, have a new media session start while the dialog is opened. This
// should update the dialog.
base::UnguessableToken new_id = base::UnguessableToken::Create();
EXPECT_CALL(dialog_delegate, ShowMediaSession(new_id.ToString(), _));
SimulateFocusGained(new_id, true);
SimulateNecessaryMetadata(new_id);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
// If we close this dialog and open a new one, the new one should receive both
// media sessions immediately.
dialog_delegate.Close();
MockMediaDialogDelegate new_dialog;
EXPECT_CALL(new_dialog, ShowMediaSession(id.ToString(), _));
EXPECT_CALL(new_dialog, ShowMediaSession(new_id.ToString(), _));
SimulateDialogOpened(&new_dialog);
ExpectHistogramCountRecorded(1, 1);
ExpectHistogramCountRecorded(2, 1);
}
TEST_F(MediaNotificationServiceTest,
SessionIsRemovedImmediatelyWhenATabCloses) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, close the tab. The session should immediately be hidden.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kTabClosed, 0);
SimulateTabClosed(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kTabClosed, 1);
}
TEST_F(MediaNotificationServiceTest, DismissesMediaSession) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Then, click the dismiss button. This should stop and hide the session.
EXPECT_CALL(dialog_delegate, HideMediaSession(id.ToString()));
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kUserDismissedNotification, 0);
SimulateDismissButtonClicked(id);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kUserDismissedNotification, 1);
}
// TODO(https://crbug.com/1034406) Flaky on Mac10.12, Linux and Win10.
#if defined(OS_MAC) || defined(OS_LINUX) || defined(OS_CHROMEOS) || \
defined(OS_WIN)
#define MAYBE_CountCastSessionsAsActive DISABLED_CountCastSessionsAsActive
#else
#define MAYBE_CountCastSessionsAsActive CountCastSessionsAsActive
#endif
TEST_F(MediaNotificationServiceCastTest, MAYBE_CountCastSessionsAsActive) {
auto media_route = CreateMediaRoute("id");
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
EXPECT_FALSE(HasActiveNotifications());
SimulateMediaRoutesUpdate({media_route});
EXPECT_TRUE(HasActiveNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
SimulateMediaRoutesUpdate({});
EXPECT_FALSE(HasActiveNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceCastTest,
HideNotification_NewCastSessionStarted) {
// If a new cast session starts, hide the media dialog.
base::UnguessableToken id = SimulatePlayingControllableMedia();
MockMediaDialogDelegate dialog_delegate;
SimulateDialogOpened(&dialog_delegate);
EXPECT_TRUE(HasOpenDialog());
auto presentation_manager =
std::make_unique<MockWebContentsPresentationManager>();
auto media_route = CreateMediaRoute("id");
auto* session = GetSession(id);
session->SetPresentationManagerForTesting(
presentation_manager.get()->GetWeakPtr());
EXPECT_CALL(observer(), OnMediaDialogClosed());
presentation_manager->NotifyMediaRoutesChanged({media_route});
EXPECT_FALSE(HasOpenDialog());
task_environment()->RunUntilIdle();
}
TEST_F(MediaNotificationServiceCastTest, ShowCastSessions) {
// Show a cast session
testing::NiceMock<MockMediaDialogDelegate> dialog_delegate;
const std::string route_id = "route_id";
SimulateMediaRoutesUpdate({CreateMediaRoute(route_id)});
EXPECT_CALL(dialog_delegate, ShowMediaSession(route_id, _));
SimulateDialogOpened(&dialog_delegate);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
}
TEST_F(MediaNotificationServiceCastTest,
ShowCastSessionsForPresentationRequest) {
MockMediaDialogDelegate dialog_delegate;
std::unique_ptr<content::WebContents> web_contents_1(
content::RenderViewHostTestHarness::CreateTestWebContents());
std::unique_ptr<content::WebContents> web_contents_2(
content::RenderViewHostTestHarness::CreateTestWebContents());
// Simulate a Cast notification.
const std::string id_1 = "route_id";
auto media_route = CreateMediaRoute(id_1);
SimulateMediaRoutesUpdate({media_route});
// Simulate a Media session notification in |web_contents_2|.
auto id_2 =
SimulatePlayingControllableMediaForWebContents(web_contents_2.get());
// Open the dialog from |web_contents_1|. Overwrite the return value of
// GetMediaRoutes() so that MediaNotificationService associates
// |web_contents_1| with the cast notification.
SetMediaRoutesManagedByPresentationManager({media_route});
EXPECT_CALL(dialog_delegate, ShowMediaSession(id_1, _));
SimulateDialogOpenedForPresentationRequest(&dialog_delegate,
web_contents_1.get());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
// Open the dialog from |web_contents_2|, which has a media session
// notification and no cast session notification.
SetMediaRoutesManagedByPresentationManager({});
EXPECT_CALL(dialog_delegate, ShowMediaSession(id_2.ToString(), _));
SimulateDialogOpenedForPresentationRequest(&dialog_delegate,
web_contents_2.get());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
}
TEST_F(MediaNotificationServiceCastTest,
ShowMediaSessionsForPresentationRequest) {
std::unique_ptr<content::WebContents> web_contents_1(
content::RenderViewHostTestHarness::CreateTestWebContents());
std::unique_ptr<content::WebContents> web_contents_2(
content::RenderViewHostTestHarness::CreateTestWebContents());
// Simulate two active media sessions.
auto id_1 =
SimulatePlayingControllableMediaForWebContents(web_contents_1.get());
auto id_2 =
SimulatePlayingControllableMediaForWebContents(web_contents_2.get());
// If the dialog is opened for a presentation request from |web_contents_1|,
// only the media session with |id_1| should show up.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id_1.ToString(), _));
SimulateDialogOpenedForPresentationRequest(&dialog_delegate,
web_contents_1.get());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
// If the dialog is opened for a presentation request from |web_contents_2|,
// only the media session with |id_2| should show up.
EXPECT_CALL(dialog_delegate, ShowMediaSession(id_2.ToString(), _));
SimulateDialogOpenedForPresentationRequest(&dialog_delegate,
web_contents_2.get());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
}
TEST_F(MediaNotificationServiceCastTest, ShowSupplementalNotifications) {
MockMediaDialogDelegate dialog_delegate;
// Do not show a supplemental notification if there is no start presentation
// request context.
EXPECT_FALSE(GetSupplementalNotification());
EXPECT_CALL(dialog_delegate, ShowMediaSession(_, _)).Times(0);
SimulateDialogOpened(&dialog_delegate);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
// Create a PresentationRequestNotificationItem.
auto supplemental_notification_id = SimulateSupplementalNotification();
// Open the dialog and a supplemental notification should show up.
EXPECT_CALL(dialog_delegate,
ShowMediaSession(supplemental_notification_id, _));
SimulateDialogOpened(&dialog_delegate);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
EXPECT_CALL(dialog_delegate,
ShowMediaSession(supplemental_notification_id, _));
SimulateDialogOpenedForPresentationRequest(&dialog_delegate, web_contents());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
// If there are notifications from other WebContents, still show dummy
// notifications.
std::unique_ptr<content::WebContents> test_web_contents(
content::RenderViewHostTestHarness::CreateTestWebContents());
auto media_session_id =
SimulatePlayingControllableMediaForWebContents(test_web_contents.get());
// Create a cast session not associated with any WebContents.
const std::string route_id = "route_id";
SimulateMediaRoutesUpdate({CreateMediaRoute(route_id)});
EXPECT_CALL(dialog_delegate, ShowMediaSession(route_id, _));
EXPECT_CALL(dialog_delegate,
ShowMediaSession(media_session_id.ToString(), _));
EXPECT_CALL(dialog_delegate,
ShowMediaSession(supplemental_notification_id, _));
SimulateDialogOpened(&dialog_delegate);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
}
TEST_F(MediaNotificationServiceCastTest, HideSupplementalNotifications) {
MockMediaDialogDelegate dialog_delegate;
auto supplemental_notification_id = SimulateSupplementalNotification();
// If there is a media session, hide the supplemental notification.
auto media_session_id =
SimulatePlayingControllableMediaForWebContents(web_contents());
EXPECT_CALL(dialog_delegate,
ShowMediaSession(media_session_id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
EXPECT_CALL(dialog_delegate,
ShowMediaSession(media_session_id.ToString(), _));
SimulateDialogOpenedForPresentationRequest(&dialog_delegate, web_contents());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
dialog_delegate.Close();
SimulateFocusLost(media_session_id);
// If there is a cast session, hide the supplemental notification.
auto media_route = CreateMediaRoute("route_id");
SimulateMediaRoutesUpdate({media_route});
SetMediaRoutesManagedByPresentationManager({media_route});
service()->OnCastNotificationsChanged();
EXPECT_CALL(dialog_delegate,
ShowMediaSession(media_route.media_route_id(), _));
SimulateDialogOpened(&dialog_delegate);
testing::Mock::VerifyAndClearExpectations(&observer());
dialog_delegate.Close();
EXPECT_CALL(dialog_delegate,
ShowMediaSession(media_route.media_route_id(), _));
SimulateDialogOpened(&dialog_delegate);
testing::Mock::VerifyAndClearExpectations(&observer());
}
// Regression test for https://crbug.com/1015903: we could end up in a
// situation where the toolbar icon was disabled indefinitely.
TEST_F(MediaNotificationServiceTest, LoseGainLoseDoesNotCauseRaceCondition) {
// First, start an active session and include artwork.
base::UnguessableToken id = SimulatePlayingControllableMedia();
SimulateHasArtwork(id);
EXPECT_TRUE(HasActiveNotifications());
// Then, stop playing media so the session is frozen, but hasn't been hidden
// yet.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// Simulate no artwork, so we wait for new artwork.
SimulateHasNoArtwork(id);
// Simulate regaining focus, but no artwork yet so we wait.
SimulateFocusGained(id, true);
SimulateNecessaryMetadata(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// Then, lose focus again before getting artwork.
SimulateFocusLost(id);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(HasFrozenNotifications());
// When the freeze timer fires, we should be hidden.
EXPECT_CALL(observer(), OnNotificationListChanged()).Times(AtLeast(1));
AdvanceClockMilliseconds(2600);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_FALSE(HasFrozenNotifications());
testing::Mock::VerifyAndClearExpectations(&observer());
}
TEST_F(MediaNotificationServiceTest, ShowsOverlayForDraggedOutNotifications) {
// First, start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Drag out the notification.
MockOverlayMediaNotification* overlay_notification =
SimulateNotificationDraggedOut(id, &dialog_delegate);
// Now, dismiss the notification. Since the notification is an overlay
// notification, this should just close the overlay notification.
EXPECT_CALL(*overlay_notification, CloseNotification());
SimulateDismissButtonClicked(id);
testing::Mock::VerifyAndClearExpectations(overlay_notification);
// After we close, we notify our manager, and the dialog should be informed
// that it can show the notification again.
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
overlay_notification->manager()->OnOverlayNotificationClosed(id.ToString());
testing::Mock::VerifyAndClearExpectations(&dialog_delegate);
}
TEST_F(MediaNotificationServiceTest, HidesInactiveNotifications) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 59 minutes, the notification should still be there.
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// But once it's been inactive for over an hour, it should disappear.
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kInactiveTimeout, 0);
AdvanceClockMinutes(2);
EXPECT_FALSE(HasActiveNotifications());
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kInactiveTimeout, 1);
// Since the user never interacted with the media before it was paused, we
// should not have recorded any post-pause interactions.
ExpectEmptyInteractionHistogram();
// If we now close the tab, then it shouldn't record that as the dismiss
// reason, since we already recorded a reason.
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kTabClosed, 0);
SimulateTabClosed(id);
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kTabClosed, 0);
}
TEST_F(MediaNotificationServiceTest, InactiveBecomesActive_PlayPause) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
// Let the notification become inactive.
AdvanceClockMinutes(70);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(IsSessionInactive(id));
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
0);
// Then, play the media. The notification should become active.
SimulatePlaybackStateChanged(id, true);
// We should have recorded an interaction even though the timer has
// finished.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
1);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest, InactiveBecomesActive_Seeking) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
// Let the notification become inactive.
AdvanceClockMinutes(70);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(IsSessionInactive(id));
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
0);
// Then, seek the media. The notification should become active.
SimulateMediaSeeked(id);
// We should have recorded an interaction even though the timer has
// finished.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(70),
1);
EXPECT_TRUE(HasActiveNotifications());
EXPECT_FALSE(IsSessionInactive(id));
// If we don't interact again, the notification should become inactive
// again.
AdvanceClockMinutes(70);
EXPECT_FALSE(HasActiveNotifications());
EXPECT_TRUE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest, DelaysHidingNotifications_PlayPause) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 59 minutes, the notification should still be there.
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// If we start playing again, we should not hide the notification, even
// after an hour.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
0);
SimulatePlaybackStateChanged(id, true);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
1);
AdvanceClockMinutes(2);
EXPECT_TRUE(HasActiveNotifications());
// If we pause again, it should hide after an hour.
SimulatePlaybackStateChanged(id, false);
AdvanceClockMinutes(61);
EXPECT_FALSE(HasActiveNotifications());
}
TEST_F(MediaNotificationServiceTest, DelaysHidingNotifications_Interactions) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 59 minutes, the notification should still be there.
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// If the user clicks to go back to the tab, it should reset the hide timer.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
0);
SimulateNotificationClicked(id);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(59),
1);
AdvanceClockMinutes(50);
EXPECT_TRUE(HasActiveNotifications());
// If the user seeks the media before an hour is up, it should reset the
// hide timer.
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(50),
0);
SimulateMediaSeeked(id);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(50),
1);
AdvanceClockMinutes(59);
EXPECT_TRUE(HasActiveNotifications());
// After the hour has passed, the notification should hide.
AdvanceClockMinutes(2);
EXPECT_FALSE(HasActiveNotifications());
}
TEST_F(MediaNotificationServiceTest,
DelaysHidingNotifications_OverlayThenPause) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Then, pull out the notification into an overlay notification.
MockOverlayMediaNotification* overlay_notification =
SimulateNotificationDraggedOut(id, &dialog_delegate);
// Then, pause the media.
SimulatePlaybackStateChanged(id, false);
// Since the notification is in an overlay, it should never time out as
// inactive.
AdvanceClockMinutes(61);
EXPECT_FALSE(IsSessionInactive(id));
// Now, close the overlay notification.
overlay_notification->manager()->OnOverlayNotificationClosed(id.ToString());
// The notification should become inactive now that it's not in an overlay.
AdvanceClockMinutes(61);
EXPECT_TRUE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest,
DelaysHidingNotifications_PauseThenOverlay) {
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media.
SimulatePlaybackStateChanged(id, false);
// Then, open a dialog.
MockMediaDialogDelegate dialog_delegate;
EXPECT_CALL(dialog_delegate, ShowMediaSession(id.ToString(), _));
SimulateDialogOpened(&dialog_delegate);
// Then, pull out the notification into an overlay notification.
MockOverlayMediaNotification* overlay_notification =
SimulateNotificationDraggedOut(id, &dialog_delegate);
// Since the notification is in an overlay, it should never time out as
// inactive.
AdvanceClockMinutes(61);
EXPECT_FALSE(IsSessionInactive(id));
// Now, close the overlay notification.
overlay_notification->manager()->OnOverlayNotificationClosed(id.ToString());
// The notification should become inactive now that it's not in an overlay.
AdvanceClockMinutes(61);
EXPECT_TRUE(IsSessionInactive(id));
}
TEST_F(MediaNotificationServiceTest, HidingNotification_FeatureDisabled) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndDisableFeature(
media::kGlobalMediaControlsAutoDismiss);
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After 61 minutes, the notification should still be there.
AdvanceClockMinutes(61);
EXPECT_TRUE(HasActiveNotifications());
ExpectHistogramDismissReasonRecorded(
GlobalMediaControlsDismissReason::kInactiveTimeout, 0);
// Since the user never interacted with the media before it was paused, we
// should not have recorded any post-pause interactions.
ExpectEmptyInteractionHistogram();
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(61),
0);
SimulatePlaybackStateChanged(id, true);
ExpectHistogramInteractionDelayAfterPause(base::TimeDelta::FromMinutes(61),
1);
}
TEST_F(MediaNotificationServiceTest, HidingNotification_TimerParams) {
const int kTimerInMinutes = 6;
base::test::ScopedFeatureList scoped_feature_list;
base::FieldTrialParams params;
params["timer_in_minutes"] = base::NumberToString(kTimerInMinutes);
scoped_feature_list.InitAndEnableFeatureWithParameters(
media::kGlobalMediaControlsAutoDismiss, params);
// Start playing active media.
base::UnguessableToken id = SimulatePlayingControllableMedia();
EXPECT_TRUE(HasActiveNotifications());
// Then, pause the media. We should still have the active notification.
SimulatePlaybackStateChanged(id, false);
EXPECT_TRUE(HasActiveNotifications());
// After (kTimerInMinutes-1) minutes, the notification should still be
// there.
AdvanceClockMinutes(kTimerInMinutes - 1);
EXPECT_TRUE(HasActiveNotifications());
// If we start playing again, we should not hide the notification, even
// after kTimerInMinutes.
ExpectHistogramInteractionDelayAfterPause(
base::TimeDelta::FromMinutes(kTimerInMinutes - 1), 0);
SimulatePlaybackStateChanged(id, true);
ExpectHistogramInteractionDelayAfterPause(
base::TimeDelta::FromMinutes(kTimerInMinutes - 1), 1);
AdvanceClockMinutes(2);
EXPECT_TRUE(HasActiveNotifications());
// If we pause again, it should hide after kTimerInMinutes.
SimulatePlaybackStateChanged(id, false);
AdvanceClockMinutes(kTimerInMinutes + 1);
EXPECT_FALSE(HasActiveNotifications());
}
| 39.42997 | 88 | 0.759888 | [
"vector"
] |
e152080f1a0d20df31115705586e4ed48d963002 | 24,188 | cpp | C++ | master/core/third/RCF/test/Test_Serialization.cpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:48.000Z | 2019-10-26T21:44:59.000Z | master/core/third/RCF/test/Test_Serialization.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | null | null | null | master/core/third/RCF/test/Test_Serialization.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:49.000Z | 2018-12-27T03:20:31.000Z |
// disable ADL warning for vc71
#ifdef _MSC_VER
#pragma warning( disable : 4675 ) // warning C4675: '...' : resolved overload was found by argument-dependent lookup
#endif
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <boost/test/minimal.hpp>
#include <boost/test/floating_point_comparison.hpp>
#define BOOST_CHECK_CLOSE(d1, d2, tol) BOOST_CHECK( boost::test_tools::check_is_close(d1, d2, tol) )
//#define BOOST_CHECK_CLOSE(d1, d2, tol)
//#define BOOST_CHECK(x) if (x) ; else { std::cout << "FAIL: " << #x << "\n"; }
//namespace boost { static const int exit_success = 0; }
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
// streams
#include <SF/IBinaryStream.hpp>
#include <SF/OBinaryStream.hpp>
#include <SF/INativeBinaryStream.hpp>
#include <SF/ONativeBinaryStream.hpp>
#include <SF/ITextStream.hpp>
#include <SF/OTextStream.hpp>
// construction and registation
#include <SF/SfNew.hpp>
#include <SF/Registry.hpp>
// serializers
#include <SF/list.hpp>
#include <SF/map.hpp>
#include <SF/memory.hpp>
#include <SF/scoped_ptr.hpp>
#include <SF/set.hpp>
#include <SF/shared_ptr.hpp>
#include <SF/string.hpp>
#include <SF/vector.hpp>
#include <SF/SerializeEnum.hpp>
//**************************************************
double fpt_tolerance = .1;
bool fpt_compare(double *pd1, double *pd2, unsigned int count)
{
for (unsigned int i=0; i<count; i++)
if ((pd1[i]-pd2[i])*(pd1[i]-pd2[i]) > fpt_tolerance)
return false;
return true;
}
bool fpt_compare(float *pf1, float *pf2, unsigned int count)
{
for (unsigned int i=0; i<count; i++)
if ((pf1[i]-pf2[i])*(pf1[i]-pf2[i]) > fpt_tolerance)
return false;
return true;
}
namespace Test {
struct GeomObject
{
GeomObject() : x(0), y(0) {}
GeomObject(int x, int y) : x(x), y(y) {}
virtual ~GeomObject() {}
bool operator==(const GeomObject &rhs) { return x == rhs.x && y == rhs.y; }
int x;
int y;
};
struct Rect : public GeomObject
{
Rect() : GeomObject(), w(0), h(0) {}
Rect(int x,int y, int w, int h) : GeomObject(x,y), w(w), h(h) {}
bool operator==(const Rect &rhs) { return x == rhs.x && y == rhs.y && w == rhs.w && h == rhs.h; }
int w;
int h;
};
class Empty {
public:
Empty() {}
};
struct D { virtual ~D() {} };
struct A;
struct B;
struct C;
struct A : public D { B *pb; };
struct B : public D { C *pc; };
struct C : public D { A *pa; };
template<typename T>
struct TestOne
{
bool operator==(const TestOne &rhs) { return n == rhs.n && t == rhs.t; }
int n;
T t;
};
template<typename T, typename U>
struct TestTwo
{
bool operator==(const TestTwo &rhs) { return t == rhs.t && u == rhs.u; }
T t;
U u;
};
enum TestEnum { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };
class ArrayContainer {
public:
ArrayContainer()
{
memset(this, 0, sizeof(ArrayContainer));
}
ArrayContainer(int n) {
memset(this, 0, sizeof(ArrayContainer));
if (n) {
srand(1); // Reinitialize random number generator so we get the same sequence each time
for (int i=0; i<NSIZE; i++)
pn[i] = rand();
for (int i=0; i<CHSIZE; i++)
for (int j=0; j<CHSIZE; j++)
for (int k=0; k<CHSIZE; k++)
ch[i][j][k] = 'A' + i + j + k;
pd = new double[DSIZE];
pd_length = DSIZE;
double pi = 3.141592654E-10;
for (int i=0; i<DSIZE; i++)
pd[i] = rand()*pi;
for (int i=0; i<PIISIZE; i++)
for (int j=0; j<PIISIZE; j++)
pii[i][j] = std::pair<int,int>(i,j);
pcc = new std::pair<char,char>[PCCSIZE];
pcc_length = PCCSIZE;
for (int i=0; i<PIISIZE; i++)
pcc[i] = std::pair<char,char>('A'+i,'A'+i);
}
}
~ArrayContainer()
{
if (pd) delete [] pd;
if (pcc) delete [] pcc;
}
friend bool operator==( const ArrayContainer &lhs, const ArrayContainer &rhs )
{
bool bOk = true;
bOk = bOk && (lhs.pn && rhs.pn && 0 == memcmp(&lhs.pn, &rhs.pn, ArrayContainer::NSIZE*sizeof(int)));
bOk = bOk && (lhs.ch && rhs.ch && 0 == memcmp(&lhs.ch, &rhs.ch, ArrayContainer::CHSIZE*ArrayContainer::CHSIZE*sizeof(char)));
bOk = bOk && (lhs.pd_length == rhs.pd_length) && (fpt_compare(lhs.pd, rhs.pd, lhs.pd_length));
bOk = bOk && (lhs.pii && rhs.pii && 0 == memcmp(&lhs.pii, &rhs.pii, ArrayContainer::PIISIZE*ArrayContainer::PIISIZE*sizeof(std::pair<int,int>)));
bOk = bOk && (lhs.pcc_length == rhs.pcc_length) && (0 == memcmp(lhs.pcc, rhs.pcc, sizeof(std::pair<char,char>)*lhs.pcc_length) );
return bOk;
}
public:
static const int NSIZE = 100;
static const int CHSIZE = 3;
static const int DSIZE = 100;
static const int PIISIZE = 4;
static const int PCCSIZE = 4;
int pn[NSIZE];
char ch[CHSIZE][CHSIZE][CHSIZE];
double *pd;
unsigned int pd_length;
std::pair<int,int> pii[PIISIZE][PIISIZE];
std::pair<char,char> *pcc;
unsigned int pcc_length;
};
class Props {
public:
Props() : width_(0) {}
int get_Width() { return width_; }
void set_Width(int width) { width_ = width; }
friend bool operator==( const Props &lhs, const Props &rhs ) { return lhs.width_ == rhs.width_; }
private:
int width_;
};
namespace K1 {
class A {
public:
A() : a(0) {}
A(int a) : a(a) {}
friend bool operator==(const A &lhs, const A &rhs) { return lhs.a == rhs.a; }
template<typename Archive>
void serialize(Archive &ar, const unsigned int)
{
ar & a;
}
private:
int a;
};
namespace K2 {
class B {
public:
B() : b(0) {}
B(int b) : b(b) {}
friend bool operator==(const B &lhs, const B &rhs) { return lhs.b == rhs.b; }
template<typename Archive>
void serialize(Archive &ar, const unsigned int)
{
ar & b;
}
private:
int b;
};
} //namespace K2
} //namespace K1
} // namespace Test
namespace Test {
template<typename Archive>
void serialize(Archive &ar, D &d, const unsigned int)
{}
template<typename Archive>
void serialize(Archive &ar, A &a, const unsigned int)
{
ar & a.pb;
}
template<typename Archive>
void serialize(Archive &ar, B &b, const unsigned int)
{
ar & b.pc;
}
template<typename Archive>
void serialize(Archive &ar, C &c, const unsigned int)
{
ar & c.pa;
}
AUTO_RUN( SF::registerType<A>("Test::A") );
AUTO_RUN( SF::registerType<B>("Test::B") );
AUTO_RUN( SF::registerType<C>("Test::C") );
// following necessary since A, B, C serializers don't invoke D's serializer
AUTO_RUN( (SF::registerBaseAndDerived<D, A>()) );
AUTO_RUN( (SF::registerBaseAndDerived<D, B>()) );
AUTO_RUN( (SF::registerBaseAndDerived<D, C>()) );
template<typename Archive>
void serialize(Archive &ar, GeomObject &geomObject, const unsigned int)
{
ar & geomObject.x & geomObject.y;
}
template<typename Archive>
void serialize(Archive &ar, Rect &rect, const unsigned int)
{
serializeParent<GeomObject>(ar, rect);
ar & rect.w & rect.h;
}
AUTO_RUN( SF::registerType<Rect>("Test::Rect") );
template<typename Archive>
void serialize(Archive &ar, Empty &e, const unsigned int)
{}
template<typename Archive, typename T>
void serialize(Archive &ar, TestOne<T> &t, const unsigned int)
{
ar & t.t & t.n;
}
template<typename Archive, typename T, typename U>
void serialize(Archive &ar, TestTwo<T,U> &t, const unsigned int)
{
ar & t.t & t.u;
}
template<typename Archive>
void serialize(Archive &ar, TestOne<int> &t, const unsigned int)
{
ar & t.t & t.n;
}
// TODO: put this in a macro (SF_SERIALIZE_ENUM or something)
SF_SERIALIZE_ENUM(TestEnum)
/*
template<typename Archive>
void serialize(Archive &ar, TestEnum &t, const unsigned int)
{
// TODO
if (ar.isRead())
{
int n = 0;
ar & n;
t = TestEnum(n);
}
else // if (ar.isWrite()))
{
int n = t;
ar & n;
}
}*/
template<typename Archive>
void serialize(Archive &ar, Props &p, const unsigned int)
{
if (ar.isRead())
{
int width;
ar & width;
p.set_Width(width);
}
else // if (ar.isWrite())
{
ar & p.get_Width();
}
}
#if defined(__BORLANDC__)
// TODO: sort out array serialization with borland
/*
// Implicit type detection of inline static arrays is broken in BCC 5.5, so need to specify the types explicitly
typedef std::pair<int,int> pair_int_int_t;
SF_BEGIN( ArrayContainer, "" )
SF_TYPED_MEMBER( pn_, "pn", int [ArrayContainer::NSIZE] );
SF_TYPED_MEMBER( ch_, "ch", char [ArrayContainer::CHSIZE][ArrayContainer::CHSIZE][ArrayContainer::CHSIZE] );
SF_DYNAMIC_ARRAY(pd, SF_THIS->pd_length, "pd");
SF_TYPED_MEMBER( pii_, "pii", pair_int_int_t [ArrayContainer::PIISIZE][ArrayContainer::PIISIZE] );
SF_DYNAMIC_ARRAY(pcc, SF_THIS->pcc_length, "pcc");
SF_END( ArrayContainer );
*/
#else
template<typename Archive>
void serialize(Archive &ar, ArrayContainer &a, const unsigned int)
{
ar & a.pn;
ar & a.ch;
ar & SF::dynamicArray(a.pd, a.pd_length);
ar & a.pii;
ar & SF::dynamicArray(a.pcc, a.pcc_length);
}
#endif
} // namespace Test
//********************************************************************
template<typename IStream, typename OStream>
void testAtomic()
{
using namespace Test;
bool b1 = true, b2 = false;
int n1 = 1, n2 = 0;
char ch1 = 'A', ch2 = 'B';
float f1 = 2.71828f, f2 = 0.0f;
double d1 = -3.141592654E-8, d2 = 0.0;
std::ostringstream os;
OStream ostr(os);
ostr << b1 << n1 << ch1 << f1 << d1;
std::istringstream is(os.str());
IStream istr(is);
istr >> b2 >> n2 >> ch2 >> f2 >> d2;
BOOST_CHECK( b2 == b1 );
BOOST_CHECK( n2 == n1 );
BOOST_CHECK( ch2 == ch1 );
BOOST_CHECK_CLOSE(f2, f1, 1.1 );
BOOST_CHECK_CLOSE(d2, d1, 1.1 );
}
template<typename IStream, typename OStream>
void testComposite()
{
using namespace Test;
GeomObject geom1(1,2), geom2(0,0);
Rect rect1(1,2,3,4), rect2(0,0,0,0);
TestOne<bool> to1, to2;
to1.t = true; to1.n = 1;
to2.t = false; to2.n = 0;
TestTwo<std::string, double> tt1, tt2;
tt1.t = "pi"; tt1.u = 3.14;
tt2.t = ""; tt2.u = 0;
std::pair<char, int> p1('a', 1), p2('\0', 0);
Props prop1, prop2;
prop1.set_Width(1);
prop2.set_Width(0);
std::ostringstream os;
OStream ostr(os);
ostr << geom1 << rect1 << to1 << tt1 << p1 << prop1;
std::istringstream is(os.str());
IStream istr(is);
istr >> geom2 >> rect2 >> to2 >> tt2 >> p2 >> prop2;
BOOST_CHECK( geom2 == geom1 );
BOOST_CHECK( rect2 == rect1 );
BOOST_CHECK( to2 == to1 );
BOOST_CHECK( tt2 == tt1 );
BOOST_CHECK( p2 == p1 );
BOOST_CHECK( prop2 == prop1 );
}
template<typename IStream, typename OStream>
void testEmptyComposite()
{
using namespace Test;
Empty e1, e2;
Empty *pe1 = NULL, *pe2 = &e1, *pe3 = NULL, *pe4 = NULL;
std::vector<int> v1, v2;
std::vector<int> *pv1 = NULL, *pv2 = &v1, *pv3 = NULL, *pv4 = NULL;
std::ostringstream os;
OStream ostr(os);
ostr << e1 << pe1 << pe2;
ostr << v1 << pv1 << pv2;
std::istringstream is(os.str());
IStream istr(is);
istr >> e2 >> pe3 >> pe4;
istr >> v2 >> pv3 >> pv4;
BOOST_CHECK( pe3 == NULL );
BOOST_CHECK( pe4 != NULL );
BOOST_CHECK( v2.empty() );
BOOST_CHECK( pv3 == NULL );
BOOST_CHECK( pv4 != NULL );
//if (pe3) delete pe3;
//if (pe4) delete pe4;
//if (pv3) delete pv3;
//if (pv4) delete pv4;
}
template<typename IStream, typename OStream>
void testArrays()
{
using namespace Test;
const SF::UInt32 SIZE = 40;
// Single dimensional static array
int pn1[SIZE];
for (int i=0;i<SIZE;i++)
pn1[i] = i-20;
int pn2[SIZE];
memset(pn2, 0, SIZE*sizeof(int));
// Single dimensional dynamic array
int *pn3 = new int[SIZE];
memcpy(pn3, pn1, SIZE*sizeof(int));
const int *pn4 = NULL;
SF::UInt32 n4 = 0;
// Multidimensional static array
int pn5[5][5][5];
for (int i=0; i<5; i++)
for (int j=0; j<5; j++)
for (int k=0;k<5; k++)
pn5[i][j][k] = i*j*k;
int pn6[5][5][5];
memset(pn6, 0, 5*5*5*sizeof(int));
const int pn7[2][2] = { {1,2}, {3,4} };
const int pn8[2][2] = { {0,0}, {0,0} };
// Object containing arrays
ArrayContainer a1(1), a2(0);
#ifndef __BORLANDC__
{
// Serialization of multidimensional arrays doesnt work with BCB, except as members of a class,
// due to compiler bugs.
std::ostringstream os;
OStream ostr(os);
ostr << pn5;
ostr << pn7;
std::istringstream is(os.str());
IStream istr(is);
istr >> pn6;
istr >> pn8;
BOOST_CHECK( pn5 && pn6 && 0 == memcmp( pn5, pn6, 5*5*5*sizeof(int) ) );
BOOST_CHECK( pn7 && pn8 && 0 == memcmp( pn7, pn8, 2*2*sizeof(int) ) );
}
#endif
std::ostringstream os;
OStream ostr(os);
ostr << pn1;
ostr << SF::dynamicArray(pn3,SIZE);
ostr << a1;
std::istringstream is(os.str());
IStream istr(is);
istr >> pn2;
istr >> SF::dynamicArray(pn4, n4);
istr >> a2;
BOOST_CHECK( pn1 && pn2 && 0 == memcmp( pn1, pn2, SIZE*sizeof(int) ) );
BOOST_CHECK( pn3 && pn4 && 0 == memcmp( pn3, pn4, SIZE*sizeof(int) ) );
BOOST_CHECK( a1 == a2 );
delete [] pn3;
delete [] pn4;
}
template<typename IStream, typename OStream>
void testEnum()
{
using namespace Test;
TestEnum x1,y1,z1, x2,y2,z2;
x1 = MONDAY;
y1 = TUESDAY;
z1 = SUNDAY;
x2 = SUNDAY;
y2 = SUNDAY;
z2 = SUNDAY;
std::ostringstream os;
OStream ostr(os);
ostr << x1 << y1 << z1;
std::istringstream is(os.str());
IStream istr(is);
istr >> x2 >> y2 >> z2;
BOOST_CHECK( x1 == x2 );
BOOST_CHECK( y1 == y2 );
BOOST_CHECK( z1 == z2 );
}
template<typename IStream, typename OStream>
void testContainers()
{
using namespace Test;
std::list<int> L1,L2;
std::set<double> S1,S2;
std::map<std::string, bool> M1,M2;
std::vector< std::pair<int,int> > V1,V2;
L1.push_back(1);
L1.push_back(2);
L1.push_back(3);
S1.insert(1.1);
S1.insert(2.2);
S1.insert(3.3);
M1["one"] = true;
M1["two"] = false;
M1["three"] = true;
std::string str1 = "In the beginning", str2;
std::ostringstream os;
OStream ostr(os);
ostr << L1;
ostr << S1;
ostr << M1;
ostr << V1;
ostr << str1;
std::istringstream is(os.str());
IStream istr(is);
istr >> L2;
istr >> S2;
istr >> M2;
istr >> V2;
istr >> str2;
BOOST_CHECK( L2.size() == L1.size() );
BOOST_CHECK( std::equal(L1.begin(), L1.end(), L2.begin()) );
BOOST_CHECK( S2.size() == S1.size() );
BOOST_CHECK( std::equal(S1.begin(), S1.end(), S2.begin()) );
BOOST_CHECK( M2.size() == M1.size() );
BOOST_CHECK( std::equal(M1.begin(), M1.end(), M2.begin()) );
BOOST_CHECK( V2.size() == V1.size() );
BOOST_CHECK( std::equal(V1.begin(), V1.end(), V2.begin()) );
BOOST_CHECK( str2.size() == str1.size() );
BOOST_CHECK( str1 == str2 );
}
template<typename IStream, typename OStream>
void testGraphs()
{
using namespace Test;
A a1,a2;
B b1,b2;
C c1,c2;
D d1,d2;
int n = 17;
int *pn = &n;
int m = 0;
int *pm = NULL;
std::ostringstream os;
OStream ostr(os);
ostr.enableContext();
{
a1.pb = &b1;
b1.pc = &c1;
c1.pa = &a1;
std::vector<D *> vec;
vec.push_back(&a1);
vec.push_back(&b1);
vec.push_back(&c1);
vec.push_back(&a1);
vec.push_back(&b1);
vec.push_back(&c1);
ostr << &n << pn;
ostr << d1;
ostr << vec;
ostr.clearContext();
ostr << a1;
ostr.clearContext();
a1.pb = NULL;
b1.pc = NULL;
c1.pa = NULL;
vec.clear();
vec.push_back(&a1);
vec.push_back(&b1);
vec.push_back(&c1);
vec.push_back(&a1);
vec.push_back(&b1);
vec.push_back(&c1);
ostr << vec;
ostr.clearContext();
ostr << a1 ;
ostr.clearContext();
}
std::istringstream is(os.str());
IStream istr(is);
{
a2.pb = NULL;
b2.pc = NULL;
c2.pa = NULL;
std::vector<D *> vec;
istr >> m >> pm;
istr >> d2;
istr >> vec;
istr >> a2 ;
BOOST_CHECK( m == n);
BOOST_CHECK( pm == &m );
BOOST_CHECK( vec.size() == 6 );
BOOST_CHECK( vec.at(0) == vec.at(3) );
BOOST_CHECK( vec.at(1) == vec.at(4) );
BOOST_CHECK( vec.at(2) == vec.at(5) );
BOOST_CHECK( ((A *) vec.at(0))->pb == ((B *) vec.at(1)) );
BOOST_CHECK( ((B *) vec.at(1))->pc == ((C *) vec.at(2)) );
BOOST_CHECK( ((C *) vec.at(2))->pa == ((A *) vec.at(0)) );
BOOST_CHECK( a2.pb->pc->pa == &a2 );
delete vec.at(0);
delete vec.at(1);
delete vec.at(2);
vec.clear();
delete a2.pb->pc;
delete a2.pb;
istr >> vec;
istr >> a2 ;
BOOST_CHECK( vec.size() == 6 );
BOOST_CHECK( vec.at(0) == vec.at(3) );
BOOST_CHECK( vec.at(1) == vec.at(4) );
BOOST_CHECK( vec.at(2) == vec.at(5) );
BOOST_CHECK( ((A *) vec.at(0))->pb == NULL );
BOOST_CHECK( ((B *) vec.at(1))->pc == NULL );
BOOST_CHECK( ((C *) vec.at(2))->pa == NULL );
BOOST_CHECK( a2.pb == NULL );
delete vec.at(0);
delete vec.at(1);
delete vec.at(2);
}
}
template<typename IStream, typename OStream>
void testPolymorphism()
{
using namespace Test;
Rect rect(1,2,3,4);
GeomObject geom(1,2);
GeomObject *pg1 = NULL, *pg2 = NULL, *pg3 = NULL;
Rect *pr1 = NULL, *pr2 = NULL;
GeomObject &rg1 = geom, &rg2 = rect;
GeomObject g;
Rect r;
GeomObject &rg3 = g;
GeomObject &rg4 = r;
pg1 = NULL;
pg2 = (GeomObject *) &geom;
pg3 = (GeomObject *) ▭
pr1 = NULL;
pr2 = ▭
std::ostringstream os;
OStream ostr(os);
ostr << pg1 << pg2 << pg3;
ostr << pr1 << pr2;
ostr << rg1 << rg2;
pg1 = reinterpret_cast<GeomObject *>(1);
pg2 = reinterpret_cast<GeomObject *>(1);
pg3 = reinterpret_cast<GeomObject *>(1);
pr1 = reinterpret_cast<Rect *>(1);
pr2 = reinterpret_cast<Rect *>(1);
std::istringstream is(os.str());
IStream istr(is);
istr >> pg1 >> pg2 >> pg3;
istr >> pr1 >> pr2;
istr >> rg3 >> rg4;
BOOST_CHECK( pg1 == NULL );
BOOST_CHECK( *pg2 == geom );
BOOST_CHECK( dynamic_cast<Rect*>(pg3) != NULL && * (dynamic_cast<Rect*>(pg3)) == rect );
BOOST_CHECK( pr1 == NULL );
BOOST_CHECK( *pr2 == rect );
BOOST_CHECK( rg1 == rg3 );
BOOST_CHECK( *(static_cast<Rect *>(&rg2)) == *(static_cast<Rect *>(&rg4)) );
delete pg2;
delete pg3;
delete pr2;
}
template<typename IStream, typename OStream>
void testSmartPointers()
{
using namespace Test;
{
// std::auto_ptr
int *pn = new int;
*pn = 1;
std::auto_ptr<int> apn(pn);
std::auto_ptr<double> apd( (double *) NULL );
std::ostringstream os;
OStream ostr(os);
ostr.enableContext();
ostr << pn << apn << apd;
pn = NULL;
apn.reset();
std::istringstream is(os.str());
IStream istr(is);
istr >> pn >> apn >> apd;
BOOST_CHECK( pn != NULL && pn == apn.get() );
BOOST_CHECK( apd.get() == NULL );
}
{
// boost::shared_ptr, boost::scoped_ptr
int *pn = new int;
*pn = 2;
boost::shared_ptr<int> spn1(pn);
boost::shared_ptr<int> spn2 = spn1;
boost::shared_ptr<int> spn3 = spn2;
boost::shared_ptr<double> spd( (double *) NULL );
boost::scoped_ptr<int> scpn1( new int(53) );
boost::scoped_ptr<int> scpn2;
std::ostringstream os;
OStream ostr(os);
ostr.enableContext();
ostr << pn;
ostr << spn1;
ostr << spn2;
ostr << spn3;
ostr << spd;
ostr << scpn1;
pn = NULL;
spn1.reset();
spn2.reset();
spn3.reset();
std::istringstream is(os.str());
IStream istr(is);
istr >> pn >> spn1 >> spn2 >> spn3 >> spd >> scpn2;
BOOST_CHECK( pn != NULL );
BOOST_CHECK( pn == spn1.get() && pn == spn2.get() && pn == spn3.get() );
BOOST_CHECK( spn1.use_count() == 3 );
BOOST_CHECK( spd.get() == NULL );
BOOST_CHECK( scpn1.get() && scpn2.get() && *scpn1 == *scpn2 );
}
}
template<typename IStream, typename OStream>
void testADL()
{
// argument dependent lookup
Test::K1::A a1(1),a2(0);
Test::K1::K2::B b1(1),b2(0);
std::ostringstream os;
OStream ostr(os);
ostr << a1 << b1;
std::istringstream is(os.str());
IStream istr(is);
istr >> a2 >> b2;
BOOST_CHECK( a1 == a2 );
BOOST_CHECK( b1 == b2 );
}
template<typename IStream, typename OStream>
void testAll()
{
testAtomic<IStream,OStream>();
testComposite<IStream,OStream>();
testEmptyComposite<IStream,OStream>();
#ifndef __BORLANDC__
testArrays<IStream,OStream>();
#endif
testEnum<IStream,OStream>();
testContainers<IStream,OStream>();
testGraphs<IStream,OStream>();
testPolymorphism<IStream,OStream>();
testSmartPointers<IStream,OStream>();
testADL<IStream,OStream>();
}
//***********************************************************
int test_main(int argc, char **argv)
{
testAll<SF::ITextStream, SF::OTextStream>();
testAll<SF::IBinaryStream, SF::OBinaryStream>();
testAll<SF::INativeBinaryStream, SF::ONativeBinaryStream>();
return boost::exit_success;
}
| 26.291304 | 158 | 0.51294 | [
"object",
"vector"
] |
e152f1e7cdc7ab5a7360903b5f51ec2425a8218b | 2,058 | cxx | C++ | MITK/Applications/HandeyeCalibrationUsingRegistration/niftkHandeyeCalibrationUsingRegistration.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 13 | 2018-07-28T13:36:38.000Z | 2021-11-01T19:17:39.000Z | MITK/Applications/HandeyeCalibrationUsingRegistration/niftkHandeyeCalibrationUsingRegistration.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | null | null | null | MITK/Applications/HandeyeCalibrationUsingRegistration/niftkHandeyeCalibrationUsingRegistration.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 10 | 2018-08-20T07:06:00.000Z | 2021-07-07T07:55:27.000Z | /*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include <cstdlib>
#include <limits>
#include <mitkCameraCalibrationFacade.h>
#include <niftkHandeyeCalibrateUsingRegistration.h>
#include <niftkHandeyeCalibrationUsingRegistrationCLP.h>
int main(int argc, char** argv)
{
PARSE_ARGS;
int returnStatus = EXIT_FAILURE;
if ( modelInputFile.length() == 0 && modelTrackingDirectory.length() == 0)
{
std::cerr << "Error: no model data specified!" << std::endl;
commandLine.getOutput()->usage(commandLine);
return returnStatus;
}
if ( cameraPointsDirectory.length() == 0)
{
std::cerr << "Error: no camera data specified!" << std::endl;
commandLine.getOutput()->usage(commandLine);
return returnStatus;
}
try
{
niftk::HandeyeCalibrateUsingRegistration::Pointer calibrator = niftk::HandeyeCalibrateUsingRegistration::New();
calibrator->Calibrate(
modelInputFile,
modelTrackingDirectory,
cameraPointsDirectory,
handTrackingDirectory,
distanceThreshold,
errorThreshold,
output
);
returnStatus = EXIT_SUCCESS;
}
catch (mitk::Exception& e)
{
MITK_ERROR << "Caught mitk::Exception: " << e.GetDescription() << ", from:" << e.GetFile() << "::" << e.GetLine() << std::endl;
returnStatus = EXIT_FAILURE + 100;
}
catch (std::exception& e)
{
MITK_ERROR << "Caught std::exception: " << e.what() << std::endl;
returnStatus = EXIT_FAILURE + 101;
}
catch (...)
{
MITK_ERROR << "Caught unknown exception:" << std::endl;
returnStatus = EXIT_FAILURE + 102;
}
return returnStatus;
}
| 28.583333 | 131 | 0.630709 | [
"model"
] |
e15916b077b640ab707b7428a7817c31a2acf1d4 | 1,442 | cpp | C++ | 802/A[ Heidi and Library (easy) ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | 802/A[ Heidi and Library (easy) ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | 802/A[ Heidi and Library (easy) ].cpp | mejanvijay/codeforces-jvj_iit-submissions | 2a2aac7e93ca92e75887eff92361174aa36207c8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d",&x)
#define su(x) scanf("%u",&x)
#define slld(x) scanf("%lld",&x)
#define sc(x) scanf("%c",&x)
#define ss(x) scanf("%s",x)
#define sf(x) scanf("%f",&x)
#define slf(x) scanf("%lf",&x)
#define ll long long int
#define mod(x,n) (x+n)%n
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define Mod 1000000007
int Occ[87];
int A[87];
set<int> St;
set<int>::iterator it;
int main()
{
// freopen("input_file_name.in","r",stdin);
// freopen("output_file_name.out","w",stdout);
int i,j,k,l,m,n,x,y,z,a,b,r,ans = 0;
// ll i,j,k,l,m,n,x,y,z,a,b,r;
sd(n); sd(k);
for(i=0;i<n;i++)
sd(A[i]);
for(i=0;i<n;i++)
{
if(St.empty())
{
St.insert(A[i]);
ans++;
}
else if( St.count(A[i])==0 && St.size()<k )
{
St.insert(A[i]);
ans++;
}
else if( St.count(A[i])==0 && St.size()==k )
{
for(j=1;j<=n;j++)
Occ[j] = INT_MAX;
for(j=i+1;j<n;j++)
{
Occ[ A[j] ] = min(Occ[ A[j] ],j);
}
a = -1;
for(it=St.begin();it!=St.end();++it)
{
if(Occ[*it]>a)
{
a = Occ[*it];
b = *it;
}
}
St.erase(b);
St.insert(A[i]);
ans++;
}
}
printf("%d\n", ans );
return 0;
} | 17.166667 | 47 | 0.488211 | [
"vector"
] |
e15d23b983c1fcb437440f9c9be1d694adb7dc1c | 4,405 | cpp | C++ | inference-engine/tests/ngraph_helpers/lpt_ngraph_functions/src/transpose_function.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2022-02-10T08:05:09.000Z | 2022-02-10T08:05:09.000Z | inference-engine/tests/ngraph_helpers/lpt_ngraph_functions/src/transpose_function.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 40 | 2020-12-04T07:46:57.000Z | 2022-02-21T13:04:40.000Z | inference-engine/tests/ngraph_helpers/lpt_ngraph_functions/src/transpose_function.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2020-08-30T11:48:03.000Z | 2020-08-30T11:48:03.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "lpt_ngraph_functions/transpose_function.hpp"
#include <ngraph/opsets/opset1.hpp>
#include "lpt_ngraph_functions/common/builders.hpp"
namespace ngraph {
namespace builder {
namespace subgraph {
std::shared_ptr<ngraph::Function> TransposeFunction::getOriginal(
const ngraph::Shape& inputShape,
const std::vector<int>& transposeConstValues,
const ngraph::element::Type precisionBeforeDequantization,
const ngraph::builder::subgraph::DequantizationOperations& dequantization) {
const std::shared_ptr<op::v0::Parameter> input = std::make_shared<ngraph::opset1::Parameter>(
precisionBeforeDequantization,
ngraph::Shape(inputShape));
const std::shared_ptr<Node> dequantizationOp = makeDequantization(input, dequantization);
const std::shared_ptr<Node> transpose = std::make_shared<ngraph::opset1::Transpose>(
dequantizationOp,
std::make_shared<ngraph::opset1::Constant>(ngraph::element::i64, ngraph::Shape{ transposeConstValues.size() }, transposeConstValues));
transpose->set_friendly_name("output");
ngraph::ResultVector results{ std::make_shared<ngraph::opset1::Result>(transpose) };
return std::make_shared<ngraph::Function>(results, ngraph::ParameterVector{ input }, "TransposeFunction");
}
std::shared_ptr<ngraph::Function> TransposeFunction::getOriginal(
const ngraph::Shape& inputShape,
const std::vector<int>& transposeConstValues,
const ngraph::element::Type precisionBeforeFq,
const FakeQuantizeOnData& fqOnData) {
const std::shared_ptr<op::v0::Parameter> input = std::make_shared<ngraph::opset1::Parameter>(
precisionBeforeFq,
ngraph::Shape(inputShape));
const std::shared_ptr<Node> quantizationOp = fqOnData.empty() ?
std::dynamic_pointer_cast<ngraph::Node>(input) :
makeFakeQuantize(input, precisionBeforeFq, fqOnData);
const std::shared_ptr<Node> transpose = std::make_shared<ngraph::opset1::Transpose>(
quantizationOp,
std::make_shared<ngraph::opset1::Constant>(ngraph::element::i64, ngraph::Shape{ transposeConstValues.size() }, transposeConstValues));
ngraph::ResultVector results{ std::make_shared<ngraph::opset1::Result>(transpose) };
return std::make_shared<ngraph::Function>(results, ngraph::ParameterVector{ input }, "TransposeFunction");
}
std::shared_ptr<ngraph::Function> TransposeFunction::getReference(
const ngraph::Shape& inputShape,
const std::vector<int>& transposeConstValues,
const ngraph::element::Type precisionBeforeDequantization,
const ngraph::builder::subgraph::DequantizationOperations& dequantizationBefore,
const ngraph::element::Type precisionAfterOperation,
const ngraph::builder::subgraph::DequantizationOperations& dequantizationAfter) {
const std::shared_ptr<op::v0::Parameter> input = std::make_shared<ngraph::opset1::Parameter>(
precisionBeforeDequantization,
ngraph::Shape(inputShape));
const std::shared_ptr<Node> quantizationOpBefore = makeDequantization(input, dequantizationBefore);
const std::shared_ptr<ngraph::opset1::Constant> transposeConstant = std::make_shared<ngraph::opset1::Constant>(
ngraph::element::i64,
ngraph::Shape{ transposeConstValues.size() },
transposeConstValues);
const std::shared_ptr<ngraph::opset1::Transpose> transpose = std::make_shared<ngraph::opset1::Transpose>(quantizationOpBefore, transposeConstant);
if (quantizationOpBefore->get_output_element_type(0) != precisionAfterOperation) {
THROW_IE_LPT_EXCEPTION(*quantizationOpBefore) << "unexpected precision '" << precisionAfterOperation << "' after operation";
}
if (transpose->get_output_element_type(0) != precisionAfterOperation) {
THROW_IE_LPT_EXCEPTION(*transpose) << "unexpected precision '" << precisionAfterOperation << "' after operation";
}
const std::shared_ptr<Node> quantizationOpAfter = makeDequantization(transpose, dequantizationAfter);
quantizationOpAfter->set_friendly_name("output");
ngraph::ResultVector results{ std::make_shared<ngraph::opset1::Result>(quantizationOpAfter) };
return std::make_shared<ngraph::Function>(results, ngraph::ParameterVector{ input }, "TransposeFunction");
}
} // namespace subgraph
} // namespace builder
} // namespace ngraph
| 48.944444 | 150 | 0.745289 | [
"shape",
"vector"
] |
e15d5391f2ddd3cd5dd81dbb9947270058cb1230 | 2,010 | cpp | C++ | service/type-analysis/TypeAnalysisTransform.cpp | disconnect3d/redex | 86b7e12bc5a0eaeb6727dd3b348702f01c6306a5 | [
"MIT"
] | 1 | 2020-04-15T01:57:49.000Z | 2020-04-15T01:57:49.000Z | service/type-analysis/TypeAnalysisTransform.cpp | willpyshan13/redex | 0bb6a6ca434c4f57e825f0c3e0d47d7f1388529f | [
"MIT"
] | null | null | null | service/type-analysis/TypeAnalysisTransform.cpp | willpyshan13/redex | 0bb6a6ca434c4f57e825f0c3e0d47d7f1388529f | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "TypeAnalysisTransform.h"
#include "CFGMutation.h"
namespace type_analyzer {
constexpr const char* CHECK_PARAM_NULL_SIGNATURE =
"Lkotlin/jvm/internal/Intrinsics;.checkParameterIsNotNull:(Ljava/lang/"
"Object;Ljava/lang/String;)V";
constexpr const char* CHECK_EXPR_NULL_SIGNATURE =
"Lkotlin/jvm/internal/Intrinsics;.checkExpressionValueIsNotNull:(Ljava/"
"lang/Object;Ljava/lang/String;)V";
Transform::Stats Transform::apply(
const type_analyzer::local::LocalTypeAnalyzer& lta,
IRCode* code,
const NullAssertionSet& null_assertion_set) {
Transform::Stats stats{};
code->build_cfg();
cfg::ControlFlowGraph& cfg = code->cfg();
cfg::CFGMutation m(cfg);
for (const auto& block : cfg.blocks()) {
auto env = lta.get_entry_state_at(block);
if (env.is_bottom()) {
continue;
}
for (auto& mie : InstructionIterable(block)) {
auto it = code->iterator_to(mie);
auto* insn = mie.insn;
lta.analyze_instruction(insn, &env);
if (insn->opcode() == OPCODE_INVOKE_STATIC &&
null_assertion_set.count(insn->get_method())) {
auto parm = env.get(insn->src(0));
if (parm.is_top() || parm.is_bottom()) {
continue;
}
if (parm.is_not_null()) {
auto anchor = cfg.find_insn(insn, block);
m.remove(anchor);
stats.null_check_insn_removed++;
}
}
}
}
m.flush();
code->clear_cfg();
return stats;
}
void Transform::setup(NullAssertionSet& null_assertion_set) {
auto check_param_method = DexMethod::get_method(CHECK_PARAM_NULL_SIGNATURE);
auto check_expr_method = DexMethod::get_method(CHECK_EXPR_NULL_SIGNATURE);
null_assertion_set.insert(check_param_method);
null_assertion_set.insert(check_expr_method);
}
} // namespace type_analyzer
| 28.714286 | 78 | 0.68408 | [
"object",
"transform"
] |
ff1500550365564f016d9762d289c078fb216bd7 | 17,216 | cpp | C++ | vts-libs/tools-support/repackatlas.cpp | melowntech/vts-libs | ffbf889b6603a8f95d3c12a2602232ff9c5d2236 | [
"BSD-2-Clause"
] | 2 | 2020-04-20T01:44:46.000Z | 2021-01-15T06:54:51.000Z | vts-libs/tools-support/repackatlas.cpp | melowntech/vts-libs | ffbf889b6603a8f95d3c12a2602232ff9c5d2236 | [
"BSD-2-Clause"
] | 2 | 2020-01-29T16:30:49.000Z | 2020-06-03T15:21:29.000Z | vts-libs/tools-support/repackatlas.cpp | melowntech/vts-libs | ffbf889b6603a8f95d3c12a2602232ff9c5d2236 | [
"BSD-2-Clause"
] | 1 | 2019-09-25T05:10:07.000Z | 2019-09-25T05:10:07.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* 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 <set>
#include <vector>
#include "utility/expect.hpp"
#include "imgproc/uvpack.hpp"
#include "repackatlas.hpp"
namespace vtslibs { namespace vts { namespace tools {
inline math::Point2d denormalize(const math::Point2d &p
, const cv::Size &texSize)
{
return { (p(0) * texSize.width), ((1.0 - p(1)) * texSize.height) };
}
inline math::Points2d denormalize(const math::Points2d &ps
, const cv::Size &texSize)
{
math::Points2d out;
for (const auto &p : ps) {
out.push_back(denormalize(p, texSize));
}
return out;
}
inline math::Points2d denormalize(Faces faces
, const math::Points2d &tc
, const cv::Size &texSize
, const TextureRegionInfo ®ionInfo)
{
if (regionInfo.regions.empty()) { return denormalize(tc, texSize); }
math::Points2d out(tc.size());
std::vector<char> seen(tc.size(), false);
const auto &remap([&](int index, const TextureRegionInfo::Region
®ion) -> void
{
auto &iseen(seen[index]);
if (iseen) { return; }
// remap from region space to texture space
auto &itc(tc[index]);
auto &otc(out[index]);
otc(0) = itc(0) * region.size.width * texSize.width;
otc(1) = (1.0 - itc(1)) * region.size.height * texSize.height;
iseen = true;
});
auto ifaceRegion(regionInfo.faces.begin());
for (const auto &face : faces) {
const auto ®ion(regionInfo.regions[*ifaceRegion++]);
for (const auto &index : face) { remap(index, region); }
}
return out;
}
inline math::Point2d normalize(const imgproc::UVCoord &uv
, const math::Size2 &texSize)
{
return { uv.x / texSize.width
, 1.0 - uv.y / texSize.height };
}
class TextureInfo {
public:
typedef std::vector<TextureInfo> list;
TextureInfo(const SubMesh &sm, const cv::Mat &texture)
: tc_(denormalize(sm.tc, texture.size()))
, faces_(sm.facesTc), texture_(texture)
{}
TextureInfo(const SubMesh &sm, const cv::Mat &texture
, const TextureRegionInfo ®ionInfo)
: tc_(denormalize(sm.facesTc, sm.tc, texture.size(), regionInfo))
, faces_(sm.facesTc), texture_(texture)
, regionInfo_(regionInfo)
{
// prepare uv rectangles for regions
for (const auto ®ion : regionInfo_.regions) {
regionRects_.emplace_back();
auto &r(regionRects_.back());
const auto &rr(region.region);
r.update(rr.ll(0) * texture.cols, rr.ll(1) * texture.rows);
r.update(rr.ur(0) * texture.cols, rr.ur(1) * texture.rows);
}
}
const math::Points2d& tc() const { return tc_; }
const Faces& faces() const { return faces_; }
const cv::Mat& texture() const { return texture_; }
const math::Point2d& uv(const Face &face, int index) const {
return tc_[face(index)];
}
imgproc::UVCoord uvCoord(const Face &face, int index) const {
const auto &p(uv(face, index));
return imgproc::UVCoord(p(0), p(1));
}
const math::Point2d& uv(int index) const {
return tc_[index];
}
const Face& face(int faceIndex) const {
return (faces_)[faceIndex];
}
int faceRegion(int faceIndex) const {
return (regionInfo_.regions.empty()
? 0 : regionInfo_.faces[faceIndex]);
}
const imgproc::UVRect* regionRect(int regionId) const {
if (regionRects_.empty()) { return nullptr; }
return ®ionRects_[regionId];
}
private:
math::Points2d tc_;
Faces faces_;
cv::Mat texture_;
const TextureRegionInfo regionInfo_;
std::vector<imgproc::UVRect> regionRects_;
};
namespace {
typedef Face::value_type VertexIndex;
typedef std::set<VertexIndex> VertexIndices;
/** Continuous mesh component.
*/
struct Component {
/** Set of components's indices to faces
*/
std::set<int> faces;
/** Set of components's indices to texture coordinates
*/
VertexIndices indices;
/** UV rectangle.
*/
imgproc::UVRect rect;
/** Region this texturing component belongs to. Defaults to 0 for
* non-regioned textures.
*/
int regionId;
typedef std::shared_ptr<Component> pointer;
typedef std::vector<pointer> list;
typedef std::set<pointer> set;
Component() {}
Component(int findex, const Face &face, const TextureInfo &tx
, int regionId = 0)
: faces{findex}, indices{face(0), face(1), face(2)}
, regionId(regionId)
{
rect.update(tx.uvCoord(face, 0));
rect.update(tx.uvCoord(face, 1));
rect.update(tx.uvCoord(face, 2));
}
void add(int findex, const Face &face, const TextureInfo &tx) {
faces.insert(findex);
indices.insert({ face(0), face(1), face(2) });
rect.update(tx.uvCoord(face, 0));
rect.update(tx.uvCoord(face, 1));
rect.update(tx.uvCoord(face, 2));
}
void add(const Component &other) {
faces.insert(other.faces.begin(), other.faces.end());
indices.insert(other.indices.begin(), other.indices.end());
rect.update(other.rect.min);
rect.update(other.rect.max);
}
void copy(cv::Mat &tex, const cv::Mat &texture, const TextureInfo &tx)
const;
imgproc::UVCoord adjustUV(const math::Point2 &p) const {
imgproc::UVCoord c(p(0), p(1));
rect.adjustUV(c);
return c;
}
};
namespace {
void clipToLowerBound(int &spos, int &ssize, int &dpos, int &dsize
, const char*)
{
if (spos >= 0) { return; }
const auto diff(-spos);
spos = 0;
ssize -= diff;
dpos += diff;
dsize -= diff;
}
void clipToUpperBound(int limit, int &spos, int &ssize, int &dsize
, const char*)
{
const auto send(spos + ssize);
if (send <= limit) { return; }
const auto diff(send - limit);
ssize -= diff;
dsize -= diff;
}
void copyFromRegion(const imgproc::UVRect ®ionRect
, const imgproc::UVRect &rect
, cv::Mat &tex, const cv::Mat &texture)
{
LOG(info2)
<< "About to copy regional patch: src: "
<< rect.width() << "x" << rect.height()
<< " " << rect.x() << " " << rect.y()
<< "; dst: "
<< rect.width() << "x" << rect.height()
<< " " << rect.packX << " " << rect.packY
<< "; region: "
<< regionRect.width() << "x" << regionRect.height()
<< " " << regionRect.x() << " " << regionRect.y()
;
const auto wrap([](int pos, int origin, int size) -> int
{
auto mod(pos % size);
if (mod < 0) { mod += size; }
return origin + mod;
});
const math::Point2i regionOrigin(regionRect.x(), regionRect.y());
const math::Size2 regionSize(regionRect.width(), regionRect.height());
const math::Size2 size(rect.width(), rect.height());
const math::Point2i diff(regionOrigin(0) - rect.x()
, regionOrigin(1) - rect.y());
// copy data
for (int j(0), je(size.height); j != je; ++j) {
const auto jsrc(wrap(j - diff(1), regionOrigin(1), regionSize.height));
if ((jsrc < 0) || (jsrc >= texture.rows)) { continue; }
for (int i(0), ie(size.width); i != ie; ++i) {
const auto isrc
(wrap(i - diff(0), regionOrigin(0), regionSize.width));
if ((isrc < 0) || (isrc >= texture.cols)) { continue; }
tex.at<cv::Vec3b>(rect.packY + j, rect.packX + i)
= texture.at<cv::Vec3b>(jsrc, isrc);
}
}
}
} // namespace
void Component::copy(cv::Mat &tex, const cv::Mat &texture
, const TextureInfo &tx) const
{
if (const auto *regionRect = tx.regionRect(regionId)) {
copyFromRegion(*regionRect, rect, tex, texture);
return;
}
cv::Rect src(rect.x(), rect.y(), rect.width(), rect.height());
cv::Rect dst(rect.packX, rect.packY, rect.width(), rect.height());
// clip if source is out of bounds
clipToLowerBound(src.x, src.width, dst.x, dst.width, "left");
clipToLowerBound(src.y, src.height, dst.y, dst.height, "top");
clipToUpperBound(texture.cols, src.x, src.width, dst.width, "right");
clipToUpperBound(texture.rows, src.y, src.height, dst.height, "bottom");
if ((src.width <= 0) || (src.height <= 0)) { return; }
cv::Mat dstPatch(tex, dst);
cv::Mat(texture, src).copyTo(dstPatch);
}
struct ComponentInfo {
/** Mesh broken to continuous components.
*/
Component::set components;
/** Mapping between texture coordinate index to owning component.
*/
Component::list tcMap;
/** Texturing information, i.e. the context of the problem.
*/
TextureInfo *tx;
typedef std::vector<ComponentInfo> list;
ComponentInfo(const TileId &tileId, int id, TextureInfo &tx);
cv::Mat composeTexture(const math::Size2 &ts) const {
const auto &texture(tx->texture());
cv::Mat tex(ts.height, ts.width, texture.type());
tex = cv::Scalar(0, 0, 0);
for (const auto &c : components) {
c->copy(tex, texture, *tx);
}
return tex;
}
math::Points2d composeTc(const math::Size2 &ts) const {
math::Points2d tc;
auto itcMap(tcMap.begin());
for (const auto &oldUv : tx->tc()) {
tc.push_back(normalize((*itcMap++)->adjustUV(oldUv), ts));
}
return tc;
}
private:
TileId tileId_;
int id_;
};
ComponentInfo::ComponentInfo(const TileId &tileId, int id, TextureInfo &tx)
: tcMap(tx.tc().size()), tx(&tx), tileId_(tileId), id_(id)
{
const auto &faces(tx.faces());
Component::list fMap(tx.faces().size());
Component::list tMap(tx.tc().size());
typedef std::array<Component::pointer*, 3> FaceComponents;
// sorts face per-vertex components by number of faces
// no components are considered empty
auto sortBySize([](FaceComponents &fc)
{
std::sort(fc.begin(), fc.end()
, [](const Component::pointer *l,
const Component::pointer *r) -> bool
{
// prefer non-null
if (!*l) { return false; }
if (!*r) { return true; }
// both are non-null; prefer longer
return ((**l).faces.size() > (**r).faces.size());
});
});
for (std::size_t i(0), e(faces.size()); i != e; ++i) {
const auto &face(faces[i]);
const auto regionId(tx.faceRegion(i));
FaceComponents fc =
{ { &tMap[face(0)], &tMap[face(1)], &tMap[face(2)] } };
sortBySize(fc);
auto assign([&](Component::pointer &owner, Component::pointer &owned)
-> void
{
// no-op
if (owned == owner) { return; }
if (!owned) {
// no component assigned yet
owned = owner;
return;
}
// forget this component beforehand
components.erase(owned);
// grab owned by value to prevent overwrite
const auto old(*owned);
// merge components
owner->add(old);
// move everything to owner
for (auto index : old.faces) { fMap[index] = owner; }
for (auto index : old.indices) { tMap[index] = owner; }
});
if (*fc[0] || *fc[1] || *fc[2]) {
auto &owner(*fc[0]);
fMap[i] = owner;
owner->add(i, face, tx);
assign(owner, *fc[1]);
assign(owner, *fc[2]);
} else {
// create new component
components.insert
(fMap[i] = *fc[0] = *fc[1] = *fc[2]
= std::make_shared<Component>(i, face, tx, regionId));
}
}
// map tc
for (auto &c : components) {
for (const auto &index : c->indices) {
tcMap[index] = c;
}
c->rect.inflate(1.0);
std::set<int> regions;
for (const auto &face : c->faces) {
regions.insert(tx.faceRegion(face));
}
if (regions.size() != 1) {
LOGTHROW(info4, std::runtime_error)
<< "Multiple regions in single component: "
<< utility::join(regions, ",", "-");
}
}
}
} // namespace
void repack(const TileId &tileId, vts::Mesh &mesh, opencv::Atlas &atlas)
{
utility::expect(mesh.submeshes.size() == atlas.size()
, "Tile %s: Number of submeshes (%d) is different from "
"texture count (%d).", tileId, mesh.submeshes.size()
, atlas.size());
int idx(0);
for (auto &sm : mesh) {
// prepare texturing stufff
TextureInfo tx(sm, atlas.get(idx));
ComponentInfo cinfo(tileId, idx, tx);
// pack patches into new atlas
auto packedSize([&]() -> math::Size2
{
// pack the patches
imgproc::RectPacker packer;
for (auto &c : cinfo.components) {
packer.addRect(&c->rect);
}
packer.pack();
return math::Size2(packer.width(), packer.height());
}());
atlas.set(idx, cinfo.composeTexture(packedSize));
sm.tc = cinfo.composeTc(packedSize);
++idx;
}
}
void repack(const TileId &tileId, Mesh &mesh, opencv::Atlas &atlas
, const TextureRegionInfo::list &textureRegions)
{
utility::expect(mesh.submeshes.size() == atlas.size()
, "Tile %s: Number of submeshes (%d) is different from "
"texture count (%d).", tileId, mesh.submeshes.size()
, atlas.size());
utility::expect(mesh.submeshes.size() == textureRegions.size()
, "Tile %s: Number of submeshes (%d) is different from "
"texture region info count (%d).", tileId
, mesh.submeshes.size(), textureRegions.size());
int idx(0);
auto iregions(textureRegions.begin());
for (auto &sm : mesh) {
const auto &textureRegion(*iregions++);
if (!textureRegion.regions.empty()) {
std::vector<int> tcRegions(sm.tc.size(), -1);
auto itxFaces(textureRegion.faces.begin());
for (const auto &f : sm.facesTc) {
const auto txFace(*itxFaces++);
for (const auto tc : f) {
auto &tcRegion(tcRegions[tc]);
if (tcRegion < 0) {
tcRegion = txFace;
} else if (tcRegion != txFace) {
LOG(warn4)
<< "Texture coordinate " << tc
<< " belongs to two components: "
<< tcRegion << " and " << txFace << ".";
}
}
}
}
// prepare texturing stufff
TextureInfo tx(sm, atlas.get(idx), textureRegion);
ComponentInfo cinfo(tileId, idx, tx);
// pack patches into new atlas
auto packedSize([&]() -> math::Size2
{
// pack the patches
imgproc::RectPacker packer;
for (auto &c : cinfo.components) {
packer.addRect(&c->rect);
}
packer.pack();
return math::Size2(packer.width(), packer.height());
}());
atlas.set(idx, cinfo.composeTexture(packedSize));
sm.tc = cinfo.composeTc(packedSize);
++idx;
}
}
} } } // namespace vtslibs::vts::tools
| 31.01982 | 79 | 0.555065 | [
"mesh",
"vector"
] |
ff19e17c8da5a7d279569c85271af3aa56ed0f5e | 545 | cpp | C++ | Engine/Mewtle/EntryPoint.cpp | TinSlam/Mewtle | 3d178c4523a6a70fd362f781b7a92847f6bac559 | [
"Apache-2.0"
] | null | null | null | Engine/Mewtle/EntryPoint.cpp | TinSlam/Mewtle | 3d178c4523a6a70fd362f781b7a92847f6bac559 | [
"Apache-2.0"
] | null | null | null | Engine/Mewtle/EntryPoint.cpp | TinSlam/Mewtle | 3d178c4523a6a70fd362f781b7a92847f6bac559 | [
"Apache-2.0"
] | null | null | null | #include <MewtlePreCompiledHeaders.h> // Add this line at the beginning of every cpp file.
#include "Mewtle.h" // The engine interface.
#include <Mewtle/Core/EntryPoint.h>
Mewtle::State* Mewtle::createInitialState(){
// Return your initial state.
return nullptr;
}
void Mewtle::init(){
MTL_INFO("Client init.");
}
void Mewtle::loadModels(){
MTL_INFO("Client load models.");
}
void Mewtle::loadTextures(){
MTL_INFO("Client load textures.");
}
void Mewtle::tick(){
MTL_INFO("Tick...");
}
void Mewtle::render(){
MTL_INFO("Render");
} | 18.166667 | 90 | 0.699083 | [
"render"
] |
ff1dcfde06bfa238645968c8d73d26c376bdf06c | 1,092 | cxx | C++ | panda/src/linmath/mathNumbers.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/linmath/mathNumbers.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/linmath/mathNumbers.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file mathNumbers.cxx
* @author mike
* @date 1999-09-24
*/
#include "mathNumbers.h"
#include <math.h>
const double MathNumbers::pi_d = 4.0 * atan(1.0);
const double MathNumbers::ln2_d = log(2.0);
const double MathNumbers::rad_2_deg_d = 180.0 / MathNumbers::pi_d;
const double MathNumbers::deg_2_rad_d = MathNumbers::pi_d / 180.0;
const float MathNumbers::pi_f = 4.0 * atan(1.0);
const float MathNumbers::ln2_f = log(2.0);
const float MathNumbers::rad_2_deg_f = 180.0 / MathNumbers::pi_d;
const float MathNumbers::deg_2_rad_f = MathNumbers::pi_d / 180.0;
const PN_stdfloat MathNumbers::pi = 4.0 * atan(1.0);
const PN_stdfloat MathNumbers::ln2 = log(2.0);
const PN_stdfloat MathNumbers::rad_2_deg = 180.0 / MathNumbers::pi_d;
const PN_stdfloat MathNumbers::deg_2_rad = MathNumbers::pi_d / 180.0;
| 35.225806 | 70 | 0.729853 | [
"3d"
] |
ff1e90b7d002256005d2f668775af09a91aa2f0b | 3,602 | cpp | C++ | UIShop/TransformDialogDlg.cpp | swjsky/sktminest | 42fa47d9ffb0f50a5727e42811e949fff920bec9 | [
"MIT"
] | 3 | 2019-12-03T09:04:04.000Z | 2021-01-29T02:03:30.000Z | UIShop/TransformDialogDlg.cpp | dushulife/LibUIDK | 04e79e64eaadfaa29641c24e9cddd9abde544aac | [
"MIT"
] | null | null | null | UIShop/TransformDialogDlg.cpp | dushulife/LibUIDK | 04e79e64eaadfaa29641c24e9cddd9abde544aac | [
"MIT"
] | 2 | 2020-06-12T04:30:31.000Z | 2020-11-25T13:23:03.000Z | // TransformDialogDlg.cpp : implementation file
//
#include "stdafx.h"
#include "UIShop.h"
#include "TransformDialogDlg.h"
#include "TransformDialog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// CTransformDialogDlg dialog
IMPLEMENT_DYNAMIC(CTransformDialogDlg, CDialog)
CTransformDialogDlg::CTransformDialogDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTransformDialogDlg::IDD, pParent)
{
}
CTransformDialogDlg::~CTransformDialogDlg()
{
}
void CTransformDialogDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDT_RES_SOURCE, m_strResSource);
DDX_Text(pDX, IDC_EDT_XUI_TARGET, m_strXUITarget);
}
BEGIN_MESSAGE_MAP(CTransformDialogDlg, CDialog)
ON_BN_CLICKED(IDC_BTN_BROWSE_RES, &CTransformDialogDlg::OnBnClickedBtnBrowseRes)
ON_BN_CLICKED(IDC_BTN_GO_SOURCE, &CTransformDialogDlg::OnBnClickedBtnGoSource)
ON_BN_CLICKED(IDC_BTN_BROWSE_XUI, &CTransformDialogDlg::OnBnClickedBtnBrowseXui)
ON_BN_CLICKED(IDC_BTN_GO_TARGET, &CTransformDialogDlg::OnBnClickedBtnGoTarget)
ON_BN_CLICKED(IDC_BTN_TRANSFORM, &CTransformDialogDlg::OnBnClickedBtnTransform)
END_MESSAGE_MAP()
// CTransformDialogDlg message handlers
void CTransformDialogDlg::OnBnClickedBtnBrowseRes()
{
if (!UpdateData())
return;
TCHAR szFilters[] = _T("All Supported File Types(*.exe, *.rc)|*.exe; *.rc|Exe Files(*.exe)|*.exe|RC Files(*.rc)|*.rc||");
CFileDialog dlg(TRUE, NULL, NULL, OFN_FILEMUSTEXIST, szFilters);
INT_PTR nRet = dlg.DoModal();
if (nRet == IDOK)
{
m_strResSource = dlg.GetPathName();
UpdateData(FALSE);
}
}
void CTransformDialogDlg::OnBnClickedBtnGoSource()
{
BOOL bRet = UpdateData();
if (!bRet)
return;
int nRet = (int)ShellExecute(NULL, _T("open"), GetFilePath(m_strResSource), NULL, NULL, SW_SHOW);
if (nRet > 32)
return; // Successful.
if (nRet == ERROR_FILE_NOT_FOUND || nRet == ERROR_PATH_NOT_FOUND)
{
AfxMessageBox(_T("The specified file or path was not found!"), MB_ICONERROR);
}
else
{
AfxMessageBox(_T("Failed to open the specified path!"), MB_ICONERROR);
}
}
void CTransformDialogDlg::OnBnClickedBtnBrowseXui()
{
if (!UpdateData())
return;
TCHAR szFilters[] = _T("XUI Files(*.xui)|*.xui||");
CFileDialog dlg(FALSE, _T("xui"), _T("Untitled.xui"), OFN_HIDEREADONLY, szFilters);
INT_PTR nRet = dlg.DoModal();
if (nRet == IDOK)
{
m_strXUITarget = dlg.GetPathName();
UpdateData(FALSE);
}
}
void CTransformDialogDlg::OnBnClickedBtnGoTarget()
{
BOOL bRet = UpdateData();
if (!bRet)
return;
int nRet = (int)ShellExecute(NULL, _T("open"), GetFilePath(m_strXUITarget), NULL, NULL, SW_SHOW);
if (nRet > 32)
return; // Successful.
if (nRet == ERROR_FILE_NOT_FOUND || nRet == ERROR_PATH_NOT_FOUND)
{
AfxMessageBox(_T("The specified file or path was not found!"), MB_ICONERROR);
}
else
{
AfxMessageBox(_T("Failed to open the specified path!"), MB_ICONERROR);
}
}
void CTransformDialogDlg::OnBnClickedBtnTransform()
{
if (!UpdateData())
return;
if (m_strResSource.IsEmpty())
{
AfxMessageBox(_T("Please input source file"));
return;
}
if (m_strXUITarget.IsEmpty())
{
AfxMessageBox(_T("Please input target file"));
return;
}
CTransformDialog td;
int nRet = td.Transform(m_strResSource, m_strXUITarget);
if (nRet == -2)
{
CString strMsg;
strMsg.Format(_T("Failded to open source file : %s"), m_strResSource);
AfxMessageBox(strMsg);
}
EndDialog(IDC_BTN_TRANSFORM);
}
| 24.174497 | 123 | 0.707385 | [
"transform"
] |
ff2288068bbc8ad3f939c63cb5e809d8892cd211 | 14,811 | cpp | C++ | src/jsgeoda_clustering.cpp | lixun910/wasmgeoda | 59beb864ba5baac142b92c84ed483003aa410607 | [
"MIT"
] | null | null | null | src/jsgeoda_clustering.cpp | lixun910/wasmgeoda | 59beb864ba5baac142b92c84ed483003aa410607 | [
"MIT"
] | null | null | null | src/jsgeoda_clustering.cpp | lixun910/wasmgeoda | 59beb864ba5baac142b92c84ed483003aa410607 | [
"MIT"
] | 1 | 2022-01-12T17:19:31.000Z | 2022-01-12T17:19:31.000Z | //
// Created by Xun Li on 6/3/21. <lixun910@gmail.com>
//
#include "../libgeoda_src/gda_clustering.h"
#include "../libgeoda_src/GenUtils.h"
#include "geojson.h"
#include "jsgeoda.h"
extern std::map<std::string, GdaGeojson*> geojson_maps;
ClusteringResult redcap(const std::string map_uid, const std::string weight_uid, int k, const std::string &method,
const std::vector<std::vector<double> > &data,
const std::vector<double>& bound_vals, double min_bound,
const std::string& scale_method, const std::string &distance_method)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
int nCPUs = 1;
int seed = 123456789;// not used
std::vector<std::vector<int> > cluster_ids = gda_redcap(k, w, data, scale_method, method, distance_method,
bound_vals, min_bound, seed, nCPUs);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
}
ClusteringResult schc(const std::string map_uid, const std::string weight_uid, int k, const std::string &method,
const std::vector<std::vector<double> > &data,
const std::vector<double>& bound_vals, double min_bound,
const std::string& scale_method, const std::string &distance_method)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
std::vector<std::vector<int> > cluster_ids = gda_schc(k, w, data, scale_method, method, distance_method,
bound_vals, min_bound);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
}
ClusteringResult azp_greedy(const std::string map_uid, const std::string weight_uid, int k,
const std::vector<std::vector<double> > &data, int inits, const std::vector<int>& init_regions,
const std::string& scale_method, const std::string &distance_method,
const std::vector<std::vector<double> >& min_bounds_values, const std::vector<double>& min_bounds,
const std::vector<std::vector<double> >& max_bounds_values, const std::vector<double>& max_bounds,
int seed)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
int seed = 123456789;// not used
std::vector<std::pair<double, std::vector<double> > > in_min_bounds, in_max_bounds;
for (int i=0; i<min_bounds.size(); ++i) {
in_min_bounds.push_back(std::make_pair(min_bounds[i], min_bounds_values[i]));
}
for (int i=0; i<max_bounds.size(); ++i) {
in_max_bounds.push_back(std::make_pair(max_bounds[i], max_bounds_values[i]));
}
std::vector<std::vector<int> > cluster_ids = gda_azp_greedy(k, w, data, scale_method, inits,
in_min_bounds, in_max_bounds, init_regions,
distance_method, seed);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
}
ClusteringResult azp_sa(const std::string map_uid, const std::string weight_uid, int k, double cooling_rate, int sa_maxit,
const std::vector<std::vector<double> > &data, int inits, const std::vector<int>& init_regions,
const std::string& scale_method, const std::string &distance_method,
const std::vector<std::vector<double> >& min_bounds_values, const std::vector<double>& min_bounds,
const std::vector<std::vector<double> >& max_bounds_values, const std::vector<double>& max_bounds,
int seed)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
int seed = 123456789;// not used
std::vector<std::pair<double, std::vector<double> > > in_min_bounds, in_max_bounds;
for (int i=0; i<min_bounds.size(); ++i) {
in_min_bounds.push_back(std::make_pair(min_bounds[i], min_bounds_values[i]));
}
for (int i=0; i<max_bounds.size(); ++i) {
in_max_bounds.push_back(std::make_pair(max_bounds[i], max_bounds_values[i]));
}
std::vector<std::vector<int> > cluster_ids = gda_azp_sa(k, w, data, scale_method, inits, cooling_rate, sa_maxit,
in_min_bounds, in_max_bounds, init_regions,
distance_method, seed);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
}
ClusteringResult azp_tabu(const std::string map_uid, const std::string weight_uid, int k, int tabu_length, int conv_tabu,
const std::vector<std::vector<double> > &data, int inits, const std::vector<int>& init_regions,
const std::string& scale_method, const std::string &distance_method,
const std::vector<std::vector<double> >& min_bounds_values, const std::vector<double>& min_bounds,
const std::vector<std::vector<double> >& max_bounds_values, const std::vector<double>& max_bounds,
int seed)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
int seed = 123456789;// not used
std::vector<std::pair<double, std::vector<double> > > in_min_bounds, in_max_bounds;
for (int i=0; i<min_bounds.size(); ++i) {
in_min_bounds.push_back(std::make_pair(min_bounds[i], min_bounds_values[i]));
}
for (int i=0; i<max_bounds.size(); ++i) {
in_max_bounds.push_back(std::make_pair(max_bounds[i], max_bounds_values[i]));
}
std::vector<std::vector<int> > cluster_ids = gda_azp_tabu(k, w, data, scale_method, inits, tabu_length, conv_tabu,
in_min_bounds, in_max_bounds, init_regions,
distance_method, seed);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
}
ClusteringResult maxp_greedy(const std::string map_uid, const std::string weight_uid,
const std::vector<std::vector<double> > &data, int iterations,
const std::string& scale_method, const std::string &distance_method,
const std::vector<std::vector<double> >& min_bounds_values, const std::vector<double>& min_bounds,
const std::vector<std::vector<double> >& max_bounds_values, const std::vector<double>& max_bounds,
int seed)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
int seed = 123456789;// not used
std::vector<std::pair<double, std::vector<double> > > in_min_bounds, in_max_bounds;
for (int i=0; i<min_bounds.size(); ++i) {
in_min_bounds.push_back(std::make_pair(min_bounds[i], min_bounds_values[i]));
}
for (int i=0; i<max_bounds.size(); ++i) {
in_max_bounds.push_back(std::make_pair(max_bounds[i], max_bounds_values[i]));
}
std::vector<int> init_regions;
std::vector<std::vector<int> > cluster_ids = gda_maxp_greedy(w, data, scale_method, iterations,
in_min_bounds, in_max_bounds, init_regions,
distance_method, seed, 1);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
}
ClusteringResult maxp_sa(const std::string map_uid, const std::string weight_uid,
const std::vector<std::vector<double> > &data, int iterations, double cooling_rate, int sa_maxit,
const std::string& scale_method, const std::string &distance_method,
const std::vector<std::vector<double> >& min_bounds_values, const std::vector<double>& min_bounds,
const std::vector<std::vector<double> >& max_bounds_values, const std::vector<double>& max_bounds,
int seed)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
int seed = 123456789;// not used
std::vector<std::pair<double, std::vector<double> > > in_min_bounds, in_max_bounds;
for (int i=0; i<min_bounds.size(); ++i) {
in_min_bounds.push_back(std::make_pair(min_bounds[i], min_bounds_values[i]));
}
for (int i=0; i<max_bounds.size(); ++i) {
in_max_bounds.push_back(std::make_pair(max_bounds[i], max_bounds_values[i]));
}
std::vector<int> init_regions;
std::vector<std::vector<int> > cluster_ids = gda_maxp_sa(w, data, scale_method, iterations, cooling_rate, sa_maxit,
in_min_bounds, in_max_bounds, init_regions,
distance_method, seed, 1);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
}
ClusteringResult maxp_tabu(const std::string map_uid, const std::string weight_uid,
const std::vector<std::vector<double> > &data, int iterations, int tabu_length, int conv_tabu,
const std::string& scale_method, const std::string &distance_method,
const std::vector<std::vector<double> >& min_bounds_values, const std::vector<double>& min_bounds,
const std::vector<std::vector<double> >& max_bounds_values, const std::vector<double>& max_bounds,
int seed)
{
ClusteringResult rst;
rst.is_valid = false;
GdaGeojson *json_map = geojson_maps[map_uid];
if (json_map) {
GeoDaWeight *w = json_map->GetWeights(weight_uid);
if (w) {
int seed = 123456789;// not used
std::vector<std::pair<double, std::vector<double> > > in_min_bounds, in_max_bounds;
for (int i=0; i<min_bounds.size(); ++i) {
in_min_bounds.push_back(std::make_pair(min_bounds[i], min_bounds_values[i]));
}
for (int i=0; i<max_bounds.size(); ++i) {
in_max_bounds.push_back(std::make_pair(max_bounds[i], max_bounds_values[i]));
}
std::vector<int> init_regions;
std::vector<std::vector<int> > cluster_ids = gda_maxp_tabu(w, data, scale_method, iterations, tabu_length, conv_tabu,
in_min_bounds, in_max_bounds, init_regions,
distance_method, seed, 1);
rst.is_valid = true;
rst.between_ss = gda_betweensumofsquare(cluster_ids, data);
rst.total_ss = gda_totalsumofsquare(data);
rst.ratio = rst.between_ss / rst.total_ss;
rst.within_ss = gda_withinsumofsquare(cluster_ids, data);
rst.cluster_vec = GenUtils::flat_2dclusters(w->num_obs, cluster_ids);
}
}
return rst;
} | 48.720395 | 129 | 0.571265 | [
"vector"
] |
ff22fbca9f54d56717277009c1250bf9f7a3545c | 869 | hpp | C++ | src/Heap.hpp | wheybags/wcp | 57c5e64fb65dd8c282309b7cd9d26484fc9b7e56 | [
"MIT"
] | 175 | 2021-03-07T13:43:17.000Z | 2022-01-22T23:57:05.000Z | src/Heap.hpp | wheybags/wcp | 57c5e64fb65dd8c282309b7cd9d26484fc9b7e56 | [
"MIT"
] | 13 | 2021-03-07T22:21:33.000Z | 2021-12-10T21:41:28.000Z | src/Heap.hpp | wheybags/wcp | 57c5e64fb65dd8c282309b7cd9d26484fc9b7e56 | [
"MIT"
] | 7 | 2021-03-08T13:24:44.000Z | 2021-07-06T00:45:11.000Z | #pragma once
#include <cstdlib>
#include <vector>
#include <cstdint>
#include <atomic>
#include <pthread.h>
// Thread safe slab allocator
class Heap
{
public:
explicit Heap(size_t blocks, size_t blockSize, size_t alignment = 4096);
Heap(Heap&& other);
~Heap();
Heap(const Heap&) = delete;
Heap& operator=(const Heap&) = delete;
uint8_t* getBlock();
void returnBlock(uint8_t* block);
size_t getBlockCount() const { return this->blocks; }
size_t getBlockSize() const { return this->blockSize; }
size_t getAlignment() const { return this->alignment; }
// NOT thread safe
size_t getFreeBlocksCount() const;
private:
std::atomic_bool* usedList = nullptr;
std::atomic_uint32_t valgrindModeUsedCount = 0;
uint8_t* data = nullptr;
size_t blocks = 0;
size_t blockSize = 0;
size_t alignment = 0;
};
| 22.282051 | 76 | 0.673188 | [
"vector"
] |
ff23050506a20aea25eec743ed498f2789b8aa07 | 3,367 | cpp | C++ | examples/freertos_tasks.cpp | gregsyoung/SensESP | 4be5286f9b156b94ce6f7918cdfadbe40580b08c | [
"Apache-2.0"
] | null | null | null | examples/freertos_tasks.cpp | gregsyoung/SensESP | 4be5286f9b156b94ce6f7918cdfadbe40580b08c | [
"Apache-2.0"
] | null | null | null | examples/freertos_tasks.cpp | gregsyoung/SensESP | 4be5286f9b156b94ce6f7918cdfadbe40580b08c | [
"Apache-2.0"
] | null | null | null | /**
* @brief Example and test program for using FreeRTOS tasks.
*
*/
#include "sensesp/controllers/system_status_controller.h"
#include "sensesp/net/discovery.h"
#include "sensesp/net/http_server.h"
#include "sensesp/net/networking.h"
#include "sensesp/net/ws_client.h"
#include "sensesp/sensors/digital_input.h"
#include "sensesp/signalk/signalk_delta_queue.h"
#include "sensesp/signalk/signalk_output.h"
#include "sensesp/signalk/signalk_value_listener.h"
#include "sensesp/system/lambda_consumer.h"
#include "sensesp/system/system_status_led.h"
#include "sensesp_minimal_app_builder.h"
using namespace sensesp;
const int kTestOutputPin = GPIO_NUM_18;
// repetition interval in ms; corresponds to 1000/(2*5)=100 Hz
const int kTestOutputInterval = 410;
const uint8_t kDigitalInputPin = 15;
reactesp::ReactESP app;
void ToggleTestOutputPin(void *parameter) {
while (true) {
digitalWrite(kTestOutputPin, !digitalRead(kTestOutputPin));
delay(kTestOutputInterval);
}
}
// The setup function performs one-time application initialization.
void setup() {
// Some initialization boilerplate when in debug mode...
#ifndef SERIAL_DEBUG_DISABLED
SetupSerialDebug(115200);
#endif
SensESPMinimalAppBuilder builder;
SensESPMinimalApp *sensesp_app = builder.set_hostname("async")->get_app();
auto *networking = new Networking(
"/system/net", "", "", SensESPBaseApp::get_hostname(), "thisisfine");
auto *http_server = new HTTPServer();
// create the SK delta object
auto sk_delta_queue_ = new SKDeltaQueue();
// create the websocket client
auto ws_client_ = new WSClient("/system/sk", sk_delta_queue_, "", 0);
ws_client_->connect_to(new LambdaConsumer<WSConnectionState>(
[](WSConnectionState input) { debugD("WSConnectionState: %d", input); }));
// create the MDNS discovery object
auto mdns_discovery_ = new MDNSDiscovery();
// create a system status controller and a led blinker
auto *system_status_controller = new SystemStatusController();
auto *system_status_led = new SystemStatusLed(LED_BUILTIN);
system_status_controller->connect_to(system_status_led);
ws_client_->get_delta_count_producer().connect_to(system_status_led);
// create a new task for toggling the output pin
pinMode(kTestOutputPin, OUTPUT);
xTaskCreate(ToggleTestOutputPin, "toggler", 2048, NULL, 1, NULL);
// listen to the changes on the digital input pin
auto digin = new DigitalInputChange(kDigitalInputPin, INPUT_PULLUP, CHANGE);
digin->connect_to(new LambdaConsumer<bool>([](bool input) {
debugD("(%d ms) Digital input changed to %d", millis(), input);
}));
// connect digin to the SK delta queue
const char *sk_path = "environment.bool.pin15";
digin->connect_to(new SKOutputFloat(sk_path, ""));
// create a new SKListener for navigation.headingMagnetic
auto hdg = new SKValueListener<float>("navigation.headingMagnetic");
hdg->connect_to(new LambdaConsumer<float>([](float input) {
debugD("Heading: %f", input);
}));
// print out free heap
app.onRepeat(2000, []() {
debugD("Free heap: %d", ESP.getFreeHeap());
});
// Start the SensESP application running
sensesp_app->start();
}
// The loop function is called in an endless loop during program execution.
// It simply calls `app.tick()` which will then execute all reactions as needed.
void loop() { app.tick(); }
| 31.46729 | 80 | 0.74161 | [
"object"
] |
ff28850b280d04ea418dec299ef7f8f5a95df6ee | 11,867 | cc | C++ | test/syscalls/linux/unix_domain_socket_test_util.cc | Pixep/gVisor | dc36c34a766500507e4ac90547b58b88625bbc0d | [
"Apache-2.0"
] | null | null | null | test/syscalls/linux/unix_domain_socket_test_util.cc | Pixep/gVisor | dc36c34a766500507e4ac90547b58b88625bbc0d | [
"Apache-2.0"
] | null | null | null | test/syscalls/linux/unix_domain_socket_test_util.cc | Pixep/gVisor | dc36c34a766500507e4ac90547b58b88625bbc0d | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "test/syscalls/linux/unix_domain_socket_test_util.h"
#include <sys/un.h>
#include <vector>
#include "gtest/gtest.h"
#include "absl/strings/str_cat.h"
#include "test/util/test_util.h"
namespace gvisor {
namespace testing {
std::string DescribeUnixDomainSocketType(int type) {
const char* type_str = nullptr;
switch (type & ~(SOCK_NONBLOCK | SOCK_CLOEXEC)) {
case SOCK_STREAM:
type_str = "SOCK_STREAM";
break;
case SOCK_DGRAM:
type_str = "SOCK_DGRAM";
break;
case SOCK_SEQPACKET:
type_str = "SOCK_SEQPACKET";
break;
}
if (!type_str) {
return absl::StrCat("Unix domain socket with unknown type ", type);
} else {
return absl::StrCat(((type & SOCK_NONBLOCK) != 0) ? "non-blocking " : "",
((type & SOCK_CLOEXEC) != 0) ? "close-on-exec " : "",
type_str, " Unix domain socket");
}
}
SocketPairKind UnixDomainSocketPair(int type) {
return SocketPairKind{DescribeUnixDomainSocketType(type), AF_UNIX, type, 0,
SyscallSocketPairCreator(AF_UNIX, type, 0)};
}
SocketPairKind FilesystemBoundUnixDomainSocketPair(int type) {
std::string description = absl::StrCat(DescribeUnixDomainSocketType(type),
" created with filesystem binding");
if ((type & SOCK_DGRAM) == SOCK_DGRAM) {
return SocketPairKind{
description, AF_UNIX, type, 0,
FilesystemBidirectionalBindSocketPairCreator(AF_UNIX, type, 0)};
}
return SocketPairKind{
description, AF_UNIX, type, 0,
FilesystemAcceptBindSocketPairCreator(AF_UNIX, type, 0)};
}
SocketPairKind AbstractBoundUnixDomainSocketPair(int type) {
std::string description = absl::StrCat(DescribeUnixDomainSocketType(type),
" created with abstract namespace binding");
if ((type & SOCK_DGRAM) == SOCK_DGRAM) {
return SocketPairKind{
description, AF_UNIX, type, 0,
AbstractBidirectionalBindSocketPairCreator(AF_UNIX, type, 0)};
}
return SocketPairKind{description, AF_UNIX, type, 0,
AbstractAcceptBindSocketPairCreator(AF_UNIX, type, 0)};
}
SocketPairKind SocketpairGoferUnixDomainSocketPair(int type) {
std::string description = absl::StrCat(DescribeUnixDomainSocketType(type),
" created with the socketpair gofer");
return SocketPairKind{description, AF_UNIX, type, 0,
SocketpairGoferSocketPairCreator(AF_UNIX, type, 0)};
}
SocketPairKind SocketpairGoferFileSocketPair(int type) {
std::string description =
absl::StrCat(((type & O_NONBLOCK) != 0) ? "non-blocking " : "",
((type & O_CLOEXEC) != 0) ? "close-on-exec " : "",
"file socket created with the socketpair gofer");
// The socketpair gofer always creates SOCK_STREAM sockets on open(2).
return SocketPairKind{description, AF_UNIX, SOCK_STREAM, 0,
SocketpairGoferFileSocketPairCreator(type)};
}
SocketPairKind FilesystemUnboundUnixDomainSocketPair(int type) {
return SocketPairKind{absl::StrCat(DescribeUnixDomainSocketType(type),
" unbound with a filesystem address"),
AF_UNIX, type, 0,
FilesystemUnboundSocketPairCreator(AF_UNIX, type, 0)};
}
SocketPairKind AbstractUnboundUnixDomainSocketPair(int type) {
return SocketPairKind{
absl::StrCat(DescribeUnixDomainSocketType(type),
" unbound with an abstract namespace address"),
AF_UNIX, type, 0, AbstractUnboundSocketPairCreator(AF_UNIX, type, 0)};
}
void SendSingleFD(int sock, int fd, char buf[], int buf_size) {
ASSERT_NO_FATAL_FAILURE(SendFDs(sock, &fd, 1, buf, buf_size));
}
void SendFDs(int sock, int fds[], int fds_size, char buf[], int buf_size) {
struct msghdr msg = {};
std::vector<char> control(CMSG_SPACE(fds_size * sizeof(int)));
msg.msg_control = &control[0];
msg.msg_controllen = control.size();
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_len = CMSG_LEN(fds_size * sizeof(int));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
for (int i = 0; i < fds_size; i++) {
memcpy(CMSG_DATA(cmsg) + i * sizeof(int), &fds[i], sizeof(int));
}
ASSERT_THAT(SendMsg(sock, &msg, buf, buf_size),
IsPosixErrorOkAndHolds(buf_size));
}
void RecvSingleFD(int sock, int* fd, char buf[], int buf_size) {
ASSERT_NO_FATAL_FAILURE(RecvFDs(sock, fd, 1, buf, buf_size, buf_size));
}
void RecvSingleFD(int sock, int* fd, char buf[], int buf_size,
int expected_size) {
ASSERT_NO_FATAL_FAILURE(RecvFDs(sock, fd, 1, buf, buf_size, expected_size));
}
void RecvFDs(int sock, int fds[], int fds_size, char buf[], int buf_size) {
ASSERT_NO_FATAL_FAILURE(
RecvFDs(sock, fds, fds_size, buf, buf_size, buf_size));
}
void RecvFDs(int sock, int fds[], int fds_size, char buf[], int buf_size,
int expected_size, bool peek) {
struct msghdr msg = {};
std::vector<char> control(CMSG_SPACE(fds_size * sizeof(int)));
msg.msg_control = &control[0];
msg.msg_controllen = control.size();
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = buf_size;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
int flags = 0;
if (peek) {
flags |= MSG_PEEK;
}
ASSERT_THAT(RetryEINTR(recvmsg)(sock, &msg, flags),
SyscallSucceedsWithValue(expected_size));
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
ASSERT_NE(cmsg, nullptr);
ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(fds_size * sizeof(int)));
ASSERT_EQ(cmsg->cmsg_level, SOL_SOCKET);
ASSERT_EQ(cmsg->cmsg_type, SCM_RIGHTS);
for (int i = 0; i < fds_size; i++) {
memcpy(&fds[i], CMSG_DATA(cmsg) + i * sizeof(int), sizeof(int));
}
}
void RecvFDs(int sock, int fds[], int fds_size, char buf[], int buf_size,
int expected_size) {
ASSERT_NO_FATAL_FAILURE(
RecvFDs(sock, fds, fds_size, buf, buf_size, expected_size, false));
}
void PeekSingleFD(int sock, int* fd, char buf[], int buf_size) {
ASSERT_NO_FATAL_FAILURE(RecvFDs(sock, fd, 1, buf, buf_size, buf_size, true));
}
void RecvNoCmsg(int sock, char buf[], int buf_size, int expected_size) {
struct msghdr msg = {};
char control[CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(struct ucred))];
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = buf_size;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sock, &msg, 0),
SyscallSucceedsWithValue(expected_size));
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
EXPECT_EQ(cmsg, nullptr);
}
void SendNullCmsg(int sock, char buf[], int buf_size) {
struct msghdr msg = {};
msg.msg_control = nullptr;
msg.msg_controllen = 0;
ASSERT_THAT(SendMsg(sock, &msg, buf, buf_size),
IsPosixErrorOkAndHolds(buf_size));
}
void SendCreds(int sock, ucred creds, char buf[], int buf_size) {
struct msghdr msg = {};
char control[CMSG_SPACE(sizeof(struct ucred))];
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_CREDENTIALS;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
memcpy(CMSG_DATA(cmsg), &creds, sizeof(struct ucred));
ASSERT_THAT(SendMsg(sock, &msg, buf, buf_size),
IsPosixErrorOkAndHolds(buf_size));
}
void SendCredsAndFD(int sock, ucred creds, int fd, char buf[], int buf_size) {
struct msghdr msg = {};
char control[CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int))] = {};
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct cmsghdr* cmsg1 = CMSG_FIRSTHDR(&msg);
cmsg1->cmsg_level = SOL_SOCKET;
cmsg1->cmsg_type = SCM_CREDENTIALS;
cmsg1->cmsg_len = CMSG_LEN(sizeof(struct ucred));
memcpy(CMSG_DATA(cmsg1), &creds, sizeof(struct ucred));
struct cmsghdr* cmsg2 = CMSG_NXTHDR(&msg, cmsg1);
cmsg2->cmsg_level = SOL_SOCKET;
cmsg2->cmsg_type = SCM_RIGHTS;
cmsg2->cmsg_len = CMSG_LEN(sizeof(int));
memcpy(CMSG_DATA(cmsg2), &fd, sizeof(int));
ASSERT_THAT(SendMsg(sock, &msg, buf, buf_size),
IsPosixErrorOkAndHolds(buf_size));
}
void RecvCreds(int sock, ucred* creds, char buf[], int buf_size) {
ASSERT_NO_FATAL_FAILURE(RecvCreds(sock, creds, buf, buf_size, buf_size));
}
void RecvCreds(int sock, ucred* creds, char buf[], int buf_size,
int expected_size) {
struct msghdr msg = {};
char control[CMSG_SPACE(sizeof(struct ucred))];
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = buf_size;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sock, &msg, 0),
SyscallSucceedsWithValue(expected_size));
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
ASSERT_NE(cmsg, nullptr);
ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(struct ucred)));
ASSERT_EQ(cmsg->cmsg_level, SOL_SOCKET);
ASSERT_EQ(cmsg->cmsg_type, SCM_CREDENTIALS);
memcpy(creds, CMSG_DATA(cmsg), sizeof(struct ucred));
}
void RecvCredsAndFD(int sock, ucred* creds, int* fd, char buf[], int buf_size) {
struct msghdr msg = {};
char control[CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int))];
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = buf_size;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sock, &msg, 0),
SyscallSucceedsWithValue(buf_size));
struct cmsghdr* cmsg1 = CMSG_FIRSTHDR(&msg);
ASSERT_NE(cmsg1, nullptr);
ASSERT_EQ(cmsg1->cmsg_len, CMSG_LEN(sizeof(struct ucred)));
ASSERT_EQ(cmsg1->cmsg_level, SOL_SOCKET);
ASSERT_EQ(cmsg1->cmsg_type, SCM_CREDENTIALS);
memcpy(creds, CMSG_DATA(cmsg1), sizeof(struct ucred));
struct cmsghdr* cmsg2 = CMSG_NXTHDR(&msg, cmsg1);
ASSERT_NE(cmsg2, nullptr);
ASSERT_EQ(cmsg2->cmsg_len, CMSG_LEN(sizeof(int)));
ASSERT_EQ(cmsg2->cmsg_level, SOL_SOCKET);
ASSERT_EQ(cmsg2->cmsg_type, SCM_RIGHTS);
memcpy(fd, CMSG_DATA(cmsg2), sizeof(int));
}
void RecvSingleFDUnaligned(int sock, int* fd, char buf[], int buf_size) {
struct msghdr msg = {};
char control[CMSG_SPACE(sizeof(int)) - sizeof(int)];
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = buf_size;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sock, &msg, 0),
SyscallSucceedsWithValue(buf_size));
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
ASSERT_NE(cmsg, nullptr);
ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(int)));
ASSERT_EQ(cmsg->cmsg_level, SOL_SOCKET);
ASSERT_EQ(cmsg->cmsg_type, SCM_RIGHTS);
memcpy(fd, CMSG_DATA(cmsg), sizeof(int));
}
void SetSoPassCred(int sock) {
int one = 1;
EXPECT_THAT(setsockopt(sock, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)),
SyscallSucceeds());
}
void UnsetSoPassCred(int sock) {
int zero = 0;
EXPECT_THAT(setsockopt(sock, SOL_SOCKET, SO_PASSCRED, &zero, sizeof(zero)),
SyscallSucceeds());
}
} // namespace testing
} // namespace gvisor
| 33.905714 | 80 | 0.683155 | [
"vector"
] |
ff32e19987a4bea0a8dfb412b1d638dd662409ce | 4,814 | cpp | C++ | opt-truss-decomp/opt_pkt/pkt_radix_map.cpp | mexuaz/AccTrussDecomposition | 15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4 | [
"MIT"
] | 9 | 2020-03-30T13:00:15.000Z | 2022-03-17T13:40:17.000Z | opt-truss-decomp/opt_pkt/pkt_radix_map.cpp | mexuaz/AccTrussDecomposition | 15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4 | [
"MIT"
] | null | null | null | opt-truss-decomp/opt_pkt/pkt_radix_map.cpp | mexuaz/AccTrussDecomposition | 15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4 | [
"MIT"
] | 2 | 2020-08-17T10:05:51.000Z | 2020-08-30T22:57:55.000Z | //
// Created by yche on 6/18/19.
//
#include <functional>
#include "util/graph/graph.h"
#include "util/log/log.h"
#include "util/timer.h"
#include "util/containers/boolarray.h"
#include "pkt_support_update_utils.h"
#include "iter_helper.h"
#include "util/containers/radix_hash_map.h"
#define REDUCE_RADIX_MAP_COST
using word_type = uint32_t;
//Process a sub-level in a level using marking based approach
void PKT_processSubLevel_marking(graph_t *g, eid_t *curr,
#ifndef BMP_QUEUE
bool *InCurr,
#else
BoolArray<word_type> &InCurr,
#endif
long currTail, int *EdgeSupport, int level,
eid_t *next,
#ifndef BMP_QUEUE
bool *InNext,
#else
BoolArray<word_type> &InNext,
#endif
long *nextTail, RadixHashMap &X,
#ifndef BMP_PROCESSED
bool *processed,
#else
BoolArray<word_type> &processed,
#endif
Edge *edgeIdtoEdge,
eid_t *off_end, bool *is_vertex_updated, IterHelper &iter_helper
) {
//Size of cache line
const long BUFFER_SIZE_BYTES = 2048;
const long BUFFER_SIZE = BUFFER_SIZE_BYTES / sizeof(eid_t);
eid_t buff[BUFFER_SIZE];
LocalWriteBuffer<eid_t, long> local_write_buffer(buff, BUFFER_SIZE, next, nextTail);
eid_t bkt_buff[BUFFER_SIZE];
LocalWriteBuffer<eid_t, size_t> local_bucket_buf(bkt_buff, BUFFER_SIZE, iter_helper.bucket_buf_,
&iter_helper.window_bucket_buf_size_);
SupportUpdater sup_updater(EdgeSupport, InNext, level, local_write_buffer, local_bucket_buf,
iter_helper.bucket_level_end_, iter_helper.in_bucket_window_);
#pragma omp for schedule(dynamic, 4)
for (long i = 0; i < currTail; i++) {
//process edge <u,v>
eid_t e1 = curr[i];
Edge edge = edgeIdtoEdge[e1];
vid_t u = edge.u;
vid_t v = edge.v;
eid_t uStart = g->num_edges[u], uEnd = off_end[u + 1];
eid_t vStart = g->num_edges[v], vEnd = off_end[v + 1];
if (vEnd - vStart > uEnd - uStart) {
swap(u, v);
}
uStart = g->num_edges[u], uEnd = off_end[u + 1];
vStart = g->num_edges[v], vEnd = off_end[v + 1];
static thread_local vector<pair<eid_t, eid_t >> intersection_res(1024 * 1024);
size_t beg = 0;
#ifdef REDUCE_RADIX_MAP_COST
//Check the adj list of vertex v
vector<int> *psum_arr_ptr = nullptr;
vector<RadixHashMap::hash_entry_t> *hash_table_ptr = nullptr;
uint32_t radix_val = 0;
X.find_u_psum_table_size(u, psum_arr_ptr, hash_table_ptr, radix_val);
#endif
for (eid_t j = vStart; j < vEnd; j++) {
vid_t w = g->adj[j];
#ifdef REDUCE_RADIX_MAP_COST
auto ptr = X.get(psum_arr_ptr, hash_table_ptr, radix_val, w);
#else
auto ptr = X.get(u, w);
#endif
if (ptr != nullptr) {
// Reduce the cost of it range checking of std::vector's `emplace_back`.
intersection_res[beg++] = make_pair(j, *ptr); // (v,w) and (u,w)
}
}
for (auto iter = 0u; iter < beg; iter++) {
eid_t e2, e3;
std::tie(e2, e3) = intersection_res[iter];
e2 = g->eid[e2];
sup_updater.PeelTriangle(e1, e2, e3, processed, InCurr);
}
#ifndef NO_SHRINK_GRAPH
is_vertex_updated[u] = true;
is_vertex_updated[v] = true;
#endif
}
sup_updater.SubmitLocalBufferNext();
iter_helper.MarkProcessed();
}
/** Computes the support of each edge in parallel
* Computes k-truss in parallel ****/
void PKT_marking(graph_t *g, int *&EdgeSupport, Edge *&edgeIdToEdge) {
log_trace("pkt-radix-shrink");
Timer convert_timer;
RadixHashMap radix_hash_map(g);
log_info("Hash Map Construction Cost: %.6lfs", convert_timer.elapsed());
IterHelper iter_helper(g, &EdgeSupport, &edgeIdToEdge);
auto process_functor = [&iter_helper, &EdgeSupport, &radix_hash_map, edgeIdToEdge, g](int level) {
PKT_processSubLevel_marking(g, iter_helper.curr_, iter_helper.in_curr_, iter_helper.curr_tail_,
EdgeSupport,
level, iter_helper.next_, iter_helper.in_next_, &iter_helper.next_tail_,
radix_hash_map,
iter_helper.processed_, edgeIdToEdge,
iter_helper.off_end_,
iter_helper.is_vertex_updated_, iter_helper);
};
AbstractPKT(g, EdgeSupport, edgeIdToEdge, iter_helper, process_functor);
}
| 35.397059 | 108 | 0.592854 | [
"vector"
] |
ff3548f71f764ade55a613481903b7564b2ef763 | 6,817 | cpp | C++ | interface/src/renderer/gl_legacy.cpp | jernvall-lab/ToothMaker | e7f09ae3ef9616418a25ef3c1ca836736c3d7449 | [
"MIT"
] | null | null | null | interface/src/renderer/gl_legacy.cpp | jernvall-lab/ToothMaker | e7f09ae3ef9616418a25ef3c1ca836736c3d7449 | [
"MIT"
] | null | null | null | interface/src/renderer/gl_legacy.cpp | jernvall-lab/ToothMaker | e7f09ae3ef9616418a25ef3c1ca836736c3d7449 | [
"MIT"
] | null | null | null | /**
* @file gl_legacy.cpp
* @brief Functionality for 2D and Humppa drawing.
*
* This is all legacy code, using fixed functionality and immediate mode stuff
* that requires OpenGL compatibility profile. New code should not call these
* methods!
*/
#include <string>
#include <math.h>
#include "gl_legacy.h"
#include "morphomaker.h" // SQUARE_WIN_SIZE
namespace {
/**
* @brief Calculates unit normal to given two vector.
* Legacy function.
* @param a Vector a.
* @param b Vector b.
* @param c Unit normal.
*/
void get_surface_normal_(GLdouble *a, GLdouble *b, GLdouble *c)
{
c[0] = a[1]*b[2] - a[2]*b[1];
c[1] = a[2]*b[0] - a[0]*b[2];
c[2] = a[0]*b[1] - a[1]*b[0];
GLdouble norm = sqrt( c[0]*c[0] + c[1]*c[1] + c[2]*c[2] );
if (norm != 0.0) {
c[0] = c[0]/norm;
c[1] = c[1]/norm;
c[2] = c[2]/norm;
}
}
} // END namespace
/**
* @brief Vertex coloring for RENDER_HUMPPA.
* Legacy function.
* @param cell Cell index.
* @param obj GLObject.
*/
void glcore::Vertex_color_RENDER_HUMPPA(int cell, GLObject& obj)
{
GLfloat colorArr[4];
float color;
if (obj.cell_data == NULL || obj.viewMode == 0) { // Mode: Shape only
colorArr[0] = DEFAULT_TOOTH_COL;
colorArr[1] = DEFAULT_TOOTH_COL;
colorArr[2] = DEFAULT_TOOTH_COL;
colorArr[3] = DEFAULT_TOOTH_COL;
}
else if (obj.viewMode==1) { // Mode: Diff & knots.
auto& colors = obj.mesh->get_vertex_colors();
colorArr[0] = colors.at(cell).r;
colorArr[1] = colors.at(cell).g;
colorArr[2] = colors.at(cell).b;
colorArr[3] = colors.at(cell).a;
}
else { // For all other view modes use red above threshold concentration.
color = 0.0;
auto data = obj.cell_data->at(cell);
if ( data.size() > (uint16_t)(obj.viewMode-2) ) {
color = data.at( obj.viewMode-2 );
}
if ( color > obj.viewThreshold ) {
colorArr[0]=1.0;
colorArr[1]=0.0;
colorArr[2]=0.0;
colorArr[3]=0.0;
}
else {
colorArr[0] = DEFAULT_TOOTH_COL;
colorArr[1] = DEFAULT_TOOTH_COL;
colorArr[2] = DEFAULT_TOOTH_COL;
colorArr[3] = DEFAULT_TOOTH_COL;
}
}
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, colorArr);
}
/**
* @brief Immediate mode vertex data renderer for RENDER_HUMPPA.
* @param obj GLObject.
* @param x Rendering field width.
* @param y Rendering field height.
*/
void glcore::PaintGL_RENDER_HUMPPA(GLObject& obj, int x, int y)
{
if (obj.mesh == NULL) return;
GLdouble aspect = ((GLdouble)x/y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho((-20.0*aspect+obj.viewPosX)*obj.zoomMultip,
(20.0*aspect+obj.viewPosX)*obj.zoomMultip,
(-20.0+obj.viewPosY)*obj.zoomMultip,
(20.0+obj.viewPosY)*obj.zoomMultip, -2000.0, 2000.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Object panning.
if (obj.mouse2Down) {
obj.viewPosY = obj.viewPosY -
obj.deltaY/(PAN_SENSITIVITY*(float)y/SQUARE_WIN_SIZE);
obj.viewPosX = obj.viewPosX +
obj.deltaX/(PAN_SENSITIVITY*(float)y/SQUARE_WIN_SIZE);
}
// Object rotation.
if (obj.mouse1Down) {
obj.rtriX += obj.deltaX;
obj.rtriY -= obj.deltaY;
}
glRotated(180.0, 1.0, 0.0, 0.0);
glRotated((double)obj.rtriY, 1.0, 0.0, 0.0);
glRotated((double)obj.rtriX, 0.0, 0.0, 1.0);
auto& polygons = obj.mesh->get_polygons();
auto& vertices = obj.mesh->get_vertices();
for ( auto& pol : polygons ) {
// Note: RENDER_HUMPPA check needs to be inside loop, as it may change
// while the loop is still rolling.
if (obj.renderMode != RENDER_HUMPPA) break;
// Calculate & assign the surface normal of the polygon.
auto& v1 = vertices.at( pol.at(0) );
auto& v2 = vertices.at( pol.at(1) );
auto& v3 = vertices.at( pol.at(2) );
GLdouble a[3] = { v1.x - v2.x, v1.y - v2.y, v1.z - v2.z };
GLdouble b[3] = { v3.x - v2.x, v3.y - v2.y, v3.z - v2.z };
GLdouble n[3];
get_surface_normal_(a,b,n);
glNormal3dv(n);
// Add an offset to the polygon to make the edges stick out better.
glPolygonOffset(1.0, 1.0);
glEnable(GL_POLYGON_OFFSET_FILL);
// Draw polygons.
glBegin(GL_POLYGON);
for ( auto& i : pol ) {
Vertex_color_RENDER_HUMPPA( i, obj );
auto p = vertices.at( i );
glVertex3d( p.x, p.y, p.z );
}
glEnd();
glDisable(GL_POLYGON_OFFSET_FILL);
// Draw polygon edges if required.
if ( obj.polygonFill ) {
GLfloat color[4] = {0.0, 0.0, 0.0, 0.0}; // Black edge color.
glLineWidth(1.0);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
glBegin(GL_LINE_LOOP);
for ( auto& i : pol ) {
auto p = vertices.at( i );
glVertex3d( p.x, p.y, p.z );
}
glEnd();
}
}
}
/**
* @brief Updates GL view for 2D models.
*/
void glcore::PaintGL_2D(GLObject& obj, GLdouble aspect)
{
GLfloat divXY;
if (obj.pixelDataHeight==0 || obj.pixelDataWidth==0) {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
return;
}
glBindTexture(GL_TEXTURE_2D, obj.texName);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, obj.pixelDataWidth, obj.pixelDataHeight,
0, GL_RGBA, GL_FLOAT, obj.img);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 10*0.1, 0.0, 10*0.1, -200.0, 200.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, obj.texName);
divXY = (obj.pixelDataWidth) / (float)(obj.pixelDataHeight) / aspect;
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0);
glVertex3f(0.5-divXY/2.0, 0.0, 0.0);
glTexCoord2f(0.0, 0.0);
glVertex3f(0.5-divXY/2.0, 1.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(0.5+divXY/2.0, 1.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0.5+divXY/2.0, 0.0, 0.0);
/* Gives MATLAB-style coordinates:
glTexCoord2f(0.0, 1.0);
glVertex3f(0.5+divXY/2.0, 0.0, 0.0);
glTexCoord2f(0.0, 0.0);
glVertex3f(0.5-divXY/2.0, 0.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f(0.5-divXY/2.0, 1.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0.5+divXY/2.0, 1.0, 0.0);
*/
glEnd();
}
| 29.132479 | 84 | 0.562858 | [
"mesh",
"object",
"shape",
"vector"
] |
ff3ac39eda1d73d1e4893f5ca6726fb2acb2a6da | 25,744 | cpp | C++ | pycoyote/pycoyote.cpp | Sonoranvideo/libcoyote | 02f8eeead5d593f932cd7ee2e16a930760a3267d | [
"Apache-2.0"
] | null | null | null | pycoyote/pycoyote.cpp | Sonoranvideo/libcoyote | 02f8eeead5d593f932cd7ee2e16a930760a3267d | [
"Apache-2.0"
] | null | null | null | pycoyote/pycoyote.cpp | Sonoranvideo/libcoyote | 02f8eeead5d593f932cd7ee2e16a930760a3267d | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 Sonoran Video Systems
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 <Python.h>
#include "../src/include/common.h"
#include "../src/include/datastructures.h"
#include "../src/include/session.h"
#include "../src/include/layouts.h"
#include <stddef.h>
#include <stdint.h>
#include "pybind11/include/pybind11/pybind11.h"
#include "pybind11/include/pybind11/stl.h"
#include "pybind11/include/pybind11/stl_bind.h"
extern EXPFUNC const std::map<Coyote::RefreshMode, std::string> RefreshMap;
extern EXPFUNC const std::map<Coyote::ResolutionMode, std::string> ResolutionMap;
namespace py = pybind11;
#define ACLASSF(a, b) .def(#b, &Coyote::a::b, py::call_guard<py::gil_scoped_release>())
#define ACLASSD(a, b) .def_readwrite(#b, &Coyote::a::b)
#define ACLASSBD(a, b) .def_readwrite(#b, &a::b)
#define EMEMDEF(a) .value(#a, Coyote::a)
static void PBEventFunc(const Coyote::PlaybackEventType EType, const int32_t PK, const int32_t Time, void *const Pass_);
static void StateEventFunc(const Coyote::StateEventType EType, void *const Pass_);
PYBIND11_MODULE(pycoyote, ModObj)
{
ModObj.def("LookupPresetLayoutByID", Coyote::LookupPresetLayoutByID);
ModObj.def("LookupPresetLayoutByString", Coyote::LookupPresetLayoutByString);
ModObj.def("GetPresetPlayers", Coyote::GetPresetPlayers);
ModObj.def("GetPresetSDIOutputs", Coyote::GetPresetSDIOutputs);
ModObj.def("GetPlayerSDIOutputs", Coyote::GetPlayerSDIOutputs);
py::class_<Coyote::BaseObject>(ModObj, "BaseObject")
.def(py::init<>());
py::class_<Coyote::CoyoteString>(ModObj, "CoyoteString")
.def(py::init<const std::string &>())
.def("__str__", &Coyote::CoyoteString::operator std::string)
.def("__eq__", &Coyote::CoyoteString::operator==)
.def("__ne__", &Coyote::CoyoteString::operator!=)
.def("__len__", &Coyote::CoyoteString::GetLength)
.def("__repr__", &Coyote::CoyoteString::operator std::string)
ACLASSF(CoyoteString, Set)
ACLASSF(CoyoteString, GetCString)
ACLASSF(CoyoteString, GetStdString)
ACLASSF(CoyoteString, GetLength);
py::enum_<Coyote::RefreshMode>(ModObj, "RefreshMode")
EMEMDEF(COYOTE_REFRESH_INVALID)
EMEMDEF(COYOTE_REFRESH_23_98)
EMEMDEF(COYOTE_REFRESH_24)
EMEMDEF(COYOTE_REFRESH_25)
EMEMDEF(COYOTE_REFRESH_29_97)
EMEMDEF(COYOTE_REFRESH_30)
EMEMDEF(COYOTE_REFRESH_50)
EMEMDEF(COYOTE_REFRESH_59_94)
EMEMDEF(COYOTE_REFRESH_60)
EMEMDEF(COYOTE_REFRESH_MAX)
.export_values();
py::enum_<Coyote::ResolutionMode>(ModObj, "ResolutionMode")
EMEMDEF(COYOTE_RES_INVALID)
EMEMDEF(COYOTE_RES_1080P)
EMEMDEF(COYOTE_RES_2160P)
EMEMDEF(COYOTE_RES_1080I)
EMEMDEF(COYOTE_RES_MAX)
.export_values();
py::enum_<Coyote::HDRMode>(ModObj, "HDRMode")
EMEMDEF(COYOTE_HDR_DISABLED)
EMEMDEF(COYOTE_HDR_BT2020)
EMEMDEF(COYOTE_HDR_DCI_P3)
EMEMDEF(COYOTE_HDR_DOLBY)
EMEMDEF(COYOTE_HDR_MAX)
.export_values();
py::enum_<Coyote::EOTFMode>(ModObj, "EOTFMode")
EMEMDEF(COYOTE_EOTF_NORMAL)
EMEMDEF(COYOTE_EOTF_HLG)
EMEMDEF(COYOTE_EOTF_PQ)
EMEMDEF(COYOTE_EOTF_UNSPECIFIED)
EMEMDEF(COYOTE_EOTF_MAX)
.export_values();
py::enum_<Coyote::AssetState>(ModObj, "AssetState")
EMEMDEF(COYOTE_ASSETSTATE_INVALID)
EMEMDEF(COYOTE_ASSETSTATE_READY)
EMEMDEF(COYOTE_ASSETSTATE_INGESTING)
EMEMDEF(COYOTE_ASSETSTATE_ERROR)
EMEMDEF(COYOTE_ASSETSTATE_PROCESSING)
EMEMDEF(COYOTE_ASSETSTATE_MAX)
.export_values();
py::enum_<Coyote::PlaybackEventType>(ModObj, "PlaybackEventType")
EMEMDEF(COYOTE_PBEVENT_END)
EMEMDEF(COYOTE_PBEVENT_TAKE)
EMEMDEF(COYOTE_PBEVENT_PAUSE)
EMEMDEF(COYOTE_PBEVENT_UNPAUSE)
EMEMDEF(COYOTE_PBEVENT_SEEK)
.export_values();
py::enum_<Coyote::HardwareMode>(ModObj, "HardwareMode")
EMEMDEF(COYOTE_MODE_INVALID)
EMEMDEF(COYOTE_MODE_Q3G)
EMEMDEF(COYOTE_MODE_S12G)
EMEMDEF(COYOTE_MODE_MAX)
.export_values();
py::enum_<Coyote::StatusCode>(ModObj, "StatusCode")
EMEMDEF(COYOTE_STATUS_INVALID)
EMEMDEF(COYOTE_STATUS_OK)
EMEMDEF(COYOTE_STATUS_FAILED)
EMEMDEF(COYOTE_STATUS_UNIMPLEMENTED)
EMEMDEF(COYOTE_STATUS_INTERNALERROR)
EMEMDEF(COYOTE_STATUS_MISUSED)
EMEMDEF(COYOTE_STATUS_NETWORKERROR)
EMEMDEF(COYOTE_STATUS_MAX)
.export_values();
py::enum_<Coyote::UnitRole>(ModObj, "UnitRole")
EMEMDEF(COYOTE_ROLE_INVALID)
EMEMDEF(COYOTE_ROLE_SINGLE)
EMEMDEF(COYOTE_ROLE_PRIMARY)
EMEMDEF(COYOTE_ROLE_MIRROR)
EMEMDEF(COYOTE_ROLE_MAX)
.export_values();
py::enum_<Coyote::StateEventType>(ModObj, "StateEventType")
EMEMDEF(COYOTE_STATE_INVALID)
EMEMDEF(COYOTE_STATE_PRESETS)
EMEMDEF(COYOTE_STATE_ASSETS)
EMEMDEF(COYOTE_STATE_HWSTATE)
EMEMDEF(COYOTE_STATE_TIMECODE)
EMEMDEF(COYOTE_STATE_MAX)
.export_values();
py::enum_<Coyote::PresetLayout>(ModObj, "PresetLayout")
EMEMDEF(COYOTE_PSLAYOUT_INVALID)
EMEMDEF(COYOTE_PSLAYOUT_A)
EMEMDEF(COYOTE_PSLAYOUT_B)
EMEMDEF(COYOTE_PSLAYOUT_C1)
EMEMDEF(COYOTE_PSLAYOUT_C2)
EMEMDEF(COYOTE_PSLAYOUT_C3)
EMEMDEF(COYOTE_PSLAYOUT_F)
EMEMDEF(COYOTE_PSLAYOUT_E)
EMEMDEF(COYOTE_PSLAYOUT_D1)
EMEMDEF(COYOTE_PSLAYOUT_D2)
EMEMDEF(COYOTE_PSLAYOUT_MAX)
.export_values();
py::enum_<Coyote::SDIOutput>(ModObj, "SDIOutput", py::arithmetic())
EMEMDEF(COYOTE_SDI_INVALID)
EMEMDEF(COYOTE_SDI_1)
EMEMDEF(COYOTE_SDI_2)
EMEMDEF(COYOTE_SDI_3)
EMEMDEF(COYOTE_SDI_4)
EMEMDEF(COYOTE_SDI_MAXVALUE)
.export_values();
py::enum_<Coyote::Player>(ModObj, "Player", py::arithmetic())
EMEMDEF(COYOTE_PLAYER_INVALID)
EMEMDEF(COYOTE_PLAYER_1)
EMEMDEF(COYOTE_PLAYER_2)
EMEMDEF(COYOTE_PLAYER_3)
EMEMDEF(COYOTE_PLAYER_4)
EMEMDEF(COYOTE_PLAYER_MAXVALUE)
.export_values();
py::class_<Coyote_NetworkInfo>(ModObj, "Coyote_NetworkInfo")
.def(py::init<>())
ACLASSBD(Coyote_NetworkInfo, IP)
ACLASSBD(Coyote_NetworkInfo, Subnet)
ACLASSBD(Coyote_NetworkInfo, AdapterID);
py::class_<Coyote::NetworkInfo, Coyote::BaseObject, Coyote_NetworkInfo>(ModObj, "NetworkInfo")
.def("__repr__", [] (Coyote::NetworkInfo &Obj) { return std::string{"<NetworkInfo, IP "} + Obj.IP.GetStdString() + ", subnet " + Obj.Subnet.GetStdString() + ">"; })
.def(py::init<>());
py::class_<Coyote_Drive>(ModObj, "Coyote_Drive")
.def(py::init<>())
ACLASSBD(Coyote_Drive, DriveLetter)
ACLASSBD(Coyote_Drive, Total)
ACLASSBD(Coyote_Drive, Used)
ACLASSBD(Coyote_Drive, Free)
ACLASSBD(Coyote_Drive, IsExternal);
py::class_<Coyote::Drive, Coyote::BaseObject, Coyote_Drive>(ModObj, "Drive")
.def("__repr__", [] (Coyote::Drive &Obj) { return std::string{"<Drive "} + Obj.DriveLetter.GetStdString() + ":\\, " + std::to_string(Obj.Free / (1024ll * 1024ll * 1024ll)) + "/" + std::to_string(Obj.Total / (1024ll * 1024ll * 1024ll)) + " GiB free>"; })
.def(py::init<>());
py::class_<Coyote_HardwareState>(ModObj, "Coyote_HardwareState")
.def(py::init<>())
ACLASSBD(Coyote_HardwareState, Resolution)
ACLASSBD(Coyote_HardwareState, RefreshRate)
ACLASSBD(Coyote_HardwareState, CurrentMode)
ACLASSBD(Coyote_HardwareState, HDRMode)
ACLASSBD(Coyote_HardwareState, EOTFSetting)
ACLASSBD(Coyote_HardwareState, SupportsS12G)
ACLASSBD(Coyote_HardwareState, ConstLumin);
py::class_<Coyote::HardwareState, Coyote::BaseObject, Coyote_HardwareState>(ModObj, "HardwareState")
.def(py::init<>())
.def("__repr__", [] (Coyote::HardwareState &Obj) { return std::string{"<HardwareState of "} + ResolutionMap.at(Obj.Resolution) + "@" + RefreshMap.at(Obj.RefreshRate) + ">"; });
py::class_<Coyote::Session>(ModObj, "Session")
.def(py::init<const std::string &, const int>(), py::call_guard<py::gil_scoped_release>(), py::arg("IP"), py::arg("NumAttempts") = -1)
.def("SynchronizerBusy",
[] (Coyote::Session &Obj)
{
bool Value{};
const Coyote::StatusCode Status = Obj.SynchronizerBusy(Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("ReadLog",
[] (Coyote::Session &Obj, const std::string SpokeName, const int Year, const int Month, const int Day)
{
std::string LogText;
const Coyote::StatusCode Status = Obj.ReadLog(SpokeName, Year, Month, Day, LogText);
return std::make_tuple(Status, LogText);
}, py::call_guard<py::gil_scoped_release>())
.def("GetLogsZip",
[] (Coyote::Session &Obj)
{
std::vector<uint8_t> Bytes;
const Coyote::StatusCode Status = Obj.GetLogsZip(Bytes);
return std::make_tuple(Status, py::bytes((const char*)Bytes.data(), Bytes.size()));
}, py::call_guard<py::gil_scoped_release>())
.def("IsMirror",
[] (Coyote::Session &Obj)
{
bool Value{};
const Coyote::StatusCode Status = Obj.IsMirror(Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("DetectUpdate",
[] (Coyote::Session &Obj)
{
bool Detected{};
std::string Version;
const Coyote::StatusCode Status = Obj.DetectUpdate(Detected, &Version);
return std::make_tuple(Status, Detected, Version);
}, py::call_guard<py::gil_scoped_release>())
.def("GetMediaState",
[] (Coyote::Session &Obj)
{
Coyote::MediaState State{};
const Coyote::StatusCode Status = Obj.GetMediaState(State);
int MaxPlayingIndex = 0;
int MaxPausedIndex = 0;
int MaxTCIndex = 0;
while (State.PlayingPresets[MaxPlayingIndex]) ++MaxPlayingIndex;
while (State.PausedPresets[MaxPausedIndex]) ++MaxPausedIndex;
while (State.TimeCodes[MaxTCIndex].PresetKey) ++MaxTCIndex;
State.PausedPresets.resize(MaxPausedIndex);
State.PlayingPresets.resize(MaxPlayingIndex);
State.TimeCodes.resize(MaxTCIndex);
return std::make_tuple(Status, State);
}, py::call_guard<py::gil_scoped_release>())
.def("GetServerVersion",
[] (Coyote::Session &Obj)
{
std::string Version;
const Coyote::StatusCode Status = Obj.GetServerVersion(Version);
return std::make_tuple(Status, Version);
}, py::call_guard<py::gil_scoped_release>())
.def("SetPlaybackEventCallback",
[] (Coyote::Session &Obj, py::object Func, py::object PyUserData)
{
static auto &Pass = *new std::map<Coyote::Session*, std::pair<py::object, py::object> >; //Prevents the destructor from being called on program exit, because we don't care and it could segfault.
if (Func.ptr() == Py_None)
{
Obj.SetPlaybackEventCallback(nullptr, nullptr);
return;
}
Pass[&Obj] = {
std::move(Func),
std::move(PyUserData)
};
Obj.SetPlaybackEventCallback(PBEventFunc, &Pass[&Obj]);
})
.def("SetStateEventCallback",
[] (Coyote::Session &Obj, Coyote::StateEventType EType, py::object Func, py::object PyUserData)
{
static auto &Pass = *new std::map<Coyote::Session*, std::pair<py::object, py::object> >;
if (Func.ptr() == Py_None)
{
Pass.erase(&Obj);
Obj.SetStateEventCallback(EType, nullptr, nullptr);
return;
}
Pass[&Obj] = {
std::move(Func),
std::move(PyUserData)
};
Obj.SetStateEventCallback(EType, StateEventFunc, &Pass[&Obj]);
})
.def("GetDesignatedPrimary",
[] (Coyote::Session &Obj)
{
Coyote::Mirror Value{};
const Coyote::StatusCode Status = Obj.GetDesignatedPrimary(Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("GetEffectivePrimary",
[] (Coyote::Session &Obj)
{
Coyote::Mirror Value{};
const Coyote::StatusCode Status = Obj.GetEffectivePrimary(Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("GetHardwareState",
[] (Coyote::Session &Obj)
{
Coyote::HardwareState Value{};
const Coyote::StatusCode Status = Obj.GetHardwareState(Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("GetCurrentRole",
[] (Coyote::Session &Obj)
{
Coyote::UnitRole Value{};
const Coyote::StatusCode Status = Obj.GetCurrentRole(Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("GetUnitID",
[] (Coyote::Session &Obj)
{
std::string UnitID, Nickname;
const Coyote::StatusCode Status = Obj.GetUnitID(UnitID, Nickname);
return std::make_tuple(Status, UnitID, Nickname);
}, py::call_guard<py::gil_scoped_release>())
.def("GetTimeCode",
[] (Coyote::Session &Obj, int32_t PK)
{
Coyote::TimeCode Value{};
const Coyote::StatusCode Status = Obj.GetTimeCode(Value, PK);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("ReadAssetMetadata",
[] (Coyote::Session &Obj, const std::string &FullPath)
{
Coyote::AssetMetadata Value{};
const Coyote::StatusCode Status = Obj.ReadAssetMetadata(FullPath, Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("GetIP",
[] (Coyote::Session &Obj, const int32_t AdapterID)
{
Coyote::NetworkInfo Value{};
const Coyote::StatusCode Status = Obj.GetIP(AdapterID, Value);
return std::make_tuple(Status, Value);
}, py::call_guard<py::gil_scoped_release>())
.def("GetDisks",
[] (Coyote::Session &Obj)
{
std::vector<Coyote::Drive> Disks;
const Coyote::StatusCode Status = Obj.GetDisks(Disks);
return std::make_tuple(Status, Disks);
}, py::call_guard<py::gil_scoped_release>())
.def("GetDrives", //Alias for GetDisks
[] (Coyote::Session &Obj)
{
std::vector<Coyote::Drive> Disks;
const Coyote::StatusCode Status = Obj.GetDisks(Disks);
return std::make_tuple(Status, Disks);
}, py::call_guard<py::gil_scoped_release>())
.def("GetPresets",
[] (Coyote::Session &Obj)
{
std::vector<Coyote::Preset> Presets;
const Coyote::StatusCode Status = Obj.GetPresets(Presets);
return std::make_tuple(Status, Presets);
}, py::call_guard<py::gil_scoped_release>())
.def("GetAssets",
[] (Coyote::Session &Obj)
{
std::vector<Coyote::Asset> Assets;
const Coyote::StatusCode Status = Obj.GetAssets(Assets);
return std::make_tuple(Status, Assets);
}, py::call_guard<py::gil_scoped_release>())
.def("GetMirrors",
[] (Coyote::Session &Obj)
{
std::vector<Coyote::Mirror> Mirrors;
const Coyote::StatusCode Status = Obj.GetMirrors(Mirrors);
return std::make_tuple(Status, Mirrors);
}, py::call_guard<py::gil_scoped_release>())
.def("GetGenlockSettings",
[] (Coyote::Session &Obj)
{
Coyote::GenlockSettings Cfg{};
const Coyote::StatusCode Status = Obj.GetGenlockSettings(Cfg);
return std::make_tuple(Status, Cfg);
}, py::call_guard<py::gil_scoped_release>())
.def("Reconnect", &Coyote::Session::Reconnect, py::call_guard<py::gil_scoped_release>(),
py::arg("Host") = std::string{})
ACLASSF(Session, Connected)
ACLASSF(Session, GetHost)
ACLASSF(Session, SetHorzGenlock)
ACLASSF(Session, SetVertGenlock)
ACLASSF(Session, Take)
ACLASSF(Session, End)
ACLASSF(Session, Pause)
ACLASSF(Session, SetPause)
ACLASSF(Session, UnsetPause)
ACLASSF(Session, SetPausedState)
ACLASSF(Session, SeekTo)
ACLASSF(Session, InstallAsset)
ACLASSF(Session, DeleteAsset)
ACLASSF(Session, RenameAsset)
ACLASSF(Session, ReadAssetMetadata)
ACLASSF(Session, ReorderPresets)
ACLASSF(Session, DeletePreset)
ACLASSF(Session, CreatePreset)
ACLASSF(Session, MovePreset)
ACLASSF(Session, UpdatePreset)
ACLASSF(Session, BeginUpdate)
ACLASSF(Session, DetectUpdate)
ACLASSF(Session, EjectDisk)
ACLASSF(Session, SetIP)
ACLASSF(Session, SelectPreset)
ACLASSF(Session, AddMirror)
ACLASSF(Session, DeconfigureSync)
ACLASSF(Session, RebootCoyote)
ACLASSF(Session, ShutdownCoyote)
ACLASSF(Session, SoftRebootCoyote)
ACLASSF(Session, SelectNext)
ACLASSF(Session, SelectPrev)
ACLASSF(Session, DeleteGoto)
ACLASSF(Session, DeleteCountdown)
ACLASSF(Session, RenameGoto)
ACLASSF(Session, RenameCountdown)
ACLASSF(Session, CreateGoto)
ACLASSF(Session, CreateCountdown)
ACLASSF(Session, TakeNext)
ACLASSF(Session, TakePrev)
ACLASSF(Session, StartSpoke)
ACLASSF(Session, RestartSpoke)
ACLASSF(Session, KillSpoke)
ACLASSF(Session, ExportLogsZip)
ACLASSF(Session, SetUnitNickname)
ACLASSF(Session, SetCommandTimeoutSecs)
ACLASSF(Session, GetCommandTimeoutSecs)
ACLASSF(Session, HasConnectionError)
.def("SetHardwareMode", &Coyote::Session::SetHardwareMode, py::call_guard<py::gil_scoped_release>(),
py::arg("Resolution"),
py::arg("RefreshRate"),
py::arg("HDRMode") = Coyote::COYOTE_HDR_DISABLED,
py::arg("EOTFSetting") = Coyote::COYOTE_EOTF_NORMAL,
py::arg("ConstLumin") = false);
py::class_<Coyote_Output>(ModObj, "Coyote_Output")
.def(py::init<>())
ACLASSBD(Coyote_Output, Filename)
ACLASSBD(Coyote_Output, Hue)
ACLASSBD(Coyote_Output, Saturation)
ACLASSBD(Coyote_Output, Contrast)
ACLASSBD(Coyote_Output, Brightness)
ACLASSBD(Coyote_Output, MediaId)
ACLASSBD(Coyote_Output, FadeOut)
ACLASSBD(Coyote_Output, Delay)
ACLASSBD(Coyote_Output, Active)
ACLASSBD(Coyote_Output, Audio)
ACLASSBD(Coyote_Output, AudioChannel1)
ACLASSBD(Coyote_Output, AudioChannel2)
ACLASSBD(Coyote_Output, AudioChannel3)
ACLASSBD(Coyote_Output, AudioChannel4)
ACLASSBD(Coyote_Output, EnableTimeCode)
ACLASSBD(Coyote_Output, OriginalHeight)
ACLASSBD(Coyote_Output, OriginalWidth)
ACLASSBD(Coyote_Output, CustomDestX)
ACLASSBD(Coyote_Output, CustomDestY)
ACLASSBD(Coyote_Output, CustHeight)
ACLASSBD(Coyote_Output, CustWidth)
ACLASSBD(Coyote_Output, JustifyTop)
ACLASSBD(Coyote_Output, JustifyBottom)
ACLASSBD(Coyote_Output, JustifyRight)
ACLASSBD(Coyote_Output, JustifyLeft)
ACLASSBD(Coyote_Output, CenterVideo)
ACLASSBD(Coyote_Output, NativeSize)
ACLASSBD(Coyote_Output, LetterPillarBox)
ACLASSBD(Coyote_Output, TempFlag)
ACLASSBD(Coyote_Output, Anamorphic)
ACLASSBD(Coyote_Output, MultiviewAudio)
ACLASSBD(Coyote_Output, HorizontalCrop)
ACLASSBD(Coyote_Output, VerticalCrop);
py::class_<Coyote::Output, Coyote::BaseObject, Coyote_Output>(ModObj, "Output")
.def(py::init<>());
py::class_<Coyote_Preset>(ModObj, "Coyote_Preset")
.def(py::init<>())
ACLASSBD(Coyote_Preset, PK)
ACLASSBD(Coyote_Preset, TRT)
ACLASSBD(Coyote_Preset, Index)
ACLASSBD(Coyote_Preset, Loop)
ACLASSBD(Coyote_Preset, TotalLoop)
ACLASSBD(Coyote_Preset, Link)
ACLASSBD(Coyote_Preset, DisplayLink)
ACLASSBD(Coyote_Preset, Fade)
ACLASSBD(Coyote_Preset, LeftVolume)
ACLASSBD(Coyote_Preset, RightVolume)
ACLASSBD(Coyote_Preset, ScrubberPosition)
ACLASSBD(Coyote_Preset, InPosition)
ACLASSBD(Coyote_Preset, OutPosition)
ACLASSBD(Coyote_Preset, IsPlaying)
ACLASSBD(Coyote_Preset, IsPaused)
ACLASSBD(Coyote_Preset, Selected)
ACLASSBD(Coyote_Preset, VolumeLinked)
ACLASSBD(Coyote_Preset, Name)
ACLASSBD(Coyote_Preset, Layout)
ACLASSBD(Coyote_Preset, Notes)
ACLASSBD(Coyote_Preset, Color)
ACLASSBD(Coyote_Preset, timeCodeUpdate)
ACLASSBD(Coyote_Preset, tcColor)
ACLASSBD(Coyote_Preset, FreezeAtEnd)
ACLASSBD(Coyote_Preset, DisplayOrderIndex)
ACLASSBD(Coyote_Preset, Dissolve);
py::class_<Coyote_TabOrdering>(ModObj, "Coyote_TabOrdering")
.def(py::init<>())
ACLASSBD(Coyote_TabOrdering, TabID)
ACLASSBD(Coyote_TabOrdering, Index);
py::class_<Coyote::TabOrdering, Coyote::BaseObject, Coyote_TabOrdering>(ModObj, "TabOrdering")
.def(py::init<>())
.def("__repr__", [] (Coyote::TabOrdering &Obj) { return std::string{"<TabOrdering for tab ID "} + std::to_string(Obj.TabID) + " with index " + std::to_string(Obj.Index) + ">"; });
py::class_<Coyote_PresetMark>(ModObj, "Coyote_PresetMark")
.def(py::init<>())
ACLASSBD(Coyote_PresetMark, MarkNumber)
ACLASSBD(Coyote_PresetMark, MarkName)
ACLASSBD(Coyote_PresetMark, MarkDisplayTime)
ACLASSBD(Coyote_PresetMark, MarkTime);
py::class_<Coyote::PresetMark, Coyote::BaseObject, Coyote_PresetMark>(ModObj, "PresetMark")
.def(py::init<>())
.def("__repr__", [] (Coyote::PresetMark &Obj) { return std::string{"<PresetMark \""} + Obj.MarkName.GetStdString() + "\", time " + std::to_string(Obj.MarkTime) + ">"; });
py::class_<Coyote::Preset, Coyote::BaseObject, Coyote_Preset>(ModObj, "Preset")
.def(py::init<>())
.def("__repr__", [] (Coyote::Preset &Obj) { return std::string{"<Preset \""} + Obj.Name.GetStdString() + "\", PK " + std::to_string(Obj.PK) + ", TRT " + std::to_string(Obj.TRT) + ">"; })
ACLASSD(Preset, Output1)
ACLASSD(Preset, Output2)
ACLASSD(Preset, Output3)
ACLASSD(Preset, Output4)
ACLASSD(Preset, gotoMarks)
ACLASSD(Preset, countDowns)
ACLASSD(Preset, TabDisplayOrder);
py::class_<Coyote_TimeCode>(ModObj, "Coyote_TimeCode")
.def(py::init<>())
ACLASSBD(Coyote_TimeCode, ScrubBar)
ACLASSBD(Coyote_TimeCode, Time)
ACLASSBD(Coyote_TimeCode, TRT)
ACLASSBD(Coyote_TimeCode, PresetKey)
ACLASSBD(Coyote_TimeCode, LeftChannelVolume)
ACLASSBD(Coyote_TimeCode, RightChannelVolume)
ACLASSBD(Coyote_TimeCode, Player1LeftVolume)
ACLASSBD(Coyote_TimeCode, Player1RightVolume)
ACLASSBD(Coyote_TimeCode, Player2LeftVolume)
ACLASSBD(Coyote_TimeCode, Player2RightVolume)
ACLASSBD(Coyote_TimeCode, Player3LeftVolume)
ACLASSBD(Coyote_TimeCode, Player3RightVolume)
ACLASSBD(Coyote_TimeCode, Player4LeftVolume)
ACLASSBD(Coyote_TimeCode, Player4RightVolume)
ACLASSBD(Coyote_TimeCode, Selected);
py::class_<Coyote::TimeCode, Coyote::BaseObject, Coyote_TimeCode>(ModObj, "TimeCode")
.def(py::init<>())
.def("__repr__", [] (Coyote::TimeCode &Obj) { return std::string{"<TimeCode for PK "} + std::to_string(Obj.PresetKey) + " with time " + std::to_string(Obj.Time) + ">"; });
py::class_<Coyote_GenlockSettings>(ModObj, "Coyote_GenlockSettings")
.def(py::init<>())
ACLASSBD(Coyote_GenlockSettings, FormatString)
ACLASSBD(Coyote_GenlockSettings, HorzValue)
ACLASSBD(Coyote_GenlockSettings, VertValue)
ACLASSBD(Coyote_GenlockSettings, Genlocked);
py::class_<Coyote::GenlockSettings, Coyote::BaseObject, Coyote_GenlockSettings>(ModObj, "GenlockSettings")
.def(py::init<>())
.def("__repr__", [] (Coyote::GenlockSettings &Obj)
{
return std::string{"<GenlockSettings, "} +
(Obj.Genlocked ? (std::string{"Genlocked at "} + Obj.FormatString.GetStdString()) : "Freerun") +
", Horz " + std::to_string(Obj.HorzValue) +
", Vert " + std::to_string(Obj.VertValue) + ">";
});
py::class_<Coyote_Mirror>(ModObj, "Coyote_Mirror")
.def(py::init<>())
ACLASSBD(Coyote_Mirror, UnitID)
ACLASSBD(Coyote_Mirror, IP)
ACLASSBD(Coyote_Mirror, Busy)
ACLASSBD(Coyote_Mirror, SupportsS12G)
ACLASSBD(Coyote_Mirror, IsAlive);
py::class_<Coyote::Mirror, Coyote::BaseObject, Coyote_Mirror>(ModObj, "Mirror")
.def(py::init<>())
.def("__repr__", [] (Coyote::Mirror &Obj)
{
return std::string{"<Mirror "} + Obj.UnitID.GetStdString() +
" at IP " + Obj.IP.GetStdString() +
", Busy: " + (Obj.Busy ? "True" : "False") +
", IsAlive: " + (Obj.IsAlive ? "True" : "False") + ">";
});
py::class_<Coyote_MediaState>(ModObj, "Coyote_MediaState")
.def(py::init<>())
ACLASSBD(Coyote_MediaState, NumPresets)
ACLASSBD(Coyote_MediaState, SelectedPreset);
py::class_<Coyote::MediaState, Coyote::BaseObject, Coyote_MediaState>(ModObj, "MediaState")
.def(py::init<>())
ACLASSD(MediaState, PlayingPresets)
ACLASSD(MediaState, PausedPresets)
ACLASSD(MediaState, TimeCodes);
py::class_<Coyote::LayoutInfo>(ModObj, "LayoutInfo")
.def(py::init<>())
.def("__repr__", [] (Coyote::LayoutInfo &Obj) { return std::string{"<LayoutInfo for preset layout "} + Obj.TextName + ">"; })
ACLASSD(LayoutInfo, TextName)
ACLASSD(LayoutInfo, ID)
ACLASSD(LayoutInfo, Players)
ACLASSD(LayoutInfo, SDIOuts);
py::class_<Coyote_Asset>(ModObj, "Coyote_Asset")
.def(py::init<>())
ACLASSBD(Coyote_Asset, FullPath)
ACLASSBD(Coyote_Asset, Checksum)
ACLASSBD(Coyote_Asset, LastModified)
ACLASSBD(Coyote_Asset, TotalSize)
ACLASSBD(Coyote_Asset, CurrentSize)
ACLASSBD(Coyote_Asset, Status);
py::class_<Coyote_AssetMetadata>(ModObj, "Coyote_AssetMetadata")
.def(py::init<>())
ACLASSBD(Coyote_AssetMetadata, FullPath)
ACLASSBD(Coyote_AssetMetadata, AssetSize)
ACLASSBD(Coyote_AssetMetadata, TRT)
ACLASSBD(Coyote_AssetMetadata, Width)
ACLASSBD(Coyote_AssetMetadata, Height)
ACLASSBD(Coyote_AssetMetadata, FPS)
ACLASSBD(Coyote_AssetMetadata, NumAudioChannels)
ACLASSBD(Coyote_AssetMetadata, AudioSampleRate)
ACLASSBD(Coyote_AssetMetadata, VideoCodec)
ACLASSBD(Coyote_AssetMetadata, AudioCodec)
ACLASSBD(Coyote_AssetMetadata, SupportedVideoCodec)
ACLASSBD(Coyote_AssetMetadata, SupportedAudioCodec);
py::class_<Coyote::AssetMetadata, Coyote::BaseObject, Coyote_AssetMetadata>(ModObj, "AssetMetadata")
.def(py::init<>())
.def("__repr__", [] (Coyote::AssetMetadata &Obj) { return std::string{"<AssetMetadata for \""} + Obj.FullPath.GetStdString() + "\">"; });
py::class_<Coyote::Asset, Coyote::BaseObject, Coyote_Asset>(ModObj, "Asset")
.def(py::init<>())
.def("__repr__", [] (Coyote::Asset &Obj) { return std::string{"<Asset \""} + Obj.FullPath.GetStdString() + "\">"; });
ModObj.doc() = "Interface for controlling Sonoran Video Systems' Coyote playback servers";
}
static void PBEventFunc(const Coyote::PlaybackEventType EType, const int32_t PK, const int32_t Time, void *const Pass_)
{
py::gil_scoped_acquire GILLock;
std::pair<py::object, py::object> *const Pass = (decltype(Pass))Pass_;
if (!Pass || !Pass->first || !PyCallable_Check(Pass->first.ptr()))
{
LDEBUG_MSG("No pass");
return;
}
Pass->first(EType, PK, Time, Pass->second);
}
static void StateEventFunc(const Coyote::StateEventType EType, void *const Pass_)
{
py::gil_scoped_acquire GILLock;
std::pair<py::object, py::object> *const Pass = (decltype(Pass))Pass_;
if (!Pass || !Pass->first || !PyCallable_Check(Pass->first.ptr()))
{
LDEBUG_MSG("No pass");
return;
}
Pass->first(EType, Pass->second);
}
| 33.784777 | 254 | 0.741338 | [
"object",
"vector"
] |
ff477562045b31c80ba4be7402cf4ce20abd0255 | 626 | cc | C++ | P7-Vectors/P67268.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | P7-Vectors/P67268.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | P7-Vectors/P67268.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | //Inversió de seqüències
#include <iostream>
#include <vector>
using namespace std;
//Pre: Llegeix una seqüčncia
//Post: Escriu la seqüčncia invertida
int main() {
int n;
while (cin >> n) {
vector<int> v(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
}
bool primer = true;
for (int i = n-1; i >= 0; --i) {
if (not primer) cout << ' ';
else primer = false;
cout << v[i];
}
cout << endl;
}
}
| 25.04 | 52 | 0.373802 | [
"vector"
] |
ff483c822e9dbb25c8ea6cec33ababc3ea2acf4a | 5,492 | cpp | C++ | urdf_editor/src/utils/convex_hull_generator.cpp | ros-industrial-consortium/CAD-to-ROS | 1c5128e48f83f640d99d5e9cde7ccefc56bcf413 | [
"Apache-2.0"
] | 9 | 2018-07-30T18:29:46.000Z | 2021-04-21T10:35:08.000Z | urdf_editor/src/utils/convex_hull_generator.cpp | ros-industrial-consortium/CAD-to-ROS | 1c5128e48f83f640d99d5e9cde7ccefc56bcf413 | [
"Apache-2.0"
] | 1 | 2018-06-07T12:51:20.000Z | 2018-06-07T13:18:24.000Z | urdf_editor/src/utils/convex_hull_generator.cpp | ros-industrial-consortium/CAD-to-ROS | 1c5128e48f83f640d99d5e9cde7ccefc56bcf413 | [
"Apache-2.0"
] | 8 | 2018-07-30T18:29:47.000Z | 2021-04-21T10:36:01.000Z | #include <urdf_editor/utils/convex_hull_generator.h>
#include <assimp/postprocess.h>
#include <ros/console.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/surface/convex_hull.h>
#include <boost/algorithm/string.hpp>
#include <string>
#include <fstream>
#include <boost/assign.hpp>
static const std::string STL_BIN_FORMAT_ID = "stlb";
static const std::map<std::string,std::string> OUTPUT_EXTENSION_MAP = boost::assign::map_list_of ("stl","stlb");
namespace urdf_editor
{
namespace utils
{
ConvexHullGenerator::ConvexHullGenerator():
scene_(NULL)
{
}
ConvexHullGenerator::~ConvexHullGenerator()
{
}
bool ConvexHullGenerator::generate(const std::string& file_path)
{
using namespace Assimp;
const aiScene* scene = importer_.ReadFile(file_path,
aiProcess_Triangulate|
aiProcess_JoinIdenticalVertices|
aiProcess_GenNormals);
if(!scene)
{
ROS_ERROR_STREAM("Read Error: " <<importer_.GetErrorString());
return false;
}
if(!scene->HasMeshes())
{
ROS_ERROR_STREAM("No meshes were found in file "<<file_path);
return false;
}
// copying scene
aiCopyScene(scene,&scene_);
return generateConvexHull(scene_);
}
bool ConvexHullGenerator::save(const std::string& file_path)
{
using namespace Assimp;
Exporter exporter;
// register STL binary exporter
unsigned int steps = aiProcess_Triangulate | aiProcess_SortByPType | aiProcess_GenSmoothNormals |
aiProcess_JoinIdenticalVertices | aiProcess_FixInfacingNormals | aiProcess_FindInvalidData ;
Exporter::ExportFormatEntry format_entry(STL_BIN_FORMAT_ID.c_str(),"Stereolithography (binary)",
"stl",&assimp::STLExporter::ExportSceneSTLBinary,
steps);
if(exporter.RegisterExporter(format_entry)!= aiReturn_SUCCESS)
{
ROS_ERROR_STREAM("Failed to register Binary STL exporter: "<<exporter.GetErrorString());
return false;
}
if(!chull_mesh_)
{
ROS_ERROR_STREAM("Mesh file has not been loaded");
return false;
}
// check extensions
std::string ext = file_path.substr(file_path.find_last_of('.')+1);
boost::algorithm::to_lower(ext);
if(OUTPUT_EXTENSION_MAP.count(ext) <= 0)
{
ROS_ERROR("Extension %s is not supported",ext.c_str());
return false;
}
// veryfing support for selected format
int ext_count = exporter.GetExportFormatCount();
std::string ext_id = OUTPUT_EXTENSION_MAP.at(ext);
bool supported = false;
for(unsigned int i = 0u; i < ext_count; i++)
{
const aiExportFormatDesc* desc = exporter.GetExportFormatDescription(i);
if(std::string(desc->id).compare(ext_id) == 0) // find binary
{
supported = true;
break;
}
}
if(!supported)
{
ROS_ERROR("Assimp exporter does not support extension %s",ext.c_str());
return false;
}
aiReturn res = exporter.Export(scene_,ext_id,file_path,steps);
if(res == aiReturn_OUTOFMEMORY)
{
ROS_ERROR("Mesh export failed due to out-of-memory error");
return false;
}
return res == aiReturn_SUCCESS;
}
bool ConvexHullGenerator::generateConvexHull(const aiScene* scene)
{
using namespace pcl;
const aiMesh* mesh = scene->mMeshes[0];
if(mesh->mNumVertices == 0)
{
ROS_ERROR("Mesh geometry is empty");
return false;
}
PointCloud<PointXYZ>::Ptr mesh_points(new PointCloud<PointXYZ>()), chull_points(new PointCloud<PointXYZ>());
PointXYZ p;
for(std::size_t i = 0; i < mesh->mNumVertices; i++)
{
p.x = mesh->mVertices[i].x;
p.y = mesh->mVertices[i].y;
p.z = mesh->mVertices[i].z;
mesh_points->points.push_back(p);
}
// generate chull
std::vector< Vertices > faces;
ConvexHull<PointXYZ> chull;
chull.setInputCloud(mesh_points);
chull.reconstruct(*chull_points,faces);
// creating assimp mesh from pcl convex-hull
std::size_t vertices_per_face = 3;
std::size_t num_vertices = chull_points->points.size();
chull_mesh_.reset(new aiMesh());
chull_mesh_->mMaterialIndex = 0;
chull_mesh_->mVertices = new aiVector3D[num_vertices];
chull_mesh_->mNumVertices = num_vertices;
chull_mesh_->mFaces = new aiFace[faces.size()];
chull_mesh_->mNumFaces = faces.size();
chull_mesh_->mName = "convex-hull";
for(std::size_t f = 0; f < faces.size();f++)
{
std::vector<unsigned int>& vertices = faces[f].vertices;
aiFace& face = chull_mesh_->mFaces[f];
face.mIndices = new unsigned int[vertices_per_face];
face.mNumIndices = vertices_per_face;
std::size_t start_index = f*vertices_per_face;
std::size_t vertex_index;
for(std::size_t v = 0; v < vertices.size() ; v++)
{
vertex_index = vertices[v];
PointXYZ& p = chull_points->points[vertex_index];
chull_mesh_->mVertices[vertex_index] = aiVector3D(p.x,p.y,p.z);
face.mIndices[v] = vertex_index;
}
}
// deleting old scene data
delete scene_->mRootNode;
delete scene_->mMeshes;
// populating scene with new mesh
scene_->mRootNode = new aiNode();
scene_->mMeshes = new aiMesh*[1];
scene_->mMeshes[0] = chull_mesh_.get();
scene_->mMeshes[ 0 ]->mMaterialIndex = 0;
scene_->mNumMeshes = 1;
scene_->mRootNode->mMeshes = new unsigned int[ 1 ];
scene_->mRootNode->mMeshes[ 0 ] = 0;
scene_->mRootNode->mNumMeshes = 1;
return !chull_points->points.empty();
}
} /* namespace utils */
} /* namespace urdf_editor */
| 27.46 | 112 | 0.676438 | [
"mesh",
"geometry",
"vector"
] |
ff4de4a480cb6f2babd7326c51e9cc1962fd3803 | 1,335 | cpp | C++ | randomize.cpp14/main.cpp | loic-yvonnet/randomize-cpp14 | ddc1022e1231483920dffad3782644eaacf784e0 | [
"MIT"
] | null | null | null | randomize.cpp14/main.cpp | loic-yvonnet/randomize-cpp14 | ddc1022e1231483920dffad3782644eaacf784e0 | [
"MIT"
] | null | null | null | randomize.cpp14/main.cpp | loic-yvonnet/randomize-cpp14 | ddc1022e1231483920dffad3782644eaacf784e0 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include "randomize.hpp"
int main() {
// (1) integral function parameter within range [1 ; 6]
std::cout << randomize::rand(1, 6) << '\n';
// (2) integral random function generation within range [1 ; 6]
auto f = randomize::get_rand(1, 12);
std::cout << f() << " " << f() << " " << f() << " " << f() << '\n';
// (3) floating-point function parameter within range [3.14 ; 42]
std::cout << randomize::rand(3.14, 42.) << '\n';
// (4) floating-poing random function generation within range [-16 ; 64]
auto g = randomize::get_rand(-16., 64.);
std::cout << g() << '\n';
// (5) integral template parameter within range [-infinity(short) ; infinity(short)]
std::cout << randomize::rand<short>() << '\n';
// (6) floating-point template parameter within range [-2 ; 3]
auto rand_double = randomize::rand<double, -2, 3>;
std::cout << rand_double() << '\n';
// (7) fill a vector with random numbers
std::vector<float> v(randomize::rand(5, 1'000));
std::generate(std::begin(v), std::end(v), randomize::get_rand(-100.f, 100.f));
std::copy(std::begin(v), std::end(v), std::ostream_iterator<float>(std::cout, " "));
// flush!
std::cout << std::endl;
}
| 35.131579 | 88 | 0.573783 | [
"vector"
] |
ff4f00ee3e2cf8bd067752ba478a316c34139bde | 6,556 | cpp | C++ | Codechef/LONG/MAY18/FAKEBS.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | Codechef/LONG/MAY18/FAKEBS.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | Codechef/LONG/MAY18/FAKEBS.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | // Question +Editorial below
#include<bits/stdc++.h>
#define pu push_back
#define m make_pair
using namespace std;
pair<string, vector< long long int > >binarysearch(long long int l[], long long int n, long long int i)
{
long long int beg = 0, end = n-1;
string s="";
vector<long long int> v;
while(beg<=end)
{
long long int mid = (beg+end)/2;
if(l[mid]==i) break;
else if(l[mid]<i) {beg = mid+1; s+="1";}
else {end = mid -1; s+="0";}
v.pu(mid);
}
return m(s,v);
}
long long int bsearch(long long int l[],long long int n,long long int key)
{
long long int beg = 0, end = n-1;
while(beg<=end)
{
long long int mid = (beg+end)/2;
if(l[mid]==key) return mid;
else if(l[mid]<key) {beg = mid+1;}
else {end = mid -1;}
}
}
pair <long long int,long long int> count(string s)
{
long long int a=0,b=0;
for(long long int i=0;i<s.size();i++)
{
if(s[i]=='0')a++;
else b++;
}
return m(a,b);
}
int main()
{
long long int t;
scanf("%lld",&t);
while(t--)
{
// Ultra precomputation
long long int n,q;
scanf("%lld %lld",&n,&q);
long long int m[n];
vector < pair < string, vector <long long int> > > v;
for(long long int i=0;i<n;i++) m[i] = i;
for(long long int i=0;i<n;i++) v.pu(binarysearch(m,n,i));
// long long int* d = (long long int*)calloc(n,sizeof(long long int));
// Check how many larger ( and smaller )
// if large>= large in logn, check for small
// Similarly for small
// If any of the two conditions aren't true, it's impossible
// If it's possible, for all logn values, if it's a 1, the value should be greater. If not swap, swapcount++
// Similarly, if the node value is 0, the value should be smaller. If not, swap, swapcount++
long long int l[n],c[n];
map <long long int,long long int> d1,d;
for(long long int i=0;i<n;i++) {scanf("%lld",&l[i]);d1[l[i]] = i;c[i] = l[i];} //cin>>l[i];
sort(c,c+n);
for(long long int i=0;i<n;i++)
{
long long int key1 = d1[l[i]];
long long int key2 = bsearch(c,n,l[i]);
pair<string,vector<long long int> > p1 = v[key1];
pair<string,vector<long long int> > p2 = v[key2];
string s = p1.first;
pair<long long int,long long int> p3= count(s);
long long int b = p3.first;
long long int a = p3.second;
if(key2 >= a && n-key2-1 >= b)
{
long long int count1 = 0, count2 = 0;
string s1 = p1.first;
for(long long int j=0;j<p1.second.size();j++)
{
if(s1[j]=='0' && l[p1.second[j]]<l[i]) count1++;
if(s1[j]=='1' && l[p1.second[j]]>l[i]) count2++;
}
d[l[i]] = count1 + count2 - min(count1,count2);
}
else d[l[i]] = -1;
}
for(long long int i=0;i<q;i++)
{
long long int k;
scanf("%lld",&k);
printf("%lld\n",d[k]);
}
}
return 0;
}
/*
1
7 1
7 1 2 3 4 5 6
7
*/
/*
THE QUESTION
There are Q
students in Chef's class. Chef's teacher has given the students a simple assignment:
Write a function that takes as arguments an array A
containing only unique elements and a number X
guaranteed to be present in the array and returns the (1
-based) index of the element that is equal to X
.
The teacher was expecting a linear search algorithm, but since Chef is such an amazing programmer, he decided to write the following binary search function:
integer binary_search(array a, integer n, integer x):
integer low, high, mid
low := 1
high := n
while low ≤ high:
mid := (low + high) / 2
if a[mid] == x:
break
else if a[mid] is less than x:
low := mid+1
else:
high := mid-1
return mid
All of Chef's classmates have copied his code and submitted it to the teacher.
Chef later realised that since he forgot to sort the array, the binary search algorithm may not work. Luckily, the teacher is tired today, so she asked Chef to assist her with grading the codes. Each student's code is graded by providing an array A
and an integer X
to it and checking if the returned index is correct. However, the teacher is lazy and provides the exact same array to all codes. The only thing that varies is the value of X
.
Chef was asked to type in the inputs. He decides that when typing in the input array for each code, he's not going to use the input array he's given, but an array created by swapping some pairs of elements of this original input array. However, he cannot change the position of the element that's equal to X
itself, since that would be suspicious.
For each of the Q
students, Chef would like to know the minimum number of swaps required to make the algorithm find the correct answer.
Input
The first line of the input contains a single integer T
denoting the number of test cases. The description of T
test cases follows.
The first line of each test case contains two space-separated integers N
and Q
denoting the number of elements in the array and the number of students.
The second line contains N
space-separated integers A1,A2,…,AN
.
The following Q
lines describe queries. Each of these lines contains a single integer X
.
Output
For each query, print a single line containing one integer — the minimum required number of swaps, or −1
if it is impossible to make the algorithm find the correct answer. (Do you really think Chef can fail?)
Constraints
1≤T≤10
1≤N,Q≤105
1≤Ai≤109
for each valid i
1≤X≤109
all elements of A
are pairwise distinct
for each query, X
is present in A
sum of N
over all test cases ≤5⋅105
sum of Q
over all test cases ≤5⋅105
*/
/*
EDITORIAL
By looking at the constraints, I get a feeling that it should be an O(qlogn) algorithm with nlogn precomputation,
ie.O((n+q)logn)
Observation 1:
On binary searching, we visit logn nodes. So technically for each query, we ony have to concern ourselves with these logn nodes.
Observation 2:
In order for the bsearch, to be correct, each of these logn nodes have to 'point' to the right direction
Eg , if I have to go to the left side, and then the right side, the node which made me look left has a value greater than X
All we need to do is check if these logn nodes are poiting in the right direction. If they aren't they need to be swapped. The answer is swapleft+ swapright - min(swapleft,swapright) = max(swapleft, swapright)
I precomputed the directions for each index 1 to n and stored it in a string, 0 for left and 1 for right. For each 0 or 1, I mantained an array of these visited nodes.
Then for ea
| 32.944724 | 307 | 0.658481 | [
"vector"
] |
ff548458802eafb5a3d79f971c788c27c70c5bd5 | 5,275 | cpp | C++ | Source/CNTKv2LibraryDll/proto/onnx/ONNX.cpp | lizishu/CNTK-1 | 93cc680d56689bc93f96f9fb08b38d9e08d86d80 | [
"MIT"
] | 1 | 2019-09-02T00:44:37.000Z | 2019-09-02T00:44:37.000Z | Source/CNTKv2LibraryDll/proto/onnx/ONNX.cpp | joelgrus/CNTK | 74d17a74e8d1d4f27a2ae3161122b58b17b15a8c | [
"MIT"
] | null | null | null | Source/CNTKv2LibraryDll/proto/onnx/ONNX.cpp | joelgrus/CNTK | 74d17a74e8d1d4f27a2ae3161122b58b17b15a8c | [
"MIT"
] | 1 | 2019-09-02T00:50:13.000Z | 2019-09-02T00:50:13.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "proto/onnx/core/graph/model.h"
#include "proto/onnx/core/graph/graph.h"
#include "proto/onnx/core/common/logging/logging.h"
#include "Logger.h"
#include "ONNX.h"
#include "CNTKToONNX.h"
#include "ONNXToCNTK.h"
#include "Utils.h"
#include <iostream>
#include <memory>
using namespace CNTK;
using namespace Microsoft::MSR::CNTK;
namespace CNTK
{
std::once_flag ONNXFormat::op_schema_initializer_flag_;
static std::string defaultLoggerId{"Default"};
static Lotus::Logging::LoggingManager default_logging_manager_{
std::unique_ptr<Lotus::Logging::ISink>{new CNTKClogSink{}},
[](){
Lotus::Logging::Severity severity;
switch (GetTraceLevel())
{
case TraceLevel::Error:
severity = Lotus::Logging::Severity::kERROR;
break;
case TraceLevel::Warning:
severity = Lotus::Logging::Severity::kWARNING;
break;
case TraceLevel::Info:
severity = Lotus::Logging::Severity::kINFO;
break;
default:
severity = Lotus::Logging::Severity::kFATAL;
}
return severity;
}(),
false,
Lotus::Logging::LoggingManager::InstanceType::Default,
&defaultLoggerId };
// MaxVersion number in ONNX 1.2 is 7. Change this number (e.g. to 1 or 5)
// to experiment with earlier version ONNX. This is to help debugging with reshape op
// (and some convolution ops which only passed with newer version)
// to do this:
// onnx::OpSchemaRegistry::DomainToVersionRange::Instance().AddDomainToVersion(LotusIR::kOnnxDomain, 1, 5);
const int ONNX2_1MAX_VERSION = 7;
// for debugging (and probably useful backward compatibility) propose, use this helper to tell
// how to implement a conversion. It is used for reshape op.
bool IsONNX1_2Supported()
{
auto map = onnx::OpSchemaRegistry::DomainToVersionRange::Instance().Map();
return map.find(onnx::ONNX_DOMAIN) != map.end() && map[onnx::ONNX_DOMAIN].second == ONNX2_1MAX_VERSION;
}
static void PrintGraph(FunctionPtr function, int spaces, bool useName = false)
{
if (function->Inputs().size() == 0)
{
cout << string(spaces, '.') + "(" + ToLegacyString(ToUTF8(useName ? function->Name() : function->Uid())) + ")" + ToLegacyString(ToUTF8(function->AsString())) << std::endl;
return;
}
for (auto input : function->Inputs())
{
cout << string(spaces, '.') + "(" + ToLegacyString(ToUTF8(useName ? function->Name() : function->Uid())) + ")" + "->" +
"(" + ToLegacyString(ToUTF8(useName ? input.Name() : input.Uid())) + ")" + ToLegacyString(ToUTF8(input.AsString()))
<< std::endl;
}
for (auto input : function->Inputs())
{
if (input.Owner() != NULL)
{
FunctionPtr f = input.Owner();
PrintGraph(f, spaces + 4, useName);
}
}
}
}
void ONNXFormat::InitializeLotusIR()
{
//
// Initializing ONNX_NAMESPACE::Utils::DataTypeUtils::GetTypeStrToProtoMap()
//
// This is a static unordered_map<string, TypeProto> variable that stores the mapping from type name(string) to TypeProto.
// If used without proper initialization, we risk poluting this static map:
// Whenever it sees a TypeProto with an unseen type name, it tries to store that TypeProto into the map.
// That TypeProto object might very likely contain TensorShapeProto, which describes the shape for that particular tensor.
// This shape will become the default for every TypeProto object created from that type name later on.
// And this leads to lots of unexpected errors such as shape inference failure.
//
// The solution is to initialize the map at the first run.
std::call_once(op_schema_initializer_flag_, [&]() {
ONNX_NAMESPACE::OpSchema tmpSchemaForInitializingAllTensorTypes;
tmpSchemaForInitializingAllTensorTypes.TypeConstraint("T", ONNX_NAMESPACE::OpSchema::all_tensor_types(), "");
});
}
void ONNXFormat::Save(const FunctionPtr& src, const std::wstring& filepath)
{
InitializeLotusIR();
auto model = CNTKToONNX::CreateModel(src);
#ifdef _WIN32
LotusIR::Model::Save(*model, filepath);
#else
LotusIR::Model::Save(*model, ToLegacyString(ToUTF8(filepath)));
#endif
}
FunctionPtr ONNXFormat::Load(const std::wstring& filepath, const DeviceDescriptor& computeDevice)
{
InitializeLotusIR();
std::shared_ptr<LotusIR::Model> model;
#ifdef _WIN32
Lotus::Common::Status loadStatus = LotusIR::Model::Load(filepath, model);
#else
Lotus::Common::Status loadStatus = LotusIR::Model::Load(ToLegacyString(ToUTF8(filepath)), model);
#endif
if (!loadStatus.IsOK())
LogicError("Failed to load model: '%s'", loadStatus.ErrorMessage().c_str());
FunctionPtr cntkFunction = ONNXToCNTK::CreateGraph(model->MainGraph(), computeDevice);
return cntkFunction;
}
| 37.94964 | 183 | 0.647204 | [
"object",
"shape",
"model"
] |
ff56ec962e58872f876521a36aeee46279554f7e | 16,639 | hpp | C++ | include/bealab/extensions/control/baytrack.hpp | damianmarelli/bealab | 3357a0b0fd836c3557f39863471680cc99721729 | [
"BSD-3-Clause"
] | 1 | 2018-04-17T13:45:21.000Z | 2018-04-17T13:45:21.000Z | include/bealab/extensions/control/baytrack.hpp | damianmarelli/bealab | 3357a0b0fd836c3557f39863471680cc99721729 | [
"BSD-3-Clause"
] | null | null | null | include/bealab/extensions/control/baytrack.hpp | damianmarelli/bealab | 3357a0b0fd836c3557f39863471680cc99721729 | [
"BSD-3-Clause"
] | null | null | null | /// @file bealab/extensions/control/baytrack.hpp
/// Implementation of Bayesian tracking techniques.
#ifndef _BEALAB_BAYTRACK_
#define _BEALAB_BAYTRACK_
#include <bealab/core/blas.hpp>
#include <bealab/scilib/stats.hpp>
#include <bealab/scilib/optimization.hpp>
#include <bealab/extensions/control/linsys.hpp>
#include <boost/circular_buffer.hpp>
namespace bealab
{
namespace control
{
//------------------------------------------------------------------------------
/// @defgroup baytrack Bayesian tracking
/// Implementation of Bayesian tracking techniques.
/// @{
using boost::circular_buffer;
/// Kalman filter
class kalman_filter : public state_space {
public:
rvec x; ///< Initial state mean
rmat P; ///< Initial state covariance
/// Constructor
kalman_filter( const rmat& A, const rmat& B, const rmat& C, const rmat& D,
const rmat& Q, const rmat& R, const rmat& P_ = rmat() ) :
state_space(A,B,C,D,Q,R)
{
int N = A.size1();
x = zeros(N);
if( P_.size1() == 0 )
P = zeros(N,N);
else
P = P_;
}
/// Constructor
kalman_filter( const state_space& ss, const rmat& P = rmat() ) :
kalman_filter( ss.A, ss.B, ss.C, ss.D, ss.Q, ss.R, P) {}
/// Prediction step
rvec prediction( const rvec& u )
{
x = A * x + B * u;
P = noproxy(A * P) * trans(A) + Q;
return x;
}
/// Update step
rvec update( const rvec& y )
{
int N = A.size1();
rmat K = trans( linsolve( noproxy(C * P) * trans(C) + R, C * P ) );
x = x + K * ( y - C * x );
P = (eye(N) - K * C) * P;
return x;
}
/// Filter one pair of input and output samples
rvec operator()( const rvec& u, const rvec& y )
{
prediction( u );
update( y );
return x;
}
/// Filter an output sample, assuming zero input.
rvec operator()( const rvec& y )
{
int M = B.size2();
rvec u = zeros(M);
return (*this)( u, y );
}
/// Filter one pair of sequences of input and output samples
vec<rvec> operator()( const vec<rvec>& U, const vec<rvec>& Y )
{
assert( U.size() == Y.size() );
int T = U.size();
vec<rvec> Xh(T);
for( int t = 0; t < T; t++ )
Xh(t) = (*this)( U(t), Y(t) );
return Xh;
}
/// Filter a sequences of output samples, assuming zero input.
vec<rvec> operator()( const vec<rvec>& Y )
{
int T = Y.size();
vec<rvec> Xh(T);
for( int t = 0; t < T; t++ )
Xh(t) = (*this)( Y(t) );
return Xh;
}
};
/// Base class for implementing a particle filter.
/// The virtual member functions need to be implemented in a derived class.
/// Need to implement either state_transition() or particle_prediction(), and
/// either likelihood_function() or particle_update().
template< class state_t = rvec, class obs_t = state_t, class out_t = obs_t >
class particle_filter_b {
protected:
/// A particles path with it's associated weight
struct particle_path {
circular_buffer<state_t> trajectory;
double weight;
};
rvec old_weights; ///< Weights before the last update step
bool init_f = false; ///< Flag to indicate that the filter was initialized
int time = 0; ///< The current time used when running the filter
/// A particles with it's associated weight
struct particle {
state_t state;
double weight;
};
/// Draw a sample from the initial distribution
virtual
state_t draw_initial_sample() = 0;
/// State transition function
virtual
state_t state_transition( const state_t& state ) { return state; }
/// Likelihood of the state given the observation
virtual
double likelihood_function( const obs_t& obs, const state_t& state ) { return 1; }
/// Default particle prediction function. Uses state_transition().
virtual
particle particle_prediction( const particle& p )
{
particle pp = p;
pp.state = state_transition( p.state );
return pp;
}
/// Default particle update function. Uses likelihood_function().
virtual
particle particle_update( const obs_t& obs, const particle& p )
{
particle pu = p;
pu.weight *= likelihood_function( obs, p.state );
return pu;
}
/// Output function
virtual
out_t output_function( const state_t& state ) = 0;
public:
vector<particle_path> x; ///< Particles of the current predicted or updated state
const int I; ///< Number of particles
const int lag; ///< Amount of lag used for smoothing.
double resample_period = 1;
/// Constructor
particle_filter_b( int I_, int lag_=0 ) :
old_weights(I_), x(I_), I(I_), lag(lag_)
{
assert( I > 0 );
for( int i = 0; i < I; i++ )
x[i].trajectory = circular_buffer<state_t>(lag+1);
}
/// Destructor
virtual
~particle_filter_b() {}
/// Implements the prediction step
virtual
void prediction()
{
#pragma omp parallel for schedule(dynamic)
for( int i = 0; i < I; i++ ) {
particle p = { x[i].trajectory.back(), x[i].weight };
particle pp = particle_prediction( p );
x[i].trajectory.push_back( pp.state );
x[i].weight = pp.weight;
}
}
/// Implements the update step
virtual
void update( const obs_t& z )
{
#pragma omp parallel for schedule(dynamic)
for( int i = 0; i < I; i++ ) {
particle p = { x[i].trajectory.back(), x[i].weight };
particle pu = particle_update( z, p );
x[i].trajectory.back() = pu.state;
old_weights(i) = x[i].weight;
x[i].weight = pu.weight;
}
normalize();
}
/// Implements the normalization step
virtual
void normalize()
{
double K = 0;
for( int i = 0; i < I; i++ )
K += x[i].weight;
// if( K == 0 ) {
// warning("Ran out of particles");
// for( int i = 0; i < I; i++ )
// x[i].weight = old_weights(i);
// }
// else {
// for( int i = 0; i < I; i++ )
// x[i].weight /= K;
// }
for( int i = 0; i < I; i++ )
x[i].weight /= K;
if( K == 0 )
warning("Ran out of particles");
}
/// Implements the re-sampling step
virtual
void resample()
{
// Store current particles
auto x0 = x;
// Build the distribution
rvec weights(I);
for( int i = 0; i < I; i++ )
weights(i) = x[i].weight;
std::discrete_distribution<> d( weights.begin(), weights.end() );
// Re-sample
for( int i = 0; i < I; i++ ) {
int idx = d(_stats::engine);
x[i].trajectory = x0[idx].trajectory;
x[i].weight = 1./I;
}
}
/// Generates the output
virtual
out_t output()
{
vec<out_t> o(I);
#pragma omp parallel for schedule(dynamic)
for( int i = 0; i < I; i++ )
o(i) = output_function( x[i].trajectory.front() ) * x[i].weight;
return sum(o);
}
/// Draw the particles of the initial state
void initialize()
{
init_f = true;
for( int i = 0; i < I; i++ ) {
x[i].trajectory.push_back( draw_initial_sample() );
x[i].weight = 1./I;
}
}
/// Filter one sample
out_t operator()( const obs_t& z )
{
if( !init_f )
initialize();
update( z );
out_t o = output();
if( mod( time+1, resample_period ) == 0 )
resample();
prediction();
time++;
return o;
}
/// Filter a vector of samples
vec<out_t> operator()( const vec<obs_t>& Z )
{
int T = Z.size();
vec<out_t> Yh(T);
for( int t = 0; t < T; t++ )
Yh(t) = (*this)( Z(t) );
return Yh;
}
};
/// Particle approximation to a Kalman filter (for testing purposes)
class particle_kalman_filter : public particle_filter_b<rvec,rvec,rvec>, public kalman_filter {
int N;
rmat Qh, Rh, Ph;
rvec draw_initial_sample() override
{
return Ph * randn(N);
}
rvec state_transition( const rvec& x ) override
{
return A * x + Qh * randn(N);
}
double likelihood_function( const rvec& y, const rvec& x ) override
{
return pdf( multivariate_normal( C*x, Rh ), y );
}
rvec output_function( const rvec& x ) override
{
return C*x;
}
public:
using particle_filter_b::prediction;
using particle_filter_b::update;
using particle_filter_b::operator();
particle_kalman_filter( int I, const rmat& A, const rmat& B, const rmat& C, const rmat& D,
const rmat& Q, const rmat& R, const rmat& P_ = rmat() ) :
particle_filter_b(I),
kalman_filter(A,B,C,D,Q,R,P_)
{
N = A.size1();
Qh = real(msqrt(Q));
Rh = real(msqrt(R));
Ph = real(msqrt(P));
}
particle_kalman_filter( int I, const state_space& ss, const rmat& P = rmat() ) :
particle_kalman_filter(I,ss.A,ss.B,ss.C,ss.D,ss.Q,ss.R,P)
{}
};
/// State associated to a Rao-Blackwellized particle filter.
struct RB_state_t {
rvec position;
rvec mean;
rmat covariance;
};
/// Base class for implementing Rao-Blackwellized particle filters.
/// The virtual member functions need to be implemented in a derived class.
class RB_particle_filter_b : public particle_filter_b< RB_state_t, rvec, rvec > {
/// Non-linear state transition function
virtual
rvec f( const rvec& x ) = 0;
/// Linear state transition function
virtual
rvec g( const rvec& x ) = 0;
/// Measurement non-linear component
virtual
rvec h( const rvec& x ) = 0;
/// Output non-linear component
virtual
rvec o( const rvec& x ) = 0;
/// Non-linear state transition matrix
virtual
rmat F( const rvec& x ) = 0;
/// Linear state transition matrix
virtual
rmat G( const rvec& x ) = 0;
/// Measurement linear component
virtual
rmat H( const rvec& x ) = 0;
/// Output linear component
virtual
rmat O( const rvec& x ) = 0;
/// Non-linear process noise covariance
virtual
rmat U( const rvec& x ) = 0;
/// Linear process noise covariance
virtual
rmat V( const rvec& x ) = 0;
/// Output noise covariance
virtual
rmat W( const rvec& x ) = 0;
/// Override
particle particle_prediction( const particle& p ) override
{
// Predicted state
particle pp;
// Non-linear elements
rvec f_ = f( p.state.position );
rmat F_ = F( p.state.position );
rmat U_ = U( p.state.position );
rvec g_ = g( p.state.position );
rmat G_ = G( p.state.position );
rmat V_ = V( p.state.position );
// Non-linear prediction
rvec nlp_mean = f_ + F_ * p.state.mean;
rmat nlp_cov = noproxy(F_ * p.state.covariance) * trans(F_) + U_;
rmat nlp_cov_h = real(msqrt(nlp_cov));
rvec nlp = rand( multivariate_normal( nlp_mean, nlp_cov_h ) );
pp.state.position = nlp;
// Linear prediction
if( det(nlp_cov) != 0 ) {
// Linear false update
rvec lfu_obs = nlp - f_;
rmat K = trans( linsolve( nlp_cov, F_ * p.state.covariance ) );
rvec lfu_mean = p.state.mean + K * ( lfu_obs - F_ * p.state.mean );
rmat lfu_cov = (eye(K.size1()) - K * F_) * p.state.covariance;
// Prediction
pp.state.mean = g_ + G_ * lfu_mean;
pp.state.covariance = noproxy(G_ * lfu_cov) * trans(G_) + V_;
}
else {
pp.state.mean = g_ + G_ * p.state.mean;
pp.state.covariance = noproxy(G_ * p.state.covariance) * trans(G_) + V_;
}
// Weight
pp.weight = p.weight;
return pp;
}
/// Override
particle particle_update( const rvec& obs, const particle& p ) override
{
// Update particles
particle pu;
// Non-linear elements
rvec h_ = h( p.state.position );
rmat H_ = H( p.state.position );
rmat W_ = W( p.state.position );
// Linear output prediction
rvec lop_mean = H_ * p.state.mean + h_;
rmat lop_cov = noproxy(H_ * p.state.covariance) * trans(H_) + W_;
// Check the singularity of lop_cov
double singular = (det(lop_cov) == 0);
// Non-linear state update
pu.state.position = p.state.position;
rvec delta = obs - lop_mean;
if( !singular ) {
int N = lop_mean.size();
double a = inner_prod( delta, linsolve( lop_cov, delta ) );
double b = log( pow(2*pi,N) * det(lop_cov) );
pu.weight = exp( -0.5 * (a+b) ) * p.weight;
if( isnan(pu.weight) )
error("Weight is nan");
}
else
pu.weight = ( norm(delta) == 0 ? 1 : 0) * p.weight;
// Linear state update
if( !singular ) {
rvec lsu_obs = obs - h_;
rmat K = trans( linsolve( lop_cov, H_ * p.state.covariance ) );
pu.state.mean = p.state.mean + K * ( lsu_obs - H_ * p.state.mean );
pu.state.covariance = (eye(K.size1()) - K * H_) * p.state.covariance;
}
else {
pu.state.mean = p.state.mean;
pu.state.covariance = p.state.covariance;
}
return pu;
}
/// Override
rvec output_function( const RB_state_t& state ) override
{
rvec o_ = o( state.position );
rmat O_ = O( state.position );
return O_ * state.mean + o_;
}
public:
/// Constructor
RB_particle_filter_b( int I, int lag=0 ) :
particle_filter_b<RB_state_t,rvec,rvec>( I, lag ) {}
/// Destructor
virtual
~RB_particle_filter_b() {}
};
/// Base class for implementing a particle smoother.
/// The virtual member functions need to be implemented in a derived class.
//template< class pos_t = rvec >
//class particle_smoother_b : public particle_filter_b<pos_t> {
//
// int L; ///< Lag size
// particles current; ///< Current updated particles
// deque<particles> lagbuffer; ///< Buffer with the updated particles within the lag
//
// /// Run one lag step
// particles smooth_one_step( const particles& filtered, const particles& lagged )
// {
//// particles rv = filtered;
//// for( int i = 0; i < I; i++ )
//// rv[i].weight *=
// return lagged;
// }
//
// /// Run the backwards smoothing process
// particles smooth_backwards()
// {
// particles lagged = current;
// for( int l = 0; l < L; l++ )
// lagged = smooth_one_step( lagbuffer[l], lagged );
// return lagged;
// }
//
//public:
//
// /// Constructor
// particle_smoother_b( int I_, int L_ ) :
// particle_filter_b(I_), L(L_) {};
//
// /// Filter one sample
// pos_t operator()( const rvec& z ) override
// {
// // Initialize
// if( !init_f )
// initialize();
//
// // Update buffer
// if( (int)lagbuffer.size() == L )
// lagbuffer.pop_back();
// lagbuffer.emplace_front( current );
//
// // Filter
// current = update( x, z );
// particles resampled = resample( current );
// x = prediction( resampled );
// time++;
//
// // Smoothing
// particles xs = smooth_backwards();
// return mean( output(xs) );
// }
//};
/// ML Kalman filter
class maximum_likelihood_kalman_filter_b {
/// State type
struct state {
rvec x;
rmat P;
};
rmat C;
rmat C_pseudoinverse;
virtual
double logLF( const rvec& z, const rvec& x ) = 0;
virtual
rvec logLF_gradient( const rvec& z, const rvec& x )
{
auto loglf = [this,&z](const rvec&x){return logLF(z,x);};
return gradient( loglf, x );
}
virtual
rvec output( const rvec& x )
{
return x;
}
/// Maximum likelihood estimation.
/// Returns the ML estimate in rv.x and the Hessian of the logLF in rv.P
state ml_estimate( const rvec& z, const rvec& guess=rvec() )
{
// Detect Rao-Blackwellization
int L = s.x.size();
int N = s.x.size();
if( C_pseudoinverse.size1() * C_pseudoinverse.size2() > 0 )
N = C_pseudoinverse.size2();
// ML Estimation
auto objfun = [this,&z](const rvec&x){return -logLF(z,x);};
auto objgrad = [this,&z](const rvec&x){return -logLF_gradient(z,x);};
optimization::bfgs opt(N);
opt.set_objective( objfun, objgrad );
if( guess.size() == 0 )
opt.guess = zeros(N);
else
opt.guess = guess;
// // Test derivatives
// rvec xt = randn(N);
// cout << "xtest = " << xt << endl;
// opt.test_derivatives( xt );
// cin.get();
// opt.stop_fincrement_relative = 1e-2;
// opt.stop_xincrement_relative = 1e-2;
rvec xh = opt.optimize();
// Return value
state ml;
ml.x = { xh, zeros(L-N) };
ml.P = jacobian( objgrad, xh );
ml.P = ( ml.P + trans(ml.P) ) / 2;
ml.P = { { ml.P, zeros(N,L-N) },
{ zeros(L-N,N), zeros(L-N,L-N) } };
return ml;
}
/// Prediction step
state prediction( const state& s )
{
state p;
p.x = A * s.x;
p.P = noproxy(A * s.P) * trans(A) + Q;
return p;
}
/// Update step
state update( const state& s, const rvec& z )
{
// ML estimate
state ml = ml_estimate( z, C*s.x );
// Update the state
state u;
u.P = inv( inv(s.P) + ml.P );
u.x = u.P * ( linsolve( s.P, s.x ) + ml.P * ml.x );
return u;
}
public:
state s; ///< Current state
rmat A; ///< State transition matrix
rmat Q; ///< Process noise covariance
/// Destructor
virtual
~maximum_likelihood_kalman_filter_b() {}
void set_C( const rmat& C_ )
{
C = C_;
C_pseudoinverse = real(pinv(C));
}
/// Filter the sample z
rvec operator()( const rvec& z )
{
s = prediction( s );
s = update( s, z );
return output(s.x);
}
/// Filter a vector of samples
vec<rvec> operator()( const vec<rvec>& Z )
{
int T = Z.size();
vec<rvec> Yh(T);
for( int t = 0; t < T; t++ )
Yh(t) = (*this)( Z(t) );
return Yh;
}
};
/// @}
}
}
#endif
| 23.804006 | 96 | 0.609832 | [
"vector"
] |
ff57f4792ba2a420c23ab1aabb9e2ecf0e7bfd32 | 2,521 | cc | C++ | rm/rmtest_p8.cc | harrynp/Record-Based-Database | bb54c3ff6c936a3bea936593ff3ecbaa80c9627e | [
"MIT"
] | 1 | 2021-01-09T11:49:20.000Z | 2021-01-09T11:49:20.000Z | rm/rmtest_p8.cc | Keith-Tachibana/Relational_Database_Management_System | abfa8ca847d96939bf743d5e03bb3d98c47b9c6c | [
"MIT"
] | null | null | null | rm/rmtest_p8.cc | Keith-Tachibana/Relational_Database_Management_System | abfa8ca847d96939bf743d5e03bb3d98c47b9c6c | [
"MIT"
] | 1 | 2020-01-17T23:04:55.000Z | 2020-01-17T23:04:55.000Z | #include "rm_test_util.h"
RC TEST_RM_PRIVATE_8(const string &tableName)
{
// Functions tested
// 1. Delete Tuples
// 2. Scan Empty table
// 3. Delete Table
cout << endl << "***** In RM Test Case Private 8 *****" << endl;
RC rc;
RID rid;
int numTuples = 100000;
void *returnedData = malloc(300);
vector<RID> rids;
vector<string> attributes;
attributes.push_back("tweetid");
attributes.push_back("userid");
attributes.push_back("sender_location");
attributes.push_back("send_time");
attributes.push_back("referred_topics");
attributes.push_back("message_text");
readRIDsFromDisk(rids, numTuples);
for(int i = 0; i < numTuples; i++)
{
rc = rm->deleteTuple(tableName, rids[i]);
if(rc != success) {
free(returnedData);
cout << "***** RelationManager::deleteTuple() failed. RM Test Case Private 8 failed *****" << endl << endl;
return -1;
}
rc = rm->readTuple(tableName, rids[i], returnedData);
if(rc == success) {
free(returnedData);
cout << "***** RelationManager::readTuple() should fail at this point. RM Test Case Private 8 failed *****" << endl << endl;
return -1;
}
if (i % 10000 == 0){
cout << (i+1) << " / " << numTuples << " have been processed." << endl;
}
}
cout << "All records have been processed." << endl;
// Set up the iterator
RM_ScanIterator rmsi3;
rc = rm->scan(tableName, "", NO_OP, NULL, attributes, rmsi3);
if(rc != success) {
free(returnedData);
cout << "***** RelationManager::scan() failed. RM Test Case Private 8 failed. *****" << endl << endl;
return -1;
}
if(rmsi3.getNextTuple(rid, returnedData) != RM_EOF)
{
cout << "***** RM_ScanIterator::getNextTuple() should fail at this point. RM Test Case Private 8 failed. *****" << endl << endl;
rmsi3.close();
free(returnedData);
return -1;
}
rmsi3.close();
free(returnedData);
// Delete a Table
rc = rm->deleteTable(tableName);
if(rc != success) {
cout << "***** RelationManager::deleteTable() failed. RM Test Case Private 8 failed. *****" << endl << endl;
return -1;
}
cout << "***** RM Test Case Private 8 finished. The result will be examined. *****" << endl << endl;
return 0;
}
int main()
{
RC rcmain = TEST_RM_PRIVATE_8("tbl_private_1");
return rcmain;
}
| 29.658824 | 136 | 0.566045 | [
"vector"
] |
ff66667851ae7f3392640507aeff2ba61d07220a | 2,112 | cxx | C++ | lib/seldon/computation/basic_functions/Functions_Base.cxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 7 | 2021-01-31T23:20:07.000Z | 2021-09-09T20:54:15.000Z | lib/seldon/computation/basic_functions/Functions_Base.cxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 1 | 2021-06-07T07:52:38.000Z | 2021-08-13T20:40:55.000Z | lib/seldon/computation/basic_functions/Functions_Base.cxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | null | null | null | #ifndef SELDON_FILE_FUNCTIONS_BASE_CXX
// in this file, we put functions such as Add, Mlt, MltAdd
// with a reduced number of templates in order
// to forbid undesired instantiations of generic functions
/*
Functions defined in this file:
M X -> Y
Mlt(M, X, Y)
alpha M X -> Y
Mlt(alpha, M, X, Y)
M X -> Y
M^T X -> Y
Mlt(Trans, M, X, Y)
*/
namespace Seldon
{
/**********************************
* Functions in Functions_MatVect *
**********************************/
template<class T0, class Prop0, class Storage0, class Allocator0>
void SolveLU(const Matrix<T0, Prop0, Storage0, Allocator0>& A,
const Vector<int>& pivot, Vector<complex<T0> >& x)
{
Vector<T0> xr(x.GetM()), xi(x.GetM());
for (int i = 0; i < x.GetM(); i++)
{
xr(i) = real(x(i));
xi(i) = imag(x(i));
}
SolveLuVector(A, pivot, xr);
SolveLuVector(A, pivot, xi);
for (int i = 0; i < x.GetM(); i++)
x(i) = complex<T0>(xr(i), xi(i));
}
template<class T0, class Storage0, class Allocator0>
void SolveLU(const SeldonTranspose& trans,
const Matrix<T0, General, Storage0, Allocator0>& A,
const Vector<int>& pivot, Vector<complex<T0> >& x)
{
Vector<T0> xr(x.GetM()), xi(x.GetM());
for (int i = 0; i < x.GetM(); i++)
{
xr(i) = real(x(i));
xi(i) = imag(x(i));
}
SolveLuVector(trans, A, pivot, xr);
SolveLuVector(trans, A, pivot, xi);
for (int i = 0; i < x.GetM(); i++)
x(i) = complex<T0>(xr(i), xi(i));
}
template<class T0, class Storage0, class Allocator0>
void SolveLU(const SeldonTranspose& trans,
const Matrix<T0, Symmetric, Storage0, Allocator0>& A,
const Vector<int>& pivot, Vector<complex<T0> >& x)
{
Vector<T0> xr(x.GetM()), xi(x.GetM());
for (int i = 0; i < x.GetM(); i++)
{
xr(i) = real(x(i));
xi(i) = imag(x(i));
}
SolveLuVector(A, pivot, xr);
SolveLuVector(A, pivot, xi);
for (int i = 0; i < x.GetM(); i++)
x(i) = complex<T0>(xr(i), xi(i));
}
}
#define SELDON_FILE_FUNCTIONS_BASE_CXX
#endif
| 23.466667 | 67 | 0.549242 | [
"vector"
] |
ff69609736f24fb429c567d6b0382ef47d2dbe81 | 807 | cc | C++ | model/aodv-weep-id-cache.cc | CaptainIRS/weep | d4e1d5db7fa5503c5d2b0b818d47d0d8ad7d1169 | [
"MIT"
] | null | null | null | model/aodv-weep-id-cache.cc | CaptainIRS/weep | d4e1d5db7fa5503c5d2b0b818d47d0d8ad7d1169 | [
"MIT"
] | null | null | null | model/aodv-weep-id-cache.cc | CaptainIRS/weep | d4e1d5db7fa5503c5d2b0b818d47d0d8ad7d1169 | [
"MIT"
] | null | null | null | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
#include "aodv-weep-id-cache.h"
#include <algorithm>
namespace ns3 {
namespace weep {
bool
IdCache::IsDuplicate (Ipv4Address addr, uint32_t id)
{
Purge ();
for (std::vector<UniqueId>::const_iterator i = m_idCache.begin ();
i != m_idCache.end (); ++i)
{
if (i->m_context == addr && i->m_id == id)
{
return true;
}
}
struct UniqueId uniqueId =
{
addr, id, m_lifetime + Simulator::Now ()
};
m_idCache.push_back (uniqueId);
return false;
}
void
IdCache::Purge ()
{
m_idCache.erase (remove_if (m_idCache.begin (), m_idCache.end (),
IsExpired ()), m_idCache.end ());
}
uint32_t
IdCache::GetSize ()
{
Purge ();
return m_idCache.size ();
}
}
}
| 18.767442 | 68 | 0.577447 | [
"vector"
] |
ff72c1e1b52fb26167ddf203e684bfa4e424fd6c | 3,338 | cxx | C++ | Rendering/FreeType/Testing/Cxx/TestTextBoundingBox.cxx | satya-arjunan/vtk8 | ee7ced57de6d382a2d12693c01e2fcdac350b25f | [
"BSD-3-Clause"
] | 3 | 2015-07-28T18:07:50.000Z | 2018-02-28T20:59:58.000Z | Rendering/FreeType/Testing/Cxx/TestTextBoundingBox.cxx | satya-arjunan/vtk8 | ee7ced57de6d382a2d12693c01e2fcdac350b25f | [
"BSD-3-Clause"
] | 14 | 2015-04-25T17:54:13.000Z | 2017-01-13T15:30:39.000Z | Rendering/FreeType/Testing/Cxx/TestTextBoundingBox.cxx | satya-arjunan/vtk8 | ee7ced57de6d382a2d12693c01e2fcdac350b25f | [
"BSD-3-Clause"
] | 4 | 2016-09-08T02:11:00.000Z | 2019-08-15T02:38:39.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: TestTextBoundingBox.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include <iostream>
#include <vtkVersion.h>
#include <vtkSmartPointer.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkNew.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkTextRenderer.h>
#include <vtkPolyData.h>
#include <vtkSphereSource.h>
#include <vtkTextActor.h>
#include <vtkTextProperty.h>
int TestTextBoundingBox(int, char *[])
{
// Create a renderer
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
renderer->SetBackground ( 1, 1, 1 ); // Set background color to white
// Create a render window
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer ( renderer );
// Create an interactor
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow ( renderWindow );
const char* first = "no descenders";
// Setup the text and add it to the renderer
vtkSmartPointer<vtkTextActor> textActor =
vtkSmartPointer<vtkTextActor>::New();
textActor->SetInput (first);
textActor->GetTextProperty()->SetFontSize ( 24 );
textActor->GetTextProperty()->SetColor ( 1.0, 0.0, 0.0 );
renderer->AddActor2D ( textActor );
// get the bounding box
double bbox[4];
textActor->GetBoundingBox(renderer, bbox);
// get the bounding box a different way
vtkNew<vtkTextRenderer> tren;
int tbox[4];
tren->GetBoundingBox(textActor->GetTextProperty(),
std::string(first), tbox, renderWindow->GetDPI());
// get the bounding box for a string with descenders
// it should have the same height
const char* second = "a couple of good descenders";
int tbox2[4];
tren->GetBoundingBox(textActor->GetTextProperty(),
std::string(second), tbox2, renderWindow->GetDPI());
if (tbox[2] != tbox2[2] || tbox[3] != tbox2[3])
{
std::cout << "vtkTextRenderer height (" << first << "):\n"
<< tbox[2] << ", " << tbox[3] << std::endl;
std::cout << "vtkTextRenderer height (" << second << "):\n"
<< tbox2[2] << ", " << tbox2[3] << std::endl;
return EXIT_FAILURE;
}
if (bbox[0] == tbox[0] && bbox[1] == tbox[1] &&
bbox[2] == tbox[2] && bbox[3] == tbox[3])
return EXIT_SUCCESS;
else
{
std::cout << "vtkTextActor GetBoundingBox:\n"
<< bbox[0] << ", " << bbox[1] << ", "
<< bbox[2] << ", " << bbox[3] << std::endl;
std::cout << "vtkTextRenderer GetBoundingBox:\n"
<< tbox[0] << ", " << tbox[1] << ", "
<< tbox[2] << ", " << tbox[3] << std::endl;
return EXIT_FAILURE;
}
}
| 34.061224 | 75 | 0.623727 | [
"render"
] |
ff757ebc74044657fefa5a9641faaa258e05e8e2 | 28,489 | cpp | C++ | src/rendering/vcTileRenderer.cpp | donutFred/vaultclient | d0af3adcf97c042937d3eaac3cd2be3a8dbd806c | [
"MIT"
] | 1 | 2020-07-15T14:04:47.000Z | 2020-07-15T14:04:47.000Z | src/rendering/vcTileRenderer.cpp | donutFred/vaultclient | d0af3adcf97c042937d3eaac3cd2be3a8dbd806c | [
"MIT"
] | null | null | null | src/rendering/vcTileRenderer.cpp | donutFred/vaultclient | d0af3adcf97c042937d3eaac3cd2be3a8dbd806c | [
"MIT"
] | null | null | null | #include "vcTileRenderer.h"
#include "vcQuadTree.h"
#include "vcGIS.h"
#include "vcSettings.h"
#include "gl/vcGLState.h"
#include "gl/vcMeshUtils.h"
#include "gl/vcRenderShaders.h"
#include "gl/vcShader.h"
#include "gl/vcMesh.h"
#include "udThread.h"
#include "udFile.h"
#include "udPlatformUtil.h"
#include "udChunkedArray.h"
#include "udStringUtil.h"
#include "stb_image.h"
#include <vector>
// Debug tiles with colour information
#define VISUALIZE_DEBUG_TILES 0
enum
{
TileVertexResolution = 2, // This should match GPU struct size
TileIndexResolution = (TileVertexResolution - 1),
MaxTextureUploadsPerFrame = 3,
};
static const float sTileFadeSpeed = 2.15f;
struct vcTileRenderer
{
float frameDeltaTime;
float totalTime;
vcSettings *pSettings;
vcQuadTree quadTree;
vcMesh *pFullTileMesh;
vcTexture *pEmptyTileTexture;
udDouble3 cameraPosition;
std::vector<std::vector<vcQuadTreeNode*>> *pRenderQueue;
std::vector<vcQuadTreeNode*> *pTransparentTiles;
// cache textures
struct vcTileCache
{
volatile bool keepLoading;
udThread *pThreads[8];
udSemaphore *pSemaphore;
udMutex *pMutex;
udChunkedArray<vcQuadTreeNode*> tileLoadList;
udChunkedArray<vcQuadTreeNode*> tileTimeoutList;
} cache;
struct
{
vcShader *pProgram;
vcShaderConstantBuffer *pConstantBuffer;
vcShaderSampler *uniform_texture;
struct
{
udFloat4x4 projectionMatrix;
udFloat4 eyePositions[TileVertexResolution * TileVertexResolution];
udFloat4 colour;
} everyObject;
} presentShader;
};
// This functionality here for now until the cache module is implemented
bool vcTileRenderer_TryWriteTile(const char *filename, void *pFileData, size_t fileLen)
{
udFile *pFile = nullptr;
if (udFile_Open(&pFile, filename, udFOF_Create | udFOF_Write) == udR_Success)
{
udFile_Write(pFile, pFileData, fileLen);
udFile_Close(&pFile);
return true;
}
return false;
}
// This functionality here for now. In the future will be migrated to udPlatformUtils.
udResult vcTileRenderer_CreateDirRecursive(const char *pFolderPath)
{
udResult result = udR_Success;
char *pMutableDirectoryPath = nullptr;
UD_ERROR_NULL(pFolderPath, udR_InvalidParameter_);
pMutableDirectoryPath = udStrdup(pFolderPath);
UD_ERROR_NULL(pMutableDirectoryPath, udR_MemoryAllocationFailure);
for (uint32_t i = 0;; ++i)
{
if (pMutableDirectoryPath[i] == '\0' || pMutableDirectoryPath[i] == '/' || pMutableDirectoryPath[i] == '\\')
{
pMutableDirectoryPath[i] = '\0';
result = udCreateDir(pMutableDirectoryPath);
// TODO: handle directories already existing
// TODO: handle path not found
//if (result != udR_Success)
// UD_ERROR_HANDLE();
pMutableDirectoryPath[i] = pFolderPath[i];
if (pMutableDirectoryPath[i] == '\0')
break;
}
}
epilogue:
udFree(pMutableDirectoryPath);
return result;
}
bool vcTileRenderer_ShouldLoadNode(vcQuadTreeNode *pNode)
{
return pNode->renderInfo.tryLoad && pNode->touched && (pNode->renderInfo.loadStatus == vcNodeRenderInfo::vcTLS_InQueue);
}
void vcTileRenderer_LoadThread(void *pThreadData)
{
vcTileRenderer *pRenderer = (vcTileRenderer*)pThreadData;
vcTileRenderer::vcTileCache *pCache = &pRenderer->cache;
while (pCache->keepLoading)
{
int loadStatus = udWaitSemaphore(pCache->pSemaphore, 1000);
if (loadStatus != 0 && pCache->tileLoadList.length == 0)
continue;
while (pCache->tileLoadList.length > 0 && pCache->keepLoading)
{
udLockMutex(pCache->pMutex);
// TODO: Store in priority order and recalculate on insert/delete
int best = -1;
vcQuadTreeNode *pNode = nullptr;
udDouble3 tileCenter = udDouble3::zero();
double bestDistancePrioritySqr = FLT_MAX;
for (int i = 0; i < (int)pCache->tileLoadList.length; ++i)
{
pNode = pCache->tileLoadList[i];
if (!vcTileRenderer_ShouldLoadNode(pNode))
{
pNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_None;
pCache->tileLoadList.RemoveSwapLast(i);
--i;
continue;
}
tileCenter = udDouble3::create(pNode->renderInfo.center, pRenderer->pSettings->maptiles.mapHeight);
double distanceToCameraSqr = udMagSq3(tileCenter - pRenderer->cameraPosition);
// root (special case)
if (pNode == &pRenderer->quadTree.nodes.pPool[pRenderer->quadTree.rootIndex])
{
best = i;
break;
}
bool betterNode = true;
if (best != -1)
{
vcQuadTreeNode *pBestNode = pCache->tileLoadList[best];
// priorities: visibility > failed to render visible area > distance
betterNode = pNode->visible && !pBestNode->visible;
if (pNode->visible == pBestNode->visible)
{
betterNode = !pNode->rendered && pBestNode->rendered;
if (pNode->rendered == pBestNode->rendered)
{
betterNode = distanceToCameraSqr < bestDistancePrioritySqr;
}
}
}
if (betterNode)
{
bestDistancePrioritySqr = distanceToCameraSqr;
best = int(i);
}
}
if (best == -1)
{
udReleaseMutex(pCache->pMutex);
break;
}
vcQuadTreeNode *pBestNode = pCache->tileLoadList[best];
pBestNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_Downloading;
pCache->tileLoadList.RemoveSwapLast(best);
char localFileName[vcMaxPathLength];
char serverAddress[vcMaxPathLength];
udSprintf(localFileName, "%s/%s/%d/%d/%d.%s", pRenderer->pSettings->cacheAssetPath, udUUID_GetAsString(pRenderer->pSettings->maptiles.tileServerAddressUUID), pBestNode->slippyPosition.z, pBestNode->slippyPosition.x, pBestNode->slippyPosition.y, pRenderer->pSettings->maptiles.tileServerExtension);
udSprintf(serverAddress, "%s/%d/%d/%d.%s", pRenderer->pSettings->maptiles.tileServerAddress, pBestNode->slippyPosition.z, pBestNode->slippyPosition.x, pBestNode->slippyPosition.y, pRenderer->pSettings->maptiles.tileServerExtension);
udReleaseMutex(pCache->pMutex);
bool downloadingFromServer = true;
char *pTileURL = serverAddress;
if (udFileExists(localFileName) == udR_Success)
{
pTileURL = localFileName;
downloadingFromServer = false;
}
udResult result = udR_Failure_;
void *pFileData = nullptr;
int64_t fileLen = -1;
int width = 0;
int height = 0;
int channelCount = 0;
uint8_t *pData = nullptr;
UD_ERROR_CHECK(udFile_Load(pTileURL, &pFileData, &fileLen));
UD_ERROR_IF(fileLen == 0, udR_InternalError);
// Node has been invalidated since download started
if (!pBestNode->touched)
{
// TODO: Put into LRU texture cache (but for now just throw it out)
pBestNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_None;
// Even though the node is now invalid - since we the data, it may be put into local disk cache
UD_ERROR_SET(udR_Success);
}
pData = stbi_load_from_memory((stbi_uc*)pFileData, (int)fileLen, (int*)&width, (int*)&height, (int*)&channelCount, 4);
UD_ERROR_NULL(pData, udR_InternalError);
pBestNode->renderInfo.transparency = 0.0f;
pBestNode->renderInfo.width = width;
pBestNode->renderInfo.height = height;
pBestNode->renderInfo.pData = udMemDup(pData, sizeof(uint32_t)*width*height, 0, udAF_None);
pBestNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_Downloaded;
epilogue:
if (result != udR_Success)
{
pBestNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_Failed;
if (result == udR_Pending)
{
pBestNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_InQueue;
udLockMutex(pCache->pMutex);
if (pBestNode->slippyPosition.z <= 10)
{
// TODO: server prioritizes these tiles, so will be available much sooner. Requeue immediately
pCache->tileLoadList.PushBack(pBestNode);
}
else
{
pBestNode->renderInfo.timeoutTime = pRenderer->totalTime + 15.0f; // 15 seconds
pCache->tileTimeoutList.PushBack(pBestNode); // timeout it, inserted last
}
udReleaseMutex(pCache->pMutex);
}
}
// This functionality here for now until the cache module is implemented
if (pFileData && fileLen > 0 && downloadingFromServer && pCache->keepLoading)
{
if (!vcTileRenderer_TryWriteTile(localFileName, pFileData, fileLen))
{
size_t index = 0;
char localFolderPath[vcMaxPathLength];
udSprintf(localFolderPath, "%s", localFileName);
if (udStrrchr(localFileName, "\\/", &index) != nullptr)
localFolderPath[index] = '\0';
if (vcTileRenderer_CreateDirRecursive(localFolderPath) == udR_Success)
vcTileRenderer_TryWriteTile(localFileName, pFileData, fileLen);
}
}
udFree(pFileData);
stbi_image_free(pData);
}
}
}
void vcTileRenderer_BuildMeshVertices(vcP3Vertex *pVerts, int *pIndicies, udFloat2 minUV, udFloat2 maxUV)
{
for (int y = 0; y < TileIndexResolution; ++y)
{
for (int x = 0; x < TileIndexResolution; ++x)
{
int index = y * TileIndexResolution + x;
int vertIndex = y * TileVertexResolution + x;
pIndicies[index * 6 + 0] = vertIndex + TileVertexResolution;
pIndicies[index * 6 + 1] = vertIndex + 1;
pIndicies[index * 6 + 2] = vertIndex;
pIndicies[index * 6 + 3] = vertIndex + TileVertexResolution;
pIndicies[index * 6 + 4] = vertIndex + TileVertexResolution + 1;
pIndicies[index * 6 + 5] = vertIndex + 1;
}
}
float normalizeVertexPositionScale = float(TileVertexResolution) / (TileVertexResolution - 1); // ensure verts are [0, 1]
for (int y = 0; y < TileVertexResolution; ++y)
{
for (int x = 0; x < TileVertexResolution; ++x)
{
uint32_t index = y * TileVertexResolution + x;
pVerts[index].position.z = (float)index;
float normX = ((float)(x) / TileVertexResolution) * normalizeVertexPositionScale;
float normY = ((float)(y) / TileVertexResolution) * normalizeVertexPositionScale;
pVerts[index].position.x = minUV.x + normX * (maxUV.x - minUV.x);
pVerts[index].position.y = minUV.y + normY * (maxUV.y - minUV.y);
}
}
}
udResult vcTileRenderer_Create(vcTileRenderer **ppTileRenderer, vcSettings *pSettings)
{
udResult result;
vcTileRenderer *pTileRenderer = nullptr;
vcP3Vertex verts[TileVertexResolution * TileVertexResolution] = {};
int indicies[TileIndexResolution * TileIndexResolution * 6] = {};
uint32_t greyPixel = 0xf3f3f3ff;
UD_ERROR_NULL(ppTileRenderer, udR_InvalidParameter_);
pTileRenderer = udAllocType(vcTileRenderer, 1, udAF_Zero);
UD_ERROR_NULL(pTileRenderer, udR_MemoryAllocationFailure);
vcQuadTree_Create(&pTileRenderer->quadTree, pSettings);
pTileRenderer->pSettings = pSettings;
pTileRenderer->cache.pSemaphore = udCreateSemaphore();
pTileRenderer->cache.pMutex = udCreateMutex();
pTileRenderer->cache.keepLoading = true;
pTileRenderer->cache.tileLoadList.Init(128);
pTileRenderer->cache.tileTimeoutList.Init(128);
for (size_t i = 0; i < udLengthOf(pTileRenderer->cache.pThreads); ++i)
udThread_Create(&pTileRenderer->cache.pThreads[i], (udThreadStart*)vcTileRenderer_LoadThread, pTileRenderer);
vcShader_CreateFromText(&pTileRenderer->presentShader.pProgram, g_tileVertexShader, g_tileFragmentShader, vcP3VertexLayout);
vcShader_GetConstantBuffer(&pTileRenderer->presentShader.pConstantBuffer, pTileRenderer->presentShader.pProgram, "u_EveryObject", sizeof(pTileRenderer->presentShader.everyObject));
vcShader_GetSamplerIndex(&pTileRenderer->presentShader.uniform_texture, pTileRenderer->presentShader.pProgram, "u_texture");
// build meshes
vcTileRenderer_BuildMeshVertices(verts, indicies, udFloat2::create(0.0f, 0.0f), udFloat2::create(1.0f, 1.0f));
vcMesh_Create(&pTileRenderer->pFullTileMesh, vcP3VertexLayout, (int)udLengthOf(vcP3VertexLayout), verts, TileVertexResolution * TileVertexResolution, indicies, TileIndexResolution * TileIndexResolution * 6);
vcTexture_Create(&pTileRenderer->pEmptyTileTexture, 1, 1, &greyPixel);
pTileRenderer->pTransparentTiles = new std::vector<vcQuadTreeNode*>();
pTileRenderer->pRenderQueue = new std::vector<std::vector<vcQuadTreeNode*>>();
for (int i = 0; i < MaxVisibleTileLevel; ++i)
pTileRenderer->pRenderQueue->push_back(std::vector<vcQuadTreeNode*>());
*ppTileRenderer = pTileRenderer;
pTileRenderer = nullptr;
result = udR_Success;
epilogue:
if (pTileRenderer)
vcTileRenderer_Destroy(&pTileRenderer);
return result;
}
udResult vcTileRenderer_Destroy(vcTileRenderer **ppTileRenderer)
{
if (ppTileRenderer == nullptr || *ppTileRenderer == nullptr)
return udR_InvalidParameter_;
vcTileRenderer *pTileRenderer = *ppTileRenderer;
pTileRenderer->cache.keepLoading = false;
for (size_t i = 0; i < udLengthOf(pTileRenderer->cache.pThreads); ++i)
udIncrementSemaphore(pTileRenderer->cache.pSemaphore);
for (size_t i = 0; i < udLengthOf(pTileRenderer->cache.pThreads); ++i)
{
udThread_Join(pTileRenderer->cache.pThreads[i]);
udThread_Destroy(&pTileRenderer->cache.pThreads[i]);
}
udDestroyMutex(&pTileRenderer->cache.pMutex);
udDestroySemaphore(&pTileRenderer->cache.pSemaphore);
pTileRenderer->cache.tileLoadList.Deinit();
pTileRenderer->cache.tileTimeoutList.Deinit();
vcShader_ReleaseConstantBuffer(pTileRenderer->presentShader.pProgram, pTileRenderer->presentShader.pConstantBuffer);
vcShader_DestroyShader(&(pTileRenderer->presentShader.pProgram));
vcMesh_Destroy(&pTileRenderer->pFullTileMesh);
vcTexture_Destroy(&pTileRenderer->pEmptyTileTexture);
delete pTileRenderer->pTransparentTiles;
delete pTileRenderer->pRenderQueue;
pTileRenderer->pTransparentTiles = nullptr;
pTileRenderer->pRenderQueue = nullptr;
vcQuadTree_Destroy(&(*ppTileRenderer)->quadTree);
udFree(*ppTileRenderer);
*ppTileRenderer = nullptr;
return udR_Success;
}
bool vcTileRenderer_UpdateTileTexture(vcTileRenderer *pTileRenderer, vcQuadTreeNode *pNode)
{
vcTileRenderer::vcTileCache *pTileCache = &pTileRenderer->cache;
if (pNode->renderInfo.loadStatus == vcNodeRenderInfo::vcTLS_None)
{
pNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_InQueue;
pNode->renderInfo.pData = nullptr;
pNode->renderInfo.pTexture = nullptr;
pNode->renderInfo.timeoutTime = pTileRenderer->totalTime;
udDouble2 min = udDouble2::create(pNode->worldBounds[0].x, pNode->worldBounds[2].y);
udDouble2 max = udDouble2::create(pNode->worldBounds[3].x, pNode->worldBounds[1].y);
pNode->renderInfo.center = (max + min) * 0.5;
pTileCache->tileLoadList.PushBack(pNode);
udIncrementSemaphore(pTileCache->pSemaphore);
}
pNode->renderInfo.tryLoad = true;
if (pNode->renderInfo.loadStatus == vcNodeRenderInfo::vcTLS_Downloaded)
{
pNode->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_Loaded;
pNode->renderInfo.tryLoad = false;
vcTexture_Create(&pNode->renderInfo.pTexture, pNode->renderInfo.width, pNode->renderInfo.height, pNode->renderInfo.pData, vcTextureFormat_RGBA8, vcTFM_Linear, true, vcTWM_Clamp, vcTCF_None, 16);
udFree(pNode->renderInfo.pData);
return true;
}
return false;
}
void vcTileRenderer_UpdateTextureQueuesRecursive(vcTileRenderer *pTileRenderer, vcQuadTreeNode *pNode, int &tileUploadCount)
{
if (tileUploadCount >= MaxTextureUploadsPerFrame)
return;
if (!vcQuadTree_IsLeafNode(pNode))
{
for (int c = 0; c < 4; ++c)
vcTileRenderer_UpdateTextureQueuesRecursive(pTileRenderer, &pTileRenderer->quadTree.nodes.pPool[pNode->childBlockIndex + c], tileUploadCount);
}
if (pNode->renderInfo.loadStatus != vcNodeRenderInfo::vcTLS_Loaded && vcQuadTree_IsVisibleLeafNode(&pTileRenderer->quadTree, pNode))
{
if (vcTileRenderer_UpdateTileTexture(pTileRenderer, pNode))
++tileUploadCount;
}
if (pNode->renderInfo.loadStatus == vcNodeRenderInfo::vcTLS_Loaded && !pNode->renderInfo.fadingIn && pNode->renderInfo.transparency == 0.0f)
{
pNode->renderInfo.fadingIn = true;
pTileRenderer->pTransparentTiles->push_back(pNode);
}
}
void vcTileRenderer_UpdateTextureQueues(vcTileRenderer *pTileRenderer)
{
// invalidate current queue
for (size_t i = 0; i < pTileRenderer->cache.tileLoadList.length; ++i)
pTileRenderer->cache.tileLoadList[i]->renderInfo.tryLoad = false;
// Limit the max number of tiles uploaded per frame
// TODO: use timings instead
int tileUploadCount = 0;
// update visible tiles textures
vcTileRenderer_UpdateTextureQueuesRecursive(pTileRenderer, &pTileRenderer->quadTree.nodes.pPool[pTileRenderer->quadTree.rootIndex], tileUploadCount);
// always request root
vcTileRenderer_UpdateTileTexture(pTileRenderer, &pTileRenderer->quadTree.nodes.pPool[pTileRenderer->quadTree.rootIndex]);
// remove from the queue any tiles that are invalid
for (int i = 0; i < (int)pTileRenderer->cache.tileLoadList.length; ++i)
{
if (!pTileRenderer->cache.tileLoadList[i]->renderInfo.tryLoad)
{
pTileRenderer->cache.tileLoadList[i]->renderInfo.loadStatus = vcNodeRenderInfo::vcTLS_None;
pTileRenderer->cache.tileLoadList.RemoveSwapLast(i);
--i;
}
}
// Note: this is a FIFO queue, so only need to check the head
while (pTileRenderer->cache.tileTimeoutList.length > 0)
{
vcQuadTreeNode *pNode = pTileRenderer->cache.tileTimeoutList[0];
if (vcTileRenderer_ShouldLoadNode(pNode) && (pNode->renderInfo.timeoutTime - pTileRenderer->totalTime) > 0.0f)
break;
pTileRenderer->cache.tileLoadList.PushBack(pNode);
pTileRenderer->cache.tileTimeoutList.RemoveSwapLast(0);
}
// TODO: For each tile in cache, LRU destroy
}
void vcTileRenderer_Update(vcTileRenderer *pTileRenderer, const double deltaTime, vcGISSpace *pSpace, const udDouble3 worldCorners[4], const udInt3 &slippyCoords, const udDouble3 &cameraWorldPos, const udDouble4x4 &viewProjectionMatrix)
{
pTileRenderer->frameDeltaTime = (float)deltaTime;
pTileRenderer->totalTime += pTileRenderer->frameDeltaTime;
pTileRenderer->cameraPosition = cameraWorldPos;
double slippyCornersViewSize = udMag3(worldCorners[1] - worldCorners[2]) * 0.5;
vcQuadTreeViewInfo viewInfo =
{
pSpace,
slippyCoords,
cameraWorldPos,
slippyCornersViewSize,
pTileRenderer->pSettings->maptiles.mapHeight,
viewProjectionMatrix,
MaxVisibleTileLevel
};
uint64_t startTime = udPerfCounterStart();
vcQuadTree_Update(&pTileRenderer->quadTree, viewInfo);
vcQuadTree_Prune(&pTileRenderer->quadTree);
udLockMutex(pTileRenderer->cache.pMutex);
vcTileRenderer_UpdateTextureQueues(pTileRenderer);
udReleaseMutex(pTileRenderer->cache.pMutex);
pTileRenderer->quadTree.metaData.generateTimeMs = udPerfCounterMilliseconds(startTime);
}
bool vcTileRenderer_NodeHasValidBounds(vcQuadTreeNode *pNode)
{
return !((pNode->tileExtents.x <= UD_EPSILON || pNode->tileExtents.y <= UD_EPSILON) ||
pNode->worldBounds[0].x > pNode->worldBounds[1].x || pNode->worldBounds[2].x > pNode->worldBounds[3].x ||
pNode->worldBounds[2].y > pNode->worldBounds[0].y || pNode->worldBounds[3].y > pNode->worldBounds[1].y);
}
bool vcTileRenderer_IsRootNode(vcTileRenderer *pTileRenderer, vcQuadTreeNode *pNode)
{
return (pNode == &pTileRenderer->quadTree.nodes.pPool[pTileRenderer->quadTree.rootIndex]);
}
bool vcTileRenderer_CanNodeDraw(vcQuadTreeNode *pNode)
{
if (!pNode->renderInfo.pTexture || pNode->renderInfo.fadingIn)
return false;
return vcTileRenderer_NodeHasValidBounds(pNode);
}
bool vcTileRenderer_DrawNode(vcTileRenderer *pTileRenderer, vcQuadTreeNode *pNode, vcMesh *pMesh, const udDouble4x4 &view, bool parentCanDraw)
{
vcTexture *pTexture = pNode->renderInfo.pTexture;
float tileTransparency = pNode->renderInfo.transparency * pTileRenderer->pSettings->maptiles.transparency;
if (pTexture == nullptr)
{
#if !VISUALIZE_DEBUG_TILES
if (!vcTileRenderer_IsRootNode(pTileRenderer, pNode) && parentCanDraw)
return false;
#endif
pTexture = pTileRenderer->pEmptyTileTexture;
tileTransparency = pTileRenderer->pSettings->maptiles.transparency;
}
for (int t = 0; t < TileVertexResolution * TileVertexResolution; ++t)
{
udFloat4 eyeSpaceVertexPosition = udFloat4::create(view * udDouble4::create(pNode->worldBounds[t], 0.0, 1.0));
pTileRenderer->presentShader.everyObject.eyePositions[t] = eyeSpaceVertexPosition;
}
pTileRenderer->presentShader.everyObject.colour = udFloat4::create(1.f, 1.f, 1.f, tileTransparency);
#if VISUALIZE_DEBUG_TILES
pTileRenderer->presentShader.everyObject.colour.w = 1.0f;
if (!pNode->renderInfo.pTexture)
{
pTileRenderer->presentShader.everyObject.colour.x = pNode->level / 21.0f;
if (!pNode->visible)
pTileRenderer->presentShader.everyObject.colour.z = pNode->level / 21.0f;
}
#endif
vcShader_BindTexture(pTileRenderer->presentShader.pProgram, pTexture, 0);
vcShader_BindConstantBuffer(pTileRenderer->presentShader.pProgram, pTileRenderer->presentShader.pConstantBuffer, &pTileRenderer->presentShader.everyObject, sizeof(pTileRenderer->presentShader.everyObject));
vcMesh_Render(pMesh, TileIndexResolution * TileIndexResolution * 2); // 2 tris per quad
pNode->rendered = true;
++pTileRenderer->quadTree.metaData.nodeRenderCount;
return true;
}
void vcTileRenderer_RecursiveSetRendered(vcTileRenderer *pTileRenderer, vcQuadTreeNode *pNode, bool rendered)
{
pNode->rendered = pNode->rendered || rendered;
if (!vcQuadTree_IsLeafNode(pNode))
{
for (int c = 0; c < 4; ++c)
vcTileRenderer_RecursiveSetRendered(pTileRenderer, &pTileRenderer->quadTree.nodes.pPool[pNode->childBlockIndex + c], pNode->rendered);
}
}
// 'true' indicates the node was able to render itself (or it didn't want to render itself).
// 'false' indicates that the nodes ancestor needs to be rendered.
bool vcTileRenderer_RecursiveBuildRenderQueue(vcTileRenderer *pTileRenderer, vcQuadTreeNode *pNode, bool canParentDraw)
{
if (!pNode->touched)
{
vcQuadTreeNode *pParentNode = &pTileRenderer->quadTree.nodes.pPool[pNode->parentIndex];
// parent can render itself (opaque), so this tile is not needed
if (pParentNode->renderInfo.pTexture && !pParentNode->renderInfo.fadingIn)
return false;
// re-test visibility
pNode->visible = pParentNode->visible && vcQuadTree_IsNodeVisible(&pTileRenderer->quadTree, pNode);
}
if (!pNode->visible)
return false;
bool childrenNeedThisTileRendered = vcQuadTree_IsLeafNode(pNode);
if (!childrenNeedThisTileRendered)
{
for (int c = 0; c < 4; ++c)
{
vcQuadTreeNode *pChildNode = &pTileRenderer->quadTree.nodes.pPool[pNode->childBlockIndex + c];
childrenNeedThisTileRendered = !vcTileRenderer_RecursiveBuildRenderQueue(pTileRenderer, pChildNode, canParentDraw || vcTileRenderer_CanNodeDraw(pChildNode)) || childrenNeedThisTileRendered;
}
}
if (pNode->renderInfo.fadingIn)
return false;
if (childrenNeedThisTileRendered)
{
if (!pNode->renderInfo.pTexture && (!vcTileRenderer_IsRootNode(pTileRenderer, pNode) && canParentDraw))
return false;
if (!vcTileRenderer_NodeHasValidBounds(pNode))
return false;
pTileRenderer->pRenderQueue->at(pNode->level).push_back(pNode);
}
// This child doesn't need parent to draw itself
return true;
}
// Depth first rendering, using stencil to ensure no overdraw
void vcTileRenderer_DrawRenderQueue(vcTileRenderer *pTileRenderer, const udDouble4x4 &view)
{
for (int i = MaxVisibleTileLevel - 1; i >= 0; --i)
{
for (size_t t = 0; t < pTileRenderer->pRenderQueue->at(i).size(); ++t)
{
vcTileRenderer_DrawNode(pTileRenderer, pTileRenderer->pRenderQueue->at(i).at(t), pTileRenderer->pFullTileMesh, view, false);
}
}
}
void vcTileRenderer_Render(vcTileRenderer *pTileRenderer, const udDouble4x4 &view, const udDouble4x4 &proj)
{
vcQuadTreeNode *pRootNode = &pTileRenderer->quadTree.nodes.pPool[pTileRenderer->quadTree.rootIndex];
if (!pRootNode->touched) // can occur on failed re-roots
return;
for (int i = 0; i < MaxVisibleTileLevel; ++i)
pTileRenderer->pRenderQueue->at(i).clear();
udDouble4x4 viewWithMapTranslation = view * udDouble4x4::translation(0, 0, pTileRenderer->pSettings->maptiles.mapHeight);
vcGLStencilSettings stencil = {};
stencil.writeMask = 0xFF;
stencil.compareFunc = vcGLSSF_Equal;
stencil.compareValue = 0;
stencil.compareMask = 0xFF;
stencil.onStencilFail = vcGLSSOP_Keep;
stencil.onDepthFail = vcGLSSOP_Keep;
stencil.onStencilAndDepthPass = vcGLSSOP_Increment;
vcGLState_SetFaceMode(vcGLSFM_Solid, vcGLSCM_None);
vcGLState_SetDepthStencilMode(vcGLSDM_LessOrEqual, true, &stencil);
if (pTileRenderer->pSettings->maptiles.transparency >= 1.0f)
vcGLState_SetBlendMode(vcGLSBM_None);
else
vcGLState_SetBlendMode(vcGLSBM_Interpolative);
if (pTileRenderer->pSettings->maptiles.blendMode == vcMTBM_Overlay)
{
vcGLState_SetViewportDepthRange(0.0f, 0.0f);
vcGLState_SetDepthStencilMode(vcGLSDM_Always, false, &stencil);
}
else if (pTileRenderer->pSettings->maptiles.blendMode == vcMTBM_Underlay)
{
vcGLState_SetViewportDepthRange(1.0f, 1.0f);
}
vcShader_Bind(pTileRenderer->presentShader.pProgram);
pTileRenderer->presentShader.everyObject.projectionMatrix = udFloat4x4::create(proj);
pRootNode->renderInfo.transparency = 1.0f;
vcTileRenderer_RecursiveBuildRenderQueue(pTileRenderer, pRootNode, vcTileRenderer_CanNodeDraw(pRootNode));
vcTileRenderer_DrawRenderQueue(pTileRenderer, viewWithMapTranslation);
// Render the root tile again (if it hasn't already been rendered normally) to cover up gaps between tiles
if (!pRootNode->rendered && pRootNode->renderInfo.pTexture && vcTileRenderer_NodeHasValidBounds(pRootNode))
vcTileRenderer_DrawNode(pTileRenderer, pRootNode, pTileRenderer->pFullTileMesh, viewWithMapTranslation, false);
// Draw transparent tiles
if (pTileRenderer->pTransparentTiles->size() > 0)
{
// We know there will always be a stenciled opaque tile behind every transparent tile, so draw
// with no depth testing, but stencil testing for map tiles
stencil.writeMask = 0xFF;
stencil.compareFunc = vcGLSSF_NotEqual;
stencil.compareValue = 0;
stencil.compareMask = 0xFF;
stencil.onStencilFail = vcGLSSOP_Keep;
stencil.onDepthFail = vcGLSSOP_Keep;
stencil.onStencilAndDepthPass = vcGLSSOP_Keep;
vcGLState_SetDepthStencilMode(vcGLSDM_Always, false, &stencil);
vcGLState_SetBlendMode(vcGLSBM_Interpolative);
for (auto tile : (*pTileRenderer->pTransparentTiles))
{
tile->renderInfo.transparency = udMin(1.0f, tile->renderInfo.transparency + pTileRenderer->frameDeltaTime * sTileFadeSpeed);
if (tile->visible && vcTileRenderer_NodeHasValidBounds(tile))
vcTileRenderer_DrawNode(pTileRenderer, tile, pTileRenderer->pFullTileMesh, viewWithMapTranslation, false);
}
for (int i = 0; i < int(pTileRenderer->pTransparentTiles->size()); ++i)
{
if (pTileRenderer->pTransparentTiles->at(i)->renderInfo.transparency >= 1.0f)
{
pTileRenderer->pTransparentTiles->at(i)->renderInfo.fadingIn = false;
pTileRenderer->pTransparentTiles->erase(pTileRenderer->pTransparentTiles->begin() + i);
--i;
}
}
}
vcTileRenderer_RecursiveSetRendered(pTileRenderer, pRootNode, pRootNode->rendered);
vcGLState_SetViewportDepthRange(0.0f, 1.0f);
vcGLState_SetDepthStencilMode(vcGLSDM_LessOrEqual, true, nullptr);
vcGLState_SetBlendMode(vcGLSBM_None);
vcShader_Bind(nullptr);
#if VISUALIZE_DEBUG_TILES
printf("touched=%d, visible=%d, rendered=%d, leaves=%d\n", pTileRenderer->quadTree.metaData.nodeTouchedCount, pTileRenderer->quadTree.metaData.visibleNodeCount, pTileRenderer->quadTree.metaData.nodeRenderCount, pTileRenderer->quadTree.metaData.leafNodeCount);
#endif
}
void vcTileRenderer_ClearTiles(vcTileRenderer *pTileRenderer)
{
udLockMutex(pTileRenderer->cache.pMutex);
pTileRenderer->pTransparentTiles->clear();
pTileRenderer->cache.tileLoadList.Clear();
vcQuadTree_Reset(&pTileRenderer->quadTree);
udReleaseMutex(pTileRenderer->cache.pMutex);
}
| 35.925599 | 303 | 0.725368 | [
"render",
"vector"
] |
ff8046d2ccf6045e17c724329b67d93aeb0a4c76 | 1,592 | cpp | C++ | src/third_party/skia/docs/examples/Surface_MakeRenderTarget_2.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 54 | 2016-04-05T17:45:19.000Z | 2022-01-31T06:27:33.000Z | src/third_party/skia/docs/examples/Surface_MakeRenderTarget_2.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 25 | 2016-03-18T04:01:06.000Z | 2020-06-27T15:39:35.000Z | src/third_party/skia/docs/examples/Surface_MakeRenderTarget_2.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 50 | 2016-03-03T20:31:58.000Z | 2022-03-31T18:26:13.000Z | // Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
// HASH=640321e8ecfb3f9329f3bc6e1f02485f
REG_FIDDLE(Surface_MakeRenderTarget_2, 256, 256, false, 0) {
void draw(SkCanvas* canvas) {
auto test_draw = [](SkCanvas* surfaceCanvas) -> void {
SkFont font(nullptr, 32);
SkPaint paint;
paint.setAntiAlias(true);
// TODO: where did this setting go?
//paint.setLCDRenderText(true);
paint.setColor(0xFFBBBBBB);
surfaceCanvas->drawRect(SkRect::MakeWH(128, 64), paint);
paint.setColor(SK_ColorWHITE);
surfaceCanvas->drawString("Text", 0, 25, font, paint);
};
auto context = canvas->recordingContext();
SkImageInfo info = SkImageInfo::MakeN32(128, 64, kOpaque_SkAlphaType);
int y = 0;
for (auto geometry : { kRGB_H_SkPixelGeometry, kBGR_H_SkPixelGeometry,
kRGB_V_SkPixelGeometry, kBGR_V_SkPixelGeometry } ) {
SkSurfaceProps props(0, geometry);
sk_sp<SkSurface> surface = context
? SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, 0, &props)
: SkSurface::MakeRaster(info, &props);
test_draw(surface->getCanvas());
surface->draw(canvas, 0, y, nullptr);
sk_sp<SkImage> image(surface->makeImageSnapshot());
SkAutoCanvasRestore acr(canvas, true);
canvas->scale(8, 8);
canvas->drawImage(image, 12, y / 8);
y += 64;
}
}
} // END FIDDLE
| 40.820513 | 100 | 0.636307 | [
"geometry"
] |
ff80532c8101da141641bb73e83dc1a2f16e88a7 | 8,545 | cpp | C++ | Samples/VoronoiDiragram/SimpleVoronoi2dSimulation.cpp | kasunindikaliyanage/Jyamithika | ae558f2ea1f784fd54f82f507969ad46b62defd5 | [
"MIT"
] | 7 | 2021-11-11T14:57:36.000Z | 2022-03-22T21:53:32.000Z | Samples/VoronoiDiragram/SimpleVoronoi2dSimulation.cpp | kasunindikaliyanage/Jyamithika | ae558f2ea1f784fd54f82f507969ad46b62defd5 | [
"MIT"
] | null | null | null | Samples/VoronoiDiragram/SimpleVoronoi2dSimulation.cpp | kasunindikaliyanage/Jyamithika | ae558f2ea1f784fd54f82f507969ad46b62defd5 | [
"MIT"
] | 6 | 2021-11-24T05:20:04.000Z | 2022-02-27T15:12:34.000Z | #include "glad\glad.h"
#include <GLFW\glfw3.h>
#include <array>
#include "GLM\glm.hpp"
#include "GLM\gtc\matrix_transform.hpp"
#include "GLM\gtc\type_ptr.hpp"
#include "GraphicUtils\Imgui\imgui.h"
#include "GraphicUtils\Imgui\imgui_impl_glfw.h"
#include "GraphicUtils\Imgui\imgui_impl_opengl3.h"
#include "GraphicUtils\ShaderProgram.h"
#include "GraphicUtils\VertexArray.h"
#include "GraphicUtils\VertexBuffer.h"
#include "GraphicUtils\GraphicUtils.h"
#include "GraphicUtils\Geometry\GFace.h"
#include "GraphicUtils\Geometry\GPoint.h"
#include "GraphicUtils\Geometry\GLine.h"
#include "Jyamithika\Core\Primitives\Point.h"
#include "Jyamithika\Core\Primitives\Bounds.h"
#include "Jyamithika\Voronoi.h"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
using std::chrono::duration;
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::milli;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void processInput(GLFWwindow* window);
const unsigned int SCREEN_WIDTH = 900;
const unsigned int SCREEN_HEIGHT = 900;
bool firstMouse = true;
float lastX = SCREEN_WIDTH / 2.0f;
float lastY = SCREEN_HEIGHT / 2.0f;
int option = 0;
//Camera camera(glm::vec3(0.0f, 0.0f, 12.0f), glm::vec3(0.0f, 1.0f, 0.0f), -90.0f, 0.0f);
// timing
float deltaTime = 0.0f; // time between current frame and last frame
float lastFrame = 0.0f;
void setup_pointcloud(std::vector<jmk::Point2d>& points)
{
std::vector<float> x_values;
std::vector<float> y_values;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
for (float i = 1; i < 99; i++)
x_values.push_back((i - 49)/50);
std::shuffle(x_values.begin(), x_values.end(), std::default_random_engine(seed));
y_values = x_values;
std::shuffle(y_values.begin(), y_values.end(), std::default_random_engine(seed));
for(int i=0; i< x_values.size(); i++)
points.push_back(jmk::Point2d(x_values[i], y_values[i]));
std::sort(points.begin(), points.end(), jmk::sort2DLRTB);
std::unique(points.begin(), points.end());
}
int main(void)
{
std::srand(std::time(nullptr));
GLFWwindow* window;
//Set up glfw context and window
{
/* Initialize the library */
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Voronoi 2d Simulation", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
}
//Set up ImGui
{
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer bindings
ImGui_ImplOpenGL3_Init("#version 130");
ImGui_ImplGlfw_InitForOpenGL(window, true);
}
std::vector<jmk::Point2d> points;
std::vector<float> point_data;
std::vector<jmk::Edge2dSimple> edges;
std::vector<float> edge_data;
std::vector<float> face_edge_data;
setup_pointcloud(points);
getReactanglePointClouds(points, point_data);
jmk::BoundRectangle rect{ -1.0,1.0,1.0,-1.0 };
auto startTime = high_resolution_clock::now();
jmk::constructVoronoiDiagram_fortunes(points, edges, rect);
auto endTime = high_resolution_clock::now();
std::chrono::duration<double> diff = endTime - startTime;
std::cout << "Voronoi Diagram 2d construction time - " << diff.count() << std::endl;
get2DLinePointsFromEdgeList(edges, edge_data);
get2DLinePointsFromFaceEdgeList(edges, face_edge_data);
VertexArray VAO_points;
VertexBuffer VBO_points(point_data.data(), point_data.size());
VAO_points.addVertexLayout(0, 2, GL_FALSE, 2 * sizeof(float), 0);
VertexArray VAO_edges;
VertexBuffer VBO_edge(edge_data.data(), edge_data.size());
VAO_edges.addVertexLayout(0, 2, GL_FALSE, 2 * sizeof(float), 0);
VertexArray VAO_face_edges;
VertexBuffer VBO_face_edge(face_edge_data.data(), face_edge_data.size());
VAO_face_edges.addVertexLayout(0, 2, GL_FALSE, 2 * sizeof(float), 0);
// TODO no need for multiple shaders. Just use uniforms. Currently we need to switch the shaders which adds
// lots for overhead
ShaderProgram shader("C:/Users/intellect/source/repos/Jyamithika/Graphics/GraphicUtils/Shaders/triangle2d.shader");
ShaderProgram line_shader("C:/Users/intellect/source/repos/Jyamithika/Graphics/GraphicUtils/Shaders/line.shader");
ShaderProgram line2_shader("C:/Users/intellect/source/repos/Jyamithika/Graphics/GraphicUtils/Shaders/line2.shader");
bool show_points = true, show_voronoi = false, show_delanuay = false;
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
// per-frame time logic
// --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
processInput(window);
/* Render here */
glClearColor(0.05f, 0.05f, 0.05f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (show_points)
{
shader.activeAsCurrentShader();
VAO_points.bindVertexArray();
glDrawArrays(GL_TRIANGLES, 0, point_data.size() / 2);
}
if (show_voronoi)
{
line_shader.activeAsCurrentShader();
VAO_edges.bindVertexArray();
glLineWidth(2);
glDrawArrays(GL_LINES, 0, edge_data.size() / 2);
}
if (show_delanuay)
{
line2_shader.activeAsCurrentShader();
VAO_face_edges.bindVertexArray();
glLineWidth(0.5);
glDrawArrays(GL_LINES, 0, face_edge_data.size() / 2);
}
ImGui::Begin(" Sample : Voronoi Diagram and Delaunay triangulation in 2d");
ImGui::Checkbox("Points", &show_points);
ImGui::Checkbox("Voronoi", &show_voronoi);
ImGui::Checkbox("Delaunay", &show_delanuay);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS)
{
option = 1;
}
else if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS)
{
option = 2;
}
else if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS)
{
option = 3;
}
else
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
}
// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
return;
if (firstMouse)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
//camera.ProcessMouseMovement(xoffset, yoffset, true);
}
// glfw: whenever the mouse scroll wheel scrolls, this callback is called
// ----------------------------------------------------------------------
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
//camera.ProcessMouseScroll(yoffset);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
} | 29.364261 | 124 | 0.703101 | [
"geometry",
"render",
"vector"
] |
ff80baed30568f5d08468a635a0935d23eb90216 | 1,916 | cpp | C++ | source/unittest/jsonwritter.cpp | kracejic/krlib | 346eed72d17892d4fec7e987d46545406c8f12dd | [
"MIT"
] | 2 | 2016-11-10T07:26:34.000Z | 2018-09-30T00:39:46.000Z | source/unittest/jsonwritter.cpp | kracejic/krlib | 346eed72d17892d4fec7e987d46545406c8f12dd | [
"MIT"
] | null | null | null | source/unittest/jsonwritter.cpp | kracejic/krlib | 346eed72d17892d4fec7e987d46545406c8f12dd | [
"MIT"
] | null | null | null | #include "kr/JsonWritter.h"
#include "catch.hpp"
#include "kr/logger.h"
TEST_CASE("JsonWritterTo")
{
std::string t;
kr::Json::WritterTo js(t);
js.startObject();
js.put("test", "test");
js.endObject();
REQUIRE(t == R"({"test":"test"})");
}
TEST_CASE("JsonWritter")
{
kr::Json::Writter js;
js.startArray();
js.endArray();
REQUIRE(js.get() == "[]");
js.startObject();
js.endObject();
REQUIRE(js.get() == "[],{}");
js.startObject("test1");
js.endObject();
REQUIRE(js.get() == "[],{},\"test1\":{}");
js.startArray("test2");
js.endArray();
REQUIRE(js.get() == "[],{},\"test1\":{},\"test2\":[]");
std::string a = js.moveText();
REQUIRE(js.get() == "");
js.put("xxx");
js.put("xxx2");
REQUIRE(js.get() == R"("xxx","xxx2")");
js.clear();
REQUIRE(js.get() == "");
std::string x = "xxx";
js.put(x);
REQUIRE(js.get() == R"("xxx")");
js.put("x", x);
REQUIRE(js.get() == R"("xxx","x":"xxx")");
}
TEST_CASE("JsonWritter complex object")
{
kr::Json::Writter js;
js.startObject();
js.startObject("data");
js.startArray("array");
js.put(true);
js.put(1);
js.put(false);
js.put("ttt");
js.put(1.5f);
js.put(2.5);
js.endArray();
js.put("obj", true);
js.put("val", "val2");
js.put("val", nullptr);
js.endObject();
js.endObject();
REQUIRE(
js.get() ==
R"({"data":{"array":[true,1,false,"ttt",1.500000,2.500000],"obj":true,"val":"val2","val":null}})");
js.clear();
REQUIRE(js.get() == "");
}
TEST_CASE("JsonWritter escaping")
{
REQUIRE(kr::Json::escape("\ntest\"") == R"(\ntest\")");
REQUIRE(kr::Json::escape("\"\"\"\"") == R"(\"\"\"\")");
REQUIRE(kr::Json::escape("\\") == R"(\\)");
REQUIRE(kr::Json::escape("\\a") == R"(\\a)");
REQUIRE(kr::Json::escape("\"\"\\\"\"") == R"(\"\"\\\"\")");
}
| 22.809524 | 107 | 0.495303 | [
"object"
] |
ff82c40f99a4eddbb4bd0d86093315464c2c9a04 | 27,267 | cpp | C++ | kehnetwork/snapshotdata.cpp | Kehom/GodotModulePack | 9f2bbcdeb00bc577598680a22601be79220c5352 | [
"MIT"
] | 4 | 2021-03-12T12:40:01.000Z | 2022-03-09T02:41:39.000Z | kehnetwork/snapshotdata.cpp | baiduwen3/GodotModulePack | 9f2bbcdeb00bc577598680a22601be79220c5352 | [
"MIT"
] | null | null | null | kehnetwork/snapshotdata.cpp | baiduwen3/GodotModulePack | 9f2bbcdeb00bc577598680a22601be79220c5352 | [
"MIT"
] | 1 | 2022-03-09T02:42:07.000Z | 2022-03-09T02:42:07.000Z | /**
* Copyright (c) 2021 Yuri Sarudiansky
*
* 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 "snapshotdata.h"
#include "snapshot.h"
#include "entityinfo.h"
#include "snapentity.h"
#include "nodespawner.h"
#include "../kehgeneral/encdecbuffer.h"
#include "scene/main/node.h"
#include "core/project_settings.h"
#include "core/io/resource_loader.h"
void kehSnapshotData::register_entity_types()
{
ProjectSettings* psettings = ProjectSettings::get_singleton();
Array clist;
if (psettings->has_setting("_global_script_classes"))
{
clist = psettings->get("_global_script_classes");
}
const bool pdebug = GLOBAL_GET("keh_modules/network/general/print_debug_info");
for (int i = 0; i < clist.size() ; i++)
{
Dictionary entry = clist[i];
if (entry.has("base") && entry["base"] == "kehSnapEntityBase")
{
String cname(entry["class"]);
String rpath(entry["path"]);
// EntityInfo is a typedef, Ref<kehEntityInfo>
EntityInfo info = memnew(kehEntityInfo);
String err = info->check(cname, rpath);
if (err.empty())
{
if (pdebug)
{
print_line(vformat("Registering snapshot object type '%s' with hash %d", cname, info->get_name_hash()));
}
// The actual registration
m_entity_info[info->get_name_hash()] = info;
// This will help obtain the necessary data given the class' resource
m_entity_name[info->get_resource()] = ResInfo(cname, info->get_name_hash());
}
else
{
WARN_PRINTS(vformat("Skipping registration of class '%s' (%d). Reason: %s", cname, info->get_name_hash(), err))
}
}
}
}
void kehSnapshotData::get_entity_types(PoolVector<uint32_t>& out_keys) const
{
for (const Map<uint32_t, EntityInfo>::Element* e = m_entity_info.front(); e; e = e->next())
{
out_keys.append(e->key());
}
}
void kehSnapshotData::register_spawner(const Ref<Script>& eclass, uint32_t chash, const Ref<kehNetNodeSpawner>& spawner, Node* parent, const Ref<FuncRef>& esetup)
{
if (esetup.is_valid())
{
ERR_FAIL_COND_MSG(!esetup->is_valid(), "Registering a Node spawner, an extra setup FuncRef was given but it's invalid.");
}
const Map<Ref<Script>, ResInfo>::Element* ename = m_entity_name.find(eclass);
ERR_FAIL_COND_MSG(!ename, vformat("Trying to register spawner associated with snapshot entity class defined in '%s', which is not registered.", eclass->get_path()));
Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ename->value().hash);
einfo->value()->register_spawner(chash, spawner, parent, esetup);
}
Node* kehSnapshotData::spawn_node(const Ref<Script>& eclass, uint32_t uid, uint32_t chash)
{
Node* ret = NULL;
const Map<Ref<Script>, ResInfo>::Element* ename = m_entity_name.find(eclass);
if (ename)
{
Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ename->value().hash);
ret = einfo->value()->spawn_node(uid, chash);
}
return ret;
}
Node* kehSnapshotData::get_game_node(uint32_t uid, const Ref<Script>& eclass) const
{
Node* ret = NULL;
const Map<Ref<Script>, ResInfo>::Element* ename = m_entity_name.find(eclass);
if (ename)
{
const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ename->value().hash);
ret = einfo->value()->get_game_node(uid);
}
return ret;
}
uint32_t kehSnapshotData::get_prediction_count(uint32_t uid, const Ref<Script>& eclass) const
{
uint32_t ret = 0;
const Map<Ref<Script>, ResInfo>::Element* ename = m_entity_name.find(eclass);
if (ename)
{
const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ename->value().hash);
ret = einfo->value()->get_pred_count(uid);
}
return ret;
}
void kehSnapshotData::despawn_node(const Ref<Script>& eclass, uint32_t uid)
{
const Map<Ref<Script>, ResInfo>::Element* ename = m_entity_name.find(eclass);
if (ename)
{
Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ename->value().hash);
einfo->value()->despawn_node(uid);
}
}
void kehSnapshotData::add_pre_spawned_node(const Ref<Script>& eclass, uint32_t uid, Node* node)
{
const Map<Ref<Script>, ResInfo>::Element* ename = m_entity_name.find(eclass);
if (ename)
{
Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ename->value().hash);
einfo->value()->add_pre_spawned(uid, node);
}
}
void kehSnapshotData::add_to_history(const Ref<kehSnapshot>& snapshot)
{
m_history.push_back(snapshot);
m_ssig_to_snap[snapshot->get_signature()] = snapshot;
m_isig_to_snap[snapshot->get_input_sig()] = snapshot;
}
void kehSnapshotData::check_history_size(uint32_t maxsize, bool has_authority)
{
int32_t popped = 0;
while (m_history.size() > maxsize)
{
m_ssig_to_snap.erase(m_history[0]->get_signature());
m_isig_to_snap.erase(m_history[0]->get_input_sig());
m_history.remove(0);
popped++;
}
if (has_authority)
{
update_prediction_count(1 - popped);
}
}
Ref<kehSnapshot> kehSnapshotData::get_snapshot(uint32_t signature) const
{
const Map<uint32_t, Ref<kehSnapshot>>::Element* e = m_ssig_to_snap.find(signature);
return (e ? e->value() : NULL);
}
Ref<kehSnapshot> kehSnapshotData::get_snapshot_by_input(uint32_t isig) const
{
const Map<uint32_t, Ref<kehSnapshot>>::Element* e = m_isig_to_snap.find(isig);
return (e ? e->value() : NULL);
}
void kehSnapshotData::reset()
{
for (Map<uint32_t, EntityInfo>::Element* e = m_entity_info.front(); e; e = e->next())
{
e->value()->clear_nodes();
}
m_server_state = Ref<kehSnapshot>(NULL);
m_history.resize(0);
m_ssig_to_snap.clear();
m_isig_to_snap.clear();
}
void kehSnapshotData::client_check_snapshot(const Ref<kehSnapshot>& snapshot)
{
// This function is meant to be run on clients but not called remotely. The objective here is to take the
// provided snapshot, which contains server data, locate the internal corresponding snapshot and chompare them.
// Any differences are to be considered as errors in the client's prediction and must be corrected using
// the server data (the incoming snapshot object).
// Corresponding snapshot means, primarily, the snapshot with the same input signatures. However, it's
// possible the server will send snapshot without any client's input. This will always be the case at the
// very beginning of the client's session, when there is not server data to initiate the local simulation.
// Still, if there is enough data loss, during the synchronization then the server will have to send snapshot
// data without any client's input.
// That said, the overall tasks here:
// - Snapshot contains input -> locate the snapshot in the history with the same signature and use that one to
// compare, removing any older (or equal) from the history.
// - Snapshot does not contain input -> take the last snapshot in the history to use for comparison and don't
// remove anything from the history.
// During the comparison, any difference must be corrected by applying the server state into all snapshots in
// the local snapshot history container.
// On errors the ideal is to locally re-simulate the game using cached input data just so no input is missed
// on small errors. Since this is not possible with Godot in a generic way then just apply the corrected
// state into the corresponding nodes and hope the interpolation will make things look "less glitchy".
Ref<kehSnapshot> local;
int32_t popcount = 0;
const uint32_t isig = snapshot->get_input_sig();
if (isig > 0)
{
Ref<kehSnapshot> finding_snap;
while (m_history.size() > 0 && m_history[0]->get_input_sig() <= isig)
{
finding_snap = m_history[0];
m_ssig_to_snap.erase(finding_snap->get_signature());
m_isig_to_snap.erase(finding_snap->get_input_sig());
m_history.remove(0);
popcount++;
}
if (finding_snap.is_valid())
{
if (finding_snap->get_input_sig() != isig)
{
// This should not occur
update_prediction_count(-popcount);
return;
}
local = finding_snap;
}
}
else
{
if (m_history.size() > 0)
{
local = m_history[m_history.size() - 1];
}
}
if (!local.is_valid())
{
update_prediction_count(-popcount);
// This should not occur...
return;
}
m_server_state = snapshot;
for (Map<uint32_t, EntityInfo>::Element* ehash = m_entity_info.front(); ehash; ehash = ehash->next())
{
EntityInfo einfo = ehash->value();
// TODO: Remove this from release builds, keeping only on debug/editor builds.
ERR_FAIL_COND_MSG(!local->has_type(ehash->key()) || !snapshot->has_type(ehash->key()), "Entity type must exist on both ends.");
// Obtain list of entities in the local snapshot. This will be used to track ones that are locally
// present but not in the server data.
Set<uint32_t> local_entity;
local->get_entity_uids(ehash->key(), local_entity);
// Iterate through entities of the server snapshot
const kehSnapshot::entity_data_t::Element* ecol = snapshot->get_entity_collection(ehash->key());
for (uint32_t i = 0; i < ecol->value().entity_array.size(); i++)
{
Ref<kehSnapEntityBase> rentity = ecol->value().entity_array[i];
Ref<kehSnapEntityBase> lentity = local->get_entity(ehash->key(), rentity->get_uid());
Node* node = NULL;
if (rentity.is_valid() && lentity.is_valid())
{
// Entity exists on both ends. First update the local entity array because it's meant to
// hold entities that are present only in the local machine (client)
local_entity.erase(rentity->get_uid());
// Check if there is any difference
const uint32_t cmask = einfo->calculate_change_mask(rentity, lentity);
if (cmask > 0)
{
// There is at least one property with different values. This means it must be corrected.
// For now just obtain the corresponding node. At the end of this function if the variable
// is valid the apply_state() will be called.
node = einfo->get_game_node(rentity->get_uid());
}
}
else
{
// Entity exists only on the server data. If necessary spawn the game node.
Node* n = einfo->get_game_node(rentity->get_uid());
if (!n)
{
node = einfo->spawn_node(rentity->get_uid(), rentity->get_class_hash());
}
}
if (node)
{
// If here then it's necessary to apply the server state into the node
rentity->call("apply_state", node);
// Propagate the new data into every snapshot in the local history.
for (uint32_t i = 0; i < m_history.size(); i++)
{
m_history[i]->add_entity(ehash->key(), einfo->clone_entity(rentity));
}
}
}
// Check entities that are in the local snapshot but not in the remote (server) one.
// The local ones must be removed from the game
for (Set<uint32_t>::Element* e = local_entity.front(); e; e = e->next())
{
despawn_node(einfo->get_resource(), e->get());
}
}
// All entities have been verified. Update the prediction count
update_prediction_count(-popcount);
}
void kehSnapshotData::encode_full(const Ref<kehSnapshot>& snapshot, Ref<kehEncDecBuffer>& into, uint32_t input_sig) const
{
// Encode the signature of the snapshot
into->write_uint(snapshot->get_signature());
// Encode input signature
into->write_uint(input_sig);
for (const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.front(); einfo; einfo = einfo->next())
{
const kehSnapshot::entity_data_t::Element* ecol = snapshot->get_entity_collection(einfo->key());
if (!ecol)
{
// This should not happen. However, should this error out?
return;
}
// Obtain entity count. Don't encode anything for this type if count is 0.
const uint32_t ecount = ecol->value().entity_array.size();
if (ecount == 0)
continue;
// Ok, there is at least one entity in the snapshot. Encode the type hash ID
into->write_uint(einfo->key());
// Then the entity count
into->write_uint(ecount);
// Now iterate through all entities within the array
for (uint32_t i = 0; i < ecount; i++)
{
einfo->value()->encode_full_entity(ecol->value().entity_array[i], into);
}
}
}
Ref<kehSnapshot> kehSnapshotData::decode_full(Ref<kehEncDecBuffer> from) const
{
// Decode the signature of the snapshot
const uint32_t sig = from->read_uint();
// Decode input signature
const uint32_t isig = from->read_uint();
if (isig > 0 && m_history.size() > 0 && isig < m_history[0]->get_input_sig())
{
// The input signature of the incoming data is older than the oldest snapshot within local history.
// Because of that, ignore the received snapshot
return NULL;
}
Ref<kehSnapshot> ret = memnew(kehSnapshot(sig, isig));
// The snapshot checking algorithm requires that each entity type has its entry within the snapshot data.
for (const Map<uint32_t, EntityInfo>::Element* e = m_entity_info.front(); e; e = e->next())
{
ret->add_type(e->key());
}
while (from->has_read_data())
{
// Read the entity type ID
const uint32_t ehash = from->read_uint();
const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ehash);
if (!einfo)
{
// FIXME: put an error message
return NULL;
}
// Take number of entities of this type
const uint32_t count = from->read_uint();
// Decode the entities of this type
for (uint32_t i = 0; i < count; i++)
{
Ref<kehSnapEntityBase> entity = einfo->value()->decode_full_entity(from);
if (entity.is_valid())
{
ret->add_entity(ehash, entity);
}
}
}
return ret;
}
void kehSnapshotData::encode_delta(const Ref<kehSnapshot>& snap, const Ref<kehSnapshot>& oldsnap, Ref<kehEncDecBuffer>& into, uint32_t isig) const
{
// Scan oldsnap comparing to snap. Encode only the changes. Removed entities must be explicitly marked
// with a changed mask = 0.
// Scanning will iterate through entities in the snap object. The same entity will be retrieved from oldsnap.
// If not found then assume iterate entity is new. A list must be used to keep track of entities that are in
// the older snapshot but not in the newer one, indicating removed game objects.
// Write snapshot signature
into->write_uint(snap->get_signature());
// Then the input signature
into->write_uint(isig);
// Encode a flag indicating if there is any change at all in this snapshot. Assume there isn't
into->write_bool(false);
// But not for the actual flag here. It's easier to change this to true
bool has_data = false;
// During entity scanning, entries from this container will be removed. After the loop any remaining
// entries are entities removed from the game
Map<uint32_t, Set<uint32_t>> tracker;
oldsnap->build_tracker(tracker);
// Iterate through valid entity types
for (const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.front(); einfo; einfo = einfo->next())
{
// Obtain easy access to the entity collections
const kehSnapshot::entity_data_t::Element* necol = snap->get_entity_collection(einfo->key());
const kehSnapshot::entity_data_t::Element* oecol = oldsnap->get_entity_collection(einfo->key());
// Get entity count in the recent snapshot
const uint32_t necount = necol->value().entity_array.size();
// Get entity count in the old snapshot
const uint32_t oecount = oecol->value().entity_array.size();
// Skip this entity type if both quantities are 0
if (necount == 0 && oecount == 0)
continue;
// At least one of the snapshots contains entities of this type. Assume every single one has been changed
uint32_t ccount = necount;
// Postponing encoding of type has and change count to a moment where it is sure there is at least one
// changed entity of this type. Originally tried to do things normally and remove the relevant bytes from
// the buffer array but it didn't work very well.
// This flag is used to tell if the type hash and change count have been encded or not, just to prevent
// multiple encodings of this data
bool written_type_header = false;
// Get writing position of the entity count as most likely it will be updated (rewritten)
const uint32_t countpos = into->get_current_size() + 4;
// Iterate through the entities of this type.
for (uint32_t i = 0; i < necount; i++)
{
// Retrieve the new state of the entity.
Ref<kehSnapEntityBase> enew = necol->value().entity_array[i];
// Retrieve the old state of the entity - obviously if it exists.
const Map<uint32_t, Ref<kehSnapEntityBase>>::Element* eoldit = oecol->value().uid_to_entity.find(enew->get_uid());
Ref<kehSnapEntityBase> eold = eoldit ? eoldit->value() : NULL;
// Assume the entity is new
uint32_t cmask = einfo->value()->get_full_change_mask();
if (enew.is_valid() && eold.is_valid())
{
// The entity exist on both snapshots so it's not new. Calculate the "real" change mask.
cmask = einfo->value()->calculate_change_mask(eold, enew);
// Remove this from the tracker so it isn't considered as a removed entity
tracker[einfo->key()].erase(enew->get_uid());
}
if (cmask != 0)
{
if (!written_type_header)
{
// Write the entity type hash ID
into->write_uint(einfo->key());
// Write the change counter
into->write_uint(ccount);
// Prevent rewriting of this information
written_type_header = true;
}
// This entity requires encoding. Do so
einfo->value()->encode_delta_entity(enew->get_uid(), enew, cmask, into);
has_data = true;
}
else
{
// The entity was not changed. Update the change counter
ccount--;
}
}
// Check th tracker for entities that are in the old snapshot but not in the new one.
// In other words, entities that were removed from the game world.
// Those must be encoded with a change mask set to 0, which will indicate "remove entities"
// when decoding the data.
for (Set<uint32_t>::Element* uid = tracker[einfo->key()].front(); uid; uid = uid->next())
{
if (!written_type_header)
{
into->write_uint(einfo->key());
into->write_uint(ccount);
written_type_header = true;
}
einfo->value()->encode_delta_entity(uid->get(), NULL, 0, into);
ccount++;
}
if (ccount > 0)
{
into->rewrite_uint(ccount, countpos);
}
}
// Everything iterated through. Check if there is anything encoded at all
if (has_data)
into->rewrite_bool(true, 8);
}
Ref<kehSnapshot> kehSnapshotData::decode_delta(Ref<kehEncDecBuffer>& from) const
{
// Decode snapshot signature
const uint32_t snapsig = from->read_uint();
// Input signature
const uint32_t isig = from->read_uint();
if (isig > 0 && m_history.size() > 0 && isig < m_history[0]->get_input_sig())
{
// The input signature of the incoming data is older than the oldest snapshot within local history.
// Because of that, ignore the received snapshot
return NULL;
}
Ref<kehSnapshot> ret = memnew(kehSnapshot(snapsig, isig));
// The snapshot checking algorithm requires that each entity type has its entry within the snapshot data.
for (const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.front(); einfo; einfo = einfo->next())
{
ret->add_type(einfo->key());
}
// Read the "has_data" flag
const bool has_data = from->read_bool();
// This will be used to track unchanged entities. Basically, when an entity is decoded the corresponding
// entry will be removed from this data. After that, remaining entries here are indicating entities that
// didn't change and must be copied from m_server_state into the new snapshot.
Map<uint32_t, Set<uint32_t>> tracker;
m_server_state->build_tracker(tracker);
if (has_data)
{
while (from->has_read_data())
{
const uint32_t ehash = from->read_uint();
const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ehash);
if (!einfo)
{
print_error(vformat("While decoding delta snapshot data, got an entity type hash %d which doesn't map to any valid registered entity type.", ehash));
return NULL;
}
// Take number of encoded entities of this type
const uint32_t count = from->read_uint();
// Decode those entities
for (uint32_t i = 0; i < count; i++)
{
uint32_t cmask = 0;
Ref<kehSnapEntityBase> nent = einfo->value()->decode_delta_entity(from, cmask);
Ref<kehSnapEntityBase> oldent = m_server_state->get_entity(ehash, nent->get_uid());
if (oldent.is_valid())
{
// The entity exists in the old state. Check if it's not marked for removal
if (cmask > 0)
{
// It isn't so "match" the delta to make the data correct (that is, take unchanged)
// data from the old state and apply into the new one.
einfo->value()->match_delta(nent, oldent, cmask);
// Add the changed entity into the decoded snapshot
ret->add_entity(ehash, nent);
}
// This is a changed entity so remove it from the tracker
tracker[ehash].erase(nent->get_uid());
}
else
{
// Entity is not in the old state. Add the decoded data into the return value in the hopes
// it is holding the entire correct data (this can be checked by comparing the cmask through).
// Change mask can be 0 in this case, when the acknowledgement still didn't arrive there, when
// server dispatched a new data set.
if (cmask > 0)
{
ret->add_entity(ehash, nent);
}
}
}
}
}
// Check the tracker
for (Map<uint32_t, Set<uint32_t>>::Element* ehash = tracker.front(); ehash; ehash = ehash->next())
{
const Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.find(ehash->key());
for (Set<uint32_t>::Element* uid = ehash->value().front(); uid; uid = uid->next())
{
Ref<kehSnapEntityBase> entity = m_server_state->get_entity(ehash->key(), uid->get());
ret->add_entity(ehash->key(), einfo->value()->clone_entity(entity));
}
}
return ret;
}
uint32_t kehSnapshotData::get_ehash(const Ref<Script>& script) const
{
uint32_t ret = 0;
const Map<Ref<Script>, ResInfo>::Element* e = m_entity_name.find(script);
if (e)
{
ret = e->value().hash;
}
else
{
// TODO: print warning indicating that it was not possible to retrieve required data based on its script.
}
return ret;
}
Ref<kehSnapEntityBase> kehSnapshotData::instantiate_snap_entity(const Ref<Script>& snap_entity, uint32_t uid, uint32_t chash) const
{
Ref<kehSnapEntityBase> ret;
const Map<Ref<Script>, ResInfo>::Element* e = m_entity_name.find(snap_entity);
if (e)
{
EntityInfo einfo = m_entity_info[e->value().hash];
ret = einfo->create_instance(uid, chash);
}
return ret;
}
String kehSnapshotData::get_comparer_data(const Ref<Script>& eclass) const
{
const Map<Ref<Script>, ResInfo>::Element* e = m_entity_name.find(eclass);
if (e)
{
EntityInfo einfo = m_entity_info[e->value().hash];
return einfo->get_comp_data();
}
// TODO: make this a message to make it clear that the specified script is not registered.
return "";
}
void kehSnapshotData::update_prediction_count(int32_t delta)
{
for (Map<uint32_t, EntityInfo>::Element* einfo = m_entity_info.front(); einfo; einfo = einfo->next())
{
einfo->value()->update_pred_count(delta);
}
}
void kehSnapshotData::_notification(int what)
{
switch (what)
{
case NOTIFICATION_PREDELETE:
{
m_entity_info.clear();
kehPropComparer::cleanup();
}
}
}
void kehSnapshotData::_bind_methods()
{
ClassDB::bind_method(D_METHOD("register_spawner", "eclass", "chash", "spawner", "parent", "esetup"), &kehSnapshotData::register_spawner);
ClassDB::bind_method(D_METHOD("spawn_node", "eclass", "uid", "chash"), &kehSnapshotData::spawn_node);
ClassDB::bind_method(D_METHOD("get_game_node", "uid", "eclass"), &kehSnapshotData::get_game_node);
ClassDB::bind_method(D_METHOD("get_prediction_count", "uid", "eclass"), &kehSnapshotData::get_prediction_count);
ClassDB::bind_method(D_METHOD("despawn_node", "eclass", "uid"), &kehSnapshotData::despawn_node);
ClassDB::bind_method(D_METHOD("add_pre_spawned_node", "eclass", "uid", "node"), &kehSnapshotData::add_pre_spawned_node);
ClassDB::bind_method(D_METHOD("get_comparer_data", "eclass"), &kehSnapshotData::get_comparer_data);
}
kehSnapshotData::kehSnapshotData()
{
register_entity_types();
}
kehSnapshotData::~kehSnapshotData()
{
}
| 34.912932 | 168 | 0.647779 | [
"object"
] |
ff866b0c7d07531142c7ac7c894736f7b7407beb | 3,859 | cpp | C++ | src/xray/xrCDB/xrCDB.cpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/xray/xrCDB/xrCDB.cpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/xray/xrCDB/xrCDB.cpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | // xrCDB.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#pragma hdrstop
#include "xrCDB.h"
using namespace CDB;
using namespace Opcode;
BOOL APIENTRY DllMain( HANDLE hModule,
u32 ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// Model building
MODEL::MODEL ()
#ifdef PROFILE_CRITICAL_SECTIONS
:cs(MUTEX_PROFILE_ID(MODEL))
#endif // PROFILE_CRITICAL_SECTIONS
{
tree = 0;
tris = 0;
tris_count = 0;
verts = 0;
verts_count = 0;
status = S_INIT;
}
MODEL::~MODEL()
{
syncronize (); // maybe model still in building
status = S_INIT;
xr_delete (tree);
xr_free (tris); tris_count = 0;
xr_free (verts); verts_count= 0;
}
struct BTHREAD_params
{
MODEL* M;
Fvector* V;
int Vcnt;
TRI* T;
int Tcnt;
build_callback* BC;
void* BCP;
};
void MODEL::build_thread (void *params)
{
_initialize_cpu_thread ();
FPU::m64r ();
BTHREAD_params P = *( (BTHREAD_params*)params );
P.M->cs.Enter ();
P.M->build_internal (P.V,P.Vcnt,P.T,P.Tcnt,P.BC,P.BCP);
P.M->status = S_READY;
P.M->cs.Leave ();
//Msg ("* xrCDB: cform build completed, memory usage: %d K",P.M->memory()/1024);
}
void MODEL::build (Fvector* V, int Vcnt, TRI* T, int Tcnt, build_callback* bc, void* bcp)
{
R_ASSERT (S_INIT == status);
R_ASSERT ((Vcnt>=4)&&(Tcnt>=2));
_initialize_cpu_thread ();
#ifdef _EDITOR
build_internal (V,Vcnt,T,Tcnt,bc,bcp);
#else
if(!strstr(Core.Params, "-mt_cdb"))
{
build_internal (V,Vcnt,T,Tcnt,bc,bcp);
}else
{
BTHREAD_params P = { this, V, Vcnt, T, Tcnt, bc, bcp };
thread_spawn (build_thread,"CDB-construction",0,&P);
while (S_INIT == status) Sleep (5);
}
#endif
}
void MODEL::build_internal (Fvector* V, int Vcnt, TRI* T, int Tcnt, build_callback* bc, void* bcp)
{
// verts
verts_count = Vcnt;
verts = xr_alloc<Fvector> (verts_count);
CopyMemory (verts,V,verts_count*sizeof(Fvector));
// tris
tris_count = Tcnt;
tris = xr_alloc<TRI> (tris_count);
CopyMemory (tris,T,tris_count*sizeof(TRI));
// callback
if (bc) bc (verts,Vcnt,tris,Tcnt,bcp);
// Release data pointers
status = S_BUILD;
// Allocate temporary "OPCODE" tris + convert tris to 'pointer' form
u32* temp_tris = xr_alloc<u32> (tris_count*3);
if (0==temp_tris) {
xr_free (verts);
xr_free (tris);
return;
}
u32* temp_ptr = temp_tris;
for (int i=0; i<tris_count; i++)
{
*temp_ptr++ = tris[i].verts[0];
*temp_ptr++ = tris[i].verts[1];
*temp_ptr++ = tris[i].verts[2];
}
// Build a non quantized no-leaf tree
OPCODECREATE OPCC;
OPCC.NbTris = tris_count;
OPCC.NbVerts = verts_count;
OPCC.Tris = (unsigned*)temp_tris;
OPCC.Verts = (Point*)verts;
OPCC.Rules = SPLIT_COMPLETE | SPLIT_SPLATTERPOINTS | SPLIT_GEOMCENTER;
OPCC.NoLeaf = true;
OPCC.Quantized = false;
// if (Memory.debug_mode) OPCC.KeepOriginal = true;
tree = xr_new<OPCODE_Model> ();
if (!tree->Build(OPCC)) {
xr_free (verts);
xr_free (tris);
xr_free (temp_tris);
return;
};
// Free temporary tris
xr_free (temp_tris);
return;
}
u32 MODEL::memory ()
{
if (S_BUILD==status) { Msg ("! xrCDB: model still isn't ready"); return 0; }
u32 V = verts_count*sizeof(Fvector);
u32 T = tris_count *sizeof(TRI);
return tree->GetUsedBytes()+V+T+sizeof(*this)+sizeof(*tree);
}
// This is the constructor of a class that has been exported.
// see xrCDB.h for the class definition
COLLIDER::COLLIDER()
{
ray_mode = 0;
box_mode = 0;
frustum_mode = 0;
}
COLLIDER::~COLLIDER()
{
r_free ();
}
RESULT& COLLIDER::r_add ()
{
rd.push_back (RESULT());
return rd.back ();
}
void COLLIDER::r_free ()
{
rd.clear_and_free ();
}
| 21.087432 | 98 | 0.64965 | [
"model"
] |
ff8c673df3f72a51e3340960d618bb2227aeb30f | 24,082 | cpp | C++ | Source/Runtime/Private/Math/Matrix4.cpp | ValtoGameEngines/Blueshift-Engine | 7d913bd85a50774c9eb151dceca02b8d4fe8e096 | [
"Apache-2.0"
] | 1 | 2019-11-15T04:20:25.000Z | 2019-11-15T04:20:25.000Z | Source/Runtime/Private/Math/Matrix4.cpp | iceman201/BlueshiftEngine | 7d913bd85a50774c9eb151dceca02b8d4fe8e096 | [
"Apache-2.0"
] | null | null | null | Source/Runtime/Private/Math/Matrix4.cpp | iceman201/BlueshiftEngine | 7d913bd85a50774c9eb151dceca02b8d4fe8e096 | [
"Apache-2.0"
] | 1 | 2020-06-29T08:05:44.000Z | 2020-06-29T08:05:44.000Z | // Copyright(c) 2017 POLYGONTEK
//
// 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 "Precompiled.h"
#include "Math/Math.h"
BE_NAMESPACE_BEGIN
const Mat4 Mat4::zero(Vec4(0, 0, 0, 0), Vec4(0, 0, 0, 0), Vec4(0, 0, 0, 0), Vec4(0, 0, 0, 0));
const Mat4 Mat4::identity(Vec4(1, 0, 0, 0), Vec4(0, 1, 0, 0), Vec4(0, 0, 1, 0), Vec4(0, 0, 0, 1));
Mat4 &Mat4::operator=(const Mat3x4 &rhs) {
mat[0][0] = rhs[0][0];
mat[0][1] = rhs[0][1];
mat[0][2] = rhs[0][2];
mat[0][3] = rhs[0][3];
mat[1][0] = rhs[1][0];
mat[1][1] = rhs[1][1];
mat[1][2] = rhs[1][2];
mat[1][3] = rhs[1][3];
mat[2][0] = rhs[2][0];
mat[2][1] = rhs[2][1];
mat[2][2] = rhs[2][2];
mat[2][3] = rhs[2][3];
mat[3][0] = 0;
mat[3][1] = 0;
mat[3][2] = 0;
mat[3][3] = 1;
return *this;
}
Mat4 Mat4::operator*(const Mat3x4 &a) const {
Mat4 dst;
dst[0][0] = mat[0][0] * a[0][0] + mat[0][1] * a[1][0] + mat[0][2] * a[2][0];
dst[0][1] = mat[0][0] * a[0][1] + mat[0][1] * a[1][1] + mat[0][2] * a[2][1];
dst[0][2] = mat[0][0] * a[0][2] + mat[0][1] * a[1][2] + mat[0][2] * a[2][2];
dst[0][3] = mat[0][0] * a[0][3] + mat[0][1] * a[1][3] + mat[0][2] * a[2][3] + mat[0][3];
dst[1][0] = mat[1][0] * a[0][0] + mat[1][1] * a[1][0] + mat[1][2] * a[2][0];
dst[1][1] = mat[1][0] * a[0][1] + mat[1][1] * a[1][1] + mat[1][2] * a[2][1];
dst[1][2] = mat[1][0] * a[0][2] + mat[1][1] * a[1][2] + mat[1][2] * a[2][2];
dst[1][3] = mat[1][0] * a[0][3] + mat[1][1] * a[1][3] + mat[1][2] * a[2][3] + mat[1][3];
dst[2][0] = mat[2][0] * a[0][0] + mat[2][1] * a[1][0] + mat[2][2] * a[2][0];
dst[2][1] = mat[2][0] * a[0][1] + mat[2][1] * a[1][1] + mat[2][2] * a[2][1];
dst[2][2] = mat[2][0] * a[0][2] + mat[2][1] * a[1][2] + mat[2][2] * a[2][2];
dst[2][3] = mat[2][0] * a[0][3] + mat[2][1] * a[1][3] + mat[2][2] * a[2][3] + mat[2][3];
dst[3][0] = mat[3][0] * a[0][0] + mat[3][1] * a[1][0] + mat[3][2] * a[2][0];
dst[3][1] = mat[3][0] * a[0][1] + mat[3][1] * a[1][1] + mat[3][2] * a[2][1];
dst[3][2] = mat[3][0] * a[0][2] + mat[3][1] * a[1][2] + mat[3][2] * a[2][2];
dst[3][3] = mat[3][0] * a[0][3] + mat[3][1] * a[1][3] + mat[3][2] * a[2][3] + mat[3][3];
return dst;
}
Mat4 Mat4::TransposedMul(const Mat3x4 &a) const {
Mat4 dst;
dst[0][0] = mat[0][0] * a[0][0] + mat[0][1] * a[0][1] + mat[0][2] * a[0][2] + mat[0][3] * a[0][3];
dst[0][1] = mat[0][0] * a[1][0] + mat[0][1] * a[1][1] + mat[0][2] * a[1][2] + mat[1][3] * a[1][3];
dst[0][2] = mat[0][0] * a[2][0] + mat[0][1] * a[2][1] + mat[0][2] * a[2][2] + mat[2][3] * a[2][3];
dst[0][3] = mat[0][3];
dst[1][0] = mat[1][0] * a[0][0] + mat[1][1] * a[0][1] + mat[1][2] * a[0][2] + mat[1][3] * a[0][3];
dst[1][1] = mat[1][0] * a[1][0] + mat[1][1] * a[1][1] + mat[1][2] * a[1][2] + mat[1][3] * a[1][3];
dst[1][2] = mat[1][0] * a[2][0] + mat[1][1] * a[2][1] + mat[1][2] * a[2][2] + mat[1][3] * a[2][3];
dst[1][3] = mat[1][3];
dst[2][0] = mat[2][0] * a[0][0] + mat[2][1] * a[0][1] + mat[2][2] * a[0][2] + mat[2][3] * a[0][3];
dst[2][1] = mat[2][0] * a[1][0] + mat[2][1] * a[1][1] + mat[2][2] * a[1][2] + mat[2][3] * a[1][3];
dst[2][2] = mat[2][0] * a[2][0] + mat[2][1] * a[2][1] + mat[2][2] * a[2][2] + mat[2][3] * a[2][3];
dst[2][3] = mat[2][3];
dst[3][0] = mat[3][0] * a[0][0] + mat[3][1] * a[0][1] + mat[3][2] * a[0][2] + mat[3][3] * a[0][3];
dst[3][1] = mat[3][0] * a[1][0] + mat[3][1] * a[1][1] + mat[3][2] * a[1][2] + mat[3][3] * a[1][3];
dst[3][2] = mat[3][0] * a[2][0] + mat[3][1] * a[2][1] + mat[3][2] * a[2][2] + mat[3][3] * a[2][3];
dst[3][3] = mat[3][3];
return dst;
}
Mat4 Mat4::Transpose() const {
Mat4 transpose;
for (int i = 0; i < 4; i++ ) {
for (int j = 0; j < 4; j++ ) {
transpose[i][j] = mat[j][i];
}
}
return transpose;
}
Mat4 &Mat4::TransposeSelf() {
float temp;
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < 4; j++) {
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
return *this;
}
float Mat4::Determinant() const {
// 2x2 sub-determinants
float det2_01_01 = mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0];
float det2_01_02 = mat[0][0] * mat[1][2] - mat[0][2] * mat[1][0];
float det2_01_03 = mat[0][0] * mat[1][3] - mat[0][3] * mat[1][0];
float det2_01_12 = mat[0][1] * mat[1][2] - mat[0][2] * mat[1][1];
float det2_01_13 = mat[0][1] * mat[1][3] - mat[0][3] * mat[1][1];
float det2_01_23 = mat[0][2] * mat[1][3] - mat[0][3] * mat[1][2];
// 3x3 sub-determinants
float det3_201_012 = mat[2][0] * det2_01_12 - mat[2][1] * det2_01_02 + mat[2][2] * det2_01_01;
float det3_201_013 = mat[2][0] * det2_01_13 - mat[2][1] * det2_01_03 + mat[2][3] * det2_01_01;
float det3_201_023 = mat[2][0] * det2_01_23 - mat[2][2] * det2_01_03 + mat[2][3] * det2_01_02;
float det3_201_123 = mat[2][1] * det2_01_23 - mat[2][2] * det2_01_13 + mat[2][3] * det2_01_12;
return (- det3_201_123 * mat[3][0] + det3_201_023 * mat[3][1] - det3_201_013 * mat[3][2] + det3_201_012 * mat[3][3]);
}
bool Mat4::InverseSelf() {
#if 1
// 84+4+16 = 104 multiplications
// 1 division
double det, invDet;
// 2x2 sub-determinants required to calculate 4x4 determinant
float det2_01_01 = mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0];
float det2_01_02 = mat[0][0] * mat[1][2] - mat[0][2] * mat[1][0];
float det2_01_03 = mat[0][0] * mat[1][3] - mat[0][3] * mat[1][0];
float det2_01_12 = mat[0][1] * mat[1][2] - mat[0][2] * mat[1][1];
float det2_01_13 = mat[0][1] * mat[1][3] - mat[0][3] * mat[1][1];
float det2_01_23 = mat[0][2] * mat[1][3] - mat[0][3] * mat[1][2];
// 3x3 sub-determinants required to calculate 4x4 determinant
float det3_201_012 = mat[2][0] * det2_01_12 - mat[2][1] * det2_01_02 + mat[2][2] * det2_01_01;
float det3_201_013 = mat[2][0] * det2_01_13 - mat[2][1] * det2_01_03 + mat[2][3] * det2_01_01;
float det3_201_023 = mat[2][0] * det2_01_23 - mat[2][2] * det2_01_03 + mat[2][3] * det2_01_02;
float det3_201_123 = mat[2][1] * det2_01_23 - mat[2][2] * det2_01_13 + mat[2][3] * det2_01_12;
det = (- det3_201_123 * mat[3][0] + det3_201_023 * mat[3][1] - det3_201_013 * mat[3][2] + det3_201_012 * mat[3][3]);
if (Math::Fabs(det) < MATRIX_INVERSE_EPSILON) {
return false;
}
invDet = 1.0f / det;
// remaining 2x2 sub-determinants
float det2_03_01 = mat[0][0] * mat[3][1] - mat[0][1] * mat[3][0];
float det2_03_02 = mat[0][0] * mat[3][2] - mat[0][2] * mat[3][0];
float det2_03_03 = mat[0][0] * mat[3][3] - mat[0][3] * mat[3][0];
float det2_03_12 = mat[0][1] * mat[3][2] - mat[0][2] * mat[3][1];
float det2_03_13 = mat[0][1] * mat[3][3] - mat[0][3] * mat[3][1];
float det2_03_23 = mat[0][2] * mat[3][3] - mat[0][3] * mat[3][2];
float det2_13_01 = mat[1][0] * mat[3][1] - mat[1][1] * mat[3][0];
float det2_13_02 = mat[1][0] * mat[3][2] - mat[1][2] * mat[3][0];
float det2_13_03 = mat[1][0] * mat[3][3] - mat[1][3] * mat[3][0];
float det2_13_12 = mat[1][1] * mat[3][2] - mat[1][2] * mat[3][1];
float det2_13_13 = mat[1][1] * mat[3][3] - mat[1][3] * mat[3][1];
float det2_13_23 = mat[1][2] * mat[3][3] - mat[1][3] * mat[3][2];
// remaining 3x3 sub-determinants
float det3_203_012 = mat[2][0] * det2_03_12 - mat[2][1] * det2_03_02 + mat[2][2] * det2_03_01;
float det3_203_013 = mat[2][0] * det2_03_13 - mat[2][1] * det2_03_03 + mat[2][3] * det2_03_01;
float det3_203_023 = mat[2][0] * det2_03_23 - mat[2][2] * det2_03_03 + mat[2][3] * det2_03_02;
float det3_203_123 = mat[2][1] * det2_03_23 - mat[2][2] * det2_03_13 + mat[2][3] * det2_03_12;
float det3_213_012 = mat[2][0] * det2_13_12 - mat[2][1] * det2_13_02 + mat[2][2] * det2_13_01;
float det3_213_013 = mat[2][0] * det2_13_13 - mat[2][1] * det2_13_03 + mat[2][3] * det2_13_01;
float det3_213_023 = mat[2][0] * det2_13_23 - mat[2][2] * det2_13_03 + mat[2][3] * det2_13_02;
float det3_213_123 = mat[2][1] * det2_13_23 - mat[2][2] * det2_13_13 + mat[2][3] * det2_13_12;
float det3_301_012 = mat[3][0] * det2_01_12 - mat[3][1] * det2_01_02 + mat[3][2] * det2_01_01;
float det3_301_013 = mat[3][0] * det2_01_13 - mat[3][1] * det2_01_03 + mat[3][3] * det2_01_01;
float det3_301_023 = mat[3][0] * det2_01_23 - mat[3][2] * det2_01_03 + mat[3][3] * det2_01_02;
float det3_301_123 = mat[3][1] * det2_01_23 - mat[3][2] * det2_01_13 + mat[3][3] * det2_01_12;
mat[0][0] = - det3_213_123 * invDet;
mat[1][0] = + det3_213_023 * invDet;
mat[2][0] = - det3_213_013 * invDet;
mat[3][0] = + det3_213_012 * invDet;
mat[0][1] = + det3_203_123 * invDet;
mat[1][1] = - det3_203_023 * invDet;
mat[2][1] = + det3_203_013 * invDet;
mat[3][1] = - det3_203_012 * invDet;
mat[0][2] = + det3_301_123 * invDet;
mat[1][2] = - det3_301_023 * invDet;
mat[2][2] = + det3_301_013 * invDet;
mat[3][2] = - det3_301_012 * invDet;
mat[0][3] = - det3_201_123 * invDet;
mat[1][3] = + det3_201_023 * invDet;
mat[2][3] = - det3_201_013 * invDet;
mat[3][3] = + det3_201_012 * invDet;
return true;
#elif 0
// 4*18 = 72 multiplications
// 4 divisions
float *mat = reinterpret_cast<float *>(this);
float s;
double d, di;
di = mat[0];
s = di;
mat[0] = d = 1.0f / di;
mat[1] *= d;
mat[2] *= d;
mat[3] *= d;
d = -d;
mat[4] *= d;
mat[8] *= d;
mat[12] *= d;
d = mat[4] * di;
mat[5] += mat[1] * d;
mat[6] += mat[2] * d;
mat[7] += mat[3] * d;
d = mat[8] * di;
mat[9] += mat[1] * d;
mat[10] += mat[2] * d;
mat[11] += mat[3] * d;
d = mat[12] * di;
mat[13] += mat[1] * d;
mat[14] += mat[2] * d;
mat[15] += mat[3] * d;
di = mat[5];
s *= di;
mat[5] = d = 1.0f / di;
mat[4] *= d;
mat[6] *= d;
mat[7] *= d;
d = -d;
mat[1] *= d;
mat[9] *= d;
mat[13] *= d;
d = mat[1] * di;
mat[0] += mat[4] * d;
mat[2] += mat[6] * d;
mat[3] += mat[7] * d;
d = mat[9] * di;
mat[8] += mat[4] * d;
mat[10] += mat[6] * d;
mat[11] += mat[7] * d;
d = mat[13] * di;
mat[12] += mat[4] * d;
mat[14] += mat[6] * d;
mat[15] += mat[7] * d;
di = mat[10];
s *= di;
mat[10] = d = 1.0f / di;
mat[8] *= d;
mat[9] *= d;
mat[11] *= d;
d = -d;
mat[2] *= d;
mat[6] *= d;
mat[14] *= d;
d = mat[2] * di;
mat[0] += mat[8] * d;
mat[1] += mat[9] * d;
mat[3] += mat[11] * d;
d = mat[6] * di;
mat[4] += mat[8] * d;
mat[5] += mat[9] * d;
mat[7] += mat[11] * d;
d = mat[14] * di;
mat[12] += mat[8] * d;
mat[13] += mat[9] * d;
mat[15] += mat[11] * d;
di = mat[15];
s *= di;
mat[15] = d = 1.0f / di;
mat[12] *= d;
mat[13] *= d;
mat[14] *= d;
d = -d;
mat[3] *= d;
mat[7] *= d;
mat[11] *= d;
d = mat[3] * di;
mat[0] += mat[12] * d;
mat[1] += mat[13] * d;
mat[2] += mat[14] * d;
d = mat[7] * di;
mat[4] += mat[12] * d;
mat[5] += mat[13] * d;
mat[6] += mat[14] * d;
d = mat[11] * di;
mat[8] += mat[12] * d;
mat[9] += mat[13] * d;
mat[10] += mat[14] * d;
return (s != 0.0f && !FLOAT_IS_NAN(s));
#else
// 6*8+2*6 = 60 multiplications
// 2*1 = 2 divisions
Mat2 r0, r1, r2, r3;
float a, det, invDet;
float *mat = reinterpret_cast<float *>(this);
// r0 = m0.Inverse();
det = mat[0*4+0] * mat[1*4+1] - mat[0*4+1] * mat[1*4+0];
if (Math::Fabs(det) < MATRIX_INVERSE_EPSILON) {
return false;
}
invDet = 1.0f / det;
r0[0][0] = mat[1*4+1] * invDet;
r0[0][1] = - mat[0*4+1] * invDet;
r0[1][0] = - mat[1*4+0] * invDet;
r0[1][1] = mat[0*4+0] * invDet;
// r1 = r0 * m1;
r1[0][0] = r0[0][0] * mat[0*4+2] + r0[0][1] * mat[1*4+2];
r1[0][1] = r0[0][0] * mat[0*4+3] + r0[0][1] * mat[1*4+3];
r1[1][0] = r0[1][0] * mat[0*4+2] + r0[1][1] * mat[1*4+2];
r1[1][1] = r0[1][0] * mat[0*4+3] + r0[1][1] * mat[1*4+3];
// r2 = m2 * r1;
r2[0][0] = mat[2*4+0] * r1[0][0] + mat[2*4+1] * r1[1][0];
r2[0][1] = mat[2*4+0] * r1[0][1] + mat[2*4+1] * r1[1][1];
r2[1][0] = mat[3*4+0] * r1[0][0] + mat[3*4+1] * r1[1][0];
r2[1][1] = mat[3*4+0] * r1[0][1] + mat[3*4+1] * r1[1][1];
// r3 = r2 - m3;
r3[0][0] = r2[0][0] - mat[2*4+2];
r3[0][1] = r2[0][1] - mat[2*4+3];
r3[1][0] = r2[1][0] - mat[3*4+2];
r3[1][1] = r2[1][1] - mat[3*4+3];
// r3.InverseSelf();
det = r3[0][0] * r3[1][1] - r3[0][1] * r3[1][0];
if (Math::Fabs(det) < MATRIX_INVERSE_EPSILON) {
return false;
}
invDet = 1.0f / det;
a = r3[0][0];
r3[0][0] = r3[1][1] * invDet;
r3[0][1] = - r3[0][1] * invDet;
r3[1][0] = - r3[1][0] * invDet;
r3[1][1] = a * invDet;
// r2 = m2 * r0;
r2[0][0] = mat[2*4+0] * r0[0][0] + mat[2*4+1] * r0[1][0];
r2[0][1] = mat[2*4+0] * r0[0][1] + mat[2*4+1] * r0[1][1];
r2[1][0] = mat[3*4+0] * r0[0][0] + mat[3*4+1] * r0[1][0];
r2[1][1] = mat[3*4+0] * r0[0][1] + mat[3*4+1] * r0[1][1];
// m2 = r3 * r2;
mat[2*4+0] = r3[0][0] * r2[0][0] + r3[0][1] * r2[1][0];
mat[2*4+1] = r3[0][0] * r2[0][1] + r3[0][1] * r2[1][1];
mat[3*4+0] = r3[1][0] * r2[0][0] + r3[1][1] * r2[1][0];
mat[3*4+1] = r3[1][0] * r2[0][1] + r3[1][1] * r2[1][1];
// m0 = r0 - r1 * m2;
mat[0*4+0] = r0[0][0] - r1[0][0] * mat[2*4+0] - r1[0][1] * mat[3*4+0];
mat[0*4+1] = r0[0][1] - r1[0][0] * mat[2*4+1] - r1[0][1] * mat[3*4+1];
mat[1*4+0] = r0[1][0] - r1[1][0] * mat[2*4+0] - r1[1][1] * mat[3*4+0];
mat[1*4+1] = r0[1][1] - r1[1][0] * mat[2*4+1] - r1[1][1] * mat[3*4+1];
// m1 = r1 * r3;
mat[0*4+2] = r1[0][0] * r3[0][0] + r1[0][1] * r3[1][0];
mat[0*4+3] = r1[0][0] * r3[0][1] + r1[0][1] * r3[1][1];
mat[1*4+2] = r1[1][0] * r3[0][0] + r1[1][1] * r3[1][0];
mat[1*4+3] = r1[1][0] * r3[0][1] + r1[1][1] * r3[1][1];
// m3 = -r3;
mat[2*4+2] = -r3[0][0];
mat[2*4+3] = -r3[0][1];
mat[3*4+2] = -r3[1][0];
mat[3*4+3] = -r3[1][1];
return true;
#endif
}
bool Mat4::AffineInverseSelf() {
Mat4 invMat;
Vec3 t;
// The bottom row vector of the matrix should always be [ 0 0 0 1 ]
if (mat[3][0] != 0.0f || mat[3][1] != 0.0f || mat[3][2] != 0.0f || mat[3][3] != 1.0f) {
return false;
}
// The translation components of the original matrix
t.x = mat[0][3];
t.y = mat[1][3];
t.z = mat[2][3];
// The rotational part of the matrix should be inverted
Mat3 r = ToMat3();
r.InverseSelf();
mat[0][0] = r.mat[0][0];
mat[1][0] = r.mat[0][1];
mat[2][0] = r.mat[0][2];
mat[0][1] = r.mat[1][0];
mat[1][1] = r.mat[1][1];
mat[2][1] = r.mat[1][2];
mat[0][2] = r.mat[2][0];
mat[1][2] = r.mat[2][1];
mat[2][2] = r.mat[2][2];
// -(Rt * T)
mat[0][3] = -(mat[0].x * t.x + mat[0].y * t.y + mat[0].z * t.z);
mat[1][3] = -(mat[1].x * t.x + mat[1].y * t.y + mat[1].z * t.z);
mat[2][3] = -(mat[2].x * t.x + mat[2].y * t.y + mat[2].z * t.z);
return true;
}
bool Mat4::EuclideanInverseSelf() {
Mat4 invMat;
Vec3 t;
float temp;
// The bottom row vector of the matrix should always be [ 0 0 0 1 ]
if (mat[3][0] != 0.0f || mat[3][1] != 0.0f || mat[3][2] != 0.0f || mat[3][3] != 1.0f) {
return false;
}
// The translation components of the original matrix
t.x = mat[0][3];
t.y = mat[1][3];
t.z = mat[2][3];
// The rotational part of the matrix is simply the transpose of the original matrix
temp = mat[0][1];
mat[0][1] = mat[1][0];
mat[1][0] = temp;
temp = mat[0][2];
mat[0][2] = mat[2][0];
mat[2][0] = temp;
temp = mat[1][2];
mat[1][2] = mat[2][1];
mat[2][1] = temp;
// -(Rt * T)
mat[0][3] = -(mat[0].x * t.x + mat[0].y * t.y + mat[0].z * t.z);
mat[1][3] = -(mat[1].x * t.x + mat[1].y * t.y + mat[1].z * t.z);
mat[2][3] = -(mat[2].x * t.x + mat[2].y * t.y + mat[2].z * t.z);
return true;
}
// Doolittle Algorithm
// Doolittle uses unit diagonals for the lower triangle
bool Mat4::DecompLU() {
float sum;
for (int i = 0; i < Rows; i++) {
// Compute a line of U
for (int j = i; j < Cols; j++) {
sum = 0;
for (int k = 0; k < i; k++) {
sum += mat[i][k] * mat[k][j];
}
mat[i][j] = mat[i][j] - sum; // not dividing by diagonals
}
// Compute a line of L
for (int j = 0; j < i; j++) {
sum = 0;
for (int k = 0; k < j; k++) {
sum += mat[i][k] * mat[k][j];
}
mat[i][j] = (mat[i][j] - sum) / mat[j][j];
}
}
return true;
}
Vec4 Mat4::SolveLU(const Vec4 &b) const {
Vec4 x, y;
float sum;
// Solve Ly = b
for (int i = 0; i < Rows; i++) {
sum = 0;
for (int j = 0; j < i; j++) {
sum += mat[i][j] * y[j];
}
y[i] = b[i] - sum; // not dividing by diagonals
}
// Solve Ux = y
for (int i = Rows - 1; i >= 0; i--) {
sum = 0;
for (int j = i; j < Cols; j++) {
sum += mat[i][j] * x[j];
}
x[i] = (y[i] - sum) / mat[i][i];
}
return x;
}
//---------------------------------------------------
//
// | 1 0 0 tx | | m00 m01 m02 m03 |
// T M = | 0 1 0 ty | | m10 m11 m12 m13 |
// | 0 0 1 tz | | m20 m21 m22 m23 |
// | 0 0 0 1 | | m30 m31 m32 m33 |
//
//---------------------------------------------------
Mat4 &Mat4::Translate(float tx, float ty, float tz) {
mat[0][3] += mat[3][3] * tx;
mat[1][3] += mat[3][3] * ty;
mat[2][3] += mat[3][3] * tz;
return *this;
}
//---------------------------------------------------
//
// | m00 m01 m02 m03 | | 1 0 0 tx |
// M T = | m10 m11 m12 m13 | | 0 1 0 ty |
// | m20 m21 m22 m23 | | 0 0 1 tz |
// | m30 m31 m32 m33 | | 0 0 0 1 |
//
//---------------------------------------------------
Mat4 &Mat4::TranslateRight(float tx, float ty, float tz) {
mat[0][3] += mat[0][0] * tx + mat[0][1] * ty + mat[0][2] * tz;
mat[1][3] += mat[1][0] * tx + mat[1][1] * ty + mat[1][2] * tz;
mat[2][3] += mat[2][0] * tx + mat[2][1] * ty + mat[2][2] * tz;
mat[3][3] += mat[3][0] * tx + mat[3][1] * ty + mat[3][2] * tz;
return *this;
}
//---------------------------------------------------
//
// | sx 0 0 0 | | m00 m01 m02 m03 |
// S M = | 0 sy 0 0 | | m10 m11 m12 m13 |
// | 0 0 sz 0 | | m20 m21 m22 m23 |
// | 0 0 0 1 | | m30 m31 m32 m33 |
//
//---------------------------------------------------
Mat4 &Mat4::Scale(float sx, float sy, float sz) {
mat[0] *= sx;
mat[1] *= sy;
mat[2] *= sz;
return *this;
}
void Mat4::SetFrustum(float left, float right, float bottom, float top, float zNear, float zFar) {
float nudge = 0.999f; // prevent artifacts with infinite far plane
// check for division by 0
if (left == right || top == bottom || zNear == zFar) {
return;
}
mat[0][0] = (2 * zNear) / (right - left);
mat[0][1] = 0.f;
mat[0][2] = (right + left) / (right - left);
mat[0][3] = 0.f;
mat[1][0] = 0.f;
mat[1][1] = (2 * zNear) / (top - bottom);
mat[1][2] = (top + bottom) / (top - bottom);
mat[1][3] = 0.f;
mat[2][0] = 0.f;
mat[2][1] = 0.f;
if (zFar != -1) {
mat[2][2] = -(zFar + zNear) / (zFar - zNear);
} else { // if zFar == -1, use an infinite far plane
mat[2][2] = -nudge;
}
if (zFar != -1) {
mat[2][3] = -(2 * zFar * zNear) / (zFar - zNear);
} else { // if zFar == -1, use an infinite far plane
mat[2][3] = -2 * zNear * nudge;
}
mat[3][0] = 0.f;
mat[3][1] = 0.f;
mat[3][2] = -1;
mat[3][3] = 0.f;
}
void Mat4::SetPerspective(float fovy, float aspect, float zNear, float zFar) {
float top = zNear * Math::Tan(DEG2RAD(fovy / (aspect * 2)));
float bottom = -top;
float left = bottom * aspect;
float right = top * aspect;
SetFrustum(left, right, bottom, top, zNear, zFar);
}
void Mat4::SetOrtho(float left, float right, float bottom, float top, float zNear, float zFar) {
mat[0][0] = 2.f / (right - left);
mat[0][1] = 0.f;
mat[0][2] = 0.f;
mat[0][3] = -(right + left) / (right - left);
mat[1][0] = 0.f;
mat[1][1] = 2.f / (top - bottom);
mat[1][2] = 0.f;
mat[1][3] = -(top + bottom) / (top - bottom);
mat[2][0] = 0.f;
mat[2][1] = 0.f;
mat[2][2] = -2.f / (zFar - zNear);
mat[2][3] = -(zFar + zNear) / (zFar - zNear);
mat[3][0] = 0.f;
mat[3][1] = 0.f;
mat[3][2] = 0.f;
mat[3][3] = 1.f;
}
//--------------------------------------------------------------------------------------------
//
// * 한점을 주어진 평면으로 반사(reflection)시키는 행렬을 만든다
//
// X = ( 2 * (-D*N) / (N*N) ) * N + D
//
// | 1-2*Nx*Nx -2*Nx*Ny -2*Nx*Nz 2*d*Nx |
// R = | -2*Nx*Ny 1-2*Ny*Ny -2*Ny*Nz 2*d*Ny |
// | -2*Nx*Nz -2*Ny*Nz 1-2*Nz*Nz 2*d*Nz |
// | 0 0 0 1 |
//
//--------------------------------------------------------------------------------------------
void Mat4::SetReflect(const Plane &plane) {
Vec3 normal = plane.normal;
float dist = -plane.offset;
mat[0][0] = 1.0f - 2.0f * normal.x * normal.x;
mat[0][1] = 0.0f - 2.0f * normal.x * normal.y;
mat[0][2] = 0.0f - 2.0f * normal.x * normal.z;
mat[0][3] = 2.0f * dist * normal.x;
mat[1][0] = mat[0][1];
mat[1][1] = 1.0f - 2.0f * normal.y * normal.y;
mat[1][2] = 0.0f - 2.0f * normal.y * normal.z;
mat[1][3] = 2.0f * dist * normal.y;
mat[2][0] = mat[0][2];
mat[2][1] = mat[1][2];
mat[2][2] = 1.0f - 2.0f * normal.z * normal.z;
mat[2][3] = 2.0f * dist * normal.z;
mat[3][0] = 0.0f;
mat[3][1] = 0.0f;
mat[3][2] = 0.0f;
mat[3][3] = 1.0f;
}
void Mat4::SetTRS(const Vec3 &translation, const Mat3 &rotation, const Vec3 &scale) {
// T * R * S
mat[0][0] = rotation[0][0] * scale.x;
mat[0][1] = rotation[1][0] * scale.y;
mat[0][2] = rotation[2][0] * scale.z;
mat[0][3] = translation.x;
mat[1][0] = rotation[0][1] * scale.x;
mat[1][1] = rotation[1][1] * scale.y;
mat[1][2] = rotation[2][1] * scale.z;
mat[1][3] = translation.y;
mat[2][0] = rotation[0][2] * scale.x;
mat[2][1] = rotation[1][2] * scale.y;
mat[2][2] = rotation[2][2] * scale.z;
mat[2][3] = translation.z;
mat[3][0] = 0.0f;
mat[3][1] = 0.0f;
mat[3][2] = 0.0f;
mat[3][3] = 1.0f;
}
void Mat4::SetTQS(const Vec3 &translation, const Quat &rotation, const Vec3 &scale) {
SetTRS(translation, rotation.ToMat3(), scale);
}
void Mat4::GetTRS(Vec3 &translation, Mat3 &rotation, Vec3 &scale) const {
ToMat3x4().GetTRS(translation, rotation, scale);
}
void Mat4::GetTQS(Vec3 &translation, Quat &rotation, Vec3 &scale) const {
Mat3 r;
GetTRS(translation, r, scale);
rotation = r.ToQuat();
}
Mat4 Mat4::FromString(const char *str) {
Mat4 m;
sscanf(str, "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f", &m[0].x, &m[0].y, &m[0].z, &m[0].w, &m[1].x, &m[1].y, &m[1].z, &m[1].w, &m[2].x, &m[2].y, &m[2].z, &m[2].w, &m[3].x, &m[3].y, &m[3].z, &m[3].w);
return m;
}
BE_NAMESPACE_END
| 33.07967 | 211 | 0.452952 | [
"vector"
] |
ff8cd26d503e84064b41a7a45c903900c765219c | 1,539 | cc | C++ | 10_LambdaFunktionen/Lambda.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | 10_LambdaFunktionen/Lambda.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | 10_LambdaFunktionen/Lambda.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int check_even(int val)
{
if (val % 2 == 0)
return 1;
else
return 0;
}
int main()
{
std::vector<int> my_vector(10, 0);
std::iota(my_vector.begin(), my_vector.end(), 0);
for (const auto &val : my_vector)
{
std::cout << val << std::endl;
}
std::cout << std::endl;
std::vector<int> my_result(10, 0);
std::vector<int> my_result2;
// TRANSFORM: Speichert True oder False in my_result
// bei Gerade/Ungerade Zahl in my_vector haben
// WICHTIG: Speichert wirklich den return Wert ab!
std::transform(my_vector.begin(), my_vector.end(), my_result.begin(),
[](int val) -> int
{
if (val % 2 == 0)
return true;
else
return false;
}
);
for (const auto &val : my_result)
{
std::cout << val << std::endl;
}
std::cout << std::endl;
// COPY IF: Speichert den Wert in my_result2
// bei Geraden/Ungeraden Zahl aus my_vector
// WICHTIG: Speichert den Value bei return True
std::copy_if(my_vector.begin(), my_vector.end(), std::back_inserter(my_result2),
[](int val) -> int
{
if (val % 2 == 0)
return true;
else
return false;
}
);
for (const auto &val : my_result2)
{
std::cout << val << std::endl;
}
std::cout << std::endl;
return 0;
} | 22.632353 | 84 | 0.533463 | [
"vector",
"transform"
] |
ff8ea4a49da635dd534268b008bb923c41b4fd44 | 9,512 | cpp | C++ | src/RadialLight.cpp | MiguelMJ/Candle | c94703db32a94c8669fbf39f22f65a73e15cfbaf | [
"MIT"
] | 80 | 2020-09-26T12:00:20.000Z | 2022-03-31T03:24:06.000Z | src/RadialLight.cpp | MiguelMJ/Candle | c94703db32a94c8669fbf39f22f65a73e15cfbaf | [
"MIT"
] | 19 | 2020-11-05T17:40:28.000Z | 2022-01-19T14:15:13.000Z | src/RadialLight.cpp | MiguelMJ/Candle | c94703db32a94c8669fbf39f22f65a73e15cfbaf | [
"MIT"
] | 8 | 2020-11-05T11:45:52.000Z | 2022-01-18T02:28:12.000Z | #ifdef CANDLE_DEBUG
#include <iostream>
#endif
#include <memory>
#include "Candle/RadialLight.hpp"
#include "SFML/Graphics.hpp"
#include "Candle/graphics/VertexArray.hpp"
#include "Candle/geometry/Vector2.hpp"
#include "Candle/geometry/Line.hpp"
namespace candle{
int RadialLight::s_instanceCount = 0;
const float BASE_RADIUS = 400.0f;
bool l_texturesReady(false);
std::unique_ptr<sf::RenderTexture> l_lightTextureFade;
std::unique_ptr<sf::RenderTexture> l_lightTexturePlain;
void initializeTextures(){
#ifdef CANDLE_DEBUG
std::cout << "RadialLight: InitializeTextures" << std::endl;
#endif
int points = 100;
l_lightTextureFade.reset(new sf::RenderTexture);
l_lightTexturePlain.reset(new sf::RenderTexture);
l_lightTextureFade->create(BASE_RADIUS*2 + 2, BASE_RADIUS*2 + 2);
l_lightTexturePlain->create(BASE_RADIUS*2 + 2, BASE_RADIUS*2 + 2);
sf::VertexArray lightShape(sf::TriangleFan, points+2);
float step = sfu::PI*2.f/points;
lightShape[0].position = {BASE_RADIUS + 1, BASE_RADIUS + 1};
for(int i = 1; i < points+2; i++){
lightShape[i].position = {
(std::sin(step*(i)) + 1) * BASE_RADIUS + 1,
(std::cos(step*(i)) + 1) * BASE_RADIUS + 1
};
lightShape[i].color.a = 0;
}
l_lightTextureFade->clear(sf::Color::Transparent);
l_lightTextureFade->draw(lightShape);
l_lightTextureFade->display();
l_lightTextureFade->setSmooth(true);
sfu::setColor(lightShape, sf::Color::White);
l_lightTexturePlain->clear(sf::Color::Transparent);
l_lightTexturePlain->draw(lightShape);
l_lightTexturePlain->display();
l_lightTexturePlain->setSmooth(true);
}
float module360(float x){
x = (float)fmod(x,360.f);
if(x < 0.f) x += 360.f;
return x;
}
RadialLight::RadialLight()
: LightSource()
{
if(!l_texturesReady){
// The first time we create a RadialLight, we must create the textures
initializeTextures();
l_texturesReady = true;
}
m_polygon.setPrimitiveType(sf::TriangleFan);
m_polygon.resize(6);
m_polygon[0].position =
m_polygon[0].texCoords = {BASE_RADIUS+1, BASE_RADIUS+1};
m_polygon[1].position =
m_polygon[5].position =
m_polygon[1].texCoords =
m_polygon[5].texCoords = {0.f, 0.f};
m_polygon[2].position =
m_polygon[2].texCoords = {BASE_RADIUS*2 + 2, 0.f};
m_polygon[3].position =
m_polygon[3].texCoords = {BASE_RADIUS*2 + 2, BASE_RADIUS*2 + 2};
m_polygon[4].position =
m_polygon[4].texCoords = {0.f, BASE_RADIUS*2 + 2};
Transformable::setOrigin(BASE_RADIUS, BASE_RADIUS);
setRange(1.0f);
setBeamAngle(360.f);
// castLight();
s_instanceCount++;
}
RadialLight::~RadialLight(){
s_instanceCount--;
#ifdef RADIAL_LIGHT_FIX
if (s_instanceCount == 0 &&
l_lightTextureFade &&
l_lightTexturePlain)
{
l_lightTextureFade.reset(nullptr);
l_lightTexturePlain.reset(nullptr);
l_texturesReady = false;
#ifdef CANDLE_DEBUG
std::cout << "RadialLight: Textures destroyed" << std::endl;
#endif
}
#endif
}
void RadialLight::draw(sf::RenderTarget& t, sf::RenderStates s) const{
sf::Transform trm = Transformable::getTransform();
trm.scale(m_range/BASE_RADIUS, m_range/BASE_RADIUS, BASE_RADIUS, BASE_RADIUS);
s.transform *= trm;
s.texture = m_fade ? &l_lightTextureFade->getTexture() : &l_lightTexturePlain->getTexture();
if(s.blendMode == sf::BlendAlpha){
s.blendMode = sf::BlendAdd;
}
t.draw(m_polygon, s);
#ifdef CANDLE_DEBUG
sf::RenderStates deb_s;
deb_s.transform = s.transform;
t.draw(m_debug, deb_s);
#endif
}
void RadialLight::resetColor(){
sfu::setColor(m_polygon, m_color);
}
void RadialLight::setBeamAngle(float r){
m_beamAngle = module360(r);
}
float RadialLight::getBeamAngle() const{
return m_beamAngle;
}
sf::FloatRect RadialLight::getLocalBounds() const{
return sf::FloatRect(0.0f, 0.0f, BASE_RADIUS*2, BASE_RADIUS*2);
}
sf::FloatRect RadialLight::getGlobalBounds() const{
float scaledRange = m_range / BASE_RADIUS;
sf::Transform trm = Transformable::getTransform();
trm.scale(scaledRange, scaledRange, BASE_RADIUS, BASE_RADIUS);
return trm.transformRect( getLocalBounds() );
}
void RadialLight::castLight(const EdgeVector::iterator& begin, const EdgeVector::iterator& end){
float scaledRange = m_range / BASE_RADIUS;
sf::Transform trm = Transformable::getTransform();
trm.scale(scaledRange, scaledRange, BASE_RADIUS, BASE_RADIUS);
std::vector<sfu::Line> rays;
rays.reserve(2 + std::distance(begin, end) * 2 * 3); // 2: beam angle, 4: corners, 2: pnts/sgmnt, 3 rays/pnt
// Start casting
float bl1 = module360(getRotation() - m_beamAngle/2);
float bl2 = module360(getRotation() + m_beamAngle/2);
bool beamAngleBigEnough = m_beamAngle < 0.1f;
auto castPoint = Transformable::getPosition();
float off = .001f;
auto angleInBeam = [&](float a)-> bool {
return beamAngleBigEnough
||(bl1 < bl2 && a > bl1 && a < bl2)
||(bl1 > bl2 && (a > bl1 || a < bl2));
};
for(float a = 45.f; a < 360.f; a += 90.f){
if(beamAngleBigEnough || angleInBeam(a)){
rays.emplace_back(castPoint, a);
}
}
sf::FloatRect lightBounds = getGlobalBounds();
for(auto it = begin; it != end; it++){
auto& s = *it;
//Only cast a ray if the line is in range
if( lightBounds.intersects( s.getGlobalBounds() ) ){
sfu::Line r1(castPoint, s.m_origin);
sfu::Line r2(castPoint, s.point(1.f));
float a1 = sfu::angle(r1.m_direction);
float a2 = sfu::angle(r2.m_direction);
if(angleInBeam(a1)){
rays.push_back(r1);
rays.emplace_back(castPoint, a1 - off);
rays.emplace_back(castPoint, a1 + off);
}
if(angleInBeam(a2)){
rays.push_back(r2);
rays.emplace_back(castPoint, a2 - off);
rays.emplace_back(castPoint, a2 + off);
}
}
}
if(bl1 > bl2){
std::sort(
rays.begin(),
rays.end(),
[bl1, bl2] (sfu::Line& r1, sfu::Line& r2){
float _bl1 = bl1-0.1;
float _bl2 = bl2+0.1;
float a1 = sfu::angle(r1.m_direction);
float a2 = sfu::angle(r2.m_direction);
return (a1 >= _bl1 && a2 <= _bl2) || (a1 < a2 && (_bl1 <= a1 || a2 <= _bl2));
}
);
}else{
std::sort(
rays.begin(),
rays.end(),
[bl1] (sfu::Line& r1, sfu::Line& r2){
return
sfu::angle(r1.m_direction) < sfu::angle(r2.m_direction);
}
);
}
if(!beamAngleBigEnough){
rays.emplace(rays.begin(), castPoint, bl1);
rays.emplace_back(castPoint, bl2);
}
sf::Transform tr_i = trm.getInverse();
// keep only the ones within the area
std::vector<sf::Vector2f> points;
points.reserve(rays.size());
for (auto& r: rays){
points.push_back(tr_i.transformPoint(castRay(begin, end, r, m_range*m_range)));
}
m_polygon.resize(points.size() + 1 + beamAngleBigEnough); // + center and last
m_polygon[0].color = m_color;
m_polygon[0].position = m_polygon[0].texCoords = tr_i.transformPoint(castPoint);
#ifdef CANDLE_DEBUG
float bl1rad = bl1 * sfu::PI/180.f;
float bl2rad = bl2 * sfu::PI/180.f;
sf::Vector2f al1(std::cos(bl1rad), std::sin(bl1rad));
sf::Vector2f al2(std::cos(bl2rad), std::sin(bl2rad));
int d_n = points.size()*2 + 4;
m_debug.resize(d_n);
m_debug[d_n-1].color = m_debug[d_n-2].color = sf::Color::Cyan;
m_debug[d_n-3].color = m_debug[d_n-4].color = sf::Color::Yellow;
m_debug[d_n-1].position = m_debug[d_n-3].position = m_polygon[0].position;
m_debug[d_n-2].position = tr_i.transformPoint(castPoint + m_range * al1);
m_debug[d_n-4].position = tr_i.transformPoint(castPoint + m_range * al2);
#endif
for(unsigned i=0; i < points.size(); i++){
sf::Vector2f p = points[i];
m_polygon[i+1].position = p;
m_polygon[i+1].texCoords = p;
m_polygon[i+1].color = m_color;
#ifdef CANDLE_DEBUG
m_debug[i*2].position = m_polygon[0].position;
m_debug[i*2+1].position = p;
m_debug[i*2].color = m_debug[i*2+1].color = sf::Color::Magenta;
#endif
}
if(beamAngleBigEnough){
m_polygon[points.size()+1] = m_polygon[1];
}
}
}
| 36.444444 | 116 | 0.561081 | [
"geometry",
"vector",
"transform"
] |
ff90a6a69a1cf9dc286ba77974fd3c26a7c5b6ad | 9,120 | cpp | C++ | src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/renderer/d3d/d3d11/InputLayoutCache.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/renderer/d3d/d3d11/InputLayoutCache.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/renderer/d3d/d3d11/InputLayoutCache.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// InputLayoutCache.cpp: Defines InputLayoutCache, a class that builds and caches
// D3D11 input layouts.
#include "libGLESv2/renderer/d3d/d3d11/InputLayoutCache.h"
#include "libGLESv2/renderer/d3d/d3d11/VertexBuffer11.h"
#include "libGLESv2/renderer/d3d/d3d11/Buffer11.h"
#include "libGLESv2/renderer/d3d/d3d11/ShaderExecutable11.h"
#include "libGLESv2/renderer/d3d/d3d11/formatutils11.h"
#include "libGLESv2/renderer/d3d/ProgramD3D.h"
#include "libGLESv2/renderer/d3d/VertexDataManager.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "third_party/murmurhash/MurmurHash3.h"
namespace rx
{
static void GetInputLayout(const TranslatedAttribute translatedAttributes[gl::MAX_VERTEX_ATTRIBS],
gl::VertexFormat inputLayout[gl::MAX_VERTEX_ATTRIBS])
{
for (unsigned int attributeIndex = 0; attributeIndex < gl::MAX_VERTEX_ATTRIBS; attributeIndex++)
{
const TranslatedAttribute &translatedAttribute = translatedAttributes[attributeIndex];
if (translatedAttributes[attributeIndex].active)
{
inputLayout[attributeIndex] = gl::VertexFormat(*translatedAttribute.attribute,
translatedAttribute.currentValueType);
}
}
}
const unsigned int InputLayoutCache::kMaxInputLayouts = 1024;
InputLayoutCache::InputLayoutCache() : mInputLayoutMap(kMaxInputLayouts, hashInputLayout, compareInputLayouts)
{
mCounter = 0;
mDevice = NULL;
mDeviceContext = NULL;
mCurrentIL = NULL;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mCurrentBuffers[i] = NULL;
mCurrentVertexStrides[i] = -1;
mCurrentVertexOffsets[i] = -1;
}
}
InputLayoutCache::~InputLayoutCache()
{
clear();
}
void InputLayoutCache::initialize(ID3D11Device *device, ID3D11DeviceContext *context)
{
clear();
mDevice = device;
mDeviceContext = context;
}
void InputLayoutCache::clear()
{
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
SafeRelease(i->second.inputLayout);
}
mInputLayoutMap.clear();
markDirty();
}
void InputLayoutCache::markDirty()
{
mCurrentIL = NULL;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mCurrentBuffers[i] = NULL;
mCurrentVertexStrides[i] = -1;
mCurrentVertexOffsets[i] = -1;
}
}
gl::Error InputLayoutCache::applyVertexBuffers(TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS],
gl::ProgramBinary *programBinary)
{
int sortedSemanticIndices[gl::MAX_VERTEX_ATTRIBS];
programBinary->sortAttributesByLayout(attributes, sortedSemanticIndices);
if (!mDevice || !mDeviceContext)
{
return gl::Error(GL_OUT_OF_MEMORY, "Internal input layout cache is not initialized.");
}
InputLayoutKey ilKey = { 0 };
static const char* semanticName = "TEXCOORD";
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
D3D11_INPUT_CLASSIFICATION inputClass = attributes[i].divisor > 0 ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA;
gl::VertexFormat vertexFormat(*attributes[i].attribute, attributes[i].currentValueType);
const d3d11::VertexFormat &vertexFormatInfo = d3d11::GetVertexFormatInfo(vertexFormat);
// Record the type of the associated vertex shader vector in our key
// This will prevent mismatched vertex shaders from using the same input layout
GLint attributeSize;
programBinary->getActiveAttribute(sortedSemanticIndices[i], 0, NULL, &attributeSize, &ilKey.elements[ilKey.elementCount].glslElementType, NULL);
ilKey.elements[ilKey.elementCount].desc.SemanticName = semanticName;
ilKey.elements[ilKey.elementCount].desc.SemanticIndex = i;
ilKey.elements[ilKey.elementCount].desc.Format = vertexFormatInfo.nativeFormat;
ilKey.elements[ilKey.elementCount].desc.InputSlot = i;
ilKey.elements[ilKey.elementCount].desc.AlignedByteOffset = 0;
ilKey.elements[ilKey.elementCount].desc.InputSlotClass = inputClass;
ilKey.elements[ilKey.elementCount].desc.InstanceDataStepRate = attributes[i].divisor;
ilKey.elementCount++;
}
}
ID3D11InputLayout *inputLayout = NULL;
InputLayoutMap::iterator keyIter = mInputLayoutMap.find(ilKey);
if (keyIter != mInputLayoutMap.end())
{
inputLayout = keyIter->second.inputLayout;
keyIter->second.lastUsedTime = mCounter++;
}
else
{
gl::VertexFormat shaderInputLayout[gl::MAX_VERTEX_ATTRIBS];
GetInputLayout(attributes, shaderInputLayout);
ProgramD3D *programD3D = ProgramD3D::makeProgramD3D(programBinary->getImplementation());
ShaderExecutable *shader = NULL;
gl::Error error = programD3D->getVertexExecutableForInputLayout(shaderInputLayout, &shader);
if (error.isError())
{
return error;
}
ShaderExecutable *shader11 = ShaderExecutable11::makeShaderExecutable11(shader);
D3D11_INPUT_ELEMENT_DESC descs[gl::MAX_VERTEX_ATTRIBS];
for (unsigned int j = 0; j < ilKey.elementCount; ++j)
{
descs[j] = ilKey.elements[j].desc;
}
HRESULT result = mDevice->CreateInputLayout(descs, ilKey.elementCount, shader11->getFunction(), shader11->getLength(), &inputLayout);
if (FAILED(result))
{
return gl::Error(GL_OUT_OF_MEMORY, "Failed to create internal input layout, HRESULT: 0x%08x", result);
}
if (mInputLayoutMap.size() >= kMaxInputLayouts)
{
TRACE("Overflowed the limit of %u input layouts, removing the least recently used "
"to make room.", kMaxInputLayouts);
InputLayoutMap::iterator leastRecentlyUsed = mInputLayoutMap.begin();
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
if (i->second.lastUsedTime < leastRecentlyUsed->second.lastUsedTime)
{
leastRecentlyUsed = i;
}
}
SafeRelease(leastRecentlyUsed->second.inputLayout);
mInputLayoutMap.erase(leastRecentlyUsed);
}
InputLayoutCounterPair inputCounterPair;
inputCounterPair.inputLayout = inputLayout;
inputCounterPair.lastUsedTime = mCounter++;
mInputLayoutMap.insert(std::make_pair(ilKey, inputCounterPair));
}
if (inputLayout != mCurrentIL)
{
mDeviceContext->IASetInputLayout(inputLayout);
mCurrentIL = inputLayout;
}
bool dirtyBuffers = false;
size_t minDiff = gl::MAX_VERTEX_ATTRIBS;
size_t maxDiff = 0;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
ID3D11Buffer *buffer = NULL;
if (attributes[i].active)
{
VertexBuffer11 *vertexBuffer = VertexBuffer11::makeVertexBuffer11(attributes[i].vertexBuffer);
Buffer11 *bufferStorage = attributes[i].storage ? Buffer11::makeBuffer11(attributes[i].storage) : NULL;
buffer = bufferStorage ? bufferStorage->getBuffer(BUFFER_USAGE_VERTEX_OR_TRANSFORM_FEEDBACK)
: vertexBuffer->getBuffer();
}
UINT vertexStride = attributes[i].stride;
UINT vertexOffset = attributes[i].offset;
if (buffer != mCurrentBuffers[i] || vertexStride != mCurrentVertexStrides[i] ||
vertexOffset != mCurrentVertexOffsets[i])
{
dirtyBuffers = true;
minDiff = std::min(minDiff, static_cast<size_t>(i));
maxDiff = std::max(maxDiff, static_cast<size_t>(i));
mCurrentBuffers[i] = buffer;
mCurrentVertexStrides[i] = vertexStride;
mCurrentVertexOffsets[i] = vertexOffset;
}
}
if (dirtyBuffers)
{
ASSERT(minDiff <= maxDiff && maxDiff < gl::MAX_VERTEX_ATTRIBS);
mDeviceContext->IASetVertexBuffers(minDiff, maxDiff - minDiff + 1, mCurrentBuffers + minDiff,
mCurrentVertexStrides + minDiff, mCurrentVertexOffsets + minDiff);
}
return gl::Error(GL_NO_ERROR);
}
std::size_t InputLayoutCache::hashInputLayout(const InputLayoutKey &inputLayout)
{
static const unsigned int seed = 0xDEADBEEF;
std::size_t hash = 0;
MurmurHash3_x86_32(inputLayout.begin(), inputLayout.end() - inputLayout.begin(), seed, &hash);
return hash;
}
bool InputLayoutCache::compareInputLayouts(const InputLayoutKey &a, const InputLayoutKey &b)
{
if (a.elementCount != b.elementCount)
{
return false;
}
return std::equal(a.begin(), a.end(), b.begin());
}
}
| 35.625 | 156 | 0.660855 | [
"vector"
] |
ff910189f63cc83830348f02eb9a7de9f9745fe0 | 10,964 | cpp | C++ | GSGL/src/scenegraph/freeview.cpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | GSGL/src/scenegraph/freeview.cpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | GSGL/src/scenegraph/freeview.cpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | //
// $Id$
//
// Copyright (c) 2008, The Periapsis Project. 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 The Periapsis Project 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 "scenegraph/freeview.hpp"
#include "math/quaternion.hpp"
namespace gsgl
{
using namespace data;
using namespace math;
namespace scenegraph
{
BROKER_DEFINE_CREATOR(gsgl::scenegraph::freeview);
//
freeview::freeview(const string & name, node *parent)
: node(name, parent), cam(0), last_code(sg_event::NULL_EVENT), relative(false),
transition_end_tick(0), transition_angular_velocity(0), transition_axis(vector::Z_AXIS), transition_linear_velocity(0), transition_path(vector::ZERO)
{
cam = new camera(this);
} // freeview::freeview()
freeview::freeview(const data::config_record & obj_conf)
: node(obj_conf), cam(0), last_code(sg_event::NULL_EVENT), relative(false),
transition_end_tick(0), transition_angular_velocity(0), transition_axis(vector::Z_AXIS), transition_linear_velocity(0), transition_path(vector::ZERO)
{
cam = new camera(this);
if (!obj_conf[L"field_of_view"].is_empty())
{
cam->get_field_of_view() = static_cast<gsgl::real_t>(obj_conf[L"field_of_view"].to_double());
}
else
{
cam->get_field_of_view() = 60;
}
} // freeview::freeview()
freeview::~freeview()
{
} // freeview::~freeview()
static config_variable<gsgl::real_t> ROTATION_STEP(L"scenegraph/freeview/rotation_step", 10.0f);
static config_variable<gsgl::real_t> TRANSITION_TIME(L"scenegraph/freeview/transition_time", 0.25f);
void freeview::reset()
{
assert(get_parent());
last_code = sg_event::NULL_EVENT;
transition_end_tick = 0;
transition_angular_velocity = 0;
transition_axis = vector::Z_AXIS;
transition_linear_velocity = 0;
transition_path = vector::ZERO;
get_translation() = vector(0, -get_parent()->default_view_distance(), 0);
get_orientation() = transform::IDENTITY;
if (get_translation().mag() > 0)
relative = true;
} // freeview::reset()
void freeview::update(const simulation_context *c)
{
if (c->cur_tick < transition_end_tick)
{
if (transition_angular_velocity)
{
quaternion rq(transition_axis, transition_angular_velocity * c->delta_tick / 1000.0f);
transform rt(rq);
get_orientation() = rt * get_orientation();
if (relative)
get_translation() = rt * get_translation();
}
else if (transition_linear_velocity)
{
get_translation() += transition_path * (transition_linear_velocity * c->delta_tick / 1000.0f);
}
}
} // freeview::update()
bool freeview::rot_absolute(sg_event::event_code code, const simulation_context *c)
{
if (code != last_code)
{
vector axis;
gsgl::real_t velocity = static_cast<gsgl::real_t>(ROTATION_STEP * math::DEG2RAD / TRANSITION_TIME);
switch (code)
{
case sg_event::VIEW_ROT_X_POS:
axis = vector::X_AXIS;
break;
case sg_event::VIEW_ROT_X_NEG:
axis = vector::X_AXIS;
velocity *= -1;
break;
case sg_event::VIEW_ROT_Y_POS:
axis = vector::Y_AXIS;
break;
case sg_event::VIEW_ROT_Y_NEG:
axis = vector::Y_AXIS;
velocity *= -1;
break;
case sg_event::VIEW_ROT_Z_POS:
axis = vector::Z_AXIS;
break;
case sg_event::VIEW_ROT_Z_NEG:
axis = vector::Z_AXIS;
velocity *= -1;
break;
default:
return false;
}
last_code = code;
transition_axis = get_orientation() * axis;
transition_angular_velocity = velocity;
}
if (transition_angular_velocity != 0)
{
transition_end_tick = c->cur_tick + static_cast<unsigned long>(1000.0f * TRANSITION_TIME);
}
return true;
} // freeview::rot_absolute()
bool freeview::rot_relative(sg_event::event_code code, const simulation_context *c)
{
if (code != last_code)
{
vector axis;
gsgl::real_t velocity = static_cast<gsgl::real_t>(ROTATION_STEP * math::DEG2RAD / TRANSITION_TIME);
switch (code)
{
case sg_event::VIEW_ROT_X_POS:
axis = vector::X_AXIS;
velocity *= -1;
break;
case sg_event::VIEW_ROT_X_NEG:
axis = vector::X_AXIS;
break;
case sg_event::VIEW_ROT_Y_POS:
axis = vector::Y_AXIS;
break;
case sg_event::VIEW_ROT_Y_NEG:
axis = vector::Y_AXIS;
velocity *= -1;
break;
case sg_event::VIEW_ROT_Z_POS:
axis = vector::Z_AXIS;
velocity *= -1;
break;
case sg_event::VIEW_ROT_Z_NEG:
axis = vector::Z_AXIS;
break;
default:
return false;
}
last_code = code;
transition_axis = get_orientation() * axis;
transition_angular_velocity = velocity;
}
if (transition_angular_velocity != 0)
{
transition_end_tick = c->cur_tick + static_cast<unsigned long>(1000.0f * TRANSITION_TIME);
}
return true;
} // freeview::rot_relative()
bool freeview::handle_event(const simulation_context *c, sg_event & e)
{
switch (e.get_code())
{
case sg_event::VIEW_ROT_X_POS:
case sg_event::VIEW_ROT_X_NEG:
case sg_event::VIEW_ROT_Y_POS:
case sg_event::VIEW_ROT_Y_NEG:
case sg_event::VIEW_ROT_Z_POS:
case sg_event::VIEW_ROT_Z_NEG:
if (relative)
return rot_relative(e.get_code(), c);
else
return rot_absolute(e.get_code(), c);
case sg_event::VIEW_TOGGLE_ROT_MODE:
// don't let us switch to relative unless we're orbiting something...
if (get_translation().mag2())
{
relative = !relative;
last_code = sg_event::NULL_EVENT;
}
return true;
case sg_event::VIEW_ZOOM_IN:
case sg_event::VIEW_ZOOM_OUT:
if (relative)
{
transition_angular_velocity = 0;
if (transition_end_tick < c->cur_tick)
{
double dist = get_translation().mag();
if (dist > 0)
{
double surf = get_parent()->minimum_view_distance();
double alt = dist - surf;
if (alt < 0.0)
alt = 0.0;
double new_alt = alt * (e.get_code() == sg_event::VIEW_ZOOM_IN ? 0.5 : 2.0);
double new_dist = surf + new_alt;
double ratio = new_dist / dist;
vector desired_position = get_translation() * static_cast<gsgl::real_t>(ratio);
vector path = desired_position - get_translation();
transition_linear_velocity = path.mag() / TRANSITION_TIME;
transition_path = path; transition_path.normalize();
transition_end_tick = c->cur_tick + static_cast<unsigned long>(1000.0f * TRANSITION_TIME);
}
}
}
return true;
case sg_event::VIEW_RESET:
reset();
return true;
default:
break;
}
return false;
} // freeview::handle_event()
} // namespace scenegraph
} // namespace gsgl
| 37.166102 | 164 | 0.505199 | [
"vector",
"transform"
] |
910d1d5fc40c0cbf96501f01a74908b9f6f5474a | 4,133 | cpp | C++ | aws-cpp-sdk-config/source/model/ConfigurationRecorderStatus.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-config/source/model/ConfigurationRecorderStatus.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-config/source/model/ConfigurationRecorderStatus.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/config/model/ConfigurationRecorderStatus.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ConfigService
{
namespace Model
{
ConfigurationRecorderStatus::ConfigurationRecorderStatus() :
m_nameHasBeenSet(false),
m_lastStartTimeHasBeenSet(false),
m_lastStopTimeHasBeenSet(false),
m_recording(false),
m_recordingHasBeenSet(false),
m_lastStatus(RecorderStatus::NOT_SET),
m_lastStatusHasBeenSet(false),
m_lastErrorCodeHasBeenSet(false),
m_lastErrorMessageHasBeenSet(false),
m_lastStatusChangeTimeHasBeenSet(false)
{
}
ConfigurationRecorderStatus::ConfigurationRecorderStatus(JsonView jsonValue) :
m_nameHasBeenSet(false),
m_lastStartTimeHasBeenSet(false),
m_lastStopTimeHasBeenSet(false),
m_recording(false),
m_recordingHasBeenSet(false),
m_lastStatus(RecorderStatus::NOT_SET),
m_lastStatusHasBeenSet(false),
m_lastErrorCodeHasBeenSet(false),
m_lastErrorMessageHasBeenSet(false),
m_lastStatusChangeTimeHasBeenSet(false)
{
*this = jsonValue;
}
ConfigurationRecorderStatus& ConfigurationRecorderStatus::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("name"))
{
m_name = jsonValue.GetString("name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("lastStartTime"))
{
m_lastStartTime = jsonValue.GetDouble("lastStartTime");
m_lastStartTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("lastStopTime"))
{
m_lastStopTime = jsonValue.GetDouble("lastStopTime");
m_lastStopTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("recording"))
{
m_recording = jsonValue.GetBool("recording");
m_recordingHasBeenSet = true;
}
if(jsonValue.ValueExists("lastStatus"))
{
m_lastStatus = RecorderStatusMapper::GetRecorderStatusForName(jsonValue.GetString("lastStatus"));
m_lastStatusHasBeenSet = true;
}
if(jsonValue.ValueExists("lastErrorCode"))
{
m_lastErrorCode = jsonValue.GetString("lastErrorCode");
m_lastErrorCodeHasBeenSet = true;
}
if(jsonValue.ValueExists("lastErrorMessage"))
{
m_lastErrorMessage = jsonValue.GetString("lastErrorMessage");
m_lastErrorMessageHasBeenSet = true;
}
if(jsonValue.ValueExists("lastStatusChangeTime"))
{
m_lastStatusChangeTime = jsonValue.GetDouble("lastStatusChangeTime");
m_lastStatusChangeTimeHasBeenSet = true;
}
return *this;
}
JsonValue ConfigurationRecorderStatus::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("name", m_name);
}
if(m_lastStartTimeHasBeenSet)
{
payload.WithDouble("lastStartTime", m_lastStartTime.SecondsWithMSPrecision());
}
if(m_lastStopTimeHasBeenSet)
{
payload.WithDouble("lastStopTime", m_lastStopTime.SecondsWithMSPrecision());
}
if(m_recordingHasBeenSet)
{
payload.WithBool("recording", m_recording);
}
if(m_lastStatusHasBeenSet)
{
payload.WithString("lastStatus", RecorderStatusMapper::GetNameForRecorderStatus(m_lastStatus));
}
if(m_lastErrorCodeHasBeenSet)
{
payload.WithString("lastErrorCode", m_lastErrorCode);
}
if(m_lastErrorMessageHasBeenSet)
{
payload.WithString("lastErrorMessage", m_lastErrorMessage);
}
if(m_lastStatusChangeTimeHasBeenSet)
{
payload.WithDouble("lastStatusChangeTime", m_lastStatusChangeTime.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace ConfigService
} // namespace Aws
| 23.617143 | 101 | 0.749819 | [
"model"
] |
910d316507725206495d6871348b1788141cbe52 | 11,058 | cxx | C++ | src/PostProcessing.cxx | samsalt/gxmc | 6efeb6f0c9eeb65c6e1003c7f27b0583b5c5e572 | [
"BSD-3-Clause"
] | null | null | null | src/PostProcessing.cxx | samsalt/gxmc | 6efeb6f0c9eeb65c6e1003c7f27b0583b5c5e572 | [
"BSD-3-Clause"
] | null | null | null | src/PostProcessing.cxx | samsalt/gxmc | 6efeb6f0c9eeb65c6e1003c7f27b0583b5c5e572 | [
"BSD-3-Clause"
] | null | null | null | #include "PostProcessing.h"
void Output(std::vector<gxcBlock> &Block, std::vector<gxcNode> &Node, gxcControl &SimulationParameter)
{
int CPU_word_size, IO_word_size, exoid, error;
float version;
CPU_word_size = sizeof(gxcData);
IO_word_size = sizeof(gxcData);
exoid = ex_open("gxcOut.exo", EX_WRITE, &CPU_word_size, &IO_word_size, &version);
error = ex_put_time(exoid, SimulationParameter.TimeOutputStepID, &SimulationParameter.TimeCurrent);
// write nodal values
gxcData *dsp_x;
gxcData *vel_x;
gxcData *acl_x;
gxcData *dsp_y;
gxcData *vel_y;
gxcData *acl_y;
gxcData *dsp_z;
gxcData *vel_z;
gxcData *acl_z;
dsp_x = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
vel_x = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
acl_x = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
dsp_y = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
vel_y = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
acl_y = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
dsp_z = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
vel_z = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
acl_z = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
for (int i = 0; i < SimulationParameter.np; i++)
{
dsp_x[i] = Node[i].Displacement[0];
vel_x[i] = Node[i].Velocity[0];
acl_x[i] = Node[i].Acceleration[0];
dsp_y[i] = Node[i].Displacement[1];
vel_y[i] = Node[i].Velocity[1];
acl_y[i] = Node[i].Acceleration[1];
dsp_z[i] = Node[i].Displacement[2];
vel_z[i] = Node[i].Velocity[2];
acl_z[i] = Node[i].Acceleration[2];
}
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 1, SimulationParameter.np, dsp_x);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 2, SimulationParameter.np, dsp_y);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 3, SimulationParameter.np, dsp_z);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 4, SimulationParameter.np, vel_x);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 5, SimulationParameter.np, vel_y);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 6, SimulationParameter.np, vel_z);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 7, SimulationParameter.np, acl_x);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 8, SimulationParameter.np, acl_y);
error = ex_put_nodal_var(exoid, SimulationParameter.TimeOutputStepID, 9, SimulationParameter.np, acl_z);
free(dsp_x);
free(vel_x);
free(acl_x);
free(dsp_y);
free(vel_y);
free(acl_y);
free(dsp_z);
free(vel_z);
free(acl_z);
// write cell values
// output cell var
if (!SimulationParameter.MeshfreeSwitch)
{
// gxcId CurrentCell{};
for (int BlockId = 0; BlockId < SimulationParameter.BlockNum; BlockId++)
{
gxcData *strain_xx;
gxcData *strain_yy;
gxcData *strain_zz;
gxcData *strain_yz;
gxcData *strain_xz;
gxcData *strain_xy;
strain_xx = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
strain_yy = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
strain_zz = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
strain_yz = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
strain_xz = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
strain_xy = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
gxcData *stress_xx;
gxcData *stress_yy;
gxcData *stress_zz;
gxcData *stress_yz;
gxcData *stress_xz;
gxcData *stress_xy;
stress_xx = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
stress_yy = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
stress_zz = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
stress_yz = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
stress_xz = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
stress_xy = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
gxcData *eps;
gxcData *damage;
eps = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
damage = (gxcData *)calloc(Block[BlockId].Info.CellNum, sizeof(gxcData));
for (int i = 0; i < Block[BlockId].Info.CellNum; i++)
{
strain_xx[i] = Block[BlockId].Cell[i]->Strain[0][0];
strain_yy[i] = Block[BlockId].Cell[i]->Strain[0][1];
strain_zz[i] = Block[BlockId].Cell[i]->Strain[0][2];
strain_yz[i] = Block[BlockId].Cell[i]->Strain[0][3];
strain_xz[i] = Block[BlockId].Cell[i]->Strain[0][4];
strain_xy[i] = Block[BlockId].Cell[i]->Strain[0][5];
stress_xx[i] = Block[BlockId].Cell[i]->Stress[0][0];
stress_yy[i] = Block[BlockId].Cell[i]->Stress[0][1];
stress_zz[i] = Block[BlockId].Cell[i]->Stress[0][2];
stress_yz[i] = Block[BlockId].Cell[i]->Stress[0][3];
stress_xz[i] = Block[BlockId].Cell[i]->Stress[0][4];
stress_xy[i] = Block[BlockId].Cell[i]->Stress[0][5];
eps[i] = Block[BlockId].Cell[i]->State[0][0];
damage[i] = Block[BlockId].Cell[i]->State[0][1];
// CurrentCell++;
}
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 1, BlockId + 1, Block[BlockId].Info.CellNum, strain_xx);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 2, BlockId + 1, Block[BlockId].Info.CellNum, strain_yy);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 3, BlockId + 1, Block[BlockId].Info.CellNum, strain_zz);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 4, BlockId + 1, Block[BlockId].Info.CellNum, strain_yz);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 5, BlockId + 1, Block[BlockId].Info.CellNum, strain_xz);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 6, BlockId + 1, Block[BlockId].Info.CellNum, strain_xy);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 7, BlockId + 1, Block[BlockId].Info.CellNum, stress_xx);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 8, BlockId + 1, Block[BlockId].Info.CellNum, stress_yy);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 9, BlockId + 1, Block[BlockId].Info.CellNum, stress_zz);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 10, BlockId + 1, Block[BlockId].Info.CellNum, stress_yz);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 11, BlockId + 1, Block[BlockId].Info.CellNum, stress_xz);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 12, BlockId + 1, Block[BlockId].Info.CellNum, stress_xy);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 13, BlockId + 1, Block[BlockId].Info.CellNum, eps);
error = ex_put_elem_var(exoid, SimulationParameter.TimeOutputStepID, 14, BlockId + 1, Block[BlockId].Info.CellNum, damage);
free(strain_xx);
free(strain_yy);
free(strain_zz);
free(strain_yz);
free(strain_xz);
free(strain_xy);
free(stress_xx);
free(stress_yy);
free(stress_zz);
free(stress_yz);
free(stress_xz);
free(stress_xy);
free(eps);
free(damage);
}
}
error = ex_close(exoid);
// update time information
SimulationParameter.TimetoOutput += SimulationParameter.TimeOutputPeriod;
SimulationParameter.TimeOutputStepID++;
std::cout << std::fixed;
std::cout<<"time="<<std::setw(6) <<SimulationParameter.TimeCurrent<<" Internal energy="<<std::setprecision(6)<<SimulationParameter.InternalEnergy<<" Kinetic energy="<<std::setprecision(6)<<SimulationParameter.KineticEnergy<<" Total energy="<<std::setprecision(6)<<SimulationParameter.KineticEnergy+SimulationParameter.InternalEnergy<<std::endl;
std::fstream logFile("gxmc.log", std::fstream::app);
logFile << std::fixed;
logFile << "time="<<std::setw(6) <<SimulationParameter.TimeCurrent<<" Internal energy="<<std::setprecision(6)<<SimulationParameter.InternalEnergy<<" Kinetic energy="<<std::setprecision(6)<<SimulationParameter.KineticEnergy<<" Total energy="<<std::setprecision(6)<<SimulationParameter.KineticEnergy+SimulationParameter.InternalEnergy<<std::endl;
logFile.close();
// EchoVar("Time",SimulationParameter.TimeCurrent);
}
// void MeshfreeOutputInit( const gxcControl &SimulationParameter)
// {
// int CPU_word_size, IO_word_size, error, OutputExoid, QANum{1};
// IO_word_size = sizeof(gxcData);
// CPU_word_size = sizeof(gxcData);
// CPU_word_size = sizeof(gxcData);
// IO_word_size = sizeof(gxcData);
// OutputExoid = ex_create("gxcOut.exo", EX_CLOBBER, &CPU_word_size, &IO_word_size);
// error = ex_put_init(OutputExoid, "gxcDatabase", 3, SimulationParameter.np, SimulationParameter.nc, 1, 0, 0);
// gxcData *xcoo, *ycoo, *zcoo;
// xcoo = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
// ycoo = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
// zcoo = (gxcData *)calloc(SimulationParameter.np, sizeof(gxcData));
// for (gxcId i = 0; i < SimulationParameter.np; i++)
// {
// xcoo[i] = SimulationParameter.CellPosition[i][0];
// ycoo[i] = SimulationParameter.CellPosition[i][1];
// zcoo[i] = SimulationParameter.CellPosition[i][2];
// }
// error = ex_put_coord(OutputExoid, xcoo, ycoo, zcoo);
// free(xcoo);
// free(ycoo);
// free(zcoo);
// char *coord_names[2];
// coord_names[0] = "X";
// coord_names[1] = "Y";
// coord_names[2] = "Z";
// error = ex_put_coord_names(OutputExoid, coord_names);
// error = ex_put_elem_block(OutputExoid, 1, "SPHERE", SimulationParameter.np, 1, 1);
// int *connect;
// connect = (int *)calloc(SimulationParameter.np, sizeof(int));
// for (gxcId i = 0; i < SimulationParameter.np; i++)
// {
// connect[i] = i + 1;
// }
// error = ex_put_elem_conn(OutputExoid, 1, connect);
// free(connect);
// error = ex_close(OutputExoid);
// } | 52.657143 | 354 | 0.650118 | [
"vector"
] |
9116fb94e54ccffb6177420f945ed51d649ddfa3 | 1,523 | cpp | C++ | aws-cpp-sdk-iot/source/model/CreateProvisioningTemplateVersionResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-iot/source/model/CreateProvisioningTemplateVersionResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-iot/source/model/CreateProvisioningTemplateVersionResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iot/model/CreateProvisioningTemplateVersionResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::IoT::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
CreateProvisioningTemplateVersionResult::CreateProvisioningTemplateVersionResult() :
m_versionId(0),
m_isDefaultVersion(false)
{
}
CreateProvisioningTemplateVersionResult::CreateProvisioningTemplateVersionResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_versionId(0),
m_isDefaultVersion(false)
{
*this = result;
}
CreateProvisioningTemplateVersionResult& CreateProvisioningTemplateVersionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("templateArn"))
{
m_templateArn = jsonValue.GetString("templateArn");
}
if(jsonValue.ValueExists("templateName"))
{
m_templateName = jsonValue.GetString("templateName");
}
if(jsonValue.ValueExists("versionId"))
{
m_versionId = jsonValue.GetInteger("versionId");
}
if(jsonValue.ValueExists("isDefaultVersion"))
{
m_isDefaultVersion = jsonValue.GetBool("isDefaultVersion");
}
return *this;
}
| 24.174603 | 146 | 0.759685 | [
"model"
] |
911bb784022cbcfc671001d7537b900f8228595e | 6,908 | cpp | C++ | Time-tracker/Time-tracker/Source.cpp | Fingolfin7/Time-Tracker | 7378ba76f31bac5391ace33490fa07e9b86882bc | [
"MIT"
] | null | null | null | Time-tracker/Time-tracker/Source.cpp | Fingolfin7/Time-Tracker | 7378ba76f31bac5391ace33490fa07e9b86882bc | [
"MIT"
] | null | null | null | Time-tracker/Time-tracker/Source.cpp | Fingolfin7/Time-Tracker | 7378ba76f31bac5391ace33490fa07e9b86882bc | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <windows.h> // allows us to use "PlaySound()"
#include <ShellAPI.h> // shell execute
#include <thread>
#include <fstream>
#include <string>
#include <chrono>
#include "Colours.h"
#pragma comment (lib, "Winmm.lib")
//function prototypes
void menu();
void save_data();
std::wstring StringToWString(const std::string& s);
//structs
struct subj {
std::string name;
double total_time{ 0 };
};
struct Timer {
std::chrono::time_point<std::chrono::steady_clock> start, end;
std::chrono::duration<double> duration;
subj* genericSubject;
Timer(subj& Subj)
:start(std::chrono::steady_clock::now()), genericSubject(&Subj), duration(0)
{
}
~Timer() {
end = std::chrono::steady_clock::now();
duration = end - start;
genericSubject->total_time += duration.count() / 60;
std::cout << "\n\nSession time (in minutes): " << duration.count() / 60 << "\n";
std::cout << "Total time (in minutes): " << genericSubject->total_time << "\n";
save_data();
}
};
//Globals
Timer* pT;
int musicFreq = 1;
bool cntnue = true;
bool toggleMusic = true;
std::vector<subj> Subject;
std::string savefile, audiofile, piechartfile, barchartfile;
const char* configfile = "Config.txt";
// a bunch of functions
void bell_sound() {
if (toggleMusic) {
PlaySound(StringToWString(audiofile).c_str(), NULL, SND_ASYNC);
}
}
//on exit handler
BOOL ctrl_handler(DWORD event)
{
if (event == CTRL_CLOSE_EVENT) {
pT->~Timer();//call timer destructer
return TRUE;
}
return FALSE;
}
void timer(subj& subject) {
system("cls");
cntnue = true;
Timer timeSubj(subject);
pT = &timeSubj; // set globall timer pointer to the address timeSubj
SetConsoleCtrlHandler((PHANDLER_ROUTINE)(ctrl_handler), TRUE); //setting the control handler
int block = 0;
std::cout << Colours::colourString("[underline]" + subject.name + ":[reset] ") << std::endl;
std::cout << "Time Elapsed: ";
std::thread secThread([&block]() {
while (cntnue) {
std::this_thread::sleep_for(std::chrono::minutes(5)); // much better than sleep()
if (cntnue) {
std::cout << Colours::colourString("[cyan]") << char(219) << Colours::colourString("[reset] ");
block++;
if (musicFreq > 0) {
if (block % 6 == 0) {
std::cout << " ";
if (block % (12 / musicFreq) == 0) {
bell_sound();
}
}
}
}
else {
return;
}
}
});
secThread.detach();
//_getch(); needed conio.h
auto a = getchar(); //included in iostream
auto b = getchar();
cntnue = false;
}
int select_subject() {
system("cls");
int choice = 0;
std::cout << "Select Subject:" << std::endl;
for (size_t i = 0; i < Subject.size(); i++) {
std::cout << i + 1 << ". " << Subject[i].name << "," << std::endl;
}
std::cout << ">";
std::cin >> choice;
return choice - 1;
}
std::wstring StringToWString(const std::string& s){
std::wstring ws(s.begin(), s.end());
return ws;
}
void show_totals() {
system("cls");
int chart = 0;
std::cout << Colours::colourString("[underline]Totals per subject:[reset] ") << std::endl << std::endl;
for (size_t i = 0; i < Subject.size(); i++) {
std::cout << Subject[i].name << "(" << Subject[i].total_time / 60 << " hrs)" << std::endl;
for (int counter = 0; counter < int(Subject[i].total_time / 60); counter++) {//each block is an hour
std::cout << Colours::colourString("[cyan]") << char(219) << Colours::colourString("[reset] ");
}
std::cout << std::endl << std::endl;
}
std::cout << "Charts: \n1.Bar Graph,\n2.Pie Chart,\n3.Neither.\n>";
std::cin >> chart;
if (chart == 1) {
ShellExecute(NULL, L"open", StringToWString(barchartfile).c_str(),
NULL, NULL, SW_RESTORE);
}
else if (chart == 2) {
ShellExecute(NULL, L"open", StringToWString(piechartfile).c_str(),
NULL, NULL, SW_RESTORE);
}
}
void menu() {
while (true) {
int optn = 0;
system("cls");
std::cout << Colours::colourString("[underline]Time Tracker[reset]") << std::endl;
std::cout << "1.New Session," << std::endl;
std::cout << "2.Show Totals," << std::endl;
std::cout << "3.Edit Subjects," << std::endl;
std::cout << "4.Change Settings," << std::endl;
std::cout << "5.Exit." << std::endl;
std::cout << ">";
std::cin >> optn;
switch (optn)
{
case 1:
timer(Subject[select_subject()]);
system("pause");
break;
case 2:
show_totals();
break;
case 3:
ShellExecute(NULL, L"open", StringToWString(savefile).c_str(), NULL, NULL, SW_RESTORE);
break;
case 4:
ShellExecute(NULL, L"open", StringToWString(configfile).c_str(), NULL, NULL, SW_RESTORE);
break;
case 5:
//exit(0);
return;
default:
std::cout << "Invalid input!" << std::endl;
std::cin.get();
break;
}
}
}
void loadSaves(std::vector<subj>& Subject) {
std::ifstream read(savefile.c_str());
std::string line;
subj genericSubj;
while (std::getline(read, line)) {
//std::cout << line << std::endl;
genericSubj.name = line.substr(0, line.find(": "));
try { genericSubj.total_time = std::stod(line.substr(line.find(": ") + 2, line.length())); }
catch (...) { genericSubj.total_time = 0.0f; }
Subject.push_back(genericSubj);
}
read.close();
}
void loadSettings() {
std::ifstream rd(configfile);
std::string line;
if (rd.is_open()) {
while (std::getline(rd, line)) {
if (line.find("Save File: ") != std::string::npos) {
savefile = std::string(line.substr(line.find(": ") + 2, line.length()));
}
if (line.find("Audio File: ") != std::string::npos) {
audiofile = line.substr(line.find(": ") + 2, line.length());
}
if (line.find("Toggle Music: ") != std::string::npos) {
if (line.find("On") != std::string::npos || line.find("on") != std::string::npos) {
toggleMusic = true;
}
else {
toggleMusic = false;
}
}
if (line.find("Music Freq: ") != std::string::npos) {
try { musicFreq = std::stoi(line.substr(line.find(": ") + 2, line.length())); }
catch (...) { musicFreq = 1; }
}
if (line.find("Pie Chart File: ") != std::string::npos) {
piechartfile = line.substr(line.find(": ") + 2, line.length());
}
if (line.find("Bar Chart File: ") != std::string::npos) {
barchartfile = line.substr(line.find(": ") + 2, line.length());
}
}
rd.close();
}
}
void save_data() {//saves time totals for each subject
std::ofstream write(savefile.c_str());
if (write.is_open()) {
for (size_t i = 0; i < Subject.size(); i++) {
write << Subject[i].name << ": " << Subject[i].total_time << std::endl;
}
}
write.close();
}
int main() {
loadSettings();
loadSaves(Subject);
menu();
return 0;
}
| 24.323944 | 105 | 0.582224 | [
"vector"
] |
91286e7bc14ad32f23025313cc17ce92bd9bec7b | 1,804 | cpp | C++ | contests/uva/uva-10922.cpp | leomaurodesenv/contest-codes | f7ae7e9d8c67e43dea7ac7dd71afce20d804f518 | [
"MIT"
] | null | null | null | contests/uva/uva-10922.cpp | leomaurodesenv/contest-codes | f7ae7e9d8c67e43dea7ac7dd71afce20d804f518 | [
"MIT"
] | null | null | null | contests/uva/uva-10922.cpp | leomaurodesenv/contest-codes | f7ae7e9d8c67e43dea7ac7dd71afce20d804f518 | [
"MIT"
] | null | null | null | /*
* Problema: 10922 - 2 the 9s
* https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1863
*/
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <numeric>
#include <string>
#include <sstream>
#include <iomanip>
#include <locale>
#include <bitset>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#define INF 0x3F3F3F3F
#define PI 3.14159265358979323846
#define EPS 1e-10
#define vet_i(var, tipo, lin, col, inic) vector< vector< tipo > > var (lin, vector< tipo > (col, inic))
#define vet_d(tipo) vector< vector< tipo > >
#define lli long long int
#define llu unsigned long long int
#define fore(var, inicio, final) for(int var=inicio; var<final; var++)
#define forec(var, inicio, final, incremento) for(int var=inicio; var<final; incremento)
#define forit(it, var) for( it = var.begin(); it != var.end(); it++ )
using namespace std;
lli get_sum(string num){
lli r = 0;
fore(i, 0, num.length()){
r += num[i] - '0';
}
return r;
}
string get_str(lli num){
stringstream ss;
ss << num;
string r = ss.str();
return r;
}
int main(){
string num, numd, numf;
lli numi, degree;
while(cin>>num && num!="0"){
degree = 0;
numf = num;
numi = get_sum(num);
if(numi%9==0){
numd="";
if(numi==9) degree=1;
else while(true){
numd = num;
num = get_str(numi);
numi = get_sum(num);
if(num != numd) degree++;
else break;
}
cout<<numf<<" is a multiple of 9 and has 9-degree "<<degree<<"."<<endl;
}
else cout<<num<<" is not a multiple of 9."<<endl;
}
return 0;
}
| 23.128205 | 103 | 0.58592 | [
"vector"
] |
91295daf51269de0c3503458822bbdc2fa118b09 | 2,994 | hpp | C++ | Graphics/Graphics/ConstantBuffer.hpp | Neko81795/Graphics | 134b174609c609f7762ef0cc3e10398d2472a1b4 | [
"MIT"
] | null | null | null | Graphics/Graphics/ConstantBuffer.hpp | Neko81795/Graphics | 134b174609c609f7762ef0cc3e10398d2472a1b4 | [
"MIT"
] | null | null | null | Graphics/Graphics/ConstantBuffer.hpp | Neko81795/Graphics | 134b174609c609f7762ef0cc3e10398d2472a1b4 | [
"MIT"
] | null | null | null | #pragma once
#include "ConstantBuffer.h"
#include "GraphicsEngine.h"
#include <exception>
#include <memory>
namespace Graphics
{
template<typename T>
ConstantBuffer<T>::ConstantBuffer(GraphicsEngine& graphics, ShaderType type, UINT slot) : Graphics(graphics), Type(type), Slot(slot)
{
Create();
Dirty = false;
}
template<typename T>
template<typename ...Arguments>
ConstantBuffer<T>::ConstantBuffer(GraphicsEngine & graphics, ShaderType type, UINT slot, Arguments ...constructorParams)
:
Graphics(graphics),
Type(type),
Slot(slot),
Data(constructorParams...)
{
Create();
Dirty = false;
}
template<typename T>
const T & ConstantBuffer<T>::GetData() const
{
return Data;
}
template<typename T>
T & ConstantBuffer<T>::GetDataForWrite()
{
Dirty = true;
return Data;
}
template<typename T>
void ConstantBuffer<T>::SetData(const T & data)
{
Data = data;
Dirty = true;
}
template<typename T>
void ConstantBuffer<T>::Use()
{
if (Dirty)
{
if (!Update())
throw std::exception("Failed to update ConstantBuffer");
}
switch (Type)
{
case ShaderType::Compute:
Graphics.DeviceContext->CSSetConstantBuffers(Slot, 1, Buffer.GetAddressOf());
break;
case ShaderType::Domain:
Graphics.DeviceContext->DSSetConstantBuffers(Slot, 1, Buffer.GetAddressOf());
break;
case ShaderType::Geometry:
Graphics.DeviceContext->GSSetConstantBuffers(Slot, 1, Buffer.GetAddressOf());
break;
case ShaderType::Hull:
Graphics.DeviceContext->HSSetConstantBuffers(Slot, 1, Buffer.GetAddressOf());
break;
case ShaderType::Pixel:
Graphics.DeviceContext->PSSetConstantBuffers(Slot, 1, Buffer.GetAddressOf());
break;
case ShaderType::Vertex:
Graphics.DeviceContext->VSSetConstantBuffers(Slot, 1, Buffer.GetAddressOf());
break;
}
}
template<typename T>
bool ConstantBuffer<T>::Update()
{
//no need to update if the data isn't dirty
if (!Dirty)
return true;
//lock access to the buffer on the GPU
D3D11_MAPPED_SUBRESOURCE mappedResource{};
if (FAILED(Graphics.DeviceContext->Map(Buffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
return false;
//update the buffer
memcpy(mappedResource.pData, &Data, sizeof(T));
//let the GPU play with it again
Graphics.DeviceContext->Unmap(Buffer.Get(), 0);
Dirty = false;
return true;
}
template<typename T>
bool ConstantBuffer<T>::Create()
{
D3D11_BUFFER_DESC desc{};
desc.ByteWidth = sizeof(T);
desc.Usage = D3D11_USAGE::D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_FLAG::D3D11_CPU_ACCESS_WRITE;//Dynamic does not support CPU Read
D3D11_SUBRESOURCE_DATA data{};
data.pSysMem = &Data;
if (FAILED(Graphics.Device->CreateBuffer(&desc, &data, Buffer.ReleaseAndGetAddressOf())))
return false;
return true;
}
} | 25.810345 | 134 | 0.689713 | [
"geometry"
] |
912a4036f4058f367d5fa0f29ecc92c192147059 | 23,947 | hpp | C++ | src/r4/vector.hpp | cppfw/r4 | 55887b638ec316e8d4239c57f2fe744d857fb6d2 | [
"MIT"
] | 1 | 2022-01-31T20:44:07.000Z | 2022-01-31T20:44:07.000Z | src/r4/vector.hpp | cppfw/r4 | 55887b638ec316e8d4239c57f2fe744d857fb6d2 | [
"MIT"
] | 5 | 2021-01-30T13:39:19.000Z | 2022-01-26T11:24:38.000Z | src/r4/vector.hpp | cppfw/r4 | 55887b638ec316e8d4239c57f2fe744d857fb6d2 | [
"MIT"
] | 2 | 2020-12-15T01:51:01.000Z | 2022-01-24T13:15:48.000Z | /*
The MIT License (MIT)
Copyright (c) 2015-2021 igagis
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.
*/
/* ================ LICENSE END ================ */
#pragma once
#include <array>
#include <utki/math.hpp>
#include "quaternion.hpp"
// Under Windows and MSVC compiler there are 'min' and 'max' macros defined for some reason, get rid of them.
#ifdef min
# undef min
#endif
#ifdef max
# undef max
#endif
namespace r4{
template <class T, size_t S> class vector : public std::array<T, S>{
static_assert(S > 0, "vector size template parameter S must be above zero");
typedef std::array<T, S> base_type;
public:
/**
* @brief First vector component.
*/
T& x()noexcept{
return this->operator[](0);
}
/**
* @brief First vector component.
*/
const T& x()const noexcept{
return this->operator[](0);
}
/**
* @brief First vector component.
*/
T& r()noexcept{
return this->operator[](0);
}
/**
* @brief First vector component.
*/
const T& r()const noexcept{
return this->operator[](0);
}
/**
* @brief Second vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 1), E&> y()noexcept{
return this->operator[](1);
}
/**
* @brief Second vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 1), const E&> y()const noexcept{
return this->operator[](1);
}
/**
* @brief Second vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 1), E&> g()noexcept{
return this->operator[](1);
}
/**
* @brief Second vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 1), const E&> g()const noexcept{
return this->operator[](1);
}
/**
* @brief Third vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 2), E&> z()noexcept{
return this->operator[](2);
}
/**
* @brief Third vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 2), const E&> z()const noexcept{
return this->operator[](2);
}
/**
* @brief Third vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 2), E&> b()noexcept{
return this->operator[](2);
}
/**
* @brief Third vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 2), const E&> b()const noexcept{
return this->operator[](2);
}
/**
* @brief Fourth vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 3), E&> w()noexcept{
return this->operator[](3);
}
/**
* @brief Fourth vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 3), const E&> w()const noexcept{
return this->operator[](3);
}
/**
* @brief Fourth vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 3), E&> a()noexcept{
return this->operator[](3);
}
/**
* @brief Fourth vector component.
*/
template <typename E = T>
std::enable_if_t<(S > 3), const E&> a()const noexcept{
return this->operator[](3);
}
/**
* @brief Default constructor.
* Default constructor does not initialize vector components to any values.
*/
constexpr vector() = default;
/**
* @brief Constructor.
* Initializes vector components to given values.
* @param v - parameter pack with initializing values.
*/
template <typename... A, std::enable_if_t<sizeof...(A) == S, bool> = true>
constexpr explicit vector(A... v)noexcept :
base_type{T(v)...}
{
static_assert(sizeof...(v) == S, "number of constructor arguments is not equal to vector size");
}
private:
template <size_t... I>
constexpr vector(std::initializer_list<T> vals, std::index_sequence<I...>)noexcept :
base_type{ *std::next(vals.begin(), I)... }
{}
public:
/**
* @brief Construct initialized vector.
* Creates a vector and initializes its components by the given values.
* @param vals - initializer list of numbers to set as components of the vector.
*/
constexpr vector(std::initializer_list<T> vals) :
vector(
[&vals](){
if(vals.size() == S){
return vals;
}
std::cerr << "wrong number of elements in initializer list of vector(std::initializer_list), expected "
<< S << ", got " << vals.size() << std::endl;
std::abort();
}(),
std::make_index_sequence<S>()
)
{}
/**
* @brief Constructor.
* Initializes all vector components to a given value.
* @param num - value to initialize all vector compone with.
*/
constexpr vector(T num)noexcept{
for(auto& c : *this){
c = num;
}
}
/**
* @brief Constructor.
* Defined only for 4 component vector.
* Initializes first three vector components to the same given value and fourth component to another given value.
* @param num - value to use for initialization of first three vector components.
* @param w - value to use for initialization of fourth vector component.
*/
template <typename E = T> constexpr vector(std::enable_if_t<S == 4, E> num, T w)noexcept{
for(size_t i = 0; i != S - 1; ++i){
this->operator[](i) = num;
}
this->operator[](S - 1) = w;
}
/**
* @brief Constructor.
* Defined only for 3 component vector.
* Initializes components to a given values.
* @param vec - 2d vector to use for initialization of first two vector components.
* @param z - value to use for initialization of 3rd vector component.
*/
template <typename E = T> constexpr vector(const vector<T, 2>& vec, std::enable_if_t<S == 3, E> z = 0)noexcept :
vector(vec.x(), vec.y(), z)
{}
/**
* @brief Constructor.
* Initializes components to a given values.
* @param vec - 4d vector to use for initialization of first two vector components.
*/
template <size_t SS> constexpr vector(const vector<T, SS>& vec)noexcept{
this->operator=(vec);
}
/**
* @brief Constructor.
* Defined only for 4 component vector.
* Initializes components to a given values.
* @param vec - 2d vector to use for initialization of first two vector components.
* @param z - value to use for initialization of 3rd vector component.
* @param w - value to use for initialization of 4th vector component.
*/
template <typename E = T> constexpr vector(const vector<T, 2>& vec, std::enable_if_t<S == 4, E> z = 0, T w = 1)noexcept :
vector(vec.x(), vec.y(), z, w)
{}
/**
* @brief Constructor.
* Defined only for 4 component vector.
* Initializes components to a given values.
* @param vec - 23 vector to use for initialization of first three vector components.
* @param w - value to use for initialization of 4th vector component.
*/
template <typename E = T> constexpr vector(const vector<T, 3>& vec, std::enable_if_t<S == 4, E> w = 1)noexcept :
vector(vec.x(), vec.y(), vec.z(), w)
{}
/**
* @brief Convert to vector with different type of component.
* Convert this vector to a vector whose component type is different from T.
* Components are converted using constructor of target type passing the source
* component as argument of the target type constructor.
* @return converted vector.
*/
template <typename TT> vector<TT, S> to()const noexcept{
vector<TT, S> ret;
for(size_t i = 0; i != S; ++i){
ret[i] = TT(this->operator[](i));
}
return ret;
}
/**
* @brief Assign from another vector.
* TODO:
* @param vec - 2d vector to assign first two components from.
* @return Reference to this vector object.
*/
template <size_t SS> vector& operator=(const vector<T, SS>& vec)noexcept{
if constexpr (SS >= S){
for(size_t i = 0; i != S; ++i){
this->operator[](i) = vec[i];
}
}else if constexpr (S < 4 || SS >= 4){
static_assert(SS < S, "");
size_t i = 0;
for(; i != SS; ++i){
this->operator[](i) = vec[i];
}
for(; i != S; ++i){
this->operator[](i) = T(0);
}
}else{
static_assert(SS < 4, "");
static_assert(S >= 4, "");
size_t i = 0;
for(; i != SS; ++i){
this->operator[](i) = vec[i];
}
for(; i != 4; ++i){
this->operator[](i) = T(0);
}
this->operator[](3) = T(1);
for(; i != S; ++i){
this->operator[](i) = T(0);
}
}
return *this;
}
/**
* @brief Assign a number.
* Sets all 4 components of this vector to a given number.
* @param num - number to use for assignment.
* @return Reference to this vector object.
*/
vector& operator=(T num)noexcept{
this->set(num);
return *this;
}
/**
* @brief Set vector components to given values.
* @param a - parameter pack of values to set the vector to.
* @return Reference to this vector object.
*/
template <typename... A> vector& set(A... a)noexcept{
this->base_type::operator=(base_type{T(a)...});
return *this;
}
/**
* @brief Set all vector components to given value.
* @param val - value to set vector components to.
* @return Reference to this vector object.
*/
vector& set(T val)noexcept{
for(auto& c : *this){
c = val;
}
return *this;
}
/**
* @brief Add and assign.
* TODO:
* @param vec - vector to use for addition.
* @return Reference to this vector object.
*/
template <size_t SS> vector& operator+=(const vector<T, SS>& vec)noexcept{
if constexpr (SS >= S){
for(size_t i = 0; i != S; ++i){
this->operator[](i) += vec[i];
}
}else if constexpr (S < 4 || SS >= 4){
static_assert(SS < S, "");
for(size_t i = 0; i != SS; ++i){
this->operator[](i) += vec[i];
}
}else{
static_assert(SS < 4, "");
static_assert(S >= 4, "");
for(size_t i = 0; i != SS; ++i){
this->operator[](i) += vec[i];
}
this->operator[](3) += T(1);
}
return *this;
}
/**
* @brief Add vector.
* Adds this vector and given vector.
* @param vec - vector to add.
* @return Vector resulting from vector addition.
*/
vector operator+(const vector& vec)const noexcept{
return (vector(*this) += vec);
}
/**
* @brief Subtract and assign.
* Subtracts given vector from this vector and assigns result back to this vector.
* @param vec - vector to subtract.
* @return Reference to this vector object.
*/
template <size_t SS> vector& operator-=(const vector<T, SS>& vec)noexcept{
if constexpr (SS >= S){
for(size_t i = 0; i != S; ++i){
this->operator[](i) -= vec[i];
}
}else if constexpr (S < 4 || SS >= 4){
static_assert(SS < S, "");
for(size_t i = 0; i != SS; ++i){
this->operator[](i) -= vec[i];
}
}else{
static_assert(SS < 4, "");
static_assert(S >= 4, "");
for(size_t i = 0; i != SS; ++i){
this->operator[](i) -= vec[i];
}
this->operator[](3) -= T(1);
}
return *this;
}
/**
* @brief Subtract vector.
* Subtracts given vector from this vector.
* @param vec - vector to subtract.
* @return Vector resulting from vector subtraction.
*/
vector operator-(const vector& vec)const noexcept{
return (vector(*this) -= vec);
}
/**
* @brief Unary minus.
* @return Negated vector.
*/
vector operator-()const noexcept{
return vector(*this).negate();
}
/**
* @brief Multiply by scalar and assign.
* Multiplies this vector by scalar and assigns result back to this vector.
* @param num - scalar to multiply by.
* @return Reference to this vector object.
*/
vector& operator*=(T num)noexcept{
for(auto& c : *this){
c *= num;
}
return *this;
}
/**
* @brief Multiply by scalar.
* Multiplies this vector by scalar.
* @param num - scalar to multiply by.
* @return Vector resulting from multiplication of this vector by scalar.
*/
vector operator*(T num)const noexcept{
return (vector(*this) *= num);
}
/**
* @brief Divide by scalar.
* Divides this vector by scalar.
* @param num - scalar to divide by.
* @return Vector resulting from division of this vector by scalar.
*/
vector operator/(T num)const noexcept{
return vector(*this) /= num;
}
/**
* @brief Multiply scalar by vector.
* @param num - scalar to multiply.
* @param vec - vector to multiply by.
* @return Vector resulting from multiplication of given scalar by given vector.
*/
friend vector operator*(T num, const vector& vec)noexcept{
return vec * num;
}
/**
* @brief Divide by scalar and assign.
* Divide this vector by scalar and assign result back to this vector.
* @param num - scalar to divide by.
* @return Reference to this vector object.
*/
vector& operator/=(T num)noexcept{
ASSERT_INFO(num != 0, "vector::operator/=(): division by 0")
for(auto& c : *this){
c /= num;
}
return *this;
}
/**
* @brief Divide by scalar.
* Divide this vector by scalar.
* @param num - scalar to divide by.
* @return Vector resulting from division of this vector by scalars.
*/
vector operator/(T num)noexcept{
ASSERT_INFO(num != 0, "vector::operator/(): division by 0")
return (vector(*this) /= num);
}
/**
* @brief Dot product.
* @param vec -vector to multiply by.
* @return Dot product of this vector and given vector.
*/
T operator*(const vector& vec)const noexcept{
T res = 0;
for(size_t i = 0; i != S; ++i){
res += this->operator[](i) * vec[i];
}
return res;
}
/**
* @brief Cross product.
* First three components of the resulting 4d vector is a result of cross
* product between two 3d vectors formed from first 3 components of initial 4d vectors.
* The forth component is a simple multiplication of 4th components of initial vectors.
* @param vec - vector to multiply by.
* @return Four-dimensional vector resulting from the cross product.
*/
template <typename E = vector> std::enable_if_t<S >= 3, E> operator%(const vector& vec)const noexcept{
static_assert(S >= 3, "cross product makes no sense for vectors with less than 3 components");
if constexpr (S == 3){
return vector{
this->y() * vec.z() - this->z() * vec.y(),
this->z() * vec.x() - this->x() * vec.z(),
this->x() * vec.y() - this->y() * vec.x()
};
}else{
return vector{
this->y() * vec.z() - this->z() * vec.y(),
this->z() * vec.x() - this->x() * vec.z(),
this->x() * vec.y() - this->y() * vec.x(),
this->w() * vec.w()
};
}
}
/**
* @brief Component-wise multiplication.
* Performs component-wise multiplication of two vectors.
* The result of such operation is also a vector.
* @param vec - vector to multiply by.
* @return Vector resulting from component-wise multiplication.
*/
vector comp_mul(const vector& vec)const noexcept{
vector res;
for(size_t i = 0; i != S; ++i){
res[i] = this->operator[](i) * vec[i];
}
return res;
}
/**
* @brief Component-wise multiplication.
* Performs component-wise multiplication of this vector by given vector.
* The result of such operation is also a vector and is stored in this vector.
* @param vec - vector to multiply by.
* @return reference to this vector.
*/
vector& comp_multiply(const vector& vec)noexcept{
for(size_t i = 0; i != S; ++i){
this->operator[](i) *= vec[i];
}
return *this;
}
/**
* @brief Component-wise division.
* Performs component-wise division of two vectors.
* Resulting vector is (x1 / x2, y1 / y2, z1 / z2, w1 / w2).
* The result of such operation is also vector.
* @param v - vector to divide by.
* @return Vector resulting from component-wise division.
*/
vector comp_div(const vector& v)const noexcept{
vector res;
for(size_t i = 0; i != S; ++i){
res[i] = this->operator[](i) / v[i];
}
return res;
}
/**
* @brief Component-wise division.
* Performs component-wise division of this vector by another given vector.
* See comp_div() for details.
* @param v - vector to divide by.
* @return reference to this vector instance.
*/
vector& comp_divide(const vector& v)noexcept{
for(size_t i = 0; i != S; ++i){
this->operator[](i) /= v[i];
}
return *this;
}
/**
* @brief Negate this vector.
* Negates this vector.
* @return Reference to this vector object.
*/
vector& negate()noexcept{
for(auto& c : *this){
c = -c;
}
return *this;
}
/**
* @brief Calculate power 2 of vector norm.
* @return Power 2 of this vector norm.
*/
T norm_pow2()const noexcept{
T res = 0;
for(size_t i = 0; i != S; ++i){
res += utki::pow2(this->operator[](i));
}
return res;
}
/**
* @brief Calculate vector norm.
* @return Vector norm.
*/
T norm()const noexcept{
return sqrt(this->norm_pow2());
}
/**
* @brief Normalize this vector.
* Normalizes this vector.
* If norm is 0 then the result is vector (1, 0, 0, 0).
* @return Reference to this vector object.
*/
vector& normalize()noexcept{
T mag = this->norm();
if(mag == 0){
this->x() = 1;
for(auto i = std::next(this->begin()); i != this->end(); ++i){
*i = T(0);
}
return *this;
}
return (*this) /= this->norm();
}
/**
* @brief Calculate normalized vector.
* @return normalized vector.
*/
vector normed()const noexcept{
return vector(*this).normalize();
}
/**
* @brief Rotate vector.
* Defined only for 2 component vector.
* Rotate this vector around (0, 0, 1) axis. Direction of the rotation is
* determined by right-hand rule. I.e. positive angle rotation is from X-axis to Y-axis.
* @param angle - angle of rotation in radians.
* @return Reference to this vector object.
*/
template <typename E = T> vector& rotate(std::enable_if_t<S == 2, E> angle)noexcept{
using std::sin;
using std::cos;
T cosa = cos(angle);
T sina = sin(angle);
T tmp = this->x() * cosa - this->y() * sina;
this->y() = this->y() * cosa + this->x() * sina;
this->x() = tmp;
return *this;
}
/**
* @brief Rotation of vector.
* Defined only for 2 component vector.
* Calculate vector resulting from rotation of this vector around (0, 0, 1) axis.
* Direction of the rotation is determined by right-hand rule.
* @param angle - angle of rotation in radians.
* @return Vector resulting from rotation of this vector.
*/
template <typename E = T> vector rot(std::enable_if_t<S == 2, E> angle)const noexcept{
return vector(*this).rotate(angle);
}
/**
* @brief Round vector components.
* @param v - vector to round.
* @return rounded vector.
*/
friend vector round(const vector& v)noexcept{
using std::round;
vector ret;
for(size_t i = 0; i != S; ++i){
ret[i] = round(v[i]);
}
return ret;
}
/**
* @brief Ceil vector components.
* @param v - vector to ceil.
* @return ceiled vector.
*/
friend vector ceil(const vector& v)noexcept{
using std::ceil;
vector ret;
for(size_t i = 0; i != S; ++i){
ret[i] = ceil(v[i]);
}
return ret;
}
/**
* @brief Floor vector components.
* @param v - vector to floor.
* @return floored vector.
*/
friend vector floor(const vector& v)noexcept{
using std::floor;
vector ret;
for(size_t i = 0; i != S; ++i){
ret[i] = floor(v[i]);
}
return ret;
}
/**
* @brief Snap each vector component to 0.
* For each component, set it to 0 if its absolute value does not exceed the given threshold.
* @param threshold - the snapping threshold.
* @return reference to this vector.
*/
vector& snap_to_zero(T threshold)noexcept{
for(auto& c : *this){
using std::abs;
if(abs(c) <= threshold){
c = 0;
}
}
return *this;
}
/**
* @brief Check if all vector components are zero.
* @return true if all vector components are zero.
* @return false otherwise.
*/
bool is_zero()const noexcept{
for(auto& c : *this){
if(c != 0){
return false;
}
}
return true;
}
/**
* @brief Check if all vector components are not zero.
* @return true if all vector components are not zero.
* @return false otherwise.
*/
bool is_not_zero()const noexcept{
for(auto& c : *this){
if(c == 0){
return false;
}
}
return true;
}
/**
* @brief Check if all vector components are positive or zero.
* @return true if all vector components are positive or zero.
* @return false otherwise.
*/
bool is_positive_or_zero()const noexcept{
for(auto& c : *this){
if(c < 0){
return false;
}
}
return true;
}
/**
* @brief Check if all vector components are positive.
* @return true if all vector components are positive.
* @return false otherwise.
*/
bool is_positive()const noexcept{
for(auto& c : *this){
if(c <= 0){
return false;
}
}
return true;
}
/**
* @brief Check if all vector components are negative.
* @return true if all vector components are negative.
* @return false otherwise.
*/
bool is_negative()const noexcept{
for(auto& c : *this){
if(c >= 0){
return false;
}
}
return true;
}
/**
* @brief Absolute vector value.
* @param v - vector to take absolute value of.
* @return vector holding absolute values of this vector's components.
*/
friend vector abs(const vector& v)noexcept{
using std::abs;
vector ret;
for(size_t i = 0; i != S; ++i){
ret[i] = abs(v[i]);
}
return ret;
}
/**
* @brief Project this vector onto a given vector.
* @param vec - vector to project onto, it does not have to be normalized.
* @return Reference to this vector object.
*/
vector& project(const vector& vec)noexcept{
ASSERT(this->norm_pow2() != 0)
(*this) = vec * (vec * (*this)) / vec.norm_pow2();
return *this;
}
/**
* @brief Rotate this vector.
* Rotate this vector with unit quaternion.
* @param q - quaternion which defines the rotation.
* @return Reference to this vector object.
*/
template <typename E = T> vector& rotate(const quaternion<std::enable_if_t<S == 3 || S == 4, E>>& q)noexcept;
/**
* @brief Get component-wise minimum of two vectors.
* @param va - first vector.
* @param vb - second vector.
* @return vector whose components are component-wise minimum of initial vectors.
*/
friend vector min(const vector& va, const vector& vb)noexcept{
using std::min;
vector ret;
for(size_t i = 0; i != S; ++i){
ret[i] = min(va[i], vb[i]);
}
return ret;
}
/**
* @brief Get component-wise maximum of two vectors.
* @param va - first vector.
* @param vb - second vector.
* @return vector whose components are component-wise maximum of initial vectors.
*/
friend vector max(const vector& va, const vector& vb)noexcept{
using std::max;
vector ret;
for(size_t i = 0; i != S; ++i){
ret[i] = max(va[i], vb[i]);
}
return ret;
}
friend std::ostream& operator<<(std::ostream& s, const vector<T, S>& vec){
static_assert(S >= 1, "");
s << vec.x();
for(auto i = std::next(vec.begin()); i != vec.end(); ++i){
s << " " << (*i);
}
return s;
}
};
template <typename TT> using vector2 = vector<TT, 2>;
template <typename TT> using vector3 = vector<TT, 3>;
template <typename TT> using vector4 = vector<TT, 4>;
static_assert(sizeof(vector<float, 4>) == sizeof(float) * 4, "size mismatch");
static_assert(sizeof(vector<double, 4>) == sizeof(double) * 4, "size mismatch");
}
#include "matrix.hpp"
namespace r4{
template <class T, size_t S>
template <typename E>
vector<T, S>& vector<T, S>::rotate(const quaternion<std::enable_if_t<S == 3 || S == 4, E>>& q)noexcept{
*this = q.template to_matrix<S>() * (*this);
return *this;
}
}
| 25.694206 | 122 | 0.632188 | [
"object",
"vector",
"3d"
] |
912da20c5f23fdb55c34a3258e1747395287f042 | 4,435 | cpp | C++ | velox/dwio/dwrf/test/RatioTrackerTest.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | 672 | 2021-09-22T16:45:58.000Z | 2022-03-31T13:42:31.000Z | velox/dwio/dwrf/test/RatioTrackerTest.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | 986 | 2021-09-22T17:02:52.000Z | 2022-03-31T23:57:25.000Z | velox/dwio/dwrf/test/RatioTrackerTest.cpp | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | 178 | 2021-09-22T17:27:47.000Z | 2022-03-31T03:18:37.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <memory>
#include "velox/dwio/dwrf/writer/RatioTracker.h"
using namespace ::testing;
namespace facebook::velox::dwrf {
TEST(RatioTrackerTest, BasicTests) {
struct TestCase {
explicit TestCase(
std::shared_ptr<RatioTracker> tracker,
const std::vector<std::pair<size_t, size_t>>& samples,
float finalResult)
: tracker{std::move(tracker)},
samples{samples},
finalResult{finalResult} {}
std::shared_ptr<RatioTracker> tracker;
const std::vector<std::pair<size_t, size_t>> samples;
const float finalResult;
};
std::vector<TestCase> testCases{
TestCase{std::make_shared<RatioTracker>(0.1f), {}, 0.1f},
TestCase{std::make_shared<RatioTracker>(0.3f), {}, 0.3f},
TestCase{std::make_shared<RatioTracker>(0.3f), {{10, 3}}, 0.3f},
TestCase{std::make_shared<RatioTracker>(0.3f), {{10, 5}}, 0.5f},
TestCase{std::make_shared<RatioTracker>(0.3f), {{10, 5}, {0, 10}}, 0.5f},
TestCase{
std::make_shared<RatioTracker>(0.3f),
{{10, 5}, {20, 10}, {10, 10}, {30, 10}},
0.5f},
TestCase{
std::make_shared<RatioTracker>(0.3f),
{{10, 11}, {20, 1}, {30, 1}, {40, 1}, {50, 1}},
0.1f},
TestCase{std::make_shared<CompressionRatioTracker>(), {}, 0.3f},
TestCase{std::make_shared<FlushOverheadRatioTracker>(), {}, 1.0f},
TestCase{std::make_shared<AverageRowSizeTracker>(), {}, 0.0f},
};
for (auto& testCase : testCases) {
auto sampleSize = 0;
for (const auto& sample : testCase.samples) {
sampleSize += (sample.first ? 1 : 0);
testCase.tracker->takeSample(sample.first, sample.second);
}
// Can consider EXPECT_NEAR if we have a specific bound.
EXPECT_FLOAT_EQ(
testCase.finalResult, testCase.tracker->getEstimatedRatio());
EXPECT_EQ(sampleSize, testCase.tracker->getSampleSize());
}
}
TEST(RatioTrackerTest, EmptyInputTests) {
struct TestCase {
explicit TestCase(
std::shared_ptr<RatioTracker> tracker,
const std::pair<size_t, size_t>& input,
bool isEmptyInput)
: tracker{std::move(tracker)},
input{input},
isEmptyInput{isEmptyInput} {}
std::shared_ptr<RatioTracker> tracker;
const std::pair<size_t, size_t> input;
const bool isEmptyInput;
};
std::vector<TestCase> testCases{
TestCase{std::make_shared<RatioTracker>(0.2f), {6, 3}, false},
TestCase{std::make_shared<RatioTracker>(0.2f), {6, 0}, false},
TestCase{std::make_shared<RatioTracker>(0.2f), {0, 0}, true},
TestCase{std::make_shared<RatioTracker>(0.2f), {0, 3}, true},
TestCase{std::make_shared<FlushOverheadRatioTracker>(), {6, 3}, false},
TestCase{std::make_shared<FlushOverheadRatioTracker>(), {6, 0}, false},
TestCase{std::make_shared<FlushOverheadRatioTracker>(), {0, 0}, true},
TestCase{std::make_shared<FlushOverheadRatioTracker>(), {0, 3}, true},
TestCase{std::make_shared<AverageRowSizeTracker>(), {6, 3}, false},
TestCase{std::make_shared<AverageRowSizeTracker>(), {6, 0}, false},
TestCase{std::make_shared<AverageRowSizeTracker>(), {0, 0}, true},
TestCase{std::make_shared<AverageRowSizeTracker>(), {0, 3}, true},
TestCase{std::make_shared<CompressionRatioTracker>(), {6, 3}, false},
TestCase{std::make_shared<CompressionRatioTracker>(), {6, 0}, true},
TestCase{std::make_shared<CompressionRatioTracker>(), {0, 0}, true},
TestCase{std::make_shared<CompressionRatioTracker>(), {0, 3}, true},
};
for (auto& testCase : testCases) {
EXPECT_EQ(
testCase.isEmptyInput,
testCase.tracker->isEmptyInput(
testCase.input.first, testCase.input.second));
}
}
} // namespace facebook::velox::dwrf
| 38.232759 | 79 | 0.65389 | [
"vector"
] |
91308da672ce530e776635e87f85556e432fded6 | 1,994 | cpp | C++ | Arrangement_on_surface_2/demo/Arrangement_on_surface_2/Callback.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Arrangement_on_surface_2/demo/Arrangement_on_surface_2/Callback.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Arrangement_on_surface_2/demo/Arrangement_on_surface_2/Callback.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z | // Copyright (c) 2012, 2020 Tel-Aviv University (Israel).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s): Alex Tsui <alextsui05@gmail.com>
// Ahmed Essam <theartful.ae@gmail.com>
#include "Callback.h"
#include <QEvent>
#include <QKeyEvent>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
namespace CGAL {
namespace Qt {
Callback::Callback(QObject* parent, QGraphicsScene* scene_) :
QObject(parent), GraphicsSceneMixin(scene_) { }
void Callback::reset( ) { }
bool Callback::eventFilter( QObject* object, QEvent* event )
{
if ( event->type( ) == QEvent::GraphicsSceneMouseMove )
{
QGraphicsSceneMouseEvent* mouseEvent =
static_cast< QGraphicsSceneMouseEvent* >( event );
this->mouseMoveEvent( mouseEvent );
return true;
}
else if ( event->type( ) == QEvent::GraphicsSceneMousePress )
{
QGraphicsSceneMouseEvent* mouseEvent =
static_cast< QGraphicsSceneMouseEvent* >( event );
this->mousePressEvent( mouseEvent );
return true;
}
else if ( event->type( ) == QEvent::GraphicsSceneMouseRelease )
{
QGraphicsSceneMouseEvent* mouseEvent =
static_cast< QGraphicsSceneMouseEvent* >( event );
this->mouseReleaseEvent( mouseEvent );
return true;
}
else if ( event->type( ) == QEvent::KeyPress )
{
QKeyEvent* keyEvent = static_cast< QKeyEvent* >( event );
this->keyPressEvent( keyEvent );
return true;
}
return QObject::eventFilter( object, event );
}
void Callback::mousePressEvent(QGraphicsSceneMouseEvent* /* event */) { }
void Callback::mouseMoveEvent(QGraphicsSceneMouseEvent* /* event */) { }
void Callback::mouseReleaseEvent(QGraphicsSceneMouseEvent* /* event */) { }
void Callback::keyPressEvent(QKeyEvent* /* event */) { }
void Callback::slotModelChanged( ) { }
} // namespace Qt
} // namespace CGAL
| 27.315068 | 77 | 0.687563 | [
"object"
] |
913286b32a66ecb4dd4a23d0d1b32ad9cddfa949 | 35,726 | cpp | C++ | SU2-Quantum/SU2_CFD/src/numerics/flow/convection/roe.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/src/numerics/flow/convection/roe.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/src/numerics/flow/convection/roe.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | 1 | 2021-12-03T06:40:08.000Z | 2021-12-03T06:40:08.000Z | /*!
* \file roe.cpp
* \brief Implementations of Roe-type schemes.
* \author F. Palacios, T. Economon
* \version 7.0.6 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 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.
*
* SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../../../../include/numerics/flow/convection/roe.hpp"
CUpwRoeBase_Flow::CUpwRoeBase_Flow(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config,
bool val_low_dissipation) : CNumerics(val_nDim, val_nVar, config) {
implicit = (config->GetKind_TimeIntScheme_Flow() == EULER_IMPLICIT);
/* A grid is defined as dynamic if there's rigid grid movement or grid deformation AND the problem is time domain */
dynamic_grid = config->GetDynamic_Grid();
kappa = config->GetRoe_Kappa(); // 1 is unstable
Gamma = config->GetGamma();
Gamma_Minus_One = Gamma - 1.0;
roe_low_dissipation = val_low_dissipation;
Flux = new su2double [nVar];
Diff_U = new su2double [nVar];
ProjFlux_i = new su2double [nVar];
ProjFlux_j = new su2double [nVar];
Conservatives_i = new su2double [nVar];
Conservatives_j = new su2double [nVar];
Lambda = new su2double [nVar];
P_Tensor = new su2double* [nVar];
invP_Tensor = new su2double* [nVar];
Jacobian_i = new su2double* [nVar];
Jacobian_j = new su2double* [nVar];
for (unsigned short iVar = 0; iVar < nVar; iVar++) {
P_Tensor[iVar] = new su2double [nVar];
invP_Tensor[iVar] = new su2double [nVar];
Jacobian_i[iVar] = new su2double [nVar];
Jacobian_j[iVar] = new su2double [nVar];
}
}
CUpwRoeBase_Flow::~CUpwRoeBase_Flow(void) {
delete [] Flux;
delete [] Diff_U;
delete [] ProjFlux_i;
delete [] ProjFlux_j;
delete [] Conservatives_i;
delete [] Conservatives_j;
delete [] Lambda;
for (unsigned short iVar = 0; iVar < nVar; iVar++) {
delete [] P_Tensor[iVar];
delete [] invP_Tensor[iVar];
delete [] Jacobian_i[iVar];
delete [] Jacobian_j[iVar];
}
delete [] P_Tensor;
delete [] invP_Tensor;
delete [] Jacobian_i;
delete [] Jacobian_j;
}
void CUpwRoeBase_Flow::FinalizeResidual(su2double *val_residual, su2double **val_Jacobian_i,
su2double **val_Jacobian_j, const CConfig* config) {
/*---
CUpwRoeBase_Flow::ComputeResidual initializes the residual (flux) and its Jacobians with the standard Roe averaging
fc_{1/2} = kappa*(fc_i+fc_j)*Normal. It then calls this method, which derived classes specialize, to account for
the dissipation part.
---*/
}
CNumerics::ResidualType<> CUpwRoeBase_Flow::ComputeResidual(const CConfig* config) {
implicit = (config->GetKind_TimeIntScheme() == EULER_IMPLICIT);
unsigned short iVar, jVar, iDim;
su2double ProjGridVel = 0.0, Energy_i, Energy_j;
AD::StartPreacc();
AD::SetPreaccIn(V_i, nDim+4); AD::SetPreaccIn(V_j, nDim+4); AD::SetPreaccIn(Normal, nDim);
if (dynamic_grid) {
AD::SetPreaccIn(GridVel_i, nDim); AD::SetPreaccIn(GridVel_j, nDim);
}
if (roe_low_dissipation){
AD::SetPreaccIn(Sensor_i); AD::SetPreaccIn(Sensor_j);
AD::SetPreaccIn(Dissipation_i); AD::SetPreaccIn(Dissipation_j);
}
/*--- Face area (norm or the normal vector) and unit normal ---*/
Area = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
Area += Normal[iDim]*Normal[iDim];
Area = sqrt(Area);
for (iDim = 0; iDim < nDim; iDim++)
UnitNormal[iDim] = Normal[iDim]/Area;
/*--- Primitive variables at point i ---*/
for (iDim = 0; iDim < nDim; iDim++)
Velocity_i[iDim] = V_i[iDim+1];
Pressure_i = V_i[nDim+1];
Density_i = V_i[nDim+2];
Enthalpy_i = V_i[nDim+3];
Energy_i = Enthalpy_i - Pressure_i/Density_i;
/*--- Primitive variables at point j ---*/
for (iDim = 0; iDim < nDim; iDim++)
Velocity_j[iDim] = V_j[iDim+1];
Pressure_j = V_j[nDim+1];
Density_j = V_j[nDim+2];
Enthalpy_j = V_j[nDim+3];
Energy_j = Enthalpy_j - Pressure_j/Density_j;
/*--- Compute variables that are common to the derived schemes ---*/
/*--- Roe-averaged variables at interface between i & j ---*/
su2double R = sqrt(fabs(Density_j/Density_i));
RoeDensity = R*Density_i;
su2double sq_vel = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
RoeVelocity[iDim] = (R*Velocity_j[iDim]+Velocity_i[iDim])/(R+1);
sq_vel += RoeVelocity[iDim]*RoeVelocity[iDim];
}
RoeEnthalpy = (R*Enthalpy_j+Enthalpy_i)/(R+1);
RoeSoundSpeed2 = (Gamma-1)*(RoeEnthalpy-0.5*sq_vel);
/*--- Negative RoeSoundSpeed^2, the jump variables is too large, clear fluxes and exit. ---*/
if (RoeSoundSpeed2 <= 0.0) {
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] = 0.0;
if (implicit){
for (jVar = 0; jVar < nVar; jVar++) {
Jacobian_i[iVar][jVar] = 0.0;
Jacobian_j[iVar][jVar] = 0.0;
}
}
}
AD::SetPreaccOut(Flux, nVar);
AD::EndPreacc();
return ResidualType<>(Flux, Jacobian_i, Jacobian_j);
}
RoeSoundSpeed = sqrt(RoeSoundSpeed2);
/*--- P tensor ---*/
GetPMatrix(&RoeDensity, RoeVelocity, &RoeSoundSpeed, UnitNormal, P_Tensor);
/*--- Projected velocity adjusted for mesh motion ---*/
ProjVelocity = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
ProjVelocity += RoeVelocity[iDim]*UnitNormal[iDim];
if (dynamic_grid) {
for (iDim = 0; iDim < nDim; iDim++)
ProjGridVel += 0.5*(GridVel_i[iDim]+GridVel_j[iDim])*UnitNormal[iDim];
ProjVelocity -= ProjGridVel;
}
/*--- Flow eigenvalues ---*/
for (iDim = 0; iDim < nDim; iDim++)
Lambda[iDim] = ProjVelocity;
Lambda[nVar-2] = ProjVelocity + RoeSoundSpeed;
Lambda[nVar-1] = ProjVelocity - RoeSoundSpeed;
/*--- Apply Mavriplis' entropy correction to eigenvalues ---*/
su2double MaxLambda = fabs(ProjVelocity) + RoeSoundSpeed;
for (iVar = 0; iVar < nVar; iVar++)
Lambda[iVar] = max(fabs(Lambda[iVar]), config->GetEntropyFix_Coeff()*MaxLambda);
/*--- Reconstruct conservative variables ---*/
Conservatives_i[0] = Density_i;
Conservatives_j[0] = Density_j;
for (iDim = 0; iDim < nDim; iDim++) {
Conservatives_i[iDim+1] = Density_i*Velocity_i[iDim];
Conservatives_j[iDim+1] = Density_j*Velocity_j[iDim];
}
Conservatives_i[nDim+1] = Density_i*Energy_i;
Conservatives_j[nDim+1] = Density_j*Energy_j;
/*--- Compute left and right fluxes ---*/
GetInviscidProjFlux(&Density_i, Velocity_i, &Pressure_i, &Enthalpy_i, Normal, ProjFlux_i);
GetInviscidProjFlux(&Density_j, Velocity_j, &Pressure_j, &Enthalpy_j, Normal, ProjFlux_j);
/*--- Initialize residual (flux) and Jacobians ---*/
for (iVar = 0; iVar < nVar; iVar++)
Flux[iVar] = kappa*(ProjFlux_i[iVar]+ProjFlux_j[iVar]);
if (implicit) {
GetInviscidProjJac(Velocity_i, &Energy_i, Normal, kappa, Jacobian_i);
GetInviscidProjJac(Velocity_j, &Energy_j, Normal, kappa, Jacobian_j);
}
/*--- Finalize in children class ---*/
FinalizeResidual(Flux, Jacobian_i, Jacobian_j, config);
/*--- Correct for grid motion ---*/
if (dynamic_grid) {
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] -= ProjGridVel*Area * 0.5*(Conservatives_i[iVar]+Conservatives_j[iVar]);
if (implicit) {
Jacobian_i[iVar][iVar] -= 0.5*ProjGridVel*Area;
Jacobian_j[iVar][iVar] -= 0.5*ProjGridVel*Area;
}
}
}
AD::SetPreaccOut(Flux, nVar);
AD::EndPreacc();
return ResidualType<>(Flux, Jacobian_i, Jacobian_j);
}
CUpwRoe_Flow::CUpwRoe_Flow(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config,
bool val_low_dissipation) : CUpwRoeBase_Flow(val_nDim, val_nVar, config, val_low_dissipation) {}
void CUpwRoe_Flow::FinalizeResidual(su2double *val_residual, su2double **val_Jacobian_i,
su2double **val_Jacobian_j, const CConfig* config) {
unsigned short iVar, jVar, kVar;
/*--- Compute inverse P tensor ---*/
GetPMatrix_inv(&RoeDensity, RoeVelocity, &RoeSoundSpeed, UnitNormal, invP_Tensor);
/*--- Diference between conservative variables at jPoint and iPoint ---*/
for (iVar = 0; iVar < nVar; iVar++)
Diff_U[iVar] = Conservatives_j[iVar]-Conservatives_i[iVar];
/*--- Low dissipation formulation ---*/
if (roe_low_dissipation)
Dissipation_ij = GetRoe_Dissipation(Dissipation_i, Dissipation_j, Sensor_i, Sensor_j, config);
else
Dissipation_ij = 1.0;
/*--- Standard Roe "dissipation" ---*/
for (iVar = 0; iVar < nVar; iVar++) {
for (jVar = 0; jVar < nVar; jVar++) {
/*--- Compute |Proj_ModJac_Tensor| = P x |Lambda| x inverse P ---*/
su2double Proj_ModJac_Tensor_ij = 0.0;
for (kVar = 0; kVar < nVar; kVar++)
Proj_ModJac_Tensor_ij += P_Tensor[iVar][kVar]*Lambda[kVar]*invP_Tensor[kVar][jVar];
/*--- Update residual and Jacobians ---*/
val_residual[iVar] -= (1.0-kappa)*Proj_ModJac_Tensor_ij*Diff_U[jVar]*Area*Dissipation_ij;
if(implicit){
val_Jacobian_i[iVar][jVar] += (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
val_Jacobian_j[iVar][jVar] -= (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
}
}
}
}
CUpwL2Roe_Flow::CUpwL2Roe_Flow(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config) :
CUpwRoeBase_Flow(val_nDim, val_nVar, config, false) {}
void CUpwL2Roe_Flow::FinalizeResidual(su2double *val_residual, su2double **val_Jacobian_i,
su2double **val_Jacobian_j, const CConfig* config) {
/*--- L2Roe: a low dissipation version of Roe's approximate Riemann solver for low Mach numbers. IJNMF 2015 ---*/
unsigned short iVar, jVar, kVar, iDim;
/*--- Clamped Mach number ---*/
su2double M_i = 0.0, M_j = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
M_i += Velocity_i[iDim]*Velocity_i[iDim];
M_j += Velocity_j[iDim]*Velocity_j[iDim];
}
M_i = sqrt(M_i / fabs(Pressure_i*Gamma/Density_i));
M_j = sqrt(M_j / fabs(Pressure_j*Gamma/Density_j));
su2double zeta = max(0.05,min(max(M_i,M_j),1.0));
/*--- Compute wave amplitudes (characteristics) ---*/
su2double proj_delta_vel = 0.0, delta_vel[3];
for (iDim = 0; iDim < nDim; iDim++) {
delta_vel[iDim] = Velocity_j[iDim] - Velocity_i[iDim];
proj_delta_vel += delta_vel[iDim]*UnitNormal[iDim];
}
proj_delta_vel *= zeta;
su2double delta_p = Pressure_j - Pressure_i;
su2double delta_rho = Density_j - Density_i;
su2double delta_wave[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
if (nDim == 2) {
delta_wave[0] = delta_rho - delta_p/RoeSoundSpeed2;
delta_wave[1] = (UnitNormal[1]*delta_vel[0]-UnitNormal[0]*delta_vel[1])*zeta;
delta_wave[2] = proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
delta_wave[3] = -proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
} else {
delta_wave[0] = delta_rho - delta_p/RoeSoundSpeed2;
delta_wave[1] = (UnitNormal[0]*delta_vel[2]-UnitNormal[2]*delta_vel[0])*zeta;
delta_wave[2] = (UnitNormal[1]*delta_vel[0]-UnitNormal[0]*delta_vel[1])*zeta;
delta_wave[3] = proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
delta_wave[4] = -proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
}
/*--- Update residual ---*/
for (iVar = 0; iVar < nVar; iVar++)
for (kVar = 0; kVar < nVar; kVar++)
val_residual[iVar] -= (1.0-kappa)*Lambda[kVar]*delta_wave[kVar]*P_Tensor[iVar][kVar]*Area;
if (!implicit) return;
/*--- If implicit use the Jacobians of the standard Roe scheme as an approximation ---*/
GetPMatrix_inv(&RoeDensity, RoeVelocity, &RoeSoundSpeed, UnitNormal, invP_Tensor);
for (iVar = 0; iVar < nVar; iVar++) {
for (jVar = 0; jVar < nVar; jVar++) {
/*--- Compute |Proj_ModJac_Tensor| = P x |Lambda| x inverse P ---*/
su2double Proj_ModJac_Tensor_ij = 0.0;
for (kVar = 0; kVar < nVar; kVar++)
Proj_ModJac_Tensor_ij += P_Tensor[iVar][kVar]*Lambda[kVar]*invP_Tensor[kVar][jVar];
val_Jacobian_i[iVar][jVar] += (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
val_Jacobian_j[iVar][jVar] -= (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
}
}
}
CUpwLMRoe_Flow::CUpwLMRoe_Flow(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config) :
CUpwRoeBase_Flow(val_nDim, val_nVar, config, false) {}
void CUpwLMRoe_Flow::FinalizeResidual(su2double *val_residual, su2double **val_Jacobian_i,
su2double **val_Jacobian_j, const CConfig* config) {
/*--- Rieper, A low-Mach number fix for Roe's approximate Riemman Solver, JCP 2011 ---*/
unsigned short iVar, jVar, kVar, iDim;
/*--- Clamped Mach number ---*/
su2double M_i = 0.0, M_j = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
M_i += Velocity_i[iDim]*Velocity_i[iDim];
M_j += Velocity_j[iDim]*Velocity_j[iDim];
}
M_i = sqrt(M_i / fabs(Pressure_i*Gamma/Density_i));
M_j = sqrt(M_j / fabs(Pressure_j*Gamma/Density_j));
su2double zeta = max(0.05,min(max(M_i,M_j),1.0));
/*--- Compute wave amplitudes (characteristics) ---*/
su2double proj_delta_vel = 0.0, delta_vel[3];
for (iDim = 0; iDim < nDim; iDim++) {
delta_vel[iDim] = Velocity_j[iDim] - Velocity_i[iDim];
proj_delta_vel += delta_vel[iDim]*UnitNormal[iDim];
}
proj_delta_vel *= zeta;
su2double delta_p = Pressure_j - Pressure_i;
su2double delta_rho = Density_j - Density_i;
su2double delta_wave[5] = {0.0, 0.0, 0.0, 0.0, 0.0};
if (nDim == 2) {
delta_wave[0] = delta_rho - delta_p/RoeSoundSpeed2;
delta_wave[1] = (UnitNormal[1]*delta_vel[0]-UnitNormal[0]*delta_vel[1]);
delta_wave[2] = proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
delta_wave[3] = -proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
} else {
delta_wave[0] = delta_rho - delta_p/RoeSoundSpeed2;
delta_wave[1] = (UnitNormal[0]*delta_vel[2]-UnitNormal[2]*delta_vel[0]);
delta_wave[2] = (UnitNormal[1]*delta_vel[0]-UnitNormal[0]*delta_vel[1]);
delta_wave[3] = proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
delta_wave[4] = -proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
}
/*--- Update residual ---*/
for (iVar = 0; iVar < nVar; iVar++)
for (kVar = 0; kVar < nVar; kVar++)
val_residual[iVar] -= (1.0-kappa)*Lambda[kVar]*delta_wave[kVar]*P_Tensor[iVar][kVar]*Area;
if (!implicit) return;
/*--- If implicit use the Jacobians of the standard Roe scheme as an approximation ---*/
GetPMatrix_inv(&RoeDensity, RoeVelocity, &RoeSoundSpeed, UnitNormal, invP_Tensor);
for (iVar = 0; iVar < nVar; iVar++) {
for (jVar = 0; jVar < nVar; jVar++) {
/*--- Compute |Proj_ModJac_Tensor| = P x |Lambda| x inverse P ---*/
su2double Proj_ModJac_Tensor_ij = 0.0;
for (kVar = 0; kVar < nVar; kVar++)
Proj_ModJac_Tensor_ij += P_Tensor[iVar][kVar]*Lambda[kVar]*invP_Tensor[kVar][jVar];
val_Jacobian_i[iVar][jVar] += (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
val_Jacobian_j[iVar][jVar] -= (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
}
}
}
CUpwTurkel_Flow::CUpwTurkel_Flow(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config) : CNumerics(val_nDim, val_nVar, config) {
implicit = (config->GetKind_TimeIntScheme_Flow() == EULER_IMPLICIT);
/* A grid is defined as dynamic if there's rigid grid movement or grid deformation AND the problem is time domain */
dynamic_grid = config->GetDynamic_Grid();
Gamma = config->GetGamma();
Gamma_Minus_One = Gamma - 1.0;
Beta_min = config->GetminTurkelBeta();
Beta_max = config->GetmaxTurkelBeta();
Flux = new su2double [nVar];
Diff_U = new su2double [nVar];
Velocity_i = new su2double [nDim];
Velocity_j = new su2double [nDim];
RoeVelocity = new su2double [nDim];
ProjFlux_i = new su2double [nVar];
ProjFlux_j = new su2double [nVar];
Lambda = new su2double [nVar];
Epsilon = new su2double [nVar];
absPeJac = new su2double* [nVar];
invRinvPe = new su2double* [nVar];
R_Tensor = new su2double* [nVar];
Matrix = new su2double* [nVar];
Art_Visc = new su2double* [nVar];
Jacobian_i = new su2double* [nVar];
Jacobian_j = new su2double* [nVar];
for (iVar = 0; iVar < nVar; iVar++) {
absPeJac[iVar] = new su2double [nVar];
invRinvPe[iVar] = new su2double [nVar];
Matrix[iVar] = new su2double [nVar];
Art_Visc[iVar] = new su2double [nVar];
R_Tensor[iVar] = new su2double [nVar];
Jacobian_i[iVar] = new su2double [nVar];
Jacobian_j[iVar] = new su2double [nVar];
}
}
CUpwTurkel_Flow::~CUpwTurkel_Flow(void) {
delete [] Flux;
delete [] Diff_U;
delete [] Velocity_i;
delete [] Velocity_j;
delete [] RoeVelocity;
delete [] ProjFlux_i;
delete [] ProjFlux_j;
delete [] Lambda;
delete [] Epsilon;
for (iVar = 0; iVar < nVar; iVar++) {
delete [] absPeJac[iVar];
delete [] invRinvPe[iVar];
delete [] Matrix[iVar];
delete [] Art_Visc[iVar];
delete [] R_Tensor[iVar];
delete [] Jacobian_i[iVar];
delete [] Jacobian_j[iVar];
}
delete [] Matrix;
delete [] Art_Visc;
delete [] absPeJac;
delete [] invRinvPe;
delete [] R_Tensor;
delete [] Jacobian_i;
delete [] Jacobian_j;
}
CNumerics::ResidualType<> CUpwTurkel_Flow::ComputeResidual(const CConfig* config) {
implicit = (config->GetKind_TimeIntScheme() == EULER_IMPLICIT);
su2double U_i[5] = {0.0}, U_j[5] = {0.0};
/*--- Face area (norm or the normal vector) ---*/
Area = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
Area += Normal[iDim]*Normal[iDim];
Area = sqrt(Area);
/*-- Unit Normal ---*/
for (iDim = 0; iDim < nDim; iDim++)
UnitNormal[iDim] = Normal[iDim]/Area;
/*--- Primitive variables at point i ---*/
for (iDim = 0; iDim < nDim; iDim++)
Velocity_i[iDim] = V_i[iDim+1];
Pressure_i = V_i[nDim+1];
Density_i = V_i[nDim+2];
Enthalpy_i = V_i[nDim+3];
Energy_i = Enthalpy_i - Pressure_i/Density_i;
SoundSpeed_i = sqrt(fabs(Pressure_i*Gamma/Density_i));
/*--- Primitive variables at point j ---*/
for (iDim = 0; iDim < nDim; iDim++)
Velocity_j[iDim] = V_j[iDim+1];
Pressure_j = V_j[nDim+1];
Density_j = V_j[nDim+2];
Enthalpy_j = V_j[nDim+3];
Energy_j = Enthalpy_j - Pressure_j/Density_j;
SoundSpeed_j = sqrt(fabs(Pressure_j*Gamma/Density_j));
/*--- Recompute conservative variables ---*/
U_i[0] = Density_i; U_j[0] = Density_j;
for (iDim = 0; iDim < nDim; iDim++) {
U_i[iDim+1] = Density_i*Velocity_i[iDim]; U_j[iDim+1] = Density_j*Velocity_j[iDim];
}
U_i[nDim+1] = Density_i*Energy_i; U_j[nDim+1] = Density_j*Energy_j;
/*--- Roe-averaged variables at interface between i & j ---*/
R = sqrt(fabs(Density_j/Density_i));
RoeDensity = R*Density_i;
sq_vel = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
RoeVelocity[iDim] = (R*Velocity_j[iDim]+Velocity_i[iDim])/(R+1);
sq_vel += RoeVelocity[iDim]*RoeVelocity[iDim];
}
RoeEnthalpy = (R*Enthalpy_j+Enthalpy_i)/(R+1);
RoeSoundSpeed = sqrt(fabs((Gamma-1)*(RoeEnthalpy-0.5*sq_vel)));
RoePressure = RoeDensity/Gamma*RoeSoundSpeed*RoeSoundSpeed;
/*--- Compute ProjFlux_i ---*/
GetInviscidProjFlux(&Density_i, Velocity_i, &Pressure_i, &Enthalpy_i, Normal, ProjFlux_i);
/*--- Compute ProjFlux_j ---*/
GetInviscidProjFlux(&Density_j, Velocity_j, &Pressure_j, &Enthalpy_j, Normal, ProjFlux_j);
ProjVelocity = 0.0; ProjVelocity_i = 0.0; ProjVelocity_j = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
ProjVelocity += RoeVelocity[iDim]*UnitNormal[iDim];
ProjVelocity_i += Velocity_i[iDim]*UnitNormal[iDim];
ProjVelocity_j += Velocity_j[iDim]*UnitNormal[iDim];
}
/*--- Projected velocity adjustment due to mesh motion ---*/
if (dynamic_grid) {
su2double ProjGridVel = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
ProjGridVel += 0.5*(GridVel_i[iDim]+GridVel_j[iDim])*UnitNormal[iDim];
}
ProjVelocity -= ProjGridVel;
ProjVelocity_i -= ProjGridVel;
ProjVelocity_j -= ProjGridVel;
}
/*--- First few flow eigenvalues of A.Normal with the normal---*/
for (iDim = 0; iDim < nDim; iDim++)
Lambda[iDim] = ProjVelocity;
local_Mach = sqrt(sq_vel)/RoeSoundSpeed;
Beta = max(Beta_min, min(local_Mach, Beta_max));
Beta2 = Beta*Beta;
one_m_Betasqr = 1.0 - Beta2; // 1-Beta*Beta
one_p_Betasqr = 1.0 + Beta2; // 1+Beta*Beta
sqr_one_m_Betasqr_Lam1 = pow((one_m_Betasqr*Lambda[0]),2); // [(1-Beta^2)*Lambda[0]]^2
sqr_two_Beta_c_Area = pow(2.0*Beta*RoeSoundSpeed*Area,2); // [2*Beta*c*Area]^2
/*--- The rest of the flow eigenvalues of preconditioned matrix---*/
Lambda[nVar-2] = 0.5 * ( one_p_Betasqr*Lambda[0] + sqrt( sqr_one_m_Betasqr_Lam1 + sqr_two_Beta_c_Area));
Lambda[nVar-1] = 0.5 * ( one_p_Betasqr*Lambda[0] - sqrt( sqr_one_m_Betasqr_Lam1 + sqr_two_Beta_c_Area));
s_hat = 1.0/Area * (Lambda[nVar-1] - Lambda[0]*Beta2);
r_hat = 1.0/Area * (Lambda[nVar-2] - Lambda[0]*Beta2);
t_hat = 0.5/Area * (Lambda[nVar-1] - Lambda[nVar-2]);
rhoB2a2 = RoeDensity*Beta2*RoeSoundSpeed*RoeSoundSpeed;
/*--- Diference variables iPoint and jPoint and absolute value of the eigen values---*/
for (iVar = 0; iVar < nVar; iVar++) {
Diff_U[iVar] = U_j[iVar]-U_i[iVar];
Lambda[iVar] = fabs(Lambda[iVar]);
}
/*--- Compute the absolute Preconditioned Jacobian in entropic Variables (do it with the Unitary Normal) ---*/
GetPrecondJacobian(Beta2, r_hat, s_hat, t_hat, rhoB2a2, Lambda, UnitNormal, absPeJac);
/*--- Compute the matrix from entropic variables to conserved variables ---*/
GetinvRinvPe(Beta2, RoeEnthalpy, RoeSoundSpeed, RoeDensity, RoeVelocity, invRinvPe);
/*--- Compute the matrix from entropic variables to conserved variables ---*/
GetRMatrix(RoePressure, RoeSoundSpeed, RoeDensity, RoeVelocity, R_Tensor);
if (implicit) {
/*--- Jacobians of the inviscid flux, scaled by
0.5 because Flux ~ 0.5*(fc_i+fc_j)*Normal ---*/
GetInviscidProjJac(Velocity_i, &Energy_i, Normal, 0.5, Jacobian_i);
GetInviscidProjJac(Velocity_j, &Energy_j, Normal, 0.5, Jacobian_j);
}
for (iVar = 0; iVar < nVar; iVar ++) {
for (jVar = 0; jVar < nVar; jVar ++) {
Matrix[iVar][jVar] = 0.0;
for (kVar = 0; kVar < nVar; kVar++)
Matrix[iVar][jVar] += absPeJac[iVar][kVar]*R_Tensor[kVar][jVar];
}
}
for (iVar = 0; iVar < nVar; iVar ++) {
for (jVar = 0; jVar < nVar; jVar ++) {
Art_Visc[iVar][jVar] = 0.0;
for (kVar = 0; kVar < nVar; kVar++)
Art_Visc[iVar][jVar] += invRinvPe[iVar][kVar]*Matrix[kVar][jVar];
}
}
/*--- Roe's Flux approximation ---*/
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] = 0.5*(ProjFlux_i[iVar]+ProjFlux_j[iVar]);
for (jVar = 0; jVar < nVar; jVar++) {
Flux[iVar] -= 0.5*Art_Visc[iVar][jVar]*Diff_U[jVar];
if (implicit) {
Jacobian_i[iVar][jVar] += 0.5*Art_Visc[iVar][jVar];
Jacobian_j[iVar][jVar] -= 0.5*Art_Visc[iVar][jVar];
}
}
}
/*--- Contributions due to mesh motion---*/
if (dynamic_grid) {
ProjVelocity = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
ProjVelocity += 0.5*(GridVel_i[iDim]+GridVel_j[iDim])*UnitNormal[iDim];
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] -= ProjVelocity * 0.5*(U_i[iVar]+U_j[iVar]);
/*--- Implicit terms ---*/
if (implicit) {
Jacobian_i[iVar][iVar] -= 0.5*ProjVelocity;
Jacobian_j[iVar][iVar] -= 0.5*ProjVelocity;
}
}
}
return ResidualType<>(Flux, Jacobian_i, Jacobian_j);
}
CUpwGeneralRoe_Flow::CUpwGeneralRoe_Flow(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config) : CNumerics(val_nDim, val_nVar, config) {
implicit = (config->GetKind_TimeIntScheme_Flow() == EULER_IMPLICIT);
/* A grid is defined as dynamic if there's rigid grid movement or grid deformation AND the problem is time domain */
dynamic_grid = config->GetDynamic_Grid();
kappa = config->GetRoe_Kappa(); // 1 is unstable
Flux = new su2double [nVar];
Diff_U = new su2double [nVar];
Velocity_i = new su2double [nDim];
Velocity_j = new su2double [nDim];
RoeVelocity = new su2double [nDim];
delta_vel = new su2double [nDim];
delta_wave = new su2double [nVar];
ProjFlux_i = new su2double [nVar];
ProjFlux_j = new su2double [nVar];
Lambda = new su2double [nVar];
Epsilon = new su2double [nVar];
P_Tensor = new su2double* [nVar];
invP_Tensor = new su2double* [nVar];
Jacobian_i = new su2double* [nVar];
Jacobian_j = new su2double* [nVar];
for (iVar = 0; iVar < nVar; iVar++) {
P_Tensor[iVar] = new su2double [nVar];
invP_Tensor[iVar] = new su2double [nVar];
Jacobian_i[iVar] = new su2double [nVar];
Jacobian_j[iVar] = new su2double [nVar];
}
}
CUpwGeneralRoe_Flow::~CUpwGeneralRoe_Flow(void) {
delete [] Flux;
delete [] Diff_U;
delete [] Velocity_i;
delete [] Velocity_j;
delete [] RoeVelocity;
delete [] delta_vel;
delete [] delta_wave;
delete [] ProjFlux_i;
delete [] ProjFlux_j;
delete [] Lambda;
delete [] Epsilon;
for (iVar = 0; iVar < nVar; iVar++) {
delete [] P_Tensor[iVar];
delete [] invP_Tensor[iVar];
delete [] Jacobian_i[iVar];
delete [] Jacobian_j[iVar];
}
delete [] P_Tensor;
delete [] invP_Tensor;
delete [] Jacobian_i;
delete [] Jacobian_j;
}
CNumerics::ResidualType<> CUpwGeneralRoe_Flow::ComputeResidual(const CConfig* config) {
AD::StartPreacc();
AD::SetPreaccIn(V_i, nDim+4); AD::SetPreaccIn(V_j, nDim+4); AD::SetPreaccIn(Normal, nDim);
AD::SetPreaccIn(S_i, 2); AD::SetPreaccIn(S_j, 2);
if (dynamic_grid) {
AD::SetPreaccIn(GridVel_i, nDim); AD::SetPreaccIn(GridVel_j, nDim);
}
su2double U_i[5] = {0.0,0.0,0.0,0.0,0.0}, U_j[5] = {0.0,0.0,0.0,0.0,0.0};
/*--- Face area (norm or the normal vector) ---*/
Area = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
Area += Normal[iDim]*Normal[iDim];
Area = sqrt(Area);
/*-- Unit Normal ---*/
for (iDim = 0; iDim < nDim; iDim++)
UnitNormal[iDim] = Normal[iDim]/Area;
/*--- Primitive variables at point i ---*/
Velocity2_i = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
Velocity_i[iDim] = V_i[iDim+1];
Velocity2_i += Velocity_i[iDim]*Velocity_i[iDim];
}
Pressure_i = V_i[nDim+1];
Density_i = V_i[nDim+2];
Enthalpy_i = V_i[nDim+3];
Energy_i = Enthalpy_i - Pressure_i/Density_i;
StaticEnthalpy_i = Enthalpy_i - 0.5*Velocity2_i;
StaticEnergy_i = StaticEnthalpy_i - Pressure_i/Density_i;
Kappa_i = S_i[1]/Density_i;
Chi_i = S_i[0] - Kappa_i*StaticEnergy_i;
SoundSpeed_i = sqrt(Chi_i + StaticEnthalpy_i*Kappa_i);
/*--- Primitive variables at point j ---*/
Velocity2_j = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
Velocity_j[iDim] = V_j[iDim+1];
Velocity2_j += Velocity_j[iDim]*Velocity_j[iDim];
}
Pressure_j = V_j[nDim+1];
Density_j = V_j[nDim+2];
Enthalpy_j = V_j[nDim+3];
Energy_j = Enthalpy_j - Pressure_j/Density_j;
StaticEnthalpy_j = Enthalpy_j - 0.5*Velocity2_j;
StaticEnergy_j = StaticEnthalpy_j - Pressure_j/Density_j;
Kappa_j = S_j[1]/Density_j;
Chi_j = S_j[0] - Kappa_j*StaticEnergy_j;
SoundSpeed_j = sqrt(Chi_j + StaticEnthalpy_j*Kappa_j);
/*--- Recompute conservative variables ---*/
U_i[0] = Density_i; U_j[0] = Density_j;
for (iDim = 0; iDim < nDim; iDim++) {
U_i[iDim+1] = Density_i*Velocity_i[iDim]; U_j[iDim+1] = Density_j*Velocity_j[iDim];
}
U_i[nDim+1] = Density_i*Energy_i; U_j[nDim+1] = Density_j*Energy_j;
/*--- Roe-averaged variables at interface between i & j ---*/
ComputeRoeAverage();
if (RoeSoundSpeed2 <= 0.0) {
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] = 0.0;
for (jVar = 0; jVar < nVar; jVar++) {
Jacobian_i[iVar][iVar] = 0.0;
Jacobian_j[iVar][iVar] = 0.0;
}
}
AD::SetPreaccOut(Flux, nVar);
AD::EndPreacc();
return ResidualType<>(Flux, Jacobian_i, Jacobian_j);
}
RoeSoundSpeed = sqrt(RoeSoundSpeed2);
/*--- Compute ProjFlux_i ---*/
GetInviscidProjFlux(&Density_i, Velocity_i, &Pressure_i, &Enthalpy_i, Normal, ProjFlux_i);
/*--- Compute ProjFlux_j ---*/
GetInviscidProjFlux(&Density_j, Velocity_j, &Pressure_j, &Enthalpy_j, Normal, ProjFlux_j);
/*--- Compute P and Lambda (do it with the Normal) ---*/
GetPMatrix(&RoeDensity, RoeVelocity, &RoeSoundSpeed, &RoeEnthalpy, &RoeChi, &RoeKappa, UnitNormal, P_Tensor);
ProjVelocity = 0.0; ProjVelocity_i = 0.0; ProjVelocity_j = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
ProjVelocity += RoeVelocity[iDim]*UnitNormal[iDim];
ProjVelocity_i += Velocity_i[iDim]*UnitNormal[iDim];
ProjVelocity_j += Velocity_j[iDim]*UnitNormal[iDim];
}
/*--- Projected velocity adjustment due to mesh motion ---*/
if (dynamic_grid) {
su2double ProjGridVel = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
ProjGridVel += 0.5*(GridVel_i[iDim]+GridVel_j[iDim])*UnitNormal[iDim];
}
ProjVelocity -= ProjGridVel;
ProjVelocity_i -= ProjGridVel;
ProjVelocity_j -= ProjGridVel;
}
/*--- Flow eigenvalues and entropy correctors ---*/
for (iDim = 0; iDim < nDim; iDim++)
Lambda[iDim] = ProjVelocity;
Lambda[nVar-2] = ProjVelocity + RoeSoundSpeed;
Lambda[nVar-1] = ProjVelocity - RoeSoundSpeed;
/*--- Compute absolute value with Mavriplis' entropy correction ---*/
MaxLambda = fabs(ProjVelocity) + RoeSoundSpeed;
Delta = config->GetEntropyFix_Coeff();
for (iVar = 0; iVar < nVar; iVar++) {
Lambda[iVar] = max(fabs(Lambda[iVar]), Delta*MaxLambda);
}
// /*--- Harten and Hyman (1983) entropy correction ---*/
// for (iDim = 0; iDim < nDim; iDim++)
// Epsilon[iDim] = 4.0*max(0.0, max(Lambda[iDim]-ProjVelocity_i, ProjVelocity_j-Lambda[iDim]));
//
// Epsilon[nVar-2] = 4.0*max(0.0, max(Lambda[nVar-2]-(ProjVelocity_i+SoundSpeed_i),(ProjVelocity_j+SoundSpeed_j)-Lambda[nVar-2]));
// Epsilon[nVar-1] = 4.0*max(0.0, max(Lambda[nVar-1]-(ProjVelocity_i-SoundSpeed_i),(ProjVelocity_j-SoundSpeed_j)-Lambda[nVar-1]));
//
// for (iVar = 0; iVar < nVar; iVar++)
// if ( fabs(Lambda[iVar]) < Epsilon[iVar] )
// Lambda[iVar] = (Lambda[iVar]*Lambda[iVar] + Epsilon[iVar]*Epsilon[iVar])/(2.0*Epsilon[iVar]);
// else
// Lambda[iVar] = fabs(Lambda[iVar]);
// for (iVar = 0; iVar < nVar; iVar++)
// Lambda[iVar] = fabs(Lambda[iVar]);
if (!implicit) {
/*--- Compute wave amplitudes (characteristics) ---*/
proj_delta_vel = 0.0;
for (iDim = 0; iDim < nDim; iDim++) {
delta_vel[iDim] = Velocity_j[iDim] - Velocity_i[iDim];
proj_delta_vel += delta_vel[iDim]*Normal[iDim];
}
delta_p = Pressure_j - Pressure_i;
delta_rho = Density_j - Density_i;
proj_delta_vel = proj_delta_vel/Area;
if (nDim == 2) {
delta_wave[0] = delta_rho - delta_p/(RoeSoundSpeed*RoeSoundSpeed);
delta_wave[1] = UnitNormal[1]*delta_vel[0]-UnitNormal[0]*delta_vel[1];
delta_wave[2] = proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
delta_wave[3] = -proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
} else {
delta_wave[0] = delta_rho - delta_p/(RoeSoundSpeed*RoeSoundSpeed);
delta_wave[1] = UnitNormal[0]*delta_vel[2]-UnitNormal[2]*delta_vel[0];
delta_wave[2] = UnitNormal[1]*delta_vel[0]-UnitNormal[0]*delta_vel[1];
delta_wave[3] = proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
delta_wave[4] = -proj_delta_vel + delta_p/(RoeDensity*RoeSoundSpeed);
}
/*--- Roe's Flux approximation ---*/
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] = 0.5*(ProjFlux_i[iVar]+ProjFlux_j[iVar]);
for (jVar = 0; jVar < nVar; jVar++)
Flux[iVar] -= 0.5*Lambda[jVar]*delta_wave[jVar]*P_Tensor[iVar][jVar]*Area;
}
/*--- Flux contribution due to grid motion ---*/
if (dynamic_grid) {
ProjVelocity = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
ProjVelocity += 0.5*(GridVel_i[iDim]+GridVel_j[iDim])*Normal[iDim];
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] -= ProjVelocity * 0.5*(U_i[iVar]+U_j[iVar]);
}
}
}
else {
/*--- Compute inverse P ---*/
GetPMatrix_inv(invP_Tensor, &RoeDensity, RoeVelocity, &RoeSoundSpeed, &RoeChi , &RoeKappa, UnitNormal);
/*--- Jacobians of the inviscid flux, scaled by
kappa because val_resconv ~ kappa*(fc_i+fc_j)*Normal ---*/
GetInviscidProjJac(Velocity_i, &Enthalpy_i, &Chi_i, &Kappa_i, Normal, kappa, Jacobian_i);
GetInviscidProjJac(Velocity_j, &Enthalpy_j, &Chi_j, &Kappa_j, Normal, kappa, Jacobian_j);
/*--- Diference variables iPoint and jPoint ---*/
for (iVar = 0; iVar < nVar; iVar++)
Diff_U[iVar] = U_j[iVar]-U_i[iVar];
/*--- Roe's Flux approximation ---*/
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] = kappa*(ProjFlux_i[iVar]+ProjFlux_j[iVar]);
for (jVar = 0; jVar < nVar; jVar++) {
Proj_ModJac_Tensor_ij = 0.0;
/*--- Compute |Proj_ModJac_Tensor| = P x |Lambda| x inverse P ---*/
for (kVar = 0; kVar < nVar; kVar++)
Proj_ModJac_Tensor_ij += P_Tensor[iVar][kVar]*Lambda[kVar]*invP_Tensor[kVar][jVar];
Flux[iVar] -= (1.0-kappa)*Proj_ModJac_Tensor_ij*Diff_U[jVar]*Area;
Jacobian_i[iVar][jVar] += (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
Jacobian_j[iVar][jVar] -= (1.0-kappa)*Proj_ModJac_Tensor_ij*Area;
}
}
/*--- Jacobian contributions due to grid motion ---*/
if (dynamic_grid) {
ProjVelocity = 0.0;
for (iDim = 0; iDim < nDim; iDim++)
ProjVelocity += 0.5*(GridVel_i[iDim]+GridVel_j[iDim])*Normal[iDim];
for (iVar = 0; iVar < nVar; iVar++) {
Flux[iVar] -= ProjVelocity * 0.5*(U_i[iVar]+U_j[iVar]);
/*--- Implicit terms ---*/
Jacobian_i[iVar][iVar] -= 0.5*ProjVelocity;
Jacobian_j[iVar][iVar] -= 0.5*ProjVelocity;
}
}
}
AD::SetPreaccOut(Flux, nVar);
AD::EndPreacc();
return ResidualType<>(Flux, Jacobian_i, Jacobian_j);
}
void CUpwGeneralRoe_Flow::ComputeRoeAverage() {
//su2double delta_rhoStaticEnergy, err_P, s, D;
// su2double tol = 10-6;
R = sqrt(fabs(Density_j/Density_i));
RoeDensity = R*Density_i;
sq_vel = 0; for (iDim = 0; iDim < nDim; iDim++) {
RoeVelocity[iDim] = (R*Velocity_j[iDim]+Velocity_i[iDim])/(R+1);
sq_vel += RoeVelocity[iDim]*RoeVelocity[iDim];
}
RoeEnthalpy = (R*Enthalpy_j+Enthalpy_i)/(R+1);
delta_rho = Density_j - Density_i;
delta_p = Pressure_j - Pressure_i;
RoeKappa = 0.5*(Kappa_i + Kappa_j);
RoeKappa = (Kappa_i + Kappa_j + 4*RoeKappa)/6;
RoeChi = 0.5*(Chi_i + Chi_j);
RoeChi = (Chi_i + Chi_j + 4*RoeChi)/6;
// RoeKappaStaticEnthalpy = 0.5*(StaticEnthalpy_i*Kappa_i + StaticEnthalpy_j*Kappa_j);
// RoeKappaStaticEnthalpy = (StaticEnthalpy_i*Kappa_i + StaticEnthalpy_j*Kappa_j + 4*RoeKappaStaticEnthalpy)/6;
// s = RoeChi + RoeKappaStaticEnthalpy;
// D = s*s*delta_rho*delta_rho + delta_p*delta_p;
// delta_rhoStaticEnergy = Density_j*StaticEnergy_j - Density_i*StaticEnergy_i;
// err_P = delta_p - RoeChi*delta_rho - RoeKappa*delta_rhoStaticEnergy;
//
//
// if (abs((D - delta_p*err_P)/Density_i)>1e-3 && abs(delta_rho/Density_i)>1e-3 && s/Density_i > 1e-3) {
//
// RoeKappa = (D*RoeKappa)/(D - delta_p*err_P);
// RoeChi = (D*RoeChi+ s*s*delta_rho*err_P)/(D - delta_p*err_P);
//
// }
RoeSoundSpeed2 = RoeChi + RoeKappa*(RoeEnthalpy-0.5*sq_vel);
}
| 34.752918 | 155 | 0.654789 | [
"mesh",
"vector"
] |
91330124ce7bc13b32d9cbb2c7ed5a576b0b59a3 | 78,018 | cc | C++ | cc/resources/resource_provider.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/resources/resource_provider.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/resources/resource_provider.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/resources/resource_provider.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <limits>
#include <unordered_map>
#include "base/atomic_sequence_num.h"
#include "base/macros.h"
#include "base/metrics/histogram.h"
#include "base/numerics/safe_math.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/trace_event.h"
#include "cc/resources/resource_util.h"
#include "cc/resources/returned_resource.h"
#include "cc/resources/transferable_resource.h"
#include "components/viz/common/resources/platform_color.h"
#include "components/viz/common/resources/shared_bitmap_manager.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/context_support.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/command_buffer/client/gpu_memory_buffer_manager.h"
#include "skia/ext/texture_handle.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/khronos/GLES2/gl2ext.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/gl/GrGLTypes.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/icc_profile.h"
#include "ui/gl/trace_util.h"
using gpu::gles2::GLES2Interface;
namespace cc {
class TextureIdAllocator {
public:
TextureIdAllocator(GLES2Interface* gl,
size_t texture_id_allocation_chunk_size)
: gl_(gl),
id_allocation_chunk_size_(texture_id_allocation_chunk_size),
ids_(new GLuint[texture_id_allocation_chunk_size]),
next_id_index_(texture_id_allocation_chunk_size) {
DCHECK(id_allocation_chunk_size_);
DCHECK_LE(id_allocation_chunk_size_,
static_cast<size_t>(std::numeric_limits<int>::max()));
}
~TextureIdAllocator() {
gl_->DeleteTextures(
static_cast<int>(id_allocation_chunk_size_ - next_id_index_),
ids_.get() + next_id_index_);
}
GLuint NextId() {
if (next_id_index_ == id_allocation_chunk_size_) {
gl_->GenTextures(static_cast<int>(id_allocation_chunk_size_), ids_.get());
next_id_index_ = 0;
}
return ids_[next_id_index_++];
}
private:
GLES2Interface* gl_;
const size_t id_allocation_chunk_size_;
std::unique_ptr<GLuint[]> ids_;
size_t next_id_index_;
DISALLOW_COPY_AND_ASSIGN(TextureIdAllocator);
};
namespace {
bool IsGpuResourceType(ResourceProvider::ResourceType type) {
return type != ResourceProvider::RESOURCE_TYPE_BITMAP;
}
GLenum TextureToStorageFormat(viz::ResourceFormat format) {
GLenum storage_format = GL_RGBA8_OES;
switch (format) {
case viz::RGBA_8888:
break;
case viz::BGRA_8888:
storage_format = GL_BGRA8_EXT;
break;
case viz::RGBA_F16:
storage_format = GL_RGBA16F_EXT;
break;
case viz::RGBA_4444:
case viz::ALPHA_8:
case viz::LUMINANCE_8:
case viz::RGB_565:
case viz::ETC1:
case viz::RED_8:
case viz::LUMINANCE_F16:
NOTREACHED();
break;
}
return storage_format;
}
bool IsFormatSupportedForStorage(viz::ResourceFormat format, bool use_bgra) {
switch (format) {
case viz::RGBA_8888:
case viz::RGBA_F16:
return true;
case viz::BGRA_8888:
return use_bgra;
case viz::RGBA_4444:
case viz::ALPHA_8:
case viz::LUMINANCE_8:
case viz::RGB_565:
case viz::ETC1:
case viz::RED_8:
case viz::LUMINANCE_F16:
return false;
}
return false;
}
GrPixelConfig ToGrPixelConfig(viz::ResourceFormat format) {
switch (format) {
case viz::RGBA_8888:
return kRGBA_8888_GrPixelConfig;
case viz::BGRA_8888:
return kBGRA_8888_GrPixelConfig;
case viz::RGBA_4444:
return kRGBA_4444_GrPixelConfig;
case viz::RGBA_F16:
return kRGBA_half_GrPixelConfig;
default:
break;
}
DCHECK(false) << "Unsupported resource format.";
return kSkia8888_GrPixelConfig;
}
class ScopedSetActiveTexture {
public:
ScopedSetActiveTexture(GLES2Interface* gl, GLenum unit)
: gl_(gl), unit_(unit) {
DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
if (unit_ != GL_TEXTURE0)
gl_->ActiveTexture(unit_);
}
~ScopedSetActiveTexture() {
// Active unit being GL_TEXTURE0 is effectively the ground state.
if (unit_ != GL_TEXTURE0)
gl_->ActiveTexture(GL_TEXTURE0);
}
private:
GLES2Interface* gl_;
GLenum unit_;
};
// Generates process-unique IDs to use for tracing a ResourceProvider's
// resources.
base::AtomicSequenceNumber g_next_resource_provider_tracing_id;
} // namespace
ResourceProvider::Resource::~Resource() {}
ResourceProvider::Resource::Resource(GLuint texture_id,
const gfx::Size& size,
Origin origin,
GLenum target,
GLenum filter,
TextureHint hint,
ResourceType type,
viz::ResourceFormat format)
: child_id(0),
gl_id(texture_id),
gl_pixel_buffer_id(0),
gl_upload_query_id(0),
gl_read_lock_query_id(0),
pixels(nullptr),
lock_for_read_count(0),
imported_count(0),
exported_count(0),
dirty_image(false),
locked_for_write(false),
lost(false),
marked_for_deletion(false),
allocated(false),
read_lock_fences_enabled(false),
has_shared_bitmap_id(false),
is_overlay_candidate(false),
#if defined(OS_ANDROID)
is_backed_by_surface_texture(false),
wants_promotion_hint(false),
#endif
read_lock_fence(nullptr),
size(size),
origin(origin),
target(target),
original_filter(filter),
filter(filter),
image_id(0),
bound_image_id(0),
hint(hint),
type(type),
usage(gfx::BufferUsage::GPU_READ_CPU_READ_WRITE),
buffer_format(gfx::BufferFormat::RGBA_8888),
format(format),
shared_bitmap(nullptr) {
}
ResourceProvider::Resource::Resource(uint8_t* pixels,
viz::SharedBitmap* bitmap,
const gfx::Size& size,
Origin origin,
GLenum filter)
: child_id(0),
gl_id(0),
gl_pixel_buffer_id(0),
gl_upload_query_id(0),
gl_read_lock_query_id(0),
pixels(pixels),
lock_for_read_count(0),
imported_count(0),
exported_count(0),
dirty_image(false),
locked_for_write(false),
lost(false),
marked_for_deletion(false),
allocated(false),
read_lock_fences_enabled(false),
has_shared_bitmap_id(!!bitmap),
is_overlay_candidate(false),
#if defined(OS_ANDROID)
is_backed_by_surface_texture(false),
wants_promotion_hint(false),
#endif
read_lock_fence(nullptr),
size(size),
origin(origin),
target(0),
original_filter(filter),
filter(filter),
image_id(0),
bound_image_id(0),
hint(TEXTURE_HINT_IMMUTABLE),
type(RESOURCE_TYPE_BITMAP),
buffer_format(gfx::BufferFormat::RGBA_8888),
format(viz::RGBA_8888),
shared_bitmap(bitmap) {
DCHECK(origin == DELEGATED || pixels);
if (bitmap)
shared_bitmap_id = bitmap->id();
}
ResourceProvider::Resource::Resource(const viz::SharedBitmapId& bitmap_id,
const gfx::Size& size,
Origin origin,
GLenum filter)
: child_id(0),
gl_id(0),
gl_pixel_buffer_id(0),
gl_upload_query_id(0),
gl_read_lock_query_id(0),
pixels(nullptr),
lock_for_read_count(0),
imported_count(0),
exported_count(0),
dirty_image(false),
locked_for_write(false),
lost(false),
marked_for_deletion(false),
allocated(false),
read_lock_fences_enabled(false),
has_shared_bitmap_id(true),
is_overlay_candidate(false),
#if defined(OS_ANDROID)
is_backed_by_surface_texture(false),
wants_promotion_hint(false),
#endif
read_lock_fence(nullptr),
size(size),
origin(origin),
target(0),
original_filter(filter),
filter(filter),
image_id(0),
bound_image_id(0),
hint(TEXTURE_HINT_IMMUTABLE),
type(RESOURCE_TYPE_BITMAP),
buffer_format(gfx::BufferFormat::RGBA_8888),
format(viz::RGBA_8888),
shared_bitmap_id(bitmap_id),
shared_bitmap(nullptr) {
}
ResourceProvider::Resource::Resource(Resource&& other) = default;
void ResourceProvider::Resource::set_mailbox(
const viz::TextureMailbox& mailbox) {
mailbox_ = mailbox;
if (IsGpuResourceType(type)) {
synchronization_state_ =
(mailbox.sync_token().HasData() ? NEEDS_WAIT : LOCALLY_USED);
needs_sync_token_ = !mailbox.sync_token().HasData();
} else {
synchronization_state_ = SYNCHRONIZED;
}
}
void ResourceProvider::Resource::SetLocallyUsed() {
synchronization_state_ = LOCALLY_USED;
mailbox_.set_sync_token(gpu::SyncToken());
needs_sync_token_ = IsGpuResourceType(type);
}
void ResourceProvider::Resource::SetSynchronized() {
synchronization_state_ = SYNCHRONIZED;
}
void ResourceProvider::Resource::UpdateSyncToken(
const gpu::SyncToken& sync_token) {
// In the case of context lost, this sync token may be empty since sync tokens
// may not be generated unless a successful flush occurred. However, we will
// assume the task runner is calling this function properly and update the
// state accordingly.
mailbox_.set_sync_token(sync_token);
synchronization_state_ = NEEDS_WAIT;
needs_sync_token_ = false;
}
int8_t* ResourceProvider::Resource::GetSyncTokenData() {
return mailbox_.GetSyncTokenData();
}
void ResourceProvider::Resource::WaitSyncToken(gpu::gles2::GLES2Interface* gl) {
// Make sure we are only called when state actually needs to wait.
DCHECK_EQ(NEEDS_WAIT, synchronization_state_);
// Make sure sync token is not stale.
DCHECK(!needs_sync_token_);
// In the case of context lost, this sync token may be empty (see comment in
// the UpdateSyncToken() function). The WaitSyncTokenCHROMIUM() function
// handles empty sync tokens properly so just wait anyways and update the
// state the synchronized.
gl->WaitSyncTokenCHROMIUM(mailbox_.sync_token().GetConstData());
SetSynchronized();
}
ResourceProvider::Child::Child()
: marked_for_deletion(false), needs_sync_tokens(true) {}
ResourceProvider::Child::Child(const Child& other) = default;
ResourceProvider::Child::~Child() {}
ResourceProvider::Settings::Settings(
viz::ContextProvider* compositor_context_provider,
bool delegated_sync_points_required,
bool enable_color_correct_rasterization,
const viz::ResourceSettings& resource_settings)
: default_resource_type(resource_settings.use_gpu_memory_buffer_resources
? RESOURCE_TYPE_GPU_MEMORY_BUFFER
: RESOURCE_TYPE_GL_TEXTURE),
enable_color_correct_rasterization(enable_color_correct_rasterization),
delegated_sync_points_required(delegated_sync_points_required) {
if (!compositor_context_provider) {
default_resource_type = RESOURCE_TYPE_BITMAP;
// Pick an arbitrary limit here similar to what hardware might.
max_texture_size = 16 * 1024;
best_texture_format = viz::RGBA_8888;
return;
}
DCHECK(IsGpuResourceType(default_resource_type));
const auto& caps = compositor_context_provider->ContextCapabilities();
use_texture_storage_ext = caps.texture_storage;
use_texture_format_bgra = caps.texture_format_bgra8888;
use_texture_usage_hint = caps.texture_usage;
use_sync_query = caps.sync_query;
if (caps.disable_one_component_textures) {
yuv_resource_format = yuv_highbit_resource_format = viz::RGBA_8888;
} else {
yuv_resource_format = caps.texture_rg ? viz::RED_8 : viz::LUMINANCE_8;
yuv_highbit_resource_format = caps.texture_half_float_linear
? viz::LUMINANCE_F16
: yuv_resource_format;
}
GLES2Interface* gl = compositor_context_provider->ContextGL();
gl->GetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
best_texture_format =
viz::PlatformColor::BestSupportedTextureFormat(use_texture_format_bgra);
best_render_buffer_format = viz::PlatformColor::BestSupportedTextureFormat(
caps.render_buffer_format_bgra8888);
}
ResourceProvider::ResourceProvider(
viz::ContextProvider* compositor_context_provider,
viz::SharedBitmapManager* shared_bitmap_manager,
gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
BlockingTaskRunner* blocking_main_thread_task_runner,
bool delegated_sync_points_required,
bool enable_color_correct_rasterization,
const viz::ResourceSettings& resource_settings)
: settings_(compositor_context_provider,
delegated_sync_points_required,
enable_color_correct_rasterization,
resource_settings),
compositor_context_provider_(compositor_context_provider),
shared_bitmap_manager_(shared_bitmap_manager),
gpu_memory_buffer_manager_(gpu_memory_buffer_manager),
blocking_main_thread_task_runner_(blocking_main_thread_task_runner),
lost_context_provider_(false),
next_id_(1),
next_child_(1),
buffer_to_texture_target_map_(
resource_settings.buffer_to_texture_target_map),
tracing_id_(g_next_resource_provider_tracing_id.GetNext()) {
DCHECK(resource_settings.texture_id_allocation_chunk_size);
DCHECK(thread_checker_.CalledOnValidThread());
// In certain cases, ThreadTaskRunnerHandle isn't set (Android Webview).
// Don't register a dump provider in these cases.
// TODO(ericrk): Get this working in Android Webview. crbug.com/517156
if (base::ThreadTaskRunnerHandle::IsSet()) {
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
this, "cc::ResourceProvider", base::ThreadTaskRunnerHandle::Get());
}
if (!compositor_context_provider)
return;
DCHECK(!texture_id_allocator_);
GLES2Interface* gl = ContextGL();
texture_id_allocator_.reset(new TextureIdAllocator(
gl, resource_settings.texture_id_allocation_chunk_size));
}
ResourceProvider::~ResourceProvider() {
base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
this);
while (!children_.empty())
DestroyChildInternal(children_.begin(), FOR_SHUTDOWN);
while (!resources_.empty())
DeleteResourceInternal(resources_.begin(), FOR_SHUTDOWN);
GLES2Interface* gl = ContextGL();
if (!IsGpuResourceType(settings_.default_resource_type)) {
// We are not in GL mode, but double check before returning.
DCHECK(!gl);
return;
}
DCHECK(gl);
#if DCHECK_IS_ON()
// Check that all GL resources has been deleted.
for (ResourceMap::const_iterator itr = resources_.begin();
itr != resources_.end(); ++itr) {
DCHECK(!IsGpuResourceType(itr->second.type));
}
#endif // DCHECK_IS_ON()
texture_id_allocator_ = nullptr;
gl->Finish();
}
bool ResourceProvider::IsTextureFormatSupported(
viz::ResourceFormat format) const {
gpu::Capabilities caps;
if (compositor_context_provider_)
caps = compositor_context_provider_->ContextCapabilities();
switch (format) {
case viz::ALPHA_8:
case viz::RGBA_4444:
case viz::RGBA_8888:
case viz::RGB_565:
case viz::LUMINANCE_8:
return true;
case viz::BGRA_8888:
return caps.texture_format_bgra8888;
case viz::ETC1:
return caps.texture_format_etc1;
case viz::RED_8:
return caps.texture_rg;
case viz::LUMINANCE_F16:
case viz::RGBA_F16:
return caps.texture_half_float_linear;
}
NOTREACHED();
return false;
}
bool ResourceProvider::IsRenderBufferFormatSupported(
viz::ResourceFormat format) const {
gpu::Capabilities caps;
if (compositor_context_provider_)
caps = compositor_context_provider_->ContextCapabilities();
switch (format) {
case viz::RGBA_4444:
case viz::RGBA_8888:
case viz::RGB_565:
return true;
case viz::BGRA_8888:
return caps.render_buffer_format_bgra8888;
case viz::RGBA_F16:
// TODO(ccameron): This will always return false on pixel tests, which
// makes it un-test-able until we upgrade Mesa.
// https://crbug.com/687720
return caps.texture_half_float_linear &&
caps.color_buffer_half_float_rgba;
case viz::LUMINANCE_8:
case viz::ALPHA_8:
case viz::RED_8:
case viz::ETC1:
case viz::LUMINANCE_F16:
// We don't currently render into these formats. If we need to render into
// these eventually, we should expand this logic.
return false;
}
NOTREACHED();
return false;
}
bool ResourceProvider::InUseByConsumer(ResourceId id) {
Resource* resource = GetResource(id);
return resource->lock_for_read_count > 0 || resource->exported_count > 0 ||
resource->lost;
}
bool ResourceProvider::IsLost(ResourceId id) {
Resource* resource = GetResource(id);
return resource->lost;
}
void ResourceProvider::LoseResourceForTesting(ResourceId id) {
Resource* resource = GetResource(id);
DCHECK(resource);
resource->lost = true;
}
viz::ResourceFormat ResourceProvider::YuvResourceFormat(int bits) const {
if (bits > 8) {
return settings_.yuv_highbit_resource_format;
} else {
return settings_.yuv_resource_format;
}
}
ResourceId ResourceProvider::CreateResource(
const gfx::Size& size,
TextureHint hint,
viz::ResourceFormat format,
const gfx::ColorSpace& color_space) {
DCHECK(!size.IsEmpty());
switch (settings_.default_resource_type) {
case RESOURCE_TYPE_GPU_MEMORY_BUFFER:
// GPU memory buffers don't support viz::LUMINANCE_F16 yet.
if (format != viz::LUMINANCE_F16) {
return CreateGLTexture(
size, hint, RESOURCE_TYPE_GPU_MEMORY_BUFFER, format,
gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, color_space);
}
// Fall through and use a regular texture.
case RESOURCE_TYPE_GL_TEXTURE:
return CreateGLTexture(size, hint, RESOURCE_TYPE_GL_TEXTURE, format,
gfx::BufferUsage::GPU_READ_CPU_READ_WRITE,
color_space);
case RESOURCE_TYPE_BITMAP:
DCHECK_EQ(viz::RGBA_8888, format);
return CreateBitmap(size, color_space);
}
LOG(FATAL) << "Invalid default resource type.";
return 0;
}
ResourceId ResourceProvider::CreateGpuMemoryBufferResource(
const gfx::Size& size,
TextureHint hint,
viz::ResourceFormat format,
gfx::BufferUsage usage,
const gfx::ColorSpace& color_space) {
DCHECK(!size.IsEmpty());
switch (settings_.default_resource_type) {
case RESOURCE_TYPE_GPU_MEMORY_BUFFER:
case RESOURCE_TYPE_GL_TEXTURE: {
return CreateGLTexture(size, hint, RESOURCE_TYPE_GPU_MEMORY_BUFFER,
format, usage, color_space);
}
case RESOURCE_TYPE_BITMAP:
DCHECK_EQ(viz::RGBA_8888, format);
return CreateBitmap(size, color_space);
}
LOG(FATAL) << "Invalid default resource type.";
return 0;
}
ResourceId ResourceProvider::CreateGLTexture(
const gfx::Size& size,
TextureHint hint,
ResourceType type,
viz::ResourceFormat format,
gfx::BufferUsage usage,
const gfx::ColorSpace& color_space) {
DCHECK_LE(size.width(), settings_.max_texture_size);
DCHECK_LE(size.height(), settings_.max_texture_size);
DCHECK(thread_checker_.CalledOnValidThread());
// TODO(crbug.com/590317): We should not assume that all resources created by
// ResourceProvider are GPU_READ_CPU_READ_WRITE. We should determine this
// based on the current RasterBufferProvider's needs.
GLenum target = type == RESOURCE_TYPE_GPU_MEMORY_BUFFER
? GetImageTextureTarget(usage, format)
: GL_TEXTURE_2D;
ResourceId id = next_id_++;
Resource* resource =
InsertResource(id, Resource(0, size, Resource::INTERNAL, target,
GL_LINEAR, hint, type, format));
resource->usage = usage;
resource->allocated = false;
resource->color_space = color_space;
return id;
}
ResourceId ResourceProvider::CreateBitmap(const gfx::Size& size,
const gfx::ColorSpace& color_space) {
DCHECK(thread_checker_.CalledOnValidThread());
std::unique_ptr<viz::SharedBitmap> bitmap =
shared_bitmap_manager_->AllocateSharedBitmap(size);
uint8_t* pixels = bitmap->pixels();
DCHECK(pixels);
ResourceId id = next_id_++;
Resource* resource = InsertResource(
id,
Resource(pixels, bitmap.release(), size, Resource::INTERNAL, GL_LINEAR));
resource->allocated = true;
resource->color_space = color_space;
return id;
}
ResourceId ResourceProvider::CreateResourceFromTextureMailbox(
const viz::TextureMailbox& mailbox,
std::unique_ptr<SingleReleaseCallbackImpl> release_callback_impl,
bool read_lock_fences_enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
// Just store the information. Mailbox will be consumed in LockForRead().
ResourceId id = next_id_++;
DCHECK(mailbox.IsValid());
Resource* resource = nullptr;
if (mailbox.IsTexture()) {
resource = InsertResource(
id, Resource(0, mailbox.size_in_pixels(), Resource::EXTERNAL,
mailbox.target(),
mailbox.nearest_neighbor() ? GL_NEAREST : GL_LINEAR,
TEXTURE_HINT_IMMUTABLE, RESOURCE_TYPE_GL_TEXTURE,
viz::RGBA_8888));
} else {
DCHECK(mailbox.IsSharedMemory());
viz::SharedBitmap* shared_bitmap = mailbox.shared_bitmap();
uint8_t* pixels = shared_bitmap->pixels();
DCHECK(pixels);
resource = InsertResource(
id, Resource(pixels, shared_bitmap, mailbox.size_in_pixels(),
Resource::EXTERNAL, GL_LINEAR));
}
resource->allocated = true;
resource->set_mailbox(mailbox);
resource->color_space = mailbox.color_space();
resource->release_callback_impl =
base::Bind(&SingleReleaseCallbackImpl::Run,
base::Owned(release_callback_impl.release()));
resource->read_lock_fences_enabled = read_lock_fences_enabled;
resource->is_overlay_candidate = mailbox.is_overlay_candidate();
#if defined(OS_ANDROID)
resource->is_backed_by_surface_texture =
mailbox.is_backed_by_surface_texture();
resource->wants_promotion_hint = mailbox.wants_promotion_hint();
if (resource->wants_promotion_hint)
wants_promotion_hints_set_.insert(id);
#endif
resource->color_space = mailbox.color_space();
return id;
}
ResourceId ResourceProvider::CreateResourceFromTextureMailbox(
const viz::TextureMailbox& mailbox,
std::unique_ptr<SingleReleaseCallbackImpl> release_callback_impl) {
return CreateResourceFromTextureMailbox(
mailbox, std::move(release_callback_impl), false);
}
void ResourceProvider::DeleteResource(ResourceId id) {
DCHECK(thread_checker_.CalledOnValidThread());
ResourceMap::iterator it = resources_.find(id);
CHECK(it != resources_.end());
Resource* resource = &it->second;
DCHECK(!resource->marked_for_deletion);
DCHECK_EQ(resource->imported_count, 0);
DCHECK(!resource->locked_for_write);
if (resource->exported_count > 0 || resource->lock_for_read_count > 0 ||
!ReadLockFenceHasPassed(resource)) {
resource->marked_for_deletion = true;
return;
} else {
DeleteResourceInternal(it, NORMAL);
}
}
void ResourceProvider::DeleteResourceInternal(ResourceMap::iterator it,
DeleteStyle style) {
TRACE_EVENT0("cc", "ResourceProvider::DeleteResourceInternal");
Resource* resource = &it->second;
DCHECK(resource->exported_count == 0 || style != NORMAL);
#if defined(OS_ANDROID)
// If this resource was interested in promotion hints, then remove it from
// the set of resources that we'll notify.
if (resource->wants_promotion_hint)
wants_promotion_hints_set_.erase(it->first);
#endif
// Exported resources are lost on shutdown.
bool exported_resource_lost =
style == FOR_SHUTDOWN && resource->exported_count > 0;
// GPU resources are lost when context is lost.
bool gpu_resource_lost =
IsGpuResourceType(resource->type) && lost_context_provider_;
bool lost_resource =
resource->lost || exported_resource_lost || gpu_resource_lost;
// Wait on sync token before deleting resources we own.
if (!lost_resource && resource->origin == Resource::INTERNAL &&
resource->synchronization_state() == Resource::NEEDS_WAIT) {
DCHECK(resource->allocated);
DCHECK(IsGpuResourceType(resource->type));
GLES2Interface* gl = ContextGL();
DCHECK(gl);
resource->WaitSyncToken(gl);
}
if (resource->image_id) {
DCHECK(resource->origin == Resource::INTERNAL);
GLES2Interface* gl = ContextGL();
DCHECK(gl);
gl->DestroyImageCHROMIUM(resource->image_id);
}
if (resource->gl_upload_query_id) {
DCHECK(resource->origin == Resource::INTERNAL);
GLES2Interface* gl = ContextGL();
DCHECK(gl);
gl->DeleteQueriesEXT(1, &resource->gl_upload_query_id);
}
if (resource->gl_read_lock_query_id) {
DCHECK(resource->origin == Resource::INTERNAL);
GLES2Interface* gl = ContextGL();
DCHECK(gl);
gl->DeleteQueriesEXT(1, &resource->gl_read_lock_query_id);
}
if (resource->gl_pixel_buffer_id) {
DCHECK(resource->origin == Resource::INTERNAL);
GLES2Interface* gl = ContextGL();
DCHECK(gl);
gl->DeleteBuffers(1, &resource->gl_pixel_buffer_id);
}
if (resource->origin == Resource::EXTERNAL) {
DCHECK(resource->mailbox().IsValid());
gpu::SyncToken sync_token = resource->mailbox().sync_token();
if (IsGpuResourceType(resource->type)) {
DCHECK(resource->mailbox().IsTexture());
GLES2Interface* gl = ContextGL();
DCHECK(gl);
if (resource->gl_id) {
DCHECK_NE(Resource::NEEDS_WAIT, resource->synchronization_state());
gl->DeleteTextures(1, &resource->gl_id);
resource->gl_id = 0;
if (!lost_resource) {
const GLuint64 fence_sync = gl->InsertFenceSyncCHROMIUM();
gl->ShallowFlushCHROMIUM();
gl->GenSyncTokenCHROMIUM(fence_sync, sync_token.GetData());
}
}
} else {
DCHECK(resource->mailbox().IsSharedMemory());
resource->shared_bitmap = nullptr;
resource->pixels = nullptr;
}
resource->release_callback_impl.Run(sync_token, lost_resource,
blocking_main_thread_task_runner_);
}
if (resource->gl_id) {
GLES2Interface* gl = ContextGL();
DCHECK(gl);
gl->DeleteTextures(1, &resource->gl_id);
resource->gl_id = 0;
}
if (resource->shared_bitmap) {
DCHECK(resource->origin != Resource::EXTERNAL);
DCHECK_EQ(RESOURCE_TYPE_BITMAP, resource->type);
delete resource->shared_bitmap;
resource->pixels = nullptr;
}
if (resource->pixels) {
DCHECK(resource->origin == Resource::INTERNAL);
delete[] resource->pixels;
resource->pixels = nullptr;
}
if (resource->gpu_memory_buffer) {
DCHECK(resource->origin == Resource::INTERNAL ||
resource->origin == Resource::DELEGATED);
resource->gpu_memory_buffer.reset();
}
resources_.erase(it);
}
void ResourceProvider::FlushPendingDeletions() const {
if (auto* gl = ContextGL())
gl->ShallowFlushCHROMIUM();
}
ResourceProvider::ResourceType ResourceProvider::GetResourceType(
ResourceId id) {
return GetResource(id)->type;
}
GLenum ResourceProvider::GetResourceTextureTarget(ResourceId id) {
return GetResource(id)->target;
}
bool ResourceProvider::IsImmutable(ResourceId id) {
if (IsGpuResourceType(settings_.default_resource_type)) {
return GetTextureHint(id) == TEXTURE_HINT_IMMUTABLE;
} else {
// Software resources are immutable; they cannot change format or be
// resized.
return true;
}
}
ResourceProvider::TextureHint ResourceProvider::GetTextureHint(ResourceId id) {
return GetResource(id)->hint;
}
gfx::ColorSpace ResourceProvider::GetResourceColorSpaceForRaster(
const Resource* resource) const {
if (!settings_.enable_color_correct_rasterization)
return gfx::ColorSpace();
return resource->color_space;
}
void ResourceProvider::CopyToResource(ResourceId id,
const uint8_t* image,
const gfx::Size& image_size) {
Resource* resource = GetResource(id);
DCHECK(!resource->locked_for_write);
DCHECK(!resource->lock_for_read_count);
DCHECK(resource->origin == Resource::INTERNAL);
DCHECK_EQ(resource->exported_count, 0);
DCHECK(ReadLockFenceHasPassed(resource));
DCHECK_EQ(image_size.width(), resource->size.width());
DCHECK_EQ(image_size.height(), resource->size.height());
if (resource->allocated)
WaitSyncTokenIfNeeded(id);
if (resource->type == RESOURCE_TYPE_BITMAP) {
DCHECK_EQ(RESOURCE_TYPE_BITMAP, resource->type);
DCHECK(resource->allocated);
DCHECK_EQ(viz::RGBA_8888, resource->format);
SkImageInfo source_info =
SkImageInfo::MakeN32Premul(image_size.width(), image_size.height());
size_t image_stride = image_size.width() * 4;
ScopedWriteLockSoftware lock(this, id);
SkCanvas dest(lock.sk_bitmap());
dest.writePixels(source_info, image, image_stride, 0, 0);
} else {
ScopedWriteLockGL lock(this, id, false);
unsigned resource_texture_id = lock.texture_id();
DCHECK(resource_texture_id);
GLES2Interface* gl = ContextGL();
DCHECK(gl);
gl->BindTexture(resource->target, resource_texture_id);
if (resource->format == viz::ETC1) {
DCHECK_EQ(resource->target, static_cast<GLenum>(GL_TEXTURE_2D));
int image_bytes =
ResourceUtil::CheckedSizeInBytes<int>(image_size, viz::ETC1);
gl->CompressedTexImage2D(resource->target, 0, GLInternalFormat(viz::ETC1),
image_size.width(), image_size.height(), 0,
image_bytes, image);
} else {
gl->TexSubImage2D(resource->target, 0, 0, 0, image_size.width(),
image_size.height(), GLDataFormat(resource->format),
GLDataType(resource->format), image);
}
const uint64_t fence_sync = gl->InsertFenceSyncCHROMIUM();
gl->OrderingBarrierCHROMIUM();
gpu::SyncToken sync_token;
gl->GenUnverifiedSyncTokenCHROMIUM(fence_sync, sync_token.GetData());
lock.set_sync_token(sync_token);
lock.set_synchronized(true);
}
}
void ResourceProvider::GenerateSyncTokenForResource(ResourceId resource_id) {
Resource* resource = GetResource(resource_id);
if (!resource->needs_sync_token())
return;
gpu::SyncToken sync_token;
GLES2Interface* gl = ContextGL();
DCHECK(gl);
const uint64_t fence_sync = gl->InsertFenceSyncCHROMIUM();
gl->OrderingBarrierCHROMIUM();
gl->GenUnverifiedSyncTokenCHROMIUM(fence_sync, sync_token.GetData());
resource->UpdateSyncToken(sync_token);
resource->SetSynchronized();
}
void ResourceProvider::GenerateSyncTokenForResources(
const ResourceIdArray& resource_ids) {
gpu::SyncToken sync_token;
bool created_sync_token = false;
for (ResourceId id : resource_ids) {
Resource* resource = GetResource(id);
if (resource->needs_sync_token()) {
if (!created_sync_token) {
GLES2Interface* gl = ContextGL();
DCHECK(gl);
const uint64_t fence_sync = gl->InsertFenceSyncCHROMIUM();
gl->OrderingBarrierCHROMIUM();
gl->GenUnverifiedSyncTokenCHROMIUM(fence_sync, sync_token.GetData());
created_sync_token = true;
}
resource->UpdateSyncToken(sync_token);
resource->SetSynchronized();
}
}
}
gpu::SyncToken ResourceProvider::GetSyncTokenForResources(
const ResourceIdArray& resource_ids) {
gpu::SyncToken latest_sync_token;
for (ResourceId id : resource_ids) {
const gpu::SyncToken& sync_token = GetResource(id)->mailbox().sync_token();
if (sync_token.release_count() > latest_sync_token.release_count())
latest_sync_token = sync_token;
}
return latest_sync_token;
}
ResourceProvider::Resource* ResourceProvider::InsertResource(
ResourceId id,
Resource resource) {
std::pair<ResourceMap::iterator, bool> result =
resources_.insert(ResourceMap::value_type(id, std::move(resource)));
DCHECK(result.second);
return &result.first->second;
}
ResourceProvider::Resource* ResourceProvider::GetResource(ResourceId id) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(id);
ResourceMap::iterator it = resources_.find(id);
DCHECK(it != resources_.end());
return &it->second;
}
const ResourceProvider::Resource* ResourceProvider::LockForRead(ResourceId id) {
Resource* resource = GetResource(id);
DCHECK(!resource->locked_for_write) << "locked for write: "
<< resource->locked_for_write;
DCHECK_EQ(resource->exported_count, 0);
// Uninitialized! Call SetPixels or LockForWrite first.
DCHECK(resource->allocated);
// Mailbox sync_tokens must be processed by a call to
// WaitSyncTokenIfNeeded() prior to calling LockForRead().
DCHECK_NE(Resource::NEEDS_WAIT, resource->synchronization_state());
LazyCreate(resource);
if (IsGpuResourceType(resource->type) && !resource->gl_id) {
DCHECK(resource->origin != Resource::INTERNAL);
DCHECK(resource->mailbox().IsTexture());
GLES2Interface* gl = ContextGL();
DCHECK(gl);
resource->gl_id = gl->CreateAndConsumeTextureCHROMIUM(
resource->mailbox().target(), resource->mailbox().name());
resource->SetLocallyUsed();
}
if (!resource->pixels && resource->has_shared_bitmap_id &&
shared_bitmap_manager_) {
std::unique_ptr<viz::SharedBitmap> bitmap =
shared_bitmap_manager_->GetSharedBitmapFromId(
resource->size, resource->shared_bitmap_id);
if (bitmap) {
resource->shared_bitmap = bitmap.release();
resource->pixels = resource->shared_bitmap->pixels();
}
}
resource->lock_for_read_count++;
if (resource->read_lock_fences_enabled) {
if (current_read_lock_fence_.get())
current_read_lock_fence_->Set();
resource->read_lock_fence = current_read_lock_fence_;
}
return resource;
}
void ResourceProvider::UnlockForRead(ResourceId id) {
DCHECK(thread_checker_.CalledOnValidThread());
ResourceMap::iterator it = resources_.find(id);
CHECK(it != resources_.end());
Resource* resource = &it->second;
DCHECK_GT(resource->lock_for_read_count, 0);
DCHECK_EQ(resource->exported_count, 0);
resource->lock_for_read_count--;
if (resource->marked_for_deletion && !resource->lock_for_read_count) {
if (!resource->child_id) {
// The resource belongs to this ResourceProvider, so it can be destroyed.
DeleteResourceInternal(it, NORMAL);
} else {
if (batch_return_resources_) {
batched_returning_resources_[resource->child_id].push_back(id);
} else {
ChildMap::iterator child_it = children_.find(resource->child_id);
ResourceIdArray unused;
unused.push_back(id);
DeleteAndReturnUnusedResourcesToChild(child_it, NORMAL, unused);
}
}
}
}
ResourceProvider::Resource* ResourceProvider::LockForWrite(ResourceId id) {
Resource* resource = GetResource(id);
DCHECK(CanLockForWrite(id));
if (resource->allocated)
WaitSyncTokenIfNeeded(id);
resource->locked_for_write = true;
resource->SetLocallyUsed();
return resource;
}
bool ResourceProvider::CanLockForWrite(ResourceId id) {
Resource* resource = GetResource(id);
return !resource->locked_for_write && !resource->lock_for_read_count &&
!resource->exported_count && resource->origin == Resource::INTERNAL &&
!resource->lost && ReadLockFenceHasPassed(resource);
}
bool ResourceProvider::IsOverlayCandidate(ResourceId id) {
Resource* resource = GetResource(id);
return resource->is_overlay_candidate;
}
gfx::BufferFormat ResourceProvider::GetBufferFormat(ResourceId id) {
Resource* resource = GetResource(id);
return resource->buffer_format;
}
#if defined(OS_ANDROID)
bool ResourceProvider::IsBackedBySurfaceTexture(ResourceId id) {
Resource* resource = GetResource(id);
return resource->is_backed_by_surface_texture;
}
bool ResourceProvider::WantsPromotionHint(ResourceId id) {
return wants_promotion_hints_set_.count(id) > 0;
}
size_t ResourceProvider::CountPromotionHintRequestsForTesting() {
return wants_promotion_hints_set_.size();
}
#endif
void ResourceProvider::UnlockForWrite(Resource* resource) {
DCHECK(resource->locked_for_write);
DCHECK_EQ(resource->exported_count, 0);
DCHECK(resource->origin == Resource::INTERNAL);
resource->locked_for_write = false;
}
void ResourceProvider::EnableReadLockFencesForTesting(ResourceId id) {
Resource* resource = GetResource(id);
DCHECK(resource);
resource->read_lock_fences_enabled = true;
}
ResourceProvider::ScopedReadLockGL::ScopedReadLockGL(
ResourceProvider* resource_provider,
ResourceId resource_id)
: resource_provider_(resource_provider), resource_id_(resource_id) {
const Resource* resource = resource_provider->LockForRead(resource_id);
texture_id_ = resource->gl_id;
target_ = resource->target;
size_ = resource->size;
color_space_ = resource->color_space;
}
ResourceProvider::ScopedReadLockGL::~ScopedReadLockGL() {
resource_provider_->UnlockForRead(resource_id_);
}
ResourceProvider::ScopedSamplerGL::ScopedSamplerGL(
ResourceProvider* resource_provider,
ResourceId resource_id,
GLenum filter)
: resource_lock_(resource_provider, resource_id),
unit_(GL_TEXTURE0),
target_(resource_provider->BindForSampling(resource_id, unit_, filter)) {}
ResourceProvider::ScopedSamplerGL::ScopedSamplerGL(
ResourceProvider* resource_provider,
ResourceId resource_id,
GLenum unit,
GLenum filter)
: resource_lock_(resource_provider, resource_id),
unit_(unit),
target_(resource_provider->BindForSampling(resource_id, unit_, filter)) {}
ResourceProvider::ScopedSamplerGL::~ScopedSamplerGL() {}
ResourceProvider::ScopedWriteLockGL::ScopedWriteLockGL(
ResourceProvider* resource_provider,
ResourceId resource_id,
bool create_mailbox)
: resource_provider_(resource_provider),
resource_id_(resource_id),
has_sync_token_(false),
synchronized_(false) {
DCHECK(thread_checker_.CalledOnValidThread());
Resource* resource = resource_provider->LockForWrite(resource_id);
resource_provider_->LazyAllocate(resource);
if (resource->image_id && resource->dirty_image)
resource_provider_->BindImageForSampling(resource);
if (create_mailbox) {
resource_provider_->CreateMailboxAndBindResource(
resource_provider_->ContextGL(), resource);
}
texture_id_ = resource->gl_id;
target_ = resource->target;
format_ = resource->format;
size_ = resource->size;
mailbox_ = resource->mailbox();
color_space_ = resource_provider->GetResourceColorSpaceForRaster(resource);
}
ResourceProvider::ScopedWriteLockGL::~ScopedWriteLockGL() {
DCHECK(thread_checker_.CalledOnValidThread());
Resource* resource = resource_provider_->GetResource(resource_id_);
DCHECK(resource->locked_for_write);
// It's not sufficient to check sync_token_.HasData() here because the sync
// might be null because of context loss. Even in that case we want to set the
// sync token because it's checked in PrepareSendToParent while drawing.
if (has_sync_token_)
resource->UpdateSyncToken(sync_token_);
if (synchronized_)
resource->SetSynchronized();
resource_provider_->UnlockForWrite(resource);
}
ResourceProvider::ScopedTextureProvider::ScopedTextureProvider(
gpu::gles2::GLES2Interface* gl,
ScopedWriteLockGL* resource_lock,
bool use_mailbox)
: gl_(gl), use_mailbox_(use_mailbox) {
if (use_mailbox_) {
texture_id_ = gl_->CreateAndConsumeTextureCHROMIUM(
resource_lock->target(), resource_lock->mailbox().name());
} else {
texture_id_ = resource_lock->texture_id();
}
DCHECK(texture_id_);
}
ResourceProvider::ScopedTextureProvider::~ScopedTextureProvider() {
if (use_mailbox_)
gl_->DeleteTextures(1, &texture_id_);
}
ResourceProvider::ScopedSkSurfaceProvider::ScopedSkSurfaceProvider(
viz::ContextProvider* context_provider,
ScopedWriteLockGL* resource_lock,
bool use_mailbox,
bool use_distance_field_text,
bool can_use_lcd_text,
int msaa_sample_count)
: texture_provider_(context_provider->ContextGL(),
resource_lock,
use_mailbox) {
GrGLTextureInfo texture_info;
texture_info.fID = texture_provider_.texture_id();
texture_info.fTarget = resource_lock->target();
GrBackendTexture backend_texture(
resource_lock->size().width(), resource_lock->size().height(),
ToGrPixelConfig(resource_lock->format()), texture_info);
uint32_t flags =
use_distance_field_text ? SkSurfaceProps::kUseDistanceFieldFonts_Flag : 0;
// Use unknown pixel geometry to disable LCD text.
SkSurfaceProps surface_props(flags, kUnknown_SkPixelGeometry);
if (can_use_lcd_text) {
// LegacyFontHost will get LCD text and skia figures out what type to use.
surface_props =
SkSurfaceProps(flags, SkSurfaceProps::kLegacyFontHost_InitType);
}
sk_surface_ = SkSurface::MakeFromBackendTextureAsRenderTarget(
context_provider->GrContext(), backend_texture, kTopLeft_GrSurfaceOrigin,
msaa_sample_count, nullptr, &surface_props);
}
ResourceProvider::ScopedSkSurfaceProvider::~ScopedSkSurfaceProvider() {
if (sk_surface_.get()) {
sk_surface_->prepareForExternalIO();
sk_surface_.reset();
}
}
void ResourceProvider::PopulateSkBitmapWithResource(SkBitmap* sk_bitmap,
const Resource* resource) {
DCHECK_EQ(viz::RGBA_8888, resource->format);
SkImageInfo info = SkImageInfo::MakeN32Premul(resource->size.width(),
resource->size.height());
sk_bitmap->installPixels(info, resource->pixels, info.minRowBytes());
}
ResourceProvider::ScopedReadLockSoftware::ScopedReadLockSoftware(
ResourceProvider* resource_provider,
ResourceId resource_id)
: resource_provider_(resource_provider), resource_id_(resource_id) {
const Resource* resource = resource_provider->LockForRead(resource_id);
resource_provider->PopulateSkBitmapWithResource(&sk_bitmap_, resource);
}
ResourceProvider::ScopedReadLockSoftware::~ScopedReadLockSoftware() {
resource_provider_->UnlockForRead(resource_id_);
}
ResourceProvider::ScopedReadLockSkImage::ScopedReadLockSkImage(
ResourceProvider* resource_provider,
ResourceId resource_id)
: resource_provider_(resource_provider), resource_id_(resource_id) {
const Resource* resource = resource_provider->LockForRead(resource_id);
if (resource->gl_id) {
GrGLTextureInfo texture_info;
texture_info.fID = resource->gl_id;
texture_info.fTarget = resource->target;
GrBackendTexture backend_texture(
resource->size.width(), resource->size.height(),
ToGrPixelConfig(resource->format), texture_info);
sk_image_ = SkImage::MakeFromTexture(
resource_provider->compositor_context_provider_->GrContext(),
backend_texture, kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType,
nullptr);
} else if (resource->pixels) {
SkBitmap sk_bitmap;
resource_provider->PopulateSkBitmapWithResource(&sk_bitmap, resource);
sk_bitmap.setImmutable();
sk_image_ = SkImage::MakeFromBitmap(sk_bitmap);
} else {
// During render process shutdown, ~RenderMessageFilter which calls
// ~HostSharedBitmapClient (which deletes shared bitmaps from child)
// can race with OnBeginFrameDeadline which draws a frame.
// In these cases, shared bitmaps (and this read lock) won't be valid.
// Renderers need to silently handle locks failing until this race
// is fixed. DCHECK that this is the only case where there are no pixels.
DCHECK(!resource->shared_bitmap_id.IsZero());
}
}
ResourceProvider::ScopedReadLockSkImage::~ScopedReadLockSkImage() {
resource_provider_->UnlockForRead(resource_id_);
}
ResourceProvider::ScopedWriteLockSoftware::ScopedWriteLockSoftware(
ResourceProvider* resource_provider,
ResourceId resource_id)
: resource_provider_(resource_provider), resource_id_(resource_id) {
Resource* resource = resource_provider->LockForWrite(resource_id);
resource_provider->PopulateSkBitmapWithResource(&sk_bitmap_, resource);
color_space_ = resource_provider->GetResourceColorSpaceForRaster(resource);
DCHECK(valid());
}
ResourceProvider::ScopedWriteLockSoftware::~ScopedWriteLockSoftware() {
DCHECK(thread_checker_.CalledOnValidThread());
Resource* resource = resource_provider_->GetResource(resource_id_);
DCHECK(resource);
resource->SetSynchronized();
resource_provider_->UnlockForWrite(resource);
}
ResourceProvider::ScopedWriteLockGpuMemoryBuffer::
ScopedWriteLockGpuMemoryBuffer(ResourceProvider* resource_provider,
ResourceId resource_id)
: resource_provider_(resource_provider), resource_id_(resource_id) {
Resource* resource = resource_provider->LockForWrite(resource_id);
DCHECK(IsGpuResourceType(resource->type));
format_ = resource->format;
size_ = resource->size;
usage_ = resource->usage;
gpu_memory_buffer_ = std::move(resource->gpu_memory_buffer);
resource->gpu_memory_buffer = nullptr;
color_space_ = resource_provider->GetResourceColorSpaceForRaster(resource);
}
ResourceProvider::ScopedWriteLockGpuMemoryBuffer::
~ScopedWriteLockGpuMemoryBuffer() {
DCHECK(thread_checker_.CalledOnValidThread());
Resource* resource = resource_provider_->GetResource(resource_id_);
DCHECK(resource);
if (gpu_memory_buffer_) {
// Note that this impacts overlay compositing, not rasterization.
if (resource_provider_->settings_.enable_color_correct_rasterization)
gpu_memory_buffer_->SetColorSpaceForScanout(resource->color_space);
DCHECK(!resource->gpu_memory_buffer);
resource_provider_->LazyCreate(resource);
resource->gpu_memory_buffer = std::move(gpu_memory_buffer_);
resource->allocated = true;
resource_provider_->LazyCreateImage(resource);
resource->dirty_image = true;
resource->is_overlay_candidate = true;
// GpuMemoryBuffer provides direct access to the memory used by the GPU.
// Read lock fences are required to ensure that we're not trying to map a
// buffer that is currently in-use by the GPU.
resource->read_lock_fences_enabled = true;
}
resource->SetSynchronized();
resource_provider_->UnlockForWrite(resource);
}
gfx::GpuMemoryBuffer*
ResourceProvider::ScopedWriteLockGpuMemoryBuffer::GetGpuMemoryBuffer() {
if (!gpu_memory_buffer_) {
gpu_memory_buffer_ =
resource_provider_->gpu_memory_buffer_manager_->CreateGpuMemoryBuffer(
size_, BufferFormat(format_), usage_, gpu::kNullSurfaceHandle);
}
return gpu_memory_buffer_.get();
}
ResourceProvider::ScopedBatchReturnResources::ScopedBatchReturnResources(
ResourceProvider* resource_provider)
: resource_provider_(resource_provider) {
resource_provider_->SetBatchReturnResources(true);
}
ResourceProvider::ScopedBatchReturnResources::~ScopedBatchReturnResources() {
resource_provider_->SetBatchReturnResources(false);
}
ResourceProvider::SynchronousFence::SynchronousFence(
gpu::gles2::GLES2Interface* gl)
: gl_(gl), has_synchronized_(true) {}
ResourceProvider::SynchronousFence::~SynchronousFence() {}
void ResourceProvider::SynchronousFence::Set() {
has_synchronized_ = false;
}
bool ResourceProvider::SynchronousFence::HasPassed() {
if (!has_synchronized_) {
has_synchronized_ = true;
Synchronize();
}
return true;
}
void ResourceProvider::SynchronousFence::Wait() {
HasPassed();
}
void ResourceProvider::SynchronousFence::Synchronize() {
TRACE_EVENT0("cc", "ResourceProvider::SynchronousFence::Synchronize");
gl_->Finish();
}
int ResourceProvider::CreateChild(const ReturnCallback& return_callback) {
DCHECK(thread_checker_.CalledOnValidThread());
Child child_info;
child_info.return_callback = return_callback;
int child = next_child_++;
children_[child] = child_info;
return child;
}
void ResourceProvider::SetChildNeedsSyncTokens(int child_id, bool needs) {
ChildMap::iterator it = children_.find(child_id);
DCHECK(it != children_.end());
it->second.needs_sync_tokens = needs;
}
void ResourceProvider::DestroyChild(int child_id) {
ChildMap::iterator it = children_.find(child_id);
DCHECK(it != children_.end());
DestroyChildInternal(it, NORMAL);
}
void ResourceProvider::DestroyChildInternal(ChildMap::iterator it,
DeleteStyle style) {
DCHECK(thread_checker_.CalledOnValidThread());
Child& child = it->second;
DCHECK(style == FOR_SHUTDOWN || !child.marked_for_deletion);
ResourceIdArray resources_for_child;
for (ResourceIdMap::iterator child_it = child.child_to_parent_map.begin();
child_it != child.child_to_parent_map.end(); ++child_it) {
ResourceId id = child_it->second;
resources_for_child.push_back(id);
}
child.marked_for_deletion = true;
DeleteAndReturnUnusedResourcesToChild(it, style, resources_for_child);
}
const ResourceProvider::ResourceIdMap& ResourceProvider::GetChildToParentMap(
int child) const {
DCHECK(thread_checker_.CalledOnValidThread());
ChildMap::const_iterator it = children_.find(child);
DCHECK(it != children_.end());
DCHECK(!it->second.marked_for_deletion);
return it->second.child_to_parent_map;
}
void ResourceProvider::PrepareSendToParent(
const ResourceIdArray& resource_ids,
std::vector<TransferableResource>* list) {
DCHECK(thread_checker_.CalledOnValidThread());
GLES2Interface* gl = ContextGL();
// This function goes through the array multiple times, store the resources
// as pointers so we don't have to look up the resource id multiple times.
std::vector<Resource*> resources;
resources.reserve(resource_ids.size());
for (const ResourceId id : resource_ids) {
Resource* resource = GetResource(id);
// Check the synchronization and sync token state when delegated sync points
// are required. The only case where we allow a sync token to not be set is
// the case where the image is dirty. In that case we will bind the image
// lazily and generate a sync token at that point.
DCHECK(!settings_.delegated_sync_points_required || resource->dirty_image ||
!resource->needs_sync_token());
// If we are validating the resource to be sent, the resource cannot be
// in a LOCALLY_USED state. It must have been properly synchronized.
DCHECK(!settings_.delegated_sync_points_required ||
Resource::LOCALLY_USED != resource->synchronization_state());
resources.push_back(resource);
}
// Lazily create any mailboxes and verify all unverified sync tokens.
std::vector<GLbyte*> unverified_sync_tokens;
std::vector<Resource*> need_synchronization_resources;
for (Resource* resource : resources) {
if (!IsGpuResourceType(resource->type))
continue;
CreateMailboxAndBindResource(gl, resource);
if (settings_.delegated_sync_points_required) {
if (resource->needs_sync_token()) {
need_synchronization_resources.push_back(resource);
} else if (resource->mailbox().HasSyncToken() &&
!resource->mailbox().sync_token().verified_flush()) {
unverified_sync_tokens.push_back(resource->GetSyncTokenData());
}
}
}
// Insert sync point to synchronize the mailbox creation or bound textures.
gpu::SyncToken new_sync_token;
if (!need_synchronization_resources.empty()) {
DCHECK(settings_.delegated_sync_points_required);
DCHECK(gl);
const uint64_t fence_sync = gl->InsertFenceSyncCHROMIUM();
gl->OrderingBarrierCHROMIUM();
gl->GenUnverifiedSyncTokenCHROMIUM(fence_sync, new_sync_token.GetData());
unverified_sync_tokens.push_back(new_sync_token.GetData());
}
if (!unverified_sync_tokens.empty()) {
DCHECK(settings_.delegated_sync_points_required);
DCHECK(gl);
gl->VerifySyncTokensCHROMIUM(unverified_sync_tokens.data(),
unverified_sync_tokens.size());
}
// Set sync token after verification.
for (Resource* resource : need_synchronization_resources) {
DCHECK(IsGpuResourceType(resource->type));
resource->UpdateSyncToken(new_sync_token);
resource->SetSynchronized();
}
// Transfer Resources
DCHECK_EQ(resources.size(), resource_ids.size());
for (size_t i = 0; i < resources.size(); ++i) {
Resource* source = resources[i];
const ResourceId id = resource_ids[i];
DCHECK(!settings_.delegated_sync_points_required ||
!source->needs_sync_token());
DCHECK(!settings_.delegated_sync_points_required ||
Resource::LOCALLY_USED != source->synchronization_state());
TransferableResource resource;
TransferResource(source, id, &resource);
source->exported_count++;
list->push_back(resource);
}
}
void ResourceProvider::ReceiveFromChild(
int child,
const std::vector<TransferableResource>& resources) {
DCHECK(thread_checker_.CalledOnValidThread());
GLES2Interface* gl = ContextGL();
Child& child_info = children_.find(child)->second;
DCHECK(!child_info.marked_for_deletion);
for (std::vector<TransferableResource>::const_iterator it = resources.begin();
it != resources.end(); ++it) {
ResourceIdMap::iterator resource_in_map_it =
child_info.child_to_parent_map.find(it->id);
if (resource_in_map_it != child_info.child_to_parent_map.end()) {
Resource* resource = GetResource(resource_in_map_it->second);
resource->marked_for_deletion = false;
resource->imported_count++;
continue;
}
if ((!it->is_software && !gl) ||
(it->is_software && !shared_bitmap_manager_)) {
TRACE_EVENT0("cc", "ResourceProvider::ReceiveFromChild dropping invalid");
std::vector<ReturnedResource> to_return;
to_return.push_back(it->ToReturnedResource());
child_info.return_callback.Run(to_return,
blocking_main_thread_task_runner_);
continue;
}
ResourceId local_id = next_id_++;
Resource* resource = nullptr;
if (it->is_software) {
resource = InsertResource(local_id,
Resource(it->mailbox_holder.mailbox, it->size,
Resource::DELEGATED, GL_LINEAR));
} else {
resource = InsertResource(
local_id, Resource(0, it->size, Resource::DELEGATED,
it->mailbox_holder.texture_target, it->filter,
TEXTURE_HINT_IMMUTABLE, RESOURCE_TYPE_GL_TEXTURE,
it->format));
resource->buffer_format = it->buffer_format;
resource->set_mailbox(viz::TextureMailbox(
it->mailbox_holder.mailbox, it->mailbox_holder.sync_token,
it->mailbox_holder.texture_target));
resource->read_lock_fences_enabled = it->read_lock_fences_enabled;
resource->is_overlay_candidate = it->is_overlay_candidate;
#if defined(OS_ANDROID)
resource->is_backed_by_surface_texture = it->is_backed_by_surface_texture;
resource->wants_promotion_hint = it->wants_promotion_hint;
if (resource->wants_promotion_hint)
wants_promotion_hints_set_.insert(local_id);
#endif
resource->color_space = it->color_space;
}
resource->child_id = child;
// Don't allocate a texture for a child.
resource->allocated = true;
resource->imported_count = 1;
resource->id_in_child = it->id;
child_info.child_to_parent_map[it->id] = local_id;
}
}
void ResourceProvider::DeclareUsedResourcesFromChild(
int child,
const ResourceIdSet& resources_from_child) {
DCHECK(thread_checker_.CalledOnValidThread());
ChildMap::iterator child_it = children_.find(child);
DCHECK(child_it != children_.end());
Child& child_info = child_it->second;
DCHECK(!child_info.marked_for_deletion);
ResourceIdArray unused;
for (ResourceIdMap::iterator it = child_info.child_to_parent_map.begin();
it != child_info.child_to_parent_map.end(); ++it) {
ResourceId local_id = it->second;
bool resource_is_in_use = resources_from_child.count(it->first) > 0;
if (!resource_is_in_use)
unused.push_back(local_id);
}
DeleteAndReturnUnusedResourcesToChild(child_it, NORMAL, unused);
}
void ResourceProvider::ReceiveReturnsFromParent(
const std::vector<ReturnedResource>& resources) {
DCHECK(thread_checker_.CalledOnValidThread());
GLES2Interface* gl = ContextGL();
std::unordered_map<int, ResourceIdArray> resources_for_child;
for (const ReturnedResource& returned : resources) {
ResourceId local_id = returned.id;
ResourceMap::iterator map_iterator = resources_.find(local_id);
// Resource was already lost (e.g. it belonged to a child that was
// destroyed).
if (map_iterator == resources_.end())
continue;
Resource* resource = &map_iterator->second;
CHECK_GE(resource->exported_count, returned.count);
resource->exported_count -= returned.count;
resource->lost |= returned.lost;
if (resource->exported_count)
continue;
if (returned.sync_token.HasData()) {
DCHECK(!resource->has_shared_bitmap_id);
if (resource->origin == Resource::INTERNAL) {
DCHECK(resource->gl_id);
DCHECK(returned.sync_token.HasData());
gl->WaitSyncTokenCHROMIUM(returned.sync_token.GetConstData());
resource->SetSynchronized();
} else {
DCHECK(!resource->gl_id);
resource->UpdateSyncToken(returned.sync_token);
}
}
if (!resource->marked_for_deletion)
continue;
if (!resource->child_id) {
// The resource belongs to this ResourceProvider, so it can be destroyed.
DeleteResourceInternal(map_iterator, NORMAL);
continue;
}
DCHECK(resource->origin == Resource::DELEGATED);
resources_for_child[resource->child_id].push_back(local_id);
}
for (const auto& children : resources_for_child) {
ChildMap::iterator child_it = children_.find(children.first);
DCHECK(child_it != children_.end());
DeleteAndReturnUnusedResourcesToChild(child_it, NORMAL, children.second);
}
}
void ResourceProvider::SetBatchReturnResources(bool batch) {
DCHECK_NE(batch_return_resources_, batch);
batch_return_resources_ = batch;
if (!batch) {
for (const auto& resources : batched_returning_resources_) {
ChildMap::iterator child_it = children_.find(resources.first);
DCHECK(child_it != children_.end());
DeleteAndReturnUnusedResourcesToChild(child_it, NORMAL, resources.second);
}
batched_returning_resources_.clear();
}
}
#if defined(OS_ANDROID)
void ResourceProvider::SendPromotionHints(
const OverlayCandidateList::PromotionHintInfoMap& promotion_hints) {
GLES2Interface* gl = ContextGL();
if (!gl)
return;
for (const auto& id : wants_promotion_hints_set_) {
const ResourceMap::iterator it = resources_.find(id);
if (it == resources_.end())
continue;
if (it->second.marked_for_deletion)
continue;
const Resource* resource = LockForRead(id);
DCHECK(resource->wants_promotion_hint);
// Insist that this is backed by a GPU texture.
if (IsGpuResourceType(resource->type)) {
DCHECK(resource->gl_id);
auto iter = promotion_hints.find(id);
bool promotable = iter != promotion_hints.end();
gl->OverlayPromotionHintCHROMIUM(resource->gl_id, promotable,
promotable ? iter->second.x() : 0,
promotable ? iter->second.y() : 0);
}
UnlockForRead(id);
}
}
#endif
void ResourceProvider::CreateMailboxAndBindResource(
gpu::gles2::GLES2Interface* gl,
Resource* resource) {
DCHECK(IsGpuResourceType(resource->type));
DCHECK(gl);
if (!resource->mailbox().IsValid()) {
LazyCreate(resource);
gpu::MailboxHolder mailbox_holder;
mailbox_holder.texture_target = resource->target;
gl->GenMailboxCHROMIUM(mailbox_holder.mailbox.name);
gl->ProduceTextureDirectCHROMIUM(resource->gl_id,
mailbox_holder.texture_target,
mailbox_holder.mailbox.name);
resource->set_mailbox(viz::TextureMailbox(mailbox_holder));
}
if (resource->image_id && resource->dirty_image) {
DCHECK(resource->gl_id);
DCHECK(resource->origin == Resource::INTERNAL);
BindImageForSampling(resource);
}
}
void ResourceProvider::TransferResource(Resource* source,
ResourceId id,
TransferableResource* resource) {
DCHECK(!source->locked_for_write);
DCHECK(!source->lock_for_read_count);
DCHECK(source->origin != Resource::EXTERNAL || source->mailbox().IsValid());
DCHECK(source->allocated);
resource->id = id;
resource->format = source->format;
resource->buffer_format = source->buffer_format;
resource->mailbox_holder.texture_target = source->target;
resource->filter = source->filter;
resource->size = source->size;
resource->read_lock_fences_enabled = source->read_lock_fences_enabled;
resource->is_overlay_candidate = source->is_overlay_candidate;
#if defined(OS_ANDROID)
resource->is_backed_by_surface_texture = source->is_backed_by_surface_texture;
resource->wants_promotion_hint = source->wants_promotion_hint;
#endif
resource->color_space = source->color_space;
if (source->type == RESOURCE_TYPE_BITMAP) {
resource->mailbox_holder.mailbox = source->shared_bitmap_id;
resource->is_software = true;
if (source->shared_bitmap) {
resource->shared_bitmap_sequence_number =
source->shared_bitmap->sequence_number();
} else {
resource->shared_bitmap_sequence_number = 0;
}
} else {
DCHECK(source->mailbox().IsValid());
DCHECK(source->mailbox().IsTexture());
DCHECK(!source->image_id || !source->dirty_image);
// This is either an external resource, or a compositor resource that we
// already exported. Make sure to forward the sync point that we were given.
resource->mailbox_holder.mailbox = source->mailbox().mailbox();
resource->mailbox_holder.texture_target = source->mailbox().target();
resource->mailbox_holder.sync_token = source->mailbox().sync_token();
}
}
void ResourceProvider::DeleteAndReturnUnusedResourcesToChild(
ChildMap::iterator child_it,
DeleteStyle style,
const ResourceIdArray& unused) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(child_it != children_.end());
Child* child_info = &child_it->second;
if (unused.empty() && !child_info->marked_for_deletion)
return;
std::vector<ReturnedResource> to_return;
to_return.reserve(unused.size());
std::vector<ReturnedResource*> need_synchronization_resources;
std::vector<GLbyte*> unverified_sync_tokens;
GLES2Interface* gl = ContextGL();
for (ResourceId local_id : unused) {
ResourceMap::iterator it = resources_.find(local_id);
CHECK(it != resources_.end());
Resource& resource = it->second;
DCHECK(!resource.locked_for_write);
ResourceId child_id = resource.id_in_child;
DCHECK(child_info->child_to_parent_map.count(child_id));
bool is_lost = resource.lost ||
(IsGpuResourceType(resource.type) && lost_context_provider_);
if (resource.exported_count > 0 || resource.lock_for_read_count > 0) {
if (style != FOR_SHUTDOWN) {
// Defer this resource deletion.
resource.marked_for_deletion = true;
continue;
}
// We can't postpone the deletion, so we'll have to lose it.
is_lost = true;
} else if (!ReadLockFenceHasPassed(&resource)) {
// TODO(dcastagna): see if it's possible to use this logic for
// the branch above too, where the resource is locked or still exported.
if (style != FOR_SHUTDOWN && !child_info->marked_for_deletion) {
// Defer this resource deletion.
resource.marked_for_deletion = true;
continue;
}
// We can't postpone the deletion, so we'll have to lose it.
is_lost = true;
}
if (IsGpuResourceType(resource.type) &&
resource.filter != resource.original_filter) {
DCHECK(resource.target);
DCHECK(resource.gl_id);
DCHECK(gl);
gl->BindTexture(resource.target, resource.gl_id);
gl->TexParameteri(resource.target, GL_TEXTURE_MIN_FILTER,
resource.original_filter);
gl->TexParameteri(resource.target, GL_TEXTURE_MAG_FILTER,
resource.original_filter);
resource.SetLocallyUsed();
}
ReturnedResource returned;
returned.id = child_id;
returned.sync_token = resource.mailbox().sync_token();
returned.count = resource.imported_count;
returned.lost = is_lost;
to_return.push_back(returned);
if (IsGpuResourceType(resource.type) && child_info->needs_sync_tokens) {
if (resource.needs_sync_token()) {
need_synchronization_resources.push_back(&to_return.back());
} else if (returned.sync_token.HasData() &&
!returned.sync_token.verified_flush()) {
// Before returning any sync tokens, they must be verified.
unverified_sync_tokens.push_back(returned.sync_token.GetData());
}
}
child_info->child_to_parent_map.erase(child_id);
resource.imported_count = 0;
DeleteResourceInternal(it, style);
}
gpu::SyncToken new_sync_token;
if (!need_synchronization_resources.empty()) {
DCHECK(child_info->needs_sync_tokens);
DCHECK(gl);
const uint64_t fence_sync = gl->InsertFenceSyncCHROMIUM();
gl->OrderingBarrierCHROMIUM();
gl->GenUnverifiedSyncTokenCHROMIUM(fence_sync, new_sync_token.GetData());
unverified_sync_tokens.push_back(new_sync_token.GetData());
}
if (!unverified_sync_tokens.empty()) {
DCHECK(child_info->needs_sync_tokens);
DCHECK(gl);
gl->VerifySyncTokensCHROMIUM(unverified_sync_tokens.data(),
unverified_sync_tokens.size());
}
// Set sync token after verification.
for (ReturnedResource* returned : need_synchronization_resources)
returned->sync_token = new_sync_token;
if (!to_return.empty())
child_info->return_callback.Run(to_return,
blocking_main_thread_task_runner_);
if (child_info->marked_for_deletion &&
child_info->child_to_parent_map.empty()) {
children_.erase(child_it);
}
}
GLenum ResourceProvider::BindForSampling(ResourceId resource_id,
GLenum unit,
GLenum filter) {
DCHECK(thread_checker_.CalledOnValidThread());
GLES2Interface* gl = ContextGL();
ResourceMap::iterator it = resources_.find(resource_id);
DCHECK(it != resources_.end());
Resource* resource = &it->second;
DCHECK(resource->lock_for_read_count);
DCHECK(!resource->locked_for_write);
ScopedSetActiveTexture scoped_active_tex(gl, unit);
GLenum target = resource->target;
gl->BindTexture(target, resource->gl_id);
if (filter != resource->filter) {
gl->TexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);
gl->TexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
resource->filter = filter;
}
if (resource->image_id && resource->dirty_image)
BindImageForSampling(resource);
return target;
}
void ResourceProvider::CreateForTesting(ResourceId id) {
LazyCreate(GetResource(id));
}
void ResourceProvider::LazyCreate(Resource* resource) {
if (!IsGpuResourceType(resource->type) ||
resource->origin != Resource::INTERNAL)
return;
if (resource->gl_id)
return;
DCHECK(resource->origin == Resource::INTERNAL);
DCHECK(!resource->mailbox().IsValid());
resource->gl_id = texture_id_allocator_->NextId();
GLES2Interface* gl = ContextGL();
DCHECK(gl);
// Create and set texture properties. Allocation is delayed until needed.
gl->BindTexture(resource->target, resource->gl_id);
gl->TexParameteri(resource->target, GL_TEXTURE_MIN_FILTER,
resource->original_filter);
gl->TexParameteri(resource->target, GL_TEXTURE_MAG_FILTER,
resource->original_filter);
gl->TexParameteri(resource->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl->TexParameteri(resource->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (settings_.use_texture_usage_hint &&
(resource->hint & TEXTURE_HINT_FRAMEBUFFER)) {
gl->TexParameteri(resource->target, GL_TEXTURE_USAGE_ANGLE,
GL_FRAMEBUFFER_ATTACHMENT_ANGLE);
}
}
void ResourceProvider::AllocateForTesting(ResourceId id) {
LazyAllocate(GetResource(id));
}
void ResourceProvider::LazyAllocate(Resource* resource) {
DCHECK(resource);
if (resource->allocated)
return;
LazyCreate(resource);
if (!resource->gl_id)
return;
resource->allocated = true;
GLES2Interface* gl = ContextGL();
gfx::Size& size = resource->size;
viz::ResourceFormat format = resource->format;
gl->BindTexture(resource->target, resource->gl_id);
if (resource->type == RESOURCE_TYPE_GPU_MEMORY_BUFFER) {
resource->gpu_memory_buffer =
gpu_memory_buffer_manager_->CreateGpuMemoryBuffer(
size, BufferFormat(format), resource->usage,
gpu::kNullSurfaceHandle);
// Note that this impacts overlay compositing, not rasterization.
if (resource->gpu_memory_buffer &&
settings_.enable_color_correct_rasterization) {
resource->gpu_memory_buffer->SetColorSpaceForScanout(
resource->color_space);
}
LazyCreateImage(resource);
resource->dirty_image = true;
resource->is_overlay_candidate = true;
// GpuMemoryBuffer provides direct access to the memory used by the GPU.
// Read lock fences are required to ensure that we're not trying to map a
// buffer that is currently in-use by the GPU.
resource->read_lock_fences_enabled = true;
} else if (settings_.use_texture_storage_ext &&
IsFormatSupportedForStorage(format,
settings_.use_texture_format_bgra) &&
(resource->hint & TEXTURE_HINT_IMMUTABLE)) {
GLenum storage_format = TextureToStorageFormat(format);
gl->TexStorage2DEXT(resource->target, 1, storage_format, size.width(),
size.height());
} else {
// viz::ETC1 does not support preallocation.
if (format != viz::ETC1) {
gl->TexImage2D(resource->target, 0, GLInternalFormat(format),
size.width(), size.height(), 0, GLDataFormat(format),
GLDataType(format), nullptr);
}
}
}
void ResourceProvider::LazyCreateImage(Resource* resource) {
DCHECK(resource->gpu_memory_buffer);
DCHECK(resource->gl_id);
DCHECK(resource->allocated);
// Avoid crashing in release builds if GpuMemoryBuffer allocation fails.
// http://crbug.com/554541
if (!resource->gpu_memory_buffer)
return;
if (!resource->image_id) {
GLES2Interface* gl = ContextGL();
DCHECK(gl);
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
// TODO(reveman): This avoids a performance problem on ARM ChromeOS
// devices. This only works with shared memory backed buffers.
// crbug.com/580166
DCHECK_EQ(resource->gpu_memory_buffer->GetHandle().type,
gfx::SHARED_MEMORY_BUFFER);
#endif
resource->image_id = gl->CreateImageCHROMIUM(
resource->gpu_memory_buffer->AsClientBuffer(), resource->size.width(),
resource->size.height(), GLInternalFormat(resource->format));
DCHECK(resource->image_id || IsGLContextLost());
resource->SetLocallyUsed();
}
}
void ResourceProvider::BindImageForSampling(Resource* resource) {
GLES2Interface* gl = ContextGL();
DCHECK(resource->gl_id);
DCHECK(resource->image_id);
// Release image currently bound to texture.
gl->BindTexture(resource->target, resource->gl_id);
if (resource->bound_image_id)
gl->ReleaseTexImage2DCHROMIUM(resource->target, resource->bound_image_id);
gl->BindTexImage2DCHROMIUM(resource->target, resource->image_id);
resource->bound_image_id = resource->image_id;
resource->dirty_image = false;
resource->SetLocallyUsed();
}
void ResourceProvider::WaitSyncTokenIfNeeded(ResourceId id) {
Resource* resource = GetResource(id);
DCHECK_EQ(resource->exported_count, 0);
DCHECK(resource->allocated);
if (Resource::NEEDS_WAIT == resource->synchronization_state()) {
DCHECK(IsGpuResourceType(resource->type));
GLES2Interface* gl = ContextGL();
DCHECK(gl);
resource->WaitSyncToken(gl);
}
}
GLint ResourceProvider::GetActiveTextureUnit(GLES2Interface* gl) {
GLint active_unit = 0;
gl->GetIntegerv(GL_ACTIVE_TEXTURE, &active_unit);
return active_unit;
}
GLenum ResourceProvider::GetImageTextureTarget(gfx::BufferUsage usage,
viz::ResourceFormat format) {
gfx::BufferFormat buffer_format = BufferFormat(format);
auto found = buffer_to_texture_target_map_.find(
viz::BufferToTextureTargetKey(usage, buffer_format));
DCHECK(found != buffer_to_texture_target_map_.end());
return found->second;
}
void ResourceProvider::ValidateResource(ResourceId id) const {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(id);
DCHECK(resources_.find(id) != resources_.end());
}
GLES2Interface* ResourceProvider::ContextGL() const {
viz::ContextProvider* context_provider = compositor_context_provider_;
return context_provider ? context_provider->ContextGL() : nullptr;
}
bool ResourceProvider::IsGLContextLost() const {
return ContextGL()->GetGraphicsResetStatusKHR() != GL_NO_ERROR;
}
bool ResourceProvider::OnMemoryDump(
const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) {
DCHECK(thread_checker_.CalledOnValidThread());
const uint64_t tracing_process_id =
base::trace_event::MemoryDumpManager::GetInstance()
->GetTracingProcessId();
for (const auto& resource_entry : resources_) {
const auto& resource = resource_entry.second;
bool backing_memory_allocated = false;
switch (resource.type) {
case RESOURCE_TYPE_GPU_MEMORY_BUFFER:
backing_memory_allocated = !!resource.gpu_memory_buffer;
break;
case RESOURCE_TYPE_GL_TEXTURE:
backing_memory_allocated = !!resource.gl_id;
break;
case RESOURCE_TYPE_BITMAP:
backing_memory_allocated = resource.has_shared_bitmap_id;
break;
}
if (!backing_memory_allocated) {
// Don't log unallocated resources - they have no backing memory.
continue;
}
// Resource IDs are not process-unique, so log with the ResourceProvider's
// unique id.
std::string dump_name =
base::StringPrintf("cc/resource_memory/provider_%d/resource_%d",
tracing_id_, resource_entry.first);
base::trace_event::MemoryAllocatorDump* dump =
pmd->CreateAllocatorDump(dump_name);
uint64_t total_bytes = ResourceUtil::UncheckedSizeInBytesAligned<size_t>(
resource.size, resource.format);
dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
base::trace_event::MemoryAllocatorDump::kUnitsBytes,
static_cast<uint64_t>(total_bytes));
// Resources may be shared across processes and require a shared GUID to
// prevent double counting the memory.
base::trace_event::MemoryAllocatorDumpGuid guid;
base::UnguessableToken shared_memory_guid;
switch (resource.type) {
case RESOURCE_TYPE_GPU_MEMORY_BUFFER:
guid =
resource.gpu_memory_buffer->GetGUIDForTracing(tracing_process_id);
shared_memory_guid =
resource.gpu_memory_buffer->GetHandle().handle.GetGUID();
break;
case RESOURCE_TYPE_GL_TEXTURE:
DCHECK(resource.gl_id);
guid = gl::GetGLTextureClientGUIDForTracing(
compositor_context_provider_->ContextSupport()
->ShareGroupTracingGUID(),
resource.gl_id);
break;
case RESOURCE_TYPE_BITMAP:
DCHECK(resource.has_shared_bitmap_id);
guid = viz::GetSharedBitmapGUIDForTracing(resource.shared_bitmap_id);
if (resource.shared_bitmap) {
shared_memory_guid =
resource.shared_bitmap->GetSharedMemoryHandle().GetGUID();
}
break;
}
DCHECK(!guid.empty());
const int kImportance = 2;
if (!shared_memory_guid.is_empty()) {
pmd->CreateSharedMemoryOwnershipEdge(dump->guid(), guid,
shared_memory_guid, kImportance);
} else {
pmd->CreateSharedGlobalAllocatorDump(guid);
pmd->AddOwnershipEdge(dump->guid(), guid, kImportance);
}
}
return true;
}
} // namespace cc
| 35.159081 | 80 | 0.707221 | [
"geometry",
"render",
"vector"
] |
91357dc9b70c76662b5851d65de8bc71beb07899 | 13,611 | cc | C++ | lib/jxl/enc_group.cc | zond/libjxl | 04267a8780d1600d2bc9a79d161d7f769b5db93c | [
"BSD-3-Clause"
] | 10 | 2021-05-10T01:18:27.000Z | 2022-03-01T09:35:53.000Z | lib/jxl/enc_group.cc | zond/libjxl | 04267a8780d1600d2bc9a79d161d7f769b5db93c | [
"BSD-3-Clause"
] | 1 | 2021-07-05T18:03:12.000Z | 2021-07-05T18:34:28.000Z | lib/jxl/enc_group.cc | zond/libjxl | 04267a8780d1600d2bc9a79d161d7f769b5db93c | [
"BSD-3-Clause"
] | 3 | 2021-04-21T08:57:00.000Z | 2021-09-13T11:33:37.000Z | // Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "lib/jxl/enc_group.h"
#include <utility>
#include "hwy/aligned_allocator.h"
#undef HWY_TARGET_INCLUDE
#define HWY_TARGET_INCLUDE "lib/jxl/enc_group.cc"
#include <hwy/foreach_target.h>
#include <hwy/highway.h>
#include "lib/jxl/ac_strategy.h"
#include "lib/jxl/aux_out.h"
#include "lib/jxl/aux_out_fwd.h"
#include "lib/jxl/base/bits.h"
#include "lib/jxl/base/compiler_specific.h"
#include "lib/jxl/base/profiler.h"
#include "lib/jxl/common.h"
#include "lib/jxl/dct_util.h"
#include "lib/jxl/dec_transforms-inl.h"
#include "lib/jxl/enc_params.h"
#include "lib/jxl/enc_transforms-inl.h"
#include "lib/jxl/image.h"
#include "lib/jxl/quantizer-inl.h"
#include "lib/jxl/quantizer.h"
HWY_BEFORE_NAMESPACE();
namespace jxl {
namespace HWY_NAMESPACE {
// NOTE: caller takes care of extracting quant from rect of RawQuantField.
void QuantizeBlockAC(const Quantizer& quantizer, const bool error_diffusion,
size_t c, int32_t quant, float qm_multiplier,
size_t quant_kind, size_t xsize, size_t ysize,
const float* JXL_RESTRICT block_in,
int32_t* JXL_RESTRICT block_out) {
PROFILER_FUNC;
const float* JXL_RESTRICT qm = quantizer.InvDequantMatrix(quant_kind, c);
const float qac = quantizer.Scale() * quant;
// Not SIMD-fied for now.
float thres[4] = {0.5f, 0.6f, 0.6f, 0.65f};
if (c != 1) {
for (int i = 1; i < 4; ++i) {
thres[i] = 0.75f;
}
}
if (!error_diffusion) {
HWY_CAPPED(float, kBlockDim) df;
HWY_CAPPED(int32_t, kBlockDim) di;
HWY_CAPPED(uint32_t, kBlockDim) du;
const auto quant = Set(df, qac * qm_multiplier);
for (size_t y = 0; y < ysize * kBlockDim; y++) {
size_t yfix = static_cast<size_t>(y >= ysize * kBlockDim / 2) * 2;
const size_t off = y * kBlockDim * xsize;
for (size_t x = 0; x < xsize * kBlockDim; x += Lanes(df)) {
auto thr = Zero(df);
if (xsize == 1) {
HWY_ALIGN uint32_t kMask[kBlockDim] = {0, 0, 0, 0,
~0u, ~0u, ~0u, ~0u};
const auto mask = MaskFromVec(BitCast(df, Load(du, kMask + x)));
thr =
IfThenElse(mask, Set(df, thres[yfix + 1]), Set(df, thres[yfix]));
} else {
// Same for all lanes in the vector.
thr = Set(
df,
thres[yfix + static_cast<size_t>(x >= xsize * kBlockDim / 2)]);
}
const auto q = Load(df, qm + off + x) * quant;
const auto in = Load(df, block_in + off + x);
const auto val = q * in;
const auto nzero_mask = Abs(val) >= thr;
const auto v = ConvertTo(di, IfThenElseZero(nzero_mask, Round(val)));
Store(v, di, block_out + off + x);
}
}
return;
}
retry:
int hfNonZeros[4] = {};
float hfError[4] = {};
float hfMaxError[4] = {};
size_t hfMaxErrorIx[4] = {};
for (size_t y = 0; y < ysize * kBlockDim; y++) {
for (size_t x = 0; x < xsize * kBlockDim; x++) {
const size_t pos = y * kBlockDim * xsize + x;
if (x < xsize && y < ysize) {
// Ensure block is initialized
block_out[pos] = 0;
continue;
}
const size_t hfix = (static_cast<size_t>(y >= ysize * kBlockDim / 2) * 2 +
static_cast<size_t>(x >= xsize * kBlockDim / 2));
const float val = block_in[pos] * (qm[pos] * qac * qm_multiplier);
float v = (std::abs(val) < thres[hfix]) ? 0 : rintf(val);
const float error = std::abs(val) - std::abs(v);
hfError[hfix] += error;
if (hfMaxError[hfix] < error) {
hfMaxError[hfix] = error;
hfMaxErrorIx[hfix] = pos;
}
if (v != 0.0f) {
hfNonZeros[hfix] += std::abs(v);
}
block_out[pos] = static_cast<int32_t>(rintf(v));
}
}
if (c != 1) return;
// TODO(veluca): include AFV?
const size_t kPartialBlockKinds =
(1 << AcStrategy::Type::IDENTITY) | (1 << AcStrategy::Type::DCT2X2) |
(1 << AcStrategy::Type::DCT4X4) | (1 << AcStrategy::Type::DCT4X8) |
(1 << AcStrategy::Type::DCT8X4);
if ((1 << quant_kind) & kPartialBlockKinds) return;
float hfErrorLimit = 0.1f * (xsize * ysize) * kDCTBlockSize * 0.25f;
bool goretry = false;
for (int i = 1; i < 4; ++i) {
if (hfError[i] >= hfErrorLimit &&
hfNonZeros[i] <= (xsize + ysize) * 0.25f) {
if (thres[i] >= 0.4f) {
thres[i] -= 0.01f;
goretry = true;
}
}
}
if (goretry) goto retry;
for (int i = 1; i < 4; ++i) {
if (hfError[i] >= hfErrorLimit && hfNonZeros[i] == 0) {
const size_t pos = hfMaxErrorIx[i];
if (hfMaxError[i] >= 0.4f) {
block_out[pos] = block_in[pos] > 0.0f ? 1.0f : -1.0f;
}
}
}
}
// NOTE: caller takes care of extracting quant from rect of RawQuantField.
void QuantizeRoundtripYBlockAC(const Quantizer& quantizer,
const bool error_diffusion, int32_t quant,
size_t quant_kind, size_t xsize, size_t ysize,
const float* JXL_RESTRICT biases,
float* JXL_RESTRICT inout,
int32_t* JXL_RESTRICT quantized) {
QuantizeBlockAC(quantizer, error_diffusion, 1, quant, 1.0f, quant_kind, xsize,
ysize, inout, quantized);
PROFILER_ZONE("enc quant adjust bias");
const float* JXL_RESTRICT dequant_matrix =
quantizer.DequantMatrix(quant_kind, 1);
HWY_CAPPED(float, kDCTBlockSize) df;
HWY_CAPPED(int32_t, kDCTBlockSize) di;
const auto inv_qac = Set(df, quantizer.inv_quant_ac(quant));
for (size_t k = 0; k < kDCTBlockSize * xsize * ysize; k += Lanes(df)) {
const auto quant = Load(di, quantized + k);
const auto adj_quant = AdjustQuantBias(di, 1, quant, biases);
const auto dequantm = Load(df, dequant_matrix + k);
Store(adj_quant * dequantm * inv_qac, df, inout + k);
}
}
void ComputeCoefficients(size_t group_idx, PassesEncoderState* enc_state,
const Image3F& opsin, Image3F* dc) {
PROFILER_FUNC;
const Rect block_group_rect = enc_state->shared.BlockGroupRect(group_idx);
const Rect group_rect = enc_state->shared.GroupRect(group_idx);
const Rect cmap_rect(
block_group_rect.x0() / kColorTileDimInBlocks,
block_group_rect.y0() / kColorTileDimInBlocks,
DivCeil(block_group_rect.xsize(), kColorTileDimInBlocks),
DivCeil(block_group_rect.ysize(), kColorTileDimInBlocks));
const size_t xsize_blocks = block_group_rect.xsize();
const size_t ysize_blocks = block_group_rect.ysize();
const size_t dc_stride = static_cast<size_t>(dc->PixelsPerRow());
const size_t opsin_stride = static_cast<size_t>(opsin.PixelsPerRow());
const ImageI& full_quant_field = enc_state->shared.raw_quant_field;
const CompressParams& cparams = enc_state->cparams;
// TODO(veluca): consider strategies to reduce this memory.
auto mem = hwy::AllocateAligned<int32_t>(3 * AcStrategy::kMaxCoeffArea);
auto fmem = hwy::AllocateAligned<float>(5 * AcStrategy::kMaxCoeffArea);
float* JXL_RESTRICT scratch_space =
fmem.get() + 3 * AcStrategy::kMaxCoeffArea;
{
// Only use error diffusion in Squirrel mode or slower.
const bool error_diffusion = cparams.speed_tier <= SpeedTier::kSquirrel;
constexpr HWY_CAPPED(float, kDCTBlockSize) d;
int32_t* JXL_RESTRICT coeffs[kMaxNumPasses][3] = {};
size_t num_passes = enc_state->progressive_splitter.GetNumPasses();
JXL_DASSERT(num_passes > 0);
for (size_t i = 0; i < num_passes; i++) {
// TODO(veluca): 16-bit quantized coeffs are not implemented yet.
JXL_ASSERT(enc_state->coeffs[i]->Type() == ACType::k32);
for (size_t c = 0; c < 3; c++) {
coeffs[i][c] = enc_state->coeffs[i]->PlaneRow(c, group_idx, 0).ptr32;
}
}
HWY_ALIGN float* coeffs_in = fmem.get();
HWY_ALIGN int32_t* quantized = mem.get();
size_t offset = 0;
for (size_t by = 0; by < ysize_blocks; ++by) {
const int32_t* JXL_RESTRICT row_quant_ac =
block_group_rect.ConstRow(full_quant_field, by);
size_t ty = by / kColorTileDimInBlocks;
const int8_t* JXL_RESTRICT row_cmap[3] = {
cmap_rect.ConstRow(enc_state->shared.cmap.ytox_map, ty),
nullptr,
cmap_rect.ConstRow(enc_state->shared.cmap.ytob_map, ty),
};
const float* JXL_RESTRICT opsin_rows[3] = {
group_rect.ConstPlaneRow(opsin, 0, by * kBlockDim),
group_rect.ConstPlaneRow(opsin, 1, by * kBlockDim),
group_rect.ConstPlaneRow(opsin, 2, by * kBlockDim),
};
float* JXL_RESTRICT dc_rows[3] = {
block_group_rect.PlaneRow(dc, 0, by),
block_group_rect.PlaneRow(dc, 1, by),
block_group_rect.PlaneRow(dc, 2, by),
};
AcStrategyRow ac_strategy_row =
enc_state->shared.ac_strategy.ConstRow(block_group_rect, by);
for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
tx++) {
const auto x_factor =
Set(d, enc_state->shared.cmap.YtoXRatio(row_cmap[0][tx]));
const auto b_factor =
Set(d, enc_state->shared.cmap.YtoBRatio(row_cmap[2][tx]));
for (size_t bx = tx * kColorTileDimInBlocks;
bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks; ++bx) {
const AcStrategy acs = ac_strategy_row[bx];
if (!acs.IsFirstBlock()) continue;
size_t xblocks = acs.covered_blocks_x();
size_t yblocks = acs.covered_blocks_y();
CoefficientLayout(&yblocks, &xblocks);
size_t size = kDCTBlockSize * xblocks * yblocks;
// DCT Y channel, roundtrip-quantize it and set DC.
const int32_t quant_ac = row_quant_ac[bx];
TransformFromPixels(acs.Strategy(), opsin_rows[1] + bx * kBlockDim,
opsin_stride, coeffs_in + size, scratch_space);
DCFromLowestFrequencies(acs.Strategy(), coeffs_in + size,
dc_rows[1] + bx, dc_stride);
QuantizeRoundtripYBlockAC(
enc_state->shared.quantizer, error_diffusion, quant_ac,
acs.RawStrategy(), xblocks, yblocks, kDefaultQuantBias,
coeffs_in + size, quantized + size);
// DCT X and B channels
for (size_t c : {0, 2}) {
TransformFromPixels(acs.Strategy(), opsin_rows[c] + bx * kBlockDim,
opsin_stride, coeffs_in + c * size,
scratch_space);
}
// Unapply color correlation
for (size_t k = 0; k < size; k += Lanes(d)) {
const auto in_x = Load(d, coeffs_in + k);
const auto in_y = Load(d, coeffs_in + size + k);
const auto in_b = Load(d, coeffs_in + 2 * size + k);
const auto out_x = in_x - x_factor * in_y;
const auto out_b = in_b - b_factor * in_y;
Store(out_x, d, coeffs_in + k);
Store(out_b, d, coeffs_in + 2 * size + k);
}
// Quantize X and B channels and set DC.
for (size_t c : {0, 2}) {
QuantizeBlockAC(enc_state->shared.quantizer, error_diffusion, c,
quant_ac,
c == 0 ? enc_state->x_qm_multiplier
: enc_state->b_qm_multiplier,
acs.RawStrategy(), xblocks, yblocks,
coeffs_in + c * size, quantized + c * size);
DCFromLowestFrequencies(acs.Strategy(), coeffs_in + c * size,
dc_rows[c] + bx, dc_stride);
}
enc_state->progressive_splitter.SplitACCoefficients(
quantized, size, acs, bx, by, offset, coeffs);
offset += size;
}
}
}
}
}
// NOLINTNEXTLINE(google-readability-namespace-comments)
} // namespace HWY_NAMESPACE
} // namespace jxl
HWY_AFTER_NAMESPACE();
#if HWY_ONCE
namespace jxl {
HWY_EXPORT(ComputeCoefficients);
void ComputeCoefficients(size_t group_idx, PassesEncoderState* enc_state,
const Image3F& opsin, Image3F* dc) {
return HWY_DYNAMIC_DISPATCH(ComputeCoefficients)(group_idx, enc_state, opsin,
dc);
}
Status EncodeGroupTokenizedCoefficients(size_t group_idx, size_t pass_idx,
size_t histogram_idx,
const PassesEncoderState& enc_state,
BitWriter* writer, AuxOut* aux_out) {
// Select which histogram to use among those of the current pass.
const size_t num_histograms = enc_state.shared.num_histograms;
// num_histograms is 0 only for lossless.
JXL_ASSERT(num_histograms == 0 || histogram_idx < num_histograms);
size_t histo_selector_bits = CeilLog2Nonzero(num_histograms);
if (histo_selector_bits != 0) {
BitWriter::Allotment allotment(writer, histo_selector_bits);
writer->Write(histo_selector_bits, histogram_idx);
ReclaimAndCharge(writer, &allotment, kLayerAC, aux_out);
}
WriteTokens(enc_state.passes[pass_idx].ac_tokens[group_idx],
enc_state.passes[pass_idx].codes,
enc_state.passes[pass_idx].context_map, writer, kLayerACTokens,
aux_out);
return true;
}
} // namespace jxl
#endif // HWY_ONCE
| 39.682216 | 80 | 0.604658 | [
"vector"
] |
9136573bd564df1f19bb2af5717f83bc5b7ab580 | 2,196 | cpp | C++ | aws-cpp-sdk-connect/source/model/CreateRoutingProfileRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-connect/source/model/CreateRoutingProfileRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-connect/source/model/CreateRoutingProfileRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/connect/model/CreateRoutingProfileRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Connect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateRoutingProfileRequest::CreateRoutingProfileRequest() :
m_instanceIdHasBeenSet(false),
m_nameHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_defaultOutboundQueueIdHasBeenSet(false),
m_queueConfigsHasBeenSet(false),
m_mediaConcurrenciesHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
Aws::String CreateRoutingProfileRequest::SerializePayload() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_descriptionHasBeenSet)
{
payload.WithString("Description", m_description);
}
if(m_defaultOutboundQueueIdHasBeenSet)
{
payload.WithString("DefaultOutboundQueueId", m_defaultOutboundQueueId);
}
if(m_queueConfigsHasBeenSet)
{
Array<JsonValue> queueConfigsJsonList(m_queueConfigs.size());
for(unsigned queueConfigsIndex = 0; queueConfigsIndex < queueConfigsJsonList.GetLength(); ++queueConfigsIndex)
{
queueConfigsJsonList[queueConfigsIndex].AsObject(m_queueConfigs[queueConfigsIndex].Jsonize());
}
payload.WithArray("QueueConfigs", std::move(queueConfigsJsonList));
}
if(m_mediaConcurrenciesHasBeenSet)
{
Array<JsonValue> mediaConcurrenciesJsonList(m_mediaConcurrencies.size());
for(unsigned mediaConcurrenciesIndex = 0; mediaConcurrenciesIndex < mediaConcurrenciesJsonList.GetLength(); ++mediaConcurrenciesIndex)
{
mediaConcurrenciesJsonList[mediaConcurrenciesIndex].AsObject(m_mediaConcurrencies[mediaConcurrenciesIndex].Jsonize());
}
payload.WithArray("MediaConcurrencies", std::move(mediaConcurrenciesJsonList));
}
if(m_tagsHasBeenSet)
{
JsonValue tagsJsonMap;
for(auto& tagsItem : m_tags)
{
tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
}
payload.WithObject("Tags", std::move(tagsJsonMap));
}
return payload.View().WriteReadable();
}
| 25.241379 | 137 | 0.759563 | [
"model"
] |
913832330ca150dddc3a43f26572b35d0244ffe1 | 48,868 | cpp | C++ | src/Tasks.cpp | SaeidSamadi/Tasks | cb3f29a5545a96df83a7d49730799c90bfb0b6f7 | [
"BSD-2-Clause"
] | null | null | null | src/Tasks.cpp | SaeidSamadi/Tasks | cb3f29a5545a96df83a7d49730799c90bfb0b6f7 | [
"BSD-2-Clause"
] | null | null | null | src/Tasks.cpp | SaeidSamadi/Tasks | cb3f29a5545a96df83a7d49730799c90bfb0b6f7 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2012-2019 CNRS-UM LIRMM, CNRS-AIST JRL
*/
// associated header
#include "Tasks/Tasks.h"
// includes
// std
#include <numeric>
#include <set>
// rbd
#include <RBDyn/MultiBody.h>
#include <RBDyn/MultiBodyConfig.h>
namespace tasks
{
/**
* PositionTask
*/
PositionTask::PositionTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Vector3d & pos,
const Eigen::Vector3d & bodyPoint)
: pos_(pos), point_(bodyPoint), bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName, bodyPoint), eval_(3),
speed_(3), normalAcc_(3), jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
}
void PositionTask::position(const Eigen::Vector3d & pos)
{
pos_ = pos;
}
const Eigen::Vector3d & PositionTask::position() const
{
return pos_;
}
void PositionTask::bodyPoint(const Eigen::Vector3d & point)
{
jac_.point(point);
}
const Eigen::Vector3d & PositionTask::bodyPoint() const
{
return jac_.point();
}
void PositionTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
eval_ = pos_ - (point_ * mbc.bodyPosW[bodyIndex_]).translation();
speed_ = jac_.velocity(mb, mbc).linear();
normalAcc_ = jac_.normalAcceleration(mb, mbc).linear();
const auto & shortJacMat = jac_.jacobian(mb, mbc).block(3, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void PositionTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
eval_ = pos_ - (point_ * mbc.bodyPosW[bodyIndex_]).translation();
speed_ = jac_.velocity(mb, mbc).linear();
normalAcc_ = jac_.normalAcceleration(mb, mbc, normalAccB).linear();
const auto & shortJacMat = jac_.jacobian(mb, mbc).block(3, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void PositionTask::updateDot(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
const auto & shortJacMat = jac_.jacobianDot(mb, mbc).block(3, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacDotMat_);
}
const Eigen::VectorXd & PositionTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & PositionTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & PositionTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & PositionTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & PositionTask::jacDot() const
{
return jacDotMat_;
}
/**
* OrientationTask
*/
OrientationTask::OrientationTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Quaterniond & ori)
: ori_(ori.matrix()), bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), eval_(3), speed_(3), normalAcc_(3),
jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
}
OrientationTask::OrientationTask(const rbd::MultiBody & mb, const std::string & bodyName, const Eigen::Matrix3d & ori)
: ori_(ori), bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), eval_(3), speed_(3), normalAcc_(3),
jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
}
void OrientationTask::orientation(const Eigen::Quaterniond & ori)
{
ori_ = ori.matrix();
}
void OrientationTask::orientation(const Eigen::Matrix3d & ori)
{
ori_ = ori;
}
const Eigen::Matrix3d & OrientationTask::orientation() const
{
return ori_;
}
void OrientationTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
eval_ = sva::rotationError(mbc.bodyPosW[bodyIndex_].rotation(), ori_);
speed_ = jac_.velocity(mb, mbc).angular();
normalAcc_ = jac_.normalAcceleration(mb, mbc).angular();
const auto & shortJacMat = jac_.jacobian(mb, mbc).block(0, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void OrientationTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
eval_ = sva::rotationError(mbc.bodyPosW[bodyIndex_].rotation(), ori_);
speed_ = jac_.velocity(mb, mbc).angular();
normalAcc_ = jac_.normalAcceleration(mb, mbc, normalAccB).angular();
const auto & shortJacMat = jac_.jacobian(mb, mbc).block(0, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void OrientationTask::updateDot(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
const auto & shortJacMat = jac_.jacobianDot(mb, mbc).block(0, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacDotMat_);
}
const Eigen::VectorXd & OrientationTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & OrientationTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & OrientationTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & OrientationTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & OrientationTask::jacDot() const
{
return jacDotMat_;
}
/**
* TransformTaskCommon
*/
TransformTaskCommon::TransformTaskCommon(const rbd::MultiBody & mb,
const std::string & bodyName,
const sva::PTransformd & X_0_t,
const sva::PTransformd & X_b_p)
: X_0_t_(X_0_t), X_b_p_(X_b_p), bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), eval_(6), speed_(6),
normalAcc_(6), jacMat_(6, mb.nrDof())
{
}
void TransformTaskCommon::target(const sva::PTransformd & X_0_t)
{
X_0_t_ = X_0_t;
}
const sva::PTransformd & TransformTaskCommon::target() const
{
return X_0_t_;
}
void TransformTaskCommon::X_b_p(const sva::PTransformd & X_b_p)
{
X_b_p_ = X_b_p;
}
const sva::PTransformd & TransformTaskCommon::X_b_p() const
{
return X_b_p_;
}
const Eigen::VectorXd & TransformTaskCommon::eval() const
{
return eval_;
}
const Eigen::VectorXd & TransformTaskCommon::speed() const
{
return speed_;
}
const Eigen::VectorXd & TransformTaskCommon::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & TransformTaskCommon::jac() const
{
return jacMat_;
}
/**
* SurfaceTransformTask
*/
SurfaceTransformTask::SurfaceTransformTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const sva::PTransformd & X_0_t,
const sva::PTransformd & X_b_p)
: TransformTaskCommon(mb, bodyName, X_0_t, X_b_p), jacMatTmp_(6, jac_.dof())
{
}
void SurfaceTransformTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
sva::PTransformd X_0_p = X_b_p_ * mbc.bodyPosW[bodyIndex_];
sva::PTransformd X_p_t = X_0_t_ * X_0_p.inv();
// see Section 4.2.6 of Joris Vaillant's PhD thesis (French) for details
sva::MotionVecd err_p = sva::transformVelocity(X_p_t);
sva::MotionVecd V_p_p = jac_.velocity(mb, mbc, X_b_p_);
sva::MotionVecd w_p_p = sva::MotionVecd(V_p_p.angular(), Eigen::Vector3d::Zero());
sva::MotionVecd AN_p_p =
jac_.normalAcceleration(mb, mbc, normalAccB, X_b_p_, sva::MotionVecd(Eigen::Vector6d::Zero()));
sva::MotionVecd wAN_p_p = sva::MotionVecd(AN_p_p.angular(), Eigen::Vector3d::Zero());
sva::MotionVecd V_err_p = err_p.cross(w_p_p) - V_p_p;
eval_ = err_p.vector();
speed_ = -V_err_p.vector();
normalAcc_ = -(V_err_p.cross(w_p_p) + err_p.cross(wAN_p_p) - AN_p_p).vector();
jacMatTmp_ = jac_.jacobian(mb, mbc, X_0_p);
for(int i = 0; i < jac_.dof(); ++i)
{
jacMatTmp_.col(i).head<6>() -=
err_p.cross(sva::MotionVecd(jacMatTmp_.col(i).head<3>(), Eigen::Vector3d::Zero())).vector();
}
jac_.fullJacobian(mb, jacMatTmp_, jacMat_);
}
/**
* TransformTask
*/
TransformTask::TransformTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const sva::PTransformd & X_0_t,
const sva::PTransformd & X_b_p,
const Eigen::Matrix3d & E_0_c)
: TransformTaskCommon(mb, bodyName, X_0_t, X_b_p), E_0_c_(E_0_c)
{
}
void TransformTask::E_0_c(const Eigen::Matrix3d & E_0_c)
{
E_0_c_ = E_0_c;
}
const Eigen::Matrix3d & TransformTask::E_0_c() const
{
return E_0_c_;
}
void TransformTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
sva::PTransformd X_0_p(X_b_p_ * mbc.bodyPosW[bodyIndex_]);
sva::PTransformd E_p_c(Eigen::Matrix3d(E_0_c_ * X_0_p.rotation().transpose()));
sva::PTransformd X_b_p_c(E_p_c * X_b_p_);
sva::MotionVecd V_p_c(jac_.velocity(mb, mbc, X_b_p_c));
sva::MotionVecd w_p_c(V_p_c.angular(), Eigen::Vector3d::Zero());
eval_ = (sva::PTransformd(E_0_c_) * sva::transformError(X_0_p, X_0_t_)).vector();
speed_ = V_p_c.vector();
normalAcc_ = jac_.normalAcceleration(mb, mbc, normalAccB, X_b_p_c, w_p_c).vector();
const auto & shortJacMat = jac_.jacobian(mb, mbc, E_p_c * X_0_p);
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
/**
* MultiRobotTransformTask
*/
MultiRobotTransformTask::MultiRobotTransformTask(const std::vector<rbd::MultiBody> & mbs,
int r1Index,
int r2Index,
const std::string & r1BodyName,
const std::string & r2BodyName,
const sva::PTransformd & X_r1b_r1s,
const sva::PTransformd & X_r2b_r2s)
: r1Index_(r1Index), r2Index_(r2Index), r1BodyIndex_(mbs[r1Index].bodyIndexByName(r1BodyName)),
r2BodyIndex_(mbs[r2Index].bodyIndexByName(r2BodyName)), X_r1b_r1s_(X_r1b_r1s), X_r2b_r2s_(X_r2b_r2s),
jacR1B_(mbs[r1Index], r1BodyName), jacR2B_(mbs[r2Index], r2BodyName), eval_(6), speed_(6), normalAcc_(6),
jacMat1_(6, jacR1B_.dof()), jacMat2_(6, jacR2B_.dof()),
fullJacMat_({Eigen::MatrixXd::Zero(6, mbs[r1Index].nrDof()), Eigen::MatrixXd::Zero(6, mbs[r2Index].nrDof())})
{
}
int MultiRobotTransformTask::r1Index() const
{
return r1Index_;
}
int MultiRobotTransformTask::r2Index() const
{
return r2Index_;
}
void MultiRobotTransformTask::X_r1b_r1s(const sva::PTransformd & X_r1b_r1s)
{
X_r1b_r1s_ = X_r1b_r1s;
}
const sva::PTransformd & MultiRobotTransformTask::X_r1b_r1s() const
{
return X_r1b_r1s_;
}
void MultiRobotTransformTask::X_r2b_r2s(const sva::PTransformd & X_r2b_r2s)
{
X_r2b_r2s_ = X_r2b_r2s;
}
const sva::PTransformd & MultiRobotTransformTask::X_r2b_r2s() const
{
return X_r2b_r2s_;
}
void MultiRobotTransformTask::update(const std::vector<rbd::MultiBody> & mbs,
const std::vector<rbd::MultiBodyConfig> & mbcs,
const std::vector<std::vector<sva::MotionVecd>> & normalAccB)
{
using namespace Eigen;
const rbd::MultiBody & mb1 = mbs[r1Index_];
const rbd::MultiBody & mb2 = mbs[r2Index_];
const rbd::MultiBodyConfig & mbc1 = mbcs[r1Index_];
const rbd::MultiBodyConfig & mbc2 = mbcs[r2Index_];
const sva::PTransformd & X_0_r1b = mbc1.bodyPosW[r1BodyIndex_];
const sva::PTransformd & X_0_r2b = mbc2.bodyPosW[r2BodyIndex_];
const std::vector<sva::MotionVecd> & normalAccBR1 = normalAccB[r1Index_];
const std::vector<sva::MotionVecd> & normalAccBR2 = normalAccB[r2Index_];
sva::PTransformd X_0_r1s = X_r1b_r1s_ * X_0_r1b;
sva::PTransformd X_0_r2s = X_r2b_r2s_ * X_0_r2b;
sva::PTransformd X_r1s_r2s = X_0_r2s * X_0_r1s.inv();
sva::PTransformd E_r2s_r1s(Matrix3d(X_r1s_r2s.rotation().transpose()));
sva::PTransformd X_r2b_r2s_r1s(E_r2s_r1s * X_r2b_r2s_);
// see Section 4.2.6 of Joris Vaillant's PhD thesis (French) for details
sva::MotionVecd err_r1s(sva::transformVelocity(X_r1s_r2s));
sva::MotionVecd V_r1s_r1s = jacR1B_.velocity(mb1, mbc1, X_r1b_r1s_);
sva::MotionVecd V_r2s_r1s = jacR2B_.velocity(mb2, mbc2, X_r2b_r2s_r1s);
sva::MotionVecd V_err_s = V_r2s_r1s - V_r1s_r1s;
sva::MotionVecd w_r1s(V_r1s_r1s.angular(), Vector3d::Zero());
sva::MotionVecd V_err_r1s = err_r1s.cross(w_r1s) + V_err_s;
sva::MotionVecd AN_r1s_r1s =
jacR1B_.normalAcceleration(mb1, mbc1, normalAccBR1, X_r1b_r1s_, sva::MotionVecd(Vector6d::Zero()));
sva::MotionVecd wAN_r1s_r1s(AN_r1s_r1s.angular(), Vector3d::Zero());
sva::MotionVecd AN_r2s_r1s = jacR2B_.normalAcceleration(mb2, mbc2, normalAccBR2, X_r2b_r2s_r1s,
sva::MotionVecd(V_err_s.angular(), Vector3d::Zero()));
sva::MotionVecd AN_err_s = AN_r2s_r1s - AN_r1s_r1s;
sva::MotionVecd AN_err_r1s = V_err_r1s.cross(w_r1s) + err_r1s.cross(wAN_r1s_r1s) + AN_err_s;
eval_ = err_r1s.vector();
speed_ = -V_err_r1s.vector();
normalAcc_ = -AN_err_r1s.vector();
jacMat1_.noalias() = jacR1B_.jacobian(mb1, mbc1, X_0_r1s);
for(int i = 0; i < jacR1B_.dof(); ++i)
{
jacMat1_.col(i).head<6>() -= err_r1s.cross(sva::MotionVecd(jacMat1_.col(i).head<3>(), Vector3d::Zero())).vector();
}
jacMat2_.noalias() = -jacR2B_.jacobian(mb2, mbc2, E_r2s_r1s * X_0_r2s);
jacR1B_.fullJacobian(mb1, jacMat1_, fullJacMat_[0]);
jacR2B_.fullJacobian(mb2, jacMat2_, fullJacMat_[1]);
}
const Eigen::VectorXd & MultiRobotTransformTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & MultiRobotTransformTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & MultiRobotTransformTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & MultiRobotTransformTask::jac(int index) const
{
return fullJacMat_[index];
}
/**
* SurfaceOrientationTask
*/
SurfaceOrientationTask::SurfaceOrientationTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Quaterniond & ori,
const sva::PTransformd & X_b_s)
: ori_(ori.matrix()), bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), X_b_s_(X_b_s), eval_(3), speed_(3),
normalAcc_(3), jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
}
SurfaceOrientationTask::SurfaceOrientationTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Matrix3d & ori,
const sva::PTransformd & X_b_s)
: ori_(ori), bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), X_b_s_(X_b_s), eval_(3), speed_(3),
normalAcc_(3), jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
}
void SurfaceOrientationTask::orientation(const Eigen::Quaterniond & ori)
{
ori_ = ori.matrix();
}
void SurfaceOrientationTask::orientation(const Eigen::Matrix3d & ori)
{
ori_ = ori;
}
const Eigen::Matrix3d & SurfaceOrientationTask::orientation() const
{
return ori_;
}
void SurfaceOrientationTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
eval_ = sva::rotationVelocity<double>(ori_ * mbc.bodyPosW[bodyIndex_].rotation().transpose()
* X_b_s_.rotation().transpose());
speed_ = jac_.velocity(mb, mbc, X_b_s_).angular();
// since X_b_s is constant, the X_b_s velocity
// (last argument of normalAccelation) is a 0 velocity vector
normalAcc_ = jac_.normalAcceleration(mb, mbc, X_b_s_, sva::MotionVecd(Eigen::Vector6d::Zero())).angular();
const auto & shortJacMat = jac_.jacobian(mb, mbc, X_b_s_ * mbc.bodyPosW[bodyIndex_]).block(0, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void SurfaceOrientationTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
eval_ = sva::rotationVelocity<double>(ori_ * mbc.bodyPosW[bodyIndex_].rotation().transpose()
* X_b_s_.rotation().transpose());
speed_ = jac_.velocity(mb, mbc, X_b_s_).angular();
// since X_b_s is constant, the X_b_s velocity
// (third argument of normalAccelation) is a 0 velocity vector
normalAcc_ = jac_.normalAcceleration(mb, mbc, normalAccB, X_b_s_, sva::MotionVecd(Eigen::Vector6d::Zero())).angular();
const auto & shortJacMat = jac_.jacobian(mb, mbc, X_b_s_ * mbc.bodyPosW[bodyIndex_]).block(0, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void SurfaceOrientationTask::updateDot(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
const auto & shortJacMat = jac_.bodyJacobianDot(mb, mbc).block(0, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacDotMat_);
}
const Eigen::VectorXd & SurfaceOrientationTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & SurfaceOrientationTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & SurfaceOrientationTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & SurfaceOrientationTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & SurfaceOrientationTask::jacDot() const
{
return jacDotMat_;
}
/**
* GazeTask
*/
GazeTask::GazeTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Vector2d & point2d,
double depthEstimate,
const sva::PTransformd & X_b_gaze,
const Eigen::Vector2d & point2d_ref)
: point2d_(new Eigen::Vector2d(point2d)), point2d_ref_(new Eigen::Vector2d(point2d_ref)), depthEstimate_(depthEstimate),
bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), X_b_gaze_(X_b_gaze),
L_img_(new Eigen::Matrix<double, 2, 6>(Eigen::Matrix<double, 2, 6>::Zero())),
surfaceVelocity_(new Eigen::Matrix<double, 6, 1>(Eigen::Matrix<double, 6, 1>::Zero())),
L_Z_dot_(new Eigen::Matrix<double, 1, 6>(Eigen::Matrix<double, 1, 6>::Zero())),
L_img_dot_(new Eigen::Matrix<double, 2, 6>(Eigen::Matrix<double, 2, 6>::Zero())), eval_(2), speed_(2), normalAcc_(2),
jacMat_(2, mb.nrDof()), jacDotMat_(2, mb.nrDof())
{
}
GazeTask::GazeTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Vector3d & point3d,
const sva::PTransformd & X_b_gaze,
const Eigen::Vector2d & point2d_ref)
: point2d_(new Eigen::Vector2d()), point2d_ref_(new Eigen::Vector2d(point2d_ref)),
bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), X_b_gaze_(X_b_gaze),
L_img_(new Eigen::Matrix<double, 2, 6>(Eigen::Matrix<double, 2, 6>::Zero())),
surfaceVelocity_(new Eigen::Matrix<double, 6, 1>(Eigen::Matrix<double, 6, 1>::Zero())),
L_Z_dot_(new Eigen::Matrix<double, 1, 6>(Eigen::Matrix<double, 1, 6>::Zero())),
L_img_dot_(new Eigen::Matrix<double, 2, 6>(Eigen::Matrix<double, 2, 6>::Zero())), eval_(2), speed_(2), normalAcc_(2),
jacMat_(2, mb.nrDof()), jacDotMat_(2, mb.nrDof())
{
*point2d_ << point3d[0] / point3d[2], point3d[1] / point3d[2];
depthEstimate_ = point3d[2];
}
GazeTask::GazeTask(const GazeTask & rhs)
: point2d_(new Eigen::Vector2d(*rhs.point2d_)), point2d_ref_(new Eigen::Vector2d(*rhs.point2d_ref_)),
depthEstimate_(rhs.depthEstimate_), bodyIndex_(rhs.bodyIndex_), jac_(rhs.jac_), X_b_gaze_(rhs.X_b_gaze_),
L_img_(new Eigen::Matrix<double, 2, 6>(*rhs.L_img_)),
surfaceVelocity_(new Eigen::Matrix<double, 6, 1>(*rhs.surfaceVelocity_)),
L_Z_dot_(new Eigen::Matrix<double, 1, 6>(*rhs.L_Z_dot_)),
L_img_dot_(new Eigen::Matrix<double, 2, 6>(*rhs.L_img_dot_)), eval_(rhs.eval_), speed_(rhs.speed_),
normalAcc_(rhs.normalAcc_), jacMat_(rhs.jacMat_), jacDotMat_(rhs.jacDotMat_)
{
}
GazeTask & GazeTask::operator=(const GazeTask & rhs)
{
if(&rhs != this)
{
*point2d_ = *rhs.point2d_;
*point2d_ref_ = *rhs.point2d_ref_;
depthEstimate_ = rhs.depthEstimate_;
bodyIndex_ = rhs.bodyIndex_;
jac_ = rhs.jac_;
X_b_gaze_ = rhs.X_b_gaze_;
*L_img_ = *rhs.L_img_;
*surfaceVelocity_ = *rhs.surfaceVelocity_;
*L_Z_dot_ = *rhs.L_Z_dot_;
*L_img_dot_ = *rhs.L_img_dot_;
eval_ = rhs.eval_;
speed_ = rhs.speed_;
normalAcc_ = rhs.normalAcc_;
jacMat_ = rhs.jacMat_;
jacDotMat_ = rhs.jacDotMat_;
}
return *this;
}
void GazeTask::error(const Eigen::Vector2d & point2d, const Eigen::Vector2d & point2d_ref)
{
*point2d_ = point2d;
*point2d_ref_ = point2d_ref;
}
void GazeTask::error(const Eigen::Vector3d & point3d, const Eigen::Vector2d & point2d_ref)
{
*point2d_ << point3d[0] / point3d[2], point3d[1] / point3d[2];
depthEstimate_ = point3d[2];
*point2d_ref_ = point2d_ref;
}
void GazeTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
// compute eval term
eval_ = *point2d_ref_ - *point2d_;
// compute speed term
rbd::imagePointJacobian(*point2d_, depthEstimate_, *L_img_);
*surfaceVelocity_ = (jac_.velocity(mb, mbc, X_b_gaze_)).vector();
speed_ = (*L_img_) * (*surfaceVelocity_);
// compute norm accel term
rbd::depthDotJacobian(speed_, depthEstimate_, *L_Z_dot_);
rbd::imagePointJacobianDot(*point2d_, speed_, depthEstimate_, (*L_Z_dot_) * (*surfaceVelocity_), *L_img_dot_);
normalAcc_ =
(*L_img_)
* (jac_.normalAcceleration(mb, mbc, normalAccB, X_b_gaze_, sva::MotionVecd(Eigen::Vector6d::Zero()))).vector()
+ (*L_img_dot_) * (*surfaceVelocity_);
// compute the task Jacobian
Eigen::MatrixXd shortJacMat =
(*L_img_) * jac_.jacobian(mb, mbc, X_b_gaze_ * mbc.bodyPosW[bodyIndex_]).block(0, 0, 6, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
const Eigen::VectorXd & GazeTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & GazeTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & GazeTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & GazeTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & GazeTask::jacDot() const
{
return jacDotMat_;
}
/**
* PositionBasedVisServoTask
*/
PositionBasedVisServoTask::PositionBasedVisServoTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const sva::PTransformd & X_t_s,
const sva::PTransformd & X_b_s)
: X_t_s_(X_t_s), X_b_s_(X_b_s), angle_(0.), axis_(Eigen::Vector3d::Zero()), bodyIndex_(mb.bodyIndexByName(bodyName)),
jac_(mb, bodyName), L_pbvs_(new Eigen::Matrix<double, 6, 6>(Eigen::Matrix<double, 6, 6>::Zero())),
surfaceVelocity_(new Eigen::Matrix<double, 6, 1>(Eigen::Matrix<double, 6, 1>::Zero())),
omegaSkew_(Eigen::Matrix3d::Zero()),
L_pbvs_dot_(new Eigen::Matrix<double, 6, 6>(Eigen::Matrix<double, 6, 6>::Zero())), eval_(6), speed_(6), normalAcc_(6),
jacMat_(6, mb.nrDof()), jacDotMat_(6, mb.nrDof())
{
}
PositionBasedVisServoTask::PositionBasedVisServoTask(const PositionBasedVisServoTask & rhs)
: X_t_s_(rhs.X_t_s_), X_b_s_(rhs.X_b_s_), angle_(rhs.angle_), axis_(rhs.axis_), bodyIndex_(rhs.bodyIndex_),
jac_(rhs.jac_), L_pbvs_(new Eigen::Matrix<double, 6, 6>(*rhs.L_pbvs_)),
surfaceVelocity_(new Eigen::Matrix<double, 6, 1>(*rhs.surfaceVelocity_)), omegaSkew_(rhs.omegaSkew_),
L_pbvs_dot_(new Eigen::Matrix<double, 6, 6>(*rhs.L_pbvs_dot_)), eval_(rhs.eval_), speed_(rhs.speed_),
normalAcc_(rhs.normalAcc_), jacMat_(rhs.jacMat_), jacDotMat_(rhs.jacDotMat_)
{
}
PositionBasedVisServoTask & PositionBasedVisServoTask::operator=(const PositionBasedVisServoTask & rhs)
{
if(&rhs != this)
{
X_t_s_ = rhs.X_t_s_;
X_b_s_ = rhs.X_b_s_;
angle_ = rhs.angle_;
axis_ = rhs.axis_;
bodyIndex_ = rhs.bodyIndex_;
jac_ = rhs.jac_;
*L_pbvs_ = *rhs.L_pbvs_;
*surfaceVelocity_ = *rhs.surfaceVelocity_;
omegaSkew_ = rhs.omegaSkew_;
*L_pbvs_dot_ = *rhs.L_pbvs_dot_;
eval_ = rhs.eval_;
speed_ = rhs.speed_;
normalAcc_ = rhs.normalAcc_;
jacMat_ = rhs.jacMat_;
jacDotMat_ = rhs.jacDotMat_;
}
return *this;
}
void PositionBasedVisServoTask::error(const sva::PTransformd & X_t_s)
{
X_t_s_ = X_t_s;
}
void PositionBasedVisServoTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
// compute eval term
rbd::getAngleAxis(X_t_s_.rotation().transpose(), angle_, axis_);
eval_.tail(3) = -X_t_s_.translation();
eval_.head(3) = angle_ * axis_;
// compute speed term
rbd::poseJacobian(X_t_s_.rotation(), *L_pbvs_);
*surfaceVelocity_ = (jac_.velocity(mb, mbc, X_b_s_)).vector();
speed_ = (*L_pbvs_) * (*surfaceVelocity_);
// compute norm accel term
rbd::getSkewSym(surfaceVelocity_->head(3), omegaSkew_);
*L_pbvs_dot_ << Eigen::Matrix3d::Zero(), Eigen::Matrix3d::Zero(), Eigen::Matrix3d::Zero(),
-X_t_s_.rotation().transpose() * omegaSkew_;
normalAcc_ =
(*L_pbvs_)
* (jac_.normalAcceleration(mb, mbc, normalAccB, X_b_s_, sva::MotionVecd(Eigen::Vector6d::Zero()))).vector()
+ (*L_pbvs_dot_) * (*surfaceVelocity_);
// compute the task Jacobian
Eigen::MatrixXd shortJacMat =
(*L_pbvs_) * jac_.jacobian(mb, mbc, X_b_s_ * mbc.bodyPosW[bodyIndex_]).block(0, 0, 6, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
const Eigen::VectorXd & PositionBasedVisServoTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & PositionBasedVisServoTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & PositionBasedVisServoTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & PositionBasedVisServoTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & PositionBasedVisServoTask::jacDot() const
{
return jacDotMat_;
}
/**
* PostureTask
*/
PostureTask::PostureTask(const rbd::MultiBody & mb, std::vector<std::vector<double>> q)
: q_(q), eval_(mb.nrDof()), jacMat_(mb.nrDof(), mb.nrDof()), jacDotMat_(mb.nrDof(), mb.nrDof())
{
eval_.setZero();
jacMat_.setIdentity();
jacDotMat_.setZero();
if(mb.nrDof() > 0 && mb.joint(0).type() == rbd::Joint::Free)
{
for(int i = 0; i < 6; ++i)
{
jacMat_(i, i) = 0;
}
}
}
void PostureTask::posture(std::vector<std::vector<double>> q)
{
q_ = q;
}
const std::vector<std::vector<double>> PostureTask::posture() const
{
return q_;
}
void PostureTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
using namespace Eigen;
int pos = mb.jointPosInDof(1);
// we drop the first joint (fixed or free flyier).
for(int i = 1; i < mb.nrJoints(); ++i)
{
// if dof == 1 is a prismatic/revolute joint
// else if dof == 4 is a spherical one
// else is a fixed one
if(mb.joint(i).dof() == 1)
{
eval_(pos) = q_[i][0] - mbc.q[i][0];
++pos;
}
else if(mb.joint(i).dof() == 4)
{
Matrix3d orid(Quaterniond(q_[i][0], q_[i][1], q_[i][2], q_[i][3]).matrix());
Vector3d err = sva::rotationError(mbc.jointConfig[i].rotation(), orid);
eval_.segment(pos, 3) = err;
pos += 3;
}
}
}
void PostureTask::updateDot(const rbd::MultiBody & /* mb */, const rbd::MultiBodyConfig & /* mbc */) {}
const Eigen::VectorXd & PostureTask::eval() const
{
return eval_;
}
const Eigen::MatrixXd & PostureTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & PostureTask::jacDot() const
{
return jacDotMat_;
}
/**
* CoMTask
*/
CoMTask::CoMTask(const rbd::MultiBody & mb, const Eigen::Vector3d & com)
: com_(com), jac_(mb), eval_(3), speed_(3), normalAcc_(3), jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
}
CoMTask::CoMTask(const rbd::MultiBody & mb, const Eigen::Vector3d & com, std::vector<double> weight)
: com_(com), jac_(mb, std::move(weight)), eval_(3), speed_(3), normalAcc_(3), jacMat_(3, mb.nrDof()),
jacDotMat_(3, mb.nrDof())
{
}
void CoMTask::com(const Eigen::Vector3d & com)
{
com_ = com;
}
const Eigen::Vector3d & CoMTask::com() const
{
return com_;
}
const Eigen::Vector3d & CoMTask::actual() const
{
return actual_;
}
void CoMTask::updateInertialParameters(const rbd::MultiBody & mb)
{
jac_.updateInertialParameters(mb);
}
void CoMTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
actual_ = rbd::computeCoM(mb, mbc);
eval_ = com_ - actual_;
speed_ = jac_.velocity(mb, mbc);
normalAcc_ = jac_.normalAcceleration(mb, mbc);
jacMat_ = jac_.jacobian(mb, mbc);
}
void CoMTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const Eigen::Vector3d & com,
const std::vector<sva::MotionVecd> & normalAccB)
{
actual_ = com;
eval_ = com_ - com;
speed_ = jac_.velocity(mb, mbc);
normalAcc_ = jac_.normalAcceleration(mb, mbc, normalAccB);
jacMat_ = jac_.jacobian(mb, mbc);
}
void CoMTask::updateDot(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
jacDotMat_ = jac_.jacobianDot(mb, mbc);
}
const Eigen::VectorXd & CoMTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & CoMTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & CoMTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & CoMTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & CoMTask::jacDot() const
{
return jacDotMat_;
}
/**
* MultiCoMTask
*/
MultiCoMTask::MultiCoMTask(const std::vector<rbd::MultiBody> & mbs,
std::vector<int> robotIndexes,
const Eigen::Vector3d & com)
: com_(com), robotIndexes_(std::move(robotIndexes)), robotsWeight_(), jac_(robotIndexes_.size()), eval_(3), speed_(3),
normalAcc_(3), jacMat_(robotIndexes_.size())
{
computeRobotsWeight(mbs);
// create CoMJacobian and jacobian matrix
for(std::size_t i = 0; i < robotIndexes_.size(); ++i)
{
int r = robotIndexes_[i];
const rbd::MultiBody & mb = mbs[r];
jac_[i] = rbd::CoMJacobian(mb, std::vector<double>(mb.nrBodies(), robotsWeight_[i]));
jacMat_[i].resize(3, mb.nrDof());
}
}
void MultiCoMTask::com(const Eigen::Vector3d & com)
{
com_ = com;
}
const Eigen::Vector3d MultiCoMTask::com() const
{
return com_;
}
const std::vector<int> & MultiCoMTask::robotIndexes() const
{
return robotIndexes_;
}
void MultiCoMTask::updateInertialParameters(const std::vector<rbd::MultiBody> & mbs)
{
computeRobotsWeight(mbs);
// upadte CoMJacobian per body weight
for(std::size_t i = 0; i < robotIndexes_.size(); ++i)
{
int r = robotIndexes_[i];
const rbd::MultiBody & mb = mbs[r];
jac_[i].weight(mb, std::vector<double>(mb.nrBodies(), robotsWeight_[i]));
}
}
void MultiCoMTask::update(const std::vector<rbd::MultiBody> & mbs, const std::vector<rbd::MultiBodyConfig> & mbcs)
{
eval_ = com_;
speed_.setZero();
normalAcc_.setZero();
for(std::size_t i = 0; i < robotIndexes_.size(); ++i)
{
int r = robotIndexes_[i];
const rbd::MultiBody & mb = mbs[r];
const rbd::MultiBodyConfig & mbc = mbcs[r];
eval_ -= rbd::computeCoM(mbs[r], mbcs[r]) * robotsWeight_[i];
speed_ += jac_[i].velocity(mb, mbc);
normalAcc_ += jac_[i].normalAcceleration(mb, mbc);
jacMat_[i] = jac_[i].jacobian(mb, mbc);
}
}
void MultiCoMTask::update(const std::vector<rbd::MultiBody> & mbs,
const std::vector<rbd::MultiBodyConfig> & mbcs,
const std::vector<std::vector<sva::MotionVecd>> & normalAccB)
{
eval_ = com_;
speed_.setZero();
normalAcc_.setZero();
for(std::size_t i = 0; i < robotIndexes_.size(); ++i)
{
int r = robotIndexes_[i];
const rbd::MultiBody & mb = mbs[r];
const rbd::MultiBodyConfig & mbc = mbcs[r];
eval_ -= rbd::computeCoM(mbs[r], mbcs[r]) * robotsWeight_[i];
speed_ += jac_[i].velocity(mb, mbc);
normalAcc_ += jac_[i].normalAcceleration(mb, mbc, normalAccB[r]);
jacMat_[i] = jac_[i].jacobian(mb, mbc);
}
}
void MultiCoMTask::update(const std::vector<rbd::MultiBody> & mbs,
const std::vector<rbd::MultiBodyConfig> & mbcs,
const std::vector<Eigen::Vector3d> & coms,
const std::vector<std::vector<sva::MotionVecd>> & normalAccB)
{
eval_ = com_;
speed_.setZero();
normalAcc_.setZero();
for(std::size_t i = 0; i < robotIndexes_.size(); ++i)
{
int r = robotIndexes_[i];
const rbd::MultiBody & mb = mbs[r];
const rbd::MultiBodyConfig & mbc = mbcs[r];
eval_ -= coms[r] * robotsWeight_[i];
speed_ += jac_[i].velocity(mb, mbc);
normalAcc_ += jac_[i].normalAcceleration(mb, mbc, normalAccB[r]);
jacMat_[i] = jac_[i].jacobian(mb, mbc);
}
}
void MultiCoMTask::computeRobotsWeight(const std::vector<rbd::MultiBody> & mbs)
{
double totalMass = 0.;
robotsWeight_.clear();
robotsWeight_.reserve(robotIndexes_.size());
// compute the total mass and the weight of each robot
for(int r : robotIndexes_)
{
double rm = std::accumulate(mbs[r].bodies().begin(), mbs[r].bodies().end(), 0.,
[](double ac, const rbd::Body & b) { return ac + b.inertia().mass(); });
robotsWeight_.push_back(rm);
totalMass += rm;
}
// divide all robotsWeight values by the total mass
std::transform(robotsWeight_.begin(), robotsWeight_.end(), robotsWeight_.begin(),
[totalMass](double w) { return w / totalMass; });
}
const Eigen::VectorXd & MultiCoMTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & MultiCoMTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & MultiCoMTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & MultiCoMTask::jac(int index) const
{
return jacMat_[index];
}
/**
* MomentumTask
*/
MomentumTask::MomentumTask(const rbd::MultiBody & mb, const sva::ForceVecd mom)
: momentum_(mom), momentumMatrix_(mb), eval_(6), speed_(6), normalAcc_(6), jacMat_(6, mb.nrDof()),
jacDotMat_(6, mb.nrDof())
{
speed_.setZero();
}
void MomentumTask::momentum(const sva::ForceVecd & mom)
{
momentum_ = mom;
}
const sva::ForceVecd MomentumTask::momentum() const
{
return momentum_;
}
void MomentumTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
Eigen::Vector3d com = rbd::computeCoM(mb, mbc);
eval_ = momentum_.vector() - rbd::computeCentroidalMomentum(mb, mbc, com).vector();
normalAcc_ = momentumMatrix_.normalMomentumDot(mb, mbc, com, rbd::computeCoMVelocity(mb, mbc)).vector();
momentumMatrix_.computeMatrix(mb, mbc, com);
jacMat_ = momentumMatrix_.matrix();
}
void MomentumTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
Eigen::Vector3d com = rbd::computeCoM(mb, mbc);
eval_ = momentum_.vector() - rbd::computeCentroidalMomentum(mb, mbc, com).vector();
normalAcc_ = momentumMatrix_.normalMomentumDot(mb, mbc, com, rbd::computeCoMVelocity(mb, mbc), normalAccB).vector();
momentumMatrix_.computeMatrix(mb, mbc, com);
jacMat_ = momentumMatrix_.matrix();
}
void MomentumTask::updateDot(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
momentumMatrix_.computeMatrixDot(mb, mbc, rbd::computeCoM(mb, mbc), rbd::computeCoMVelocity(mb, mbc));
jacDotMat_ = momentumMatrix_.matrixDot();
}
const Eigen::VectorXd & MomentumTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & MomentumTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & MomentumTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & MomentumTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & MomentumTask::jacDot() const
{
return jacDotMat_;
}
/**
* LinVelocityTask
*/
LinVelocityTask::LinVelocityTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Vector3d & v,
const Eigen::Vector3d & bodyPoint)
: vel_(v), point_(bodyPoint), bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName, bodyPoint), eval_(3),
speed_(3), normalAcc_(3), jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
// this task don't have any derivative
speed_.setZero();
}
void LinVelocityTask::velocity(const Eigen::Vector3d & v)
{
vel_ = v;
}
const Eigen::Vector3d & LinVelocityTask::velocity() const
{
return vel_;
}
void LinVelocityTask::bodyPoint(const Eigen::Vector3d & point)
{
jac_.point(point);
}
const Eigen::Vector3d & LinVelocityTask::bodyPoint() const
{
return jac_.point();
}
void LinVelocityTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
eval_ = vel_ - jac_.velocity(mb, mbc).linear();
normalAcc_ = jac_.normalAcceleration(mb, mbc).linear();
const auto & shortJacMat = jac_.jacobian(mb, mbc).block(3, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void LinVelocityTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
eval_ = vel_ - jac_.velocity(mb, mbc).linear();
normalAcc_ = jac_.normalAcceleration(mb, mbc, normalAccB).linear();
const auto & shortJacMat = jac_.jacobian(mb, mbc).block(3, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacMat_);
}
void LinVelocityTask::updateDot(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
const auto & shortJacMat = jac_.jacobianDot(mb, mbc).block(3, 0, 3, jac_.dof());
jac_.fullJacobian(mb, shortJacMat, jacDotMat_);
}
const Eigen::VectorXd & LinVelocityTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & LinVelocityTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & LinVelocityTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & LinVelocityTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & LinVelocityTask::jacDot() const
{
return jacDotMat_;
}
/**
* OrientationTrackingTask
*/
OrientationTrackingTask::OrientationTrackingTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Vector3d & bodyPoint,
const Eigen::Vector3d & bodyAxis,
const std::vector<std::string> & trackingJointsName,
const Eigen::Vector3d & trackedPoint)
: bodyIndex_(mb.bodyIndexByName(bodyName)), bodyPoint_(bodyPoint), bodyAxis_(bodyAxis), zeroJacIndex_(),
trackedPoint_(trackedPoint), jac_(mb, bodyName), eval_(3), shortJacMat_(3, jac_.dof()), jacMat_(3, mb.nrDof()),
jacDotMat_(3, mb.nrDof())
{
std::set<int> trackingJointsIndex;
for(const std::string & name : trackingJointsName)
{
trackingJointsIndex.insert(mb.jointIndexByName(name));
}
int jacPos = 0;
for(int i : jac_.jointsPath())
{
const rbd::Joint & curJoint = mb.joint(i);
if(trackingJointsIndex.find(i) == std::end(trackingJointsIndex))
{
for(int j = 0; j < curJoint.dof(); ++j)
{
zeroJacIndex_.push_back(jacPos + j);
}
}
jacPos += curJoint.dof();
}
}
void OrientationTrackingTask::trackedPoint(const Eigen::Vector3d & tp)
{
trackedPoint_ = tp;
}
const Eigen::Vector3d & OrientationTrackingTask::trackedPoint() const
{
return trackedPoint_;
}
void OrientationTrackingTask::bodyPoint(const Eigen::Vector3d & bp)
{
bodyPoint_ = sva::PTransformd(bp);
}
const Eigen::Vector3d & OrientationTrackingTask::bodyPoint() const
{
return bodyPoint_.translation();
}
void OrientationTrackingTask::bodyAxis(const Eigen::Vector3d & ba)
{
bodyAxis_ = ba;
}
const Eigen::Vector3d & OrientationTrackingTask::bodyAxis() const
{
return bodyAxis_;
}
void OrientationTrackingTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
using namespace Eigen;
const sva::PTransformd & bodyTf = mbc.bodyPosW[bodyIndex_];
Vector3d desDir(trackedPoint_ - (bodyPoint_ * bodyTf).translation());
Vector3d curDir(bodyTf.rotation().transpose() * bodyAxis_);
desDir.normalize();
curDir.normalize();
Matrix3d targetOri(Quaterniond::FromTwoVectors(curDir, desDir).inverse().matrix());
eval_ =
sva::rotationError<double>(mbc.bodyPosW[bodyIndex_].rotation(), targetOri * mbc.bodyPosW[bodyIndex_].rotation());
shortJacMat_ = jac_.jacobian(mb, mbc).block(0, 0, 3, shortJacMat_.cols());
zeroJacobian(shortJacMat_);
jac_.fullJacobian(mb, shortJacMat_, jacMat_);
}
void OrientationTrackingTask::updateDot(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
shortJacMat_ = jac_.jacobianDot(mb, mbc).block(0, 0, 3, shortJacMat_.cols());
zeroJacobian(shortJacMat_);
jac_.fullJacobian(mb, shortJacMat_, jacDotMat_);
}
const Eigen::MatrixXd & OrientationTrackingTask::jac()
{
return jacMat_;
}
const Eigen::MatrixXd & OrientationTrackingTask::jacDot()
{
return jacDotMat_;
}
const Eigen::VectorXd & OrientationTrackingTask::eval()
{
return eval_;
}
void OrientationTrackingTask::zeroJacobian(Eigen::MatrixXd & jac) const
{
for(int i : zeroJacIndex_)
{
jac.col(i).setZero();
}
}
/**
* RelativeDistTask
*/
RelativeDistTask::RelativeDistTask(const rbd::MultiBody & mb,
const double timestep,
const rbInfo & rbi1,
const rbInfo & rbi2,
const Eigen::Vector3d & u1,
const Eigen::Vector3d & u2)
: timestep_(timestep), isVectorFixed_(false), eval_(1), speed_(1), normalAcc_(1), jacMat_(1, mb.nrDof())
{
rbInfo_[0] = RelativeDistTask::RelativeBodiesInfo(mb, rbi1, u1);
rbInfo_[1] = RelativeDistTask::RelativeBodiesInfo(mb, rbi2, u2);
if(u1 != Eigen::Vector3d::Zero() && u2 != Eigen::Vector3d::Zero())
{
isVectorFixed_ = true;
}
}
RelativeDistTask::RelativeBodiesInfo::RelativeBodiesInfo(const rbd::MultiBody & mb,
const rbInfo & rbi,
const Eigen::Vector3d & fixedVector)
: b1Index(mb.bodyIndexByName(std::get<0>(rbi))), r_b1_p(std::get<1>(rbi)), r_0_b2p(std::get<2>(rbi)),
jac(mb, std::get<0>(rbi), r_b1_p), u(fixedVector), offn(Eigen::Vector3d::Zero())
{
}
void RelativeDistTask::robotPoint(const int bIndex, const Eigen::Vector3d & point)
{
for(RelativeBodiesInfo & rbi : rbInfo_)
{
if(rbi.b1Index == bIndex)
{
rbi.r_b1_p = point;
rbi.jac.point(point);
}
}
}
void RelativeDistTask::envPoint(const int bIndex, const Eigen::Vector3d & point)
{
for(RelativeBodiesInfo & rbi : rbInfo_)
{
if(rbi.b1Index == bIndex)
{
rbi.r_0_b2p = point;
}
}
}
void RelativeDistTask::vector(const int bIndex, const Eigen::Vector3d & u)
{
for(RelativeBodiesInfo & rbi : rbInfo_)
{
if(rbi.b1Index == bIndex)
{
rbi.u = u;
}
}
}
void RelativeDistTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
double sign = 1;
jacMat_.setZero();
eval_.setZero();
speed_.setZero();
normalAcc_.setZero();
for(RelativeBodiesInfo & rbi : rbInfo_)
{
// Compute the error
sva::PTransformd X_0_p1 = sva::PTransformd(rbi.r_b1_p) * mbc.bodyPosW[rbi.b1Index];
Eigen::Vector3d r_0_p2 = rbi.r_0_b2p;
Eigen::Vector3d r_p2_p1 = X_0_p1.translation() - r_0_p2;
double d;
Eigen::Vector3d n, dn;
if(isVectorFixed_)
{
d = std::abs(r_p2_p1.dot(rbi.u));
n = -rbi.u;
dn = Eigen::Vector3d::Zero();
}
else
{
d = r_p2_p1.norm();
n = (r_0_p2 - X_0_p1.translation()) / d;
dn = (n - rbi.offn) / timestep_;
}
eval_[0] += sign * d;
// Compute the jacobian matrix
Eigen::MatrixXd shortMat;
Eigen::MatrixXd fullJac;
fullJac.resize(3, mb.nrDof());
shortMat = rbi.jac.jacobian(mb, mbc);
rbi.jac.fullJacobian(mb, shortMat.block(3, 0, 3, rbi.jac.dof()), fullJac);
jacMat_ += sign * n.transpose() * fullJac;
// Compute the speed
speed_[0] += sign * rbi.jac.velocity(mb, mbc).linear().dot(n);
// Compute the normal acceleration (JDot alpha)
normalAcc_[0] += sign * (fullJac * rbd::dofToVector(mb, mbc.alpha)).dot(dn)
+ sign * rbi.jac.normalAcceleration(mb, mbc, normalAccB).linear().dot(n);
// Update offn and sign
// little hack: sign is +1 for the first pair and -1 for the second
sign *= -1;
rbi.offn = n;
}
}
const Eigen::VectorXd & RelativeDistTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & RelativeDistTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & RelativeDistTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & RelativeDistTask::jac() const
{
return jacMat_;
}
/**
* VectorOrientationTask
*/
VectorOrientationTask::VectorOrientationTask(const rbd::MultiBody & mb,
const std::string & bodyName,
const Eigen::Vector3d & bodyVector,
const Eigen::Vector3d & targetVector)
: actualVector_(Eigen::Vector3d::Zero()), bodyVector_(bodyVector), targetVector_(targetVector),
bodyIndex_(mb.bodyIndexByName(bodyName)), jac_(mb, bodyName), eval_(3), speed_(3), normalAcc_(3),
jacMat_(3, mb.nrDof())
{
}
void VectorOrientationTask::update(const rbd::MultiBody & mb,
const rbd::MultiBodyConfig & mbc,
const std::vector<sva::MotionVecd> & normalAccB)
{
// Evaluation of eval
Eigen::Matrix3d E_0_b = mbc.bodyPosW[bodyIndex_].rotation().transpose();
actualVector_ = E_0_b * bodyVector_;
eval_ = targetVector_ - actualVector_;
// Evaluation of speed and jacMat
Eigen::MatrixXd shortMat, fullJac(3, mb.nrDof());
shortMat = jac_.bodyJacobian(mb, mbc);
jac_.fullJacobian(mb, shortMat.block(0, 0, 3, jac_.dof()), fullJac);
jacMat_ = -E_0_b * skewMatrix(bodyVector_) * fullJac;
Eigen::Vector3d w_b_b = jac_.bodyVelocity(mb, mbc).angular();
speed_ = E_0_b * (w_b_b.cross(bodyVector_));
// Evaluation of normalAcc
Eigen::Vector3d bodyNormalAcc = jac_.bodyNormalAcceleration(mb, mbc, normalAccB).angular();
normalAcc_ = w_b_b.cross(w_b_b.cross(bodyVector_));
normalAcc_ += bodyNormalAcc.cross(bodyVector_);
normalAcc_ = E_0_b * normalAcc_;
}
Eigen::Matrix3d VectorOrientationTask::skewMatrix(const Eigen::Vector3d & v)
{
Eigen::Matrix3d m;
m << 0., -v[2], v[1], v[2], 0., -v[0], -v[1], v[0], 0.;
return m;
}
void VectorOrientationTask::bodyVector(const Eigen::Vector3d & vector)
{
bodyVector_ = vector;
}
const Eigen::Vector3d & VectorOrientationTask::bodyVector() const
{
return bodyVector_;
}
void VectorOrientationTask::target(const Eigen::Vector3d & vector)
{
targetVector_ = vector;
}
const Eigen::Vector3d & VectorOrientationTask::target() const
{
return targetVector_;
}
const Eigen::Vector3d & VectorOrientationTask::actual() const
{
return actualVector_;
}
const Eigen::VectorXd & VectorOrientationTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & VectorOrientationTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & VectorOrientationTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & VectorOrientationTask::jac() const
{
return jacMat_;
}
/**
* NetWrenchTask
*/
NetWrenchTask::NetWrenchTask(const rbd::MultiBody & mb,
const std::string & bodyName)
: bodyIndex_(mb.bodyIndexByName(bodyName)), eval_(3),
speed_(3), normalAcc_(3), jacMat_(3, mb.nrDof()), jacDotMat_(3, mb.nrDof())
{
}
void NetWrenchTask::update(const rbd::MultiBody & mb, const rbd::MultiBodyConfig & mbc)
{
}
const Eigen::VectorXd & NetWrenchTask::eval() const
{
return eval_;
}
const Eigen::VectorXd & NetWrenchTask::speed() const
{
return speed_;
}
const Eigen::VectorXd & NetWrenchTask::normalAcc() const
{
return normalAcc_;
}
const Eigen::MatrixXd & NetWrenchTask::jac() const
{
return jacMat_;
}
const Eigen::MatrixXd & NetWrenchTask::jacDot() const
{
return jacDotMat_;
}
} // namespace tasks
| 29.563218 | 120 | 0.649894 | [
"vector",
"transform"
] |
914751e62d2ccba6dbdac8bddd0e0afcacec3914 | 5,053 | cpp | C++ | UVA/10061.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | UVA/10061.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | UVA/10061.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
vector<string> findPosibleChilds(string &p1, string &p2){
set<string> posibles={"A", "B", "AB", "O"};
vector<string> toReturn;
if(p1=="A"){
if(p2=="A" || p2=="O"){
posibles.erase("B");
posibles.erase("AB");
}
if(p2=="AB"){
posibles.erase("O");
}
}
else if(p1=="B"){
if(p2=="B" || p2=="O"){
posibles.erase("AB");
}
if(p2=="B"){
posibles.erase("A");
}
if(p2=="AB"){
posibles.erase("O");
}
}
else if(p1=="AB"){
posibles.erase("O");
if(p2=="O"){
posibles.erase("AB");
}
}
else if(p1=="O"){
posibles.erase("AB");
if(p2=="A"){
posibles.erase("B");
}
if(p2=="B"){
posibles.erase("A");
}
if(p2=="AB"){
posibles.erase("AB");
posibles.erase("O");
}
if(p2=="O"){
posibles.erase("A");
posibles.erase("B");
}
}
for(string s : posibles){
toReturn.push_back(s);
}
return toReturn;
}
vector<string> findPosibleParent(string p, string child){
set<string> posibles={"A", "B", "AB", "O"};
vector<string> toReturn;
if(p=="A"){
if(child=="B"){
posibles.erase("A");
posibles.erase("O");
}
if(child=="AB"){
posibles.erase("A");
posibles.erase("O");
}
if(child=="O"){
posibles.erase("AB");
}
}
if(p=="B"){
if(child=="A"){
posibles.erase("B");
posibles.erase("O");
}
if(child=="AB"){
posibles.erase("B");
posibles.erase("O");
}
if(child=="O"){
posibles.erase("AB");
}
}
if(p=="AB"){
if(child=="AB"){
posibles.erase("O");
}
if(child=="O"){
posibles.clear();
}
}
if(p=="O"){
if(child=="A"){
posibles.erase("B");
posibles.erase("O");
}
if(child=="B"){
posibles.erase("A");
posibles.erase("O");
}
if(child=="O"){
posibles.erase("AB");
}
if(child=="AB"){
posibles.clear();
}
}
for(string s : posibles){
toReturn.push_back(s);
}
return toReturn;
}
void printType(string type, int rh){
if(rh==-1){
cout << type << "+";
}
else if(rh>=0){
cout << type << "+";
cout << ", " << type << "-";
}
else{
cout << type << "-";
}
}
void printAns(vector<string> &ans, int totalRH){
if(ans.size()>1){
cout << "{";
printType(ans[0], totalRH);
for(int i=1; i<ans.size(); i++){
cout << ", ";
printType(ans[i], totalRH);
}
cout << "}";
}
else if(ans.size()==1){
if(totalRH>=0){
cout << "{";
printType(ans[0], totalRH);
cout << "}";
}
else{
cout << ans[0] << "-";
}
}
else{
cout << "IMPOSSIBLE";
}
}
int main(){
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
int actCase=1;
string p1, p2, child;
vector<string> ans;
while(cin >> p1 >> p2 >> child){
vector<string> ans;
if(p1=="E" && p2=="N" && child=="D"){
break;
}
cout << "Case " << actCase++ << ": ";
if(child=="?"){
int totalRH=0;
string tmpP1=p1.substr(0, p1.size()-1);
string tmpP2=p2.substr(0, p2.size()-1);
totalRH+=(p1[p1.size()-1]=='+' ? 1 : -1);
totalRH+=(p2[p2.size()-1]=='+' ? 1 : -1);
ans=findPosibleChilds(tmpP1, tmpP2);
cout << p1 << " " << p2 << " ";
printAns(ans, totalRH);
}
else{
int totalRH=1;
string knownParent=p1!="?" ? p1 : p2;
string tmpParent=knownParent.substr(0, knownParent.size()-1);
string tmpChild=child.substr(0, child.size()-1);
bool isParentNeg=knownParent[knownParent.size()-1]=='-';
bool isChildNeg=child[child.size()-1]=='-';
//cout << "Going with RH: " << totalRH << "\n";
if(isParentNeg && !isChildNeg){
totalRH=-1;
}
//cout << "FInding for: " << tmpParent << ", " << tmpChild << "\n";
ans=findPosibleParent(tmpParent, tmpChild);
if(p1!="?"){
cout << p1 << " ";
printAns(ans, totalRH);
cout << " " << child;
}
else{
printAns(ans, totalRH);
cout << " " << p2 << " " << child;
}
}
cout << "\n";
}
return 0;
}
| 25.139303 | 79 | 0.398773 | [
"vector"
] |
914c80cc94040e82c6c369b2c22450a6644730fd | 1,782 | hpp | C++ | tools/Vitis-AI-Library/usefultools/src/tools_extra_ops.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 1 | 2022-02-17T22:13:23.000Z | 2022-02-17T22:13:23.000Z | tools/Vitis-AI-Library/usefultools/src/tools_extra_ops.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | tools/Vitis-AI-Library/usefultools/src/tools_extra_ops.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Xilinx 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.
*/
#pragma once
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <string>
#include <vector>
#include <xir/graph/subgraph.hpp>
namespace py = pybind11;
std::string xmodel_to_txt(std::string xmodel);
py::dict xdputil_query();
py::dict xdputil_status();
std::vector<uint32_t> read_register(void* handle, uint32_t ip_index,
uint64_t cu_base_addr,
const std::vector<uint32_t>& addrs);
std::vector<std::string> xilinx_version(std::vector<std::string> so_names);
bool test_dpu_runner_mt(const xir::Subgraph* subgraph, uint32_t runner_num,
const std::vector<std::string>& input_filenames,
const std::vector<std::string>& output_filenames);
template <class T>
std::string to_string(T t, std::ios_base& (*f)(std::ios_base&), std::string prefix = "0x") {
std::ostringstream oss;
oss << prefix << f << t;
return oss.str();
}
std::map<std::string, std::string> get_reg_id_to_parameter(
const xir::Subgraph* s);
bool test_op_run(const std::string& graph, const std::string& op,
const std::string& ref_dir, const std::string& dump_dir);
| 37.914894 | 92 | 0.680696 | [
"vector"
] |
914fb12c32771e1fe4e3c10656ad6a968ce613d3 | 21,174 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Commands/Monkey/src/MonkeySourceRandom.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Commands/Monkey/src/MonkeySourceRandom.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Commands/Monkey/src/MonkeySourceRandom.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "MonkeySourceRandom.h"
#include "elastos/droid/os/SystemClock.h"
#include <elastos/core/Math.h>
using Elastos::Droid::View::IKeyEvent;
using Elastos::Droid::View::IKeyEventHelper;
using Elastos::Droid::View::CKeyEventHelper;
using Elastos::Droid::View::IKeyCharacterMapHelper;
using Elastos::Droid::View::CKeyCharacterMapHelper;
using Elastos::Droid::Os::SystemClock;
using Elastos::Droid::View::ISurface;
using Elastos::Droid::Hardware::Display::IDisplayManagerGlobalHelper;
using Elastos::Droid::Hardware::Display::CDisplayManagerGlobalHelper;
using Elastos::Droid::Graphics::CPointF;
using Elastos::Core::Math;
using Elastos::Droid::Hardware::Display::IDisplayManagerGlobal;
namespace Elastos {
namespace Droid {
namespace Commands {
namespace Monkey {
/** Key events that move around the UI. */
static const AutoPtr<ArrayOf<Int32> > NAV_KEYS = ArrayOf<Int32>::Alloc(4);
/**
* Key events that perform major navigation options (so shouldn't be sent
* as much).
*/
static const AutoPtr<ArrayOf<Int32> > MAJOR_NAV_KEYS = ArrayOf<Int32>::Alloc(2);
/** Key events that perform system operations. */
static const AutoPtr<ArrayOf<Int32> > SYS_KEYS = ArrayOf<Int32>::Alloc(8);
/** Possible screen rotation degrees **/
static const AutoPtr<ArrayOf<Int32> > SCREEN_ROTATION_DEGREES = ArrayOf<Int32>::Alloc(4);
/** If a physical key exists? */
static const AutoPtr<ArrayOf<Boolean> > PHYSICAL_KEY_EXISTS = MonkeySourceRandom::InitStatics();
AutoPtr< ArrayOf<Boolean> > MonkeySourceRandom::InitStatics()
{
AutoPtr<IKeyEventHelper> helper;
ASSERT_SUCCEEDED(CKeyEventHelper::AcquireSingleton((IKeyEventHelper**)&helper));
Int32 length = 0;
helper->GetMaxKeyCode(&length);
++length;
AutoPtr<ArrayOf<Boolean> > ret = ArrayOf<Boolean>::Alloc(length);
for (Int32 i = 0; i < length; ++i) {
ret->Set(i, TRUE);
}
NAV_KEYS->Set(0, IKeyEvent::KEYCODE_DPAD_UP);
NAV_KEYS->Set(1, IKeyEvent::KEYCODE_DPAD_DOWN);
NAV_KEYS->Set(2, IKeyEvent::KEYCODE_DPAD_LEFT);
NAV_KEYS->Set(3, IKeyEvent::KEYCODE_DPAD_RIGHT);
MAJOR_NAV_KEYS->Set(0, IKeyEvent::KEYCODE_MENU);//KeyEvent.KEYCODE_SOFT_RIGHT
MAJOR_NAV_KEYS->Set(1, IKeyEvent::KEYCODE_DPAD_CENTER);
SYS_KEYS->Set(0, IKeyEvent::KEYCODE_HOME);
SYS_KEYS->Set(1, IKeyEvent::KEYCODE_BACK);
SYS_KEYS->Set(2, IKeyEvent::KEYCODE_CALL);
SYS_KEYS->Set(3, IKeyEvent::KEYCODE_ENDCALL);
SYS_KEYS->Set(4, IKeyEvent::KEYCODE_VOLUME_UP);
SYS_KEYS->Set(5, IKeyEvent::KEYCODE_VOLUME_DOWN);
SYS_KEYS->Set(6, IKeyEvent::KEYCODE_VOLUME_MUTE);
SYS_KEYS->Set(7, IKeyEvent::KEYCODE_MUTE);
AutoPtr<IKeyCharacterMapHelper> keyMapHelper;
CKeyCharacterMapHelper::AcquireSingleton((IKeyCharacterMapHelper**)&keyMapHelper);
// Only examine SYS_KEYS
length = SYS_KEYS->GetLength();
for (Int32 i = 0; i < length; ++i) {
Boolean hasKey;
keyMapHelper->DeviceHasKey((*SYS_KEYS)[i], &hasKey);
ret->Set((*SYS_KEYS)[i], hasKey);
}
SCREEN_ROTATION_DEGREES->Set(0, ISurface::ROTATION_0);
SCREEN_ROTATION_DEGREES->Set(1, ISurface::ROTATION_90);
SCREEN_ROTATION_DEGREES->Set(2, ISurface::ROTATION_180);
SCREEN_ROTATION_DEGREES->Set(3, ISurface::ROTATION_270);
return ret;
}
MonkeySourceRandom::MonkeySourceRandom()
: mFactors(ArrayOf<Float>::Alloc(IMonkeySourceRandom::FACTORZ_COUNT))
, mEventCount(0)
, mVerbose(0)
, mThrottle(0)
{}
MonkeySourceRandom::~MonkeySourceRandom()
{
}
void MonkeySourceRandom::GetKeyName(
/* [in] */ Int32 keycode,
/* [out] */ String* pRet)
{
AutoPtr<IKeyEventHelper> helper;
ASSERT_SUCCEEDED(CKeyEventHelper::AcquireSingleton((IKeyEventHelper**)&helper));
helper->KeyCodeToString(keycode, pRet);
}
void MonkeySourceRandom::GetKeyCode(
/* [in] */ const String& keyName,
/* [out] */ Int32 * pKeycode)
{
AutoPtr<IKeyEventHelper> helper;
ASSERT_SUCCEEDED(CKeyEventHelper::AcquireSingleton((IKeyEventHelper**)&helper));
helper->KeyCodeFromString(keyName, pKeycode);
}
void MonkeySourceRandom::Init(
/* [in] */ IRandom * pRandom,
/* [in] */ IObjectContainer * mainApps,
/* [in] */ Int64 throttle,
/* [in] */ Boolean randomizeThrottle)
{
// default values for random distributions
// note, these are straight percentages, to match user input (cmd line args)
// but they will be converted to 0..1 values before the main loop runs.
mFactors->Set(IMonkeySourceRandom::FACTOR_TOUCH, 15.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_MOTION, 10.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_TRACKBALL, 15.0f);
// Adjust the values if we want to enable rotation by default.
mFactors->Set(IMonkeySourceRandom::FACTOR_ROTATION, 0.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_NAV, 25.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_MAJORNAV, 15.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_SYSOPS, 2.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_APPSWITCH, 2.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_FLIP, 1.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_ANYTHING, 13.0f);
mFactors->Set(IMonkeySourceRandom::FACTOR_PINCHZOOM, 2.0f);
mRandom = pRandom;
mMainApps = new List<AutoPtr<IComponentName> >();
AutoPtr<IObjectEnumerator> enumerator;
mainApps->GetObjectEnumerator((IObjectEnumerator**)&enumerator);
Boolean hasNext = FALSE;
while (enumerator->MoveNext(&hasNext), hasNext) {
AutoPtr<IInterface> element;
enumerator->Current((IInterface**)&element);
mMainApps->PushBack(IComponentName::Probe(element));
}
CMonkeyEventQueue::New(pRandom, throttle, randomizeThrottle,
(IMonkeyEventQueue**)&mQ);
}
Boolean MonkeySourceRandom::AdjustEventFactors()
{
// go through all values and compute totals for user & default values
Float userSum = 0.0f;
Float defaultSum = 0.0f;
Int32 defaultCount = 0;
for (Int32 i = 0; i < IMonkeySourceRandom::FACTORZ_COUNT; ++i) {
if ((*mFactors)[i] <= 0.0f) { // user values are zero or negative
userSum -= (*mFactors)[i];
}
else {
defaultSum += (*mFactors)[i];
++defaultCount;
}
}
// if the user request was > 100%, reject it
if (userSum > 100.0f) {
PFL_EX("** Event weights > 100%%");
return FALSE;
}
// if the user specified all of the weights, then they need to be 100%
if (defaultCount == 0 && (userSum < 99.9f || userSum > 100.1f)) {
PFL_EX("** Event weights != 100%%");
return FALSE;
}
// compute the adjustment necessary
Float defaultsTarget = (100.0f - userSum);
Float defaultsAdjustment = defaultsTarget / defaultSum;
// fix all values, by adjusting defaults, or flipping user values back to >0
for (Int32 i = 0; i < IMonkeySourceRandom::FACTORZ_COUNT; ++i) {
if ((*mFactors)[i] <= 0.0f) { // user values are zero or negative
(*mFactors)[i] = -(*mFactors)[i];
}
else {
(*mFactors)[i] *= defaultsAdjustment;
}
}
// if verbose, show factors
if (mVerbose > 0) {
PFL_EX("// Event percentages:");
for (Int32 i = 0; i < IMonkeySourceRandom::FACTORZ_COUNT; ++i) {
PFL_EX("// %d: %f%%", i, (*mFactors)[i]);
}
}
if (!ValidateKeys()) {
return FALSE;
}
// finally, normalize and convert to running sum
Float sum = 0.0f;
for (Int32 i = 0; i < IMonkeySourceRandom::FACTORZ_COUNT; ++i) {
sum += (*mFactors)[i] / 100.0f;
(*mFactors)[i] = sum;
}
return TRUE;
}
Boolean MonkeySourceRandom::ValidateKeyCategory(
/* [in] */const String& catName,
/* [in] */ ArrayOf<Int32> *keys,
/* [in] */ Float factor)
{
if (factor < 0.1f) {
return TRUE;
}
Int32 length = keys->GetLength();
for(Int32 i = 0; i < length; ++i) {
if((*PHYSICAL_KEY_EXISTS)[(*keys)[i]]) {
return TRUE;
}
}
PFL_EX("** %s has no physical keys but with factor %f%%.",
catName.string(), factor);
return FALSE;
}
Boolean MonkeySourceRandom::ValidateKeys()
{
return ValidateKeyCategory(
String("NAV_KEYS"),
NAV_KEYS,
(*mFactors)[IMonkeySourceRandom::FACTOR_NAV]) &&
ValidateKeyCategory(
String("MAJOR_NAV_KEYS"),
MAJOR_NAV_KEYS,
(*mFactors)[IMonkeySourceRandom::FACTOR_MAJORNAV]) &&
ValidateKeyCategory(
String("SYS_KEYS"),
SYS_KEYS,
(*mFactors)[IMonkeySourceRandom::FACTOR_SYSOPS]);
}
ECode MonkeySourceRandom::SetFactors(
/* [in] */ ArrayOf<Float> *factors)
{
Int32 c = IMonkeySourceRandom::FACTORZ_COUNT;
if (factors->GetLength() < c) {
c = factors->GetLength();
}
for(Int32 i = 0; i < c; ++i) {
mFactors->Set(i, (*factors)[i]);
}
return NOERROR;
}
ECode MonkeySourceRandom::SetFactors(
/* [in] */ Int32 index,
/* [in] */ Float v)
{
mFactors->Set(index, v);
return NOERROR;
}
void MonkeySourceRandom::GeneratePointerEvent(
/* [in] */ IRandom *random,
/* [in] */ Int32 gesture)
{
AutoPtr<IDisplay> display ;
AutoPtr<IDisplayManagerGlobal> global;
AutoPtr<IDisplayManagerGlobalHelper> helper;
CDisplayManagerGlobalHelper::AcquireSingleton((IDisplayManagerGlobalHelper**)&helper);
helper->GetInstance((IDisplayManagerGlobal**)&global);
if (global == NULL) {
PFL_EX("***** Monkey Error: failed to get IDisplayManagerGlobal.");
assert(global != NULL && "***** Monkey Error: failed to get IDisplayManagerGlobal.");
return;
}
global->GetRealDisplay(IDisplay::DEFAULT_DISPLAY, (IDisplay**)&display);
if (display == NULL) {
PFL_EX("***** Monkey Error: failed to get default display.");
assert(display != NULL && "***** Monkey Error: failed to get default display.");
return;
}
AutoPtr<IPointF> p1 = RandomPoint(random, display);
AutoPtr<IPointF> v1 = RandomVector(random);
Int64 downAt = SystemClock::GetUptimeMillis();
AutoPtr<IMonkeyTouchEvent> event;
CMonkeyTouchEvent::New(IMotionEvent::ACTION_DOWN, (IMonkeyTouchEvent**)&event);
event->SetDownTime(downAt);
Float x = 0;
Float y = 0;
p1->GetX(&x);
p1->GetY(&y);
event->AddPointer(0, x, y);
event->SetIntermediateNote(FALSE);
mQ->AddLast(IMonkeyEvent::Probe(event));
// sometimes we'll move during the touch
if (gesture == GESTURE_DRAG) {
Int32 count;
random->NextInt32(10, &count);
for (Int32 i = 0; i < count; ++i) {
RandomWalk(random, display, p1, v1);
event = NULL;
CMonkeyTouchEvent::New(IMotionEvent::ACTION_MOVE, (IMonkeyTouchEvent**)&event);
event->SetDownTime(downAt);
p1->GetX(&x);
p1->GetY(&y);
event->AddPointer(0, x, y);
event->SetIntermediateNote(TRUE);
mQ->AddLast(IMonkeyEvent::Probe(event));
}
}
else if(gesture == GESTURE_PINCH_OR_ZOOM) {
AutoPtr<IPointF> p2 = RandomPoint(random, display);
AutoPtr<IPointF> v2 = RandomVector(random);
Float x2;
Float y2;
RandomWalk(random, display, p1, v1);
event = NULL;
CMonkeyTouchEvent::New(IMotionEvent::ACTION_POINTER_DOWN | (1 << IMotionEvent::ACTION_POINTER_INDEX_SHIFT),
(IMonkeyTouchEvent**)&event);
event->SetDownTime(downAt);
p1->GetX(&x);
p1->GetY(&y);
event->AddPointer(0, x, y);
p2->GetX(&x2);
p2->GetY(&y2);
event->AddPointer(1, x2, y2);
event->SetIntermediateNote(TRUE);
mQ->AddLast(IMonkeyEvent::Probe(event));
Int32 count;
random->NextInt32(10, &count);
for (Int32 i = 0; i < count; ++i) {
RandomWalk(random, display, p1, v1);
RandomWalk(random, display, p2, v2);
event = NULL;
CMonkeyTouchEvent::New(IMotionEvent::ACTION_MOVE, (IMonkeyTouchEvent**)&event);
event->SetDownTime(downAt);
p1->GetX(&x);
p1->GetY(&y);
p2->GetX(&x2);
p2->GetY(&y2);
event->AddPointer(0, x, y);
event->AddPointer(1, x2, y2);
event->SetIntermediateNote(TRUE);
mQ->AddLast(IMonkeyEvent::Probe(event));
}
RandomWalk(random, display, p1, v1);
RandomWalk(random, display, p2, v2);
event = NULL;
CMonkeyTouchEvent::New(IMotionEvent::ACTION_POINTER_UP | (1 << IMotionEvent::ACTION_POINTER_INDEX_SHIFT),
(IMonkeyTouchEvent**)&event);
event->SetDownTime(downAt);
p1->GetX(&x);
p1->GetY(&y);
p2->GetX(&x2);
p2->GetY(&y2);
event->AddPointer(0, x, y);
event->AddPointer(1, x2, y2);
event->SetIntermediateNote(TRUE);
mQ->AddLast(IMonkeyEvent::Probe(event));
}
RandomWalk(random, display, p1, v1);
event = NULL;
CMonkeyTouchEvent::New(IMotionEvent::ACTION_UP, (IMonkeyTouchEvent**)&event);
event->SetDownTime(downAt);
p1->GetX(&x);
p1->GetY(&y);
event->AddPointer(0, x, y);
event->SetIntermediateNote(FALSE);
mQ->AddLast(IMonkeyEvent::Probe(event));
}
AutoPtr<IPointF> MonkeySourceRandom::RandomPoint(
/* [in] */ IRandom* random,
/* [in] */ IDisplay* display)
{
AutoPtr<IPointF> point;
Int32 width;
Int32 heigth;
display->GetWidth(&width);
display->GetHeight(&heigth);
random->NextInt32(width, &width);
random->NextInt32(heigth, &heigth);
CPointF::New(width, heigth, (IPointF**)&point);
return point;
}
AutoPtr<IPointF> MonkeySourceRandom::RandomVector(
/* [in] */ IRandom* random)
{
AutoPtr<IPointF> point;
Float nf1;
Float nf2;
random->NextFloat(&nf1);
random->NextFloat(&nf2);
CPointF::New((nf1 - 0.5f) * 50, (nf2 - 0.5f) * 50, (IPointF**)&point);
return point;
}
void MonkeySourceRandom::RandomWalk(
/* [in] */ IRandom* random,
/* [in] */ IDisplay* display,
/* [in] */ IPointF* point,
/* [in] */ IPointF* vector)
{
using Elastos::Core::Math;
Float px, py;
Float vx, vy;
Float rdmx, rdmy;
point->GetX(&px);
point->GetY(&py);
vector->GetX(&vx);
vector->GetY(&vy);
random->NextFloat(&rdmx);
random->NextFloat(&rdmy);
Int32 width, height;
display->GetWidth(&width);
display->GetHeight(&height);
point->Set(Math::Max(Math::Min(px + rdmx * vx, (Float)width), 0.0f)
, Math::Max(Math::Min(py + rdmy * vy, (Float)height), 0.0f));
}
void MonkeySourceRandom::GenerateTrackballEvent(
/* [in] */ IRandom *random)
{
for (Int32 i = 0; i < 10; ++i) {
// generate a small random step
Int32 dX;
random->NextInt32(10, &dX);
dX = dX - 5;
Int32 dY;
random->NextInt32(10, &dY);
dY = dY - 5;
AutoPtr<IMonkeyMotionEvent> event;
CMonkeyTrackballEvent::New(IMotionEvent::ACTION_MOVE, (IMonkeyMotionEvent**)&event);
event->AddPointer(0, dX, dY);
event->SetIntermediateNote(i > 0);
mQ->AddLast(IMonkeyEvent::Probe(event));
}
// 10% of trackball moves end with a click
Int32 rdm;
random->NextInt32(10, &rdm);
if (0 == rdm) {
Int64 downAt = SystemClock::GetUptimeMillis();
AutoPtr<IMonkeyMotionEvent> event;
CMonkeyTrackballEvent::New(IMotionEvent::ACTION_DOWN, (IMonkeyMotionEvent**)&event);
event->SetDownTime(downAt);
event->AddPointer(0, 0, 0);
event->SetIntermediateNote(TRUE);
mQ->AddLast(IMonkeyEvent::Probe(event));
event = NULL;
CMonkeyTrackballEvent::New(IMotionEvent::ACTION_UP, (IMonkeyMotionEvent**)&event);
event->SetDownTime(downAt);
event->AddPointer(0, 0, 0);
event->SetIntermediateNote(FALSE);
mQ->AddLast(IMonkeyEvent::Probe(event));
}
}
void MonkeySourceRandom::GenerateRotationEvent(
/* [in] */ IRandom *random)
{
AutoPtr<IMonkeyRotationEvent> event;
Int32 rdmInt32;
Boolean rdmBool;
random->NextInt32(SCREEN_ROTATION_DEGREES->GetLength(), &rdmInt32);
random->NextBoolean(&rdmBool);
CMonkeyRotationEvent::New((*SCREEN_ROTATION_DEGREES)[rdmInt32],
rdmBool, (IMonkeyRotationEvent**)&event);
mQ->AddLast(IMonkeyEvent::Probe(event));
}
void MonkeySourceRandom::GenerateEvents()
{
Float cls;
mRandom->NextFloat(&cls);
Int32 lastKey = 0;
if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_TOUCH]) {
GeneratePointerEvent(mRandom, GESTURE_TAP);
return;
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_MOTION]) {
GeneratePointerEvent(mRandom, GESTURE_DRAG);
return;
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_PINCHZOOM]) {
GeneratePointerEvent(mRandom, GESTURE_PINCH_OR_ZOOM);
return;
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_TRACKBALL]) {
GenerateTrackballEvent(mRandom);
return;
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_ROTATION]) {
GenerateRotationEvent(mRandom);
return;
}
// The remaining event categories are injected as key events
for (;;) {
if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_NAV]) {
mRandom->NextInt32(NAV_KEYS->GetLength(), &lastKey);
lastKey = (*NAV_KEYS)[lastKey];
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_MAJORNAV]) {
mRandom->NextInt32(MAJOR_NAV_KEYS->GetLength(), &lastKey);
lastKey = (*MAJOR_NAV_KEYS)[lastKey];
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_SYSOPS]) {
mRandom->NextInt32(SYS_KEYS->GetLength(), &lastKey);
lastKey = (*SYS_KEYS)[lastKey];
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_APPSWITCH]) {
AutoPtr<IMonkeyActivityEvent> e;
Int32 size = mMainApps->GetSize();
mRandom->NextInt32(size, &size);
CMonkeyActivityEvent::New((*mMainApps)[size], (IMonkeyActivityEvent**)&e);
mQ->AddLast(IMonkeyEvent::Probe(e));
return;
}
else if (cls < (*mFactors)[IMonkeySourceRandom::FACTOR_FLIP]) {
AutoPtr<IMonkeyFlipEvent> e;
CMonkeyFlipEvent::New(mKeyboardOpen, (IMonkeyFlipEvent**)&e);
mKeyboardOpen = !mKeyboardOpen;
mQ->AddLast(IMonkeyEvent::Probe(e));
return;
}
else {
AutoPtr<IKeyEventHelper> helper;
ASSERT_SUCCEEDED(CKeyEventHelper::AcquireSingleton((IKeyEventHelper**)&helper));
Int32 length = 0;
helper->GetMaxKeyCode(&length);
mRandom->NextInt32(--length, &lastKey);
++lastKey;
}
if (lastKey != IKeyEvent::KEYCODE_POWER
&& lastKey != IKeyEvent::KEYCODE_ENDCALL
&& (*PHYSICAL_KEY_EXISTS)[lastKey])
{
break;
}
}
AutoPtr<IMonkeyKeyEvent> e;
CMonkeyKeyEvent::New(IKeyEvent::ACTION_DOWN, lastKey, (IMonkeyKeyEvent**)&e);
mQ->AddLast(IMonkeyEvent::Probe(e));
e = NULL;
CMonkeyKeyEvent::New(IKeyEvent::ACTION_UP, lastKey, (IMonkeyKeyEvent**)&e);
mQ->AddLast(IMonkeyEvent::Probe(e));
}
ECode MonkeySourceRandom::SetVerbose(
/* [in] */ Int32 verbose)
{
mVerbose = verbose;
return NOERROR;
}
ECode MonkeySourceRandom::Validate(
/* [out] */ Boolean *result)
{
//check factors
VALIDATE_NOT_NULL(result);
*result = AdjustEventFactors();
return NOERROR;
}
ECode MonkeySourceRandom::GenerateActivity()
{
AutoPtr<IMonkeyActivityEvent> e;
Int32 size = mMainApps->GetSize();
mRandom->NextInt32(size, &size);
CMonkeyActivityEvent::New((*mMainApps)[size], (IMonkeyActivityEvent**)&e);
mQ->AddLast(IMonkeyEvent::Probe(e));
return NOERROR;
}
ECode MonkeySourceRandom::GetNextEvent(
/* [out] */IMonkeyEvent **event)
{
VALIDATE_NOT_NULL(event);
Boolean empty;
mQ->IsEmpty(&empty);
if (empty) {
GenerateEvents();
}
++mEventCount;
mQ->GetFirst(event);
mQ->RemoveFirst();
return NOERROR;
}
} // namespace Monkey
} // namespace Commands
} // namespace Droid
} // namespace Elastos
| 33.13615 | 115 | 0.628743 | [
"vector"
] |
915aea7b9ada2e89b227f254eb64c83ab2b3496b | 677 | cpp | C++ | libraries/wasmlib/wasmlib.cpp | xiaoyu1998/wasm.cdt | 79e8a65ec682164b7c917a6d209adbbda0e17059 | [
"MIT"
] | 3 | 2019-08-28T09:42:32.000Z | 2020-10-19T06:24:26.000Z | libraries/wasmlib/wasmlib.cpp | xiaoyu1998/wasm.cdt | 79e8a65ec682164b7c917a6d209adbbda0e17059 | [
"MIT"
] | null | null | null | libraries/wasmlib/wasmlib.cpp | xiaoyu1998/wasm.cdt | 79e8a65ec682164b7c917a6d209adbbda0e17059 | [
"MIT"
] | 4 | 2019-08-29T02:05:53.000Z | 2020-01-08T08:33:07.000Z | #include "core/datastream.hpp"
#include "contracts/system.hpp"
#include "contracts/privileged.hpp"
namespace wasm {
extern "C" {
__attribute__((wasm_wasm_import))
uint64_t current_time();
__attribute__((wasm_wasm_import))
uint32_t get_active_producers(uint64_t*, uint32_t);
}
uint64_t current_block_time() {
return current_time();
}
std::vector<name> get_active_producers() {
auto prod_cnt = get_active_producers(nullptr, 0)/8;
std::vector<name> active_prods(prod_cnt);
get_active_producers((uint64_t*)active_prods.data(), active_prods.size() * sizeof(name));
return active_prods;
}
} // namespace wasm
| 24.178571 | 94 | 0.697194 | [
"vector"
] |
915c7e925d8ab2fff9962869378d0d44863cf6f1 | 7,026 | hpp | C++ | src/object.hpp | nilern/kauno | a82f43bc535378afe9ce427ffb16921bf966fd47 | [
"MIT"
] | null | null | null | src/object.hpp | nilern/kauno | a82f43bc535378afe9ce427ffb16921bf966fd47 | [
"MIT"
] | null | null | null | src/object.hpp | nilern/kauno | a82f43bc535378afe9ce427ffb16921bf966fd47 | [
"MIT"
] | null | null | null | #ifndef OBJECT_H
#define OBJECT_H
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <optional>
using std::optional;
namespace kauno {
class State;
struct Header {
uintptr_t bits;
};
struct Type;
template<typename T>
class ORef {
T* ptr_;
public:
explicit ORef(T* ptr) : ptr_(ptr) {}
Header* header() const { return (Header*)ptr_ - 1; }
bool is_marked() const { return header()->bits & 1; }
void set_marked() const { header()->bits |= 1; }
ORef<Type> type() const { return ORef<Type>((Type*)(void*)(header()->bits & ~1)); }
void set_type(ORef<Type> type) const { header()->bits = (size_t)type.data() | (header()->bits & 1); }
T* data() const { return ptr_; }
bool operator==(ORef<T> other) const { return ptr_ == other.ptr_; }
bool operator!=(ORef<T> other) const { return ptr_ != other.ptr_; }
bool is_instance_dyn(ORef<Type> super) const { return type() == super; }
template<typename S>
bool is_instance(State const& state) const { return is_instance_dyn(S::reify(state)); }
template<typename U>
ORef<U> unchecked_cast() const { return ORef<U>((U*)ptr_); }
template<typename U>
optional<ORef<U>> try_cast(State const& state) const {
return is_instance<U>(state) ? optional(unchecked_cast<U>()) : optional<ORef<U>>();
}
ORef<void> as_void() const { return unchecked_cast<void>(); }
};
template<typename T>
class NRef {
T* ptr_;
public:
NRef() : ptr_(nullptr) {}
explicit NRef(T* ptr) : ptr_(ptr) {}
explicit NRef(ORef<T> oref) : ptr_(oref.data()) {}
bool has_value() const { return ptr_ != nullptr; }
optional<ORef<T>> data() const { return ptr_ ? optional(ORef(ptr_)) : optional<ORef<T>>(); }
T* ptr() const { return ptr_; }
};
/** Pointer to data stack entry */
template<typename T>
class SRef {
T* ptr_;
public:
explicit SRef(T* ptr) : ptr_(ptr) {}
T* data() const { return ptr_; }
template<typename U>
SRef<U> unchecked_cast() const { return SRef<U>((U*)ptr_); }
};
template<typename T>
class Handle;
/** Type stack entry */
class DynRef {
void* sptr_;
NRef<Type> type_;
public:
DynRef(ORef<Type> type, void* data) : sptr_(data), type_(NRef(type)) {}
template<typename T>
explicit DynRef(ORef<T>* ptr) : sptr_((void*)ptr), type_() {}
ORef<Type> type() const {
optional<ORef<Type>> const opt_type = type_.data();
if (opt_type.has_value()) {
return *opt_type;
} else {
return unchecked_oref().type();
}
}
void* data() const {
optional<ORef<Type>> const opt_type = type_.data();
if (opt_type.has_value()) {
return sptr_;
} else {
return unchecked_oref().data();
}
}
void* stack_ptr() const { return sptr_; }
SRef<void> unchecked_sref() const;
Handle<void> unchecked_handle() const;
template<typename T>
optional<SRef<T>> try_sref() const;
template<typename T>
optional<Handle<T>> try_handle() const;
ORef<void> unchecked_oref() const { return *(ORef<void>*)sptr_; }
bool is_instance_dyn(ORef<Type> super) const {
optional<ORef<Type>> const opt_type = type_.data();
if (opt_type.has_value()) {
return *opt_type == super;
} else {
return unchecked_oref().is_instance_dyn(super);
}
}
void repush(State& state) const;
ORef<void> to_heap(State& state) const;
};
/** Pointer to type stack entry */
class AnySRef {
DynRef* dyn_ref_ptr_;
public:
explicit AnySRef(DynRef* dyn_ref_ptr) : dyn_ref_ptr_(dyn_ref_ptr) {}
ORef<Type> type() const { return dyn_ref_ptr_->type(); }
void* data() const { return dyn_ref_ptr_->data(); }
bool is_instance_dyn(ORef<Type> super) const { return dyn_ref_ptr_->is_instance_dyn(super); }
template<typename T>
Handle<T> unchecked_handle() const;
template<typename T>
optional<SRef<T>> try_sref() const;
template<typename T>
optional<Handle<T>> try_handle() const;
ORef<void> to_heap(State& state) const { return dyn_ref_ptr_->to_heap(state); }
};
/** Pointer to object reference on the data stack */
template<typename T>
class Handle {
ORef<T>* oref_ptr_;
public:
explicit Handle(ORef<T>* oref_ptr) : oref_ptr_(oref_ptr) {}
ORef<T> oref() const { return oref_ptr_->template unchecked_cast<T>(); }
T* data() const { return oref().data(); }
template<typename U>
Handle<U> unchecked_cast() const { return Handle<U>((ORef<U>*)oref_ptr_); }
Handle<void> as_void() const { return unchecked_cast<void>(); }
};
SRef<void> DynRef::unchecked_sref() const { return SRef(sptr_); }
Handle<void> DynRef::unchecked_handle() const { return Handle((ORef<void>*)sptr_); }
template<typename T>
optional<SRef<T>> DynRef::try_sref() const {
return type_.has_value() ?
optional(unchecked_sref().unchecked_cast<T>())
: optional<SRef<T>>();
}
template<typename T>
optional<Handle<T>> DynRef::try_handle() const {
return type_.has_value() ?
optional<Handle<T>>()
: optional(unchecked_handle().unchecked_cast<T>());
}
template<typename T>
Handle<T> AnySRef::unchecked_handle() const {
return dyn_ref_ptr_->unchecked_handle().unchecked_cast<T>();
}
template<typename T>
optional<SRef<T>> AnySRef::try_sref() const { return dyn_ref_ptr_->try_sref<T>(); }
template<typename T>
optional<Handle<T>> AnySRef::try_handle() const { return dyn_ref_ptr_->try_handle<T>(); }
struct Field {
NRef<Type> type;
size_t offset;
size_t size;
bool inlined;
Field(NRef<Type> type_, size_t offset_);
};
struct Type {
size_t hash;
size_t align;
size_t min_size;
bool inlineable;
bool is_bits;
bool has_indexed;
size_t fields_count; // if is_bits then byte count else field_types count
Field fields[0];
static ORef<Type> reify(State const& state);
private:
Type(State& state,
size_t align_, size_t min_size_, bool inlineable_, bool is_bits_, bool has_indexed_, size_t fields_count_);
public:
static Type create_bits(State& state, size_t align, size_t size, bool inlineable) {
return Type(state, align, size, inlineable, true, false, 0);
}
static Type create_record(State& state, size_t align, size_t size, bool inlineable, size_t fields_count) {
return Type(state, align, size, inlineable, false, false, fields_count);
}
static Type create_indexed(State& state, size_t align, size_t min_size, size_t fields_count) {
return Type(state, align, min_size, false, false, true, fields_count);
}
};
Field::Field(NRef<Type> type_, size_t offset_)
: type(type_), offset(offset_),
size(0), inlined(false)
{
optional<ORef<Type>> const t = type_.data();
if (t.has_value()) {
size = t->data()->min_size;
inlined = t->data()->inlineable;
}
}
struct None {};
}
#endif // OBJECT_H
| 25.182796 | 116 | 0.637774 | [
"object"
] |
9162688702def1b599595936a787d9cb802e4127 | 2,042 | hpp | C++ | src/netspeak/QueryNormalizer.hpp | netspeak/netspeak4-application-cpp | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | null | null | null | src/netspeak/QueryNormalizer.hpp | netspeak/netspeak4-application-cpp | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | 7 | 2020-06-02T18:37:02.000Z | 2021-02-17T11:04:22.000Z | src/netspeak/QueryNormalizer.hpp | netspeak/netspeak4-application-ngrams | b322c19e22c71f39be95b37b14f43daab1cb9024 | [
"MIT"
] | null | null | null | #ifndef NETSPEAK_QUERY_NORMALIZER_HPP
#define NETSPEAK_QUERY_NORMALIZER_HPP
#include <memory>
#include <string>
#include <vector>
#include "netspeak/Dictionaries.hpp"
#include "netspeak/model/NormQuery.hpp"
#include "netspeak/model/Query.hpp"
#include "netspeak/regex/RegexIndex.hpp"
namespace netspeak {
// TODO: cache for regex queries
/**
* This class is responsable for normalizing queries.
*
* A norm query (normalized query)
*/
class QueryNormalizer {
private:
std::shared_ptr<regex::RegexIndex> regex_index_;
std::shared_ptr<Dictionaries::Map> dictionary_;
bool lower_case;
public:
struct InitConfig {
std::shared_ptr<regex::RegexIndex> regex_index = nullptr;
std::shared_ptr<Dictionaries::Map> dictionary = nullptr;
bool lower_case = false;
};
QueryNormalizer() {}
QueryNormalizer(InitConfig config);
QueryNormalizer(const QueryNormalizer&) = delete;
struct Options {
/**
* @brief The maximum number of norm queries allowed to be returned.
*/
size_t max_norm_queries;
/**
* @brief Same as \c max_length but as a minimum.
*/
uint32_t min_length;
/**
* @brief The maximum length norm queries are allowed to have.
*
* This means that only phrases up to this length can be matched by the norm
* queries.
*/
uint32_t max_length;
/**
* @brief The maximum number of words each regex can be replaced with.
*
* A regex will (usually) be replaced with an alternation of words that
* match that regex. This value determines with how many words each regex
* will be replaced with at most.
*/
size_t max_regex_matches;
/**
* @brief The maximum amount of time spend on each regex to find matching
* words for that regex.
*/
std::chrono::nanoseconds max_regex_time;
};
void normalize(std::shared_ptr<const model::Query> query,
const Options& options,
std::vector<model::NormQuery>& norm_queries);
};
} // namespace netspeak
#endif
| 24.60241 | 80 | 0.684133 | [
"vector",
"model"
] |
916f910fb01e6a6ed87a63c38754a7583ebc35f8 | 21,776 | hpp | C++ | task6_parallelization_and_numa_awareness/ParallelRadixJoins.hpp | cakebytheoceanLuo/data_processing_on_modern_hardware | 9d334be7a9cd426a881164a2938195422006e069 | [
"MIT"
] | null | null | null | task6_parallelization_and_numa_awareness/ParallelRadixJoins.hpp | cakebytheoceanLuo/data_processing_on_modern_hardware | 9d334be7a9cd426a881164a2938195422006e069 | [
"MIT"
] | null | null | null | task6_parallelization_and_numa_awareness/ParallelRadixJoins.hpp | cakebytheoceanLuo/data_processing_on_modern_hardware | 9d334be7a9cd426a881164a2938195422006e069 | [
"MIT"
] | null | null | null | //
// Created by Alexander Beischl on 2020-05-19.
//
#include "Relation.hpp"
#include "ThreadPool.hpp"
#include "Barrier.hpp"
#include <numa.h>
#include <numaif.h>
#include <cassert>
#include <unordered_set>
#include <vector>
#include <thread>
#include <atomic>
enum class Partitioning { naive, softwareManaged, multiPass };
// Assume relation r is smaller
uint64_t hash_join(const relation &r, const relation &s) {
uint64_t matches = 0;
std::unordered_set<keyType> hashTable;
hashTable.reserve(r.size());
// Build the hash table by inserting all tuples from r
for (auto &t : r) {
hashTable.insert(t.key);
}
// Probe the hash table for each element of s
for (auto &t : s) {
matches += hashTable.count(t.key);
}
return matches;
}
// Helper function, needed to reuse it for multi-pass partitioning
// Shift can be used for the multi-pass partitioning
partition partition_naive(const relation &r, size_t start, size_t end, uint8_t bits, uint8_t shift = 0) {
SplitHelper split(bits); // Define the partitioning
// Step 1: Build histograms to derive the prefix sums
std::vector<uint64_t> histogram(split.fanOut, 0);
for (size_t i = start; i < end; i++) {
// If needed: shift the key. Apply the split mask to determine the partition
const size_t bucket = (r[i].key >> shift) & split.mask;
histogram[bucket]++;
}
// Step 2: Use prefix sum to partition data
uint64_t prefSum = 0;
std::vector<uint64_t> startPos(split.fanOut, 0); // Store partition starts
for (size_t i = 0; i < split.fanOut; i++) {
startPos[i] = prefSum; // Store the offset of this buckets array
prefSum += histogram[i]; // Update the offset of the next bucket
}
// Step 3 partition the data
relation parts(prefSum); // Relation to store the partitioned data
std::vector<uint64_t> offset(split.fanOut, 0); // Vector of partition offsets
for (size_t i = start; i < end; i++) {
auto bucket = (r[i].key >> shift) & split.mask; // Determine partition
auto pos = startPos[bucket] + offset[bucket]; // Determine position
parts[pos] = r[i]; // Write the tuple to the position
offset[bucket]++; // Update the offset of this partition
}
return {parts, startPos}; // Return the partitioned relation + start positions
}
partition partition_naive(const relation &r, uint8_t bits, uint8_t shift = 0) {
return partition_naive(r, 0, r.size(), bits, shift);
}
std::pair<partition, std::vector<uint64_t>> partition_softwareManaged(const relation &r, uint8_t bits) {
SplitHelper split(bits); // Define the partitioning
// Step 1: Build histograms to derive the prefix sums
std::vector<uint64_t> histogram(split.fanOut, 0);
for (auto &t : r) {
// Apply the split mask to determine the partition
const uint64_t bucket = t.key & split.mask;
histogram[bucket]++;
}
// Step 2: Use prefix sum to partition data
uint64_t prefSum = 0;
std::vector<uint64_t> startPos(split.fanOut, 0); // Store partition starts
for (uint64_t i = 0; i < split.fanOut; i++) {
startPos[i] = prefSum;
auto tmp = histogram[i]; // Store the offset of this buckets array
// Align the offsets for non-temporal writes
if (tmp % tuplesPerCL != 0)
tmp += tuplesPerCL - (tmp % tuplesPerCL);
prefSum += tmp; // Update the offset of the next bucket
}
/// From this point on the data is not dense anymore
// Step 3 partition
// Initialize a software managed buffer per partition + its current offset
std::vector<SoftwareManagedBuffer> buffers(split.fanOut);
std::vector<uint8_t> bufferOffset(split.fanOut, 0);
relation parts(prefSum); // Relation to store the partitioned data
std::vector<uint64_t> offset(split.fanOut, 0); // Vector of partition offsets
for (auto &t : r) {
auto bucket = t.key & split.mask; // Determine the bucket
auto &buff = buffers[bucket]; // Get the software-managed buffer
auto &pos = bufferOffset[bucket]; // Determine the position in the buffer
buff.tuples[pos] = t; // Write the tuple into the buffer
pos++;
// Buffer full?
if (pos == tuplesPerCL) {
auto writePos = &parts[startPos[bucket] +
offset[bucket]]; // Determine pos to write to
auto writePtr = reinterpret_cast<uint8_t *>(writePos);
storeNontemp(writePtr, &buff); // Non-temporal write to the position
offset[bucket] += tuplesPerCL; // Update write head
pos = 0; // Update software-managed buffer offset
}
}
// Handle not empty buffers
for (uint64_t i = 0; i < split.fanOut; i++) {
auto &buff = buffers[i];
auto &pos = bufferOffset[i];
for (size_t j = 0; j < pos; j++) {
auto writePos = startPos[i] + offset[i];
parts[writePos] = buff.tuples[j];
offset[i]++;
}
}
partition result = {parts, startPos};
return std::make_pair(result, offset);
}
partition partition_multiPass(const relation &r, uint8_t bits1, uint8_t bits2) {
// Partition 1. stage
partition p1 = partition_naive(r, bits1);
// Partition 2. stage
relation result; // Store the tuples of the result
std::vector<uint64_t> startPos; // Start positions of all sub-partitions
uint64_t offset = 0;
for (uint64_t i = 0; i < p1.start.size(); i++) {
auto start = p1.start[i];
auto end = (i == p1.start.size() - 1) ? p1.r.size() : p1.start[i + 1];
auto p2 = partition_naive(p1.r, start, end, bits2, bits1); // Partition
for (auto e : p2.r)
result.push_back(e); // Insert partition into result
for (auto e : p2.start)
startPos.push_back(offset + e); // Adapt startPos from local to global
offset += (end - start); // Update offset by the partition's #elements
}
return {result, startPos};
}
uint64_t radix_join(const relation &r, const relation &s, Partitioning type, uint8_t bits) {
uint64_t matches = 0;
// Step 1: partitioning phase
partition pr{};
partition ps{};
std::vector<uint64_t> offR{};
std::vector<uint64_t> offS{};
switch (type) {
case Partitioning::naive:
pr = partition_naive(r, bits);
ps = partition_naive(s, bits);
break;
case Partitioning::multiPass:
pr = partition_multiPass(r, bits, bits);
ps = partition_multiPass(s, bits, bits);
break;
case Partitioning::softwareManaged: {
auto tmpR = partition_softwareManaged(r, bits);
auto tmpS = partition_softwareManaged(s, bits);
pr = tmpR.first;
offR = tmpR.second;
ps = tmpS.first;
offS = tmpS.second;
} break;
}
// Step 2: partition-wise build & probe phase
for (size_t i = 0; i < pr.start.size(); i++) {
// Determine range of partitions
auto start_r = pr.start[i]; // For r
auto end_r = (i == pr.start.size() - 1) ? pr.r.size() : pr.start[i + 1]; // For r
auto start_s = ps.start[i]; // For S
auto end_s = (i == ps.start.size() - 1) ? ps.r.size() : ps.start[i + 1]; // For S
if (type == Partitioning::softwareManaged) { // Handle padding
end_r = std::min(end_r, static_cast<uint64_t>(start_r + offR[i]));
end_s = std::min(end_s, static_cast<uint64_t>(start_s + offS[i]));
}
std::unordered_set<keyType> hashTable;
hashTable.reserve(end_r - start_r);
// Step 1: build phase
for (auto j = start_r; j != end_r; j++) {
hashTable.insert(pr.r[j].key);
}
// Step 2: probe phase
for (auto j = start_s; j != end_s; j++) {
matches += hashTable.count(ps.r[j].key);
}
}
return matches;
}
partition parallel_partition(const relation &r, uint8_t bits1, uint8_t num_threads) {
/// Partition 1. stage
uint8_t shift = 0;
SplitHelper split(bits1); // Define the partitioning
relation parts(r.size()); // Relation to store the partitioned data
std::vector<uint64_t> offset_stage1(split.fanOut, 0); // Vector of partition offsets
// IMPORTANT: it is just my assumption, that each task has same number of entries
// the number of thread has to be the power of 2
// the relation size has to be the power of 2
// I just make this assumption to avoid the last task having differently sized chunk
assert(r.size() % num_threads == 0);
std::mutex global_histogram_lock;
std::vector<uint64_t> global_histogram(split.fanOut, 0);
std::vector<std::vector<uint64_t>> local_histograms(num_threads, std::vector<uint64_t>(split.fanOut, 0));
{
Barrier barrier(num_threads);
ThreadPool<void(void)> threadpool_stage1(num_threads);
for (size_t task_id = 0; task_id < num_threads; task_id++) {
std::function<void(void)> f = [&local_histograms, task_id, &r, num_threads, shift, &split, &global_histogram, &global_histogram_lock, &barrier, &parts]() {
// Step 1: Build histograms to derive the prefix sums
std::vector<uint64_t> &local_histogram = local_histograms[task_id];
const size_t local_start_offset = task_id * (r.size() / num_threads);
for (size_t i = 0; i < r.size() / num_threads; i++) {
// If needed: shift the key. Apply the split mask to determine the partition
const size_t bucket = (r[local_start_offset + i].key >> shift) & split.mask;
local_histogram[bucket]++;
}
/// Update to the global histogram
for (size_t i = 0; i < split.fanOut; i++) {
std::scoped_lock<std::mutex> sc{global_histogram_lock};
global_histogram[i] += local_histogram[i];
}
/// Barrier
barrier.Wait();
// Step 2: Use prefix sum to partition data
std::vector<uint64_t> local_startPos(split.fanOut, 0); // Store partition starts
for (size_t i = 0; i < split.fanOut; i++) {
uint64_t prefSum = 0;
// Less than i
for (size_t prev_histogram = 0; prev_histogram < i; prev_histogram++) {
prefSum += global_histogram[prev_histogram];
}
// Same i, but tasks chronologically before this task
for (size_t prev_task = 0; prev_task < task_id; prev_task++) {
prefSum += local_histograms[prev_task][i];
}
local_startPos[i] = prefSum; // Store the offset of this buckets array
}
/// NO Barrier :D
// Step 3 partition the data
std::vector<uint64_t> local_offset(split.fanOut, 0); // Vector of partition offsets
for (size_t i = 0; i < r.size() / num_threads; i++) {
const size_t bucket = (r[local_start_offset + i].key >> shift) & split.mask; // Determine partition
const size_t pos = local_startPos[bucket] + local_offset[bucket]; // Determine position
parts[pos] = r[local_start_offset + i]; // Write the tuple to the position
local_offset[bucket]++; // Update the offset of this partition
}
};
threadpool_stage1.addTask(std::move(f));
}
}
/// To get global_startPos is just little work and non-relevant with the threading above, so I decide just to scalar code it.
size_t tmp = 0;
std::vector<uint64_t> global_startPos(split.fanOut, 0); // Store partition starts
for (size_t i = 0; i < split.fanOut; i++) {
global_startPos[i] = tmp; // Store the offset of this buckets array
tmp += global_histogram[i]; // Update the offset of the next bucket
}
/// I decide to only have SINGLE pass partition. Reason see in my document.
return {parts, global_startPos};
// partition p1 = {parts, global_startPos};
// /// Partition 2. stage
// std::vector<partition> partitions_stage2;
// partitions_stage2.resize(p1.start.size());
// {
// ThreadPool<void(void)> threadpool_stage2(num_threads);
// for (uint64_t i = 0; i < p1.start.size(); i++) {
// auto start = p1.start[i];
// auto end = (i == p1.start.size() - 1) ? p1.r.size() : p1.start[i + 1];
// std::function<void(void)> f = [&partitions_stage2, &p1, start, end, bits2, bits1, i] {
// partitions_stage2[i] = partition_naive(p1.r, start, end, bits2, bits1); // Partition
// };
// threadpool_stage2.addTask(std::move(f));
// }
// }
// relation result; // Store the tuples of the result
// std::vector<uint64_t> startPos; // Start positions of all sub-partitions
// uint64_t offset = 0;
// for (uint64_t i = 0; i < p1.start.size(); i++) {
// auto start = p1.start[i];
// auto end = (i == p1.start.size() - 1) ? p1.r.size() : p1.start[i + 1];
// const auto& p2 = partitions_stage2[i];
// for (auto e : p2.r) {
// result.push_back(e); // Insert partition into result
// }
// for (auto e : p2.start) {
// startPos.push_back(offset + e); // Adapt startPos from local to global
// }
// offset += (end - start); // Update offset by the partition's #elements
// }
// return {result, startPos};
}
// Feel free to adapt the function signature if needed
uint64_t parallel_radix_join(const relation &r, const relation &s, uint8_t bits, uint8_t num_threads) {
/// Implement the parallel radix join with multi-pass partitioning
/// using task-level parallelism (TLP) [Part 1]
/// Use the provided serial implementation of the multi-pass partitioning and adapt it.
/// Step 1: partitioning phase with multi-pass partitioning
partition pr{};
partition ps{};
pr = parallel_partition(r, bits, num_threads);
ps = parallel_partition(s, bits, num_threads);
/// Step 2: partition-wise build & probe phase
std::atomic<uint64_t> matches = 0;
{
ThreadPool<void(void)> threadpool_step2(num_threads);
assert(static_cast<size_t>(1 << bits) == pr.start.size());
for (size_t i = 0; i < static_cast<size_t>(1 << bits) /* fan out */; i++) {
std::function<void(void)> f = [i, &pr, &ps, &matches]() {
// Determine range of partitions
auto start_r = pr.start[i]; // For r
auto end_r = (i == pr.start.size() - 1) ? pr.r.size() : pr.start[i + 1]; // For r
auto start_s = ps.start[i]; // For S
auto end_s = (i == ps.start.size() - 1) ? ps.r.size() : ps.start[i + 1]; // For S
std::unordered_set<keyType> hashTable;
hashTable.reserve(end_r - start_r);
// Step 1: build phase
for (auto j = start_r; j != end_r; j++) {
hashTable.insert(pr.r[j].key);
}
// Step 2: probe phase
uint64_t local_mathces = 0;
for (auto j = start_s; j != end_s; j++) {
local_mathces += hashTable.count(ps.r[j].key);
}
matches += local_mathces;
};
threadpool_step2.addTask(std::move(f));
}
}
return matches;
}
//// TODO: return multiple partition
partition* numa_partition(const relation &r, uint8_t bits1, uint8_t num_threads) {
/// Partition 1. stage
uint8_t shift = 0;
SplitHelper split(bits1); // Define the partitioning
// https://stackoverflow.com/questions/49105427/c-numa-optimization
/// I delete you later, after the join is done. :D
partition* parts_ptrs = new partition[num_threads];
std::vector<uint64_t> offset_stage1(split.fanOut, 0); // Vector of partition offsets
// IMPORTANT: it is just my assumption, that each task has same number of entries
// the number of thread has to be the power of 2
// the relation size has to be the power of 2
// I just make this assumption to avoid the last task having differently sized chunk
assert(r.size() % num_threads == 0);
{
ThreadPool<void(void)> threadpool_stage1(num_threads);
for (size_t task_id = 0; task_id < num_threads; task_id++) {
std::function<void(void)> f = [task_id, &r, num_threads, shift, &split, &parts_ptrs]() {
/// Step 0: configure on a NUMA node
/// runs the current task and its children on a specific node.
/// E5-2660 v2 hash 2 Sockets (2 NUMA node)
/// Thread [0, 19] on Node 0 | Thread [20, 39] on Node 1 | Thread [40, 59] on Node 0 | Thread [60, 59] on Node 1 | ......
// TODO(jigao): I am not sure. Hope this works!
const int node_id = (num_threads / 20) & 1;
if (numa_run_on_node(node_id) != 0) {
printf("could not assign current thread to node %d!\n", 1);
}
numa_set_preferred(node_id);
// Step 1: Build histograms to derive the prefix sums
std::vector<uint64_t> local_histogram(split.fanOut, 0);
const size_t local_start_offset = task_id * (r.size() / num_threads);
for (size_t i = 0; i < r.size() / num_threads; i++) {
// If needed: shift the key. Apply the split mask to determine the partition
const size_t bucket = (r[local_start_offset + i].key >> shift) & split.mask;
local_histogram[bucket]++;
}
/// Step 2: no communication with global and other threads.
// Step 2: Use prefix sum to partition data
std::vector<uint64_t> local_startPos(split.fanOut, 0); // Store partition starts
uint64_t prefSum = 0;
for (size_t i = 0; i < split.fanOut; i++) {
local_startPos[i] = prefSum; // Store the offset of this buckets array
prefSum += local_histogram[i]; // Update the offset of the next bucket
}
// Step 3 partition the data
relation local_parts(prefSum); // Relation to store the partitioned data
std::vector<uint64_t> local_offset(split.fanOut, 0); // Vector of partition offsets
for (size_t i = 0; i < r.size() / num_threads; i++) {
const size_t bucket = (r[local_start_offset + i].key >> shift) & split.mask; // Determine partition
const size_t pos = local_startPos[bucket] + local_offset[bucket]; // Determine position
local_parts[pos] = r[local_start_offset + i]; // Write the tuple to the position
local_offset[bucket]++; // Update the offset of this partition
}
/// Step4: this workload done.
/// initialization with respect to first touch policy
parts_ptrs[task_id] = partition{local_parts, local_startPos};
};
threadpool_stage1.addTask(std::move(f));
}
}
return parts_ptrs;
}
uint64_t numa_radix_join(relation &r, relation &s, uint8_t bits, uint8_t num_threads) {
/// Implement a NUMA-aware version of your parallel radix join [Part 2]
if(numa_available() < 0){
printf("System does not support NUMA API!\n");
}
/// runs the current task and its children on a specific node.
if (numa_run_on_node(0) != 0) {
printf("could not assign current thread to node %d!\n", 1);
}
numa_set_preferred(0);
// equivalent as following
// nodemask_t mask;
// nodemask_zero(&mask);
// numa_bitmask_setbit(&mask, );
// numa_bind(&mask);
/// Step 1: partitioning phase with multi-pass partitioning
partition* pr = numa_partition(r, bits, num_threads);
partition* ps = numa_partition(s, bits, num_threads);
/// Step 2: partition-wise build & probe phase
std::atomic<uint64_t> matches = 0;
{
ThreadPool<void(void)> threadpool_step2(num_threads);
assert(static_cast<size_t>(1 << bits) == pr[0].start.size());
for (size_t i = 0; i < static_cast<size_t>(1 << bits); i++) {
std::function<void(void)> f = [num_threads, i, &pr, &ps, &matches]() {
/// Step 0: configure on a NUMA node
/// runs the current task and its children on a specific node.
/// E5-2660 v2 hash 2 Sockets (2 NUMA node)
/// Thread [0, 19] on Node 0 | Thread [20, 39] on Node 1 | Thread [40, 59] on Node 0 | Thread [60, 59] on Node 1 | ......
// TODO(jigao): I am not sure. Hope this works!
const int node_id = (num_threads / 20) & 1;
if (numa_run_on_node(node_id) != 0) {
printf("could not assign current thread to node %d!\n", 1);
}
numa_set_preferred(node_id);
std::unordered_set<keyType> hashTable;
size_t reserve_size = 0;
for (size_t part_id = 0; part_id < num_threads; part_id++) {
auto start_r = pr[part_id].start[i]; // For r
auto end_r = (i == pr[part_id].start.size() - 1) ? pr[part_id].r.size() : pr[part_id].start[i + 1]; // For r
reserve_size += (end_r - start_r);
}
hashTable.reserve(reserve_size);
for (size_t part_id = 0; part_id < num_threads; part_id++) {
// Determine range of partitions
auto start_r = pr[part_id].start[i]; // For r
auto end_r = (i == pr[part_id].start.size() - 1) ? pr[part_id].r.size() : pr[part_id].start[i + 1]; // For r
// Step 1: build phase
/// Take i (aka the partition bit pattern) from all local partition from all threads
for (auto j = start_r; j != end_r; j++) {
hashTable.insert(pr[part_id].r[j].key);
}
}
for (size_t part_id = 0; part_id < num_threads; part_id++) {
// Determine range of partitions
auto start_s = ps[part_id].start[i]; // For S
auto end_s = (i == ps[part_id].start.size() - 1) ? ps[part_id].r.size() : ps[part_id].start[i + 1]; // For S
// Step 2: probe phase
uint64_t local_matches = 0;
/// Take i (aka the partition bit pattern) from all local partition from all threads
for (auto j = start_s; j != end_s; j++) {
local_matches += hashTable.count(ps[part_id].r[j].key);
}
matches += local_matches;
}
};
threadpool_step2.addTask(std::move(f));
}
}
delete[](pr);
delete[](ps);
return matches;
} | 39.306859 | 161 | 0.619443 | [
"vector"
] |
917cc075994380cc407083a61b783b4db67ab190 | 5,075 | cpp | C++ | src/world.cpp | LangdalP/BasicPhysicsDemo | f814b1cbcaa03ee4b0772c2c40de8a41c795fca2 | [
"MIT"
] | null | null | null | src/world.cpp | LangdalP/BasicPhysicsDemo | f814b1cbcaa03ee4b0772c2c40de8a41c795fca2 | [
"MIT"
] | null | null | null | src/world.cpp | LangdalP/BasicPhysicsDemo | f814b1cbcaa03ee4b0772c2c40de8a41c795fca2 | [
"MIT"
] | null | null | null |
#include "world.h"
#include <iostream>
#include <fstream>
#include <vector>
#include "json.hpp"
using json = nlohmann::json;
// Input: The json for a single rigidBody
b2ObjectDef load_body_from_json(json j)
{
b2BodyDef bDef;
bDef.type = b2_staticBody;
std::vector<b2PolygonShape> shapes;
shapes.reserve(30);
std::vector<b2FixtureDef> fixDefs;
std::vector<b2Vec2> shapeVertices;
shapeVertices.reserve(4);
int shapeIdx = 0;
for (const auto &element : j["polygons"]) {
b2PolygonShape shape;
for (const auto &vertex : element) {
float x = vertex["x"].get<float>() * 2.0;
float y = vertex["y"].get<float>() * 2.0;
shapeVertices.push_back(b2Vec2(x, y));
std::cout << "V: ( " << x << " , " << y << " )" << std::endl;
}
std::cout << "Done adding vertices. Added num vertices: " << shapeVertices.size() << std::endl;
shape.Set(shapeVertices.data(), shapeVertices.size());
shapes.push_back(shape);
b2FixtureDef fixDef;
//fixDef.shape = shapes.data() + shapeIdx;
fixDef.shape = &shapes[shapes.size()-1];
fixDef.density = 1;
fixDef.restitution = 0.1;
fixDefs.push_back(fixDef);
shapeVertices.clear();
++shapeIdx;
}
b2ObjectDef def;
def.bDef = bDef;
def.pShapes = shapes;
def.fDefs = fixDefs;
def.objName = j["name"].get<std::string>();
return def;
};
std::vector<b2ObjectDef> load_bodies_from_file(std::string fname)
{
std::ifstream fStream(fname);
json j;
fStream >> j;
std::vector<b2ObjectDef> objects;
for (const auto &element : j["rigidBodies"]) {
objects.push_back(load_body_from_json(element));
std::cout << "Done with object loading" << std::endl;
}
return objects;
}
///////////// Object Store class /////////////////
ObjectStore::ObjectStore(std::vector<b2ObjectDef> objects)
{
for (const auto &obj : objects) {
m_objects[obj.objName] = obj;
}
}
ObjectStore::~ObjectStore()
{
}
b2ObjectDef ObjectStore::GetObject(std::string name) const
{
auto obj = m_objects.at(name);
for (int i = 0; i < (int)obj.fDefs.size(); ++i)
obj.fDefs[i].shape = &obj.pShapes[i];
return m_objects.at(name);
}
b2ObjectDef ObjectStore::GetObjectAsDynamic(std::string name) const
{
auto obj = m_objects.at(name);
obj.bDef.type = b2_dynamicBody;
for (int i = 0; i < (int)obj.fDefs.size(); ++i)
obj.fDefs[i].shape = &obj.pShapes[i];
return obj;
}
b2ObjectDef ObjectStore::GetObjectAtPos(std::string name, float x, float y) const
{
auto obj = m_objects.at(name);
obj.bDef.position.Set(x, y);
for (int i = 0; i < (int)obj.fDefs.size(); ++i)
obj.fDefs[i].shape = &obj.pShapes[i];
return obj;
}
b2ObjectDef ObjectStore::GetObjectAsDynamicAtPos(std::string name, float x, float y) const
{
auto obj = m_objects.at(name);
obj.bDef.type = b2_dynamicBody;
obj.bDef.position.Set(x, y);
for (int i = 0; i < (int)obj.fDefs.size(); ++i)
obj.fDefs[i].shape = &obj.pShapes[i];
return obj;
}
/////////////////// Done with class ///////////////
b2World* CreateEmptyWorld()
{
b2Vec2 grav_vec( 0, -9.81 );
b2World* world = new b2World( grav_vec );
return world;
}
b2World* CreateTestWorld()
{
b2Vec2 grav_vec( 0, -9.81 );
b2World* world = new b2World( grav_vec );
// Bodies and fixtures
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set( 0, 5);
ballBodyDef.angle = 0;
b2Body *ballBody = world->CreateBody( &ballBodyDef );
b2CircleShape circleShape;
circleShape.m_p.Set( 0, 0 );
circleShape.m_radius = 1;
b2FixtureDef ballFixtureDef;
ballFixtureDef.shape = &circleShape;
ballFixtureDef.density = 1;
ballFixtureDef.restitution = 1;
ballBody->CreateFixture( &ballFixtureDef );
// Edge shapes
b2BodyDef groundBodyDef;
groundBodyDef.type = b2_staticBody;
groundBodyDef.position.Set( 0.0, 0.1 );
b2Body *groundBody = world->CreateBody( &groundBodyDef );
b2EdgeShape groundShape;
groundShape.Set( b2Vec2( -15, 0.0 ), b2Vec2( 15, 0.0 ) );
b2FixtureDef groundFixtureDef;
groundFixtureDef.shape = &groundShape;
groundFixtureDef.density = 1;
groundBody->CreateFixture( &groundFixtureDef );
const auto objStore = CreateStoreFromFile("objs.json");
b2ObjectDef eggObj = objStore.GetObjectAsDynamicAtPos("Egg", -2, 3);
CreateBodyFromObject(eggObj, world);
b2ObjectDef bananaObj = objStore.GetObjectAtPos("Banana", 5, 5);
CreateBodyFromObject(bananaObj, world);
return world;
}
ObjectStore CreateStoreFromFile(std::string fname)
{
const std::vector<b2ObjectDef> bodies = load_bodies_from_file(fname);
return ObjectStore(bodies);
}
b2Body* CreateBodyFromObject(b2ObjectDef obj, b2World* world)
{
auto* body = world->CreateBody( &obj.bDef );
for (auto &fix : obj.fDefs ) {
body->CreateFixture( &fix );
}
return body;
}
| 27.139037 | 103 | 0.632709 | [
"object",
"shape",
"vector"
] |
9181338ee241444d8852835d1cbc75b75de5f47b | 201,795 | cpp | C++ | cvc3/src/theory_arith/theory_arith_old.cpp | kencheung/js-symbolic-executor | 18266513cc9bc885434890c8612aa26f0e2eab8b | [
"Apache-2.0"
] | 5 | 2015-10-11T08:32:50.000Z | 2019-02-01T22:59:18.000Z | cvc3/src/theory_arith/theory_arith_old.cpp | kencheung/js-symbolic-executor | 18266513cc9bc885434890c8612aa26f0e2eab8b | [
"Apache-2.0"
] | null | null | null | cvc3/src/theory_arith/theory_arith_old.cpp | kencheung/js-symbolic-executor | 18266513cc9bc885434890c8612aa26f0e2eab8b | [
"Apache-2.0"
] | null | null | null | /*****************************************************************************/
/*!
* \file theory_arith_old.cpp
*
* Author: Clark Barrett, Vijay Ganesh.
*
* Created: Fri Jan 17 18:39:18 2003
*
* <hr>
*
* License to use, copy, modify, sell and/or distribute this software
* and its documentation for any purpose is hereby granted without
* royalty, subject to the terms and conditions defined in the \ref
* LICENSE file provided with this distribution.
*
* <hr>
*
*/
/*****************************************************************************/
#include "theory_arith_old.h"
#include "arith_proof_rules.h"
//#include "arith_expr.h"
#include "arith_exception.h"
#include "typecheck_exception.h"
#include "eval_exception.h"
#include "parser_exception.h"
#include "smtlib_exception.h"
#include "theory_core.h"
#include "command_line_flags.h"
//TODO: remove this dependency
#include "../theory_core/core_proof_rules.h"
using namespace std;
using namespace CVC3;
///////////////////////////////////////////////////////////////////////////////
// TheoryArithOld::FreeConst Methods //
///////////////////////////////////////////////////////////////////////////////
namespace CVC3 {
ostream& operator<<(ostream& os, const TheoryArithOld::FreeConst& fc) {
os << "FreeConst(r=" << fc.getConst() << ", "
<< (fc.strict()? "strict" : "non-strict") << ")";
return os;
}
///////////////////////////////////////////////////////////////////////////////
// TheoryArithOld::Ineq Methods //
///////////////////////////////////////////////////////////////////////////////
ostream& operator<<(ostream& os, const TheoryArithOld::Ineq& ineq) {
os << "Ineq(" << ineq.ineq().getExpr() << ", isolated on "
<< (ineq.varOnRHS()? "RHS" : "LHS") << ", const = "
<< ineq.getConst() << ")";
return os;
}
} // End of namespace CVC3
///////////////////////////////////////////////////////////////////////////////
// TheoryArithOld Private Methods //
///////////////////////////////////////////////////////////////////////////////
Theorem TheoryArithOld::isIntegerThm(const Expr& e) {
// Quick checks
Type t = e.getType();
if (isReal(t)) return Theorem();
if (isInt(t)) return typePred(e);
// Try harder
return isIntegerDerive(Expr(IS_INTEGER, e), typePred(e));
}
Theorem TheoryArithOld::isIntegerDerive(const Expr& isIntE, const Theorem& thm) {
const Expr& e = thm.getExpr();
// We found it!
if(e == isIntE) return thm;
Theorem res;
// If the theorem is an AND, look inside each child
if(e.isAnd()) {
int i, iend=e.arity();
for(i=0; i<iend; ++i) {
res = isIntegerDerive(isIntE, getCommonRules()->andElim(thm, i));
if(!res.isNull()) return res;
}
}
return res;
}
const Rational& TheoryArithOld::freeConstIneq(const Expr& ineq, bool varOnRHS) {
DebugAssert(isIneq(ineq), "TheoryArithOld::freeConstIneq("+ineq.toString()+")");
const Expr& e = varOnRHS? ineq[0] : ineq[1];
switch(e.getKind()) {
case PLUS:
return e[0].getRational();
case RATIONAL_EXPR:
return e.getRational();
default: { // MULT, DIV, or Variable
static Rational zero(0);
return zero;
}
}
}
const TheoryArithOld::FreeConst&
TheoryArithOld::updateSubsumptionDB(const Expr& ineq, bool varOnRHS,
bool& subsumed) {
TRACE("arith ineq", "TheoryArithOld::updateSubsumptionDB(", ineq,
", var isolated on "+string(varOnRHS? "RHS" : "LHS")+")");
DebugAssert(isLT(ineq) || isLE(ineq), "TheoryArithOld::updateSubsumptionDB("
+ineq.toString()+")");
// Indexing expression: same as ineq only without the free const
Expr index;
const Expr& t = varOnRHS? ineq[0] : ineq[1];
bool strict(isLT(ineq));
Rational c(0);
if(isPlus(t)) {
DebugAssert(t.arity() >= 2, "TheoryArithOld::updateSubsumptionDB("
+ineq.toString()+")");
c = t[0].getRational(); // Extract the free const in ineq
Expr newT;
if(t.arity() == 2) {
newT = t[1];
} else {
vector<Expr> kids;
Expr::iterator i=t.begin(), iend=t.end();
kids.push_back(rat(0));
for(++i; i!=iend; ++i) kids.push_back(*i);
DebugAssert(kids.size() > 0, "kids.size = "+int2string(kids.size())
+", ineq = "+ineq.toString());
newT = plusExpr(kids);
}
if(varOnRHS)
index = leExpr(rat(0), canonSimplify(ineq[1] - newT).getRHS());
else
index = leExpr(canonSimplify(ineq[0]-newT).getRHS(), rat(0));
} else if(isRational(t)) {
c = t.getRational();
if(varOnRHS)
index = leExpr(rat(0), ineq[1]);
else
index = leExpr(ineq[0], rat(0));
} else if(isLT(ineq))
index = leExpr(ineq[0], ineq[1]);
else
index = ineq;
// Now update the database, check for subsumption, and extract the constant
CDMap<Expr, FreeConst>::iterator i=d_freeConstDB.find(index),
iend=d_freeConstDB.end();
if(i == iend) {
subsumed = false;
// Create a new entry
CDOmap<Expr,FreeConst>& obj = d_freeConstDB[index];
obj = FreeConst(c,strict);
TRACE("arith ineq", "freeConstDB["+index.toString()+"] := ", obj, "");
return obj.get();
} else {
CDOmap<Expr,FreeConst>& obj = d_freeConstDB[index];
const FreeConst& fc = obj.get();
if(varOnRHS) {
subsumed = (c < fc.getConst() ||
(c == fc.getConst() && (!strict || fc.strict())));
} else {
subsumed = (c > fc.getConst() ||
(c == fc.getConst() && (strict || !fc.strict())));
}
if(!subsumed) {
obj = FreeConst(c,strict);
TRACE("arith ineq", "freeConstDB["+index.toString()+"] := ", obj, "");
}
return obj.get();
}
}
bool TheoryArithOld::kidsCanonical(const Expr& e) {
if(isLeaf(e)) return true;
bool res(true);
for(int i=0; res && i<e.arity(); ++i) {
Expr simp(canon(e[i]).getRHS());
res = (e[i] == simp);
IF_DEBUG(if(!res) debugger.getOS() << "\ne[" << i << "] = " << e[i]
<< "\nsimplified = " << simp << endl;)
}
return res;
}
///////////////////////////////////////////////////////////////////////////////
// //
// Function: TheoryArithOld::canon //
// Author: Clark Barrett, Vijay Ganesh. //
// Created: Sat Feb 8 14:46:32 2003 //
// Description: Compute a canonical form for expression e and return a //
// theorem that e is equal to its canonical form. //
// Note that canonical form for arith expressions is one of the following: //
// 1. rational constant //
// 2. arithmetic leaf //
// (i.e. variable or term from some other theory) //
// 3. (MULT rat leaf) //
// where rat is a non-zero rational constant, leaf is an arithmetic leaf //
// 4. (PLUS const term_0 term_1 ... term_n) //
// where each term_i is either a leaf or (MULT rat leaf) //
// and each leaf in term_i must be strictly greater than the leaf in //
// term_{i+1}. //
// //
///////////////////////////////////////////////////////////////////////////////
Theorem TheoryArithOld::canon(const Expr& e)
{
TRACE("arith canon","canon(",e,") {");
DebugAssert(kidsCanonical(e), "TheoryArithOld::canon("+e.toString()+")");
Theorem result;
switch (e.getKind()) {
case UMINUS: {
Theorem thm = d_rules->uMinusToMult(e[0]);
Expr e2 = thm.getRHS();
result = transitivityRule(thm, canon(e2));
}
break;
case PLUS: /* {
Theorem plusThm, plusThm1;
plusThm = d_rules->canonFlattenSum(e);
plusThm1 = d_rules->canonComboLikeTerms(plusThm.getRHS());
result = transitivityRule(plusThm,plusThm1);
}
*/
result = d_rules->canonPlus(e);
break;
case MINUS: {
DebugAssert(e.arity() == 2,"");
Theorem minus_eq_sum = d_rules->minusToPlus(e[0], e[1]);
// this produces e0 + (-1)*e1; we have to canonize it in 2 steps
Expr sum(minus_eq_sum.getRHS());
Theorem thm(canon(sum[1]));
if(thm.getLHS() == thm.getRHS())
result = canonThm(minus_eq_sum);
// The sum changed; do the work
else {
vector<unsigned> changed;
vector<Theorem> thms;
changed.push_back(1);
thms.push_back(thm);
Theorem sum_eq_canon = canonThm(substitutivityRule(sum, changed, thms));
result = transitivityRule(minus_eq_sum, sum_eq_canon);
}
break;
}
case MULT:
result = d_rules->canonMult(e);
break;
/*
case MULT: {
Theorem thmMult, thmMult1;
Expr exprMult;
Expr e0 = e[0];
Expr e1 = e[1];
if(e0.isRational()) {
if(rat(0) == e0)
result = d_rules->canonMultZero(e1);
else if (rat(1) == e0)
result = d_rules->canonMultOne(e1);
else
switch(e1.getKind()) {
case RATIONAL_EXPR :
result = d_rules->canonMultConstConst(e0,e1);
break;
case MULT:
DebugAssert(e1[0].isRational(),
"theory_arith::canon:\n "
"canon:MULT:MULT child is not canonical: "
+ e1[0].toString());
thmMult = d_rules->canonMultConstTerm(e0,e1[0],e1[1]);
result = transitivityRule(thmMult,canon(thmMult.getRHS()));
break;
case PLUS:{
Theorem thmPlus, thmPlus1;
Expr ePlus;
std::vector<Theorem> thmPlusVector;
thmPlus = d_rules->canonMultConstSum(e0,e1);
ePlus = thmPlus.getRHS();
Expr::iterator i = ePlus.begin();
for(;i != ePlus.end();++i)
thmPlusVector.push_back(canon(*i));
thmPlus1 = substitutivityRule(PLUS, thmPlusVector);
result = transitivityRule(thmPlus, thmPlus1);
break;
}
default:
result = reflexivityRule(e);
break;
}
}
else {
if(e1.isRational()){
// canonMultTermConst just reverses the order of the const and the
// term. Then canon is called again.
Theorem t1 = d_rules->canonMultTermConst(e1,e0);
result = transitivityRule(t1,canon(t1.getRHS()));
}
else
// This is where the assertion for non-linear multiplication is
// produced.
result = d_rules->canonMultTerm1Term2(e0,e1);
}
break;
}
*/
case DIVIDE:{
/*
case DIVIDE:{
if (e[1].isRational()) {
if (e[1].getRational() == 0)
throw ArithException("Divide by 0 error in "+e.toString());
Theorem thm = d_rules->canonDivideVar(e[0], e[1]);
Expr e2 = thm.getRHS();
result = transitivityRule(thm, canon(e2));
}
else
{
// TODO: to be handled
throw ArithException("Divide by a non-const not handled in "+e.toString());
}
break;
}
*/
// Division by 0 is OK (total extension, protected by TCCs)
// if (e[1].isRational() && e[1].getRational() == 0)
// throw ArithException("Divide by 0 error in "+e.toString());
if (e[1].getKind() == PLUS)
throw ArithException("Divide by a PLUS expression not handled in"+e.toString());
result = d_rules->canonDivide(e);
break;
}
case POW:
if(e[1].isRational())
result = d_rules->canonPowConst(e);
else {
// x ^ 1 --> x
if (e[0].isRational() && e[0].getRational() == 1) {
result = d_rules->powerOfOne(e);
} else
result = reflexivityRule(e);
}
break;
default:
result = reflexivityRule(e);
break;
}
TRACE("arith canon","canon => ",result," }");
return result;
}
Theorem
TheoryArithOld::canonSimplify(const Expr& e) {
TRACE("arith simplify", "canonSimplify(", e, ") {");
DebugAssert(kidsCanonical(e),
"TheoryArithOld::canonSimplify("+e.toString()+")");
DebugAssert(leavesAreSimp(e), "Expected leaves to be simplified");
Expr tmp(e);
Theorem thm = canon(e);
if(thm.getRHS().hasFind())
thm = transitivityRule(thm, find(thm.getRHS()));
// We shouldn't rely on simplification in this function anymore
DebugAssert(thm.getRHS() == simplifyExpr(thm.getRHS()),
"canonSimplify("+e.toString()+")\n"
+"canon(e) = "+thm.getRHS().toString()
+"\nsimplify(canon(e)) = "+simplifyExpr(thm.getRHS()).toString());
// if(tmp != thm.getRHS())
// thm = transitivityRule(thm, simplifyThm(thm.getRHS()));
// while(tmp != thm.getRHS()) {
// tmp = thm.getRHS();
// thm = canon(thm);
// if(tmp != thm.getRHS())
// thm = transitivityRule(thm, simplifyThm(thm.getRHS()));
// }
TRACE("arith", "canonSimplify =>", thm, " }");
return thm;
}
/*! accepts a theorem, canonizes it, applies iffMP and substituvity to
* derive the canonized thm
*/
Theorem
TheoryArithOld::canonPred(const Theorem& thm) {
vector<Theorem> thms;
DebugAssert(thm.getExpr().arity() == 2,
"TheoryArithOld::canonPred: bad theorem: "+thm.toString());
Expr e(thm.getExpr());
thms.push_back(canonSimplify(e[0]));
thms.push_back(canonSimplify(e[1]));
Theorem result = iffMP(thm, substitutivityRule(e.getOp(), thms));
return result;
}
/*! accepts an equivalence theorem, canonizes it, applies iffMP and
* substituvity to derive the canonized thm
*/
Theorem
TheoryArithOld::canonPredEquiv(const Theorem& thm) {
vector<Theorem> thms;
DebugAssert(thm.getRHS().arity() == 2,
"TheoryArithOld::canonPredEquiv: bad theorem: "+thm.toString());
Expr e(thm.getRHS());
thms.push_back(canonSimplify(e[0]));
thms.push_back(canonSimplify(e[1]));
Theorem result = transitivityRule(thm, substitutivityRule(e.getOp(), thms));
return result;
}
/*! accepts an equivalence theorem whose RHS is a conjunction,
* canonizes it, applies iffMP and substituvity to derive the
* canonized thm
*/
Theorem
TheoryArithOld::canonConjunctionEquiv(const Theorem& thm) {
vector<Theorem> thms;
return thm;
}
/*! Pseudo-code for doSolve. (Input is an equation) (output is a Theorem)
* -# translate e to the form e' = 0
* -# if (e'.isRational()) then {if e' != 0 return false else true}
* -# a for loop checks if all the variables are integers.
* - if not isolate a suitable real variable and call processRealEq().
* - if all variables are integers then isolate suitable variable
* and call processIntEq().
*/
Theorem TheoryArithOld::doSolve(const Theorem& thm)
{
const Expr& e = thm.getExpr();
if (e.isTrue() || e.isFalse()) return thm;
TRACE("arith eq","doSolve(",e,") {");
DebugAssert(thm.isRewrite(), "thm = "+thm.toString());
Theorem eqnThm;
vector<Theorem> thms;
// Move LHS to the RHS, if necessary
if(e[0].isRational() && e[0].getRational() == 0)
eqnThm = thm;
else {
eqnThm = iffMP(thm, d_rules->rightMinusLeft(e));
eqnThm = canonPred(eqnThm);
}
// eqnThm is of the form 0 = e'
// 'right' is of the form e'
Expr right = eqnThm.getRHS();
// Check for trivial equation
if (right.isRational()) {
Theorem result = iffMP(eqnThm, d_rules->constPredicate(eqnThm.getExpr()));
TRACE("arith eq","doSolve => ",result," }");
return result;
}
//normalize
eqnThm = iffMP(eqnThm, normalize(eqnThm.getExpr()));
TRACE("arith eq","doSolve => ",eqnThm.getExpr()," }");
right = eqnThm.getRHS();
//eqn is of the form 0 = e' and is normalized where 'right' denotes e'
//FIXME: change processRealEq to accept equations as well instead of theorems
try {
if (isMult(right)) {
DebugAssert(right.arity() > 1, "Expected arity > 1");
if (right[0].isRational()) {
Rational r = right[0].getRational();
if (r == 0) return getCommonRules()->trueTheorem();
else if (r == 1) {
enqueueFact(iffMP(eqnThm, d_rules->multEqZero(eqnThm.getExpr())));
return getCommonRules()->trueTheorem();
}
Theorem res = iffMP(eqnThm,
d_rules->multEqn(eqnThm.getLHS(),
right, rat(1/r)));
res = canonPred(res);
return doSolve(res);
}
else {
enqueueFact(iffMP(eqnThm, d_rules->multEqZero(eqnThm.getExpr())));
return getCommonRules()->trueTheorem();
}
}
else if (isPow(right)) {
DebugAssert(right.arity() == 2, "Expected arity 2");
if (right[0].isRational()) {
return doSolve(iffMP(eqnThm, d_rules->powEqZero(eqnThm.getExpr())));
}
throw ArithException("Can't solve exponential eqn: "+eqnThm.toString());
}
else {
if(!isInteger(right)) {
return processRealEq(eqnThm);
}
else {
return processIntEq(eqnThm);
}
}
} catch(ArithException& e) {
FatalAssert(false, "We should never get here!!! : " + e.toString());
// // Nonlinear bail out
// Theorem res;
// if (isPlus(right)) {
// // Solve for something
// // Try to simulate groebner basis by picking the highest term
// Expr isolated = right[1];
// int isolated_degree = termDegree(isolated);
// for (int i = 2; i < right.arity(); i ++) {
// int degree = termDegree(right[i]);
// if (degree > isolated_degree) {
// isolated = right[i];
// isolated_degree = degree;
// }
// }
// Rational coeff;
// if (isMult(isolated) && isolated[0].isRational()) {
// coeff = isolated[0].getRational();
// DebugAssert(coeff != 0, "Expected nonzero coeff");
// isolated = canon(isolated / rat(coeff)).getRHS();
// } else coeff = 1;
// res = iffMP(eqnThm, d_rules->multEqn(rat(0), right, rat(-1/coeff)));
// res = canonPred(res);
// res = iffMP(res, d_rules->plusPredicate(res.getLHS(), res.getRHS(), isolated, EQ));
// res = canonPred(res);
// TRACE("arith nonlinear", "solved for: ", res.getExpr(), "");
// } else
// res = symmetryRule(eqnThm); // Flip to e' = 0
// TRACE("arith eq", "doSolve: failed to solve an equation: ", e, "");
// IF_DEBUG(debugger.counter("FAILED to solve equalities")++;)
// setIncomplete("Non-linear arithmetic equalities");
//
// // Since we are forgetting about this equation, setup for updates
// TRACE("arith nonlinear", "adding setup to ", eqnThm.getExpr(), "");
// setupRec(eqnThm.getExpr());
// return getCommonRules()->trueTheorem();
}
FatalAssert(false, "");
return Theorem();
}
/*! pick a monomial for the input equation. This function is used only
* if the equation is an integer equation. Choose the monomial with
* the smallest absolute value of coefficient.
*/
bool TheoryArithOld::pickIntEqMonomial(const Expr& right, Expr& isolated, bool& nonlin)
{
DebugAssert(isPlus(right) && right.arity() > 1,
"TheoryArithOld::pickIntEqMonomial right is wrong :-): " +
right.toString());
DebugAssert(right[0].isRational(),
"TheoryArithOld::pickIntEqMonomial. right[0] must be const" +
right.toString());
// DebugAssert(isInteger(right),
// "TheoryArithOld::pickIntEqMonomial: right is of type int: " +
// right.toString());
//right is of the form "C + a1x1 + ... + anxn". min is initialized
//to a1
Expr::iterator istart = right.begin(), iend = right.end();
istart++;
Expr::iterator i = istart, j;
bool found = false;
nonlin = false;
Rational min, coeff;
Expr leaf;
for(; i != iend; ++i) {
if (isLeaf(*i)) {
leaf = *i;
coeff = 1;
}
else if (isMult(*i) && (*i).arity() == 2 && (*i)[0].isRational() && isLeaf((*i)[1])) {
leaf = (*i)[1];
coeff = abs((*i)[0].getRational());
}
else {
nonlin = true;
continue;
}
for (j = istart; j != iend; ++j) {
if (j != i && isLeafIn(leaf, *j)) break;
}
if (j == iend) {
if (!found || min > coeff) {
min = coeff;
isolated = *i;
found = true;
}
}
}
return found;
}
/*! input is 0=e' Theorem and some of the vars in e' are of
* type REAL. isolate one of them and send back to framework. output
* is "var = e''" Theorem.
*/
Theorem
TheoryArithOld::processRealEq(const Theorem& eqn)
{
DebugAssert(eqn.getLHS().isRational() &&
eqn.getLHS().getRational() == 0,
"processRealEq invariant violated");
Expr right = eqn.getRHS();
// Find variable to isolate and store it in left. Pick the largest
// (according to the total ordering) variable. FIXME: change from
// total ordering to the ordering we devised for inequalities.
// TODO: I have to pick a variable that appears as a variable in the
// term but does not appear as a variable anywhere else. The variable
// must appear as a single leaf and not in a MULT expression with some
// other variables and nor in a POW expression.
bool found = false;
Expr left;
if (isPlus(right)) {
DebugAssert(right[0].isRational(), "Expected first term to be rational");
for(int i = 1, iend = right.arity(); i < iend; ++i) {
Expr c = right[i];
DebugAssert(!isRational(c), "Expected non-rational");
if(!isInteger(c)) {
if (isLeaf(c) ||
((isMult(c) && c.arity() == 2 && isLeaf(c[1])))) {
Expr leaf = isLeaf(c) ? c : c[1];
int j;
for (j = 1; j < iend; ++j) {
if (j!= i
&& isLeafIn(leaf, right[j])
) {
break;
}
}
if (j == iend) {
left = c;
found = true;
break;
}
}
}
}
}
else if ((isMult(right) && right.arity() == 2 && isLeaf(right[1])) ||
isLeaf(right)) {
left = right;
found = true;
}
if (!found) {
// The only way we can not get an isolated in the reals is if all of them
// are non-linear. In this case we might have some integers to solve for
// so we try that. The integer solver shouldn't be able to solve for the
// reals, as they are not solvable and we should be safe. One of such
// examples is if some constant ITE got skolemized and we have an equation
// like SKOLEM = x^2 (bug79), in which case we should solve for the SKOLEM
// where skolem is an INT variable.
if (isNonlinearEq(eqn.getExpr()))
return processIntEq(eqn);
else throw
ArithException("Can't find a leaf for solve in "+eqn.toString());
}
Rational r = -1;
if (isMult(left)) {
DebugAssert(left.arity() == 2, "only leaf should be chosen as lhs");
DebugAssert(left[0].getRational() != 0, "left = "+left.toString());
r = -1/left[0].getRational();
left = left[1];
}
DebugAssert(isReal(getBaseType(left)) && !isInteger(left),
"TheoryArithOld::ProcessRealEq: left is integer:\n left = "
+left.toString());
// Normalize equation so that coefficient of the monomial
// corresponding to "left" in eqn[1] is -1
Theorem result(iffMP(eqn,
d_rules->multEqn(eqn.getLHS(), eqn.getRHS(), rat(r))));
result = canonPred(result);
// Isolate left
result = iffMP(result, d_rules->plusPredicate(result.getLHS(),
result.getRHS(), left, EQ));
result = canonPred(result);
TRACE("arith","processRealEq => ",result," }");
return result;
}
void TheoryArithOld::getFactors(const Expr& e, set<Expr>& factors)
{
switch (e.getKind()) {
case RATIONAL_EXPR: break;
case MULT: {
Expr::iterator i = e.begin(), iend = e.end();
for (; i != iend; ++i) {
getFactors(*i, factors);
}
break;
}
case POW: {
DebugAssert(e.arity() == 2, "invariant violated");
if (!isIntegerConst(e[0]) || e[0].getRational() <= 0) {
throw ArithException("not positive integer exponent in "+e.toString());
}
if (isLeaf(e[1])) factors.insert(e[1]);
break;
}
default: {
DebugAssert(isLeaf(e), "expected leaf");
DebugAssert(factors.find(e) == factors.end(), "expected new entry");
factors.insert(e);
break;
}
}
}
/*!
* \param eqn is a single equation 0 = e
* \return an equivalent Theorem (x = t AND 0 = e'), or just x = t
*/
Theorem
TheoryArithOld::processSimpleIntEq(const Theorem& eqn)
{
TRACE("arith eq", "processSimpleIntEq(", eqn.getExpr(), ") {");
DebugAssert(eqn.isRewrite(),
"TheoryArithOld::processSimpleIntEq: eqn must be equality" +
eqn.getExpr().toString());
Expr right = eqn.getRHS();
DebugAssert(eqn.getLHS().isRational() && 0 == eqn.getLHS().getRational(),
"TheoryArithOld::processSimpleIntEq: LHS must be 0:\n" +
eqn.getExpr().toString());
DebugAssert(!isMult(right) && !isPow(right), "should have been handled above");
if (isPlus(right)) {
if (2 == right.arity() &&
(isLeaf(right[1]) ||
(isMult(right[1]) && right[1].arity() == 2 && right[1][0].isRational() && isLeaf(right[1][1])))) {
//we take care of special cases like 0 = c + a.x, 0 = c + x,
Expr c,x;
separateMonomial(right[1], c, x);
Theorem isIntx(isIntegerThm(x));
DebugAssert(!isIntx.isNull(), "right = "+right.toString()
+"\n x = "+x.toString());
Theorem res(iffMP(eqn, d_rules->intVarEqnConst(eqn.getExpr(), isIntx)));
TRACE("arith eq", "processSimpleIntEq[0 = c + a*x] => ", res, " }");
return res;
}
// Pick a suitable monomial. isolated can be of the form x, a.x, -a.x
Expr isolated;
bool nonlin;
if (pickIntEqMonomial(right, isolated, nonlin)) {
TRACE("arith eq", "processSimpleIntEq: isolated = ", isolated, "");
// First, we compute the 'sign factor' with which to multiply the
// eqn. if the coeff of isolated is positive (i.e. 'isolated' is
// of the form x or a.x where a>0 ) then r must be -1 and if coeff
// of 'isolated' is negative, r=1.
Rational r = isMult(isolated) ?
((isolated[0].getRational() > 0) ? -1 : 1) : -1;
Theorem result;
if (-1 == r) {
// r=-1 and hence 'isolated' is 'x' or 'a.x' where a is
// positive. modify eqn (0=e') to the equation (0=canon(-1*e'))
result = iffMP(eqn, d_rules->multEqn(eqn.getLHS(), right, rat(r)));
result = canonPred(result);
Expr e = result.getRHS();
// Isolate the 'isolated'
result = iffMP(result,
d_rules->plusPredicate(result.getLHS(),result.getRHS(),
isolated, EQ));
} else {
//r is 1 and hence isolated is -a.x. Make 'isolated' positive.
const Rational& minusa = isolated[0].getRational();
Rational a = -1*minusa;
isolated = (a == 1)? isolated[1] : rat(a) * isolated[1];
// Isolate the 'isolated'
result = iffMP(eqn, d_rules->plusPredicate(eqn.getLHS(),
right,isolated,EQ));
}
// Canonize the result
result = canonPred(result);
//if isolated is 'x' or 1*x, then return result else continue processing.
if(!isMult(isolated) || isolated[0].getRational() == 1) {
TRACE("arith eq", "processSimpleIntEq[x = rhs] => ", result, " }");
return result;
} else if (!nonlin) {
DebugAssert(isMult(isolated) && isolated[0].getRational() >= 2,
"TheoryArithOld::processSimpleIntEq: isolated must be mult "
"with coeff >= 2.\n isolated = " + isolated.toString());
// Compute IS_INTEGER() for lhs and rhs
Expr lhs = result.getLHS();
Expr rhs = result.getRHS();
Expr a, x;
separateMonomial(lhs, a, x);
Theorem isIntLHS = isIntegerThm(x);
vector<Theorem> isIntRHS;
if(!isPlus(rhs)) { // rhs is a MULT
Expr c, v;
separateMonomial(rhs, c, v);
isIntRHS.push_back(isIntegerThm(v));
DebugAssert(!isIntRHS.back().isNull(), "");
} else { // rhs is a PLUS
DebugAssert(isPlus(rhs), "rhs = "+rhs.toString());
DebugAssert(rhs.arity() >= 2, "rhs = "+rhs.toString());
Expr::iterator i=rhs.begin(), iend=rhs.end();
++i; // Skip the free constant
for(; i!=iend; ++i) {
Expr c, v;
separateMonomial(*i, c, v);
isIntRHS.push_back(isIntegerThm(v));
DebugAssert(!isIntRHS.back().isNull(), "");
}
}
// Derive (EXISTS (x:INT): x = t2 AND 0 = t3)
result = d_rules->eqElimIntRule(result, isIntLHS, isIntRHS);
// Skolemize the quantifier
result = getCommonRules()->skolemize(result);
// Canonize t2 and t3 generated by this rule
DebugAssert(result.getExpr().isAnd() && result.getExpr().arity() == 2,
"processSimpleIntEq: result = "+result.getExpr().toString());
Theorem thm1 = canonPred(getCommonRules()->andElim(result, 0));
Theorem thm2 = canonPred(getCommonRules()->andElim(result, 1));
Theorem newRes = getCommonRules()->andIntro(thm1, thm2);
if(newRes.getExpr() != result.getExpr()) result = newRes;
TRACE("arith eq", "processSimpleIntEq => ", result, " }");
return result;
}
}
throw
ArithException("Can't find a leaf for solve in "+eqn.toString());
} else {
// eqn is 0 = x. Flip it and return
Theorem result = symmetryRule(eqn);
TRACE("arith eq", "processSimpleIntEq[x = 0] => ", result, " }");
return result;
}
}
/*! input is 0=e' Theorem and all of the vars in e' are of
* type INT. isolate one of them and send back to framework. output
* is "var = e''" Theorem and some associated equations in
* solved form.
*/
Theorem
TheoryArithOld::processIntEq(const Theorem& eqn)
{
TRACE("arith eq", "processIntEq(", eqn.getExpr(), ") {");
// Equations in the solved form.
std::vector<Theorem> solvedAndNewEqs;
Theorem newEq(eqn), result;
bool done(false);
do {
result = processSimpleIntEq(newEq);
// 'result' is of the from (x1=t1) AND 0=t'
if(result.isRewrite()) {
solvedAndNewEqs.push_back(result);
done = true;
}
else if (result.getExpr().isBoolConst()) {
done = true;
}
else {
DebugAssert(result.getExpr().isAnd() && result.getExpr().arity() == 2,
"TheoryArithOld::processIntEq("+eqn.getExpr().toString()
+")\n result = "+result.getExpr().toString());
solvedAndNewEqs.push_back(getCommonRules()->andElim(result, 0));
newEq = getCommonRules()->andElim(result, 1);
}
} while(!done);
Theorem res;
if (result.getExpr().isFalse()) res = result;
else if (solvedAndNewEqs.size() > 0)
res = solvedForm(solvedAndNewEqs);
else res = result;
TRACE("arith eq", "processIntEq => ", res.getExpr(), " }");
return res;
}
/*!
* Takes a vector of equations and for every equation x_i=t_i
* substitutes t_j for x_j in t_i for all j>i. This turns the system
* of equations into a solved form.
*
* Assumption: variables x_j may appear in the RHS terms t_i ONLY for
* i<j, but not for i>=j.
*/
Theorem
TheoryArithOld::solvedForm(const vector<Theorem>& solvedEqs)
{
DebugAssert(solvedEqs.size() > 0, "TheoryArithOld::solvedForm()");
// Trace code
TRACE_MSG("arith eq", "TheoryArithOld::solvedForm:solvedEqs(\n [");
IF_DEBUG(if(debugger.trace("arith eq")) {
for(vector<Theorem>::const_iterator j = solvedEqs.begin(),
jend=solvedEqs.end(); j!=jend;++j)
TRACE("arith eq", "", j->getExpr(), ",\n ");
})
TRACE_MSG("arith eq", " ]) {");
// End of Trace code
vector<Theorem>::const_reverse_iterator
i = solvedEqs.rbegin(),
iend = solvedEqs.rend();
// Substitution map: a variable 'x' is mapped to a Theorem x=t.
// This map accumulates the resulting solved form.
ExprMap<Theorem> subst;
for(; i!=iend; ++i) {
if(i->isRewrite()) {
Theorem thm = substAndCanonize(*i, subst);
TRACE("arith eq", "solvedForm: subst["+i->getLHS().toString()+"] = ",
thm.getExpr(), "");
subst[i->getLHS()] = thm;
}
else {
// This is the FALSE case: just return the contradiction
DebugAssert(i->getExpr().isFalse(),
"TheoryArithOld::solvedForm: an element of solvedEqs must "
"be either EQ or FALSE: "+i->toString());
return *i;
}
}
// Now we've collected the solved form in 'subst'. Wrap it up into
// a conjunction and return.
vector<Theorem> thms;
for(ExprMap<Theorem>::iterator i=subst.begin(), iend=subst.end();
i!=iend; ++i)
thms.push_back(i->second);
if (thms.size() > 1) return getCommonRules()->andIntro(thms);
else return thms.back();
}
/*!
* ASSUMPTION: 't' is a fully canonized arithmetic term, and every
* element of subst is a fully canonized equation of the form x=e,
* indexed by the LHS variable.
*/
Theorem
TheoryArithOld::substAndCanonize(const Expr& t, ExprMap<Theorem>& subst)
{
TRACE("arith eq", "substAndCanonize(", t, ") {");
// Quick and dirty check: return immediately if subst is empty
if(subst.empty()) {
Theorem res(reflexivityRule(t));
TRACE("arith eq", "substAndCanonize[subst empty] => ", res, " }");
return res;
}
// Check if we can substitute 't' directly
ExprMap<Theorem>::iterator i = subst.find(t), iend=subst.end();
if(i!=iend) {
TRACE("arith eq", "substAndCanonize[subst] => ", i->second, " }");
return i->second;
}
// The base case: t is an i-leaf
if(isLeaf(t)) {
Theorem res(reflexivityRule(t));
TRACE("arith eq", "substAndCanonize[i-leaf] => ", res, " }");
return res;
}
// 't' is an arithmetic term; recurse into the children
vector<Theorem> thms;
vector<unsigned> changed;
for(unsigned j=0, jend=t.arity(); j!=jend; ++j) {
Theorem thm = substAndCanonize(t[j], subst);
if(thm.getRHS() != t[j]) {
thm = canonThm(thm);
thms.push_back(thm);
changed.push_back(j);
}
}
// Do the actual substitution and canonize the result
Theorem res;
if(thms.size() > 0) {
res = substitutivityRule(t, changed, thms);
res = canonThm(res);
}
else
res = reflexivityRule(t);
TRACE("arith eq", "substAndCanonize => ", res, " }");
return res;
}
/*!
* ASSUMPTION: 't' is a fully canonized equation of the form x = t,
* and so is every element of subst, indexed by the LHS variable.
*/
Theorem
TheoryArithOld::substAndCanonize(const Theorem& eq, ExprMap<Theorem>& subst)
{
// Quick and dirty check: return immediately if subst is empty
if(subst.empty()) return eq;
DebugAssert(eq.isRewrite(), "TheoryArithOld::substAndCanonize: t = "
+eq.getExpr().toString());
const Expr& t = eq.getRHS();
// Do the actual substitution in the term t
Theorem thm = substAndCanonize(t, subst);
// Substitution had no result: return the original equation
if(thm.getRHS() == t) return eq;
// Otherwise substitute the result into the equation
vector<Theorem> thms;
vector<unsigned> changed;
thms.push_back(thm);
changed.push_back(1);
return iffMP(eq, substitutivityRule(eq.getExpr(), changed, thms));
}
void TheoryArithOld::processBuffer()
{
// Process the inequalities in the buffer
bool varOnRHS;
// If we are in difference logic only, just return
if (diffLogicOnly) return;
while (!inconsistent() && (d_bufferIdx_0 < d_buffer_0.size() || d_bufferIdx_1 < d_buffer_1.size() || d_bufferIdx_2 < d_buffer_2.size() || d_bufferIdx_3 < d_buffer_3.size())) {
// Get the unprojected inequality
Theorem ineqThm;
if (d_bufferIdx_0 < d_buffer_0.size()) {
ineqThm = d_buffer_0[d_bufferIdx_0];
d_bufferIdx_0 = d_bufferIdx_0 + 1;
} else if (d_bufferIdx_1 < d_buffer_1.size()) {
ineqThm = d_buffer_1[d_bufferIdx_1];
d_bufferIdx_1 = d_bufferIdx_1 + 1;
} else if (d_bufferIdx_2 < d_buffer_2.size()) {
ineqThm = d_buffer_2[d_bufferIdx_2];
d_bufferIdx_2 = d_bufferIdx_2 + 1;
} else {
ineqThm = d_buffer_3[d_bufferIdx_3];
d_bufferIdx_3 = d_bufferIdx_3 + 1;
}
// // Skip this inequality if it is stale
// if(isStale(ineqThm.getExpr())) {
// TRACE("arith buffer", "processBuffer(", ineqThm.getExpr(), ")... skipping stale");
// continue;
// }
// Dejan: project the finds, not the originals (if not projected already)
const Expr& inequality = ineqThm.getExpr();
Theorem inequalityFindThm = inequalityToFind(ineqThm, true);
Expr inequalityFind = inequalityFindThm.getExpr();
// if (inequality != inequalityFind)
// enqueueFact(inequalityFindThm);
TRACE("arith buffer", "processing: ", inequality, "");
TRACE("arith buffer", "with find : ", inequalityFind, "");
if (!isIneq(inequalityFind)) {
TRACE("arith buffer", "find not an inequality... ", "", "skipping");
continue;
}
if (alreadyProjected.find(inequalityFind) != alreadyProjected.end()) {
TRACE("arith buffer", "already projected ... ", "", "skipping");
continue;
}
// We put the dummy for now, isolate variable will set it properly (or the find's one)
// This one is just if the find is different. If the find is different
// We will not check it again in update, so we're fine
Expr dummy;
alreadyProjected[inequality] = dummy;
if (inequality != inequalityFind) {
alreadyProjected[inequalityFind] = dummy;
Expr rhs = inequalityFind[1];
// Collect the statistics about variables
if(isPlus(rhs)) {
for(Expr::iterator i=rhs.begin(), iend=rhs.end(); i!=iend; ++i) {
Expr monomial = *i;
updateStats(monomial);
}
} else // It's a monomial
updateStats(rhs);
}
// See if this one is subsumed by a stronger inequality
// c1 <= t1, t2 <= c2
Rational c1, c2;
Expr t1, t2;
// Every term in the buffer has to have a lower bound set!!!
// Except for the ones that changed the find
extractTermsFromInequality(inequalityFind, c1, t1, c2, t2);
if (termLowerBound.find(t1) != termLowerBound.end() && c1 != termLowerBound[t1]) {
TRACE("arith ineq", "skipping because stronger bounds asserted ", inequalityFind.toString(), ":" + t1.toString());
DebugAssert(termLowerBoundThm.find(t1) != termLowerBoundThm.end(), "No lower bound on asserted atom!!! " + t1.toString());
Theorem strongerBound = termLowerBoundThm[t1];
//enqueueFact(d_rules->implyWeakerInequality(strongerBound.getExpr(), inequalityFindThm.getExpr()));
continue;
}
Theorem thm1 = isolateVariable(inequalityFindThm, varOnRHS);
const Expr& ineq = thm1.getExpr();
if (ineq.isFalse())
setInconsistent(thm1);
else
if(!ineq.isTrue()) {
// Check that the variable is indeed isolated correctly
DebugAssert(varOnRHS? !isPlus(ineq[1]) : !isPlus(ineq[0]), "TheoryArithOld::processBuffer(): bad result from isolateVariable:\nineq = "+ineq.toString());
// and project the inequality
projectInequalities(thm1, varOnRHS);
}
}
}
void TheoryArithOld::updateStats(const Rational& c, const Expr& v)
{
TRACE("arith stats", "updateStats("+c.toString()+", ", v, ")");
// we can get numbers as checking for variables is not possible (nonlinear stuff)
if (v.isRational()) return;
if (v.getType() != d_realType) {
// Dejan: update the max coefficient of the variable
if (c < 0) {
// Goes to the left side
ExprMap<Rational>::iterator maxFind = maxCoefficientLeft.find(v);
if (maxFind == maxCoefficientLeft.end()) {
maxCoefficientLeft[v] = - c;
TRACE("arith stats", "max left", "", "");
}
else
if ((*maxFind).second < -c) {
TRACE("arith stats", "max left", "", "");
maxCoefficientLeft[v] = -c;
}
} else {
// Stays on the right side
ExprMap<Rational>::iterator maxFind = maxCoefficientRight.find(v);
if (maxFind == maxCoefficientRight.end()) {
maxCoefficientRight[v] = c;
TRACE("arith stats", "max right", "", "");
}
else
if((*maxFind).second < c) {
TRACE("arith stats", "max right", "", "");
maxCoefficientRight[v] = c;
}
}
}
if(c > 0) {
if(d_countRight.count(v) > 0) d_countRight[v] = d_countRight[v] + 1;
else d_countRight[v] = 1;
}
else
if(d_countLeft.count(v) > 0) d_countLeft[v] = d_countLeft[v] + 1;
else d_countLeft[v] = 1;
}
void TheoryArithOld::updateStats(const Expr& monomial)
{
Expr c, m;
separateMonomial(monomial, c, m);
updateStats(c.getRational(), m);
}
int TheoryArithOld::extractTermsFromInequality(const Expr& inequality,
Rational& c1, Expr& t1,
Rational& c2, Expr& t2) {
TRACE("arith extract", "extract(", inequality.toString(), ")");
DebugAssert(isIneq(inequality), "extractTermsFromInequality: expexting an inequality got: " + inequality.getString() + ")");
Expr rhs = inequality[1];
c1 = 0;
// Extract the non-constant term (both sides)
vector<Expr> positive_children, negative_children;
if (isPlus(rhs)) {
int start_i = 0;
if (rhs[0].isRational()) {
start_i = 1;
c1 = -rhs[0].getRational();
}
int end_i = rhs.arity();
for(int i = start_i; i < end_i; i ++) {
const Expr& term = rhs[i];
positive_children.push_back(term);
negative_children.push_back(canon(multExpr(rat(-1),term)).getRHS());
}
} else {
positive_children.push_back(rhs);
negative_children.push_back(canon(multExpr(rat(-1), rhs)).getRHS());
}
int num_vars = positive_children.size();
// c1 <= t1
t1 = (num_vars > 1 ? canon(plusExpr(positive_children)).getRHS() : positive_children[0]);
// c2 is the upper bound on t2 : t2 <= c2
c2 = -c1;
t2 = (num_vars > 1 ? canon(plusExpr(negative_children)).getRHS() : negative_children[0]);
TRACE("arith extract", "extract: ", c1.toString() + " <= ", t1.toString());
return num_vars;
}
bool TheoryArithOld::addToBuffer(const Theorem& thm, bool priority) {
TRACE("arith buffer", "addToBuffer(", thm.getExpr().toString(), ")");
Expr ineq = thm.getExpr();
const Expr& rhs = thm.getExpr()[1];
bool nonLinear = false;
Rational nonLinearConstant = 0;
Expr compactNonLinear;
Theorem compactNonLinearThm;
// Collect the statistics about variables and check for non-linearity
if(isPlus(rhs)) {
for(Expr::iterator i=rhs.begin(), iend=rhs.end(); i!=iend; ++i) {
Expr monomial = *i;
updateStats(monomial);
// check for non-linear
if (isMult(monomial)) {
if ((monomial[0].isRational() && monomial.arity() >= 3) ||
(!monomial[0].isRational() && monomial.arity() >= 2) ||
(monomial.arity() == 2 && isPow(monomial[1])))
nonLinear = true;
}
}
if (nonLinear) {
compactNonLinearThm = d_rules->compactNonLinearTerm(rhs);
compactNonLinear = compactNonLinearThm.getRHS();
}
}
else // It's a monomial
{
updateStats(rhs);
if (isMult(rhs))
if ((rhs[0].isRational() && rhs.arity() >= 3)
|| (!rhs[0].isRational() && rhs.arity() >= 2)
|| (rhs.arity() == 2 && isPow(rhs[1]))) {
nonLinear = true;
compactNonLinear = rhs;
compactNonLinearThm = reflexivityRule(compactNonLinear);
}
}
if (bufferedInequalities.find(ineq) != bufferedInequalities.end()) {
TRACE("arith buffer", "addToBuffer()", "", "... already in db");
if (formulaAtoms.find(ineq) != formulaAtoms.end()) {
TRACE("arith buffer", "it's a formula atom, enqueuing.", "", "");
enqueueFact(thm);
}
return false;
}
if (nonLinear && (isMult(rhs) || compactNonLinear != rhs)) {
TRACE("arith nonlinear", "compact version of ", rhs, " is " + compactNonLinear.toString());
// Replace the rhs with the compacted nonlinear term
Theorem thm1 = (compactNonLinear != rhs ?
iffMP(thm, substitutivityRule(ineq, 1, compactNonLinearThm)) : thm);
// Now, try to deduce the signednes of multipliers
Rational c = (isMult(rhs) ? 0 : compactNonLinear[0].getRational());
// We can deduct the signs if the constant is not bigger than 0
if (c <= 0) {
thm1 = d_rules->nonLinearIneqSignSplit(thm1);
TRACE("arith nonlinear", "spliting on signs : ", thm1.getExpr(), "");
enqueueFact(thm1);
}
}
// Get c1, c2, t1, t2 such that c1 <= t1 and t2 <= c2
Expr t1, t2;
Rational c1, c2;
int num_vars = extractTermsFromInequality(ineq, c1, t1, c2, t2);
// If 2 variable, do add to difference logic (allways, just in case)
bool factIsDiffLogic = false;
if (num_vars <= 2) {
TRACE("arith diff", t2, " < ", c2);
// c1 <= t1, check if difference logic
// t1 of the form 0 + ax + by
Expr ax = (num_vars == 2 ? t2[1] : t2);
Expr a_expr, x;
separateMonomial(ax, a_expr, x);
Rational a = a_expr.getRational();
Expr by = (num_vars == 2 ? t2[2] : (a < 0 ? zero : rat(-1)*zero));
Expr b_expr, y;
separateMonomial(by, b_expr, y);
Rational b = b_expr.getRational();
// Check for non-linear
if (!isLeaf(x) || !isLeaf(y))
setIncomplete("Non-linear arithmetic inequalities");
if (a == 1 && b == -1) {
diffLogicGraph.addEdge(x, y, c2, thm);
factIsDiffLogic = true;
}
else if (a == -1 && b == 1) {
diffLogicGraph.addEdge(y, x, c2, thm);
factIsDiffLogic = true;
}
// Not difference logic, put it in the 3 or more vars buffer
else {
diffLogicOnly = false;
TRACE("arith diff", "not diff logic", thm.getExpr().toString(), "");
}
if (diffLogicGraph.isUnsat()) {
TRACE("diff unsat", "UNSAT", " : ", diffLogicGraph.getUnsatTheorem());
setInconsistent(diffLogicGraph.getUnsatTheorem());
return false;
}
} else {
diffLogicOnly = false;
TRACE("arith diff", "not diff logic", thm.getExpr().toString(), "");
}
// For now we treat all the bound as LE, weaker
CDMap<Expr, Rational>::iterator find_lower = termLowerBound.find(t1);
if (find_lower != termLowerBound.end()) {
// found bound c <= t1
Rational found_c = (*find_lower).second;
// If found c is bigger than the new one, we are done
if (c1 <= found_c && !(found_c == c1 && ineq.getKind() == LT)) {
TRACE("arith buffer", "addToBuffer()", "", "... lower_bound subsumed");
// Removed assert. Can happen that an atom is not asserted yet, and get's implied as
// a formula atom and then asserted here. it's fine
//DebugAssert(!thm.isAssump(), "Should have been propagated: " + ineq.toString() + "");
return false;
} else {
Theorem oldLowerBound = termLowerBoundThm[t1];
Expr oldIneq = oldLowerBound.getExpr();
if (formulaAtoms.find(oldIneq) != formulaAtoms.end())
enqueueFact(getCommonRules()->implMP(thm, d_rules->implyWeakerInequality(ineq, oldIneq)));
termLowerBound[t1] = c1;
termLowerBoundThm[t1] = thm;
}
} else {
termLowerBound[t1] = c1;
termLowerBoundThm[t1] = thm;
}
CDMap<Expr, Rational>::iterator find_upper = termUpperBound.find(t2);
if (find_upper != termUpperBound.end()) {
// found bound t2 <= c
Rational found_c = (*find_upper).second;
// If found c is smaller than the new one, we are done
if (found_c <= c2 && !(found_c == c2 && ineq.getKind() == LT)) {
TRACE("arith buffer", "addToBuffer()", "", "... upper_bound subsumed");
//DebugAssert(!thm.isAssump(), "Should have been propagated: " + ineq.toString() + "");
return false;
} else {
termUpperBound[t2] = c2;
termUpperBoundThm[t2] = thm;
}
} else {
termUpperBound[t2] = c2;
termUpperBoundThm[t2] = thm;
}
// See if the bounds on the term can infer conflict or equality
if (termUpperBound.find(t1) != termUpperBound.end() &&
termLowerBound.find(t1) != termLowerBound.end() &&
termUpperBound[t1] <= termLowerBound[t1]) {
Theorem thm1 = termUpperBoundThm[t1];
Theorem thm2 = termLowerBoundThm[t1];
TRACE("arith propagate", "adding inequalities: ", thm1.getExpr().toString(), " with " + thm2.getExpr().toString());
enqueueFact(d_rules->addInequalities(thm1, thm2));
} else
if (termUpperBound.find(t2) != termUpperBound.end() &&
termLowerBound.find(t2) != termLowerBound.end() &&
termUpperBound[t2] <= termLowerBound[t2]) {
Theorem thm1 = termUpperBoundThm[t2];
Theorem thm2 = termLowerBoundThm[t2];
TRACE("arith propagate", "adding inequalities: ", thm1.getExpr().toString(), " with " + thm2.getExpr().toString());
enqueueFact(d_rules->addInequalities(thm1, thm2));
}
if (true) {
// See if we can propagate anything to the formula atoms
// c1 <= t1 ===> c <= t1 for c < c1
AtomsMap::iterator find = formulaAtomLowerBound.find(t1);
AtomsMap::iterator find_end = formulaAtomLowerBound.end();
if (find != find_end) {
set< pair<Rational, Expr> >::iterator bounds = (*find).second.begin();
set< pair<Rational, Expr> >::iterator bounds_end = (*find).second.end();
while (bounds != bounds_end) {
TRACE("arith atoms", "trying propagation", ineq, (*bounds).second);
const Expr& implied = (*bounds).second;
// Try to do some theory propagation
if ((*bounds).first < c1 || (!(ineq.getKind() == LE && implied.getKind() == LT) && (*bounds).first == c1)) {
// c1 <= t1 => c <= t1 (for c <= c1)
// c1 < t1 => c <= t1 (for c <= c1)
// c1 <= t1 => c < t1 (for c < c1)
Theorem impliedThm = getCommonRules()->implMP(thm, d_rules->implyWeakerInequality(ineq, implied));
enqueueFact(impliedThm);
}
bounds ++;
}
}
//
// c1 <= t1 ==> !(t1 <= c) for c < c1
// ==> !(-c <= t2)
// i.e. all coefficient in in the implied are opposite of t1
find = formulaAtomUpperBound.find(t1);
find_end = formulaAtomUpperBound.end();
if (find != find_end) {
set< pair<Rational, Expr> >::iterator bounds = (*find).second.begin();
set< pair<Rational, Expr> >::iterator bounds_end = (*find).second.end();
while (bounds != bounds_end) {
TRACE("arith atoms", "trying propagation", ineq, (*bounds).second);
const Expr& implied = (*bounds).second;
// Try to do some theory propagation
if ((*bounds).first < c1) {
Theorem impliedThm = getCommonRules()->implMP(thm, d_rules->implyNegatedInequality(ineq, implied));
enqueueFact(impliedThm);
}
bounds ++;
}
}
}
// Register this as a resource
theoryCore()->getResource();
// If out of resources, bail out
if (theoryCore()->outOfResources()) return false;
// Checking because we could have projected it as a find of some other
// equation
if (alreadyProjected.find(ineq) == alreadyProjected.end()) {
// We buffer it if it's not marked for not buffering
if (dontBuffer.find(ineq) == dontBuffer.end()) {
// We give priority to the one that can produce a conflict
if (priority)
d_buffer_0.push_back(thm);
else {
// Push it into the buffer (one var)
if (num_vars == 1) d_buffer_1.push_back(thm);
else if (num_vars == 2) d_buffer_2.push_back(thm);
else d_buffer_3.push_back(thm);
}
if (factIsDiffLogic) diff_logic_size = diff_logic_size + 1;
}
}
// Remember that it's in the buffer
bufferedInequalities[ineq] = thm;
// Since we care about this atom, lets set it up
if (!ineq.hasFind())
theoryCore()->setupTerm(ineq, this, thm);
return true;
}
Theorem TheoryArithOld::isolateVariable(const Theorem& inputThm,
bool& isolatedVarOnRHS)
{
Theorem result(inputThm);
const Expr& e = inputThm.getExpr();
TRACE("arith","isolateVariable(",e,") {");
TRACE("arith ineq", "isolateVariable(", e, ") {");
//we assume all the children of e are canonized
DebugAssert(isLT(e)||isLE(e),
"TheoryArithOld::isolateVariable: " + e.toString() +
" wrong kind");
int kind = e.getKind();
DebugAssert(e[0].isRational() && e[0].getRational() == 0,
"TheoryArithOld::isolateVariable: theorem must be of "
"the form 0 < rhs: " + inputThm.toString());
const Expr& zero = e[0];
Expr right = e[1];
// Check for trivial in-equation.
if (right.isRational()) {
result = iffMP(result, d_rules->constPredicate(e));
TRACE("arith ineq","isolateVariable => ",result.getExpr()," }");
TRACE("arith","isolateVariable => ",result," }");
return result;
}
// Normalization of inequality to make coefficients integer and
// relatively prime.
Expr factor(computeNormalFactor(right, false));
TRACE("arith", "isolateVariable: factor = ", factor, "");
DebugAssert(factor.getRational() > 0,
"isolateVariable: factor="+factor.toString());
// Now multiply the inequality by the factor, unless it is 1
if(factor.getRational() != 1) {
result = iffMP(result, d_rules->multIneqn(e, factor));
// And canonize the result
result = canonPred(result);
result = rafineInequalityToInteger(result);
right = result.getExpr()[1];
}
// Find monomial to isolate and store it in isolatedMonomial
Expr isolatedMonomial = right;
if (isPlus(right))
isolatedMonomial = pickMonomial(right);
TRACE("arith ineq", "isolatedMonomial => ",isolatedMonomial,"");
// Set the correct isolated monomial
// Now, if something gets updated, but this monomial is not changed, we don't
// Have to rebuffer it as the projection will still be accurate when updated
alreadyProjected[e] = isolatedMonomial;
Rational r = -1;
isolatedVarOnRHS = true;
if (isMult(isolatedMonomial)) {
r = ((isolatedMonomial[0].getRational()) >= 0)? -1 : 1;
isolatedVarOnRHS =
((isolatedMonomial[0].getRational()) >= 0)? true : false;
}
isolatedMonomial = canon(rat(-1)*isolatedMonomial).getRHS();
TRACE("arith ineq", "-(isolatedMonomial) => ",isolatedMonomial,"");
// Isolate isolatedMonomial on to the LHS
result = iffMP(result, d_rules->plusPredicate(zero, right,
isolatedMonomial, kind));
// Canonize the resulting inequality
TRACE("arith ineq", "resutl => ",result,"");
result = canonPred(result);
if(1 != r) {
result = iffMP(result, d_rules->multIneqn(result.getExpr(), rat(r)));
result = canonPred(result);
}
TRACE("arith ineq","isolateVariable => ",result.getExpr()," }");
TRACE("arith","isolateVariable => ",result," }");
return result;
}
Expr
TheoryArithOld::computeNormalFactor(const Expr& right, bool normalizeConstants) {
// Strategy: compute f = lcm(d1...dn)/gcd(c1...cn), where the RHS is
// of the form c1/d1*x1 + ... + cn/dn*xn
Rational factor;
if(isPlus(right)) {
vector<Rational> nums, denoms;
for(int i=0, iend=right.arity(); i<iend; ++i) {
switch(right[i].getKind()) {
case RATIONAL_EXPR:
if (normalizeConstants) {
Rational c(abs(right[i].getRational()));
nums.push_back(c.getNumerator());
denoms.push_back(c.getDenominator());
break;
}
break;
case MULT: {
Rational c(abs(right[i][0].getRational()));
nums.push_back(c.getNumerator());
denoms.push_back(c.getDenominator());
break;
}
default: // it's a variable
nums.push_back(1);
denoms.push_back(1);
break;
}
}
Rational gcd_nums = gcd(nums);
// x/0 == 0 in our model, as a total extension of arithmetic. The
// particular value of x/0 is irrelevant, since the DP is guarded
// by the top-level TCCs, and it is safe to return any value in
// cases when terms are undefined.
factor = (gcd_nums==0)? 0 : (lcm(denoms) / gcd_nums);
} else if(isMult(right)) {
const Rational& r = right[0].getRational();
factor = (r==0)? 0 : (1/abs(r));
}
else
factor = 1;
return rat(factor);
}
bool TheoryArithOld::lessThanVar(const Expr& isolatedMonomial, const Expr& var2)
{
DebugAssert(!isRational(var2) && !isRational(isolatedMonomial),
"TheoryArithOld::findMaxVar: isolatedMonomial cannot be rational" +
isolatedMonomial.toString());
Expr c, var0, var1;
separateMonomial(isolatedMonomial, c, var0);
separateMonomial(var2, c, var1);
return var0 < var1;
}
/*! "Stale" means it contains non-simplified subexpressions. For
* terms, it checks the expression's find pointer; for formulas it
* checks the children recursively (no caching!). So, apply it with
* caution, and only to simple atomic formulas (like inequality).
*/
bool TheoryArithOld::isStale(const Expr& e) {
if(e.isTerm())
return e != find(e).getRHS();
// It's better be a simple predicate (like inequality); we check the
// kids recursively
bool stale=false;
for(Expr::iterator i=e.begin(), iend=e.end(); !stale && i!=iend; ++i)
stale = isStale(*i);
return stale;
}
bool TheoryArithOld::isStale(const TheoryArithOld::Ineq& ineq) {
TRACE("arith stale", "isStale(", ineq, ") {");
const Expr& ineqExpr = ineq.ineq().getExpr();
const Rational& c = freeConstIneq(ineqExpr, ineq.varOnRHS());
bool strict(isLT(ineqExpr));
const FreeConst& fc = ineq.getConst();
bool subsumed;
if (ineqExpr.hasFind() && find(ineqExpr[1]).getRHS() != ineqExpr[1])
return true;
if(ineq.varOnRHS()) {
subsumed = (c < fc.getConst() ||
(c == fc.getConst() && !strict && fc.strict()));
} else {
subsumed = (c > fc.getConst() ||
(c == fc.getConst() && strict && !fc.strict()));
}
bool res;
if(subsumed) {
res = true;
TRACE("arith ineq", "isStale[subsumed] => ", res? "true" : "false", " }");
}
else {
res = isStale(ineqExpr);
TRACE("arith ineq", "isStale[updated] => ", res? "true" : "false", " }");
}
return res;
}
void TheoryArithOld::separateMonomial(const Expr& e, Expr& c, Expr& var) {
TRACE("separateMonomial", "separateMonomial(", e, ")");
DebugAssert(!isPlus(e),
"TheoryArithOld::separateMonomial(e = "+e.toString()+")");
if(isMult(e)) {
DebugAssert(e.arity() >= 2,
"TheoryArithOld::separateMonomial(e = "+e.toString()+")");
c = e[0];
if(e.arity() == 2) var = e[1];
else {
vector<Expr> kids = e.getKids();
kids[0] = rat(1);
var = multExpr(kids);
}
} else {
c = rat(1);
var = e;
}
DebugAssert(c.isRational(), "TheoryArithOld::separateMonomial(e = "
+e.toString()+", c = "+c.toString()+")");
DebugAssert(!isMult(var) || (var[0].isRational() && var[0].getRational()==1),
"TheoryArithOld::separateMonomial(e = "
+e.toString()+", var = "+var.toString()+")");
}
void TheoryArithOld::projectInequalities(const Theorem& theInequality,
bool isolatedVarOnRHS)
{
TRACE("arith project", "projectInequalities(", theInequality.getExpr(),
", isolatedVarOnRHS="+string(isolatedVarOnRHS? "true" : "false")
+") {");
DebugAssert(isLE(theInequality.getExpr()) ||
isLT(theInequality.getExpr()),
"TheoryArithOld::projectIsolatedVar: "\
"theInequality is of the wrong form: " +
theInequality.toString());
//TODO: DebugAssert to check if the isolatedMonomial is of the right
//form and the whether we are indeed getting inequalities.
Theorem theIneqThm(theInequality);
Expr theIneq = theIneqThm.getExpr();
// If the inequality is strict and integer, change it to non-strict
if(isLT(theIneq)) {
Theorem isIntLHS(isIntegerThm(theIneq[0]));
Theorem isIntRHS(isIntegerThm(theIneq[1]));
if ((!isIntLHS.isNull() && !isIntRHS.isNull())) {
Theorem thm = d_rules->lessThanToLE(theInequality, isIntLHS, isIntRHS, !isolatedVarOnRHS);
theIneqThm = canonPred(iffMP(theIneqThm, thm));
theIneq = theIneqThm.getExpr();
}
}
Expr isolatedMonomial = isolatedVarOnRHS ? theIneq[1] : theIneq[0];
Expr monomialVar, a;
separateMonomial(isolatedMonomial, a, monomialVar);
bool subsumed;
const FreeConst& bestConst = updateSubsumptionDB(theIneq, isolatedVarOnRHS, subsumed);
if(subsumed) {
IF_DEBUG(debugger.counter("subsumed inequalities")++;)
TRACE("arith ineq", "subsumed inequality: ", theIneq, "");
} else {
// If the isolated variable is actually a non-linear term, we are
// incomplete
if(isMult(monomialVar) || isPow(monomialVar))
setIncomplete("Non-linear arithmetic inequalities");
// First, we need to make sure the isolated inequality is
// setup properly.
// setupRec(theIneq[0]);
// setupRec(theIneq[1]);
theoryCore()->setupTerm(theIneq[0], this, theIneqThm);
theoryCore()->setupTerm(theIneq[1], this, theIneqThm);
// Add the inequality into the appropriate DB.
ExprMap<CDList<Ineq> *>& db1 = isolatedVarOnRHS ? d_inequalitiesRightDB : d_inequalitiesLeftDB;
ExprMap<CDList<Ineq> *>::iterator it1 = db1.find(monomialVar);
if(it1 == db1.end()) {
CDList<Ineq> * list = new(true) CDList<Ineq>(theoryCore()->getCM()->getCurrentContext());
list->push_back(Ineq(theIneqThm, isolatedVarOnRHS, bestConst));
db1[monomialVar] = list;
}
else
((*it1).second)->push_back(Ineq(theIneqThm, isolatedVarOnRHS, bestConst));
ExprMap<CDList<Ineq> *>& db2 = isolatedVarOnRHS ? d_inequalitiesLeftDB : d_inequalitiesRightDB;
ExprMap<CDList<Ineq> *>::iterator it = db2.find(monomialVar);
if(it == db2.end()) {
TRACE_MSG("arith ineq", "projectInequalities[not in DB] => }");
return;
}
CDList<Ineq>& listOfDBIneqs = *((*it).second);
Theorem betaLTt, tLTalpha, thm;
for(int i = listOfDBIneqs.size() - 1; !inconsistent() && i >= 0; --i) {
const Ineq& ineqEntry = listOfDBIneqs[i];
const Theorem& ineqThm = ineqEntry.ineq(); //inequalityToFind(ineqEntry.ineq(), isolatedVarOnRHS);
// ineqExntry might be stale
if(!isStale(ineqEntry)) {
betaLTt = isolatedVarOnRHS ? theIneqThm : ineqThm;
tLTalpha = isolatedVarOnRHS ? ineqThm : theIneqThm;
thm = normalizeProjectIneqs(betaLTt, tLTalpha);
if (thm.isNull()) continue;
IF_DEBUG(debugger.counter("real shadows")++;)
// Check for TRUE and FALSE theorems
Expr e(thm.getExpr());
if(e.isFalse()) {
setInconsistent(thm);
TRACE_MSG("arith ineq", "projectInequalities[inconsistent] => }");
return;
}
else {
if(!e.isTrue() && !e.isEq()) {
// setup the term so that it comes out in updates
addToBuffer(thm, false);
}
else if(e.isEq())
enqueueFact(thm);
}
} else {
IF_DEBUG(debugger.counter("stale inequalities")++;)
}
}
}
TRACE_MSG("arith ineq", "projectInequalities => }");
}
Theorem TheoryArithOld::normalizeProjectIneqs(const Theorem& ineqThm1,
const Theorem& ineqThm2)
{
//ineq1 is of the form beta < b.x or beta < x [ or with <= ]
//ineq2 is of the form a.x < alpha or x < alpha.
Theorem betaLTt = ineqThm1, tLTalpha = ineqThm2;
Expr ineq1 = betaLTt.getExpr();
Expr ineq2 = tLTalpha.getExpr();
Expr c,x;
separateMonomial(ineq2[0], c, x);
Theorem isIntx(isIntegerThm(x));
Theorem isIntBeta(isIntegerThm(ineq1[0]));
Theorem isIntAlpha(isIntegerThm(ineq2[1]));
bool isInt = !(isIntx.isNull() || isIntBeta.isNull() || isIntAlpha.isNull());
TRACE("arith ineq", "normalizeProjectIneqs(", ineq1,
", "+ineq2.toString()+") {");
DebugAssert((isLE(ineq1) || isLT(ineq1)) &&
(isLE(ineq2) || isLT(ineq2)),
"TheoryArithOld::normalizeProjectIneqs: Wrong Kind inputs: " +
ineq1.toString() + ineq2.toString());
DebugAssert(!isPlus(ineq1[1]) && !isPlus(ineq2[0]),
"TheoryArithOld::normalizeProjectIneqs: Wrong Kind inputs: " +
ineq1.toString() + ineq2.toString());
//compute the factors to multiply the two inequalities with
//so that they get the form beta < t and t < alpha.
Rational factor1 = 1, factor2 = 1;
Rational b = isMult(ineq1[1]) ? (ineq1[1])[0].getRational() : 1;
Rational a = isMult(ineq2[0]) ? (ineq2[0])[0].getRational() : 1;
if(b != a) {
factor1 = a;
factor2 = b;
}
//if the ineqs are of type int then apply one of the gray
//dark shadow rules.
// FIXME: intResult should also be checked for immediate
// optimizations, as those below for 'result'. Also, if intResult
// is a single inequality, we may want to handle it similarly to the
// 'result' rather than enqueuing directly.
if(isInt && (a >= 2 || b >= 2)) {
Theorem intResult;
if(a <= b)
intResult = d_rules->darkGrayShadow2ab(betaLTt, tLTalpha,
isIntAlpha, isIntBeta, isIntx);
else
intResult = d_rules->darkGrayShadow2ba(betaLTt, tLTalpha,
isIntAlpha, isIntBeta, isIntx);
enqueueFact(intResult);
// Fetch dark and gray shadows
const Expr& DorG = intResult.getExpr();
DebugAssert(DorG.isOr() && DorG.arity()==2, "DorG = "+DorG.toString());
const Expr& G = DorG[1];
DebugAssert(G.getKind()==GRAY_SHADOW, "G = "+G.toString());
// Set the higher splitter priority for dark shadow
// Expr tmp = simplifyExpr(D);
// if (!tmp.isBoolConst())
// addSplitter(tmp, 5);
// Also set a higher priority to the NEGATION of GRAY_SHADOW
Expr tmp = simplifyExpr(!G);
if (!tmp.isBoolConst())
addSplitter(tmp, 1);
IF_DEBUG(debugger.counter("dark+gray shadows")++;)
// Dejan: Let's forget about the real shadow, we are doing integers
// /return intResult;
}
//actually normalize the inequalities
if(1 != factor1) {
Theorem thm2 = iffMP(betaLTt, d_rules->multIneqn(ineq1, rat(factor1)));
betaLTt = canonPred(thm2);
ineq1 = betaLTt.getExpr();
}
if(1 != factor2) {
Theorem thm2 = iffMP(tLTalpha, d_rules->multIneqn(ineq2, rat(factor2)));
tLTalpha = canonPred(thm2);
ineq2 = tLTalpha.getExpr();
}
//IF_DEBUG(debugger.counter("real shadows")++;)
Expr beta(ineq1[0]);
Expr alpha(ineq2[1]);
// In case of alpha <= t <= alpha, we generate t = alpha
if(isLE(ineq1) && isLE(ineq2) && alpha == beta) {
Theorem result = d_rules->realShadowEq(betaLTt, tLTalpha);
TRACE("arith ineq", "normalizeProjectIneqs => ", result, " }");
return result;
}
// Check if this inequality is a finite interval
// if(isInt)
// processFiniteInterval(betaLTt, tLTalpha);
// // Only do the real shadow if a and b = 1
// if (isInt && a > 1 && b > 1)
// return Theorem();
//project the normalized inequalities.
Theorem result = d_rules->realShadow(betaLTt, tLTalpha);
// FIXME: Clark's changes. Is 'rewrite' more or less efficient?
// result = iffMP(result, rewrite(result.getExpr()));
// TRACE("arith ineq", "normalizeProjectIneqs => ", result, " }");
// Now, transform the result into 0 < rhs and see if rhs is a const
Expr e(result.getExpr());
// int kind = e.getKind();
if(!(e[0].isRational() && e[0].getRational() == 0))
result = iffMP(result, d_rules->rightMinusLeft(e));
result = canonPred(result);
//result is "0 kind e'". where e' is equal to canon(e[1]-e[0])
Expr right = result.getExpr()[1];
// Check for trivial inequality
if (right.isRational())
result = iffMP(result, d_rules->constPredicate(result.getExpr()));
else
result = normalize(result);
TRACE("arith ineq", "normalizeProjectIneqs => ", result, " }");
return result;
}
Rational TheoryArithOld::currentMaxCoefficient(Expr var)
{
// We prefer real variables
if (var.getType() == d_realType) return -100;
// Find the biggest left side coefficient
ExprMap<Rational>::iterator findMaxLeft = maxCoefficientLeft.find(var);
Rational leftMax = -1;
if (findMaxLeft != maxCoefficientLeft.end())
leftMax = (*findMaxLeft).second;
//
ExprMap<Rational>::iterator findMaxRight = maxCoefficientRight.find(var);
Rational rightMax = -1;
if (findMaxRight != maxCoefficientRight.end())
rightMax = (*findMaxRight).second;
// What is the max coefficient
// If one is undefined, dont take it. My first thought was to project away unbounded
// ones, but it happens that you get another constraint on it later and the hell breaks
// loose if they have big coefficients.
Rational returnValue;
if (leftMax == -1) returnValue = rightMax;
else if (rightMax == -1) returnValue = leftMax;
else if (leftMax < rightMax) returnValue = rightMax;
else returnValue = leftMax;
TRACE("arith stats", "max coeff of ", var.toString(), ": " + returnValue.toString() + "(left=" + leftMax.toString() + ",right=" + rightMax.toString());
return returnValue;
}
void TheoryArithOld::fixCurrentMaxCoefficient(Expr var, Rational max) {
fixedMaxCoefficient[var] = max;
}
void TheoryArithOld::selectSmallestByCoefficient(const vector<Expr>& input, vector<Expr>& output) {
// Clear the output vector
output.clear();
// Get the first variable, and set it as best
Expr best_variable = input[0];
Rational best_coefficient = currentMaxCoefficient(best_variable);
output.push_back(best_variable);
for(unsigned int i = 1; i < input.size(); i ++) {
// Get the current variable
Expr current_variable = input[i];
// Get the current variable's max coefficient
Rational current_coefficient = currentMaxCoefficient(current_variable);
// If strictly better than the current best, remember it
if ((current_coefficient < best_coefficient)) {
best_variable = current_variable;
best_coefficient = current_coefficient;
output.clear();
}
// If equal to the current best, push it to the stack (in 10% range)
if (current_coefficient == best_coefficient)
output.push_back(current_variable);
}
// Fix the selected best coefficient
//fixCurrentMaxCoefficient(best_variable, best_coefficient);
}
Expr TheoryArithOld::pickMonomial(const Expr& right)
{
DebugAssert(isPlus(right), "TheoryArithOld::pickMonomial: Wrong Kind: " +
right.toString());
if(theoryCore()->getFlags()["var-order"].getBool()) {
Expr::iterator i = right.begin();
Expr isolatedMonomial = right[1];
//PLUS always has at least two elements and the first element is
//always a constant. hence ++i in the initialization of the for
//loop.
for(++i; i != right.end(); ++i)
if(lessThanVar(isolatedMonomial,*i))
isolatedMonomial = *i;
return isolatedMonomial;
}
ExprMap<Expr> var2monomial;
vector<Expr> vars;
Expr::iterator i = right.begin(), iend = right.end();
for(;i != iend; ++i) {
if(i->isRational())
continue;
Expr c, var;
separateMonomial(*i, c, var);
var2monomial[var] = *i;
vars.push_back(var);
}
vector<Expr> largest;
d_graph.selectLargest(vars, largest);
DebugAssert(0 < largest.size(),
"TheoryArithOld::pickMonomial: selectLargest: failed!!!!");
// DEJAN: Rafine the largest by coefficient values
vector<Expr> largest_small_coeff;
selectSmallestByCoefficient(largest, largest_small_coeff);
DebugAssert(0 < largest_small_coeff.size(), "TheoryArithOld::pickMonomial: selectLargestByCOefficient: failed!!!!");
size_t pickedVar = 0;
// Pick the variable which will generate the fewest number of
// projections
size_t size = largest_small_coeff.size();
int minProjections = -1;
if (size > 1)
for(size_t k=0; k< size; ++k) {
const Expr& var(largest_small_coeff[k]), monom(var2monomial[var]);
// Grab the counters for the variable
int nRight = (d_countRight.count(var) > 0)? d_countRight[var] : 0;
int nLeft = (d_countLeft.count(var) > 0)? d_countLeft[var] : 0;
int n(nRight*nLeft);
TRACE("arith ineq", "pickMonomial: var=", var,
", nRight="+int2string(nRight)+", nLeft="+int2string(nLeft));
if(minProjections < 0 || minProjections > n) {
minProjections = n;
pickedVar = k;
}
TRACE("arith ineq", "Number of projections for "+var.toString()+" = ", n, "");
}
const Expr& largestVar = largest_small_coeff[pickedVar];
// FIXME: TODO: update the counters (subtract counts for the vars
// other than largestVar
// Update the graph (all edges to the largest in the graph, not just the small coefficients).
for(size_t k = 0; k < vars.size(); ++k) {
if(vars[k] != largestVar)
d_graph.addEdge(largestVar, vars[k]);
}
TRACE("arith buffer", "picked var : ", var2monomial[largestVar].toString(), "");
return var2monomial[largestVar];
}
void TheoryArithOld::VarOrderGraph::addEdge(const Expr& e1, const Expr& e2)
{
TRACE("arith var order", "addEdge("+e1.toString()+" > ", e2, ")");
DebugAssert(e1 != e2, "TheoryArithOld::VarOrderGraph::addEdge("
+e1.toString()+", "+e2.toString()+")");
d_edges[e1].push_back(e2);
}
//returns true if e1 < e2, else false(i.e e2 < e1 or e1,e2 are not
//comparable)
bool TheoryArithOld::VarOrderGraph::lessThan(const Expr& e1, const Expr& e2)
{
d_cache.clear();
//returns true if e1 is in the subtree rooted at e2 implying e1 < e2
return dfs(e1,e2);
}
//returns true if e1 is in the subtree rooted at e2 implying e1 < e2
bool TheoryArithOld::VarOrderGraph::dfs(const Expr& e1, const Expr& e2)
{
if(e1 == e2)
return true;
if(d_cache.count(e2) > 0)
return false;
if(d_edges.count(e2) == 0)
return false;
d_cache[e2] = true;
vector<Expr>& e2Edges = d_edges[e2];
vector<Expr>::iterator i = e2Edges.begin();
vector<Expr>::iterator iend = e2Edges.end();
//if dfs finds e1 then i != iend else i is equal to iend
for(; i != iend && !dfs(e1,*i); ++i);
return (i != iend);
}
void TheoryArithOld::VarOrderGraph::dfs(const Expr& v, vector<Expr>& output_list)
{
TRACE("arith shared", "dfs(", v.toString(), ")");
// If visited already we are done
if (d_cache.count(v) > 0) return;
// Dfs further
if(d_edges.count(v) != 0) {
// We have edges, so lets dfs it further
vector<Expr>& vEdges = d_edges[v];
vector<Expr>::iterator e = vEdges.begin();
vector<Expr>::iterator e_end = vEdges.end();
while (e != e_end) {
dfs(*e, output_list);
e ++;
}
}
// Mark as visited and add to the output list
d_cache[v] = true;
output_list.push_back(v);
}
void TheoryArithOld::VarOrderGraph::getVerticesTopological(vector<Expr>& output_list)
{
// Clear the cache
d_cache.clear();
output_list.clear();
// Go through all the vertices and run a dfs from them
ExprMap< vector<Expr> >::iterator v_it = d_edges.begin();
ExprMap< vector<Expr> >::iterator v_it_end = d_edges.end();
while (v_it != v_it_end)
{
// Run dfs from this vertex
dfs(v_it->first, output_list);
// Go to the next one
v_it ++;
}
}
void TheoryArithOld::VarOrderGraph::selectSmallest(vector<Expr>& v1,
vector<Expr>& v2)
{
int v1Size = v1.size();
vector<bool> v3(v1Size);
for(int j=0; j < v1Size; ++j)
v3[j] = false;
for(int j=0; j < v1Size; ++j) {
if(v3[j]) continue;
for(int i =0; i < v1Size; ++i) {
if((i == j) || v3[i])
continue;
if(lessThan(v1[i],v1[j])) {
v3[j] = true;
break;
}
}
}
vector<Expr> new_v1;
for(int j = 0; j < v1Size; ++j)
if(!v3[j]) v2.push_back(v1[j]);
else new_v1.push_back(v1[j]);
v1 = new_v1;
}
void TheoryArithOld::VarOrderGraph::selectLargest(const vector<Expr>& v1,
vector<Expr>& v2)
{
int v1Size = v1.size();
vector<bool> v3(v1Size);
for(int j=0; j < v1Size; ++j)
v3[j] = false;
for(int j=0; j < v1Size; ++j) {
if(v3[j]) continue;
for(int i =0; i < v1Size; ++i) {
if((i == j) || v3[i])
continue;
if(lessThan(v1[j],v1[i])) {
v3[j] = true;
break;
}
}
}
for(int j = 0; j < v1Size; ++j)
if(!v3[j]) v2.push_back(v1[j]);
}
///////////////////////////////////////////////////////////////////////////////
// TheoryArithOld Public Methods //
///////////////////////////////////////////////////////////////////////////////
TheoryArithOld::TheoryArithOld(TheoryCore* core)
: TheoryArith(core, "ArithmeticOld"),
d_diseq(core->getCM()->getCurrentContext()),
d_diseqIdx(core->getCM()->getCurrentContext(), 0, 0),
diseqSplitAlready(core->getCM()->getCurrentContext()),
d_inModelCreation(core->getCM()->getCurrentContext(), false, 0),
d_freeConstDB(core->getCM()->getCurrentContext()),
d_buffer_0(core->getCM()->getCurrentContext()),
d_buffer_1(core->getCM()->getCurrentContext()),
d_buffer_2(core->getCM()->getCurrentContext()),
d_buffer_3(core->getCM()->getCurrentContext()),
// Initialize index to 0 at scope 0
d_bufferIdx_0(core->getCM()->getCurrentContext(), 0, 0),
d_bufferIdx_1(core->getCM()->getCurrentContext(), 0, 0),
d_bufferIdx_2(core->getCM()->getCurrentContext(), 0, 0),
d_bufferIdx_3(core->getCM()->getCurrentContext(), 0, 0),
diff_logic_size(core->getCM()->getCurrentContext(), 0, 0),
d_bufferThres(&(core->getFlags()["ineq-delay"].getInt())),
d_splitSign(&(core->getFlags()["nonlinear-sign-split"].getBool())),
d_grayShadowThres(&(core->getFlags()["grayshadow-threshold"].getInt())),
d_countRight(core->getCM()->getCurrentContext()),
d_countLeft(core->getCM()->getCurrentContext()),
d_sharedTerms(core->getCM()->getCurrentContext()),
d_sharedTermsList(core->getCM()->getCurrentContext()),
d_sharedVars(core->getCM()->getCurrentContext()),
bufferedInequalities(core->getCM()->getCurrentContext()),
termLowerBound(core->getCM()->getCurrentContext()),
termLowerBoundThm(core->getCM()->getCurrentContext()),
termUpperBound(core->getCM()->getCurrentContext()),
termUpperBoundThm(core->getCM()->getCurrentContext()),
alreadyProjected(core->getCM()->getCurrentContext()),
dontBuffer(core->getCM()->getCurrentContext()),
diffLogicOnly(core->getCM()->getCurrentContext(), true, 0),
diffLogicGraph(0, core, 0, core->getCM()->getCurrentContext()),
shared_index_1(core->getCM()->getCurrentContext(), 0, 0),
shared_index_2(core->getCM()->getCurrentContext(), 0, 0),
termUpperBounded(core->getCM()->getCurrentContext()),
termLowerBounded(core->getCM()->getCurrentContext()),
termConstrainedBelow(core->getCM()->getCurrentContext()),
termConstrainedAbove(core->getCM()->getCurrentContext())
{
IF_DEBUG(d_diseq.setName("CDList[TheoryArithOld::d_diseq]");)
IF_DEBUG(d_buffer_0.setName("CDList[TheoryArithOld::d_buffer_0]");)
IF_DEBUG(d_buffer_1.setName("CDList[TheoryArithOld::d_buffer_1]");)
IF_DEBUG(d_buffer_2.setName("CDList[TheoryArithOld::d_buffer_2]");)
IF_DEBUG(d_buffer_3.setName("CDList[TheoryArithOld::d_buffer_3]");)
IF_DEBUG(d_bufferIdx_1.setName("CDList[TheoryArithOld::d_bufferIdx_0]");)
IF_DEBUG(d_bufferIdx_1.setName("CDList[TheoryArithOld::d_bufferIdx_1]");)
IF_DEBUG(d_bufferIdx_2.setName("CDList[TheoryArithOld::d_bufferIdx_2]");)
IF_DEBUG(d_bufferIdx_3.setName("CDList[TheoryArithOld::d_bufferIdx_3]");)
getEM()->newKind(REAL, "_REAL", true);
getEM()->newKind(INT, "_INT", true);
getEM()->newKind(SUBRANGE, "_SUBRANGE", true);
getEM()->newKind(UMINUS, "_UMINUS");
getEM()->newKind(PLUS, "_PLUS");
getEM()->newKind(MINUS, "_MINUS");
getEM()->newKind(MULT, "_MULT");
getEM()->newKind(DIVIDE, "_DIVIDE");
getEM()->newKind(POW, "_POW");
getEM()->newKind(INTDIV, "_INTDIV");
getEM()->newKind(MOD, "_MOD");
getEM()->newKind(LT, "_LT");
getEM()->newKind(LE, "_LE");
getEM()->newKind(GT, "_GT");
getEM()->newKind(GE, "_GE");
getEM()->newKind(IS_INTEGER, "_IS_INTEGER");
getEM()->newKind(NEGINF, "_NEGINF");
getEM()->newKind(POSINF, "_POSINF");
getEM()->newKind(DARK_SHADOW, "_DARK_SHADOW");
getEM()->newKind(GRAY_SHADOW, "_GRAY_SHADOW");
getEM()->newKind(REAL_CONST, "_REAL_CONST");
d_kinds.push_back(REAL);
d_kinds.push_back(INT);
d_kinds.push_back(SUBRANGE);
d_kinds.push_back(IS_INTEGER);
d_kinds.push_back(UMINUS);
d_kinds.push_back(PLUS);
d_kinds.push_back(MINUS);
d_kinds.push_back(MULT);
d_kinds.push_back(DIVIDE);
d_kinds.push_back(POW);
d_kinds.push_back(INTDIV);
d_kinds.push_back(MOD);
d_kinds.push_back(LT);
d_kinds.push_back(LE);
d_kinds.push_back(GT);
d_kinds.push_back(GE);
d_kinds.push_back(RATIONAL_EXPR);
d_kinds.push_back(NEGINF);
d_kinds.push_back(POSINF);
d_kinds.push_back(DARK_SHADOW);
d_kinds.push_back(GRAY_SHADOW);
d_kinds.push_back(REAL_CONST);
registerTheory(this, d_kinds, true);
d_rules = createProofRulesOld();
diffLogicGraph.setRules(d_rules);
diffLogicGraph.setArith(this);
d_realType = Type(getEM()->newLeafExpr(REAL));
d_intType = Type(getEM()->newLeafExpr(INT));
// Make the zero variable
Theorem thm_exists_zero = getCommonRules()->varIntroSkolem(rat(0));
zero = thm_exists_zero.getExpr()[1];
}
// Destructor: delete the proof rules class if it's present
TheoryArithOld::~TheoryArithOld() {
if(d_rules != NULL) delete d_rules;
// Clear the inequality databases
for(ExprMap<CDList<Ineq> *>::iterator i=d_inequalitiesRightDB.begin(),
iend=d_inequalitiesRightDB.end(); i!=iend; ++i) {
delete (i->second);
free(i->second);
}
for(ExprMap<CDList<Ineq> *>::iterator i=d_inequalitiesLeftDB.begin(),
iend=d_inequalitiesLeftDB.end(); i!=iend; ++i) {
delete (i->second);
free (i->second);
}
unregisterTheory(this, d_kinds, true);
}
void TheoryArithOld::collectVars(const Expr& e, vector<Expr>& vars,
set<Expr>& cache) {
// Check the cache first
if(cache.count(e) > 0) return;
// Not processed yet. Cache the expression and proceed
cache.insert(e);
if(isLeaf(e)) vars.push_back(e);
else
for(Expr::iterator i=e.begin(), iend=e.end(); i!=iend; ++i)
collectVars(*i, vars, cache);
}
void
TheoryArithOld::processFiniteInterval
(const Theorem& alphaLEax,
const Theorem& bxLEbeta) {
const Expr& ineq1(alphaLEax.getExpr());
const Expr& ineq2(bxLEbeta.getExpr());
DebugAssert(isLE(ineq1), "TheoryArithOld::processFiniteInterval: ineq1 = "
+ineq1.toString());
DebugAssert(isLE(ineq2), "TheoryArithOld::processFiniteInterval: ineq2 = "
+ineq2.toString());
// If the inequalities are not integer, just return (nothing to do)
if(!isInteger(ineq1[0])
|| !isInteger(ineq1[1])
|| !isInteger(ineq2[0])
|| !isInteger(ineq2[1]))
return;
const Expr& ax = ineq1[1];
const Expr& bx = ineq2[0];
DebugAssert(!isPlus(ax) && !isRational(ax),
"TheoryArithOld::processFiniteInterval:\n ax = "+ax.toString());
DebugAssert(!isPlus(bx) && !isRational(bx),
"TheoryArithOld::processFiniteInterval:\n bx = "+bx.toString());
Expr a = isMult(ax)? ax[0] : rat(1);
Expr b = isMult(bx)? bx[0] : rat(1);
Theorem thm1(alphaLEax), thm2(bxLEbeta);
// Multiply the inequalities by 'b' and 'a', and canonize them, if necessary
if(a != b) {
thm1 = canonPred(iffMP(alphaLEax, d_rules->multIneqn(ineq1, b)));
thm2 = canonPred(iffMP(bxLEbeta, d_rules->multIneqn(ineq2, a)));
}
// Check that a*beta - b*alpha == c > 0
const Expr& alphaLEt = thm1.getExpr();
const Expr& alpha = alphaLEt[0];
const Expr& t = alphaLEt[1];
const Expr& beta = thm2.getExpr()[1];
Expr c = canon(beta - alpha).getRHS();
if(c.isRational() && c.getRational() >= 1) {
// This is a finite interval. First, derive t <= alpha + c:
// canon(alpha+c) => (alpha+c == beta) ==> [symmetry] beta == alpha+c
// Then substitute that in thm2
Theorem bEQac = symmetryRule(canon(alpha + c));
// Substitute beta == alpha+c for the second child of thm2
vector<unsigned> changed;
vector<Theorem> thms;
changed.push_back(1);
thms.push_back(bEQac);
Theorem tLEac = substitutivityRule(thm2.getExpr(), changed, thms);
tLEac = iffMP(thm2, tLEac);
// Derive and enqueue the finite interval constraint
Theorem isInta(isIntegerThm(alpha));
Theorem isIntt(isIntegerThm(t));
if (d_sharedTerms.find(thm1.getExpr()[1]) != d_sharedTerms.end())
enqueueFact(d_rules->finiteInterval(thm1, tLEac, isInta, isIntt));
}
}
void
TheoryArithOld::processFiniteIntervals(const Expr& x) {
// If x is not integer, do not bother
if(!isInteger(x)) return;
// Process every pair of the opposing inequalities for 'x'
ExprMap<CDList<Ineq> *>::iterator iLeft, iRight;
iLeft = d_inequalitiesLeftDB.find(x);
if(iLeft == d_inequalitiesLeftDB.end()) return;
iRight = d_inequalitiesRightDB.find(x);
if(iRight == d_inequalitiesRightDB.end()) return;
// There are some opposing inequalities; get the lists
CDList<Ineq>& ineqsLeft = *(iLeft->second);
CDList<Ineq>& ineqsRight = *(iRight->second);
// Get the sizes of the lists
size_t sizeLeft = ineqsLeft.size();
size_t sizeRight = ineqsRight.size();
// Process all the pairs of the opposing inequalities
for(size_t l=0; l<sizeLeft; ++l)
for(size_t r=0; r<sizeRight; ++r)
processFiniteInterval(ineqsRight[r], ineqsLeft[l]);
}
/*! This function recursively decends expression tree <strong>without
* caching</strong> until it hits a node that is already setup. Be
* careful on what expressions you are calling it.
*/
void
TheoryArithOld::setupRec(const Expr& e) {
if(e.hasFind()) return;
// First, set up the kids recursively
for (int k = 0; k < e.arity(); ++k) {
setupRec(e[k]);
}
// Create a find pointer for e
e.setFind(reflexivityRule(e));
e.setEqNext(reflexivityRule(e));
// And call our own setup()
setup(e);
}
void TheoryArithOld::addSharedTerm(const Expr& e) {
return;
if (d_sharedTerms.find(e) == d_sharedTerms.end()) {
d_sharedTerms[e] = true;
d_sharedTermsList.push_back(e);
}
}
void TheoryArithOld::assertFact(const Theorem& e)
{
TRACE("arith assert", "assertFact(", e.getExpr().toString(), ")");
// Pick up any multiplicative case splits and enqueue them
for (unsigned i = 0; i < multiplicativeSignSplits.size(); i ++)
enqueueFact(multiplicativeSignSplits[i]);
multiplicativeSignSplits.clear();
const Expr& expr = e.getExpr();
if (expr.isNot() && expr[0].isEq()) {
IF_DEBUG(debugger.counter("[arith] received disequalities")++;)
// Expr eq = expr[0];
//
// // We want to expand on difference logic disequalities as soon as possible
// bool diff_logic = false;
// if (eq[1].isRational() && eq[1].getRational() == 0) {
// if (!isPlus(eq[0])) {
// if (isLeaf(eq[0])) diff_logic = true;
// }
// else {
// int arity = eq[0].arity();
// if (arity <= 2) {
// if (eq[0][0].isRational())
// diff_logic = true;
// else {
// Expr ax = eq[0][0], a, x;
// Expr by = eq[0][1], b, y;
// separateMonomial(ax, a, x);
// separateMonomial(by, b, y);
// if (isLeaf(x) && isLeaf(y))
// if ((a.getRational() == 1 && b.getRational() == -1) ||
// (a.getRational() == -1 && b.getRational() == 1))
// diff_logic = true;
// }
// }
// if (arity == 3 && eq[0][0].isRational()) {
// Expr ax = eq[0][1], a, x;
// Expr by = eq[0][2], b, y;
// separateMonomial(ax, a, x);
// separateMonomial(by, b, y);
// if (isLeaf(x) && isLeaf(y))
// if ((a.getRational() == 1 && b.getRational() == -1) ||
// (a.getRational() == -1 && b.getRational() == 1))
// diff_logic = true;
// }
// }
// }
//
// if (diff_logic)
// enqueueFact(d_rules->diseqToIneq(e));
// else
d_diseq.push_back(e);
}
else if (!expr.isEq()){
if (expr.isNot()) {
// If expr[0] is asserted to *not* be an integer, we track it
// so we will detect if it ever becomes equal to an integer.
if (expr[0].getKind() == IS_INTEGER) {
expr[0][0].addToNotify(this, expr[0]);
}
// This can only be negation of dark or gray shadows, or
// disequalities, which we ignore. Negations of inequalities
// are handled in rewrite, we don't even receive them here.
// if (isGrayShadow(expr[0])) {
// TRACE("arith gray", "expanding ", expr.toString(), "");
// Theorem expand = d_rules->expandGrayShadowRewrite(expr[0]);
// enqueueFact(iffMP(e, substitutivityRule(expr, 0, expand)));
// }
}
else if(isDarkShadow(expr)) {
enqueueFact(d_rules->expandDarkShadow(e));
IF_DEBUG(debugger.counter("received DARK_SHADOW")++;)
}
else if(isGrayShadow(expr)) {
IF_DEBUG(debugger.counter("received GRAY_SHADOW")++;)
const Rational& c1 = expr[2].getRational();
const Rational& c2 = expr[3].getRational();
// If gray shadow bigger than the treshold, we are done
if (*d_grayShadowThres > -1 && (c2 - c1 > *d_grayShadowThres)) {
setIncomplete("Some gray shadows ignored due to threshold");
return;
}
const Expr& v = expr[0];
const Expr& ee = expr[1];
if(c1 == c2)
enqueueFact(d_rules->expandGrayShadow0(e));
else {
Theorem gThm(e);
// Check if we can reduce the number of cases in G(ax,c,c1,c2)
if(ee.isRational() && isMult(v)
&& v[0].isRational() && v[0].getRational() >= 2) {
IF_DEBUG(debugger.counter("reduced const GRAY_SHADOW")++;)
gThm = d_rules->grayShadowConst(e);
}
// (Possibly) new gray shadow
const Expr& g = gThm.getExpr();
if(g.isFalse())
setInconsistent(gThm);
else if(g[2].getRational() == g[3].getRational())
enqueueFact(d_rules->expandGrayShadow0(gThm));
else if(g[3].getRational() - g[2].getRational() <= 5) {
// Assert c1+e <= v <= c2+e
enqueueFact(d_rules->expandGrayShadow(gThm));
// Split G into 2 cases x = l_bound and the other
Theorem thm2 = d_rules->splitGrayShadowSmall(gThm);
enqueueFact(thm2);
}
else {
// Assert c1+e <= v <= c2+e
enqueueFact(d_rules->expandGrayShadow(gThm));
// Split G into 2 cases (binary search b/w c1 and c2)
Theorem thm2 = d_rules->splitGrayShadow(gThm);
enqueueFact(thm2);
// Fetch the two gray shadows
// DebugAssert(thm2.getExpr().isAnd() && thm2.getExpr().arity()==2,
// "thm2 = "+thm2.getExpr().toString());
// const Expr& G1orG2 = thm2.getExpr()[0];
// DebugAssert(G1orG2.isOr() && G1orG2.arity()==2,
// "G1orG2 = "+G1orG2.toString());
// const Expr& G1 = G1orG2[0];
// const Expr& G2 = G1orG2[1];
// DebugAssert(G1.getKind()==GRAY_SHADOW, "G1 = "+G1.toString());
// DebugAssert(G2.getKind()==GRAY_SHADOW, "G2 = "+G2.toString());
// // Split on the left disjunct first (keep the priority low)
// Expr tmp = simplifyExpr(G1);
// if (!tmp.isBoolConst())
// addSplitter(tmp, 1);
// tmp = simplifyExpr(G2);
// if (!tmp.isBoolConst())
// addSplitter(tmp, -1);
}
}
}
else {
DebugAssert(isLE(expr) || isLT(expr) || isIntPred(expr),
"expected LE or LT: "+expr.toString());
if(isLE(expr) || isLT(expr)) {
IF_DEBUG(debugger.counter("recevied inequalities")++;)
// // Assert the equivalent negated inequality
// Theorem thm;
// if (isLE(expr)) thm = d_rules->negatedInequality(!gtExpr(expr[0],expr[1]));
// else thm = d_rules->negatedInequality(!geExpr(expr[0],expr[1]));
// thm = symmetryRule(thm);
// Theorem thm2 = simplify(thm.getRHS()[0]);
// DebugAssert(thm2.getLHS() != thm2.getRHS(), "Expected rewrite");
// thm2 = getCommonRules()->substitutivityRule(thm.getRHS(), thm2);
// thm = transitivityRule(thm, thm2);
// enqueueFact(iffMP(e, thm));
// Buffer the inequality
addToBuffer(e);
unsigned total_buf_size = d_buffer_0.size() + d_buffer_1.size() + d_buffer_2.size() + d_buffer_3.size();
unsigned processed = d_bufferIdx_0 + d_bufferIdx_1 + d_bufferIdx_2 + d_bufferIdx_3;
TRACE("arith ineq", "buffer.size() = ", total_buf_size,
", index="+int2string(processed)
+", threshold="+int2string(*d_bufferThres));
if(!diffLogicOnly && *d_bufferThres >= 0 && (total_buf_size > *d_bufferThres + processed) && !d_inModelCreation) {
processBuffer();
}
} else {
IF_DEBUG(debugger.counter("arith IS_INTEGER")++;)
if (!isInteger(expr[0])) {
enqueueFact(d_rules->IsIntegerElim(e));
}
}
}
}
else {
IF_DEBUG(debugger.counter("[arith] received t1=t2")++;)
// const Expr lhs = e.getExpr()[0];
// const Expr rhs = e.getExpr()[1];
//
// CDMap<Expr, Rational>::iterator l_bound_find = termLowerBound[lhs];
// if (l_bound_find != termLowerBound.end()) {
// Rational lhs_bound = (*l_bound_find).second;
// CDMap<Expr, Rational>::iterator l_bound_find_rhs = termLowerBound[rhs];
// if (l_bound_find_rhs != termLowerBound.end()) {
//
// } else {
// // Add the new bound for the rhs
// termLowerBound[rhs] = lhs_bound;
// termLowerBoundThm =
// }
//
// }
}
}
void TheoryArithOld::checkSat(bool fullEffort)
{
// vector<Expr>::const_iterator e;
// vector<Expr>::const_iterator eEnd;
// TODO: convert back to use iterators
TRACE("arith checksat", "checksat(fullEffort = ", fullEffort? "true, modelCreation = " : "false, modelCreation = ", (d_inModelCreation ? "true)" : "false)"));
TRACE("arith ineq", "TheoryArithOld::checkSat(fullEffort=",
fullEffort? "true" : "false", ")");
if (fullEffort) {
// Process the buffer if necessary
if (!inconsistent())
processBuffer();
// Expand the needded inequalitites
int total_buffer_size = d_buffer_0.size() + d_buffer_1.size() + d_buffer_2.size() + d_buffer_3.size();
int constrained_vars = 0;
if (!inconsistent() && total_buffer_size > 0)
constrained_vars = computeTermBounds();
bool something_enqueued = false;
if (d_inModelCreation || (!inconsistent() && total_buffer_size > 0 && constrained_vars > 0)) {
// If in model creation we might have to reconsider some of the dis-equalities
if (d_inModelCreation) d_diseqIdx = 0;
// Now go and try to split
for(; d_diseqIdx < d_diseq.size(); d_diseqIdx = d_diseqIdx+1) {
TRACE("model", "[arith] refining diseq: ", d_diseq[d_diseqIdx].getExpr() , "");
// Get the disequality theorem and the expression
Theorem diseqThm = d_diseq[d_diseqIdx];
Expr diseq = diseqThm.getExpr();
// If we split on this one already
if (diseqSplitAlready.find(diseq) != diseqSplitAlready.end()) continue;
// Get the equality
Expr eq = diseq[0];
// Get the left-hand-side and the right-hands side
Expr lhs = eq[0];
Expr rhs = eq[1];
DebugAssert(lhs.hasFind() && rhs.hasFind(), "Part of dis-equality has no find!");
lhs = find(lhs).getRHS();
rhs = find(rhs).getRHS();
// If the value of the equality is already determined by instantiation, we just skip it
// This can happen a lot as we infer equalities in difference logic
if (lhs.isRational() && rhs.isRational()) {
TRACE("arith diseq", "disequality already evaluated : ", diseq.toString(), "");
continue;
}
// We can allow ourselfs not to care about specific values if we are
// not in model creation
if (!d_inModelCreation) {
// If the left or the right hand side is unbounded, we don't care right now
if (!isConstrained(lhs) || !isConstrained(rhs)) continue;
if (getUpperBound(lhs) < getLowerBound(rhs)) continue;
if (getUpperBound(rhs) < getLowerBound(lhs)) continue;
}
TRACE("arith ineq", "[arith] refining diseq: ", d_diseq[d_diseqIdx].getExpr() , "");
// We don't know the value of the disequlaity, split on it (for now)
enqueueFact(d_rules->diseqToIneq(diseqThm));
something_enqueued = true;
// Mark it as split already
diseqSplitAlready[diseq] = true;
}
}
IF_DEBUG(
{
bool dejans_printouts = false;
if (dejans_printouts) {
cerr << "Disequalities after CheckSat" << endl;
for (unsigned i = 0; i < d_diseq.size(); i ++) {
Expr diseq = d_diseq[i].getExpr();
Expr d_find = find(diseq[0]).getRHS();
cerr << diseq.toString() << ":" << d_find.toString() << endl;
}
cerr << "Arith Buffer after CheckSat (0)" << endl;
for (unsigned i = 0; i < d_buffer_0.size(); i ++) {
Expr ineq = d_buffer_0[i].getExpr();
Expr rhs = find(ineq[1]).getRHS();
cerr << ineq.toString() << ":" << rhs.toString() << endl;
}
cerr << "Arith Buffer after CheckSat (1)" << endl;
for (unsigned i = 0; i < d_buffer_1.size(); i ++) {
Expr ineq = d_buffer_1[i].getExpr();
Expr rhs = find(ineq[1]).getRHS();
cerr << ineq.toString() << ":" << rhs.toString() << endl;
}
cerr << "Arith Buffer after CheckSat (2)" << endl;
for (unsigned i = 0; i < d_buffer_2.size(); i ++) {
Expr ineq = d_buffer_2[i].getExpr();
Expr rhs = find(ineq[1]).getRHS();
cerr << ineq.toString() << ":" << rhs.toString() << endl;
}
cerr << "Arith Buffer after CheckSat (3)" << endl;
for (unsigned i = 0; i < d_buffer_3.size(); i ++) {
Expr ineq = d_buffer_3[i].getExpr();
Expr rhs = find(ineq[1]).getRHS();
cerr << ineq.toString() << ":" << rhs.toString() << endl;
}
}
}
)
}
}
void TheoryArithOld::refineCounterExample()
{
d_inModelCreation = true;
TRACE("model", "refineCounterExample[TheoryArithOld] ", "", "{");
CDMap<Expr, bool>::iterator it = d_sharedTerms.begin(), it2,
iend = d_sharedTerms.end();
// Add equalities over all pairs of shared terms as suggested
// splitters. Notice, that we want to split on equality
// (positively) first, to reduce the size of the model.
for(; it!=iend; ++it) {
// Copy by value: the elements in the pair from *it are NOT refs in CDMap
Expr e1 = (*it).first;
for(it2 = it, ++it2; it2!=iend; ++it2) {
Expr e2 = (*it2).first;
DebugAssert(isReal(getBaseType(e1)),
"TheoryArithOld::refineCounterExample: e1 = "+e1.toString()
+"\n type(e1) = "+e1.getType().toString());
if(findExpr(e1) != findExpr(e2)) {
DebugAssert(isReal(getBaseType(e2)),
"TheoryArithOld::refineCounterExample: e2 = "+e2.toString()
+"\n type(e2) = "+e2.getType().toString());
Expr eq = simplifyExpr(e1.eqExpr(e2));
if (!eq.isBoolConst()) {
addSplitter(eq);
}
}
}
}
TRACE("model", "refineCounterExample[Theory::Arith] ", "", "}");
}
void
TheoryArithOld::findRationalBound(const Expr& varSide, const Expr& ratSide,
const Expr& var,
Rational &r)
{
Expr c, x;
separateMonomial(varSide, c, x);
if (!findExpr(ratSide).isRational() && isNonlinearEq(ratSide.eqExpr(rat(0))))
throw ArithException("Could not generate the model due to non-linear arithmetic");
DebugAssert(findExpr(c).isRational(),
"seperateMonomial failed");
DebugAssert(findExpr(ratSide).isRational(),
"smallest variable in graph, should not have variables"
" in inequalities: ");
DebugAssert(x == var, "separateMonomial found different variable: "
+ var.toString());
r = findExpr(ratSide).getRational() / findExpr(c).getRational();
}
bool
TheoryArithOld::findBounds(const Expr& e, Rational& lub, Rational& glb)
{
bool strictLB=false, strictUB=false;
bool right = (d_inequalitiesRightDB.count(e) > 0
&& d_inequalitiesRightDB[e]->size() > 0);
bool left = (d_inequalitiesLeftDB.count(e) > 0
&& d_inequalitiesLeftDB[e]->size() > 0);
int numRight = 0, numLeft = 0;
if(right) { //rationals less than e
CDList<Ineq> * ratsLTe = d_inequalitiesRightDB[e];
for(unsigned int i=0; i<ratsLTe->size(); i++) {
DebugAssert((*ratsLTe)[i].varOnRHS(), "variable on wrong side!");
Expr ineq = (*ratsLTe)[i].ineq().getExpr();
Expr leftSide = ineq[0], rightSide = ineq[1];
Rational r;
findRationalBound(rightSide, leftSide, e , r);
if(numRight==0 || r>glb){
glb = r;
strictLB = isLT(ineq);
}
numRight++;
}
TRACE("model", " =>Lower bound ", glb.toString(), "");
}
if(left) { //rationals greater than e
CDList<Ineq> * ratsGTe = d_inequalitiesLeftDB[e];
for(unsigned int i=0; i<ratsGTe->size(); i++) {
DebugAssert((*ratsGTe)[i].varOnLHS(), "variable on wrong side!");
Expr ineq = (*ratsGTe)[i].ineq().getExpr();
Expr leftSide = ineq[0], rightSide = ineq[1];
Rational r;
findRationalBound(leftSide, rightSide, e, r);
if(numLeft==0 || r<lub) {
lub = r;
strictUB = isLT(ineq);
}
numLeft++;
}
TRACE("model", " =>Upper bound ", lub.toString(), "");
}
if(!left && !right) {
lub = 0;
glb = 0;
}
if(!left && right) {lub = glb +2;}
if(!right && left) {glb = lub-2;}
DebugAssert(glb <= lub, "Greatest lower bound needs to be smaller "
"than least upper bound");
return strictLB;
}
void TheoryArithOld::assignVariables(std::vector<Expr>&v)
{
int count = 0;
if (diffLogicOnly)
{
// Compute the model
diffLogicGraph.computeModel();
// Get values for the variables
for (unsigned i = 0; i < v.size(); i ++) {
Expr x = v[i];
assignValue(x, rat(diffLogicGraph.getValuation(x)));
}
// Done
return;
}
while (v.size() > 0)
{
std::vector<Expr> bottom;
d_graph.selectSmallest(v, bottom);
TRACE("model", "Finding variables to assign. Iteration # ", count, "");
for(unsigned int i = 0; i<bottom.size(); i++)
{
Expr e = bottom[i];
TRACE("model", "Found: ", e, "");
// Check if it is already a concrete constant
if(e.isRational()) continue;
Rational lub, glb;
bool strictLB;
strictLB = findBounds(e, lub, glb);
Rational mid;
if(isInteger(e)) {
if(strictLB && glb.isInteger())
mid = glb + 1;
else
mid = ceil(glb);
}
else
mid = (lub + glb)/2;
TRACE("model", "Assigning mid = ", mid, " {");
assignValue(e, rat(mid));
TRACE("model", "Assigned find(e) = ", findExpr(e), " }");
if(inconsistent()) return; // Punt immediately if failed
}
count++;
}
}
void TheoryArithOld::computeModelBasic(const std::vector<Expr>& v)
{
d_inModelCreation = true;
vector<Expr> reps;
TRACE("model", "Arith=>computeModel ", "", "{");
for(unsigned int i=0; i <v.size(); ++i) {
const Expr& e = v[i];
if(findExpr(e) == e) {
TRACE("model", "arith variable:", e , "");
reps.push_back(e);
}
else {
TRACE("model", "arith variable:", e , "");
TRACE("model", " ==> is defined by: ", findExpr(e) , "");
}
}
assignVariables(reps);
TRACE("model", "Arith=>computeModel", "", "}");
d_inModelCreation = false;
}
// For any arith expression 'e', if the subexpressions are assigned
// concrete values, then find(e) must already be a concrete value.
void TheoryArithOld::computeModel(const Expr& e, vector<Expr>& vars) {
DebugAssert(findExpr(e).isRational(), "TheoryArithOld::computeModel("
+e.toString()+")\n e is not assigned concrete value.\n"
+" find(e) = "+findExpr(e).toString());
assignValue(simplify(e));
vars.push_back(e);
}
Theorem TheoryArithOld::checkIntegerEquality(const Theorem& thm) {
// Check if this is a rewrite theorem
bool rewrite = thm.isRewrite();
// If it's an integer theorem, then rafine it to integer domain
Expr eq = (rewrite ? thm.getRHS() : thm.getExpr());
TRACE("arith rafine", "TheoryArithOld::checkIntegerEquality(", eq, ")");
DebugAssert(eq.getKind() == EQ, "checkIntegerEquality: must be an equality");
// Trivial equalities, we don't care
if (!isPlus(eq[1]) && !isPlus(eq[0])) return thm;
Expr old_sum = (isPlus(eq[1]) ? eq[1] : eq[0]);
// Get the sum part
vector<Expr> children;
bool const_is_integer = true; // Assuming only one constant is present (canon called before this)
for (int i = 0; i < old_sum.arity(); i ++)
if (!old_sum[i].isRational())
children.push_back(old_sum[i]);
else
const_is_integer = old_sum[i].getRational().isInteger();
// If the constants are integers, we don't care
if (const_is_integer) return thm;
Expr sum = (children.size() > 1 ? plusExpr(children) : children[0]);
// Check for integer of the remainder of the sum
Theorem isIntegerEquality = isIntegerThm(sum);
// If it is an integer, it's unsat
if (!isIntegerEquality.isNull()) {
Theorem false_thm = d_rules->intEqualityRationalConstant(isIntegerEquality, eq);
if (rewrite) return transitivityRule(thm, false_thm);
else return iffMP(thm, false_thm);
}
else return thm;
}
Theorem TheoryArithOld::rafineInequalityToInteger(const Theorem& thm) {
// Check if this is a rewrite theorem
bool rewrite = thm.isRewrite();
// If it's an integer theorem, then rafine it to integer domain
Expr ineq = (rewrite ? thm.getRHS() : thm.getExpr());
TRACE("arith rafine", "TheoryArithOld::rafineInequalityToInteger(", ineq, ")");
DebugAssert(isIneq(ineq), "rafineInequalityToInteger: must be an inequality");
// Trivial inequalities are rafined
// if (!isPlus(ineq[1])) return thm;
// Get the sum part
vector<Expr> children;
if (isPlus(ineq[1])) {
for (int i = 0; i < ineq[1].arity(); i ++)
if (!ineq[1][i].isRational())
children.push_back(ineq[1][i]);
} else children.push_back(ineq[1]);
Expr sum = (children.size() > 1 ? plusExpr(children) : children[0]);
// Check for integer of the remainder of the sum
Theorem isIntegerInequality = isIntegerThm(sum);
// If it is an integer, do rafine it
if (!isIntegerInequality.isNull()) {
Theorem rafine = d_rules->rafineStrictInteger(isIntegerInequality, ineq);
TRACE("arith rafine", "TheoryArithOld::rafineInequalityToInteger()", "=>", rafine.getRHS());
if (rewrite) return canonPredEquiv(transitivityRule(thm, rafine));
else return canonPred(iffMP(thm, rafine));
}
else return thm;
}
/*! accepts a rewrite theorem over eqn|ineqn and normalizes it
* and returns a theorem to that effect. assumes e is non-trivial
* i.e. e is not '0=const' or 'const=0' or '0 <= const' etc.
*/
Theorem TheoryArithOld::normalize(const Expr& e) {
//e is an eqn or ineqn. e is not a trivial eqn or ineqn
//trivial means 0 = const or 0 <= const.
TRACE("arith normalize", "normalize(", e, ") {");
DebugAssert(e.isEq() || isIneq(e),
"normalize: input must be Eq or Ineq: " + e.toString());
DebugAssert(!isIneq(e) || (0 == e[0].getRational()),
"normalize: if (e is ineq) then e[0] must be 0" +
e.toString());
if(e.isEq()) {
if(e[0].isRational()) {
DebugAssert(0 == e[0].getRational(),
"normalize: if e is Eq and e[0] is rat then e[0]==0");
}
else {
//if e[0] is not rational then e[1] must be rational.
DebugAssert(e[1].isRational() && 0 == e[1].getRational(),
"normalize: if e is Eq and e[1] is rat then e[1]==0\n"
" e = "+e.toString());
}
}
Expr factor;
if(e[0].isRational())
factor = computeNormalFactor(e[1], false);
else
factor = computeNormalFactor(e[0], false);
TRACE("arith normalize", "normalize: factor = ", factor, "");
DebugAssert(factor.getRational() > 0,
"normalize: factor="+ factor.toString());
Theorem thm(reflexivityRule(e));
// Now multiply the equality by the factor, unless it is 1
if(factor.getRational() != 1) {
int kind = e.getKind();
switch(kind) {
case EQ:
//TODO: DEJAN FIX
thm = d_rules->multEqn(e[0], e[1], factor);
// And canonize the result
thm = canonPredEquiv(thm);
// If this is an equation of the form 0 = c + sum, c is not integer, but sum is
// then equation has no solutions
thm = checkIntegerEquality(thm);
break;
case LE:
case LT:
case GE:
case GT: {
thm = d_rules->multIneqn(e, factor);
// And canonize the result
thm = canonPredEquiv(thm);
// Try to rafine to integer domain
thm = rafineInequalityToInteger(thm);
break;
}
default:
// MS .net doesn't accept "..." + int
ostringstream ss;
ss << "normalize: control should not reach here " << kind;
DebugAssert(false, ss.str());
break;
}
} else
if (e.getKind() == EQ)
thm = checkIntegerEquality(thm);
TRACE("arith normalize", "normalize => ", thm, " }");
return(thm);
}
Theorem TheoryArithOld::normalize(const Theorem& eIffEqn) {
if (eIffEqn.isRewrite()) return transitivityRule(eIffEqn, normalize(eIffEqn.getRHS()));
else return iffMP(eIffEqn, normalize(eIffEqn.getExpr()));
}
Theorem TheoryArithOld::rewrite(const Expr& e)
{
DebugAssert(leavesAreSimp(e), "Expected leaves to be simplified");
TRACE("arith", "TheoryArithOld::rewrite(", e, ") {");
Theorem thm;
if (!e.isTerm()) {
if (!e.isAbsLiteral()) {
if (e.isPropAtom() && leavesAreNumConst(e)) {
if (e.getSize() < 200) {
Expr eNew = e;
thm = reflexivityRule(eNew);
while (eNew.containsTermITE()) {
thm = transitivityRule(thm, getCommonRules()->liftOneITE(eNew));
DebugAssert(!thm.isRefl(), "Expected non-reflexive");
thm = transitivityRule(thm, theoryCore()->getCoreRules()->rewriteIteCond(thm.getRHS()));
thm = transitivityRule(thm, simplify(thm.getRHS()));
eNew = thm.getRHS();
}
}
else {
thm = d_rules->rewriteLeavesConst(e);
if (thm.isRefl()) {
e.setRewriteNormal();
}
else {
thm = transitivityRule(thm, simplify(thm.getRHS()));
}
}
// if (!thm.getRHS().isBoolConst()) {
// e.setRewriteNormal();
// thm = reflexivityRule(e);
// }
}
else {
e.setRewriteNormal();
thm = reflexivityRule(e);
}
TRACE("arith", "TheoryArithOld::rewrite[non-literal] => ", thm, " }");
return thm;
}
switch(e.getKind()) {
case EQ:
{
// canonical form for an equality of two leaves
// is just l == r instead of 0 + (-1 * l) + r = 0.
if (isLeaf(e[0]) && isLeaf(e[1]))
thm = reflexivityRule(e);
else { // Otherwise, it is "lhs = 0"
//first convert e to the form 0=e'
if((e[0].isRational() && e[0].getRational() == 0)
|| (e[1].isRational() && e[1].getRational() == 0))
//already in 0=e' or e'=0 form
thm = reflexivityRule(e);
else {
thm = d_rules->rightMinusLeft(e);
thm = canonPredEquiv(thm);
}
// Check for trivial equation
if ((thm.getRHS())[0].isRational() && (thm.getRHS())[1].isRational()) {
thm = transitivityRule(thm, d_rules->constPredicate(thm.getRHS()));
} else {
//else equation is non-trivial
thm = normalize(thm);
// Normalization may yield non-simplified terms
if (!thm.getRHS().isBoolConst())
thm = canonPredEquiv(thm);
}
}
// Equations must be oriented such that lhs >= rhs as Exprs;
// this ordering is given by operator<(Expr,Expr).
const Expr& eq = thm.getRHS();
if(eq.isEq() && eq[0] < eq[1])
thm = transitivityRule(thm, getCommonRules()->rewriteUsingSymmetry(eq));
// Check if the equation is nonlinear
Expr nonlinearEq = thm.getRHS();
if (nonlinearEq.isEq() && isNonlinearEq(nonlinearEq)) {
TRACE("arith nonlinear", "nonlinear eq rewrite: ", nonlinearEq, "");
Expr left = nonlinearEq[0];
Expr right = nonlinearEq[1];
// Check for multiplicative equations, i.e. x*y = 0
if (isNonlinearSumTerm(left) && right.isRational() && right.getRational() == 0) {
Theorem eq_thm = d_rules->multEqZero(nonlinearEq);
thm = transitivityRule(thm, eq_thm);
thm = transitivityRule(thm, theoryCore()->simplify(thm.getRHS()));
break;
}
// Heuristics for a sum
if (isPlus(left)) {
// Search for common factor
if (left[0].getRational() == 0) {
Expr::iterator i = left.begin(), iend = left.end();
++ i;
set<Expr> factors;
set<Expr>::iterator is, isend;
getFactors(*i, factors);
for (++i; i != iend; ++i) {
set<Expr> factors2;
getFactors(*i, factors2);
for (is = factors.begin(), isend = factors.end(); is != isend;) {
if (factors2.find(*is) == factors2.end()) {
factors.erase(is ++);
} else
++ is;
}
if (factors.empty()) break;
}
if (!factors.empty()) {
thm = transitivityRule(thm, d_rules->divideEqnNonConst(left, rat(0), *(factors.begin())));
// got (factor != 0) OR (left / factor = right / factor), need to simplify
thm = transitivityRule(thm, simplify(thm.getRHS()));
TRACE("arith nonlinear", "nonlinear eq rewrite (factoring): ", thm.getRHS(), "");
break;
}
}
// Look for equal powers (eq in the form of c + pow1 - pow2 = 0)
Rational constant;
Expr power1;
Expr power2;
if (isPowersEquality(nonlinearEq, power1, power2)) {
// Eliminate the powers
thm = transitivityRule(thm, d_rules->elimPower(nonlinearEq));
thm = transitivityRule(thm, simplify(thm.getRHS()));
TRACE("arith nonlinear", "nonlinear eq rewrite (equal powers): ", thm.getRHS(), "");
break;
} else
// Look for one power equality (c - pow = 0);
if (isPowerEquality(nonlinearEq, constant, power1)) {
Rational pow1 = power1[0].getRational();
if (pow1 % 2 == 0 && constant < 0) {
thm = transitivityRule(thm, d_rules->evenPowerEqNegConst(nonlinearEq));
TRACE("arith nonlinear", "nonlinear eq rewrite (even power = negative): ", thm.getRHS(), "");
break;
}
DebugAssert(constant != 0, "Expected nonzero const");
Rational root = ratRoot(constant, pow1.getUnsigned());
if (root != 0) {
thm = transitivityRule(thm, d_rules->elimPowerConst(nonlinearEq, root));
thm = transitivityRule(thm, simplify(thm.getRHS()));
TRACE("arith nonlinear", "nonlinear eq rewrite (rational root): ", thm.getRHS(), "");
break;
} else {
Theorem isIntPower(isIntegerThm(left));
if (!isIntPower.isNull()) {
thm = transitivityRule(thm, d_rules->intEqIrrational(nonlinearEq, isIntPower));
TRACE("arith nonlinear", "nonlinear eq rewrite (irational root): ", thm.getRHS(), "");
break;
}
}
}
}
// Non-solvable nonlinear equations are rewritten as conjunction of inequalities
if (!canPickEqMonomial(nonlinearEq[0])) {
thm = transitivityRule(thm, d_rules->eqToIneq(nonlinearEq));
thm = transitivityRule(thm, simplify(thm.getRHS()));
TRACE("arith nonlinear", "nonlinear eq rewrite (not solvable): ", thm.getRHS(), "");
break;
}
}
}
break;
case GRAY_SHADOW:
case DARK_SHADOW:
thm = reflexivityRule(e);
break;
case IS_INTEGER: {
Theorem res(isIntegerDerive(e, typePred(e[0])));
if(!res.isNull())
thm = getCommonRules()->iffTrue(res);
else
thm = reflexivityRule(e);
break;
}
case NOT:
if (!isIneq(e[0]))
//in this case we have "NOT of DARK or GRAY_SHADOW."
thm = reflexivityRule(e);
else {
//In this case we have the "NOT of ineq". get rid of NOT
//and then treat like an ineq
thm = d_rules->negatedInequality(e);
DebugAssert(isGE(thm.getRHS()) || isGT(thm.getRHS()),
"Expected GE or GT");
thm = transitivityRule(thm, d_rules->flipInequality(thm.getRHS()));
thm = transitivityRule(thm, d_rules->rightMinusLeft(thm.getRHS()));
thm = canonPredEquiv(thm);
// If the inequality is strict and integer, change it to non-strict
Expr theIneq = thm.getRHS();
if(isLT(theIneq)) {
// Check if integer
Theorem isIntLHS(isIntegerThm(theIneq[0]));
Theorem isIntRHS(isIntegerThm(theIneq[1]));
bool isInt = (!isIntLHS.isNull() && !isIntRHS.isNull());
if (isInt) {
thm = canonPredEquiv(
transitivityRule(thm, d_rules->lessThanToLERewrite(theIneq, isIntLHS, isIntRHS, true)));
}
}
// Check for trivial inequation
if ((thm.getRHS())[1].isRational())
thm = transitivityRule(thm, d_rules->constPredicate(thm.getRHS()));
else {
//else ineq is non-trivial
thm = normalize(thm);
// Normalization may yield non-simplified terms
thm = canonPredEquiv(thm);
}
}
break;
case LT:
case GT:
case LE:
case GE: {
if (isGE(e) || isGT(e)) {
thm = d_rules->flipInequality(e);
thm = transitivityRule(thm, d_rules->rightMinusLeft(thm.getRHS()));
}
else
thm = d_rules->rightMinusLeft(e);
thm = canonPredEquiv(thm);
// If the inequality is strict and integer, change it to non-strict
Expr theIneq = thm.getRHS();
if(isLT(theIneq)) {
// Check if integer
Theorem isIntLHS(isIntegerThm(theIneq[0]));
Theorem isIntRHS(isIntegerThm(theIneq[1]));
bool isInt = (!isIntLHS.isNull() && !isIntRHS.isNull());
if (isInt) {
thm = canonPredEquiv(
transitivityRule(thm, d_rules->lessThanToLERewrite(theIneq, isIntLHS, isIntRHS, true)));
}
}
// Check for trivial inequation
if ((thm.getRHS())[1].isRational())
thm = transitivityRule(thm, d_rules->constPredicate(thm.getRHS()));
else { // ineq is non-trivial
thm = normalize(thm);
thm = canonPredEquiv(thm);
if (thm.getRHS()[1].isRational())
thm = transitivityRule(thm, d_rules->constPredicate(thm.getRHS()));
}
break;
}
default:
DebugAssert(false,
"Theory_Arith::rewrite: control should not reach here");
break;
}
}
else {
if (e.isAtomic())
thm = canon(e);
else
thm = reflexivityRule(e);
}
// TODO: this needs to be reviewed, esp for non-linear case
// Arith canonization is idempotent
if (theoryOf(thm.getRHS()) == this)
thm.getRHS().setRewriteNormal();
TRACE("arith", "TheoryArithOld::rewrite => ", thm, " }");
return thm;
}
void TheoryArithOld::setup(const Expr& e)
{
if (!e.isTerm()) {
if (e.isNot()) return;
// if(e.getKind() == IS_INTEGER) {
// e[0].addToNotify(this, e);
// return;
// }
if (isIneq(e)) {
DebugAssert((isLT(e)||isLE(e)) &&
e[0].isRational() && e[0].getRational() == 0,
"TheoryArithOld::setup: expected 0 < rhs:" + e.toString());
e[1].addToNotify(this, e);
} else {
// if (e.isEq()) {
// // Nonlinear solved equations
// if (isNonlinearEq(e) && e[0].isRational() && e[0].getRational() == 0)
// e[0].addToNotify(this, e);
// }
//
// DebugAssert(isGrayShadow(e), "TheoryArithOld::setup: expected grayshadow" + e.toString());
//
// // Do not add the variable, just the subterm e[0].addToNotify(this, e);
// e[1].addToNotify(this, e);
}
return;
}
int k(0), ar(e.arity());
for ( ; k < ar; ++k) {
e[k].addToNotify(this, e);
TRACE("arith setup", "e["+int2string(k)+"]: ", *(e[k].getNotify()), "");
}
}
void TheoryArithOld::update(const Theorem& e, const Expr& d)
{
TRACE("arith update", "update on " + d.toString() + " with ", e.getRHS().toString(), ".");
if (inconsistent()) return;
// We accept atoms without find, but only inequalities (they come from the buffer)
DebugAssert(d.hasFind() || isIneq(d), "update on a non-inequality term/atom");
IF_DEBUG(debugger.counter("arith update total")++;)
// if (isGrayShadow(d)) {
// TRACE("shadow update", "updating index of " + d.toString() + " with ", e.getRHS().toString(), ".");
//
// // Substitute e[1] for e[0] in d and enqueue new shadow
// DebugAssert(e.getLHS() == d[1], "Mismatch");
// Theorem thm = find(d);
//
// // DebugAssert(thm.getRHS() == trueExpr(), "Expected find = true");
// vector<unsigned> changed;
// vector<Theorem> children;
// changed.push_back(1);
// children.push_back(e);
// Theorem thm2 = substitutivityRule(d, changed, children);
// if (thm.getRHS() == trueExpr()) {
// enqueueFact(iffMP(getCommonRules()->iffTrueElim(thm), thm2));
// }
// else {
// enqueueFact(getCommonRules()->iffFalseElim(
// transitivityRule(symmetryRule(thm2), thm)));
// }
// IF_DEBUG(debugger.counter("arith update ineq")++;)
// }
// else
if (isIneq(d)) {
// Substitute e[1] for e[0] in d and enqueue new inequality
DebugAssert(e.getLHS() == d[1], "Mismatch");
Theorem thm;
if (d.hasFind()) thm = find(d);
// bool diff_logic = false;
// Expr new_rhs = e.getRHS();
// if (!isPlus(new_rhs)) {
// if (isLeaf(new_rhs)) diff_logic = true;
// }
// else {
// int arity = new_rhs.arity();
// if (arity == 2) {
// if (new_rhs[0].isRational()) diff_logic = true;
// else {
// Expr ax = new_rhs[0], a, x;
// Expr by = new_rhs[1], b, y;
// separateMonomial(ax, a, x);
// separateMonomial(by, b, y);
// if ((a.getRational() == 1 && b.getRational() == -1) ||
// (a.getRational() == -1 && b.getRational() == 1))
// diff_logic = true;
// }
// } else {
// if (arity == 3 && new_rhs[0].isRational()) {
// Expr ax = new_rhs[1], a, x;
// Expr by = new_rhs[2], b, y;
// separateMonomial(ax, a, x);
// separateMonomial(by, b, y);
// if ((a.getRational() == 1 && b.getRational() == -1) ||
// (a.getRational() == -1 && b.getRational() == 1))
// diff_logic = true;
// }
// }
// }
// DebugAssert(thm.getRHS() == trueExpr(), "Expected find = true");
vector<unsigned> changed;
vector<Theorem> children;
changed.push_back(1);
children.push_back(e);
Theorem thm2 = substitutivityRule(d, changed, children);
Expr newIneq = thm2.getRHS();
// If this inequality is bufferred but not yet projected, just wait for it
// but don't add the find to the buffer as it will be projected as a find
// We DO want it to pass through all the buffer stuff but NOT get into the buffer
// NOTE: this means that the difference logic WILL get processed
if ((thm.isNull() || thm.getRHS() != falseExpr()) &&
bufferedInequalities.find(d) != bufferedInequalities.end() &&
alreadyProjected.find(d) == alreadyProjected.end()) {
TRACE("arith update", "simplified but not projected : ", thm2.getRHS(), "");
dontBuffer[thm2.getRHS()] = true;
}
if (thm.isNull()) {
// This hy is in the buffer, not in the core
// if it has been projected, than it's parent has been projected and will get reprojected
// accuratlz. If it has not been projected, we don't care it's still there
TRACE("arith update", "in udpate, but no find", "", "");
if (bufferedInequalities.find(d) != bufferedInequalities.end()) {
if (thm2.getRHS()[1].isRational()) enqueueFact(iffMP(bufferedInequalities[d], thm2));
else if (alreadyProjected.find(d) != alreadyProjected.end()) {
// the parent will get reprojected
alreadyProjected[d] = d;
}
}
}
else if (thm.getRHS() == trueExpr()) {
if (!newIneq[1].isRational() || newIneq[1].getRational() <= 0)
enqueueFact(iffMP(getCommonRules()->iffTrueElim(thm), thm2));
}
else {
enqueueFact(getCommonRules()->iffFalseElim(
transitivityRule(symmetryRule(thm2), thm)));
}
IF_DEBUG(debugger.counter("arith update ineq")++;)
}
else if (d.isEq()) {
TRACE("arith nonlinear", "TheoryArithOld::update() on equality ", d, "");
// We get equalitites from the non-solve nonlinear equations
// only the right hand sides get updated
vector<unsigned> changed;
vector<Theorem> children;
changed.push_back(0);
children.push_back(e);
Theorem thm = substitutivityRule(d, changed, children);
Expr newEq = thm.getRHS();
Theorem d_find = find(d);
if (d_find.getRHS() == trueExpr()) enqueueFact(iffMP(getCommonRules()->iffTrueElim(d_find), thm));
else enqueueFact(getCommonRules()->iffFalseElim(transitivityRule(symmetryRule(thm), d_find)));
}
else if (d.getKind() == IS_INTEGER) {
// This should only happen if !d has been asserted
DebugAssert(e.getRHS() == findExpr(d[0]), "Unexpected");
if (isInteger(e.getRHS())) {
Theorem thm = substitutivityRule(d, find(d[0]));
thm = transitivityRule(symmetryRule(find(d)), thm);
thm = iffMP(thm, simplify(thm.getExpr()));
setInconsistent(thm);
}
else {
e.getRHS().addToNotify(this, d);
}
}
else if (find(d).getRHS() == d) {
// Theorem thm = canonSimp(d);
// TRACE("arith", "TheoryArithOld::update(): thm = ", thm, "");
// DebugAssert(leavesAreSimp(thm.getRHS()), "updateHelper error: "
// +thm.getExpr().toString());
// assertEqualities(transitivityRule(thm, rewrite(thm.getRHS())));
// IF_DEBUG(debugger.counter("arith update find(d)=d")++;)
Theorem thm = simplify(d);
// If the original is was a shared term, add this one as as a shared term also
if (d_sharedTerms.find(d) != d_sharedTerms.end()) addSharedTerm(thm.getRHS());
DebugAssert(thm.getRHS().isAtomic(), "Expected atomic");
assertEqualities(thm);
}
}
Theorem TheoryArithOld::solve(const Theorem& thm)
{
DebugAssert(thm.isRewrite() && thm.getLHS().isTerm(), "");
const Expr& lhs = thm.getLHS();
const Expr& rhs = thm.getRHS();
// Check for already solved equalities.
// Have to be careful about the types: integer variable cannot be
// assigned a real term. Also, watch for e[0] being a subexpression
// of e[1]: this would create an unsimplifiable expression.
if (isLeaf(lhs) && !isLeafIn(lhs, rhs)
&& (!isInteger(lhs) || isInteger(rhs))
// && !e[0].subExprOf(e[1])
)
return thm;
// Symmetric version is already solved
if (isLeaf(rhs) && !isLeafIn(rhs, lhs)
&& (!isInteger(rhs) || isInteger(lhs))
// && !e[1].subExprOf(e[0])
)
return symmetryRule(thm);
return doSolve(thm);
}
void TheoryArithOld::computeModelTerm(const Expr& e, std::vector<Expr>& v) {
switch(e.getKind()) {
case RATIONAL_EXPR: // Skip the constants
break;
case PLUS:
case MULT:
case DIVIDE:
case POW: // This is not a variable; extract the variables from children
for(Expr::iterator i=e.begin(), iend=e.end(); i!=iend; ++i)
// getModelTerm(*i, v);
v.push_back(*i);
break;
default: { // Otherwise it's a variable. Check if it has a find pointer
Expr e2(findExpr(e));
if(e==e2) {
TRACE("model", "TheoryArithOld::computeModelTerm(", e, "): a variable");
// Leave it alone (it has no descendants)
// v.push_back(e);
} else {
TRACE("model", "TheoryArithOld::computeModelTerm("+e.toString()
+"): has find pointer to ", e2, "");
v.push_back(e2);
}
}
}
}
Expr TheoryArithOld::computeTypePred(const Type& t, const Expr& e) {
Expr tExpr = t.getExpr();
switch(tExpr.getKind()) {
case INT:
return Expr(IS_INTEGER, e);
case SUBRANGE: {
std::vector<Expr> kids;
kids.push_back(Expr(IS_INTEGER, e));
kids.push_back(leExpr(tExpr[0], e));
kids.push_back(leExpr(e, tExpr[1]));
return andExpr(kids);
}
default:
return e.getEM()->trueExpr();
}
}
void TheoryArithOld::checkAssertEqInvariant(const Theorem& e)
{
if (e.isRewrite()) {
DebugAssert(e.getLHS().isTerm(), "Expected equation");
if (isLeaf(e.getLHS())) {
// should be in solved form
DebugAssert(!isLeafIn(e.getLHS(),e.getRHS()),
"Not in solved form: lhs appears in rhs");
}
else {
DebugAssert(e.getLHS().hasFind(), "Expected lhs to have find");
DebugAssert(!leavesAreSimp(e.getLHS()),
"Expected at least one unsimplified leaf on lhs");
}
DebugAssert(canonSimp(e.getRHS()).getRHS() == e.getRHS(),
"Expected canonSimp(rhs) = canonSimp(rhs)");
}
else {
Expr expr = e.getExpr();
if (expr.isFalse()) return;
vector<Theorem> eqs;
Theorem thm;
int index, index2;
for (index = 0; index < expr.arity(); ++index) {
thm = getCommonRules()->andElim(e, index);
eqs.push_back(thm);
if (thm.getExpr().isFalse()) return;
DebugAssert(eqs[index].isRewrite() &&
eqs[index].getLHS().isTerm(), "Expected equation");
}
// Check for solved form
for (index = 0; index < expr.arity(); ++index) {
DebugAssert(isLeaf(eqs[index].getLHS()), "expected leaf on lhs");
DebugAssert(canonSimp(eqs[index].getRHS()).getRHS() == eqs[index].getRHS(),
"Expected canonSimp(rhs) = canonSimp(rhs)");
DebugAssert(recursiveCanonSimpCheck(eqs[index].getRHS()),
"Failed recursive canonSimp check");
for (index2 = 0; index2 < expr.arity(); ++index2) {
DebugAssert(index == index2 ||
eqs[index].getLHS() != eqs[index2].getLHS(),
"Not in solved form: repeated lhs");
DebugAssert(!isLeafIn(eqs[index].getLHS(),eqs[index2].getRHS()),
"Not in solved form: lhs appears in rhs");
}
}
}
}
void TheoryArithOld::checkType(const Expr& e)
{
switch (e.getKind()) {
case INT:
case REAL:
if (e.arity() > 0) {
throw Exception("Ill-formed arithmetic type: "+e.toString());
}
break;
case SUBRANGE:
if (e.arity() != 2 ||
!isIntegerConst(e[0]) ||
!isIntegerConst(e[1]) ||
e[0].getRational() > e[1].getRational()) {
throw Exception("bad SUBRANGE type expression"+e.toString());
}
break;
default:
DebugAssert(false, "Unexpected kind in TheoryArithOld::checkType"
+getEM()->getKindName(e.getKind()));
}
}
Cardinality TheoryArithOld::finiteTypeInfo(Expr& e, Unsigned& n,
bool enumerate, bool computeSize)
{
Cardinality card = CARD_INFINITE;
switch (e.getKind()) {
case SUBRANGE: {
card = CARD_FINITE;
Expr typeExpr = e;
if (enumerate) {
Rational r = typeExpr[0].getRational() + n;
if (r <= typeExpr[1].getRational()) {
e = rat(r);
}
else e = Expr();
}
if (computeSize) {
Rational r = typeExpr[1].getRational() - typeExpr[0].getRational() + 1;
n = r.getUnsigned();
}
break;
}
default:
break;
}
return card;
}
void TheoryArithOld::computeType(const Expr& e)
{
switch (e.getKind()) {
case REAL_CONST:
e.setType(d_realType);
break;
case RATIONAL_EXPR:
if(e.getRational().isInteger())
e.setType(d_intType);
else
e.setType(d_realType);
break;
case UMINUS:
case PLUS:
case MINUS:
case MULT:
case POW: {
bool isInt = true;
for(int k = 0; k < e.arity(); ++k) {
if(d_realType != getBaseType(e[k]))
throw TypecheckException("Expecting type REAL with `" +
getEM()->getKindName(e.getKind()) + "',\n"+
"but got a " + getBaseType(e[k]).toString()+
" for:\n" + e.toString());
if(isInt && !isInteger(e[k]))
isInt = false;
}
if(isInt)
e.setType(d_intType);
else
e.setType(d_realType);
break;
}
case DIVIDE: {
Expr numerator = e[0];
Expr denominator = e[1];
if (getBaseType(numerator) != d_realType ||
getBaseType(denominator) != d_realType) {
throw TypecheckException("Expecting only REAL types with `DIVIDE',\n"
"but got " + getBaseType(numerator).toString()+
" and " + getBaseType(denominator).toString() +
" for:\n" + e.toString());
}
if(denominator.isRational() && 1 == denominator.getRational())
e.setType(numerator.getType());
else
e.setType(d_realType);
break;
}
case LT:
case LE:
case GT:
case GE:
case GRAY_SHADOW:
// Need to know types for all exprs -Clark
// e.setType(boolType());
// break;
case DARK_SHADOW:
for (int k = 0; k < e.arity(); ++k) {
if (d_realType != getBaseType(e[k]))
throw TypecheckException("Expecting type REAL with `" +
getEM()->getKindName(e.getKind()) + "',\n"+
"but got a " + getBaseType(e[k]).toString()+
" for:\n" + e.toString());
}
e.setType(boolType());
break;
case IS_INTEGER:
if(d_realType != getBaseType(e[0]))
throw TypecheckException("Expected type REAL, but got "
+getBaseType(e[0]).toString()
+"\n\nExpr = "+e.toString());
e.setType(boolType());
break;
default:
DebugAssert(false,"TheoryArithOld::computeType: unexpected expression:\n "
+e.toString());
break;
}
}
Type TheoryArithOld::computeBaseType(const Type& t) {
IF_DEBUG(int kind = t.getExpr().getKind();)
DebugAssert(kind==INT || kind==REAL || kind==SUBRANGE,
"TheoryArithOld::computeBaseType("+t.toString()+")");
return realType();
}
Expr
TheoryArithOld::computeTCC(const Expr& e) {
Expr tcc(Theory::computeTCC(e));
switch(e.getKind()) {
case DIVIDE:
DebugAssert(e.arity() == 2, "");
return tcc.andExpr(!(e[1].eqExpr(rat(0))));
default:
return tcc;
}
}
///////////////////////////////////////////////////////////////////////////////
//parseExprOp:
//translating special Exprs to regular EXPR??
///////////////////////////////////////////////////////////////////////////////
Expr
TheoryArithOld::parseExprOp(const Expr& e) {
TRACE("parser", "TheoryArithOld::parseExprOp(", e, ")");
//std::cout << "Were here";
// If the expression is not a list, it must have been already
// parsed, so just return it as is.
switch(e.getKind()) {
case ID: {
int kind = getEM()->getKind(e[0].getString());
switch(kind) {
case NULL_KIND: return e; // nothing to do
case REAL:
case INT:
case NEGINF:
case POSINF: return getEM()->newLeafExpr(kind);
default:
DebugAssert(false, "Bad use of bare keyword: "+e.toString());
return e;
}
}
case RAW_LIST: break; // break out of switch, do the hard work
default:
return e;
}
DebugAssert(e.getKind() == RAW_LIST && e.arity() > 0,
"TheoryArithOld::parseExprOp:\n e = "+e.toString());
const Expr& c1 = e[0][0];
int kind = getEM()->getKind(c1.getString());
switch(kind) {
case UMINUS: {
if(e.arity() != 2)
throw ParserException("UMINUS requires exactly one argument: "
+e.toString());
return uminusExpr(parseExpr(e[1]));
}
case PLUS: {
vector<Expr> k;
Expr::iterator i = e.begin(), iend=e.end();
// Skip first element of the vector of kids in 'e'.
// The first element is the operator.
++i;
// Parse the kids of e and push them into the vector 'k'
for(; i!=iend; ++i) k.push_back(parseExpr(*i));
return plusExpr(k);
}
case MINUS: {
if(e.arity() == 2) {
if (false && (getEM()->getInputLang() == SMTLIB_LANG
|| getEM()->getInputLang() == SMTLIB_V2_LANG)) {
throw ParserException("Unary Minus should use '~' instead of '-' in SMT-LIB expr:"
+e.toString());
}
else {
return uminusExpr(parseExpr(e[1]));
}
}
else if(e.arity() == 3)
return minusExpr(parseExpr(e[1]), parseExpr(e[2]));
else
throw ParserException("MINUS requires one or two arguments:"
+e.toString());
}
case MULT: {
vector<Expr> k;
Expr::iterator i = e.begin(), iend=e.end();
// Skip first element of the vector of kids in 'e'.
// The first element is the operator.
++i;
// Parse the kids of e and push them into the vector 'k'
for(; i!=iend; ++i) k.push_back(parseExpr(*i));
return multExpr(k);
}
case POW: {
return powExpr(parseExpr(e[1]), parseExpr(e[2]));
}
case DIVIDE:
{ return divideExpr(parseExpr(e[1]), parseExpr(e[2])); }
case LT:
{ return ltExpr(parseExpr(e[1]), parseExpr(e[2])); }
case LE:
{ return leExpr(parseExpr(e[1]), parseExpr(e[2])); }
case GT:
{ return gtExpr(parseExpr(e[1]), parseExpr(e[2])); }
case GE:
{ return geExpr(parseExpr(e[1]), parseExpr(e[2])); }
case INTDIV:
case MOD:
case SUBRANGE: {
vector<Expr> k;
Expr::iterator i = e.begin(), iend=e.end();
// Skip first element of the vector of kids in 'e'.
// The first element is the operator.
++i;
// Parse the kids of e and push them into the vector 'k'
for(; i!=iend; ++i)
k.push_back(parseExpr(*i));
return Expr(kind, k, e.getEM());
}
case IS_INTEGER: {
if(e.arity() != 2)
throw ParserException("IS_INTEGER requires exactly one argument: "
+e.toString());
return Expr(IS_INTEGER, parseExpr(e[1]));
}
default:
DebugAssert(false,
"TheoryArithOld::parseExprOp: invalid input " + e.toString());
break;
}
return e;
}
///////////////////////////////////////////////////////////////////////////////
// Pretty-printing //
///////////////////////////////////////////////////////////////////////////////
ExprStream&
TheoryArithOld::print(ExprStream& os, const Expr& e) {
switch(os.lang()) {
case SIMPLIFY_LANG:
switch(e.getKind()) {
case RATIONAL_EXPR:
e.print(os);
break;
case SUBRANGE:
os <<"ERROR:SUBRANGE:not supported in Simplify\n";
break;
case IS_INTEGER:
os <<"ERROR:IS_INTEGER:not supported in Simplify\n";
break;
case PLUS: {
int i=0, iend=e.arity();
os << "(+ ";
if(i!=iend) os << e[i];
++i;
for(; i!=iend; ++i) os << " " << e[i];
os << ")";
break;
}
case MINUS:
os << "(- " << e[0] << " " << e[1]<< ")";
break;
case UMINUS:
os << "-" << e[0] ;
break;
case MULT: {
int i=0, iend=e.arity();
os << "(* " ;
if(i!=iend) os << e[i];
++i;
for(; i!=iend; ++i) os << " " << e[i];
os << ")";
break;
}
case POW:
os << "(" << push << e[1] << space << "^ " << e[0] << push << ")";
break;
case DIVIDE:
os << "(" << push << e[0] << space << "/ " << e[1] << push << ")";
break;
case LT:
if (isInt(e[0].getType()) || isInt(e[1].getType())) {
}
os << "(< " << e[0] << " " << e[1] <<")";
break;
case LE:
os << "(<= " << e[0] << " " << e[1] << ")";
break;
case GT:
os << "(> " << e[0] << " " << e[1] << ")";
break;
case GE:
os << "(>= " << e[0] << " " << e[1] << ")";
break;
case DARK_SHADOW:
case GRAY_SHADOW:
os <<"ERROR:SHADOW:not supported in Simplify\n";
break;
default:
// Print the top node in the default LISP format, continue with
// pretty-printing for children.
e.print(os);
break;
}
break; // end of case SIMPLIFY_LANG
case TPTP_LANG:
switch(e.getKind()) {
case RATIONAL_EXPR:
e.print(os);
break;
case SUBRANGE:
os <<"ERROR:SUBRANGE:not supported in TPTP\n";
break;
case IS_INTEGER:
os <<"ERROR:IS_INTEGER:not supported in TPTP\n";
break;
case PLUS: {
if(!isInteger(e[0])){
os<<"ERRPR:plus only supports inteters now in TPTP\n";
break;
}
int i=0, iend=e.arity();
if(iend <=1){
os<<"ERROR,plus must have more than two numbers in TPTP\n";
break;
}
for(i=0; i <= iend-2; ++i){
os << "$plus_int(";
os << e[i] << ",";
}
os<< e[iend-1];
for(i=0 ; i <= iend-2; ++i){
os << ")";
}
break;
}
case MINUS:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "$minus_int(" << e[0] << "," << e[1]<< ")";
break;
case UMINUS:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "$uminus_int(" << e[0] <<")" ;
break;
case MULT: {
if(!isInteger(e[0])){
os<<"ERRPR:times only supports inteters now in TPTP\n";
break;
}
int i=0, iend=e.arity();
if(iend <=1){
os<<"ERROR:times must have more than two numbers in TPTP\n";
break;
}
for(i=0; i <= iend-2; ++i){
os << "$times_int(";
os << e[i] << ",";
}
os<< e[iend-1];
for(i=0 ; i <= iend-2; ++i){
os << ")";
}
break;
}
case POW:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "$power_int(" << push << e[1] << space << "^ " << e[0] << push << ")";
break;
case DIVIDE:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "divide_int(" <<e[0] << "," << e[1] << ")";
break;
case LT:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "$less_int(" << e[0] << "," << e[1] <<")";
break;
case LE:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "$lesseq_int(" << e[0] << "," << e[1] << ")";
break;
case GT:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "$greater_int(" << e[0] << "," << e[1] << ")";
break;
case GE:
if(!isInteger(e[0])){
os<<"ERRPR:arithmetic operations only support inteters now in TPTP\n";
break;
}
os << "$greatereq_int(" << e[0] << "," << e[1] << ")";
break;
case DARK_SHADOW:
case GRAY_SHADOW:
os <<"ERROR:SHADOW:not supported in TPTP\n";
break;
case INT:
os <<"$int";
break;
case REAL:
os <<"ERROR:REAL not supported in TPTP\n";
default:
// Print the top node in the default LISP format, continue with
// pretty-printing for children.
e.print(os);
break;
}
break; // end of case TPTP_LANG
case PRESENTATION_LANG:
switch(e.getKind()) {
case REAL:
os << "REAL";
break;
case INT:
os << "INT";
break;
case RATIONAL_EXPR:
e.print(os);
break;
case NEGINF:
os << "NEGINF";
break;
case POSINF:
os << "POSINF";
break;
case SUBRANGE:
if(e.arity() != 2) e.printAST(os);
else
os << "[" << push << e[0] << ".." << e[1] << push << "]";
break;
case IS_INTEGER:
if(e.arity() == 1)
os << "IS_INTEGER(" << push << e[0] << push << ")";
else
e.printAST(os);
break;
case PLUS: {
int i=0, iend=e.arity();
os << "(" << push;
if(i!=iend) os << e[i];
++i;
for(; i!=iend; ++i) os << space << "+ " << e[i];
os << push << ")";
break;
}
case MINUS:
os << "(" << push << e[0] << space << "- " << e[1] << push << ")";
break;
case UMINUS:
os << "-(" << push << e[0] << push << ")";
break;
case MULT: {
int i=0, iend=e.arity();
os << "(" << push;
if(i!=iend) os << e[i];
++i;
for(; i!=iend; ++i) os << space << "* " << e[i];
os << push << ")";
break;
}
case POW:
os << "(" << push << e[1] << space << "^ " << e[0] << push << ")";
break;
case DIVIDE:
os << "(" << push << e[0] << space << "/ " << e[1] << push << ")";
break;
case LT:
if (isInt(e[0].getType()) || isInt(e[1].getType())) {
}
os << "(" << push << e[0] << space << "< " << e[1] << push << ")";
break;
case LE:
os << "(" << push << e[0] << space << "<= " << e[1] << push << ")";
break;
case GT:
os << "(" << push << e[0] << space << "> " << e[1] << push << ")";
break;
case GE:
os << "(" << push << e[0] << space << ">= " << e[1] << push << ")";
break;
case DARK_SHADOW:
os << "DARK_SHADOW(" << push << e[0] << ", " << space << e[1] << push << ")";
break;
case GRAY_SHADOW:
os << "GRAY_SHADOW(" << push << e[0] << "," << space << e[1]
<< "," << space << e[2] << "," << space << e[3] << push << ")";
break;
default:
// Print the top node in the default LISP format, continue with
// pretty-printing for children.
e.printAST(os);
break;
}
break; // end of case PRESENTATION_LANG
case SPASS_LANG: {
switch(e.getKind()) {
case REAL_CONST:
printRational(os, e[0].getRational(), true);
break;
case RATIONAL_EXPR:
printRational(os, e.getRational());
break;
case REAL:
throw SmtlibException("TheoryArithOld::print: SPASS: REAL not implemented");
break;
case INT:
throw SmtlibException("TheoryArithOld::print: SPASS: INT not implemented");
break;
case SUBRANGE:
throw SmtlibException("TheoryArithOld::print: SPASS: SUBRANGE not implemented");
break;
case IS_INTEGER:
throw SmtlibException("TheoryArithOld::print: SPASS: IS_INTEGER not implemented");
case PLUS: {
int arity = e.arity();
if(2 == arity) {
os << push << "plus("
<< e[0] << "," << space << e[1]
<< push << ")";
}
else if(2 < arity) {
for (int i = 0 ; i < arity - 2; i++){
os << push << "plus(";
os << e[i] << "," << space;
}
os << push << "plus("
<< e[arity - 2] << "," << space << e[arity - 1]
<< push << ")";
for (int i = 0 ; i < arity - 2; i++){
os << push << ")";
}
}
else {
throw SmtlibException("TheoryArithOld::print: SPASS: Less than two arguments for plus");
}
break;
}
case MINUS: {
os << push << "plus(" << e[0]
<< "," << space << push << "mult(-1,"
<< space << e[1] << push << ")" << push << ")";
break;
}
case UMINUS: {
os << push << "plus(0,"
<< space << push << "mult(-1,"
<< space << e[0] << push << ")" << push << ")";
break;
}
case MULT: {
int arity = e.arity();
if (2 == arity){
os << push << "mult("
<< e[0] << "," << space << e[1]
<< push << ")";
}
else if (2 < arity){
for (int i = 0 ; i < arity - 2; i++){
os << push << "mult(";
os << e[i] << "," << space;
}
os << push << "mult("
<< e[arity - 2] << "," << space << e[arity - 1]
<< push << ")";
for (int i = 0 ; i < arity - 2; i++){
os << push << ")";
}
}
else{
throw SmtlibException("TheoryArithOld::print: SPASS: Less than two arguments for mult");
}
break;
}
case POW:
if (e[0].isRational() && e[0].getRational().isInteger()) {
int i=0, iend=e[0].getRational().getInt();
for(; i!=iend; ++i) {
if (i < iend-2) {
os << push << "mult(";
}
os << e[1] << "," << space;
}
os << push << "mult("
<< e[1] << "," << space << e[1];
for (i=0; i < iend-1; ++i) {
os << push << ")";
}
}
else {
throw SmtlibException("TheoryArithOld::print: SPASS: POW not supported: " + e.toString(PRESENTATION_LANG));
}
break;
case DIVIDE: {
os << "ERROR "<< endl;break;
throw SmtlibException("TheoryArithOld::print: SPASS: unexpected use of DIVIDE");
break;
}
case LT: {
Rational r;
os << push << "ls(" << space;
os << e[0] << "," << space << e[1] << push << ")";
break;
}
case LE: {
Rational r;
os << push << "le(" << space;
os << e[0] << "," << space << e[1] << push << ")";
break;
}
case GT: {
Rational r;
os << push << "gs(" << space;
os << e[0] << "," << space << e[1] << push << ")";
break;
}
case GE: {
Rational r;
os << push << "ge(" << space;
os << e[0] << "," << space << e[1] << push << ")";
break;
}
default:
throw SmtlibException("TheoryArithOld::print: SPASS: default not supported");
}
break; // end of case SPASS_LANG
}
case SMTLIB_LANG:
case SMTLIB_V2_LANG: {
switch(e.getKind()) {
case REAL_CONST:
printRational(os, e[0].getRational(), (os.lang() == SMTLIB_LANG));
break;
case RATIONAL_EXPR:
printRational(os, e.getRational());
break;
case REAL:
os << "Real";
break;
case INT:
os << "Int";
break;
case SUBRANGE:
throw SmtlibException("TheoryArithOld::print: SMTLIB: SUBRANGE not implemented");
// if(e.arity() != 2) e.print(os);
// else
// os << "(" << push << "SUBRANGE" << space << e[0]
// << space << e[1] << push << ")";
break;
case IS_INTEGER:
if(e.arity() == 1)
os << "(" << push << "IsInt" << space << e[0] << push << ")";
else
throw SmtlibException("TheoryArithOld::print: SMTLIB: IS_INTEGER used unexpectedly");
break;
case PLUS: {
if(e.arity() == 1 && os.lang() == SMTLIB_V2_LANG) {
os << e[0];
} else {
os << "(" << push << "+";
Expr::iterator i = e.begin(), iend = e.end();
for(; i!=iend; ++i) {
os << space << (*i);
}
os << push << ")";
}
break;
}
case MINUS: {
os << "(" << push << "- " << e[0] << space << e[1] << push << ")";
break;
}
case UMINUS: {
if (os.lang() == SMTLIB_LANG) {
os << "(" << push << "~" << space << e[0] << push << ")";
}
else {
os << "(" << push << "-" << space << e[0] << push << ")";
}
break;
}
case MULT: {
int i=0, iend=e.arity();
if(iend == 1 && os.lang() == SMTLIB_V2_LANG) {
os << e[0];
} else {
for(; i!=iend; ++i) {
if (i < iend-1) {
os << "(" << push << "*";
}
os << space << e[i];
}
for (i=0; i < iend-1; ++i) os << push << ")";
}
break;
}
case POW:
if (e[0].isRational() && e[0].getRational().isInteger()) {
int i=0, iend=e[0].getRational().getInt();
for(; i!=iend; ++i) {
if (i < iend-1) {
os << "(" << push << "*";
}
os << space << e[1];
}
for (i=0; i < iend-1; ++i) os << push << ")";
}
else
throw SmtlibException("TheoryArithOld::print: SMTLIB: POW not supported: " + e.toString(PRESENTATION_LANG));
// os << "(" << push << "^ " << e[1] << space << e[0] << push << ")";
break;
case DIVIDE: {
throw SmtlibException("TheoryArithOld::print: SMTLIB: unexpected use of DIVIDE");
break;
}
case LT: {
Rational r;
os << "(" << push << "<" << space;
os << e[0] << space << e[1] << push << ")";
break;
}
case LE: {
Rational r;
os << "(" << push << "<=" << space;
os << e[0] << space << e[1] << push << ")";
break;
}
case GT: {
Rational r;
os << "(" << push << ">" << space;
os << e[0] << space << e[1] << push << ")";
break;
}
case GE: {
Rational r;
os << "(" << push << ">=" << space;
os << e[0] << space << e[1] << push << ")";
break;
}
case DARK_SHADOW:
throw SmtlibException("TheoryArithOld::print: SMTLIB: DARK_SHADOW not supported");
os << "(" << push << "DARK_SHADOW" << space << e[0]
<< space << e[1] << push << ")";
break;
case GRAY_SHADOW:
throw SmtlibException("TheoryArithOld::print: SMTLIB: GRAY_SHADOW not supported");
os << "GRAY_SHADOW(" << push << e[0] << "," << space << e[1]
<< "," << space << e[2] << "," << space << e[3] << push << ")";
break;
default:
throw SmtlibException("TheoryArithOld::print: SMTLIB: default not supported");
// Print the top node in the default LISP format, continue with
// pretty-printing for children.
e.printAST(os);
break;
}
break; // end of case SMTLIB_LANG
}
case LISP_LANG:
switch(e.getKind()) {
case REAL:
case INT:
case RATIONAL_EXPR:
case NEGINF:
case POSINF:
e.print(os);
break;
case SUBRANGE:
if(e.arity() != 2) e.printAST(os);
else
os << "(" << push << "SUBRANGE" << space << e[0]
<< space << e[1] << push << ")";
break;
case IS_INTEGER:
if(e.arity() == 1)
os << "(" << push << "IS_INTEGER" << space << e[0] << push << ")";
else
e.printAST(os);
break;
case PLUS: {
int i=0, iend=e.arity();
os << "(" << push << "+";
for(; i!=iend; ++i) os << space << e[i];
os << push << ")";
break;
}
case MINUS:
//os << "(" << push << e[0] << space << "- " << e[1] << push << ")";
os << "(" << push << "- " << e[0] << space << e[1] << push << ")";
break;
case UMINUS:
os << "(" << push << "-" << space << e[0] << push << ")";
break;
case MULT: {
int i=0, iend=e.arity();
os << "(" << push << "*";
for(; i!=iend; ++i) os << space << e[i];
os << push << ")";
break;
}
case POW:
os << "(" << push << "^ " << e[1] << space << e[0] << push << ")";
break;
case DIVIDE:
os << "(" << push << "/ " << e[0] << space << e[1] << push << ")";
break;
case LT:
os << "(" << push << "< " << e[0] << space << e[1] << push << ")";
break;
case LE:
os << "(" << push << "<= " << e[0] << space << e[1] << push << ")";
break;
case GT:
os << "(" << push << "> " << e[1] << space << e[0] << push << ")";
break;
case GE:
os << "(" << push << ">= " << e[0] << space << e[1] << push << ")";
break;
case DARK_SHADOW:
os << "(" << push << "DARK_SHADOW" << space << e[0]
<< space << e[1] << push << ")";
break;
case GRAY_SHADOW:
os << "(" << push << "GRAY_SHADOW" << space << e[0] << space
<< e[1] << space << e[2] << space << e[3] << push << ")";
break;
default:
// Print the top node in the default LISP format, continue with
// pretty-printing for children.
e.printAST(os);
break;
}
break; // end of case LISP_LANG
default:
// Print the top node in the default LISP format, continue with
// pretty-printing for children.
e.printAST(os);
}
return os;
}
Theorem TheoryArithOld::inequalityToFind(const Theorem& inequalityThm, bool normalizeRHS) {
// Which side of the inequality
int index = (normalizeRHS ? 1 : 0);
TRACE("arith find", "inequalityToFind(", int2string(index) + ", " + inequalityThm.getExpr().toString(), ")");
// Get the inequality expression
const Expr& inequality = inequalityThm.getExpr();
// The theorem we will return
Theorem inequalityFindThm;
// If the inequality side has a find
if (inequality[index].hasFind()) {
// Get the find of the rhs (lhs)
Theorem rhsFindThm = inequality[index].getFind();
// Get the theorem simplifys the find (in case the updates haven't updated all the finds yet
// Fixed with d_theroyCore.inUpdate()
rhsFindThm = transitivityRule(rhsFindThm, simplify(rhsFindThm.getRHS()));
// If not the same as the original
Expr rhsFind = rhsFindThm.getRHS();
if (rhsFind != inequality[index]) {
// Substitute in the inequality
vector<unsigned> changed;
vector<Theorem> children;
changed.push_back(index);
children.push_back(rhsFindThm);
rhsFindThm = iffMP(inequalityThm, substitutivityRule(inequality, changed, children));
// If on the left-hand side, we are done
if (index == 0)
inequalityFindThm = rhsFindThm;
else
// If on the right-hand side and left-hand side is 0, normalize it
if (inequality[0].isRational() && inequality[0].getRational() == 0)
inequalityFindThm = normalize(rhsFindThm);
else
inequalityFindThm = rhsFindThm;
} else
inequalityFindThm = inequalityThm;
} else
inequalityFindThm = inequalityThm;
TRACE("arith find", "inequalityToFind ==>", inequalityFindThm.getExpr(), "");
return inequalityFindThm;
}
void TheoryArithOld::registerAtom(const Expr& e) {
// Trace it
TRACE("arith atoms", "registerAtom(", e.toString(), ")");
// Mark it
formulaAtoms[e] = true;
// If it is a atomic formula, add it to the map
if (e.isAbsAtomicFormula() && isIneq(e)) {
Expr rightSide = e[1];
Rational leftSide = e[0].getRational();
//Get the terms for : c1 op t1 and t2 -op c2
Expr t1, t2;
Rational c1, c2;
extractTermsFromInequality(e, c1, t1, c2, t2);
if (true) {
TRACE("arith atoms", "registering lower bound for ", t1.toString(), " = " + c1.toString() + ")");
formulaAtomLowerBound[t1].insert(pair<Rational, Expr>(c1, e));
// See if the bounds on the registered term can infered from already asserted facts
CDMap<Expr, Rational>::iterator lowerBoundFind = termLowerBound.find(t1);
if (lowerBoundFind != termLowerBound.end()) {
Rational boundValue = (*lowerBoundFind).second;
Theorem boundThm = termLowerBoundThm[t1];
Expr boundIneq = boundThm.getExpr();
if (boundValue > c1 || (boundValue == c1 && !(boundIneq.getKind() == LE && e.getKind() == LT))) {
enqueueFact(getCommonRules()->implMP(boundThm, d_rules->implyWeakerInequality(boundIneq, e)));
}
}
// See if the bounds on the registered term can falsified from already asserted facts
CDMap<Expr, Rational>::iterator upperBoundFind = termUpperBound.find(t1);
if (upperBoundFind != termUpperBound.end()) {
Rational boundValue = (*upperBoundFind).second;
Theorem boundThm = termUpperBoundThm[t1];
Expr boundIneq = boundThm.getExpr();
if (boundValue < c1 || (boundValue == c1 && boundIneq.getKind() == LT && e.getKind() == LT)) {
enqueueFact(getCommonRules()->implMP(boundThm, d_rules->implyNegatedInequality(boundIneq, e)));
}
}
TRACE("arith atoms", "registering upper bound for ", t2.toString(), " = " + c2.toString() + ")");
formulaAtomUpperBound[t2].insert(pair<Rational, Expr>(c2, e));
}
}
}
TheoryArithOld::DifferenceLogicGraph::DifferenceLogicGraph(TheoryArithOld* arith, TheoryCore* core, ArithProofRules* rules, Context* context)
: d_pathLenghtThres(&(core->getFlags()["pathlength-threshold"].getInt())),
arith(arith),
core(core),
rules(rules),
unsat_theorem(context),
biggestEpsilon(context, 0, 0),
smallestPathDifference(context, 1, 0),
leGraph(context),
varInCycle(context)
{
}
Theorem TheoryArithOld::DifferenceLogicGraph::getUnsatTheorem() {
return unsat_theorem;
}
bool TheoryArithOld::DifferenceLogicGraph::isUnsat() {
return !getUnsatTheorem().isNull();
}
bool TheoryArithOld::DifferenceLogicGraph::existsEdge(const Expr& x, const Expr& y) {
Expr index = x - y;
Graph::iterator find_le = leGraph.find(index);
if (find_le != leGraph.end()) {
EdgeInfo edge_info = (*find_le).second;
if (edge_info.isDefined()) return true;
}
return false;
}
bool TheoryArithOld::DifferenceLogicGraph::inCycle(const Expr& x) {
return (varInCycle.find(x) != varInCycle.end());
}
TheoryArithOld::DifferenceLogicGraph::Graph::ElementReference TheoryArithOld::DifferenceLogicGraph::getEdge(const Expr& x, const Expr& y) {
Expr index = x - y;
Graph::ElementReference edge_info = leGraph[index];
// If a new edge and x != y, then add vertices to the apropriate lists
if (x != y && !edge_info.get().isDefined()) {
// Adding a new edge, take a resource
core->getResource();
EdgesList::iterator y_it = incomingEdges.find(y);
if (y_it == incomingEdges.end() || (*y_it).second == 0) {
CDList<Expr>* list = new(true) CDList<Expr>(core->getCM()->getCurrentContext());
list->push_back(x);
incomingEdges[y] = list;
} else
((*y_it).second)->push_back(x);
EdgesList::iterator x_it = outgoingEdges.find(x);
if (x_it == outgoingEdges.end() || (*x_it).second == 0) {
CDList<Expr>* list = new(true) CDList<Expr>(core->getCM()->getCurrentContext());
list->push_back(y);
outgoingEdges[x] = list;
} else
((*x_it).second)->push_back(y);
}
return edge_info;
}
TheoryArithOld::DifferenceLogicGraph::EpsRational TheoryArithOld::DifferenceLogicGraph::getEdgeWeight(const Expr& x, const Expr& y) {
if (!existsEdge(x, y))
return EpsRational::PlusInfinity;
else {
EdgeInfo edgeInfo = getEdge(x, y).get();
return edgeInfo.length;
}
}
void TheoryArithOld::DifferenceLogicGraph::addEdge(const Expr& x, const Expr& y, const Rational& bound, const Theorem& edge_thm) {
TRACE("arith diff", x, " --> ", y);
DebugAssert(x != y, "addEdge, given two equal expressions!");
if (isUnsat()) return;
// If out of resources, bail out
if (core->outOfResources()) return;
// Get the kind of the inequality (NOTE isNull -- for model computation we add a vertex with no theorem)
// FIXME: Later, add a debug assert for the theorem that checks that this variable is cvc3diffLogicSource
int kind = (edge_thm.isNull() ? LE : edge_thm.getExpr().getKind());
DebugAssert(kind == LT || kind == LE, "addEdge, not an <= or <!");
// Get the EpsRational bound
Rational k = (kind == LE ? 0 : -1);
EpsRational c(bound, k);
// Get the current (or a fresh new edge info)
Graph::ElementReference edgeInfoRef = getEdge(x, y);
// If uninitialized, or smaller length (we prefer shorter paths, so one edge is better)
EdgeInfo edgeInfo = edgeInfoRef.get();
// If the edge changed to the better, do the work
if (!edgeInfo.isDefined() || c <= edgeInfo.length) {
// Update model generation data
if (edgeInfo.isDefined()) {
EpsRational difference = edgeInfo.length - c;
Rational rationalDifference = difference.getRational();
if (rationalDifference > 0 && rationalDifference < smallestPathDifference) {
smallestPathDifference = rationalDifference;
TRACE("diff model", "smallest path difference : ", smallestPathDifference, "");
}
}
Rational newEpsilon = - c.getEpsilon();
if (newEpsilon > biggestEpsilon) {
biggestEpsilon = newEpsilon;
TRACE("diff model", "biggest epsilon : ", biggestEpsilon, "");
}
// Set the edge info
edgeInfo.length = c;
edgeInfo.explanation = edge_thm;
edgeInfo.path_length_in_edges = 1;
edgeInfoRef = edgeInfo;
// Try simple cycle x --> y --> x, to keep invariants (no cycles or one negative)
if (existsEdge(y, x)) {
varInCycle[x] = true;
varInCycle[y] = true;
tryUpdate(x, y, x);
if (isUnsat())
return;
}
// For all edges coming into x, z ---> x, update z ---> y and add updated ones to the updated_in_y vector
CDList<Expr>* in_x = incomingEdges[x];
vector<Expr> updated_in_y;
updated_in_y.push_back(x);
// If there
if (in_x) {
IF_DEBUG(int total = 0; int updated = 0;);
for (unsigned it = 0; it < in_x->size() && !isUnsat(); it ++) {
const Expr& z = (*in_x)[it];
if (z != arith->zero && z.hasFind() && core->find(z).getRHS() != z) continue;
if (z != y && z != x && x != y) {
IF_DEBUG(total ++;);
TRACE("diff update", "trying with ", z.toString() + " --> ", x.toString());
if (tryUpdate(z, x, y)) {
updated_in_y.push_back(z);
IF_DEBUG(updated++;);
}
}
}
TRACE("diff updates", "Updates : ", int2string(updated), " of " + int2string(total));
}
// For all edges coming into y, z_1 ---> y, and all edges going out of y, y ---> z_2, update z1 --> z_2
CDList<Expr>* out_y = outgoingEdges[y];
if (out_y)
for (unsigned it_z1 = 0; it_z1 < updated_in_y.size() && !isUnsat(); it_z1 ++) {
for (unsigned it_z2 = 0; it_z2 < out_y->size() && !isUnsat(); it_z2 ++) {
const Expr& z1 = updated_in_y[it_z1];
const Expr& z2 = (*out_y)[it_z2];
if (z2 != arith->zero && z2.hasFind() && core->find(z2).getRHS() != z2) continue;
if (z1 != z2 && z1 != y && z2 != y)
tryUpdate(z1, y, z2);
}
}
} else {
TRACE("arith propagate", "could have propagated ", edge_thm.getExpr(), edge_thm.isAssump() ? " ASSUMPTION " : "not assumption");
}
}
void TheoryArithOld::DifferenceLogicGraph::getEdgeTheorems(const Expr& x, const Expr& z, const EdgeInfo& edgeInfo, std::vector<Theorem>& outputTheorems) {
TRACE("arith diff", "Getting theorems from ", x, " to " + z.toString() + " length = " + edgeInfo.length.toString() + ", edge_length = " + int2string(edgeInfo.path_length_in_edges));
if (edgeInfo.path_length_in_edges == 1) {
DebugAssert(x == sourceVertex || z == sourceVertex || !edgeInfo.explanation.isNull(), "Edge from " + x.toString() + " to " + z.toString() + " has no theorem!");
if (x != sourceVertex && z != sourceVertex)
outputTheorems.push_back(edgeInfo.explanation);
}
else {
const Expr& y = edgeInfo.in_path_vertex;
EdgeInfo x_y = getEdge(x, y);
DebugAssert(x_y.isDefined(), "getEdgeTheorems: the cycle edge is not defined!");
EdgeInfo y_z = getEdge(y, z);
DebugAssert(y_z.isDefined(), "getEdgeTheorems: the cycle edge is not defined!");
getEdgeTheorems(x, y, x_y, outputTheorems);
getEdgeTheorems(y, z, y_z, outputTheorems);
}
}
void TheoryArithOld::DifferenceLogicGraph::analyseConflict(const Expr& x, int kind) {
// Get the cycle info
Graph::ElementReference x_x_cycle_ref = getEdge(x, x);
EdgeInfo x_x_cycle = x_x_cycle_ref.get();
DebugAssert(x_x_cycle.isDefined(), "analyseConflict: the cycle edge is not defined!");
// Vector to keep the theorems in
vector<Theorem> inequalities;
// Get the theorems::analyse
getEdgeTheorems(x, x, x_x_cycle, inequalities);
// Set the unsat theorem
unsat_theorem = rules->cycleConflict(inequalities);
TRACE("diff unsat", "negative cycle : ", int2string(inequalities.size()), " vertices.");
}
bool TheoryArithOld::DifferenceLogicGraph::tryUpdate(const Expr& x, const Expr& y, const Expr& z) {
// x -> y -> z, if z -> x they are all in a cycle
if (existsEdge(z, x)) {
varInCycle[x] = true;
varInCycle[y] = true;
varInCycle[z] = true;
}
//Get all the edges
Graph::ElementReference x_y_le_ref = getEdge(x, y);
EdgeInfo x_y_le = x_y_le_ref;
if (*d_pathLenghtThres >= 0 && x_y_le.path_length_in_edges > *d_pathLenghtThres) return false;
Graph::ElementReference y_z_le_ref = getEdge(y, z);
EdgeInfo y_z_le = y_z_le_ref;
if (*d_pathLenghtThres >= 0 && y_z_le.path_length_in_edges > *d_pathLenghtThres) return false;
Graph::ElementReference x_z_le_ref = getEdge(x, z);
EdgeInfo x_z_le = x_z_le_ref;
bool cycle = (x == z);
bool updated = false;
// Try <= + <= --> <=
if (!isUnsat() && x_y_le.isDefined() && y_z_le.isDefined()) {
EpsRational combined_length = x_y_le.length + y_z_le.length;
int combined_edge_length = x_y_le.path_length_in_edges + y_z_le.path_length_in_edges;
if (!x_z_le.isDefined() || combined_length < x_z_le.length ||
(combined_length == x_z_le.length && (combined_edge_length < x_z_le.path_length_in_edges))) {
if (!cycle || combined_length <= EpsRational::Zero) {
if (!cycle || combined_length < EpsRational::Zero) {
// Remember the path differences
if (!cycle) {
EpsRational difference = x_z_le.length - combined_length;
Rational rationalDifference = difference.getRational();
Rational newEpsilon = - x_z_le.length.getEpsilon();
if (rationalDifference > 0 && rationalDifference < smallestPathDifference) {
smallestPathDifference = rationalDifference;
TRACE("diff model", "smallest path difference : ", smallestPathDifference, "");
}
if (newEpsilon > biggestEpsilon) {
biggestEpsilon = newEpsilon;
TRACE("diff model", "biggest epsilon : ", biggestEpsilon, "");
}
}
// If we have a constraint among two integers variables strenghten it
bool addAndEnqueue = false;
if (core->okToEnqueue() && !combined_length.isInteger())
if (x.getType() == arith->intType() && z.getType() == arith->intType())
addAndEnqueue = true;
x_z_le.length = combined_length;
x_z_le.path_length_in_edges = combined_edge_length;
x_z_le.in_path_vertex = y;
x_z_le_ref = x_z_le;
if (addAndEnqueue) {
vector<Theorem> pathTheorems;
getEdgeTheorems(x, z, x_z_le, pathTheorems);
core->enqueueFact(rules->addInequalities(pathTheorems));
}
TRACE("arith diff", x.toString() + " -- > " + z.toString(), " : ", combined_length.toString());
updated = true;
} else
if (core->okToEnqueue()) {
// 0 length cycle
vector<Theorem> antecedentThms;
getEdgeTheorems(x, y, x_y_le, antecedentThms);
getEdgeTheorems(y, z, y_z_le, antecedentThms);
core->enqueueFact(rules->implyEqualities(antecedentThms));
}
// Try to propagate somthing in the original formula
if (updated && !cycle && x != sourceVertex && z != sourceVertex && core->okToEnqueue())
arith->tryPropagate(x, z, x_z_le, LE);
}
if (cycle && combined_length < EpsRational::Zero)
analyseConflict(x, LE);
}
}
return updated;
}
void TheoryArithOld::DifferenceLogicGraph::expandSharedTerm(const Expr& x) {
}
TheoryArithOld::DifferenceLogicGraph::~DifferenceLogicGraph() {
for (EdgesList::iterator it = incomingEdges.begin(), it_end = incomingEdges.end(); it != it_end; it ++) {
if ((*it).second) {
delete (*it).second;
free ((*it).second);
}
}
for (EdgesList::iterator it = outgoingEdges.begin(), it_end = outgoingEdges.end(); it != it_end; it ++) {
if ((*it).second) {
delete (*it).second;
free ((*it).second);
}
}
}
void TheoryArithOld::tryPropagate(const Expr& x, const Expr& y, const DifferenceLogicGraph::EdgeInfo& x_y_edge, int kind) {
TRACE("diff atoms", "trying propagation", " x = " + x.toString(), " y = " + y.toString());
// bail on non representative terms (we don't pass non-representative terms)
// if (x.hasFind() && find(x).getRHS() != x) return;
// if (y.hasFind() && find(y).getRHS() != y) return;
// given edge x - z (kind) lenth
// Make the index (c1 <= y - x)
vector<Expr> t1_summands;
t1_summands.push_back(rat(0));
if (y != zero) t1_summands.push_back(y);
// We have to canonize in case it is nonlinear
// nonlinear terms are canonized with a constants --> 1*x*y, hence (-1)*1*x*y will not be canonical
if (x != zero) t1_summands.push_back(canon(rat(-1)*x).getRHS());
Expr t1 = canon(plusExpr(t1_summands)).getRHS();
TRACE("diff atoms", "trying propagation", " t1 = " + t1.toString(), "");
// The constant c1 <= y - x
Rational c1 = - x_y_edge.length.getRational();
// See if we can propagate anything to the formula atoms
// c1 <= t1 ===> c <= t1 for c < c1
AtomsMap::iterator find = formulaAtomLowerBound.find(t1);
AtomsMap::iterator find_end = formulaAtomLowerBound.end();
if (find != find_end) {
set< pair<Rational, Expr> >::iterator bounds = (*find).second.begin();
set< pair<Rational, Expr> >::iterator bounds_end = (*find).second.end();
while (bounds != bounds_end) {
const Expr& implied = (*bounds).second;
// Try to do some theory propagation
if ((*bounds).first < c1 || (implied.getKind() == LE && (*bounds).first == c1)) {
TRACE("diff atoms", "found propagation", "", "");
// c1 <= t1 => c <= t1 (for c <= c1)
// c1 < t1 => c <= t1 (for c <= c1)
// c1 <= t1 => c < t1 (for c < c1)
vector<Theorem> antecedentThms;
diffLogicGraph.getEdgeTheorems(x, y, x_y_edge, antecedentThms);
Theorem impliedThm = d_rules->implyWeakerInequalityDiffLogic(antecedentThms, implied);
enqueueFact(impliedThm);
}
bounds ++;
}
}
//
// c1 <= t1 ==> !(t1 <= c) for c < c1
// ==> !(-c <= t2)
// i.e. all coefficient in in the implied are opposite of t1
find = formulaAtomUpperBound.find(t1);
find_end = formulaAtomUpperBound.end();
if (find != find_end) {
set< pair<Rational, Expr> >::iterator bounds = (*find).second.begin();
set< pair<Rational, Expr> >::iterator bounds_end = (*find).second.end();
while (bounds != bounds_end) {
const Expr& implied = (*bounds).second;
// Try to do some theory propagation
if ((*bounds).first < c1) {
TRACE("diff atoms", "found negated propagation", "", "");
vector<Theorem> antecedentThms;
diffLogicGraph.getEdgeTheorems(x, y, x_y_edge, antecedentThms);
Theorem impliedThm = d_rules->implyNegatedInequalityDiffLogic(antecedentThms, implied);
enqueueFact(impliedThm);
}
bounds ++;
}
}
}
void TheoryArithOld::DifferenceLogicGraph::computeModel() {
// If source vertex is null, create it
if (sourceVertex.isNull()) {
Theorem thm_exists_zero = arith->getCommonRules()->varIntroSkolem(arith->zero);
sourceVertex = thm_exists_zero.getExpr()[1];
}
// The empty theorem to pass around
Theorem thm;
// Add an edge to all the vertices
EdgesList::iterator vertexIt = incomingEdges.begin();
EdgesList::iterator vertexItEnd = incomingEdges.end();
for (; vertexIt != vertexItEnd; vertexIt ++) {
Expr vertex = (*vertexIt).first;
if (core->find(vertex).getRHS() != vertex) continue;
if (vertex != sourceVertex && !existsEdge(sourceVertex, vertex))
addEdge(sourceVertex, vertex, 0, thm);
}
vertexIt = outgoingEdges.begin();
vertexItEnd = outgoingEdges.end();
for (; vertexIt != vertexItEnd; vertexIt ++) {
Expr vertex = (*vertexIt).first;
if (core->find(vertex).getRHS() != vertex) continue;
if (vertex != sourceVertex && !existsEdge(sourceVertex, vertex))
addEdge(sourceVertex, vertex, 0, thm);
}
// Also add an edge to cvcZero
if (!existsEdge(sourceVertex, arith->zero))
addEdge(sourceVertex, arith->zero, 0, thm);
// For the < edges we will have a small enough epsilon to add
// So, we will upper-bound the number of vertices and then divide
// the smallest edge with that number so as to not be able to bypass
}
Rational TheoryArithOld::DifferenceLogicGraph::getValuation(const Expr& x) {
// For numbers, return it's value
if (x.isRational()) return x.getRational();
// For the source vertex, we don't care
if (x == sourceVertex) return 0;
// The path from source to targer vertex
Graph::ElementReference x_le_c_ref = getEdge(sourceVertex, x);
EdgeInfo x_le_c = x_le_c_ref;
// The path from source to zero (adjusment)
Graph::ElementReference zero_le_c_ref = getEdge(sourceVertex, arith->zero);
EdgeInfo zero_le_c = zero_le_c_ref;
TRACE("diff model", "zero adjustment: ", zero_le_c.length.getRational(), "");
TRACE("diff model", "zero adjustment (eps): ", zero_le_c.length.getEpsilon(), "");
// Value adjusted with the epsilon
Rational epsAdjustment = (biggestEpsilon > 0 ? (x_le_c.length.getEpsilon() - zero_le_c.length.getEpsilon()) * smallestPathDifference / (2 * (biggestEpsilon + 1)) : 0);
Rational value = x_le_c.length.getRational() + epsAdjustment;
TRACE("diff model" , "biggest epsilon: ", biggestEpsilon, "");
TRACE("diff model" , "smallestPathDifference: ", smallestPathDifference, "");
TRACE("diff model" , "x_le_c.getEpsilon: ", x_le_c.length.getEpsilon(), "");
TRACE("diff model" , "x_le_c.length: ", x_le_c.length.getRational(), "");
// Value adjusted with the shift for zero
value = zero_le_c.length.getRational() - value;
TRACE("diff model", "Value of ", x, " : " + value.toString());
// Return it
return value;
}
// The infinity constant
const TheoryArithOld::DifferenceLogicGraph::EpsRational TheoryArithOld::DifferenceLogicGraph::EpsRational::PlusInfinity(PLUS_INFINITY);
// The negative infinity constant
const TheoryArithOld::DifferenceLogicGraph::EpsRational TheoryArithOld::DifferenceLogicGraph::EpsRational::MinusInfinity(MINUS_INFINITY);
// The negative infinity constant
const TheoryArithOld::DifferenceLogicGraph::EpsRational TheoryArithOld::DifferenceLogicGraph::EpsRational::Zero;
void TheoryArithOld::addMultiplicativeSignSplit(const Theorem& case_split_thm) {
multiplicativeSignSplits.push_back(case_split_thm);
}
bool TheoryArithOld::addPairToArithOrder(const Expr& smaller, const Expr& bigger) {
TRACE("arith var order", "addPairToArithOrder(" + smaller.toString(), ", ", bigger.toString() + ")");
// We only accept arithmetic terms
if (!isReal(smaller.getType()) && !isInt(smaller.getType())) return false;
if (!isReal(bigger.getType()) && !isInt(bigger.getType())) return false;
// We don't want to introduce loops
FatalAssert(!d_graph.lessThan(smaller, bigger), "The pair (" + bigger.toString() + "," + smaller.toString() + ") is already in the order");
// Update the graph
d_graph.addEdge(smaller, bigger);
return true;
}
bool TheoryArithOld::isNonlinearSumTerm(const Expr& term) {
if (isPow(term)) return true;
if (!isMult(term)) return false;
int vars = 0;
for (int j = 0; j < term.arity(); j ++)
if (isPow(term[j])) return true;
else if (isLeaf(term[j])) {
vars ++;
if (vars > 1) return true;
}
return false;
}
bool TheoryArithOld::isNonlinearEq(const Expr& e) {
DebugAssert(e.isEq(), "TheoryArithOld::isNonlinear: expecting an equation" + e.toString());
const Expr& lhs = e[0];
const Expr& rhs = e[1];
if (isNonlinearSumTerm(lhs) || isNonlinearSumTerm(rhs)) return true;
// Check the right-hand side
for (int i = 0; i < lhs.arity(); i ++)
if (isNonlinearSumTerm(lhs[i])) return true;
// Check the left hand side
for (int i = 0; i < rhs.arity(); i ++)
if (isNonlinearSumTerm(rhs[i])) return true;
return false;
}
bool TheoryArithOld::isPowersEquality(const Expr& eq, Expr& power1, Expr& power2) {
// equality should be in the form 0 + x1^n - x2^n = 0
DebugAssert(eq.isEq(), "TheoryArithOld::isPowersEquality, expecting an equality got " + eq.toString());
if (!isPlus(eq[0])) return false;
if (eq[0].arity() != 3) return false;
if (!(eq[0][0].isRational()) || !(eq[0][0].getRational() == 0)) return false;
// Process the first term
Expr term1 = eq[0][1];
Rational term1_c;
if (isPow(term1)) {
term1_c = 1;
power1 = term1;
} else
if (isMult(term1) && term1.arity() == 2) {
if (term1[0].isRational()) {
term1_c = term1[0].getRational();
if (isPow(term1[1])) {
if (term1_c == 1) power1 = term1[1];
else if (term1_c == -1) power2 = term1[1];
else return false;
} else return false;
} else return false;
} else return false;
// Process the second term
Expr term2 = eq[0][2];
Rational term2_c;
if (isPow(term2)) {
term2_c = 1;
power1 = term2;
} else
if (isMult(term2) && term2.arity() == 2) {
if (term2[0].isRational()) {
term2_c = term2[0].getRational();
if (isPow(term2[1])) {
if (term2_c == 1) power1 = term2[1];
else if (term2_c == -1) power2 = term2[1];
else return false;
} else return false;
} else return false;
} else return false;
// Check that they are of opposite signs
if (term1_c == term2_c) return false;
// Check that the powers are equal numbers
if (!power1[0].isRational()) return false;
if (!power2[0].isRational()) return false;
if (power1[0].getRational() != power2[0].getRational()) return false;
// Everything is fine
return true;
}
bool TheoryArithOld::isPowerEquality(const Expr& eq, Rational& constant, Expr& power1) {
DebugAssert(eq.isEq(), "TheoryArithOld::isPowerEquality, expecting an equality got " + eq.toString());
if (!isPlus(eq[0])) return false;
if (eq[0].arity() != 2) return false;
if (!eq[0][0].isRational()) return false;
constant = eq[0][0].getRational();
Expr term = eq[0][1];
if (isPow(term)) {
power1 = term;
constant = -constant;
} else
if (isMult(term) && term.arity() == 2) {
if (term[0].isRational() && isPow(term[1])) {
Rational term2_c = term[0].getRational();
if (term2_c == 1) {
power1 = term[1];
constant = -constant;
} else if (term2_c == -1) {
power1 = term[1];
return true;
} else return false;
} else return false;
} else return false;
// Check that the power is an integer
if (!power1[0].isRational()) return false;
if (!power1[0].getRational().isInteger()) return false;
return true;
}
int TheoryArithOld::termDegree(const Expr& e) {
if (isLeaf(e)) return 1;
if (isPow(e)) return termDegree(e[1]) * e[0].getRational().getInt();
if (isMult(e)) {
int degree = 0;
for (int i = 0; i < e.arity(); i ++) degree += termDegree(e[i]);
return degree;
}
return 0;
}
bool TheoryArithOld::canPickEqMonomial(const Expr& right)
{
Expr::iterator istart = right.begin();
Expr::iterator iend = right.end();
// Skip the first one
istart++;
for(Expr::iterator i = istart; i != iend; ++i) {
Expr leaf;
Rational coeff;
// Check if linear term
if (isLeaf(*i)) {
leaf = *i;
coeff = 1;
} else if (isMult(*i) && (*i).arity() == 2 && (*i)[0].isRational() && isLeaf((*i)[1])) {
leaf = (*i)[1];
coeff = abs((*i)[0].getRational());
} else
continue;
// If integer, must be coeff 1/-1
if (!isIntegerThm(leaf).isNull())
if (coeff != 1 && coeff != -1)
continue;
// Check if a leaf in other ones
Expr::iterator j;
for (j = istart; j != iend; ++j)
if (j != i && isLeafIn(leaf, *j))
break;
if (j == iend)
return true;
}
return false;
}
bool TheoryArithOld::isBounded(const Expr& t, BoundsQueryType queryType) {
TRACE("arith shared", "isBounded(", t.toString(), ")");
return hasUpperBound(t, queryType) && hasLowerBound(t, queryType);
}
TheoryArithOld::DifferenceLogicGraph::EpsRational TheoryArithOld::getUpperBound(const Expr& t, BoundsQueryType queryType)
{
TRACE("arith shared", "getUpperBound(", t.toString(), ")");
// If t is a constant it's bounded
if (t.isRational()) {
TRACE("arith shared", "getUpperBound(", t.toString(), ") ==> " + t.getRational().toString());
return t.getRational();
}
// If buffered, just return it
CDMap<Expr, DifferenceLogicGraph::EpsRational>::iterator find_t = termUpperBounded.find(t);
if (find_t != termUpperBounded.end()) {
TRACE("arith shared", "getUpperBound(", t.toString(), ") ==> " + (*find_t).second.toString());
return (*find_t).second;
} else if (queryType == QueryWithCacheAll) {
// Asked for cache query, so no bound is found
TRACE("arith shared", "getUpperBound(", t.toString(), ") ==> +inf");
return DifferenceLogicGraph::EpsRational::PlusInfinity;
}
// Assume it's not bounded
DifferenceLogicGraph::EpsRational upperBound = DifferenceLogicGraph::EpsRational::PlusInfinity;
// We always buffer the leaves, so all that's left are the terms
if (!isLeaf(t)) {
if (isMult(t)) {
// We only handle linear terms
if (!isNonlinearSumTerm(t)) {
// Separate the multiplication
Expr c, v;
separateMonomial(t, c, v);
// Get the upper-bound for the variable
if (c.getRational() > 0) upperBound = getUpperBound(v);
else upperBound = getLowerBound(v);
if (upperBound.isFinite()) upperBound = upperBound * c.getRational();
else upperBound = DifferenceLogicGraph::EpsRational::PlusInfinity;
}
} else if (isPlus(t)) {
// If one of them is unconstrained then the term itself is unconstrained
upperBound = DifferenceLogicGraph::EpsRational::Zero;
for (int i = 0; i < t.arity(); i ++) {
Expr t_i = t[i];
DifferenceLogicGraph::EpsRational t_i_upperBound = getUpperBound(t_i, queryType);
if (t_i_upperBound.isFinite()) upperBound = upperBound + t_i_upperBound;
else {
upperBound = DifferenceLogicGraph::EpsRational::PlusInfinity;
// Not-bounded, check for constrained
if (queryType == QueryWithCacheLeavesAndConstrainedComputation) {
for(; i < t.arity() && isConstrainedAbove(t[i], QueryWithCacheLeaves); i ++);
if (i == t.arity()) {
TRACE("arith shared", "getUpperBound(", t.toString(), ") ==> constrained");
termConstrainedAbove[t] = true;
}
break;
} else break;
}
}
}
}
// Buffer it
if (upperBound.isFinite()) {
termUpperBounded[t] = upperBound;
termConstrainedAbove[t] = true;
}
// Return if bounded or not
TRACE("arith shared", "getUpperBound(", t.toString(), ") ==> " + upperBound.toString());
return upperBound;
}
TheoryArithOld::DifferenceLogicGraph::EpsRational TheoryArithOld::getLowerBound(const Expr& t, BoundsQueryType queryType)
{
TRACE("arith shared", "getLowerBound(", t.toString(), ")");
// If t is a constant it's bounded
if (t.isRational()) {
TRACE("arith shared", "getLowerBound(", t.toString(), ") ==> " + t.getRational().toString());
return t.getRational();
}
// If buffered, just return it
CDMap<Expr, DifferenceLogicGraph::EpsRational>::iterator t_find = termLowerBounded.find(t);
if (t_find != termLowerBounded.end()) {
TRACE("arith shared", "getLowerBound(", t.toString(), ") ==> " + (*t_find).second.toString());
return (*t_find).second;
} else if (queryType == QueryWithCacheAll) {
// Asked for cache query, so no bound is found
TRACE("arith shared", "getLowerBound(", t.toString(), ") ==> -inf");
return DifferenceLogicGraph::EpsRational::MinusInfinity;
}
// Assume it's not bounded
DifferenceLogicGraph::EpsRational lowerBound = DifferenceLogicGraph::EpsRational::MinusInfinity;
// Leaves are always buffered
if (!isLeaf(t)) {
if (isMult(t)) {
// We only handle linear terms
if (!isNonlinearSumTerm(t)) {
// Separate the multiplication
Expr c, v;
separateMonomial(t, c, v);
// Get the upper-bound for the variable
if (c.getRational() > 0) lowerBound = getLowerBound(v);
else lowerBound = getUpperBound(v);
if (lowerBound.isFinite()) lowerBound = lowerBound * c.getRational();
else lowerBound = DifferenceLogicGraph::EpsRational::MinusInfinity;
}
} else if (isPlus(t)) {
// If one of them is unconstrained then the term itself is unconstrained
lowerBound = DifferenceLogicGraph::EpsRational::Zero;
for (int i = 0; i < t.arity(); i ++) {
Expr t_i = t[i];
DifferenceLogicGraph::EpsRational t_i_lowerBound = getLowerBound(t_i, queryType);
if (t_i_lowerBound.isFinite()) lowerBound = lowerBound + t_i_lowerBound;
else {
lowerBound = DifferenceLogicGraph::EpsRational::MinusInfinity;
// Not-bounded, check for constrained
if (queryType == QueryWithCacheLeavesAndConstrainedComputation) {
for(; i < t.arity() && isConstrainedBelow(t[i], QueryWithCacheLeaves); i ++);
if (i == t.arity()) {
TRACE("arith shared", "getLowerBound(", t.toString(), ") ==> constrained");
termConstrainedBelow[t] = true;
}
break;
} else break;
}
}
}
}
// Buffer it
if (lowerBound.isFinite()) {
termLowerBounded[t] = lowerBound;
termConstrainedBelow[t] = true;
}
// Return if bounded or not
TRACE("arith shared", "getLowerBound(", t.toString(), ") ==> " + lowerBound.toString());
return lowerBound;
}
int TheoryArithOld::computeTermBounds()
{
int computeTermBoundsConstrainedCount = 0;
vector<Expr> sorted_vars;
// Get the variables in the topological order
if (!diffLogicOnly) d_graph.getVerticesTopological(sorted_vars);
// Or if difference logic only, just get them
else {
diffLogicGraph.getVariables(sorted_vars);
IF_DEBUG(
diffLogicGraph.writeGraph(cerr);
)
}
// Go in the reverse topological order and try to see if the vats are constrained/bounded
for (int i = sorted_vars.size() - 1; i >= 0; i --)
{
// Get the variable
Expr v = sorted_vars[i];
// If the find is not identity, skip it
if (v.hasFind() && find(v).getRHS() != v) continue;
TRACE("arith shared", "processing: ", v.toString(), "");
// If the variable is not an integer, it's unconstrained, unless we are in model generation
if (isIntegerThm(v).isNull() && !d_inModelCreation) continue;
// We only do the computation if the variable is not already constrained
if (!isConstrained(v, QueryWithCacheAll)) {
// Recall if we already computed the constraint
bool constrainedAbove = isConstrained(v, QueryWithCacheAll);
// See if it's bounded from above in the difference graph
DifferenceLogicGraph::EpsRational upperBound = diffLogicGraph.getEdgeWeight(v, zero);
if (!constrainedAbove) constrainedAbove = upperBound.isFinite();
// Try to refine the bound by checking projected inequalities
if (!diffLogicOnly) {
ExprMap<CDList<Ineq> *>::iterator v_left_find = d_inequalitiesLeftDB.find(v);
// If not constraint from one side, it's unconstrained
if (v_left_find != d_inequalitiesLeftDB.end()) {
// Check right hand side for an unconstrained variable
CDList<Ineq>*& left_list = (*v_left_find).second;
if (left_list && left_list->size() > 0) {
for (unsigned ineq_i = 0; ineq_i < left_list->size(); ineq_i ++) {
// Get the inequality
Ineq ineq = (*left_list)[ineq_i];
// Get the right-hand side (v <= rhs)
Expr rhs = ineq.ineq().getExpr()[1];
// If rhs changed, skip it
if (rhs.hasFind() && find(rhs).getRHS() != rhs) continue;
// Compute the upper bound while
DifferenceLogicGraph::EpsRational currentUpperBound = getUpperBound(rhs, (constrainedAbove ? QueryWithCacheLeaves : QueryWithCacheLeavesAndConstrainedComputation));
if (currentUpperBound.isFinite() && (!upperBound.isFinite() || currentUpperBound < upperBound)) {
upperBound = currentUpperBound;
constrainedAbove = true;
}
// If not constrained, check if right-hand-side is constrained
if (!constrainedAbove) constrainedAbove = isConstrainedAbove(rhs, QueryWithCacheAll);
}
}
}
}
// Difference logic case (no projections)
else if (!constrainedAbove) {
// If there is no incoming edges, then the variable is not constrained
if (!diffLogicGraph.hasIncoming(v)) constrainedAbove = false;
// If there is a cycle from t to t, all the variables
// in the graph are constrained by each-other (we could
// choose one, but it's too complicated)
else if (diffLogicGraph.inCycle(v)) constrainedAbove = true;
// Otherwise, since there is no bounds, and the cycles
// can be shifted (since one of them can be taken as
// unconstrained), we can assume that the variables is
// not constrained. Conundrum here is that when in model-generation
// we actually should take it as constrained so that it's
// split on and we are on the safe side
else constrainedAbove = d_inModelCreation;
}
// Cache the upper bound and upper constrained computation
if (constrainedAbove) termConstrainedAbove[v] = true;
if (upperBound.isFinite()) termUpperBounded[v] = upperBound;
// Recall the below computation if it's there
bool constrainedBelow = isConstrainedBelow(v, QueryWithCacheAll);
// See if it's bounded from below in the difference graph
DifferenceLogicGraph::EpsRational lowerBound = diffLogicGraph.getEdgeWeight(zero, v);
if (lowerBound.isFinite()) lowerBound = -lowerBound;
else lowerBound = DifferenceLogicGraph::EpsRational::MinusInfinity;
if (!constrainedBelow) constrainedBelow = lowerBound.isFinite();
// Try to refine the bound by checking projected inequalities
if (!diffLogicOnly) {
ExprMap<CDList<Ineq> *>::iterator v_right_find = d_inequalitiesRightDB.find(v);
// If not constraint from one side, it's unconstrained
if (v_right_find != d_inequalitiesRightDB.end()) {
// Check right hand side for an unconstrained variable
CDList<Ineq>*& right_list = (*v_right_find).second;
if (right_list && right_list->size() > 0) {
for (unsigned ineq_i = 0; ineq_i < right_list->size(); ineq_i ++) {
// Get the inequality
Ineq ineq = (*right_list)[ineq_i];
// Get the right-hand side (lhs <= 0)
Expr lhs = ineq.ineq().getExpr()[0];
// If lhs has changed, skip it
if (lhs.hasFind() && find(lhs).getRHS() != lhs) continue;
// Compute the lower bound
DifferenceLogicGraph::EpsRational currentLowerBound = getLowerBound(lhs, (constrainedBelow ? QueryWithCacheLeaves : QueryWithCacheLeavesAndConstrainedComputation));
if (currentLowerBound.isFinite() && (!lowerBound.isFinite() || currentLowerBound > lowerBound)) {
lowerBound = currentLowerBound;
constrainedBelow = true;
}
// If not constrained, check if right-hand-side is constrained
if (!constrainedBelow) constrainedBelow = isConstrainedBelow(lhs, QueryWithCacheAll);
}
}
}
}
// Difference logic case (no projections)
else if (!constrainedBelow) {
// If there is no incoming edges, then the variable is not constrained
if (!diffLogicGraph.hasOutgoing(v)) constrainedBelow = false;
// If there is a cycle from t to t, all the variables
// in the graph are constrained by each-other (we could
// choose one, but it's too complicated)
else if (diffLogicGraph.inCycle(v)) constrainedBelow = true;
// Otherwise, since there is no bounds, and the cycles
// can be shifted (since one of them can be taken as
// unconstrained), we can assume that the variables is
// not constrained. Conundrum here is that when in model-generation
// we actually should take it as constrained so that it's
// split on and we are on the safe side
else constrainedBelow = d_inModelCreation;
}
// Cache the lower bound and lower constrained computation
if (constrainedBelow) termConstrainedBelow[v] = true;
if (lowerBound.isFinite()) termLowerBounded[v] = lowerBound;
// Is this variable constrained
if (constrainedAbove && constrainedBelow) computeTermBoundsConstrainedCount ++;
TRACE("arith shared", (constrainedAbove && constrainedBelow ? "constrained " : "unconstrained "), "", "");
} else
computeTermBoundsConstrainedCount ++;
}
TRACE("arith shared", "number of constrained variables : ", int2string(computeTermBoundsConstrainedCount), " of " + int2string(sorted_vars.size()));
return computeTermBoundsConstrainedCount;
}
bool TheoryArithOld::isConstrainedAbove(const Expr& t, BoundsQueryType queryType)
{
TRACE("arith shared", "isConstrainedAbove(", t.toString(), ")");
// Rational numbers are constrained
if (t.isRational()) {
TRACE("arith shared", "isConstrainedAbove() ==> true", "", "");
return true;
}
// Look it up in the cache
CDMap<Expr, bool>::iterator t_find = termConstrainedAbove.find(t);
if (t_find != termConstrainedAbove.end()) {
TRACE("arith shared", "isConstrainedAbove() ==> true", "", "");
return true;
}
else if (queryType == QueryWithCacheAll) {
TRACE("arith shared", "isConstrainedAbove() ==> false", "", "");
return false;
}
bool constrainedAbove = true;
if (isLeaf(t)) {
// Leaves are always cached
constrainedAbove = false;
} else {
if (isMult(t)) {
// Non-linear terms are constrained by default
// we only deal with the linear stuff
if (!isNonlinearSumTerm(t)) {
// Separate the multiplication
Expr c, v;
separateMonomial(t, c, v);
// Check if the variable is constrained
if (c.getRational() > 0) constrainedAbove = isConstrainedAbove(v, queryType);
else constrainedAbove = isConstrainedBelow(v, queryType);
}
} else if (isPlus(t)) {
// If one of them is unconstrained then the term itself is unconstrained
for (int i = 0; i < t.arity() && constrainedAbove; i ++)
if (!isConstrainedAbove(t[i])) constrainedAbove = false;
}
}
// Remember it
if (constrainedAbove) termConstrainedAbove[t] = true;
TRACE("arith shared", "isConstrainedAbove() ==> ", constrainedAbove ? "true" : "false", "");
// Return in
return constrainedAbove;
}
bool TheoryArithOld::isConstrainedBelow(const Expr& t, BoundsQueryType queryType)
{
TRACE("arith shared", "isConstrainedBelow(", t.toString(), ")");
// Rational numbers are constrained
if (t.isRational()) return true;
// Look it up in the cache
CDMap<Expr, bool>::iterator t_find = termConstrainedBelow.find(t);
if (t_find != termConstrainedBelow.end()) {
TRACE("arith shared", "isConstrainedBelow() ==> true", "", "");
return true;
}
else if (queryType == QueryWithCacheAll) {
TRACE("arith shared", "isConstrainedBelow() ==> false", "", "");
return false;
}
bool constrainedBelow = true;
if (isLeaf(t)) {
// Leaves are always cached
constrainedBelow = false;
} else {
if (isMult(t)) {
// Non-linear terms are constrained by default
// we only deal with the linear stuff
if (!isNonlinearSumTerm(t)) {
// Separate the multiplication
Expr c, v;
separateMonomial(t, c, v);
// Check if the variable is constrained
if (c.getRational() > 0) constrainedBelow = isConstrainedBelow(v, queryType);
else constrainedBelow = isConstrainedAbove(v, queryType);
}
} else if (isPlus(t)) {
// If one of them is unconstrained then the term itself is unconstrained
constrainedBelow = true;
for (int i = 0; i < t.arity() && constrainedBelow; i ++)
if (!isConstrainedBelow(t[i]))
constrainedBelow = false;
}
}
// Cache it
if (constrainedBelow) termConstrainedBelow[t] = true;
TRACE("arith shared", "isConstrainedBelow() ==> ", constrainedBelow ? "true" : "false", "");
// Return it
return constrainedBelow;
}
bool TheoryArithOld::isConstrained(const Expr& t, bool intOnly, BoundsQueryType queryType)
{
TRACE("arith shared", "isConstrained(", t.toString(), ")");
// For the reals we consider them unconstrained if not asked for full check
if (intOnly && isIntegerThm(t).isNull()) return false;
bool result = (isConstrainedAbove(t, queryType) && isConstrainedBelow(t, queryType));
TRACE("arith shared", "isConstrained(", t.toString(), (result ? ") ==> true " : ") ==> false ") );
return result;
}
bool TheoryArithOld::DifferenceLogicGraph::hasIncoming(const Expr& x)
{
EdgesList::iterator find_x = incomingEdges.find(x);
// No edges at all meaning no incoming
if (find_x == incomingEdges.end()) return false;
// The pointer being null, also no incoming
CDList<Expr>*& list = (*find_x).second;
if (!list) return false;
// If in model creation, source vertex goes to all vertices
if (sourceVertex.isNull())
return list->size() > 0;
else
return list->size() > 1;
}
bool TheoryArithOld::DifferenceLogicGraph::hasOutgoing(const Expr& x)
{
EdgesList::iterator find_x = outgoingEdges.find(x);
// No edges at all meaning no incoming
if (find_x == outgoingEdges.end()) return false;
// The pointer being null, also no incoming
CDList<Expr>*& list = (*find_x).second;
if (!list) return false;
// If the list is not empty we have outgoing edges
return list->size() > 0;
}
void TheoryArithOld::DifferenceLogicGraph::getVariables(vector<Expr>& variables)
{
set<Expr> vars_set;
EdgesList::iterator incoming_it = incomingEdges.begin();
EdgesList::iterator incoming_it_end = incomingEdges.end();
while (incoming_it != incoming_it_end) {
Expr var = (*incoming_it).first;
if (var != sourceVertex)
vars_set.insert(var);
incoming_it ++;
}
EdgesList::iterator outgoing_it = outgoingEdges.begin();
EdgesList::iterator outgoing_it_end = outgoingEdges.end();
while (outgoing_it != outgoing_it_end) {
Expr var = (*outgoing_it).first;
if (var != sourceVertex)
vars_set.insert(var);
outgoing_it ++;
}
set<Expr>::iterator set_it = vars_set.begin();
set<Expr>::iterator set_it_end = vars_set.end();
while (set_it != set_it_end) {
variables.push_back(*set_it);
set_it ++;
}
}
void TheoryArithOld::DifferenceLogicGraph::writeGraph(ostream& out) {
return;
out << "digraph G {" << endl;
EdgesList::iterator incoming_it = incomingEdges.begin();
EdgesList::iterator incoming_it_end = incomingEdges.end();
while (incoming_it != incoming_it_end) {
Expr var_u = (*incoming_it).first;
CDList<Expr>* edges = (*incoming_it).second;
if (edges)
for (unsigned edge_i = 0; edge_i < edges->size(); edge_i ++) {
Expr var_v = (*edges)[edge_i];
out << var_u.toString() << " -> " << var_v.toString() << endl;
}
incoming_it ++;
}
out << "}" << endl;
}
| 33.892341 | 182 | 0.601031 | [
"vector",
"model",
"transform"
] |
9182ed15c05dd24cd7747db254a6e08b62ecc0a5 | 4,883 | hpp | C++ | src/e2/src/ASN1/lib/e2ap_config.hpp | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 5 | 2020-08-31T08:27:42.000Z | 2022-03-27T10:39:37.000Z | src/e2/src/ASN1/lib/e2ap_config.hpp | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 1 | 2020-08-28T23:32:17.000Z | 2020-08-28T23:32:17.000Z | src/e2/src/ASN1/lib/e2ap_config.hpp | shadansari/onos-cu-cp | 16cbf4828bd11e4c7319e7a009a26b6f39fde628 | [
"Apache-2.0"
] | 5 | 2020-08-27T23:04:34.000Z | 2021-11-17T01:49:52.000Z | /*****************************************************************************
# *
# Copyright 2019 AT&T Intellectual Property *
# Copyright 2019 Nokia *
# *
# 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 E2AP_CONFIG_HPP
#define E2AP_CONFIG_HPP
#include <string>
#include <vector>
enum enum_Transmission_Bandwidth {
enum_bw6,
enum_bw15,
enum_bw25,
enum_bw50,
enum_bw75,
enum_bw100,
enum_bw1
};
enum enum_NRNRB{
enum_nrb11, enum_nrb18, enum_nrb24, enum_nrb25, enum_nrb31, enum_nrb32,
enum_nrb38, enum_nrb51, enum_nrb52, enum_nrb65, enum_nrb66, enum_nrb78,
enum_nrb79, enum_nrb93, enum_nrb106, enum_nrb107, enum_nrb121,
enum_nrb132, enum_nrb133, enum_nrb135, enum_nrb160, enum_nrb162,
enum_nrb189, enum_nrb216, enum_nrb217, enum_nrb245, enum_nrb264,
enum_nrb270, enum_nrb273
};
enum enum_NRSCS {
enum_scs15, enum_scs30, enum_scs60, enum_scs120
};
class eNB_config {
public:
uint8_t* pLMN_Identity;
uint8_t* macro_eNB_ID;
int64_t pCI;
uint8_t* tAC;
uint8_t* eUTRANcellIdentifier;
int64_t uL_EARFCN;
int64_t dL_EARFCN;
enum_Transmission_Bandwidth uL_Bandwidth;
enum_Transmission_Bandwidth dL_Bandwidth;
/*Default Constructor*/
eNB_config() {
pLMN_Identity = (uint8_t*)"abc";
macro_eNB_ID = (uint8_t*)"5";
pCI = 0;
tAC = (uint8_t*)"ab";
eUTRANcellIdentifier = (uint8_t*)"def";
uL_EARFCN = 21400;
dL_EARFCN = 3400;
uL_Bandwidth = enum_bw25;
dL_Bandwidth = enum_bw50;
}
};
class gNB_config {
public:
uint8_t* pLMN_Identity;
uint8_t* gNB_ID;
int64_t nrpCI;
uint8_t* tAC;
uint8_t* nRcellIdentifier;
int64_t uL_nRARFCN;
int64_t dL_nRARFCN;
enum enum_NRNRB uL_NRNRB;
enum enum_NRNRB dL_NRNRB;
enum enum_NRSCS uL_NRSCS;
enum enum_NRSCS dL_NRSCS;
uint8_t ul_freqBandIndicatorNr;
uint8_t dl_freqBandIndicatorNr;
std::string measurementTimingConfiguration;
/*Default Constructor*/
gNB_config() {
pLMN_Identity = (uint8_t*)"xyz";
gNB_ID = (uint8_t*)"3";
nrpCI = 1;
tAC = (uint8_t*)"ab";
nRcellIdentifier = (uint8_t*)"gnb_id_123";
uL_nRARFCN = 21400;
dL_nRARFCN = 21500;
uL_NRNRB = enum_nrb11;
dL_NRNRB = enum_nrb121;
uL_NRSCS = enum_scs15;
dL_NRSCS = enum_scs120;
ul_freqBandIndicatorNr = 11;
dl_freqBandIndicatorNr = 12;
measurementTimingConfiguration = "dummy timing";
}
};
enum enum_RICactionType {
RICactionType_report,
RICactionType_insert,
RICactionType_policy
};
enum enum_RICcause {
RICcause_radioNetwork = 1,
RICcause_transport,
RICcause_protocol,
RICcause_misc,
RICcause_ric
};
struct RIC_action_t {
unsigned char action_id;
enum_RICactionType action_type;
bool isAdmitted = false; //for response/failure only
enum_RICcause notAdmitted_cause; //for response/failure only
unsigned int notAdmitted_subCause; //for response/failure only
RIC_action_t() {;}
RIC_action_t(unsigned char id, enum_RICactionType type)
{
action_id = id;
action_type = type;
}
};
struct RICsubscription_params_t {
uint16_t request_id = 0;
uint16_t seq_number = 0;
uint16_t ran_func_id = 0;
std::string event_trigger_def = "";
std::vector<RIC_action_t> actionList;
} ;
#endif
| 30.329193 | 79 | 0.545976 | [
"vector"
] |
9183cd2bf2299bc7b5fba9574c23cbef99a6aaaf | 32,236 | cpp | C++ | src/ringct/rctSigs.cpp | flywithfang/dfa | 8f796294a2c8ed24f142183545ab87afd77c2b4e | [
"MIT"
] | null | null | null | src/ringct/rctSigs.cpp | flywithfang/dfa | 8f796294a2c8ed24f142183545ab87afd77c2b4e | [
"MIT"
] | null | null | null | src/ringct/rctSigs.cpp | flywithfang/dfa | 8f796294a2c8ed24f142183545ab87afd77c2b4e | [
"MIT"
] | null | null | null | // Copyright (c) 2016, Monero Research Labs
//
// Author: Shen Noether <shen.noether@gmx.com>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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 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 "misc_log_ex.h"
#include "misc_language.h"
#include "common/perf_timer.h"
#include "common/threadpool.h"
#include "common/util.h"
#include "rctSigs.h"
#include "bulletproofs.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_config.h"
using namespace crypto;
using namespace std;
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "ringct"
#define CHECK_AND_ASSERT_MES_L1(expr, ret, message) {if(!(expr)) {MCERROR("verify", message); return ret;}}
namespace rct {
Bulletproof proveRangeBulletproof(keyV &C, keyV &noises, const std::vector<uint64_t> &amounts, const std::vector<key>& shared_secs)
{
CHECK_AND_ASSERT_THROW_MES(amounts.size() == shared_secs.size(), "Invalid amounts/sk sizes");
noises.resize(amounts.size());
for (size_t i = 0; i < amounts.size(); ++i)
{
const key & shared_sec = shared_secs[i];
noises[i] = rct::genCommitmentMask(shared_sec);
}
Bulletproof proof = bulletproof_PROVE(amounts, noises);
CHECK_AND_ASSERT_THROW_MES(proof.V.size() == amounts.size(), "V does not have the expected size");
C = proof.V;
return proof;
}
bool verBulletproof(const Bulletproof &proof)
{
try { return bulletproof_VERIFY(proof); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
bool verBulletproof(const std::vector<const Bulletproof*> &proofs)
{
try { return bulletproof_VERIFY(proofs); }
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (...) { return false; }
}
//Borromean (c.f. gmax/andytoshi's paper)
boroSig genBorromean(const key64 x, const key64 P1, const key64 P2, const bits indices) {
key64 L[2], alpha;
auto wiper = epee::misc_utils::create_scope_leave_handler([&](){memwipe(alpha, sizeof(alpha));});
key c;
int naught = 0, prime = 0, ii = 0, jj=0;
boroSig bb;
for (ii = 0 ; ii < 64 ; ii++) {
naught = indices[ii]; prime = (indices[ii] + 1) % 2;
skGen(alpha[ii]);
scalarmultBase(L[naught][ii], alpha[ii]);
if (naught == 0) {
skGen(bb.s1[ii]);
c = hash_to_scalar(L[naught][ii]);
addKeys2(L[prime][ii], bb.s1[ii], c, P2[ii]);
}
}
bb.ee = hash_to_scalar(L[1]); //or L[1]..
key LL, cc;
for (jj = 0 ; jj < 64 ; jj++) {
if (!indices[jj]) {
sc_mulsub(bb.s0[jj].bytes, x[jj].bytes, bb.ee.bytes, alpha[jj].bytes);
} else {
skGen(bb.s0[jj]);
addKeys2(LL, bb.s0[jj], bb.ee, P1[jj]); //different L0
cc = hash_to_scalar(LL);
sc_mulsub(bb.s1[jj].bytes, x[jj].bytes, cc.bytes, alpha[jj].bytes);
}
}
return bb;
}
//see above.
bool verifyBorromean(const boroSig &bb, const ge_p3 P1[64], const ge_p3 P2[64]) {
key64 Lv1; key chash, LL;
int ii = 0;
ge_p2 p2;
for (ii = 0 ; ii < 64 ; ii++) {
// equivalent of: addKeys2(LL, bb.s0[ii], bb.ee, P1[ii]);
ge_double_scalarmult_base_vartime(&p2, bb.ee.bytes, &P1[ii], bb.s0[ii].bytes);
ge_tobytes(LL.bytes, &p2);
chash = hash_to_scalar(LL);
// equivalent of: addKeys2(Lv1[ii], bb.s1[ii], chash, P2[ii]);
ge_double_scalarmult_base_vartime(&p2, chash.bytes, &P2[ii], bb.s1[ii].bytes);
ge_tobytes(Lv1[ii].bytes, &p2);
}
key eeComputed = hash_to_scalar(Lv1); //hash function fine
return equalKeys(eeComputed, bb.ee);
}
bool verifyBorromean(const boroSig &bb, const key64 P1, const key64 P2) {
ge_p3 P1_p3[64], P2_p3[64];
for (size_t i = 0 ; i < 64 ; ++i) {
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P1_p3[i], P1[i].bytes) == 0, false, "point conv failed");
CHECK_AND_ASSERT_MES_L1(ge_frombytes_vartime(&P2_p3[i], P2[i].bytes) == 0, false, "point conv failed");
}
return verifyBorromean(bb, P1_p3, P2_p3);
}
bool clsag_prepare(const rct::key &p, const rct::key &z, rct::key &I, rct::key &D, const rct::key &H, rct::key &a, rct::key &aG, rct::key &aH) {
rct::skpkGen(a,aG); // aG = a*G
rct::scalarmultKey(aH,H,a); // aH = a*H
rct::scalarmultKey(I,H,p); // I = p*H
rct::scalarmultKey(D,H,z); // D = z*H
return true;
}
bool clsag_sign(const rct::key &c, const rct::key &a, const rct::key &p, const rct::key &z, const rct::key &mu_P, const rct::key &mu_C, rct::key &s) {
rct::key s0_p_mu_P;
sc_mul(s0_p_mu_P.bytes,mu_P.bytes,p.bytes);
rct::key s0_add_z_mu_C;
sc_muladd(s0_add_z_mu_C.bytes,mu_C.bytes,z.bytes,s0_p_mu_P.bytes);
sc_mulsub(s.bytes,c.bytes,s0_add_z_mu_C.bytes,a.bytes);
return true;
}
// Generate a CLSAG signature
// See paper by Goodell et al. (https://eprint.iacr.org/2019/654)
//
// The keys are set as follows:
// P[l] == p*G
// C[l] == z*G
// C[i] == C_nonzero[i] - C_offset (for hashing purposes) for all i
clsag CLSAG_Gen(const key &message, const keyV & P, const key & p, const keyV & C, const key & z, const keyV & C_nonzero, const key & C_offset, const unsigned int l) {
clsag sig;
size_t n = P.size(); // ring size
CHECK_AND_ASSERT_THROW_MES(n == C.size(), "Signing and commitment key vector sizes must match!");
CHECK_AND_ASSERT_THROW_MES(n == C_nonzero.size(), "Signing and commitment key vector sizes must match!");
CHECK_AND_ASSERT_THROW_MES(l < n, "Signing index out of range!");
// Key images
ge_p3 H_p3;
hash_to_p3(H_p3,P[l]);
key H;
ge_p3_tobytes(H.bytes,&H_p3);
key D;
// Initial values
key a;
key aG;
key aH;
{
clsag_prepare(p,z,sig.I,D,H,a,aG,aH);
}
geDsmp I_precomp;
geDsmp D_precomp;
precomp(I_precomp.k,sig.I);
precomp(D_precomp.k,D);
// Offset key image
scalarmultKey(sig.D,D,INV_EIGHT);
// Aggregation hashes
keyV mu_P_to_hash(2*n+4); // domain, I, D, P, C, C_offset
keyV mu_C_to_hash(2*n+4); // domain, I, D, P, C, C_offset
sc_0(mu_P_to_hash[0].bytes);
memcpy(mu_P_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_0,sizeof(config::HASH_KEY_CLSAG_AGG_0)-1);
sc_0(mu_C_to_hash[0].bytes);
memcpy(mu_C_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_1,sizeof(config::HASH_KEY_CLSAG_AGG_1)-1);
for (size_t i = 1; i < n+1; ++i) {
mu_P_to_hash[i] = P[i-1];
mu_C_to_hash[i] = P[i-1];
}
for (size_t i = n+1; i < 2*n+1; ++i) {
mu_P_to_hash[i] = C_nonzero[i-n-1];
mu_C_to_hash[i] = C_nonzero[i-n-1];
}
mu_P_to_hash[2*n+1] = sig.I;
mu_P_to_hash[2*n+2] = sig.D;
mu_P_to_hash[2*n+3] = C_offset;
mu_C_to_hash[2*n+1] = sig.I;
mu_C_to_hash[2*n+2] = sig.D;
mu_C_to_hash[2*n+3] = C_offset;
key mu_P, mu_C;
mu_P = hash_to_scalar(mu_P_to_hash);
mu_C = hash_to_scalar(mu_C_to_hash);
// Initial commitment
keyV c_to_hash(2*n+5); // domain, P, C, C_offset, message, aG, aH
key c;
sc_0(c_to_hash[0].bytes);
memcpy(c_to_hash[0].bytes,config::HASH_KEY_CLSAG_ROUND,sizeof(config::HASH_KEY_CLSAG_ROUND)-1);
for (size_t i = 1; i < n+1; ++i)
{
c_to_hash[i] = P[i-1];
c_to_hash[i+n] = C_nonzero[i-1];
}
c_to_hash[2*n+1] = C_offset;
c_to_hash[2*n+2] = message;
{
c_to_hash[2*n+3] = aG;
c_to_hash[2*n+4] = aH;
}
c = rct::hash_to_scalar(c_to_hash);
size_t i;
i = (l + 1) % n;
if (i == 0)
copy(sig.c1, c);
// Decoy indices
sig.s = keyV(n);
key c_new;
key L;
key R;
key c_p; // = c[i]*mu_P
key c_c; // = c[i]*mu_C
geDsmp P_precomp;
geDsmp C_precomp;
geDsmp H_precomp;
ge_p3 Hi_p3;
while (i != l) {
sig.s[i] = skGen();
sc_0(c_new.bytes);
sc_mul(c_p.bytes,mu_P.bytes,c.bytes);
sc_mul(c_c.bytes,mu_C.bytes,c.bytes);
// Precompute points
precomp(P_precomp.k,P[i]);
precomp(C_precomp.k,C[i]);
// Compute L
addKeys_aGbBcC(L,sig.s[i],c_p,P_precomp.k,c_c,C_precomp.k);
// Compute R
hash_to_p3(Hi_p3,P[i]);
ge_dsm_precomp(H_precomp.k, &Hi_p3);
addKeys_aAbBcC(R,sig.s[i],H_precomp.k,c_p,I_precomp.k,c_c,D_precomp.k);
c_to_hash[2*n+3] = L;
c_to_hash[2*n+4] = R;
c_new = rct::hash_to_scalar(c_to_hash);
copy(c,c_new);
i = (i + 1) % n;
if (i == 0)
copy(sig.c1,c);
}
// Compute final scalar
clsag_sign(c,a,p,z,mu_P,mu_C,sig.s[l]);
memwipe(&a, sizeof(key));
return sig;
}
key get_pre_mlsag_hash(const rctSig &rv)
{
keyV hashes;
hashes.reserve(3);
hashes.push_back(rv.message);
crypto::hash h;
std::stringstream ss;
binary_archive<true> ba(ss);
CHECK_AND_ASSERT_THROW_MES(!rv.mixRing.empty(), "Empty mixRing");
const size_t inputs = rv.mixRing.size() ;
const size_t outputs = rv.ecdhInfo.size();
key prehash;
CHECK_AND_ASSERT_THROW_MES(const_cast<rctSig&>(rv).serialize_rctsig_base(ba, inputs, outputs),
"Failed to serialize rctSigBase");
cryptonote::get_blob_hash(ss.str(), h);
hashes.push_back(hash2rct(h));
std::vector<key> kv;
if (rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG)
{
kv.reserve((6*2+9) * rv.p.bulletproofs.size());
for (const auto &p: rv.p.bulletproofs)
{
// V are not hashed as they're expanded from outCommitments.mask
// (and thus hashed as part of rctSigBase above)
kv.push_back(p.A);
kv.push_back(p.S);
kv.push_back(p.T1);
kv.push_back(p.T2);
kv.push_back(p.taux);
kv.push_back(p.mu);
for (size_t n = 0; n < p.L.size(); ++n)
kv.push_back(p.L[n]);
for (size_t n = 0; n < p.R.size(); ++n)
kv.push_back(p.R[n]);
kv.push_back(p.a);
kv.push_back(p.b);
kv.push_back(p.t);
}
}
hashes.push_back(cn_fast_hash(kv));
prehash = rct::cn_fast_hash(hashes);
return prehash;
}
clsag proveRctCLSAGSimple(const key &message, const std::vector<ctkey> &decoys, const ctkey &real_in, const key &noise, const key &in_C2, unsigned int index) {
//setup vars
size_t rows = 1;
size_t cols = decoys.size();
CHECK_AND_ASSERT_THROW_MES(cols >= 1, "Empty pubs");
keyV tmp(rows + 1);
// std::vector<key> sk(rows + 1);
keyM M(cols, tmp);
keyV P, C, C_nonzero;
P.reserve(decoys.size());
C.reserve(decoys.size());
C_nonzero.reserve(decoys.size());
for (const ctkey &decoy: decoys)
{
const key &otk=decoy.otk;
const key &commitment=decoy.commitment;
P.push_back(otk);//otk
C_nonzero.push_back(commitment);
rct::key tmp;
///Ci-C2
subKeys(tmp, commitment, in_C2);
C.push_back(tmp);
}
//otk_sec
const key & otk_sec=real_in.otk_sec;
const key & real_noise=real_in.noise;
// sk[0] = copy(otk_sec);
key noise_delta;
sc_sub(noise_delta.bytes, real_noise.bytes, noise.bytes);
clsag result = CLSAG_Gen(message, P, otk_sec, C, noise_delta, C_nonzero, in_C2, index);
// memwipe(sk.data(), sk.size() * sizeof(key));
return result;
}
bool verRctCLSAGSimple(const key &message, const clsag &sig, const ctkeyV & pubs, const key & C_offset) {
try
{
PERF_TIMER(verRctCLSAGSimple);
const size_t n = pubs.size();
// Check data
CHECK_AND_ASSERT_MES(n >= 1, false, "Empty pubs");
CHECK_AND_ASSERT_MES(n == sig.s.size(), false, "Signature scalar vector is the wrong size!");
for (size_t i = 0; i < n; ++i)
CHECK_AND_ASSERT_MES(sc_check(sig.s[i].bytes) == 0, false, "Bad signature scalar!");
CHECK_AND_ASSERT_MES(sc_check(sig.c1.bytes) == 0, false, "Bad signature commitment!");
CHECK_AND_ASSERT_MES(!(sig.I == rct::identity()), false, "Bad key image!");
// Cache commitment offset for efficient subtraction later
ge_p3 C_offset_p3;
CHECK_AND_ASSERT_MES(ge_frombytes_vartime(&C_offset_p3, C_offset.bytes) == 0, false, "point conv failed");
ge_cached C_offset_cached;
ge_p3_to_cached(&C_offset_cached, &C_offset_p3);
// Prepare key images
key c = copy(sig.c1);
key D_8 = scalarmult8(sig.D);
CHECK_AND_ASSERT_MES(!(D_8 == rct::identity()), false, "Bad auxiliary key image!");
geDsmp I_precomp;
geDsmp D_precomp;
precomp(I_precomp.k,sig.I);
precomp(D_precomp.k,D_8);
// Aggregation hashes
keyV mu_P_to_hash(2*n+4); // domain, I, D, P, C, C_offset
keyV mu_C_to_hash(2*n+4); // domain, I, D, P, C, C_offset
sc_0(mu_P_to_hash[0].bytes);
memcpy(mu_P_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_0,sizeof(config::HASH_KEY_CLSAG_AGG_0)-1);
sc_0(mu_C_to_hash[0].bytes);
memcpy(mu_C_to_hash[0].bytes,config::HASH_KEY_CLSAG_AGG_1,sizeof(config::HASH_KEY_CLSAG_AGG_1)-1);
for (size_t i = 1; i < n+1; ++i) {
mu_P_to_hash[i] = pubs[i-1].otk;
mu_C_to_hash[i] = pubs[i-1].otk;
}
for (size_t i = n+1; i < 2*n+1; ++i) {
mu_P_to_hash[i] = pubs[i-n-1].commitment;
mu_C_to_hash[i] = pubs[i-n-1].commitment;
}
mu_P_to_hash[2*n+1] = sig.I;
mu_P_to_hash[2*n+2] = sig.D;
mu_P_to_hash[2*n+3] = C_offset;
mu_C_to_hash[2*n+1] = sig.I;
mu_C_to_hash[2*n+2] = sig.D;
mu_C_to_hash[2*n+3] = C_offset;
key mu_P, mu_C;
mu_P = hash_to_scalar(mu_P_to_hash);
mu_C = hash_to_scalar(mu_C_to_hash);
// Set up round hash
keyV c_to_hash(2*n+5); // domain, P, C, C_offset, message, L, R
sc_0(c_to_hash[0].bytes);
memcpy(c_to_hash[0].bytes,config::HASH_KEY_CLSAG_ROUND,sizeof(config::HASH_KEY_CLSAG_ROUND)-1);
for (size_t i = 1; i < n+1; ++i)
{
c_to_hash[i] = pubs[i-1].otk;
c_to_hash[i+n] = pubs[i-1].commitment;
}
c_to_hash[2*n+1] = C_offset;
c_to_hash[2*n+2] = message;
key c_p; // = c[i]*mu_P
key c_c; // = c[i]*mu_C
key c_new;
key L;
key R;
geDsmp P_precomp;
geDsmp C_precomp;
size_t i = 0;
ge_p3 hash8_p3;
geDsmp hash_precomp;
ge_p3 temp_p3;
ge_p1p1 temp_p1;
while (i < n) {
sc_0(c_new.bytes);
sc_mul(c_p.bytes,mu_P.bytes,c.bytes);
sc_mul(c_c.bytes,mu_C.bytes,c.bytes);
// Precompute points for L/R
precomp(P_precomp.k,pubs[i].otk);
CHECK_AND_ASSERT_MES(ge_frombytes_vartime(&temp_p3, pubs[i].commitment.bytes) == 0, false, "point conv failed");
ge_sub(&temp_p1,&temp_p3,&C_offset_cached);
ge_p1p1_to_p3(&temp_p3,&temp_p1);
ge_dsm_precomp(C_precomp.k,&temp_p3);
// Compute L
addKeys_aGbBcC(L,sig.s[i],c_p,P_precomp.k,c_c,C_precomp.k);
// Compute R
hash_to_p3(hash8_p3,pubs[i].otk);
ge_dsm_precomp(hash_precomp.k, &hash8_p3);
addKeys_aAbBcC(R,sig.s[i],hash_precomp.k,c_p,I_precomp.k,c_c,D_precomp.k);
c_to_hash[2*n+3] = L;
c_to_hash[2*n+4] = R;
c_new = hash_to_scalar(c_to_hash);
CHECK_AND_ASSERT_MES(!(c_new == rct::zero()), false, "Bad signature hash");
copy(c,c_new);
i = i + 1;
}
sc_sub(c_new.bytes,c.bytes,sig.c1.bytes);
return sc_isnonzero(c_new.bytes) == 0;
}
catch (...) { return false; }
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
void getKeyFromBlockchain(ctkey & a, size_t reference_index) {
a.noise = pkGen();
a.otk = pkGen();
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" + 1 columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
tuple<ctkeyM, xmr_amount> populateFromBlockchain(ctkeyV inPk, int mixin) {
int rows = inPk.size();
ctkeyM rv(mixin + 1, inPk);
int index = randXmrAmount(mixin);
int i = 0, j = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
for (j = 0; j < rows; j++) {
getKeyFromBlockchain(rv[i][j], (size_t)randXmrAmount);
}
}
}
return make_tuple(rv, index);
}
//These functions get keys from blockchain
//replace these when connecting blockchain
//getKeyFromBlockchain grabs a key from the blockchain at "reference_index" to mix with
//populateFromBlockchain creates a keymatrix with "mixin" columns and one of the columns is inPk
// the return value are the key matrix, and the index where inPk was put (random).
xmr_amount populateFromBlockchainSimple(ctkeyV & mixRing, const ctkey & inPk, int mixin) {
int index = randXmrAmount(mixin);
int i = 0;
for (i = 0; i <= mixin; i++) {
if (i != index) {
getKeyFromBlockchain(mixRing[i], (size_t)randXmrAmount(1000));
} else {
mixRing[i] = inPk;
}
}
return index;
}
//RCT simple
//for post-rct only
rctSig genRctSimple(const key &message, const std::vector<ctkey> & inSk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, xmr_amount txnFee, const ctkeyM & mixRing, const std::vector<key> &shared_secs, const std::vector<unsigned int> & index, std::vector<ctkey> &outSk) {
// const bool bulletproof = rct_config.range_proof_type != RangeProofBorromean;
CHECK_AND_ASSERT_THROW_MES(inamounts.size() > 0, "Empty inamounts");
CHECK_AND_ASSERT_THROW_MES(inamounts.size() == inSk.size(), "Different number of inamounts/inSk");
CHECK_AND_ASSERT_THROW_MES(outamounts.size() == destinations.size(), "Different number of amounts/destinations");
CHECK_AND_ASSERT_THROW_MES(shared_secs.size() == destinations.size(), "Different number of shared_secs/destinations");
CHECK_AND_ASSERT_THROW_MES(index.size() == inSk.size(), "Different number of index/inSk");
CHECK_AND_ASSERT_THROW_MES(mixRing.size() == inSk.size(), "Different number of mixRing/inSk");
for (size_t n = 0; n < mixRing.size(); ++n) {
CHECK_AND_ASSERT_THROW_MES(index[n] < mixRing[n].size(), "Bad index into mixRing");
}
rctSig rv{};
rv.type = RCTTypeCLSAG;
rv.message = message;
rv.outCommitments.resize(destinations.size());
rv.ecdhInfo.resize(destinations.size());
size_t i;
//keyV masks(destinations.size()); //sk mask..
outSk.resize(destinations.size());
for (i = 0; i < destinations.size(); i++) {
//add destination to sig
rv.outCommitments[i].otk = copy(destinations[i]);
}
rv.p.bulletproofs.clear();
{
// if (rct_config.range_proof_type == RangeProofPaddedBulletproof)
{
rct::keyV C, noises;
{
rv.p.bulletproofs.push_back(proveRangeBulletproof(C, noises, outamounts, shared_secs));
#ifdef DBG
CHECK_AND_ASSERT_THROW_MES(verBulletproof(rv.p.bulletproofs.back()), "verBulletproof failed on newly created proof");
#endif
}
for (i = 0; i < outamounts.size(); ++i)
{
rv.outCommitments[i].commitment = rct::scalarmult8(C[i]);
outSk[i].noise = noises[i];
}
}
}
key sumout = zero();
for (i = 0; i < outamounts.size(); ++i)
{
const key & noise=outSk[i].noise;
sc_add(sumout.bytes, noise.bytes, sumout.bytes);
//mask amount
auto a = outamounts[i];
auto a2 = rct::ecdhEncode(a, shared_secs[i]);
rv.ecdhInfo[i].amount = a2;
}
//set txn fee
rv.txnFee = txnFee;
// TODO: unused ??
// key txnFeeKey = scalarmultH(d2h(rv.txnFee));
rv.mixRing = mixRing;
std::vector<key> &in_C2s = rv.p.pseudoOuts ;
in_C2s.resize(inamounts.size());
if (rv.type == RCTTypeCLSAG)
rv.p.CLSAGs.resize(inamounts.size());
key sum_in = zero(); //sum pseudoOut masks
std::vector<key> noises(inamounts.size());
for (i = 0 ; i < inamounts.size() - 1; i++) {
skGen(noises[i]);
sc_add(sum_in.bytes, noises[i].bytes, sum_in.bytes);
//aG+bH
genC(in_C2s[i], noises[i], inamounts[i]);
}
sc_sub(noises[i].bytes, sumout.bytes, sum_in.bytes);
//
genC(in_C2s[i], noises[i], inamounts[i]);
DP(in_C2s[i]);
key full_message = get_pre_mlsag_hash(rv);
for (i = 0 ; i < inamounts.size(); i++)
{
if (rv.type == RCTTypeCLSAG)
{
const ctkey & real_in = inSk[i];
const std::vector<ctkey> & decoys=rv.mixRing[i];
const key & in_C2=in_C2s[i];
const key & noise=noises[i];
rv.p.CLSAGs[i] = proveRctCLSAGSimple(full_message, decoys, real_in, noise, in_C2, index[i]);
}
}
return rv;
}
rctSig genRctSimple(const key &message, const ctkeyV & inSk, const ctkeyV & inPk, const keyV & destinations, const vector<xmr_amount> &inamounts, const vector<xmr_amount> &outamounts, const keyV &amount_keys, xmr_amount txnFee, unsigned int mixin) {
std::vector<unsigned int> index;
index.resize(inPk.size());
ctkeyM mixRing;
ctkeyV outSk;
mixRing.resize(inPk.size());
for (size_t i = 0; i < inPk.size(); ++i) {
mixRing[i].resize(mixin+1);
index[i] = populateFromBlockchainSimple(mixRing[i], inPk[i], mixin);
}
return genRctSimple(message, inSk, destinations, inamounts, outamounts, txnFee, mixRing, amount_keys, index, outSk);
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctSemanticsSimple(const std::vector<const rctSig*> & rvv) {
try
{
PERF_TIMER(verRctSemanticsSimple);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter(tpool);
std::deque<bool> results;
std::vector<const Bulletproof*> proofs;
size_t max_non_bp_proofs = 0;
for (const rctSig *rvp: rvv)
{
CHECK_AND_ASSERT_MES(rvp, false, "rctSig pointer is NULL");
const rctSig &rv = *rvp;
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG,
false, "verRctSemanticsSimple called on non simple rctSig");
// const bool bulletproof = is_rct_bulletproof(rv.type);
{
CHECK_AND_ASSERT_MES(rv.outCommitments.size() == n_bulletproof_amounts(rv.p.bulletproofs), false, "Mismatched sizes of outCommitments and bulletproofs");
if (rv.type == RCTTypeCLSAG)
{
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.p.CLSAGs.size(), false, "Mismatched sizes of rv.p.pseudoOuts and rv.p.CLSAGs");
}
}
CHECK_AND_ASSERT_MES(rv.outCommitments.size() == rv.ecdhInfo.size(), false, "Mismatched sizes of outCommitments and rv.ecdhInfo");
}
results.resize(max_non_bp_proofs);
for (const rctSig *rvp: rvv)
{
const rctSig &rv = *rvp;
const bool bulletproof = true;
const keyV &pseudoOuts = rv.p.pseudoOuts ;
rct::keyV masks(rv.outCommitments.size());
for (size_t i = 0; i < rv.outCommitments.size(); i++) {
masks[i] = rv.outCommitments[i].commitment;
}
key sumOutpks = addKeys(masks);
DP(sumOutpks);
const key txnFeeKey = scalarmultH(d2h(rv.txnFee));
addKeys(sumOutpks, txnFeeKey, sumOutpks);
key sumPseudoOuts = addKeys(pseudoOuts);
DP(sumPseudoOuts);
//check pseudoOuts vs Outs..
if (!equalKeys(sumPseudoOuts, sumOutpks)) {
MINFO("Sum check failed");
return false;
}
if (bulletproof)
{
for (size_t i = 0; i < rv.p.bulletproofs.size(); i++)
proofs.push_back(&rv.p.bulletproofs[i]);
}
}
if (!proofs.empty() && !verBulletproof(proofs))
{
MINFO("Aggregate range proof verified failed");
return false;
}
if (!waiter.wait())
return false;
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
MINFO("Range proof verified failed for proof " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
MINFO("Error in verRctSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
MINFO("Error in verRctSemanticsSimple, but not an actual exception");
return false;
}
}
bool verRctSemanticsSimple(const rctSig & rv)
{
return verRctSemanticsSimple(std::vector<const rctSig*>(1, &rv));
}
//ver RingCT simple
//assumes only post-rct style inputs (at least for max anonymity)
bool verRctNonSemanticsSimple(const rctSig & rv) {
try
{
PERF_TIMER(verRctNonSemanticsSimple);
CHECK_AND_ASSERT_MES(rv.type == RCTTypeSimple || rv.type == RCTTypeBulletproof || rv.type == RCTTypeBulletproof2 || rv.type == RCTTypeCLSAG,
false, "verRctNonSemanticsSimple called on non simple rctSig");
const bool bulletproof = true;
// semantics check is early, and mixRing/MGs aren't resolved yet
if (bulletproof)
CHECK_AND_ASSERT_MES(rv.p.pseudoOuts.size() == rv.mixRing.size(), false, "Mismatched sizes of rv.p.pseudoOuts and mixRing");
const size_t threads = std::max(rv.outCommitments.size(), rv.mixRing.size());
std::deque<bool> results(threads);
tools::threadpool& tpool = tools::threadpool::getInstance();
tools::threadpool::waiter waiter(tpool);
const keyV &pseudoOuts = rv.p.pseudoOuts ;
const key message = get_pre_mlsag_hash(rv);
results.clear();
results.resize(rv.mixRing.size());
for (size_t i = 0 ; i < rv.mixRing.size() ; i++) {
tpool.submit(&waiter, [&, i] {
if (rv.type == RCTTypeCLSAG)
{
results[i] = verRctCLSAGSimple(message, rv.p.CLSAGs[i], rv.mixRing[i], pseudoOuts[i]);
}
});
}
if (!waiter.wait())
return false;
for (size_t i = 0; i < results.size(); ++i) {
if (!results[i]) {
MINFO("verRctMGSimple/verRctCLSAGSimple failed for input " << i);
return false;
}
}
return true;
}
// we can get deep throws from ge_frombytes_vartime if input isn't valid
catch (const std::exception &e)
{
MINFO("Error in verRctNonSemanticsSimple: " << e.what());
return false;
}
catch (...)
{
MINFO("Error in verRctNonSemanticsSimple, but not an actual exception");
return false;
}
}
std::tuple<xmr_amount,key> decodeRctSimple(const uint64_t encrypted_amount, const rct::key& commitment,const rct::key & shared_sec)
{
//crypto::derivation_to_scalar(kA,i,ss);
//mask amount and mask
const uint64_t amount = rct::ecdhDecode(encrypted_amount, shared_sec);
const auto noise = rct::genCommitmentMask(shared_sec);
key C = commitment;
DP("C");DP(C);
key C2;
CHECK_AND_ASSERT_THROW_MES(sc_check(noise.bytes) == 0, "warning, bad ECDH mask");
//noise*G+bH
addKeys2(C2, noise, rct::d2h(amount), H);
DP("C2");DP(C2);
if (rct::equalKeys(C, C2) == false) {
CHECK_AND_ASSERT_THROW_MES(false, "warning, amount decoded incorrectly, will be unable to spend");
}
return {amount,noise};
}
}
| 38.014151 | 329 | 0.572807 | [
"vector"
] |
91876390e354e0fb784f2c850960a9005f4aa49e | 7,744 | cxx | C++ | BeastHttp/src/tests/chain_router/main.cxx | johnfindeed/BeastHttp | c3881006c4a1dedd3b62244880023a3e810d42c1 | [
"BSD-2-Clause"
] | null | null | null | BeastHttp/src/tests/chain_router/main.cxx | johnfindeed/BeastHttp | c3881006c4a1dedd3b62244880023a3e810d42c1 | [
"BSD-2-Clause"
] | null | null | null | BeastHttp/src/tests/chain_router/main.cxx | johnfindeed/BeastHttp | c3881006c4a1dedd3b62244880023a3e810d42c1 | [
"BSD-2-Clause"
] | null | null | null | #define BOOST_TEST_MODULE chain_router_test
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <http/base/cb.hxx>
#include <http/base/regex.hxx>
#include <http/base/request_processor.hxx>
#include <http/literals.hxx>
#include <http/chain_router.hxx>
#include <boost/beast/http.hpp>
#include <unordered_map>
using namespace _0xdead4ead;
class test_session
{
public:
using self_type = test_session;
template<class>
class context;
class flesh;
using flesh_type = flesh;
using context_type = context<flesh_type>;
using resource_regex_type = std::string;
using resource_type = boost::beast::string_view;
using method_type = boost::beast::http::verb;
using body_type = boost::beast::http::string_body;
using cbexecutor_type = http::base::cb::executor;
using request_type = boost::beast::http::request<body_type>;
using regex_type = http::base::regex;
using regex_flag_type = typename regex_type::flag_type;
using storage_type = http::base::cb::storage<self_type, std::function, std::vector>;
using resource_map_type = std::unordered_map<resource_regex_type, std::shared_ptr<storage_type>>;
using method_map_type = std::map<method_type, resource_map_type>;
class flesh
{};
template<class Flesh>
class context
{
public:
context(Flesh&)
{}
};
}; // class test_session
static const std::regex::flag_type regex_flags = std::regex::ECMAScript;
BOOST_AUTO_TEST_CASE(no_1) {
http::chain_router<test_session> router{regex_flags};
http::base::request_processor<test_session>
procs{router.resource_map(), router.method_map(), router.regex_flags()};
router.route("/testpath").get(
[](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/testpath");
});
router.route("/path/to/resource").get(
[](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/path/to/resource");
});
procs.provide({boost::beast::http::verb::get, "/testpath", 11}, test_session::flesh{});
procs.provide({boost::beast::http::verb::get, "/path/to/resource", 11}, test_session::flesh{});
} // BOOST_AUTO_TEST_CASE(no_1)
BOOST_AUTO_TEST_CASE(no_2) {
http::chain_router<test_session> router{regex_flags};
http::base::request_processor<test_session>
procs{router.resource_map(), router.method_map(), router.regex_flags()};
router.route("/a/b/c").get(
[](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
std::next(_1x)();
}, [](auto request, auto /*context*/, auto _2x){
BOOST_CHECK(request.target() == "/b");
std::next(_2x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/c");
});
router.route("/a/b/c/d")
.get([](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/a/b/c/d");
}).post([](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/a/b/c/d");
BOOST_CHECK_EQUAL(request.body(), "postdata");
}).put([](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/a/b/c/d");
BOOST_CHECK_EQUAL(request.body(), "putdata");
});
router.route("/a/b/c/d/e")
.get([](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
std::next(_1x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/b");
}).post([](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
BOOST_CHECK_EQUAL(request.body(), "postdata");
std::next(_1x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/b");
BOOST_CHECK_EQUAL(request.body(), "postdata");
}).put([](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
BOOST_CHECK_EQUAL(request.body(), "putdata");
std::next(_1x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/b");
BOOST_CHECK_EQUAL(request.body(), "putdata");
});
procs.provide({boost::beast::http::verb::get, "/a/b/c", 11}, test_session::flesh{});
procs.provide({boost::beast::http::verb::get, "/a/b/c/d", 11}, test_session::flesh{});
procs.provide({boost::beast::http::verb::post, "/a/b/c/d", 11, "postdata"}, test_session::flesh{});
procs.provide({boost::beast::http::verb::put, "/a/b/c/d", 11, "putdata"}, test_session::flesh{});
procs.provide({boost::beast::http::verb::get, "/a/b/c/d/e", 11}, test_session::flesh{});
procs.provide({boost::beast::http::verb::post, "/a/b/c/d/e", 11, "postdata"}, test_session::flesh{});
procs.provide({boost::beast::http::verb::put, "/a/b/c/d/e", 11, "putdata"}, test_session::flesh{});
} // BOOST_AUTO_TEST_CASE(no_2)
BOOST_AUTO_TEST_CASE(literals_no_1) {
using http::literals::operator""_route;
http::chain_router<test_session> router{regex_flags};
http::base::request_processor<test_session>
procs{router.resource_map(), router.method_map(), router.regex_flags()};
"^/a/b/c$"_route.advance(router).get(
[](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
std::next(_1x)();
}, [](auto request, auto /*context*/, auto _2x){
BOOST_CHECK(request.target() == "/b");
std::next(_2x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/c");
});
"^/a/b/c/d$"_route.advance(router)
.get([](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/a/b/c/d");
}).post([](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/a/b/c/d");
BOOST_CHECK_EQUAL(request.body(), "postdata");
}).put([](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/a/b/c/d");
BOOST_CHECK_EQUAL(request.body(), "putdata");
});
"^/a/b/c/d/e$"_route.advance(router)
.get([](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
std::next(_1x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/b");
}).post([](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
BOOST_CHECK_EQUAL(request.body(), "postdata");
std::next(_1x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/b");
BOOST_CHECK_EQUAL(request.body(), "postdata");
}).put([](auto request, auto /*context*/, auto _1x){
BOOST_CHECK(request.target() == "/a");
BOOST_CHECK_EQUAL(request.body(), "putdata");
std::next(_1x)();
}, [](auto request, auto /*context*/){
BOOST_CHECK(request.target() == "/b");
BOOST_CHECK_EQUAL(request.body(), "putdata");
});
procs.provide({boost::beast::http::verb::get, "/a/b/c", 11}, test_session::flesh{});
procs.provide({boost::beast::http::verb::get, "/a/b/c/d", 11}, test_session::flesh{});
procs.provide({boost::beast::http::verb::post, "/a/b/c/d", 11, "postdata"}, test_session::flesh{});
procs.provide({boost::beast::http::verb::put, "/a/b/c/d", 11, "putdata"}, test_session::flesh{});
procs.provide({boost::beast::http::verb::get, "/a/b/c/d/e", 11}, test_session::flesh{});
procs.provide({boost::beast::http::verb::post, "/a/b/c/d/e", 11, "postdata"}, test_session::flesh{});
procs.provide({boost::beast::http::verb::put, "/a/b/c/d/e", 11, "putdata"}, test_session::flesh{});
} // BOOST_AUTO_TEST_CASE(literals_no_1)
| 35.686636 | 105 | 0.6086 | [
"vector"
] |
9265af8bd5cd4da61556f3239a95fe46aed277cd | 4,304 | cpp | C++ | submitted_models/bosdyn_spot/src/logical_contact_system.cpp | jfkeller/subt_explorer_canary1_sensor_config_1 | 1f0419130b79f48c66e83c084e704e521782a95a | [
"ECL-2.0",
"Apache-2.0"
] | 173 | 2020-04-09T18:39:39.000Z | 2022-03-15T06:15:07.000Z | submitted_models/bosdyn_spot/src/logical_contact_system.cpp | jfkeller/subt_explorer_canary1_sensor_config_1 | 1f0419130b79f48c66e83c084e704e521782a95a | [
"ECL-2.0",
"Apache-2.0"
] | 538 | 2020-04-09T18:34:04.000Z | 2022-02-20T09:53:17.000Z | submitted_models/bosdyn_spot/src/logical_contact_system.cpp | jfkeller/subt_explorer_canary1_sensor_config_1 | 1f0419130b79f48c66e83c084e704e521782a95a | [
"ECL-2.0",
"Apache-2.0"
] | 89 | 2020-04-14T20:46:48.000Z | 2022-03-14T16:45:30.000Z | #include <memory>
#include <ignition/msgs/int32_v.pb.h>
#include <ignition/plugin/Register.hh>
#include <ignition/transport/Node.hh>
#include <ignition/gazebo/Model.hh>
#include <ignition/gazebo/System.hh>
#include <ignition/gazebo/components.hh>
using namespace ignition;
using namespace gazebo;
namespace subt
{
class LogicalContactSystem : public System, public ISystemConfigure, public ISystemPostUpdate
{
public: void Configure(const Entity& _entity, const std::shared_ptr<const sdf::Element>& _sdf,
EntityComponentManager& _ecm, EventManager& _eventMgr) override
{
const Model model(_entity);
if (!model.Valid(_ecm))
{
ignerr << "LogicalContactSystem should be attached to a model entity. Failed to initialize." << std::endl;
return;
}
if (!_sdf->HasElement("group"))
{
ignerr << "LogicalContactSystem doesn't have any <group> element. It will not do anything." << std::endl;
return;
}
auto sdf = _sdf->Clone();
for (auto group = sdf->GetElement("group"); group; group = group->GetNextElement("group"))
{
if (!group->HasAttribute("name"))
{
ignerr << "LogicalContactSystem found a group without the 'name' attribute, ignoring it." << std::endl;
continue;
}
const auto name = group->GetAttribute("name")->GetAsString();
this->collisionNames[name].clear(); // initialize the map key
for (auto collision = group->GetElement("collision"); collision; collision = collision->GetNextElement("collision"))
{
const auto collName = collision->GetValue()->GetAsString();
if (collName.empty())
{
ignerr << "LogicalContactSystem found empty <collision> tag in group [" << name << "], it will be ignored." << std::endl;
continue;
}
this->collisions[collName] = kNullEntity;
this->collisionNames[name].push_back(collName);
}
}
std::string topic {"/model/" + model.Name(_ecm) + "/logical_contacts"};
if (_sdf->HasElement("topic"))
topic = _sdf->Get<std::string>("topic");
this->pub = this->node.Advertise<ignition::msgs::Int32_V>(topic);
std::stringstream ss;
for (const auto& groupPair : this->collisionNames)
{
ss << " - '" << groupPair.first << "' with collisions [";
for (size_t i = 0; i < groupPair.second.size(); ++i)
{
ss << "'" << groupPair.second[i] << "'";
if (i < groupPair.second.size() - 1)
ss << ", ";
}
ss << "]" << std::endl;
}
ignmsg << "LogicalContactSystem publishing on [" << topic << "] is handling the following groups:\n" << ss.str();
}
public: void PostUpdate(const UpdateInfo& _info, const EntityComponentManager& _ecm) override
{
ignition::msgs::Int32_V msg;
size_t i = 0;
msg.mutable_header()->mutable_stamp()->CopyFrom(convert<msgs::Time>(_info.simTime));
msg.mutable_data()->Resize(this->collisionNames.size(), -1);
for (const auto& groupPair : this->collisionNames)
{
msg.mutable_data()->Set(i, false);
for (const auto& name : groupPair.second)
{
auto& entity = this->collisions.at(name);
if (entity == kNullEntity)
{
auto collisionEntities = _ecm.EntitiesByComponents(
components::Collision(), components::Name(name));
if (!collisionEntities.empty())
entity = collisionEntities[0];
}
if (entity != kNullEntity)
{
const auto& contacts = _ecm.Component<components::ContactSensorData>(entity);
if (contacts != nullptr && contacts->Data().contact_size() > 0)
{
msg.mutable_data()->Set(i,true);
break;
}
}
}
i += 1;
}
this->pub.Publish(msg);
}
protected: transport::Node node;
protected: transport::Node::Publisher pub;
protected: std::map<std::string, std::vector<std::string>> collisionNames;
protected: std::unordered_map<std::string, Entity> collisions;
};
}
IGNITION_ADD_PLUGIN(subt::LogicalContactSystem,
System,
ISystemConfigure,
ISystemPostUpdate)
IGNITION_ADD_PLUGIN_ALIAS(subt::LogicalContactSystem, "subt::LogicalContactSystem") | 32.360902 | 131 | 0.615939 | [
"vector",
"model"
] |
92674b808f525dd8a4c9c33d13744c3de42faa47 | 1,314 | cpp | C++ | platform/3ds/Texture.cpp | Streetwalrus/WalrusRPG | 53d88ef36ca1b2c169b5755dd95ac2c5626b91f5 | [
"MIT"
] | 12 | 2015-06-30T19:38:06.000Z | 2017-11-27T20:26:32.000Z | platform/3ds/Texture.cpp | Pokespire/pokespire | 53d88ef36ca1b2c169b5755dd95ac2c5626b91f5 | [
"MIT"
] | 18 | 2015-06-26T01:44:48.000Z | 2016-07-01T16:26:17.000Z | platform/3ds/Texture.cpp | Pokespire/pokespire | 53d88ef36ca1b2c169b5755dd95ac2c5626b91f5 | [
"MIT"
] | 1 | 2016-12-12T05:15:46.000Z | 2016-12-12T05:15:46.000Z | #include "Texture.h"
#include "lodepng.h"
#include "render/Pixel.h"
#include <3ds.h>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <sf2d.h>
#include "utility/misc.h"
using namespace WalrusRPG::Graphics; /*Texture*/
using WalrusRPG::Graphics::Pixel;
using WalrusRPG::PIAF::File;
using WalrusRPG::Utils::Rect;
#include "Logger.h"
Texture::Texture(char *data) : data()
{
uint16_t *data_16 = (uint16_t *) data;
this->data =
sf2d_create_texture(data_16[0], data_16[1], TEXFMT_RGB565, SF2D_PLACE_VRAM);
memcpy(&this->data->tex, &data_16[3], data_16[0] * data_16[1] * sizeof(uint16_t));
}
Texture::Texture(WalrusRPG::PIAF::File entry)
{
unsigned char *pic;
unsigned width, height;
signed result = lodepng_decode32(&pic, &width, &height, (unsigned char *) entry.get(),
entry.file_size);
data =
sf2d_create_texture_mem_RGBA8(pic, width, height, TEXFMT_RGBA8, SF2D_PLACE_RAM);
free(pic);
}
Texture::~Texture()
{
sf2d_free_texture(data);
}
const Rect Texture::get_dimensions()
{
return {0, 0, data->width, data->height};
}
const Pixel Texture::get_pixel(unsigned x, unsigned y)
{
u32 pixel = sf2d_get_pixel(data, x, y);
return Pixel(RGBA8_GET_R(pixel), RGBA8_GET_G(pixel), RGBA8_GET_B(pixel));
}
| 24.792453 | 90 | 0.673516 | [
"render"
] |
9269c883c98a8843ac123d542903b4cc1f577753 | 3,029 | cpp | C++ | torrentR/src/BkgModelHiddenFunctions.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 125 | 2015-01-22T05:43:23.000Z | 2022-03-22T17:15:59.000Z | torrentR/src/BkgModelHiddenFunctions.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 59 | 2015-02-10T09:13:06.000Z | 2021-11-11T02:32:38.000Z | torrentR/src/BkgModelHiddenFunctions.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 98 | 2015-01-17T01:25:10.000Z | 2022-03-18T17:29:42.000Z | /* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
#include <vector>
#include <string>
#include <iostream>
#include <Rcpp.h>
#include "RegionParams.h"
using namespace std;
//compute the change in parameters over time
//use the annoying "hyperparameter" models that bkg model uses
// exporting the models not because they are complicated
// but to make sure the code is >consistent<
// NucModifyRatio
// etbR
// RatioDrift
// flow = number of flow
RcppExport SEXP AdjustEmptyToBeadRatioForFlowR(SEXP R_etbR, SEXP R_NucModifyRatio, SEXP R_RatioDrift, SEXP R_flow, SEXP R_fit_taue) {
SEXP ret = R_NilValue; // Use this when there is nothing to be returned.
char *exceptionMesg = NULL;
try {
float etbR = Rcpp::as<float>(R_etbR);
float NucModifyRatio = Rcpp::as<float>(R_NucModifyRatio);
float RatioDrift = Rcpp::as<float>(R_RatioDrift);
int flow = Rcpp::as<int>(R_flow);
bool fit_taue = Rcpp::as<bool> (R_fit_taue);
float out_val;
if (!fit_taue){
// if_use_obsolete_etbR_equation==true, therefore Copy(=1.0) and phi(=0.6) are not used
float local_phi = 0.6;
float local_Copy = 1.0;
float local_Ampl = 0.0;
out_val = xAdjustEmptyToBeadRatioForFlow(etbR,local_Ampl, local_Copy, local_phi, NucModifyRatio, RatioDrift, flow, true);
}
else
out_val = xAdjustEmptyToBeadRatioForFlowWithAdjR(etbR,NucModifyRatio,RatioDrift,flow);
ret = Rcpp::List::create(Rcpp::Named("etbR") = out_val);
} catch(...) {
::Rf_error("c++ exception (unknown reason)");
}
if(exceptionMesg != NULL)
Rf_error(exceptionMesg);
return ret;
}
//xComputeTauBfromEmptyUsingRegionLinearModel(float tau_R_m,float tau_R_o, float etbR);
RcppExport SEXP ComputeTauBfromEmptyUsingRegionLinearModelR(SEXP R_etbR, SEXP R_tau_R_m, SEXP R_tau_R_o) {
SEXP ret = R_NilValue; // Use this when there is nothing to be returned.
char *exceptionMesg = NULL;
try {
float etbR = Rcpp::as<float>(R_etbR);
float tau_R_m = Rcpp::as<float>(R_tau_R_m);
float tau_R_o = Rcpp::as<float>(R_tau_R_o);
float out_val = xComputeTauBfromEmptyUsingRegionLinearModel(tau_R_m, tau_R_o, etbR,4,65);
ret = Rcpp::List::create(Rcpp::Named("tauB") = out_val);
} catch(...) {
::Rf_error("c++ exception (unknown reason)");
}
if(exceptionMesg != NULL)
Rf_error(exceptionMesg);
return ret;
}
RcppExport SEXP ComputeTauBfromEmptyUsingRegionLinearModelUsingTauER(SEXP R_etbR, SEXP R_tauE) {
SEXP ret = R_NilValue; // Use this when there is nothing to be returned.
char *exceptionMesg = NULL;
try {
float etbR = Rcpp::as<float>(R_etbR);
float tauE = Rcpp::as<float>(R_tauE);
float out_val = xComputeTauBfromEmptyUsingRegionLinearModelWithAdjR(tauE,etbR,4,65);
ret = Rcpp::List::create(Rcpp::Named("tauB") = out_val);
} catch(...) {
::Rf_error("c++ exception (unknown reason)");
}
if(exceptionMesg != NULL)
Rf_error(exceptionMesg);
return ret;
}
| 30.908163 | 133 | 0.691647 | [
"vector",
"model"
] |
926f1f9dde334faa16a2f6a6e9641e6e3e72b05b | 19,923 | cpp | C++ | unittests/rbusProvider.cpp | lgirdk/rbus | f6273d2ddb985878b192275e573e72b43df467af | [
"Apache-2.0"
] | null | null | null | unittests/rbusProvider.cpp | lgirdk/rbus | f6273d2ddb985878b192275e573e72b43df467af | [
"Apache-2.0"
] | null | null | null | unittests/rbusProvider.cpp | lgirdk/rbus | f6273d2ddb985878b192275e573e72b43df467af | [
"Apache-2.0"
] | null | null | null | /*
* If not stated otherwise in this file or this component's Licenses.txt file
* the following copyright and licenses apply:
*
* Copyright 2020 RDK Management
*
* 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 "gtest/gtest.h"
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <rbus_core.h>
#include <rbus.h>
#include "rbusProviderConsumer.h"
#include <errno.h>
#define __STDC_FORMAT_MACROS 1
#include <inttypes.h>
void getCompileTime(struct tm *t);
typedef enum _rbus_legacy_support
{
RBUS_LEGACY_STRING = 0, /**< Null terminated string */
RBUS_LEGACY_INT, /**< Integer (2147483647 or -2147483648) as String */
RBUS_LEGACY_UNSIGNEDINT, /**< Unsigned Integer (ex: 4,294,967,295) as String */
RBUS_LEGACY_BOOLEAN, /**< Boolean as String (ex:"true", "false" */
RBUS_LEGACY_DATETIME, /**< ISO-8601 format (YYYY-MM-DDTHH:MM:SSZ) as String */
RBUS_LEGACY_BASE64, /**< Base64 representation of data as String */
RBUS_LEGACY_LONG, /**< Long (ex: 9223372036854775807 or -9223372036854775808) as String */
RBUS_LEGACY_UNSIGNEDLONG, /**< Unsigned Long (ex: 18446744073709551615) as String */
RBUS_LEGACY_FLOAT, /**< Float (ex: 1.2E-38 or 3.4E+38) as String */
RBUS_LEGACY_DOUBLE, /**< Double (ex: 2.3E-308 or 1.7E+308) as String */
RBUS_LEGACY_BYTE,
RBUS_LEGACY_NONE
} rbusLegacyDataType_t;
rbusError_t getVCHandler(rbusHandle_t handle, rbusProperty_t property, rbusGetHandlerOptions_t* opts)
{
char const* name = rbusProperty_GetName(property);
(void)handle;
(void)opts;
rbusValue_t value;
rbusValue_Init(&value);
if(strcmp("Device.rbusProvider.Param1",name) == 0)
{
/*fake a value change every 'myfreq' times this function is called*/
static int32_t mydata = 0; /*the actual value to send back*/
static int32_t mydelta = 1; /*how much to change the value by*/
static int32_t mycount = 0; /*number of times this function called*/
static int32_t myfreq = 2; /*number of times this function called before changing value*/
static int32_t mymin = 0, mymax=5; /*keep value between mymin and mymax*/
mycount++;
if((mycount % myfreq) == 0)
{
mydata += mydelta;
if(mydata == mymax)
mydelta = -1;
else if(mydata == mymin)
mydelta = 1;
}
printf("Provider: Called get handler for [%s] val=[%d]\n", name, mydata);
rbusValue_SetInt32(value, mydata);
} else if(strcmp("Device.rbusProvider.DateTime",name) == 0) {
rbusDateTime_t timeVal;
struct tm compileTime;
getCompileTime(&compileTime);
memcpy(&(timeVal.m_time), &compileTime, sizeof(struct tm));
rbusValue_SetTime(value, &(timeVal));
} else if(strcmp("Device.rbusProvider.Object",name) == 0) {
rbusObject_t obj = NULL;
rbusObject_Init(&obj, name);
rbusValue_SetObject(value, obj);
} else if(strcmp("Device.rbusProvider.Property",name) == 0) {
rbusProperty_t prop = NULL;
rbusProperty_Init(&prop, name, NULL);
rbusValue_SetProperty(value, prop);
}
else if(strcmp("Device.rbusProvider.Int16",name) == 0)
rbusValue_SetInt16(value, GTEST_VAL_INT16);
else if(strcmp("Device.rbusProvider.Int32",name) == 0)
rbusValue_SetInt32(value, GTEST_VAL_INT32);
else if(strcmp("Device.rbusProvider.Int64",name) == 0)
rbusValue_SetInt64(value, GTEST_VAL_INT64);
else if(strcmp("Device.rbusProvider.UInt16",name) == 0)
rbusValue_SetUInt16(value, GTEST_VAL_UINT16);
else if(strcmp("Device.rbusProvider.UInt32",name) == 0)
rbusValue_SetUInt32(value, GTEST_VAL_UINT32);
else if(strcmp("Device.rbusProvider.UInt64",name) == 0)
rbusValue_SetUInt64(value, GTEST_VAL_UINT64);
else if(strcmp("Device.rbusProvider.Single",name) == 0)
rbusValue_SetSingle(value, GTEST_VAL_SINGLE);
else if(strcmp("Device.rbusProvider.Double",name) == 0)
rbusValue_SetDouble(value, GTEST_VAL_DOUBLE);
else if(strcmp("Device.rbusMultiProvider0.Param1",name) == 0)
rbusValue_SetString(value, name);
else if(strcmp("Device.rbusMultiProvider1.Param1",name) == 0)
rbusValue_SetString(value, name);
else if(strcmp("Device.rbusMultiProvider2.Param1",name) == 0)
rbusValue_SetString(value, name);
rbusProperty_SetValue(property, value);
rbusValue_Release(value);
return RBUS_ERROR_SUCCESS;
}
rbusError_t setHandler(rbusHandle_t handle, rbusProperty_t property, rbusSetHandlerOptions_t* opts)
{
(void)handle;
(void)opts;
char const* name = rbusProperty_GetName(property);
rbusValue_t value = rbusProperty_GetValue(property);
char *val = NULL;
rbusError_t rc = RBUS_ERROR_SUCCESS;
if(!value) return RBUS_ERROR_BUS_ERROR;
val = rbusValue_ToString(value,NULL,0);
printf("setHandler called: property=%s value %s\n", name,val);
if(strcmp(val,"register_row") == 0) {
rc = rbusTable_registerRow(handle, "Device.rbusProvider.PartialPath", NULL, 1);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
if(RBUS_ERROR_SUCCESS == rc)
{
rc = rbusTable_unregisterRow(handle, "Device.rbusProvider.PartialPath");
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
}
} else if(strcmp(val,"unregister_row_fail") == 0) {
rc = rbusTable_unregisterRow(handle, "Device.rbusProvider.PartialPath123");
EXPECT_EQ(rc,RBUS_ERROR_INVALID_INPUT);
}
free(val);
return rc;
}
rbusError_t ppTableGetHandler(rbusHandle_t handle, rbusProperty_t property, rbusGetHandlerOptions_t* opts)
{
char const* name = rbusProperty_GetName(property);
(void)handle;
(void)opts;
printf(
"ppTableGetHandler called:\n" \
"\tproperty=%s\n",
name);
return RBUS_ERROR_SUCCESS;
}
rbusError_t ppTableAddRowHandler(
rbusHandle_t handle,
char const* tableName,
char const* aliasName,
uint32_t* instNum)
{
(void)handle;
(void)aliasName;
if(!strcmp(tableName, "Device.rbusProvider.PartialPath"))
{
static int instanceNumber = 1;
*instNum = instanceNumber++;
}
printf("partialPathTableAddRowHandler table=%s instNum=%d\n", tableName, *instNum);
return RBUS_ERROR_SUCCESS;
}
rbusError_t ppTableRemRowHandler(
rbusHandle_t handle,
char const* rowName)
{
(void)handle;
(void)rowName;
return RBUS_ERROR_SUCCESS;
}
rbusError_t ppParamGetHandler(rbusHandle_t handle, rbusProperty_t property, rbusGetHandlerOptions_t* opts)
{
rbusValue_t value;
char const* name = rbusProperty_GetName(property);
(void)handle;
(void)opts;
printf(
"ppParamGetHandler called:\n" \
"\tproperty=%s\n",
name);
if(!strcmp(name, "Device.rbusProvider.PartialPath.1.Param1") ||
!strcmp(name, "Device.rbusProvider.PartialPath.1.Param2") ||
!strcmp(name, "Device.rbusProvider.PartialPath.2.Param1") ||
!strcmp(name, "Device.rbusProvider.PartialPath.2.Param2")
)
{
/*set value to the name of the parameter so consumer can easily verify result*/
rbusValue_Init(&value);
rbusValue_SetString(value, name);
rbusProperty_SetValue(property, value);
rbusValue_Release(value);
return RBUS_ERROR_SUCCESS;
}
else
{
printf("ppParamGetHandler invalid name %s\n", name);
return RBUS_ERROR_BUS_ERROR;
}
}
static rbusError_t methodHandler(rbusHandle_t handle, char const* methodName, rbusObject_t inParams, rbusObject_t outParams, rbusMethodAsyncHandle_t asyncHandle)
{
(void)handle;
(void)asyncHandle;
rbusValue_t value;
rbusError_t rc = RBUS_ERROR_BUS_ERROR;
printf("methodHandler called: %s\n", methodName);
rbusObject_fwrite(inParams, 1, stdout);
if(strstr(methodName, "Method()")) {
rbusValue_Init(&value);
rbusValue_SetString(value, "Method1()");
rbusObject_SetValue(outParams, "name", value);
rbusValue_Release(value);
rc = RBUS_ERROR_SUCCESS;
} else if(strstr(methodName, "MethodAsync1()")) {
sleep(4);
rbusValue_Init(&value);
rbusValue_SetString(value, "MethodAsync1()");
rbusObject_SetValue(outParams, "name", value);
rbusValue_Release(value);
rc = RBUS_ERROR_SUCCESS;
}
printf("methodHandler %s\n",(RBUS_ERROR_SUCCESS == rc) ? "success": "fail");
return rc;
}
int rbusProvider(rbusGtest_t test, pid_t pid, int *consumer_status)
{
rbusHandle_t handle;
int rc = RBUS_ERROR_BUS_ERROR, wait_ret = -1;
char *componentName = NULL;
rbusDataElement_t dataElements[] = {
{(char *)"Device.rbusProvider.Param1", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Param2", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, setHandler, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Param3", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, setHandler, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Int16", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Int32", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, setHandler, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Int64", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.UInt16", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.UInt32", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, setHandler, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.UInt64", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Single", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Double", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Object", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Property", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.DateTime", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.PartialPath.{i}.", RBUS_ELEMENT_TYPE_TABLE, {ppTableGetHandler, NULL, ppTableAddRowHandler, ppTableRemRowHandler, NULL, NULL}},
{(char *)"Device.rbusProvider.PartialPath.{i}.Param1", RBUS_ELEMENT_TYPE_PROPERTY, {ppParamGetHandler, setHandler, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.PartialPath.{i}.Param2", RBUS_ELEMENT_TYPE_PROPERTY, {ppParamGetHandler, NULL, NULL, NULL, NULL, NULL}},
{(char *)"Device.rbusProvider.Method()", RBUS_ELEMENT_TYPE_METHOD, {NULL, NULL, NULL, NULL, NULL, methodHandler}},
{(char *)"Device.rbusProvider.MethodAsync1()", RBUS_ELEMENT_TYPE_METHOD, {NULL, NULL, NULL, NULL, NULL, methodHandler}}
};
#define elements_count sizeof(dataElements)/sizeof(dataElements[0])
componentName = strdup(__func__);
printf("%s: start\n",componentName);
rc = rbus_open(&handle, componentName);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
if(RBUS_ERROR_SUCCESS != rc) goto exit2;
if(RBUS_GTEST_ASYNC_SUB4 == test)
sleep(7);
rc = rbus_regDataElements(handle, elements_count, dataElements);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
if(RBUS_ERROR_SUCCESS != rc) goto exit1;
if(RBUS_GTEST_GET1 == test ||
RBUS_GTEST_GET_EXT1 == test ||
RBUS_GTEST_SET4 == test ||
RBUS_GTEST_SET_MULTI4 == test ||
RBUS_GTEST_SET_MULTI5 == test)
{
rc |= rbusTable_addRow(handle, "Device.rbusProvider.PartialPath.", NULL, NULL);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
rc |= rbusTable_addRow(handle, "Device.rbusProvider.PartialPath.", NULL, NULL);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
}
wait_ret = waitpid(pid, consumer_status, 0);
EXPECT_EQ(wait_ret,pid);
if(wait_ret != pid) printf("%s: waitpid() failed %d: %s\n",__func__,errno,strerror(errno));
rc = (wait_ret != pid) ? RBUS_ERROR_BUS_ERROR : RBUS_ERROR_SUCCESS;
if(RBUS_GTEST_SET4 == test )
{
rc |= rbusTable_removeRow(handle,"Device.rbusProvider.PartialPath.0");
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
}
rc |= rbus_unregDataElements(handle, elements_count, dataElements);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
exit1:
rc |= rbus_close(handle);
exit2:
free(componentName);
printf("%s: exit\n",__func__);
return rc;
}
int rbusProvider1(int runtime,int should_exit)
{
rbusHandle_t handle;
int rc = RBUS_ERROR_BUS_ERROR;
char *componentName = NULL;
rbusDataElement_t dataElements[] = {
{(char *)"Device.rbusProvider.Param1", RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}}
};
#define elements_count sizeof(dataElements)/sizeof(dataElements[0])
printf("%s: start\n",__func__);
componentName = strdup(__func__);
rc = rbus_open(&handle, componentName);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
if(RBUS_ERROR_SUCCESS != rc) goto exit2;
rc = rbus_regDataElements(handle, 1, dataElements);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
if(RBUS_ERROR_SUCCESS != rc) goto exit1;
sleep(runtime);
if(!should_exit)
goto exit2;
exit1:
rc |= rbus_close(handle);
exit2:
free(componentName);
printf("%s: exit\n",__func__);
return rc;
}
int rbusMultiProvider(int index)
{
rbusHandle_t handle;
int rc = RBUS_ERROR_BUS_ERROR, wait_ret = -1;
sigset_t set;
int sig;
char el_name[64] = {0};
char componentName[32] = {0};
rbusDataElement_t dataElements[] = {
{NULL, RBUS_ELEMENT_TYPE_PROPERTY, {getVCHandler, NULL, NULL, NULL, NULL, NULL}}
};
#define elements_count sizeof(dataElements)/sizeof(dataElements[0])
snprintf(componentName,sizeof(componentName),"%s%d",__func__,index);
printf("%s: start\n",componentName);
rc = rbus_open(&handle, componentName);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
if(RBUS_ERROR_SUCCESS != rc) goto exit2;
snprintf(el_name,sizeof(el_name),"Device.%s.Param1",componentName);
dataElements[0].name = el_name;
rc = rbus_regDataElements(handle, elements_count, dataElements);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
if(RBUS_ERROR_SUCCESS != rc) goto exit1;
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
sigprocmask(SIG_BLOCK, &set, NULL);
sigwait(&set, &sig);
printf("%s Got signal %d: %s\n", componentName, sig, strsignal(sig));
rc |= rbus_unregDataElements(handle, elements_count, dataElements);
EXPECT_EQ(rc,RBUS_ERROR_SUCCESS);
exit1:
rc |= rbus_close(handle);
exit2:
printf("%s: exit\n",componentName);
return rc;
}
static int handle_get(const char * destination, const char * method, rbusMessage message, void * user_data, rbusMessage *response, const rtMessageHeader* hdr)
{
(void) message;
(void) method;
(void) hdr;
char buffer[32] = {0};
rbusGtest_t *test = (rbusGtest_t *)user_data;
rbusMessage_Init(response);
rbusMessage_SetInt32(*response, RTMESSAGE_BUS_SUCCESS);
rbusMessage_SetInt32(*response, 1);
if(RBUS_GTEST_GET24 != *test)
rbusMessage_SetString(*response, destination);
switch(*test)
{
case RBUS_GTEST_GET13:
rbusMessage_SetInt32(*response, RBUS_LEGACY_UNSIGNEDINT);
snprintf(buffer, sizeof(buffer), "%d", GTEST_VAL_UINT32);
break;
case RBUS_GTEST_GET14:
rbusMessage_SetInt32(*response, RBUS_LEGACY_BOOLEAN);
snprintf(buffer, sizeof(buffer), "%d", GTEST_VAL_BOOL);
break;
case RBUS_GTEST_GET15:
rbusMessage_SetInt32(*response, RBUS_LEGACY_LONG);
snprintf(buffer, sizeof(buffer), "%" PRIi64, GTEST_VAL_INT64);
break;
case RBUS_GTEST_GET16:
rbusMessage_SetInt32(*response, RBUS_LEGACY_UNSIGNEDLONG);
snprintf(buffer, sizeof(buffer), "%" PRIu64, GTEST_VAL_UINT64);
break;
case RBUS_GTEST_GET17:
rbusMessage_SetInt32(*response, RBUS_LEGACY_FLOAT);
snprintf(buffer, sizeof(buffer), "%.15f", GTEST_VAL_SINGLE);
break;
case RBUS_GTEST_GET18:
rbusMessage_SetInt32(*response, RBUS_LEGACY_DOUBLE);
snprintf(buffer, sizeof(buffer), "%.15f", GTEST_VAL_DOUBLE);
break;
case RBUS_GTEST_GET19:
rbusMessage_SetInt32(*response, RBUS_LEGACY_BYTE);
snprintf(buffer, sizeof(buffer), "%s", GTEST_VAL_STRING);
break;
case RBUS_GTEST_GET20:
{
struct tm compileTime;
char buf[80] = {0};
getCompileTime(&compileTime);
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &compileTime);
rbusMessage_SetInt32(*response, RBUS_LEGACY_DATETIME);
snprintf(buffer, sizeof(buffer), "%s", buf);
}
break;
case RBUS_GTEST_GET21:
rbusMessage_SetInt32(*response, RBUS_LEGACY_BASE64);
snprintf(buffer, sizeof(buffer), "%s", GTEST_VAL_STRING);
break;
case RBUS_GTEST_GET22:
rbusMessage_SetInt32(*response, RBUS_LEGACY_STRING);
snprintf(buffer, sizeof(buffer), "%s", GTEST_VAL_STRING);
break;
case RBUS_GTEST_GET23:
rbusMessage_SetInt32(*response, RBUS_LEGACY_INT);
snprintf(buffer, sizeof(buffer), "%d", GTEST_VAL_INT32);
break;
}
rbusMessage_SetString(*response, buffer);
return 0;
}
int rbuscoreProvider(rbusGtest_t test, pid_t pid, int *consumer_status)
{
rbus_error_t err = RTMESSAGE_BUS_ERROR_GENERAL;
int rc = RBUS_ERROR_BUS_ERROR, wait_ret = -1;
const char *object_name = NULL;
rbus_method_table_entry_t table[1] = {{METHOD_GETPARAMETERVALUES, &test, handle_get}};
printf("%s: start \n",__func__);
switch(test)
{
case RBUS_GTEST_GET13: object_name = "Device.rbuscoreProvider.GetLegUInt32"; break;
case RBUS_GTEST_GET14: object_name = "Device.rbuscoreProvider.GetLegBoolean"; break;
case RBUS_GTEST_GET15: object_name = "Device.rbuscoreProvider.GetLegLong"; break;
case RBUS_GTEST_GET16: object_name = "Device.rbuscoreProvider.GetLegULong"; break;
case RBUS_GTEST_GET17: object_name = "Device.rbuscoreProvider.GetLegFloat"; break;
case RBUS_GTEST_GET18: object_name = "Device.rbuscoreProvider.GetLegDouble"; break;
case RBUS_GTEST_GET19: object_name = "Device.rbuscoreProvider.GetLegBytes"; break;
case RBUS_GTEST_GET20: object_name = "Device.rbuscoreProvider.GetLegDateTime"; break;
case RBUS_GTEST_GET21: object_name = "Device.rbuscoreProvider.GetLegBase64"; break;
case RBUS_GTEST_GET22: object_name = "Device.rbuscoreProvider.GetLegString"; break;
case RBUS_GTEST_GET23: object_name = "Device.rbuscoreProvider.GetLegInt32"; break;
case RBUS_GTEST_GET24: object_name = "Device.rbuscoreProvider.GetLegCrInt32"; break;
}
err = rbus_openBrokerConnection(object_name);
EXPECT_EQ(err,RTMESSAGE_BUS_SUCCESS);
if(RTMESSAGE_BUS_SUCCESS != err) goto exit1;
err = rbus_registerObj(object_name, handle_get, NULL);
EXPECT_EQ(err,RTMESSAGE_BUS_SUCCESS);
if(RTMESSAGE_BUS_SUCCESS != err) goto exit2;
err = rbus_registerMethodTable(object_name, table, 1);
EXPECT_EQ(err,RTMESSAGE_BUS_SUCCESS);
if(RTMESSAGE_BUS_SUCCESS != err) goto exit2;
wait_ret = waitpid(pid, consumer_status, 0);
EXPECT_EQ(wait_ret,pid);
if(wait_ret != pid) printf("%s: waitpid() failed %d: %s\n",__func__,errno,strerror(errno));
rc = (wait_ret != pid) ? RBUS_ERROR_BUS_ERROR : RBUS_ERROR_SUCCESS;
exit2:
err = rbus_closeBrokerConnection();
EXPECT_EQ(err,RTMESSAGE_BUS_SUCCESS);
rc |= (RTMESSAGE_BUS_SUCCESS == err) ? RBUS_ERROR_SUCCESS : RBUS_ERROR_BUS_ERROR;
exit1:
printf("%s: exit\n",__func__);
return rc;
}
| 36.690608 | 161 | 0.70913 | [
"object"
] |
92717df59ca9edcb71b9458076a57ddfea37e23b | 3,922 | hpp | C++ | src/helper_functions.hpp | brisyramshere/meshmonk | a0a7cf79902541cf9c800d83a4d4f14fcd756f6f | [
"Apache-2.0"
] | 53 | 2017-02-03T14:59:54.000Z | 2022-03-14T05:40:58.000Z | src/helper_functions.hpp | brisyramshere/meshmonk | a0a7cf79902541cf9c800d83a4d4f14fcd756f6f | [
"Apache-2.0"
] | 16 | 2018-07-16T10:34:15.000Z | 2022-01-18T04:37:12.000Z | src/helper_functions.hpp | brisyramshere/meshmonk | a0a7cf79902541cf9c800d83a4d4f14fcd756f6f | [
"Apache-2.0"
] | 23 | 2018-07-05T14:59:52.000Z | 2022-01-14T07:01:47.000Z | #ifndef HELPER_FUNCTIONS_HPP_INCLUDED
#define HELPER_FUNCTIONS_HPP_INCLUDED
#include <iostream>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
//#include <OpenMesh/Core/IO/reader/OBJReader.hh>
//#include <OpenMesh/Core/IO/writer/OBJWriter.hh>
#include <nanoflann.hpp>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include "../global.hpp"
typedef OpenMesh::TriMesh_ArrayKernelT<> TriMesh;
typedef Eigen::SparseMatrix<float, 0, int> SparseMat;
typedef Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic> MatDynInt; //matrix MxN of type unsigned int
typedef Eigen::Matrix< int, Eigen::Dynamic, 3> FacesMat; //matrix Mx3 of type unsigned int
typedef Eigen::VectorXf VecDynFloat;
typedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic> MatDynFloat; //matrix MxN of type float
typedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat; //matrix Mx6 of type float
typedef Eigen::MatrixX3f Vec3Mat;
namespace registration {
void fuse_affinities(SparseMat &ioAffinity1,
const SparseMat &inAffinity2);
void normalize_sparse_matrix(SparseMat &ioMat);
template <typename VecMatType>
void radius_nearest_neighbours(const VecMatType &inQueriedPoints,
const VecMatType &inSourcePoints,
MatDynInt &outNeighbourIndices,
MatDynFloat &outNeighbourSquaredDistances,
const float paramRadius = 3.0,
const size_t paramLeafsize = 15);
void convert_mesh_to_matrices(const TriMesh &inMesh,
FeatureMat &outFeatures,
FacesMat &outFaces);
void convert_mesh_to_matrices(const TriMesh &inMesh,
FeatureMat &outFeatures);
void convert_mesh_to_matrices(const TriMesh &inMesh,
FeatureMat &outFeatures,
FacesMat &outFaces,
VecDynFloat &outFlags);
void convert_matrices_to_mesh(const Vec3Mat &inPositions,
const FacesMat &inFaces,
TriMesh &outMesh);
void convert_matrices_to_mesh(const FeatureMat &inFeatures,
const FacesMat &inFaces,
TriMesh &outMesh);
void convert_matrices_to_mesh(const FeatureMat &inFeatures,
const FacesMat &inFaces,
const VecDynFloat &inFlags,
TriMesh &outMesh);
//void load_obj_to_eigen(const std::string inObjFilename,
// TriMesh &outMesh,
// FeatureMat &outFeatureMatrix);
//void write_eigen_to_obj(const FeatureMat &inFeatures,
// TriMesh &inMesh,
// const std::string inObjFilename);
//bool import_data(const std::string inFloatingMeshPath,
// const std::string inTargetMeshPath,
// FeatureMat &outFloatingFeatures,
// FeatureMat &outTargetFeatures,
// FacesMat &outFloatingFaces,
// FacesMat &outTargetFaces);
//bool export_data(FeatureMat &inResultFeatures,
// FacesMat &inResultFaces,
// const std::string inResultMeshPath);
void update_normals_for_altered_positions(TriMesh &ioMesh,
FeatureMat &ioFeatures);
void update_normals_for_altered_positions(const Vec3Mat &inPositions,
const FacesMat &inFaces,
Vec3Mat &outNormals);
void update_normals_safely(const FeatureMat &features, TriMesh &mesh);
}//namespace registration
#endif // HELPER_FUNCTIONS_HPP_INCLUDED
| 38.831683 | 112 | 0.609383 | [
"mesh"
] |
927f66b6a0794963c0efdc395cb35b7442046bc1 | 8,268 | cpp | C++ | code/engine.vc2008/xrGame/aimers_base.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | 6 | 2020-07-06T13:34:28.000Z | 2021-07-12T10:36:23.000Z | code/engine.vc2008/xrGame/aimers_base.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrGame/aimers_base.cpp | Pavel3333/xray-oxygen | 42331cd5f30511214c704d6ca9d919c209363eea | [
"Apache-2.0"
] | 5 | 2020-10-18T11:55:26.000Z | 2022-03-28T07:21:35.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : aimers_base.cpp
// Created : 04.04.2008
// Modified : 08.04.2008
// Author : Dmitriy Iassenev
// Description : aimers base class
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "aimers_base.h"
#include "gameobject.h"
#include "../include/xrrender/kinematics.h"
#include "../xrPhysics/animation_movement_controller.h"
using aimers::base;
base::base (
CGameObject* object,
LPCSTR animation_id,
bool animation_start,
Fvector const& target
) :
m_object ( *object ),
m_kinematics ( smart_cast<IKinematics&>( *object->Visual() ) ),
m_animated ( smart_cast<IKinematicsAnimated&>( *object->Visual() ) ),
m_target ( target ),
m_animation_id ( m_animated.LL_MotionID( animation_id ) ),
m_animation_start ( animation_start )
{
animation_movement_controller const* controller = m_object.animation_movement();
if (!controller)
m_start_transform = m_object.XFORM();
else
m_start_transform = controller->start_transform();
VERIFY ( _valid(m_start_transform) );
}
void base::callback (CBoneInstance* bone)
{
VERIFY (bone);
Fmatrix* rotation = static_cast<Fmatrix*>(bone->callback_param());
VERIFY (rotation);
VERIFY2 ( _valid( *rotation ), "base::callback[rotation] " );
Fvector position = bone->mTransform.c;
bone->mTransform.mulA_43(*rotation);
bone->mTransform.c = position;
VERIFY2 ( _valid( bone->mTransform ), "base::callback " );
}
void base::aim_at_position (
Fvector const& bone_position,
Fvector const& object_position,
Fvector object_direction,
Fmatrix& result
)
{
#if 0
Msg (
"[%d][%s] bone_position[%f][%f][%f] object_position[%f][%f][%f] object_direction[%f][%f][%f]",
Device.dwFrame,
m_animated.LL_MotionDefName_dbg(m_animation_id).first,
VPUSH(bone_position),
VPUSH(object_position),
VPUSH(object_direction)
);
#endif // #if 0
VERIFY2 (
_valid(bone_position),
make_string(
"[%f][%f][%f]",
VPUSH(bone_position)
)
);
VERIFY2 (
_valid(object_position),
make_string(
"[%f][%f][%f]",
VPUSH(object_position)
)
);
VERIFY2 (
_valid(object_direction),
make_string(
"[%f][%f][%f]",
VPUSH(object_direction)
)
);
VERIFY2 (
_valid(m_target),
make_string(
"[%f][%f][%f]",
VPUSH(m_target)
)
);
VERIFY2 (
object_direction.square_magnitude() > EPS_L,
make_string("[%f]", object_direction.square_magnitude())
);
object_direction.normalize ();
Fvector const object2bone = Fvector().sub(bone_position, object_position);
VERIFY ( _valid(object2bone) );
float const offset = object2bone.dotproduct(object_direction);
VERIFY ( _valid(offset) );
Fvector const current_point = Fvector().mad(object_position, object_direction, offset);
VERIFY ( _valid(current_point) );
Fvector bone2current = Fvector().sub(current_point, bone_position);
VERIFY ( _valid(bone2current) );
if (bone2current.magnitude() < EPS_L)
bone2current.set ( 0.f, 0.f, EPS_L );
VERIFY ( _valid(bone2current) );
float const sphere_radius_sqr = bone2current.square_magnitude();
VERIFY ( _valid(sphere_radius_sqr) );
Fvector direction_target = Fvector().sub(m_target, bone_position);
VERIFY ( _valid(direction_target) );
if (direction_target.magnitude() < EPS_L)
direction_target.set ( 0.f, 0.f, EPS_L );
VERIFY ( _valid(direction_target) );
float const invert_magnitude = 1.f/direction_target.magnitude();
direction_target.mul (invert_magnitude);
VERIFY2 (
fsimilar(direction_target.magnitude(), 1.f),
make_string(
"[%f][%f] [%f][%f][%f] [%f][%f][%f]",
direction_target.magnitude(),
invert_magnitude,
VPUSH(m_target),
VPUSH(bone_position)
)
);
float const to_circle_center = sphere_radius_sqr*invert_magnitude;
VERIFY ( _valid(to_circle_center) );
Fvector const circle_center = Fvector().mad(bone_position, direction_target, to_circle_center);
VERIFY ( _valid(circle_center) );
Fplane const plane = Fplane().build(circle_center, direction_target);
VERIFY2 ( _valid(plane), make_string("[%f][%f][%f] [%f][%f][%f] [%f][%f][%f] %f", VPUSH(circle_center), VPUSH(direction_target), VPUSH(plane.n), plane.d) );
Fvector projection;
plane.project (projection, current_point);
VERIFY ( _valid(projection) );
Fvector projection2circle_center = Fvector().sub(projection, circle_center);
VERIFY ( _valid(projection2circle_center) );
if (projection2circle_center.magnitude() < EPS_L)
projection2circle_center.set ( 0.f, 0.f, EPS_L );
VERIFY ( _valid(projection2circle_center) );
Fvector const center2projection_direction = projection2circle_center.normalize();
VERIFY ( _valid(center2projection_direction) );
float circle_radius_sqr = sphere_radius_sqr - _sqr(to_circle_center);
VERIFY ( _valid(circle_radius_sqr) );
if (circle_radius_sqr < 0.f)
circle_radius_sqr = 0.f;
VERIFY ( _valid(circle_radius_sqr) );
float const circle_radius = _sqrt(circle_radius_sqr);
VERIFY ( _valid(circle_radius) );
Fvector const target_point = Fvector().mad(circle_center, center2projection_direction, circle_radius);
VERIFY ( _valid(target_point) );
Fvector const current_direction = Fvector(bone2current).normalize();
VERIFY ( _valid(current_direction) );
Fvector target2bone = Fvector().sub(target_point, bone_position);
VERIFY ( _valid(target2bone) );
if (target2bone.magnitude() < EPS_L)
target2bone.set ( 0.f, 0.f, EPS_L);
VERIFY ( _valid(target2bone) );
Fvector const target_direction = target2bone.normalize();
VERIFY ( _valid(target_direction) );
Fmatrix transform0;
{
Fvector cross_product = Fvector().crossproduct(current_direction, target_direction);
VERIFY ( _valid(cross_product) );
float const sin_alpha = clampr(cross_product.magnitude(), -1.f, 1.f);
if (!fis_zero(sin_alpha)) {
float cos_alpha = clampr(current_direction.dotproduct(target_direction), -1.f, 1.f);
transform0.rotation (cross_product.div(sin_alpha), atan2f(sin_alpha, cos_alpha));
VERIFY ( _valid(transform0) );
}
else {
float const dot_product = clampr(current_direction.dotproduct(target_direction), -1.f, 1.f);
if (fsimilar(_abs(dot_product), 0.f))
transform0.identity ();
else {
VERIFY (fsimilar(_abs(dot_product), 1.f));
cross_product.crossproduct (current_direction, direction_target);
float const sin_alpha2 = clampr(cross_product.magnitude(), -1.f, 1.f);
if (!fis_zero(sin_alpha2)) {
transform0.rotation (cross_product.div(sin_alpha2), dot_product > 0.f ? 0.f : PI);
VERIFY ( _valid(transform0) );
}
else {
transform0.rotation ( Fvector().set(0.f, 0.f, 1.f) , dot_product > 0.f ? 0.f : PI);
VERIFY ( _valid(transform0) );
}
}
}
}
Fmatrix transform1;
{
Fvector target2target_point = Fvector().sub(m_target, target_point);
if (target2target_point.magnitude() < EPS_L)
target2target_point.set (0.f, 0.f, EPS_L);
Fvector const new_direction = target2target_point.normalize();
Fvector old_direction;
transform0.transform_dir (old_direction, object_direction);
Fvector cross_product = Fvector().crossproduct(old_direction, new_direction);
float const sin_alpha = clampr(cross_product.magnitude(), -1.f, 1.f);
if (!fis_zero(sin_alpha)) {
float const cos_alpha = clampr(old_direction.dotproduct(new_direction), -1.f, 1.f);
transform1.rotation (cross_product.div(sin_alpha), atan2f(sin_alpha, cos_alpha));
}
else {
float const dot_product = clampr(current_direction.dotproduct(target_direction), -1.f, 1.f);
if (fsimilar(_abs(dot_product), 0.f))
transform1.identity ();
else {
VERIFY (fsimilar(_abs(dot_product), 1.f));
transform1.rotation (target_direction, dot_product > 0.f ? 0.f : PI);
}
}
}
VERIFY ( _valid(transform0) );
VERIFY ( _valid(transform1) );
result.mul_43 (transform1, transform0);
VERIFY ( _valid(result) );
}
| 34.165289 | 164 | 0.667876 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.