text
stringlengths 5
1.04M
|
|---|
/*
* (C) Copyright 1996-2012 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include "eckit/sql/expression/function/FunctionAVG.h"
#include "eckit/sql/expression/function/FunctionFactory.h"
namespace eckit {
namespace sql {
namespace expression {
namespace function {
/* Static self-registration */
static FunctionBuilder<FunctionAVG> avgFunctionBuilder("avg");
static FunctionBuilder<FunctionAVG> meanFunctionBuilder("mean");
FunctionAVG::FunctionAVG(const std::string& name, const expression::Expressions& args) :
FunctionExpression(name, args),
count_(0),
value_(0) {}
FunctionAVG::FunctionAVG(const FunctionAVG& other) :
FunctionExpression(other.name_, other.args_),
count_(other.count_),
value_(other.value_) {}
std::shared_ptr<SQLExpression> FunctionAVG::clone() const {
return std::make_shared<FunctionAVG>(*this);
}
const type::SQLType* FunctionAVG::type() const {
return &type::SQLType::lookup("double");
}
FunctionAVG::~FunctionAVG() {}
double FunctionAVG::eval(bool& missing) const {
if (!count_) {
missing = true;
return 0;
}
return value_ / count_;
}
void FunctionAVG::prepare(SQLSelect& sql) {
FunctionExpression::prepare(sql);
value_ = 0;
count_ = 0;
}
void FunctionAVG::cleanup(SQLSelect& sql) {
// cout << "Cleanup FunctionAVG " << count_ << " " << value_ << std::endl;
FunctionExpression::cleanup(sql);
value_ = 0;
count_ = 0;
}
void FunctionAVG::partialResult() {
bool missing = false;
double value = args_[0]->eval(missing);
if (!missing) {
value_ += value;
count_++;
}
// else cout << "missing" << std::endl;
}
} // namespace function
} // namespace expression
} // namespace sql
} // namespace eckit
|
#include <mtpio/chain/whitelisted_intrinsics.hpp>
#include <mtpio/chain/exceptions.hpp>
namespace mtpio { namespace chain {
template<typename Iterator>
bool find_intrinsic_helper( uint64_t h, const std::string& name, Iterator& itr, const Iterator& end ) {
for( ; itr != end && itr->first == h; ++itr ) {
if( itr->second.compare( 0, itr->second.size(), name.c_str(), name.size() ) == 0 ) {
return true;
}
}
return false;
}
whitelisted_intrinsics_type::iterator
find_intrinsic( whitelisted_intrinsics_type& whitelisted_intrinsics, uint64_t h, const std::string& name )
{
auto itr = whitelisted_intrinsics.lower_bound( h );
const auto end = whitelisted_intrinsics.end();
if( !find_intrinsic_helper( h, name, itr, end ) )
return end;
return itr;
}
whitelisted_intrinsics_type::const_iterator
find_intrinsic( const whitelisted_intrinsics_type& whitelisted_intrinsics, uint64_t h, const std::string& name )
{
auto itr = whitelisted_intrinsics.lower_bound( h );
const auto end = whitelisted_intrinsics.end();
if( !find_intrinsic_helper( h, name, itr, end ) )
return end;
return itr;
}
bool is_intrinsic_whitelisted( const whitelisted_intrinsics_type& whitelisted_intrinsics, const std::string& name )
{
uint64_t h = static_cast<uint64_t>( std::hash<std::string>{}( name ) );
auto itr = whitelisted_intrinsics.lower_bound( h );
const auto end = whitelisted_intrinsics.end();
return find_intrinsic_helper( h, name, itr, end );
}
void add_intrinsic_to_whitelist( whitelisted_intrinsics_type& whitelisted_intrinsics, const std::string& name )
{
uint64_t h = static_cast<uint64_t>( std::hash<std::string>{}( name ) );
auto itr = find_intrinsic( whitelisted_intrinsics, h, name );
MTP_ASSERT( itr == whitelisted_intrinsics.end(), database_exception,
"cannot add intrinsic '${name}' since it already exists in the whitelist",
("name", name)
);
whitelisted_intrinsics.emplace( std::piecewise_construct,
std::forward_as_tuple( h ),
std::forward_as_tuple( name.c_str(), name.size(),
whitelisted_intrinsics.get_allocator() )
);
}
void remove_intrinsic_from_whitelist( whitelisted_intrinsics_type& whitelisted_intrinsics, const std::string& name )
{
uint64_t h = static_cast<uint64_t>( std::hash<std::string>{}( name ) );
auto itr = find_intrinsic( whitelisted_intrinsics, h, name );
MTP_ASSERT( itr != whitelisted_intrinsics.end(), database_exception,
"cannot remove intrinsic '${name}' since it does not exist in the whitelist",
("name", name)
);
whitelisted_intrinsics.erase( itr );
}
void reset_intrinsic_whitelist( whitelisted_intrinsics_type& whitelisted_intrinsics,
const std::set<std::string>& s )
{
whitelisted_intrinsics.clear();
for( const auto& name : s ) {
uint64_t h = static_cast<uint64_t>( std::hash<std::string>{}( name ) );
whitelisted_intrinsics.emplace( std::piecewise_construct,
std::forward_as_tuple( h ),
std::forward_as_tuple( name.c_str(), name.size(),
whitelisted_intrinsics.get_allocator() )
);
}
}
std::set<std::string> convert_intrinsic_whitelist_to_set( const whitelisted_intrinsics_type& whitelisted_intrinsics ) {
std::set<std::string> s;
for( const auto& p : whitelisted_intrinsics ) {
s.emplace( p.second.c_str(), p.second.size() );
}
return s;
}
} }
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include "convolution_vulkan.h"
#include <algorithm>
#include "layer_type.h"
namespace ncnn {
DEFINE_LAYER_CREATOR(Convolution_vulkan)
Convolution_vulkan::Convolution_vulkan()
{
support_vulkan = true;
padding = 0;
pipeline_convolution = 0;
pipeline_convolution_1x1s1d1 = 0;
pipeline_convolution_pack4 = 0;
pipeline_convolution_pack4_1x1s1d1 = 0;
pipeline_convolution_pack4_3x3s1d1_lds_8_8_2 = 0;
winograd_padding = 0;
winograd_crop = 0;
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_input = 0;
pipeline_convolution_pack4_3x3s1d1_winograd63_gemm = 0;
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_output = 0;
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_input = 0;
pipeline_convolution_pack4_3x3s1d1_winograd23_gemm = 0;
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_output = 0;
pipeline_convolution_pack1to4 = 0;
pipeline_convolution_pack4to1 = 0;
pipeline_innerproduct = 0;
pipeline_innerproduct_pack4 = 0;
pipeline_innerproduct_pack1to4 = 0;
pipeline_innerproduct_pack4to1 = 0;
}
int Convolution_vulkan::create_pipeline(const Option& opt)
{
{
padding = ncnn::create_layer(ncnn::LayerType::Padding);
padding->vkdev = vkdev;
ncnn::ParamDict pd;
pd.set(0, pad_h);
pd.set(1, pad_h);
pd.set(2, pad_w);
pd.set(3, pad_w);
pd.set(4, 0);
pd.set(5, 0.f);
padding->load_param(pd);
padding->create_pipeline(opt);
}
const int maxk = kernel_w * kernel_h;
int num_input = weight_data_size / maxk / num_output;
std::vector<vk_specialization_type> specializations(10);
specializations[0].i = kernel_w;
specializations[1].i = kernel_h;
specializations[2].i = dilation_w;
specializations[3].i = dilation_h;
specializations[4].i = stride_w;
specializations[5].i = stride_h;
specializations[6].i = bias_term;
specializations[7].i = activation_type;
specializations[8].f = activation_params.w == 1 ? activation_params[0] : 0.f;
specializations[9].f = activation_params.w == 2 ? activation_params[1] : 0.f;
// pack1
if (num_input % 4 != 0 && num_output % 4 != 0)
{
pipeline_convolution = new Pipeline(vkdev);
pipeline_convolution->set_optimal_local_size_xyz(32, 32, std::max(1, num_output / 8));
pipeline_convolution->create("convolution", opt, specializations, 4, 10);
if (kernel_w == 1 && kernel_h == 1 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1)
{
pipeline_convolution_1x1s1d1 = new Pipeline(vkdev);
pipeline_convolution_1x1s1d1->set_optimal_local_size_xyz(-1, 1, std::max(1, num_output / 8));
std::vector<vk_specialization_type> specializations(4);
specializations[0].i = bias_term;
specializations[1].i = activation_type;
specializations[2].f = activation_params.w == 1 ? activation_params[0] : 0.f;
specializations[3].f = activation_params.w == 2 ? activation_params[1] : 0.f;
pipeline_convolution_1x1s1d1->create("convolution_1x1s1d1", opt, specializations, 4, 8);
}
}
// pack4
if (num_input % 4 == 0 && num_output % 4 == 0)
{
pipeline_convolution_pack4 = new Pipeline(vkdev);
pipeline_convolution_pack4->set_optimal_local_size_xyz(32, 32, std::max(1, num_output / 8));
pipeline_convolution_pack4->create("convolution_pack4", opt, specializations, 4, 10);
if (kernel_w == 1 && kernel_h == 1 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1)
{
pipeline_convolution_pack4_1x1s1d1 = new Pipeline(vkdev);
pipeline_convolution_pack4_1x1s1d1->set_local_size_xyz(8, 1, std::min(8, num_output / 4));
std::vector<vk_specialization_type> specializations(4);
specializations[0].i = bias_term;
specializations[1].i = activation_type;
specializations[2].f = activation_params.w == 1 ? activation_params[0] : 0.f;
specializations[3].f = activation_params.w == 2 ? activation_params[1] : 0.f;
pipeline_convolution_pack4_1x1s1d1->create("convolution_pack4_1x1s1d1", opt, specializations, 4, 8);
}
if (kernel_w == 3 && kernel_h == 3 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1)
{
std::vector<vk_specialization_type> specializations(4);
specializations[0].i = bias_term;
specializations[1].i = activation_type;
specializations[2].f = activation_params.w == 1 ? activation_params[0] : 0.f;
specializations[3].f = activation_params.w == 2 ? activation_params[1] : 0.f;
pipeline_convolution_pack4_3x3s1d1_lds_8_8_2 = new Pipeline(vkdev);
pipeline_convolution_pack4_3x3s1d1_lds_8_8_2->set_local_size_xyz(8, 8, 2);
pipeline_convolution_pack4_3x3s1d1_lds_8_8_2->create("convolution_pack4_3x3s1d1_lds_8_8_2", opt, specializations, 4, 10);
if (num_input >= 16 && num_output >= 16)
{
{
winograd_padding = ncnn::create_layer(ncnn::LayerType::Padding);
winograd_padding->vkdev = vkdev;
ncnn::ParamDict pd;
pd.set(0, -233);
pd.set(1, -233);
pd.set(2, -233);
pd.set(3, -233);
pd.set(4, 0);
pd.set(5, 0.f);
winograd_padding->load_param(pd);
winograd_padding->create_pipeline(opt);
}
{
winograd_crop = ncnn::create_layer(ncnn::LayerType::Crop);
winograd_crop->vkdev = vkdev;
ncnn::ParamDict pd;
pd.set(0, -233);
pd.set(1, -233);
pd.set(2, -233);
pd.set(3, 0);
pd.set(4, 0);
pd.set(5, 0);
winograd_crop->load_param(pd);
winograd_crop->create_pipeline(opt);
}
}
if (num_input >= 64 && num_output >= 64)
{
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_input = new Pipeline(vkdev);
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_input->set_local_size_xyz(8, 8, 1);
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_input->create("convolution_pack4_3x3s1d1_winograd63_transform_input", opt, std::vector<vk_specialization_type>(), 2, 7);
pipeline_convolution_pack4_3x3s1d1_winograd63_gemm = new Pipeline(vkdev);
pipeline_convolution_pack4_3x3s1d1_winograd63_gemm->set_local_size_xyz(4, 4, 4);
pipeline_convolution_pack4_3x3s1d1_winograd63_gemm->create("convolution_pack4_3x3s1d1_winograd63_gemm", opt, std::vector<vk_specialization_type>(), 3, 6);
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_output = new Pipeline(vkdev);
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_output->set_local_size_xyz(8, 8, 1);
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_output->create("convolution_pack4_3x3s1d1_winograd63_transform_output", opt, specializations, 3, 7);
}
else if (num_input >= 16 && num_output >= 16)
{
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_input = new Pipeline(vkdev);
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_input->set_local_size_xyz(8, 8, 1);
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_input->create("convolution_pack4_3x3s1d1_winograd23_transform_input", opt, std::vector<vk_specialization_type>(), 2, 7);
pipeline_convolution_pack4_3x3s1d1_winograd23_gemm = new Pipeline(vkdev);
pipeline_convolution_pack4_3x3s1d1_winograd23_gemm->set_local_size_xyz(4, 4, 4);
pipeline_convolution_pack4_3x3s1d1_winograd23_gemm->create("convolution_pack4_3x3s1d1_winograd23_gemm", opt, std::vector<vk_specialization_type>(), 3, 6);
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_output = new Pipeline(vkdev);
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_output->set_local_size_xyz(8, 8, 1);
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_output->create("convolution_pack4_3x3s1d1_winograd23_transform_output", opt, specializations, 3, 7);
}
}
}
// pack1to4
if (num_input % 4 != 0 && num_output % 4 == 0)
{
pipeline_convolution_pack1to4 = new Pipeline(vkdev);
pipeline_convolution_pack1to4->set_optimal_local_size_xyz(32, 32, std::max(1, num_output / 8));
pipeline_convolution_pack1to4->create("convolution_pack1to4", opt, specializations, 4, 10);
}
// pack4to1
if (num_input % 4 == 0 && num_output % 4 != 0)
{
pipeline_convolution_pack4to1 = new Pipeline(vkdev);
pipeline_convolution_pack4to1->set_optimal_local_size_xyz(32, 32, std::max(1, num_output / 8));
pipeline_convolution_pack4to1->create("convolution_pack4to1", opt, specializations, 4, 10);
}
// fc
if (kernel_w == 1 && kernel_h == 1)
{
std::vector<vk_specialization_type> specializations(4);
specializations[0].i = bias_term;
specializations[1].i = activation_type;
specializations[2].f = activation_params.w == 1 ? activation_params[0] : 0.f;
specializations[3].f = activation_params.w == 2 ? activation_params[1] : 0.f;
// pack1
if (num_input % 4 != 0 && num_output % 4 != 0)
{
pipeline_innerproduct = new Pipeline(vkdev);
pipeline_innerproduct->set_optimal_local_size_xyz(num_output, 1, 1);
pipeline_innerproduct->create("innerproduct", opt, specializations, 4, 10);
}
// pack4
if (num_input % 4 == 0 && num_output % 4 == 0)
{
pipeline_innerproduct_pack4 = new Pipeline(vkdev);
pipeline_innerproduct_pack4->set_optimal_local_size_xyz(num_output / 4, 1, 1);
pipeline_innerproduct_pack4->create("innerproduct_pack4", opt, specializations, 4, 10);
}
// pack1to4
if (num_input % 4 != 0 && num_output % 4 == 0)
{
pipeline_innerproduct_pack1to4 = new Pipeline(vkdev);
pipeline_innerproduct_pack1to4->set_optimal_local_size_xyz(num_output / 4, 1, 1);
pipeline_innerproduct_pack1to4->create("innerproduct_pack1to4", opt, specializations, 4, 10);
}
// pack4to1
if (num_input % 4 == 0 && num_output % 4 != 0)
{
pipeline_innerproduct_pack4to1 = new Pipeline(vkdev);
pipeline_innerproduct_pack4to1->set_optimal_local_size_xyz(num_output, 1, 1);
pipeline_innerproduct_pack4to1->create("innerproduct_pack4to1", opt, specializations, 4, 10);
}
}
return 0;
}
int Convolution_vulkan::destroy_pipeline(const Option& opt)
{
if (padding)
{
padding->destroy_pipeline(opt);
delete padding;
padding = 0;
}
delete pipeline_convolution;
pipeline_convolution = 0;
delete pipeline_convolution_1x1s1d1;
pipeline_convolution_1x1s1d1 = 0;
delete pipeline_convolution_pack4;
pipeline_convolution_pack4 = 0;
delete pipeline_convolution_pack4_1x1s1d1;
pipeline_convolution_pack4_1x1s1d1 = 0;
delete pipeline_convolution_pack4_3x3s1d1_lds_8_8_2;
pipeline_convolution_pack4_3x3s1d1_lds_8_8_2 = 0;
if (winograd_padding)
{
winograd_padding->destroy_pipeline(opt);
delete winograd_padding;
winograd_padding = 0;
}
if (winograd_crop)
{
winograd_crop->destroy_pipeline(opt);
delete winograd_crop;
winograd_crop = 0;
}
delete pipeline_convolution_pack4_3x3s1d1_winograd63_transform_input;
delete pipeline_convolution_pack4_3x3s1d1_winograd63_gemm;
delete pipeline_convolution_pack4_3x3s1d1_winograd63_transform_output;
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_input = 0;
pipeline_convolution_pack4_3x3s1d1_winograd63_gemm = 0;
pipeline_convolution_pack4_3x3s1d1_winograd63_transform_output = 0;
delete pipeline_convolution_pack4_3x3s1d1_winograd23_transform_input;
delete pipeline_convolution_pack4_3x3s1d1_winograd23_gemm;
delete pipeline_convolution_pack4_3x3s1d1_winograd23_transform_output;
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_input = 0;
pipeline_convolution_pack4_3x3s1d1_winograd23_gemm = 0;
pipeline_convolution_pack4_3x3s1d1_winograd23_transform_output = 0;
delete pipeline_convolution_pack1to4;
pipeline_convolution_pack1to4 = 0;
delete pipeline_convolution_pack4to1;
pipeline_convolution_pack4to1 = 0;
// fc
delete pipeline_innerproduct;
pipeline_innerproduct = 0;
delete pipeline_innerproduct_pack4;
pipeline_innerproduct_pack4 = 0;
delete pipeline_innerproduct_pack1to4;
pipeline_innerproduct_pack1to4 = 0;
delete pipeline_innerproduct_pack4to1;
pipeline_innerproduct_pack4to1 = 0;
return 0;
}
int Convolution_vulkan::upload_model(VkTransfer& cmd, const Option& opt)
{
const int maxk = kernel_w * kernel_h;
int num_input = weight_data_size / maxk / num_output;
// pack1
if (num_input % 4 != 0 && num_output % 4 != 0)
{
cmd.record_upload(weight_data, weight_data_gpu, opt);
}
// pack4
if (num_input % 4 == 0 && num_output % 4 == 0)
{
// src = kw-kh-inch-outch
// dst = 4a-4b-kw-kh-inch/4a-outch/4b
Mat weight_data_pack4;
{
Mat weight_data_r2 = weight_data.reshape(maxk, num_input, num_output);
weight_data_pack4.create(maxk, num_input/4, num_output/4, (size_t)4*16, 16);
for (int q=0; q+3<num_output; q+=4)
{
const Mat k0 = weight_data_r2.channel(q);
const Mat k1 = weight_data_r2.channel(q+1);
const Mat k2 = weight_data_r2.channel(q+2);
const Mat k3 = weight_data_r2.channel(q+3);
Mat g0 = weight_data_pack4.channel(q/4);
for (int p=0; p+3<num_input; p+=4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p+1);
const float* k02 = k0.row(p+2);
const float* k03 = k0.row(p+3);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p+1);
const float* k12 = k1.row(p+2);
const float* k13 = k1.row(p+3);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p+1);
const float* k22 = k2.row(p+2);
const float* k23 = k2.row(p+3);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p+1);
const float* k32 = k3.row(p+2);
const float* k33 = k3.row(p+3);
float* g00 = g0.row(p/4);
for (int k=0; k<maxk; k++)
{
g00[0] = k00[k];
g00[1] = k01[k];
g00[2] = k02[k];
g00[3] = k03[k];
g00[4] = k10[k];
g00[5] = k11[k];
g00[6] = k12[k];
g00[7] = k13[k];
g00[8] = k20[k];
g00[9] = k21[k];
g00[10] = k22[k];
g00[11] = k23[k];
g00[12] = k30[k];
g00[13] = k31[k];
g00[14] = k32[k];
g00[15] = k33[k];
g00 += 16;
}
}
}
}
cmd.record_upload(weight_data_pack4, weight_data_gpu_pack4, opt);
bool is_conv3x3s1d1 = kernel_w == 3 && kernel_h == 3 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1;
if (is_conv3x3s1d1 && num_input >= 64 && num_output >= 64)
{
// winograd63 transform kernel
Mat weight_data_tm;
weight_data_tm.create(8*8, num_input, num_output);
const float ktm[8][3] = {
{ 1.0f, 0.0f, 0.0f},
{-2.0f/9, -2.0f/9, -2.0f/9},
{-2.0f/9, 2.0f/9, -2.0f/9},
{1.0f/90, 1.0f/45, 2.0f/45},
{1.0f/90, -1.0f/45, 2.0f/45},
{1.0f/45, 1.0f/90, 1.0f/180},
{1.0f/45, -1.0f/90, 1.0f/180},
{ 0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for
for (int p = 0; p<num_output; p++)
{
for (int q = 0; q<num_input; q++)
{
const float* kernel0 = (const float*)weight_data + p*num_input * 9 + q * 9;
float* kernel_tm0 = weight_data_tm.channel(p).row(q);
// transform kernel, transposed
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[8][3];
for (int i=0; i<8; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// v
for (int j=0; j<8; j++)
{
float* tmpp = &tmp[j][0];
for (int i=0; i<8; i++)
{
kernel_tm0[j*8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// src = 64-inch-outch
// dst = 4a-4b-64-inch/4a-outch/4b
Mat weight_data_pack4_tm;
{
weight_data_pack4_tm.create(64, num_input/4, num_output/4, (size_t)4*16, 16);
for (int q=0; q+3<num_output; q+=4)
{
const Mat k0 = weight_data_tm.channel(q);
const Mat k1 = weight_data_tm.channel(q+1);
const Mat k2 = weight_data_tm.channel(q+2);
const Mat k3 = weight_data_tm.channel(q+3);
Mat g0 = weight_data_pack4_tm.channel(q/4);
for (int p=0; p+3<num_input; p+=4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p+1);
const float* k02 = k0.row(p+2);
const float* k03 = k0.row(p+3);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p+1);
const float* k12 = k1.row(p+2);
const float* k13 = k1.row(p+3);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p+1);
const float* k22 = k2.row(p+2);
const float* k23 = k2.row(p+3);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p+1);
const float* k32 = k3.row(p+2);
const float* k33 = k3.row(p+3);
float* g00 = g0.row(p/4);
for (int k=0; k<64; k++)
{
g00[0] = k00[k];
g00[1] = k01[k];
g00[2] = k02[k];
g00[3] = k03[k];
g00[4] = k10[k];
g00[5] = k11[k];
g00[6] = k12[k];
g00[7] = k13[k];
g00[8] = k20[k];
g00[9] = k21[k];
g00[10] = k22[k];
g00[11] = k23[k];
g00[12] = k30[k];
g00[13] = k31[k];
g00[14] = k32[k];
g00[15] = k33[k];
g00 += 16;
}
}
}
}
cmd.record_upload(weight_data_pack4_tm, weight_data_gpu_pack4_tm, opt);
}
else if (is_conv3x3s1d1 && num_input >= 16 && num_output >= 16)
{
// winograd23 transform kernel
Mat weight_data_tm;
weight_data_tm.create(4*4, num_input, num_output);
// G
const float ktm[4][3] = {
{ 1.0f, 0.0f, 0.0f},
{ 1.0f/2, 1.0f/2, 1.0f/2},
{ 1.0f/2, -1.0f/2, 1.0f/2},
{ 0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for
for (int p = 0; p<num_output; p++)
{
for (int q = 0; q<num_input; q++)
{
const float* kernel0 = (const float*)weight_data + p*num_input * 9 + q * 9;
float* kernel_tm0 = weight_data_tm.channel(p).row(q);
// transform kernel
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[4][3];
for (int i=0; i<4; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j=0; j<4; j++)
{
float* tmpp = &tmp[j][0];
for (int i=0; i<4; i++)
{
kernel_tm0[j*4 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// src = 16-inch-outch
// dst = 4a-4b-16-inch/4a-outch/4b
Mat weight_data_pack4_tm;
{
weight_data_pack4_tm.create(16, num_input/4, num_output/4, (size_t)4*16, 16);
for (int q=0; q+3<num_output; q+=4)
{
const Mat k0 = weight_data_tm.channel(q);
const Mat k1 = weight_data_tm.channel(q+1);
const Mat k2 = weight_data_tm.channel(q+2);
const Mat k3 = weight_data_tm.channel(q+3);
Mat g0 = weight_data_pack4_tm.channel(q/4);
for (int p=0; p+3<num_input; p+=4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p+1);
const float* k02 = k0.row(p+2);
const float* k03 = k0.row(p+3);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p+1);
const float* k12 = k1.row(p+2);
const float* k13 = k1.row(p+3);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p+1);
const float* k22 = k2.row(p+2);
const float* k23 = k2.row(p+3);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p+1);
const float* k32 = k3.row(p+2);
const float* k33 = k3.row(p+3);
float* g00 = g0.row(p/4);
for (int k=0; k<16; k++)
{
g00[0] = k00[k];
g00[1] = k01[k];
g00[2] = k02[k];
g00[3] = k03[k];
g00[4] = k10[k];
g00[5] = k11[k];
g00[6] = k12[k];
g00[7] = k13[k];
g00[8] = k20[k];
g00[9] = k21[k];
g00[10] = k22[k];
g00[11] = k23[k];
g00[12] = k30[k];
g00[13] = k31[k];
g00[14] = k32[k];
g00[15] = k33[k];
g00 += 16;
}
}
}
}
cmd.record_upload(weight_data_pack4_tm, weight_data_gpu_pack4_tm, opt);
}
}
// pack1to4
if (num_input % 4 != 0 && num_output % 4 == 0)
{
// src = kw-kh-inch-outch
// dst = 4b-kw-kh-inch-outch/4b
Mat weight_data_pack1to4;
{
Mat weight_data_r2 = weight_data.reshape(maxk, num_input, num_output);
weight_data_pack1to4.create(maxk, num_input, num_output/4, (size_t)4*4, 4);
for (int q=0; q+3<num_output; q+=4)
{
const Mat k0 = weight_data_r2.channel(q);
const Mat k1 = weight_data_r2.channel(q+1);
const Mat k2 = weight_data_r2.channel(q+2);
const Mat k3 = weight_data_r2.channel(q+3);
Mat g0 = weight_data_pack1to4.channel(q/4);
for (int p=0; p<num_input; p++)
{
const float* k00 = k0.row(p);
const float* k10 = k1.row(p);
const float* k20 = k2.row(p);
const float* k30 = k3.row(p);
float* g00 = g0.row(p);
for (int k=0; k<maxk; k++)
{
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00 += 4;
}
}
}
}
cmd.record_upload(weight_data_pack1to4, weight_data_gpu_pack1to4, opt);
}
// pack4to1
if (num_input % 4 == 0 && num_output % 4 != 0)
{
// src = kw-kh-inch-outch
// dst = 4a-kw-kh-inch/4a-outch
Mat weight_data_pack4to1;
{
Mat weight_data_r2 = weight_data.reshape(maxk, num_input, num_output);
weight_data_pack4to1.create(maxk, num_input/4, num_output, (size_t)4*4, 4);
for (int q=0; q<num_output; q++)
{
const Mat k0 = weight_data_r2.channel(q);
Mat g0 = weight_data_pack4to1.channel(q);
for (int p=0; p+3<num_input; p+=4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p+1);
const float* k02 = k0.row(p+2);
const float* k03 = k0.row(p+3);
float* g00 = g0.row(p/4);
for (int k=0; k<maxk; k++)
{
g00[0] = k00[k];
g00[1] = k01[k];
g00[2] = k02[k];
g00[3] = k03[k];
g00 += 4;
}
}
}
}
cmd.record_upload(weight_data_pack4to1, weight_data_gpu_pack4to1, opt);
}
if (bias_term)
{
if (num_output % 4 != 0)
{
cmd.record_upload(bias_data, bias_data_gpu, opt);
}
if (num_output % 4 == 0)
{
Mat bias_data_pack4;
convert_packing(bias_data, bias_data_pack4, 4);
cmd.record_upload(bias_data_pack4, bias_data_gpu_pack4, opt);
}
}
return 0;
}
int Convolution_vulkan::forward(const VkMat& bottom_blob, VkMat& top_blob, VkCompute& cmd, const Option& opt) const
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
// flattened blob, implement as InnerProduct
if (bottom_blob.dims == 1 && kernel_w == 1 && kernel_h == 1)
{
int num_input = weight_data_size / num_output;
if (bottom_blob.w * bottom_blob.elempack == num_input)
{
int out_elempack = num_output % 4 == 0 ? 4 : 1;
size_t out_elemsize = elemsize / elempack * out_elempack;
if (opt.use_fp16_packed && !opt.use_fp16_storage)
{
if (out_elempack == 4) out_elemsize = 4*2u;
if (out_elempack == 1) out_elemsize = 4u;
}
top_blob.create(num_output / out_elempack, out_elemsize, out_elempack, opt.blob_vkallocator, opt.staging_vkallocator);
if (top_blob.empty())
return -100;
std::vector<VkMat> bindings(4);
bindings[0] = bottom_blob;
bindings[1] = top_blob;
if (elempack == 1 && out_elempack == 1)
{
bindings[2] = weight_data_gpu;
bindings[3] = bias_term ? bias_data_gpu : bindings[2];// TODO use dummy buffer
}
else if (elempack == 4 && out_elempack == 4)
{
bindings[2] = weight_data_gpu_pack4;
bindings[3] = bias_term ? bias_data_gpu_pack4 : bindings[2];// TODO use dummy buffer
}
else if (elempack == 1 && out_elempack == 4)
{
bindings[2] = weight_data_gpu_pack1to4;
bindings[3] = bias_term ? bias_data_gpu_pack4 : bindings[2];// TODO use dummy buffer
}
else if (elempack == 4 && out_elempack == 1)
{
bindings[2] = weight_data_gpu_pack4to1;
bindings[3] = bias_term ? bias_data_gpu : bindings[2];// TODO use dummy buffer
}
std::vector<vk_constant_type> constants(10);
constants[0].i = bottom_blob.dims;
constants[1].i = bottom_blob.w;
constants[2].i = bottom_blob.h;
constants[3].i = bottom_blob.c;
constants[4].i = bottom_blob.cstep;
constants[5].i = top_blob.dims;
constants[6].i = top_blob.w;
constants[7].i = top_blob.h;
constants[8].i = top_blob.c;
constants[9].i = top_blob.cstep;
const Pipeline* pipeline = 0;
if (elempack == 1 && out_elempack == 1)
{
pipeline = pipeline_innerproduct;
}
else if (elempack == 4 && out_elempack == 4)
{
pipeline = pipeline_innerproduct_pack4;
}
else if (elempack == 1 && out_elempack == 4)
{
pipeline = pipeline_innerproduct_pack1to4;
}
else if (elempack == 4 && out_elempack == 1)
{
pipeline = pipeline_innerproduct_pack4to1;
}
cmd.record_pipeline(pipeline, bindings, constants, top_blob);
return 0;
}
}
const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1;
VkMat bottom_blob_bordered = bottom_blob;
if (pad_w > 0 || pad_h > 0)
{
ncnn::Option opt_pad = opt;
opt_pad.blob_vkallocator = opt.workspace_vkallocator;
padding->forward(bottom_blob, bottom_blob_bordered, cmd, opt_pad);
w = bottom_blob_bordered.w;
h = bottom_blob_bordered.h;
}
else if (pad_w == -233 && pad_h == -233)
{
int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w;
int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h;
if (wpad > 0 || hpad > 0)
{
ncnn::Option opt_pad = opt;
opt_pad.blob_vkallocator = opt.workspace_vkallocator;
VkMat padding_param_blob(4, (size_t)4u, 1, opt.staging_vkallocator, opt.staging_vkallocator);
padding_param_blob.prepare_staging_buffer();
int* padding_params = padding_param_blob.mapped();
padding_params[0] = hpad / 2;
padding_params[1] = hpad - hpad / 2;
padding_params[2] = wpad / 2;
padding_params[3] = wpad - wpad / 2;
std::vector<VkMat> padding_inputs(2);
padding_inputs[0] = bottom_blob;
padding_inputs[1] = padding_param_blob;
std::vector<VkMat> padding_outputs(1);
padding->forward(padding_inputs, padding_outputs, cmd, opt_pad);
bottom_blob_bordered = padding_outputs[0];
}
w = bottom_blob_bordered.w;
h = bottom_blob_bordered.h;
}
int outw = (w - kernel_extent_w) / stride_w + 1;
int outh = (h - kernel_extent_h) / stride_h + 1;
int out_elempack = num_output % 4 == 0 ? 4 : 1;
size_t out_elemsize = elemsize / elempack * out_elempack;
if (opt.use_fp16_packed && !opt.use_fp16_storage)
{
if (out_elempack == 4) out_elemsize = 4*2u;
if (out_elempack == 1) out_elemsize = 4u;
}
bool is_conv3x3s1d1 = kernel_w == 3 && kernel_h == 3 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1;
if (elempack == 4 && out_elempack == 4 && is_conv3x3s1d1 && channels * elempack >= 64 && num_output >= 64)
{
// winograd63
int outw_bordered = (outw + 5) / 6 * 6;
int outh_bordered = (outh + 5) / 6 * 6;
int w_bordered = outw_bordered + 2;
int h_bordered = outh_bordered + 2;
int block_x = outw_bordered / 6;
int block_y = outh_bordered / 6;
// pad to 6n+2
{
ncnn::Option opt_pad = opt;
opt_pad.blob_vkallocator = opt.workspace_vkallocator;
VkMat padding_param_blob(4, (size_t)4u, 1, opt.staging_vkallocator, opt.staging_vkallocator);
padding_param_blob.prepare_staging_buffer();
int* padding_params = padding_param_blob.mapped();
padding_params[0] = 0;
padding_params[1] = h_bordered - bottom_blob_bordered.h;
padding_params[2] = 0;
padding_params[3] = w_bordered - bottom_blob_bordered.w;
std::vector<VkMat> padding_inputs(2);
padding_inputs[0] = bottom_blob_bordered;
padding_inputs[1] = padding_param_blob;
std::vector<VkMat> padding_outputs(1);
winograd_padding->forward(padding_inputs, padding_outputs, cmd, opt_pad);
bottom_blob_bordered = padding_outputs[0];
}
// transform input
VkMat bottom_tm_blob;
{
bottom_tm_blob.create(64, block_x * block_y, channels, elemsize, elempack, opt.workspace_vkallocator, opt.staging_vkallocator);
if (bottom_tm_blob.empty())
return -100;
std::vector<VkMat> bindings(2);
bindings[0] = bottom_blob_bordered;
bindings[1] = bottom_tm_blob;
std::vector<vk_constant_type> constants(7);
constants[0].i = bottom_blob_bordered.w;
constants[1].i = bottom_blob_bordered.h;
constants[2].i = bottom_blob_bordered.c;
constants[3].i = bottom_blob_bordered.cstep;
constants[4].i = bottom_tm_blob.cstep;
constants[5].i = block_x;
constants[6].i = block_y;
VkMat dispatcher;
dispatcher.w = block_x;
dispatcher.h = block_y;
dispatcher.c = bottom_tm_blob.c;
cmd.record_pipeline(pipeline_convolution_pack4_3x3s1d1_winograd63_transform_input, bindings, constants, dispatcher);
}
// gemm
VkMat top_tm_blob;
{
top_tm_blob.create(64, block_x * block_y, num_output / out_elempack, elemsize, out_elempack, opt.workspace_vkallocator, opt.staging_vkallocator);
if (top_tm_blob.empty())
return -100;
std::vector<VkMat> bindings(3);
bindings[0] = bottom_tm_blob;
bindings[1] = top_tm_blob;
bindings[2] = weight_data_gpu_pack4_tm;
std::vector<vk_constant_type> constants(6);
constants[0].i = bottom_tm_blob.c;
constants[1].i = bottom_tm_blob.cstep;
constants[2].i = (top_tm_blob.h + 3) / 4;
constants[3].i = top_tm_blob.h;
constants[4].i = top_tm_blob.c;
constants[5].i = top_tm_blob.cstep;
VkMat dispatcher;
dispatcher.w = top_tm_blob.w;
dispatcher.h = (top_tm_blob.h + 3) / 4;
dispatcher.c = top_tm_blob.c;
cmd.record_pipeline(pipeline_convolution_pack4_3x3s1d1_winograd63_gemm, bindings, constants, dispatcher);
}
// transform output
VkMat top_blob_bordered;
{
top_blob_bordered.create(outw_bordered, outh_bordered, num_output / out_elempack, elemsize, out_elempack, opt.blob_vkallocator, opt.staging_vkallocator);
if (top_blob_bordered.empty())
return -100;
std::vector<VkMat> bindings(3);
bindings[0] = top_tm_blob;
bindings[1] = top_blob_bordered;
bindings[2] = bias_term ? bias_data_gpu_pack4 : bindings[1];
std::vector<vk_constant_type> constants(7);
constants[0].i = top_tm_blob.c;
constants[1].i = top_tm_blob.cstep;
constants[2].i = block_x;
constants[3].i = block_y;
constants[4].i = top_blob_bordered.w;
constants[5].i = top_blob_bordered.h;
constants[6].i = top_blob_bordered.cstep;
VkMat dispatcher;
dispatcher.w = block_x;
dispatcher.h = block_y;
dispatcher.c = top_blob_bordered.c;
cmd.record_pipeline(pipeline_convolution_pack4_3x3s1d1_winograd63_transform_output, bindings, constants, dispatcher);
}
// crop top_blob
{
VkMat crop_param_blob(6, (size_t)4u, 1, opt.staging_vkallocator, opt.staging_vkallocator);
crop_param_blob.prepare_staging_buffer();
int* crop_params = crop_param_blob.mapped();
crop_params[0] = 0;
crop_params[1] = 0;
crop_params[2] = 0;
crop_params[3] = outw;
crop_params[4] = outh;
crop_params[5] = num_output;
std::vector<VkMat> crop_inputs(2);
crop_inputs[0] = top_blob_bordered;
crop_inputs[1] = crop_param_blob;
std::vector<VkMat> crop_outputs(1);
winograd_crop->forward(crop_inputs, crop_outputs, cmd, opt);
top_blob = crop_outputs[0];
}
return 0;
}
else if (elempack == 4 && out_elempack == 4 && is_conv3x3s1d1 && channels * elempack >= 16 && num_output >= 16)
{
// winograd23
int outw_bordered = (outw + 1) / 2 * 2;
int outh_bordered = (outh + 1) / 2 * 2;
int w_bordered = outw_bordered + 2;
int h_bordered = outh_bordered + 2;
int block_x = outw_bordered / 2;
int block_y = outh_bordered / 2;
// pad to 2n+2
{
ncnn::Option opt_pad = opt;
opt_pad.blob_vkallocator = opt.workspace_vkallocator;
VkMat padding_param_blob(4, (size_t)4u, 1, opt.staging_vkallocator, opt.staging_vkallocator);
padding_param_blob.prepare_staging_buffer();
int* padding_params = padding_param_blob.mapped();
padding_params[0] = 0;
padding_params[1] = h_bordered - bottom_blob_bordered.h;
padding_params[2] = 0;
padding_params[3] = w_bordered - bottom_blob_bordered.w;
std::vector<VkMat> padding_inputs(2);
padding_inputs[0] = bottom_blob_bordered;
padding_inputs[1] = padding_param_blob;
std::vector<VkMat> padding_outputs(1);
winograd_padding->forward(padding_inputs, padding_outputs, cmd, opt_pad);
bottom_blob_bordered = padding_outputs[0];
}
// transform input
VkMat bottom_tm_blob;
{
bottom_tm_blob.create(16, block_x * block_y, channels, elemsize, elempack, opt.workspace_vkallocator, opt.staging_vkallocator);
if (bottom_tm_blob.empty())
return -100;
std::vector<VkMat> bindings(2);
bindings[0] = bottom_blob_bordered;
bindings[1] = bottom_tm_blob;
std::vector<vk_constant_type> constants(7);
constants[0].i = bottom_blob_bordered.w;
constants[1].i = bottom_blob_bordered.h;
constants[2].i = bottom_blob_bordered.c;
constants[3].i = bottom_blob_bordered.cstep;
constants[4].i = bottom_tm_blob.cstep;
constants[5].i = block_x;
constants[6].i = block_y;
VkMat dispatcher;
dispatcher.w = block_x;
dispatcher.h = block_y;
dispatcher.c = bottom_tm_blob.c;
cmd.record_pipeline(pipeline_convolution_pack4_3x3s1d1_winograd23_transform_input, bindings, constants, dispatcher);
}
// gemm
VkMat top_tm_blob;
{
top_tm_blob.create(16, block_x * block_y, num_output / out_elempack, elemsize, out_elempack, opt.workspace_vkallocator, opt.staging_vkallocator);
if (top_tm_blob.empty())
return -100;
std::vector<VkMat> bindings(3);
bindings[0] = bottom_tm_blob;
bindings[1] = top_tm_blob;
bindings[2] = weight_data_gpu_pack4_tm;
std::vector<vk_constant_type> constants(6);
constants[0].i = bottom_tm_blob.c;
constants[1].i = bottom_tm_blob.cstep;
constants[2].i = (top_tm_blob.h + 3) / 4;
constants[3].i = top_tm_blob.h;
constants[4].i = top_tm_blob.c;
constants[5].i = top_tm_blob.cstep;
VkMat dispatcher;
dispatcher.w = top_tm_blob.w;
dispatcher.h = (top_tm_blob.h + 3) / 4;
dispatcher.c = top_tm_blob.c;
cmd.record_pipeline(pipeline_convolution_pack4_3x3s1d1_winograd23_gemm, bindings, constants, dispatcher);
}
// transform output
VkMat top_blob_bordered;
{
top_blob_bordered.create(outw_bordered, outh_bordered, num_output / out_elempack, elemsize, out_elempack, opt.blob_vkallocator, opt.staging_vkallocator);
if (top_blob_bordered.empty())
return -100;
std::vector<VkMat> bindings(3);
bindings[0] = top_tm_blob;
bindings[1] = top_blob_bordered;
bindings[2] = bias_term ? bias_data_gpu_pack4 : bindings[1];
std::vector<vk_constant_type> constants(7);
constants[0].i = top_tm_blob.c;
constants[1].i = top_tm_blob.cstep;
constants[2].i = block_x;
constants[3].i = block_y;
constants[4].i = top_blob_bordered.w;
constants[5].i = top_blob_bordered.h;
constants[6].i = top_blob_bordered.cstep;
VkMat dispatcher;
dispatcher.w = block_x;
dispatcher.h = block_y;
dispatcher.c = top_blob_bordered.c;
cmd.record_pipeline(pipeline_convolution_pack4_3x3s1d1_winograd23_transform_output, bindings, constants, dispatcher);
}
// crop top_blob
{
VkMat crop_param_blob(6, (size_t)4u, 1, opt.staging_vkallocator, opt.staging_vkallocator);
crop_param_blob.prepare_staging_buffer();
int* crop_params = crop_param_blob.mapped();
crop_params[0] = 0;
crop_params[1] = 0;
crop_params[2] = 0;
crop_params[3] = outw;
crop_params[4] = outh;
crop_params[5] = num_output;
std::vector<VkMat> crop_inputs(2);
crop_inputs[0] = top_blob_bordered;
crop_inputs[1] = crop_param_blob;
std::vector<VkMat> crop_outputs(1);
winograd_crop->forward(crop_inputs, crop_outputs, cmd, opt);
top_blob = crop_outputs[0];
}
return 0;
}
top_blob.create(outw, outh, num_output / out_elempack, out_elemsize, out_elempack, opt.blob_vkallocator, opt.staging_vkallocator);
if (top_blob.empty())
return -100;
std::vector<VkMat> bindings(4);
bindings[0] = bottom_blob_bordered;
bindings[1] = top_blob;
if (elempack == 1 && out_elempack == 1)
{
bindings[2] = weight_data_gpu;
bindings[3] = bias_term ? bias_data_gpu : bindings[2];// TODO use dummy buffer
}
else if (elempack == 4 && out_elempack == 4)
{
bindings[2] = weight_data_gpu_pack4;
bindings[3] = bias_term ? bias_data_gpu_pack4 : bindings[2];// TODO use dummy buffer
}
else if (elempack == 1 && out_elempack == 4)
{
bindings[2] = weight_data_gpu_pack1to4;
bindings[3] = bias_term ? bias_data_gpu_pack4 : bindings[2];// TODO use dummy buffer
}
else if (elempack == 4 && out_elempack == 1)
{
bindings[2] = weight_data_gpu_pack4to1;
bindings[3] = bias_term ? bias_data_gpu : bindings[2];// TODO use dummy buffer
}
// record
if (elempack == 1 && out_elempack == 1 && kernel_w == 1 && kernel_h == 1 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1)
{
std::vector<vk_constant_type> constants(8);
constants[0].i = bottom_blob_bordered.dims;
constants[1].i = bottom_blob_bordered.cstep / 4;
constants[2].i = bottom_blob_bordered.c;
constants[3].i = bottom_blob_bordered.cstep / 4;
constants[4].i = top_blob.dims;
constants[5].i = top_blob.cstep / 4;
constants[6].i = top_blob.c;
constants[7].i = top_blob.cstep / 4;
VkMat dispatcher;
dispatcher.w = top_blob.cstep / 4;
dispatcher.h = 1;
dispatcher.c = top_blob.c;
cmd.record_pipeline(pipeline_convolution_1x1s1d1, bindings, constants, dispatcher);
}
else if (elempack == 4 && out_elempack == 4 && kernel_w == 1 && kernel_h == 1 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1)
{
std::vector<vk_constant_type> constants(8);
constants[0].i = bottom_blob_bordered.dims;
constants[1].i = (bottom_blob_bordered.cstep + 3) / 4;
constants[2].i = bottom_blob_bordered.c;
constants[3].i = bottom_blob_bordered.cstep;
constants[4].i = top_blob.dims;
constants[5].i = (top_blob.cstep + 3) / 4;
constants[6].i = top_blob.c;
constants[7].i = top_blob.cstep;
VkMat dispatcher;
dispatcher.w = (top_blob.cstep + 3) / 4;
dispatcher.h = 1;
dispatcher.c = top_blob.c;
cmd.record_pipeline(pipeline_convolution_pack4_1x1s1d1, bindings, constants, dispatcher);
}
else if (elempack == 4 && out_elempack == 4 && kernel_w == 3 && kernel_h == 3 && stride_w == 1 && stride_h == 1 && dilation_w == 1 && dilation_h == 1)
{
std::vector<vk_constant_type> constants(10);
constants[0].i = bottom_blob_bordered.dims;
constants[1].i = bottom_blob_bordered.w;
constants[2].i = bottom_blob_bordered.h;
constants[3].i = bottom_blob_bordered.c;
constants[4].i = bottom_blob_bordered.cstep;
constants[5].i = top_blob.dims;
constants[6].i = top_blob.w;
constants[7].i = top_blob.h;
constants[8].i = top_blob.c;
constants[9].i = top_blob.cstep;
cmd.record_pipeline(pipeline_convolution_pack4_3x3s1d1_lds_8_8_2, bindings, constants, top_blob);
}
else
{
std::vector<vk_constant_type> constants(10);
constants[0].i = bottom_blob_bordered.dims;
constants[1].i = bottom_blob_bordered.w;
constants[2].i = bottom_blob_bordered.h;
constants[3].i = bottom_blob_bordered.c;
constants[4].i = bottom_blob_bordered.cstep;
constants[5].i = top_blob.dims;
constants[6].i = top_blob.w;
constants[7].i = top_blob.h;
constants[8].i = top_blob.c;
constants[9].i = top_blob.cstep;
const Pipeline* pipeline = 0;
if (elempack == 1 && out_elempack == 1)
{
pipeline = pipeline_convolution;
}
else if (elempack == 4 && out_elempack == 4)
{
pipeline = pipeline_convolution_pack4;
}
else if (elempack == 1 && out_elempack == 4)
{
pipeline = pipeline_convolution_pack1to4;
}
else if (elempack == 4 && out_elempack == 1)
{
pipeline = pipeline_convolution_pack4to1;
}
cmd.record_pipeline(pipeline, bindings, constants, top_blob);
}
return 0;
}
} // namespace ncnn
|
#include "stdafx.h"
/*
// init.cpp
// Add these headers before the header with the using namespace System
// directive, or add them in a .cpp file that does not have a
// using namespace System directive.
#include <windows.h>
#include <_vcclrit.h>
// Call this function before you call anything in this DLL.
// It is safe to call from multiple threads, is not reference
// counted, and is reentrancy safe.
extern "C" __declspec(dllexport) void __stdcall DllEnsureInit(void)
{
// Do nothing else here. If you need extra initialization steps,
// create static objects with constructors that perform
// initialization.
__crt_dll_initialize();
// Do nothing else here.
}
// Call this function after this whole process is totally done
// calling anything in this DLL. It is safe to call from multiple
// threads, is not reference counted, and is reentrancy safe.
// First call will terminate.
extern "C" __declspec(dllexport) void __stdcall DllForceTerm(void)
{
// Do nothing else here. If you need extra terminate steps,
// use atexit.
__crt_dll_terminate();
// Do nothing else here.
}
*/
|
#include <memory>
#include <string>
#include <vector>
#include "Options.h"
Option::Option(std::unique_ptr<const std::string>&& key_,
std::unique_ptr<const std::string>&& value_) noexcept : _key(std::move(key_)),
_value(std::move(value_))
{
// Empty
}
std::unique_ptr<const Option> Option::Create(const char arg_[]) noexcept
{
return Create(std::string(arg_));
}
std::unique_ptr<const Option> Option::Create(const std::string&& arg_) noexcept
{
auto result{std::unique_ptr<const Option>{nullptr}};
if (!arg_.empty())
{
auto key{new std::string{}};
auto value{new std::string{}};
auto valid{true};
std::size_t k{0};
valid = (arg_[k++] == DELIMITER);
if (k < arg_.size() && valid)
{
if (arg_[k] == DELIMITER)
{
++k;
}
else
{
valid = (arg_.size() == 2);
}
while (k < arg_.size() && valid)
{
valid = (arg_[k] != DELIMITER);
if (valid)
{
*key += arg_[k++];
}
}
if (valid)
{
result = std::unique_ptr<const Option>(new Option(std::unique_ptr<const std::string>(key),
std::unique_ptr<const std::string>(value)));
}
}
}
return result;
}
const std::string& Option::Key() const noexcept
{
return *_key;
}
const std::string& Option::Value() const noexcept
{
return *_value;
}
bool Option::Valid() const noexcept
{
return !(_key->empty());
}
void OptionCollection::Parse(const int argc_, const char** argv_)
{
std::vector<std::string> args{};
for (std::size_t k{1}; k < static_cast<std::size_t>(argc_); ++k)
{
args.push_back(std::string(argv_[k]));
}
Parse(std::move(args));
}
void OptionCollection::Parse(const std::vector<std::string>&& args_)
{
bool valid = true;
for (auto&& k{args_.cbegin()}; k != args_.cend() && valid; ++k)
{
auto o{Option::Create(std::move(const_cast<std::string&>(*k)))};
if (o != nullptr && o->Valid())
{
_options.push_back(std::move(o));
}
else
{
valid = false;
}
}
if (!valid)
{
_options.clear();
}
}
std::size_t OptionCollection::Count() const noexcept
{
return _options.size();
}
const Option& OptionCollection::operator [](const std::size_t i_) const
{
return *(_options[i_]);
}
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich 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 "CJavaDebug.h"
#include "ModelBase/src/model/TreeManager.h"
#include "../debugger/JavaDebugger.h"
namespace OODebug {
CJavaDebug::CJavaDebug() : CommandWithFlags{"debug", {}, false}
{}
Interaction::CommandResult* CJavaDebug::executeNamed(Visualization::Item* source, Visualization::Item*,
const std::unique_ptr<Visualization::Cursor>&, const QString&, const QStringList&)
{
while (source && !source->node()) source = source->parent();
Q_ASSERT(source);
auto manager = source->node()->manager();
Q_ASSERT(manager);
auto result = JavaDebugger::instance().debugTree(manager, "exported/" + manager->root()->symbolName());
Q_ASSERT(result);
return result;
}
bool CJavaDebug::canInterpret(Visualization::Item* source, Visualization::Item* target,
const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& cursor)
{
if (CommandWithFlags::canInterpret(source, target, commandTokens, cursor))
{
// Check if there is a tree manager
while (source && !source->node()) source = source->parent();
return source && source->node()->manager();
}
return false;
}
}
|
#include "CesiumJsonReader/ExtensionsJsonHandler.h"
#include "CesiumJsonReader/ExtensionReaderContext.h"
using namespace CesiumJsonReader;
using namespace CesiumUtility;
void ExtensionsJsonHandler::reset(
IJsonHandler* pParent,
ExtensibleObject* pObject,
const std::string& objectType) {
ObjectJsonHandler::reset(pParent);
this->_pObject = pObject;
if (this->_objectType != objectType) {
this->_objectType = objectType;
}
}
IJsonHandler*
ExtensionsJsonHandler::readObjectKey(const std::string_view& str) {
this->_currentExtensionHandler =
this->_context.createExtensionHandler(str, this->_objectType);
if (this->_currentExtensionHandler) {
this->_currentExtensionHandler->reset(this, *this->_pObject, str);
return this->_currentExtensionHandler.get();
} else {
return this->ignoreAndContinue();
}
}
|
#include <chrono>
#include <cascara/cascara.hpp>
using namespace cascara;
#include "../system_cmd.hpp"
#ifdef __APPLE_CC__
#define EXEC_TRUE "/usr/bin/true"
#define EXEC_FALSE "/usr/bin/false"
#define EXEC_ECHO "/bin/echo"
#define EXEC_SLEEP "/bin/sleep"
#define EXEC_GREP "/usr/bin/grep"
#else
#define EXEC_TRUE "/bin/true"
#define EXEC_FALSE "/bin/false"
#define EXEC_ECHO "/bin/echo"
#define EXEC_SLEEP "/bin/sleep"
#define EXEC_GREP "/bin/grep"
#endif
INITIALIZE_EASYLOGGINGPP
int main() {
describe("SystemCmd", []() {
// it("simple echo", []() {
// assert.equal(0, SystemCmd("/bin/sleep").arg("60").run().exitCode);
// });
it("not launched", []() {
assert.isFalse(SystemCmd("WTF").run().ok);
});
it("syncron sleep", []() {
auto start = std::chrono::high_resolution_clock::now(); //measure time starting here
assert.isTrue(SystemCmd(EXEC_SLEEP).arg("1").run().ok, "sleep should be ok");
auto end = std::chrono::high_resolution_clock::now(); //end measurement here
auto elapsed = end - start;
assert.isTrue(std::chrono::microseconds{1000000} <= elapsed, "time is not ok");
});
it("launched", []() {
assert.isTrue(SystemCmd(EXEC_TRUE).run().ok);
});
it("return ok", []() {
assert.equal(0, SystemCmd(EXEC_TRUE).run().exitCode);
});
it("return false", []() {
assert.equal(1, SystemCmd(EXEC_FALSE).run().exitCode);
});
it("stdout empty", []() {
assert.isTrue(SystemCmd(EXEC_TRUE).run().getSout().str().empty());
});
it("stderr empty", []() {
assert.isTrue(SystemCmd(EXEC_TRUE).run().getSerr().str().empty());
});
it("stdout hello world", []() {
assert.equal(SystemCmd(EXEC_ECHO).arg("hello world").run().getSout().str(), "hello world\n");
assert.equal(SystemCmd(EXEC_ECHO).arg("hello world").run().getSerr().str(), "");
});
it("stderr output", []() {
assert.isTrue(SystemCmd(EXEC_GREP).arg("---Fehler").run().getSout().str().empty());
assert.isFalse(SystemCmd(EXEC_GREP).arg("---Fehler").run().getSerr().str().empty());
});
});
exit();
}
|
/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Reporter Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include <ironbee/predicate/reporter.hpp>
#include <boost/foreach.hpp>
using namespace std;
namespace IronBee {
namespace Predicate {
Reporter::Reporter(bool use_prefix) :
m_num_errors(0),
m_num_warnings(0),
m_use_prefix(use_prefix)
{
// nop
}
void Reporter::error(const string& message)
{
m_messages.push_back("ERROR: " + message);
++m_num_errors;
}
void Reporter::warn(const string& message)
{
m_messages.push_back("WARNING: " + message);
++m_num_warnings;
}
namespace {
class reporter_helper
{
public:
reporter_helper(Reporter& parent, bool use_prefix) :
m_parent(parent),
m_use_prefix(use_prefix)
{
/*nop*/
}
void operator()(
bool is_error,
const string& message,
const node_cp& node
) const
{
if (m_use_prefix) {
if (is_error) {
m_parent.error(node->to_s() + ":" + message);
}
else {
m_parent.warn(node->to_s() + ":" + message);
}
}
else {
if (is_error) {
m_parent.error(message);
}
else {
m_parent.warn(message);
}
}
}
private:
Reporter& m_parent;
bool m_use_prefix;
};
}
Reporter::operator reporter_t()
{
return reporter_helper(*this, m_use_prefix);
}
void Reporter::write_report(ostream& out) const
{
BOOST_FOREACH(const string& msg, m_messages) {
out << msg << endl;
}
}
NodeReporter::NodeReporter(
reporter_t reporter,
const node_cp& node
):
m_reporter(reporter),
m_node(node)
{
// nop
}
void NodeReporter::error(const string& msg)
{
m_reporter(true, msg, m_node);
}
void NodeReporter::warn(const string& msg)
{
m_reporter(false, msg, m_node);
}
} // Predicate
} // IronBee
|
// Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/scheduler/scheduler_state_machine.h"
#include "base/debug/trace_event.h"
#include "cc/scheduler/scheduler.h"
#include "cc/test/begin_frame_args_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#define EXPECT_ACTION_UPDATE_STATE(action) \
EXPECT_EQ(action, state.NextAction()) << state.AsValue()->ToString(); \
if (action == SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE || \
action == SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED) { \
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE, \
state.begin_impl_frame_state()) \
<< state.AsValue()->ToString(); \
} \
state.UpdateState(action); \
if (action == SchedulerStateMachine::ACTION_NONE) { \
if (state.begin_impl_frame_state() == \
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_BEGIN_FRAME_STARTING) \
state.OnBeginImplFrameDeadlinePending(); \
if (state.begin_impl_frame_state() == \
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE) \
state.OnBeginImplFrameIdle(); \
}
namespace cc {
namespace {
const SchedulerStateMachine::BeginImplFrameState all_begin_impl_frame_states[] =
{SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE,
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_BEGIN_FRAME_STARTING,
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME,
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE, };
const SchedulerStateMachine::CommitState all_commit_states[] = {
SchedulerStateMachine::COMMIT_STATE_IDLE,
SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_STARTED,
SchedulerStateMachine::COMMIT_STATE_READY_TO_COMMIT,
SchedulerStateMachine::COMMIT_STATE_WAITING_FOR_ACTIVATION,
SchedulerStateMachine::COMMIT_STATE_WAITING_FOR_FIRST_DRAW};
// Exposes the protected state fields of the SchedulerStateMachine for testing
class StateMachine : public SchedulerStateMachine {
public:
explicit StateMachine(const SchedulerSettings& scheduler_settings)
: SchedulerStateMachine(scheduler_settings) {}
void CreateAndInitializeOutputSurfaceWithActivatedCommit() {
DidCreateAndInitializeOutputSurface();
output_surface_state_ = OUTPUT_SURFACE_ACTIVE;
}
void SetCommitState(CommitState cs) { commit_state_ = cs; }
CommitState CommitState() const { return commit_state_; }
ForcedRedrawOnTimeoutState ForcedRedrawState() const {
return forced_redraw_state_;
}
void SetBeginImplFrameState(BeginImplFrameState bifs) {
begin_impl_frame_state_ = bifs;
}
BeginImplFrameState begin_impl_frame_state() const {
return begin_impl_frame_state_;
}
OutputSurfaceState output_surface_state() const {
return output_surface_state_;
}
bool NeedsCommit() const { return needs_commit_; }
void SetNeedsRedraw(bool b) { needs_redraw_ = b; }
void SetNeedsForcedRedrawForTimeout(bool b) {
forced_redraw_state_ = FORCED_REDRAW_STATE_WAITING_FOR_COMMIT;
active_tree_needs_first_draw_ = true;
}
bool NeedsForcedRedrawForTimeout() const {
return forced_redraw_state_ != FORCED_REDRAW_STATE_IDLE;
}
void SetActiveTreeNeedsFirstDraw(bool needs_first_draw) {
active_tree_needs_first_draw_ = needs_first_draw;
}
bool CanDraw() const { return can_draw_; }
bool Visible() const { return visible_; }
bool PendingActivationsShouldBeForced() const {
return SchedulerStateMachine::PendingActivationsShouldBeForced();
}
void SetHasPendingTree(bool has_pending_tree) {
has_pending_tree_ = has_pending_tree;
}
};
TEST(SchedulerStateMachineTest, TestNextActionBeginsMainFrameIfNeeded) {
SchedulerSettings default_scheduler_settings;
// If no commit needed, do nothing.
{
StateMachine state(default_scheduler_settings);
state.SetCanStart();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION)
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetCommitState(SchedulerStateMachine::COMMIT_STATE_IDLE);
state.SetNeedsRedraw(false);
state.SetVisible(true);
EXPECT_FALSE(state.BeginFrameNeeded());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_FALSE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
}
// If commit requested but can_start is still false, do nothing.
{
StateMachine state(default_scheduler_settings);
state.SetCommitState(SchedulerStateMachine::COMMIT_STATE_IDLE);
state.SetNeedsRedraw(false);
state.SetVisible(true);
state.SetNeedsCommit();
EXPECT_FALSE(state.BeginFrameNeeded());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_FALSE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
}
// If commit requested, begin a main frame.
{
StateMachine state(default_scheduler_settings);
state.SetCommitState(SchedulerStateMachine::COMMIT_STATE_IDLE);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetNeedsRedraw(false);
state.SetVisible(true);
state.SetNeedsCommit();
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
// Begin the frame, make sure needs_commit and commit_state update correctly.
{
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.UpdateState(SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
}
}
// Explicitly test main_frame_before_draw_enabled = false
TEST(SchedulerStateMachineTest, MainFrameBeforeDrawDisabled) {
SchedulerSettings scheduler_settings;
scheduler_settings.impl_side_painting = true;
scheduler_settings.main_frame_before_draw_enabled = false;
StateMachine state(scheduler_settings);
state.SetCommitState(SchedulerStateMachine::COMMIT_STATE_IDLE);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetNeedsRedraw(false);
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsCommit();
EXPECT_TRUE(state.BeginFrameNeeded());
// Commit to the pending tree.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(),
SchedulerStateMachine::COMMIT_STATE_WAITING_FOR_FIRST_DRAW);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(),
SchedulerStateMachine::COMMIT_STATE_WAITING_FOR_FIRST_DRAW);
// Verify that the next commit doesn't start until the previous
// commit has been drawn.
state.SetNeedsCommit();
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Make sure that a draw of the active tree doesn't spuriously advance
// the commit state and unblock the next commit.
state.SetNeedsRedraw(true);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(),
SchedulerStateMachine::COMMIT_STATE_WAITING_FOR_FIRST_DRAW);
EXPECT_TRUE(state.has_pending_tree());
// Verify NotifyReadyToActivate unblocks activation, draw, and
// commit in that order.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
state.NotifyReadyToActivate();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(),
SchedulerStateMachine::COMMIT_STATE_WAITING_FOR_FIRST_DRAW);
EXPECT_TRUE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_EQ(state.CommitState(), SchedulerStateMachine::COMMIT_STATE_IDLE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(),
SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT);
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(),
SchedulerStateMachine::COMMIT_STATE_WAITING_FOR_FIRST_DRAW);
}
// Explicitly test main_frame_before_activation_enabled = true
TEST(SchedulerStateMachineTest, MainFrameBeforeActivationEnabled) {
SchedulerSettings scheduler_settings;
scheduler_settings.impl_side_painting = true;
scheduler_settings.main_frame_before_activation_enabled = true;
StateMachine state(scheduler_settings);
state.SetCommitState(SchedulerStateMachine::COMMIT_STATE_IDLE);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetNeedsRedraw(false);
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsCommit();
EXPECT_TRUE(state.BeginFrameNeeded());
// Commit to the pending tree.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(), SchedulerStateMachine::COMMIT_STATE_IDLE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Verify that the next commit starts while there is still a pending tree.
state.SetNeedsCommit();
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Verify the pending commit doesn't overwrite the pending
// tree until the pending tree has been activated.
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Verify NotifyReadyToActivate unblocks activation, draw, and
// commit in that order.
state.NotifyReadyToActivate();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(state.CommitState(), SchedulerStateMachine::COMMIT_STATE_IDLE);
}
TEST(SchedulerStateMachineTest,
TestFailedDrawForAnimationCheckerboardSetsNeedsCommitAndDoesNotDrawAgain) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsRedraw(true);
EXPECT_TRUE(state.RedrawPending());
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
// We're drawing now.
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_FALSE(state.RedrawPending());
EXPECT_FALSE(state.CommitPending());
// Failing the draw makes us require a commit.
state.DidDrawIfPossibleCompleted(DRAW_ABORTED_CHECKERBOARD_ANIMATIONS);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_TRUE(state.RedrawPending());
EXPECT_TRUE(state.CommitPending());
}
TEST(SchedulerStateMachineTest, TestFailedDrawForMissingHighResNeedsCommit) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsRedraw(true);
EXPECT_TRUE(state.RedrawPending());
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_FALSE(state.RedrawPending());
EXPECT_FALSE(state.CommitPending());
// Missing high res content requires a commit (but not a redraw)
state.DidDrawIfPossibleCompleted(DRAW_ABORTED_MISSING_HIGH_RES_CONTENT);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_FALSE(state.RedrawPending());
EXPECT_TRUE(state.CommitPending());
}
TEST(SchedulerStateMachineTest,
TestsetNeedsRedrawDuringFailedDrawDoesNotRemoveNeedsRedraw) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsRedraw(true);
EXPECT_TRUE(state.RedrawPending());
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
// We're drawing now.
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_FALSE(state.RedrawPending());
EXPECT_FALSE(state.CommitPending());
// While still in the same BeginMainFrame callback on the main thread,
// set needs redraw again. This should not redraw.
state.SetNeedsRedraw(true);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Failing the draw for animation checkerboards makes us require a commit.
state.DidDrawIfPossibleCompleted(DRAW_ABORTED_CHECKERBOARD_ANIMATIONS);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_TRUE(state.RedrawPending());
}
void TestFailedDrawsEventuallyForceDrawAfterNextCommit(
bool main_frame_before_draw_enabled) {
SchedulerSettings scheduler_settings;
scheduler_settings.main_frame_before_draw_enabled =
main_frame_before_draw_enabled;
scheduler_settings.maximum_number_of_failed_draws_before_draw_is_forced_ = 1;
StateMachine state(scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Start a commit.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.CommitPending());
// Then initiate a draw.
state.SetNeedsRedraw(true);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
// Fail the draw.
state.DidDrawIfPossibleCompleted(DRAW_ABORTED_CHECKERBOARD_ANIMATIONS);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.BeginFrameNeeded());
EXPECT_TRUE(state.RedrawPending());
// But the commit is ongoing.
EXPECT_TRUE(state.CommitPending());
// Finish the commit. Note, we should not yet be forcing a draw, but should
// continue the commit as usual.
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.RedrawPending());
// The redraw should be forced at the end of the next BeginImplFrame.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
if (main_frame_before_draw_enabled) {
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_FORCED);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
}
TEST(SchedulerStateMachineTest,
TestFailedDrawsEventuallyForceDrawAfterNextCommit) {
bool main_frame_before_draw_enabled = false;
TestFailedDrawsEventuallyForceDrawAfterNextCommit(
main_frame_before_draw_enabled);
}
TEST(SchedulerStateMachineTest,
TestFailedDrawsEventuallyForceDrawAfterNextCommit_CommitBeforeDraw) {
bool main_frame_before_draw_enabled = true;
TestFailedDrawsEventuallyForceDrawAfterNextCommit(
main_frame_before_draw_enabled);
}
TEST(SchedulerStateMachineTest, TestFailedDrawsDoNotRestartForcedDraw) {
SchedulerSettings scheduler_settings;
int draw_limit = 1;
scheduler_settings.maximum_number_of_failed_draws_before_draw_is_forced_ =
draw_limit;
scheduler_settings.impl_side_painting = true;
StateMachine state(scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Start a commit.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.CommitPending());
// Then initiate a draw.
state.SetNeedsRedraw(true);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
// Fail the draw enough times to force a redraw,
// then once more for good measure.
for (int i = 0; i < draw_limit + 1; ++i)
state.DidDrawIfPossibleCompleted(DRAW_ABORTED_CHECKERBOARD_ANIMATIONS);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.BeginFrameNeeded());
EXPECT_TRUE(state.RedrawPending());
// But the commit is ongoing.
EXPECT_TRUE(state.CommitPending());
EXPECT_TRUE(state.ForcedRedrawState() ==
SchedulerStateMachine::FORCED_REDRAW_STATE_WAITING_FOR_COMMIT);
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.RedrawPending());
EXPECT_FALSE(state.CommitPending());
// Now force redraw should be in waiting for activation
EXPECT_TRUE(state.ForcedRedrawState() ==
SchedulerStateMachine::FORCED_REDRAW_STATE_WAITING_FOR_ACTIVATION);
// After failing additional draws, we should still be in a forced
// redraw, but not back in WAITING_FOR_COMMIT.
for (int i = 0; i < draw_limit + 1; ++i)
state.DidDrawIfPossibleCompleted(DRAW_ABORTED_CHECKERBOARD_ANIMATIONS);
EXPECT_TRUE(state.RedrawPending());
EXPECT_TRUE(state.ForcedRedrawState() ==
SchedulerStateMachine::FORCED_REDRAW_STATE_WAITING_FOR_ACTIVATION);
}
TEST(SchedulerStateMachineTest, TestFailedDrawIsRetriedInNextBeginImplFrame) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Start a draw.
state.SetNeedsRedraw(true);
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_TRUE(state.RedrawPending());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
// Failing the draw for animation checkerboards makes us require a commit.
state.DidDrawIfPossibleCompleted(DRAW_ABORTED_CHECKERBOARD_ANIMATIONS);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.RedrawPending());
// We should not be trying to draw again now, but we have a commit pending.
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// We should try to draw again at the end of the next BeginImplFrame on
// the impl thread.
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
}
TEST(SchedulerStateMachineTest, TestDoestDrawTwiceInSameFrame) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsRedraw(true);
// Draw the first frame.
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidDrawIfPossibleCompleted(DRAW_SUCCESS);
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Before the next BeginImplFrame, set needs redraw again.
// This should not redraw until the next BeginImplFrame.
state.SetNeedsRedraw(true);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Move to another frame. This should now draw.
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidDrawIfPossibleCompleted(DRAW_SUCCESS);
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// We just swapped, so we should proactively request another BeginImplFrame.
EXPECT_TRUE(state.BeginFrameNeeded());
}
TEST(SchedulerStateMachineTest, TestNextActionDrawsOnBeginImplFrame) {
SchedulerSettings default_scheduler_settings;
// When not in BeginImplFrame deadline, or in BeginImplFrame deadline
// but not visible, don't draw.
size_t num_commit_states =
sizeof(all_commit_states) / sizeof(SchedulerStateMachine::CommitState);
size_t num_begin_impl_frame_states =
sizeof(all_begin_impl_frame_states) /
sizeof(SchedulerStateMachine::BeginImplFrameState);
for (size_t i = 0; i < num_commit_states; ++i) {
for (size_t j = 0; j < num_begin_impl_frame_states; ++j) {
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetCommitState(all_commit_states[i]);
state.SetBeginImplFrameState(all_begin_impl_frame_states[j]);
bool visible =
(all_begin_impl_frame_states[j] !=
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE);
state.SetVisible(visible);
// Case 1: needs_commit=false
EXPECT_NE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE,
state.NextAction());
// Case 2: needs_commit=true
state.SetNeedsCommit();
EXPECT_NE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE,
state.NextAction())
<< state.AsValue()->ToString();
}
}
// When in BeginImplFrame deadline we should always draw for SetNeedsRedraw
// except if we're ready to commit, in which case we expect a commit first.
for (size_t i = 0; i < num_commit_states; ++i) {
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetCanDraw(true);
state.SetCommitState(all_commit_states[i]);
state.SetBeginImplFrameState(
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE);
state.SetNeedsRedraw(true);
state.SetVisible(true);
SchedulerStateMachine::Action expected_action;
if (all_commit_states[i] ==
SchedulerStateMachine::COMMIT_STATE_READY_TO_COMMIT) {
expected_action = SchedulerStateMachine::ACTION_COMMIT;
} else {
expected_action = SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE;
EXPECT_EQ(state.NextAction(), SchedulerStateMachine::ACTION_ANIMATE)
<< state.AsValue()->ToString();
state.UpdateState(state.NextAction());
}
// Case 1: needs_commit=false.
EXPECT_EQ(state.NextAction(), expected_action)
<< state.AsValue()->ToString();
// Case 2: needs_commit=true.
state.SetNeedsCommit();
EXPECT_EQ(state.NextAction(), expected_action)
<< state.AsValue()->ToString();
}
}
TEST(SchedulerStateMachineTest, TestNoCommitStatesRedrawWhenInvisible) {
SchedulerSettings default_scheduler_settings;
size_t num_commit_states =
sizeof(all_commit_states) / sizeof(SchedulerStateMachine::CommitState);
for (size_t i = 0; i < num_commit_states; ++i) {
// There shouldn't be any drawing regardless of BeginImplFrame.
for (size_t j = 0; j < 2; ++j) {
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetCommitState(all_commit_states[i]);
state.SetVisible(false);
state.SetNeedsRedraw(true);
if (j == 1) {
state.SetBeginImplFrameState(
SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE);
}
// Case 1: needs_commit=false.
EXPECT_NE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE,
state.NextAction());
// Case 2: needs_commit=true.
state.SetNeedsCommit();
EXPECT_NE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE,
state.NextAction())
<< state.AsValue()->ToString();
}
}
}
TEST(SchedulerStateMachineTest, TestCanRedraw_StopsDraw) {
SchedulerSettings default_scheduler_settings;
size_t num_commit_states =
sizeof(all_commit_states) / sizeof(SchedulerStateMachine::CommitState);
for (size_t i = 0; i < num_commit_states; ++i) {
// There shouldn't be any drawing regardless of BeginImplFrame.
for (size_t j = 0; j < 2; ++j) {
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetCommitState(all_commit_states[i]);
state.SetVisible(false);
state.SetNeedsRedraw(true);
if (j == 1)
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
state.SetCanDraw(false);
EXPECT_NE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE,
state.NextAction());
}
}
}
TEST(SchedulerStateMachineTest,
TestCanRedrawWithWaitingForFirstDrawMakesProgress) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetActiveTreeNeedsFirstDraw(true);
state.SetNeedsCommit();
state.SetNeedsRedraw(true);
state.SetVisible(true);
state.SetCanDraw(false);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
}
void TestSetNeedsCommitIsNotLost(bool main_frame_before_draw_enabled) {
SchedulerSettings scheduler_settings;
scheduler_settings.main_frame_before_draw_enabled =
main_frame_before_draw_enabled;
StateMachine state(scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetNeedsCommit();
state.SetVisible(true);
state.SetCanDraw(true);
EXPECT_TRUE(state.BeginFrameNeeded());
// Begin the frame.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
// Now, while the frame is in progress, set another commit.
state.SetNeedsCommit();
EXPECT_TRUE(state.NeedsCommit());
// Let the frame finish.
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_READY_TO_COMMIT,
state.CommitState());
// Expect to commit regardless of BeginImplFrame state.
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_BEGIN_FRAME_STARTING,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_COMMIT, state.NextAction());
state.OnBeginImplFrameDeadlinePending();
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_COMMIT, state.NextAction());
state.OnBeginImplFrameDeadline();
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_COMMIT, state.NextAction());
state.OnBeginImplFrameIdle();
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_COMMIT, state.NextAction());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_BEGIN_FRAME_STARTING,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_COMMIT, state.NextAction());
// Finish the commit, then make sure we start the next commit immediately
// and draw on the next BeginImplFrame.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
if (main_frame_before_draw_enabled) {
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_TRUE(state.active_tree_needs_first_draw());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidDrawIfPossibleCompleted(DRAW_SUCCESS);
state.DidSwapBuffersComplete();
if (!main_frame_before_draw_enabled) {
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
}
TEST(SchedulerStateMachineTest, TestSetNeedsCommitIsNotLost) {
bool main_frame_before_draw_enabled = false;
TestSetNeedsCommitIsNotLost(main_frame_before_draw_enabled);
}
TEST(SchedulerStateMachineTest, TestSetNeedsCommitIsNotLost_CommitBeforeDraw) {
bool main_frame_before_draw_enabled = true;
TestSetNeedsCommitIsNotLost(main_frame_before_draw_enabled);
}
TEST(SchedulerStateMachineTest, TestFullCycle) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Start clean and set commit.
state.SetNeedsCommit();
// Begin the frame.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Tell the scheduler the frame finished.
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_READY_TO_COMMIT,
state.CommitState());
// Commit.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_TRUE(state.active_tree_needs_first_draw());
EXPECT_TRUE(state.needs_redraw());
// Expect to do nothing until BeginImplFrame deadline
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// At BeginImplFrame deadline, draw.
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidDrawIfPossibleCompleted(DRAW_SUCCESS);
state.DidSwapBuffersComplete();
// Should be synchronized, no draw needed, no action needed.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_FALSE(state.needs_redraw());
}
TEST(SchedulerStateMachineTest, TestFullCycleWithCommitRequestInbetween) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Start clean and set commit.
state.SetNeedsCommit();
// Begin the frame.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Request another commit while the commit is in flight.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Tell the scheduler the frame finished.
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_READY_TO_COMMIT,
state.CommitState());
// First commit.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_TRUE(state.active_tree_needs_first_draw());
EXPECT_TRUE(state.needs_redraw());
// Expect to do nothing until BeginImplFrame deadline.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// At BeginImplFrame deadline, draw.
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidDrawIfPossibleCompleted(DRAW_SUCCESS);
state.DidSwapBuffersComplete();
// Should be synchronized, no draw needed, no action needed.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_FALSE(state.needs_redraw());
// Next BeginImplFrame should initiate second commit.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
TEST(SchedulerStateMachineTest, TestRequestCommitInvisible) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
}
TEST(SchedulerStateMachineTest, TestGoesInvisibleBeforeFinishCommit) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Start clean and set commit.
state.SetNeedsCommit();
// Begin the frame while visible.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Become invisible and abort BeginMainFrame.
state.SetVisible(false);
state.BeginMainFrameAborted(false);
// We should now be back in the idle state as if we never started the frame.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// We shouldn't do anything on the BeginImplFrame deadline.
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Become visible again.
state.SetVisible(true);
// Although we have aborted on this frame and haven't cancelled the commit
// (i.e. need another), don't send another BeginMainFrame yet.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_TRUE(state.NeedsCommit());
// Start a new frame.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
// We should be starting the commit now.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
}
TEST(SchedulerStateMachineTest, AbortBeginMainFrameAndCancelCommit) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.DidCreateAndInitializeOutputSurface();
state.SetVisible(true);
state.SetCanDraw(true);
// Get into a begin frame / commit state.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
// Abort the commit, cancelling future commits.
state.BeginMainFrameAborted(true);
// Verify that another commit doesn't start on the same frame.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_FALSE(state.NeedsCommit());
// Start a new frame; draw because this is the first frame since output
// surface init'd.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
// Verify another commit doesn't start on another frame either.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_FALSE(state.NeedsCommit());
// Verify another commit can start if requested, though.
state.SetNeedsCommit();
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME,
state.NextAction());
}
TEST(SchedulerStateMachineTest,
AbortBeginMainFrameAndCancelCommitWhenInvisible) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.DidCreateAndInitializeOutputSurface();
state.SetVisible(true);
state.SetCanDraw(true);
// Get into a begin frame / commit state.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
// Become invisible and abort BeginMainFrame.
state.SetVisible(false);
state.BeginMainFrameAborted(true);
// Verify that another commit doesn't start on the same frame.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_FALSE(state.NeedsCommit());
// Become visible and start a new frame.
state.SetVisible(true);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Draw because this is the first frame since output surface init'd.
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
// Verify another commit doesn't start on another frame either.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_FALSE(state.NeedsCommit());
// Verify another commit can start if requested, though.
state.SetNeedsCommit();
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME,
state.NextAction());
}
TEST(SchedulerStateMachineTest,
AbortBeginMainFrameAndRequestCommitWhenInvisible) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.DidCreateAndInitializeOutputSurface();
state.SetVisible(true);
state.SetCanDraw(true);
// Get into a begin frame / commit state.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
// Become invisible and abort BeginMainFrame.
state.SetVisible(false);
state.BeginMainFrameAborted(true);
// Verify that another commit doesn't start on the same frame.
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_FALSE(state.NeedsCommit());
// Asking for a commit while not visible won't make it happen.
state.SetNeedsCommit();
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_TRUE(state.NeedsCommit());
// Become visible but nothing happens until the next frame.
state.SetVisible(true);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_TRUE(state.NeedsCommit());
// We should get that commit when we begin the next frame.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
TEST(SchedulerStateMachineTest,
AbortBeginMainFrameAndRequestCommitAndBeginImplFrameWhenInvisible) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.DidCreateAndInitializeOutputSurface();
state.SetVisible(true);
state.SetCanDraw(true);
// Get into a begin frame / commit state.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
EXPECT_FALSE(state.NeedsCommit());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
// Become invisible and abort BeginMainFrame.
state.SetVisible(false);
state.BeginMainFrameAborted(true);
// Asking for a commit while not visible won't make it happen.
state.SetNeedsCommit();
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_TRUE(state.NeedsCommit());
// Begin a frame when not visible, the scheduler animates but does not commit.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
EXPECT_TRUE(state.NeedsCommit());
// Become visible and the requested commit happens immediately.
state.SetVisible(true);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_IDLE, state.CommitState());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
TEST(SchedulerStateMachineTest, TestFirstContextCreation) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.SetVisible(true);
state.SetCanDraw(true);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION);
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Check that the first init does not SetNeedsCommit.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Check that a needs commit initiates a BeginMainFrame.
state.SetNeedsCommit();
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
TEST(SchedulerStateMachineTest, TestContextLostWhenCompletelyIdle) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
EXPECT_NE(SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION,
state.NextAction());
state.DidLoseOutputSurface();
EXPECT_EQ(SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION,
state.NextAction());
state.UpdateState(state.NextAction());
// Once context recreation begins, nothing should happen.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Recreate the context.
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
// When the context is recreated, we should begin a commit.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
}
TEST(SchedulerStateMachineTest,
TestContextLostWhenIdleAndCommitRequestedWhileRecreating) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
EXPECT_NE(SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION,
state.NextAction());
state.DidLoseOutputSurface();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Once context recreation begins, nothing should happen.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// While context is recreating, commits shouldn't begin.
state.SetNeedsCommit();
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Recreate the context
state.DidCreateAndInitializeOutputSurface();
EXPECT_FALSE(state.RedrawPending());
// When the context is recreated, we should begin a commit
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_EQ(SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT,
state.CommitState());
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Finishing the first commit after initializing an output surface should
// automatically cause a redraw.
EXPECT_TRUE(state.RedrawPending());
// Once the context is recreated, whether we draw should be based on
// SetCanDraw.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_EQ(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE,
state.NextAction());
state.SetCanDraw(false);
EXPECT_EQ(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT,
state.NextAction());
state.SetCanDraw(true);
EXPECT_EQ(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE,
state.NextAction());
}
TEST(SchedulerStateMachineTest, TestContextLostWhileCommitInProgress) {
SchedulerSettings scheduler_settings;
StateMachine state(scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Get a commit in flight.
state.SetNeedsCommit();
// Set damage and expect a draw.
state.SetNeedsRedraw(true);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Cause a lost context while the BeginMainFrame is in flight.
state.DidLoseOutputSurface();
// Ask for another draw. Expect nothing happens.
state.SetNeedsRedraw(true);
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
// Finish the frame, and commit.
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
// We will abort the draw when the output surface is lost if we are
// waiting for the first draw to unblock the main thread.
EXPECT_TRUE(state.active_tree_needs_first_draw());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT);
// Expect to begin context recreation only in BEGIN_IMPL_FRAME_STATE_IDLE
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION,
state.NextAction());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_BEGIN_FRAME_STARTING,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
state.OnBeginImplFrameDeadlinePending();
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
state.OnBeginImplFrameDeadline();
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
}
TEST(SchedulerStateMachineTest,
TestContextLostWhileCommitInProgressAndAnotherCommitRequested) {
SchedulerSettings scheduler_settings;
StateMachine state(scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Get a commit in flight.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Set damage and expect a draw.
state.SetNeedsRedraw(true);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Cause a lost context while the BeginMainFrame is in flight.
state.DidLoseOutputSurface();
// Ask for another draw and also set needs commit. Expect nothing happens.
state.SetNeedsRedraw(true);
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Finish the frame, and commit.
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_TRUE(state.active_tree_needs_first_draw());
// Because the output surface is missing, we expect the draw to abort.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT);
// Expect to begin context recreation only in BEGIN_IMPL_FRAME_STATE_IDLE
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_IDLE,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION,
state.NextAction());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_BEGIN_FRAME_STARTING,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
state.OnBeginImplFrameDeadlinePending();
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_BEGIN_FRAME,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
state.OnBeginImplFrameDeadline();
EXPECT_EQ(SchedulerStateMachine::BEGIN_IMPL_FRAME_STATE_INSIDE_DEADLINE,
state.begin_impl_frame_state());
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
state.OnBeginImplFrameIdle();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION);
// After we get a new output surface, the commit flow should start.
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
}
TEST(SchedulerStateMachineTest, DontDrawBeforeCommitAfterLostOutputSurface) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsRedraw(true);
// Cause a lost output surface, and restore it.
state.DidLoseOutputSurface();
EXPECT_EQ(SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION,
state.NextAction());
state.UpdateState(state.NextAction());
state.DidCreateAndInitializeOutputSurface();
EXPECT_FALSE(state.RedrawPending());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_EQ(SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME,
state.NextAction());
}
TEST(SchedulerStateMachineTest,
TestPendingActivationsShouldBeForcedAfterLostOutputSurface) {
SchedulerSettings settings;
settings.impl_side_painting = true;
StateMachine state(settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetCommitState(
SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT);
// Cause a lost context.
state.DidLoseOutputSurface();
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_TRUE(state.PendingActivationsShouldBeForced());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE);
EXPECT_TRUE(state.PendingDrawsShouldBeAborted());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT);
}
TEST(SchedulerStateMachineTest, TestNoBeginMainFrameWhenInvisible) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(false);
state.SetNeedsCommit();
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction());
}
TEST(SchedulerStateMachineTest, TestFinishCommitWhenCommitInProgress) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(false);
state.SetCommitState(
SchedulerStateMachine::COMMIT_STATE_BEGIN_MAIN_FRAME_SENT);
state.SetNeedsCommit();
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_EQ(SchedulerStateMachine::ACTION_COMMIT, state.NextAction());
state.UpdateState(state.NextAction());
EXPECT_TRUE(state.active_tree_needs_first_draw());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_DRAW_AND_SWAP_ABORT);
}
TEST(SchedulerStateMachineTest, TestInitialActionsWhenContextLost) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsCommit();
state.DidLoseOutputSurface();
// When we are visible, we normally want to begin output surface creation
// as soon as possible.
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_BEGIN_OUTPUT_SURFACE_CREATION);
state.DidCreateAndInitializeOutputSurface();
EXPECT_EQ(state.output_surface_state(),
SchedulerStateMachine::OUTPUT_SURFACE_WAITING_FOR_FIRST_COMMIT);
// We should not send a BeginMainFrame when we are invisible, even if we've
// lost the output surface and are trying to get the first commit, since the
// main thread will just abort anyway.
state.SetVisible(false);
EXPECT_EQ(SchedulerStateMachine::ACTION_NONE, state.NextAction())
<< state.AsValue()->ToString();
}
TEST(SchedulerStateMachineTest, ReportIfNotDrawing) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetCanDraw(true);
state.SetVisible(true);
EXPECT_FALSE(state.PendingDrawsShouldBeAborted());
state.SetCanDraw(false);
state.SetVisible(true);
EXPECT_TRUE(state.PendingDrawsShouldBeAborted());
state.SetCanDraw(true);
state.SetVisible(false);
EXPECT_TRUE(state.PendingDrawsShouldBeAborted());
state.SetCanDraw(false);
state.SetVisible(false);
EXPECT_TRUE(state.PendingDrawsShouldBeAborted());
state.SetCanDraw(true);
state.SetVisible(true);
EXPECT_FALSE(state.PendingDrawsShouldBeAborted());
}
TEST(SchedulerStateMachineTest, TestTriggerDeadlineEarlyAfterAbortedCommit) {
SchedulerSettings settings;
settings.impl_side_painting = true;
StateMachine state(settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// This test mirrors what happens during the first frame of a scroll gesture.
// First we get the input event and a BeginFrame.
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
// As a response the compositor requests a redraw and a commit to tell the
// main thread about the new scroll offset.
state.SetNeedsRedraw(true);
state.SetNeedsCommit();
// We should start the commit normally.
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Since only the scroll offset changed, the main thread will abort the
// commit.
state.BeginMainFrameAborted(true);
// Since the commit was aborted, we should draw right away instead of waiting
// for the deadline.
EXPECT_TRUE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
}
void FinishPreviousCommitAndDrawWithoutExitingDeadline(
StateMachine* state_ptr) {
// Gross, but allows us to use macros below.
StateMachine& state = *state_ptr;
state.NotifyBeginMainFrameStarted();
state.NotifyReadyToCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_COMMIT);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.NotifyReadyToActivate();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ACTIVATE_SYNC_TREE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
}
TEST(SchedulerStateMachineTest, TestImplLatencyTakesPriority) {
SchedulerSettings settings;
settings.impl_side_painting = true;
StateMachine state(settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// This test ensures that impl-draws are prioritized over main thread updates
// in prefer impl latency mode.
state.SetNeedsRedraw(true);
state.SetNeedsCommit();
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Verify the deadline is not triggered early until we enter
// prefer impl latency mode.
EXPECT_FALSE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
state.SetImplLatencyTakesPriority(true);
EXPECT_TRUE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
// Trigger the deadline.
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
state.DidSwapBuffers();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.DidSwapBuffersComplete();
// Request a new commit and finish the previous one.
state.SetNeedsCommit();
FinishPreviousCommitAndDrawWithoutExitingDeadline(&state);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.DidSwapBuffersComplete();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Finish the previous commit and draw it.
FinishPreviousCommitAndDrawWithoutExitingDeadline(&state);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// Verify we do not send another BeginMainFrame if was are swap throttled
// and did not just swap.
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_FALSE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
}
TEST(SchedulerStateMachineTest, TestTriggerDeadlineEarlyOnLostOutputSurface) {
SchedulerSettings default_scheduler_settings;
StateMachine state(default_scheduler_settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
state.SetNeedsCommit();
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_FALSE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
state.DidLoseOutputSurface();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
// The deadline should be triggered immediately when output surface is lost.
EXPECT_TRUE(state.ShouldTriggerBeginImplFrameDeadlineEarly());
}
TEST(SchedulerStateMachineTest, TestSetNeedsAnimate) {
SchedulerSettings settings;
settings.impl_side_painting = true;
StateMachine state(settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Test requesting an animation that, when run, causes us to draw.
state.SetNeedsAnimate();
EXPECT_TRUE(state.BeginFrameNeeded());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
state.OnBeginImplFrameDeadlinePending();
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
}
TEST(SchedulerStateMachineTest, TestAnimateBeforeCommit) {
SchedulerSettings settings;
settings.impl_side_painting = true;
StateMachine state(settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Check that animations are updated before we start a commit.
state.SetNeedsAnimate();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.SetNeedsCommit();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
EXPECT_TRUE(state.BeginFrameNeeded());
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_SEND_BEGIN_MAIN_FRAME);
state.OnBeginImplFrameDeadlinePending();
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
}
TEST(SchedulerStateMachineTest, TestSetNeedsAnimateAfterAnimate) {
SchedulerSettings settings;
settings.impl_side_painting = true;
StateMachine state(settings);
state.SetCanStart();
state.UpdateState(state.NextAction());
state.CreateAndInitializeOutputSurfaceWithActivatedCommit();
state.SetVisible(true);
state.SetCanDraw(true);
// Test requesting an animation after we have already animated during this
// frame.
state.SetNeedsRedraw(true);
EXPECT_TRUE(state.BeginFrameNeeded());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrame(CreateBeginFrameArgsForTesting());
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_ANIMATE);
state.SetNeedsAnimate();
EXPECT_ACTION_UPDATE_STATE(SchedulerStateMachine::ACTION_NONE);
state.OnBeginImplFrameDeadline();
EXPECT_ACTION_UPDATE_STATE(
SchedulerStateMachine::ACTION_DRAW_AND_SWAP_IF_POSSIBLE);
}
} // namespace
} // namespace cc
|
#ifndef DIKE_PROCESSOR_HPP
#define DIKE_PROCESSOR_HPP
#include <map>
#include <thread>
#include "DikeIO.hpp"
typedef std::map<std::string, std::string> DikeProcessorConfig;
class DikeProcessor {
public:
DikeProcessor(){};
virtual ~DikeProcessor() {
if(workerThread.joinable()) {
workerThread.join();
}
}
virtual int Run(DikeProcessorConfig & dikeProcessorConfig, DikeIO * output) = 0;
// DikeAsyncWriter * dikeWriter = NULL;
std::thread workerThread;
uint64_t record_counter = 0;
bool isRunning;
std::thread startWorker() {
return std::thread([this] { this->Worker(); });
}
virtual void Worker() = 0;
};
#endif /* DIKE_PROCESSOR_HPP */
|
/*
Energy
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
Thermal conductivity evaluator with one liquid (water) phase.
*/
#ifndef AMANZI_ENERGY_TCM_EVALUATOR_ONEPHASE_HH_
#define AMANZI_ENERGY_TCM_EVALUATOR_ONEPHASE_HH_
#include "secondary_variable_field_evaluator.hh"
#include "H2O_ThermalConductivity.hh"
namespace Amanzi {
namespace Energy {
// Equation of State model
class TCMEvaluator_OnePhase : public SecondaryVariableFieldEvaluator {
public:
// constructor format for all derived classes
TCMEvaluator_OnePhase(Teuchos::ParameterList& plist);
TCMEvaluator_OnePhase(const TCMEvaluator_OnePhase& other);
Teuchos::RCP<FieldEvaluator> Clone() const;
// Required methods from SecondaryVariableFieldModel
virtual void EvaluateField_(
const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& result);
virtual void EvaluateFieldPartialDerivative_(
const Teuchos::Ptr<State>& S, Key wrt_key, const Teuchos::Ptr<CompositeVector>& result);
protected:
// We have one model so far; hence, no factory is needed.
Teuchos::RCP<AmanziEOS::H2O_ThermalConductivity> tc_;
double k_rock_;
// Keys for fields dependencies
Key temperature_key_, porosity_key_;
};
} // namespace Energy
} // namespace Amanzi
#endif
|
/*
* main.cpp
*
* Created on: 21. 5. 2019
* Author: ondra
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <imtjson/operations.h>
#include <shared/toString.h>
#include "proxy.h"
#include <cmath>
#include <ctime>
#include "../api.h"
#include <imtjson/stringValue.h>
#include <shared/linear_map.h>
#include <shared/iterator_stream.h>
#include <imtjson/binary.h>
#include <imtjson/streams.h>
#include <imtjson/binjson.tcc>
#include "../isotime.h"
#include <imtjson/string.h>
#include <shared/logOutput.h>
using ondra_shared::logNote;
using ondra_shared::logError;
using namespace json;
class Interface: public AbstractBrokerAPI {
public:
Proxy px;
Interface(const std::string &path):AbstractBrokerAPI(path, {
Object({
{"name","key"},
{"label","ID"},
{"type","string"}}),
Object({
{"name","secret"},
{"label","Secret"},
{"type","string"}}),
Object({
{"name","server"},
{"label","Server"},
{"type","enum"},
{"options",Object({
{"main","www.bitmex.com"},
{"testnet","testnet.bitmex.com"}})},
{"default","main"}})})
,optionsFile(path+".conf"){}
virtual TradesSync syncTrades(json::Value lastId, const std::string_view & pair) override;
virtual Orders getOpenOrders(const std::string_view & par)override;
virtual Ticker getTicker(const std::string_view & piar)override;
virtual json::Value placeOrder(const std::string_view & pair,
double size,
double price,
json::Value clientId,
json::Value replaceId,
double replaceSize)override;
virtual bool reset()override;
virtual MarketInfo getMarketInfo(const std::string_view & pair)override;
virtual double getFees(const std::string_view &pair)override;
virtual std::vector<std::string> getAllPairs()override;
virtual BrokerInfo getBrokerInfo() override;
virtual void onLoadApiKey(json::Value keyData) override;
virtual void onInit() override;
virtual Interface *createSubaccount(const std::string &path) override {
return new Interface(path);
}
virtual double getBalance(const std::string_view & symb, const std::string_view & pair) override;
struct SymbolInfo {
String id;
String qtc;
bool inverse;
double multiplier;
double lotSize;
double leverage;
double tickSize;
double quantoMult;
};
using SymbolList = ondra_shared::linear_map<std::string_view, SymbolInfo>;
SymbolList slist;
const SymbolInfo &getSymbol(const std::string_view &id);
virtual json::Value getSettings(const std::string_view &) const override;
virtual json::Value setSettings(json::Value v) override;
virtual void restoreSettings(json::Value v) override;
private:
std::size_t uid_cnt = Proxy::now();
void updateSymbols();
Value balanceCache;
Value positionCache;
Value orderCache;
Value readOrders();
std::uint64_t quoteEachMin = 5;
bool allowSmallOrders = false;
std::string optionsFile;
json::Value saveOptions();
void loadOptions();
Value getBalanceCache();
};
int main(int argc, char **argv) {
using namespace json;
if (argc < 2) {
std::cerr << "Requires a signle parametr" << std::endl;
return 1;
}
Interface ifc(argv[1]);
ifc.dispatch();
}
Value Interface::getBalanceCache() {
if (!balanceCache.hasValue()) {
balanceCache = px.request("GET","/api/v1/user/margin", Object({{"currency","XBt"},
{"columns",{"marginBalance"}}}));
}
return balanceCache;
}
inline double Interface::getBalance(const std::string_view &symb, const std::string_view &) {
if (symb == "BTC") {
return getBalanceCache()["marginBalance"].getNumber()*1e-8;
} else if (symb == "USD") {
return getBalanceCache()["marginBalance"].getNumber()*1e-8/0.000001;
} else {
const SymbolInfo &s = getSymbol(symb);
if (!positionCache.hasValue()) {
positionCache = px.request("GET","/api/v1/position",Object({{"columns",{"symbol","currentQty"}}}));
}
Value x = positionCache.find([&](Value v){return v["symbol"] == symb;});
double q = x["currentQty"].getNumber();
if (s.inverse) q = -q;
return q*s.multiplier;
}
return 0;
}
inline Interface::TradesSync Interface::syncTrades(json::Value lastId, const std::string_view &pair) {
const SymbolInfo &s = getSymbol(pair);
Value trades;
Value lastExecId = lastId[1];
Value columns = {"execID","transactTime","side","lastQty","lastPx","symbol","execType"};
if (lastId.hasValue()) {
trades = px.request("GET","/api/v1/execution/tradeHistory",Object({
{"filter", Object({{"execType",Value(json::array,{"Trade"})}})},
{"startTime",lastId[0]},
{"count", 100},
{"symbol", pair},
{"columns",columns}}));
} else {
trades = px.request("GET","/api/v1/execution/tradeHistory",Object({
{"filter", Object({{"execType",Value(json::array,{"Trade"})}})},
{"reverse",true},
{"count", 1},
{"symbol", pair},
{"columns",columns}}));
}
auto idx = trades.findIndex([&](Value item) {
return item["execID"] == lastExecId;
});
if (idx != -1) {
trades = trades.slice(idx+1);
}
Value lastExecTime = lastId[0];
TradesSync resp;
for (Value item: trades) {
lastExecId = item["execID"];
lastExecTime = item["transactTime"];
StrViewA side = item["side"].getString();
double mult = side=="Buy"?1:side=="Sell"?-1:0;
if (mult == 0) continue;
if (s.inverse) mult=-mult;
double size = mult*item["lastQty"].getNumber()*s.multiplier;
double price = s.inverse?1.0/item["lastPx"].getNumber():item["lastPx"].getNumber();
resp.trades.push_back(Trade{
lastExecId,
parseTime(lastExecTime.toString(), ParseTimeFormat::iso),
size,
price,
size,
price
});
}
if (resp.trades.empty()) {
resp.lastId = lastId;
} else {
resp.lastId = {lastExecTime, lastExecId};
}
return resp;
}
inline Interface::Orders Interface::getOpenOrders(const std::string_view &pair) {
const SymbolInfo &s = getSymbol(pair);
Value orders = readOrders();
Value myorders = orders.filter([&](const Value &v) {
return v["symbol"].getString() == pair;
});
Orders resp;
for (Value ord: myorders) {
double mult = ord["side"].getString() == "Sell"?-1:1;
double size = ord["orderQty"].getNumber();
double price = ord["price"].getNumber();
StrViewA clid = ord["clOrdID"].getString();
Value id = ord["orderID"];
Value clientId;
if (!clid.empty()) try{
clientId = Value::fromString(clid)[0];
} catch (...) {
}
if (s.inverse) {
mult = -mult;
price = 1/price;
}
resp.push_back(Order {
id,clientId,size*s.multiplier*mult,price
});
}
return resp;
}
inline Interface::Ticker Interface::getTicker(const std::string_view &pair) {
const SymbolInfo &s = getSymbol(pair);
Value resp = px.request("GET","/api/v1/orderBook/L2", Object({{"symbol",pair},{"depth",1}}));
double bid = 0;
double ask = 0;
for (Value v: resp) {
double price = v["price"].getNumber();
if (v["side"].getString() == "Sell") {
if (s.inverse) bid =1/price; else ask = price;
}
else if (v["side"].getString() == "Buy") {
if (s.inverse) ask =1/price; else bid = price;
}
if (bid == 0) bid = ask;
if (ask == 0) ask = bid;
}
return Ticker{bid, ask, sqrt(bid*ask), px.now()*1000};
}
static bool almostSame(double a, double b) {
double mdl = (fabs(a) + fabs(b))/2;
return fabs(a - b) < mdl*1e-6;
}
inline json::Value Interface::placeOrder(const std::string_view &pair,
double size, double price, json::Value clientId, json::Value replaceId,
double replaceSize) {
auto now = px.now()*1000;
const SymbolInfo &s = getSymbol(pair);
if (s.inverse && price) {
size = -size;
price = 1/price;
price = round(price/s.tickSize)*s.tickSize;
}
Value side = size < 0?"Sell":"Buy";
Value qty = fabs(size/s.multiplier);
Value curOrders = readOrders();
if (replaceId.hasValue()) {
Value toCancel = curOrders.find([&](Value v) {
return v["orderID"] == replaceId;
});
if (toCancel.hasValue()) {
std::uint64_t orderTime = parseTime(toCancel["transactTime"].toString(), ParseTimeFormat::iso);
std::uint64_t limitTime = quoteEachMin*60000;
if (size != 0 && quoteEachMin && now-orderTime < limitTime) {
logNote("Re-quote disallowed for this time ($1<$2)", now-orderTime , limitTime );
return toCancel["orderID"];
}
if (toCancel["Side"] == side && toCancel["symbol"].getString() == pair
&& almostSame(toCancel["orderQty"].getNumber() , qty.getNumber())
&& almostSame(toCancel["price"].getNumber() , price)) {
return toCancel["orderID"];
} else {
if (size) {
Object order;
order.setItems({{"orderID", replaceId},
{"orderQty", qty},
{"price",price}});
Value resp = px.request("PUT","/api/v1/order",Value(),order);
return resp["orderID"];
} else{
px.request("DELETE","/api/v1/order",Object({{"orderID",replaceId}}));
return nullptr;
}
}
}
}
if (size == 0) return nullptr;
Value clId;
if (clientId.hasValue()) {
clId = {clientId, ++uid_cnt};
clId = clId.toString();
}
Object order;
order.setItems({{"symbol", pair},
{"side",side},
{"orderQty",qty},
{"price",price},
{"clOrdID", clId},
{"ordType","Limit"},
{"execInst","ParticipateDoNotInitiate"}});
Value resp = px.request("POST","/api/v1/order",Value(),order);
return resp["orderID"];
}
inline bool Interface::reset() {
balanceCache = nullptr;
positionCache = nullptr;
orderCache = nullptr;
return true;
}
inline Interface::MarketInfo Interface::getMarketInfo(const std::string_view &pair) {
const SymbolInfo &s = getSymbol(pair);
if (s.inverse) {
return MarketInfo{
std::string(pair),
s.qtc.str(),
s.multiplier*s.lotSize,
s.tickSize,
s.multiplier*s.lotSize,
allowSmallOrders?0:0.0101/s.quantoMult,
0,
currency,
s.leverage,
true,
"USD",
px.testnet
};
} else {
return MarketInfo{
std::string(pair),
s.qtc.str(),
s.multiplier*s.lotSize,
s.tickSize,
s.multiplier*s.lotSize,
allowSmallOrders?0:0.0101/s.quantoMult,
0,
currency,
s.leverage,
false,
"XBT",
px.testnet
};
}
}
inline double Interface::getFees(const std::string_view &pair) {
return 0;
}
Interface::BrokerInfo Interface::getBrokerInfo() {
return BrokerInfo{
px.hasKey(),
"bitmex",
"BitMEX",
"https://www.bitmex.com/register/ns01mS",
"1.1",
R"mit(Copyright (c) 2019 Ondřej Novák
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.)mit",
"iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAB1klEQVR42u3a0VECQRBF0dEyEb4x"
"K+IyK/kmFE2Bhemd7ulzEtBa3vbFKscAAAAAAAAAAAAAdvCx8oc/vq9/VR7U5fce9qyut8f053D/"
"uTz1+356B9aK+PCPMIANPfv2Lx1ApfO/Mxeg8fk3gARfAA2AZf1fNgD9dwH0P0H/DaB5/w2gef+X"
"DED/XQD9T9J/A2jefwNo3v/TB6D/LoD+J+q/ATTvvwE07/+pA9B/F0D/k/XfAJr33wCa9/+0Aei/"
"C6D/CftvAM37bwDN+3/KAPTfBdD/pP03gOb9N4Dm/Q8fgP67APqfuP9jjPGl1S6AD79p/0MHoP8u"
"gP4n778BUGsA+j+3/2ED0H8XQP8L9N8AqDMA/Z/f/5AB6L8LoP9F+m8A1BiA/sf0f/oA9N8F0P9C"
"/TcA8g9A/+P6P3UA+u8C6H+x/hsAuQeg/7H9H2PSfwVX63/FUy0BGIC3v9EA9D++/1MG4O9/FwAD"
"0H8D0P9y/X97APrvAmAA+m8A+l+y/28NQP9dAAxA/w1A/8v2/+UB6L8LgAHovwHof+n+vzQA/XcB"
"MAD9NwD9L9//wwPQfxcAA9B/A9D/Lfp/aAD67wJgAPpvAPq/Tf8BAAAAAAAAAAAA2MQ/A0e46eQ0"
"zFcAAAAASUVORK5CYII=", true, true
};
}
inline std::vector<std::string> Interface::getAllPairs() {
if (slist.empty()) updateSymbols();
std::vector<std::string> out;
out.reserve(slist.size());
for (auto &&k: slist) {
out.push_back(k.second.id.str());
}
return out;
}
inline void Interface::onLoadApiKey(json::Value keyData) {
px.setTestnet(keyData["server"].getString() == "testnet");
px.privKey = keyData["secret"].getString();
px.pubKey = keyData["key"].getString();
}
inline void Interface::onInit() {
loadOptions();
}
void Interface::updateSymbols() {
Value resp = px.request("GET", "/api/v1/instrument/active",
Object({{"columns",{"optionUnderlyingPrice","isQuanto","settlCurrency","symbol","isInverse","rootSymbol","quoteCurrency","multiplier","lotSize","initMargin","tickSize"}}}));
std::vector<SymbolList::value_type> smap;
for (Value s : resp) {
SymbolInfo sinfo;
sinfo.id = s["symbol"].toString();
if (s["optionUnderlyingPrice"].hasValue())
continue;
if (s["settlCurrency"].getString() != "XBt")
continue;
sinfo.inverse = s["isInverse"].getBool();
if (sinfo.inverse) {
if (s["rootSymbol"].getString() != "XBT")
continue;
sinfo.qtc = "BTC";
}
sinfo.qtc = "BTC";
sinfo.quantoMult = 1;
sinfo.multiplier = fabs(s["multiplier"].getNumber())/ (100000000.0*sinfo.quantoMult);
sinfo.lotSize = s["lotSize"].getNumber();
sinfo.leverage = 1/s["initMargin"].getNumber();
sinfo.tickSize = s["tickSize"].getNumber();
smap.push_back( { sinfo.id.str(), sinfo });
}
slist.swap(smap);
}
const Interface::SymbolInfo& Interface::getSymbol(const std::string_view &id) {
if (slist.empty()) {
updateSymbols();
}
auto iter = slist.find(id);
if (iter == slist.end()) throw std::runtime_error("Unknown symbol");
return iter->second;
}
inline json::Value Interface::getSettings(const std::string_view&) const {
char m[4];
m[0] = 'm';
m[1] = (quoteEachMin/10)%10+'0';
m[2] = quoteEachMin%10+'0';
m[3] = 0;
return {
Object({
{"name","quoteEachMin"},
{"label","Allow to move the order"},
{"type","enum"},
{"options",Object({
{"m00", "anytime"},
{"m01", "every 1 minute"},
{"m02", "every 2 minutes"},
{"m03", "every 3 minutes"},
{"m04", "every 4 minutes"},
{"m05", "every 5 minutes"},
{"m07", "every 6 minutes"},
{"m10", "every 10 minutes"},
{"m10", "every 12 minutes"},
{"m15", "every 15 minutes"},
{"m20", "every 20 minutes"},
{"m30", "every 30 minutes"},
{"m60", "every 60 minutes"}})},
{"default",m}}),
Object({
{"name","allowSmallOrders"},
{"label","Allow small orders (spam orders},"},
{"type","enum"},
{"options", Object({
{"allow", "Allow (not recommended},"},
{"disallow", "Disallow"}})},
{"default",allowSmallOrders?"allow":"disallow"}})
};
}
inline json::Value Interface::setSettings(json::Value v) {
auto m = v["quoteEachMin"].getString();
if (m.size() > 1) {
quoteEachMin = std::strtod(m.data()+1,nullptr);
}
allowSmallOrders = v["allowSmallOrders"].getString() == "allow";
return saveOptions();
}
inline void Interface::restoreSettings(json::Value v) {
quoteEachMin = v["quoteEachMin"].getUInt();
allowSmallOrders = v["allowSmallOrders"].getBool();
remove(optionsFile.c_str());
}
Value Interface::readOrders() {
if (!orderCache.hasValue()) {
orderCache = px.request("GET","/api/v1/order",Object({
{"filter",Object({
{"ordStatus",{"New","PartiallyFilled","DoneForDay","Stopped"}}})}}));
}
return orderCache;
}
inline json::Value Interface::saveOptions() {
Object opt;
opt.set("quoteEachMin",quoteEachMin);
opt.set("allowSmallOrders", allowSmallOrders);
Value s = opt;
/* std::ofstream file(optionsFile,std::ios::out|std::ios::trunc);
s.toStream(file);*/
return s;
}
inline void Interface::loadOptions() {
try {
std::ifstream file(optionsFile, std::ios::in);
if (!file) return;
Value v = Value::fromStream(file);
quoteEachMin = v["quoteEachMin"].getUInt();
allowSmallOrders = v["allowSmallOrders"].getUInt();
} catch (std::exception &e) {
logError("Failed to load config: $1", e.what());
}
}
|
#include "linux_parser.h"
#include <dirent.h>
#include <unistd.h>
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
using std::stof;
using std::string;
using std::to_string;
using std::vector;
namespace fs = std::filesystem;
// DONE: An example of how to read data from the filesystem
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
filestream.close();
return value;
}
// DONE: An example of how to read data from the filesystem
string LinuxParser::Kernel() {
string os, version, kernel;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
stream.close();
return kernel;
}
// BONUS: Update this to use std::filesystem
vector<int> LinuxParser::Pids() {
vector<int> pids;
for (const auto& filename : fs::directory_iterator(kProcDirectory))
if (fs::is_directory(filename)) {
string directory(filename.path());
directory.erase(0, kProcDirectory.length());
if (std::all_of(directory.begin(), directory.end(), isdigit)) {
int pid = stoi(directory);
pids.push_back(pid);
}
}
return pids;
}
// DONE: Read and return the system memory utilization
LinuxParser::Memory LinuxParser::MemoryUtilization() {
// This function should read only the memory values, the actual calculation
// should be done in system.cpp
std::ifstream stream(kProcDirectory + kMeminfoFilename);
string line, key, unit;
Memory memory;
int idx{0};
float value{0.0};
if (stream.is_open()) {
// Get the values first, then we make the calculation.
while (getline(stream, line)) {
// Maybe redundant, but it ensures we are reading the correct element.
std::istringstream ss(line);
ss >> key >> value >> unit;
auto it = std::find(memory.keywords.begin(), memory.keywords.end(), key);
if (it != memory.keywords.end()) {
idx = it - memory.keywords.begin();
memory.values[idx] = value;
}
}
}
stream.close();
return memory;
}
// DONE: Read and return the system uptime
long LinuxParser::UpTime() {
long uptime{0};
string line;
std::ifstream stream(kProcDirectory + kUptimeFilename);
if (stream.is_open()) {
getline(stream, line);
uptime = stof(line.substr(0, line.find(" ")));
}
stream.close();
return uptime;
}
// TODO: Read and return the number of jiffies for the system
long LinuxParser::Jiffies() { return 0; }
// TODO: Read and return the number of active jiffies for a PID
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::ActiveJiffies(int pid [[maybe_unused]]) { return 0; }
// TODO: Read and return the number of active jiffies for the system
long LinuxParser::ActiveJiffies() { return 0; }
// TODO: Read and return the number of idle jiffies for the system
long LinuxParser::IdleJiffies() { return 0; }
// TODO: Read and return CPU utilization
vector<string> LinuxParser::CpuUtilization() { return {}; }
// DONE: Read and return the total number of processes
int LinuxParser::TotalProcesses() {
int processes{0};
string line;
const string keyword{"processes"};
std::ifstream stream(kProcDirectory + kStatFilename);
if (stream.is_open()) {
while (getline(stream, line)) {
if (line.find(keyword) != string::npos)
processes = stoi(line.substr(keyword.length() + 1));
}
}
stream.close();
return processes;
}
// DONE: Read and return the number of running processes
int LinuxParser::RunningProcesses() {
int procs_running{0};
string line;
const string keyword{"procs_running"};
std::ifstream stream(kProcDirectory + kStatFilename);
if (stream.is_open()) {
while (getline(stream, line)) {
if (line.find(keyword) != string::npos)
procs_running = stoi(line.substr(keyword.length() + 1));
}
}
stream.close();
return procs_running;
}
void LinuxParser::NumCores(int& cores) {
string line;
std::ifstream stream(kProcDirectory+k);
}
// TODO: Read and return the command associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Command(int pid [[maybe_unused]]) { return string(); }
// TODO: Read and return the memory used by a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Ram(int pid [[maybe_unused]]) { return string(); }
// TODO: Read and return the user ID associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Uid(int pid [[maybe_unused]]) { return string(); }
// TODO: Read and return the user associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::User(int pid [[maybe_unused]]) { return string(); }
// TODO: Read and return the uptime of a process
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::UpTime(int pid [[maybe_unused]]) { return 0; }
|
/*
MIT License
Copyright (c) 2009 Gaetan Guidet
This file is part of gcore.
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 <gcore/functor.h>
void gcore::Bind(void (*f)(void), gcore::Functor0 &cb) {
cb = gcore::FunctionTranslator0<void (*)(void)>(f);
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoingui.h"
#include "bitcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "miner.h"
#include "networkstyle.h"
#include "notificator.h"
#include "openuridialog.h"
#include "optionsdialog.h"
#include "optionsmodel.h"
#include "rpcconsole.h"
#include "utilitydialog.h"
#ifdef ENABLE_WALLET
#include "blockexplorer.h"
#include "walletframe.h"
#include "walletmodel.h"
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include "init.h"
#include "masternodelist.h"
#include "guiinterface.h"
#include "util.h"
#include <iostream>
#include <QAction>
#include <QApplication>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
#include <QIcon>
#include <QListWidget>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressBar>
#include <QProgressDialog>
#include <QSettings>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QTimer>
#include <QToolBar>
#include <QUrlQuery>
#include <QVBoxLayout>
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMainWindow(parent),
clientModel(0),
walletFrame(0),
unitDisplayControl(0),
labelStakingIcon(0),
labelEncryptionIcon(0),
labelTorIcon(0),
labelConnectionsIcon(0),
labelBlocksIcon(0),
progressBarLabel(0),
progressBar(0),
progressDialog(0),
appMenuBar(0),
overviewAction(0),
historyAction(0),
masternodeAction(0),
quitAction(0),
sendCoinsAction(0),
usedSendingAddressesAction(0),
usedReceivingAddressesAction(0),
signMessageAction(0),
verifyMessageAction(0),
bip38ToolAction(0),
multisigCreateAction(0),
multisigSpendAction(0),
multisigSignAction(0),
aboutAction(0),
receiveCoinsAction(0),
governanceAction(0),
privacyAction(0),
optionsAction(0),
toggleHideAction(0),
encryptWalletAction(0),
backupWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
openRPCConsoleAction(0),
openAction(0),
showHelpMessageAction(0),
multiSendAction(0),
trayIcon(0),
trayIconMenu(0),
notificator(0),
rpcConsole(0),
explorerWindow(0),
prevBlocks(0),
spinnerFrame(0)
{
/* Open CSS when configured */
this->setStyleSheet(GUIUtil::loadStyleSheet());
GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);
QString windowTitle = tr("RealCoin Core") + " - ";
#ifdef ENABLE_WALLET
/* if compiled with wallet support, -disablewallet can still disable the wallet */
enableWallet = !GetBoolArg("-disablewallet", false);
#else
enableWallet = false;
#endif // ENABLE_WALLET
if (enableWallet) {
windowTitle += tr("Wallet");
} else {
windowTitle += tr("Node");
}
QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", ""));
if (!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle;
windowTitle += " " + networkStyle->getTitleAddText();
#ifndef Q_OS_MAC
QApplication::setWindowIcon(networkStyle->getAppIcon());
setWindowIcon(networkStyle->getAppIcon());
#else
MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());
#endif
setWindowTitle(windowTitle);
rpcConsole = new RPCConsole(enableWallet ? this : 0);
#ifdef ENABLE_WALLET
if (enableWallet) {
/** Create wallet frame*/
walletFrame = new WalletFrame(this);
explorerWindow = new BlockExplorer(this);
} else
#endif // ENABLE_WALLET
{
/* When compiled without wallet or -disablewallet is provided,
* the central widget is the rpc console.
*/
setCentralWidget(rpcConsole);
}
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions(networkStyle);
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon(networkStyle);
// Create status bar
statusBar();
// Status bar notification icons
QFrame* frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0, 0, 0, 0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout* frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3, 0, 3, 0);
frameBlocksLayout->setSpacing(3);
unitDisplayControl = new UnitDisplayStatusBarControl();
labelStakingIcon = new QLabel();
labelAutoMintIcon = new QPushButton();
labelAutoMintIcon->setObjectName("labelAutoMintIcon");
labelAutoMintIcon->setFlat(true); // Make the button look like a label, but clickable
labelAutoMintIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}");
labelAutoMintIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelEncryptionIcon = new QPushButton();
labelEncryptionIcon->setObjectName("labelEncryptionIcon");
labelEncryptionIcon->setFlat(true); // Make the button look like a label, but clickable
labelEncryptionIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}");
labelEncryptionIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelTorIcon = new QLabel();
labelConnectionsIcon = new QPushButton();
labelConnectionsIcon->setObjectName("labelConnectionsIcon");
labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable
labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}");
labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelBlocksIcon = new QLabel();
#ifdef ENABLE_WALLET
if (enableWallet) {
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelStakingIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelAutoMintIcon);
}
#endif // ENABLE_WALLET
frameBlocksLayout->addWidget(labelTorIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(true);
progressBarLabel->setObjectName("progressBarLabel");
progressBar = new GUIUtil::ProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(true);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://doc.qt.io/qt-5/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if (curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") {
progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
// Jump directly to tabs in RPC-console
connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo()));
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole()));
connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork()));
connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers()));
connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair()));
connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor()));
connect(openMNConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showMNConfEditor()));
connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups()));
connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers()));
connect(labelEncryptionIcon, SIGNAL(clicked()), walletFrame, SLOT(toggleLockWallet()));
connect(labelAutoMintIcon, SIGNAL(clicked()), this, SLOT(optionsClicked()));
// Get restart command-line parameters and handle restart
connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList)));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
connect(openBlockExplorerAction, SIGNAL(triggered()), explorerWindow, SLOT(show()));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), explorerWindow, SLOT(hide()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
// Subscribe to notifications from core
subscribeToCoreSignals();
QTimer* timerStakingIcon = new QTimer(labelStakingIcon);
connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(setStakingStatus()));
timerStakingIcon->start(10000);
setStakingStatus();
QTimer* timerAutoMintIcon = new QTimer(labelAutoMintIcon);
connect(timerAutoMintIcon, SIGNAL(timeout()), this, SLOT(setAutoMintStatus()));
timerAutoMintIcon->start(10000);
setAutoMintStatus();
}
BitcoinGUI::~BitcoinGUI()
{
// Unsubscribe from notifications from core
unsubscribeFromCoreSignals();
GUIUtil::saveWindowGeometry("nWindow", this);
if (trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::cleanup();
#endif
}
void BitcoinGUI::createActions(const NetworkStyle* networkStyle)
{
QActionGroup* tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
#ifdef Q_OS_MAC
overviewAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1));
#else
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
#endif
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a RealCoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
sendCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
#else
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
#endif
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and realcoin: URIs)"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
receiveCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3));
#else
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
#endif
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
#ifdef Q_OS_MAC
historyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4));
#else
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
#endif
tabGroup->addAction(historyAction);
privacyAction = new QAction(QIcon(":/icons/privacy"), tr("&Privacy"), this);
privacyAction->setStatusTip(tr("Privacy Actions for zREA"));
privacyAction->setToolTip(privacyAction->statusTip());
privacyAction->setCheckable(true);
#ifdef Q_OS_MAC
privacyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5));
#else
privacyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
#endif
tabGroup->addAction(privacyAction);
#ifdef ENABLE_WALLET
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction = new QAction(QIcon(":/icons/masternodes"), tr("&Masternodes"), this);
masternodeAction->setStatusTip(tr("Browse masternodes"));
masternodeAction->setToolTip(masternodeAction->statusTip());
masternodeAction->setCheckable(true);
#ifdef Q_OS_MAC
masternodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_6));
#else
masternodeAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_6));
#endif
tabGroup->addAction(masternodeAction);
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(gotoMasternodePage()));
}
governanceAction = new QAction(QIcon(":/icons/governance"), tr("&Governance"), this);
governanceAction->setStatusTip(tr("Show Proposals"));
governanceAction->setToolTip(governanceAction->statusTip());
governanceAction->setCheckable(true);
#ifdef Q_OS_MAC
governanceAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_7));
#else
governanceAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_7));
#endif
tabGroup->addAction(governanceAction);
// These showNormalIfMinimized are needed because Send Coins and Receive Coins
// can be triggered from the tray menu, and need to show the GUI to be useful.
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(privacyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(privacyAction, SIGNAL(triggered()), this, SLOT(gotoPrivacyPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(governanceAction, SIGNAL(triggered()), this, SLOT(gotoGovernancePage()));
#endif // ENABLE_WALLET
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(networkStyle->getAppIcon(), tr("&About RealCoin Core"), this);
aboutAction->setStatusTip(tr("Show information about RealCoin Core"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for RealCoin"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(networkStyle->getAppIcon(), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
unlockWalletAction = new QAction(tr("&Unlock Wallet..."), this);
unlockWalletAction->setToolTip(tr("Unlock wallet"));
lockWalletAction = new QAction(tr("&Lock Wallet"), this);
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your RealCoin addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified RealCoin addresses"));
bip38ToolAction = new QAction(QIcon(":/icons/key"), tr("&BIP38 tool"), this);
bip38ToolAction->setToolTip(tr("Encrypt and decrypt private keys using a passphrase"));
multiSendAction = new QAction(QIcon(":/icons/edit"), tr("&MultiSend"), this);
multiSendAction->setToolTip(tr("MultiSend Settings"));
multiSendAction->setCheckable(true);
openInfoAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Information"), this);
openInfoAction->setStatusTip(tr("Show diagnostic information"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug console"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging console"));
openNetworkAction = new QAction(QIcon(":/icons/connect_4"), tr("&Network Monitor"), this);
openNetworkAction->setStatusTip(tr("Show network monitor"));
openPeersAction = new QAction(QIcon(":/icons/connect_4"), tr("&Peers list"), this);
openPeersAction->setStatusTip(tr("Show peers info"));
openRepairAction = new QAction(QIcon(":/icons/options"), tr("Wallet &Repair"), this);
openRepairAction->setStatusTip(tr("Show wallet repair options"));
openConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open Wallet &Configuration File"), this);
openConfEditorAction->setStatusTip(tr("Open configuration file"));
openMNConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open &Masternode Configuration File"), this);
openMNConfEditorAction->setStatusTip(tr("Open Masternode configuration file"));
showBackupsAction = new QAction(QIcon(":/icons/browse"), tr("Show Automatic &Backups"), this);
showBackupsAction->setStatusTip(tr("Show automatically created wallet backups"));
usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this);
usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this);
usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
multisigCreateAction = new QAction(QIcon(":/icons/address-book"), tr("&Multisignature creation..."), this);
multisigCreateAction->setStatusTip(tr("Create a new multisignature address and add it to this wallet"));
multisigSpendAction = new QAction(QIcon(":/icons/send"), tr("&Multisignature spending..."), this);
multisigSpendAction->setStatusTip(tr("Spend from a multisignature address"));
multisigSignAction = new QAction(QIcon(":/icons/editpaste"), tr("&Multisignature signing..."), this);
multisigSignAction->setStatusTip(tr("Sign with a multisignature address"));
openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this);
openAction->setStatusTip(tr("Open a RealCoin: URI or payment request"));
openBlockExplorerAction = new QAction(QIcon(":/icons/explorer"), tr("&Blockchain explorer"), this);
openBlockExplorerAction->setStatusTip(tr("Block explorer window"));
showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this);
showHelpMessageAction->setMenuRole(QAction::NoRole);
showHelpMessageAction->setStatusTip(tr("Show the RealCoin Core help message to get a list with possible RealCoin command-line options"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
#ifdef ENABLE_WALLET
if (walletFrame) {
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(unlockWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(unlockWallet(bool)));
connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
connect(bip38ToolAction, SIGNAL(triggered()), this, SLOT(gotoBip38Tool()));
connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
connect(multiSendAction, SIGNAL(triggered()), this, SLOT(gotoMultiSendDialog()));
connect(multisigCreateAction, SIGNAL(triggered()), this, SLOT(gotoMultisigCreate()));
connect(multisigSpendAction, SIGNAL(triggered()), this, SLOT(gotoMultisigSpend()));
connect(multisigSignAction, SIGNAL(triggered()), this, SLOT(gotoMultisigSign()));
}
#endif // ENABLE_WALLET
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu* file = appMenuBar->addMenu(tr("&File"));
if (walletFrame) {
file->addAction(openAction);
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(usedSendingAddressesAction);
file->addAction(usedReceivingAddressesAction);
file->addSeparator();
file->addAction(multisigCreateAction);
file->addAction(multisigSpendAction);
file->addAction(multisigSignAction);
file->addSeparator();
}
file->addAction(quitAction);
QMenu* settings = appMenuBar->addMenu(tr("&Settings"));
if (walletFrame) {
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addAction(unlockWalletAction);
settings->addAction(lockWalletAction);
settings->addAction(bip38ToolAction);
settings->addAction(multiSendAction);
settings->addSeparator();
}
settings->addAction(optionsAction);
if (walletFrame) {
QMenu* tools = appMenuBar->addMenu(tr("&Tools"));
tools->addAction(openInfoAction);
tools->addAction(openRPCConsoleAction);
tools->addAction(openNetworkAction);
tools->addAction(openPeersAction);
tools->addAction(openRepairAction);
tools->addSeparator();
tools->addAction(openConfEditorAction);
tools->addAction(openMNConfEditorAction);
tools->addAction(showBackupsAction);
tools->addAction(openBlockExplorerAction);
}
QMenu* help = appMenuBar->addMenu(tr("&Help"));
help->addAction(showHelpMessageAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
if (walletFrame) {
QToolBar* toolbar = new QToolBar(tr("Tabs toolbar"));
toolbar->setObjectName("Main-Toolbar"); // Name for CSS addressing
toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
// // Add some empty space at the top of the toolbars
// QAction* spacer = new QAction(this);
// toolbar->addAction(spacer);
// toolbar->widgetForAction(spacer)->setObjectName("ToolbarSpacer");
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(privacyAction);
toolbar->addAction(historyAction);
toolbar->addAction(privacyAction);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
toolbar->addAction(masternodeAction);
}
toolbar->addAction(governanceAction);
toolbar->setMovable(false); // remove unused icon in upper left corner
toolbar->setOrientation(Qt::Vertical);
toolbar->setIconSize(QSize(40,40));
overviewAction->setChecked(true);
/** Create additional container for toolbar and walletFrame and make it the central widget.
This is a workaround mostly for toolbar styling on Mac OS but should work fine for every other OSes too.
*/
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(toolbar);
layout->addWidget(walletFrame);
layout->setSpacing(0);
layout->setContentsMargins(QMargins());
layout->setDirection(QBoxLayout::LeftToRight);
QWidget* containerWidget = new QWidget();
containerWidget->setLayout(layout);
setCentralWidget(containerWidget);
}
}
void BitcoinGUI::setClientModel(ClientModel* clientModel)
{
this->clientModel = clientModel;
if (clientModel) {
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks());
connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
// Receive and report messages from client model
connect(clientModel, SIGNAL(message(QString, QString, unsigned int)), this, SLOT(message(QString, QString, unsigned int)));
// Show progress dialog
connect(clientModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int)));
rpcConsole->setClientModel(clientModel);
updateTorIcon();
#ifdef ENABLE_WALLET
if (walletFrame) {
walletFrame->setClientModel(clientModel);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(clientModel->getOptionsModel());
connect(clientModel->getOptionsModel(), SIGNAL(zeromintEnableChanged(bool)), this, SLOT(setAutoMintStatus()));
//Show trayIcon
if (trayIcon)
{
trayIcon->show();
}
} else {
// Disable possibility to show main window via action
toggleHideAction->setEnabled(false);
if (trayIconMenu) {
// Disable context menu on tray icon
trayIconMenu->clear();
}
}
}
#ifdef ENABLE_WALLET
bool BitcoinGUI::addWallet(const QString& name, WalletModel* walletModel)
{
if (!walletFrame)
return false;
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
if (!walletFrame)
return false;
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
if (!walletFrame)
return;
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
#endif // ENABLE_WALLET
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
privacyAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction->setEnabled(enabled);
}
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
multisigCreateAction->setEnabled(enabled);
multisigSpendAction->setEnabled(enabled);
multisigSignAction->setEnabled(enabled);
bip38ToolAction->setEnabled(enabled);
usedSendingAddressesAction->setEnabled(enabled);
usedReceivingAddressesAction->setEnabled(enabled);
openAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon(const NetworkStyle* networkStyle)
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
QString toolTip = tr("RealCoin Core client") + " " + networkStyle->getTitleAddText();
trayIcon->setToolTip(toolTip);
trayIcon->setIcon(networkStyle->getAppIcon());
trayIcon->hide();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
}
void BitcoinGUI::createTrayIconMenu()
{
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler* dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow*)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addAction(privacyAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addAction(bip38ToolAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openInfoAction);
trayIconMenu->addAction(openRPCConsoleAction);
trayIconMenu->addAction(openNetworkAction);
trayIconMenu->addAction(openPeersAction);
trayIconMenu->addAction(openRepairAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openConfEditorAction);
trayIconMenu->addAction(openMNConfEditorAction);
trayIconMenu->addAction(showBackupsAction);
trayIconMenu->addAction(openBlockExplorerAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger) {
// Click on system tray icon triggers show/hide of the main window
toggleHidden();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if (!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, enableWallet);
dlg.setModel(clientModel->getOptionsModel());
dlg.setCurrentIndex(0);
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
if (!clientModel)
return;
HelpMessageDialog dlg(this, true);
dlg.exec();
}
void BitcoinGUI::showHelpMessageClicked()
{
HelpMessageDialog* help = new HelpMessageDialog(this, false);
help->setAttribute(Qt::WA_DeleteOnClose);
help->show();
}
#ifdef ENABLE_WALLET
void BitcoinGUI::openClicked()
{
OpenURIDialog dlg(this);
if (dlg.exec()) {
emit receivedURI(dlg.getURI());
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoMasternodePage()
{
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction->setChecked(true);
if (walletFrame) walletFrame->gotoMasternodePage();
}
}
void BitcoinGUI::gotoGovernancePage()
{
governanceAction->setChecked(true);
if (walletFrame) walletFrame->gotoGovernancePage();
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoPrivacyPage()
{
privacyAction->setChecked(true);
if (walletFrame) walletFrame->gotoPrivacyPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
sendCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void BitcoinGUI::gotoMultisigCreate()
{
if(walletFrame) walletFrame->gotoMultisigDialog(0);
}
void BitcoinGUI::gotoMultisigSpend()
{
if(walletFrame) walletFrame->gotoMultisigDialog(1);
}
void BitcoinGUI::gotoMultisigSign()
{
if(walletFrame) walletFrame->gotoMultisigDialog(2);
}
void BitcoinGUI::gotoBip38Tool()
{
if (walletFrame) walletFrame->gotoBip38Tool();
}
void BitcoinGUI::gotoMultiSendDialog()
{
multiSendAction->setChecked(true);
if (walletFrame)
walletFrame->gotoMultiSendDialog();
}
void BitcoinGUI::gotoBlockExplorerPage()
{
if (walletFrame) walletFrame->gotoBlockExplorerPage();
}
#endif // ENABLE_WALLET
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch (count) {
case 0:
icon = ":/icons/connect_0";
break;
case 1:
case 2:
case 3:
icon = ":/icons/connect_1";
break;
case 4:
case 5:
case 6:
icon = ":/icons/connect_2";
break;
case 7:
case 8:
case 9:
icon = ":/icons/connect_3";
break;
default:
icon = ":/icons/connect_4";
break;
}
QIcon connectionItem = QIcon(icon).pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelConnectionsIcon->setIcon(connectionItem);
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to RealCoin network", "", count));
}
void BitcoinGUI::setNumBlocks(int count)
{
if (!clientModel)
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
QDateTime currentDate = QDateTime::currentDateTime();
int secs = lastBlockDate.secsTo(currentDate);
tooltip = tr("Processed %n blocks of transaction history.", "", count);
// Set icon state: spinning if catching up, tick otherwise
// if(secs < 25*60) // 90*60 for bitcoin but we are 4x times faster
if (masternodeSync.IsBlockchainSynced()) {
QString strSyncStatus;
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
if (masternodeSync.IsSynced()) {
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
} else {
int nAttempt;
int progress = 0;
labelBlocksIcon->setPixmap(QIcon(QString(
":/movies/spinner-%1")
.arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
#ifdef ENABLE_WALLET
if (walletFrame)
walletFrame->showOutOfSyncWarning(false);
#endif // ENABLE_WALLET
nAttempt = masternodeSync.RequestedMasternodeAttempt < MASTERNODE_SYNC_THRESHOLD ?
masternodeSync.RequestedMasternodeAttempt + 1 :
MASTERNODE_SYNC_THRESHOLD;
progress = nAttempt + (masternodeSync.RequestedMasternodeAssets - 1) * MASTERNODE_SYNC_THRESHOLD;
progressBar->setMaximum(4 * MASTERNODE_SYNC_THRESHOLD);
progressBar->setFormat(tr("Synchronizing additional data: %p%"));
progressBar->setValue(progress);
}
strSyncStatus = QString(masternodeSync.GetSyncStatus().c_str());
progressBarLabel->setText(strSyncStatus);
tooltip = strSyncStatus + QString("<br>") + tooltip;
} else {
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60 * 60;
const int DAY_IN_SECONDS = 24 * 60 * 60;
const int WEEK_IN_SECONDS = 7 * 24 * 60 * 60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if (secs < 2 * DAY_IN_SECONDS) {
timeBehindText = tr("%n hour(s)", "", secs / HOUR_IN_SECONDS);
} else if (secs < 2 * WEEK_IN_SECONDS) {
timeBehindText = tr("%n day(s)", "", secs / DAY_IN_SECONDS);
} else if (secs < YEAR_IN_SECONDS) {
timeBehindText = tr("%n week(s)", "", secs / WEEK_IN_SECONDS);
} else {
int years = secs / YEAR_IN_SECONDS;
int remainder = secs % YEAR_IN_SECONDS;
timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)", "", remainder / WEEK_IN_SECONDS));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind. Scanning block %2").arg(timeBehindText).arg(count));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
if (count != prevBlocks) {
labelBlocksIcon->setPixmap(QIcon(QString(
":/movies/spinner-%1")
.arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
}
prevBlocks = count;
#ifdef ENABLE_WALLET
if (walletFrame)
walletFrame->showOutOfSyncWarning(true);
#endif // ENABLE_WALLET
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString& title, const QString& message, unsigned int style, bool* ret)
{
QString strTitle = tr("RealCoin Core"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
} else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "RealCoin - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
} else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
} else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent* e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if (e->type() == QEvent::WindowStateChange) {
if (clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) {
QWindowStateChangeEvent* wsevt = static_cast<QWindowStateChangeEvent*>(e);
if (!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) {
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent* event)
{
#ifndef Q_OS_MAC // Ignored on Mac
if (clientModel && clientModel->getOptionsModel()) {
if (!clientModel->getOptionsModel()->getMinimizeOnClose()) {
QApplication::quit();
}
}
#endif
QMainWindow::closeEvent(event);
}
#ifdef ENABLE_WALLET
void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address)
{
// Only send notifications when not disabled
if(!bdisableSystemnotifications){
// On new transaction, make an info balloon
message((amount) < 0 ? (pwalletMain->fMultiSendNotify == true ? tr("Sent MultiSend transaction") : tr("Sent transaction")) : tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(unit, amount, true))
.arg(type)
.arg(address),
CClientUIInterface::MSG_INFORMATION);
pwalletMain->fMultiSendNotify = false;
}
}
#endif // ENABLE_WALLET
void BitcoinGUI::dragEnterEvent(QDragEnterEvent* event)
{
// Accept only URIs
if (event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent* event)
{
if (event->mimeData()->hasUrls()) {
foreach (const QUrl& uri, event->mimeData()->urls()) {
emit receivedURI(uri.toString());
}
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject* object, QEvent* event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip) {
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
#ifdef ENABLE_WALLET
void BitcoinGUI::setStakingStatus()
{
if (walletFrame) {
if (pwalletMain)
fMultiSend = pwalletMain->isMultiSendEnabled();
if (nLastCoinStakeSearchInterval) {
labelStakingIcon->show();
labelStakingIcon->setPixmap(QIcon(":/icons/staking_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(
tr("Staking is active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active")));
} else {
labelStakingIcon->show();
labelStakingIcon->setPixmap(
QIcon(":/icons/staking_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(
tr("Staking is not active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active")));
}
}
}
void BitcoinGUI::setAutoMintStatus()
{
if (walletFrame) {
if (fEnableZeromint) {
labelAutoMintIcon->show();
labelAutoMintIcon->setIcon(QIcon(":/icons/automint_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelAutoMintIcon->setToolTip(
tr("AutoMint is currently enabled and set to ") + QString::number(nZeromintPercentage) + "%.\n");
} else {
labelAutoMintIcon->show();
labelAutoMintIcon->setIcon(
QIcon(":/icons/automint_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelAutoMintIcon->setToolTip(tr("AutoMint is disabled"));
}
}
}
bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
// URI has to be valid
if (walletFrame && walletFrame->handlePaymentRequest(recipient)) {
showNormalIfMinimized();
gotoSendCoinsPage();
return true;
}
return false;
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch (status) {
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setIcon(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::UnlockedForAnonymizationOnly:
labelEncryptionIcon->show();
labelEncryptionIcon->setIcon(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b> for anonymization and staking only"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setIcon(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
#endif // ENABLE_WALLET
void BitcoinGUI::updateTorIcon()
{
std::string ip_port;
bool tor_enabled = clientModel->getTorInfo(ip_port);
if (tor_enabled) {
if (labelTorIcon->pixmap() == 0) {
QString ip_port_q = QString::fromStdString(ip_port);
labelTorIcon->setPixmap(QIcon(":/icons/onion").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelTorIcon->setToolTip(tr("Tor is <b>enabled</b>: %1").arg(ip_port_q));
} else {
labelTorIcon->show();
}
} else {
labelTorIcon->hide();
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
if (!clientModel)
return;
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden()) {
show();
activateWindow();
} else if (isMinimized()) {
showNormal();
activateWindow();
} else if (GUIUtil::isObscured(this)) {
raise();
activateWindow();
} else if (fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested()) {
if (rpcConsole)
rpcConsole->hide();
qApp->quit();
}
}
void BitcoinGUI::showProgress(const QString& title, int nProgress)
{
if (nProgress == 0) {
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
} else if (nProgress == 100) {
if (progressDialog) {
progressDialog->close();
progressDialog->deleteLater();
}
} else if (progressDialog)
progressDialog->setValue(nProgress);
}
static bool ThreadSafeMessageBox(BitcoinGUI* gui, const std::string& message, const std::string& caption, unsigned int style)
{
bool modal = (style & CClientUIInterface::MODAL);
// The SECURE flag has no effect in the Qt GUI.
// bool secure = (style & CClientUIInterface::SECURE);
style &= ~CClientUIInterface::SECURE;
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(gui, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
void BitcoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
void BitcoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
/** Get restart command-line parameters and request restart */
void BitcoinGUI::handleRestart(QStringList args)
{
if (!ShutdownRequested())
emit requestedRestart(args);
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl() : optionsModel(0),
menu(0)
{
createContextMenu();
setToolTip(tr("Unit to show amounts in. Click to select another unit."));
}
/** So that it responds to button clicks */
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent* event)
{
onDisplayUnitsClicked(event->pos());
}
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu();
foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) {
QAction* menuAction = new QAction(QString(BitcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
menu->addAction(menuAction);
}
connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onMenuSelection(QAction*)));
}
/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel* optionsModel)
{
if (optionsModel) {
this->optionsModel = optionsModel;
// be aware of a display unit change reported by the OptionsModel object.
connect(optionsModel, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int)));
// initialize the display units label with the current value in the model.
updateDisplayUnit(optionsModel->getDisplayUnit());
}
}
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
setPixmap(QIcon(":/icons/unit_" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE));
} else {
setPixmap(QIcon(":/icons/unit_t" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE));
}
}
/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
QPoint globalPos = mapToGlobal(point);
menu->exec(globalPos);
}
/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
if (action) {
optionsModel->setDisplayUnit(action->data());
}
}
|
//
// FILE NAME: CIDKernel_StackDump_Linux.Cpp
//
// AUTHOR: Will Mason
//
// CREATED: 01/18/1999
//
// COPYRIGHT: Charmed Quark Systems, Ltd - 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file provides the Linux versions of the stack dump functions that
// are called to get a dump of the call sequence to a place where an error
// has occured. The methods here are actually statics of TKrnlThread, but
// they are done here because they are really standalone and very platform
// specific.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDKernel_.hpp"
namespace
{
// ---------------------------------------------------------------------------
// Local static data
//
// __fdDump
// This is the handle of the file being dumped to. Its set and then
// used by all of the APIs. The dump operations are protected so we
// don't have to worry about thread's stepping on each other's toes.
//
// __mtx
// This is the critical section structure that we used to insure that
// only one thread enters the dump function at a time. Its initilized
// during DLL init.
//
// __pszTargetDir
// The directory into which dump files are placed. This is settable via
// the CIDLIB_ERRDUMPDIR environment variable. If not set, then they
// will go into the current directory.
// ---------------------------------------------------------------------------
tCIDLib::TSInt __fdDump;
pthread_mutex_t __mtx;
const tCIDLib::TSCh* __pszTargetDir = 0;
// ---------------------------------------------------------------------------
// Local functions
// ---------------------------------------------------------------------------
tCIDLib::TVoid __WriteStr(const tCIDLib::TSCh* const pszStr)
{
::write(__fdDump, pszStr, ::strlen(pszStr));
}
tCIDLib::TVoid __WriteLine(const tCIDLib::TSCh* const pszStr)
{
::write(__fdDump, pszStr, ::strlen(pszStr));
tCIDLib::TSCh schNewLine = '\n';
::write(__fdDump, &schNewLine, 1);
}
tCIDLib::TVoid __FmtCard4(tCIDLib::TCard4 c4Val
, tCIDLib::TSCh* const pszBuf
, tCIDLib::ERadices eRadix)
{
static tCIDLib::TSCh chChars[] =
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
tCIDLib::TBoolean bLeading0 = kCIDLib::True;
tCIDLib::TCard4 c4Divisor, c4Tmp;
tCIDLib::TInt4 i4Ind, i4StrInd;
//
// Put a 0 in the first byte just in case the value is zero.
// Otherwise, the code below would leave an empty string.
//
pszBuf[0] = '\000';
if (eRadix == tCIDLib::ERadices::Hex)
{
c4Divisor = 0x10000000;
i4Ind = 7;
}
else
{
//
// Divisor starts at the billions since largest number is
// around 4 billion.
//
c4Divisor = 1000000000;
i4Ind = 9;
}
i4StrInd = 0;
for (; i4Ind >= 0; i4Ind--)
{
c4Tmp = c4Val / c4Divisor;
// If non-zero make sure that leading zero is cleared
if (c4Tmp)
bLeading0 = kCIDLib::False;
if (!bLeading0 || (eRadix == tCIDLib::ERadices::Hex))
{
pszBuf[i4StrInd] = chChars[c4Tmp];
i4StrInd++;
}
// Bump down the value by the modulus
c4Val -= (c4Tmp * c4Divisor);
if (eRadix == tCIDLib::ERadices::Hex)
c4Divisor >>= 4;
else
c4Divisor /= 10;
}
if (i4StrInd)
pszBuf[i4StrInd] = 0;
}
tCIDLib::TVoid __CreateFile()
{
//
// Build the name of the file that we are going to output to. Its the
// target directory, plus the process name and the process id. We
// build the name itself into a separate directory because, if we cannot
// create the file in the target dir, we create in the current directory.
//
tCIDLib::TSCh szFullName[kCIDLib::c4MaxPathLen + 1];
szFullName[0] = 0;
tCIDLib::TSCh* pszNameEnd = szFullName;
if (__pszTargetDir)
{
::strcpy(szFullName, __pszTargetDir);
tCIDLib::TCard4 c4Len = ::strlen(szFullName);
if (szFullName[c4Len - 1] != '\\')
{
::strcat(szFullName, "\\");
c4Len++;
}
pszNameEnd = szFullName + c4Len;
}
tCIDLib::TSCh szTmpBuf[kCIDLib::c4MaxPathLen + 1];
TRawStr::pszConvert(TKrnlSysInfo::pszProcessName(), szTmpBuf, kCIDLib::c4MaxPathLen);
::sprintf(pszNameEnd, "%s_%i", szTmpBuf, ::getpid());
TRawStr::pszConvert(kCIDLib::pszErrInfExt, szTmpBuf, kCIDLib::c4MaxPathLen);
::strcat(szFullName, szTmpBuf);
//
// Ok, we are doing pretty well so far, so lets open or create
// the file and seek to the end in order to append beyond any
// current content.
//
tCIDLib::TCard4 c4Mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;
tCIDLib::TSInt iFlags = O_CREAT | O_APPEND | O_WRONLY;
__fdDump = ::open(szFullName, iFlags, c4Mode);
if (__fdDump == -1)
{
// If its not because the path is bad, then throw the error
if (errno == EISDIR || errno == EACCES || errno == ENAMETOOLONG ||
errno == ENOENT || errno == ENOTDIR || errno == EROFS)
{
// Just open the file in the current directory
__fdDump = ::open(szTmpBuf, iFlags, c4Mode);
}
}
}
}
// ---------------------------------------------------------------------------
// Intra-facility functions
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TCIDKrnlModule::__bInitTermStackDump(const tCIDLib::EInitTerm eInitTerm)
{
if (eInitTerm == tCIDLib::EInitTerm::Initialize)
{
::pthread_mutex_init(&__mtx, 0);
//
// See if there is an environment variable for the target output
// directory for dump files.
//
tCIDLib::TSCh szTmpBuf[1024];
TRawStr::pszConvert(kCIDKernel_::pszErrDumpDir, szTmpBuf, 1023);
tCIDLib::TSCh* pszTmp = ::getenv(szTmpBuf);
if (pszTmp)
{
__pszTargetDir = new tCIDLib::TSCh[::strlen(pszTmp) + 1];
::strcpy(const_cast<tCIDLib::TSCh*>(__pszTargetDir), pszTmp);
}
}
else
{
::pthread_mutex_destroy(&__mtx);
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TKrnlThread: Public, static methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TKrnlThread::DumpException( const TKrnlThread& kthrCaller
, const tCIDLib::TCh* const pszThreadName
, const tCIDLib::TVoid* const pExceptData)
{
tCIDLib::TSCh szTmp[512];
// Create the file that we dump to
__CreateFile();
if (__fdDump == -1)
return;
// Write the header for an exception
__WriteLine("--------------------------------------");
__WriteLine("Signal in Process: ");
// Log out the common info that we do for all dumps
__WriteStr(" Process: ");
TRawStr::pszConvert(TKrnlSysInfo::pszProcessName(), szTmp, 511);
__WriteLine(szTmp);
__WriteStr(" Thread: ");
TRawStr::pszConvert(pszThreadName, szTmp, 511);
__WriteLine(szTmp);
tCIDLib::TZStr64 szSigNum;
szSigNum[0] = kCIDLib::chNull;
TRawStr::bFormatVal(tCIDLib::TInt4(pExceptData), szSigNum, 64);
TRawStr::pszConvert(szSigNum, szTmp, 511);
__WriteStr(szTmp);
__WriteStr(": ");
__WriteLine(sys_siglist[tCIDLib::TInt4(pExceptData)]);
::close(__fdDump);
__fdDump = -1;
}
tCIDLib::TVoid
TKrnlThread::DumpRuntimeError( const TKrnlThread& kthrCaller
, const tCIDLib::TCh* const pszThreadName
, const tCIDLib::TCh* const pszFacility
, const tCIDLib::TCh* const pszError
, const tCIDLib::TCh* const pszAuxText
, const tCIDLib::TErrCode errcId
, const tCIDLib::TErrCode errcKrnlId
, const tCIDLib::TOSErrCode errcHostId
, const tCIDLib::TCh* const pszFile
, const tCIDLib::TCard4 c4LineNumber)
{
tCIDLib::TSCh szTmp[512];
// Insure only on thread tries to dump at once
::pthread_mutex_lock(&__mtx);
// Create the file and store the handle locally for use
__CreateFile();
if (__fdDump == -1)
{
::pthread_mutex_unlock(&__mtx);
return;
}
// Write out the runtime error header
__WriteLine("--------------------------------------");
__WriteLine("Runtime Error: ");
// Log the common stuff that's logged for all dumps
__WriteStr(" Process: ");
TRawStr::pszConvert(TKrnlSysInfo::pszProcessName(), szTmp, 511);
__WriteLine(szTmp);
__WriteStr(" Thread: ");
TRawStr::pszConvert(pszThreadName, szTmp, 511);
__WriteLine(szTmp);
__WriteLine("\r\nError Information:");
__WriteStr(" Facility: ");
TRawStr::pszConvert(pszFacility, szTmp, 511);
__WriteLine(szTmp);
__WriteStr(" Error: ");
TRawStr::pszConvert(pszError, szTmp, 511);
__WriteLine(szTmp);
if (pszAuxText)
{
__WriteStr(" Aux Error Text: ");
TRawStr::pszConvert(pszAuxText, szTmp, 511);
__WriteLine(szTmp);
}
__WriteStr(" Error Id: ");
__FmtCard4(errcId, szTmp, tCIDLib::ERadices::Dec);
__WriteLine(szTmp);
__WriteStr(" Kernel Error Id: ");
__FmtCard4(errcKrnlId, szTmp, tCIDLib::ERadices::Dec);
__WriteLine(szTmp);
__WriteStr(" Host Error Id: ");
__FmtCard4(errcHostId, szTmp, tCIDLib::ERadices::Dec);
__WriteLine(szTmp);
__WriteStr(" File: ");
TRawStr::pszConvert(pszFile, szTmp, 511);
__WriteLine(szTmp);
__WriteStr(".");
__FmtCard4(c4LineNumber, szTmp, tCIDLib::ERadices::Dec);
__WriteLine(szTmp);
::close(__fdDump);
__fdDump = -1;
::pthread_mutex_unlock(&__mtx);
}
|
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/documentai/v1/document_processor_service.proto
#include "google/cloud/documentai/internal/document_processor_metadata_decorator.h"
#include "google/cloud/common_options.h"
#include "google/cloud/internal/api_client_header.h"
#include "google/cloud/status_or.h"
#include <google/cloud/documentai/v1/document_processor_service.grpc.pb.h>
#include <memory>
namespace google {
namespace cloud {
namespace documentai_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
DocumentProcessorServiceMetadata::DocumentProcessorServiceMetadata(
std::shared_ptr<DocumentProcessorServiceStub> child)
: child_(std::move(child)),
api_client_header_(
google::cloud::internal::ApiClientHeader("generator")) {}
StatusOr<google::cloud::documentai::v1::ProcessResponse>
DocumentProcessorServiceMetadata::ProcessDocument(
grpc::ClientContext& context,
google::cloud::documentai::v1::ProcessRequest const& request) {
SetMetadata(context, "name=" + request.name());
return child_->ProcessDocument(context, request);
}
future<StatusOr<google::longrunning::Operation>>
DocumentProcessorServiceMetadata::AsyncBatchProcessDocuments(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::documentai::v1::BatchProcessRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncBatchProcessDocuments(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DocumentProcessorServiceMetadata::AsyncReviewDocument(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::documentai::v1::ReviewDocumentRequest const& request) {
SetMetadata(*context, "human_review_config=" + request.human_review_config());
return child_->AsyncReviewDocument(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DocumentProcessorServiceMetadata::AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::GetOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncGetOperation(cq, std::move(context), request);
}
future<Status> DocumentProcessorServiceMetadata::AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::CancelOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncCancelOperation(cq, std::move(context), request);
}
void DocumentProcessorServiceMetadata::SetMetadata(
grpc::ClientContext& context, std::string const& request_params) {
context.AddMetadata("x-goog-request-params", request_params);
SetMetadata(context);
}
void DocumentProcessorServiceMetadata::SetMetadata(
grpc::ClientContext& context) {
context.AddMetadata("x-goog-api-client", api_client_header_);
auto const& options = internal::CurrentOptions();
if (options.has<UserProjectOption>()) {
context.AddMetadata("x-goog-user-project",
options.get<UserProjectOption>());
}
auto const& authority = options.get<AuthorityOption>();
if (!authority.empty()) context.set_authority(authority);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace documentai_internal
} // namespace cloud
} // namespace google
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file optimizer_op.cc
* \brief Optimizer operators
* \author Junyuan Xie
*/
#include "./optimizer_op-inl.h"
#include "./elemwise_op_common.h"
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(SGDParam);
DMLC_REGISTER_PARAMETER(SGDMomParam);
DMLC_REGISTER_PARAMETER(MultiSGDParam);
DMLC_REGISTER_PARAMETER(MultiSGDMomParam);
DMLC_REGISTER_PARAMETER(FTMLParam);
DMLC_REGISTER_PARAMETER(AdamParam);
DMLC_REGISTER_PARAMETER(NAGParam);
DMLC_REGISTER_PARAMETER(NAGMomParam);
DMLC_REGISTER_PARAMETER(RMSPropParam);
DMLC_REGISTER_PARAMETER(RMSPropAlexParam);
DMLC_REGISTER_PARAMETER(FtrlParam);
DMLC_REGISTER_PARAMETER(SignSGDParam);
DMLC_REGISTER_PARAMETER(SignumParam);
DMLC_REGISTER_PARAMETER(AdagradParam);
DMLC_REGISTER_PARAMETER(LambUpdatePhaseOneParam);
DMLC_REGISTER_PARAMETER(LambUpdatePhaseTwoParam);
NNVM_REGISTER_OP(signsgd_update)
.describe(R"code(Update function for SignSGD optimizer.
.. math::
g_t = \nabla J(W_{t-1})\\
W_t = W_{t-1} - \eta_t \text{sign}(g_t)
It updates the weights using::
weight = weight - learning_rate * sign(gradient)
.. note::
- sparse ndarray not supported for this optimizer yet.
)code" ADD_FILELINE)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr_parser(ParamParser<SignSGDParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<2, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<FCompute>("FCompute<cpu>", SignSGDUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_arguments(SignSGDParam::__FIELDS__());
NNVM_REGISTER_OP(signum_update)
.describe(R"code(SIGN momentUM (Signum) optimizer.
.. math::
g_t = \nabla J(W_{t-1})\\
m_t = \beta m_{t-1} + (1 - \beta) g_t\\
W_t = W_{t-1} - \eta_t \text{sign}(m_t)
It updates the weights using::
state = momentum * state + (1-momentum) * gradient
weight = weight - learning_rate * sign(state)
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
.. note::
- sparse ndarray not supported for this optimizer yet.
)code" ADD_FILELINE)
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<SignumParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<3, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<3, 1>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2};
})
.set_attr<FCompute>("FCompute<cpu>", SignumUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mom", "NDArray-or-Symbol", "Momentum")
.add_arguments(SignumParam::__FIELDS__());
template <int req>
struct SGDMomStdDnsRspDnsKernel<req, cpu> {
template <typename DType, typename IType, typename RType>
MSHADOW_XINLINE static void Map(int i,
index_t row_length,
DType* out_data,
DType* mom_data,
const DType* weight_data,
const IType* grad_idx,
const DType* grad_data,
const RType* prefix_sum,
const DType clip_gradient,
const DType momentum,
const DType lr,
const DType wd,
const DType rescale_grad) {
const bool non_zero = (i == 0) ? prefix_sum[0] > 0 : prefix_sum[i] > prefix_sum[i - 1];
const index_t row_i = i * row_length;
const RType grad_i = (prefix_sum[i] - 1) * row_length;
for (index_t j = 0; j < row_length; j++) {
const index_t data_i = row_i + j;
const DType grad = non_zero ? grad_data[grad_i + j] : static_cast<DType>(0);
DType grad_rescaled = rescale_grad * grad;
if (clip_gradient >= 0.0f) {
grad_rescaled = mshadow_op::clip::Map(grad_rescaled, clip_gradient);
}
grad_rescaled += wd * weight_data[data_i];
mom_data[data_i] *= momentum;
mom_data[data_i] -= lr * grad_rescaled;
KERNEL_ASSIGN(out_data[data_i], req, weight_data[data_i] + mom_data[data_i]);
}
}
};
/*
* \brief standard momentum update for dense weight on cpu.
* state is expected to be dense, while grad is expected to be row_sparse.
*/
template <>
void SGDMomStdUpdateDnsRspDnsImpl<cpu>(const SGDMomParam& param,
const OpContext& ctx,
const TBlob& weight,
const NDArray& grad,
const TBlob& mom,
const OpReqType& req,
TBlob* out) {
using namespace mxnet_op;
using namespace rowsparse;
using namespace mshadow;
Stream<cpu>* s = ctx.get_stream<cpu>();
if (req == kNullOp)
return;
CHECK_EQ(req, kWriteInplace) << "kWriteInplace is expected for sparse sgd_mom_update";
CHECK_GT(weight.shape_.Size(), 0);
CHECK_GT(mom.shape_.Size(), 0);
MSHADOW_REAL_TYPE_SWITCH(weight.type_flag_, DType, {
MSHADOW_IDX_TYPE_SWITCH(grad.aux_type(kIdx), IType, {
MXNET_ASSIGN_REQ_SWITCH(req, req_type, {
DType* weight_data = weight.dptr<DType>();
const IType* grad_idx = grad.aux_data(kIdx).dptr<IType>();
const DType* grad_val = grad.data().dptr<DType>();
DType* mom_data = mom.dptr<DType>();
DType* out_data = out->dptr<DType>();
const nnvm::dim_t num_rows = weight.shape_[0];
const auto row_length = weight.shape_.ProdShape(1, weight.ndim());
Tensor<cpu, 1, char> workspace = ctx.requested[0].get_space_typed<cpu, 1, char>(
Shape1(num_rows * sizeof(nnvm::dim_t)), s);
nnvm::dim_t* prefix_sum = reinterpret_cast<nnvm::dim_t*>(workspace.dptr_);
// mark row flags
Kernel<set_zero, cpu>::Launch(s, num_rows, prefix_sum);
if (grad.storage_initialized()) {
Kernel<MarkRowFlgKernel, cpu>::Launch(s, grad.aux_shape(kIdx)[0], prefix_sum, grad_idx);
// calculate inclusive prefix sum
for (nnvm::dim_t i = 1; i < num_rows; i++) {
prefix_sum[i] += prefix_sum[i - 1];
}
}
Kernel<SGDMomStdDnsRspDnsKernel<req_type, cpu>, cpu>::Launch(
s,
num_rows,
row_length,
out_data,
mom_data,
weight_data,
grad_idx,
grad_val,
prefix_sum,
static_cast<DType>(param.clip_gradient),
static_cast<DType>(param.momentum),
static_cast<DType>(param.lr),
static_cast<DType>(param.wd),
static_cast<DType>(param.rescale_grad));
});
});
});
}
template <int req>
struct AdamStdDnsRspDnsKernel<req, cpu> {
template <typename DType, typename IType, typename RType>
MSHADOW_XINLINE static void Map(int i,
const nnvm::dim_t row_length,
DType* out_data,
DType* mean_data,
DType* var_data,
const DType* weight_data,
const IType* grad_idx,
const DType* grad_data,
const RType* prefix_sum,
const DType clip_gradient,
const DType beta1,
const DType beta2,
const DType lr,
const DType wd,
const DType epsilon,
const DType rescale_grad) {
using namespace mshadow_op;
const bool non_zero = (i == 0) ? prefix_sum[0] > 0 : prefix_sum[i] > prefix_sum[i - 1];
const index_t row_i = i * row_length;
const RType grad_i = (prefix_sum[i] - 1) * row_length;
for (index_t j = 0; j < row_length; j++) {
const index_t data_i = row_i + j;
DType grad_rescaled = non_zero ? static_cast<DType>(grad_data[grad_i + j] * rescale_grad) :
static_cast<DType>(0);
if (clip_gradient >= 0.0f) {
grad_rescaled = clip::Map(grad_rescaled, clip_gradient);
}
grad_rescaled += weight_data[data_i] * wd;
mean_data[data_i] = beta1 * mean_data[data_i] + (1.f - beta1) * grad_rescaled;
var_data[data_i] = beta2 * var_data[data_i] + (1.f - beta2) * square::Map(grad_rescaled);
KERNEL_ASSIGN(out_data[data_i],
req,
weight_data[data_i] -
lr * mean_data[data_i] / (square_root::Map(var_data[data_i]) + epsilon));
}
}
};
template <>
void AdamStdUpdateDnsRspDnsImpl<cpu>(const AdamParam& param,
const OpContext& ctx,
const TBlob& weight,
const NDArray& grad,
const TBlob& mean,
const TBlob& var,
const OpReqType& req,
TBlob* out) {
using namespace mxnet_op;
using namespace rowsparse;
using namespace mshadow;
Stream<cpu>* s = ctx.get_stream<cpu>();
if (req == kNullOp)
return;
CHECK_EQ(req, kWriteInplace) << "kWriteInplace is expected for sparse adam_update";
CHECK_GT(weight.shape_.Size(), 0);
CHECK_GT(mean.shape_.Size(), 0);
CHECK_GT(var.shape_.Size(), 0);
MSHADOW_REAL_TYPE_SWITCH(weight.type_flag_, DType, {
MSHADOW_IDX_TYPE_SWITCH(grad.aux_type(kIdx), IType, {
MXNET_ASSIGN_REQ_SWITCH(req, req_type, {
const DType* weight_data = weight.dptr<DType>();
const IType* grad_idx = grad.aux_data(kIdx).dptr<IType>();
const DType* grad_val = grad.data().dptr<DType>();
DType* mean_data = mean.dptr<DType>();
DType* var_data = var.dptr<DType>();
DType* out_data = out->dptr<DType>();
nnvm::dim_t num_rows = weight.shape_[0];
nnvm::dim_t row_length = weight.shape_.ProdShape(1, weight.ndim());
Tensor<cpu, 1, char> workspace = ctx.requested[0].get_space_typed<cpu, 1, char>(
Shape1(num_rows * sizeof(nnvm::dim_t)), s);
nnvm::dim_t* prefix_sum = reinterpret_cast<nnvm::dim_t*>(workspace.dptr_);
// mark row flags
Kernel<set_zero, cpu>::Launch(s, num_rows, prefix_sum);
if (grad.storage_initialized()) {
Kernel<MarkRowFlgKernel, cpu>::Launch(s, grad.aux_shape(kIdx)[0], prefix_sum, grad_idx);
// calculate inclusive prefix sum
for (nnvm::dim_t i = 1; i < num_rows; i++) {
prefix_sum[i] += prefix_sum[i - 1];
}
}
Kernel<AdamStdDnsRspDnsKernel<req_type, cpu>, cpu>::Launch(
s,
num_rows,
row_length,
out_data,
mean_data,
var_data,
weight_data,
grad_idx,
grad_val,
prefix_sum,
static_cast<DType>(param.clip_gradient),
static_cast<DType>(param.beta1),
static_cast<DType>(param.beta2),
static_cast<DType>(param.lr),
static_cast<DType>(param.wd),
static_cast<DType>(param.epsilon),
static_cast<DType>(param.rescale_grad));
});
});
});
}
/*!
* \brief Storge type inference function for SGD.
*/
inline bool SGDStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
using namespace common;
const SGDParam& param = nnvm::get<SGDParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 2U);
CHECK_EQ(out_attrs->size(), 1U);
const int weight_stype = in_attrs->at(0);
const int grad_stype = in_attrs->at(1);
bool dispatched = false;
if (!dispatched && ContainsOnlyStorage(*in_attrs, kDefaultStorage)) {
// dns, ... -> dns
dispatched =
storage_type_assign(out_attrs, kDefaultStorage, dispatch_mode, DispatchMode::kFCompute);
}
if (!dispatched && grad_stype == kRowSparseStorage &&
(weight_stype == kRowSparseStorage || weight_stype == kDefaultStorage)) {
// grad's stype = rsp
dispatched = storage_type_assign(out_attrs,
static_cast<NDArrayStorageType>(weight_stype),
dispatch_mode,
DispatchMode::kFComputeEx);
// warn users if lazy_update is turned on
if (dispatched && param.wd != 0 && param.lazy_update)
LogLazyUpdate();
}
if (!dispatched) {
dispatched = dispatch_fallback(out_attrs, dispatch_mode);
}
return dispatched;
}
NNVM_REGISTER_OP(multi_sgd_update)
.describe(R"code(Update function for Stochastic Gradient Descent (SDG) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
)code" ADD_FILELINE)
.set_num_inputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDParam& param = dmlc::get<MultiSGDParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights * 2);
})
.set_num_outputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDParam& param = dmlc::get<MultiSGDParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights);
})
.set_attr_parser(ParamParser<MultiSGDParam>)
.set_attr<mxnet::FInferShape>("FInferShape", MultiSGDShape<MultiSGDParam, 2>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<-1, -1>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
uint32_t num_args =
dmlc::get<MultiSGDParam>(attrs.parsed).num_weights;
std::vector<std::string> ret;
for (uint32_t i = 0; i < num_args; ++i) {
ret.push_back(std::string("weight_") + std::to_string(i));
ret.push_back(std::string("grad_") + std::to_string(i));
}
return ret;
})
.set_attr<FCompute>("FCompute<cpu>", MultiSGDUpdate<cpu, type_identity, 2>)
.add_argument("data", "NDArray-or-Symbol[]", "Weights")
.add_arguments(MultiSGDParam::__FIELDS__());
NNVM_REGISTER_OP(multi_sgd_mom_update)
.describe(R"code(Momentum update function for Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \alpha * \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \alpha * \nabla J(W_{t-1})\\
W_t = W_{t-1} + v_t
It updates the weights using::
v = momentum * v - learning_rate * gradient
weight += v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
)code" ADD_FILELINE)
.set_num_inputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDMomParam& param = dmlc::get<MultiSGDMomParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights * 3);
})
.set_num_outputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDMomParam& param = dmlc::get<MultiSGDMomParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights);
})
.set_attr_parser(ParamParser<MultiSGDMomParam>)
.set_attr<mxnet::FInferShape>("FInferShape", MultiSGDShape<MultiSGDMomParam, 3>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<-1, -1>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
uint32_t num_args =
dmlc::get<MultiSGDParam>(attrs.parsed).num_weights;
std::vector<std::string> ret;
for (uint32_t i = 0; i < num_args; ++i) {
ret.push_back(std::string("weight_") + std::to_string(i));
ret.push_back(std::string("grad_") + std::to_string(i));
ret.push_back(std::string("mom_") + std::to_string(i));
}
return ret;
})
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
std::vector<uint32_t> ret;
const MultiSGDMomParam& param =
dmlc::get<MultiSGDMomParam>(attrs.parsed);
ret.reserve(param.num_weights);
for (int i = 0; i < param.num_weights; ++i) {
ret.push_back(i * 3 + 2);
}
return ret;
})
.set_attr<FCompute>("FCompute<cpu>", MultiSGDMomUpdate<cpu, type_identity, 3>)
.add_argument("data", "NDArray-or-Symbol[]", "Weights, gradients and momentum")
.add_arguments(MultiSGDMomParam::__FIELDS__());
NNVM_REGISTER_OP(multi_mp_sgd_update)
.describe(
R"code(Update function for multi-precision Stochastic Gradient Descent (SDG) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
)code" ADD_FILELINE)
.set_num_inputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDParam& param = dmlc::get<MultiSGDParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights * 3);
})
.set_num_outputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDParam& param = dmlc::get<MultiSGDParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights);
})
.set_attr_parser(ParamParser<MultiSGDParam>)
.set_attr<mxnet::FInferShape>("FInferShape", MultiSGDShape<MultiSGDParam, 3>)
.set_attr<nnvm::FInferType>("FInferType", MP_MultiSGD_InferType<MultiSGDParam, 3, 1>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
uint32_t num_args =
dmlc::get<MultiSGDParam>(attrs.parsed).num_weights;
std::vector<std::string> ret;
for (uint32_t i = 0; i < num_args; ++i) {
ret.push_back(std::string("weight_") + std::to_string(i));
ret.push_back(std::string("grad_") + std::to_string(i));
ret.push_back(std::string("weight32_") +
std::to_string(i));
}
return ret;
})
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
std::vector<uint32_t> ret;
const MultiSGDParam& param =
dmlc::get<MultiSGDParam>(attrs.parsed);
ret.reserve(param.num_weights);
for (int i = 0; i < param.num_weights; ++i) {
ret.push_back(i * 3 + 2);
}
return ret;
})
.set_attr<FCompute>("FCompute<cpu>", MultiSGDUpdate<cpu, single_precision, 3>)
.add_argument("data", "NDArray-or-Symbol[]", "Weights")
.add_arguments(MultiSGDParam::__FIELDS__());
NNVM_REGISTER_OP(multi_mp_sgd_mom_update)
.describe(
R"code(Momentum update function for multi-precision Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \alpha * \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \alpha * \nabla J(W_{t-1})\\
W_t = W_{t-1} + v_t
It updates the weights using::
v = momentum * v - learning_rate * gradient
weight += v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
)code" ADD_FILELINE)
.set_num_inputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDMomParam& param = dmlc::get<MultiSGDMomParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights * 4);
})
.set_num_outputs([](const nnvm::NodeAttrs& attrs) {
const MultiSGDMomParam& param = dmlc::get<MultiSGDMomParam>(attrs.parsed);
return static_cast<uint32_t>(param.num_weights);
})
.set_attr_parser(ParamParser<MultiSGDMomParam>)
.set_attr<mxnet::FInferShape>("FInferShape", MultiSGDShape<MultiSGDMomParam, 4>)
.set_attr<nnvm::FInferType>("FInferType", MP_MultiSGD_InferType<MultiSGDMomParam, 4, 2>)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
uint32_t num_args =
dmlc::get<MultiSGDMomParam>(attrs.parsed).num_weights;
std::vector<std::string> ret;
for (uint32_t i = 0; i < num_args; ++i) {
ret.push_back(std::string("weight_") + std::to_string(i));
ret.push_back(std::string("grad_") + std::to_string(i));
ret.push_back(std::string("mom_") + std::to_string(i));
ret.push_back(std::string("weight32_") +
std::to_string(i));
}
return ret;
})
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
std::vector<uint32_t> ret;
const MultiSGDMomParam& param =
dmlc::get<MultiSGDMomParam>(attrs.parsed);
for (int i = 0; i < param.num_weights; ++i) {
ret.push_back(i * 4 + 2);
ret.push_back(i * 4 + 3);
}
return ret;
})
.set_attr<FCompute>("FCompute<cpu>", MultiSGDMomUpdate<cpu, single_precision, 4>)
.add_argument("data", "NDArray-or-Symbol[]", "Weights")
.add_arguments(MultiSGDMomParam::__FIELDS__());
NNVM_REGISTER_OP(sgd_update)
MXNET_ADD_SPARSE_OP_ALIAS(sgd_update)
.describe(R"code(Update function for Stochastic Gradient Descent (SGD) optimizer.
It updates the weights using::
weight = weight - learning_rate * (gradient + wd * weight)
However, if gradient is of ``row_sparse`` storage type and ``lazy_update`` is True,
only the row slices whose indices appear in grad.indices are updated::
for row in gradient.indices:
weight[row] = weight[row] - learning_rate * (gradient[row] + wd * weight[row])
)code" ADD_FILELINE)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr_parser(ParamParser<SGDParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<2, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>)
.set_attr<FInferStorageType>("FInferStorageType", SGDStorageType)
.set_attr<FCompute>("FCompute<cpu>", SGDUpdate<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", SGDUpdateEx<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_arguments(SGDParam::__FIELDS__());
NNVM_REGISTER_OP(sgd_mom_update)
MXNET_ADD_SPARSE_OP_ALIAS(sgd_mom_update)
.describe(R"code(Momentum update function for Stochastic Gradient Descent (SGD) optimizer.
Momentum update has better convergence rates on neural networks. Mathematically it looks
like below:
.. math::
v_1 = \alpha * \nabla J(W_0)\\
v_t = \gamma v_{t-1} - \alpha * \nabla J(W_{t-1})\\
W_t = W_{t-1} + v_t
It updates the weights using::
v = momentum * v - learning_rate * gradient
weight += v
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.
However, if grad's storage type is ``row_sparse``, ``lazy_update`` is True and weight's storage
type is the same as momentum's storage type,
only the row slices whose indices appear in grad.indices are updated (for both weight and momentum)::
for row in gradient.indices:
v[row] = momentum[row] * v[row] - learning_rate * gradient[row]
weight[row] += v[row]
)code" ADD_FILELINE)
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<SGDMomParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<3, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<3, 1>)
.set_attr<FInferStorageType>("FInferStorageType", StdOptStorageType<1, SGDMomParam>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2};
})
.set_attr<FResourceRequestEx>("FResourceRequestEx",
[](const NodeAttrs& attrs,
const int dev_mask,
const DispatchMode dispatch_mode) {
std::vector<ResourceRequest> request;
if (dispatch_mode == DispatchMode::kFComputeEx) {
request.emplace_back(ResourceRequest::kTempSpace);
}
return request;
})
.set_attr<FCompute>("FCompute<cpu>", SGDMomUpdate<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", SGDMomUpdateEx<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mom", "NDArray-or-Symbol", "Momentum")
.add_arguments(SGDMomParam::__FIELDS__());
NNVM_REGISTER_OP(mp_sgd_update)
.describe("Updater function for multi-precision sgd optimizer")
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<SGDParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<3, 1>)
.set_attr<nnvm::FInferType>("FInferType", MP_InferType<2, 1, 3>)
.set_attr<FCompute>("FCompute<cpu>", MP_SGDUpdate<cpu>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2};
})
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "gradient")
.add_argument("weight32", "NDArray-or-Symbol", "Weight32")
.add_arguments(SGDParam::__FIELDS__());
NNVM_REGISTER_OP(mp_sgd_mom_update)
.describe("Updater function for multi-precision sgd optimizer")
.set_num_inputs(4)
.set_num_outputs(1)
.set_attr_parser(ParamParser<SGDMomParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<4, 1>)
.set_attr<nnvm::FInferType>("FInferType", MP_InferType<2, 1, 4>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3};
})
.set_attr<FCompute>("FCompute<cpu>", MP_SGDMomUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mom", "NDArray-or-Symbol", "Momentum")
.add_argument("weight32", "NDArray-or-Symbol", "Weight32")
.add_arguments(SGDMomParam::__FIELDS__());
NNVM_REGISTER_OP(ftml_update)
.describe(R"code(The FTML optimizer described in
*FTML - Follow the Moving Leader in Deep Learning*,
available at http://proceedings.mlr.press/v70/zheng17a/zheng17a.pdf.
.. math::
g_t = \nabla J(W_{t-1})\\
v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\
d_t = \frac{ 1 - \beta_1^t }{ \eta_t } (\sqrt{ \frac{ v_t }{ 1 - \beta_2^t } } + \epsilon)
\sigma_t = d_t - \beta_1 d_{t-1}
z_t = \beta_1 z_{ t-1 } + (1 - \beta_1^t) g_t - \sigma_t W_{t-1}
W_t = - \frac{ z_t }{ d_t }
)code" ADD_FILELINE)
.set_num_inputs(5)
.set_num_outputs(1)
.set_attr_parser(ParamParser<FTMLParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<5, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<5, 1>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3, 4};
})
.set_attr<FCompute>("FCompute<cpu>", FTMLUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("d", "NDArray-or-Symbol", "Internal state ``d_t``")
.add_argument("v", "NDArray-or-Symbol", "Internal state ``v_t``")
.add_argument("z", "NDArray-or-Symbol", "Internal state ``z_t``")
.add_arguments(FTMLParam::__FIELDS__());
NNVM_REGISTER_OP(adam_update)
MXNET_ADD_SPARSE_OP_ALIAS(adam_update)
.describe(R"code(Update function for Adam optimizer. Adam is seen as a generalization
of AdaGrad.
Adam update consists of the following steps, where g represents gradient and m, v
are 1st and 2nd order moment estimates (mean and variance).
.. math::
g_t = \nabla J(W_{t-1})\\
m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t\\
v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\
W_t = W_{t-1} - \alpha \frac{ m_t }{ \sqrt{ v_t } + \epsilon }
It updates the weights using::
m = beta1*m + (1-beta1)*grad
v = beta2*v + (1-beta2)*(grad**2)
w += - learning_rate * m / (sqrt(v) + epsilon)
However, if grad's storage type is ``row_sparse``, ``lazy_update`` is True and the storage
type of weight is the same as those of m and v,
only the row slices whose indices appear in grad.indices are updated (for w, m and v)::
for row in grad.indices:
m[row] = beta1*m[row] + (1-beta1)*grad[row]
v[row] = beta2*v[row] + (1-beta2)*(grad[row]**2)
w[row] += - learning_rate * m[row] / (sqrt(v[row]) + epsilon)
)code" ADD_FILELINE)
.set_num_inputs(4)
.set_num_outputs(1)
.set_attr_parser(ParamParser<AdamParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<4, 1>)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<4, 1>)
.set_attr<FInferStorageType>("FInferStorageType", StdOptStorageType<2, AdamParam>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3};
})
.set_attr<FCompute>("FCompute<cpu>", AdamUpdate<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", AdamUpdateEx<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mean", "NDArray-or-Symbol", "Moving mean")
.add_argument("var", "NDArray-or-Symbol", "Moving variance")
.add_arguments(AdamParam::__FIELDS__());
NNVM_REGISTER_OP(nag_mom_update)
.describe(R"code(Update function for Nesterov Accelerated Gradient( NAG) optimizer.
It updates the weights using the following formula,
.. math::
v_t = \gamma v_{t-1} + \eta * \nabla J(W_{t-1} - \gamma v_{t-1})\\
W_t = W_{t-1} - v_t
Where
:math:`\eta` is the learning rate of the optimizer
:math:`\gamma` is the decay rate of the momentum estimate
:math:`\v_t` is the update vector at time step `t`
:math:`\W_t` is the weight vector at time step `t`
)code" ADD_FILELINE)
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<NAGMomParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<3, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<3, 1>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2};
})
.set_attr<FCompute>("FCompute<cpu>", NAGMomUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mom", "NDArray-or-Symbol", "Momentum")
.add_arguments(NAGMomParam::__FIELDS__());
NNVM_REGISTER_OP(mp_nag_mom_update)
.describe(
R"code(Update function for multi-precision Nesterov Accelerated Gradient( NAG) optimizer.
)code" ADD_FILELINE)
.set_num_inputs(4)
.set_num_outputs(1)
.set_attr_parser(ParamParser<NAGMomParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<4, 1>)
.set_attr<nnvm::FInferType>("FInferType", MP_InferType<2, 1, 4>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3};
})
.set_attr<FCompute>("FCompute<cpu>", MP_NAGMomUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mom", "NDArray-or-Symbol", "Momentum")
.add_argument("weight32", "NDArray-or-Symbol", "Weight32")
.add_arguments(NAGMomParam::__FIELDS__());
NNVM_REGISTER_OP(rmsprop_update)
.describe(R"code(Update function for `RMSProp` optimizer.
`RMSprop` is a variant of stochastic gradient descent where the gradients are
divided by a cache which grows with the sum of squares of recent gradients?
`RMSProp` is similar to `AdaGrad`, a popular variant of `SGD` which adaptively
tunes the learning rate of each parameter. `AdaGrad` lowers the learning rate for
each parameter monotonically over the course of training.
While this is analytically motivated for convex optimizations, it may not be ideal
for non-convex problems. `RMSProp` deals with this heuristically by allowing the
learning rates to rebound as the denominator decays over time.
Define the Root Mean Square (RMS) error criterion of the gradient as
:math:`RMS[g]_t = \sqrt{E[g^2]_t + \epsilon}`, where :math:`g` represents
gradient and :math:`E[g^2]_t` is the decaying average over past squared gradient.
The :math:`E[g^2]_t` is given by:
.. math::
E[g^2]_t = \rho * E[g^2]_{t-1} + (1-\rho) * g_t^2
The update step is
.. math::
\theta_{t+1} = \theta_t - \frac{\eta}{RMS[g]_t} g_t
The RMSProp code follows the version in
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
Tieleman & Hinton, 2012.
Hinton suggests the momentum term :math:`\rho` to be 0.9 and the learning rate
:math:`\eta` to be 0.001.
)code" ADD_FILELINE)
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<RMSPropParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<3, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<3, 1>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2};
})
.set_attr<FCompute>("FCompute<cpu>", RMSPropUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("n", "NDArray-or-Symbol", "n")
.add_arguments(RMSPropParam::__FIELDS__());
NNVM_REGISTER_OP(rmspropalex_update)
.describe(R"code(Update function for RMSPropAlex optimizer.
`RMSPropAlex` is non-centered version of `RMSProp`.
Define :math:`E[g^2]_t` is the decaying average over past squared gradient and
:math:`E[g]_t` is the decaying average over past gradient.
.. math::
E[g^2]_t = \rho * E[g^2]_{t-1} + (1 - \rho) * g_t^2\\
E[g]_t = \rho * E[g]_{t-1} + (1 - \rho) * g_t\\
momentum_t = \gamma * momentum_{t-1} - \frac{\eta}{\sqrt{E[g^2]_t - E[g]_t^2 + \epsilon}} g_t\\
The update step is
.. math::
\theta_{t+1} = \theta_t + momentum_t
The RMSPropAlex code follows the version in
http://arxiv.org/pdf/1308.0850v5.pdf Eq(38) - Eq(45) by Alex Graves, 2013.
Graves suggests the momentum term :math:`\rho` to be 0.95, :math:`\gamma`
to be 0.9 and the learning rate :math:`\eta` to be 0.0001.
)code" ADD_FILELINE)
.set_num_inputs(5)
.set_num_outputs(1)
.set_attr_parser(ParamParser<RMSPropAlexParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<5, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<5, 1>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3, 4};
})
.set_attr<FCompute>("FCompute<cpu>", RMSPropAlexUpdate<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("n", "NDArray-or-Symbol", "n")
.add_argument("g", "NDArray-or-Symbol", "g")
.add_argument("delta", "NDArray-or-Symbol", "delta")
.add_arguments(RMSPropAlexParam::__FIELDS__());
NNVM_REGISTER_OP(ftrl_update)
MXNET_ADD_SPARSE_OP_ALIAS(ftrl_update)
.describe(R"code(Update function for Ftrl optimizer.
Referenced from *Ad Click Prediction: a View from the Trenches*, available at
http://dl.acm.org/citation.cfm?id=2488200.
It updates the weights using::
rescaled_grad = clip(grad * rescale_grad, clip_gradient)
z += rescaled_grad - (sqrt(n + rescaled_grad**2) - sqrt(n)) * weight / learning_rate
n += rescaled_grad**2
w = (sign(z) * lamda1 - z) / ((beta + sqrt(n)) / learning_rate + wd) * (abs(z) > lamda1)
If w, z and n are all of ``row_sparse`` storage type,
only the row slices whose indices appear in grad.indices are updated (for w, z and n)::
for row in grad.indices:
rescaled_grad[row] = clip(grad[row] * rescale_grad, clip_gradient)
z[row] += rescaled_grad[row] - (sqrt(n[row] + rescaled_grad[row]**2) - sqrt(n[row])) * weight[row] / learning_rate
n[row] += rescaled_grad[row]**2
w[row] = (sign(z[row]) * lamda1 - z[row]) / ((beta + sqrt(n[row])) / learning_rate + wd) * (abs(z[row]) > lamda1)
)code" ADD_FILELINE)
.set_num_inputs(4)
.set_num_outputs(1)
.set_attr_parser(ParamParser<FtrlParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<4, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<4, 1>)
.set_attr<FInferStorageType>("FInferStorageType", ElemwiseStorageType<4, 1, false, true, false>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3};
})
.set_attr<FCompute>("FCompute<cpu>", FtrlUpdate<cpu>)
.set_attr<FComputeEx>("FComputeEx<cpu>", FtrlUpdateEx<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("z", "NDArray-or-Symbol", "z")
.add_argument("n", "NDArray-or-Symbol", "Square of grad")
.add_arguments(FtrlParam::__FIELDS__());
NNVM_REGISTER_OP(_sparse_adagrad_update)
.describe(R"code(Update function for AdaGrad optimizer.
Referenced from *Adaptive Subgradient Methods for Online Learning and Stochastic Optimization*,
and available at http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf.
Updates are applied by::
rescaled_grad = clip(grad * rescale_grad, clip_gradient)
history = history + square(rescaled_grad)
w = w - learning_rate * rescaled_grad / sqrt(history + epsilon)
Note that non-zero values for the weight decay option are not supported.
)code" ADD_FILELINE)
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<AdagradParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<3, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<3, 1>)
.set_attr<FInferStorageType>("FInferStorageType", AdagradStorageType)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2};
})
.set_attr<FComputeEx>("FComputeEx<cpu>", AdagradUpdateEx<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("history", "NDArray-or-Symbol", "History")
.add_arguments(AdagradParam::__FIELDS__());
NNVM_REGISTER_OP(lamb_update_phase1)
.describe(R"code(Phase I of lamb update it performs the following operations and returns g:.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
grad = grad * rescale_grad
if (grad < -clip_gradient)
then
grad = -clip_gradient
if (grad > clip_gradient)
then
grad = clip_gradient
mean = beta1 * mean + (1 - beta1) * grad;
variance = beta2 * variance + (1. - beta2) * grad ^ 2;
if (bias_correction)
then
mean_hat = mean / (1. - beta1^t);
var_hat = var / (1 - beta2^t);
g = mean_hat / (var_hat^(1/2) + epsilon) + wd * weight;
else
g = mean / (var_data^(1/2) + epsilon) + wd * weight;
\end{gather*}
)code" ADD_FILELINE)
.set_num_inputs(4)
.set_num_outputs(1)
.set_attr_parser(ParamParser<LambUpdatePhaseOneParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<4, 1>)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<4, 1>)
.set_attr<FCompute>("FCompute<cpu>", LambUpdatePhaseOne<cpu>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3};
})
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mean", "NDArray-or-Symbol", "Moving mean")
.add_argument("var", "NDArray-or-Symbol", "Moving variance")
.add_arguments(LambUpdatePhaseOneParam::__FIELDS__());
NNVM_REGISTER_OP(lamb_update_phase2)
.describe(R"code(Phase II of lamb update it performs the following operations and updates grad.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
if (lower_bound >= 0)
then
r1 = max(r1, lower_bound)
if (upper_bound >= 0)
then
r1 = max(r1, upper_bound)
if (r1 == 0 or r2 == 0)
then
lr = lr
else
lr = lr * (r1/r2)
weight = weight - lr * g
\end{gather*}
)code" ADD_FILELINE)
.set_num_inputs(4)
.set_num_outputs(1)
.set_attr_parser(ParamParser<LambUpdatePhaseTwoParam>)
.set_attr<mxnet::FInferShape>("FInferShape", LambUpdatePhaseTwoShape)
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<4, 1>)
.set_attr<FCompute>("FCompute<cpu>", LambUpdatePhaseTwo<cpu>)
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("g", "NDArray-or-Symbol", "Output of lamb_update_phase 1")
.add_argument("r1", "NDArray-or-Symbol", "r1")
.add_argument("r2", "NDArray-or-Symbol", "r2")
.add_arguments(LambUpdatePhaseTwoParam::__FIELDS__());
NNVM_REGISTER_OP(mp_lamb_update_phase1)
.describe(R"code(Mixed Precision version of Phase I of lamb update
it performs the following operations and returns g:.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
grad32 = grad(float16) * rescale_grad
if (grad < -clip_gradient)
then
grad = -clip_gradient
if (grad > clip_gradient)
then
grad = clip_gradient
mean = beta1 * mean + (1 - beta1) * grad;
variance = beta2 * variance + (1. - beta2) * grad ^ 2;
if (bias_correction)
then
mean_hat = mean / (1. - beta1^t);
var_hat = var / (1 - beta2^t);
g = mean_hat / (var_hat^(1/2) + epsilon) + wd * weight32;
else
g = mean / (var_data^(1/2) + epsilon) + wd * weight32;
\end{gather*}
)code" ADD_FILELINE)
.set_num_inputs(5)
.set_num_outputs(1)
.set_attr_parser(ParamParser<LambUpdatePhaseOneParam>)
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<5, 1>)
.set_attr<nnvm::FInferType>("FInferType", MPLambPhaseOneType<2, 1, 5>)
.set_attr<FCompute>("FCompute<cpu>", MPLambUpdatePhaseOne<cpu>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{2, 3};
})
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("grad", "NDArray-or-Symbol", "Gradient")
.add_argument("mean", "NDArray-or-Symbol", "Moving mean")
.add_argument("var", "NDArray-or-Symbol", "Moving variance")
.add_argument("weight32", "NDArray-or-Symbol", "Weight32")
.add_arguments(LambUpdatePhaseOneParam::__FIELDS__());
NNVM_REGISTER_OP(mp_lamb_update_phase2)
.describe(R"code(Mixed Precision version Phase II of lamb update
it performs the following operations and updates grad.
Link to paper: https://arxiv.org/pdf/1904.00962.pdf
.. math::
\begin{gather*}
if (lower_bound >= 0)
then
r1 = max(r1, lower_bound)
if (upper_bound >= 0)
then
r1 = max(r1, upper_bound)
if (r1 == 0 or r2 == 0)
then
lr = lr
else
lr = lr * (r1/r2)
weight32 = weight32 - lr * g
weight(float16) = weight32
\end{gather*}
)code" ADD_FILELINE)
.set_num_inputs(5)
.set_num_outputs(1)
.set_attr_parser(ParamParser<LambUpdatePhaseTwoParam>)
.set_attr<mxnet::FInferShape>("FInferShape", MPLambUpdatePhaseTwoShape)
.set_attr<nnvm::FInferType>("FInferType", MP_InferType<1, 1, 5>)
.set_attr<FCompute>("FCompute<cpu>", MPLambUpdatePhaseTwo<cpu>)
.set_attr<nnvm::FMutateInputs>("FMutateInputs",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<uint32_t>{4};
})
.add_argument("weight", "NDArray-or-Symbol", "Weight")
.add_argument("g", "NDArray-or-Symbol", "Output of mp_lamb_update_phase 1")
.add_argument("r1", "NDArray-or-Symbol", "r1")
.add_argument("r2", "NDArray-or-Symbol", "r2")
.add_argument("weight32", "NDArray-or-Symbol", "Weight32")
.add_arguments(LambUpdatePhaseTwoParam::__FIELDS__());
} // namespace op
} // namespace mxnet
|
/*
* DIF Template Manager
*
* Eduard Grasa <eduard.grasa@i2cat.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include <dirent.h>
#include <errno.h>
#include <poll.h>
#include <sys/inotify.h>
#define RINA_PREFIX "ipcm.dif-template-manager"
#include <librina/logs.h>
#include "configuration.h"
#include "dif-template-manager.h"
#include "ipcm.h"
using namespace std;
namespace rinad {
//Class DIFConfigFolderMonitor
DIFConfigFolderMonitor::DIFConfigFolderMonitor(const std::string& folder,
DIFTemplateManager * dtm,
DIFAllocator * da) :
rina::SimpleThread(std::string("dif-config-folder-monitor"), false)
{
folder_name = folder;
stop = false;
dif_template_manager = dtm;
dif_allocator = da;
}
DIFConfigFolderMonitor::~DIFConfigFolderMonitor() throw()
{
}
void DIFConfigFolderMonitor::do_stop()
{
rina::ScopedLock g(lock);
stop = true;
}
bool DIFConfigFolderMonitor::has_to_stop()
{
rina::ScopedLock g(lock);
return stop;
}
static bool str_ends_with(const std::string& str, const std::string& suffix)
{
if (suffix.size() > str.size()) {
return false;
}
return std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
}
void DIFConfigFolderMonitor::process_events(int fd)
{
char buf[4096]
__attribute__ ((aligned(__alignof__(struct inotify_event))));
const struct inotify_event *event;
int i;
ssize_t len;
char *ptr;
std::stringstream ss;
DIFTemplate * dif_template;
for (;;) {
len = read(fd, buf, sizeof buf);
if (len == -1 && errno != EAGAIN) {
LOG_ERR("Problems reading inotify file descriptor");
return;
}
if (len <= 0)
return;
for (ptr = buf; ptr < buf + len;
ptr += sizeof(struct inotify_event) + event->len) {
event = (const struct inotify_event *) ptr;
std::string file_name = std::string(event->name);
if (file_name == DIFAllocator::STATIC_DIF_ALLOCATOR_FILE_NAME) {
dif_allocator->update_directory_contents();
continue;
}
if (! str_ends_with(file_name, ".dif")) {
continue;
}
if (event->mask & IN_CLOSE_WRITE) {
LOG_DBG("The file of DIF template %s has been modified.",
event->name);
ss << folder_name << "/" << file_name;
dif_template = parse_dif_template(ss.str(), file_name);
ss.str(std::string());
if (dif_template != 0) {
//TODO augment dif_template with the defaults
dif_template_manager->add_dif_template(file_name, dif_template);
}
}
if (event->mask & IN_DELETE) {
LOG_DBG("The file of DIF template %s has been deleted.",
event->name);
dif_template_manager->remove_dif_template(file_name);
}
}
}
}
int DIFConfigFolderMonitor::run()
{
int fd;
int wd;
int pollnum;
struct pollfd fds[1];
LOG_DBG("DIF Template monitor started, monitoring folder %s",
folder_name.c_str());
fd = inotify_init1(IN_NONBLOCK);
if (fd == -1) {
LOG_ERR("Error initializing inotify, stopping DIF template monitor");
return -1;
}
wd = inotify_add_watch(fd, folder_name.c_str(), IN_CLOSE_WRITE | IN_DELETE);
if (wd == -1) {
LOG_ERR("Error adding a watch, stopping DIF template monitor");
close(fd);
return -1;
}
fds[0].fd = fd;
fds[0].events = POLLIN;
while (!has_to_stop()) {
pollnum = poll(fds, 1, 1000);
if (pollnum == EINVAL) {
LOG_ERR("Poll returned EINVAL, stopping DIF template monitor");
close(fd);
return -1;
}
if (pollnum <= 0) {
//No changes during this period or error that can be ignored
continue;
}
if (fds[0].revents & POLLIN) {
process_events(fd);
}
}
/* Close inotify file descriptor */
close(fd);
LOG_DBG("DIF Template Manager stopped");
return 0;
}
//Class DIF Template Manager
const std::string DIFTemplateManager::DEFAULT_TEMPLATE_NAME = "default.dif";
DIFTemplateManager::DIFTemplateManager(const std::string& folder,
DIFAllocator * dif_allocator)
{
stringstream ss;
std::string::size_type pos = folder.rfind("/");
if (pos == std::string::npos) {
ss << ".";
} else {
ss << folder.substr(0, pos);
}
folder_name = ss.str();
LOG_INFO("Template folder: %s", folder_name.c_str());
default_template = 0;
//load current templates from template folder
if (load_initial_dif_templates() != 0) {
return;
}
//Create a thread that monitors the DIF template folder when required
monitor = new DIFConfigFolderMonitor(folder_name,
this,
dif_allocator);
monitor->start();
}
DIFTemplateManager::~DIFTemplateManager()
{
void * status;
if (monitor) {
monitor->do_stop();
monitor->join(&status);
delete monitor;
}
// Destroy all DIF templates in the map
for (std::map<std::string, rinad::DIFTemplate *>::iterator it = dif_templates.begin();
it != dif_templates.end(); ++it){
delete it->second;
}
}
int DIFTemplateManager::load_initial_dif_templates()
{
DIR *dirp;
struct dirent *dp;
DIFTemplate * dif_template;
std::string file_name;
std::stringstream ss;
std::list<rinad::DIFTemplate *> templates;
if ((dirp = opendir(folder_name.c_str())) == NULL) {
LOG_ERR("Failed to open folder %s", folder_name.c_str());
return -1;
}
do {
errno = 0;
if ((dp = readdir(dirp)) != NULL) {
if (! str_ends_with(std::string(dp->d_name), ".dif")) {
continue;
}
LOG_DBG("Found DIF template file called: %s", dp->d_name);
file_name = std::string(dp->d_name);
ss << folder_name << "/" << file_name;
dif_template = parse_dif_template(ss.str(), file_name);
ss.str(std::string());
if (strcmp(dp->d_name, DEFAULT_TEMPLATE_NAME.c_str()) == 0) {
LOG_DBG("Default DIF template found");
default_template = dif_template;
add_dif_template(file_name, dif_template);
} else {
templates.push_back(dif_template);
}
}
} while (dp != NULL);
closedir(dirp);
//Add all templates, cannot be done before because first we need to add
//the default template (if present)
for (std::list<rinad::DIFTemplate *>::iterator it = templates.begin();
it != templates.end(); ++it) {
add_dif_template((*it)->templateName, *it);
}
if (!default_template) {
LOG_WARN("Default DIF template not present");
}
return 0;
}
int DIFTemplateManager::get_dif_template(const std::string& name, rinad::DIFTemplate& dif_template)
{
rina::ReadScopedLock g(templates_lock);
std::map<std::string, rinad::DIFTemplate*>::iterator it = dif_templates.find(name);
if (it == dif_templates.end()) {
LOG_ERR("Could not find DIF template with name %s", name.c_str());
return -1;
} else {
dif_template = *(it->second);
return 0;
}
}
void DIFTemplateManager::augment_dif_template(rinad::DIFTemplate * dif_template)
{
if (!default_template || dif_template->templateName == DEFAULT_TEMPLATE_NAME ||
dif_template->difType != rina::NORMAL_IPC_PROCESS) {
return;
}
if (dif_template->dataTransferConstants.address_length_ == 0) {
dif_template->dataTransferConstants = default_template->dataTransferConstants;
}
if (dif_template->qosCubes.size() == 0) {
for (std::list<rina::QoSCube>::iterator it = default_template->qosCubes.begin();
it != default_template->qosCubes.end(); ++it) {
dif_template->qosCubes.push_back(rina::QoSCube(*it));
}
}
if (dif_template->etConfiguration.policy_set_.name_ == std::string()) {
dif_template->etConfiguration = default_template->etConfiguration;
}
if (dif_template->rmtConfiguration.pft_conf_.policy_set_.name_ == std::string()) {
dif_template->rmtConfiguration.pft_conf_ = default_template->rmtConfiguration.pft_conf_;
}
if (dif_template->rmtConfiguration.policy_set_.name_ == std::string()) {
dif_template->rmtConfiguration = default_template->rmtConfiguration;
}
if (dif_template->routingConfiguration.policy_set_.name_ == std::string()) {
dif_template->routingConfiguration = default_template->routingConfiguration;
}
if (dif_template->nsmConfiguration.policy_set_.name_ == std::string()) {
dif_template->nsmConfiguration = default_template->nsmConfiguration;
}
if (dif_template->faConfiguration.policy_set_.name_ == std::string()) {
dif_template->faConfiguration = default_template->faConfiguration;
}
if (dif_template->raConfiguration.pduftg_conf_.policy_set_.name_ == std::string()) {
dif_template->raConfiguration = default_template->raConfiguration;
}
if (dif_template->knownIPCProcessAddresses.size() == 0) {
for (std::list<rinad::KnownIPCProcessAddress>::iterator it =
default_template->knownIPCProcessAddresses.begin();
it != default_template->knownIPCProcessAddresses.end(); ++it) {
dif_template->knownIPCProcessAddresses.push_back(rinad::KnownIPCProcessAddress(*it));
}
}
if (dif_template->addressPrefixes.size() == 0) {
for (std::list<rinad::AddressPrefixConfiguration>::iterator it =
default_template->addressPrefixes.begin();
it != default_template->addressPrefixes.end(); ++it) {
dif_template->addressPrefixes.push_back(rinad::AddressPrefixConfiguration(*it));
}
}
if (dif_template->secManConfiguration.policy_set_.name_ == std::string()) {
dif_template->secManConfiguration = default_template->secManConfiguration;
}
if (dif_template->configParameters.size() == 0 && default_template->configParameters.size() != 0) {
for (std::map<std::string, std::string>::iterator it =
default_template->configParameters.begin();
it != default_template->configParameters.end(); ++it) {
dif_template->configParameters[it->first] = it->second;
}
}
}
void DIFTemplateManager::add_dif_template(const std::string& name,
rinad::DIFTemplate * dif_template)
{
if (!dif_template) {
LOG_ERR("Cannot add a bogus dif_template");
return;
}
rina::WriteScopedLock g(templates_lock);
//Augment dif_template with default_template
augment_dif_template(dif_template);
//If the template already exists destroy the old version
internal_remove_dif_template(name);
dif_templates[name] = dif_template;
if (name == DEFAULT_TEMPLATE_NAME) {
default_template = dif_template;
}
LOG_INFO("Added or modified DIF template called: %s", name.c_str());
}
void DIFTemplateManager::remove_dif_template(const std::string& name)
{
rina::WriteScopedLock g(templates_lock);
internal_remove_dif_template(name);
if (name == DEFAULT_TEMPLATE_NAME) {
LOG_WARN("Default DIF template removed");
default_template = 0;
}
}
void DIFTemplateManager::internal_remove_dif_template(const std::string& name)
{
std::map<std::string, rinad::DIFTemplate*>::iterator it = dif_templates.find(name);
if (it != dif_templates.end()) {
dif_templates.erase(name);
delete it->second;
LOG_INFO("Removed DIF template called: %s", name.c_str());
}
}
void DIFTemplateManager::get_all_dif_templates(std::list<rinad::DIFTemplate>& out_templates)
{
std::map<std::string, rinad::DIFTemplate*>::iterator it;
rina::ReadScopedLock g(templates_lock);
for (it = dif_templates.begin(); it != dif_templates.end(); ++it) {
out_templates.push_back(*(it->second));
}
}
} //namespace rinad
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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 <graphene/app/application.hpp>
#include <graphene/witness/witness.hpp>
#include <graphene/account_history/account_history_plugin.hpp>
#include <graphene/crosschain/crosschain_transaction_record_plugin.hpp>
#include <graphene/transaction/transaction_plugin.hpp>
#include <fc/exception/exception.hpp>
#include <fc/thread/thread.hpp>
#include <fc/interprocess/signals.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <iostream>
#include <fstream>
#ifdef WIN32
#include <tchar.h>
#include <signal.h>
#include <windows.h>
#include <Dbghelp.h>
inline void CreateMiniDump(EXCEPTION_POINTERS* pep, LPCTSTR strFileName)
{
std::cout << "in Create dump" << std::endl;
HANDLE hFile = CreateFile(strFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
{
MINIDUMP_EXCEPTION_INFORMATION mdei;
mdei.ThreadId = GetCurrentThreadId();
mdei.ExceptionPointers = pep;
mdei.ClientPointers = FALSE;
MINIDUMP_TYPE mdt = (MINIDUMP_TYPE)0x0000ffff;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &mdei, NULL, NULL);
CloseHandle(hFile);
}
}
LONG WINAPI UnhandledExceptionFilterEx(struct _EXCEPTION_POINTERS *pException)
{
TCHAR szMbsFile[MAX_PATH] = { 0 };
::GetModuleFileName(NULL, szMbsFile, MAX_PATH);
TCHAR* pFind = _tcsrchr(szMbsFile, '\\');
_tcscat(szMbsFile, _T(".dmp"));
CreateMiniDump(pException, szMbsFile);
// TODO: MiniDumpWriteDump
return EXCEPTION_CONTINUE_SEARCH;
}
#else
# include <csignal>
#endif
using namespace graphene;
namespace bpo = boost::program_options;
void write_default_logging_config_to_stream(std::ostream& out);
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename, const std::set<std::string> discard_logs = std::set<std::string>());
int main(int argc, char** argv) {
#ifdef WIN32
SetUnhandledExceptionFilter(UnhandledExceptionFilterEx);
#endif
fc::time_point::start_ntp();
app::application* node = new app::application();
fc::oexception unhandled_exception;
try
{
bpo::options_description app_options("Graphene Witness Node");
bpo::options_description cfg_options("Graphene Witness Node");
app_options.add_options()
("help,h", "Print this help message and exit.")
("version,v", "Show version info and exit.")
("data-dir,d", bpo::value<boost::filesystem::path>()->default_value("witness_node_data_dir"), "Directory containing databases, configuration file, etc.")
;
bpo::variables_map options;
auto witness_plug = node->register_plugin<miner_plugin::miner_plugin>();
//auto history_plug = node->register_plugin<account_history::account_history_plugin>();
auto transaction_plg = node->register_plugin<graphene::transaction::transaction_plugin>();
auto crosschain_record_plug = node->register_plugin<crosschain::crosschain_record_plugin>();
try
{
bpo::options_description cli, cfg;
node->set_program_options(cli, cfg);
app_options.add(cli);
cfg_options.add(cfg);
bpo::store(bpo::parse_command_line(argc, argv, app_options), options);
}
catch (const boost::program_options::error& e)
{
std::cerr << "Error parsing command line: " << e.what() << "\n";
return 1;
}
if (options.count("help"))
{
std::cout << app_options << std::endl;
return 0;
}
if (options.count("version"))
{
std::cout << WITENESS_NODE_VERSION << std::endl;
return 0;
}
bool b_testnet = false;
if (options.count("testnet"))
{
b_testnet = true;
chain::address::testnet_mode = true;
}
fc::path data_dir;
if (options.count("data-dir"))
{
data_dir = options["data-dir"].as<boost::filesystem::path>();
if (data_dir.is_relative())
{
data_dir = fc::current_path() / data_dir;
}
}
if (b_testnet)
{
data_dir = data_dir / "testnet";
}
bool log_p2p = true;
std::set<std::string> discard_log;
if (options.count("nop2plog"))
{
discard_log.insert("p2p");
log_p2p = false;
}
fc::path config_ini_path = data_dir / "config.ini";
if (fc::exists(config_ini_path))
{
//check signature of the config.ini
auto cfg_options_copy = cfg_options;
cfg_options_copy.add_options()
("cfg-signature", bpo::value<string>()->default_value(""), "The signature of configuration file");
bool delete_flag = false;
bpo::variables_map ini_options;
bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(), cfg_options_copy, true), ini_options);
if (!ini_options.count("cfg-signature"))
{
delete_flag = true;
}
else
{
string cfg_signature = ini_options["cfg-signature"].as<string>();
if (cfg_signature != WITENESS_CFG_SIGNATURE)
{
delete_flag = true;
}
}
// delete the old config file because the signature or format is changed
if (delete_flag)
{
fc::path config_copy_path = data_dir / "config.ini.auto-bk";
fc::remove(config_copy_path);
fc::copy(config_ini_path, config_copy_path);
fc::remove(config_ini_path);
}
}
if (fc::exists(config_ini_path))
{
// get the basic options
bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(), cfg_options, true), options);
// try to get logging options from the config file.
try
{
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path, discard_log);
if (logging_config)
{
fc::configure_logging(*logging_config);
}
else
{
fc::configure_logging(fc::logging_config::default_config(config_ini_path, log_p2p));
}
}
catch (const fc::exception&)
{
wlog("Error parsing logging config from config file ${config}, using default config", ("config", config_ini_path.preferred_string()));
fc::configure_logging(fc::logging_config::default_config(config_ini_path, log_p2p));
}
}
else
{
ilog("Writing new config file at ${path}", ("path", config_ini_path));
if (!fc::exists(data_dir))
{
fc::create_directories(data_dir);
}
cfg_options.add_options()
("cfg-signature", bpo::value<string>()->default_value(WITENESS_CFG_SIGNATURE), "The signature of configuration file");
std::ofstream out_cfg(config_ini_path.preferred_string());
for (const boost::shared_ptr<bpo::option_description> od : cfg_options.options())
{
if (!od->description().empty())
{
out_cfg << "# " << od->description() << "\n";
}
boost::any store;
if (!od->semantic()->apply_default(store))
{
out_cfg << "# " << od->long_name() << " = \n";
}
else
{
auto example = od->format_parameter();
if (example.empty())
{
// This is a boolean switch
out_cfg << od->long_name() << " = " << "false\n";
}
else
{
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length() - 1);
out_cfg << od->long_name() << " = " << example << "\n";
}
}
out_cfg << "\n";
}
write_default_logging_config_to_stream(out_cfg);
out_cfg.close();
// read the default logging config we just wrote out to the file and start using it
fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path, discard_log);
if (logging_config)
{
fc::configure_logging(*logging_config);
}
else
{
fc::configure_logging(fc::logging_config::default_config(config_ini_path, log_p2p));
}
}
bpo::notify(options);
node->initialize(data_dir, options);
node->initialize_plugins(options);
node->startup();
node->startup_plugins();
node->chain_database()->broad_trxs.connect([&](const deque<signed_transaction>& b) {
try
{
for (const auto& one_trx : b)
{
node->p2p_node()->broadcast_transaction(one_trx);
}
}
catch (...)
{}
});
auto chain_types = node->get_crosschain_chain_types();
for (auto& chain_type : chain_types)
{
crosschain_record_plug->add_acquire_plugin(chain_type);
}
fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
fc::set_signal_handler([&exit_promise](int signal) {
elog("Caught SIGINT attempting to exit cleanly");
exit_promise->set_value(signal);
}, SIGINT);
fc::set_signal_handler([&exit_promise](int signal) {
elog("Caught SIGTERM attempting to exit cleanly");
exit_promise->set_value(signal);
}, SIGTERM);
ilog("Started witness node on a chain with ${h} blocks.", ("h", node->chain_database()->head_block_num()));
ilog("Chain ID is ${id}", ("id", node->chain_database()->get_chain_id()));
int signal = exit_promise->wait();
node->stop_block_processing();
ilog("Exiting from signal ${n}", ("n", signal));
node->shutdown_plugins();
node->shutdown();
return 0;
}
catch (const fc::exception& e)
{
// deleting the node can yield, so do this outside the exception handler
unhandled_exception = e;
}
catch (const std::exception&e)
{
elog("Exiting with std::exception:\n${e}", ("e", e.what()));
unhandled_exception = fc::exception();
}
catch (...)
{
elog("Exiting with uncertain exception");
unhandled_exception = fc::exception();
}
if (unhandled_exception)
{
elog("Exiting with error:\n${e}", ("e", unhandled_exception->to_detail_string()));
node->shutdown();
return 1;
}
}
// logging config is too complicated to be parsed by boost::program_options,
// so we do it by hand
//
// Currently, you can only specify the filenames and logging levels, which
// are all most users would want to change. At a later time, options can
// be added to control rotation intervals, compression, and other seldom-
// used features
void write_default_logging_config_to_stream(std::ostream& out)
{
out << "# declare an appender named \"stderr\" that writes messages to the console\n"
"[log.console_appender.stderr]\n"
"stream=std_error\n\n"
"# declare an appender named \"p2p\" that writes messages to p2p.log\n"
"[log.file_appender.p2p]\n"
"filename=logs/p2p/p2p.log\n"
"# filename can be absolute or relative to this config file\n\n"
"# route any messages logged to the default logger to the \"stderr\" logger we\n"
"# declared above, if they are info level are higher\n"
"[logger.default]\n"
"level=info\n"
"appenders=stderr\n\n"
"# route messages sent to the \"p2p\" logger to the p2p appender declared above\n"
"[logger.p2p]\n"
"level=error\n"
"appenders=p2p\n\n";
}
fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path& config_ini_filename, const std::set<std::string> discard_logs/*=std::set<std::string>()*/)
{
try
{
fc::logging_config logging_config;
bool found_logging_config = false;
boost::property_tree::ptree config_ini_tree;
boost::property_tree::ini_parser::read_ini(config_ini_filename.preferred_string().c_str(), config_ini_tree);
for (const auto& section : config_ini_tree)
{
const std::string& section_name = section.first;
const boost::property_tree::ptree& section_tree = section.second;
const std::string console_appender_section_prefix = "log.console_appender.";
const std::string file_appender_section_prefix = "log.file_appender.";
const std::string logger_section_prefix = "logger.";
if (boost::starts_with(section_name, console_appender_section_prefix))
{
std::string console_appender_name = section_name.substr(console_appender_section_prefix.length());
std::string stream_name = section_tree.get<std::string>("stream");
// construct a default console appender config here
// stdout/stderr will be taken from ini file, everything else hard-coded here
fc::console_appender::config console_appender_config;
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::debug,
fc::console_appender::color::green));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::warn,
fc::console_appender::color::brown));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::error,
fc::console_appender::color::cyan));
console_appender_config.stream = fc::variant(stream_name).as<fc::console_appender::stream::type>();
logging_config.appenders.push_back(fc::appender_config(console_appender_name, "console", fc::variant(console_appender_config)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, file_appender_section_prefix))
{
std::string file_appender_name = section_name.substr(file_appender_section_prefix.length());
fc::path file_name = section_tree.get<std::string>("filename");
if (file_name.is_relative())
{
file_name = fc::absolute(config_ini_filename).parent_path() / file_name;
}
// construct a default file appender config here
// filename will be taken from ini file, everything else hard-coded here
fc::file_appender::config file_appender_config;
file_appender_config.filename = file_name;
file_appender_config.flush = true;
file_appender_config.rotate = true;
file_appender_config.rotation_interval = fc::hours(1);
file_appender_config.rotation_limit = fc::days(1);
logging_config.appenders.push_back(fc::appender_config(file_appender_name, "file", fc::variant(file_appender_config)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, logger_section_prefix))
{
std::string logger_name = section_name.substr(logger_section_prefix.length());
if (discard_logs.find(logger_name) != discard_logs.end())
{
std::cout << "Discard " << logger_name << std::endl;
continue;
}
std::string level_string = section_tree.get<std::string>("level");
std::string appenders_string = section_tree.get<std::string>("appenders");
fc::logger_config logger_config(logger_name);
logger_config.level = fc::variant(level_string).as<fc::log_level>();
boost::split(logger_config.appenders, appenders_string,
boost::is_any_of(" ,"),
boost::token_compress_on);
logging_config.loggers.push_back(logger_config);
found_logging_config = true;
}
}
if (found_logging_config)
{
return logging_config;
}
else
{
return fc::optional<fc::logging_config>();
}
}
FC_RETHROW_EXCEPTIONS(warn, "")
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = GetLastBlockIndex(pindexBest, false);
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
double GetPoWMHashPS()
{
/* if (pindexBest->nHeight >= LAST_POW_BLOCK)
return 0;
*/
int nPoWInterval = 72;
int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
CBlockIndex* pindex = pindexGenesisBlock;
CBlockIndex* pindexPrevWork = pindexGenesisBlock;
while (pindex)
{
if (pindex->IsProofOfWork())
{
int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
pindexPrevWork = pindex;
}
pindex = pindex->pnext;
}
return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}
double GetPoSKernelPS()
{
int nPoSInterval = 72;
double dStakeKernelsTriedAvg = 0;
int nStakesHandled = 0, nStakesTime = 0;
CBlockIndex* pindex = pindexBest;;
CBlockIndex* pindexPrevStake = NULL;
while (pindex && nStakesHandled < nPoSInterval)
{
if (pindex->IsProofOfStake())
{
dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
pindexPrevStake = pindex;
nStakesHandled++;
}
pindex = pindex->pprev;
}
return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier)));
result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fPrintTransactionDetail)
{
Object entry;
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
TxToJSON(tx, 0, entry);
txinfo.push_back(entry);
}
else
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
if (block.IsProofOfStake())
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
return result;
}
Value getbestblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
return obj;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.01");
nTransactionFee = AmountFromValue(params[0]);
nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent
return true;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblockbynumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
uint256 hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
// Check that the block satisfies synchronized checkpoint
if (CheckpointsMode == Checkpoints::STRICT)
result.push_back(Pair("policy", "strict"));
if (CheckpointsMode == Checkpoints::ADVISORY)
result.push_back(Pair("policy", "advisory"));
if (CheckpointsMode == Checkpoints::PERMISSIVE)
result.push_back(Pair("policy", "permissive"));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
return result;
}
|
#include <list>
#include <tst/set.hpp>
#include <tst/check.hpp>
#include <utki/linq.hpp>
#include <utki/config.hpp>
#if M_COMPILER != M_COMPILER_MSVC || M_COMPILER_MSVC_TOOLS_V >= 142
namespace{
tst::set set("linq", [](tst::suite& suite){
suite.add(
"linq_from_rvalue_select",
[](){
std::vector<std::pair<int, std::string>> in = {{
{13, "13"},
{14, "14"},
{1, "1"}
}};
auto out = utki::linq(std::move(in)).select(
[](auto v){
auto r = std::make_pair(std::move(v.second), 13.4f);
tst::check(v.second.empty(), SL);
return r;
}
).get();
static_assert(std::is_same<decltype(out), std::vector<std::pair<std::string, float>>>::value, "not same");
decltype(out) expected = {{
{"13", 13.4f},
{"14", 13.4f},
{"1", 13.4f}
}};
tst::check(out == expected, SL);
tst::check(in.empty(), SL);
}
);
suite.add(
"linq_from_lvalue_select",
[](){
std::map<int, const std::string> in = {{
{13, "13"},
{14, "14"},
{1, "1"}
}};
auto out = utki::linq(in).select(
[](auto v, auto i){
auto r = std::make_pair(std::move(v.second), i);
tst::check(!v.second.empty(), SL);
return r;
}
).get();
// since original container is a map, the order of elements is sorted by map key
decltype(out) expected = {{
{"1", 0},
{"13", 1},
{"14", 2}
}};
tst::check(out == expected, [&](auto&o){o << "out.size() = " << out.size() << std::endl;}, SL);
tst::check(!in.empty(), SL);
tst::check(!in.begin()->second.empty(), SL);
}
);
suite.add(
"linq_from_const_lvalue_select",
[](){
const std::list<std::pair<int, const std::string>> in = {{
{13, "13"},
{14, "14"},
{1, "1"}
}};
auto out = utki::linq(in).select(
[](auto v){
auto r = std::make_pair(std::move(v.second), 13.4f);
tst::check(!v.second.empty(), SL);
return r;
}
).get();
decltype(out) expected = {{
{"13", 13.4f},
{"14", 13.4f},
{"1", 13.4f}
}};
tst::check(out == expected, SL);
tst::check(!in.empty(), SL);
tst::check(!in.front().second.empty(), SL);
}
);
suite.add(
"linq_from_rvalue_group_by",
[](){
std::vector<std::pair<int, std::string>> in = {{
{13, "13"},
{14, "14"},
{1, "1"},
{132, "13"},
{15, "15"},
{133, "13"},
{11, "1"}
}};
auto out = utki::linq(std::move(in)).select(
[](auto v, auto i){
auto r = std::make_tuple(std::move(v.second), v.first, i);
tst::check(v.second.empty(), SL);
return r;
}
).group_by(
[](const auto& v)->const std::string&{
return std::get<0>(v);
}
).get();
decltype(out) expected = {{
{"1", {
{"1", 1, 2}, {"1", 11, 6}
} },
{"13", {
{"13", 13, 0}, {"13", 132, 3}, {"13", 133, 5}
} },
{"14", {
{"14", 14, 1}
} },
{"15", {
{"15", 15, 4}
} }
}};
tst::check(!out.empty(), SL);
tst::check(out == expected, SL);
tst::check(in.empty(), SL);
}
);
suite.add(
"linq_from_const_lvalue_where",
[](){
const std::list<std::pair<int, const std::string>> in = {{
{13, "13"},
{14, "14"},
{1, "1"},
{13, "13_2"},
{3, "3"},
{13, "13_3"}
}};
auto out = utki::linq(in).where([](const decltype(in)::value_type& v){return v.first == 13;}).get();
decltype(out) expected = {{
{13, "13"},
{13, "13_2"},
{13, "13_3"}
}};
tst::check(out == expected, SL);
tst::check(!in.empty(), SL);
tst::check(!in.front().second.empty(), SL);
}
);
suite.add(
"linq_from_const_lvalue_group_by_where",
[](){
const std::list<std::pair<int, const std::string>> in = {{
{13, "13"},
{14, "14"},
{1, "1"},
{13, "13_2"},
{3, "3"},
{3, "3_2"}
}};
auto out = utki::linq(in).group_by([](const auto& v){return v.first;}).where([](const auto& v){return v.second.size() == 2;}).get();
tst::check(!in.empty(), SL);
tst::check(!in.front().second.empty(), SL);
tst::check(out.size() == 2, [&](auto&o){o << "out.size() = " << out.size();}, SL);
tst::check(out.begin()->first == 3, [&](auto&o){o << "out.begin()->first = " << out.begin()->first;}, SL);
tst::check(std::next(out.begin())->first == 13, [&](auto&o){o << "std::next(out.begin())->first = " << std::next(out.begin())->first;}, SL);
tst::check(out.begin()->second.size() == 2, [&](auto&o){o << "out.begin()->second.size() = " << out.begin()->second.size();}, SL);
}
);
suite.add(
"linq_from_rvalue_order_by",
[](){
std::vector<std::pair<int, std::string>> in = {{
{13, "13"},
{14, "hgb"},
{14, "asdh"},
{5, "asd"},
{1, "1"}
}};
auto out = utki::linq(std::move(in)).order_by(
[](const auto& v) -> const int&{
return v.first;
}
).get();
static_assert(std::is_same<decltype(out), decltype(in)>::value, "not same");
decltype(out) expected = {{
{1, "1"},
{5, "asd"},
{13, "13"},
{14, "hgb"},
{14, "asdh"}
}};
#ifdef DEBUG
for(auto& e : out){
LOG([&](auto&o){o << "e = " << e.first << " " << e.second << std::endl;})
}
#endif
tst::check(out == expected, SL);
tst::check(in.empty(), SL);
}
);
suite.add(
"linq_from_lvalue_order_by",
[](){
std::vector<std::pair<int, std::string>> in = {{
{13, "13"},
{14, "hgb"},
{14, "asdh"},
{5, "asd"},
{1, "1"}
}};
auto out = utki::linq(in).order_by(
[](const auto& v) -> const int&{
return v.first;
}
).get();
static_assert(std::is_same<decltype(out), decltype(in)>::value, "not same");
decltype(out) expected = {{
{1, "1"},
{5, "asd"},
{13, "13"},
{14, "hgb"},
{14, "asdh"}
}};
#ifdef DEBUG
for(auto& e : out){
LOG([&](auto&o){o << "e = " << e.first << " " << e.second << std::endl;})
}
#endif
tst::check(out == expected, SL);
tst::check(!in.empty(), SL);
tst::check(!in.begin()->second.empty(), SL);
}
);
suite.add(
"linq_from_const_lvalue_order_by",
[](){
const std::vector<std::pair<int, std::string>> in = {{
{13, "13"},
{14, "hgb"},
{14, "asdh"},
{5, "asd"},
{1, "1"}
}};
auto out = utki::linq(in).order_by(
[](const auto& v) -> const int&{
return v.first;
}
).get();
static_assert(std::is_same<decltype(out), std::remove_const<decltype(in)>::type>::value, "not same");
decltype(out) expected = {{
{1, "1"},
{5, "asd"},
{13, "13"},
{14, "hgb"},
{14, "asdh"}
}};
#ifdef DEBUG
for(auto& e : out){
LOG([&](auto&o){o << "e = " << e.first << " " << e.second << std::endl;})
}
#endif
tst::check(out == expected, SL);
tst::check(!in.empty(), SL);
tst::check(!in.begin()->second.empty(), SL);
}
);
suite.add(
"select_shared_ptr",
[](){
struct test_struct{
bool& destroyed;
test_struct(bool& destroyed) : destroyed(destroyed){}
~test_struct(){
this->destroyed = true;
}
};
bool destroyed = false;
struct wrapper{
std::shared_ptr<test_struct> ts;
int dummy;
~wrapper(){}
std::shared_ptr<test_struct> get_ts()const{
return this->ts;
}
};
std::vector<wrapper> vec{
{ std::make_shared<test_struct>(destroyed), 10 },
{ std::make_shared<test_struct>(destroyed), 13 }
};
auto res = utki::linq(vec).select([](const auto& i) -> std::shared_ptr<const test_struct> {
return i.get_ts();
}).get();
vec.clear();
tst::check(!destroyed, SL);
res.clear();
tst::check(destroyed, SL);
}
);
});
}
#endif // ~ non-MSVC compiler or MSVC compiler tools >= v142
|
// Don't modify, automatically generated file by QuickFIX2OpenDDS.py
#ifndef __Logout_h__
#define __Logout_h__
#include "LogoutTypeSupportImpl.h"
#include <quickfix/Message.h>
using namespace DistributedATS;
#include "HeaderAdapter.hpp"
class LogoutAdapter
{
public:
static void FIX2DDS(const FIX::Message&, DistributedATS_Logout::Logout& ddsMsg ) __attribute__ ((visibility ("default")));
static void DDS2FIX(const DistributedATS_Logout::Logout& ddsMsg, FIX::Message&) __attribute__ ((visibility ("default")));
};
#endif
|
// Copyright 2019 The Fuchsia 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 <fuchsia/hardware/platform/device/c/banjo.h>
#include <fuchsia/hardware/spiimpl/cpp/banjo.h>
#include <lib/ddk/debug.h>
#include <lib/ddk/driver.h>
#include <lib/ddk/metadata.h>
#include <memory>
#include <ddktl/device.h>
#include "src/devices/bus/drivers/platform/test/test-spi-bind.h"
#define DRIVER_NAME "test-spi"
namespace spi {
class TestSpiDevice;
using DeviceType = ddk::Device<TestSpiDevice>;
class TestSpiDevice : public DeviceType,
public ddk::SpiImplProtocol<TestSpiDevice, ddk::base_protocol> {
public:
static zx_status_t Create(zx_device_t* parent) {
auto dev = std::make_unique<TestSpiDevice>(parent, 0);
pdev_protocol_t pdev;
zx_status_t status;
zxlogf(INFO, "TestSpiDevice::Create: %s ", DRIVER_NAME);
status = device_get_protocol(parent, ZX_PROTOCOL_PDEV, &pdev);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: could not get ZX_PROTOCOL_PDEV", __func__);
return status;
}
status = dev->DdkAdd("test-spi");
if (status != ZX_OK) {
zxlogf(ERROR, "%s: DdkAdd failed: %d", __func__, status);
return status;
}
status = dev->DdkAddMetadata(DEVICE_METADATA_PRIVATE, &dev->bus_id_, sizeof dev->bus_id_);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: DdkAddMetadata failed: %d", __func__, status);
return status;
}
// devmgr is now in charge of dev.
__UNUSED auto ptr = dev.release();
zxlogf(INFO, "%s: returning ZX_OK", __func__);
return ZX_OK;
}
explicit TestSpiDevice(zx_device_t* parent, uint32_t bus_id)
: DeviceType(parent), bus_id_(bus_id) {}
uint32_t SpiImplGetChipSelectCount() { return 1; }
zx_status_t SpiImplExchange(uint32_t cs, const uint8_t* txdata_list, size_t txdata_count,
uint8_t* out_rxdata_list, size_t rxdata_count,
size_t* out_rxdata_actual) {
// TX only, ignore
if (!out_rxdata_list) {
return ZX_OK;
}
// RX only, fill with pattern
else if (!txdata_list) {
for (size_t i = 0; i < rxdata_count; i++) {
out_rxdata_list[i] = i & 0xff;
}
*out_rxdata_actual = rxdata_count;
return ZX_OK;
}
// Both TX and RX; copy
else {
if (txdata_count != rxdata_count) {
return ZX_ERR_INVALID_ARGS;
}
memcpy(out_rxdata_list, txdata_list, txdata_count);
*out_rxdata_actual = txdata_count;
return ZX_OK;
}
}
zx_status_t SpiImplRegisterVmo(uint32_t chip_select, uint32_t vmo_id, zx::vmo vmo,
uint64_t offset, uint64_t size, uint32_t rights) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t SpiImplUnregisterVmo(uint32_t chip_select, uint32_t vmo_id, zx::vmo* out_vmo) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t SpiImplTransmitVmo(uint32_t chip_select, uint32_t vmo_id, uint64_t offset,
uint64_t size) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t SpiImplReceiveVmo(uint32_t chip_select, uint32_t vmo_id, uint64_t offset,
uint64_t size) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t SpiImplExchangeVmo(uint32_t chip_select, uint32_t tx_vmo_id, uint64_t tx_offset,
uint32_t rx_vmo_id, uint64_t rx_offset, uint64_t size) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t SpiImplLockBus(uint32_t chip_select) { return ZX_ERR_NOT_SUPPORTED; }
zx_status_t SpiImplUnlockBus(uint32_t chip_select) { return ZX_ERR_NOT_SUPPORTED; }
// Methods required by the ddk mixins
void DdkRelease() { delete this; }
private:
uint32_t bus_id_;
};
zx_status_t test_spi_bind(void* ctx, zx_device_t* parent) { return TestSpiDevice::Create(parent); }
constexpr zx_driver_ops_t driver_ops = []() {
zx_driver_ops_t driver_ops = {};
driver_ops.version = DRIVER_OPS_VERSION;
driver_ops.bind = test_spi_bind;
return driver_ops;
}();
} // namespace spi
ZIRCON_DRIVER(test_spi, spi::driver_ops, "zircon", "0.1");
|
/*
* 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 <gtest/gtest.h>
#include "ApiLevelsUtils.h"
#include "DexClass.h"
#include "DexUtil.h"
#include "IRAssembler.h"
#include "ScopeHelper.h"
namespace {
std::vector<DexClass*> create_scope(bool add_parent) {
std::vector<DexClass*> scope = create_empty_scope();
auto obj_t = type::java_lang_Object();
auto a_t = DexType::make_type("Landroidx/ArrayMap;");
auto a_cls = create_internal_class(a_t, obj_t, {});
scope.push_back(a_cls);
auto b_t = DexType::make_type("Landroidx/ArraySet;");
auto b_cls = create_internal_class(b_t, obj_t, {});
scope.push_back(b_cls);
auto c_t = DexType::make_type("Landroidx/LongSparseArray;");
auto c_cls = create_internal_class(c_t, a_t, {});
scope.push_back(c_cls);
auto d_t = DexType::make_type("Landroidx/FragmentContainer;");
auto d_cls = create_internal_class(d_t, obj_t, {});
scope.push_back(d_cls);
if (add_parent) {
auto d_t = DexType::make_type("Landroidx/ArraySetParentClass;");
auto d_cls = create_internal_class(d_t, obj_t, {});
b_cls->set_super_class(d_t);
scope.push_back(d_cls);
}
return scope;
}
void add_usage(Scope* scope, DexMethodRef* mref) {
auto obj_t = type::java_lang_Object();
auto new_t = DexType::make_type("LUsage;");
auto new_cls = create_internal_class(new_t, obj_t, {});
scope->push_back(new_cls);
std::string code_str = R"(
(method (private) "LUsage;.bar:()V"
(
(new-instance "Landroidx/ArrayMap;")
(move-result-pseudo-object v0)
(invoke-virtual (v0) ")";
code_str += SHOW(mref);
code_str += R"(")
(move-result-object v0)
(return-void)
)
)
)";
std::cout << code_str << std::endl;
auto method = assembler::method_from_string(code_str);
new_cls->add_method(method);
}
} // namespace
TEST(ApiUtilsTest, testParseInputFormat) {
g_redex = new RedexContext();
Scope scope = create_scope(false);
api::ApiLevelsUtils api_utils(scope, std::getenv("api_utils_easy_input_path"),
21);
const auto& framework_cls_to_api = api_utils.get_framework_classes();
EXPECT_EQ(framework_cls_to_api.size(), 5);
auto a_t = DexType::make_type("Landroid/util/ArrayMap;");
EXPECT_EQ(framework_cls_to_api.at(a_t).mrefs_info.size(), 2);
EXPECT_EQ(framework_cls_to_api.at(a_t).frefs_info.size(), 0);
auto b_t = DexType::make_type("Landroid/util/ArraySet;");
EXPECT_EQ(framework_cls_to_api.at(b_t).mrefs_info.size(), 2);
auto c_t = DexType::make_type("Landroid/util/LongSparseArray;");
EXPECT_EQ(framework_cls_to_api.at(c_t).mrefs_info.size(), 0);
auto d_t = DexType::make_type("Landroid/app/FragmentContainer;");
EXPECT_EQ(framework_cls_to_api.at(d_t).mrefs_info.size(), 0);
delete g_redex;
}
TEST(ApiUtilsTest, testEasyInput_EasyReleaseLibraries) {
g_redex = new RedexContext();
Scope scope = create_scope(false);
api::ApiLevelsUtils api_utils(scope, std::getenv("api_utils_easy_input_path"),
21);
const auto& types_to_framework_api = api_utils.get_types_to_framework_api();
EXPECT_EQ(types_to_framework_api.size(), 3);
auto a_framework = DexType::make_type("Landroid/util/ArrayMap;");
auto a_release = DexType::make_type("Landroidx/ArrayMap;");
EXPECT_EQ(types_to_framework_api.at(a_release).cls, a_framework);
auto b_framework = DexType::make_type("Landroid/util/ArraySet;");
auto b_release = DexType::make_type("Landroidx/ArraySet;");
EXPECT_EQ(types_to_framework_api.at(b_release).cls, b_framework);
auto c_framework = DexType::make_type("Landroid/util/LongSparseArray;");
auto c_release = DexType::make_type("Landroidx/LongSparseArray;");
EXPECT_EQ(types_to_framework_api.at(c_release).cls, c_framework);
}
TEST(ApiUtilsTest, testEasyInput_SubClassMissingInReleaseLibraries) {
g_redex = new RedexContext();
Scope scope = create_scope(true);
api::ApiLevelsUtils api_utils(scope, std::getenv("api_utils_easy_input_path"),
21);
const auto& types_to_framework_api = api_utils.get_types_to_framework_api();
EXPECT_EQ(types_to_framework_api.size(), 2);
auto a_framework = DexType::make_type("Landroid/util/ArrayMap;");
auto a_release = DexType::make_type("Landroidx/ArrayMap;");
EXPECT_EQ(types_to_framework_api.at(a_release).cls, a_framework);
auto c_framework = DexType::make_type("Landroid/util/LongSparseArray;");
auto c_release = DexType::make_type("Landroidx/LongSparseArray;");
EXPECT_EQ(types_to_framework_api.at(c_release).cls, c_framework);
}
TEST(ApiUtilsTest, testEasyInput_MethodMissingButNotTruePrivate) {
g_redex = new RedexContext();
Scope scope = create_scope(false);
auto void_args = DexTypeList::make_type_list({});
auto void_object = DexProto::make_proto(type::java_lang_Object(), void_args);
auto a_release = DexType::make_type("Landroidx/ArrayMap;");
auto method = static_cast<DexMethod*>(DexMethod::make_method(
a_release, DexString::make_string("foo"), void_object));
method->set_access(ACC_PUBLIC);
method->set_virtual(true);
method->set_external();
method->set_code(assembler::ircode_from_string("((return-void))"));
auto a_cls = type_class(a_release);
a_cls->add_method(method);
api::ApiLevelsUtils api_utils(scope, std::getenv("api_utils_easy_input_path"),
21);
const auto& types_to_framework_api = api_utils.get_types_to_framework_api();
EXPECT_EQ(types_to_framework_api.size(), 3);
auto b_framework = DexType::make_type("Landroid/util/ArraySet;");
auto b_release = DexType::make_type("Landroidx/ArraySet;");
EXPECT_EQ(types_to_framework_api.at(b_release).cls, b_framework);
}
TEST(ApiUtilsTest, testEasyInput_MethodMissing) {
g_redex = new RedexContext();
Scope scope = create_scope(false);
auto void_args = DexTypeList::make_type_list({});
auto void_object = DexProto::make_proto(type::java_lang_Object(), void_args);
auto a_release = DexType::make_type("Landroidx/ArrayMap;");
auto method = static_cast<DexMethod*>(DexMethod::make_method(
a_release, DexString::make_string("foo"), void_object));
method->set_access(ACC_PUBLIC);
method->set_virtual(true);
method->set_external();
method->set_code(assembler::ircode_from_string("((return-void))"));
auto a_cls = type_class(a_release);
a_cls->add_method(method);
// We need to actually use the method outside of the class, for it to be
// considered missing.
add_usage(&scope, method);
api::ApiLevelsUtils api_utils(scope, std::getenv("api_utils_easy_input_path"),
21);
const auto& types_to_framework_api = api_utils.get_types_to_framework_api();
EXPECT_EQ(types_to_framework_api.size(), 1);
auto b_framework = DexType::make_type("Landroid/util/ArraySet;");
auto b_release = DexType::make_type("Landroidx/ArraySet;");
EXPECT_EQ(types_to_framework_api.at(b_release).cls, b_framework);
}
|
#include <bits/stdc++.h>
#define ll long int
using namespace std;
int main() {
string s;
cin>>s;
vector<int> v;
for(int i=0;i<s.length();i++)
{
if(s[i]!='+')
{
v.push_back(s[i]-'0');
}
}
sort(v.begin(),v.end());
int i=0;
for(;i<v.size()-1;i++){
cout<<v[i]<<"+";
}
cout<<v[i]<<endl;
return 0;
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/source_context.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/source_context.pb.h>
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace google {
namespace protobuf {
namespace {
const ::google::protobuf::Descriptor* SourceContext_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
SourceContext_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AssignDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() {
protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"google/protobuf/source_context.proto");
GOOGLE_CHECK(file != NULL);
SourceContext_descriptor_ = file->message_type(0);
static const int SourceContext_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, file_name_),
};
SourceContext_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
SourceContext_descriptor_,
SourceContext::default_instance_,
SourceContext_offsets_,
-1,
-1,
-1,
sizeof(SourceContext),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, _is_default_instance_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fsource_5fcontext_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
SourceContext_descriptor_, &SourceContext::default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto() {
delete SourceContext::default_instance_;
delete SourceContext_reflection_;
}
void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n$google/protobuf/source_context.proto\022\017"
"google.protobuf\"\"\n\rSourceContext\022\021\n\tfile"
"_name\030\001 \001(\tBU\n\023com.google.protobufB\022Sour"
"ceContextProtoP\001\240\001\001\242\002\003GPB\252\002\036Google.Proto"
"buf.WellKnownTypesb\006proto3", 186);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/source_context.proto", &protobuf_RegisterTypes);
SourceContext::default_instance_ = new SourceContext();
SourceContext::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fsource_5fcontext_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fsource_5fcontext_2eproto() {
protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
}
} static_descriptor_initializer_google_2fprotobuf_2fsource_5fcontext_2eproto_;
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SourceContext::kFileNameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SourceContext::SourceContext()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceContext)
}
void SourceContext::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
SourceContext::SourceContext(const SourceContext& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceContext)
}
void SourceContext::SharedCtor() {
_is_default_instance_ = false;
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
SourceContext::~SourceContext() {
// @@protoc_insertion_point(destructor:google.protobuf.SourceContext)
SharedDtor();
}
void SourceContext::SharedDtor() {
file_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != default_instance_) {
}
}
void SourceContext::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SourceContext::descriptor() {
protobuf_AssignDescriptorsOnce();
return SourceContext_descriptor_;
}
const SourceContext& SourceContext::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
return *default_instance_;
}
SourceContext* SourceContext::default_instance_ = NULL;
SourceContext* SourceContext::New(::google::protobuf::Arena* arena) const {
SourceContext* n = new SourceContext;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void SourceContext::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceContext)
file_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
bool SourceContext::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.SourceContext)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string file_name = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_file_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->file_name().data(), this->file_name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.SourceContext.file_name"));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.protobuf.SourceContext)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.protobuf.SourceContext)
return false;
#undef DO_
}
void SourceContext::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.SourceContext)
// optional string file_name = 1;
if (this->file_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->file_name().data(), this->file_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.SourceContext.file_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->file_name(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.SourceContext)
}
::google::protobuf::uint8* SourceContext::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceContext)
// optional string file_name = 1;
if (this->file_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->file_name().data(), this->file_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.SourceContext.file_name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->file_name(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceContext)
return target;
}
int SourceContext::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.SourceContext)
int total_size = 0;
// optional string file_name = 1;
if (this->file_name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->file_name());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SourceContext::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceContext)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const SourceContext* source =
::google::protobuf::internal::DynamicCastToGenerated<const SourceContext>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.SourceContext)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.SourceContext)
MergeFrom(*source);
}
}
void SourceContext::MergeFrom(const SourceContext& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceContext)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
if (from.file_name().size() > 0) {
file_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.file_name_);
}
}
void SourceContext::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.SourceContext)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SourceContext::CopyFrom(const SourceContext& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.SourceContext)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SourceContext::IsInitialized() const {
return true;
}
void SourceContext::Swap(SourceContext* other) {
if (other == this) return;
InternalSwap(other);
}
void SourceContext::InternalSwap(SourceContext* other) {
file_name_.Swap(&other->file_name_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SourceContext::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = SourceContext_descriptor_;
metadata.reflection = SourceContext_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// SourceContext
// optional string file_name = 1;
void SourceContext::clear_file_name() {
file_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& SourceContext::file_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceContext.file_name)
return file_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void SourceContext::set_file_name(const ::std::string& value) {
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.SourceContext.file_name)
}
void SourceContext::set_file_name(const char* value) {
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceContext.file_name)
}
void SourceContext::set_file_name(const char* value, size_t size) {
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceContext.file_name)
}
::std::string* SourceContext::mutable_file_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceContext.file_name)
return file_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* SourceContext::release_file_name() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceContext.file_name)
return file_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void SourceContext::set_allocated_file_name(::std::string* file_name) {
if (file_name != NULL) {
} else {
}
file_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), file_name);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
|
#include "node.h"
#include "AVLTree.h"
#include <string>
#include <sstream>
#include <iostream>
#include "typeinfo"
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::stringstream;
AVLTree::AVLTree(){
}
AVLTree::AVLTree(int Valor){
this -> Raiz = new Node(Valor);
}
AVLTree::~AVLTree(){
}
Node AVLTree::getRoot(){
return *Raiz;
}
Node* AVLTree::getRootPointer(){
return Raiz;
}
void AVLTree::SetRoot(Node* Nodo){
this -> Raiz = Nodo;
}
void AVLTree::AddNode(int ValorInsertar){
Node* Nodo = new Node(ValorInsertar);
Node* RaizTemporal = Raiz;
int Seguir = 1;
while(Seguir == 1){
if ((*Raiz).getValue() != 0){
if ((!(*Raiz).hasLeftSon()) && (!(*Raiz).hasRightSon())){
if (ValorInsertar > (*Raiz).getValue()){
Raiz -> setRightSon(Nodo);
Nodo -> setParent(Raiz);
bool Continuar = true, Agregar = true;
int Lado = 1;
EstaBalanceado(Raiz, Continuar, Agregar, Lado);
Seguir = 0;
}else if(ValorInsertar < (*Raiz).getValue()){
Raiz -> setLeftSon(Nodo);
Nodo -> setParent(Raiz);
bool Continuar = true, Agregar = true;
int Lado = 0;
EstaBalanceado(Raiz, Continuar, Agregar, Lado);
Seguir = 0;
}
}else{
if(ValorInsertar > (*RaizTemporal).getValue()){
if ((*RaizTemporal).hasRightSon()){
RaizTemporal = RaizTemporal -> getRightSonPointer();
}else{
RaizTemporal -> setRightSon(Nodo);
Nodo -> setParent(RaizTemporal);
bool Continuar = true, Agregar = true;
int Lado = 1;
EstaBalanceado(RaizTemporal, Continuar, Agregar, Lado);
Seguir = 0;
}
}else{
if ((*RaizTemporal).hasLeftSon()){
RaizTemporal = RaizTemporal -> getLeftSonPointer();
}else{
RaizTemporal -> setLeftSon(Nodo);
Nodo -> setParent(RaizTemporal);
bool Continuar = true, Agregar = true;
int Lado = 0;
EstaBalanceado(RaizTemporal, Continuar, Agregar, Lado);
Seguir = 0;
}
}
}
}else if((*Raiz).getValue() == 0){
Raiz = new Node(ValorInsertar);
Seguir = 0;
}
}
}
void AVLTree::DeleteNode(int ValorEliminar, int NodosTotales, int CasoEspecial){
Node* NodoEliminar = Raiz;
cout << "Nodo a eliminar: " << (*NodoEliminar).getValue();
int Revisar = 0;
int Repetido = 0;
if (CasoEspecial == 0){
while(ValorEliminar != (*NodoEliminar).getValue() && (Revisar <= NodosTotales)){
Revisar++;
if (ValorEliminar > (*NodoEliminar).getValue()){
if ((*NodoEliminar).hasRightSon()){
NodoEliminar = NodoEliminar -> getRightSonPointer();
}
}else if(ValorEliminar < (*NodoEliminar).getValue()){
if((*NodoEliminar).hasLeftSon()){
NodoEliminar = NodoEliminar -> getLeftSonPointer();
}
}
}
}else{
while((Revisar < NodosTotales) && (Repetido < 2)){
Revisar++;
if (ValorEliminar >= (*NodoEliminar).getValue()){
if((*NodoEliminar).getValue() == ValorEliminar){
Repetido++;
}
if ((*NodoEliminar).hasRightSon()){
NodoEliminar = NodoEliminar -> getRightSonPointer();
}
}else if(ValorEliminar <= (*NodoEliminar).getValue()){
if((*NodoEliminar).getValue() == ValorEliminar){
Repetido++;
}
if((*NodoEliminar).hasLeftSon()){
NodoEliminar = NodoEliminar -> getLeftSonPointer();
}
}
}
}
bool TieneHijoIzquierdo = (NodoEliminar) -> hasLeftSon();
bool TieneHijoDerecho = (NodoEliminar) -> hasRightSon();
if(!TieneHijoIzquierdo && !TieneHijoDerecho){
//Cuando solo se elimina un nodo que no tiene hijos(Caso1).
Node* PadreDeEliminado;
if(NodoEliminar -> hasParent()){
Node* PadreDeEliminado = NodoEliminar -> getParentPointer();
}else{
PadreDeEliminado = NULL;
}
if(PadreDeEliminado){
if (ValorEliminar > (*PadreDeEliminado).getValue()){
PadreDeEliminado -> setRightSon(NULL);
NodoEliminar -> setParent(NULL);
bool Continuar = true, Agregar = false;
int Lado = 1;
//EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}else{
PadreDeEliminado -> setLeftSon(NULL);
NodoEliminar -> setParent(NULL);
bool Continuar = true, Agregar = false;
int Lado = 0;
//EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}
}else{
Raiz = new Node(0);
}
}else if((TieneHijoIzquierdo && !TieneHijoDerecho) || (!TieneHijoIzquierdo && TieneHijoDerecho)){
//Cuando el nodo a eliminar tiene hijo izquierdo o derecho;
Node* PadreDeEliminado;
if(NodoEliminar -> hasParent()){
PadreDeEliminado = NodoEliminar -> getParentPointer();
}else{
PadreDeEliminado = NULL;
}
if (TieneHijoIzquierdo && !TieneHijoDerecho && PadreDeEliminado){
if ((*PadreDeEliminado).getLeftSon().getValue() == ValorEliminar){
(NodoEliminar -> getLeftSonPointer()) -> setParent(PadreDeEliminado);
PadreDeEliminado -> setLeftSon(NodoEliminar -> getLeftSonPointer());
bool Continuar = true, Agregar = false;
int Lado = 0;
EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}else if((*PadreDeEliminado).getRightSon().getValue() == ValorEliminar){
(NodoEliminar -> getLeftSonPointer()) ->setParent(PadreDeEliminado);
PadreDeEliminado -> setRightSon(NodoEliminar -> getLeftSonPointer());
bool Continuar = true, Agregar = false;
int Lado = 1;
EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}
}else if(!TieneHijoIzquierdo && TieneHijoDerecho && PadreDeEliminado){
Node* PadreDeEliminado = NodoEliminar -> getParentPointer();
if ((*PadreDeEliminado).getLeftSon().getValue() == ValorEliminar){
(NodoEliminar -> getRightSonPointer()) -> setParent(PadreDeEliminado);
PadreDeEliminado -> setLeftSon(NodoEliminar -> getRightSonPointer());
bool Continuar = true, Agregar = false;
int Lado = 0;
EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}else if((*PadreDeEliminado).getRightSon().getValue() == ValorEliminar){
(NodoEliminar -> getRightSonPointer()) -> setParent(PadreDeEliminado);
PadreDeEliminado -> setRightSon(NodoEliminar -> getRightSonPointer());
bool Continuar = true, Agregar = false;
int Lado = 1;
EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}
}else if(TieneHijoIzquierdo && !TieneHijoDerecho && !PadreDeEliminado){
PadreDeEliminado = PadreDeEliminado -> getLeftSonPointer();
PadreDeEliminado -> setParent(NULL);
bool Continuar = true, Agregar = false;
int Lado = 0;
EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}else if(!TieneHijoIzquierdo && TieneHijoDerecho && !PadreDeEliminado){
PadreDeEliminado = PadreDeEliminado -> getRightSonPointer();
PadreDeEliminado -> setParent(NULL);
bool Continuar = true, Agregar = false;
int Lado = 1;
EstaBalanceado(PadreDeEliminado, Continuar, Agregar, Lado);
}
}else if(TieneHijoIzquierdo && TieneHijoDerecho){
///cuando quiere eliminar un nodo que tiene ambos hijos.
Node* NuevoNodo = ReturnLefterSon(NodoEliminar -> getRightSonPointer());
NodoEliminar -> setValue((*NuevoNodo).getValue());
DeleteNode((*NuevoNodo).getValue(), NodosTotales, 1);
}
}
Node* AVLTree::ReturnLefterSon(Node* Nodo){
if (Nodo -> getLeftSonPointer() != NULL){
Nodo = Nodo -> getLeftSonPointer();
return ReturnLefterSon(Nodo);
}
return Nodo;
}
void AVLTree::EstaBalanceado(Node* Nodo, bool Continuar, bool Agregar, int Lado){
//Lado = 1 -> derecho, Lado = 0 -> Izquierdo
Continuar = true;
while(Nodo && Continuar){
if (Agregar == true){
if (Lado == 0){
Nodo -> setLevel((Nodo -> getLevel()) - 1);
}else{
Nodo -> setLevel((Nodo -> getLevel()) + 1);
}
}else{
if (Lado == 0){
Nodo -> setLevel((Nodo -> getLevel()) + 1);
}else{
Nodo -> setLevel((Nodo -> getLevel()) - 1);
}
}
if (Nodo -> getLevel() == 0){
Continuar = false;
}else if(Nodo -> getLevel() == -2){
if ((Nodo -> getLeftSonPointer()) -> getLevel() == 1){
RSDx2(Nodo);
}else{
RSD(Nodo);
}
Continuar = false;
}else if(Nodo -> getLevel() == 2){
if ((Nodo -> getRightSonPointer()) -> getLevel() == -1){
RSIx2(Nodo);
}else{
RSI(Nodo);
}
Continuar = false;
}
if (Nodo -> getParentPointer()){
if (((Nodo -> getParentPointer()) -> getRightSonPointer()) == Nodo){
Lado = 1;
}else{
Lado = 0;
}
}
Nodo = Nodo -> getParentPointer();
}
}
void AVLTree::RSI(Node* Nodo){
Node* Padre = Nodo -> getParentPointer();
Node* Hijo = Nodo;
Node* HijoIzquierdo = Hijo -> getRightSonPointer();
Node* Nieto = HijoIzquierdo -> getLeftSonPointer();
if(Padre){
if((Padre -> getRightSonPointer()) == Hijo){
Padre -> setRightSon(HijoIzquierdo);
}else{
Padre -> setLeftSon(HijoIzquierdo);
}
}else{
Raiz = HijoIzquierdo;
}
Hijo -> setRightSon(Nieto);
HijoIzquierdo -> setLeftSon(Hijo);
Hijo -> setParent(HijoIzquierdo);
if(Nieto){
Nieto -> setParent(Hijo);
}
HijoIzquierdo -> setParent(Padre);
Hijo -> setLevel(0);
HijoIzquierdo -> setLevel(0);
}
void AVLTree::RSD(Node* Nodo){
Node* Padre = Nodo -> getParentPointer();
Node* Hijo = Nodo;
Node* HijoIzquierdo = Hijo -> getLeftSonPointer();
Node* Nieto = HijoIzquierdo -> getRightSonPointer();
if(Padre){
if((Padre -> getRightSonPointer()) == Hijo){
Padre -> setRightSon(HijoIzquierdo);
}else{
Padre -> setLeftSon(HijoIzquierdo);
}
}else{
Raiz = HijoIzquierdo;
}
Hijo -> setLeftSon(Nieto);
HijoIzquierdo -> setRightSon(Hijo);
Hijo -> setParent(HijoIzquierdo);
if(Nieto){
Nieto -> setParent(Hijo);
}
HijoIzquierdo -> setParent(Padre);
Hijo -> setLevel(0);
HijoIzquierdo -> setLevel(0);
}
void AVLTree::RSDx2(Node* Nodo){
Node* Hijo = Nodo;
Node* Padre = Nodo -> getParentPointer();
Node* HijoIzquierdo = Hijo -> getLeftSonPointer();
Node* Nieto = HijoIzquierdo -> getRightSonPointer();
Node* SubIzquierdo = Nieto -> getLeftSonPointer();
Node* SubDerecho = Nieto -> getRightSonPointer();
if(Padre){
if((Padre -> getRightSonPointer()) == Nodo){
Padre -> setRightSon(Nieto);
}else{
Padre -> setLeftSon(Nieto);
}
}else{
Raiz = Nieto;
}
HijoIzquierdo -> setRightSon(SubIzquierdo);
Hijo -> setLeftSon(SubDerecho);
Nieto -> setLeftSon(HijoIzquierdo);
Nieto -> setRightSon(Hijo);
Nieto -> setParent(Padre);
Hijo -> setParent(HijoIzquierdo);
HijoIzquierdo -> setParent(Nieto);
if(SubIzquierdo){
SubIzquierdo -> setParent(HijoIzquierdo);
}
if(SubDerecho){
SubDerecho -> setParent(Hijo);
}
if((Nieto -> getLevel()) == -1){
HijoIzquierdo -> setLevel(0);
Hijo -> setLevel(1);
}else if((Nieto -> getLevel()) == 0){
HijoIzquierdo -> setLevel(0);
Hijo -> setLevel(0);
}else if((Nieto -> getLevel()) == 1){
HijoIzquierdo -> setLevel(-1);
Hijo -> setLevel(0);
}
}
void AVLTree::RSIx2(Node* Nodo){
Node* Padre = Nodo -> getParentPointer();
Node* Hijo = Nodo;
Node* HijoIzquierdo = Hijo -> getRightSonPointer();
Node* Nieto = HijoIzquierdo -> getLeftSonPointer();
Node* SubIzquierdo = Nieto -> getLeftSonPointer();
Node* SubDerecho = Nieto -> getRightSonPointer();
if(Padre){
if((Padre -> getRightSonPointer()) == Nodo){
Padre -> setRightSon(Nieto);
}else{
Padre -> setLeftSon(Nieto);
}
}else{
Raiz = Nieto;
}
HijoIzquierdo -> setLeftSon(SubIzquierdo);
Hijo -> setRightSon(SubDerecho);
Nieto -> setLeftSon(Hijo);
Nieto -> setRightSon(HijoIzquierdo);
Nieto -> setParent(Padre);
Hijo -> setParent(HijoIzquierdo);
HijoIzquierdo -> setParent(Nieto);
if(SubIzquierdo){
SubIzquierdo -> setParent(Hijo);
}
if(SubDerecho){
SubDerecho -> setParent(HijoIzquierdo);
}
if((Nieto -> getLevel()) == -1){
HijoIzquierdo -> setLevel(1);
Hijo -> setLevel(0);
}else if((Nieto -> getLevel()) == 0){
HijoIzquierdo -> setLevel(0);
Hijo -> setLevel(0);
}else if((Nieto -> getLevel()) == 1){
HijoIzquierdo -> setLevel(0);
Hijo -> setLevel(-1);
}
}
void AVLTree::Recorrido(Node* Nodo){
if(!Nodo){
return;
}else{
cout << (*Nodo).getValue() << endl;
Recorrido(Nodo -> getLeftSonPointer());
Recorrido(Nodo -> getRightSonPointer());
}
}
Node* AVLTree::BuscarNodo(int valor, int NodosTotales){
Node* ValorABuscar = Raiz;
int Revisar = 0;
while(valor != (*ValorABuscar).getValue() && (Revisar <= NodosTotales)){
Revisar++;
if (valor > (*ValorABuscar).getValue()){
if ((*ValorABuscar).hasRightSon()){
ValorABuscar = ValorABuscar -> getRightSonPointer();
}
}else if(valor < (*ValorABuscar).getValue()){
if((*ValorABuscar).hasLeftSon()){
ValorABuscar = ValorABuscar -> getLeftSonPointer();
}
}
}
return ValorABuscar -> getParentPointer();
}
|
//
// Type.cpp
// dgmpp
//
// Created by Artem Shimanski on 30.10.2017.
//
#include <utility>
#include "Type.hpp"
#include "SDE.hpp"
#include <numeric>
namespace dgmpp {
struct EffectComparator {
bool operator() (const std::unique_ptr<Effect>& lhs, MetaInfo::Effect::Category rhs) {
return lhs->metaInfo().category < rhs;
}
bool operator() (MetaInfo::Effect::Category lhs, const std::unique_ptr<Effect>& rhs) {
return lhs < rhs->metaInfo().category;
}
};
Type::~Type() {
}
Type::Type (TypeID typeID) : Type (SDE::get(typeID)) {
}
Type::Type (const MetaInfo::Type& metaInfo): metaInfo_(metaInfo) {
for (const auto& i: metaInfo.attributes())
attributesMap_.emplace(i.first->attributeID, new Attribute(*i.first, i.second, *this));
effects_.reserve(metaInfo.effects().size());
for (auto i: metaInfo.effects()) {
if (i->effectID == EffectID::gangBoost)
effects_.push_back(std::unique_ptr<Effect>(new WarfareBuffEffect(*i, *this)));
else
effects_.push_back(std::unique_ptr<Effect>(new Effect(*i, *this)));
}
}
Type::Type (const Type& other): Type(other.metaInfo_) {
for (const auto& i: other.attributesMap_) {
if (i.second && i.second->forcedValue_) {
*attribute_(i.second->metaInfo_.attributeID) = *i.second->forcedValue_;
}
}
identifierValue_ = other.identifierValue_;
}
void Type::parent_ (Type* parent) {
if (isEnabled_())
setEnabled_(false);
if (parentType_)
cacheValue_ = cache_().extract(this);
if (parent) {
if (cacheValue_) {
parent->cache_().splice(std::move(*cacheValue_));
cacheValue_ = nullptr;
}
#if DGMPP_THREADSAFE
if (mutexValue_)
mutexValue_ = nullptr;
#endif
}
parentType_ = parent;
if (parent && parent->isEnabled_())
setEnabled_(true);
}
void Type::batchUpdates_(std::function<void()> updates) {
cache_().batchUpdates(updates);
}
Attribute::Proxy Type::attribute_ (AttributeID attributeID) {
return {*this, attributesMap_.emplace(attributeID, nullptr).first};
}
Effect* Type::effect_ (EffectID effectID) const {
auto i = std::find_if(effects_.begin(), effects_.end(), [=](const auto& a) {
return a->metaInfo().effectID == effectID;
});
return i != effects_.end() ? i->get() : nullptr;
}
void Type::setEnabled_ (bool enabled) {
if (enabled == enabled_)
return;
enabled_ = enabled;
if (enabled)
activateEffects_(MetaInfo::Effect::Category::generic);
else
deactivateEffects_(MetaInfo::Effect::Category::generic);
if (enabled)
resetCache_();
}
void Type::addModifier_(const Modifier* modifier) {
switch (modifier->metaInfo().type) {
case MetaInfo::Modifier::ModifierType::item : {
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, modifier);
assert (itemModifiersSet_.find(key) == itemModifiersSet_.end());
itemModifiersSet_.insert(key);
break;
}
case MetaInfo::Modifier::ModifierType::location : {
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, modifier);
assert (locationModifiersSet_.find(key) == locationModifiersSet_.end());
locationModifiersSet_.insert(key);
break;
}
case MetaInfo::Modifier::ModifierType::locationGroup : {
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, modifier->metaInfo().require.groupID, modifier);
assert (locationGroupModifiersSet_.find(key) == locationGroupModifiersSet_.end());
locationGroupModifiersSet_.insert(key);
break;
}
case MetaInfo::Modifier::ModifierType::locationRequiredSkill :
case MetaInfo::Modifier::ModifierType::ownerRequiredSkill : {
auto skillID = modifier->metaInfo().require.typeID;
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, skillID, modifier);
assert (locationRequiredSkillModifiersSet_.find(key) == locationRequiredSkillModifiersSet_.end());
locationRequiredSkillModifiersSet_.insert(key);
break;
}
case MetaInfo::Modifier::ModifierType::locationRequiredDomainSkill : {
if (auto type = modifier->owner().domain_(modifier->metaInfo().require.domain)) {
auto skillID = type->metaInfo().typeID;
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, skillID, modifier);
assert (locationRequiredSkillModifiersSet_.find(key) == locationRequiredSkillModifiersSet_.end());
locationRequiredSkillModifiersSet_.insert(key);
break;
}
break;
}
default:
assert(!"Invalid MetaInfo::Modifier::ModifierType value");
}
resetCache_();
}
void Type::removeModifier_ (const Modifier* modifier) {
switch (modifier->metaInfo().type) {
case MetaInfo::Modifier::ModifierType::item : {
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, modifier);
assert (itemModifiersSet_.find(key) != itemModifiersSet_.end());
itemModifiersSet_.erase(key);
break;
}
case MetaInfo::Modifier::ModifierType::location : {
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, modifier);
assert (locationModifiersSet_.find(key) != locationModifiersSet_.end());
locationModifiersSet_.erase(key);
break;
}
case MetaInfo::Modifier::ModifierType::locationGroup : {
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, modifier->metaInfo().require.groupID, modifier);
assert (locationGroupModifiersSet_.find(key) != locationGroupModifiersSet_.end());
locationGroupModifiersSet_.erase(key);
break;
}
case MetaInfo::Modifier::ModifierType::locationRequiredSkill :
case MetaInfo::Modifier::ModifierType::ownerRequiredSkill : {
auto skillID = modifier->metaInfo().require.typeID;
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, skillID, modifier);
assert (locationRequiredSkillModifiersSet_.find(key) != locationRequiredSkillModifiersSet_.end());
locationRequiredSkillModifiersSet_.erase(key);
break;
}
case MetaInfo::Modifier::ModifierType::locationRequiredDomainSkill : {
if (auto type = modifier->owner().domain_(modifier->metaInfo().require.domain)) {
auto skillID = type->metaInfo().typeID;
auto key = std::make_tuple(modifier->metaInfo().modifiedAttributeID, skillID, modifier);
assert (locationRequiredSkillModifiersSet_.find(key) != locationRequiredSkillModifiersSet_.end());
locationRequiredSkillModifiersSet_.erase(key);
break;
}
break;
}
default:
assert(!"Invalid MetaInfo::Modifier::ModifierType value");
}
resetCache_();
}
std::list<const Modifier*> Type::itemModifiers_ (const MetaInfo::Attribute& attribute) {
auto key = std::make_tuple(attribute.attributeID);
auto range = equal_range(itemModifiersSet_, key);
std::list<const Modifier*> result;
std::transform(range.first, range.second, std::back_inserter(result), [](const auto& i) { return std::get<const Modifier*>(i); });
return result;
}
std::list<const Modifier*> Type::locationModifiers_ (const MetaInfo::Attribute& attribute) {
auto key = std::make_tuple(attribute.attributeID);
auto range = equal_range(locationModifiersSet_, key);
std::list<const Modifier*> result;
std::transform(range.first, range.second, std::back_inserter(result), [](const auto& i) { return std::get<const Modifier*>(i); });
return result;
}
std::list<const Modifier*> Type::locationGroupModifiers_ (const MetaInfo::Attribute& attribute, Type& type) {
auto key = std::make_tuple(attribute.attributeID, type.metaInfo().groupID);
auto range = equal_range(locationGroupModifiersSet_, key);
std::list<const Modifier*> result;
std::transform(range.first, range.second, std::back_inserter(result), [](const auto& i) { return std::get<const Modifier*>(i); });
return result;
}
std::list<const Modifier*> Type::locationRequiredSkillModifiers_ (const MetaInfo::Attribute& attribute, Type& type) {
auto attributeID = attribute.attributeID;
auto key = std::make_tuple(attributeID);
auto range = equal_range(locationRequiredSkillModifiersSet_, key);
if (range.first != range.second) {
auto subset = decltype(locationRequiredSkillModifiersSet_)(range.first, range.second);
// auto &subset = locationRequiredSkillModifiers_;
std::list<const Modifier*> list;
for (auto skillID: type.metaInfo().requiredSkills()) {
auto key = std::make_tuple(attributeID, skillID);
auto result = equal_range(subset, key);
if (result.first != result.second) {
std::transform(result.first, result.second, std::back_inserter(list), [](const auto& i) { return std::get<const Modifier*>(i); });
}
}
return list;
}
return {};
}
std::list<const Modifier*> Type::modifiers_ (const MetaInfo::Attribute& attribute) {
std::list<const Modifier*> result;
result.splice(result.end(), itemModifiers_(attribute));
if (auto parent = owner_()) {
result.splice(result.end(), parent->locationModifiers_(attribute));
result.splice(result.end(), parent->modifiersMatchingType_(attribute, *this));
}
return result;
}
std::list<const Modifier*> Type::modifiersMatchingType_ (const MetaInfo::Attribute& attribute, Type& type) {
std::list<const Modifier*> result;
result.splice(result.end(), locationGroupModifiers_(attribute, type));
result.splice(result.end(), locationRequiredSkillModifiers_(attribute, type));
if (auto parent = parent_()) {
result.splice(result.end(), parent->modifiersMatchingType_(attribute, type));
}
if (!buffs_.empty()) {
std::map<std::pair<WarfareBuffID, AttributeID>, std::pair<Float, const Modifier*>> modifiers;
for (const auto& buff: buffs_) {
for (const auto& modifier: std::get<const WarfareBuff*>(buff)->modifiers()) {
if (modifier.metaInfo().modifiedAttributeID == attribute.attributeID && modifier.match(&type)) {
auto key = std::make_pair(std::get<WarfareBuffID>(buff), modifier.metaInfo().modifyingAttributeID);
auto v = std::abs(modifier.value());
auto i = modifiers.find(key);
if (i == modifiers.end() || i->second.first < v) {
modifiers[key] = std::make_pair(v, &modifier);
}
}
}
}
std::transform(modifiers.begin(), modifiers.end(), std::back_inserter(result), [](const auto& i) { return i.second.second; });
/*std::vector<std::tuple<Float, WarfareBuffID, const WarfareBuff*>> v;
v.reserve(buffs_.size());
std::transform(buffs_.begin(), buffs_.end(), std::back_inserter(v), [](const auto& i) {
return std::tuple_cat(std::make_tuple(std::abs(std::get<const WarfareBuff*>(i)->value_())), i);
});
auto i = v.begin();
while (i != v.end()) {
auto j =std::upper_bound(i, v.end(), std::get<WarfareBuffID>(*i), [](auto id, const auto& v) {
return id < std::get<WarfareBuffID>(v);
});
auto max = std::max_element(i, j, [](const auto& a, const auto& b) {
return std::get<Float>(a) < std::get<Float>(b);
});
for (const auto& m: std::get<const WarfareBuff*>(*max)->modifiers()) {
if (m.metaInfo().modifiedAttributeID == attribute.attributeID && m.match(&type))
result.push_back(&m);
}
i = j;
}*/
}
return result;
}
void Type::activateEffects_ (MetaInfo::Effect::Category category) {
batchUpdates_([&]() {
auto range = std::equal_range(effects_.begin(), effects_.end(), category, EffectComparator());
std::for_each(range.first, range.second, [&](const auto& i) {
if (!i->isActive()) {
activate_(i.get());
}
});
});
}
void Type::deactivateEffects_ (MetaInfo::Effect::Category category) {
batchUpdates_([&]() {
auto range = std::equal_range(effects_.begin(), effects_.end(), category, EffectComparator());
std::for_each(range.first, range.second, [&](const auto& i) {
if (i->isActive()) {
deactivate_(i.get());
}
});
});
}
void Type::activate_ (Effect* effect) {
effect->setActive_(true);
for (const auto& modifier: effect->modifiers()) {
if (auto type = modifier.domain())
type->addModifier_(&modifier);
}
if (auto warfareBuffEffect = dynamic_cast<WarfareBuffEffect*>(effect)) {
if (auto gang = domain_(MetaInfo::Modifier::Domain::gang)) {
for (const auto& buff: warfareBuffEffect->warfareBuffs())
gang->addBuff_(&buff);
}
}
}
void Type::deactivate_ (Effect* effect) {
if (auto warfareBuffEffect = dynamic_cast<WarfareBuffEffect*>(effect)) {
if (auto gang = domain_(MetaInfo::Modifier::Domain::gang)) {
for (const auto& buff: warfareBuffEffect->warfareBuffs())
gang->removeBuff_(&buff);
}
}
effect->setActive_(false);
for (const auto& modifier: effect->modifiers()) {
if (auto type = modifier.domain())
type->removeModifier_(&modifier);
}
}
std::vector<Effect*> Type::activeEffects_() const {
std::vector<Effect*> effects;
effects.reserve(effects_.size());
for (const auto& effect: effects_) {
if (effect->isActive())
effects.push_back(effect.get());
}
return effects;
}
void Type::resetCache_() {
cache_().reset();
}
Type* Type::domain_ (MetaInfo::Modifier::Domain domain) noexcept {
if (domain == MetaInfo::Modifier::Domain::self)
return this;
else if (auto parent = parent_())
return parent->domain_(domain);
else
return nullptr;
}
Type::AttributesCache& Type::cache_() {
if (cacheValue_ != nullptr)
return *cacheValue_;
else if (auto parent = parent_()) {
return parent->cache_();
}
else {
cacheValue_ = std::unique_ptr<Type::AttributesCache>(new Type::AttributesCache);
return *cacheValue_;
}
}
void Type::addBuff_ (const WarfareBuff* buff) {
auto key = std::make_tuple(buff->metaInfo().warfareBuffID, buff);
assert (buffs_.find(key) == buffs_.end());
buffs_.insert(key);
}
void Type::removeBuff_ (const WarfareBuff* buff) {
auto key = std::make_tuple(buff->metaInfo().warfareBuffID, buff);
assert (buffs_.find(key) != buffs_.end());
buffs_.erase(key);
}
std::unordered_set<Type*> Type::affectors_() {
std::unordered_set<Type*> types;
for (const auto& i: attributesMap_) {
if (i.second) {
for (const auto& j: modifiers_(i.second->metaInfo())) {
types.insert(&j->owner());
}
}
}
return types;
}
std::list<Attribute*> Type::attributes_() const {
std::list<Attribute*> attributes;
for (const auto& i: attributesMap_) {
if (i.second) {
attributes.push_back(i.second.get());
}
}
return attributes;
}
#if DGMPP_THREADSAFE
std::mutex& Type::mutex_() const noexcept {
if (mutexValue_ != nullptr)
return *mutexValue_;
else if (auto parent = parent_())
return parent->mutex_();
else {
mutexValue_ = std::unique_ptr<std::mutex>(new std::mutex);
return *mutexValue_;
}
}
#endif
}
|
/***********************************************************************************************************************
* *
* libscopeprotocols *
* *
* Copyright (c) 2012-2022 Andrew D. Zonenberg and contributors *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "scopeprotocols.h"
#include "VectorPhaseFilter.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
VectorPhaseFilter::VectorPhaseFilter(const string& color)
: Filter(OscilloscopeChannel::CHANNEL_TYPE_ANALOG, color, CAT_RF)
{
//Set up channels
CreateInput("I");
CreateInput("Q");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory methods
bool VectorPhaseFilter::ValidateChannel(size_t i, StreamDescriptor stream)
{
if(stream.m_channel == NULL)
return false;
if(i > 1)
return false;
if(stream.m_channel->GetType() == OscilloscopeChannel::CHANNEL_TYPE_ANALOG)
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors
void VectorPhaseFilter::SetDefaultName()
{
char hwname[256];
snprintf(hwname, sizeof(hwname), "VectorPhase(%s,%s)", GetInputDisplayName(0).c_str(), GetInputDisplayName(1).c_str());
m_hwname = hwname;
m_displayname = m_hwname;
}
string VectorPhaseFilter::GetProtocolName()
{
return "Vector Phase";
}
bool VectorPhaseFilter::NeedsConfig()
{
return true;
}
float VectorPhaseFilter::GetVoltageRange(size_t /*stream*/)
{
return 370;
}
float VectorPhaseFilter::GetOffset(size_t /*stream*/)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Actual decoder logic
void VectorPhaseFilter::Refresh()
{
//Make sure we've got valid inputs
if(!VerifyAllInputsOKAndAnalog())
{
SetData(NULL, 0);
return;
}
//Get the input data
auto a = GetAnalogInputWaveform(0);
auto b = GetAnalogInputWaveform(1);
auto len = min(a->m_samples.size(), b->m_samples.size());
//Set up the output waveform
auto cap = new AnalogWaveform;
cap->Resize(len);
cap->CopyTimestamps(a);
float* fa = (float*)&a->m_samples[0];
float* fb = (float*)&b->m_samples[0];
float scale = 180 / M_PI;
for(size_t i=0; i<len; i++)
cap->m_samples[i] = atan2(fa[i], fb[i]) * scale;
//Copy our time scales from the input
cap->m_timescale = a->m_timescale;
cap->m_startTimestamp = a->m_startTimestamp;
cap->m_startFemtoseconds = a->m_startFemtoseconds;
SetYAxisUnits(Unit(Unit::UNIT_DEGREES), 0);
SetData(cap, 0);
}
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012-2014 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <BeastConfig.h>
#include <ripple/server/Role.h>
namespace ripple {
// Get state nodes from a ledger
// Inputs:
// limit: integer, maximum number of entries
// marker: opaque, resume point
// binary: boolean, format
// Outputs:
// ledger_hash: chosen ledger's hash
// ledger_index: chosen ledger's index
// state: array of state nodes
// marker: resume point, if any
Json::Value doLedgerData (RPC::Context& context)
{
int const BINARY_PAGE_LENGTH = 2048;
int const JSON_PAGE_LENGTH = 256;
Ledger::pointer lpLedger;
auto const& params = context.params;
Json::Value jvResult = RPC::lookupLedger (params, lpLedger, context.netOps);
if (!lpLedger)
return jvResult;
uint256 resumePoint;
if (params.isMember ("marker"))
{
Json::Value const& jMarker = params["marker"];
if (!jMarker.isString ())
return RPC::expected_field_error ("marker", "valid");
if (!resumePoint.SetHex (jMarker.asString ()))
return RPC::expected_field_error ("marker", "valid");
}
bool isBinary = params["binary"].asBool();
int limit = -1;
int maxLimit = isBinary ? BINARY_PAGE_LENGTH : JSON_PAGE_LENGTH;
if (params.isMember ("limit"))
{
Json::Value const& jLimit = params["limit"];
if (!jLimit.isIntegral ())
return RPC::expected_field_error ("limit", "integer");
limit = jLimit.asInt ();
}
if ((limit < 0) || ((limit > maxLimit) && (context.role != Role::ADMIN)))
limit = maxLimit;
jvResult["ledger_hash"] = to_string (lpLedger->getHash());
jvResult["ledger_index"] = std::to_string( lpLedger->getLedgerSeq ());
Json::Value& nodes = (jvResult["state"] = Json::arrayValue);
SHAMap& map = *(lpLedger->peekAccountStateMap ());
for (;;)
{
SHAMapItem::pointer item = map.peekNextItem (resumePoint);
if (!item)
break;
resumePoint = item->getTag();
if (limit-- <= 0)
{
--resumePoint;
jvResult["marker"] = to_string (resumePoint);
break;
}
if (isBinary)
{
Json::Value& entry = nodes.append (Json::objectValue);
entry["data"] = strHex (
item->peekData().begin(), item->peekData().size());
entry["index"] = to_string (item->getTag ());
}
else
{
SLE sle (item->peekSerializer(), item->getTag ());
Json::Value& entry = nodes.append (sle.getJson (0));
entry["index"] = to_string (item->getTag ());
}
}
return jvResult;
}
} // ripple
|
// Copyright 2014 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 "third_party/blink/renderer/core/paint/background_image_geometry.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
#include "third_party/blink/renderer/core/layout/layout_table_col.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/rounded_border_geometry.h"
#include "third_party/blink/renderer/core/style/border_edge.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
namespace blink {
namespace {
// Return the amount of space to leave between image tiles for the
// background-repeat: space property.
inline LayoutUnit GetSpaceBetweenImageTiles(LayoutUnit area_size,
LayoutUnit tile_size) {
int number_of_tiles = (area_size / tile_size).ToInt();
LayoutUnit space(-1);
if (number_of_tiles > 1) {
// Spec doesn't specify rounding, so use the same method as for
// background-repeat: round.
space = (area_size - number_of_tiles * tile_size) / (number_of_tiles - 1);
}
return space;
}
bool FixedBackgroundPaintsInLocalCoordinates(
const LayoutObject& obj,
const GlobalPaintFlags global_paint_flags) {
const auto* view = DynamicTo<LayoutView>(obj);
if (!view)
return false;
return !(view->GetBackgroundPaintLocation() &
kBackgroundPaintInScrollingContents);
}
PhysicalOffset AccumulatedScrollOffsetForFixedBackground(
const LayoutBoxModelObject& object,
const LayoutBoxModelObject* container) {
PhysicalOffset result;
if (&object == container)
return result;
LayoutObject::AncestorSkipInfo skip_info(container);
for (const LayoutBlock* block = object.ContainingBlock(&skip_info);
block && !skip_info.AncestorSkipped();
block = block->ContainingBlock(&skip_info)) {
if (block->HasOverflowClip())
result += PhysicalOffsetToBeNoop(block->ScrolledContentOffset());
if (block == container)
break;
}
return result;
}
} // anonymous namespace
bool NeedsFullSizeDestination(const FillLayer& fill_layer) {
// When dealing with a mask, the dest rect needs to maintain the full size
// and the mask should be expanded to fill it out. This allows the mask to
// correctly mask the entire area it is meant to. This is unnecessary on the
// last layer, so the normal background path is taken for efficiency when
// creating the paint shader later on.
return fill_layer.GetType() == EFillLayerType::kMask && fill_layer.Next() &&
fill_layer.Composite() != kCompositeSourceOver;
}
void BackgroundImageGeometry::SetNoRepeatX(const FillLayer& fill_layer,
LayoutUnit x_offset,
LayoutUnit snapped_x_offset) {
if (NeedsFullSizeDestination(fill_layer)) {
SetPhaseX(-x_offset.ToFloat());
SetSpaceSize(
PhysicalSize(unsnapped_dest_rect_.Width(), SpaceSize().height));
return;
}
if (x_offset > 0) {
// Move the dest rect if the offset is positive. The image "stays" where
// it is over the dest rect, so this effectively modifies the phase.
unsnapped_dest_rect_.Move(PhysicalOffset(x_offset, LayoutUnit()));
snapped_dest_rect_.SetX(LayoutUnit(unsnapped_dest_rect_.X().Round()));
// Make the dest as wide as a tile, which will reduce the dest
// rect if the tile is too small to fill the paint_rect. If not,
// the dest rect will be clipped when intersected with the paint
// rect.
unsnapped_dest_rect_.SetWidth(tile_size_.width);
snapped_dest_rect_.SetWidth(tile_size_.width);
SetPhaseX(0);
} else {
// Otherwise, if the offset is negative use it to move the image under
// the dest rect (since we can't paint outside the paint_rect).
SetPhaseX(-x_offset.ToFloat());
// Reduce the width of the dest rect to draw only the portion of the
// tile that remains visible after offsetting the image.
// TODO(schenney): This might grow the dest rect if the dest rect has
// been adjusted for opaque borders.
unsnapped_dest_rect_.SetWidth(tile_size_.width + x_offset);
snapped_dest_rect_.SetWidth(tile_size_.width + snapped_x_offset);
}
// Force the horizontal space to zero, retaining vertical.
SetSpaceSize(PhysicalSize(LayoutUnit(), SpaceSize().height));
}
void BackgroundImageGeometry::SetNoRepeatY(const FillLayer& fill_layer,
LayoutUnit y_offset,
LayoutUnit snapped_y_offset) {
if (NeedsFullSizeDestination(fill_layer)) {
SetPhaseY(-y_offset.ToFloat());
SetSpaceSize(
PhysicalSize(SpaceSize().width, unsnapped_dest_rect_.Height()));
return;
}
if (y_offset > 0) {
// Move the dest rect if the offset is positive. The image "stays" where
// it is in the paint rect, so this effectively modifies the phase.
unsnapped_dest_rect_.Move(PhysicalOffset(LayoutUnit(), y_offset));
snapped_dest_rect_.SetY(LayoutUnit(unsnapped_dest_rect_.Y().Round()));
// Make the dest as wide as a tile, which will reduce the dest
// rect if the tile is too small to fill the paint_rect. If not,
// the dest rect will be clipped when intersected with the paint
// rect.
unsnapped_dest_rect_.SetHeight(tile_size_.height);
snapped_dest_rect_.SetHeight(tile_size_.height);
SetPhaseY(0);
} else {
// Otherwise, if the offset is negative, use it to move the image under
// the dest rect (since we can't paint outside the paint_rect).
SetPhaseY(-y_offset.ToFloat());
// Reduce the height of the dest rect to draw only the portion of the
// tile that remains visible after offsetting the image.
// TODO(schenney): This might grow the dest rect if the dest rect has
// been adjusted for opaque borders.
unsnapped_dest_rect_.SetHeight(tile_size_.height + y_offset);
snapped_dest_rect_.SetHeight(tile_size_.height + snapped_y_offset);
}
// Force the vertical space to zero, retaining horizontal.
SetSpaceSize(PhysicalSize(SpaceSize().width, LayoutUnit()));
}
void BackgroundImageGeometry::SetRepeatX(const FillLayer& fill_layer,
LayoutUnit available_width,
LayoutUnit extra_offset) {
// All values are unsnapped to accurately set phase in the presence of
// zoom and large values. That is, accurately render the
// background-position value.
if (tile_size_.width) {
// Recompute computed_position because here we need to resolve against
// unsnapped widths to correctly set the phase.
LayoutUnit computed_position =
MinimumValueForLength(fill_layer.PositionX(), available_width) -
OffsetInBackground(fill_layer).left;
// Identify the number of tiles that fit within the computed
// position in the direction we should be moving.
float number_of_tiles_in_position;
if (fill_layer.BackgroundXOrigin() == BackgroundEdgeOrigin::kRight) {
number_of_tiles_in_position =
(available_width - computed_position + extra_offset).ToFloat() /
tile_size_.width.ToFloat();
} else {
number_of_tiles_in_position =
(computed_position + extra_offset).ToFloat() /
tile_size_.width.ToFloat();
}
// Assuming a non-integral number of tiles, find out how much of the
// partial tile is visible. That is the phase.
float fractional_position_within_tile =
1.0f -
(number_of_tiles_in_position - truncf(number_of_tiles_in_position));
SetPhaseX(fractional_position_within_tile * tile_size_.width);
} else {
SetPhaseX(0);
}
SetSpaceSize(PhysicalSize(LayoutUnit(), SpaceSize().height));
}
void BackgroundImageGeometry::SetRepeatY(const FillLayer& fill_layer,
LayoutUnit available_height,
LayoutUnit extra_offset) {
// All values are unsnapped to accurately set phase in the presence of
// zoom and large values. That is, accurately render the
// background-position value.
if (tile_size_.height) {
// Recompute computed_position because here we need to resolve against
// unsnapped widths to correctly set the phase.
LayoutUnit computed_position =
MinimumValueForLength(fill_layer.PositionY(), available_height) -
OffsetInBackground(fill_layer).top;
// Identify the number of tiles that fit within the computed
// position in the direction we should be moving.
float number_of_tiles_in_position;
if (fill_layer.BackgroundYOrigin() == BackgroundEdgeOrigin::kBottom) {
number_of_tiles_in_position =
(available_height - computed_position + extra_offset).ToFloat() /
tile_size_.height.ToFloat();
} else {
number_of_tiles_in_position =
(computed_position + extra_offset).ToFloat() /
tile_size_.height.ToFloat();
}
// Assuming a non-integral number of tiles, find out how much of the
// partial tile is visible. That is the phase.
float fractional_position_within_tile =
1.0f -
(number_of_tiles_in_position - truncf(number_of_tiles_in_position));
SetPhaseY(fractional_position_within_tile * tile_size_.height);
} else {
SetPhaseY(0);
}
SetSpaceSize(PhysicalSize(SpaceSize().width, LayoutUnit()));
}
void BackgroundImageGeometry::SetSpaceX(LayoutUnit space,
LayoutUnit extra_offset) {
SetSpaceSize(PhysicalSize(space, SpaceSize().height));
// Modify the phase to start a full tile at the edge of the paint area
LayoutUnit actual_width = tile_size_.width + space;
SetPhaseX(actual_width ? actual_width - fmodf(extra_offset, actual_width)
: 0);
}
void BackgroundImageGeometry::SetSpaceY(LayoutUnit space,
LayoutUnit extra_offset) {
SetSpaceSize(PhysicalSize(SpaceSize().width, space));
// Modify the phase to start a full tile at the edge of the paint area
LayoutUnit actual_height = tile_size_.height + space;
SetPhaseY(actual_height ? actual_height - fmodf(extra_offset, actual_height)
: 0);
}
void BackgroundImageGeometry::UseFixedAttachment(
const PhysicalOffset& attachment_point) {
PhysicalOffset aligned_point = attachment_point;
phase_.Move(
std::max((aligned_point.left - unsnapped_dest_rect_.X()).ToFloat(), 0.f),
std::max((aligned_point.top - unsnapped_dest_rect_.Y()).ToFloat(), 0.f));
}
enum ColumnGroupDirection { kColumnGroupStart, kColumnGroupEnd };
static void ExpandToTableColumnGroup(const LayoutTableCell& cell,
const LayoutTableCol& column_group,
LayoutUnit& value,
ColumnGroupDirection column_direction) {
auto sibling_cell = column_direction == kColumnGroupStart
? &LayoutTableCell::PreviousCell
: &LayoutTableCell::NextCell;
for (const auto* sibling = (cell.*sibling_cell)(); sibling;
sibling = (sibling->*sibling_cell)()) {
LayoutTableCol* innermost_col =
cell.Table()
->ColElementAtAbsoluteColumn(sibling->AbsoluteColumnIndex())
.InnermostColOrColGroup();
if (!innermost_col || innermost_col->EnclosingColumnGroup() != column_group)
break;
value += sibling->Size().Width();
}
}
PhysicalOffset BackgroundImageGeometry::GetPositioningOffsetForCell(
const LayoutTableCell& cell,
const LayoutBox& positioning_box) {
LayoutUnit h_border_spacing(cell.Table()->HBorderSpacing());
LayoutUnit v_border_spacing(cell.Table()->VBorderSpacing());
// TODO(layout-ng): It looks incorrect to use Location() in this function.
if (positioning_box.IsTableSection()) {
return PhysicalOffset(cell.Location().X() - h_border_spacing,
cell.Location().Y() - v_border_spacing);
}
if (positioning_box.IsTableRow()) {
return PhysicalOffset(cell.Location().X() - h_border_spacing, LayoutUnit());
}
PhysicalRect sections_rect(PhysicalOffset(), cell.Table()->Size());
cell.Table()->SubtractCaptionRect(sections_rect);
LayoutUnit height_of_captions =
cell.Table()->Size().Height() - sections_rect.Height();
PhysicalOffset offset_in_background = PhysicalOffset(
LayoutUnit(), (cell.Section()->Location().Y() -
cell.Table()->BorderBefore() - height_of_captions) +
cell.Location().Y());
DCHECK(positioning_box.IsLayoutTableCol());
if (ToLayoutTableCol(positioning_box).IsTableColumn()) {
offset_in_background.top -= v_border_spacing;
return offset_in_background;
}
DCHECK(ToLayoutTableCol(positioning_box).IsTableColumnGroup());
LayoutUnit offset = offset_in_background.left;
ExpandToTableColumnGroup(cell, ToLayoutTableCol(positioning_box), offset,
kColumnGroupStart);
offset_in_background.left += offset;
offset_in_background.top -= v_border_spacing;
return offset_in_background;
}
PhysicalSize BackgroundImageGeometry::GetBackgroundObjectDimensions(
const LayoutTableCell& cell,
const LayoutBox& positioning_box) {
PhysicalSize border_spacing(LayoutUnit(cell.Table()->HBorderSpacing()),
LayoutUnit(cell.Table()->VBorderSpacing()));
if (positioning_box.IsTableSection()) {
return PhysicalSizeToBeNoop(positioning_box.Size()) - border_spacing -
border_spacing;
}
if (positioning_box.IsTableRow()) {
return PhysicalSizeToBeNoop(positioning_box.Size()) -
PhysicalSize(border_spacing.width, LayoutUnit()) -
PhysicalSize(border_spacing.width, LayoutUnit());
}
DCHECK(positioning_box.IsLayoutTableCol());
PhysicalRect sections_rect(PhysicalOffset(), cell.Table()->Size());
cell.Table()->SubtractCaptionRect(sections_rect);
LayoutUnit column_height = sections_rect.Height() -
cell.Table()->BorderBefore() -
border_spacing.height - border_spacing.height;
if (ToLayoutTableCol(positioning_box).IsTableColumn())
return PhysicalSize(cell.Size().Width(), column_height);
DCHECK(ToLayoutTableCol(positioning_box).IsTableColumnGroup());
LayoutUnit width = cell.Size().Width();
ExpandToTableColumnGroup(cell, ToLayoutTableCol(positioning_box), width,
kColumnGroupStart);
ExpandToTableColumnGroup(cell, ToLayoutTableCol(positioning_box), width,
kColumnGroupEnd);
return PhysicalSize(width, column_height);
}
bool BackgroundImageGeometry::ShouldUseFixedAttachment(
const FillLayer& fill_layer) {
// Solid color background should use default attachment.
return fill_layer.GetImage() &&
fill_layer.Attachment() == EFillAttachment::kFixed;
}
namespace {
PhysicalRect FixedAttachmentPositioningArea(
const LayoutBoxModelObject& obj,
const LayoutBoxModelObject* container,
const GlobalPaintFlags flags) {
// TODO(crbug.com/966142): We should consider ancestor with transform as the
// fixed background container, instead of always the viewport.
LocalFrameView* frame_view = obj.View()->GetFrameView();
if (!frame_view)
return PhysicalRect();
ScrollableArea* layout_viewport = frame_view->LayoutViewport();
DCHECK(layout_viewport);
PhysicalRect rect(PhysicalOffset(),
PhysicalSize(layout_viewport->VisibleContentRect().Size()));
if (FixedBackgroundPaintsInLocalCoordinates(obj, flags))
return rect;
// The LayoutView is the only object that can paint a fixed background into
// its scrolling contents layer, so it gets a special adjustment here.
if (auto* layout_view = DynamicTo<LayoutView>(obj)) {
if (obj.GetBackgroundPaintLocation() &
kBackgroundPaintInScrollingContents) {
rect.offset =
PhysicalOffsetToBeNoop(layout_view->ScrolledContentOffset());
}
}
rect.Move(AccumulatedScrollOffsetForFixedBackground(obj, container));
if (container) {
rect.Move(
-container->LocalToAbsolutePoint(PhysicalOffset(), kIgnoreTransforms));
}
// By now we have converted the viewport rect to the border box space of
// |container|, however |container| does not necessarily create a paint
// offset translation node, thus its paint offset must be added to convert
// the rect to the space of the transform node.
// TODO(trchen): This function does only one simple thing -- mapping the
// viewport rect from frame space to whatever space the current paint
// context uses. However we can't always invoke geometry mapper because
// there are at least one caller uses this before PrePaint phase.
if (container) {
DCHECK_GE(container->GetDocument().Lifecycle().GetState(),
DocumentLifecycle::kPrePaintClean);
rect.Move(container->FirstFragment().PaintOffset());
}
return rect;
}
} // Anonymous namespace
BackgroundImageGeometry::BackgroundImageGeometry(
const LayoutView& view,
const PhysicalOffset& element_positioning_area_offset)
: box_(&view), positioning_box_(&view.RootBox()), painting_view_(true) {
// The background of the box generated by the root element covers the
// entire canvas and will be painted by the view object, but the we should
// still use the root element box for positioning.
positioning_size_override_ = PhysicalSizeToBeNoop(view.RootBox().Size());
// The background image should paint from the root element's coordinate space.
element_positioning_area_offset_ = element_positioning_area_offset;
}
BackgroundImageGeometry::BackgroundImageGeometry(
const LayoutBoxModelObject& obj)
: box_(&obj), positioning_box_(&obj) {
// Specialized constructor should be used for LayoutView.
DCHECK(!IsA<LayoutView>(obj));
}
BackgroundImageGeometry::BackgroundImageGeometry(
const LayoutTableCell& cell,
const LayoutObject* background_object)
: box_(&cell),
positioning_box_(background_object && !background_object->IsTableCell()
? &ToLayoutBoxModelObject(*background_object)
: &cell),
painting_table_cell_(true) {
cell_using_container_background_ =
background_object && !background_object->IsTableCell();
if (cell_using_container_background_) {
element_positioning_area_offset_ =
GetPositioningOffsetForCell(cell, ToLayoutBox(*background_object));
positioning_size_override_ =
GetBackgroundObjectDimensions(cell, ToLayoutBox(*background_object));
}
}
void BackgroundImageGeometry::ComputeDestRectAdjustments(
const FillLayer& fill_layer,
const PhysicalRect& unsnapped_positioning_area,
bool disallow_border_derived_adjustment,
LayoutRectOutsets& unsnapped_dest_adjust,
LayoutRectOutsets& snapped_dest_adjust) const {
switch (fill_layer.Clip()) {
case EFillBox::kContent:
// If the PaddingOutsets are zero then this is equivalent to
// kPadding and we should apply the snapping logic.
unsnapped_dest_adjust = positioning_box_->PaddingOutsets();
if (!unsnapped_dest_adjust.IsZero()) {
unsnapped_dest_adjust += positioning_box_->BorderBoxOutsets();
// We're not trying to match a border position, so don't snap.
snapped_dest_adjust = unsnapped_dest_adjust;
return;
}
FALLTHROUGH;
case EFillBox::kPadding:
unsnapped_dest_adjust = positioning_box_->BorderBoxOutsets();
if (disallow_border_derived_adjustment) {
// Nothing to drive snapping behavior, so don't snap.
snapped_dest_adjust = unsnapped_dest_adjust;
} else {
// Force the snapped dest rect to match the inner border to
// avoid gaps between the background and border.
// TODO(schenney) The LayoutUnit(float) constructor always
// rounds down. We should FromFloatFloor or FromFloatCeil to
// move toward the border.
FloatRect inner_border_rect =
RoundedBorderGeometry::PixelSnappedRoundedInnerBorder(
positioning_box_->StyleRef(), unsnapped_positioning_area)
.Rect();
snapped_dest_adjust.SetLeft(LayoutUnit(inner_border_rect.X()) -
unsnapped_dest_rect_.X());
snapped_dest_adjust.SetTop(LayoutUnit(inner_border_rect.Y()) -
unsnapped_dest_rect_.Y());
snapped_dest_adjust.SetRight(unsnapped_dest_rect_.Right() -
LayoutUnit(inner_border_rect.MaxX()));
snapped_dest_adjust.SetBottom(unsnapped_dest_rect_.Bottom() -
LayoutUnit(inner_border_rect.MaxY()));
}
return;
case EFillBox::kBorder: {
if (disallow_border_derived_adjustment) {
// All adjustments remain 0.
return;
}
// The dest rects can be adjusted. The snapped dest rect is forced
// to match the inner border to avoid gaps between the background and
// border, while the unsnapped dest moves according to the
// border box outsets. This leaves the unsnapped dest accurately
// conveying the content creator's intent when used for determining
// the pixels to use from sprite maps and other size and positioning
// properties.
// Note that the snapped adjustments do not have the same effect as
// pixel snapping the unsnapped rectangle. Border snapping snaps both
// the size and position of the borders, sometimes adjusting the inner
// border by more than a pixel when done (particularly under magnifying
// zoom).
// TODO(schenney) The LayoutUnit(float) constructor always
// rounds down. We should FromFloatFloor or FromFloatCeil to
// move toward the border.
BorderEdge edges[4];
positioning_box_->StyleRef().GetBorderEdgeInfo(edges);
FloatRect inner_border_rect =
RoundedBorderGeometry::PixelSnappedRoundedInnerBorder(
positioning_box_->StyleRef(), unsnapped_positioning_area)
.Rect();
LayoutRectOutsets box_outsets = positioning_box_->BorderBoxOutsets();
if (edges[static_cast<unsigned>(BoxSide::kTop)].ObscuresBackground()) {
snapped_dest_adjust.SetTop(LayoutUnit(inner_border_rect.Y()) -
unsnapped_dest_rect_.Y());
unsnapped_dest_adjust.SetTop(box_outsets.Top());
}
if (edges[static_cast<unsigned>(BoxSide::kRight)].ObscuresBackground()) {
snapped_dest_adjust.SetRight(unsnapped_dest_rect_.Right() -
LayoutUnit(inner_border_rect.MaxX()));
unsnapped_dest_adjust.SetRight(box_outsets.Right());
}
if (edges[static_cast<unsigned>(BoxSide::kBottom)].ObscuresBackground()) {
snapped_dest_adjust.SetBottom(unsnapped_dest_rect_.Bottom() -
LayoutUnit(inner_border_rect.MaxY()));
unsnapped_dest_adjust.SetBottom(box_outsets.Bottom());
}
if (edges[static_cast<unsigned>(BoxSide::kLeft)].ObscuresBackground()) {
snapped_dest_adjust.SetLeft(LayoutUnit(inner_border_rect.X()) -
unsnapped_dest_rect_.X());
unsnapped_dest_adjust.SetLeft(box_outsets.Left());
}
}
return;
case EFillBox::kText:
return;
}
}
void BackgroundImageGeometry::ComputePositioningAreaAdjustments(
const FillLayer& fill_layer,
const PhysicalRect& unsnapped_positioning_area,
bool disallow_border_derived_adjustment,
LayoutRectOutsets& unsnapped_box_outset,
LayoutRectOutsets& snapped_box_outset) const {
switch (fill_layer.Origin()) {
case EFillBox::kContent:
// If the PaddingOutsets are zero then this is equivalent to
// kPadding and we should apply the snapping logic.
unsnapped_box_outset = positioning_box_->PaddingOutsets();
if (!unsnapped_box_outset.IsZero()) {
unsnapped_box_outset += positioning_box_->BorderBoxOutsets();
// We're not trying to match a border position, so don't snap.
snapped_box_outset = unsnapped_box_outset;
return;
}
FALLTHROUGH;
case EFillBox::kPadding:
unsnapped_box_outset = positioning_box_->BorderBoxOutsets();
if (disallow_border_derived_adjustment) {
snapped_box_outset = unsnapped_box_outset;
} else {
// Force the snapped positioning area to fill to the borders.
// Note that the snapped adjustments do not have the same effect as
// pixel snapping the unsnapped rectangle. Border snapping snaps both
// the size and position of the borders, sometimes adjusting the inner
// border by more than a pixel when done (particularly under magnifying
// zoom).
FloatRect inner_border_rect =
RoundedBorderGeometry::PixelSnappedRoundedInnerBorder(
positioning_box_->StyleRef(), unsnapped_positioning_area)
.Rect();
snapped_box_outset.SetLeft(LayoutUnit(inner_border_rect.X()) -
unsnapped_positioning_area.X());
snapped_box_outset.SetTop(LayoutUnit(inner_border_rect.Y()) -
unsnapped_positioning_area.Y());
snapped_box_outset.SetRight(unsnapped_positioning_area.Right() -
LayoutUnit(inner_border_rect.MaxX()));
snapped_box_outset.SetBottom(unsnapped_positioning_area.Bottom() -
LayoutUnit(inner_border_rect.MaxY()));
}
return;
case EFillBox::kBorder:
// All adjustments remain 0.
snapped_box_outset = unsnapped_box_outset = LayoutRectOutsets(0, 0, 0, 0);
return;
case EFillBox::kText:
return;
}
}
void BackgroundImageGeometry::ComputePositioningArea(
const LayoutBoxModelObject* container,
PaintPhase paint_phase,
GlobalPaintFlags flags,
const FillLayer& fill_layer,
const PhysicalRect& paint_rect,
PhysicalRect& unsnapped_positioning_area,
PhysicalRect& snapped_positioning_area,
PhysicalOffset& unsnapped_box_offset,
PhysicalOffset& snapped_box_offset) {
if (ShouldUseFixedAttachment(fill_layer)) {
// No snapping for fixed attachment.
SetHasNonLocalGeometry();
unsnapped_positioning_area =
FixedAttachmentPositioningArea(*box_, container, flags);
unsnapped_dest_rect_ = snapped_dest_rect_ = snapped_positioning_area =
unsnapped_positioning_area;
} else {
unsnapped_dest_rect_ = paint_rect;
if (painting_view_ || cell_using_container_background_)
unsnapped_positioning_area.size = positioning_size_override_;
else
unsnapped_positioning_area = unsnapped_dest_rect_;
// Attempt to shrink the destination rect if possible while also ensuring
// that it paints to the border:
//
// * for background-clip content-box/padding-box, we can restrict to the
// respective box, but for padding-box we also try to force alignment
// with the inner border.
//
// * for border-box, we can modify individual edges iff the border fully
// obscures the background.
//
// It is unsafe to derive dest from border information when any of the
// following is true:
// * the layer is not painted as part of a regular background phase
// (e.g.paint_phase == kMask)
// * non-SrcOver compositing is active
// * painting_view_ is set, meaning we're dealing with a
// LayoutView - for which dest rect is overflowing (expanded to cover
// the whole canvas).
// * We are painting table cells using the table background, or the table
// has collapsed borders
// * There is a border image, because it may not be opaque or may be outset.
bool disallow_border_derived_adjustment =
!ShouldPaintSelfBlockBackground(paint_phase) ||
fill_layer.Composite() != CompositeOperator::kCompositeSourceOver ||
painting_view_ || painting_table_cell_ ||
positioning_box_->StyleRef().BorderImage().GetImage() ||
positioning_box_->StyleRef().BorderCollapse() ==
EBorderCollapse::kCollapse;
// Compute all the outsets we need to apply to the rectangles. These
// outsets also include the snapping behavior.
LayoutRectOutsets unsnapped_dest_adjust;
LayoutRectOutsets snapped_dest_adjust;
ComputeDestRectAdjustments(fill_layer, unsnapped_positioning_area,
disallow_border_derived_adjustment,
unsnapped_dest_adjust, snapped_dest_adjust);
LayoutRectOutsets unsnapped_box_outset;
LayoutRectOutsets snapped_box_outset;
ComputePositioningAreaAdjustments(fill_layer, unsnapped_positioning_area,
disallow_border_derived_adjustment,
unsnapped_box_outset, snapped_box_outset);
// Apply the adjustments.
snapped_dest_rect_ = unsnapped_dest_rect_;
snapped_dest_rect_.Contract(snapped_dest_adjust);
snapped_dest_rect_ = PhysicalRect(PixelSnappedIntRect(snapped_dest_rect_));
unsnapped_dest_rect_.Contract(unsnapped_dest_adjust);
snapped_positioning_area = unsnapped_positioning_area;
snapped_positioning_area.Contract(snapped_box_outset);
snapped_positioning_area =
PhysicalRect(PixelSnappedIntRect(snapped_positioning_area));
unsnapped_positioning_area.Contract(unsnapped_box_outset);
// Offset of the positioning area from the corner of the
// positioning_box_->
// TODO(schenney): Could we enable dest adjust for collapsed
// borders if we computed this based on the actual offset between
// the rects?
unsnapped_box_offset = PhysicalOffset(
unsnapped_box_outset.Left() - unsnapped_dest_adjust.Left(),
unsnapped_box_outset.Top() - unsnapped_dest_adjust.Top());
snapped_box_offset =
PhysicalOffset(snapped_box_outset.Left() - snapped_dest_adjust.Left(),
snapped_box_outset.Top() - snapped_dest_adjust.Top());
}
}
void BackgroundImageGeometry::CalculateFillTileSize(
const FillLayer& fill_layer,
const PhysicalSize& unsnapped_positioning_area_size,
const PhysicalSize& snapped_positioning_area_size) {
StyleImage* image = fill_layer.GetImage();
EFillSizeType type = fill_layer.SizeType();
// Tile size is snapped for images without intrinsic dimensions (typically
// generated content) and unsnapped for content that has intrinsic
// dimensions. Once we choose here we stop tracking whether the tile size is
// snapped or unsnapped.
PhysicalSize positioning_area_size = !image->HasIntrinsicSize()
? snapped_positioning_area_size
: unsnapped_positioning_area_size;
PhysicalSize image_intrinsic_size = PhysicalSize::FromFloatSizeFloor(
image->ImageSize(positioning_box_->GetDocument(),
positioning_box_->StyleRef().EffectiveZoom(),
FloatSize(positioning_area_size),
LayoutObject::ShouldRespectImageOrientation(box_)));
switch (type) {
case EFillSizeType::kSizeLength: {
tile_size_ = positioning_area_size;
const Length& layer_width = fill_layer.SizeLength().Width();
const Length& layer_height = fill_layer.SizeLength().Height();
if (layer_width.IsFixed()) {
tile_size_.width = LayoutUnit(layer_width.Value());
} else if (layer_width.IsPercentOrCalc()) {
tile_size_.width =
ValueForLength(layer_width, positioning_area_size.width);
}
if (layer_height.IsFixed()) {
tile_size_.height = LayoutUnit(layer_height.Value());
} else if (layer_height.IsPercentOrCalc()) {
tile_size_.height =
ValueForLength(layer_height, positioning_area_size.height);
}
// If one of the values is auto we have to use the appropriate
// scale to maintain our aspect ratio.
if (layer_width.IsAuto() && !layer_height.IsAuto()) {
if (!image->HasIntrinsicSize()) {
// Spec says that auto should be 100% in the absence of
// an intrinsic ratio or size.
tile_size_.width = positioning_area_size.width;
} else if (image_intrinsic_size.height) {
float adjusted_width = image_intrinsic_size.width.ToFloat() /
image_intrinsic_size.height.ToFloat() *
tile_size_.height.ToFloat();
if (image_intrinsic_size.width >= 1 && adjusted_width < 1)
adjusted_width = 1;
tile_size_.width = LayoutUnit(adjusted_width);
}
} else if (!layer_width.IsAuto() && layer_height.IsAuto()) {
if (!image->HasIntrinsicSize()) {
// Spec says that auto should be 100% in the absence of
// an intrinsic ratio or size.
tile_size_.height = positioning_area_size.height;
} else if (image_intrinsic_size.width) {
float adjusted_height = image_intrinsic_size.height.ToFloat() /
image_intrinsic_size.width.ToFloat() *
tile_size_.width.ToFloat();
if (image_intrinsic_size.height >= 1 && adjusted_height < 1)
adjusted_height = 1;
tile_size_.height = LayoutUnit(adjusted_height);
}
} else if (layer_width.IsAuto() && layer_height.IsAuto()) {
// If both width and height are auto, use the image's intrinsic size.
tile_size_ = image_intrinsic_size;
}
tile_size_.ClampNegativeToZero();
return;
}
case EFillSizeType::kContain:
case EFillSizeType::kCover: {
// Always use the snapped positioning area size for this computation,
// so that we resize the image to completely fill the actual painted
// area.
float horizontal_scale_factor =
image_intrinsic_size.width
? snapped_positioning_area_size.width.ToFloat() /
image_intrinsic_size.width
: 1.0f;
float vertical_scale_factor =
image_intrinsic_size.height
? snapped_positioning_area_size.height.ToFloat() /
image_intrinsic_size.height
: 1.0f;
// Force the dimension that determines the size to exactly match the
// positioning_area_size in that dimension, so that rounding of floating
// point approximation to LayoutUnit do not shrink the image to smaller
// than the positioning_area_size.
if (type == EFillSizeType::kContain) {
// Snap the dependent dimension to avoid bleeding/blending artifacts
// at the edge of the image when we paint it.
if (horizontal_scale_factor < vertical_scale_factor) {
tile_size_ = PhysicalSize(
snapped_positioning_area_size.width,
LayoutUnit(std::max(1.0f, roundf(image_intrinsic_size.height *
horizontal_scale_factor))));
} else {
tile_size_ = PhysicalSize(
LayoutUnit(std::max(1.0f, roundf(image_intrinsic_size.width *
vertical_scale_factor))),
snapped_positioning_area_size.height);
}
return;
}
if (horizontal_scale_factor > vertical_scale_factor) {
tile_size_ = PhysicalSize(
snapped_positioning_area_size.width,
LayoutUnit(std::max(
1.0f, image_intrinsic_size.height * horizontal_scale_factor)));
} else {
tile_size_ =
PhysicalSize(LayoutUnit(std::max(1.0f, image_intrinsic_size.width *
vertical_scale_factor)),
snapped_positioning_area_size.height);
}
return;
}
case EFillSizeType::kSizeNone:
// This value should only be used while resolving style.
NOTREACHED();
}
NOTREACHED();
return;
}
void BackgroundImageGeometry::Calculate(const LayoutBoxModelObject* container,
PaintPhase paint_phase,
GlobalPaintFlags flags,
const FillLayer& fill_layer,
const PhysicalRect& paint_rect) {
// Unsnapped positioning area is used to derive quantities
// that reference source image maps and define non-integer values, such
// as phase and position.
PhysicalRect unsnapped_positioning_area;
// Snapped positioning area is used for sizing images based on the
// background area (like cover and contain), and for setting the repeat
// spacing.
PhysicalRect snapped_positioning_area;
// Additional offset from the corner of the positioning_box_
PhysicalOffset unsnapped_box_offset;
PhysicalOffset snapped_box_offset;
// This method also sets the destination rects.
ComputePositioningArea(container, paint_phase, flags, fill_layer, paint_rect,
unsnapped_positioning_area, snapped_positioning_area,
unsnapped_box_offset, snapped_box_offset);
// Sets the tile_size_.
CalculateFillTileSize(fill_layer, unsnapped_positioning_area.size,
snapped_positioning_area.size);
EFillRepeat background_repeat_x = fill_layer.RepeatX();
EFillRepeat background_repeat_y = fill_layer.RepeatY();
// Maintain both snapped and unsnapped available widths and heights.
// Unsnapped values are used for most thing, but snapped are used
// to computed sizes that must fill the area, such as round and space.
LayoutUnit unsnapped_available_width =
unsnapped_positioning_area.Width() - tile_size_.width;
LayoutUnit unsnapped_available_height =
unsnapped_positioning_area.Height() - tile_size_.height;
LayoutUnit snapped_available_width =
snapped_positioning_area.Width() - tile_size_.width;
LayoutUnit snapped_available_height =
snapped_positioning_area.Height() - tile_size_.height;
PhysicalSize snapped_positioning_area_size = snapped_positioning_area.size;
// Computed position is for placing things within the destination, so use
// snapped values.
LayoutUnit computed_x_position =
MinimumValueForLength(fill_layer.PositionX(), snapped_available_width) -
OffsetInBackground(fill_layer).left;
LayoutUnit computed_y_position =
MinimumValueForLength(fill_layer.PositionY(), snapped_available_height) -
OffsetInBackground(fill_layer).top;
if (background_repeat_x == EFillRepeat::kRoundFill &&
snapped_positioning_area_size.width > LayoutUnit() &&
tile_size_.width > LayoutUnit()) {
int nr_tiles = std::max(
1, RoundToInt(snapped_positioning_area_size.width / tile_size_.width));
LayoutUnit rounded_width = snapped_positioning_area_size.width / nr_tiles;
// Maintain aspect ratio if background-size: auto is set
if (fill_layer.SizeLength().Height().IsAuto() &&
background_repeat_y != EFillRepeat::kRoundFill) {
tile_size_.height = tile_size_.height * rounded_width / tile_size_.width;
}
tile_size_.width = rounded_width;
// Force the first tile to line up with the edge of the positioning area.
SetPhaseX(tile_size_.width
? tile_size_.width -
fmodf(computed_x_position + unsnapped_box_offset.left,
tile_size_.width)
: 0);
SetSpaceSize(PhysicalSize());
}
if (background_repeat_y == EFillRepeat::kRoundFill &&
snapped_positioning_area_size.height > LayoutUnit() &&
tile_size_.height > LayoutUnit()) {
int nr_tiles = std::max(1, RoundToInt(snapped_positioning_area_size.height /
tile_size_.height));
LayoutUnit rounded_height = snapped_positioning_area_size.height / nr_tiles;
// Maintain aspect ratio if background-size: auto is set
if (fill_layer.SizeLength().Width().IsAuto() &&
background_repeat_x != EFillRepeat::kRoundFill) {
tile_size_.width = tile_size_.width * rounded_height / tile_size_.height;
}
tile_size_.height = rounded_height;
// Force the first tile to line up with the edge of the positioning area.
SetPhaseY(tile_size_.height
? tile_size_.height -
fmodf(computed_y_position + unsnapped_box_offset.top,
tile_size_.height)
: 0);
SetSpaceSize(PhysicalSize());
}
if (background_repeat_x == EFillRepeat::kRepeatFill) {
// Repeat must set the phase accurately, so use unsnapped values.
SetRepeatX(fill_layer, unsnapped_available_width,
unsnapped_box_offset.left);
} else if (background_repeat_x == EFillRepeat::kSpaceFill &&
tile_size_.width > LayoutUnit()) {
// SpaceFill uses snapped values to fill the painted area.
LayoutUnit space = GetSpaceBetweenImageTiles(
snapped_positioning_area_size.width, tile_size_.width);
if (space >= LayoutUnit())
SetSpaceX(space, snapped_box_offset.left);
else
background_repeat_x = EFillRepeat::kNoRepeatFill;
}
if (background_repeat_x == EFillRepeat::kNoRepeatFill) {
// NoRepeat moves the dest rects, so needs both snapped and
// unsnapped parameters.
LayoutUnit x_offset =
fill_layer.BackgroundXOrigin() == BackgroundEdgeOrigin::kRight
? unsnapped_available_width - computed_x_position
: computed_x_position;
LayoutUnit snapped_x_offset =
fill_layer.BackgroundXOrigin() == BackgroundEdgeOrigin::kRight
? snapped_available_width - computed_x_position
: computed_x_position;
SetNoRepeatX(fill_layer, unsnapped_box_offset.left + x_offset,
snapped_box_offset.left + snapped_x_offset);
if (OffsetInBackground(fill_layer).left > tile_size_.width)
unsnapped_dest_rect_ = snapped_dest_rect_ = PhysicalRect();
}
if (background_repeat_y == EFillRepeat::kRepeatFill) {
// Repeat must set the phase accurately, so use unsnapped values.
SetRepeatY(fill_layer, unsnapped_available_height,
unsnapped_box_offset.top);
} else if (background_repeat_y == EFillRepeat::kSpaceFill &&
tile_size_.height > LayoutUnit()) {
// SpaceFill uses snapped values to fill the painted area.
LayoutUnit space = GetSpaceBetweenImageTiles(
snapped_positioning_area_size.height, tile_size_.height);
if (space >= LayoutUnit())
SetSpaceY(space, snapped_box_offset.top);
else
background_repeat_y = EFillRepeat::kNoRepeatFill;
}
if (background_repeat_y == EFillRepeat::kNoRepeatFill) {
// NoRepeat moves the dest rects, so needs both snapped and
// unsnapped parameters.
LayoutUnit y_offset =
fill_layer.BackgroundYOrigin() == BackgroundEdgeOrigin::kBottom
? unsnapped_available_height - computed_y_position
: computed_y_position;
LayoutUnit snapped_y_offset =
fill_layer.BackgroundYOrigin() == BackgroundEdgeOrigin::kBottom
? snapped_available_height - computed_y_position
: computed_y_position;
SetNoRepeatY(fill_layer, unsnapped_box_offset.top + y_offset,
snapped_box_offset.top + snapped_y_offset);
if (OffsetInBackground(fill_layer).top > tile_size_.height)
unsnapped_dest_rect_ = snapped_dest_rect_ = PhysicalRect();
}
if (ShouldUseFixedAttachment(fill_layer))
UseFixedAttachment(paint_rect.offset);
// Clip the final output rect to the paint rect.
unsnapped_dest_rect_.Intersect(paint_rect);
// Clip the snapped rect, and re-snap the dest rect as we may have
// adjusted it with unsnapped values.
snapped_dest_rect_.Intersect(paint_rect);
snapped_dest_rect_ = PhysicalRect(PixelSnappedIntRect(snapped_dest_rect_));
}
const ImageResourceObserver& BackgroundImageGeometry::ImageClient() const {
return *(painting_view_ ? box_ : positioning_box_);
}
const Document& BackgroundImageGeometry::ImageDocument() const {
return box_->GetDocument();
}
const ComputedStyle& BackgroundImageGeometry::ImageStyle() const {
const bool use_style_from_positioning_box =
painting_view_ || cell_using_container_background_;
return (use_style_from_positioning_box ? positioning_box_ : box_)->StyleRef();
}
InterpolationQuality BackgroundImageGeometry::ImageInterpolationQuality()
const {
return box_->StyleRef().GetInterpolationQuality();
}
PhysicalOffset BackgroundImageGeometry::OffsetInBackground(
const FillLayer& fill_layer) const {
if (ShouldUseFixedAttachment(fill_layer))
return PhysicalOffset();
return element_positioning_area_offset_;
}
} // namespace blink
|
/******************************************************************************
* $Id$
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Implements OGRPGTableLayer class, access to an existing table.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2000, Frank Warmerdam
* Copyright (c) 2008-2014, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "ogr_pg.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_error.h"
#include "ogr_p.h"
#define PQexec this_is_an_error
CPL_CVSID("$Id$");
#define USE_COPY_UNSET -10
#define UNSUPPORTED_OP_READ_ONLY "%s : unsupported operation on a read-only datasource."
/************************************************************************/
/* OGRPGTableFeatureDefn */
/************************************************************************/
class OGRPGTableFeatureDefn : public OGRPGFeatureDefn
{
private:
OGRPGTableLayer *poLayer;
void SolveFields();
public:
OGRPGTableFeatureDefn( OGRPGTableLayer* poLayerIn,
const char * pszName = NULL ) :
OGRPGFeatureDefn(pszName), poLayer(poLayerIn)
{
}
virtual void UnsetLayer()
{
poLayer = NULL;
OGRPGFeatureDefn::UnsetLayer();
}
virtual int GetFieldCount()
{ SolveFields(); return OGRPGFeatureDefn::GetFieldCount(); }
virtual OGRFieldDefn *GetFieldDefn( int i )
{ SolveFields(); return OGRPGFeatureDefn::GetFieldDefn(i); }
virtual int GetFieldIndex( const char * pszName )
{ SolveFields(); return OGRPGFeatureDefn::GetFieldIndex(pszName); }
virtual int GetGeomFieldCount()
{ if (poLayer != NULL && !poLayer->HasGeometryInformation())
SolveFields();
return OGRPGFeatureDefn::GetGeomFieldCount(); }
virtual OGRGeomFieldDefn *GetGeomFieldDefn( int i )
{ if (poLayer != NULL && !poLayer->HasGeometryInformation())
SolveFields();
return OGRPGFeatureDefn::GetGeomFieldDefn(i); }
virtual int GetGeomFieldIndex( const char * pszName)
{ if (poLayer != NULL && !poLayer->HasGeometryInformation())
SolveFields();
return OGRPGFeatureDefn::GetGeomFieldIndex(pszName); }
};
/************************************************************************/
/* SolveFields() */
/************************************************************************/
void OGRPGTableFeatureDefn::SolveFields()
{
if( poLayer == NULL )
return;
poLayer->ReadTableDefinition();
}
/************************************************************************/
/* GetFIDColumn() */
/************************************************************************/
const char *OGRPGTableLayer::GetFIDColumn()
{
ReadTableDefinition();
if( pszFIDColumn != NULL )
return pszFIDColumn;
else
return "";
}
/************************************************************************/
/* OGRPGTableLayer() */
/************************************************************************/
OGRPGTableLayer::OGRPGTableLayer( OGRPGDataSource *poDSIn,
CPLString& osCurrentSchema,
const char * pszTableNameIn,
const char * pszSchemaNameIn,
const char * pszDescriptionIn,
const char * pszGeomColForcedIn,
int bUpdate )
{
poDS = poDSIn;
pszQueryStatement = NULL;
bUpdateAccess = bUpdate;
bGeometryInformationSet = FALSE;
bLaunderColumnNames = TRUE;
bPreservePrecision = TRUE;
bCopyActive = FALSE;
bUseCopy = USE_COPY_UNSET; // unknown
bUseCopyByDefault = FALSE;
bFIDColumnInCopyFields = FALSE;
bFirstInsertion = TRUE;
pszTableName = CPLStrdup( pszTableNameIn );
if (pszSchemaNameIn)
pszSchemaName = CPLStrdup( pszSchemaNameIn );
else
pszSchemaName = CPLStrdup( osCurrentSchema );
this->pszGeomColForced =
pszGeomColForcedIn ? CPLStrdup(pszGeomColForcedIn) : NULL;
pszSqlGeomParentTableName = NULL;
bTableDefinitionValid = -1;
bHasWarnedIncompatibleGeom = FALSE;
bHasWarnedAlreadySetFID = FALSE;
/* Just in provision for people yelling about broken backward compatibility ... */
bRetrieveFID = CPLTestBool(CPLGetConfigOption("OGR_PG_RETRIEVE_FID", "TRUE"));
/* -------------------------------------------------------------------- */
/* Build the layer defn name. */
/* -------------------------------------------------------------------- */
CPLString osDefnName;
if ( pszSchemaNameIn && osCurrentSchema != pszSchemaNameIn )
{
osDefnName.Printf("%s.%s", pszSchemaNameIn, pszTableName );
pszSqlTableName = CPLStrdup(CPLString().Printf("%s.%s",
OGRPGEscapeColumnName(pszSchemaNameIn).c_str(),
OGRPGEscapeColumnName(pszTableName).c_str() ));
}
else
{
//no prefix for current_schema in layer name, for backwards compatibility
osDefnName = pszTableName;
pszSqlTableName = CPLStrdup(OGRPGEscapeColumnName(pszTableName));
}
if( pszGeomColForced != NULL )
{
osDefnName += "(";
osDefnName += pszGeomColForced;
osDefnName += ")";
}
osPrimaryKey = CPLGetConfigOption( "PGSQL_OGR_FID", "ogc_fid" );
papszOverrideColumnTypes = NULL;
nForcedSRSId = UNDETERMINED_SRID;
nForcedGeometryTypeFlags = -1;
bCreateSpatialIndexFlag = TRUE;
bInResetReading = FALSE;
poFeatureDefn = new OGRPGTableFeatureDefn( this, osDefnName );
SetDescription( poFeatureDefn->GetName() );
poFeatureDefn->Reference();
bAutoFIDOnCreateViaCopy = FALSE;
bDeferredCreation = FALSE;
iFIDAsRegularColumnIndex = -1;
pszDescription = (pszDescriptionIn) ? CPLStrdup(pszDescriptionIn) : NULL;
if( pszDescriptionIn != NULL && !EQUAL(pszDescriptionIn, "") )
{
OGRLayer::SetMetadataItem("DESCRIPTION", pszDescriptionIn);
}
}
//************************************************************************/
/* ~OGRPGTableLayer() */
/************************************************************************/
OGRPGTableLayer::~OGRPGTableLayer()
{
if( bDeferredCreation ) RunDeferredCreationIfNecessary();
if ( bCopyActive ) EndCopy();
CPLFree( pszSqlTableName );
CPLFree( pszTableName );
CPLFree( pszSqlGeomParentTableName );
CPLFree( pszSchemaName );
CPLFree( pszDescription );
CPLFree( pszGeomColForced );
CSLDestroy( papszOverrideColumnTypes );
}
/************************************************************************/
/* GetMetadataDomainList() */
/************************************************************************/
char ** OGRPGTableLayer::GetMetadataDomainList()
{
if( pszDescription == NULL )
GetMetadata();
if( pszDescription[0] != '\0' )
return CSLAddString(NULL, "");
return NULL;
}
/************************************************************************/
/* GetMetadata() */
/************************************************************************/
char ** OGRPGTableLayer::GetMetadata(const char* pszDomain)
{
if( (pszDomain == NULL || EQUAL(pszDomain, "")) &&
pszDescription == NULL )
{
PGconn *hPGConn = poDS->GetPGConn();
CPLString osCommand;
osCommand.Printf(
"SELECT d.description FROM pg_class c "
"JOIN pg_namespace n ON c.relnamespace=n.oid "
"JOIN pg_description d "
"ON d.objoid = c.oid AND d.classoid = 'pg_class'::regclass::oid AND d.objsubid = 0 "
"WHERE c.relname = %s AND n.nspname = %s AND c.relkind in ('r', 'v') ",
OGRPGEscapeString(hPGConn, pszTableName).c_str(),
OGRPGEscapeString(hPGConn, pszSchemaName).c_str());
PGresult* hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
const char* pszDesc = NULL;
if ( hResult && PGRES_TUPLES_OK == PQresultStatus(hResult) &&
PQntuples( hResult ) == 1 )
{
pszDesc = PQgetvalue(hResult,0,0);
if( pszDesc )
OGRLayer::SetMetadataItem("DESCRIPTION", pszDesc);
}
pszDescription = CPLStrdup(pszDesc ? pszDesc : "");
OGRPGClearResult( hResult );
}
return OGRLayer::GetMetadata(pszDomain);
}
/************************************************************************/
/* GetMetadataItem() */
/************************************************************************/
const char *OGRPGTableLayer::GetMetadataItem(const char* pszName, const char* pszDomain)
{
GetMetadata(pszDomain);
return OGRLayer::GetMetadataItem(pszName, pszDomain);
}
/************************************************************************/
/* SetMetadata() */
/************************************************************************/
CPLErr OGRPGTableLayer::SetMetadata(char** papszMD, const char* pszDomain)
{
OGRLayer::SetMetadata(papszMD, pszDomain);
if( osForcedDescription.size() && (pszDomain == NULL || EQUAL(pszDomain, "")) )
{
OGRLayer::SetMetadataItem("DESCRIPTION", osForcedDescription);
}
if( !bDeferredCreation && (pszDomain == NULL || EQUAL(pszDomain, "")) )
{
const char* l_pszDescription = OGRLayer::GetMetadataItem("DESCRIPTION");
PGconn *hPGConn = poDS->GetPGConn();
CPLString osCommand;
osCommand.Printf( "COMMENT ON TABLE %s IS %s",
pszSqlTableName,
l_pszDescription && l_pszDescription[0] != '\0' ?
OGRPGEscapeString(hPGConn, l_pszDescription).c_str() : "NULL" );
PGresult* hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
OGRPGClearResult( hResult );
CPLFree(pszDescription);
pszDescription = CPLStrdup(l_pszDescription ? l_pszDescription : "");
}
return CE_None;
}
/************************************************************************/
/* SetMetadataItem() */
/************************************************************************/
CPLErr OGRPGTableLayer::SetMetadataItem(const char* pszName, const char* pszValue,
const char* pszDomain)
{
if( (pszDomain == NULL || EQUAL(pszDomain, "")) && pszName != NULL &&
EQUAL(pszName, "DESCRIPTION") && osForcedDescription.size() )
{
pszValue = osForcedDescription;
}
OGRLayer::SetMetadataItem(pszName, pszValue, pszDomain);
if( !bDeferredCreation &&
(pszDomain == NULL || EQUAL(pszDomain, "")) && pszName != NULL &&
EQUAL(pszName, "DESCRIPTION") )
{
SetMetadata( GetMetadata() );
}
return CE_None;
}
/************************************************************************/
/* SetForcedDescription() */
/************************************************************************/
void OGRPGTableLayer::SetForcedDescription( const char* pszDescriptionIn )
{
osForcedDescription = pszDescriptionIn;
CPLFree(pszDescription);
pszDescription = CPLStrdup( pszDescriptionIn );
SetMetadataItem( "DESCRIPTION", osForcedDescription );
}
/************************************************************************/
/* SetGeometryInformation() */
/************************************************************************/
void OGRPGTableLayer::SetGeometryInformation(PGGeomColumnDesc* pasDesc,
int nGeomFieldCount)
{
// Flag must be set before instantiating geometry fields.
bGeometryInformationSet = TRUE;
for(int i=0; i<nGeomFieldCount; i++)
{
OGRPGGeomFieldDefn* poGeomFieldDefn =
new OGRPGGeomFieldDefn(this, pasDesc[i].pszName);
poGeomFieldDefn->SetNullable(pasDesc[i].bNullable);
poGeomFieldDefn->nSRSId = pasDesc[i].nSRID;
poGeomFieldDefn->GeometryTypeFlags = pasDesc[i].GeometryTypeFlags;
poGeomFieldDefn->ePostgisType = pasDesc[i].ePostgisType;
if( pasDesc[i].pszGeomType != NULL )
{
OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pasDesc[i].pszGeomType);
if( (poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_3D) && (eGeomType != wkbUnknown) )
eGeomType = wkbSetZ(eGeomType);
if( (poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED) && (eGeomType != wkbUnknown) )
eGeomType = wkbSetM(eGeomType);
poGeomFieldDefn->SetType(eGeomType);
}
poFeatureDefn->AddGeomFieldDefn(poGeomFieldDefn, FALSE);
}
}
/************************************************************************/
/* ReadTableDefinition() */
/* */
/* Build a schema from the named table. Done by querying the */
/* catalog. */
/************************************************************************/
int OGRPGTableLayer::ReadTableDefinition()
{
PGresult *hResult;
CPLString osCommand;
PGconn *hPGConn = poDS->GetPGConn();
if( bTableDefinitionValid >= 0 )
return bTableDefinitionValid;
bTableDefinitionValid = FALSE;
poDS->EndCopy();
CPLString osSchemaClause;
osSchemaClause.Printf("AND n.nspname=%s",
OGRPGEscapeString(hPGConn, pszSchemaName).c_str());
const char* pszTypnameEqualsAnyClause;
if (poDS->sPostgreSQLVersion.nMajor == 7 && poDS->sPostgreSQLVersion.nMinor <= 3)
pszTypnameEqualsAnyClause = "ANY(SELECT '{int2, int4, int8, serial, bigserial}')";
else
pszTypnameEqualsAnyClause = "ANY(ARRAY['int2','int4','int8','serial','bigserial'])";
const char* pszAttnumEqualAnyIndkey;
if( poDS->sPostgreSQLVersion.nMajor > 8 || (
poDS->sPostgreSQLVersion.nMajor == 8 && poDS->sPostgreSQLVersion.nMinor >= 2) )
pszAttnumEqualAnyIndkey = "a.attnum = ANY(i.indkey)";
else
pszAttnumEqualAnyIndkey = "(i.indkey[0]=a.attnum OR i.indkey[1]=a.attnum OR i.indkey[2]=a.attnum "
"OR i.indkey[3]=a.attnum OR i.indkey[4]=a.attnum OR i.indkey[5]=a.attnum "
"OR i.indkey[6]=a.attnum OR i.indkey[7]=a.attnum OR i.indkey[8]=a.attnum "
"OR i.indkey[9]=a.attnum)";
CPLString osEscapedTableNameSingleQuote = OGRPGEscapeString(hPGConn, pszTableName);
const char* pszEscapedTableNameSingleQuote = osEscapedTableNameSingleQuote.c_str();
/* See #1889 for why we don't use 'AND a.attnum = ANY(i.indkey)' */
osCommand.Printf("SELECT a.attname, a.attnum, t.typname, "
"t.typname = %s AS isfid "
"FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n, pg_index i "
"WHERE a.attnum > 0 AND a.attrelid = c.oid "
"AND a.atttypid = t.oid AND c.relnamespace = n.oid "
"AND c.oid = i.indrelid AND i.indisprimary = 't' "
"AND t.typname !~ '^geom' AND c.relname = %s "
"AND %s %s ORDER BY a.attnum",
pszTypnameEqualsAnyClause, pszEscapedTableNameSingleQuote,
pszAttnumEqualAnyIndkey, osSchemaClause.c_str() );
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
if ( hResult && PGRES_TUPLES_OK == PQresultStatus(hResult) )
{
if ( PQntuples( hResult ) == 1 && PQgetisnull( hResult,0,0 ) == false )
{
/* Check if single-field PK can be represented as integer. */
CPLString osValue(PQgetvalue(hResult, 0, 3));
if( osValue == "t" )
{
osPrimaryKey.Printf( "%s", PQgetvalue(hResult,0,0) );
const char* pszFIDType = PQgetvalue(hResult, 0, 2);
CPLDebug( "PG", "Primary key name (FID): %s, type : %s",
osPrimaryKey.c_str(), pszFIDType );
if( EQUAL(pszFIDType, "int8") )
SetMetadataItem(OLMD_FID64, "YES");
}
}
else if ( PQntuples( hResult ) > 1 )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Multi-column primary key in \'%s\' detected but not supported.",
pszTableName );
}
OGRPGClearResult( hResult );
/* Zero tuples means no PK is defined, perfectly valid case. */
}
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s", PQerrorMessage(hPGConn) );
}
/* -------------------------------------------------------------------- */
/* Fire off commands to get back the columns of the table. */
/* -------------------------------------------------------------------- */
osCommand.Printf(
"SELECT DISTINCT a.attname, t.typname, a.attlen,"
" format_type(a.atttypid,a.atttypmod), a.attnum, a.attnotnull, a.atthasdef "
"FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n "
"WHERE c.relname = %s "
"AND a.attnum > 0 AND a.attrelid = c.oid "
"AND a.atttypid = t.oid "
"AND c.relnamespace=n.oid "
"%s "
"ORDER BY a.attnum",
pszEscapedTableNameSingleQuote, osSchemaClause.c_str());
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
if( !hResult || PQresultStatus(hResult) != PGRES_TUPLES_OK )
{
OGRPGClearResult( hResult );
CPLError( CE_Failure, CPLE_AppDefined,
"%s", PQerrorMessage(hPGConn) );
return bTableDefinitionValid;
}
if( PQntuples(hResult) == 0 )
{
OGRPGClearResult( hResult );
CPLDebug( "PG",
"No field definitions found for '%s', is it a table?",
pszTableName );
return bTableDefinitionValid;
}
/* -------------------------------------------------------------------- */
/* Parse the returned table information. */
/* -------------------------------------------------------------------- */
int iRecord;
int bHasDefault = FALSE;
for( iRecord = 0; iRecord < PQntuples(hResult); iRecord++ )
{
const char *pszType = NULL;
const char *pszFormatType = NULL;
const char *pszNotNull = NULL;
const char *pszHasDef = NULL;
OGRFieldDefn oField( PQgetvalue( hResult, iRecord, 0 ), OFTString);
pszType = PQgetvalue(hResult, iRecord, 1 );
int nWidth = atoi(PQgetvalue(hResult,iRecord,2));
pszFormatType = PQgetvalue(hResult,iRecord,3);
pszNotNull = PQgetvalue(hResult,iRecord,5);
pszHasDef = PQgetvalue(hResult,iRecord,6);
if( pszNotNull && EQUAL(pszNotNull, "t") )
oField.SetNullable(FALSE);
if( pszHasDef && EQUAL(pszHasDef, "t") )
bHasDefault = TRUE;
if( EQUAL(oField.GetNameRef(),osPrimaryKey) )
{
pszFIDColumn = CPLStrdup(oField.GetNameRef());
CPLDebug("PG","Using column '%s' as FID for table '%s'", pszFIDColumn, pszTableName );
continue;
}
else if( EQUAL(pszType,"geometry") ||
EQUAL(pszType,"geography") ||
EQUAL(oField.GetNameRef(),"WKB_GEOMETRY") )
{
OGRPGGeomFieldDefn* poGeomFieldDefn = NULL;
if( !bGeometryInformationSet )
{
if( pszGeomColForced == NULL ||
EQUAL(pszGeomColForced, oField.GetNameRef()) )
poGeomFieldDefn = new OGRPGGeomFieldDefn(this, oField.GetNameRef());
}
else
{
int idx = poFeatureDefn->GetGeomFieldIndex(oField.GetNameRef());
if( idx >= 0 )
poGeomFieldDefn = poFeatureDefn->myGetGeomFieldDefn(idx);
}
if( poGeomFieldDefn != NULL )
{
if( EQUAL(pszType,"geometry") )
poGeomFieldDefn->ePostgisType = GEOM_TYPE_GEOMETRY;
else if( EQUAL(pszType,"geography") )
{
poGeomFieldDefn->ePostgisType = GEOM_TYPE_GEOGRAPHY;
poGeomFieldDefn->nSRSId = 4326;
}
else
{
poGeomFieldDefn->ePostgisType = GEOM_TYPE_WKB;
if( EQUAL(pszType,"OID") )
bWkbAsOid = TRUE;
}
poGeomFieldDefn->SetNullable(oField.IsNullable());
if( !bGeometryInformationSet )
poFeatureDefn->AddGeomFieldDefn(poGeomFieldDefn, FALSE);
}
continue;
}
OGRPGCommonLayerSetType(oField, pszType, pszFormatType, nWidth);
//CPLDebug("PG", "name=%s, type=%s", oField.GetNameRef(), pszType);
poFeatureDefn->AddFieldDefn( &oField );
}
OGRPGClearResult( hResult );
if( bHasDefault )
{
osCommand.Printf(
"SELECT a.attname, pg_get_expr(def.adbin, c.oid) "
"FROM pg_attrdef def, pg_class c, pg_attribute a, pg_type t, pg_namespace n "
"WHERE c.relname = %s AND a.attnum > 0 AND a.attrelid = c.oid "
"AND a.atttypid = t.oid AND c.relnamespace=n.oid AND "
"def.adrelid = c.oid AND def.adnum = a.attnum "
"%s "
"ORDER BY a.attnum",
pszEscapedTableNameSingleQuote, osSchemaClause.c_str());
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
if( !hResult || PQresultStatus(hResult) != PGRES_TUPLES_OK )
{
OGRPGClearResult( hResult );
CPLError( CE_Failure, CPLE_AppDefined,
"%s", PQerrorMessage(hPGConn) );
return bTableDefinitionValid;
}
for( iRecord = 0; iRecord < PQntuples(hResult); iRecord++ )
{
const char *pszName = PQgetvalue( hResult, iRecord, 0 );
const char *pszDefault = PQgetvalue( hResult, iRecord, 1 );
int nIdx = poFeatureDefn->GetFieldIndex(pszName);
if( nIdx >= 0 )
{
OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(nIdx);
OGRPGCommonLayerNormalizeDefault(poFieldDefn, pszDefault);
}
}
OGRPGClearResult( hResult );
}
bTableDefinitionValid = TRUE;
ResetReading();
/* If geometry type, SRID, etc... have always been set by SetGeometryInformation() */
/* no need to issue a new SQL query. Just record the geom type in the layer definition */
if (bGeometryInformationSet)
{
return TRUE;
}
bGeometryInformationSet = TRUE;
// get layer geometry type (for PostGIS dataset)
for(int iField = 0; iField < poFeatureDefn->GetGeomFieldCount(); iField++)
{
OGRPGGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(iField);
/* Get the geometry type and dimensions from the table, or */
/* from its parents if it is a derived table, or from the parent of the parent, etc.. */
int bGoOn = TRUE;
int bHasPostGISGeometry =
(poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY);
while(bGoOn)
{
osEscapedTableNameSingleQuote = OGRPGEscapeString(hPGConn,
(pszSqlGeomParentTableName) ? pszSqlGeomParentTableName : pszTableName);
pszEscapedTableNameSingleQuote = osEscapedTableNameSingleQuote.c_str();
osCommand.Printf(
"SELECT type, coord_dimension, srid FROM %s WHERE f_table_name = %s",
(bHasPostGISGeometry) ? "geometry_columns" : "geography_columns",
pszEscapedTableNameSingleQuote);
osCommand += CPLString().Printf(" AND %s=%s",
(bHasPostGISGeometry) ? "f_geometry_column" : "f_geography_column",
OGRPGEscapeString(hPGConn,poGeomFieldDefn->GetNameRef()).c_str());
osCommand += CPLString().Printf(" AND f_table_schema = %s",
OGRPGEscapeString(hPGConn,pszSchemaName).c_str());
hResult = OGRPG_PQexec(hPGConn,osCommand);
if ( hResult && PQntuples(hResult) == 1 && !PQgetisnull(hResult,0,0) )
{
const char* pszType = PQgetvalue(hResult,0,0);
int dim = atoi(PQgetvalue(hResult,0,1));
bool bHasM = pszType[strlen(pszType)-1] == 'M';
int GeometryTypeFlags = 0;
if( dim == 3 )
{
if (bHasM)
GeometryTypeFlags |= OGRGeometry::OGR_G_MEASURED;
else
GeometryTypeFlags |= OGRGeometry::OGR_G_3D;
}
else if( dim == 4 )
GeometryTypeFlags |= OGRGeometry::OGR_G_3D | OGRGeometry::OGR_G_MEASURED;
int nSRSId = atoi(PQgetvalue(hResult,0,2));
poGeomFieldDefn->GeometryTypeFlags = GeometryTypeFlags;
if( nSRSId > 0 )
poGeomFieldDefn->nSRSId = nSRSId;
OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszType);
if( poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_3D && eGeomType != wkbUnknown )
eGeomType = wkbSetZ(eGeomType);
if( poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED && eGeomType != wkbUnknown )
eGeomType = wkbSetM(eGeomType);
poGeomFieldDefn->SetType(eGeomType);
bGoOn = FALSE;
}
else
{
/* Fetch the name of the parent table */
osCommand.Printf(
"SELECT pg_class.relname FROM pg_class WHERE oid = "
"(SELECT pg_inherits.inhparent FROM pg_inherits WHERE inhrelid = "
"(SELECT c.oid FROM pg_class c, pg_namespace n "
"WHERE c.relname = %s AND c.relnamespace=n.oid AND "
"n.nspname = %s))",
pszEscapedTableNameSingleQuote,
OGRPGEscapeString(hPGConn, pszSchemaName).c_str() );
OGRPGClearResult( hResult );
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
if ( hResult && PQntuples( hResult ) == 1 && !PQgetisnull( hResult,0,0 ) )
{
CPLFree(pszSqlGeomParentTableName);
pszSqlGeomParentTableName = CPLStrdup( PQgetvalue(hResult,0,0) );
}
else
{
/* No more parent : stop recursion */
bGoOn = FALSE;
}
}
OGRPGClearResult( hResult );
}
}
return bTableDefinitionValid;
}
/************************************************************************/
/* SetTableDefinition() */
/************************************************************************/
void OGRPGTableLayer::SetTableDefinition(const char* pszFIDColumnName,
const char* pszGFldName,
OGRwkbGeometryType eType,
const char* pszGeomType,
int nSRSId,
int GeometryTypeFlags)
{
bTableDefinitionValid = TRUE;
bGeometryInformationSet = TRUE;
pszFIDColumn = CPLStrdup(pszFIDColumnName);
poFeatureDefn->SetGeomType(wkbNone);
if( eType != wkbNone )
{
OGRPGGeomFieldDefn* poGeomFieldDefn = new OGRPGGeomFieldDefn(this, pszGFldName);
poGeomFieldDefn->SetType(eType);
poGeomFieldDefn->GeometryTypeFlags = GeometryTypeFlags;
if( EQUAL(pszGeomType,"geometry") )
{
poGeomFieldDefn->ePostgisType = GEOM_TYPE_GEOMETRY;
poGeomFieldDefn->nSRSId = nSRSId;
}
else if( EQUAL(pszGeomType,"geography") )
{
poGeomFieldDefn->ePostgisType = GEOM_TYPE_GEOGRAPHY;
poGeomFieldDefn->nSRSId = 4326;
}
else
{
poGeomFieldDefn->ePostgisType = GEOM_TYPE_WKB;
if( EQUAL(pszGeomType,"OID") )
bWkbAsOid = TRUE;
}
poFeatureDefn->AddGeomFieldDefn(poGeomFieldDefn, FALSE);
}
else if( pszGFldName != NULL )
m_osFirstGeometryFieldName = pszGFldName;
}
/************************************************************************/
/* SetSpatialFilter() */
/************************************************************************/
void OGRPGTableLayer::SetSpatialFilter( int iGeomField, OGRGeometry * poGeomIn )
{
if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() ||
GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone )
{
if( iGeomField != 0 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid geometry field index : %d", iGeomField);
}
return;
}
m_iGeomFieldFilter = iGeomField;
if( InstallFilter( poGeomIn ) )
{
BuildWhere();
ResetReading();
}
}
/************************************************************************/
/* BuildWhere() */
/* */
/* Build the WHERE statement appropriate to the current set of */
/* criteria (spatial and attribute queries). */
/************************************************************************/
void OGRPGTableLayer::BuildWhere()
{
osWHERE = "";
OGRPGGeomFieldDefn* poGeomFieldDefn = NULL;
if( poFeatureDefn->GetGeomFieldCount() != 0 )
poGeomFieldDefn = poFeatureDefn->myGetGeomFieldDefn(m_iGeomFieldFilter);
if( m_poFilterGeom != NULL && poGeomFieldDefn != NULL &&
poDS->sPostGISVersion.nMajor >= 0 && (
poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY ||
poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY) )
{
char szBox3D_1[128];
char szBox3D_2[128];
OGREnvelope sEnvelope;
m_poFilterGeom->getEnvelope( &sEnvelope );
if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY )
{
if( sEnvelope.MinX < -180.0 )
sEnvelope.MinX = -180.0;
if( sEnvelope.MinY < -90.0 )
sEnvelope.MinY = -90.0;
if( sEnvelope.MaxX > 180.0 )
sEnvelope.MaxX = 180.0;
if( sEnvelope.MaxY > 90.0 )
sEnvelope.MaxY = 90.0;
}
CPLsnprintf(szBox3D_1, sizeof(szBox3D_1), "%.18g %.18g", sEnvelope.MinX, sEnvelope.MinY);
CPLsnprintf(szBox3D_2, sizeof(szBox3D_2), "%.18g %.18g", sEnvelope.MaxX, sEnvelope.MaxY);
osWHERE.Printf("WHERE %s && %s('BOX3D(%s, %s)'::box3d,%d) ",
OGRPGEscapeColumnName(poGeomFieldDefn->GetNameRef()).c_str(),
(poDS->sPostGISVersion.nMajor >= 2) ? "ST_SetSRID" : "SetSRID",
szBox3D_1, szBox3D_2, poGeomFieldDefn->nSRSId );
}
if( strlen(osQuery) > 0 )
{
if( strlen(osWHERE) == 0 )
{
osWHERE.Printf( "WHERE %s ", osQuery.c_str() );
}
else
{
osWHERE += "AND (";
osWHERE += osQuery;
osWHERE += ")";
}
}
}
/************************************************************************/
/* BuildFullQueryStatement() */
/************************************************************************/
void OGRPGTableLayer::BuildFullQueryStatement()
{
CPLString osFields = BuildFields();
if( pszQueryStatement != NULL )
{
CPLFree( pszQueryStatement );
pszQueryStatement = NULL;
}
pszQueryStatement = (char *)
CPLMalloc(strlen(osFields)+strlen(osWHERE)
+strlen(pszSqlTableName) + 40);
snprintf( pszQueryStatement,
strlen(osFields)+strlen(osWHERE)
+strlen(pszSqlTableName) + 40,
"SELECT %s FROM %s %s",
osFields.c_str(), pszSqlTableName, osWHERE.c_str() );
}
/************************************************************************/
/* ResetReading() */
/************************************************************************/
void OGRPGTableLayer::ResetReading()
{
if( bInResetReading )
return;
bInResetReading = TRUE;
if( bDeferredCreation ) RunDeferredCreationIfNecessary();
poDS->EndCopy();
bUseCopyByDefault = FALSE;
BuildFullQueryStatement();
OGRPGLayer::ResetReading();
bInResetReading = FALSE;
}
/************************************************************************/
/* GetNextFeature() */
/************************************************************************/
OGRFeature *OGRPGTableLayer::GetNextFeature()
{
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return NULL;
poDS->EndCopy();
if( pszQueryStatement == NULL )
ResetReading();
if( pszQueryStatement == NULL )
ResetReading();
OGRPGGeomFieldDefn* poGeomFieldDefn = NULL;
if( poFeatureDefn->GetGeomFieldCount() != 0 )
poGeomFieldDefn = poFeatureDefn->myGetGeomFieldDefn(m_iGeomFieldFilter);
poFeatureDefn->GetFieldCount();
while( true )
{
OGRFeature *poFeature;
poFeature = GetNextRawFeature();
if( poFeature == NULL )
return NULL;
/* We just have to look if there is a geometry filter */
/* If there's a PostGIS geometry column, the spatial filter */
/* is already taken into account in the select request */
/* The attribute filter is always taken into account by the select request */
if( m_poFilterGeom == NULL
|| poGeomFieldDefn == NULL
|| poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY
|| poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY
|| FilterGeometry( poFeature->GetGeomFieldRef(m_iGeomFieldFilter) ) )
{
if( poFeature && iFIDAsRegularColumnIndex >= 0 )
{
poFeature->SetField(iFIDAsRegularColumnIndex, poFeature->GetFID());
}
return poFeature;
}
delete poFeature;
}
}
/************************************************************************/
/* BuildFields() */
/* */
/* Build list of fields to fetch, performing any required */
/* transformations (such as on geometry). */
/************************************************************************/
CPLString OGRPGTableLayer::BuildFields()
{
int i = 0;
CPLString osFieldList;
poFeatureDefn->GetFieldCount();
if( pszFIDColumn != NULL && poFeatureDefn->GetFieldIndex( pszFIDColumn ) == -1 )
{
osFieldList += OGRPGEscapeColumnName(pszFIDColumn);
}
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRPGGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(i);
CPLString osEscapedGeom =
OGRPGEscapeColumnName(poGeomFieldDefn->GetNameRef());
if( osFieldList.size() > 0 )
osFieldList += ", ";
if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY )
{
if ( poDS->sPostGISVersion.nMajor < 0 || poDS->bUseBinaryCursor )
{
osFieldList += osEscapedGeom;
}
else if (CPLTestBool(CPLGetConfigOption("PG_USE_BASE64", "NO")))
{
if (poDS->sPostGISVersion.nMajor >= 2)
osFieldList += "encode(ST_AsEWKB(";
else
osFieldList += "encode(AsEWKB(";
osFieldList += osEscapedGeom;
osFieldList += "), 'base64') AS ";
osFieldList += OGRPGEscapeColumnName(
CPLSPrintf("EWKBBase64_%s", poGeomFieldDefn->GetNameRef()));
}
else if ( !CPLTestBool(CPLGetConfigOption("PG_USE_TEXT", "NO")) &&
/* perhaps works also for older version, but I didn't check */
(poDS->sPostGISVersion.nMajor > 1 ||
(poDS->sPostGISVersion.nMajor == 1 && poDS->sPostGISVersion.nMinor >= 1)) )
{
/* This will return EWKB in an hex encoded form */
osFieldList += osEscapedGeom;
}
else if ( poDS->sPostGISVersion.nMajor >= 1 )
{
if (poDS->sPostGISVersion.nMajor >= 2)
osFieldList += "ST_AsEWKT(";
else
osFieldList += "AsEWKT(";
osFieldList += osEscapedGeom;
osFieldList += ") AS ";
osFieldList += OGRPGEscapeColumnName(
CPLSPrintf("AsEWKT_%s", poGeomFieldDefn->GetNameRef()));
}
else
{
osFieldList += "AsText(";
osFieldList += osEscapedGeom;
osFieldList += ") AS ";
osFieldList += OGRPGEscapeColumnName(
CPLSPrintf("AsText_%s", poGeomFieldDefn->GetNameRef()));
}
}
else if ( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY )
{
#if defined(BINARY_CURSOR_ENABLED)
if ( poDS->bUseBinaryCursor )
{
osFieldList += "ST_AsBinary(";
osFieldList += osEscapedGeom;
osFieldList += ") AS";
osFieldList += OGRPGEscapeColumnName(
CPLSPrintf("AsBinary_%s", poGeomFieldDefn->GetNameRef()));
}
else
#endif
if (CPLTestBool(CPLGetConfigOption("PG_USE_BASE64", "NO")))
{
osFieldList += "encode(ST_AsEWKB(";
osFieldList += osEscapedGeom;
osFieldList += "::geometry), 'base64') AS ";
osFieldList += OGRPGEscapeColumnName(
CPLSPrintf("EWKBBase64_%s", poGeomFieldDefn->GetNameRef()));
}
else if ( !CPLTestBool(CPLGetConfigOption("PG_USE_TEXT", "NO")) )
{
osFieldList += osEscapedGeom;
}
else
{
osFieldList += "ST_AsEWKT(";
osFieldList += osEscapedGeom;
osFieldList += "::geometry) AS ";
osFieldList += OGRPGEscapeColumnName(
CPLSPrintf("AsEWKT_%s", poGeomFieldDefn->GetNameRef()));
}
}
else
{
osFieldList += osEscapedGeom;
}
}
for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
{
const char *pszName = poFeatureDefn->GetFieldDefn(i)->GetNameRef();
if( osFieldList.size() > 0 )
osFieldList += ", ";
#if defined(BINARY_CURSOR_ENABLED)
/* With a binary cursor, it is not possible to get the time zone */
/* of a timestamptz column. So we fallback to asking it in text mode */
if ( poDS->bUseBinaryCursor &&
poFeatureDefn->GetFieldDefn(i)->GetType() == OFTDateTime)
{
osFieldList += "CAST (";
osFieldList += OGRPGEscapeColumnName(pszName);
osFieldList += " AS text)";
}
else
#endif
{
osFieldList += OGRPGEscapeColumnName(pszName);
}
}
return osFieldList;
}
/************************************************************************/
/* SetAttributeFilter() */
/************************************************************************/
OGRErr OGRPGTableLayer::SetAttributeFilter( const char *pszQuery )
{
CPLFree(m_pszAttrQueryString);
m_pszAttrQueryString = (pszQuery) ? CPLStrdup(pszQuery) : NULL;
if( pszQuery == NULL )
osQuery = "";
else
osQuery = pszQuery;
BuildWhere();
ResetReading();
return OGRERR_NONE;
}
/************************************************************************/
/* DeleteFeature() */
/************************************************************************/
OGRErr OGRPGTableLayer::DeleteFeature( GIntBig nFID )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = NULL;
CPLString osCommand;
GetLayerDefn()->GetFieldCount();
if( !bUpdateAccess )
{
CPLError( CE_Failure, CPLE_NotSupported,
UNSUPPORTED_OP_READ_ONLY,
"DeleteFeature");
return OGRERR_FAILURE;
}
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return OGRERR_FAILURE;
poDS->EndCopy();
bAutoFIDOnCreateViaCopy = FALSE;
/* -------------------------------------------------------------------- */
/* We can only delete features if we have a well defined FID */
/* column to target. */
/* -------------------------------------------------------------------- */
if( pszFIDColumn == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined,
"DeleteFeature(" CPL_FRMT_GIB ") failed. Unable to delete features in tables without\n"
"a recognised FID column.",
nFID );
return OGRERR_FAILURE;
}
/* -------------------------------------------------------------------- */
/* Form the statement to drop the record. */
/* -------------------------------------------------------------------- */
osCommand.Printf( "DELETE FROM %s WHERE %s = " CPL_FRMT_GIB,
pszSqlTableName, OGRPGEscapeColumnName(pszFIDColumn).c_str(), nFID );
/* -------------------------------------------------------------------- */
/* Execute the delete. */
/* -------------------------------------------------------------------- */
OGRErr eErr;
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"DeleteFeature() DELETE statement failed.\n%s",
PQerrorMessage(hPGConn) );
eErr = OGRERR_FAILURE;
}
else
{
if( EQUAL(PQcmdStatus(hResult), "DELETE 0") )
eErr = OGRERR_NON_EXISTING_FEATURE;
else
eErr = OGRERR_NONE;
}
OGRPGClearResult( hResult );
return eErr;
}
/************************************************************************/
/* ISetFeature() */
/* */
/* SetFeature() is implemented by an UPDATE SQL command */
/************************************************************************/
OGRErr OGRPGTableLayer::ISetFeature( OGRFeature *poFeature )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = NULL;
CPLString osCommand;
int i = 0;
int bNeedComma = FALSE;
OGRErr eErr = OGRERR_FAILURE;
GetLayerDefn()->GetFieldCount();
if( !bUpdateAccess )
{
CPLError( CE_Failure, CPLE_NotSupported,
UNSUPPORTED_OP_READ_ONLY,
"SetFeature");
return OGRERR_FAILURE;
}
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return OGRERR_FAILURE;
poDS->EndCopy();
if( NULL == poFeature )
{
CPLError( CE_Failure, CPLE_AppDefined,
"NULL pointer to OGRFeature passed to SetFeature()." );
return eErr;
}
if( poFeature->GetFID() == OGRNullFID )
{
CPLError( CE_Failure, CPLE_AppDefined,
"FID required on features given to SetFeature()." );
return eErr;
}
if( pszFIDColumn == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to update features in tables without\n"
"a recognised FID column.");
return eErr;
}
/* In case the FID column has also been created as a regular field */
if( iFIDAsRegularColumnIndex >= 0 )
{
if( !poFeature->IsFieldSet( iFIDAsRegularColumnIndex ) ||
poFeature->GetFieldAsInteger64(iFIDAsRegularColumnIndex) != poFeature->GetFID() )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Inconsistent values of FID and field of same name");
return OGRERR_FAILURE;
}
}
/* -------------------------------------------------------------------- */
/* Form the UPDATE command. */
/* -------------------------------------------------------------------- */
osCommand.Printf( "UPDATE %s SET ", pszSqlTableName );
/* Set the geometry */
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRPGGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(i);
OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i);
if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_WKB )
{
if( bNeedComma )
osCommand += ", ";
else
bNeedComma = TRUE;
osCommand += OGRPGEscapeColumnName(poGeomFieldDefn->GetNameRef());
osCommand += " = ";
if ( poGeom != NULL )
{
if( !bWkbAsOid )
{
char *pszBytea = GeometryToBYTEA( poGeom,
poDS->sPostGISVersion.nMajor,
poDS->sPostGISVersion.nMinor );
if( pszBytea != NULL )
{
if (poDS->bUseEscapeStringSyntax)
osCommand += "E";
osCommand = osCommand + "'" + pszBytea + "'";
CPLFree( pszBytea );
}
else
osCommand += "NULL";
}
else
{
Oid oid = GeometryToOID( poGeom );
if( oid != 0 )
{
osCommand += CPLString().Printf( "'%d' ", oid );
}
else
osCommand += "NULL";
}
}
else
osCommand += "NULL";
}
else if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY ||
poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY )
{
if( bNeedComma )
osCommand += ", ";
else
bNeedComma = TRUE;
osCommand += OGRPGEscapeColumnName(poGeomFieldDefn->GetNameRef());
osCommand += " = ";
if( poGeom != NULL )
{
poGeom->closeRings();
poGeom->set3D(poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_3D);
poGeom->setMeasured(poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED);
}
if ( !CPLTestBool(CPLGetConfigOption("PG_USE_TEXT", "NO")) )
{
if ( poGeom != NULL )
{
char* pszHexEWKB = OGRGeometryToHexEWKB( poGeom, poGeomFieldDefn->nSRSId,
poDS->sPostGISVersion.nMajor,
poDS->sPostGISVersion.nMinor);
if ( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY )
osCommand += CPLString().Printf("'%s'::GEOGRAPHY", pszHexEWKB);
else
osCommand += CPLString().Printf("'%s'::GEOMETRY", pszHexEWKB);
OGRFree( pszHexEWKB );
}
else
osCommand += "NULL";
}
else
{
char *pszWKT = NULL;
if (poGeom != NULL)
poGeom->exportToWkt( &pszWKT );
int nSRSId = poGeomFieldDefn->nSRSId;
if( pszWKT != NULL )
{
if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY )
osCommand +=
CPLString().Printf(
"ST_GeographyFromText('SRID=%d;%s'::TEXT) ", nSRSId, pszWKT );
else if( poDS->sPostGISVersion.nMajor >= 1 )
osCommand +=
CPLString().Printf(
"GeomFromEWKT('SRID=%d;%s'::TEXT) ", nSRSId, pszWKT );
else
osCommand +=
CPLString().Printf(
"GeometryFromText('%s'::TEXT,%d) ", pszWKT, nSRSId );
OGRFree( pszWKT );
}
else
osCommand += "NULL";
}
}
}
for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
{
if( iFIDAsRegularColumnIndex == i )
continue;
if( bNeedComma )
osCommand += ", ";
else
bNeedComma = TRUE;
osCommand = osCommand
+ OGRPGEscapeColumnName(poFeatureDefn->GetFieldDefn(i)->GetNameRef()) + " = ";
if( !poFeature->IsFieldSet( i ) )
{
osCommand += "NULL";
}
else
{
OGRPGCommonAppendFieldValue(osCommand, poFeature, i,
(OGRPGCommonEscapeStringCbk)OGRPGEscapeString, hPGConn);
}
}
/* Add the WHERE clause */
osCommand += " WHERE ";
osCommand = osCommand + OGRPGEscapeColumnName(pszFIDColumn) + " = ";
osCommand += CPLString().Printf( CPL_FRMT_GIB, poFeature->GetFID() );
/* -------------------------------------------------------------------- */
/* Execute the update. */
/* -------------------------------------------------------------------- */
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"UPDATE command for feature " CPL_FRMT_GIB " failed.\n%s\nCommand: %s",
poFeature->GetFID(), PQerrorMessage(hPGConn), osCommand.c_str() );
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
if( EQUAL(PQcmdStatus(hResult), "UPDATE 0") )
eErr = OGRERR_NON_EXISTING_FEATURE;
else
eErr = OGRERR_NONE;
OGRPGClearResult( hResult );
return eErr;
}
/************************************************************************/
/* ICreateFeature() */
/************************************************************************/
OGRErr OGRPGTableLayer::ICreateFeature( OGRFeature *poFeature )
{
GetLayerDefn()->GetFieldCount();
if( !bUpdateAccess )
{
CPLError( CE_Failure, CPLE_NotSupported,
UNSUPPORTED_OP_READ_ONLY,
"CreateFeature");
return OGRERR_FAILURE;
}
if( NULL == poFeature )
{
CPLError( CE_Failure, CPLE_AppDefined,
"NULL pointer to OGRFeature passed to CreateFeature()." );
return OGRERR_FAILURE;
}
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return OGRERR_FAILURE;
/* In case the FID column has also been created as a regular field */
GIntBig nFID = poFeature->GetFID();
if( iFIDAsRegularColumnIndex >= 0 )
{
if( nFID == OGRNullFID )
{
if( poFeature->IsFieldSet( iFIDAsRegularColumnIndex ) )
{
poFeature->SetFID(
poFeature->GetFieldAsInteger64(iFIDAsRegularColumnIndex));
}
}
else
{
if( !poFeature->IsFieldSet( iFIDAsRegularColumnIndex ) ||
poFeature->GetFieldAsInteger64(iFIDAsRegularColumnIndex) != nFID )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Inconsistent values of FID and field of same name");
return OGRERR_FAILURE;
}
}
}
/* Auto-promote FID column to 64bit if necessary */
if( pszFIDColumn != NULL &&
!CPL_INT64_FITS_ON_INT32(nFID) &&
GetMetadataItem(OLMD_FID64) == NULL )
{
poDS->EndCopy();
CPLString osCommand;
osCommand.Printf( "ALTER TABLE %s ALTER COLUMN %s TYPE INT8",
pszSqlTableName,
OGRPGEscapeColumnName(pszFIDColumn).c_str() );
PGconn *hPGConn = poDS->GetPGConn();
PGresult* hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s",
osCommand.c_str(),
PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
SetMetadataItem(OLMD_FID64, "YES");
}
if( bFirstInsertion )
{
bFirstInsertion = FALSE;
if( CPLTestBool(CPLGetConfigOption("OGR_TRUNCATE", "NO")) )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult;
CPLString osCommand;
osCommand.Printf("TRUNCATE TABLE %s", pszSqlTableName );
hResult = OGRPG_PQexec( hPGConn, osCommand.c_str() );
OGRPGClearResult( hResult );
}
}
// We avoid testing the config option too often.
if( bUseCopy == USE_COPY_UNSET )
bUseCopy = CPLTestBool( CPLGetConfigOption( "PG_USE_COPY", "NO") );
OGRErr eErr;
if( !bUseCopy )
{
eErr = CreateFeatureViaInsert( poFeature );
}
else
{
/* If there's a unset field with a default value, then we must use */
/* a specific INSERT statement to avoid unset fields to be bound to NULL */
int bHasDefaultValue = FALSE;
int iField;
int nFieldCount = poFeatureDefn->GetFieldCount();
for( iField = 0; iField < nFieldCount; iField++ )
{
if( !poFeature->IsFieldSet( iField ) &&
poFeature->GetFieldDefnRef(iField)->GetDefault() != NULL )
{
bHasDefaultValue = TRUE;
break;
}
}
if( bHasDefaultValue )
{
eErr = CreateFeatureViaInsert( poFeature );
}
else
{
int bFIDSet = (pszFIDColumn != NULL && poFeature->GetFID() != OGRNullFID);
if( bCopyActive && bFIDSet != bFIDColumnInCopyFields )
{
eErr = CreateFeatureViaInsert( poFeature );
}
else if( !bCopyActive && poFeatureDefn->GetFieldCount() == 0 &&
poFeatureDefn->GetGeomFieldCount() == 0 && !bFIDSet )
{
eErr = CreateFeatureViaInsert( poFeature );
}
else
{
if ( !bCopyActive )
{
/* This is a heuristics. If the first feature to be copied has a */
/* FID set (and that a FID column has been identified), then we will */
/* try to copy FID values from features. Otherwise, we will not */
/* do and assume that the FID column is an autoincremented column. */
bFIDColumnInCopyFields = bFIDSet;
}
eErr = CreateFeatureViaCopy( poFeature );
if( bFIDSet )
bAutoFIDOnCreateViaCopy = FALSE;
if( eErr == OGRERR_NONE && bAutoFIDOnCreateViaCopy )
{
poFeature->SetFID( ++iNextShapeId );
}
}
}
}
if( eErr == OGRERR_NONE && iFIDAsRegularColumnIndex >= 0 )
{
poFeature->SetField(iFIDAsRegularColumnIndex, poFeature->GetFID());
}
return eErr;
}
/************************************************************************/
/* OGRPGEscapeColumnName( ) */
/************************************************************************/
CPLString OGRPGEscapeColumnName(const char* pszColumnName)
{
CPLString osStr;
osStr += "\"";
char ch;
for(int i=0; (ch = pszColumnName[i]) != '\0'; i++)
{
if (ch == '"')
osStr.append(1, ch);
osStr.append(1, ch);
}
osStr += "\"";
return osStr;
}
/************************************************************************/
/* OGRPGEscapeString( ) */
/************************************************************************/
CPLString OGRPGEscapeString(PGconn *hPGConn,
const char* pszStrValue, int nMaxLength,
const char* pszTableName,
const char* pszFieldName )
{
CPLString osCommand;
/* We need to quote and escape string fields. */
osCommand += "'";
int nSrcLen = static_cast<int>(strlen(pszStrValue));
int nSrcLenUTF = CPLStrlenUTF8(pszStrValue);
if (nMaxLength > 0 && nSrcLenUTF > nMaxLength)
{
CPLDebug( "PG",
"Truncated %s.%s field value '%s' to %d characters.",
pszTableName, pszFieldName, pszStrValue, nMaxLength );
int iUTF8Char = 0;
for(int iChar = 0; iChar < nSrcLen; iChar++ )
{
if( (((unsigned char *) pszStrValue)[iChar] & 0xc0) != 0x80 )
{
if( iUTF8Char == nMaxLength )
{
nSrcLen = iChar;
break;
}
iUTF8Char ++;
}
}
}
char* pszDestStr = (char*)CPLMalloc(2 * nSrcLen + 1);
/* -------------------------------------------------------------------- */
/* PQescapeStringConn was introduced in PostgreSQL security releases */
/* 8.1.4, 8.0.8, 7.4.13, 7.3.15 */
/* PG_HAS_PQESCAPESTRINGCONN is added by a test in 'configure' */
/* so it is not set by default when building OGR for Win32 */
/* -------------------------------------------------------------------- */
#if defined(PG_HAS_PQESCAPESTRINGCONN)
int nError;
PQescapeStringConn (hPGConn, pszDestStr, pszStrValue, nSrcLen, &nError);
if (nError == 0)
osCommand += pszDestStr;
else
CPLError(CE_Warning, CPLE_AppDefined,
"PQescapeString(): %s\n"
" input: '%s'\n"
" got: '%s'\n",
PQerrorMessage( hPGConn ),
pszStrValue, pszDestStr );
#else
PQescapeString(pszDestStr, pszStrValue, nSrcLen);
osCommand += pszDestStr;
#endif
CPLFree(pszDestStr);
osCommand += "'";
return osCommand;
}
/************************************************************************/
/* CreateFeatureViaInsert() */
/************************************************************************/
OGRErr OGRPGTableLayer::CreateFeatureViaInsert( OGRFeature *poFeature )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult;
CPLString osCommand;
int i;
int bNeedComma = FALSE;
int bEmptyInsert = FALSE;
poDS->EndCopy();
/* -------------------------------------------------------------------- */
/* Form the INSERT command. */
/* -------------------------------------------------------------------- */
osCommand.Printf( "INSERT INTO %s (", pszSqlTableName );
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(i);
OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i);
if( poGeom == NULL )
continue;
if( !bNeedComma )
bNeedComma = TRUE;
else
osCommand += ", ";
osCommand += OGRPGEscapeColumnName(poGeomFieldDefn->GetNameRef()) + " ";
}
/* Use case of ogr_pg_60 test */
if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL )
{
if( bNeedComma )
osCommand += ", ";
osCommand = osCommand + OGRPGEscapeColumnName(pszFIDColumn) + " ";
bNeedComma = TRUE;
}
int nFieldCount = poFeatureDefn->GetFieldCount();
for( i = 0; i < nFieldCount; i++ )
{
if( iFIDAsRegularColumnIndex == i )
continue;
if( !poFeature->IsFieldSet( i ) )
continue;
if( !bNeedComma )
bNeedComma = TRUE;
else
osCommand += ", ";
osCommand = osCommand
+ OGRPGEscapeColumnName(poFeatureDefn->GetFieldDefn(i)->GetNameRef());
}
if (!bNeedComma)
bEmptyInsert = TRUE;
osCommand += ") VALUES (";
/* Set the geometry */
bNeedComma = FALSE;
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRPGGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(i);
OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i);
if( poGeom == NULL )
continue;
if( bNeedComma )
osCommand += ", ";
else
bNeedComma = TRUE;
if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY ||
poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY )
{
CheckGeomTypeCompatibility(i, poGeom);
poGeom->closeRings();
poGeom->set3D(poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_3D);
poGeom->setMeasured(poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED);
int nSRSId = poGeomFieldDefn->nSRSId;
if ( !CPLTestBool(CPLGetConfigOption("PG_USE_TEXT", "NO")) )
{
char *pszHexEWKB = OGRGeometryToHexEWKB( poGeom, nSRSId,
poDS->sPostGISVersion.nMajor,
poDS->sPostGISVersion.nMinor );
if ( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY )
osCommand += CPLString().Printf("'%s'::GEOGRAPHY", pszHexEWKB);
else
osCommand += CPLString().Printf("'%s'::GEOMETRY", pszHexEWKB);
OGRFree( pszHexEWKB );
}
else
{
char *pszWKT = NULL;
poGeom->exportToWkt( &pszWKT );
if( pszWKT != NULL )
{
if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY )
osCommand +=
CPLString().Printf(
"ST_GeographyFromText('SRID=%d;%s'::TEXT) ", nSRSId, pszWKT );
else if( poDS->sPostGISVersion.nMajor >= 1 )
osCommand +=
CPLString().Printf(
"GeomFromEWKT('SRID=%d;%s'::TEXT) ", nSRSId, pszWKT );
else
osCommand +=
CPLString().Printf(
"GeometryFromText('%s'::TEXT,%d) ", pszWKT, nSRSId );
OGRFree( pszWKT );
}
else
osCommand += "''";
}
}
else if( !bWkbAsOid )
{
char *pszBytea = GeometryToBYTEA( poGeom,
poDS->sPostGISVersion.nMajor,
poDS->sPostGISVersion.nMinor );
if( pszBytea != NULL )
{
if (poDS->bUseEscapeStringSyntax)
osCommand += "E";
osCommand = osCommand + "'" + pszBytea + "'";
CPLFree( pszBytea );
}
else
osCommand += "''";
}
else if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_WKB &&
bWkbAsOid && poGeom != NULL )
{
Oid oid = GeometryToOID( poGeom );
if( oid != 0 )
{
osCommand += CPLString().Printf( "'%d' ", oid );
}
else
osCommand += "''";
}
}
if( poFeature->GetFID() != OGRNullFID && pszFIDColumn != NULL )
{
if( bNeedComma )
osCommand += ", ";
osCommand += CPLString().Printf( CPL_FRMT_GIB " ", poFeature->GetFID() );
bNeedComma = TRUE;
}
for( i = 0; i < nFieldCount; i++ )
{
if( iFIDAsRegularColumnIndex == i )
continue;
if( !poFeature->IsFieldSet( i ) )
continue;
if( bNeedComma )
osCommand += ", ";
else
bNeedComma = TRUE;
OGRPGCommonAppendFieldValue(osCommand, poFeature, i,
(OGRPGCommonEscapeStringCbk)OGRPGEscapeString, hPGConn);
}
osCommand += ")";
if (bEmptyInsert)
osCommand.Printf( "INSERT INTO %s DEFAULT VALUES", pszSqlTableName );
int bReturnRequested = FALSE;
/* RETURNING is only available since Postgres 8.2 */
/* We only get the FID, but we also could add the unset fields to get */
/* the default values */
if (bRetrieveFID && pszFIDColumn != NULL && poFeature->GetFID() == OGRNullFID &&
(poDS->sPostgreSQLVersion.nMajor >= 9 ||
(poDS->sPostgreSQLVersion.nMajor == 8 && poDS->sPostgreSQLVersion.nMinor >= 2)))
{
bReturnRequested = TRUE;
osCommand += " RETURNING ";
osCommand += OGRPGEscapeColumnName(pszFIDColumn);
}
/* -------------------------------------------------------------------- */
/* Execute the insert. */
/* -------------------------------------------------------------------- */
hResult = OGRPG_PQexec(hPGConn, osCommand);
if (bReturnRequested && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) == 1 && PQnfields(hResult) == 1 )
{
const char* pszFID = PQgetvalue(hResult, 0, 0 );
poFeature->SetFID(CPLAtoGIntBig(pszFID));
}
else if( bReturnRequested || PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"INSERT command for new feature failed.\n%s\nCommand: %s",
PQerrorMessage(hPGConn), osCommand.c_str() );
if( !bHasWarnedAlreadySetFID && poFeature->GetFID() != OGRNullFID &&
pszFIDColumn != NULL )
{
bHasWarnedAlreadySetFID = TRUE;
CPLError(CE_Warning, CPLE_AppDefined,
"You've inserted feature with an already set FID and that's perhaps the reason for the failure. "
"If so, this can happen if you reuse the same feature object for sequential insertions. "
"Indeed, since GDAL 1.8.0, the FID of an inserted feature is got from the server, so it is not a good idea"
"to reuse it afterwards... All in all, try unsetting the FID with SetFID(-1) before calling CreateFeature()");
}
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
return OGRERR_NONE;
}
/************************************************************************/
/* CreateFeatureViaCopy() */
/************************************************************************/
OGRErr OGRPGTableLayer::CreateFeatureViaCopy( OGRFeature *poFeature )
{
PGconn *hPGConn = poDS->GetPGConn();
CPLString osCommand;
int i;
/* Tell the datasource we are now planning to copy data */
poDS->StartCopy( this );
/* First process geometry */
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRPGGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(i);
OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i);
char *pszGeom = NULL;
if ( NULL != poGeom )
{
CheckGeomTypeCompatibility(i, poGeom);
poGeom->closeRings();
poGeom->set3D(poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_3D);
poGeom->setMeasured(poGeomFieldDefn->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED);
if( poGeomFieldDefn->ePostgisType == GEOM_TYPE_WKB )
pszGeom = GeometryToBYTEA( poGeom,
poDS->sPostGISVersion.nMajor,
poDS->sPostGISVersion.nMinor );
else
pszGeom = OGRGeometryToHexEWKB( poGeom, poGeomFieldDefn->nSRSId,
poDS->sPostGISVersion.nMajor,
poDS->sPostGISVersion.nMinor );
}
if (osCommand.size() > 0)
osCommand += "\t";
if ( pszGeom )
{
osCommand += pszGeom;
CPLFree( pszGeom );
}
else
{
osCommand += "\\N";
}
}
OGRPGCommonAppendCopyFieldsExceptGeom(osCommand,
poFeature,
pszFIDColumn,
bFIDColumnInCopyFields,
(OGRPGCommonEscapeStringCbk)OGRPGEscapeString,
hPGConn);
/* Add end of line marker */
osCommand += "\n";
/* ------------------------------------------------------------ */
/* Execute the copy. */
/* ------------------------------------------------------------ */
OGRErr result = OGRERR_NONE;
/* This is for postgresql 7.4 and higher */
#if !defined(PG_PRE74)
int copyResult = PQputCopyData(hPGConn, osCommand.c_str(),
static_cast<int>(strlen(osCommand.c_str())));
#ifdef DEBUG_VERBOSE
CPLDebug("PG", "PQputCopyData(%s)", osCommand.c_str());
#endif
switch (copyResult)
{
case 0:
CPLError( CE_Failure, CPLE_AppDefined, "Writing COPY data blocked.");
result = OGRERR_FAILURE;
break;
case -1:
CPLError( CE_Failure, CPLE_AppDefined, "%s", PQerrorMessage(hPGConn) );
result = OGRERR_FAILURE;
break;
}
#else /* else defined(PG_PRE74) */
int copyResult = PQputline(hPGConn, osCommand.c_str());
if (copyResult == EOF)
{
CPLError( CE_Failure, CPLE_AppDefined, "Writing COPY data blocked.");
result = OGRERR_FAILURE;
}
#endif /* end of defined(PG_PRE74) */
return result;
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGRPGTableLayer::TestCapability( const char * pszCap )
{
if ( bUpdateAccess )
{
if( EQUAL(pszCap,OLCSequentialWrite) ||
EQUAL(pszCap,OLCCreateField) ||
EQUAL(pszCap,OLCCreateGeomField) ||
EQUAL(pszCap,OLCDeleteField) ||
EQUAL(pszCap,OLCAlterFieldDefn) )
return TRUE;
else if( EQUAL(pszCap,OLCRandomWrite) ||
EQUAL(pszCap,OLCDeleteFeature) )
{
GetLayerDefn()->GetFieldCount();
return pszFIDColumn != NULL;
}
}
if( EQUAL(pszCap,OLCRandomRead) )
{
GetLayerDefn()->GetFieldCount();
return pszFIDColumn != NULL;
}
else if( EQUAL(pszCap,OLCFastFeatureCount) ||
EQUAL(pszCap,OLCFastSetNextByIndex) )
{
if( m_poFilterGeom == NULL )
return TRUE;
OGRPGGeomFieldDefn* poGeomFieldDefn = NULL;
if( poFeatureDefn->GetGeomFieldCount() > 0 )
poGeomFieldDefn = poFeatureDefn->myGetGeomFieldDefn(m_iGeomFieldFilter);
return poGeomFieldDefn == NULL ||
(poDS->sPostGISVersion.nMajor >= 0 &&
(poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY ||
poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY));
}
else if( EQUAL(pszCap,OLCFastSpatialFilter) )
{
OGRPGGeomFieldDefn* poGeomFieldDefn = NULL;
if( poFeatureDefn->GetGeomFieldCount() > 0 )
poGeomFieldDefn = poFeatureDefn->myGetGeomFieldDefn(m_iGeomFieldFilter);
return poGeomFieldDefn == NULL ||
(poDS->sPostGISVersion.nMajor >= 0 &&
(poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY ||
poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOGRAPHY));
}
else if( EQUAL(pszCap,OLCTransactions) )
return TRUE;
else if( EQUAL(pszCap,OLCFastGetExtent) )
{
OGRPGGeomFieldDefn* poGeomFieldDefn = NULL;
if( poFeatureDefn->GetGeomFieldCount() > 0 )
poGeomFieldDefn = poFeatureDefn->myGetGeomFieldDefn(0);
return poGeomFieldDefn != NULL &&
poDS->sPostGISVersion.nMajor >= 0 &&
poGeomFieldDefn->ePostgisType == GEOM_TYPE_GEOMETRY;
}
else if( EQUAL(pszCap,OLCStringsAsUTF8) )
return TRUE;
else if( EQUAL(pszCap,OLCCurveGeometries) )
return TRUE;
else if( EQUAL(pszCap,OLCMeasuredGeometries) )
return TRUE;
else
return FALSE;
}
/************************************************************************/
/* CreateField() */
/************************************************************************/
OGRErr OGRPGTableLayer::CreateField( OGRFieldDefn *poFieldIn, int bApproxOK )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = NULL;
CPLString osCommand;
CPLString osFieldType;
OGRFieldDefn oField( poFieldIn );
GetLayerDefn()->GetFieldCount();
if( !bUpdateAccess )
{
CPLError( CE_Failure, CPLE_NotSupported,
UNSUPPORTED_OP_READ_ONLY,
"CreateField");
return OGRERR_FAILURE;
}
if( pszFIDColumn != NULL &&
EQUAL( oField.GetNameRef(), pszFIDColumn ) &&
oField.GetType() != OFTInteger &&
oField.GetType() != OFTInteger64 )
{
CPLError(CE_Failure, CPLE_AppDefined, "Wrong field type for %s",
oField.GetNameRef());
return OGRERR_FAILURE;
}
/* -------------------------------------------------------------------- */
/* Do we want to "launder" the column names into Postgres */
/* friendly format? */
/* -------------------------------------------------------------------- */
if( bLaunderColumnNames )
{
char *pszSafeName = OGRPGCommonLaunderName( oField.GetNameRef(), "PG" );
oField.SetName( pszSafeName );
CPLFree( pszSafeName );
if( EQUAL(oField.GetNameRef(),"oid") )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Renaming field 'oid' to 'oid_' to avoid conflict with internal oid field." );
oField.SetName( "oid_" );
}
}
const char* pszOverrideType = CSLFetchNameValue(papszOverrideColumnTypes, oField.GetNameRef());
if( pszOverrideType != NULL )
osFieldType = pszOverrideType;
else
{
osFieldType = OGRPGCommonLayerGetType(oField, bPreservePrecision, bApproxOK);
if (osFieldType.size() == 0)
return OGRERR_FAILURE;
}
CPLString osNotNullDefault;
if( !oField.IsNullable() )
osNotNullDefault += " NOT NULL";
if( oField.GetDefault() != NULL && !oField.IsDefaultDriverSpecific() )
{
osNotNullDefault += " DEFAULT ";
osNotNullDefault += OGRPGCommonLayerGetPGDefault(&oField);
}
/* -------------------------------------------------------------------- */
/* Create the new field. */
/* -------------------------------------------------------------------- */
if( bDeferredCreation )
{
if( !(pszFIDColumn != NULL && EQUAL(pszFIDColumn,oField.GetNameRef())) )
{
osCreateTable += ", ";
osCreateTable += OGRPGEscapeColumnName(oField.GetNameRef());
osCreateTable += " ";
osCreateTable += osFieldType;
osCreateTable += osNotNullDefault;
}
}
else
{
poDS->EndCopy();
osCommand.Printf( "ALTER TABLE %s ADD COLUMN %s %s",
pszSqlTableName, OGRPGEscapeColumnName(oField.GetNameRef()).c_str(),
osFieldType.c_str() );
osCommand += osNotNullDefault;
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s",
osCommand.c_str(),
PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
}
poFeatureDefn->AddFieldDefn( &oField );
if( pszFIDColumn != NULL &&
EQUAL( oField.GetNameRef(), pszFIDColumn ) )
{
iFIDAsRegularColumnIndex = poFeatureDefn->GetFieldCount() - 1;
}
return OGRERR_NONE;
}
/************************************************************************/
/* RunAddGeometryColumn() */
/************************************************************************/
OGRErr OGRPGTableLayer::RunAddGeometryColumn( OGRPGGeomFieldDefn *poGeomField )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult;
CPLString osCommand;
const char *pszGeometryType = OGRToOGCGeomType(poGeomField->GetType());
const char *suffix = "";
int dim = 2;
if( (poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_3D) &&
(poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED) )
dim = 4;
else if( (poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED) )
{
if( !(wkbFlatten(poGeomField->GetType()) == wkbUnknown) )
suffix = "M";
dim = 3;
}
else if( poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_3D )
dim = 3;
osCommand.Printf(
"SELECT AddGeometryColumn(%s,%s,%s,%d,'%s%s',%d)",
OGRPGEscapeString(hPGConn, pszSchemaName).c_str(),
OGRPGEscapeString(hPGConn, pszTableName).c_str(),
OGRPGEscapeString(hPGConn, poGeomField->GetNameRef()).c_str(),
poGeomField->nSRSId, pszGeometryType, suffix, dim );
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str());
if( !hResult
|| PQresultStatus(hResult) != PGRES_TUPLES_OK )
{
CPLError( CE_Failure, CPLE_AppDefined, "AddGeometryColumn failed for layer %s.",
GetName());
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
if( !poGeomField->IsNullable() )
{
osCommand.Printf( "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL",
pszSqlTableName,
OGRPGEscapeColumnName(poGeomField->GetNameRef()).c_str() );
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str());
OGRPGClearResult( hResult );
}
return OGRERR_NONE;
}
/************************************************************************/
/* RunCreateSpatialIndex() */
/************************************************************************/
OGRErr OGRPGTableLayer::RunCreateSpatialIndex( OGRPGGeomFieldDefn *poGeomField )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult;
CPLString osCommand;
osCommand.Printf("CREATE INDEX %s ON %s USING GIST (%s)",
OGRPGEscapeColumnName(
CPLSPrintf("%s_%s_geom_idx", pszTableName, poGeomField->GetNameRef())).c_str(),
pszSqlTableName,
OGRPGEscapeColumnName(poGeomField->GetNameRef()).c_str());
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str());
if( !hResult
|| PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined, "CREATE INDEX failed for layer %s.", GetName());
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
return OGRERR_NONE;
}
/************************************************************************/
/* CreateGeomField() */
/************************************************************************/
OGRErr OGRPGTableLayer::CreateGeomField( OGRGeomFieldDefn *poGeomFieldIn,
CPL_UNUSED int bApproxOK )
{
OGRwkbGeometryType eType = poGeomFieldIn->GetType();
if( eType == wkbNone )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot create geometry field of type wkbNone");
return OGRERR_FAILURE;
}
// Check if GEOMETRY_NAME layer creation option was set, but no initial
// column was created in ICreateLayer()
CPLString osGeomFieldName =
( m_osFirstGeometryFieldName.size() ) ? m_osFirstGeometryFieldName :
CPLString(poGeomFieldIn->GetNameRef());
m_osFirstGeometryFieldName = ""; // reset for potential next geom columns
OGRPGGeomFieldDefn *poGeomField =
new OGRPGGeomFieldDefn( this, osGeomFieldName );
if( EQUAL(poGeomField->GetNameRef(), "") )
{
if( poFeatureDefn->GetGeomFieldCount() == 0 )
poGeomField->SetName( "wkb_geometry" );
else
poGeomField->SetName(
CPLSPrintf("wkb_geometry%d", poFeatureDefn->GetGeomFieldCount()+1) );
}
poGeomField->SetSpatialRef(poGeomFieldIn->GetSpatialRef());
/* -------------------------------------------------------------------- */
/* Do we want to "launder" the column names into Postgres */
/* friendly format? */
/* -------------------------------------------------------------------- */
if( bLaunderColumnNames )
{
char *pszSafeName = OGRPGCommonLaunderName( poGeomField->GetNameRef(), "PG" );
poGeomField->SetName( pszSafeName );
CPLFree( pszSafeName );
}
OGRSpatialReference* poSRS = poGeomField->GetSpatialRef();
int nSRSId = poDS->GetUndefinedSRID();
if( nForcedSRSId != UNDETERMINED_SRID )
nSRSId = nForcedSRSId;
else if( poSRS != NULL )
nSRSId = poDS->FetchSRSId( poSRS );
int GeometryTypeFlags = 0;
if( OGR_GT_HasZ((OGRwkbGeometryType)eType) )
GeometryTypeFlags |= OGRGeometry::OGR_G_3D;
if( OGR_GT_HasM((OGRwkbGeometryType)eType) )
GeometryTypeFlags |= OGRGeometry::OGR_G_MEASURED;
if( nForcedGeometryTypeFlags >= 0 )
{
GeometryTypeFlags = nForcedGeometryTypeFlags;
eType = OGR_GT_SetModifier(eType,
GeometryTypeFlags & OGRGeometry::OGR_G_3D,
GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED);
}
poGeomField->SetType(eType);
poGeomField->SetNullable( poGeomFieldIn->IsNullable() );
poGeomField->nSRSId = nSRSId;
poGeomField->GeometryTypeFlags = GeometryTypeFlags;
poGeomField->ePostgisType = GEOM_TYPE_GEOMETRY;
/* -------------------------------------------------------------------- */
/* Create the new field. */
/* -------------------------------------------------------------------- */
if( !bDeferredCreation )
{
poDS->EndCopy();
if( RunAddGeometryColumn(poGeomField) != OGRERR_NONE )
{
delete poGeomField;
return OGRERR_FAILURE;
}
if( bCreateSpatialIndexFlag )
{
if( RunCreateSpatialIndex(poGeomField) != OGRERR_NONE )
{
delete poGeomField;
return OGRERR_FAILURE;
}
}
}
poFeatureDefn->AddGeomFieldDefn( poGeomField, FALSE );
return OGRERR_NONE;
}
/************************************************************************/
/* DeleteField() */
/************************************************************************/
OGRErr OGRPGTableLayer::DeleteField( int iField )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = NULL;
CPLString osCommand;
GetLayerDefn()->GetFieldCount();
if( !bUpdateAccess )
{
CPLError( CE_Failure, CPLE_NotSupported,
UNSUPPORTED_OP_READ_ONLY,
"DeleteField");
return OGRERR_FAILURE;
}
if (iField < 0 || iField >= poFeatureDefn->GetFieldCount())
{
CPLError( CE_Failure, CPLE_NotSupported,
"Invalid field index");
return OGRERR_FAILURE;
}
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return OGRERR_FAILURE;
poDS->EndCopy();
osCommand.Printf( "ALTER TABLE %s DROP COLUMN %s",
pszSqlTableName,
OGRPGEscapeColumnName(poFeatureDefn->GetFieldDefn(iField)->GetNameRef()).c_str() );
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s",
osCommand.c_str(),
PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
return poFeatureDefn->DeleteFieldDefn( iField );
}
/************************************************************************/
/* AlterFieldDefn() */
/************************************************************************/
OGRErr OGRPGTableLayer::AlterFieldDefn( int iField, OGRFieldDefn* poNewFieldDefn, int nFlagsIn )
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = NULL;
CPLString osCommand;
GetLayerDefn()->GetFieldCount();
if( !bUpdateAccess )
{
CPLError( CE_Failure, CPLE_NotSupported,
UNSUPPORTED_OP_READ_ONLY,
"AlterFieldDefn");
return OGRERR_FAILURE;
}
if (iField < 0 || iField >= poFeatureDefn->GetFieldCount())
{
CPLError( CE_Failure, CPLE_NotSupported,
"Invalid field index");
return OGRERR_FAILURE;
}
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return OGRERR_FAILURE;
poDS->EndCopy();
OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn(iField);
OGRFieldDefn oField( poNewFieldDefn );
poDS->SoftStartTransaction();
if (!(nFlagsIn & ALTER_TYPE_FLAG))
oField.SetType(poFieldDefn->GetType());
if (!(nFlagsIn & ALTER_WIDTH_PRECISION_FLAG))
{
oField.SetWidth(poFieldDefn->GetWidth());
oField.SetPrecision(poFieldDefn->GetPrecision());
}
if ((nFlagsIn & ALTER_TYPE_FLAG) ||
(nFlagsIn & ALTER_WIDTH_PRECISION_FLAG))
{
CPLString osFieldType = OGRPGCommonLayerGetType(oField,
bPreservePrecision,
TRUE);
if (osFieldType.size() == 0)
{
poDS->SoftRollbackTransaction();
return OGRERR_FAILURE;
}
osCommand.Printf( "ALTER TABLE %s ALTER COLUMN %s TYPE %s",
pszSqlTableName,
OGRPGEscapeColumnName(poFieldDefn->GetNameRef()).c_str(),
osFieldType.c_str() );
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s",
osCommand.c_str(),
PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
poDS->SoftRollbackTransaction();
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
}
if( (nFlagsIn & ALTER_NULLABLE_FLAG) &&
poFieldDefn->IsNullable() != poNewFieldDefn->IsNullable() )
{
oField.SetNullable(poNewFieldDefn->IsNullable());
if( poNewFieldDefn->IsNullable() )
osCommand.Printf( "ALTER TABLE %s ALTER COLUMN %s DROP NOT NULL",
pszSqlTableName,
OGRPGEscapeColumnName(poFieldDefn->GetNameRef()).c_str() );
else
osCommand.Printf( "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL",
pszSqlTableName,
OGRPGEscapeColumnName(poFieldDefn->GetNameRef()).c_str() );
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s",
osCommand.c_str(),
PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
poDS->SoftRollbackTransaction();
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
}
if( (nFlagsIn & ALTER_DEFAULT_FLAG) &&
((poFieldDefn->GetDefault() == NULL && poNewFieldDefn->GetDefault() != NULL) ||
(poFieldDefn->GetDefault() != NULL && poNewFieldDefn->GetDefault() == NULL) ||
(poFieldDefn->GetDefault() != NULL && poNewFieldDefn->GetDefault() != NULL &&
strcmp(poFieldDefn->GetDefault(), poNewFieldDefn->GetDefault()) != 0)) )
{
oField.SetDefault(poNewFieldDefn->GetDefault());
if( poNewFieldDefn->GetDefault() == NULL )
osCommand.Printf( "ALTER TABLE %s ALTER COLUMN %s DROP DEFAULT",
pszSqlTableName,
OGRPGEscapeColumnName(poFieldDefn->GetNameRef()).c_str() );
else
osCommand.Printf( "ALTER TABLE %s ALTER COLUMN %s SET DEFAULT %s",
pszSqlTableName,
OGRPGEscapeColumnName(poFieldDefn->GetNameRef()).c_str(),
OGRPGCommonLayerGetPGDefault(poNewFieldDefn).c_str());
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s",
osCommand.c_str(),
PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
poDS->SoftRollbackTransaction();
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
}
if( (nFlagsIn & ALTER_NAME_FLAG) )
{
if (bLaunderColumnNames)
{
char *pszSafeName = OGRPGCommonLaunderName( oField.GetNameRef(), "PG" );
oField.SetName( pszSafeName );
CPLFree( pszSafeName );
}
if( EQUAL(oField.GetNameRef(),"oid") )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Renaming field 'oid' to 'oid_' to avoid conflict with internal oid field." );
oField.SetName( "oid_" );
}
if ( strcmp(poFieldDefn->GetNameRef(), oField.GetNameRef()) != 0 )
{
osCommand.Printf( "ALTER TABLE %s RENAME COLUMN %s TO %s",
pszSqlTableName,
OGRPGEscapeColumnName(poFieldDefn->GetNameRef()).c_str(),
OGRPGEscapeColumnName(oField.GetNameRef()).c_str() );
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s",
osCommand.c_str(),
PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
poDS->SoftRollbackTransaction();
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
}
}
poDS->SoftCommitTransaction();
if (nFlagsIn & ALTER_NAME_FLAG)
poFieldDefn->SetName(oField.GetNameRef());
if (nFlagsIn & ALTER_TYPE_FLAG)
poFieldDefn->SetType(oField.GetType());
if (nFlagsIn & ALTER_WIDTH_PRECISION_FLAG)
{
poFieldDefn->SetWidth(oField.GetWidth());
poFieldDefn->SetPrecision(oField.GetPrecision());
}
if (nFlagsIn & ALTER_NULLABLE_FLAG)
poFieldDefn->SetNullable(oField.IsNullable());
if (nFlagsIn & ALTER_DEFAULT_FLAG)
poFieldDefn->SetDefault(oField.GetDefault());
return OGRERR_NONE;
}
/************************************************************************/
/* GetFeature() */
/************************************************************************/
OGRFeature *OGRPGTableLayer::GetFeature( GIntBig nFeatureId )
{
GetLayerDefn()->GetFieldCount();
if( pszFIDColumn == NULL )
return OGRLayer::GetFeature( nFeatureId );
/* -------------------------------------------------------------------- */
/* Issue query for a single record. */
/* -------------------------------------------------------------------- */
OGRFeature *poFeature = NULL;
PGresult *hResult = NULL;
PGconn *hPGConn = poDS->GetPGConn();
CPLString osFieldList = BuildFields();
CPLString osCommand;
poDS->EndCopy();
poDS->SoftStartTransaction();
osCommand.Printf(
"DECLARE getfeaturecursor %s for "
"SELECT %s FROM %s WHERE %s = " CPL_FRMT_GIB,
( poDS->bUseBinaryCursor ) ? "BINARY CURSOR" : "CURSOR",
osFieldList.c_str(), pszSqlTableName, OGRPGEscapeColumnName(pszFIDColumn).c_str(),
nFeatureId );
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
if( hResult && PQresultStatus(hResult) == PGRES_COMMAND_OK )
{
OGRPGClearResult( hResult );
hResult = OGRPG_PQexec(hPGConn, "FETCH ALL in getfeaturecursor" );
if( hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK )
{
int nRows = PQntuples(hResult);
if (nRows > 0)
{
int* panTempMapFieldNameToIndex = NULL;
int* panTempMapFieldNameToGeomIndex = NULL;
CreateMapFromFieldNameToIndex(hResult,
poFeatureDefn,
panTempMapFieldNameToIndex,
panTempMapFieldNameToGeomIndex);
poFeature = RecordToFeature(hResult,
panTempMapFieldNameToIndex,
panTempMapFieldNameToGeomIndex,
0 );
CPLFree(panTempMapFieldNameToIndex);
CPLFree(panTempMapFieldNameToGeomIndex);
if( poFeature && iFIDAsRegularColumnIndex >= 0 )
{
poFeature->SetField(iFIDAsRegularColumnIndex, poFeature->GetFID());
}
if (nRows > 1)
{
CPLError(CE_Warning, CPLE_AppDefined,
"%d rows in response to the WHERE %s = " CPL_FRMT_GIB " clause !",
nRows, pszFIDColumn, nFeatureId );
}
}
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Attempt to read feature with unknown feature id (" CPL_FRMT_GIB ").", nFeatureId );
}
}
}
else if ( hResult && PQresultStatus(hResult) == PGRES_FATAL_ERROR )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s", PQresultErrorMessage( hResult ) );
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
OGRPGClearResult( hResult );
hResult = OGRPG_PQexec(hPGConn, "CLOSE getfeaturecursor");
OGRPGClearResult( hResult );
poDS->SoftCommitTransaction();
return poFeature;
}
/************************************************************************/
/* GetFeatureCount() */
/************************************************************************/
GIntBig OGRPGTableLayer::GetFeatureCount( int bForce )
{
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return 0;
poDS->EndCopy();
if( TestCapability(OLCFastFeatureCount) == FALSE )
return OGRPGLayer::GetFeatureCount( bForce );
/* -------------------------------------------------------------------- */
/* In theory it might be wise to cache this result, but it */
/* won't be trivial to work out the lifetime of the value. */
/* After all someone else could be adding records from another */
/* application when working against a database. */
/* -------------------------------------------------------------------- */
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = NULL;
CPLString osCommand;
GIntBig nCount = 0;
osCommand.Printf(
"SELECT count(*) FROM %s %s",
pszSqlTableName, osWHERE.c_str() );
hResult = OGRPG_PQexec(hPGConn, osCommand);
if( hResult != NULL && PQresultStatus(hResult) == PGRES_TUPLES_OK )
nCount = CPLAtoGIntBig(PQgetvalue(hResult,0,0));
else
CPLDebug( "PG", "%s; failed.", osCommand.c_str() );
OGRPGClearResult( hResult );
return nCount;
}
/************************************************************************/
/* ResolveSRID() */
/************************************************************************/
void OGRPGTableLayer::ResolveSRID(OGRPGGeomFieldDefn* poGFldDefn)
{
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = NULL;
CPLString osCommand;
int nSRSId = poDS->GetUndefinedSRID();
osCommand.Printf(
"SELECT srid FROM geometry_columns "
"WHERE f_table_name = %s AND "
"f_geometry_column = %s",
OGRPGEscapeString(hPGConn, pszTableName).c_str(),
OGRPGEscapeString(hPGConn, poGFldDefn->GetNameRef()).c_str());
osCommand += CPLString().Printf(" AND f_table_schema = %s",
OGRPGEscapeString(hPGConn, pszSchemaName).c_str());
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str() );
if( hResult
&& PQresultStatus(hResult) == PGRES_TUPLES_OK
&& PQntuples(hResult) == 1 )
{
nSRSId = atoi(PQgetvalue(hResult,0,0));
}
OGRPGClearResult( hResult );
/* With PostGIS 2.0, SRID = 0 can also mean that there's no constraint */
/* so we need to fetch from values */
/* We assume that all geometry of this column have identical SRID */
if( nSRSId <= 0 && poGFldDefn->ePostgisType == GEOM_TYPE_GEOMETRY &&
poDS->sPostGISVersion.nMajor >= 0 )
{
CPLString osGetSRID;
const char* psGetSRIDFct;
if (poDS->sPostGISVersion.nMajor >= 2)
psGetSRIDFct = "ST_SRID";
else
psGetSRIDFct = "getsrid";
osGetSRID += "SELECT ";
osGetSRID += psGetSRIDFct;
osGetSRID += "(";
osGetSRID += OGRPGEscapeColumnName(poGFldDefn->GetNameRef());
osGetSRID += ") FROM ";
osGetSRID += pszSqlTableName;
osGetSRID += " LIMIT 1";
hResult = OGRPG_PQexec(poDS->GetPGConn(), osGetSRID );
if( hResult
&& PQresultStatus(hResult) == PGRES_TUPLES_OK
&& PQntuples(hResult) == 1 )
{
nSRSId = atoi(PQgetvalue(hResult,0,0));
}
OGRPGClearResult( hResult );
}
poGFldDefn->nSRSId = nSRSId;
}
/************************************************************************/
/* StartCopy() */
/************************************************************************/
OGRErr OGRPGTableLayer::StartCopy()
{
/*CPLDebug("PG", "OGRPGDataSource(%p)::StartCopy(%p)", poDS, this);*/
CPLString osFields = BuildCopyFields();
size_t size = strlen(osFields) + strlen(pszSqlTableName) + 100;
char *pszCommand = (char *) CPLMalloc(size);
snprintf( pszCommand, size,
"COPY %s (%s) FROM STDIN;",
pszSqlTableName, osFields.c_str() );
PGconn *hPGConn = poDS->GetPGConn();
PGresult *hResult = OGRPG_PQexec(hPGConn, pszCommand);
if ( !hResult || (PQresultStatus(hResult) != PGRES_COPY_IN))
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s", PQerrorMessage(hPGConn) );
}
else
bCopyActive = TRUE;
OGRPGClearResult( hResult );
CPLFree( pszCommand );
return OGRERR_NONE;
}
/************************************************************************/
/* EndCopy() */
/************************************************************************/
OGRErr OGRPGTableLayer::EndCopy()
{
if( !bCopyActive )
return OGRERR_NONE;
/*CPLDebug("PG", "OGRPGDataSource(%p)::EndCopy(%p)", poDS, this);*/
/* This method is called from the datasource when
a COPY operation is ended */
OGRErr result = OGRERR_NONE;
PGconn *hPGConn = poDS->GetPGConn();
CPLDebug( "PG", "PQputCopyEnd()" );
bCopyActive = FALSE;
/* This is for postgresql 7.4 and higher */
#if !defined(PG_PRE74)
int copyResult = PQputCopyEnd(hPGConn, NULL);
switch (copyResult)
{
case 0:
CPLError( CE_Failure, CPLE_AppDefined, "Writing COPY data blocked.");
result = OGRERR_FAILURE;
break;
case -1:
CPLError( CE_Failure, CPLE_AppDefined, "%s", PQerrorMessage(hPGConn) );
result = OGRERR_FAILURE;
break;
}
#else /* defined(PG_PRE74) */
PQputline(hPGConn, "\\.\n");
int copyResult = PQendcopy(hPGConn);
if (copyResult != 0)
{
CPLError( CE_Failure, CPLE_AppDefined, "%s", PQerrorMessage(hPGConn) );
result = OGRERR_FAILURE;
}
#endif /* defined(PG_PRE74) */
/* Now check the results of the copy */
PGresult * hResult = PQgetResult( hPGConn );
if( hResult && PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"COPY statement failed.\n%s",
PQerrorMessage(hPGConn) );
result = OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
if( !bUseCopyByDefault )
bUseCopy = USE_COPY_UNSET;
return result;
}
/************************************************************************/
/* BuildCopyFields() */
/************************************************************************/
CPLString OGRPGTableLayer::BuildCopyFields()
{
int i = 0;
int nFIDIndex = -1;
CPLString osFieldList;
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(i);
if( osFieldList.size() > 0 )
osFieldList += ", ";
osFieldList += OGRPGEscapeColumnName(poGeomFieldDefn->GetNameRef());
}
if( bFIDColumnInCopyFields )
{
if( osFieldList.size() > 0 )
osFieldList += ", ";
nFIDIndex = poFeatureDefn->GetFieldIndex( pszFIDColumn );
osFieldList += OGRPGEscapeColumnName(pszFIDColumn);
}
for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
{
if (i == nFIDIndex)
continue;
const char *pszName = poFeatureDefn->GetFieldDefn(i)->GetNameRef();
if( osFieldList.size() > 0 )
osFieldList += ", ";
osFieldList += OGRPGEscapeColumnName(pszName);
}
return osFieldList;
}
/************************************************************************/
/* CheckGeomTypeCompatibility() */
/************************************************************************/
void OGRPGTableLayer::CheckGeomTypeCompatibility(int iGeomField,
OGRGeometry* poGeom)
{
if (bHasWarnedIncompatibleGeom)
return;
OGRwkbGeometryType eExpectedGeomType =
poFeatureDefn->GetGeomFieldDefn(iGeomField)->GetType();
OGRwkbGeometryType eFlatLayerGeomType = wkbFlatten(eExpectedGeomType);
OGRwkbGeometryType eFlatGeomType = wkbFlatten(poGeom->getGeometryType());
if (eFlatLayerGeomType == wkbUnknown)
return;
if (eFlatLayerGeomType == wkbGeometryCollection)
bHasWarnedIncompatibleGeom = eFlatGeomType != wkbMultiPoint &&
eFlatGeomType != wkbMultiLineString &&
eFlatGeomType != wkbMultiPolygon &&
eFlatGeomType != wkbGeometryCollection;
else
bHasWarnedIncompatibleGeom = (eFlatGeomType != eFlatLayerGeomType);
if (bHasWarnedIncompatibleGeom)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Geometry to be inserted is of type %s, whereas the layer geometry type is %s.\n"
"Insertion is likely to fail",
OGRGeometryTypeToName(poGeom->getGeometryType()),
OGRGeometryTypeToName(eExpectedGeomType));
}
}
/************************************************************************/
/* SetOverrideColumnTypes() */
/************************************************************************/
void OGRPGTableLayer::SetOverrideColumnTypes( const char* pszOverrideColumnTypes )
{
if( pszOverrideColumnTypes == NULL )
return;
const char* pszIter = pszOverrideColumnTypes;
CPLString osCur;
while(*pszIter != '\0')
{
if( *pszIter == '(' )
{
/* Ignore commas inside ( ) pair */
while(*pszIter != '\0')
{
if( *pszIter == ')' )
{
osCur += *pszIter;
pszIter ++;
break;
}
osCur += *pszIter;
pszIter ++;
}
if( *pszIter == '\0')
break;
}
if( *pszIter == ',' )
{
papszOverrideColumnTypes = CSLAddString(papszOverrideColumnTypes, osCur);
osCur = "";
}
else
osCur += *pszIter;
pszIter ++;
}
if( osCur.size() )
papszOverrideColumnTypes = CSLAddString(papszOverrideColumnTypes, osCur);
}
/************************************************************************/
/* GetExtent() */
/* */
/* For PostGIS use internal ST_EstimatedExtent(geometry) function */
/* if bForce == 0 */
/************************************************************************/
OGRErr OGRPGTableLayer::GetExtent( int iGeomField, OGREnvelope *psExtent, int bForce )
{
CPLString osCommand;
if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() ||
GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone )
{
if( iGeomField != 0 )
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid geometry field index : %d", iGeomField);
}
return OGRERR_FAILURE;
}
if( bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE )
return OGRERR_FAILURE;
poDS->EndCopy();
OGRPGGeomFieldDefn* poGeomFieldDefn =
poFeatureDefn->myGetGeomFieldDefn(iGeomField);
const char* pszExtentFct;
// if bForce is 0 and ePostgisType is not GEOM_TYPE_GEOGRAPHY we can use
// the ST_EstimatedExtent function which is quicker
// ST_EstimatedExtent was called ST_Estimated_Extent up to PostGIS 2.0.x
// ST_EstimatedExtent returns NULL in absence of statistics (an exception before
// PostGIS 1.5.4)
if ( bForce == 0 && TestCapability(OLCFastGetExtent) )
{
PGconn *hPGConn = poDS->GetPGConn();
if ( poDS->sPostGISVersion.nMajor > 2 ||
( poDS->sPostGISVersion.nMajor == 2 && poDS->sPostGISVersion.nMinor >= 1 ) )
pszExtentFct = "ST_EstimatedExtent";
else
pszExtentFct = "ST_Estimated_Extent";
osCommand.Printf( "SELECT %s(%s, %s, %s)",
pszExtentFct,
OGRPGEscapeString(hPGConn, pszSchemaName).c_str(),
OGRPGEscapeString(hPGConn, pszTableName).c_str(),
OGRPGEscapeString(hPGConn, poGeomFieldDefn->GetNameRef()).c_str() );
/* Quiet error: ST_Estimated_Extent may return an error if statistics */
/* have not been computed */
if( RunGetExtentRequest(psExtent, bForce, osCommand, TRUE) == OGRERR_NONE )
return OGRERR_NONE;
CPLDebug(
"PG",
"Unable to get estimated extent by PostGIS. Trying real extent." );
}
return OGRPGLayer::GetExtent( iGeomField, psExtent, bForce );
}
/************************************************************************/
/* SetDeferredCreation() */
/************************************************************************/
void OGRPGTableLayer::SetDeferredCreation(int bDeferredCreationIn, CPLString osCreateTableIn)
{
bDeferredCreation = bDeferredCreationIn;
osCreateTable = osCreateTableIn;
}
/************************************************************************/
/* RunDeferredCreationIfNecessary() */
/************************************************************************/
OGRErr OGRPGTableLayer::RunDeferredCreationIfNecessary()
{
if( !bDeferredCreation )
return OGRERR_NONE;
bDeferredCreation = FALSE;
poDS->EndCopy();
int i;
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRPGGeomFieldDefn *poGeomField = (OGRPGGeomFieldDefn*) poFeatureDefn->GetGeomFieldDefn(i);
if (poDS->sPostGISVersion.nMajor >= 2 ||
poGeomField->ePostgisType == GEOM_TYPE_GEOGRAPHY)
{
const char *pszGeometryType = OGRToOGCGeomType(poGeomField->GetType());
osCreateTable += ", ";
osCreateTable += OGRPGEscapeColumnName(poGeomField->GetNameRef());
osCreateTable += " ";
if( poGeomField->ePostgisType == GEOM_TYPE_GEOMETRY )
osCreateTable += "geometry(";
else
osCreateTable += "geography(";
osCreateTable += pszGeometryType;
if( (poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_3D) && (poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED) )
osCreateTable += "ZM";
else if( poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_3D )
osCreateTable += "Z";
else if( poGeomField->GeometryTypeFlags & OGRGeometry::OGR_G_MEASURED )
osCreateTable += "M";
if( poGeomField->nSRSId > 0 )
osCreateTable += CPLSPrintf(",%d", poGeomField->nSRSId);
osCreateTable += ")";
if( !poGeomField->IsNullable() )
osCreateTable += " NOT NULL";
}
}
osCreateTable += " )";
CPLString osCommand(osCreateTable);
PGresult *hResult;
PGconn *hPGConn = poDS->GetPGConn();
hResult = OGRPG_PQexec(hPGConn, osCommand.c_str());
if( PQresultStatus(hResult) != PGRES_COMMAND_OK )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s\n%s", osCommand.c_str(), PQerrorMessage(hPGConn) );
OGRPGClearResult( hResult );
return OGRERR_FAILURE;
}
OGRPGClearResult( hResult );
// For PostGIS 1.X, use AddGeometryColumn() to create geometry columns
if (poDS->sPostGISVersion.nMajor < 2)
{
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRPGGeomFieldDefn *poGeomField = (OGRPGGeomFieldDefn*) poFeatureDefn->GetGeomFieldDefn(i);
if( poGeomField->ePostgisType == GEOM_TYPE_GEOMETRY &&
RunAddGeometryColumn(poGeomField) != OGRERR_NONE )
{
return OGRERR_FAILURE;
}
}
}
if( bCreateSpatialIndexFlag )
{
for( i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ )
{
OGRPGGeomFieldDefn *poGeomField = (OGRPGGeomFieldDefn*) poFeatureDefn->GetGeomFieldDefn(i);
if( RunCreateSpatialIndex(poGeomField) != OGRERR_NONE )
{
return OGRERR_FAILURE;
}
}
}
char** papszMD = OGRLayer::GetMetadata();
if( papszMD != NULL )
SetMetadata( papszMD );
return OGRERR_NONE;
}
|
/*****************************************************************************
Copyright (c) [2017] [Blandizzi Pietro]
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 <iostream>
#include <stdlib.h>
class Node {
friend class List;
int data;
Node *next;
public:
int getData () {return data;}
Node* getNext () {return next;}
void setNext (Node* n) {next = n;}
};
class List {
Node* head;
public:
Node* getHead() {return head;}
List() {head = nullptr;}
void addNode (int data);
void addNodeHead(int data);
void PrintList ();
int getLength ();
};
void List::addNodeHead(int data)
{
Node *n = new Node;
n->data = data;
n->next = nullptr;
//head is null;
if (head == nullptr) {
head = n;
return;
}
//insert in head
Node* t = head;
n->next = t;
head = n;
return;
}
void List::addNode(int data)
{
Node *n = new Node;
n->data = data;
n->next = nullptr;
//head is null;
if (head == nullptr) {
head = n;
return;
}
//insert in head
Node* t = head;
while (t->next != nullptr) {
t = t->next;
}
t->next =n;
return;
}
void List::PrintList()
{
//head is null;
if (head == nullptr) {
return;
}
Node* t = head;
while (t != nullptr) {
std::cout << t->data << " ";
t = t->next;
}
return;
}
int List::getLength ()
{
int res = 0;
Node* n = head;
while (n != nullptr) {
res++;
n = n->next;
}
return res;
}
Node* listIntersectionV1 ( List& l1, List& l2)
{
int s1 = l1.getLength();
int s2 = l2.getLength();
Node* lg, *sh;
if (s1 >= s2) {
lg = l1.getHead();
sh = l2.getHead();
}
else if (s1 < s2) {
lg = l2.getHead();
sh = l1.getHead();
}
for (int i = abs(s1-s2); i>0; i--)
lg = lg->getNext();
while (lg!=nullptr) { // same length now
if (lg == sh)
return lg;
lg = lg->getNext();
sh = sh->getNext();
}
return nullptr;
}
int getListSizeAndTail (Node* n, Node **t)
{
Node* trav = n;
int length = 0;
while (trav->getNext()!= nullptr) {
length++;
trav = trav->getNext();
}
(*t) = trav;
return length+1;
}
Node* listIntersectionV2 (Node* n1,Node* n2)
{
Node *t1, *t2;
int s1 = getListSizeAndTail (n1,&t1);
int s2 = getListSizeAndTail (n2,&t2);
if (t1!=t2)
return nullptr;
Node *lg,*sh;
if (s1 >= s2) {
lg = n1;
sh = n2;
}
else if (s1 < s2) {
lg = n2;
sh = n1;
}
for (int i = abs(s1-s2); i>0; i--)
lg = lg->getNext();
while (lg!=nullptr) { // same length now
if (lg == sh)
return lg;
lg = lg->getNext();
sh = sh->getNext();
}
return nullptr;
}
int main()
{
//Create the list and adding some elements
List l,l1;
l.addNode(1);
l.addNode(2);
l.addNode(3);
l.addNode(4);
l.addNode(5);
l.addNode(6);
l.addNode(7);
l1.addNode(8);
l1.addNode(7);
l1.addNode(6);
l1.addNode(5);
//makeIntersection
Node *n1,*n2;
n1 = l.getHead();
n2 = l1.getHead();
//intersection after five
while (n1->getData()!=5)
n1 = n1->getNext();
while (n2->getNext()!=nullptr)
n2 = n2->getNext();
n2->setNext(n1->getNext());
l.PrintList();
std::cout << std::endl;
l1.PrintList();
std::cout << std::endl;
Node* res = listIntersectionV2(l.getHead(),l1.getHead());
if (res != nullptr)
std::cout<< "Intersection in: "<<res->getData();
else
std::cout<< "No intersection";
return 0;
}
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2015-2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <modules/base/processors/volumeboundingbox.h>
#include <modules/base/algorithm/meshutils.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo VolumeBoundingBox::processorInfo_{
"org.inviwo.VolumeBoundingBox", // Class identifier
"Volume Bounding Box", // Display name
"Volume Operation", // Category
CodeState::Stable, // Code state
Tags::None, // Tags
};
const ProcessorInfo VolumeBoundingBox::getProcessorInfo() const { return processorInfo_; }
VolumeBoundingBox::VolumeBoundingBox()
: Processor()
, volume_("volume")
, mesh_("mesh")
, color_("color", "Color", vec4(1.0f), vec4(0.0f), vec4(1.0f)) {
addPort(volume_);
addPort(mesh_);
color_.setSemantics(PropertySemantics::Color);
addProperty(color_);
}
void VolumeBoundingBox::process() {
auto mesh = meshutil::boundingBoxAdjacency(volume_.getData()->getModelMatrix(), color_);
mesh->setWorldMatrix(volume_.getData()->getWorldMatrix());
mesh_.setData(mesh);
}
} // namespace inviwo
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "noui.h"
#include "ui_interface.h"
#include "util.h"
#include <cstdio>
#include <stdint.h>
#include <string>
static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
bool fSecure = style & CClientUIInterface::SECURE;
style &= ~CClientUIInterface::SECURE;
std::string strCaption;
// Check for usage of predefined caption
switch (style) {
case CClientUIInterface::MSG_ERROR:
strCaption += _("Error");
break;
case CClientUIInterface::MSG_WARNING:
strCaption += _("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
strCaption += _("Information");
break;
default:
strCaption += caption; // Use supplied caption (can be empty)
}
if (!fSecure)
LogPrintf("%s: %s\n", strCaption, message);
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
static bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style)
{
return noui_ThreadSafeMessageBox(message, caption, style);
}
static void noui_InitMessage(const std::string& message)
{
LogPrintf("init message: %s\n", message);
}
void noui_connect()
{
// Connect bitcoinnoomyd signal handlers
uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox);
uiInterface.ThreadSafeQuestion.connect(noui_ThreadSafeQuestion);
uiInterface.InitMessage.connect(noui_InitMessage);
}
|
#ifndef XR_RETURNSELF_HPP
#define XR_RETURNSELF_HPP
//==============================================================================
//
// XRhodes
//
// copyright (c) Gyorgy Straub. All rights reserved.
//
// License: https://github.com/zyndor/xrhodes#License-bsd-2-clause
//
//==============================================================================
namespace xr
{
template <typename... Args>
class ReturnSelf;
namespace detail
{
template <typename... Args>
using ReturnSelf = xr::ReturnSelf<Args...> (*)(Args...);
}
//==============================================================================
///@brief Return type for functions required to return a pointer to a function of
/// a signature identical to theirs, as typically required for state machines.
/// This is achieved through forward declaration and implicit conversions.
///@usage ReturnSelf<Input, Etc> StateFunction(Input, Etc);
template <typename... Args>
class ReturnSelf
{
public:
// types
using Type = detail::ReturnSelf<Args...>;
// structors
ReturnSelf(Type fn)
: mFn(fn)
{}
// operator overloads
operator Type()
{
return mFn;
}
private:
// data
Type mFn;
};
}
#endif //XR_RETURNSELF_HPP
|
/*
* Copyright (c) 2018-2020 The Forge Interactive Inc.
*
* This file is part of The-Forge
* (see https://github.com/ConfettiFX/The-Forge).
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifdef USE_UI_PRECOMPILED_SHADERS
#include "Shaders/Compiled/imgui.vert.h"
#include "Shaders/Compiled/imgui.frag.h"
#endif
#include "../../Common_3/ThirdParty/OpenSource/imgui/imgui.h"
#include "../../Common_3/ThirdParty/OpenSource/imgui/imgui_internal.h"
#include "../../Common_3/ThirdParty/OpenSource/tinyimageformat/tinyimageformat_query.h"
#include "AppUI.h"
#include "../../Common_3/OS/Interfaces/IOperatingSystem.h"
#include "../../Common_3/OS/Interfaces/IInput.h"
#include "../../Common_3/OS/Interfaces/ILog.h"
#include "../../Common_3/Renderer/IRenderer.h"
#include "../../Common_3/Renderer/IResourceLoader.h"
#include "../../Common_3/OS/Interfaces/IMemory.h" //NOTE: this should be the last include in a .cpp
#define LABELID(prop) eastl::string().sprintf("##%llu", (uint64_t)(prop.pData)).c_str()
#define LABELID1(prop) eastl::string().sprintf("##%llu", (uint64_t)(prop)).c_str()
namespace ImGui {
bool SliderFloatWithSteps(const char* label, float* v, float v_min, float v_max, float v_step, const char* display_format)
{
eastl::string text_buf;
bool value_changed = false;
if (!display_format)
display_format = "%.1f";
text_buf.sprintf(display_format, *v);
if (ImGui::GetIO().WantTextInput)
{
value_changed = ImGui::SliderFloat(label, v, v_min, v_max, text_buf.c_str());
int v_i = int(((*v - v_min) / v_step) + 0.5f);
*v = v_min + float(v_i) * v_step;
}
else
{
// Map from [v_min,v_max] to [0,N]
const int countValues = int((v_max - v_min) / v_step);
int v_i = int(((*v - v_min) / v_step) + 0.5f);
value_changed = ImGui::SliderInt(label, &v_i, 0, countValues, text_buf.c_str());
// Remap from [0,N] to [v_min,v_max]
*v = v_min + float(v_i) * v_step;
}
if (*v < v_min)
*v = v_min;
if (*v > v_max)
*v = v_max;
return value_changed;
}
bool SliderIntWithSteps(const char* label, int32_t* v, int32_t v_min, int32_t v_max, int32_t v_step, const char* display_format)
{
eastl::string text_buf;
bool value_changed = false;
if (!display_format)
display_format = "%d";
text_buf.sprintf(display_format, *v);
if (ImGui::GetIO().WantTextInput)
{
value_changed = ImGui::SliderInt(label, v, v_min, v_max, text_buf.c_str());
int32_t v_i = int((*v - v_min) / v_step);
*v = v_min + int32_t(v_i) * v_step;
}
else
{
// Map from [v_min,v_max] to [0,N]
const int countValues = int((v_max - v_min) / v_step);
int32_t v_i = int((*v - v_min) / v_step);
value_changed = ImGui::SliderInt(label, &v_i, 0, countValues, text_buf.c_str());
// Remap from [0,N] to [v_min,v_max]
*v = v_min + int32_t(v_i) * v_step;
}
if (*v < v_min)
*v = v_min;
if (*v > v_max)
*v = v_max;
return value_changed;
}
} // namespace ImGui
class ImguiGUIDriver: public GUIDriver
{
public:
// Declare virtual destructor
virtual ~ImguiGUIDriver() {}
bool init(Renderer* pRenderer, uint32_t const maxDynamicUIUpdatesPerBatch);
void exit();
bool load(RenderTarget** ppRts, uint32_t count, PipelineCache* pCache);
void unload();
bool addFont(void* pFontBuffer, uint32_t fontBufferSize, void* pFontGlyphRanges, float fontSize, uintptr_t* pFont);
void* getContext();
bool update(GUIUpdate* pGuiUpdate);
void draw(Cmd* q);
bool onButton(uint32_t button, bool press, const float2* vec)
{
ImGui::SetCurrentContext(context);
ImGuiIO& io = ImGui::GetIO();
pMovePosition = vec;
switch (button)
{
case InputBindings::BUTTON_DPAD_LEFT: mNavInputs[ImGuiNavInput_DpadLeft] = (float)press; break;
case InputBindings::BUTTON_DPAD_RIGHT: mNavInputs[ImGuiNavInput_DpadRight] = (float)press; break;
case InputBindings::BUTTON_DPAD_UP: mNavInputs[ImGuiNavInput_DpadUp] = (float)press; break;
case InputBindings::BUTTON_DPAD_DOWN: mNavInputs[ImGuiNavInput_DpadDown] = (float)press; break;
case InputBindings::BUTTON_EAST: mNavInputs[ImGuiNavInput_Cancel] = (float)press; break;
case InputBindings::BUTTON_WEST: mNavInputs[ImGuiNavInput_Menu] = (float)press; break;
case InputBindings::BUTTON_NORTH: mNavInputs[ImGuiNavInput_Input] = (float)press; break;
case InputBindings::BUTTON_L1: mNavInputs[ImGuiNavInput_FocusPrev] = (float)press; break;
case InputBindings::BUTTON_R1: mNavInputs[ImGuiNavInput_FocusNext] = (float)press; break;
case InputBindings::BUTTON_L2: mNavInputs[ImGuiNavInput_TweakSlow] = (float)press; break;
case InputBindings::BUTTON_R2: mNavInputs[ImGuiNavInput_TweakFast] = (float)press; break;
case InputBindings::BUTTON_R3: if (!press) { mActive = !mActive; } break;
case InputBindings::BUTTON_KEYSHIFTL:
case InputBindings::BUTTON_KEYSHIFTR:
io.KeyShift = press;
break;
case InputBindings::BUTTON_SOUTH:
case InputBindings::BUTTON_MOUSE_RIGHT:
case InputBindings::BUTTON_MOUSE_MIDDLE:
case InputBindings::BUTTON_MOUSE_SCROLL_UP:
case InputBindings::BUTTON_MOUSE_SCROLL_DOWN:
{
const float scrollScale = 0.25f; // This should maybe be customized by client? 1.f would scroll ~5 lines of txt according to ImGui doc.
mNavInputs[ImGuiNavInput_Activate] = (float)press;
if (pMovePosition)
{
if (InputBindings::BUTTON_SOUTH == button)
io.MouseDown[0] = press;
else if (InputBindings::BUTTON_MOUSE_RIGHT == button)
io.MouseDown[1] = press;
else if (InputBindings::BUTTON_MOUSE_MIDDLE == button)
io.MouseDown[2] = press;
else if (InputBindings::BUTTON_MOUSE_SCROLL_UP == button)
io.MouseWheel = 1.f * scrollScale;
else if(InputBindings::BUTTON_MOUSE_SCROLL_DOWN == button)
io.MouseWheel = -1.f * scrollScale;
}
if (!mActive)
return true;
if (io.MousePos.x != -FLT_MAX && io.MousePos.y != -FLT_MAX)
{
return !(io.WantCaptureMouse);
}
else if (pMovePosition)
{
io.MousePos = *pMovePosition;
for (uint32_t i = 0; i < mLastUpdateCount; ++i)
{
if (ImGui::IsMouseHoveringRect(mLastUpdateMin[i], mLastUpdateMax[i], false))
{
io.WantCaptureMouse = true;
return false;
}
}
return true;
}
}
// Note that for keyboard keys, we only set them to true here if they are pressed because we may have a press/release
// happening in one frame and it would never get registered. Instead, unpressed are deferred at the end of update().
// This scenario occurs with mobile soft (on-screen) keyboards.
case InputBindings::BUTTON_BACK:
if (press)
io.KeysDown[InputBindings::BUTTON_BACK] = true;
mPostUpdateKeyDownStates[InputBindings::BUTTON_BACK] = press;
break;
case InputBindings::BUTTON_KEYLEFT:
if (press)
io.KeysDown[InputBindings::BUTTON_KEYLEFT] = true;
mPostUpdateKeyDownStates[InputBindings::BUTTON_KEYLEFT] = press;
break;
case InputBindings::BUTTON_KEYRIGHT:
if (press)
io.KeysDown[InputBindings::BUTTON_KEYRIGHT] = true;
mPostUpdateKeyDownStates[InputBindings::BUTTON_KEYRIGHT] = press;
break;
case InputBindings::BUTTON_KEYHOME:
if (press)
io.KeysDown[InputBindings::BUTTON_KEYHOME] = true;
mPostUpdateKeyDownStates[InputBindings::BUTTON_KEYHOME] = press;
break;
case InputBindings::BUTTON_KEYEND:
if (press)
io.KeysDown[InputBindings::BUTTON_KEYEND] = true;
mPostUpdateKeyDownStates[InputBindings::BUTTON_KEYEND] = press;
break;
case InputBindings::BUTTON_KEYDELETE:
if (press)
io.KeysDown[InputBindings::BUTTON_KEYDELETE] = true;
mPostUpdateKeyDownStates[InputBindings::BUTTON_KEYDELETE] = press;
break;
default:
break;
}
return false;
}
bool onText(const wchar_t* pText)
{
ImGui::SetCurrentContext(context);
ImGuiIO& io = ImGui::GetIO();
uint32_t len = (uint32_t)wcslen(pText);
for (uint32_t i = 0; i < len; ++i)
io.AddInputCharacter(pText[i]);
return !ImGui::GetIO().WantCaptureMouse;
}
uint8_t wantTextInput() const
{
ImGui::SetCurrentContext(context);
//The User flags are not what I expect them to be.
//We need access to Per-Component InputFlags
ImGuiContext* guiContext = (ImGuiContext*)this->context;
ImGuiInputTextFlags currentInputFlags = guiContext->InputTextState.UserFlags;
//0 -> Not pressed
//1 -> Digits Only keyboard
//2 -> Full Keyboard (Chars + Digits)
int inputState = ImGui::GetIO().WantTextInput ? 2 : 0;
//keyboard only Numbers
if (inputState > 0 && (currentInputFlags & ImGuiInputTextFlags_CharsDecimal))
{
inputState = 1;
}
return inputState;
}
bool isFocused()
{
ImGui::SetCurrentContext(context);
return ImGui::GetIO().WantCaptureMouse;
}
void setCustomShader(Shader* pShader)
{
pShaderTextured = pShader;
mCustomShader = true;
}
static void* alloc_func(size_t size, void* user_data) { return tf_malloc(size); }
static void dealloc_func(void* ptr, void* user_data) { tf_free(ptr); }
protected:
static const uint32_t MAX_FRAMES = 3;
ImGuiContext* context;
eastl::vector<Texture*> mFontTextures;
float2 dpiScale;
uint32_t frameIdx;
Renderer* pRenderer;
Shader* pShaderTextured;
RootSignature* pRootSignatureTextured;
DescriptorSet* pDescriptorSetUniforms;
DescriptorSet* pDescriptorSetTexture;
Pipeline* pPipelineTextured;
Buffer* pVertexBuffer;
Buffer* pIndexBuffer;
Buffer* pUniformBuffer[MAX_FRAMES];
/// Default states
Sampler* pDefaultSampler;
VertexLayout mVertexLayoutTextured = {};
uint32_t mMaxDynamicUIUpdatesPerBatch;
uint32_t mDynamicUIUpdates;
float mNavInputs[ImGuiNavInput_COUNT];
const float2* pMovePosition;
uint32_t mLastUpdateCount;
float2 mLastUpdateMin[64] = {};
float2 mLastUpdateMax[64] = {};
bool mActive;
bool mCustomShader;
bool mPostUpdateKeyDownStates[512];
};
static const uint64_t VERTEX_BUFFER_SIZE = 1024 * 64 * sizeof(ImDrawVert);
static const uint64_t INDEX_BUFFER_SIZE = 128 * 1024 * sizeof(ImDrawIdx);
void initGUIDriver(Renderer* pRenderer, GUIDriver** ppDriver)
{
ImguiGUIDriver* pDriver = tf_new(ImguiGUIDriver);
*ppDriver = pDriver;
}
void removeGUIDriver(GUIDriver* pDriver)
{
tf_delete(pDriver);
}
static float4 ToFloat4Color(uint color)
{
float4 col; // Translate colours back by bit shifting
col.x = (float)((color & 0xFF000000) >> 24);
col.y = (float)((color & 0x00FF0000) >> 16);
col.z = (float)((color & 0x0000FF00) >> 8);
col.w = (float)(color & 0x000000FF);
return col;
}
static uint ToUintColor(float4 color)
{
uint c = (((uint)color.x << 24) & 0xFF000000) | (((uint)color.y << 16) & 0x00FF0000) | (((uint)color.z << 8) & 0x0000FF00) |
(((uint)color.w) & 0x000000FF);
return c;
}
void IWidget::ProcessCallbacks(bool deferred)
{
if (!deferred)
{
mHovered = ImGui::IsItemHovered();
mActive = ImGui::IsItemActive();
mFocused = ImGui::IsItemFocused();
mEdited = ImGui::IsItemEdited();
mDeactivated = ImGui::IsItemDeactivated();
mDeactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit();
}
if (mDeferred != deferred)
{
return;
}
if (pOnHover && mHovered)
pOnHover();
if (pOnActive && mActive)
pOnActive();
if (pOnFocus && mFocused)
pOnFocus();
if (pOnEdited && mEdited)
pOnEdited();
if (pOnDeactivated && mDeactivated)
pOnDeactivated();
if (pOnDeactivatedAfterEdit && mDeactivatedAfterEdit)
pOnDeactivatedAfterEdit();
}
void CollapsingHeaderWidget::Draw()
{
if (mPreviousCollapsed != mCollapsed)
{
ImGui::SetNextTreeNodeOpen(!mCollapsed);
mPreviousCollapsed = mCollapsed;
}
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_CollapsingHeader;
if (mDefaultOpen)
flags |= ImGuiTreeNodeFlags_DefaultOpen;
if (!mHeaderIsVisible || ImGui::CollapsingHeader(mLabel.c_str(), flags))
{
for (IWidget* widget : mGroupedWidgets)
widget->Draw();
}
ProcessCallbacks();
}
void DebugTexturesWidget::Draw()
{
for (Texture* tex : mTextures)
{
ImGui::Image(tex, mTextureDisplaySize);
ImGui::SameLine();
}
ProcessCallbacks();
}
void LabelWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ProcessCallbacks();
}
void ColorLabelWidget::Draw()
{
ImGui::TextColored(mColor,"%s", mLabel.c_str());
ProcessCallbacks();
}
void HorizontalSpaceWidget::Draw()
{
ImGui::SameLine();
ProcessCallbacks();
}
void SeparatorWidget::Draw()
{
ImGui::Separator();
ProcessCallbacks();
}
void VerticalSeparatorWidget::Draw()
{
for (uint32_t i = 0; i < mLineCount; ++i)
{
ImGui::VerticalSeparator();
}
ProcessCallbacks();
}
void ButtonWidget::Draw()
{
ImGui::Button(mLabel.c_str());
ProcessCallbacks();
}
void SliderFloatWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::SliderFloatWithSteps(LABELID1(pData), pData, mMin, mMax, mStep, mFormat.c_str());
ProcessCallbacks();
}
void SliderFloat2Widget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
for (uint32_t i = 0; i < 2; ++i)
{
ImGui::SliderFloatWithSteps(LABELID1(&pData->operator[](i)), &pData->operator[](i), mMin[i], mMax[i], mStep[i], mFormat.c_str());
ProcessCallbacks();
}
}
void SliderFloat3Widget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
for (uint32_t i = 0; i < 3; ++i)
{
ImGui::SliderFloatWithSteps(LABELID1(&pData->operator[](i)), &pData->operator[](i), mMin[i], mMax[i], mStep[i], mFormat.c_str());
ProcessCallbacks();
}
}
void SliderFloat4Widget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
for (uint32_t i = 0; i < 4; ++i)
{
ImGui::SliderFloatWithSteps(LABELID1(&pData->operator[](i)), &pData->operator[](i), mMin[i], mMax[i], mStep[i], mFormat.c_str());
ProcessCallbacks();
}
}
void SliderIntWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::SliderIntWithSteps(LABELID1(pData), pData, mMin, mMax, mStep, mFormat.c_str());
ProcessCallbacks();
}
void SliderUintWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::SliderIntWithSteps(LABELID1(pData), (int32_t*)pData, (int32_t)mMin, (int32_t)mMax, (int32_t)mStep, mFormat.c_str());
ProcessCallbacks();
}
void RadioButtonWidget::Draw()
{
ImGui::RadioButton(mLabel.c_str(), pData, mRadioId);
ProcessCallbacks();
}
void CheckboxWidget::Draw()
{
ImGui::Text("%s", mLabel.c_str());
ImGui::Checkbox(LABELID1(pData), pData);
ProcessCallbacks();
}
void OneLineCheckboxWidget::Draw()
{
ImGui::Checkbox(LABELID1(pData), pData);
ImGui::SameLine();
ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(mColor),"%s", mLabel.c_str());
ProcessCallbacks();
}
void CursorLocationWidget::Draw()
{
ImGui::SetCursorPos(mLocation);
ProcessCallbacks();
}
void DropdownWidget::Draw()
{
uint32_t& current = *pData;
ImGui::Text("%s", mLabel.c_str());
if (ImGui::BeginCombo(LABELID1(pData), mNames[current].c_str()))
{
for (uint32_t i = 0; i < (uint32_t)mNames.size(); ++i)
{
if (ImGui::Selectable(mNames[i].c_str()))
{
uint32_t prevVal = current;
current = i;
// Note that callbacks are sketchy with BeginCombo/EndCombo, so we manually process them here
if (pOnEdited)
pOnEdited();
if (current != prevVal)
{
if (pOnDeactivatedAfterEdit)
pOnDeactivatedAfterEdit();
}
}
}
ImGui::EndCombo();
}
}
void ColumnWidget::Draw()
{
// Test a simple 4 col table.
ImGui::BeginColumns(mLabel.c_str(), mNumColumns, ImGuiColumnsFlags_NoResize | ImGuiColumnsFlags_NoForceWithinWindow);
for (uint32_t i = 0; i < mNumColumns; ++i)
{
mPerColumnWidgets[i]->Draw();
ImGui::NextColumn();
}
ImGui::EndColumns();
ProcessCallbacks();
}
void ProgressBarWidget::Draw()
{
size_t currProgress = *pData;
ImGui::Text("%s", mLabel.c_str());
ImGui::ProgressBar((float)currProgress / mMaxProgress);
ProcessCallbacks();
}
void ColorSliderWidget::Draw()
{
uint& colorPick = *(uint*)pData;
float4 combo_color = ToFloat4Color(colorPick) / 255.0f;
float col[4] = { combo_color.x, combo_color.y, combo_color.z, combo_color.w };
ImGui::Text("%s", mLabel.c_str());
if (ImGui::ColorEdit4(LABELID1(pData), col, ImGuiColorEditFlags_AlphaPreview))
{
if (col[0] != combo_color.x || col[1] != combo_color.y || col[2] != combo_color.z || col[3] != combo_color.w)
{
combo_color = col;
colorPick = ToUintColor(combo_color * 255.0f);
}
}
ProcessCallbacks();
}
void HistogramWidget::Draw()
{
ImGui::PlotHistogram(mLabel.c_str(), pValues, mCount, 0, mHistogramTitle->c_str(), *mMinScale, *mMaxScale, mHistogramSize);
ProcessCallbacks();
}
void PlotLinesWidget::Draw()
{
ImGui::PlotLines(mLabel.c_str(), mValues, mNumValues, 0, mTitle->c_str(), *mScaleMin, *mScaleMax, *mPlotScale);
ProcessCallbacks();
}
void ColorPickerWidget::Draw()
{
uint& colorPick = *(uint*)pData;
float4 combo_color = ToFloat4Color(colorPick) / 255.0f;
float col[4] = { combo_color.x, combo_color.y, combo_color.z, combo_color.w };
ImGui::Text("%s", mLabel.c_str());
if (ImGui::ColorPicker4(LABELID1(pData), col, ImGuiColorEditFlags_AlphaPreview))
{
if (col[0] != combo_color.x || col[1] != combo_color.y || col[2] != combo_color.z || col[3] != combo_color.w)
{
combo_color = col;
colorPick = ToUintColor(combo_color * 255.0f);
}
}
ProcessCallbacks();
}
void TextboxWidget::Draw()
{
ImGui::InputText(LABELID1(pData), (char*)pData, mLength, mAutoSelectAll ? ImGuiInputTextFlags_AutoSelectAll : 0);
ProcessCallbacks();
}
void DynamicTextWidget::Draw()
{
ImGui::TextColored(*pColor, "%s", pData);
ProcessCallbacks();
}
void FilledRectWidget::Draw()
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
float2 pos = window->Pos - window->Scroll + mPos;
float2 pos2 = float2(pos.x + mScale.x, pos.y + mScale.y);
ImGui::GetWindowDrawList()->AddRectFilled(pos, pos2, ImGui::GetColorU32(mColor));
ProcessCallbacks();
}
void DrawTextWidget::Draw()
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
float2 pos = window->Pos - window->Scroll + mPos;
const float2 line_size = ImGui::CalcTextSize(mLabel.c_str());
ImGui::GetWindowDrawList()->AddText(pos, ImGui::GetColorU32(mColor), mLabel.c_str());
ImRect bounding_box(pos, pos + line_size);
ImGui::ItemSize(bounding_box);
ImGui::ItemAdd(bounding_box, 0);
ProcessCallbacks();
}
void DrawTooltipWidget::Draw()
{
if ((*mShowTooltip) == true)
{
ImGui::BeginTooltip();
ImGui::TextUnformatted(mText);
ImGui::EndTooltip();
}
ProcessCallbacks();
}
void DrawLineWidget::Draw()
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
float2 pos1 = window->Pos - window->Scroll + mPos1;
float2 pos2 = window->Pos - window->Scroll + mPos2;
ImGui::GetWindowDrawList()->AddLine(pos1, pos2, ImGui::GetColorU32(mColor));
if (mAddItem)
{
ImRect bounding_box(pos1, pos2);
ImGui::ItemSize(bounding_box);
ImGui::ItemAdd(bounding_box, 0);
}
ProcessCallbacks();
}
void DrawCurveWidget::Draw()
{
ImGuiWindow* window = ImGui::GetCurrentWindow();
for (uint32_t i = 0; i < mNumPoints-1; i++)
{
float2 pos1 = window->Pos - window->Scroll + mPos[i];
float2 pos2 = window->Pos - window->Scroll + mPos[i+1];
ImGui::GetWindowDrawList()->AddLine(pos1, pos2, ImGui::GetColorU32(mColor), mThickness);
}
ProcessCallbacks();
}
static void SetDefaultStyle()
{
ImGuiStyle& style = ImGui::GetStyle();
style.WindowRounding = 0.4f;
float4* colors = style.Colors;
colors[ImGuiCol_Text] = float4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = float4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = float4(0.06f, 0.06f, 0.06f, 1.0f);
colors[ImGuiCol_ChildBg] = float4(1.00f, 1.00f, 1.00f, 0.00f);
colors[ImGuiCol_PopupBg] = float4(0.08f, 0.08f, 0.08f, 0.94f);
colors[ImGuiCol_Border] = float4(0.43f, 0.43f, 0.50f, 0.50f);
colors[ImGuiCol_BorderShadow] = float4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = float4(0.20f, 0.21f, 0.22f, 0.54f);
colors[ImGuiCol_FrameBgHovered] = float4(0.40f, 0.40f, 0.40f, 0.40f);
colors[ImGuiCol_FrameBgActive] = float4(0.18f, 0.18f, 0.18f, 0.67f);
colors[ImGuiCol_TitleBg] = float4(0.04f, 0.04f, 0.04f, 1.00f);
colors[ImGuiCol_TitleBgActive] = float4(0.29f, 0.29f, 0.29f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = float4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = float4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = float4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = float4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = float4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = float4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_CheckMark] = float4(0.94f, 0.94f, 0.94f, 1.00f);
colors[ImGuiCol_SliderGrab] = float4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = float4(0.86f, 0.86f, 0.86f, 1.00f);
colors[ImGuiCol_Button] = float4(0.44f, 0.44f, 0.44f, 0.40f);
colors[ImGuiCol_ButtonHovered] = float4(0.46f, 0.47f, 0.48f, 1.00f);
colors[ImGuiCol_ButtonActive] = float4(0.42f, 0.42f, 0.42f, 1.00f);
colors[ImGuiCol_Header] = float4(0.70f, 0.70f, 0.70f, 0.31f);
colors[ImGuiCol_HeaderHovered] = float4(0.70f, 0.70f, 0.70f, 0.80f);
colors[ImGuiCol_HeaderActive] = float4(0.48f, 0.50f, 0.52f, 1.00f);
colors[ImGuiCol_Separator] = float4(0.43f, 0.43f, 0.50f, 0.50f);
colors[ImGuiCol_SeparatorHovered] = float4(0.72f, 0.72f, 0.72f, 0.78f);
colors[ImGuiCol_SeparatorActive] = float4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_ResizeGrip] = float4(0.91f, 0.91f, 0.91f, 0.25f);
colors[ImGuiCol_ResizeGripHovered] = float4(0.81f, 0.81f, 0.81f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = float4(0.46f, 0.46f, 0.46f, 0.95f);
colors[ImGuiCol_PlotLines] = float4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = float4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = float4(0.73f, 0.60f, 0.15f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = float4(1.00f, 0.60f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = float4(0.87f, 0.87f, 0.87f, 0.35f);
colors[ImGuiCol_ModalWindowDarkening] = float4(0.80f, 0.80f, 0.80f, 0.35f);
colors[ImGuiCol_DragDropTarget] = float4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = float4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = float4(1.00f, 1.00f, 1.00f, 0.70f);
const float2 dpiScale = getDpiScale();
style.ScaleAllSizes(min(dpiScale.x, dpiScale.y));
}
bool ImguiGUIDriver::init(Renderer* renderer, uint32_t const maxDynamicUIUpdatesPerBatch)
{
mHandledGestures = false;
pRenderer = renderer;
mMaxDynamicUIUpdatesPerBatch = maxDynamicUIUpdatesPerBatch;
mActive = true;
memset(mPostUpdateKeyDownStates, false, sizeof(mPostUpdateKeyDownStates));
/************************************************************************/
// Rendering resources
/************************************************************************/
SamplerDesc samplerDesc = { FILTER_LINEAR,
FILTER_LINEAR,
MIPMAP_MODE_NEAREST,
ADDRESS_MODE_CLAMP_TO_EDGE,
ADDRESS_MODE_CLAMP_TO_EDGE,
ADDRESS_MODE_CLAMP_TO_EDGE };
addSampler(pRenderer, &samplerDesc, &pDefaultSampler);
if (!mCustomShader)
{
#ifdef USE_UI_PRECOMPILED_SHADERS
BinaryShaderDesc binaryShaderDesc = {};
binaryShaderDesc.mStages = SHADER_STAGE_VERT | SHADER_STAGE_FRAG;
binaryShaderDesc.mVert.mByteCodeSize = sizeof(gShaderImguiVert);
binaryShaderDesc.mVert.pByteCode = (char*)gShaderImguiVert;
binaryShaderDesc.mVert.pEntryPoint = "main";
binaryShaderDesc.mFrag.mByteCodeSize = sizeof(gShaderImguiFrag);
binaryShaderDesc.mFrag.pByteCode = (char*)gShaderImguiFrag;
binaryShaderDesc.mFrag.pEntryPoint = "main";
addShaderBinary(pRenderer, &binaryShaderDesc, &pShaderTextured);
#else
ShaderLoadDesc texturedShaderDesc = {};
texturedShaderDesc.mStages[0] = { "imgui.vert", NULL, 0, NULL };
texturedShaderDesc.mStages[1] = { "imgui.frag", NULL, 0, NULL };
addShader(pRenderer, &texturedShaderDesc, &pShaderTextured);
#endif
}
const char* pStaticSamplerNames[] = { "uSampler" };
RootSignatureDesc textureRootDesc = { &pShaderTextured, 1 };
textureRootDesc.mStaticSamplerCount = 1;
textureRootDesc.ppStaticSamplerNames = pStaticSamplerNames;
textureRootDesc.ppStaticSamplers = &pDefaultSampler;
addRootSignature(pRenderer, &textureRootDesc, &pRootSignatureTextured);
DescriptorSetDesc setDesc = { pRootSignatureTextured, DESCRIPTOR_UPDATE_FREQ_PER_BATCH, 1 + (maxDynamicUIUpdatesPerBatch * MAX_FRAMES) };
addDescriptorSet(pRenderer, &setDesc, &pDescriptorSetTexture);
setDesc = { pRootSignatureTextured, DESCRIPTOR_UPDATE_FREQ_NONE, MAX_FRAMES };
addDescriptorSet(pRenderer, &setDesc, &pDescriptorSetUniforms);
BufferLoadDesc vbDesc = {};
vbDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_VERTEX_BUFFER;
vbDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU;
vbDesc.mDesc.mSize = VERTEX_BUFFER_SIZE * MAX_FRAMES;
vbDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT;
vbDesc.ppBuffer = &pVertexBuffer;
addResource(&vbDesc, NULL);
BufferLoadDesc ibDesc = vbDesc;
ibDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_INDEX_BUFFER;
ibDesc.mDesc.mSize = INDEX_BUFFER_SIZE * MAX_FRAMES;
ibDesc.ppBuffer = &pIndexBuffer;
addResource(&ibDesc, NULL);
BufferLoadDesc ubDesc = {};
ubDesc.mDesc.mDescriptors = DESCRIPTOR_TYPE_UNIFORM_BUFFER;
ubDesc.mDesc.mMemoryUsage = RESOURCE_MEMORY_USAGE_CPU_TO_GPU;
ubDesc.mDesc.mFlags = BUFFER_CREATION_FLAG_PERSISTENT_MAP_BIT;
ubDesc.mDesc.mSize = sizeof(mat4);
for (uint32_t i = 0; i < MAX_FRAMES; ++i)
{
ubDesc.ppBuffer = &pUniformBuffer[i];
addResource(&ubDesc, NULL);
}
mVertexLayoutTextured.mAttribCount = 3;
mVertexLayoutTextured.mAttribs[0].mSemantic = SEMANTIC_POSITION;
mVertexLayoutTextured.mAttribs[0].mFormat = TinyImageFormat_R32G32_SFLOAT;
mVertexLayoutTextured.mAttribs[0].mBinding = 0;
mVertexLayoutTextured.mAttribs[0].mLocation = 0;
mVertexLayoutTextured.mAttribs[0].mOffset = 0;
mVertexLayoutTextured.mAttribs[1].mSemantic = SEMANTIC_TEXCOORD0;
mVertexLayoutTextured.mAttribs[1].mFormat = TinyImageFormat_R32G32_SFLOAT;
mVertexLayoutTextured.mAttribs[1].mBinding = 0;
mVertexLayoutTextured.mAttribs[1].mLocation = 1;
mVertexLayoutTextured.mAttribs[1].mOffset = TinyImageFormat_BitSizeOfBlock(mVertexLayoutTextured.mAttribs[0].mFormat) / 8;
mVertexLayoutTextured.mAttribs[2].mSemantic = SEMANTIC_COLOR;
mVertexLayoutTextured.mAttribs[2].mFormat = TinyImageFormat_R8G8B8A8_UNORM;
mVertexLayoutTextured.mAttribs[2].mBinding = 0;
mVertexLayoutTextured.mAttribs[2].mLocation = 2;
mVertexLayoutTextured.mAttribs[2].mOffset =
mVertexLayoutTextured.mAttribs[1].mOffset + TinyImageFormat_BitSizeOfBlock(mVertexLayoutTextured.mAttribs[1].mFormat) / 8;
/************************************************************************/
/************************************************************************/
dpiScale = getDpiScale();
//// init UI (input)
ImGui::SetAllocatorFunctions(alloc_func, dealloc_func);
context = ImGui::CreateContext();
ImGui::SetCurrentContext(context);
SetDefaultStyle();
ImGuiIO& io = ImGui::GetIO();
io.NavActive = true;
io.WantCaptureMouse = false;
io.KeyMap[ImGuiKey_Backspace] = InputBindings::BUTTON_BACK;
io.KeyMap[ImGuiKey_LeftArrow] = InputBindings::BUTTON_KEYLEFT;
io.KeyMap[ImGuiKey_RightArrow] = InputBindings::BUTTON_KEYRIGHT;
io.KeyMap[ImGuiKey_Home] = InputBindings::BUTTON_KEYHOME;
io.KeyMap[ImGuiKey_End] = InputBindings::BUTTON_KEYEND;
io.KeyMap[ImGuiKey_Delete] = InputBindings::BUTTON_KEYDELETE;
for (uint32_t i = 0; i < MAX_FRAMES; ++i)
{
DescriptorData params[1] = {};
params[0].pName = "uniformBlockVS";
params[0].ppBuffers = &pUniformBuffer[i];
updateDescriptorSet(pRenderer, i, pDescriptorSetUniforms, 1, params);
}
return true;
}
void ImguiGUIDriver::exit()
{
removeSampler(pRenderer, pDefaultSampler);
if (!mCustomShader)
removeShader(pRenderer, pShaderTextured);
removeDescriptorSet(pRenderer, pDescriptorSetTexture);
removeDescriptorSet(pRenderer, pDescriptorSetUniforms);
removeRootSignature(pRenderer, pRootSignatureTextured);
removeResource(pVertexBuffer);
removeResource(pIndexBuffer);
for (uint32_t i = 0; i < MAX_FRAMES; ++i)
removeResource(pUniformBuffer[i]);
for (Texture*& pFontTexture : mFontTextures)
removeResource(pFontTexture);
mFontTextures.set_capacity(0);
ImGui::DestroyDemoWindow();
ImGui::DestroyContext(context);
}
bool ImguiGUIDriver::addFont(void* pFontBuffer, uint32_t fontBufferSize, void* pFontGlyphRanges, float fontSize, uintptr_t* pFont)
{
// Build and load the texture atlas into a texture
int width, height, bytesPerPixel;
unsigned char* pixels = NULL;
ImGuiIO& io = ImGui::GetIO();
ImFontConfig config = {};
config.FontDataOwnedByAtlas = false;
ImFont* font = io.Fonts->AddFontFromMemoryTTF(pFontBuffer, fontBufferSize,
fontSize * min(dpiScale.x, dpiScale.y), &config,
(const ImWchar*)pFontGlyphRanges);
if (font != NULL)
{
io.FontDefault = font;
*pFont = (uintptr_t)font;
}
else
{
*pFont = (uintptr_t)io.Fonts->AddFontDefault();
}
io.Fonts->Build();
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytesPerPixel);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
Texture* pTexture = NULL;
SyncToken token = {};
TextureLoadDesc loadDesc = {};
TextureDesc textureDesc = {};
textureDesc.mArraySize = 1;
textureDesc.mDepth = 1;
textureDesc.mDescriptors = DESCRIPTOR_TYPE_TEXTURE;
textureDesc.mFormat = TinyImageFormat_R8G8B8A8_UNORM;
textureDesc.mHeight = height;
textureDesc.mMipLevels = 1;
textureDesc.mSampleCount = SAMPLE_COUNT_1;
textureDesc.mStartState = RESOURCE_STATE_COMMON;
textureDesc.mWidth = width;
textureDesc.pName = "ImGui Font Texture";
loadDesc.pDesc = &textureDesc;
loadDesc.ppTexture = &pTexture;
addResource(&loadDesc, &token);
waitForToken(&token);
TextureUpdateDesc updateDesc = { pTexture };
beginUpdateResource(&updateDesc);
for (uint32_t r = 0; r < updateDesc.mRowCount; ++r)
{
memcpy(updateDesc.pMappedData + r * updateDesc.mDstRowStride,
pixels + r * updateDesc.mSrcRowStride, updateDesc.mSrcRowStride);
}
endUpdateResource(&updateDesc, &token);
mFontTextures.emplace_back(pTexture);
io.Fonts->TexID = (void*)(mFontTextures.size() - 1);
DescriptorData params[1] = {};
params[0].pName = "uTex";
params[0].ppTextures = &pTexture;
updateDescriptorSet(pRenderer, (uint32_t)mFontTextures.size() - 1, pDescriptorSetTexture, 1, params);
return true;
}
bool ImguiGUIDriver::load(RenderTarget** ppRts, uint32_t count, PipelineCache* pCache)
{
UNREF_PARAM(count);
BlendStateDesc blendStateDesc = {};
blendStateDesc.mSrcFactors[0] = BC_SRC_ALPHA;
blendStateDesc.mDstFactors[0] = BC_ONE_MINUS_SRC_ALPHA;
blendStateDesc.mSrcAlphaFactors[0] = BC_SRC_ALPHA;
blendStateDesc.mDstAlphaFactors[0] = BC_ONE_MINUS_SRC_ALPHA;
blendStateDesc.mMasks[0] = ALL;
blendStateDesc.mRenderTargetMask = BLEND_STATE_TARGET_ALL;
blendStateDesc.mIndependentBlend = false;
DepthStateDesc depthStateDesc = {};
depthStateDesc.mDepthTest = false;
depthStateDesc.mDepthWrite = false;
RasterizerStateDesc rasterizerStateDesc = {};
rasterizerStateDesc.mCullMode = CULL_MODE_NONE;
rasterizerStateDesc.mScissor = true;
PipelineDesc desc = {};
desc.pCache = pCache;
desc.mType = PIPELINE_TYPE_GRAPHICS;
GraphicsPipelineDesc& pipelineDesc = desc.mGraphicsDesc;
pipelineDesc.mDepthStencilFormat = TinyImageFormat_UNDEFINED;
pipelineDesc.mRenderTargetCount = 1;
pipelineDesc.mSampleCount = ppRts[0]->mSampleCount;
pipelineDesc.pBlendState = &blendStateDesc;
pipelineDesc.mSampleQuality = ppRts[0]->mSampleQuality;
pipelineDesc.pColorFormats = &ppRts[0]->mFormat;
pipelineDesc.pDepthState = &depthStateDesc;
pipelineDesc.pRasterizerState = &rasterizerStateDesc;
pipelineDesc.pRootSignature = pRootSignatureTextured;
pipelineDesc.pShaderProgram = pShaderTextured;
pipelineDesc.pVertexLayout = &mVertexLayoutTextured;
pipelineDesc.mPrimitiveTopo = PRIMITIVE_TOPO_TRI_LIST;
addPipeline(pRenderer, &desc, &pPipelineTextured);
return true;
}
void ImguiGUIDriver::unload()
{
removePipeline(pRenderer, pPipelineTextured);
}
void* ImguiGUIDriver::getContext()
{
return context;
}
bool ImguiGUIDriver::update(GUIUpdate* pGuiUpdate)
{
ImGui::SetCurrentContext(context);
// #TODO: Use window size as render-target size cannot be trusted to be the same as window size
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize.x = pGuiUpdate->width;
io.DisplaySize.y = pGuiUpdate->height;
io.DeltaTime = pGuiUpdate->deltaTime;
if (pMovePosition)
io.MousePos = *pMovePosition;
memcpy(io.NavInputs, mNavInputs, sizeof(mNavInputs));
ImGui::NewFrame();
bool ret = false;
if (mActive)
{
if (pGuiUpdate->showDemoWindow)
ImGui::ShowDemoWindow();
mLastUpdateCount = pGuiUpdate->componentCount;
for (uint32_t compIndex = 0; compIndex < pGuiUpdate->componentCount; ++compIndex)
{
GuiComponent* pComponent = pGuiUpdate->pGuiComponents[compIndex];
eastl::string title = pComponent->mTitle;
int32_t guiComponentFlags = pComponent->mFlags;
bool* pCloseButtonActiveValue = pComponent->mHasCloseButton ? &pComponent->mHasCloseButton : NULL;
const eastl::vector<eastl::string>& contextualMenuLabels = pComponent->mContextualMenuLabels;
const eastl::vector<WidgetCallback>& contextualMenuCallbacks = pComponent->mContextualMenuCallbacks;
const float4& windowRect = pComponent->mInitialWindowRect;
float4& currentWindowRect = pComponent->mCurrentWindowRect;
IWidget** pProps = pComponent->mWidgets.data();
uint32_t propCount = (uint32_t)pComponent->mWidgets.size();
if (title == "")
title.sprintf("##%llu", (uint64_t)pComponent);
// Setup the ImGuiWindowFlags
ImGuiWindowFlags guiWinFlags = GUI_COMPONENT_FLAGS_NONE;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_TITLE_BAR)
guiWinFlags |= ImGuiWindowFlags_NoTitleBar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_RESIZE)
guiWinFlags |= ImGuiWindowFlags_NoResize;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_MOVE)
guiWinFlags |= ImGuiWindowFlags_NoMove;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_NoScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_COLLAPSE)
guiWinFlags |= ImGuiWindowFlags_NoCollapse;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_AUTO_RESIZE)
guiWinFlags |= ImGuiWindowFlags_AlwaysAutoResize;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_INPUTS)
guiWinFlags |= ImGuiWindowFlags_NoInputs;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_MEMU_BAR)
guiWinFlags |= ImGuiWindowFlags_MenuBar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_HORIZONTAL_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_HorizontalScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_FOCUS_ON_APPEARING)
guiWinFlags |= ImGuiWindowFlags_NoFocusOnAppearing;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_BRING_TO_FRONT_ON_FOCUS)
guiWinFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_VERTICAL_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_AlwaysVerticalScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_HORIZONTAL_SCROLLBAR)
guiWinFlags |= ImGuiWindowFlags_AlwaysHorizontalScrollbar;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_USE_WINDOW_PADDING)
guiWinFlags |= ImGuiWindowFlags_AlwaysUseWindowPadding;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_NAV_INPUT)
guiWinFlags |= ImGuiWindowFlags_NoNavInputs;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_NAV_FOCUS)
guiWinFlags |= ImGuiWindowFlags_NoNavFocus;
ImGui::PushFont((ImFont*)pComponent->pFont);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, pComponent->mAlpha);
bool result = ImGui::Begin(title.c_str(), pCloseButtonActiveValue, guiWinFlags);
if (result)
{
// Setup the contextual menus
if (!contextualMenuLabels.empty() && ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered()
{
for (size_t i = 0; i < contextualMenuLabels.size(); i++)
{
if (ImGui::MenuItem(contextualMenuLabels[i].c_str()))
{
if (i < contextualMenuCallbacks.size())
contextualMenuCallbacks[i]();
}
}
ImGui::EndPopup();
}
bool overrideSize = false;
bool overridePos = false;
if ((guiComponentFlags & GUI_COMPONENT_FLAGS_NO_RESIZE) && !(guiComponentFlags & GUI_COMPONENT_FLAGS_ALWAYS_AUTO_RESIZE))
overrideSize = true;
if (guiComponentFlags & GUI_COMPONENT_FLAGS_NO_MOVE)
overridePos = true;
ImGui::SetWindowSize(
float2(windowRect.z, windowRect.w), overrideSize ? ImGuiCond_Always : ImGuiCond_Once);
ImGui::SetWindowPos(
float2(windowRect.x, windowRect.y), overridePos ? ImGuiCond_Always : ImGuiCond_Once);
if (guiComponentFlags & GUI_COMPONENT_FLAGS_START_COLLAPSED)
ImGui::SetWindowCollapsed(true, ImGuiCond_Once);
for (uint32_t i = 0; i < propCount; ++i)
{
if (pProps[i] != nullptr)
{
pProps[i]->Draw();
}
}
ret = ret || ImGui::GetIO().WantCaptureMouse;
}
float2 pos = ImGui::GetWindowPos();
float2 size = ImGui::GetWindowSize();
currentWindowRect.x = pos.x;
currentWindowRect.y = pos.y;
currentWindowRect.z = size.x;
currentWindowRect.w = size.y;
mLastUpdateMin[compIndex] = pos;
mLastUpdateMax[compIndex] = pos + size;
// Need to call ImGui::End event if result is false since we called ImGui::Begin
ImGui::End();
ImGui::PopStyleVar();
ImGui::PopFont();
}
}
ImGui::EndFrame();
if (mActive)
{
for (uint32_t compIndex = 0; compIndex < pGuiUpdate->componentCount; ++compIndex)
{
GuiComponent* pComponent = pGuiUpdate->pGuiComponents[compIndex];
IWidget** pProps = pComponent->mWidgets.data();
uint32_t propCount = (uint32_t)pComponent->mWidgets.size();
for (uint32_t i = 0; i < propCount; ++i)
{
if (pProps[i] != nullptr)
{
pProps[i]->ProcessCallbacks(true);
}
}
}
}
if (!io.MouseDown[0])
{
io.MousePos = float2(-FLT_MAX);
}
mHandledGestures = false;
// Apply post update keydown states
memcpy(io.KeysDown, mPostUpdateKeyDownStates, sizeof(io.KeysDown));
return ret;
}
void ImguiGUIDriver::draw(Cmd* pCmd)
{
/************************************************************************/
/************************************************************************/
ImGui::SetCurrentContext(context);
ImGui::Render();
mDynamicUIUpdates = 0;
ImDrawData* draw_data = ImGui::GetDrawData();
Pipeline* pPipeline = pPipelineTextured;
uint32_t vSize = 0;
uint32_t iSize = 0;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
vSize += (int)(cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
iSize += (int)(cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
}
vSize = min<uint32_t>(vSize, VERTEX_BUFFER_SIZE);
iSize = min<uint32_t>(iSize, INDEX_BUFFER_SIZE);
// Copy and convert all vertices into a single contiguous buffer
uint64_t vOffset = frameIdx * VERTEX_BUFFER_SIZE;
uint64_t iOffset = frameIdx * INDEX_BUFFER_SIZE;
uint64_t vtx_dst = vOffset;
uint64_t idx_dst = iOffset;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
BufferUpdateDesc update = { pVertexBuffer, vtx_dst };
beginUpdateResource(&update);
memcpy(update.pMappedData, cmd_list->VtxBuffer.data(), cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
endUpdateResource(&update, NULL);
update = { pIndexBuffer, idx_dst };
beginUpdateResource(&update);
memcpy(update.pMappedData, cmd_list->IdxBuffer.data(), cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
endUpdateResource(&update, NULL);
vtx_dst += (cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
idx_dst += (cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
}
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
float mvp[4][4] = {
{ 2.0f / (R - L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f / (T - B), 0.0f, 0.0f },
{ 0.0f, 0.0f, 0.5f, 0.0f },
{ (R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f },
};
BufferUpdateDesc update = { pUniformBuffer[frameIdx] };
beginUpdateResource(&update);
*((mat4*)update.pMappedData) = *(mat4*)mvp;
endUpdateResource(&update, NULL);
const uint32_t vertexStride = sizeof(ImDrawVert);
cmdSetViewport(pCmd, 0.0f, 0.0f, draw_data->DisplaySize.x, draw_data->DisplaySize.y, 0.0f, 1.0f);
cmdSetScissor(
pCmd, (uint32_t)draw_data->DisplayPos.x, (uint32_t)draw_data->DisplayPos.y, (uint32_t)draw_data->DisplaySize.x,
(uint32_t)draw_data->DisplaySize.y);
cmdBindPipeline(pCmd, pPipeline);
cmdBindIndexBuffer(pCmd, pIndexBuffer, INDEX_TYPE_UINT16, iOffset);
cmdBindVertexBuffer(pCmd, 1, &pVertexBuffer, &vertexStride, &vOffset);
cmdBindDescriptorSet(pCmd, frameIdx, pDescriptorSetUniforms);
// Render command lists
int vtx_offset = 0;
int idx_offset = 0;
float2 pos = draw_data->DisplayPos;
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
// User callback (registered via ImDrawList::AddCallback)
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Apply scissor/clipping rectangle
//const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) };
//pCmd->pDxCmdList->RSSetScissorRects(1, &r);
cmdSetScissor(
pCmd, (uint32_t)(pcmd->ClipRect.x - pos.x), (uint32_t)(pcmd->ClipRect.y - pos.y),
(uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x), (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y));
size_t id = (size_t)pcmd->TextureId;
if (id >= mFontTextures.size())
{
uint32_t setIndex = (uint32_t)mFontTextures.size() + (frameIdx * mMaxDynamicUIUpdatesPerBatch + mDynamicUIUpdates);
DescriptorData params[1] = {};
params[0].pName = "uTex";
params[0].ppTextures = (Texture**)&pcmd->TextureId;
updateDescriptorSet(pRenderer, setIndex, pDescriptorSetTexture, 1, params);
cmdBindDescriptorSet(pCmd, setIndex, pDescriptorSetTexture);
++mDynamicUIUpdates;
}
else
{
cmdBindDescriptorSet(pCmd, (uint32_t)id, pDescriptorSetTexture);
}
cmdDrawIndexed(pCmd, pcmd->ElemCount, idx_offset, vtx_offset);
}
idx_offset += pcmd->ElemCount;
}
vtx_offset += (int)cmd_list->VtxBuffer.size();
}
frameIdx = (frameIdx + 1) % MAX_FRAMES;
}
|
#include "common.h"
#include "song_factory.h"
SongFactory::SongFactory() {
}
spISong SongFactory::CreateSongObj(umMusicAttribute& song_map) {
spISong ret = nullptr;
ret = std::make_shared<CSong>(song_map);
return ret;
}
|
/*************************************************************************/
/* collision_shape_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "collision_shape_2d.h"
#include "collision_object_2d.h"
#include "engine.h"
#include "scene/resources/capsule_shape_2d.h"
#include "scene/resources/circle_shape_2d.h"
#include "scene/resources/concave_polygon_shape_2d.h"
#include "scene/resources/convex_polygon_shape_2d.h"
#include "scene/resources/rectangle_shape_2d.h"
#include "scene/resources/segment_shape_2d.h"
#include "scene/resources/shape_line_2d.h"
void CollisionShape2D::_shape_changed() {
update();
}
void CollisionShape2D::_update_in_shape_owner(bool p_xform_only) {
parent->shape_owner_set_transform(owner_id, get_transform());
if (p_xform_only)
return;
parent->shape_owner_set_disabled(owner_id, disabled);
parent->shape_owner_set_one_way_collision(owner_id, one_way_collision);
}
void CollisionShape2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_PARENTED: {
parent = Object::cast_to<CollisionObject2D>(get_parent());
if (parent) {
owner_id = parent->create_shape_owner(this);
if (shape.is_valid()) {
parent->shape_owner_add_shape(owner_id, shape);
}
_update_in_shape_owner();
}
/*if (Engine::get_singleton()->is_editor_hint()) {
//display above all else
set_z_as_relative(false);
set_z_index(VS::CANVAS_ITEM_Z_MAX - 1);
}*/
} break;
case NOTIFICATION_ENTER_TREE: {
if (parent) {
_update_in_shape_owner();
}
} break;
case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
if (parent) {
_update_in_shape_owner(true);
}
} break;
case NOTIFICATION_UNPARENTED: {
if (parent) {
parent->remove_shape_owner(owner_id);
}
owner_id = 0;
parent = NULL;
} break;
/*
case NOTIFICATION_TRANSFORM_CHANGED: {
if (!is_inside_scene())
break;
_update_parent();
} break;*/
case NOTIFICATION_DRAW: {
if (!Engine::get_singleton()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) {
break;
}
if (!shape.is_valid()) {
break;
}
rect = Rect2();
Color draw_col = get_tree()->get_debug_collisions_color();
if (disabled) {
float g = draw_col.get_v();
draw_col.r = g;
draw_col.g = g;
draw_col.b = g;
}
shape->draw(get_canvas_item(), draw_col);
rect = shape->get_rect();
rect = rect.grow(3);
if (one_way_collision) {
Color dcol = get_tree()->get_debug_collisions_color(); //0.9,0.2,0.2,0.4);
dcol.a = 1.0;
Vector2 line_to(0, 20);
draw_line(Vector2(), line_to, dcol, 3);
Vector<Vector2> pts;
float tsize = 8;
pts.push_back(line_to + (Vector2(0, tsize)));
pts.push_back(line_to + (Vector2(0.707 * tsize, 0)));
pts.push_back(line_to + (Vector2(-0.707 * tsize, 0)));
Vector<Color> cols;
for (int i = 0; i < 3; i++)
cols.push_back(dcol);
draw_primitive(pts, cols, Vector<Vector2>()); //small arrow
}
} break;
}
}
void CollisionShape2D::set_shape(const Ref<Shape2D> &p_shape) {
if (shape.is_valid())
shape->disconnect("changed", this, "_shape_changed");
shape = p_shape;
update();
if (parent) {
parent->shape_owner_clear_shapes(owner_id);
if (shape.is_valid()) {
parent->shape_owner_add_shape(owner_id, shape);
}
}
if (shape.is_valid())
shape->connect("changed", this, "_shape_changed");
update_configuration_warning();
}
Ref<Shape2D> CollisionShape2D::get_shape() const {
return shape;
}
bool CollisionShape2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
if (!shape.is_valid())
return false;
return shape->_edit_is_selected_on_click(p_point, p_tolerance);
}
String CollisionShape2D::get_configuration_warning() const {
if (!Object::cast_to<CollisionObject2D>(get_parent())) {
return TTR("CollisionShape2D only serves to provide a collision shape to a CollisionObject2D derived node. Please only use it as a child of Area2D, StaticBody2D, RigidBody2D, KinematicBody2D, etc. to give them a shape.");
}
if (!shape.is_valid()) {
return TTR("A shape must be provided for CollisionShape2D to function. Please create a shape resource for it!");
}
return String();
}
void CollisionShape2D::set_disabled(bool p_disabled) {
disabled = p_disabled;
update();
if (parent) {
parent->shape_owner_set_disabled(owner_id, p_disabled);
}
}
bool CollisionShape2D::is_disabled() const {
return disabled;
}
void CollisionShape2D::set_one_way_collision(bool p_enable) {
one_way_collision = p_enable;
update();
if (parent) {
parent->shape_owner_set_one_way_collision(owner_id, p_enable);
}
}
bool CollisionShape2D::is_one_way_collision_enabled() const {
return one_way_collision;
}
void CollisionShape2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_shape", "shape"), &CollisionShape2D::set_shape);
ClassDB::bind_method(D_METHOD("get_shape"), &CollisionShape2D::get_shape);
ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &CollisionShape2D::set_disabled);
ClassDB::bind_method(D_METHOD("is_disabled"), &CollisionShape2D::is_disabled);
ClassDB::bind_method(D_METHOD("set_one_way_collision", "enabled"), &CollisionShape2D::set_one_way_collision);
ClassDB::bind_method(D_METHOD("is_one_way_collision_enabled"), &CollisionShape2D::is_one_way_collision_enabled);
ClassDB::bind_method(D_METHOD("_shape_changed"), &CollisionShape2D::_shape_changed);
ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape");
ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled");
ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "one_way_collision"), "set_one_way_collision", "is_one_way_collision_enabled");
}
CollisionShape2D::CollisionShape2D() {
rect = Rect2(-Point2(10, 10), Point2(20, 20));
set_notify_local_transform(true);
owner_id = 0;
parent = NULL;
disabled = false;
one_way_collision = false;
}
|
/*
* 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/waf-regional/model/DeleteRegexMatchSetRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::WAFRegional::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteRegexMatchSetRequest::DeleteRegexMatchSetRequest() :
m_regexMatchSetIdHasBeenSet(false),
m_changeTokenHasBeenSet(false)
{
}
Aws::String DeleteRegexMatchSetRequest::SerializePayload() const
{
JsonValue payload;
if(m_regexMatchSetIdHasBeenSet)
{
payload.WithString("RegexMatchSetId", m_regexMatchSetId);
}
if(m_changeTokenHasBeenSet)
{
payload.WithString("ChangeToken", m_changeToken);
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection DeleteRegexMatchSetRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSWAF_Regional_20161128.DeleteRegexMatchSet"));
return headers;
}
|
// ************************************************************************ //
// WARNING
// -------
// The types declared in this file were generated from data read from a
// Type Library. If this type library is explicitly or indirectly (via
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the
// Type Library, the contents of this file will be regenerated and all
// manual modifications will be lost.
// ************************************************************************ //
// C++ TLBWRTR : $Revision: 1.151.1.0.1.21 $
// File generated on 1/28/2002 8:27:45 AM from Type Library described below.
// ************************************************************************ //
// Type Lib: C:\Program Files\Common Files\Microsoft Shared\Office10\MSO.DLL (2)
// LIBID: {2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}
// LCID: 0
// Helpfile: C:\Program Files\Common Files\Microsoft Shared\Office10\vbaof10.chm
// HelpString: Microsoft Office 10.0 Object Library
// DepndLst:
// (1) v2.0 stdole, (C:\WINNT\System32\stdole2.tlb)
// Parent TypeLibrary:
// (0) v4.2 MSProject, (..\typelibraries\msprj8.olb)
// Errors:
// Hint: Symbol 'RGB' renamed to 'rgb'
// Hint: Symbol 'RGB' renamed to 'rgb'
// ************************************************************************ //
#include <vcl.h>
#pragma hdrstop
#include <oleserver.hpp>
#if defined(USING_ATL)
#include <atl\atlvcl.h>
#endif
#include "Office_2k_srvr.h"
#if !defined(__PRAGMA_PACKAGE_SMART_INIT)
#define __PRAGMA_PACKAGE_SMART_INIT
#pragma package(smart_init)
#endif
namespace Office_2k
{
}; // namespace Office_2k
|
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int merge(vector <int> &v){
if(v.size() == 1) return 0;
int inversoes = 0;
vector <int> metade1, metade2;
for(int i=0; i<v.size()/2; i++){
metade1.push_back(v[i]);
}
for(int i=v.size()/2; i<v.size(); i++){
metade2.push_back(v[i]);
}
inversoes += merge(metade1);
inversoes += merge(metade2);
int tam1 = metade1.size(), tam2 = metade2.size(), pos1 = 0, pos2 = 0;
for(int j=0; j<v.size(); j++){
if(pos1 == tam1){
v[j] = metade2[pos2];
pos2++;
}
else if(pos2 == tam2){
v[j] = metade1[pos1];
pos1++;
}
else if(metade1[pos1] < metade2[pos2]){
v[j] = metade1[pos1];
pos1++;
}
else if(metade1[pos1] > metade2[pos2]){
v[j] = metade2[pos2];
pos2++;
inversoes += tam1 - pos1;
}
}
return inversoes;
}
int main(){
int qtde, temp;
scanf("%d", &qtde);
vector <int> valores;
for(int i=0; i<qtde; i++){
scanf("%d", &temp);
valores.push_back(temp);
}
int inv = 0;
inv = merge(valores);
printf("%d\n", inv);
return 0;
}
|
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/backends/arm/math/scale.h"
#include "lite/backends/arm/math/funcs.h"
namespace paddle {
namespace lite {
namespace arm {
namespace math {
template <>
void scale<float>(
const float* din, float* dout, int num, float scale, float bias) {
int cnt = num >> 4;
int remain = num % 16;
float32x4_t vscale = vdupq_n_f32(scale);
float32x4_t vbias = vdupq_n_f32(bias);
if (cnt > 0) {
#ifdef __aarch64__
asm volatile(
"1: \n"
"ld1 {v4.4s}, [%[din]], #16 \n"
"and v8.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v5.4s}, [%[din]], #16 \n"
"and v9.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v6.4s}, [%[din]], #16 \n"
"and v10.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v7.4s}, [%[din]], #16 \n"
"and v11.16b, %[vbias].16b, %[vbias].16b \n"
"fmla v8.4s, v4.4s, %[vscale].4s \n"
"fmla v9.4s, v5.4s, %[vscale].4s \n"
"fmla v10.4s, v6.4s, %[vscale].4s \n"
"fmla v11.4s, v7.4s, %[vscale].4s \n"
"stp q8, q9, [%[dout]], #32 \n"
"subs %w[cnt], %w[cnt], #1 \n"
"stp q10, q11, [%[dout]], #32 \n"
"bne 1b \n"
"0: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale), [vbias] "w"(vbias)
: "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else
asm volatile(
"1: @ loop header \n"
"vld1.32 {d8-d11}, [%[din]]! @ load din 0 \n"
"vand.32 q8, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q9, %q[vbias], %q[vbias] @ out bias \n"
"vld1.32 {d12-d15}, [%[din]]! @ load din 0 \n"
"vand.32 q10, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q11, %q[vbias], %q[vbias] @ out bias \n"
"vmla.f32 q8, q4, %q[vscale] @ mla \n"
"vmla.f32 q9, q5, %q[vscale] @ mla \n"
"vmla.f32 q10, q6, %q[vscale] @ mla \n"
"vmla.f32 q11, q7, %q[vscale] @ mla \n"
"vst1.32 {d16-d19}, [%[dout]]! @ store result, add pointer\n"
"subs %[cnt], #1 @ loop count minus 1\n"
"vst1.32 {d20-d23}, [%[dout]]! @ store result, add pointer\n"
"bne 1b @ jump to main loop start "
"2: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale), [vbias] "w"(vbias)
: "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif
}
if (remain > 0) {
for (int i = 0; i < remain; i++) {
*dout = *din * scale + bias;
dout++;
din++;
}
}
}
template <>
void scale_relu<float>(
const float* din, float* dout, int num, float scale, float bias) {
int cnt = num >> 4;
int remain = num % 16;
float32x4_t vscale = vdupq_n_f32(scale);
float32x4_t vbias = vdupq_n_f32(bias);
float32x4_t vzero = vdupq_n_f32(0.f);
if (cnt > 0) {
#ifdef __aarch64__
asm volatile(
"1: \n"
"ld1 {v4.4s}, [%[din]], #16 \n"
"and v8.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v5.4s}, [%[din]], #16 \n"
"and v9.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v6.4s}, [%[din]], #16 \n"
"and v10.16b, %[vbias].16b, %[vbias].16b\n"
"ld1 {v7.4s}, [%[din]], #16 \n"
"and v11.16b, %[vbias].16b, %[vbias].16b\n"
"fmla v8.4s, v4.4s, %[vscale].4s \n"
"fmla v9.4s, v5.4s, %[vscale].4s \n"
"fmla v10.4s, v6.4s, %[vscale].4s \n"
"fmla v11.4s, v7.4s, %[vscale].4s \n"
"fmax v8.4s, v8.4s, %[vzero].4s \n"
"fmax v9.4s, v9.4s, %[vzero].4s \n"
"fmax v10.4s, v10.4s, %[vzero].4s \n"
"fmax v11.4s, v11.4s, %[vzero].4s \n"
"stp q8, q9, [%[dout]], #32 \n"
"subs %w[cnt], %w[cnt], #1 \n"
"stp q10, q11, [%[dout]], #32 \n"
"bne 1b \n"
"0: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale), [vbias] "w"(vbias), [vzero] "w"(vzero)
: "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else
asm volatile(
"1: @ loop header \n"
"vld1.32 {d8-d11}, [%[din]]! @ load din 0 \n"
"vand.32 q8, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q9, %q[vbias], %q[vbias] @ out bias \n"
"vld1.32 {d12-d15}, [%[din]]! @ load din 0 \n"
"vand.32 q10, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q11, %q[vbias], %q[vbias] @ out bias \n"
"vmla.f32 q8, q4, %q[vscale] @ mla \n"
"vmla.f32 q9, q5, %q[vscale] @ mla \n"
"vmla.f32 q10, q6, %q[vscale] @ mla \n"
"vmla.f32 q11, q7, %q[vscale] @ mla \n"
"vmax.f32 q8, q8, %q[vzero] @ relu \n"
"vmax.f32 q9, q9, %q[vzero] @ relu \n"
"vmax.f32 q10, q10, %q[vzero] @ relu \n"
"vmax.f32 q11, q11, %q[vzero] @ relu \n"
"vst1.32 {d16-d19}, [%[dout]]! @ store result, add pointer\n"
"subs %[cnt], #1 @ loop count minus 1\n"
"vst1.32 {d20-d23}, [%[dout]]! @ store result, add pointer\n"
"bne 1b @ jump to main loop start "
"2: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale), [vbias] "w"(vbias), [vzero] "w"(vzero)
: "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif
}
if (remain > 0) {
for (int i = 0; i < remain; i++) {
*dout = *din * scale + bias;
*dout = *dout > 0.f ? *dout : 0.f;
dout++;
din++;
}
}
}
template <>
void scale_relu6<float>(const float* din,
float* dout,
int num,
float scale,
float bias,
float alpha) {
int cnt = num >> 4;
int remain = num % 16;
float32x4_t vscale = vdupq_n_f32(scale);
float32x4_t vbias = vdupq_n_f32(bias);
float32x4_t vzero = vdupq_n_f32(0.f);
float32x4_t valpha = vdupq_n_f32(alpha);
if (cnt > 0) {
#ifdef __aarch64__
asm volatile(
"1: \n"
"ld1 {v4.4s}, [%[din]], #16 \n"
"and v8.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v5.4s}, [%[din]], #16 \n"
"and v9.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v6.4s}, [%[din]], #16 \n"
"and v10.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v7.4s}, [%[din]], #16 \n"
"and v11.16b, %[vbias].16b, %[vbias].16b \n"
"fmla v8.4s, v4.4s, %[vscale].4s \n"
"fmla v9.4s, v5.4s, %[vscale].4s \n"
"fmla v10.4s, v6.4s, %[vscale].4s \n"
"fmla v11.4s, v7.4s, %[vscale].4s \n"
"fmax v8.4s, v8.4s, %[vzero].4s \n"
"fmax v9.4s, v9.4s, %[vzero].4s \n"
"fmax v10.4s, v10.4s, %[vzero].4s \n"
"fmax v11.4s, v11.4s, %[vzero].4s \n"
"fmin v8.4s, v8.4s, %[valpha].4s \n"
"fmin v9.4s, v9.4s, %[valpha].4s \n"
"fmin v10.4s, v10.4s, %[valpha].4s \n"
"fmin v11.4s, v11.4s, %[valpha].4s \n"
"stp q8, q9, [%[dout]], #32 \n"
"subs %w[cnt], %w[cnt], #1 \n"
"stp q10, q11, [%[dout]], #32 \n"
"bne 1b \n"
"0: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale),
[vbias] "w"(vbias),
[vzero] "w"(vzero),
[valpha] "w"(valpha)
: "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else
asm volatile(
"1: @ loop header \n"
"vld1.32 {d8-d11}, [%[din]]! @ load din 0 \n"
"vand.32 q8, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q9, %q[vbias], %q[vbias] @ out bias \n"
"vld1.32 {d12-d15}, [%[din]]! @ load din 0 \n"
"vand.32 q10, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q11, %q[vbias], %q[vbias] @ out bias \n"
"vmla.f32 q8, q4, %q[vscale] @ mla \n"
"vmla.f32 q9, q5, %q[vscale] @ mla \n"
"vmla.f32 q10, q6, %q[vscale] @ mla \n"
"vmla.f32 q11, q7, %q[vscale] @ mla \n"
"vmax.f32 q8, q8, %q[vzero] @ relu \n"
"vmax.f32 q9, q9, %q[vzero] @ relu \n"
"vmax.f32 q10, q10, %q[vzero] @ relu \n"
"vmax.f32 q11, q11, %q[vzero] @ relu \n"
"vmin.f32 q8, q8, %q[valpha] @ relu \n"
"vmin.f32 q9, q9, %q[valpha] @ relu \n"
"vmin.f32 q10, q10, %q[valpha] @ relu \n"
"vmin.f32 q11, q11, %q[valpha] @ relu \n"
"vst1.32 {d16-d19}, [%[dout]]! @ store result, add pointer\n"
"subs %[cnt], #1 @ loop count minus 1\n"
"vst1.32 {d20-d23}, [%[dout]]! @ store result, add pointer\n"
"bne 1b @ jump to main loop start "
"2: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale),
[vbias] "w"(vbias),
[vzero] "w"(vzero),
[valpha] "w"(valpha)
: "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif
}
if (remain > 0) {
for (int i = 0; i < remain; i++) {
*dout = *din * scale + bias;
*dout = *dout > 0.f ? (*dout < alpha ? *dout : alpha) : 0.f;
dout++;
din++;
}
}
}
template <>
void scale_leaky_relu<float>(const float* din,
float* dout,
int num,
float scale,
float bias,
float alpha) {
int cnt = num >> 4;
int remain = num % 16;
float32x4_t vscale = vdupq_n_f32(scale);
float32x4_t vbias = vdupq_n_f32(bias);
float32x4_t vzero = vdupq_n_f32(0.f);
float32x4_t valpha = vdupq_n_f32(alpha);
if (cnt > 0) {
#ifdef __aarch64__
asm volatile(
"1: \n"
"ld1 {v4.4s}, [%[din]], #16 \n"
"and v8.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v5.4s}, [%[din]], #16 \n"
"and v9.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v6.4s}, [%[din]], #16 \n"
"and v10.16b, %[vbias].16b, %[vbias].16b \n"
"ld1 {v7.4s}, [%[din]], #16 \n"
"and v11.16b, %[vbias].16b, %[vbias].16b \n"
"fmla v8.4s, v4.4s, %[vscale].4s \n"
"fmla v9.4s, v5.4s, %[vscale].4s \n"
"fmla v10.4s, v6.4s, %[vscale].4s \n"
"fmla v11.4s, v7.4s, %[vscale].4s \n"
"fcmge v12.4s, v8.4s, %[vzero].4s \n"
"fmul v16.4s, v8.4s, %[valpha].4s \n"
"fcmge v13.4s, v9.4s, %[vzero].4s \n"
"fmul v17.4s, v9.4s, %[valpha].4s \n"
"fcmge v14.4s, v10.4s, %[vzero].4s \n"
"fmul v18.4s, v10.4s, %[valpha].4s \n"
"fcmge v15.4s, v11.4s, %[vzero].4s \n"
"fmul v19.4s, v11.4s, %[valpha].4s \n"
"bif v8.16b, v16.16b, v12.16b \n" /* choose*/
"bif v9.16b, v17.16b, v13.16b \n" /* choose*/
"bif v10.16b, v18.16b, v14.16b \n" /* choose*/
"bif v11.16b, v19.16b, v15.16b \n" /* choose*/
"stp q8, q9, [%[dout]], #32 \n"
"subs %w[cnt], %w[cnt], #1 \n"
"stp q10, q11, [%[dout]], #32 \n"
"bne 1b \n"
"0: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale),
[vbias] "w"(vbias),
[vzero] "w"(vzero),
[valpha] "w"(valpha)
: "cc",
"memory",
"v4",
"v5",
"v6",
"v7",
"v8",
"v9",
"v10",
"v11",
"v12",
"v13",
"v14",
"v15");
#else
asm volatile(
"1: @ loop header \n"
"vld1.32 {d8-d11}, [%[din]]! @ load din 0 \n"
"vand.32 q8, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q9, %q[vbias], %q[vbias] @ out bias \n"
"vld1.32 {d12-d15}, [%[din]]! @ load din 0 \n"
"vand.32 q10, %q[vbias], %q[vbias] @ out bias \n"
"vand.32 q11, %q[vbias], %q[vbias] @ out bias \n"
"vmla.f32 q8, q4, %q[vscale] @ mla \n"
"vmla.f32 q9, q5, %q[vscale] @ mla \n"
"vmla.f32 q10, q6, %q[vscale] @ mla \n"
"vmla.f32 q11, q7, %q[vscale] @ mla \n"
"vcge.f32 q12, q8, %q[vzero] @ relu \n"
"vmul.f32 q14, q8, %q[valpha] @ mul \n"
"vcge.f32 q13, q9, %q[vzero] @ relu \n"
"vmul.f32 q15, q9, %q[valpha] @ mul \n"
"vbif q8, q14, q12 @ choose \n"
"vbif q9, q15, q13 @ choose \n"
"vcge.f32 q12, q10, %q[vzero] @ relu \n"
"vmul.f32 q14, q10, %q[valpha] @ mul \n"
"vcge.f32 q13, q11, %q[vzero] @ relu \n"
"vmul.f32 q15, q11, %q[valpha] @ mul \n"
"vst1.32 {d16-d19}, [%[dout]]! @ store result, add pointer\n"
"vbif q10, q14, q12 @ choose \n"
"vbif q11, q15, q13 @ choose \n"
"subs %[cnt], #1 @ loop count minus 1\n"
"vst1.32 {d20-d23}, [%[dout]]! @ store result, add pointer\n"
"bne 1b @ jump to main loop start "
"2: \n"
: [dout] "+r"(dout), [din] "+r"(din), [cnt] "+r"(cnt)
: [vscale] "w"(vscale),
[vbias] "w"(vbias),
[vzero] "w"(vzero),
[valpha] "w"(valpha)
: "cc",
"memory",
"q4",
"q5",
"q6",
"q7",
"q8",
"q9",
"q10",
"q11",
"q12",
"q13",
"q14",
"q15");
#endif
}
if (remain > 0) {
for (int i = 0; i < remain; i++) {
*dout = *din * scale + bias;
*dout = *dout > 0.f ? *dout : (*dout * alpha);
dout++;
din++;
}
}
}
template <>
void scale<int>(const int* din, int* dout, int num, int scale, int bias) {
int cnt = num >> 4;
int remain = num % 16;
int32x4_t vscale = vdupq_n_s32(scale);
int32x4_t vbias = vdupq_n_s32(bias);
#pragma omp parallel for
for (int i = 0; i < cnt; i++) {
const int* din_ptr = din + (i << 4);
int* dout_ptr = dout + (i << 4);
int32x4_t din0 = vld1q_s32(din_ptr);
int32x4_t din1 = vld1q_s32(din_ptr + 4);
int32x4_t din2 = vld1q_s32(din_ptr + 8);
int32x4_t din3 = vld1q_s32(din_ptr + 12);
int32x4_t vsum1 = vmlaq_s32(vbias, din0, vscale);
int32x4_t vsum2 = vmlaq_s32(vbias, din1, vscale);
int32x4_t vsum3 = vmlaq_s32(vbias, din2, vscale);
int32x4_t vsum4 = vmlaq_s32(vbias, din3, vscale);
vst1q_s32(dout_ptr, vsum1);
vst1q_s32(dout_ptr + 4, vsum2);
vst1q_s32(dout_ptr + 8, vsum3);
vst1q_s32(dout_ptr + 12, vsum4);
}
if (remain > 0) {
const int* din_ptr = din + (cnt << 4);
int* dout_ptr = dout + (cnt << 4);
for (int i = 0; i < remain; i++) {
*dout_ptr = *din_ptr * scale + bias;
dout_ptr++;
din_ptr++;
}
}
}
template <>
void scale_relu<int>(const int* din, int* dout, int num, int scale, int bias) {
int cnt = num >> 4;
int remain = num % 16;
int32x4_t vscale = vdupq_n_s32(scale);
int32x4_t vbias = vdupq_n_s32(bias);
int32x4_t vzero = vdupq_n_s32(0);
#pragma omp parallel for
for (int i = 0; i < cnt; i++) {
const int* din_ptr = din + (i << 4);
int* dout_ptr = dout + (i << 4);
int32x4_t din0 = vld1q_s32(din_ptr);
int32x4_t din1 = vld1q_s32(din_ptr + 4);
int32x4_t din2 = vld1q_s32(din_ptr + 8);
int32x4_t din3 = vld1q_s32(din_ptr + 12);
int32x4_t vsum1 = vmlaq_s32(vbias, din0, vscale);
int32x4_t vsum2 = vmlaq_s32(vbias, din1, vscale);
int32x4_t vsum3 = vmlaq_s32(vbias, din2, vscale);
int32x4_t vsum4 = vmlaq_s32(vbias, din3, vscale);
vsum1 = vmaxq_s32(vsum1, vzero);
vsum2 = vmaxq_s32(vsum2, vzero);
vsum3 = vmaxq_s32(vsum3, vzero);
vsum4 = vmaxq_s32(vsum4, vzero);
vst1q_s32(dout_ptr, vsum1);
vst1q_s32(dout_ptr + 4, vsum2);
vst1q_s32(dout_ptr + 8, vsum3);
vst1q_s32(dout_ptr + 12, vsum4);
}
if (remain > 0) {
const int* din_ptr = din + (cnt << 4);
int* dout_ptr = dout + (cnt << 4);
for (int i = 0; i < remain; i++) {
*dout_ptr = *din_ptr * scale + bias;
*dout_ptr = *dout_ptr > 0 ? *dout_ptr : 0;
dout_ptr++;
din_ptr++;
}
}
}
template <>
void scale_relu6<int>(
const int* din, int* dout, int num, int scale, int bias, int alpha) {
int cnt = num >> 4;
int remain = num % 16;
int32x4_t vscale = vdupq_n_s32(scale);
int32x4_t vbias = vdupq_n_s32(bias);
int32x4_t vzero = vdupq_n_s32(0);
int32x4_t valpha = vdupq_n_s32(alpha);
#pragma omp parallel for
for (int i = 0; i < cnt; i++) {
const int* din_ptr = din + (i << 4);
int* dout_ptr = dout + (i << 4);
int32x4_t din0 = vld1q_s32(din_ptr);
int32x4_t din1 = vld1q_s32(din_ptr + 4);
int32x4_t din2 = vld1q_s32(din_ptr + 8);
int32x4_t din3 = vld1q_s32(din_ptr + 12);
int32x4_t vsum1 = vmlaq_s32(vbias, din0, vscale);
int32x4_t vsum2 = vmlaq_s32(vbias, din1, vscale);
int32x4_t vsum3 = vmlaq_s32(vbias, din2, vscale);
int32x4_t vsum4 = vmlaq_s32(vbias, din3, vscale);
vsum1 = vmaxq_s32(vsum1, vzero);
vsum2 = vmaxq_s32(vsum2, vzero);
vsum3 = vmaxq_s32(vsum3, vzero);
vsum4 = vmaxq_s32(vsum4, vzero);
vsum1 = vminq_s32(vsum1, valpha);
vsum2 = vminq_s32(vsum2, valpha);
vsum3 = vminq_s32(vsum3, valpha);
vsum4 = vminq_s32(vsum4, valpha);
vst1q_s32(dout_ptr, vsum1);
vst1q_s32(dout_ptr + 4, vsum2);
vst1q_s32(dout_ptr + 8, vsum3);
vst1q_s32(dout_ptr + 12, vsum4);
}
if (remain > 0) {
const int* din_ptr = din + (cnt << 4);
int* dout_ptr = dout + (cnt << 4);
for (int i = 0; i < remain; i++) {
*dout_ptr = *din_ptr * scale + bias;
*dout_ptr = *dout_ptr > 0 ? (*dout_ptr > alpha ? alpha : *dout_ptr) : 0;
dout_ptr++;
din_ptr++;
}
}
}
template <>
void scale_leaky_relu<int>(
const int* din, int* dout, int num, int scale, int bias, int alpha) {
int cnt = num >> 4;
int remain = num % 16;
int32x4_t vscale = vdupq_n_s32(scale);
int32x4_t vbias = vdupq_n_s32(bias);
int32x4_t vzero = vdupq_n_s32(0);
int32x4_t valpha = vdupq_n_s32(alpha);
#pragma omp parallel for
for (int i = 0; i < cnt; i++) {
const int* din_ptr = din + (i << 4);
int* dout_ptr = dout + (i << 4);
int32x4_t din0 = vld1q_s32(din_ptr);
int32x4_t din1 = vld1q_s32(din_ptr + 4);
int32x4_t din2 = vld1q_s32(din_ptr + 8);
int32x4_t din3 = vld1q_s32(din_ptr + 12);
int32x4_t vsum1 = vmlaq_s32(vbias, din0, vscale);
int32x4_t vsum2 = vmlaq_s32(vbias, din1, vscale);
int32x4_t vsum3 = vmlaq_s32(vbias, din2, vscale);
int32x4_t vsum4 = vmlaq_s32(vbias, din3, vscale);
uint32x4_t v1 = vcgeq_s32(vsum1, vzero);
uint32x4_t v2 = vcgeq_s32(vsum2, vzero);
uint32x4_t v3 = vcgeq_s32(vsum3, vzero);
uint32x4_t v4 = vcgeq_s32(vsum4, vzero);
int32x4_t v11 = vmulq_s32(vsum1, valpha);
int32x4_t v21 = vmulq_s32(vsum1, valpha);
int32x4_t v31 = vmulq_s32(vsum1, valpha);
int32x4_t v41 = vmulq_s32(vsum1, valpha);
vsum1 = vbslq_s32(v1, vsum1, v11);
vsum2 = vbslq_s32(v2, vsum2, v21);
vsum3 = vbslq_s32(v3, vsum3, v31);
vsum4 = vbslq_s32(v4, vsum4, v41);
vst1q_s32(dout_ptr, vsum1);
vst1q_s32(dout_ptr + 4, vsum2);
vst1q_s32(dout_ptr + 8, vsum3);
vst1q_s32(dout_ptr + 12, vsum4);
}
if (remain > 0) {
const int* din_ptr = din + (cnt << 4);
int* dout_ptr = dout + (cnt << 4);
for (int i = 0; i < remain; i++) {
*dout_ptr = *din_ptr * scale + bias;
*dout_ptr = *dout_ptr > 0 ? *dout_ptr : (*dout_ptr) * alpha;
dout_ptr++;
din_ptr++;
}
}
}
template <>
void scale<int64_t>(
const int64_t* din, int64_t* dout, int num, int64_t scale, int64_t bias) {
const int64_t* din_ptr = din;
int64_t* dout_ptr = dout;
for (int i = 0; i < num; i++) {
*dout_ptr = *din_ptr * scale + bias;
dout_ptr++;
din_ptr++;
}
}
template <>
void scale_relu<int64_t>(
const int64_t* din, int64_t* dout, int num, int64_t scale, int64_t bias) {
const int64_t* din_ptr = din;
int64_t* dout_ptr = dout;
for (int i = 0; i < num; i++) {
*dout_ptr = *din_ptr * scale + bias;
*dout_ptr = *dout_ptr > 0 ? *dout_ptr : 0;
dout_ptr++;
din_ptr++;
}
}
template <>
void scale_relu6<int64_t>(const int64_t* din,
int64_t* dout,
int num,
int64_t scale,
int64_t bias,
int64_t alpha) {
const int64_t* din_ptr = din;
int64_t* dout_ptr = dout;
for (int i = 0; i < num; i++) {
*dout_ptr = *din_ptr * scale + bias;
*dout_ptr = *dout_ptr > 0 ? (*dout_ptr > alpha ? alpha : *dout_ptr) : 0;
dout_ptr++;
din_ptr++;
}
}
template <>
void scale_leaky_relu<int64_t>(const int64_t* din,
int64_t* dout,
int num,
int64_t scale,
int64_t bias,
int64_t alpha) {
const int64_t* din_ptr = din;
int64_t* dout_ptr = dout;
for (int i = 0; i < num; i++) {
*dout_ptr = *din_ptr * scale + bias;
*dout_ptr = *dout_ptr > 0 ? *dout_ptr : (*dout_ptr) * alpha;
dout_ptr++;
din_ptr++;
}
}
template <>
void scale<float>(const float* din,
float* dout,
int outer_dim,
int scale_dim,
int inner_dim,
const float* scale_data,
const float* bias_data) {
int cnt = inner_dim >> 4;
int remain = inner_dim % 16;
int size = inner_dim * scale_dim;
for (int n = 0; n < outer_dim; n++) {
const float* din_ptr_n = din + n * size;
float* dout_ptr_n = dout + n * size;
#pragma omp parallel for
for (int i = 0; i < scale_dim; i++) {
const float* din_ptr = din_ptr_n + i * inner_dim;
float* dout_ptr = dout_ptr_n + i * inner_dim;
float scale = scale_data[i];
float32x4_t vscale = vdupq_n_f32(scale);
float bias = bias_data[i];
float32x4_t vbias = vdupq_n_f32(bias);
for (int j = 0; j < cnt; j++) {
float32x4_t din0 = vld1q_f32(din_ptr);
float32x4_t din1 = vld1q_f32(din_ptr + 4);
float32x4_t din2 = vld1q_f32(din_ptr + 8);
float32x4_t din3 = vld1q_f32(din_ptr + 12);
float32x4_t vsum1 = vmlaq_f32(vbias, din0, vscale);
float32x4_t vsum2 = vmlaq_f32(vbias, din1, vscale);
float32x4_t vsum3 = vmlaq_f32(vbias, din2, vscale);
float32x4_t vsum4 = vmlaq_f32(vbias, din3, vscale);
din_ptr += 16;
vst1q_f32(dout_ptr, vsum1);
vst1q_f32(dout_ptr + 4, vsum2);
vst1q_f32(dout_ptr + 8, vsum3);
vst1q_f32(dout_ptr + 12, vsum4);
dout_ptr += 16;
}
for (int j = 0; j < remain; j++) {
*dout_ptr = *din_ptr * scale + bias;
dout_ptr++;
din_ptr++;
}
}
}
}
template <>
void scale<float>(const float* din,
float* dout,
int outer_dim,
int scale_dim,
const float* scale_data,
const float* bias_data) {
int cnt = scale_dim >> 4;
int remain = scale_dim % 16;
for (int n = 0; n < outer_dim; n++) {
const float* din_ptr_n = din + n * scale_dim;
float* dout_ptr_n = dout + n * scale_dim;
#pragma omp parallel for
for (int i = 0; i < cnt; i++) {
int idx = i << 4;
const float* din_ptr = din_ptr_n + idx;
const float* scale_ptr = scale_data + idx;
const float* bias_ptr = bias_data + idx;
float* dout_ptr = dout_ptr_n + idx;
float32x4_t din0 = vld1q_f32(din_ptr);
float32x4_t vscale0 = vld1q_f32(scale_ptr);
float32x4_t vbias0 = vld1q_f32(bias_ptr);
float32x4_t din1 = vld1q_f32(din_ptr + 4);
float32x4_t vscale1 = vld1q_f32(scale_ptr + 4);
float32x4_t vbias1 = vld1q_f32(bias_ptr + 4);
float32x4_t din2 = vld1q_f32(din_ptr + 8);
float32x4_t vscale2 = vld1q_f32(scale_ptr + 8);
float32x4_t vbias2 = vld1q_f32(bias_ptr + 8);
float32x4_t vsum1 = vmlaq_f32(vbias0, din0, vscale0);
float32x4_t vsum2 = vmlaq_f32(vbias1, din1, vscale1);
float32x4_t din3 = vld1q_f32(din_ptr + 12);
float32x4_t vscale3 = vld1q_f32(scale_ptr + 12);
float32x4_t vbias3 = vld1q_f32(bias_ptr + 12);
vst1q_f32(dout_ptr, vsum1);
vst1q_f32(dout_ptr + 4, vsum2);
float32x4_t vsum3 = vmlaq_f32(vbias2, din2, vscale2);
float32x4_t vsum4 = vmlaq_f32(vbias3, din3, vscale3);
vst1q_f32(dout_ptr + 8, vsum3);
vst1q_f32(dout_ptr + 12, vsum4);
}
int idx = cnt << 4;
const float* din_ptr = din_ptr_n + idx;
float* dout_ptr = dout_ptr_n + idx;
const float* scale_ptr = scale_data + idx;
const float* bias_ptr = bias_data + idx;
for (int j = 0; j < remain; j++) {
*dout_ptr = *din_ptr * (*scale_ptr) + (*bias_ptr);
dout_ptr++;
din_ptr++;
scale_ptr++;
bias_ptr++;
}
}
}
} // namespace math
} // namespace arm
} // namespace lite
} // namespace paddle
|
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2018 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "chain.h"
#include "rpc/server.h"
#include "init.h"
#include "validation.h"
#include "script/script.h"
#include "script/standard.h"
#include "sync.h"
#include "util.h"
#include "utiltime.h"
#include "wallet.h"
#include "merkleblock.h"
#include "core_io.h"
#include <fstream>
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <univalue.h>
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
void EnsureWalletIsUnlocked();
bool EnsureWalletIsAvailable(bool avoidException);
std::string static EncodeDumpTime(int64_t nTime) {
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
int64_t static DecodeDumpTime(const std::string &str) {
static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
static const std::locale loc(std::locale::classic(),
new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
std::istringstream iss(str);
iss.imbue(loc);
boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
iss >> ptime;
if (ptime.is_not_a_date_time())
return 0;
return (ptime - epoch).total_seconds();
}
std::string static EncodeDumpString(const std::string &str) {
std::stringstream ret;
BOOST_FOREACH(unsigned char c, str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos+2 < str.length()) {
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
pos += 2;
}
ret << c;
}
return ret.str();
}
UniValue importprivkey(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
"importprivkey \"neonprivkey\" ( \"label\" ) ( rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet.\n"
"\nArguments:\n"
"1. \"neonprivkey\" (string, required) The private key (see dumpprivkey)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nDump a private key\n"
+ HelpExampleCli("dumpprivkey", "\"myaddress\"") +
"\nImport the private key with rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\"") +
"\nImport using a label and without rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
"\nImport using default blank label and without rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\" \"\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::string strSecret = request.params[0].get_str();
std::string strLabel = "";
if (request.params.size() > 1)
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (request.params.size() > 2)
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
CKey key = vchSecret.GetKey();
if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
{
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, strLabel, "receive");
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress))
return NullUniValue;
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(key, pubkey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
// whenever a key is imported, we need to scan the whole chain
pwalletMain->UpdateTimeFirstKey(1);
if (fRescan) {
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
}
return NullUniValue;
}
void ImportAddress(const CBitcoinAddress& address, const std::string& strLabel);
void ImportScript(const CScript& script, const std::string& strLabel, bool isRedeemScript)
{
if (!isRedeemScript && ::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE)
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(script) && !pwalletMain->AddWatchOnly(script, 0 /* nCreateTime */))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
if (isRedeemScript) {
if (!pwalletMain->HaveCScript(script) && !pwalletMain->AddCScript(script))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
ImportAddress(CBitcoinAddress(CScriptID(script)), strLabel);
} else {
CTxDestination destination;
if (ExtractDestination(script, destination)) {
pwalletMain->SetAddressBook(destination, strLabel, "receive");
}
}
}
void ImportAddress(const CBitcoinAddress& address, const std::string& strLabel)
{
CScript script = GetScriptForDestination(address.Get());
ImportScript(script, strLabel, false);
// add to address book or update label
if (address.IsValid())
pwalletMain->SetAddressBook(address.Get(), strLabel, "receive");
}
UniValue importaddress(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"importaddress \"address\" ( \"label\" rescan p2sh )\n"
"\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n"
"1. \"script\" (string, required) The hex-encoded script (or address)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"If you have the full public key, you should call importpubkey instead of this.\n"
"\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n"
"as change, and not show up in many RPCs.\n"
"\nExamples:\n"
"\nImport a script with rescan\n"
+ HelpExampleCli("importaddress", "\"myscript\"") +
"\nImport using a label without rescan\n"
+ HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false")
);
std::string strLabel = "";
if (request.params.size() > 1)
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (request.params.size() > 2)
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
// Whether to import a p2sh version, too
bool fP2SH = false;
if (request.params.size() > 3)
fP2SH = request.params[3].get_bool();
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(request.params[0].get_str());
if (address.IsValid()) {
if (fP2SH)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead");
ImportAddress(address, strLabel);
} else if (IsHex(request.params[0].get_str())) {
std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
ImportScript(CScript(data.begin(), data.end()), strLabel, fP2SH);
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Nucleon address or script");
}
if (fRescan)
{
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importprunedfunds(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
"importprunedfunds\n"
"\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n"
"\nArguments:\n"
"1. \"rawtransaction\" (string, required) A raw transaction in hex funding an already-existing address in wallet\n"
"2. \"txoutproof\" (string, required) The hex output from gettxoutproof that contains the transaction\n"
);
CMutableTransaction tx;
if (!DecodeHexTx(tx, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
CWalletTx wtx(pwalletMain, MakeTransactionRef(std::move(tx)));
CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
//Search partial merkle tree in proof for our transaction and index in valid block
std::vector<uint256> vMatch;
std::vector<unsigned int> vIndex;
unsigned int txnIndex = 0;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
std::vector<uint256>::const_iterator it;
if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
}
txnIndex = vIndex[it - vMatch.begin()];
}
else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
}
wtx.nIndex = txnIndex;
wtx.hashBlock = merkleBlock.header.GetHash();
LOCK2(cs_main, pwalletMain->cs_wallet);
if (pwalletMain->IsMine(wtx)) {
pwalletMain->AddToWallet(wtx, false);
return NullUniValue;
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
}
UniValue removeprunedfunds(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"removeprunedfunds \"txid\"\n"
"\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will effect wallet balances.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The hex-encoded id of the transaction you are deleting\n"
"\nExamples:\n"
+ HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("removprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(request.params[0].get_str());
std::vector<uint256> vHash;
vHash.push_back(hash);
std::vector<uint256> vHashOut;
if(pwalletMain->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not properly delete the transaction.");
}
if(vHashOut.empty()) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction does not exist in wallet.");
}
return NullUniValue;
}
UniValue importpubkey(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"importpubkey \"pubkey\" ( \"label\" rescan )\n"
"\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n"
"1. \"pubkey\" (string, required) The hex-encoded public key\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nImport a public key with rescan\n"
+ HelpExampleCli("importpubkey", "\"mypubkey\"") +
"\nImport using a label without rescan\n"
+ HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false")
);
std::string strLabel = "";
if (request.params.size() > 1)
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (request.params.size() > 2)
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
if (!IsHex(request.params[0].get_str()))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
CPubKey pubKey(data.begin(), data.end());
if (!pubKey.IsFullyValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
LOCK2(cs_main, pwalletMain->cs_wallet);
ImportAddress(CBitcoinAddress(pubKey.GetID()), strLabel);
ImportScript(GetScriptForRawPubKey(pubKey), strLabel, false);
if (fRescan)
{
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importwallet(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"importwallet \"filename\"\n"
"\nImports keys from a wallet dump file (see dumpwallet).\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The wallet file\n"
"\nExamples:\n"
"\nDump the wallet\n"
+ HelpExampleCli("dumpwallet", "\"test\"") +
"\nImport the wallet\n"
+ HelpExampleCli("importwallet", "\"test\"") +
"\nImport using the json rpc call\n"
+ HelpExampleRpc("importwallet", "\"test\"")
);
if (fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::ifstream file;
file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate);
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
bool fGood = true;
int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
file.seekg(0, file.beg);
pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
while (file.good()) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(vstr[0]))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwalletMain->SetAddressBook(keyid, strLabel, "receive");
nTimeBegin = std::min(nTimeBegin, nTime);
}
file.close();
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
pwalletMain->UpdateTimeFirstKey(nTimeBegin);
CBlockIndex *pindex = chainActive.FindEarliestAtLeast(nTimeBegin - 7200);
LogPrintf("Rescanning last %i blocks\n", pindex ? chainActive.Height() - pindex->nHeight + 1 : 0);
pwalletMain->ScanForWalletTransactions(pindex);
pwalletMain->MarkDirty();
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return NullUniValue;
}
UniValue importelectrumwallet(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"importelectrumwallet \"filename\" index\n"
"\nImports keys from an Electrum wallet export file (.csv or .json)\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The Electrum wallet export file, should be in csv or json format\n"
"2. index (numeric, optional, default=0) Rescan the wallet for transactions starting from this block index\n"
"\nExamples:\n"
"\nImport the wallet\n"
+ HelpExampleCli("importelectrumwallet", "\"test.csv\"")
+ HelpExampleCli("importelectrumwallet", "\"test.json\"") +
"\nImport using the json rpc call\n"
+ HelpExampleRpc("importelectrumwallet", "\"test.csv\"")
+ HelpExampleRpc("importelectrumwallet", "\"test.json\"")
);
if (fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::ifstream file;
std::string strFileName = request.params[0].get_str();
size_t nDotPos = strFileName.find_last_of(".");
if(nDotPos == std::string::npos)
throw JSONRPCError(RPC_INVALID_PARAMETER, "File has no extension, should be .json or .csv");
std::string strFileExt = strFileName.substr(nDotPos+1);
if(strFileExt != "json" && strFileExt != "csv")
throw JSONRPCError(RPC_INVALID_PARAMETER, "File has wrong extension, should be .json or .csv");
file.open(strFileName.c_str(), std::ios::in | std::ios::ate);
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open Electrum wallet export file");
bool fGood = true;
int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
file.seekg(0, file.beg);
pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
if(strFileExt == "csv") {
while (file.good()) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
std::string line;
std::getline(file, line);
if (line.empty() || line == "address,private_key")
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(","));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(vstr[1]))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
continue;
}
LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
}
} else {
// json
char* buffer = new char [nFilesize];
file.read(buffer, nFilesize);
UniValue data(UniValue::VOBJ);
if(!data.read(buffer))
throw JSONRPCError(RPC_TYPE_ERROR, "Cannot parse Electrum wallet export file");
delete[] buffer;
std::vector<std::string> vKeys = data.getKeys();
for (size_t i = 0; i < data.size(); i++) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, int(i*100/data.size()))));
if(!data[vKeys[i]].isStr())
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(data[vKeys[i]].get_str()))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
continue;
}
LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
}
}
file.close();
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
// Whether to perform rescan after import
int nStartHeight = 0;
if (request.params.size() > 1)
nStartHeight = request.params[1].get_int();
if (chainActive.Height() < nStartHeight)
nStartHeight = chainActive.Height();
// Assume that electrum wallet was created at that block
int nTimeBegin = chainActive[nStartHeight]->GetBlockTime();
pwalletMain->UpdateTimeFirstKey(nTimeBegin);
LogPrintf("Rescanning %i blocks\n", chainActive.Height() - nStartHeight + 1);
pwalletMain->ScanForWalletTransactions(chainActive[nStartHeight], true);
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return NullUniValue;
}
UniValue dumpprivkey(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpprivkey \"address\"\n"
"\nReveals the private key corresponding to 'address'.\n"
"Then the importprivkey can be used with this output\n"
"\nArguments:\n"
"1. \"address\" (string, required) The neon address for the private key\n"
"\nResult:\n"
"\"key\" (string) The private key\n"
"\nExamples:\n"
+ HelpExampleCli("dumpprivkey", "\"myaddress\"")
+ HelpExampleCli("importprivkey", "\"mykey\"")
+ HelpExampleRpc("dumpprivkey", "\"myaddress\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::string strAddress = request.params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Nucleon address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CKey vchSecret;
if (!pwalletMain->GetKey(keyID, vchSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret).ToString();
}
UniValue dumphdinfo(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"dumphdinfo\n"
"Returns an object containing sensitive private info about this HD wallet.\n"
"\nResult:\n"
"{\n"
" \"hdseed\": \"seed\", (string) The HD seed (bip32, in hex)\n"
" \"mnemonic\": \"words\", (string) The mnemonic for this HD wallet (bip39, english words) \n"
" \"mnemonicpassphrase\": \"passphrase\", (string) The mnemonic passphrase for this HD wallet (bip39)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("dumphdinfo", "")
+ HelpExampleRpc("dumphdinfo", "")
);
LOCK(pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
CHDChain hdChainCurrent;
if (!pwalletMain->GetHDChain(hdChainCurrent))
throw JSONRPCError(RPC_WALLET_ERROR, "This wallet is not a HD wallet.");
if (!pwalletMain->GetDecryptedHDChain(hdChainCurrent))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot decrypt HD seed");
SecureString ssMnemonic;
SecureString ssMnemonicPassphrase;
hdChainCurrent.GetMnemonic(ssMnemonic, ssMnemonicPassphrase);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("hdseed", HexStr(hdChainCurrent.GetSeed())));
obj.push_back(Pair("mnemonic", ssMnemonic.c_str()));
obj.push_back(Pair("mnemonicpassphrase", ssMnemonicPassphrase.c_str()));
return obj;
}
UniValue dumpwallet(const JSONRPCRequest& request)
{
if (!EnsureWalletIsAvailable(request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpwallet \"filename\"\n"
"\nDumps all wallet keys in a human-readable format.\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename\n"
"\nExamples:\n"
+ HelpExampleCli("dumpwallet", "\"test\"")
+ HelpExampleRpc("dumpwallet", "\"test\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::ofstream file;
file.open(request.params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CTxDestination, int64_t> mapKeyBirth;
std::set<CKeyID> setKeyPool;
pwalletMain->GetKeyBirthTimes(mapKeyBirth);
pwalletMain->GetAllReserveKeys(setKeyPool);
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (const auto& entry : mapKeyBirth) {
if (const CKeyID* keyID = boost::get<CKeyID>(&entry.first)) { // set and test
vKeyBirth.push_back(std::make_pair(entry.second, *keyID));
}
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by Nucleon Core %s\n", CLIENT_BUILD);
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
file << "\n";
// add the base58check encoded extended master if the wallet uses HD
CHDChain hdChainCurrent;
if (pwalletMain->GetHDChain(hdChainCurrent))
{
if (!pwalletMain->GetDecryptedHDChain(hdChainCurrent))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot decrypt HD chain");
SecureString ssMnemonic;
SecureString ssMnemonicPassphrase;
hdChainCurrent.GetMnemonic(ssMnemonic, ssMnemonicPassphrase);
file << "# mnemonic: " << ssMnemonic << "\n";
file << "# mnemonic passphrase: " << ssMnemonicPassphrase << "\n\n";
SecureVector vchSeed = hdChainCurrent.GetSeed();
file << "# HD seed: " << HexStr(vchSeed) << "\n\n";
CExtKey masterKey;
masterKey.SetMaster(&vchSeed[0], vchSeed.size());
CBitcoinExtKey b58extkey;
b58extkey.SetKey(masterKey);
file << "# extended private masterkey: " << b58extkey.ToString() << "\n";
CExtPubKey masterPubkey;
masterPubkey = masterKey.Neuter();
CBitcoinExtPubKey b58extpubkey;
b58extpubkey.SetKey(masterPubkey);
file << "# extended public masterkey: " << b58extpubkey.ToString() << "\n\n";
for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i)
{
CHDAccount acc;
if(hdChainCurrent.GetAccount(i, acc)) {
file << "# external chain counter: " << acc.nExternalChainCounter << "\n";
file << "# internal chain counter: " << acc.nInternalChainCounter << "\n\n";
} else {
file << "# WARNING: ACCOUNT " << i << " IS MISSING!" << "\n\n";
}
}
}
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr = CBitcoinAddress(keyid).ToString();
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
file << strprintf("%s %s ", CBitcoinSecret(key).ToString(), strTime);
if (pwalletMain->mapAddressBook.count(keyid)) {
file << strprintf("label=%s", EncodeDumpString(pwalletMain->mapAddressBook[keyid].name));
} else if (setKeyPool.count(keyid)) {
file << "reserve=1";
} else {
file << "change=1";
}
file << strprintf(" # addr=%s%s\n", strAddr, (pwalletMain->mapHdPubKeys.count(keyid) ? " hdkeypath="+pwalletMain->mapHdPubKeys[keyid].GetKeyPath() : ""));
}
}
file << "\n";
file << "# End of dump\n";
file.close();
return NullUniValue;
}
UniValue ProcessImport(const UniValue& data, const int64_t timestamp)
{
try {
bool success = false;
// Required fields.
const UniValue& scriptPubKey = data["scriptPubKey"];
// Should have script or JSON with "address".
if (!(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address")) && !(scriptPubKey.getType() == UniValue::VSTR)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid scriptPubKey");
}
// Optional fields.
const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
const bool& internal = data.exists("internal") ? data["internal"].get_bool() : false;
const bool& watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : "";
bool isScript = scriptPubKey.getType() == UniValue::VSTR;
bool isP2SH = strRedeemScript.length() > 0;
const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
// Parse the output.
CScript script;
CBitcoinAddress address;
if (!isScript) {
address = CBitcoinAddress(output);
if (!address.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
script = GetScriptForDestination(address.Get());
} else {
if (!IsHex(output)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey");
}
std::vector<unsigned char> vData(ParseHex(output));
script = CScript(vData.begin(), vData.end());
}
// Watchonly and private keys
if (watchOnly && keys.size()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between watchonly and keys");
}
// Internal + Label
if (internal && data.exists("label")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between internal and label");
}
// Not having Internal + Script
if (!internal && isScript) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set for hex scriptPubKey");
}
// Keys / PubKeys size check.
if (!isP2SH && (keys.size() > 1 || pubKeys.size() > 1)) { // Address / scriptPubKey
throw JSONRPCError(RPC_INVALID_PARAMETER, "More than private key given for one address");
}
// Invalid P2SH redeemScript
if (isP2SH && !IsHex(strRedeemScript)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script");
}
// Process. //
// P2SH
if (isP2SH) {
// Import redeem script.
std::vector<unsigned char> vData(ParseHex(strRedeemScript));
CScript redeemScript = CScript(vData.begin(), vData.end());
// Invalid P2SH address
if (!script.IsPayToScriptHash()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid P2SH address / script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(redeemScript) && !pwalletMain->AddWatchOnly(redeemScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (!pwalletMain->HaveCScript(redeemScript) && !pwalletMain->AddCScript(redeemScript)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
}
CBitcoinAddress redeemAddress = CBitcoinAddress(CScriptID(redeemScript));
CScript redeemDestination = GetScriptForDestination(redeemAddress.Get());
if (::IsMine(*pwalletMain, redeemDestination) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(redeemDestination) && !pwalletMain->AddWatchOnly(redeemDestination, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
// add to address book or update label
if (address.IsValid()) {
pwalletMain->SetAddressBook(address.Get(), label, "receive");
}
// Import private keys.
if (keys.size()) {
for (size_t i = 0; i < keys.size(); i++) {
const std::string& privkey = keys[i].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(privkey);
if (!fGood) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
CKey key = vchSecret.GetKey();
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
}
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, label, "receive");
if (pwalletMain->HaveKey(vchAddress)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key");
}
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
}
pwalletMain->UpdateTimeFirstKey(timestamp);
}
}
success = true;
} else {
// Import public keys.
if (pubKeys.size() && keys.size() == 0) {
const std::string& strPubKey = pubKeys[0].get_str();
if (!IsHex(strPubKey)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
}
std::vector<unsigned char> vData(ParseHex(strPubKey));
CPubKey pubKey(vData.begin(), vData.end());
if (!pubKey.IsFullyValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
}
CBitcoinAddress pubKeyAddress = CBitcoinAddress(pubKey.GetID());
// Consistency check.
if (!isScript && !(pubKeyAddress.Get() == address.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
// Consistency check.
if (isScript) {
CBitcoinAddress scriptAddress;
CTxDestination destination;
if (ExtractDestination(script, destination)) {
scriptAddress = CBitcoinAddress(destination);
if (!(scriptAddress.Get() == pubKeyAddress.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
}
}
CScript pubKeyScript = GetScriptForDestination(pubKeyAddress.Get());
if (::IsMine(*pwalletMain, pubKeyScript) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(pubKeyScript) && !pwalletMain->AddWatchOnly(pubKeyScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
// add to address book or update label
if (pubKeyAddress.IsValid()) {
pwalletMain->SetAddressBook(pubKeyAddress.Get(), label, "receive");
}
// TODO Is this necessary?
CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey);
if (::IsMine(*pwalletMain, scriptRawPubKey) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(scriptRawPubKey) && !pwalletMain->AddWatchOnly(scriptRawPubKey, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
success = true;
}
// Import private keys.
if (keys.size()) {
const std::string& strPrivkey = keys[0].get_str();
// Checks.
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strPrivkey);
if (!fGood) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
CKey key = vchSecret.GetKey();
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
}
CPubKey pubKey = key.GetPubKey();
assert(key.VerifyPubKey(pubKey));
CBitcoinAddress pubKeyAddress = CBitcoinAddress(pubKey.GetID());
// Consistency check.
if (!isScript && !(pubKeyAddress.Get() == address.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
// Consistency check.
if (isScript) {
CBitcoinAddress scriptAddress;
CTxDestination destination;
if (ExtractDestination(script, destination)) {
scriptAddress = CBitcoinAddress(destination);
if (!(scriptAddress.Get() == pubKeyAddress.Get())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
}
}
CKeyID vchAddress = pubKey.GetID();
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, label, "receive");
if (pwalletMain->HaveKey(vchAddress)) {
return false;
}
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
if (!pwalletMain->AddKeyPubKey(key, pubKey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
}
pwalletMain->UpdateTimeFirstKey(timestamp);
success = true;
}
// Import scriptPubKey only.
if (pubKeys.size() == 0 && keys.size() == 0) {
if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwalletMain->MarkDirty();
if (!pwalletMain->HaveWatchOnly(script) && !pwalletMain->AddWatchOnly(script, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (scriptPubKey.getType() == UniValue::VOBJ) {
// add to address book or update label
if (address.IsValid()) {
pwalletMain->SetAddressBook(address.Get(), label, "receive");
}
}
success = true;
}
}
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(success));
return result;
} catch (const UniValue& e) {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", e);
return result;
} catch (...) {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields"));
return result;
}
}
int64_t GetImportTimestamp(const UniValue& data, int64_t now)
{
if (data.exists("timestamp")) {
const UniValue& timestamp = data["timestamp"];
if (timestamp.isNum()) {
return timestamp.get_int64();
} else if (timestamp.isStr() && timestamp.get_str() == "now") {
return now;
}
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
}
throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
}
UniValue importmulti(const JSONRPCRequest& mainRequest)
{
// clang-format off
if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)
throw std::runtime_error(
"importmulti \"requests\" \"options\"\n\n"
"Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options).\n\n"
"Arguments:\n"
"1. requests (array, required) Data to be imported\n"
" [ (array of json objects)\n"
" {\n"
" \"scriptPubKey\": \"<script>\" | { \"address\":\"<address>\" }, (string / json, required) Type of scriptPubKey (string for script, json for address)\n"
" \"timestamp\": timestamp | \"now\" , (integer / string, required) Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\n"
" or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n"
" key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n"
" \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n"
" 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n"
" creation time of all keys being imported by the importmulti call will be scanned.\n"
" \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n"
" \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n"
" \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n"
" \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be be treated as not incoming payments\n"
" \"watchonly\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be considered watched even when they're not spendable, only allowed if keys are empty\n"
" \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n"
" }\n"
" ,...\n"
" ]\n"
"2. options (json, optional)\n"
" {\n"
" \"rescan\": <false>, (boolean, optional, default: true) Stating if should rescan the blockchain after all imports\n"
" }\n"
"\nExamples:\n" +
HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, "
"{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") +
"\nResponse is an array with the same size as the input that has the execution result :\n"
" [{ \"success\": true } , { \"success\": false, \"error\": { \"code\": -1, \"message\": \"Internal Server Error\"} }, ... ]\n");
// clang-format on
if (!EnsureWalletIsAvailable(mainRequest.fHelp)) {
return NullUniValue;
}
RPCTypeCheck(mainRequest.params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ));
const UniValue& requests = mainRequest.params[0];
//Default options
bool fRescan = true;
if (mainRequest.params.size() > 1) {
const UniValue& options = mainRequest.params[1];
if (options.exists("rescan")) {
fRescan = options["rescan"].get_bool();
}
}
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
// Verify all timestamps are present before importing any keys.
const int64_t now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0;
for (const UniValue& data : requests.getValues()) {
GetImportTimestamp(data, now);
}
bool fRunScan = false;
const int64_t minimumTimestamp = 1;
int64_t nLowestTimestamp = 0;
if (fRescan && chainActive.Tip()) {
nLowestTimestamp = chainActive.Tip()->GetBlockTime();
} else {
fRescan = false;
}
UniValue response(UniValue::VARR);
BOOST_FOREACH (const UniValue& data, requests.getValues()) {
const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
const UniValue result = ProcessImport(data, timestamp);
response.push_back(result);
if (!fRescan) {
continue;
}
// If at least one request was successful then allow rescan.
if (result["success"].get_bool()) {
fRunScan = true;
}
// Get the lowest timestamp.
if (timestamp < nLowestTimestamp) {
nLowestTimestamp = timestamp;
}
}
if (fRescan && fRunScan && requests.size()) {
CBlockIndex* pindex = nLowestTimestamp > minimumTimestamp ? chainActive.FindEarliestAtLeast(std::max<int64_t>(nLowestTimestamp - 7200, 0)) : chainActive.Genesis();
CBlockIndex* scannedRange = nullptr;
if (pindex) {
scannedRange = pwalletMain->ScanForWalletTransactions(pindex, true);
pwalletMain->ReacceptWalletTransactions();
}
if (!scannedRange || scannedRange->nHeight > pindex->nHeight) {
std::vector<UniValue> results = response.getValues();
response.clear();
response.setArray();
size_t i = 0;
for (const UniValue& request : requests.getValues()) {
// If key creation date is within the successfully scanned
// range, or if the import result already has an error set, let
// the result stand unmodified. Otherwise replace the result
// with an error message.
if (GetImportTimestamp(request, now) - 7200 >= scannedRange->GetBlockTimeMax() || results.at(i).exists("error")) {
response.push_back(results.at(i));
} else {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, strprintf("Failed to rescan before time %d, transactions may be missing.", scannedRange->GetBlockTimeMax())));
response.push_back(std::move(result));
}
++i;
}
}
}
return response;
}
|
/*
* @Author: seenli
* @Date: 2021-01-18 17:15:22
* @LastEditors: seenli
* @LastEditTime: 2021-01-18 17:50:18
* @FilePath: \Ch11\ch11_drill.cpp
* @Description: Programming Principles and Practice Using C++ Second Edition
*/
// Chapter 11, drill
#include "../includes/std_lib_facilities.h"
void int_output() {
cout << showbase << "Birth year: " << endl
<< 1980 << "\t(decimal)" << endl
<< hex << 1980 << "\t(hexadecimal)" << endl
<< oct << 1980 << "\t(octal)" << endl;
}
void int_input() {
int a{}, b{}, c{}, d{};
cin >> a >> hex >> b >> oct >> c >> d;
cout << a << '\t' << b << '\t' << c << '\t' << d << endl;
}
void float_output() {
cout << 1234567.89 << "\t(general)\n"
<< fixed << 1234567.89 << "\t(fixed)\n"
<< scientific << 1234567.89 << "\t(scientific)\n";
}
int main()
try {
int_output();
cout << "==================================================================" << endl;
int_input();
cout << "==================================================================" << endl;
float_output();
cout << "==================================================================" << endl;
cout << setw(10) << "Wuethrich" << " | " << "Benjamin" << " | "
<< setw(16) << "+1345 326 5181" << " | " << setw(29) << "benjamin.wuethrich@gmail.com" << endl
<< setw(10) << "Forrest" << " | " << setw(8) << "Kara" << " | "
<< setw(16) << "+1345 516 1920" << " | " << setw(29) << "kara_forrest@hotmail.com" << endl
<< setw(10) << "Aarnau" << " | " << setw(8) << "Mayra" << " | "
<< "+34 66 696 55 63" << " | " << setw(29) << "mayraaachen@hotmail.com" << endl
<< setw(10) << "Michel" << " | " << setw(8) << "Tanael" << " | "
<< "+41 79 374 48 62" << " | " << setw(29) << "tanael@gmail.com" << endl
<< setw(10) << "Widler" << " | " << setw(8) << "Andrea" << " | "
<< "+41 79 293 29 38" << " | " << setw(29) << "andreawidler@bluewin.ch" << endl
<< "Amanatidou" << " | " << "Elisabet" << " | "
<< "+41 76 701 61 28" << " | " << "elisabet.amanatidou@gmail.com" << endl;
system("pause");
return 0;
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
keep_window_open();
return 1;
}
catch (...) {
cerr << "exception\n";
keep_window_open();
return 2;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparamsbase.h>
#include <tinyformat.h>
#include <util.h>
#include <assert.h>
#include <memory>
const std::string CBaseChainParams::MAIN = "main";
const std::string CBaseChainParams::TESTNET = "test";
const std::string CBaseChainParams::REGTEST = "regtest";
void AppendParamsHelpMessages(std::string& strUsage, bool debugHelp)
{
strUsage += HelpMessageGroup(_("Chain selection options:"));
strUsage += HelpMessageOpt("-testnet", _("Use the test chain"));
if (debugHelp) {
strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
"This is intended for regression testing tools and app development.");
}
}
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
#ifdef BUILD_BTC
nRPCPort = 8332;
#else // BUILD_EQB
nRPCPort = 8330;
#endif // END_BUILD
}
};
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseChainParams
{
public:
CBaseTestNetParams()
{
#ifdef BUILD_BTC
nRPCPort = 18332;
#else // BUILD_EQB
nRPCPort = 18330;
#endif // END_BUILD
strDataDir = "testnet3";
}
};
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseChainParams
{
public:
CBaseRegTestParams()
{
#ifdef BUILD_BTC
nRPCPort = 18443;
#else // BUILD_EQB
nRPCPort = 18440;
#endif // END_BUILD
strDataDir = "regtest";
}
};
static std::unique_ptr<CBaseChainParams> globalChainBaseParams;
const CBaseChainParams& BaseParams()
{
assert(globalChainBaseParams);
return *globalChainBaseParams;
}
std::unique_ptr<CBaseChainParams> CreateBaseChainParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return std::unique_ptr<CBaseChainParams>(new CBaseMainParams());
else if (chain == CBaseChainParams::TESTNET)
return std::unique_ptr<CBaseChainParams>(new CBaseTestNetParams());
else if (chain == CBaseChainParams::REGTEST)
return std::unique_ptr<CBaseChainParams>(new CBaseRegTestParams());
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectBaseParams(const std::string& chain)
{
globalChainBaseParams = CreateBaseChainParams(chain);
}
std::string ChainNameFromCommandLine()
{
bool fRegTest = gArgs.GetBoolArg("-regtest", false);
bool fTestNet = gArgs.GetBoolArg("-testnet", false);
if (fTestNet && fRegTest)
throw std::runtime_error("Invalid combination of -regtest and -testnet.");
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
|
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "controller.h"
#include "listmodel.h"
#include "hellolistener.h"
#include "logging.h"
int main(int argc, char *argv[]) {
INIT_LOG
QGuiApplication app(argc, argv);
QCoreApplication::setOrganizationName("TRAPTA");
QCoreApplication::setOrganizationDomain("trapta.eu");
QCoreApplication::setApplicationName("TRAPTAViewer");
HelloListener helloListener;
SocketAdapter socketAdapter;
QObject::connect(&helloListener, SIGNAL(hello(QString,int)),
&socketAdapter, SLOT(connectToServer(QString,int)));
ListModel listModel;
Controller controller;
QObject::connect(&socketAdapter, SIGNAL(incomingJsonDocument(QJsonDocument)),
&listModel, SLOT(processJsonDocument(QJsonDocument)));
QObject::connect(&socketAdapter, SIGNAL(connected()),
&controller, SLOT(connected()));
QObject::connect(&socketAdapter, SIGNAL(disconnected(QString)),
&controller, SLOT(disconnected(QString)));
QObject::connect(&controller, SIGNAL(needToQuit()),
&socketAdapter, SLOT(close()));
QObject::connect(&socketAdapter, SIGNAL(closed()),
&app, SLOT(quit()));
if (socketAdapter.isConnected()) controller.connected();
else controller.disconnected(QString());
listModel.processJsonDocument(socketAdapter.jsonDocument());
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("listModel", &listModel);
engine.rootContext()->setContextProperty("controller", &controller);
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
app.exec();
socketAdapter.quit();
helloListener.quit();
}
|
#ifndef _APPLICATIONS_IO_BOARD_TARGET_CONFIG_HXX_
#define _APPLICATIONS_IO_BOARD_TARGET_CONFIG_HXX_
#include "openlcb/ConfiguredConsumer.hxx"
#include "openlcb/ConfiguredProducer.hxx"
#include "openlcb/ConfigRepresentation.hxx"
#include "openlcb/MemoryConfig.hxx"
namespace openlcb
{
/// Defines the identification information for the node. The arguments are:
///
/// - 4 (version info, always 4 by the standard
/// - Manufacturer name
/// - Model name
/// - Hardware version
/// - Software version
///
/// This data will be used for all purposes of the identification:
///
/// - the generated cdi.xml will include this data
/// - the Simple Node Ident Info Protocol will return this data
/// - the ACDI memory space will contain this data.
extern const SimpleNodeStaticValues SNIP_STATIC_DATA = {
4, "OpenMRN", "Test IO Board - Tiva Launchpad 123",
"ek-tm4c123gxl", "1.01"};
#define NUM_OUTPUTS 3
#define NUM_INPUTS 2
/// Declares a repeated group of a given base group and number of repeats. The
/// ProducerConfig and ConsumerConfig groups represent the configuration layout
/// needed by the ConfiguredProducer and ConfiguredConsumer classes, and come
/// from their respective hxx file.
using AllConsumers = RepeatedGroup<ConsumerConfig, NUM_OUTPUTS>;
using AllProducers = RepeatedGroup<ProducerConfig, NUM_INPUTS>;
/// Modify this value every time the EEPROM needs to be cleared on the node
/// after an update.
static constexpr uint16_t CANONICAL_VERSION = 0x184f;
/// Defines the main segment in the configuration CDI. This is laid out at
/// origin 128 to give space for the ACDI user data at the beginning.
CDI_GROUP(IoBoardSegment, Segment(MemoryConfigDefs::SPACE_CONFIG), Offset(128));
/// Each entry declares the name of the current entry, then the type and then
/// optional arguments list.
CDI_GROUP_ENTRY(internal_config, InternalConfigData);
CDI_GROUP_ENTRY(consumers, AllConsumers, Name("Output LEDs"));
CDI_GROUP_ENTRY(producers, AllProducers, Name("Input buttons"));
CDI_GROUP_END();
/// The main structure of the CDI. ConfigDef is the symbol we use in main.cxx
/// to refer to the configuration defined here.
CDI_GROUP(ConfigDef, MainCdi());
/// Adds the <identification> tag with the values from SNIP_STATIC_DATA above.
CDI_GROUP_ENTRY(ident, Identification);
/// Adds an <acdi> tag.
CDI_GROUP_ENTRY(acdi, Acdi);
/// Adds a segment for changing the values in the ACDI user-defined
/// space. UserInfoSegment is defined in the system header.
CDI_GROUP_ENTRY(userinfo, UserInfoSegment);
/// Adds the main configuration segment.
CDI_GROUP_ENTRY(seg, IoBoardSegment);
CDI_GROUP_END();
} // namespace openlcb
#endif // _APPLICATIONS_IO_BOARD_TARGET_CONFIG_HXX_
|
/****************************************************
Date: Oct 9th
link: https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3488/
****************************************************/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <limits.h>
using namespace std;
/*
Q: Serialize and Deserialize BST
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or
memory buffer, or transmitted across a network connection link to be reconstructed later in the same or
another computer environment.
Design an algorithm to serialize and deserialize a binary search tree.
There is no restriction on how your serialization/deserialization algorithm should work.
You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to
the original tree structure.
The encoded string should be as compact as possible.
Example 1:
Input: root = [2,1,3]
Output: [2,1,3]
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The input tree is guaranteed to be a binary search tree.
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec
{
private:
void collect(TreeNode *node, string &data)
{
if (node == NULL)
{
data += "-1;";
return;
}
data += std::to_string(node->val) + ";";
collect(node->left, data);
collect(node->right, data);
}
TreeNode *Create(queue<int> &vals)
{
int val = vals.front();
vals.pop();
if (val < 0)
{
return NULL;
}
TreeNode *node = new TreeNode(val);
node->left = Create(vals);
node->right = Create(vals);
return node;
}
public:
// Encodes a tree to a single string.
string serialize(TreeNode *root)
{
string ans;
collect(root, ans);
return ans;
}
// Decodes your encoded data to tree.
TreeNode *deserialize(string data)
{
int s = 0;
int p = 0;
int l = data.size();
queue<int> vals;
while ((p < l - 1) && (s < l))
{
p = data.find_first_of(';', p);
string n = data.substr(s, p - s);
int num = stoi(n);
vals.push(num);
s = p + 1;
p++;
}
return Create(vals);
}
};
// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;
|
//=================================================================================================
/*!
// \file src/mathtest/smatdmatadd/SCbSDb.cpp
// \brief Source file for the SCbSDb sparse matrix/dense matrix addition math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'SCbSDb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using SCb = blaze::SymmetricMatrix< blaze::CompressedMatrix<TypeB> >;
using SDb = blaze::SymmetricMatrix< blaze::DynamicMatrix<TypeB> >;
// Creator type definitions
using CSCb = blazetest::Creator<SCb>;
using CSDb = blazetest::Creator<SDb>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i*i; ++j ) {
RUN_SMATDMATADD_OPERATION_TEST( CSCb( i, j ), CSDb( i ) );
}
}
// Running tests with large matrices
RUN_SMATDMATADD_OPERATION_TEST( CSCb( 67UL, 7UL ), CSDb( 67UL ) );
RUN_SMATDMATADD_OPERATION_TEST( CSCb( 128UL, 16UL ), CSDb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// Copyright (c) 2014-2017 The Botcoin Core developers
#include "governance.h"
#include "test/test_botcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(ratecheck_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(ratecheck_test)
{
CRateCheckBuffer buffer;
BOOST_CHECK(buffer.GetCount() == 0);
BOOST_CHECK(buffer.GetMinTimestamp() == numeric_limits<int64_t>::max());
BOOST_CHECK(buffer.GetMaxTimestamp() == 0);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(1);
std::cout << "buffer.GetMinTimestamp() = " << buffer.GetMinTimestamp() << std::endl;
BOOST_CHECK(buffer.GetCount() == 1);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 1);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(2);
BOOST_CHECK(buffer.GetCount() == 2);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 2);
//BOOST_CHECK(fabs(buffer.GetRate() - 2.0) < 1.0e-9);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(3);
BOOST_CHECK(buffer.GetCount() == 3);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 3);
int64_t nMin = buffer.GetMinTimestamp();
int64_t nMax = buffer.GetMaxTimestamp();
double dRate = buffer.GetRate();
std::cout << "buffer.GetCount() = " << buffer.GetCount() << std::endl;
std::cout << "nMin = " << nMin << std::endl;
std::cout << "nMax = " << nMax << std::endl;
std::cout << "buffer.GetRate() = " << dRate << std::endl;
//BOOST_CHECK(fabs(buffer.GetRate() - (3.0/2.0)) < 1.0e-9);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(4);
BOOST_CHECK(buffer.GetCount() == 4);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 4);
//BOOST_CHECK(fabs(buffer.GetRate() - (4.0/3.0)) < 1.0e-9);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(5);
BOOST_CHECK(buffer.GetCount() == 5);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 5);
BOOST_CHECK(fabs(buffer.GetRate() - (5.0/4.0)) < 1.0e-9);
buffer.AddTimestamp(6);
BOOST_CHECK(buffer.GetCount() == 5);
BOOST_CHECK(buffer.GetMinTimestamp() == 2);
BOOST_CHECK(buffer.GetMaxTimestamp() == 6);
BOOST_CHECK(fabs(buffer.GetRate() - (5.0/4.0)) < 1.0e-9);
CRateCheckBuffer buffer2;
std::cout << "Before loop tests" << std::endl;
for(int64_t i = 1; i < 11; ++i) {
std::cout << "In loop: i = " << i << std::endl;
buffer2.AddTimestamp(i);
BOOST_CHECK(buffer2.GetCount() == (i <= 5 ? i : 5));
BOOST_CHECK(buffer2.GetMinTimestamp() == max(int64_t(1), i - 4));
BOOST_CHECK(buffer2.GetMaxTimestamp() == i);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include <realm/object-store/impl/external_commit_helper.hpp>
#include <realm/object-store/impl/realm_coordinator.hpp>
#include <algorithm>
using namespace realm;
using namespace realm::_impl;
using namespace realm::util;
static std::string normalize_realm_path_for_windows_kernel_object_name(std::string realm_path)
{
// windows named objects names should not contain backslash
std::replace(realm_path.begin(), realm_path.end(), '\\', '/');
// always use lowercase for the drive letter as a win32 named objects name
auto position = realm_path.find(':');
if (position != std::string::npos && position > 0) {
realm_path[position - 1] = tolower(realm_path[position - 1]);
}
return realm_path;
}
static std::string create_condvar_sharedmemory_name(std::string realm_path)
{
realm_path = normalize_realm_path_for_windows_kernel_object_name(realm_path);
std::string name("Local\\Realm_ObjectStore_ExternalCommitHelper_SharedCondVar_");
name.append(realm_path);
return name;
}
ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent)
: m_parent(parent)
, m_shared_part(create_condvar_sharedmemory_name(parent.get_path()))
{
m_mutex.set_shared_part(InterprocessMutex::SharedPart(),
normalize_realm_path_for_windows_kernel_object_name(parent.get_path()),
"ExternalCommitHelper_ControlMutex");
m_commit_available.set_shared_part(
m_shared_part->cv, normalize_realm_path_for_windows_kernel_object_name(parent.get_path()),
"ExternalCommitHelper_CommitCondVar",
normalize_realm_path_for_windows_kernel_object_name(std::filesystem::temp_directory_path().u8string()));
{
auto lock = std::unique_lock(m_mutex);
m_last_count = m_shared_part->num_signals;
}
m_thread = std::thread([this]() {
listen();
});
}
ExternalCommitHelper::~ExternalCommitHelper()
{
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
m_keep_listening = false;
m_commit_available.notify_all();
}
m_thread.join();
m_commit_available.release_shared_part();
}
void ExternalCommitHelper::notify_others()
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
m_shared_part->num_signals++;
m_commit_available.notify_all();
}
void ExternalCommitHelper::listen()
{
auto lock = std::unique_lock(m_mutex);
while (true) {
m_commit_available.wait(m_mutex, nullptr, [&] {
return !m_keep_listening || m_shared_part->num_signals != m_last_count;
});
m_last_count = m_shared_part->num_signals;
if (!m_keep_listening)
return;
lock.unlock();
m_parent.on_change();
lock.lock();
}
}
|
#include <cstdio>
#include <stack>
using namespace std;
int main() {
stack<int> s;
int n;
while (scanf("%d", &n) && n != 0) {
int m, cont = 0, pos;
bool ok;
while (scanf("%d", &m) && m != 0) {
if (cont == 0) {
ok = true;
pos = 1;
while (!s.empty()) s.pop();
}
if (ok){
if (s.empty()) s.push(pos), pos++;
while (s.top() != m && pos <= n) {
s.push(pos);
pos++;
}
if (s.top() == m) s.pop();
else ok = false;
}
cont++;
if (cont == n) {
if (ok) printf("Yes\n");
else printf("No\n");
cont = 0;
}
}
printf("\n");
}
return 0;
}
|
/**
* ODVpi - Benchmark code extending OpenDaVinci
* (https://github.com/se-research/OpenDaVINCI)
* Copyright (C) 2016 Philip Masek, Magnus Thulin
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <csignal>
#include <sstream>
#include <iostream>
#include <cerrno>
// WRITE TO FILE
#include <fstream>
// WRITE TO FILE END
// SERIAL
#include <termios.h>
#include <fcntl.h> /* For O_RDWR */
#include <unistd.h> /* For open(), creat() */
#include <cstring>
// SERIAL END
using namespace std;
int setUpSerialPort(const char* port_location) {
int PORT = open( port_location, O_RDWR| O_NOCTTY );
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( PORT, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B115200);
cfsetispeed (&tty, (speed_t)B115200);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( PORT, TCIFLUSH );
if ( tcsetattr ( PORT, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
return PORT;
}
const char* readFromPort(int PORT) {
int n = 0,
spot = 0;
char buf = '\0';
/* Whole response*/
char response[64];
memset(response, '\0', sizeof response);
int i = 0;
do {
n = read( PORT, &buf, 1 );
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0 );
if (n < 0) {
} else if (n == 0) {
} else {
stringstream ss;
ss << response;
return ss.str().c_str();
}
return "";
}
int32_t main(int32_t argc, char **argv) {
const char* device_location = NULL;
const char* output_file_path = NULL;
for (int args=0;args<argc;args++){
if (string(argv[args])=="-d" || string(argv[args])=="--device") {
device_location = argv[args+1];
} else if (string(argv[args])=="-o" || string(argv[args])=="--output") {
output_file_path = argv[args+1];
}
}
int port = setUpSerialPort(device_location);
ofstream output_file;
int in = 0;
timespec end, start;
clock_gettime(CLOCK_MONOTONIC, &start);
if (output_file_path) {
output_file.open(output_file_path);
while (true) {
const char* msg = readFromPort(port);
output_file << msg;
in++;
if (std::strstr(msg, "end") != NULL) {
output_file.close();
break;
}
}
} else {
while (true) {
readFromPort(port);
in++;
if (in == 12000)
break;
}
}
clock_gettime(CLOCK_MONOTONIC, &end);
cout << in << " Start: " << start.tv_sec << " End: " << end.tv_sec << " Duration: " << end.tv_sec-start.tv_sec << endl;
return 0;
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gmock/gmock.h>
#include <set>
#include <string>
#include <process/clock.hpp>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <process/gtest.hpp>
#include <process/pid.hpp>
#include <process/protobuf.hpp>
#include <process/timeout.hpp>
#include <stout/gtest.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include "common/type_utils.hpp"
#include "log/coordinator.hpp"
#include "log/log.hpp"
#include "log/replica.hpp"
#include "messages/messages.hpp"
using namespace mesos;
using namespace mesos::internal;
using namespace mesos::internal::log;
using process::Clock;
using process::Future;
using process::Timeout;
using process::UPID;
using testing::_;
using testing::Eq;
using testing::Return;
#include "tests/utils.hpp"
using namespace mesos::internal::tests;
class ReplicaTest : public TemporaryDirectoryTest {};
TEST_F(ReplicaTest, Promise)
{
const std::string path = os::getcwd() + "/.log";
Replica replica(path);
PromiseRequest request;
PromiseResponse response;
Future<PromiseResponse> future;
request.set_id(2);
future = protocol::promise(replica.pid(), request);
AWAIT_READY(future);
response = future.get();
EXPECT_TRUE(response.okay());
EXPECT_EQ(2u, response.id());
EXPECT_TRUE(response.has_position());
EXPECT_EQ(0u, response.position());
EXPECT_FALSE(response.has_action());
request.set_id(1);
future = protocol::promise(replica.pid(), request);
AWAIT_READY(future);
response = future.get();
EXPECT_FALSE(response.okay());
EXPECT_EQ(1u, response.id());
EXPECT_FALSE(response.has_position());
EXPECT_FALSE(response.has_action());
request.set_id(3);
future = protocol::promise(replica.pid(), request);
AWAIT_READY(future);
response = future.get();
EXPECT_TRUE(response.okay());
EXPECT_EQ(3u, response.id());
EXPECT_TRUE(response.has_position());
EXPECT_EQ(0u, response.position());
EXPECT_FALSE(response.has_action());
}
TEST_F(ReplicaTest, Append)
{
const std::string path = os::getcwd() + "/.log";
Replica replica(path);
const uint64_t id = 1;
PromiseRequest request1;
request1.set_id(id);
Future<PromiseResponse> future1 =
protocol::promise(replica.pid(), request1);
AWAIT_READY(future1);
PromiseResponse response1 = future1.get();
EXPECT_TRUE(response1.okay());
EXPECT_EQ(id, response1.id());
EXPECT_TRUE(response1.has_position());
EXPECT_EQ(0u, response1.position());
EXPECT_FALSE(response1.has_action());
WriteRequest request2;
request2.set_id(id);
request2.set_position(1);
request2.set_type(Action::APPEND);
request2.mutable_append()->set_bytes("hello world");
Future<WriteResponse> future2 =
protocol::write(replica.pid(), request2);
AWAIT_READY(future2);
WriteResponse response2 = future2.get();
EXPECT_TRUE(response2.okay());
EXPECT_EQ(id, response2.id());
EXPECT_EQ(1u, response2.position());
Future<std::list<Action> > actions = replica.read(1, 1);
AWAIT_READY(actions);
ASSERT_EQ(1u, actions.get().size());
Action action = actions.get().front();
EXPECT_EQ(1u, action.position());
EXPECT_EQ(1u, action.promised());
EXPECT_TRUE(action.has_performed());
EXPECT_EQ(1u, action.performed());
EXPECT_FALSE(action.has_learned());
EXPECT_TRUE(action.has_type());
EXPECT_EQ(Action::APPEND, action.type());
EXPECT_FALSE(action.has_nop());
EXPECT_TRUE(action.has_append());
EXPECT_FALSE(action.has_truncate());
EXPECT_EQ("hello world", action.append().bytes());
}
TEST_F(ReplicaTest, Recover)
{
const std::string path = os::getcwd() + "/.log";
Replica replica1(path);
const uint64_t id = 1;
PromiseRequest request1;
request1.set_id(id);
Future<PromiseResponse> future1 =
protocol::promise(replica1.pid(), request1);
AWAIT_READY(future1);
PromiseResponse response1 = future1.get();
EXPECT_TRUE(response1.okay());
EXPECT_EQ(id, response1.id());
EXPECT_TRUE(response1.has_position());
EXPECT_EQ(0u, response1.position());
EXPECT_FALSE(response1.has_action());
WriteRequest request2;
request2.set_id(id);
request2.set_position(1);
request2.set_type(Action::APPEND);
request2.mutable_append()->set_bytes("hello world");
Future<WriteResponse> future2 =
protocol::write(replica1.pid(), request2);
AWAIT_READY(future2);
WriteResponse response2 = future2.get();
EXPECT_TRUE(response2.okay());
EXPECT_EQ(id, response2.id());
EXPECT_EQ(1u, response2.position());
Future<std::list<Action> > actions1 = replica1.read(1, 1);
AWAIT_READY(actions1);
ASSERT_EQ(1u, actions1.get().size());
{
Action action = actions1.get().front();
EXPECT_EQ(1u, action.position());
EXPECT_EQ(1u, action.promised());
EXPECT_TRUE(action.has_performed());
EXPECT_EQ(1u, action.performed());
EXPECT_FALSE(action.has_learned());
EXPECT_TRUE(action.has_type());
EXPECT_EQ(Action::APPEND, action.type());
EXPECT_FALSE(action.has_nop());
EXPECT_TRUE(action.has_append());
EXPECT_FALSE(action.has_truncate());
EXPECT_EQ("hello world", action.append().bytes());
}
Replica replica2(path);
Future<std::list<Action> > actions2 = replica2.read(1, 1);
AWAIT_READY(actions2);
ASSERT_EQ(1u, actions2.get().size());
{
Action action = actions2.get().front();
EXPECT_EQ(1u, action.position());
EXPECT_EQ(1u, action.promised());
EXPECT_TRUE(action.has_performed());
EXPECT_EQ(1u, action.performed());
EXPECT_FALSE(action.has_learned());
EXPECT_TRUE(action.has_type());
EXPECT_EQ(Action::APPEND, action.type());
EXPECT_FALSE(action.has_nop());
EXPECT_TRUE(action.has_append());
EXPECT_FALSE(action.has_truncate());
EXPECT_EQ("hello world", action.append().bytes());
}
}
class CoordinatorTest : public TemporaryDirectoryTest {};
TEST_F(CoordinatorTest, Elect)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network;
network.add(replica1.pid());
network.add(replica2.pid());
Coordinator coord(2, &replica1, &network);
{
Result<uint64_t> result = coord.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
{
Future<std::list<Action> > actions = replica1.read(0, 0);
AWAIT_READY(actions);
ASSERT_EQ(1u, actions.get().size());
EXPECT_EQ(0u, actions.get().front().position());
ASSERT_TRUE(actions.get().front().has_type());
ASSERT_EQ(Action::NOP, actions.get().front().type());
}
}
TEST_F(CoordinatorTest, AppendRead)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network;
network.add(replica1.pid());
network.add(replica2.pid());
Coordinator coord(2, &replica1, &network);
{
Result<uint64_t> result = coord.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
uint64_t position;
{
Result<uint64_t> result2 =
coord.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(result2);
position = result2.get();
EXPECT_EQ(1u, position);
}
{
Future<std::list<Action> > actions = replica1.read(position, position);
AWAIT_READY(actions);
ASSERT_EQ(1u, actions.get().size());
EXPECT_EQ(position, actions.get().front().position());
ASSERT_TRUE(actions.get().front().has_type());
ASSERT_EQ(Action::APPEND, actions.get().front().type());
EXPECT_EQ("hello world", actions.get().front().append().bytes());
}
}
TEST_F(CoordinatorTest, AppendReadError)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network;
network.add(replica1.pid());
network.add(replica2.pid());
Coordinator coord(2, &replica1, &network);
{
Result<uint64_t> result = coord.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
uint64_t position;
{
Result<uint64_t> result2 =
coord.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(result2);
position = result2.get();
EXPECT_EQ(1u, position);
}
{
position += 1;
Future<std::list<Action> > actions = replica1.read(position, position);
AWAIT_FAILED(actions);
EXPECT_EQ("Bad read range (past end of log)", actions.failure());
}
}
TEST_F(CoordinatorTest, ElectNoQuorum)
{
const std::string path = os::getcwd() + "/.log";
Replica replica(path);
Network network;
network.add(replica.pid());
Coordinator coord(2, &replica, &network);
Clock::pause();
// Create a timeout here so that we can advance time.
Timeout timeout = Timeout::in(Seconds(10));
Clock::advance(Seconds(10));
{
Result<uint64_t> result = coord.elect(timeout);
EXPECT_TRUE(result.isNone());
}
Clock::resume();
}
TEST_F(CoordinatorTest, AppendNoQuorum)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network;
network.add(replica1.pid());
network.add(replica2.pid());
Coordinator coord(2, &replica1, &network);
{
Result<uint64_t> result = coord.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
network.remove(replica2.pid());
Clock::pause();
// Create a timeout here so that we can advance time.
Timeout timeout = Timeout::in(Seconds(10));
Clock::advance(Seconds(10));
{
Result<uint64_t> result = coord.append("hello world", timeout);
EXPECT_TRUE(result.isNone());
}
Clock::resume();
}
TEST_F(CoordinatorTest, Failover)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network1;
network1.add(replica1.pid());
network1.add(replica2.pid());
Coordinator coord1(2, &replica1, &network1);
{
Result<uint64_t> result = coord1.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
uint64_t position;
{
Result<uint64_t> result =
coord1.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(result);
position = result.get();
EXPECT_EQ(1u, position);
}
Network network2;
network2.add(replica1.pid());
network2.add(replica2.pid());
Coordinator coord2(2, &replica2, &network2);
{
Result<uint64_t> result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Future<std::list<Action> > actions = replica2.read(position, position);
AWAIT_READY(actions);
ASSERT_EQ(1u, actions.get().size());
EXPECT_EQ(position, actions.get().front().position());
ASSERT_TRUE(actions.get().front().has_type());
ASSERT_EQ(Action::APPEND, actions.get().front().type());
EXPECT_EQ("hello world", actions.get().front().append().bytes());
}
}
TEST_F(CoordinatorTest, Demoted)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network1;
network1.add(replica1.pid());
network1.add(replica2.pid());
Coordinator coord1(2, &replica1, &network1);
{
Result<uint64_t> result = coord1.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
uint64_t position;
{
Result<uint64_t> result =
coord1.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(result);
position = result.get();
EXPECT_EQ(1u, position);
}
Network network2;
network2.add(replica1.pid());
network2.add(replica2.pid());
Coordinator coord2(2, &replica2, &network2);
{
Result<uint64_t> result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Result<uint64_t> result =
coord1.append("hello moto", Timeout::in(Seconds(10)));
ASSERT_TRUE(result.isError());
EXPECT_EQ("Coordinator demoted", result.error());
}
{
Result<uint64_t> result =
coord2.append("hello hello", Timeout::in(Seconds(10)));
ASSERT_SOME(result);
position = result.get();
EXPECT_EQ(2u, position);
}
{
Future<std::list<Action> > actions = replica2.read(position, position);
AWAIT_READY(actions);
ASSERT_EQ(1u, actions.get().size());
EXPECT_EQ(position, actions.get().front().position());
ASSERT_TRUE(actions.get().front().has_type());
ASSERT_EQ(Action::APPEND, actions.get().front().type());
EXPECT_EQ("hello hello", actions.get().front().append().bytes());
}
}
TEST_F(CoordinatorTest, Fill)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
const std::string path3 = os::getcwd() + "/.log3";
Replica replica1(path1);
Replica replica2(path2);
Network network1;
network1.add(replica1.pid());
network1.add(replica2.pid());
Coordinator coord1(2, &replica1, &network1);
{
Result<uint64_t> result = coord1.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
uint64_t position;
{
Result<uint64_t> result =
coord1.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(result);
position = result.get();
EXPECT_EQ(1u, position);
}
Replica replica3(path3);
Network network2;
network2.add(replica2.pid());
network2.add(replica3.pid());
Coordinator coord2(2, &replica3, &network2);
{
Result<uint64_t> result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_TRUE(result.isNone());
result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Future<std::list<Action> > actions = replica3.read(position, position);
AWAIT_READY(actions);
ASSERT_EQ(1u, actions.get().size());
EXPECT_EQ(position, actions.get().front().position());
ASSERT_TRUE(actions.get().front().has_type());
ASSERT_EQ(Action::APPEND, actions.get().front().type());
EXPECT_EQ("hello world", actions.get().front().append().bytes());
}
}
TEST_F(CoordinatorTest, NotLearnedFill)
{
DROP_MESSAGES(Eq(LearnedMessage().GetTypeName()), _, _);
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
const std::string path3 = os::getcwd() + "/.log3";
Replica replica1(path1);
Replica replica2(path2);
Network network1;
network1.add(replica1.pid());
network1.add(replica2.pid());
Coordinator coord1(2, &replica1, &network1);
{
Result<uint64_t> result = coord1.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
uint64_t position;
{
Result<uint64_t> result =
coord1.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(result);
position = result.get();
EXPECT_EQ(1u, position);
}
Replica replica3(path3);
Network network2;
network2.add(replica2.pid());
network2.add(replica3.pid());
Coordinator coord2(2, &replica3, &network2);
{
Result<uint64_t> result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_TRUE(result.isNone());
result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Future<std::list<Action> > actions = replica3.read(position, position);
AWAIT_READY(actions);
ASSERT_EQ(1u, actions.get().size());
EXPECT_EQ(position, actions.get().front().position());
ASSERT_TRUE(actions.get().front().has_type());
ASSERT_EQ(Action::APPEND, actions.get().front().type());
EXPECT_EQ("hello world", actions.get().front().append().bytes());
}
}
TEST_F(CoordinatorTest, MultipleAppends)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network;
network.add(replica1.pid());
network.add(replica2.pid());
Coordinator coord(2, &replica1, &network);
{
Result<uint64_t> result = coord.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
for (uint64_t position = 1; position <= 10; position++) {
Result<uint64_t> result =
coord.append(stringify(position), Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Future<std::list<Action> > actions = replica1.read(1, 10);
AWAIT_READY(actions);
EXPECT_EQ(10u, actions.get().size());
foreach (const Action& action, actions.get()) {
ASSERT_TRUE(action.has_type());
ASSERT_EQ(Action::APPEND, action.type());
EXPECT_EQ(stringify(action.position()), action.append().bytes());
}
}
}
TEST_F(CoordinatorTest, MultipleAppendsNotLearnedFill)
{
DROP_MESSAGES(Eq(LearnedMessage().GetTypeName()), _, _);
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
const std::string path3 = os::getcwd() + "/.log3";
Replica replica1(path1);
Replica replica2(path2);
Network network1;
network1.add(replica1.pid());
network1.add(replica2.pid());
Coordinator coord1(2, &replica1, &network1);
{
Result<uint64_t> result = coord1.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
for (uint64_t position = 1; position <= 10; position++) {
Result<uint64_t> result =
coord1.append(stringify(position), Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
Replica replica3(path3);
Network network2;
network2.add(replica2.pid());
network2.add(replica3.pid());
Coordinator coord2(2, &replica3, &network2);
{
Result<uint64_t> result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_TRUE(result.isNone());
result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(10u, result.get());
}
{
Future<std::list<Action> > actions = replica3.read(1, 10);
AWAIT_READY(actions);
EXPECT_EQ(10u, actions.get().size());
foreach (const Action& action, actions.get()) {
ASSERT_TRUE(action.has_type());
ASSERT_EQ(Action::APPEND, action.type());
EXPECT_EQ(stringify(action.position()), action.append().bytes());
}
}
}
TEST_F(CoordinatorTest, Truncate)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
Replica replica2(path2);
Network network;
network.add(replica1.pid());
network.add(replica2.pid());
Coordinator coord(2, &replica1, &network);
{
Result<uint64_t> result = coord.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
for (uint64_t position = 1; position <= 10; position++) {
Result<uint64_t> result =
coord.append(stringify(position), Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Result<uint64_t> result = coord.truncate(7, Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(11u, result.get());
}
{
Future<std::list<Action> > actions = replica1.read(6, 10);
AWAIT_FAILED(actions);
EXPECT_EQ("Bad read range (truncated position)", actions.failure());
}
{
Future<std::list<Action> > actions = replica1.read(7, 10);
AWAIT_READY(actions);
EXPECT_EQ(4u, actions.get().size());
foreach (const Action& action, actions.get()) {
ASSERT_TRUE(action.has_type());
ASSERT_EQ(Action::APPEND, action.type());
EXPECT_EQ(stringify(action.position()), action.append().bytes());
}
}
}
TEST_F(CoordinatorTest, TruncateNotLearnedFill)
{
DROP_MESSAGES(Eq(LearnedMessage().GetTypeName()), _, _);
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
const std::string path3 = os::getcwd() + "/.log3";
Replica replica1(path1);
Replica replica2(path2);
Network network1;
network1.add(replica1.pid());
network1.add(replica2.pid());
Coordinator coord1(2, &replica1, &network1);
{
Result<uint64_t> result = coord1.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
for (uint64_t position = 1; position <= 10; position++) {
Result<uint64_t> result =
coord1.append(stringify(position), Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Result<uint64_t> result = coord1.truncate(7, Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(11u, result.get());
}
Replica replica3(path3);
Network network2;
network2.add(replica2.pid());
network2.add(replica3.pid());
Coordinator coord2(2, &replica3, &network2);
{
Result<uint64_t> result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_TRUE(result.isNone());
result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(11u, result.get());
}
{
Future<std::list<Action> > actions = replica3.read(6, 10);
AWAIT_FAILED(actions);
EXPECT_EQ("Bad read range (truncated position)", actions.failure());
}
{
Future<std::list<Action> > actions = replica3.read(7, 10);
AWAIT_READY(actions);
EXPECT_EQ(4u, actions.get().size());
foreach (const Action& action, actions.get()) {
ASSERT_TRUE(action.has_type());
ASSERT_EQ(Action::APPEND, action.type());
EXPECT_EQ(stringify(action.position()), action.append().bytes());
}
}
}
TEST_F(CoordinatorTest, TruncateLearnedFill)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
const std::string path3 = os::getcwd() + "/.log3";
Replica replica1(path1);
Replica replica2(path2);
Network network1;
network1.add(replica1.pid());
network1.add(replica2.pid());
Coordinator coord1(2, &replica1, &network1);
{
Result<uint64_t> result = coord1.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(0u, result.get());
}
for (uint64_t position = 1; position <= 10; position++) {
Result<uint64_t> result =
coord1.append(stringify(position), Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(position, result.get());
}
{
Result<uint64_t> result = coord1.truncate(7, Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(11u, result.get());
}
Replica replica3(path3);
Network network2;
network2.add(replica2.pid());
network2.add(replica3.pid());
Coordinator coord2(2, &replica3, &network2);
{
Result<uint64_t> result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_TRUE(result.isNone());
result = coord2.elect(Timeout::in(Seconds(10)));
ASSERT_SOME(result);
EXPECT_EQ(11u, result.get());
}
{
Future<std::list<Action> > actions = replica3.read(6, 10);
AWAIT_FAILED(actions);
EXPECT_EQ("Bad read range (truncated position)", actions.failure());
}
{
Future<std::list<Action> > actions = replica3.read(7, 10);
AWAIT_READY(actions);
EXPECT_EQ(4u, actions.get().size());
foreach (const Action& action, actions.get()) {
ASSERT_TRUE(action.has_type());
ASSERT_EQ(Action::APPEND, action.type());
EXPECT_EQ(stringify(action.position()), action.append().bytes());
}
}
}
class LogTest : public TemporaryDirectoryTest {};
TEST_F(LogTest, WriteRead)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
std::set<UPID> pids;
pids.insert(replica1.pid());
Log log(2, path2, pids);
Log::Writer writer(&log, Seconds(10));
Result<Log::Position> position =
writer.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(position);
Log::Reader reader(&log);
Result<std::list<Log::Entry> > entries =
reader.read(position.get(), position.get(), Timeout::in(Seconds(10)));
ASSERT_SOME(entries);
ASSERT_EQ(1u, entries.get().size());
EXPECT_EQ(position.get(), entries.get().front().position);
EXPECT_EQ("hello world", entries.get().front().data);
}
TEST_F(LogTest, Position)
{
const std::string path1 = os::getcwd() + "/.log1";
const std::string path2 = os::getcwd() + "/.log2";
Replica replica1(path1);
std::set<UPID> pids;
pids.insert(replica1.pid());
Log log(2, path2, pids);
Log::Writer writer(&log, Seconds(10));
Result<Log::Position> position =
writer.append("hello world", Timeout::in(Seconds(10)));
ASSERT_SOME(position);
ASSERT_EQ(position.get(), log.position(position.get().identity()));
}
TEST_F(CoordinatorTest, RacingElect) {}
TEST_F(CoordinatorTest, FillNoQuorum) {}
TEST_F(CoordinatorTest, FillInconsistent) {}
TEST_F(CoordinatorTest, LearnedOnOneReplica_NotLearnedOnAnother) {}
TEST_F(CoordinatorTest,
LearnedOnOneReplica_NotLearnedOnAnother_AnotherFailsAndRecovers) {}
|
/*
* @file StUCMException.cpp
* @author Stephen Tramer
*
* @(#)cpp/api:$Id: StUCMException.cxx,v 1.2 2010/03/30 20:05:36 fine Exp $
*
* See StUCMException.h for detals.
*/
#include <string>
#include "StUCMException.h"
//using namespace TxLogging;
StUCMException::StUCMException(const std::string& description,
Severity severity)
: description_(description),
severity_(severity)
{} // EMPTY
StUCMException::StUCMException(Severity severity)
: severity_(severity)
{} // EMPTY
StUCMException::~StUCMException()
{} //EMPTY
std::string
StUCMException::getDescription() const
{
return description_;
}
StUCMException::Severity
StUCMException::getSeverity() const
{
return severity_;
}
void
StUCMException::setDescription(const std::string& desc)
{
description_ = desc;
}
|
/*
* Copyright 2021-2022 Hewlett Packard Enterprise Development LP
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "filesystem_help.h"
#include "./my_strerror_r.h"
#include "chpl/queries/ErrorMessage.h"
#include "chpl/queries/Location.h"
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
namespace chpl {
static std::string my_strerror(int errno_) {
char errbuf[256];
int rc;
errbuf[0] = '\0';
rc = my_strerror_r(errno_, errbuf, sizeof(errbuf));
if (rc != 0)
strncpy(errbuf, "<unknown error>", sizeof(errbuf));
return std::string(errbuf);
}
FILE* openfile(const char* path, const char* mode, ErrorMessage& errorOut) {
FILE* fp = fopen(path, mode);
if (fp == nullptr) {
std::string strerr = my_strerror(errno);
// set errorOut. NULL will be returned.
errorOut = ErrorMessage::build(ID(), Location(), ErrorMessage::ERROR,
"opening %s: %s",
path, strerr.c_str());
}
return fp;
}
bool closefile(FILE* fp, const char* path, ErrorMessage& errorOut) {
int rc = fclose(fp);
if (rc != 0) {
std::string strerr = my_strerror(errno);
errorOut = ErrorMessage::build(ID(), Location(), ErrorMessage::ERROR,
"closing %s: %s",
path, strerr.c_str());
return false;
}
return true;
}
bool readfile(const char* path,
std::string& strOut,
ErrorMessage& errorOut) {
FILE* fp = openfile(path, "r", errorOut);
if (fp == nullptr) {
return false;
}
// Try to get the file length in order to optimize string allocation
long len = 0;
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (len > 0) strOut.reserve(len);
char buf[256];
while (true) {
size_t got = fread(buf, 1, sizeof(buf), fp);
if (got > 0) {
strOut.append(buf, got);
} else {
if (ferror(fp)) {
errorOut = ErrorMessage::build(ID(), Location(), ErrorMessage::ERROR,
"reading %s", path);
ErrorMessage ignored;
closefile(fp, path, ignored);
return false;
}
// otherwise, end of file reached
break;
}
}
bool ok = closefile(fp, path, errorOut);
if (!ok) {
return false;
}
return true;
}
bool fileExists(const char* path) {
struct stat s;
int err = stat(path, &s);
return err == 0;
}
}
|
// Copyright 2017 The Fuchsia 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 <assert.h>
#include <fuchsia/hardware/ethernet/c/banjo.h>
#include <fuchsia/hardware/usb/function/c/banjo.h>
#include <inttypes.h>
#include <lib/sync/completion.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <threads.h>
#include <zircon/compiler.h>
#include <zircon/device/usb-peripheral.h>
#include <zircon/errors.h>
#include <zircon/hw/usb/cdc.h>
#include <zircon/listnode.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <algorithm>
#include <atomic>
#include <memory>
#include <optional>
#include <thread>
#include <ddk/debug.h>
#include <ddk/device.h>
#include <ddk/driver.h>
#include <ddk/metadata.h>
#include <fbl/algorithm.h>
#include <fbl/auto_lock.h>
#include <fbl/mutex.h>
#include <inet6/inet6.h>
#include <usb/usb-request.h>
#include "src/connectivity/ethernet/drivers/usb-cdc-function/usb_cdc-bind.h"
namespace usb_cdc_function {
#define BULK_REQ_SIZE 2048
#define BULK_TX_COUNT 16
#define BULK_RX_COUNT 16
#define INTR_COUNT 8
#define BULK_MAX_PACKET 512 // FIXME(voydanoff) USB 3.0 support
#define INTR_MAX_PACKET sizeof(usb_cdc_speed_change_notification_t)
typedef struct {
zx_device_t* zxdev = nullptr;
usb_function_protocol_t function = {};
list_node_t bulk_out_reqs __TA_GUARDED(tx_mutex) = {}; // list of usb_request_t
list_node_t bulk_in_reqs __TA_GUARDED(rx_mutex) = {}; // list of usb_request_t
list_node_t intr_reqs __TA_GUARDED(intr_mutex) = {}; // list of usb_request_t
list_node_t tx_pending_infos = {}; // list of ethernet_netbuf_t
bool unbound = false; // set to true when device is going away. Guarded by tx_mutex
std::atomic_bool suspending = false; // set to true when the device is suspending
// Device attributes
uint8_t mac_addr[ETH_MAC_SIZE] = {};
// Ethernet lock -- must be acquired after tx_mutex
// when both locks are held.
mtx_t ethernet_mutex = {};
ethernet_ifc_protocol_t ethernet_ifc = {};
bool online = false;
usb_speed_t speed = 0;
// TX lock -- Must be acquired before ethernet_mutex
// when both locks are held.
mtx_t tx_mutex = {};
mtx_t rx_mutex = {};
mtx_t intr_mutex = {};
uint8_t bulk_out_addr = 0;
uint8_t bulk_in_addr = 0;
uint8_t intr_addr = 0;
uint16_t bulk_max_packet = 0;
size_t parent_req_size = 0;
mtx_t pending_request_lock = {};
cnd_t pending_requests_completed = {};
std::atomic_int32_t pending_request_count;
std::atomic_int32_t allocated_requests_count;
sync_completion_t requests_freed_completion;
size_t usb_request_offset = 0;
std::optional<std::thread> suspend_thread;
} usb_cdc_t;
typedef struct txn_info {
ethernet_netbuf_t netbuf;
ethernet_impl_queue_tx_callback completion_cb;
void* cookie;
list_node_t node;
} txn_info_t;
static void complete_txn(txn_info_t* txn, zx_status_t status) {
txn->completion_cb(txn->cookie, status, &txn->netbuf);
}
static struct {
usb_interface_descriptor_t comm_intf;
usb_cs_header_interface_descriptor_t cdc_header;
usb_cs_union_interface_descriptor_1_t cdc_union;
usb_cs_ethernet_interface_descriptor_t cdc_eth;
usb_endpoint_descriptor_t intr_ep;
usb_interface_descriptor_t cdc_intf_0;
usb_interface_descriptor_t cdc_intf_1;
usb_endpoint_descriptor_t bulk_out_ep;
usb_endpoint_descriptor_t bulk_in_ep;
} descriptors = {
.comm_intf =
{
.bLength = sizeof(usb_interface_descriptor_t),
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 0, // set later
.bAlternateSetting = 0,
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ETHERNET,
.bInterfaceProtocol = 0,
.iInterface = 0,
},
.cdc_header =
{
.bLength = sizeof(usb_cs_header_interface_descriptor_t),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_DST_HEADER,
.bcdCDC = 0x120,
},
.cdc_union =
{
.bLength = sizeof(usb_cs_union_interface_descriptor_1_t),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_DST_UNION,
.bControlInterface = 0, // set later
.bSubordinateInterface = 0, // set later
},
.cdc_eth =
{
.bLength = sizeof(usb_cs_ethernet_interface_descriptor_t),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_DST_ETHERNET,
.iMACAddress = 0, // set later
.bmEthernetStatistics = 0,
.wMaxSegmentSize = ETH_MTU,
.wNumberMCFilters = 0,
.bNumberPowerFilters = 0,
},
.intr_ep =
{
.bLength = sizeof(usb_endpoint_descriptor_t),
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 0, // set later
.bmAttributes = USB_ENDPOINT_INTERRUPT,
.wMaxPacketSize = htole16(INTR_MAX_PACKET),
.bInterval = 8,
},
.cdc_intf_0 =
{
.bLength = sizeof(usb_interface_descriptor_t),
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 0, // set later
.bAlternateSetting = 0,
.bNumEndpoints = 0,
.bInterfaceClass = USB_CLASS_CDC,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
.iInterface = 0,
},
.cdc_intf_1 =
{
.bLength = sizeof(usb_interface_descriptor_t),
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 0, // set later
.bAlternateSetting = 1,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
.iInterface = 0,
},
.bulk_out_ep =
{
.bLength = sizeof(usb_endpoint_descriptor_t),
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 0, // set later
.bmAttributes = USB_ENDPOINT_BULK,
.wMaxPacketSize = htole16(BULK_MAX_PACKET),
.bInterval = 0,
},
.bulk_in_ep =
{
.bLength = sizeof(usb_endpoint_descriptor_t),
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 0, // set later
.bmAttributes = USB_ENDPOINT_BULK,
.wMaxPacketSize = htole16(BULK_MAX_PACKET),
.bInterval = 0,
},
};
static void cdc_tx_complete(void* ctx, usb_request_t* req);
static zx_status_t instrumented_request_alloc(void* ctx, usb_request_t** out, uint64_t data_size,
uint8_t ep_address, size_t req_size) {
usb_cdc_t* cdc = static_cast<usb_cdc_t*>(ctx);
cdc->allocated_requests_count++;
return usb_request_alloc(out, data_size, ep_address, req_size);
}
static void instrumented_request_release(void* ctx, usb_request_t* req) {
usb_cdc_t* cdc = static_cast<usb_cdc_t*>(ctx);
usb_request_release(req);
cdc->allocated_requests_count--;
if (cdc->suspending && (cdc->allocated_requests_count.load() == 0)) {
sync_completion_signal(&cdc->requests_freed_completion);
}
}
zx_status_t insert_usb_request(void* ctx, list_node_t* list, usb_request_t* req,
size_t parent_req_size, bool tail = true) {
usb_cdc_t* cdc = static_cast<usb_cdc_t*>(ctx);
if (cdc->suspending) {
instrumented_request_release(ctx, req);
return ZX_OK;
}
if (tail) {
return usb_req_list_add_tail(list, req, parent_req_size);
} else {
return usb_req_list_add_head(list, req, parent_req_size);
}
}
static void usb_request_callback(void* ctx, usb_request_t* req) {
usb_cdc_t* cdc = static_cast<usb_cdc_t*>(ctx);
if (cdc->suspending) {
instrumented_request_release(ctx, req);
return;
}
// Invoke the real completion if not shutting down.
if (!cdc->unbound) {
usb_request_complete_t completion;
memcpy(&completion, reinterpret_cast<unsigned char*>(req) + cdc->usb_request_offset,
sizeof(completion));
completion.callback(completion.ctx, req);
}
int value = --cdc->pending_request_count;
if (value == 0) {
mtx_lock(&cdc->pending_request_lock);
cnd_signal(&cdc->pending_requests_completed);
mtx_unlock(&cdc->pending_request_lock);
}
}
static void usb_request_queue(void* ctx, usb_function_protocol_t* function, usb_request_t* req,
const usb_request_complete_t* completion) {
usb_cdc_t* cdc = static_cast<usb_cdc_t*>(ctx);
if (cdc->suspending) {
instrumented_request_release(ctx, req);
return;
}
mtx_lock(&cdc->pending_request_lock);
if (cdc->unbound) {
mtx_unlock(&cdc->pending_request_lock);
return;
}
cdc->pending_request_count++;
mtx_unlock(&cdc->pending_request_lock);
usb_request_complete_t internal_completion;
internal_completion.callback = usb_request_callback;
internal_completion.ctx = ctx;
memcpy(reinterpret_cast<unsigned char*>(req) + cdc->usb_request_offset, completion,
sizeof(*completion));
usb_function_request_queue(function, req, &internal_completion);
}
static zx_status_t cdc_generate_mac_address(zx_device_t* parent, usb_cdc_t* cdc) {
size_t actual;
auto status = device_get_metadata(parent, DEVICE_METADATA_MAC_ADDRESS, &cdc->mac_addr,
sizeof(cdc->mac_addr), &actual);
if (status != ZX_OK || actual != sizeof(cdc->mac_addr)) {
zxlogf(WARNING, "CDC: MAC address metadata not found. Generating random address");
zx_cprng_draw(cdc->mac_addr, sizeof(cdc->mac_addr));
cdc->mac_addr[0] = 0x02;
}
char buffer[sizeof(cdc->mac_addr) * 3];
snprintf(buffer, sizeof(buffer), "%02X%02X%02X%02X%02X%02X", cdc->mac_addr[0], cdc->mac_addr[1],
cdc->mac_addr[2], cdc->mac_addr[3], cdc->mac_addr[4], cdc->mac_addr[5]);
// Make the host and device addresses different so packets are routed correctly.
cdc->mac_addr[5] ^= 1;
return usb_function_alloc_string_desc(&cdc->function, buffer, &descriptors.cdc_eth.iMACAddress);
}
static zx_status_t cdc_ethernet_impl_query(void* ctx, uint32_t options, ethernet_info_t* info) {
zxlogf(DEBUG, "%s:", __func__);
auto* cdc = static_cast<usb_cdc_t*>(ctx);
// No options are supported
if (options) {
zxlogf(ERROR, "%s: unexpected options (0x%" PRIx32 ") to ethernet_impl_query", __func__,
options);
return ZX_ERR_INVALID_ARGS;
}
memset(info, 0, sizeof(*info));
info->mtu = ETH_MTU;
memcpy(info->mac, cdc->mac_addr, sizeof(cdc->mac_addr));
info->netbuf_size = sizeof(txn_info_t);
return ZX_OK;
}
static void cdc_ethernet_impl_stop(void* cookie) {
zxlogf(DEBUG, "%s:", __func__);
auto* cdc = static_cast<usb_cdc_t*>(cookie);
mtx_lock(&cdc->tx_mutex);
mtx_lock(&cdc->ethernet_mutex);
cdc->ethernet_ifc.ops = NULL;
mtx_unlock(&cdc->ethernet_mutex);
mtx_unlock(&cdc->tx_mutex);
}
static zx_status_t cdc_ethernet_impl_start(void* ctx_cookie, const ethernet_ifc_protocol_t* ifc) {
zxlogf(DEBUG, "%s:", __func__);
auto* cdc = static_cast<usb_cdc_t*>(ctx_cookie);
zx_status_t status = ZX_OK;
if (cdc->unbound) {
return ZX_ERR_BAD_STATE;
}
mtx_lock(&cdc->ethernet_mutex);
if (cdc->ethernet_ifc.ops) {
status = ZX_ERR_ALREADY_BOUND;
} else {
cdc->ethernet_ifc = *ifc;
ethernet_ifc_status(&cdc->ethernet_ifc, cdc->online ? ETHERNET_STATUS_ONLINE : 0);
}
mtx_unlock(&cdc->ethernet_mutex);
return status;
}
static zx_status_t cdc_send_locked(usb_cdc_t* cdc, ethernet_netbuf_t* netbuf) {
if (!cdc->ethernet_ifc.ops) {
return ZX_ERR_BAD_STATE;
}
const auto* byte_data = static_cast<const uint8_t*>(netbuf->data_buffer);
size_t length = netbuf->data_size;
// Make sure that we can get all of the tx buffers we need to use
usb_request_t* tx_req = usb_req_list_remove_head(&cdc->bulk_in_reqs, cdc->parent_req_size);
if (tx_req == NULL) {
return ZX_ERR_SHOULD_WAIT;
}
// Send data
tx_req->header.length = length;
ssize_t bytes_copied = usb_request_copy_to(tx_req, byte_data, tx_req->header.length, 0);
if (bytes_copied < 0) {
zxlogf(SERIAL, "%s: failed to copy data into send req (error %zd)", __func__, bytes_copied);
zx_status_t status = insert_usb_request(cdc, &cdc->bulk_in_reqs, tx_req, cdc->parent_req_size);
ZX_DEBUG_ASSERT(status == ZX_OK);
return ZX_ERR_INTERNAL;
}
usb_request_complete_t complete = {
.callback = cdc_tx_complete,
.ctx = cdc,
};
usb_request_queue(cdc, &cdc->function, tx_req, &complete);
return ZX_OK;
}
static void cdc_ethernet_impl_queue_tx(void* context, uint32_t options, ethernet_netbuf_t* netbuf,
ethernet_impl_queue_tx_callback completion_cb,
void* cookie) {
auto* cdc = static_cast<usb_cdc_t*>(context);
size_t length = netbuf->data_size;
zx_status_t status;
txn_info_t* txn = containerof(netbuf, txn_info_t, netbuf);
txn->completion_cb = completion_cb;
txn->cookie = cookie;
if (!cdc->online || length > ETH_MTU || length == 0 || cdc->unbound) {
complete_txn(txn, ZX_ERR_INVALID_ARGS);
return;
}
zxlogf(SERIAL, "%s: sending %zu bytes", __func__, length);
mtx_lock(&cdc->tx_mutex);
if (cdc->unbound || cdc->suspending) {
status = ZX_ERR_IO_NOT_PRESENT;
} else {
status = cdc_send_locked(cdc, netbuf);
if (status == ZX_ERR_SHOULD_WAIT) {
// No buffers available, queue it up
txn_info_t* txn = containerof(netbuf, txn_info_t, netbuf);
list_add_tail(&cdc->tx_pending_infos, &txn->node);
}
}
mtx_unlock(&cdc->tx_mutex);
if (status != ZX_ERR_SHOULD_WAIT) {
complete_txn(txn, status);
}
}
static zx_status_t cdc_ethernet_impl_set_param(void* cookie, uint32_t param, int32_t value,
const uint8_t* data, size_t data_size) {
return ZX_ERR_NOT_SUPPORTED;
}
static ethernet_impl_protocol_ops_t ethernet_impl_ops = []() {
ethernet_impl_protocol_ops_t ops = {};
ops.query = cdc_ethernet_impl_query;
ops.stop = cdc_ethernet_impl_stop;
ops.start = cdc_ethernet_impl_start;
ops.queue_tx = cdc_ethernet_impl_queue_tx;
ops.set_param = cdc_ethernet_impl_set_param;
return ops;
}();
static void cdc_intr_complete(void* ctx, usb_request_t* req) {
auto* cdc = static_cast<usb_cdc_t*>(ctx);
zxlogf(SERIAL, "%s %d %ld", __func__, req->response.status, req->response.actual);
mtx_lock(&cdc->intr_mutex);
if (cdc->suspending) {
instrumented_request_release(ctx, req);
} else {
zx_status_t status = insert_usb_request(ctx, &cdc->intr_reqs, req, cdc->parent_req_size);
ZX_DEBUG_ASSERT(status == ZX_OK);
}
mtx_unlock(&cdc->intr_mutex);
}
static void cdc_send_notifications(usb_cdc_t* cdc) {
usb_request_t* req;
usb_cdc_notification_t network_notification = {
.bmRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
.bNotification = USB_CDC_NC_NETWORK_CONNECTION,
.wValue = cdc->online,
.wIndex = descriptors.cdc_intf_0.bInterfaceNumber,
.wLength = 0,
};
usb_cdc_speed_change_notification_t speed_notification = {
.notification =
{
.bmRequestType = USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
.bNotification = USB_CDC_NC_CONNECTION_SPEED_CHANGE,
.wValue = 0,
.wIndex = descriptors.cdc_intf_0.bInterfaceNumber,
.wLength = 2 * sizeof(uint32_t),
},
.downlink_br = 0,
.uplink_br = 0,
};
if (cdc->online) {
if (cdc->speed == USB_SPEED_SUPER) {
// Claim to be gigabit speed.
speed_notification.downlink_br = speed_notification.uplink_br = 1000 * 1000 * 1000;
} else {
// Claim to be 100 megabit speed.
speed_notification.downlink_br = speed_notification.uplink_br = 100 * 1000 * 1000;
}
} else {
speed_notification.downlink_br = speed_notification.uplink_br = 0;
}
mtx_lock(&cdc->intr_mutex);
req = usb_req_list_remove_head(&cdc->intr_reqs, cdc->parent_req_size);
mtx_unlock(&cdc->intr_mutex);
if (!req) {
zxlogf(ERROR, "%s: no interrupt request available", __func__);
return;
}
auto result = usb_request_copy_to(req, &network_notification, sizeof(network_notification), 0);
ZX_ASSERT(result == sizeof(network_notification));
req->header.length = sizeof(network_notification);
usb_request_complete_t complete = {
.callback = cdc_intr_complete,
.ctx = cdc,
};
usb_request_queue(cdc, &cdc->function, req, &complete);
mtx_lock(&cdc->intr_mutex);
req = usb_req_list_remove_head(&cdc->intr_reqs, cdc->parent_req_size);
mtx_unlock(&cdc->intr_mutex);
if (!req) {
zxlogf(ERROR, "%s: no interrupt request available", __func__);
return;
}
result = usb_request_copy_to(req, &speed_notification, sizeof(speed_notification), 0);
ZX_ASSERT(result == sizeof(speed_notification));
req->header.length = sizeof(speed_notification);
usb_request_queue(cdc, &cdc->function, req, &complete);
}
static void cdc_rx_complete(void* ctx, usb_request_t* req) {
auto* cdc = static_cast<usb_cdc_t*>(ctx);
zxlogf(SERIAL, "%s %d %ld", __func__, req->response.status, req->response.actual);
if (req->response.status == ZX_ERR_IO_NOT_PRESENT) {
mtx_lock(&cdc->rx_mutex);
zx_status_t status =
insert_usb_request(ctx, &cdc->bulk_out_reqs, req, cdc->parent_req_size, false);
ZX_DEBUG_ASSERT(status == ZX_OK);
mtx_unlock(&cdc->rx_mutex);
return;
}
if (req->response.status != ZX_OK) {
zxlogf(ERROR, "%s: usb_read_complete called with status %d", __func__, req->response.status);
}
if (req->response.status == ZX_OK) {
mtx_lock(&cdc->ethernet_mutex);
if (cdc->ethernet_ifc.ops) {
void* data = NULL;
usb_request_mmap(req, &data);
ethernet_ifc_recv(&cdc->ethernet_ifc, reinterpret_cast<uint8_t*>(data), req->response.actual,
0);
}
mtx_unlock(&cdc->ethernet_mutex);
}
usb_request_complete_t complete = {
.callback = cdc_rx_complete,
.ctx = cdc,
};
usb_request_queue(cdc, &cdc->function, req, &complete);
}
static void cdc_tx_complete(void* ctx, usb_request_t* req) {
auto* cdc = static_cast<usb_cdc_t*>(ctx);
zxlogf(SERIAL, "%s %d %ld", __func__, req->response.status, req->response.actual);
if (cdc->unbound) {
return;
}
mtx_lock(&cdc->tx_mutex);
{
if (cdc->suspending) {
mtx_unlock(&cdc->tx_mutex);
instrumented_request_release(ctx, req);
return;
}
zx_status_t status = insert_usb_request(ctx, &cdc->bulk_in_reqs, req, cdc->parent_req_size);
ZX_DEBUG_ASSERT(status == ZX_OK);
}
bool additional_tx_queued = false;
txn_info_t* txn;
zx_status_t send_status = ZX_OK;
if ((txn = list_peek_head_type(&cdc->tx_pending_infos, txn_info_t, node))) {
if ((send_status = cdc_send_locked(cdc, &txn->netbuf)) != ZX_ERR_SHOULD_WAIT) {
list_remove_head(&cdc->tx_pending_infos);
additional_tx_queued = true;
}
}
mtx_unlock(&cdc->tx_mutex);
if (additional_tx_queued) {
mtx_lock(&cdc->ethernet_mutex);
complete_txn(txn, send_status);
mtx_unlock(&cdc->ethernet_mutex);
}
}
static size_t cdc_get_descriptors_size(void* ctx) { return sizeof(descriptors); }
static void cdc_get_descriptors(void* ctx, uint8_t* buffer, size_t buffer_size,
size_t* out_actual) {
const size_t length = std::min(sizeof(descriptors), buffer_size);
memcpy(buffer, &descriptors, length);
*out_actual = length;
}
static zx_status_t cdc_control(void* ctx, const usb_setup_t* setup, const uint8_t* write_buffer,
size_t write_size, uint8_t* out_read_buffer, size_t read_size,
size_t* out_read_actual) {
if (out_read_actual != NULL) {
*out_read_actual = 0;
}
zxlogf(DEBUG, "%s", __func__);
// USB_CDC_SET_ETHERNET_PACKET_FILTER is the only control request required by the spec
if (setup->bmRequestType == (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) &&
setup->bRequest == USB_CDC_SET_ETHERNET_PACKET_FILTER) {
zxlogf(DEBUG, "%s: USB_CDC_SET_ETHERNET_PACKET_FILTER", __func__);
// TODO(voydanoff) implement the requested packet filtering
return ZX_OK;
}
return ZX_ERR_NOT_SUPPORTED;
}
static zx_status_t cdc_set_configured(void* ctx, bool configured, usb_speed_t speed) {
zxlogf(INFO, "%s: %d %d", __func__, configured, speed);
auto* cdc = static_cast<usb_cdc_t*>(ctx);
zx_status_t status;
mtx_lock(&cdc->ethernet_mutex);
cdc->online = false;
if (cdc->ethernet_ifc.ops) {
ethernet_ifc_status(&cdc->ethernet_ifc, 0);
}
mtx_unlock(&cdc->ethernet_mutex);
if (configured) {
if ((status = usb_function_config_ep(&cdc->function, &descriptors.intr_ep, NULL)) != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_config_ep failed", __func__);
return status;
}
cdc->speed = speed;
} else {
usb_function_disable_ep(&cdc->function, cdc->bulk_out_addr);
usb_function_disable_ep(&cdc->function, cdc->bulk_in_addr);
usb_function_disable_ep(&cdc->function, cdc->intr_addr);
cdc->speed = USB_SPEED_UNDEFINED;
}
cdc_send_notifications(cdc);
return ZX_OK;
}
static zx_status_t cdc_set_interface(void* ctx, uint8_t interface, uint8_t alt_setting) {
zxlogf(INFO, "%s: %d %d", __func__, interface, alt_setting);
auto* cdc = static_cast<usb_cdc_t*>(ctx);
zx_status_t status;
if (interface != descriptors.cdc_intf_0.bInterfaceNumber || alt_setting > 1) {
return ZX_ERR_INVALID_ARGS;
}
// TODO(voydanoff) fullspeed and superspeed support
if (alt_setting) {
if ((status = usb_function_config_ep(&cdc->function, &descriptors.bulk_out_ep, NULL)) !=
ZX_OK ||
(status = usb_function_config_ep(&cdc->function, &descriptors.bulk_in_ep, NULL)) != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_config_ep failed", __func__);
}
} else {
if ((status = usb_function_disable_ep(&cdc->function, cdc->bulk_out_addr)) != ZX_OK ||
(status = usb_function_disable_ep(&cdc->function, cdc->bulk_in_addr)) != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_disable_ep failed", __func__);
}
}
bool online = false;
if (alt_setting && status == ZX_OK) {
online = true;
// queue our OUT reqs
mtx_lock(&cdc->rx_mutex);
usb_request_t* req;
while ((req = usb_req_list_remove_head(&cdc->bulk_out_reqs, cdc->parent_req_size)) != NULL) {
usb_request_complete_t complete = {
.callback = cdc_rx_complete,
.ctx = cdc,
};
usb_request_queue(cdc, &cdc->function, req, &complete);
}
mtx_unlock(&cdc->rx_mutex);
}
mtx_lock(&cdc->ethernet_mutex);
cdc->online = online;
if (cdc->ethernet_ifc.ops) {
ethernet_ifc_status(&cdc->ethernet_ifc, online ? ETHERNET_STATUS_ONLINE : 0);
}
mtx_unlock(&cdc->ethernet_mutex);
// send status notifications on interrupt endpoint
cdc_send_notifications(cdc);
return status;
}
usb_function_interface_protocol_ops_t device_ops = {
.get_descriptors_size = cdc_get_descriptors_size,
.get_descriptors = cdc_get_descriptors,
.control = cdc_control,
.set_configured = cdc_set_configured,
.set_interface = cdc_set_interface,
};
static void usb_cdc_unbind(void* ctx) {
zxlogf(DEBUG, "%s", __func__);
auto* cdc = static_cast<usb_cdc_t*>(ctx);
{
fbl::AutoLock l(&cdc->tx_mutex);
cdc->unbound = true;
}
{
fbl::AutoLock l(&cdc->pending_request_lock);
while (cdc->pending_request_count) {
cnd_wait(&cdc->pending_requests_completed, &cdc->pending_request_lock);
}
}
{
fbl::AutoLock l(&cdc->tx_mutex);
txn_info_t* txn;
while ((txn = list_remove_head_type(&cdc->tx_pending_infos, txn_info_t, node)) != NULL) {
complete_txn(txn, ZX_ERR_PEER_CLOSED);
}
}
device_unbind_reply(cdc->zxdev);
}
static void usb_cdc_release(void* ctx) {
zxlogf(DEBUG, "%s", __func__);
auto* cdc = static_cast<usb_cdc_t*>(ctx);
usb_request_t* req;
while ((req = usb_req_list_remove_head(&cdc->bulk_out_reqs, cdc->parent_req_size)) != NULL) {
instrumented_request_release(ctx, req);
}
while ((req = usb_req_list_remove_head(&cdc->bulk_in_reqs, cdc->parent_req_size)) != NULL) {
instrumented_request_release(ctx, req);
}
while ((req = usb_req_list_remove_head(&cdc->intr_reqs, cdc->parent_req_size)) != NULL) {
instrumented_request_release(ctx, req);
}
mtx_destroy(&cdc->ethernet_mutex);
mtx_destroy(&cdc->tx_mutex);
mtx_destroy(&cdc->rx_mutex);
mtx_destroy(&cdc->intr_mutex);
if (cdc->suspend_thread.has_value()) {
cdc->suspend_thread->join();
}
delete cdc;
}
static void usb_cdc_suspend(void* ctx, uint8_t requested_state, bool enable_wake,
uint8_t suspend_reason) {
auto* cdc = static_cast<usb_cdc_t*>(ctx);
cdc->suspend_thread.emplace([cdc]() {
// Start the suspend process by setting the suspend bool to true
// When the pipeline tries to submit requests, they will be immediately
// free'd.
cdc->suspending = true;
// Disable endpoints to prevent new requests present in our
// pipeline from getting queued.
usb_function_disable_ep(&cdc->function, cdc->bulk_out_addr);
usb_function_disable_ep(&cdc->function, cdc->bulk_in_addr);
usb_function_disable_ep(&cdc->function, cdc->intr_addr);
// Cancel all requests in the pipeline -- the completion handler
// will free these requests as they come in.
usb_function_cancel_all(&cdc->function, cdc->intr_addr);
usb_function_cancel_all(&cdc->function, cdc->bulk_out_addr);
usb_function_cancel_all(&cdc->function, cdc->bulk_in_addr);
// Requests external to us should have been returned (or in the process of being returned)
// at this point. Acquire all the locks to ensure that nothing touches any of
// our request lists, and complete all requests. If an ongoing transaction
// tries to add to one of these lists, since suspending was set to true,
// the request will be free'd instead.
list_node_t bulk_out_reqs;
list_node_t bulk_in_reqs;
list_node_t intr_reqs;
{
mtx_lock(&cdc->intr_mutex);
list_move(&cdc->intr_reqs, &intr_reqs);
mtx_unlock(&cdc->intr_mutex);
mtx_lock(&cdc->rx_mutex);
list_move(&cdc->bulk_out_reqs, &bulk_out_reqs);
mtx_unlock(&cdc->rx_mutex);
mtx_lock(&cdc->tx_mutex);
list_move(&cdc->bulk_in_reqs, &bulk_in_reqs);
mtx_unlock(&cdc->tx_mutex);
}
usb_request_t* req;
while ((req = usb_req_list_remove_head(&bulk_out_reqs, cdc->parent_req_size)) != NULL) {
instrumented_request_release(cdc, req);
}
while ((req = usb_req_list_remove_head(&bulk_in_reqs, cdc->parent_req_size)) != NULL) {
instrumented_request_release(cdc, req);
}
while ((req = usb_req_list_remove_head(&intr_reqs, cdc->parent_req_size)) != NULL) {
instrumented_request_release(cdc, req);
}
// Wait for all the requests in the pipeline to asynchronously fail.
// Either the completion routine or the submitter should free the requests.
// It shouldn't be possible to have any "stray" requests that aren't in-flight at this point,
// so this is guaranteed to complete.
sync_completion_wait(&cdc->requests_freed_completion, ZX_TIME_INFINITE);
list_node_t list;
{
fbl::AutoLock l(&cdc->tx_mutex);
list_move(&cdc->tx_pending_infos, &list);
}
txn_info_t* txn;
while ((txn = list_remove_head_type(&list, txn_info_t, node)) != NULL) {
complete_txn(txn, ZX_ERR_PEER_CLOSED);
}
device_suspend_reply(cdc->zxdev, ZX_OK, 0);
});
}
static zx_protocol_device_t usb_cdc_proto = []() {
zx_protocol_device_t dev = {};
dev.version = DEVICE_OPS_VERSION;
dev.unbind = usb_cdc_unbind;
dev.release = usb_cdc_release;
dev.suspend = usb_cdc_suspend;
return dev;
}();
zx_status_t usb_cdc_bind(void* ctx, zx_device_t* parent) {
zxlogf(INFO, "%s", __func__);
device_add_args_t args = {};
auto cdc = std::make_unique<usb_cdc_t>();
if (!cdc) {
return ZX_ERR_NO_MEMORY;
}
zx_status_t status = device_get_protocol(parent, ZX_PROTOCOL_USB_FUNCTION, &cdc->function);
if (status != ZX_OK) {
return status;
}
cnd_init(&cdc->pending_requests_completed);
list_initialize(&cdc->bulk_out_reqs);
list_initialize(&cdc->bulk_in_reqs);
list_initialize(&cdc->intr_reqs);
list_initialize(&cdc->tx_pending_infos);
mtx_init(&cdc->ethernet_mutex, mtx_plain);
mtx_init(&cdc->tx_mutex, mtx_plain);
mtx_init(&cdc->rx_mutex, mtx_plain);
mtx_init(&cdc->intr_mutex, mtx_plain);
cdc->bulk_max_packet = BULK_MAX_PACKET; // FIXME(voydanoff) USB 3.0 support
cdc->parent_req_size = usb_function_get_request_size(&cdc->function);
uint64_t req_size =
cdc->parent_req_size + sizeof(usb_req_internal_t) + sizeof(usb_request_complete_t);
cdc->usb_request_offset = cdc->parent_req_size + sizeof(usb_req_internal_t);
status = usb_function_alloc_interface(&cdc->function, &descriptors.comm_intf.bInterfaceNumber);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_alloc_interface failed", __func__);
goto fail;
}
status = usb_function_alloc_interface(&cdc->function, &descriptors.cdc_intf_0.bInterfaceNumber);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_alloc_interface failed", __func__);
goto fail;
}
descriptors.cdc_intf_1.bInterfaceNumber = descriptors.cdc_intf_0.bInterfaceNumber;
descriptors.cdc_union.bControlInterface = descriptors.comm_intf.bInterfaceNumber;
descriptors.cdc_union.bSubordinateInterface = descriptors.cdc_intf_0.bInterfaceNumber;
status = usb_function_alloc_ep(&cdc->function, USB_DIR_OUT, &cdc->bulk_out_addr);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_alloc_ep failed", __func__);
goto fail;
}
status = usb_function_alloc_ep(&cdc->function, USB_DIR_IN, &cdc->bulk_in_addr);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_alloc_ep failed", __func__);
goto fail;
}
status = usb_function_alloc_ep(&cdc->function, USB_DIR_IN, &cdc->intr_addr);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: usb_function_alloc_ep failed", __func__);
goto fail;
}
descriptors.bulk_out_ep.bEndpointAddress = cdc->bulk_out_addr;
descriptors.bulk_in_ep.bEndpointAddress = cdc->bulk_in_addr;
descriptors.intr_ep.bEndpointAddress = cdc->intr_addr;
status = cdc_generate_mac_address(parent, cdc.get());
if (status != ZX_OK) {
goto fail;
}
// allocate bulk out usb requests
usb_request_t* req;
for (int i = 0; i < BULK_TX_COUNT; i++) {
status =
instrumented_request_alloc(cdc.get(), &req, BULK_REQ_SIZE, cdc->bulk_out_addr, req_size);
if (status != ZX_OK) {
goto fail;
}
status = usb_req_list_add_head(&cdc->bulk_out_reqs, req, cdc->parent_req_size);
ZX_DEBUG_ASSERT(status == ZX_OK);
}
// allocate bulk in usb requests
for (int i = 0; i < BULK_RX_COUNT; i++) {
status =
instrumented_request_alloc(cdc.get(), &req, BULK_REQ_SIZE, cdc->bulk_in_addr, req_size);
if (status != ZX_OK) {
goto fail;
}
// As per the CDC-ECM spec, we need to send a zero-length packet to signify the end of
// transmission when the endpoint max packet size is a factor of the total transmission size
req->header.send_zlp = true;
status = usb_req_list_add_head(&cdc->bulk_in_reqs, req, cdc->parent_req_size);
ZX_DEBUG_ASSERT(status == ZX_OK);
}
// allocate interrupt requests
for (int i = 0; i < INTR_COUNT; i++) {
status = instrumented_request_alloc(cdc.get(), &req, INTR_MAX_PACKET, cdc->intr_addr, req_size);
if (status != ZX_OK) {
goto fail;
}
status = usb_req_list_add_head(&cdc->intr_reqs, req, cdc->parent_req_size);
ZX_DEBUG_ASSERT(status == ZX_OK);
}
args.version = DEVICE_ADD_ARGS_VERSION;
args.name = "cdc-eth-function";
args.ctx = cdc.get();
args.ops = &usb_cdc_proto;
args.proto_id = ZX_PROTOCOL_ETHERNET_IMPL;
args.proto_ops = ðernet_impl_ops;
status = device_add(parent, &args, &cdc->zxdev);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: add_device failed %d", __func__, status);
goto fail;
}
usb_function_set_interface(&cdc->function, cdc.get(), &device_ops);
{
// The DDK now owns this reference.
__UNUSED auto released = cdc.release();
}
return ZX_OK;
fail:
usb_cdc_release(cdc.get());
return status;
}
static constexpr zx_driver_ops_t driver_ops = []() {
zx_driver_ops_t ops = {};
ops.version = DRIVER_OPS_VERSION;
ops.bind = usb_cdc_bind;
return ops;
}();
} // namespace usb_cdc_function
// clang-format off
ZIRCON_DRIVER(usb_cdc, usb_cdc_function::driver_ops, "zircon", "0.1");
|
#pragma once
#include "Headers.hpp"
LPVOID WINAPIV memset(LPVOID dst,INT val,size_t count);
LPVOID WINAPIV memcpy(LPVOID dst,LPCVOID src,size_t count);
INT WINAPIV _purecall();
|
/** \file
* \brief Implementation of class NodeRespecterLayout.
*
* Force-directed layout algorithm respecting the height and width of nodes,
* aiming to minimize node overlaps as well as edges crossing through
* non-incident nodes.
*
* \author Max Ilsen
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/basic/simple_graph_alg.h>
#include <ogdf/energybased/NodeRespecterLayout.h>
#include <ogdf/packing/TileToRowsCCPacker.h>
//#define OGDF_NODERESPECTERLAYOUT_DEBUG
namespace ogdf {
NodeRespecterLayout::NodeRespecterLayout()
: m_randomInitialPlacement(true)
, m_postProcessing(PostProcessingMode::Complete)
, m_bendNormalizationAngle(Math::pi)
, m_numberOfIterations(30000)
, m_minimalTemperature(1.0)
, m_initialTemperature(10.0)
, m_temperatureDecreaseOffset(0.0)
, m_gravitation(1.0/16.0)
, m_oscillationAngle(Math::pi_2)
, m_desiredMinEdgeLength(LayoutStandards::defaultNodeSeparation())
, m_initDummiesPerEdge(1)
, m_maxDummiesPerEdge(3)
, m_dummyInsertionThreshold(5)
, m_maxDisturbance(0)
, m_repulsionDistance(2*m_desiredMinEdgeLength)
, m_minDistCC(LayoutStandards::defaultCCSeparation())
, m_pageRatio(1.0)
{ }
void NodeRespecterLayout::setRandomInitialPlacement(bool randomInitialPlacement)
{
m_randomInitialPlacement = randomInitialPlacement;
}
void NodeRespecterLayout::setPostProcessing(PostProcessingMode postProcessing)
{
m_postProcessing = postProcessing;
}
void NodeRespecterLayout::setBendNormalizationAngle(double bendNormalizationAngle)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(bendNormalizationAngle, 0.0));
OGDF_ASSERT(OGDF_GEOM_ET.leq(bendNormalizationAngle, Math::pi));
m_bendNormalizationAngle = bendNormalizationAngle;
}
void NodeRespecterLayout::setNumberOfIterations(int numberOfIterations)
{
OGDF_ASSERT(numberOfIterations >= 0);
m_numberOfIterations = numberOfIterations;
}
void NodeRespecterLayout::setMinimalTemperature(double minimalTemperature)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(minimalTemperature, 0.0));
m_minimalTemperature = minimalTemperature;
}
void NodeRespecterLayout::setInitialTemperature(double initialTemperature)
{
OGDF_ASSERT(OGDF_GEOM_ET.greater(initialTemperature, m_minimalTemperature));
m_initialTemperature = initialTemperature;
}
void NodeRespecterLayout::setTemperatureDecreaseOffset(double temperatureDecreaseOffset)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(temperatureDecreaseOffset, 0.0));
OGDF_ASSERT(OGDF_GEOM_ET.leq(temperatureDecreaseOffset, 1.0));
m_temperatureDecreaseOffset = temperatureDecreaseOffset;
}
void NodeRespecterLayout::setGravitation(double gravitation)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(gravitation, 0.0));
m_gravitation = gravitation;
}
void NodeRespecterLayout::setOscillationAngle(double oscillationAngle)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(oscillationAngle, 0.0));
OGDF_ASSERT(OGDF_GEOM_ET.leq(oscillationAngle, Math::pi));
m_oscillationAngle = oscillationAngle;
}
void NodeRespecterLayout::setDesiredMinEdgeLength(double desiredMinEdgeLength)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(desiredMinEdgeLength, 0.0));
m_desiredMinEdgeLength = desiredMinEdgeLength;
}
void NodeRespecterLayout::setInitDummiesPerEdge(int initDummiesPerEdge)
{
OGDF_ASSERT(initDummiesPerEdge >= 0);
m_initDummiesPerEdge = initDummiesPerEdge;
}
void NodeRespecterLayout::setMaxDummiesPerEdge(int maxDummiesPerEdge)
{
OGDF_ASSERT(maxDummiesPerEdge >= m_initDummiesPerEdge);
m_maxDummiesPerEdge = maxDummiesPerEdge;
}
void NodeRespecterLayout::setDummyInsertionThreshold(double dummyInsertionThreshold)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(dummyInsertionThreshold, 1.0));
m_dummyInsertionThreshold = dummyInsertionThreshold;
}
void NodeRespecterLayout::setMaxDisturbance(double maxDisturbance)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(maxDisturbance, 0.0));
m_maxDisturbance = maxDisturbance;
}
void NodeRespecterLayout::setRepulsionDistance(double repulsionDistance)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(repulsionDistance, 0.0));
m_repulsionDistance = repulsionDistance;
}
void NodeRespecterLayout::setMinDistCC(double minDistCC)
{
OGDF_ASSERT(OGDF_GEOM_ET.geq(minDistCC, 0.0));
m_minDistCC = minDistCC;
}
void NodeRespecterLayout::setPageRatio(double pageRatio)
{
OGDF_ASSERT(OGDF_GEOM_ET.greater(pageRatio, 0.0));
m_pageRatio = pageRatio;
}
void NodeRespecterLayout::initData()
{
m_impulseX.init(m_copy, 0);
m_impulseY.init(m_copy, 0);
m_localTemperature.init(m_copy, m_initialTemperature);
m_nodeRadius.init(m_copy, 0.0);
m_desiredDistance.init(m_copy);
m_degreeSum = m_copy.numberOfEdges() == 0 ? 1 : m_copy.numberOfEdges() * 2;
m_barycenterX = 0;
m_barycenterY = 0;
m_iterCounter = m_numberOfIterations;
m_globalTemperature = m_initialTemperature;
m_factor = m_temperatureDecreaseOffset <= 0.0 ? 0.0 :
(m_initialTemperature - m_minimalTemperature) /
(m_numberOfIterations * m_temperatureDecreaseOffset);
m_cos = cos(m_oscillationAngle / 2.0);
}
void NodeRespecterLayout::freeData()
{
m_impulseX.init();
m_impulseY.init();
m_localTemperature.init();
m_nodeRadius.init();
m_desiredDistance.init();
}
void NodeRespecterLayout::createBends(const ArrayBuffer<edge> &origEdges, GraphAttributes &attr)
{
DPoint inter;
// Get bounding rectangles of all nodes.
NodeArray<DRect> nodeRects(m_copy);
if (m_postProcessing != PostProcessingMode::None) {
m_copyAttr.nodeBoundingBoxes(nodeRects);
}
auto toSegment = [&](node v, node w) {
return DSegment(m_copyAttr.x(v), m_copyAttr.y(v),
m_copyAttr.x(w), m_copyAttr.y(w));
};
// For all dummy nodes (in the correct order for each edge):
for (edge eOrig : origEdges) {
DPolyline &bendLine = attr.bends(eOrig);
List<edge> chain = m_copy.chain(eOrig);
node last = chain.popFrontRet()->source();
for (edge e : chain) {
// Get last --> v --> next where v is a dummy node.
node v = e->source();
node next = e->target();
#ifdef OGDF_DEBUG
OGDF_ASSERT(m_copy.isDummy(v));
#endif
DSegment segmentLastNext = toSegment(last, next);
DSegment segmentLastV = toSegment(last, v);
DSegment segmentVNext = toSegment(v, next);
if (m_postProcessing == PostProcessingMode::Complete ||
(m_postProcessing == PostProcessingMode::KeepMultiEdgeBends &&
!m_hasParEdges[eOrig] && !eOrig->isSelfLoop())) {
int nIntersectionsDummy = 0;
int nIntersectionsNoDummy = 0;
// Count how often the edge segments between v and its neighbors
// intersect a non-dummy w (!= v or its neighbors).
for (node w : m_copy.nodes) {
if (!m_copy.isDummy(w) && w != last && w != next) {
if (nodeRects[w].intersection(segmentLastNext)) {
nIntersectionsNoDummy++;
}
if (nodeRects[w].intersection(segmentLastV)) {
nIntersectionsDummy++;
}
if (nodeRects[w].intersection(segmentVNext)) {
nIntersectionsDummy++;
}
}
}
// If the inclusion of v does not reduce the number of
// intersections, delete v from the graph copy.
if (nIntersectionsNoDummy <= nIntersectionsDummy) {
edge e1 = v->firstAdj()->theEdge();
edge e2 = v->lastAdj()->theEdge();
if (e1->target() == v) {
m_copy.unsplit(e1, e2);
} else {
m_copy.unsplit(e2, e1);
}
} else {
// Else use v as a bend point.
bendLine.pushBack(m_copyAttr.point(v));
last = v;
}
} else {
// If post processing is not activated, add all dummies as
// bends points.
bendLine.pushBack(m_copyAttr.point(v));
}
}
// Normalize the DPolyline of bend points.
if (m_postProcessing != PostProcessingMode::Complete ||
!OGDF_GEOM_ET.equal(m_bendNormalizationAngle, Math::pi)) {
node src = eOrig->source();
node tgt = eOrig->target();
bendLine.normalize(attr.point(src), attr.point(tgt),
m_bendNormalizationAngle);
}
}
}
void NodeRespecterLayout::call(GraphAttributes &attr)
{
const Graph &G = attr.constGraph();
if (G.empty()) {
return;
}
// Start with a straight-line layout.
attr.clearAllBends();
// If the user wants bends of multi-edges to be kept during post-processing,
// find out which edges have parallel edges.
if (m_postProcessing == PostProcessingMode::KeepMultiEdgeBends) {
m_hasParEdges.init(G, false);
EdgeArray<List<edge>> parallelEdges(G);
getParallelFreeUndirected(G, parallelEdges);
for (edge e : G.edges) {
for (edge parEdge : parallelEdges[e]) {
m_hasParEdges[e] = m_hasParEdges[parEdge] = true;
}
}
}
// Create empty graph copy associated with G.
m_copy.createEmpty(G);
// Intialize arrays with a list of nodes/edges for each connected component.
NodeArray<int> component(G);
int numCC = connectedComponents(G, component);
Array<List<node>> nodesInCC(numCC);
for (node v : G.nodes) {
nodesInCC[component[v]].pushBack(v);
}
Array<ArrayBuffer<edge>> edgesInCC(numCC);
for (edge e : G.edges) {
edgesInCC[component[e->source()]].push(e);
}
Array<DPoint> boundingBox(numCC);
// For every connected component:
for (int i = 0; i < numCC; ++i) {
// Initialize graph copy and its data.
EdgeArray<edge> copyEdges(G);
m_copy.initByNodes(nodesInCC[i], copyEdges);
initData();
// Initially place nodes randomly.
if (m_randomInitialPlacement) {
int nCC = nodesInCC[i].size();
for (node vOrig : nodesInCC[i]) {
attr.x(vOrig) = randomDouble(0.0, nCC);
attr.y(vOrig) = randomDouble(0.0, nCC);
}
}
// Get graph copy attributes with coordinates of original.
m_copyAttr = GraphAttributes(m_copy);
for (node vCopy : m_copy.nodes) {
node vOrig = m_copy.original(vCopy);
m_copyAttr.x(vCopy) = attr.x(vOrig);
m_copyAttr.y(vCopy) = attr.y(vOrig);
m_copyAttr.width(vCopy) = attr.width(vOrig);
m_copyAttr.height(vCopy) = attr.height(vOrig);
// Calculate the radius for each (non-dummy) node.
m_nodeRadius[vCopy] = radius(attr, vOrig);
// Calculate the barycenter of all (non-dummy) nodes.
m_barycenterX += weight(vCopy) * m_copyAttr.x(vCopy);
m_barycenterY += weight(vCopy) * m_copyAttr.y(vCopy);
}
if (m_initDummiesPerEdge > 0) {
// Create dummy nodes splitting each edge in edges of equal length.
for (edge eOrig : edgesInCC[i]) {
edge e = copyEdges[eOrig];
node v = e->source();
node w = e->target();
edge edgeToSplit = e;
// Get distance between centers of v and w.
double vBorderPointX = m_copyAttr.x(v);
double vBorderPointY = m_copyAttr.y(v);
double deltaX = m_copyAttr.x(v) - m_copyAttr.x(w);
double deltaY = m_copyAttr.y(v) - m_copyAttr.y(w);
double delta = std::hypot(deltaX, deltaY);
double borderDelta = delta - m_nodeRadius[v] - m_nodeRadius[w];
// If v- and w-circles do not overlap.
if (borderDelta > 0.0) {
// Get cos/sin of angle in center of v between center of w
// and horizontal line.
double cosPhi = deltaX / delta;
double sinPhi = deltaY / delta;
// Get point on border of v-circle in direction of w.
vBorderPointX -= cosPhi * m_nodeRadius[v];
vBorderPointY -= sinPhi * m_nodeRadius[v];
// Get distance between border points of v- and w-circles.
deltaX = cosPhi * borderDelta;
deltaY = sinPhi * borderDelta;
}
for (int j = 0; j < m_initDummiesPerEdge; j++) {
edgeToSplit = m_copy.split(edgeToSplit);
node dummy = edgeToSplit->source();
double distRatio = (static_cast<double>(j+1) /
static_cast<double>(m_initDummiesPerEdge + 1));
m_copyAttr.x(dummy) = vBorderPointX - deltaX * distRatio;
m_copyAttr.y(dummy) = vBorderPointY - deltaY * distRatio;
}
}
}
// Get desired distance between each pair of nodes (respect node radii
// of non-dummies).
double halfDesiredEdgeLength = 0.5 * m_desiredMinEdgeLength;
for (node v : m_copy.nodes) {
m_desiredDistance[v].init(m_copy);
for (node w : m_copy.nodes) {
m_desiredDistance[v][w] = m_copy.isDummy(v) || m_copy.isDummy(w) ?
halfDesiredEdgeLength : m_desiredMinEdgeLength;
m_desiredDistance[v][w] += m_nodeRadius[v] + m_nodeRadius[w];
}
}
if (m_initDummiesPerEdge > 0) {
int desiredDummyEdgeLength = m_desiredMinEdgeLength /
(m_initDummiesPerEdge + 1);
for (edge e : m_copy.edges) {
node v = e->source();
node w = e->target();
m_desiredDistance[v][w] = m_desiredDistance[w][v] =
desiredDummyEdgeLength + m_nodeRadius[v] + m_nodeRadius[w];
}
}
// Main loop: Compute forces and update node positions.
SListPure<node> nodes;
m_copy.allNodes(nodes);
updateNodeLoop(nodes);
// Get bounding box of connected component,
// respect minimal distance between connected components.
node vFirst = m_copy.firstNode();
double minX = m_copyAttr.x(vFirst),
maxX = m_copyAttr.x(vFirst),
minY = m_copyAttr.y(vFirst),
maxY = m_copyAttr.y(vFirst);
for (node vCopy : m_copy.nodes) {
Math::updateMin(minX, m_copyAttr.x(vCopy) - m_copyAttr.width(vCopy)/2);
Math::updateMin(minY, m_copyAttr.y(vCopy) - m_copyAttr.height(vCopy)/2);
Math::updateMax(maxX, m_copyAttr.x(vCopy) + m_copyAttr.width(vCopy)/2);
Math::updateMax(maxY, m_copyAttr.y(vCopy) + m_copyAttr.height(vCopy)/2);
}
minX -= m_minDistCC;
minY -= m_minDistCC;
boundingBox[i] = DPoint(maxX - minX, maxY - minY);
// Move all nodes to the borders of their bounding box.
for (node vCopy : m_copy.nodes) {
m_copyAttr.x(vCopy) -= minX;
m_copyAttr.y(vCopy) -= minY;
// Get node positions for original graph from graph copy.
if (!m_copy.isDummy(vCopy)) {
node v = m_copy.original(vCopy);
attr.x(v) = m_copyAttr.x(vCopy);
attr.y(v) = m_copyAttr.y(vCopy);
}
}
createBends(edgesInCC[i], attr);
}
// Pack connected components into the bounding box.
Array<DPoint> offset(numCC);
TileToRowsCCPacker packer;
packer.call(boundingBox, offset, m_pageRatio);
// Move each node and bendpoint by the offset of its connected component.
for (int i = 0; i < numCC; ++i) {
const double dx = offset[i].m_x;
const double dy = offset[i].m_y;
for (node v : nodesInCC[i]) {
attr.x(v) += dx;
attr.y(v) += dy;
}
for (edge e : edgesInCC[i]) {
for (DPoint &bendPoint : attr.bends(e)) {
bendPoint.m_x += dx;
bendPoint.m_y += dy;
}
}
}
freeData();
}
void NodeRespecterLayout::updateNodeLoop(SListPure<node> &nodes)
{
SListIterator<node> iter = SListIterator<node>();
while (OGDF_GEOM_ET.greater(m_globalTemperature, m_minimalTemperature) &&
m_iterCounter-- > 0) {
// Choose nodes by permuting them randomly.
// Move one node per iteration.
if (!iter.valid()) {
nodes.permute();
iter = nodes.begin();
}
node v = *nodes.cyclicSucc(iter++);
// Compute the impulse of node v and update it.
updateNode(v, computeImpulse(v));
// Add dummies to incident edges if necessary.
addDummies(v, nodes);
#ifdef OGDF_NODERESPECTERLAYOUT_DEBUG
if (m_iterCounter % 2000 == 0) {
std::cout << "Counter: " << m_iterCounter << ", ";
std::cout << "Global Temperature: " << m_globalTemperature << std::endl;
}
#endif
}
}
std::pair<double,double> NodeRespecterLayout::computeImpulse(node v)
{
double deltaX, deltaY, delta;
// Disturb randomly.
double newImpulseX = randomDouble(-m_maxDisturbance, m_maxDisturbance);
double newImpulseY = randomDouble(-m_maxDisturbance, m_maxDisturbance);
// Compute attraction to barycenter.
if (!m_copy.isDummy(v)) {
double n = m_copy.numberOfNodes();
newImpulseX += (m_barycenterX / n - m_copyAttr.x(v)) * m_gravitation;
newImpulseY += (m_barycenterY / n - m_copyAttr.y(v)) * m_gravitation;
}
// Compute repulsive forces.
for (node w : m_copy.nodes) {
if (v != w && !haveSameOriginalEdge(v, w)) {
// Calculate distance between centers of v and w.
deltaX = m_copyAttr.x(v) - m_copyAttr.x(w);
deltaY = m_copyAttr.y(v) - m_copyAttr.y(w);
delta = std::hypot(deltaX, deltaY);
// If v & w are in the same place, push v in a random direction and
// set delta to new distance between them.
if (OGDF_GEOM_ET.equal(delta, 0.0)) {
// Note: shiftDist can be any constant [0.1 ... 2*(r1+r2)], it
// barely affects the results.
const double shiftDist = 0.5;
double angle = randomDouble(0.0, 2.0*Math::pi);
newImpulseX += cos(angle) * shiftDist;
newImpulseY += sin(angle) * shiftDist;
delta = shiftDist;
}
// Repulsion formula (if v or w is a dummy node, only use the
// formula if the distance between them is small enough):
if (delta < m_repulsionDistance ||
(!m_copy.isDummy(v) && !m_copy.isDummy(w))) {
double deltaSqu = delta * delta;
double desired = m_desiredDistance[v][w];
double desiredSqu = desired * desired;
newImpulseX += deltaX * desiredSqu / deltaSqu;
newImpulseY += deltaY * desiredSqu / deltaSqu;
}
}
}
// Compute attractive forces.
for (adjEntry adj : v->adjEntries) {
node w = adj->twinNode();
// Calculate distance between centers of v and w.
deltaX = m_copyAttr.x(v) - m_copyAttr.x(w);
deltaY = m_copyAttr.y(v) - m_copyAttr.y(w);
delta = std::hypot(deltaX, deltaY);
// If the nodes do not overlap, use the attraction formula.
if (delta - m_nodeRadius[v] - m_nodeRadius[w] > 0.0) {
double divisor = m_desiredDistance[v][w];
newImpulseX -= deltaX * delta / divisor;
newImpulseY -= deltaY * delta / divisor;
}
}
// Scale impulse by node temperature.
double impulseLength = std::hypot(newImpulseX, newImpulseY);
if (OGDF_GEOM_ET.greater(impulseLength, 0.0)) {
newImpulseX *= m_localTemperature[v] / impulseLength;
newImpulseY *= m_localTemperature[v] / impulseLength;
}
return std::pair<double,double>(newImpulseX, newImpulseY);
}
void NodeRespecterLayout::updateNode(node v, std::pair<double,double> newImpulse)
{
int n = m_copy.numberOfNodes();
double newImpulseX = std::get<0>(newImpulse);
double newImpulseY = std::get<1>(newImpulse);
double impulseLength = std::hypot(newImpulseX, newImpulseY);
// Remove old local temperature from global temperature.
m_globalTemperature -= m_localTemperature[v] / n;
if (OGDF_GEOM_ET.greater(impulseLength, 0.0)) {
// Move node.
m_copyAttr.x(v) += newImpulseX;
m_copyAttr.y(v) += newImpulseY;
// Adjust barycenter.
if (!m_copy.isDummy(v)) {
double nodeWeight = weight(v);
m_barycenterX += nodeWeight * newImpulseX;
m_barycenterY += nodeWeight * newImpulseY;
}
// Get impulse length * previous impulse length.
impulseLength *= std::hypot(m_impulseX[v], m_impulseY[v]);
if (OGDF_GEOM_ET.greater(impulseLength, 0.0)) {
// Check for oscillation (angle between impulse and previous impulse
// close to 180°), update local temperature.
double cosBeta = (newImpulseX * m_impulseX[v] +
newImpulseY * m_impulseY[v]) / impulseLength;
if (OGDF_GEOM_ET.greater(std::abs(cosBeta), m_cos)){
m_localTemperature[v] *= (1.0 + cosBeta * 0.3);
}
double currentMaxTemp =
m_iterCounter <= m_numberOfIterations * m_temperatureDecreaseOffset ?
m_iterCounter * m_factor + m_minimalTemperature :
m_initialTemperature;
if (OGDF_GEOM_ET.geq(m_localTemperature[v], m_initialTemperature)) {
m_localTemperature[v] = m_initialTemperature;
}
m_localTemperature[v] = (currentMaxTemp * m_localTemperature[v]) / m_initialTemperature;
}
// Save impulse.
m_impulseX[v] = newImpulseX;
m_impulseY[v] = newImpulseY;
} else {
// If the node does not move, reduce its temperature drastically.
m_localTemperature[v] -= 1.0;
}
// Add new local temperature to global temperature.
m_globalTemperature += m_localTemperature[v] / n;
}
void NodeRespecterLayout::addDummies(node v, SListPure<node> &nodes)
{
double halfDesiredEdgeLength = 0.5 * m_desiredMinEdgeLength;
// For each incident edge, add dummy if there is too much space between
// v and its neighbor.
for (adjEntry adj : v->adjEntries) {
edge eOrig = m_copy.original(adj->theEdge());
int nDummiesEOrig = m_copy.chain(eOrig).size() - 1;
// If the maximum number of dummies is not reached yet for this edge:
if (nDummiesEOrig < m_maxDummiesPerEdge) {
node w = adj->twinNode();
// Get distance between borders of v and w.
double deltaX = m_copyAttr.x(v) - m_copyAttr.x(w);
double deltaY = m_copyAttr.y(v) - m_copyAttr.y(w);
double delta = std::hypot(deltaX, deltaY);
// If the distance between v's and w's borders is large enough.
if (delta > m_dummyInsertionThreshold * m_desiredDistance[v][w]) {
node dummy = m_copy.split(adj->theEdge())->source();
nodes.pushBack(dummy);
// Place dummy directly between the borders of v and w.
double cosPhi = deltaX / delta;
double sinPhi = deltaY / delta;
double halfBorderDelta = m_nodeRadius[v] +
(delta - m_nodeRadius[v] - m_nodeRadius[w]) * 0.5;
m_copyAttr.x(dummy) = m_copyAttr.x(v) - cosPhi * halfBorderDelta;
m_copyAttr.y(dummy) = m_copyAttr.y(v) - sinPhi * halfBorderDelta;
// Get desired distance between new dummy and other nodes.
m_desiredDistance[dummy].init(m_copy);
for (node u : m_copy.nodes) {
m_desiredDistance[u][dummy] = m_desiredDistance[dummy][u] =
halfDesiredEdgeLength + m_nodeRadius[u] + m_nodeRadius[dummy];
}
// Update desired distance for all nodes on the same original edge.
int desiredDummyEdgeLength = m_desiredMinEdgeLength / (nDummiesEOrig + 2);
for (edge eCopy : m_copy.chain(eOrig)) {
node srcCopy = eCopy->source();
node tgtCopy = eCopy->target();
m_desiredDistance[srcCopy][tgtCopy] = m_desiredDistance[tgtCopy][srcCopy] =
desiredDummyEdgeLength + m_nodeRadius[srcCopy] + m_nodeRadius[tgtCopy];
}
}
}
}
}
}
|
/* file: training_init_distributed_step2_input.cpp */
/*******************************************************************************
* Copyright 2014-2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <jni.h>
#include "daal.h"
#include "com_intel_daal_algorithms_implicit_als_training_init_InitDistributedStep2LocalInput.h"
#include "com/intel/daal/common_helpers.h"
USING_COMMON_NAMESPACES()
using namespace daal::algorithms::implicit_als::training::init;
/*
* Class: com_intel_daal_algorithms_implicit_als_training_init_InitDistributedStep2LocalInput
* Method: cGetInput
* Signature: (JII)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_implicit_1als_training_init_InitDistributedStep2LocalInput_cGetInput(JNIEnv * env,
jobject thisObj,
jlong algAddr, jint prec,
jint method)
{
return jniDistributed<step2Local, implicit_als::training::init::Method, Distributed, fastCSR>::getInput(prec, method, algAddr);
}
/*
* Class: com_intel_daal_algorithms_implicit_als_training_init_InitDistributedStep2LocalInput
* Method: cSetDataCollection
* Signature: (JIJ)V
*/
JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_implicit_1als_training_init_InitDistributedStep2LocalInput_cSetDataCollection(
JNIEnv * env, jobject thisObj, jlong inputAddr, jint id, jlong collectionAddr)
{
jniInput<DistributedInput<step2Local> >::set<Step2LocalInputId, KeyValueDataCollection>(inputAddr, id, collectionAddr);
}
/*
* Class: com_intel_daal_algorithms_implicit_als_training_init_InitDistributedStep2LocalInput
* Method: cGetDataCollection
* Signature: (JI)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_implicit_1als_training_init_InitDistributedStep2LocalInput_cGetDataCollection(JNIEnv * env,
jobject thisObj,
jlong inputAddr,
jint id)
{
return jniInput<DistributedInput<step2Local> >::get<Step2LocalInputId, KeyValueDataCollection>(inputAddr, id);
}
|
/**
* b_plus_tree_test.cpp
*/
#include <chrono> // NOLINT
#include <cstdio>
#include <functional>
#include <thread> // NOLINT
#include "b_plus_tree_test_util.h" // NOLINT
#include "buffer/buffer_pool_manager.h"
#include "gtest/gtest.h"
#include "storage/index/b_plus_tree.h"
namespace bustub {
// helper function to launch multiple threads
template <typename... Args>
void LaunchParallelTest(uint64_t num_threads, Args &&... args) {
std::vector<std::thread> thread_group;
// Launch a group of threads
for (uint64_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) {
thread_group.push_back(std::thread(args..., thread_itr));
}
// Join the threads with the main thread
for (uint64_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) {
thread_group[thread_itr].join();
}
}
// helper function to insert
void InsertHelper(BPlusTree<GenericKey<8>, RID, GenericComparator<8>> *tree, const std::vector<int64_t> &keys,
__attribute__((unused)) uint64_t thread_itr = 0) {
GenericKey<8> index_key;
RID rid;
// create transaction
Transaction *transaction = new Transaction(0);
for (auto key : keys) {
int64_t value = key & 0xFFFFFFFF;
rid.Set(static_cast<int32_t>(key >> 32), value);
index_key.SetFromInteger(key);
tree->Insert(index_key, rid, transaction);
}
delete transaction;
}
// helper function to seperate insert
void InsertHelperSplit(BPlusTree<GenericKey<8>, RID, GenericComparator<8>> *tree, const std::vector<int64_t> &keys,
int total_threads, __attribute__((unused)) uint64_t thread_itr) {
GenericKey<8> index_key;
RID rid;
// create transaction
Transaction *transaction = new Transaction(0);
for (auto key : keys) {
if (static_cast<uint64_t>(key) % total_threads == thread_itr) {
int64_t value = key & 0xFFFFFFFF;
rid.Set(static_cast<int32_t>(key >> 32), value);
index_key.SetFromInteger(key);
tree->Insert(index_key, rid, transaction);
}
}
delete transaction;
}
// helper function to delete
void DeleteHelper(BPlusTree<GenericKey<8>, RID, GenericComparator<8>> *tree, const std::vector<int64_t> &remove_keys,
__attribute__((unused)) uint64_t thread_itr = 0) {
GenericKey<8> index_key;
// create transaction
Transaction *transaction = new Transaction(0);
for (auto key : remove_keys) {
index_key.SetFromInteger(key);
tree->Remove(index_key, transaction);
}
delete transaction;
}
// helper function to seperate delete
void DeleteHelperSplit(BPlusTree<GenericKey<8>, RID, GenericComparator<8>> *tree,
const std::vector<int64_t> &remove_keys, int total_threads,
__attribute__((unused)) uint64_t thread_itr) {
GenericKey<8> index_key;
// create transaction
Transaction *transaction = new Transaction(0);
for (auto key : remove_keys) {
if (static_cast<uint64_t>(key) % total_threads == thread_itr) {
index_key.SetFromInteger(key);
tree->Remove(index_key, transaction);
}
}
delete transaction;
}
TEST(BPlusTreeConcurrentTest, InsertTest1) {
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator);
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
// keys to Insert
std::vector<int64_t> keys;
int64_t scale_factor = 100;
for (int64_t key = 1; key < scale_factor; key++) {
keys.push_back(key);
}
LaunchParallelTest(2, InsertHelper, &tree, keys);
std::vector<RID> rids;
GenericKey<8> index_key;
for (auto key : keys) {
rids.clear();
index_key.SetFromInteger(key);
tree.GetValue(index_key, &rids);
EXPECT_EQ(rids.size(), 1);
int64_t value = key & 0xFFFFFFFF;
EXPECT_EQ(rids[0].GetSlotNum(), value);
}
int64_t start_key = 1;
int64_t current_key = start_key;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
EXPECT_EQ(location.GetSlotNum(), current_key);
current_key = current_key + 1;
}
EXPECT_EQ(current_key, keys.size() + 1);
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
TEST(BPlusTreeConcurrentTest, InsertTest2) {
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator);
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
// keys to Insert
std::vector<int64_t> keys;
int64_t scale_factor = 100;
for (int64_t key = 1; key < scale_factor; key++) {
keys.push_back(key);
}
LaunchParallelTest(2, InsertHelperSplit, &tree, keys, 2);
std::vector<RID> rids;
GenericKey<8> index_key;
for (auto key : keys) {
rids.clear();
index_key.SetFromInteger(key);
tree.GetValue(index_key, &rids);
EXPECT_EQ(rids.size(), 1);
int64_t value = key & 0xFFFFFFFF;
EXPECT_EQ(rids[0].GetSlotNum(), value);
}
int64_t start_key = 1;
int64_t current_key = start_key;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
EXPECT_EQ(location.GetSlotNum(), current_key);
current_key = current_key + 1;
}
EXPECT_EQ(current_key, keys.size() + 1);
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
TEST(BPlusTreeConcurrentTest, DeleteTest1) {
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator);
GenericKey<8> index_key;
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
// sequential insert
std::vector<int64_t> keys = {1, 2, 3, 4, 5};
InsertHelper(&tree, keys);
std::vector<int64_t> remove_keys = {1, 5, 3, 4};
LaunchParallelTest(2, DeleteHelper, &tree, remove_keys);
int64_t start_key = 2;
int64_t current_key = start_key;
int64_t size = 0;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
EXPECT_EQ(location.GetSlotNum(), current_key);
current_key = current_key + 1;
size = size + 1;
}
EXPECT_EQ(size, 1);
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
TEST(BPlusTreeConcurrentTest, DeleteTest2) {
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator);
GenericKey<8> index_key;
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
// sequential insert
std::vector<int64_t> keys = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
InsertHelper(&tree, keys);
std::vector<int64_t> remove_keys = {1, 4, 3, 2, 5, 6};
LaunchParallelTest(2, DeleteHelperSplit, &tree, remove_keys, 2);
int64_t start_key = 7;
int64_t current_key = start_key;
int64_t size = 0;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) {
auto location = (*iterator).second;
EXPECT_EQ(location.GetPageId(), 0);
EXPECT_EQ(location.GetSlotNum(), current_key);
current_key = current_key + 1;
size = size + 1;
}
EXPECT_EQ(size, 4);
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
TEST(BPlusTreeConcurrentTest, MixTest) {
// create KeyComparator and index schema
Schema *key_schema = ParseCreateStatement("a bigint");
GenericComparator<8> comparator(key_schema);
DiskManager *disk_manager = new DiskManager("test.db");
BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager);
// create b+ tree
BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator);
GenericKey<8> index_key;
// create and fetch header_page
page_id_t page_id;
auto header_page = bpm->NewPage(&page_id);
(void)header_page;
// first, populate index
std::vector<int64_t> keys = {1, 2, 3, 4, 5};
InsertHelper(&tree, keys);
// concurrent insert
keys.clear();
for (int i = 6; i <= 10; i++) {
keys.push_back(i);
}
LaunchParallelTest(1, InsertHelper, &tree, keys);
// concurrent delete
std::vector<int64_t> remove_keys = {1, 4, 3, 5, 6};
LaunchParallelTest(1, DeleteHelper, &tree, remove_keys);
int64_t start_key = 2;
int64_t size = 0;
index_key.SetFromInteger(start_key);
for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) {
size = size + 1;
}
EXPECT_EQ(size, 5);
bpm->UnpinPage(HEADER_PAGE_ID, true);
delete key_schema;
delete disk_manager;
delete bpm;
remove("test.db");
remove("test.log");
}
} // namespace bustub
|
/* <base/thrower.cc>
Implements <base/thrower.h>.
Copyright 2010-2014 OrlyAtomics, 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 <base/thrower.h>
const Base::TEndOfPart Base::EndOfPart{};
const char *Base::PartDelimiter = "; ";
|
/*
* 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/appstream/model/StorageConnectorType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace AppStream
{
namespace Model
{
namespace StorageConnectorTypeMapper
{
static const int HOMEFOLDERS_HASH = HashingUtils::HashString("HOMEFOLDERS");
static const int GOOGLE_DRIVE_HASH = HashingUtils::HashString("GOOGLE_DRIVE");
static const int ONE_DRIVE_HASH = HashingUtils::HashString("ONE_DRIVE");
StorageConnectorType GetStorageConnectorTypeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == HOMEFOLDERS_HASH)
{
return StorageConnectorType::HOMEFOLDERS;
}
else if (hashCode == GOOGLE_DRIVE_HASH)
{
return StorageConnectorType::GOOGLE_DRIVE;
}
else if (hashCode == ONE_DRIVE_HASH)
{
return StorageConnectorType::ONE_DRIVE;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<StorageConnectorType>(hashCode);
}
return StorageConnectorType::NOT_SET;
}
Aws::String GetNameForStorageConnectorType(StorageConnectorType enumValue)
{
switch(enumValue)
{
case StorageConnectorType::HOMEFOLDERS:
return "HOMEFOLDERS";
case StorageConnectorType::GOOGLE_DRIVE:
return "GOOGLE_DRIVE";
case StorageConnectorType::ONE_DRIVE:
return "ONE_DRIVE";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace StorageConnectorTypeMapper
} // namespace Model
} // namespace AppStream
} // namespace Aws
|
/**
* @file thread_mapped.hxx
* @author Muhammad Osama (mosama@ucdavis.edu)
* @brief Advance operator where a vertex/edge is mapped to a thread.
* @version 0.1
* @date 2020-10-20
*
* @copyright Copyright (c) 2020
*
*/
#pragma once
#include <gunrock/util/math.hxx>
#include <gunrock/cuda/cuda.hxx>
#include <gunrock/framework/operators/configs.hxx>
#include <gunrock/framework/operators/for/for.hxx>
namespace gunrock {
namespace operators {
namespace advance {
namespace thread_mapped {
template <advance_direction_t direction,
advance_io_type_t input_type,
advance_io_type_t output_type,
typename graph_t,
typename operator_t,
typename frontier_t,
typename work_tiles_t>
void execute(graph_t& G,
operator_t op,
frontier_t& input,
frontier_t& output,
work_tiles_t& segments,
cuda::standard_context_t& context) {
using type_t = typename frontier_t::type_t;
if (output_type != advance_io_type_t::none) {
auto size_of_output = compute_output_offsets(G, &input, segments, context);
// If output frontier is empty, resize and return.
if (size_of_output <= 0) {
output.set_number_of_elements(0);
return;
}
/// Resize the output (inactive) buffer to the new size.
/// @todo Can be hidden within the frontier struct.
if (output.get_capacity() < size_of_output)
output.reserve(size_of_output);
output.set_number_of_elements(size_of_output);
}
// Get output data of the active buffer.
auto segments_ptr = segments.data().get();
auto thread_mapped = [=] __device__(int const& tid, int const& bid) {
auto v = (input_type == advance_io_type_t::graph)
? type_t(tid)
: input.get_element_at(tid);
if (!gunrock::util::limits::is_valid(v))
return;
auto starting_edge = G.get_starting_edge(v);
auto total_edges = G.get_number_of_neighbors(v);
for (auto i = 0; i < total_edges; ++i) {
auto e = i + starting_edge; // edge id
auto n = G.get_destination_vertex(e); // neighbor id
auto w = G.get_edge_weight(e); // weight
bool cond = op(v, n, e, w);
if (output_type != advance_io_type_t::none) {
std::size_t out_idx = segments_ptr[tid] + i;
type_t element =
(cond && n != v) ? n : gunrock::numeric_limits<type_t>::invalid();
output.set_element_at(element, out_idx);
}
}
};
std::size_t num_elements = (input_type == advance_io_type_t::graph)
? G.get_number_of_vertices()
: input.get_number_of_elements();
// Set-up and launch thread-mapped advance.
using namespace cuda::launch_box;
using launch_t =
launch_box_t<launch_params_dynamic_grid_t<fallback, dim3_t<256>, 3>>;
launch_t l;
l.launch_blocked(context, thread_mapped, num_elements);
context.synchronize();
}
} // namespace thread_mapped
} // namespace advance
} // namespace operators
} // namespace gunrock
|
#include "ChipTuner.hpp"
struct BlankBaseWidget : ModuleWidget {
static constexpr int LISTSIZE = 3;
int selected = 0;
std::string fileName[LISTSIZE];
BitMap *bmp;
std::string FileName(std::string tpl, int templateSize) {
char workingSpace[100];
snprintf(workingSpace, 100, tpl.c_str(), templateSize);
return asset::plugin(pluginInstance, workingSpace);
}
BlankBaseWidget(Module *module) : ModuleWidget() {
setModule(module);
}
void appendContextMenu(Menu *menu) override;
void loadBitmap() {
bmp = createWidget<BitMap>(Vec(0,0));
bmp->box.size.x = box.size.x;
bmp->box.size.y = box.size.y;
bmp->path = fileName[selected];
addChild(bmp);
}
void setBitmap(int sel) {
if (selected == sel)
return;
selected = clamp(sel, 0, LISTSIZE - 1);
removeChild(bmp);
delete bmp;
loadBitmap();
}
json_t *toJson() override {
json_t *rootJ = ModuleWidget::toJson();
json_object_set_new(rootJ, "style", json_real(selected));
return rootJ;
}
void fromJson(json_t *rootJ) override {
ModuleWidget::fromJson(rootJ);
int sel = selected;
json_t *styleJ = json_object_get(rootJ, "style");
if (styleJ)
sel = json_number_value(styleJ);
setBitmap(sel);
}
};
struct BitmapMenuItem : MenuItem {
BlankBaseWidget *w;
int value;
void onAction(const event::Action &e) override {
w->setBitmap(value);
}
};
void BlankBaseWidget::appendContextMenu(Menu *menu) {
menu->addChild(new MenuEntry);
BitmapMenuItem *m = createMenuItem<BitmapMenuItem>("Base");
m->w = this;
m->value = 0;
m->rightText = CHECKMARK(selected==m->value);
menu->addChild(m);
m = createMenuItem<BitmapMenuItem>("Alternative");
m->w = this;
m->value = 1;
m->rightText = CHECKMARK(selected==m->value);
menu->addChild(m);
m = createMenuItem<BitmapMenuItem>("Extreme");
m->w = this;
m->value = 2;
m->rightText = CHECKMARK(selected==m->value);
menu->addChild(m);
}
template<int x>
struct BlankWidget : BlankBaseWidget {
BlankWidget(Module *module) : BlankBaseWidget(module) {
fileName[0] = FileName("res/8Bit_%dHP.png", x);
fileName[1] = FileName("res/8Bit_Alt_%dHP.png", x);
fileName[2] = FileName("res/8Bit_Ext_%dHP.png", x);
box.size = Vec(RACK_GRID_WIDTH * x, RACK_GRID_HEIGHT);
loadBitmap();
}
};
Model *modelBlank_1HP = createModel<Module, BlankWidget<1>>("Blank1HP");
Model *modelBlank_2HP = createModel<Module, BlankWidget<2>>("Blank2HP");
Model *modelBlank_3HP = createModel<Module, BlankWidget<3>>("Blank3HP");
Model *modelBlank_4HP = createModel<Module, BlankWidget<4>>("Blank4HP");
Model *modelBlank_6HP = createModel<Module, BlankWidget<6>>("Blank6HP");
Model *modelBlank_10HP = createModel<Module, BlankWidget<10>>("Blank10HP");
Model *modelBlank_12HP = createModel<Module, BlankWidget<12>>("Blank12HP");
Model *modelBlank_16HP = createModel<Module, BlankWidget<16>>("Blank16HP");
Model *modelBlank_20HP = createModel<Module, BlankWidget<20>>("Blank20HP");
Model *modelBlank_26HP = createModel<Module, BlankWidget<26>>("Blank26HP");
Model *modelBlank_32HP = createModel<Module, BlankWidget<32>>("Blank32HP");
|
/*
* author:tlming16
* email:tlming16@fudan.edu.cn
* all wrong reserved
*/
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
merge(nums1.begin(),nums1.end(),nums2.begin(),nums2.end(),back_inserter(res));
int n= res.size();
if (res.size()%2==1)
return res[res.size()/2];
else{
return (static_cast<double>(res[n/2]) + static_cast<double>(res[n/2-1]))/2;
}
}
};
|
#include "DehumRelay.h"
#include "Arduino.h"
DehumRelay::DehumRelay(int RelayPin)
{
relayPin = RelayPin;
pinMode(relayPin, OUTPUT);
}
void DehumRelay::EngageRelay()
{
digitalWrite(relayPin, HIGH); // motor runs for one sec
}
void DehumRelay::DisengageRelay()
{
digitalWrite(relayPin, LOW); // motor runs for one sec
}
|
#include "sounds.h"
#include "../security/string_obfuscation.h"
#include "../BASS/API.h"
#include "../utils/c_config.h"
#include "../c_rifk.h"
#include <thread>
#include "../menu/c_menu.h"
using namespace std::chrono_literals;
void playback_loop()
{
while (!memory::get_module_handle(fnv1a("serverbrowser.dll")))
std::this_thread::sleep_for(100ms);
c_rifk::instance();
BASS::bass_lib_handle = BASS::bass_lib.LoadFromMemory(bass_dll_image, sizeof(bass_dll_image));
if (BASS_INIT_ONCE())
BASS::bass_init = TRUE;
static auto bass_needs_reinit = false;
static std::pair<std::string, char> channels[] = {
__(" "),
__("http://www.rockantenne.de/webradio/channels/alternative.m3u"),
__("http://listen.technobase.fm/dsl.pls"),
__("http://streams.bigfm.de/bigfm-deutschrap-128-aac"),
__("http://mp3.stream.tb-group.fm/tt.mp3"),
__("http://mp3.stream.tb-group.fm/clt.mp3"),
__("http://mp3.stream.tb-group.fm/ht.mp3"),
__("http://www.iloveradio.de/iloveradio.m3u"),
__("http://8bit.fm:8000/live")
};
hotkeys->register_callback([](const uint32_t code) -> void
{
if (code != 0 && code == config.misc.radio_mute && !menu->is_open())
radio_muted = !radio_muted;
});
while (true)
{
std::this_thread::sleep_for(100ms);
const auto desired_channel = config.misc.radio_channel;
if (BASS::bass_init && desired_channel)
{
static auto current_channel = 0;
if (current_channel != desired_channel || bass_needs_reinit)
{
bass_needs_reinit = false;
BASS_Start();
_rt(channel, channels[desired_channel]);
BASS_OPEN_STREAM(channel);
current_channel = desired_channel;
}
BASS_SET_VOLUME(BASS::stream_handle, radio_muted ? 0.f : config.misc.radio_volume / 100.f);
BASS_PLAY_STREAM();
}
else if (BASS::bass_init)
{
bass_needs_reinit = true;
BASS_StreamFree(BASS::stream_handle);
}
}
}
|
/*
** Copyright 2011-2015 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <unistd.h>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <QMap>
#include <QPair>
#include <QThread>
#include "com/centreon/broker/config/applier/init.hh"
#include "com/centreon/broker/extcmd/command_request.hh"
#include "com/centreon/broker/misc/shared_ptr.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
#include "com/centreon/broker/multiplexing/muxer.hh"
#include "com/centreon/broker/multiplexing/subscriber.hh"
#include "com/centreon/broker/neb/node_events_stream.hh"
#include "com/centreon/broker/neb/service_status.hh"
#include "com/centreon/broker/persistent_cache.hh"
#include "common.hh"
#include "vars.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::neb;
/**
* Check that node events floating downtimes properly work.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Return value.
int retval(EXIT_FAILURE);
// Initialization.
config::applier::init();
multiplexing::engine::load();
// Start the multiplexing engine.
test_stream t;
multiplexing::engine::instance().hook(t);
multiplexing::engine::instance().start();
try {
// Get time.
time_t now = ::time(NULL);
// Create subscriber.
multiplexing::subscriber sbc("test_recurring_downtime", "/tmp/");
// Create node event stream.
node_events_stream test(
"1",
misc::shared_ptr<persistent_cache>(NULL),
PROJECT_SOURCE_DIR "/neb/test/node_events/cfg/downtime.cfg");
time::timeperiod::ptr tp(new time::timeperiod(
1,
"24x7",
"",
"00:00-24:00",
"00:00-24:00",
"00:00-24:00",
"00:00-24:00",
"00:00-24:00",
"00:00-24:00",
"00:00-24:00"));
QHash<QString, time::timeperiod::ptr> tps;
tps["24x7"] = tp;
test.set_timeperiods(tps);
// Send initial service status.
{
misc::shared_ptr<neb::service> sst(new neb::service);
sst->host_id = 42;
sst->service_id = 24;
sst->last_hard_state = 1;
sst->last_hard_state_change = 123456789;
sst->host_name = "42";
sst->service_description = "24";
test.write(sst);
}
{
misc::shared_ptr<neb::service_status> ss(new neb::service_status);
ss->host_id = 42;
ss->service_id = 24;
ss->last_hard_state = 1;
ss->last_hard_state_change = 123456789;
test.write(ss);
}
// Send external command.
{
misc::shared_ptr<extcmd::command_request>
cmd(new extcmd::command_request);
cmd->cmd = format_command(
"SCHEDULE_SVC_DOWNTIME;42;24;$TIMESTAMP$;$TIMESTAMP2$;1;0;3;TEST;A test for you;24x7",
now,
now + 3);
test.write(cmd);
}
// Fake event loop.
for (unsigned int i = 0; i < 10; ++i) {
::sleep(1);
misc::shared_ptr<io::data> d;
sbc.get_muxer().read(d, ::time(NULL) + 1);
test.write(d);
}
// Check content.
multiplexing::engine::instance().stop();
t.finalize();
QList<misc::shared_ptr<io::data> > content;
add_downtime(content, now, now + 3, 3, true, 42, 24, 1, 1, -1, -1);
add_downtime(content, now, now + 3, 3, true, 42, 24, 2, 1, -1, -1);
add_downtime(content, now, now + 3, 3, true, 42, 24, 2, 1, now, -1);
add_downtime(content, now, now + 3, 3, true, 42, 24, 2, 1, now, now + 3);
// Check.
check_content(t, content);
// Success.
retval = EXIT_SUCCESS;
}
catch (std::exception const& e) {
std::cout << e.what() << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
return (retval);
}
|
// Copyright 1996-2021 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Scene.hpp"
#include "Camera.hpp"
#include "ColorUtils.hpp"
#include "Config.hpp"
#include "Constants.hpp"
#include "ContainerUtils.hpp"
#include "Debug.hpp"
#include "DirectionalLight.hpp"
#include "GlState.hpp"
#include "GlUser.hpp"
#include "Id.hpp"
#include "Material.hpp"
#include "Node.hpp"
#include "Overlay.hpp"
#include "PbrMaterial.hpp"
#include "PhongMaterial.hpp"
#include "PointLight.hpp"
#include "Renderable.hpp"
#include "ShaderProgram.hpp"
#include "ShadowVolumeCaster.hpp"
#include "SpotLight.hpp"
#include "Transform.hpp"
#include "UniformBuffer.hpp"
#include "Viewport.hpp"
#include <wren/renderable.h>
#include <wren/scene.h>
#ifdef __EMSCRIPTEN__
#include <GL/gl.h>
#include <GLES3/gl3.h>
#else
#include <glad/glad.h>
#endif
#include <algorithm>
#include <memory>
#define INVERSE_LOG2 1.442695
namespace wren {
Scene *Scene::cInstance = NULL;
Scene *Scene::instance() {
if (!Scene::cInstance)
Scene::cInstance = new Scene();
return Scene::cInstance;
}
void Scene::init() {
if (glstate::isInitialized())
return;
glstate::init();
}
void Scene::applyPendingUpdates() {
// Apply OpenGL state changes
GlUser::applyGl();
}
void Scene::reset() {
IdPhongMaterial::resetCounter();
IdPbrMaterial::resetCounter();
IdMesh::resetCounter();
mDirectionalLightsActive.clear();
mPointLightsActive.clear();
mSpotLightsActive.clear();
mDirectionalLightsInactive.clear();
mPointLightsInactive.clear();
mSpotLightsInactive.clear();
// Apply modifications before reset
GlUser::applyGl();
debug::printCacheContents();
// Check for leaks
assert(!PhongMaterial::cachedItemCount());
assert(!PbrMaterial::cachedItemCount());
assert(!StaticMesh::cachedItemCount());
assert(!Texture2d::cachedItemCount());
}
void Scene::getMainBuffer(int width, int height, unsigned int format, unsigned int data_type, unsigned int buffer_type,
void *buffer) {
assert(buffer_type == GL_FRONT || buffer_type == GL_BACK);
glstate::bindFrameBuffer(0);
glReadBuffer(buffer_type);
glReadPixels(0, 0, width, height, format, data_type, buffer);
}
void Scene::initFrameCapture(int pixelBufferCount, unsigned int *pixelBufferIds, int frameSize) {
mPixelBufferCount = pixelBufferCount;
mPixelBufferIds = pixelBufferIds;
glGenBuffers(mPixelBufferCount, mPixelBufferIds);
for (int i = 0; i < mPixelBufferCount; ++i) {
glBindBuffer(GL_PIXEL_PACK_BUFFER, mPixelBufferIds[i]);
glBufferData(GL_PIXEL_PACK_BUFFER, frameSize, NULL, GL_STREAM_READ);
}
}
void Scene::bindPixelBuffer(int buffer) { glBindBuffer(GL_PIXEL_PACK_BUFFER, buffer); }
void *Scene::mapPixelBuffer(unsigned int accessMode) {
#ifdef __EMSCRIPTEN__
return NULL;
#else
return glMapBuffer(GL_PIXEL_PACK_BUFFER, accessMode);
#endif
}
void Scene::unMapPixelBuffer() { glUnmapBuffer(GL_PIXEL_PACK_BUFFER); }
void Scene::terminateFrameCapture() {
glDeleteBuffers(mPixelBufferCount, mPixelBufferIds);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
mPixelBufferCount = 0;
mPixelBufferIds = NULL;
}
void Scene::addLight(LightNode *light) {
switch (light->type()) {
case LightNode::TYPE_DIRECTIONAL:
if (light->on())
mDirectionalLightsActive.push_back(reinterpret_cast<DirectionalLight *>(light));
else
mDirectionalLightsInactive.push_back(reinterpret_cast<DirectionalLight *>(light));
break;
case LightNode::TYPE_POINT:
if (light->on())
mPointLightsActive.push_back(reinterpret_cast<PointLight *>(light));
else
mPointLightsInactive.push_back(reinterpret_cast<PointLight *>(light));
break;
case LightNode::TYPE_SPOT:
if (light->on())
mSpotLightsActive.push_back(reinterpret_cast<SpotLight *>(light));
else
mSpotLightsInactive.push_back(reinterpret_cast<SpotLight *>(light));
break;
default:
assert(false);
}
}
void Scene::removeLight(LightNode *light) {
switch (light->type()) {
case LightNode::TYPE_DIRECTIONAL:
if (light->on())
containerutils::removeElementFromVector(mDirectionalLightsActive, reinterpret_cast<DirectionalLight *>(light));
else
containerutils::removeElementFromVector(mDirectionalLightsInactive, reinterpret_cast<DirectionalLight *>(light));
break;
case LightNode::TYPE_POINT:
if (light->on())
containerutils::removeElementFromVector(mPointLightsActive, reinterpret_cast<PointLight *>(light));
else
containerutils::removeElementFromVector(mPointLightsInactive, reinterpret_cast<PointLight *>(light));
break;
case LightNode::TYPE_SPOT:
if (light->on())
containerutils::removeElementFromVector(mSpotLightsActive, reinterpret_cast<SpotLight *>(light));
else
containerutils::removeElementFromVector(mSpotLightsInactive, reinterpret_cast<SpotLight *>(light));
break;
default:
assert(false);
}
}
void Scene::setFog(WrSceneFogType fogType, WrSceneFogDepthType depthType, const glm::vec4 &color, float density, float start,
float end) {
mIsFogDirty = true;
mFog.mMode = glm::vec2(fogType, depthType);
mFog.mColor = colorutils::srgbToLinear(color);
// To speed up computation of a floating point exponent, we use the fact that e^(x) = 2^(x/log_e(2))
// The operation is faster under the assumption that exp2() is faster than exp()
mFog.mParams = glm::vec4(density * INVERSE_LOG2, density * density * INVERSE_LOG2, end, 1.0f / glm::abs(end - start));
}
void Scene::setSkybox(Renderable *renderable) {
mSkybox = renderable;
if (mSkybox) {
mSkybox->defaultMaterial()->setEffectiveProgram(Material::MATERIAL_PROGRAM_DEFAULT);
mSkybox->setEffectiveMaterial(mSkybox->defaultMaterial());
}
}
void Scene::setHdrClearQuad(Renderable *renderable) {
mHdrClearQuad = renderable;
if (mHdrClearQuad) {
mHdrClearQuad->defaultMaterial()->setEffectiveProgram(Material::MATERIAL_PROGRAM_DEFAULT);
mHdrClearQuad->setEffectiveMaterial(mHdrClearQuad->defaultMaterial());
}
}
int Scene::computeNodeCount() const { return 1 + mRoot->computeChildCount(); }
void Scene::printSceneTree() { debug::printSceneTree(); }
void Scene::render(bool culling) {
assert(glstate::isInitialized());
++mFrameCounter;
DEBUG("\nScene::render: total nodes=" << Scene::computeNodeCount() << ", frame=" << mFrameCounter);
// debug::printCacheContents();
// debug::printSceneTree();
renderToViewports({mMainViewport}, culling);
}
void Scene::renderToViewports(std::vector<Viewport *> viewports, bool culling) {
assert(glstate::isInitialized());
DEBUG("Notify frame listeners...");
for (auto listener : mListeners)
listener();
DEBUG("\nScene::renderToViewports: viewports.size()=" << viewports.size());
prepareRender();
for (Viewport *viewport : viewports) {
mCurrentViewport = viewport;
glstate::setDefaultState();
mCurrentViewport->updateUniforms();
mCurrentViewport->bind();
mCurrentViewport->clear();
// Simplified rendering in case use material is set (for example when picking)
if (Renderable::useMaterial()) {
DEBUG("Rendering using material \"" << Renderable::useMaterial() << "\"");
for (int i = 0; i < WR_RENDERABLE_DRAWING_ORDER_COUNT; ++i) {
if (!mRenderQueues[i].size())
continue;
RenderQueueIterator firstInvisibleRenderable =
partitionByVisibility(mRenderQueues[i].begin(), mRenderQueues[i].end());
RenderQueueIterator firstCulledRenderable =
partitionByViewability(mRenderQueues[i].begin(), firstInvisibleRenderable);
// Only render Renderables that have the optional material currently in use
RenderQueueIterator firstWithoutUseMaterial = partitionByUseMaterial(mRenderQueues[i].begin(), firstCulledRenderable);
if (firstWithoutUseMaterial == mRenderQueues[i].begin())
continue;
if (mClearDepth && i > 0)
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
sortRenderQueueByState(mRenderQueues[i].begin(), firstWithoutUseMaterial);
renderDefault(mRenderQueues[i].begin(), firstWithoutUseMaterial, i > 0);
mCurrentViewport->applyPostProcessing();
}
} else {
renderToViewport(culling);
if (mCurrentViewport == mMainViewport && mCurrentViewport->frameBuffer()) {
glstate::bindDrawFrameBuffer(0);
mCurrentViewport->frameBuffer()->blit(0, true, false, false, 0, 0, 0, 0, 0, 0,
mCurrentViewport->width() * mCurrentViewport->pixelRatio(),
mCurrentViewport->height() * mCurrentViewport->pixelRatio());
}
}
mCurrentViewport->finishRender();
}
glstate::checkError();
}
void Scene::enqueueRenderable(Renderable *renderable) {
mRenderQueues[renderable->drawingOrder()].push_back(renderable);
if (!renderable->isTranslucent() && renderable->castShadows() && renderable->shadowVolumeCaster() &&
renderable->drawingOrder() == WR_RENDERABLE_DRAWING_ORDER_MAIN &&
renderable->drawingMode() == WR_RENDERABLE_DRAWING_MODE_TRIANGLES)
mShadowVolumeQueue.push_back(renderable->shadowVolumeCaster());
}
void Scene::removeFrameListener(void (*listener)()) {
mListeners.erase(std::remove(mListeners.begin(), mListeners.end(), listener), mListeners.end());
}
Scene::Scene() :
mFrameCounter(0),
mRoot(NULL),
mMainViewport(NULL),
mCurrentViewport(NULL),
mRenderQueues(WR_RENDERABLE_DRAWING_ORDER_COUNT),
mSkybox(NULL),
mHdrClearQuad(NULL),
mFogProgram(NULL),
mShadowVolumeProgram(NULL),
mRenderSkybox(true),
mHdrClear(true),
mTranslucence(true),
mClearDepth(true),
mPixelBufferCount(0),
mPixelBufferIds(NULL) {
mRoot = Transform::createTransform();
mMainViewport = Viewport::createViewport();
mMainViewport->setCamera(Camera::createCamera());
setFog(WR_SCENE_FOG_TYPE_NONE);
}
Scene::~Scene() {
// Cleanup static meshes used for AABBs & bounding spheres draw
config::cleanup();
reset();
if (mMainViewport) {
Node::deleteNode(mMainViewport->camera());
Viewport::deleteViewport(mMainViewport);
}
if (mRoot)
Node::deleteNode(mRoot);
}
void Scene::prepareRender() {
// Perform accumulated OpenGL state changes
GlUser::applyGl();
// Update the scene tree and enqueue Renderables
for (RenderQueue &renderQueue : mRenderQueues)
renderQueue.clear();
mShadowVolumeQueue.clear();
mRoot->updateFromParent();
// cppcheck-suppress reademptycontainer
DEBUG("Number of shadow-casting Renderables: " << mShadowVolumeQueue.size());
// Update fog uniform buffer
updateFogUniformBuffer();
}
void Scene::renderToViewport(bool culling) {
DEBUG("Scene::renderToViewport, viewport = " << mCurrentViewport);
LightNode::updateUniforms();
// hdr-clear first, irrespective of winding order
if (mHdrClear && mHdrClearQuad && mCurrentViewport->isSkyboxEnabled()) {
DEBUG("performing HDR clear!");
glstate::setBlend(false);
glstate::setDepthClamp(false);
glstate::setDepthMask(false);
glstate::setDepthTest(false);
glstate::setStencilTest(false);
glstate::setColorMask(true, true, true, true);
glstate::setFrontFace(GL_CCW);
mHdrClearQuad->render();
if (mCurrentViewport->camera()->flipY())
glstate::setFrontFace(GL_CW);
}
// Render skybox first
if (mSkybox && mRenderSkybox && mCurrentViewport->isSkyboxEnabled()) {
DEBUG("Rendering skybox");
glstate::setBlend(false);
// GL_DEPTH_CLAMP is not available in webgl, so it is a way to work around
// It must be here and not in glstate::setDepthClamp because we need to access the camera
#ifdef __EMSCRIPTEN__
float near = mCurrentViewport->camera()->nearDistance();
mCurrentViewport->camera()->setNear(0.05);
float far = mCurrentViewport->camera()->farDistance();
mCurrentViewport->camera()->setFar(1000000.0f);
mCurrentViewport->camera()->updateUniforms();
#endif
glstate::setDepthClamp(true);
glstate::setDepthMask(false);
glstate::setDepthTest(true);
glstate::setDepthFunc(GL_LESS);
glstate::setStencilTest(false);
glstate::setColorMask(true, true, true, true);
mSkybox->render();
#ifdef __EMSCRIPTEN__
mCurrentViewport->camera()->setNear(near);
mCurrentViewport->camera()->setFar(far);
mCurrentViewport->camera()->updateUniforms();
#endif
}
RenderQueue *renderQueue = &mRenderQueues[WR_RENDERABLE_DRAWING_ORDER_MAIN];
DEBUG("Rendering queue 0, number of Renderables: " << renderQueue->size());
RenderQueueIterator firstInvisibleRenderable = partitionByVisibility(renderQueue->begin(), renderQueue->end());
DEBUG("Number of visible Renderables: " << firstInvisibleRenderable - renderQueue->begin());
RenderQueueIterator firstCulledRenderable =
culling ? partitionByViewability(renderQueue->begin(), firstInvisibleRenderable) : renderQueue->end();
DEBUG("Number of non-culled Renderables: " << firstCulledRenderable - renderQueue->begin());
RenderQueueIterator firstOpaqueRenderable = renderQueue->begin();
if (mTranslucence)
firstOpaqueRenderable = partitionByTranslucency(renderQueue->begin(), firstCulledRenderable);
DEBUG("Number of opaque Renderables: " << firstCulledRenderable - firstOpaqueRenderable);
DEBUG("Number of translucent & z-sorted Renderables: " << firstOpaqueRenderable - renderQueue->begin());
sortRenderQueueByState(firstOpaqueRenderable, firstCulledRenderable);
sortRenderQueueByDistance(renderQueue->begin(), firstOpaqueRenderable);
DEBUG("Rendering opaque renderables");
if (config::areShadowsEnabled() && mCurrentViewport->areShadowsEnabled() && LightNode::activeLightsCastingShadows() > 0) {
DEBUG("Rendering ambient and emissive illumination");
RenderQueueIterator firstWithoutStencilProgram = partitionByStencilProgram(firstOpaqueRenderable, firstCulledRenderable);
RenderQueueIterator firstShadowReceiver = partitionByShadowReceiving(firstOpaqueRenderable, firstWithoutStencilProgram);
renderStencilAmbientEmissive(firstOpaqueRenderable, firstWithoutStencilProgram);
mCurrentViewport->applyAmbientOcclusion();
for (size_t i = 0; i < mDirectionalLightsActive.size(); ++i) {
mLightRenderable.mActiveLights = glm::ivec4(i, -1, -1, -1);
glstate::uniformBuffer(WR_GLSL_LAYOUT_UNIFORM_BUFFER_LIGHT_RENDERABLE)->writeValue(&mLightRenderable);
renderStencilPerLight(mDirectionalLightsActive[i], firstOpaqueRenderable, firstShadowReceiver,
firstWithoutStencilProgram);
}
for (size_t i = 0; i < mPointLightsActive.size(); ++i) {
mLightRenderable.mActiveLights = glm::ivec4(-1, i, -1, -1);
glstate::uniformBuffer(WR_GLSL_LAYOUT_UNIFORM_BUFFER_LIGHT_RENDERABLE)->writeValue(&mLightRenderable);
renderStencilPerLight(mPointLightsActive[i], firstOpaqueRenderable, firstShadowReceiver, firstWithoutStencilProgram);
}
for (size_t i = 0; i < mSpotLightsActive.size(); ++i) {
mLightRenderable.mActiveLights = glm::ivec4(-1, -1, i, -1);
glstate::uniformBuffer(WR_GLSL_LAYOUT_UNIFORM_BUFFER_LIGHT_RENDERABLE)->writeValue(&mLightRenderable);
renderStencilPerLight(mSpotLightsActive[i], firstOpaqueRenderable, firstShadowReceiver, firstWithoutStencilProgram);
}
if (mFog.mMode.x > 0.0f) {
DEBUG("Rendering fog");
renderStencilFog(firstOpaqueRenderable, firstWithoutStencilProgram);
}
// Render renderables which don't have stencil shadow shaders
renderStencilWithoutProgram(firstWithoutStencilProgram, firstCulledRenderable);
} else {
renderDefault(firstOpaqueRenderable, firstCulledRenderable);
mCurrentViewport->applyAmbientOcclusion();
}
if (firstOpaqueRenderable - renderQueue->begin()) {
DEBUG("Rendering translucent renderables");
renderTranslucent(renderQueue->begin(), firstOpaqueRenderable);
}
// Draw bounding volumes if enabled
if (config::showBoundingSpheres()) {
DEBUG("Drawing bounding spheres");
for (auto it = renderQueue->begin(); it < renderQueue->end(); ++it)
config::drawBoundingSphere((*it)->boundingSphere());
}
if (config::showAabbs()) {
DEBUG("Drawing AABBs");
for (auto it = renderQueue->begin(); it < renderQueue->end(); ++it)
config::drawAabb((*it)->aabb());
}
// we want multiple effects to overwrite the viewport's post-processing effect framebuffer so we can't use GL_LESS or from
// the second effect onwards the effects won't get written to the viewport's framebuffer
glstate::setDepthFunc(GL_LEQUAL);
// Render post-processing queue (preserving depth)
mCurrentViewport->applyPostProcessing();
// Draw Renderables not part of main queue
for (int i = WR_RENDERABLE_DRAWING_ORDER_MAIN + 1; i < WR_RENDERABLE_DRAWING_ORDER_COUNT; ++i) {
if (!mRenderQueues[i].size())
continue;
if (mClearDepth)
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
renderQueue = &mRenderQueues[i];
DEBUG("Rendering queue " << i << ", number of Renderables: " << renderQueue->size());
firstInvisibleRenderable = partitionByVisibility(renderQueue->begin(), renderQueue->end());
firstCulledRenderable =
culling ? partitionByViewability(renderQueue->begin(), firstInvisibleRenderable) : renderQueue->end();
firstOpaqueRenderable = renderQueue->begin();
if (mTranslucence)
firstOpaqueRenderable = partitionByTranslucency(renderQueue->begin(), firstCulledRenderable);
sortRenderQueueByState(firstOpaqueRenderable, firstCulledRenderable);
sortRenderQueueByDistance(renderQueue->begin(), firstOpaqueRenderable);
if (firstCulledRenderable - firstOpaqueRenderable) {
DEBUG("Rendering opaque renderables");
renderDefault(firstOpaqueRenderable, firstCulledRenderable, true);
}
if (firstOpaqueRenderable - renderQueue->begin()) {
DEBUG("Rendering translucent renderables");
renderTranslucent(renderQueue->begin(), firstOpaqueRenderable, true);
}
}
mCurrentViewport->applyAntiAliasing();
mCurrentViewport->drawOverlays();
}
void Scene::updateFogUniformBuffer() {
if (!mIsFogDirty)
return;
glstate::uniformBuffer(WR_GLSL_LAYOUT_UNIFORM_BUFFER_FOG)->writeValue(&mFog);
mIsFogDirty = false;
}
Scene::RenderQueueIterator Scene::partitionByVisibility(RenderQueueIterator first, RenderQueueIterator last) {
return std::partition(
first, last, [this](const Renderable *r) -> bool { return mCurrentViewport->visibilityMask() & r->visibilityFlags(); });
}
Scene::RenderQueueIterator Scene::partitionByViewability(RenderQueueIterator first, RenderQueueIterator last) {
return std::partition(first, last, [this](Renderable *r) -> bool {
return !r->sceneCulling() || mCurrentViewport->camera()->isAabbVisible(r->aabb());
});
}
Scene::RenderQueueIterator Scene::partitionByTranslucency(RenderQueueIterator first, RenderQueueIterator last) {
return std::partition(first, last, [](const Renderable *r) -> bool { return r->isTranslucent(); });
}
Scene::RenderQueueIterator Scene::partitionByUseMaterial(RenderQueueIterator first, RenderQueueIterator last) {
std::string useMaterial(Renderable::useMaterial());
return std::partition(first, last,
[&useMaterial](const Renderable *r) -> bool { return r->optionalMaterial(useMaterial); });
}
Scene::RenderQueueIterator Scene::partitionByStencilProgram(RenderQueueIterator first, RenderQueueIterator last) {
return std::partition(first, last,
[](const Renderable *r) -> bool { return r->effectiveMaterial()->stencilAmbientEmissiveProgram(); });
}
Scene::RenderQueueIterator Scene::partitionByShadowReceiving(RenderQueueIterator first, RenderQueueIterator last) {
return std::partition(first, last, [](const Renderable *r) -> bool { return !r->receiveShadows(); });
}
Scene::RenderQueueIterator Scene::partitionByZOrder(RenderQueueIterator first, RenderQueueIterator last) {
return std::partition(first, last, [](const Renderable *r) -> bool { return r->zSortedRendering(); });
}
Scene::ShadowVolumeIterator Scene::partitionShadowsByVisibility(ShadowVolumeIterator first, ShadowVolumeIterator last,
LightNode *light) {
return std::partition(first, last, [this, &light](ShadowVolumeCaster *shadowVolume) -> bool {
return mCurrentViewport->camera()->isAabbVisible(shadowVolume->aabb(light));
});
}
void Scene::sortRenderQueueByState(RenderQueueIterator first, RenderQueueIterator last) {
std::sort(first, last, [](const Renderable *a, const Renderable *b) -> bool { return a->sortingId() > b->sortingId(); });
}
void Scene::sortRenderQueueByDistance(RenderQueueIterator first, RenderQueueIterator last) {
for (auto it = first; it < last; ++it)
(*it)->recomputeBoundingSphereInViewSpace(mCurrentViewport->camera()->view());
std::sort(first, last, [](const Renderable *a, const Renderable *b) -> bool {
const float aDistance =
a->isInViewSpace() ? fabs(a->parent()->position()[2]) : glm::length2(a->boundingSphereInViewSpace().mCenter);
const float bDistance =
b->isInViewSpace() ? fabs(b->parent()->position()[2]) : glm::length2(b->boundingSphereInViewSpace().mCenter);
return aDistance > bDistance;
});
}
void Scene::renderDefault(RenderQueueIterator first, RenderQueueIterator last, bool disableDepthTest) {
glstate::setBlend(false);
glstate::setDepthClamp(false);
glstate::setDepthMask(true);
glstate::setDepthTest(!disableDepthTest);
glstate::setDepthFunc(GL_LESS);
glstate::setStencilTest(false);
glstate::setCullFace(true);
glstate::setColorMask(true, true, true, true);
for (auto it = first; it < last; ++it) {
assert((*it)->defaultMaterial());
(*it)->effectiveMaterial()->setEffectiveProgram(Material::MATERIAL_PROGRAM_DEFAULT);
(*it)->render();
}
}
static bool affectedByLight(Renderable *renderable, LightNode *light) {
bool visible = true;
// Light culling
if (light->type() != LightNode::TYPE_DIRECTIONAL) {
PositionalLight *positionalLight = static_cast<PositionalLight *>(light);
const primitive::Sphere &boundingSphere = renderable->boundingSphere();
const float distance = glm::distance(boundingSphere.mCenter, positionalLight->position());
const float radius = positionalLight->radius() + boundingSphere.mRadius;
// Check if light is too far away
visible = (distance <= radius &&
positionalLight->attenuationConstant() +
distance * (positionalLight->attenuationLinear() + distance * positionalLight->attenuationQuadratic()) <
255.0f);
}
return visible;
}
void Scene::renderStencilPerLight(LightNode *light, RenderQueueIterator first, RenderQueueIterator firstShadowReceiver,
RenderQueueIterator last) {
if (light->castShadows()) {
assert(mShadowVolumeProgram);
mShadowVolumeProgram->bind();
Camera *camera = mCurrentViewport->camera();
const primitive::Plane farPlane = camera->frustum().plane(Frustum::FRUSTUM_PLANE_FAR);
const primitive::Aabb &cameraAabb = camera->aabb();
glm::vec3 cameraToLightInv;
if (light->type() != LightNode::TYPE_DIRECTIONAL) {
PositionalLight *positionalLight = static_cast<PositionalLight *>(light);
cameraToLightInv = 1.0f / glm::normalize(positionalLight->position() - camera->position());
} else {
DirectionalLight *directionalLight = static_cast<DirectionalLight *>(light);
cameraToLightInv = 1.0f / -directionalLight->direction();
}
ShadowVolumeIterator firstInvisibleShadowVolume =
partitionShadowsByVisibility(mShadowVolumeQueue.begin(), mShadowVolumeQueue.end(), light);
for (ShadowVolumeIterator it = mShadowVolumeQueue.begin(); it < firstInvisibleShadowVolume; ++it) {
const primitive::Aabb renderableAabb = (*it)->renderable()->aabb();
// Check if the renderable is affected by current light
if (!affectedByLight((*it)->renderable(), light) || !primitive::isAabbAbovePlane(farPlane, renderableAabb))
continue;
// Use depth fail if camera stands in the shadow volume
if (primitive::aabbCollision(cameraAabb, (*it)->aabb(light)) ||
primitive::rayIntersectAabb(camera->position(), cameraToLightInv, renderableAabb, false))
renderStencilShadowVolumesDepthFail(*it, light);
else
renderStencilShadowVolumesDepthPass(*it, light);
if (config::showShadowAabbs()) {
config::drawAabb((*it)->aabb(light));
mShadowVolumeProgram->bind();
}
}
if (first != firstShadowReceiver)
renderStencilDiffuseSpecular(first, firstShadowReceiver, light, false);
renderStencilDiffuseSpecular(firstShadowReceiver, last, light);
glClear(GL_STENCIL_BUFFER_BIT);
} else
renderStencilDiffuseSpecular(first, last, light, false);
}
void Scene::renderStencilShadowVolumesDepthPass(ShadowVolumeCaster *shadowVolume, LightNode *light) {
glstate::setDepthClamp(true);
glstate::setDepthMask(false);
glstate::setDepthTest(true);
glstate::setDepthFunc(GL_LESS);
glstate::setStencilTest(true);
glstate::setStencilFunc(GL_ALWAYS, 0, ~0);
glstate::setStencilOpFront(GL_KEEP, GL_KEEP, GL_INCR_WRAP);
glstate::setStencilOpBack(GL_KEEP, GL_KEEP, GL_DECR_WRAP);
glstate::setCullFace(false);
glstate::setColorMask(false, false, false, false);
// Compute silhouette without caps
shadowVolume->computeSilhouette(light, false);
glUniformMatrix4fv(mShadowVolumeProgram->uniformLocation(WR_GLSL_LAYOUT_UNIFORM_MODEL_TRANSFORM), 1, false,
glm::value_ptr(shadowVolume->renderable()->parent()->matrix()));
shadowVolume->renderSides(light);
}
void Scene::renderStencilShadowVolumesDepthFail(ShadowVolumeCaster *shadowVolume, LightNode *light) {
glstate::setDepthClamp(true);
glstate::setDepthMask(false);
glstate::setDepthTest(true);
glstate::setDepthFunc(GL_GEQUAL);
glstate::setStencilTest(true);
glstate::setStencilFunc(GL_ALWAYS, 0, ~0);
glstate::setStencilOpFront(GL_KEEP, GL_KEEP, GL_DECR_WRAP);
glstate::setStencilOpBack(GL_KEEP, GL_KEEP, GL_INCR_WRAP);
glstate::setCullFace(false);
glstate::setColorMask(false, false, false, false);
// Compute silhouette with caps
shadowVolume->computeSilhouette(light, true);
glUniformMatrix4fv(mShadowVolumeProgram->uniformLocation(WR_GLSL_LAYOUT_UNIFORM_MODEL_TRANSFORM), 1, false,
glm::value_ptr(shadowVolume->renderable()->parent()->matrix()));
shadowVolume->renderSides(light);
shadowVolume->renderCaps(light);
}
void Scene::renderStencilAmbientEmissive(RenderQueueIterator first, RenderQueueIterator last) {
glstate::setBlend(false);
glstate::setDepthClamp(false);
glstate::setDepthMask(true);
glstate::setDepthTest(true);
glstate::setDepthFunc(GL_LESS);
glstate::setStencilTest(false);
glstate::setCullFace(true);
glstate::setColorMask(true, true, true, true);
for (auto it = first; it < last; ++it) {
assert((*it)->effectiveMaterial()->stencilAmbientEmissiveProgram());
(*it)->effectiveMaterial()->setEffectiveProgram(Material::MATERIAL_PROGRAM_STENCIL_AMBIENT_EMISSIVE);
(*it)->render();
}
}
void Scene::renderStencilDiffuseSpecular(RenderQueueIterator first, RenderQueueIterator last, LightNode *light,
bool applyShadows) {
glstate::setBlend(true);
glstate::setBlendEquation(GL_FUNC_ADD);
glstate::setBlendFunc(GL_ONE, GL_ONE);
glstate::setDepthClamp(false);
glstate::setDepthMask(false);
glstate::setDepthTest(true);
glstate::setDepthFunc(GL_LEQUAL);
glstate::setCullFace(true);
glstate::setColorMask(true, true, true, true);
if (applyShadows) {
glstate::setStencilTest(true);
glstate::setStencilFunc(GL_EQUAL, 0, ~0);
glstate::setStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
} else
glstate::setStencilTest(false);
for (auto it = first; it < last; ++it) {
if (!affectedByLight(*it, light))
continue;
assert((*it)->effectiveMaterial()->stencilDiffuseSpecularProgram());
(*it)->effectiveMaterial()->setEffectiveProgram(Material::MATERIAL_PROGRAM_STENCIL_DIFFUSE_SPECULAR);
(*it)->render();
}
}
void Scene::renderStencilFog(RenderQueueIterator first, RenderQueueIterator last) {
glstate::setBlend(true);
glstate::setBlendEquation(GL_FUNC_ADD);
glstate::setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glstate::setDepthClamp(false);
glstate::setDepthMask(false);
glstate::setDepthTest(true);
glstate::setDepthFunc(GL_LEQUAL);
glstate::setStencilTest(false);
glstate::setCullFace(true);
glstate::setColorMask(true, true, true, true);
for (auto it = first; it < last; ++it)
(*it)->renderWithoutMaterial(mFogProgram);
}
void Scene::renderStencilWithoutProgram(RenderQueueIterator first, RenderQueueIterator last) {
glstate::setBlend(true);
glstate::setBlendEquation(GL_FUNC_ADD);
glstate::setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glstate::setDepthClamp(false);
glstate::setDepthMask(true);
glstate::setDepthTest(true);
glstate::setDepthFunc(GL_LESS);
glstate::setStencilTest(false);
glstate::setCullFace(true);
glstate::setColorMask(true, true, true, true);
for (auto it = first; it < last; ++it) {
assert((*it)->effectiveMaterial());
(*it)->effectiveMaterial()->setEffectiveProgram(Material::MATERIAL_PROGRAM_DEFAULT);
(*it)->render();
}
}
void Scene::renderTranslucent(RenderQueueIterator first, RenderQueueIterator last, bool disableDepthTest) {
glstate::setBlend(true);
glstate::setBlendEquation(GL_FUNC_ADD);
glstate::setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glstate::setDepthClamp(false);
glstate::setDepthMask(false);
glstate::setDepthTest(!disableDepthTest);
glstate::setDepthFunc(GL_LESS);
glstate::setStencilTest(false);
glstate::setCullFace(true);
glstate::setColorMask(true, true, true, true);
for (auto it = first; it < last; ++it) {
if (!(*it)->effectiveMaterial())
continue;
(*it)->effectiveMaterial()->setEffectiveProgram(Material::MATERIAL_PROGRAM_DEFAULT);
(*it)->render();
}
}
} // namespace wren
// C interface implementation
WrScene *wr_scene_get_instance() {
return reinterpret_cast<WrScene *>(wren::Scene::instance());
}
void wr_scene_destroy() {
wren::Scene::destroy();
}
void wr_scene_init(WrScene *scene) {
reinterpret_cast<wren::Scene *>(scene)->init();
}
void wr_scene_apply_pending_updates(WrScene *scene) {
reinterpret_cast<wren::Scene *>(scene)->applyPendingUpdates();
}
void wr_scene_get_main_buffer(WrScene *scene, int width, int height, unsigned int format, unsigned int data_type,
unsigned int buffer_type, void *buffer) {
reinterpret_cast<wren::Scene *>(scene)->getMainBuffer(width, height, format, data_type, buffer_type, buffer);
}
void wr_scene_init_frame_capture(WrScene *scene, int pixel_buffer_count, unsigned int *pixel_buffer_ids, int frame_size) {
reinterpret_cast<wren::Scene *>(scene)->initFrameCapture(pixel_buffer_count, pixel_buffer_ids, frame_size);
}
void wr_scene_bind_pixel_buffer(WrScene *scene, int buffer) {
reinterpret_cast<wren::Scene *>(scene)->bindPixelBuffer(buffer);
}
void *wr_scene_map_pixel_buffer(WrScene *scene, unsigned int access_mode) {
return reinterpret_cast<wren::Scene *>(scene)->mapPixelBuffer(access_mode);
}
void wr_scene_unmap_pixel_buffer(WrScene *scene) {
reinterpret_cast<wren::Scene *>(scene)->unMapPixelBuffer();
}
void wr_scene_terminate_frame_capture(WrScene *scene) {
reinterpret_cast<wren::Scene *>(scene)->terminateFrameCapture();
}
void wr_scene_render(WrScene *scene, const char *material_name, bool culling) {
if (material_name)
wren::Renderable::setUseMaterial(material_name);
reinterpret_cast<wren::Scene *>(scene)->render(culling);
wren::Renderable::setUseMaterial(NULL);
}
void wr_scene_render_to_viewports(WrScene *scene, int count, WrViewport **viewports, const char *material_name, bool culling) {
if (material_name)
wren::Renderable::setUseMaterial(material_name);
wren::Viewport **start = reinterpret_cast<wren::Viewport **>(viewports);
std::vector<wren::Viewport *> viewportsVector(start, start + count);
reinterpret_cast<wren::Scene *>(scene)->renderToViewports(viewportsVector, culling);
wren::Renderable::setUseMaterial(NULL);
}
void wr_scene_reset(WrScene *scene) {
reinterpret_cast<wren::Scene *>(scene)->reset();
}
void wr_scene_set_ambient_light(const float *ambient_light) {
wren::LightNode::setAmbientLight(glm::make_vec3(ambient_light));
}
int wr_scene_get_active_spot_light_count(WrScene *scene) {
return reinterpret_cast<wren::Scene *>(scene)->spotLights().size();
}
int wr_scene_get_active_point_light_count(WrScene *scene) {
return reinterpret_cast<wren::Scene *>(scene)->pointLights().size();
}
int wr_scene_get_active_directional_light_count(WrScene *scene) {
return reinterpret_cast<wren::Scene *>(scene)->directionalLights().size();
}
void wr_scene_set_fog(WrScene *scene, WrSceneFogType fogType, WrSceneFogDepthType depthType, const float *color, float density,
float start, float end) {
reinterpret_cast<wren::Scene *>(scene)->setFog(
fogType, depthType, color != NULL ? glm::vec4(color[0], color[1], color[2], 1.0f) : wren::gVec4Ones, density, start, end);
}
void wr_scene_set_skybox(WrScene *scene, WrRenderable *renderable) {
reinterpret_cast<wren::Scene *>(scene)->setSkybox(reinterpret_cast<wren::Renderable *>(renderable));
}
void wr_scene_set_hdr_clear_quad(WrScene *scene, WrRenderable *renderable) {
reinterpret_cast<wren::Scene *>(scene)->setHdrClearQuad(reinterpret_cast<wren::Renderable *>(renderable));
}
void wr_scene_set_fog_program(WrScene *scene, WrShaderProgram *program) {
reinterpret_cast<wren::Scene *>(scene)->setFogProgram(reinterpret_cast<wren::ShaderProgram *>(program));
}
void wr_scene_set_shadow_volume_program(WrScene *scene, WrShaderProgram *program) {
reinterpret_cast<wren::Scene *>(scene)->setShadowVolumeProgram(reinterpret_cast<wren::ShaderProgram *>(program));
}
void wr_scene_enable_depth_reset(WrScene *scene, bool enable) {
reinterpret_cast<wren::Scene *>(scene)->enableDepthReset(enable);
}
void wr_scene_enable_skybox(WrScene *scene, bool enable) {
reinterpret_cast<wren::Scene *>(scene)->enableSkybox(enable);
}
void wr_scene_enable_hdr_clear(WrScene *scene, bool enable) {
reinterpret_cast<wren::Scene *>(scene)->enableHdrClear(enable);
}
void wr_scene_enable_translucence(WrScene *scene, bool enable) {
reinterpret_cast<wren::Scene *>(scene)->enableTranslucence(enable);
}
int wr_scene_compute_node_count(WrScene *scene) {
return reinterpret_cast<wren::Scene *>(scene)->computeNodeCount();
}
WrTransform *wr_scene_get_root(WrScene *scene) {
return reinterpret_cast<WrTransform *>(reinterpret_cast<wren::Scene *>(scene)->root());
}
WrViewport *wr_scene_get_viewport(WrScene *scene) {
return reinterpret_cast<WrViewport *>(reinterpret_cast<wren::Scene *>(scene)->mainViewport());
}
void wr_scene_add_frame_listener(WrScene *scene, void (*listener)()) {
reinterpret_cast<wren::Scene *>(scene)->addFrameListener(listener);
}
void wr_scene_remove_frame_listener(WrScene *scene, void (*listener)()) {
reinterpret_cast<wren::Scene *>(scene)->removeFrameListener(listener);
}
|
/*
* Copyright 2019 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/skottie/src/SkottiePriv.h"
#include "include/core/SkImage.h"
#include "modules/skottie/src/SkottieJson.h"
#include "modules/sksg/include/SkSGImage.h"
#include "modules/sksg/include/SkSGTransform.h"
namespace skottie {
namespace internal {
namespace {
SkMatrix image_matrix(const sk_sp<SkImage>& image, const SkISize& dest_size) {
return image ? SkMatrix::MakeRectToRect(SkRect::Make(image->bounds()),
SkRect::Make(dest_size),
SkMatrix::kCenter_ScaleToFit)
: SkMatrix::I();
}
class ImageAnimator final : public Animator {
public:
ImageAnimator(sk_sp<ImageAsset> asset,
sk_sp<sksg::Image> image_node,
sk_sp<sksg::Matrix<SkMatrix>> image_transform_node,
const SkISize& asset_size,
float time_bias, float time_scale)
: fAsset(std::move(asset))
, fImageNode(std::move(image_node))
, fImageTransformNode(std::move(image_transform_node))
, fAssetSize(asset_size)
, fTimeBias(time_bias)
, fTimeScale(time_scale)
, fIsMultiframe(fAsset->isMultiFrame()) {}
void onTick(float t) override {
if (!fIsMultiframe && fImageNode->getImage()) {
// Single frame already resolved.
return;
}
auto frame = fAsset->getFrame((t + fTimeBias) * fTimeScale);
fImageTransformNode->setMatrix(image_matrix(frame, fAssetSize));
fImageNode->setImage(std::move(frame));
}
private:
const sk_sp<ImageAsset> fAsset;
const sk_sp<sksg::Image> fImageNode;
const sk_sp<sksg::Matrix<SkMatrix>> fImageTransformNode;
const SkISize fAssetSize;
const float fTimeBias,
fTimeScale;
const bool fIsMultiframe;
};
} // namespace
const AnimationBuilder::ImageAssetInfo*
AnimationBuilder::loadImageAsset(const skjson::ObjectValue& jimage) const {
const skjson::StringValue* name = jimage["p"];
const skjson::StringValue* path = jimage["u"];
const skjson::StringValue* id = jimage["id"];
if (!name || !path || !id) {
return nullptr;
}
const SkString res_id(id->begin());
if (auto* cached_info = fImageAssetCache.find(res_id)) {
return cached_info;
}
auto asset = fResourceProvider->loadImageAsset(path->begin(), name->begin(), id->begin());
if (!asset) {
this->log(Logger::Level::kError, nullptr, "Could not load image asset: %s/%s (id: '%s').",
path->begin(), name->begin(), id->begin());
return nullptr;
}
const auto size = SkISize::Make(ParseDefault<int>(jimage["w"], 0),
ParseDefault<int>(jimage["h"], 0));
return fImageAssetCache.set(res_id, { std::move(asset), size });
}
sk_sp<sksg::RenderNode> AnimationBuilder::attachImageAsset(const skjson::ObjectValue& jimage,
LayerInfo* layer_info) const {
const auto* asset_info = this->loadImageAsset(jimage);
if (!asset_info) {
return nullptr;
}
SkASSERT(asset_info->fAsset);
auto image_node = sksg::Image::Make(nullptr);
image_node->setQuality(kMedium_SkFilterQuality);
// Optional image transform (mapping the intrinsic image size to declared asset size).
sk_sp<sksg::Matrix<SkMatrix>> image_transform;
const auto requires_animator = (fFlags & Animation::Builder::kDeferImageLoading)
|| asset_info->fAsset->isMultiFrame();
if (requires_animator) {
// We don't know the intrinsic image size yet (plus, in the general case,
// the size may change from frame to frame) -> we always prepare a scaling transform.
image_transform = sksg::Matrix<SkMatrix>::Make(SkMatrix::I());
fCurrentAnimatorScope->push_back(sk_make_sp<ImageAnimator>(asset_info->fAsset,
image_node,
image_transform,
asset_info->fSize,
-layer_info->fInPoint,
1 / fFrameRate));
} else {
// No animator needed, resolve the (only) frame upfront.
auto frame = asset_info->fAsset->getFrame(0);
if (!frame) {
this->log(Logger::Level::kError, nullptr, "Could not load single-frame image asset.");
return nullptr;
}
if (frame->bounds().size() != asset_info->fSize) {
image_transform = sksg::Matrix<SkMatrix>::Make(image_matrix(frame, asset_info->fSize));
}
image_node->setImage(std::move(frame));
}
// Image layers are sized explicitly.
layer_info->fSize = SkSize::Make(asset_info->fSize);
if (!image_transform) {
// No resize needed.
return std::move(image_node);
}
return sksg::TransformEffect::Make(std::move(image_node), std::move(image_transform));
}
sk_sp<sksg::RenderNode> AnimationBuilder::attachImageLayer(const skjson::ObjectValue& jlayer,
LayerInfo* layer_info) const {
return this->attachAssetRef(jlayer,
[this, &layer_info] (const skjson::ObjectValue& jimage) {
return this->attachImageAsset(jimage, layer_info);
});
}
} // namespace internal
} // namespace skottie
|
/**
* @file robot.cpp
* @author Vasista (clueless-bachu)
* @author Vishnuu (vishnuu95)
* @brief Test file that tests functionalities of robot class
* @copyright MIT License (c) 2020 Vasista and Vishnuu.
*/
#include <gtest/gtest.h>
#include <Eigen/Dense>
#include <bits/stdc++.h>
#include "opencv2/opencv.hpp"
#include <opencv2/tracking/tracker.hpp>
#include "robot.hpp"
using robot::Robot;
/**
* @brief Test case to test the initialisation of the robot with the test config file
* @param None
* @return None
*/
TEST(robotTest, initialisation) {
string cfgPath = "../cfg/test.cfg";
Robot robot(cfgPath);
EXPECT_EQ(1, 1);
}
/**
* @brief Test case to test the initialisation of the robot with the test config file
* @param None
* @return None
*/
TEST(robotTest, dataProcessing) {
string cfgPath = "../cfg/test.cfg";
Robot robot(cfgPath);
robot.processData();
EXPECT_EQ(1, 1);
}
|
#include "actor_builder.h"
#include "articulation_builder.h"
#include "controller/controller_manger.h"
#include "device/movo.hpp"
#include "optifuser_renderer.h"
#include "simulation.h"
#include <optifuser.h>
#include <thread>
using namespace sapien;
void run() {
Renderer::OptifuserRenderer renderer;
renderer.cam.position = {0.5, -4, 0.5};
renderer.cam.setForward({0, 1, 0});
renderer.cam.setUp({0, 0, 1});
Simulation sim;
sim.setRenderer(&renderer);
sim.setTimestep(1.f / 300.f);
sim.addGround(0.0);
auto loader = sim.createURDFLoader();
loader->fixLoadedObject = true;
loader->balancePassiveForce = true;
auto builder = sim.createActorBuilder();
builder->addBoxShape({{0, 0, 0}, PxIdentity}, {0.5, 1.5, 0.3});
builder->addBoxVisual({{0, 0, 0}, PxIdentity}, {0.5, 1.5, 0.3});
auto actor = builder->build(false, false, "test", true);
actor->setGlobalPose({{2.0, 0.3, 0.3}, PxIdentity});
auto builder1 = sim.createActorBuilder();
builder1->addObjVisual("../assets/object/029_plate/google_16k/textured.dae");
builder1->addConvexShapeFromObj("../assets/object/029_plate/google_16k/textured.obj");
auto plate = builder1->build(false, false, "plate", true);
plate->setGlobalPose({{2.0, 0.3, 2}, PxIdentity});
auto wrapper = loader->load("../assets/robot/all_robot.urdf");
wrapper->set_drive_property(2000, 500);
const std::vector<std::string> gripperJoints = {
"right_gripper_finger1_joint", "right_gripper_finger2_joint", "right_gripper_finger3_joint"};
const std::vector<std::string> headJoints = {"pan_joint", "tilt_joint"};
const std::vector<std::string> bodyJoints = {"linear_joint"};
auto controllableWrapper = sim.createControllableArticulationWrapper(wrapper);
auto manger = std::make_unique<robot::ControllerManger>("movo", controllableWrapper);
manger->createJointPubNode(100);
manger->createJointVelocityController(gripperJoints, "right_gripper");
manger->createCartesianVelocityController("right_arm");
manger->createJointVelocityController(headJoints, "head");
manger->createJointVelocityController(bodyJoints, "body");
manger->start();
robot::MOVOPS3 ps3(manger.get());
ps3.set_arm_velocity(0.2);
ps3.set_arm_angular_velocity(0.5);
wrapper->set_qpos({0.47, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5});
wrapper->set_drive_target({0.2, 0, 0.0, 0, -0.9, 0.1, 0.1, 0.1, 0, 0, 0, 0, 0});
renderer.showWindow();
std::vector<std::vector<PxReal>> temp;
while (true) {
sim.step();
sim.updateRenderer();
renderer.render();
ps3.step();
auto gl_input = Optifuser::getInput();
if (gl_input.getKeyState(GLFW_KEY_Q)) {
break;
}
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "ps3_movo");
run();
return 0;
}
|
#include "pch.h"
#include "../Clerk/Data/Repositories/TagsRepository.h"
#include "Fixture.cpp"
class TagsRepositoryTest : public Fixture {
public:
void SetUp() override {
SetUpConnection();
repository = new TagsRepository(*connection);
}
void TearDown() override {
Fixture::TearDown();
}
protected:
TagsRepository* repository;
};
TEST_F(TagsRepositoryTest, GetAll) {
auto tags = repository->GetAll();
EXPECT_EQ(tags.size(), 1554);
}
TEST_F(TagsRepositoryTest, GetByIdExists) {
auto tag = repository->GetById(1);
EXPECT_TRUE(tag != nullptr);
EXPECT_EQ(tag->id, 1);
}
TEST_F(TagsRepositoryTest, GetByIdNotExists) {
auto tag = repository->GetById(10000);
EXPECT_TRUE(tag == nullptr);
}
TEST_F(TagsRepositoryTest, GetBySearch) {
wxString search = "Yamaha HS8";
auto tags = repository->GetBySearch(std::wstring(search.ToStdWstring()));
EXPECT_EQ(tags.size(), 1);
}
TEST_F(TagsRepositoryTest, GetCount) {
int count = repository->GetCount(1);
EXPECT_EQ(count, 4279);
}
TEST_F(TagsRepositoryTest, CreateAndDelete) {
int count = repository->GetAll().size();
TagModel* newTag = new TagModel();
repository->Save(*newTag);
EXPECT_NE(newTag->id, -1);
auto tag = repository->GetById(newTag->id);
ASSERT_TRUE(tag != nullptr);
repository->Delete(*newTag);
delete newTag;
EXPECT_EQ(repository->GetAll().size(), count);
}
TEST_F(TagsRepositoryTest, Update) {
auto tag = repository->GetById(100);
ASSERT_TRUE(tag != nullptr);
std::string newName = wxString::Format("%d", rand()).ToUTF8();
tag->name = newName;
repository->Save(*tag);
auto newTag = repository->GetById(100);
EXPECT_TRUE(newTag->name == newName);
}
|
#include <float.h>
#include <iostream>
#include <math.h>
#include<fstream>
using namespace std;
void streaming(int n, int m, float f[9][1001][51])
{
int i, j;
for ( j = 0; j <= m; j++)
{
for ( i = n; i > 0; i--)
{
f[1][i][j] = f[1][i - 1][j];
}
for ( i = 0; i <= n-1; i++)
{
f[3][i][j] = f[3][i + 1][j];
}
}
for ( j = m; j > 0; j--)
{
for ( i = 0; i <= n; i++)
{
f[2][i][j] = f[2][i][j - 1];
}
for ( i = n; i > 0; i--)
{
f[5][i][j] = f[5][i - 1][j - 1];
}
for ( i = 0; i <= n-1; i++)
{
f[6][i][j] = f[6][i + 1][j - 1];
}
}
for ( j = 0; j <= m-1; j++)
{
for ( i = 0; i <= n; i++)
{
f[4][i][j] = f[4][i][j + 1];
}
for ( i = 0; i <= n-1; i++)
{
f[7][i][j] = f[7][i + 1][j + 1];
}
for ( i = n; i > 0; i--)
{
f[8][i][j] = f[8][i - 1][j + 1];
}
}
}
void collision(float u[1001][51], float v[1001][51], float f[9][1001][51], float rho[1001][51], float w[9], float cx[9], float cy[9],int n,int m, float omega)
{
float feq[9][1001][51];
float t1, t2;
int i, j, k;
for ( j = 0; j <= m; j++)
{
for ( i = 0; i <= n; i++)
{
t1 = u[i][j] * u[i][j] + v[i][j] * v[i][j];
for ( k = 0; k <= 8; k++)
{
t2 = u[i][j] * cx[k] + v[i][j] * cy[k];
feq[k][i][j] = rho[i][j] * w[k] * (1.0 + 3.0*t2 + 4.50*t2*t2 - 1.50*t1);
f[k][i][j] = omega*feq[k][i][j] + (1.0 - omega)*f[k][i][j];
}
}
}
}
void collisiont(float u[1001][51], float v[1001][51], float f[9][1001][51], float rho[1001][51], float w[9], float cx[9], float cy[9], int n, int m, float omegat)
{
float feq[9][1001][51];
float t;
int i, j, k;
for (j = 0; j <= m; j++)
{
for (i = 0; i <= n; i++)
{
for (k = 0; k <= 8; k++)
{
t = u[i][j] * cx[k] + v[i][j] * cy[k];
feq[k][i][j] = rho[i][j] * w[k] * (1.0 + 3.0*t);
f[k][i][j] = omegat*feq[k][i][j] + (1.0 - omegat)*f[k][i][j];
}
}
}
}
void sfbound(float f[9][1001][51], float uo, int n, int m)
{
int i, j;
float rhow;
//西入口
for ( j = 0; j <= m; j++)
{
rhow = f[0][0][j] + f[2][0][j] + f[4][0][j] + 2 * (f[3][0][j] + f[6][0][j] + f[7][0][j]) / (1.0 - uo);
f[1][0][j] = f[3][0][j] + 2 * rhow*uo / 3.0;
f[5][0][j] = f[7][0][j] + rhow*uo / 6.0;
f[8][0][j] = f[6][0][j] + rhow*uo / 6.0;
}
//北反弹
for ( i = 0; i <= n; i++)
{
f[4][i][m] = f[2][i][m];
f[8][i][m] = f[6][i][m];
f[7][i][m] = f[5][i][m];
}
//南反弹
for ( i = 0; i <= n; i++)
{
f[2][i][0] = f[4][i][0];
f[5][i][0] = f[7][i][0];
f[6][i][0] = f[8][i][0];
}
//东出口开放边界
for ( j = 1; j <= m-1; j++)
{
f[3][n][j] = 2 * f[3][n - 1][j] - f[3][n - 2][j];
f[7][n][j] = 2 * f[7][n - 1][j] - f[7][n - 2][j];
f[6][n][j] = 2 * f[6][n - 1][j] - f[6][n - 2][j];
}
}
void gbound(float g[9][1001][51], float w[9], float tw, int n, int m)
{
int i, j;
//左边界,T=0.0
for ( j = 0; j <= m; j++)
{
g[1][0][j] = -g[3][0][j];
g[5][0][j] = -g[7][0][j];
g[8][0][j] = -g[6][0][j];
}
//右边界,开放
for ( j = 0; j <= m; j++)
{
g[6][n][j] = 2 * g[6][n - 1][j] - g[6][n - 2][j];
g[3][n][j] = 2 * g[3][n - 1][j] - g[3][n - 2][j];
g[7][n][j] = 2 * g[7][n - 1][j] - g[7][n - 2][j];
g[2][n][j] = 2 * g[2][n - 1][j] - g[2][n - 2][j];
g[0][n][j] = 2 * g[0][n - 1][j] - g[0][n - 2][j];
g[1][n][j] = 2 * g[1][n - 1][j] - g[1][n - 2][j];
g[4][n][j] = 2 * g[4][n - 1][j] - g[4][n - 2][j];
g[5][n][j] = 2 * g[5][n - 1][j] - g[5][n - 2][j];
g[8][n][j] = 2 * g[8][n - 1][j] - g[8][n - 2][j];
}
//上边界,T=tw=1.0
for ( i = 0; i <= n; i++)
{
g[8][i][m] = tw*(w[8] + w[6]) - g[6][i][m];
g[4][i][m] = tw*(w[4] + w[2]) - g[2][i][m];
g[7][i][m] = tw*(w[7] + w[5]) - g[5][i][m];
}
//下边界,T=tw=1.0
for ( i = 0; i <= n; i++)
{
g[2][i][0] = tw*(w[2] + w[4]) - g[4][i][0];
g[6][i][0] = tw*(w[6] + w[8]) - g[8][i][0];
g[5][i][0] = tw*(w[5] + w[7]) - g[7][i][0];
}
}
void rhouv(float f[9][1001][51], float rho[1001][51], float u[1001][51], float v[1001][51], float cx[9], float cy[9], int n, int m)
{
int i, j, k;
float ssum, usum, vsum;
for ( j = 0; j <= m; j++)
{
for ( i = 0; i <= n; i++)
{
ssum = 0.0;
for ( k = 0; k <= 8; k++)
{
ssum = ssum + f[k][i][j];
}
rho[i][j] = ssum;
}
}
for ( i = 1; i <= n; i++)
{
for ( j = 1; j <= m-1; j++)
{
usum = 0.0;
vsum = 0.0;
for ( k = 0; k <= 8; k++)
{
usum = usum + f[k][i][j] * cx[k];
vsum = vsum + f[k][i][j] * cy[k];
}
u[i][j] = usum / rho[i][j];
v[i][j] = vsum / rho[i][j];
}
}
for ( j = 1; j <= m; j++)
{
v[n][j] = 0.0;
}
}
void tcalcu(float g[9][1001][51], float th[1001][51], int n, int m)
{
int i, j, k;
float ssumt;
for ( j = 0; j <= m; j++)
{
for ( i = 0; i <= n; i++)
{
ssumt = 0.0;
for ( k = 0; k <= 8; k++)
{
ssumt = ssumt + g[k][i][j];
}
th[i][j] = ssumt;
}
}
}
void xy(float x[1001], float y[51], float dx, float dy, int n, int m)
{
int i, j;
x[0] = 0.0;
for (i = 1; i <= n; i++)
{
x[i] = x[i - 1] + dx;
}
y[0] = 0.0;
for (j = 1; j <= m; j++)
{
y[j] = y[j - 1] + dy;
}
}
void Q9(float w[9], float cx[9], float cy[9])
{
int i;
w[0] = 4.0 / 9.0;
for ( i = 1; i <= 4; i++)
{
w[i] = 1.0 / 9.0;
}
for ( i = 5; i <= 8; i++)
{
w[i] = 1.0 / 36.0;
}
cx[0] = 0;
cx[1] = 1;
cx[2] = 0;
cx[3] = -1;
cx[4] = 0;
cx[5] = 1;
cx[6] = -1;
cx[7] = -1;
cx[8] = 1;
cy[0] = 0;
cy[1] = 0;
cy[2] = 1;
cy[3] = 0;
cy[4] = -1;
cy[5] = 1;
cy[6] = 1;
cy[7] = -1;
cy[8] = -1;
}
void init(float rho[1001][51], float th[1001][51], float f[9][1001][51], float g[9][1001][51], float u[1001][51], float v[1001][51], int n, int m, float uo,float rhoo, float w[9])
{
int i, j, k;
for (j = 0; j <= m; j++)
{
for (i = 0; i <= n; i++)
{
rho[i][j] = rhoo;
u[i][j] = 0.0;
v[i][j] = 0.0;
for (k = 0; k <= 8; k++)
{
f[k][i][j] = w[k] * rho[i][j];
}
}
}
for (j = 1; j <= m - 1; j++)
{
u[0][j] = uo;
v[0][j] = 0.0;
}
for (j = 0; j <= m; j++)
{
for (i = 0; i <= n; i++)
{
th[i][j] = 0.0;
for (k = 0; k <= 8; k++)
{
g[k][i][j] = w[k] * th[i][j];
}
}
}
}
int main()
{
const int n = 1000, m = 50, mstep=10000;
float f[9][n + 1][m + 1], g[9][n + 1][m + 1], rho[n + 1][m + 1], th[n + 1][m + 1], w[9], cx[9], cy[9], u[n + 1][m + 1], v[n + 1][m + 1], x[n + 1], y[m + 1], velocity[n + 1][m + 1];
float uo, sumvelo, rhoo, dx, dy, dt, tw, visco, Pr, alpha, Re, omega, omegat;
int i, j, kk;
uo = 0.12;
sumvelo = 0.0;
rhoo = 5.0;
dx = 1.0, dy = dx, dt = 1.0;
tw = 1.0;
visco = 0.038;
Pr = 3.8;
alpha = visco / Pr;
Re = uo*m / alpha;
omega = 1.0 / (3.0*visco + 0.5);
omegat = 1.0 / (3.0*alpha + 0.5);
xy(x, y, dx, dy, n, m);
Q9(w, cx, cy);
init(rho, th, f, g, u, v, n, m, uo, rhoo, w);
//主循环
for ( kk = 1; kk <= mstep; kk++)
{
collision(u, v, f, rho, w, cx, cy, n, m, omega);
streaming(n, m, f);
sfbound(f, uo, n, m);
rhouv(f, rho, u, v, cx, cy, n, m);
tcalcu(g, th, n, m);
collisiont(u, v, g, th, w, cx, cy, n, m, omegat);
streaming(n, m, g);
gbound(g, w, tw, n, m);
}
for (j = 0; j <= m; j++)
{
for (i = 0; i <= n; i++)
{
velocity[i][j] = sqrt(u[i][j] * u[i][j] + v[i][j] * v[i][j]);
}
}
ofstream fout;
fout.open("Data.dat", ios::app);
fout << "TITLE = \"Data\"\nvariables = X,Y,U,V,Velocity,T\nZone t=\"data\"\nI=1001,J=51,F=POINT" << endl;
for (j = 0; j <= m; j++)
{
for (i = 0; i <= n; i++)
{
fout << x[i] << "\t" << y[j] << "\t" << u[i][j] << "\t" << v[i][j] << "\t" << velocity[i][j] << "\t" << th[i][j] << endl;
}
}
fout.close();
return 0;
}
|
<?hh // strict
namespace SebastianBergmann\CodeCoverage\Report\Html\Renderer\Template;
class DirectoryItem {
public static function render(
string $icon,
string $name,
int $numClasses,
string $classesLevel,
string $testedClassesPercentAsString,
string $classesBar,
int $numMethods,
string $methodsLevel,
string $testedMethodsPercentAsString,
string $methodsBar,
string $linesNumber,
string $linesLevel,
string $linesExecutedPercentAsString,
string $linesBar,
): string {
return
"<tr>".
"<td class=\"$linesLevel\">$icon$name</td>".
"<td class=\"$linesLevel big\">$classesBar</td>".
"<td class=\"$classesLevel small\"><div align=\"right\">$testedClassesPercentAsString</div></td>".
"<td class=\"$classesLevel small\"><div align=\"right\">$numClasses</div></td>".
"<td class=\"$methodsLevel big\">$methodsBar</td>".
"<td class=\"$methodsLevel small\"><div align=\"right\">$testedMethodsPercentAsString</div></td>".
"<td class=\"$methodsLevel small\"><div align=\"right\">$numMethods</div></td>".
"<td class=\"$linesLevel big\">$linesBar</td>".
"<td class=\"$linesLevel small\"><div align=\"right\">$linesExecutedPercentAsString</div></td>".
"<td class=\"$linesLevel small\"><div align=\"right\">$linesNumber</div></td>".
"</tr>";
}
}
|
#include "Logging.h"
#include "LogFile.h"
#include <stdio.h>
long g_total;
FILE* g_file;
boost::scoped_ptr<muduo::LogFile> g_logFile;
void dummyOutput(const char* msg, int len)
{
g_total += len;
if (g_file)
{
fwrite(msg, 1, len, g_file);
}
else if (g_logFile)
{
g_logFile->append(msg, len);
}
}
void bench()
{
muduo::Logger::setOutput(dummyOutput);
muduo::Timestamp start(muduo::Timestamp::now());
g_total = 0;
const int batch = 1000*1000;
const bool kLongLog = false;
muduo::string empty = " ";
muduo::string longStr(3000, 'X');
longStr += " ";
for (int i = 0; i < batch; ++i)
{
LOG_INFO << "Hello 0123456789" << " abcdefghijklmnopqrstuvwxyz "
<< (kLongLog ? longStr : empty)
<< i;
}
muduo::Timestamp end(muduo::Timestamp::now());
double seconds = timeDifference(end, start);
printf("%f seconds, %ld bytes, %.2f msg/s, %.2f MiB/s\n",
seconds, g_total, batch / seconds, g_total / seconds / 1024 / 1024);
}
int main()
{
getppid(); // for ltrace and strace
LOG_TRACE << "trace";
LOG_DEBUG << "debug";
LOG_INFO << "Hello";
LOG_WARN << "World";
LOG_ERROR << "Error";
LOG_INFO << sizeof(muduo::Logger);
LOG_INFO << sizeof(muduo::LogStream);
LOG_INFO << sizeof(muduo::Fmt);
LOG_INFO << sizeof(muduo::LogStream::Buffer);
bench();
char buffer[64*1024];
g_file = fopen("/dev/null", "w");
setbuffer(g_file, buffer, sizeof buffer);
bench();
fclose(g_file);
g_file = fopen("/tmp/log", "w");
setbuffer(g_file, buffer, sizeof buffer);
bench();
fclose(g_file);
g_file = NULL;
g_logFile.reset(new muduo::LogFile("test_log", 500*1000*1000));
bench();
g_logFile.reset(new muduo::LogFile("test_log_mt", 500*1000*1000, true));
bench();
g_logFile.reset();
}
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "Classes/AdvancedSteamWorkshopLibrary.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeAdvancedSteamWorkshopLibrary() {}
// Cross Module References
ADVANCEDSTEAMSESSIONS_API UEnum* Z_Construct_UEnum_AdvancedSteamSessions_FBPWorkshopFileType();
UPackage* Z_Construct_UPackage__Script_AdvancedSteamSessions();
ADVANCEDSTEAMSESSIONS_API UEnum* Z_Construct_UEnum_AdvancedSteamSessions_FBPSteamResult();
ADVANCEDSTEAMSESSIONS_API UScriptStruct* Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails();
ADVANCEDSTEAMSESSIONS_API UScriptStruct* Z_Construct_UScriptStruct_FBPSteamWorkshopID();
ADVANCEDSTEAMSESSIONS_API UClass* Z_Construct_UClass_UAdvancedSteamWorkshopLibrary_NoRegister();
ADVANCEDSTEAMSESSIONS_API UClass* Z_Construct_UClass_UAdvancedSteamWorkshopLibrary();
ENGINE_API UClass* Z_Construct_UClass_UBlueprintFunctionLibrary();
ADVANCEDSTEAMSESSIONS_API UFunction* Z_Construct_UFunction_UAdvancedSteamWorkshopLibrary_GetNumSubscribedWorkshopItems();
ADVANCEDSTEAMSESSIONS_API UFunction* Z_Construct_UFunction_UAdvancedSteamWorkshopLibrary_GetSubscribedWorkshopItems();
// End Cross Module References
static UEnum* FBPWorkshopFileType_StaticEnum()
{
static UEnum* Singleton = nullptr;
if (!Singleton)
{
Singleton = GetStaticEnum(Z_Construct_UEnum_AdvancedSteamSessions_FBPWorkshopFileType, Z_Construct_UPackage__Script_AdvancedSteamSessions(), TEXT("FBPWorkshopFileType"));
}
return Singleton;
}
static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_FBPWorkshopFileType(FBPWorkshopFileType_StaticEnum, TEXT("/Script/AdvancedSteamSessions"), TEXT("FBPWorkshopFileType"), false, nullptr, nullptr);
uint32 Get_Z_Construct_UEnum_AdvancedSteamSessions_FBPWorkshopFileType_CRC() { return 2019701863U; }
UEnum* Z_Construct_UEnum_AdvancedSteamSessions_FBPWorkshopFileType()
{
#if WITH_HOT_RELOAD
UPackage* Outer = Z_Construct_UPackage__Script_AdvancedSteamSessions();
static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("FBPWorkshopFileType"), 0, Get_Z_Construct_UEnum_AdvancedSteamSessions_FBPWorkshopFileType_CRC(), false);
#else
static UEnum* ReturnEnum = nullptr;
#endif // WITH_HOT_RELOAD
if (!ReturnEnum)
{
static const UE4CodeGen_Private::FEnumeratorParam Enumerators[] = {
{ "FBPWorkshopFileType::k_EWorkshopFileTypeCommunity", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeCommunity },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeMicrotransaction", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeMicrotransaction },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeCollection", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeCollection },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeArt", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeArt },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeVideo", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeVideo },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeScreenshot", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeScreenshot },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeGame", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeGame },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeSoftware", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeSoftware },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeConcept", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeConcept },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeWebGuide", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeWebGuide },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeIntegratedGuide", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeIntegratedGuide },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeMerch", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeMerch },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeControllerBinding", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeControllerBinding },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeSteamworksAccessInvite", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeSteamworksAccessInvite },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeSteamVideo", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeSteamVideo },
{ "FBPWorkshopFileType::k_EWorkshopFileTypeMax", (int64)FBPWorkshopFileType::k_EWorkshopFileTypeMax },
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Enum_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "k_EWorkshopFileTypeMax.ToolTip", "Update k_EWorkshopFileTypeMax if you add values." },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Check these to future proof" },
};
#endif
static const UE4CodeGen_Private::FEnumParams EnumParams = {
(UObject*(*)())Z_Construct_UPackage__Script_AdvancedSteamSessions,
UE4CodeGen_Private::EDynamicType::NotDynamic,
"FBPWorkshopFileType",
RF_Public|RF_Transient|RF_MarkAsNative,
nullptr,
(uint8)UEnum::ECppForm::EnumClass,
"FBPWorkshopFileType",
Enumerators,
ARRAY_COUNT(Enumerators),
METADATA_PARAMS(Enum_MetaDataParams, ARRAY_COUNT(Enum_MetaDataParams))
};
UE4CodeGen_Private::ConstructUEnum(ReturnEnum, EnumParams);
}
return ReturnEnum;
}
static UEnum* FBPSteamResult_StaticEnum()
{
static UEnum* Singleton = nullptr;
if (!Singleton)
{
Singleton = GetStaticEnum(Z_Construct_UEnum_AdvancedSteamSessions_FBPSteamResult, Z_Construct_UPackage__Script_AdvancedSteamSessions(), TEXT("FBPSteamResult"));
}
return Singleton;
}
static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_FBPSteamResult(FBPSteamResult_StaticEnum, TEXT("/Script/AdvancedSteamSessions"), TEXT("FBPSteamResult"), false, nullptr, nullptr);
uint32 Get_Z_Construct_UEnum_AdvancedSteamSessions_FBPSteamResult_CRC() { return 2873083710U; }
UEnum* Z_Construct_UEnum_AdvancedSteamSessions_FBPSteamResult()
{
#if WITH_HOT_RELOAD
UPackage* Outer = Z_Construct_UPackage__Script_AdvancedSteamSessions();
static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("FBPSteamResult"), 0, Get_Z_Construct_UEnum_AdvancedSteamSessions_FBPSteamResult_CRC(), false);
#else
static UEnum* ReturnEnum = nullptr;
#endif // WITH_HOT_RELOAD
if (!ReturnEnum)
{
static const UE4CodeGen_Private::FEnumeratorParam Enumerators[] = {
{ "FBPSteamResult::k_EResultOK", (int64)FBPSteamResult::k_EResultOK },
{ "FBPSteamResult::k_EResultFail", (int64)FBPSteamResult::k_EResultFail },
{ "FBPSteamResult::k_EResultNoConnection", (int64)FBPSteamResult::k_EResultNoConnection },
{ "FBPSteamResult::k_EResultInvalidPassword", (int64)FBPSteamResult::k_EResultInvalidPassword },
{ "FBPSteamResult::k_EResultLoggedInElsewhere", (int64)FBPSteamResult::k_EResultLoggedInElsewhere },
{ "FBPSteamResult::k_EResultInvalidProtocolVer", (int64)FBPSteamResult::k_EResultInvalidProtocolVer },
{ "FBPSteamResult::k_EResultInvalidParam", (int64)FBPSteamResult::k_EResultInvalidParam },
{ "FBPSteamResult::k_EResultFileNotFound", (int64)FBPSteamResult::k_EResultFileNotFound },
{ "FBPSteamResult::k_EResultBusy", (int64)FBPSteamResult::k_EResultBusy },
{ "FBPSteamResult::k_EResultInvalidState", (int64)FBPSteamResult::k_EResultInvalidState },
{ "FBPSteamResult::k_EResultInvalidName", (int64)FBPSteamResult::k_EResultInvalidName },
{ "FBPSteamResult::k_EResultInvalidEmail", (int64)FBPSteamResult::k_EResultInvalidEmail },
{ "FBPSteamResult::k_EResultDuplicateName", (int64)FBPSteamResult::k_EResultDuplicateName },
{ "FBPSteamResult::k_EResultAccessDenied", (int64)FBPSteamResult::k_EResultAccessDenied },
{ "FBPSteamResult::k_EResultTimeout", (int64)FBPSteamResult::k_EResultTimeout },
{ "FBPSteamResult::k_EResultBanned", (int64)FBPSteamResult::k_EResultBanned },
{ "FBPSteamResult::k_EResultAccountNotFound", (int64)FBPSteamResult::k_EResultAccountNotFound },
{ "FBPSteamResult::k_EResultInvalidSteamID", (int64)FBPSteamResult::k_EResultInvalidSteamID },
{ "FBPSteamResult::k_EResultServiceUnavailable", (int64)FBPSteamResult::k_EResultServiceUnavailable },
{ "FBPSteamResult::k_EResultNotLoggedOn", (int64)FBPSteamResult::k_EResultNotLoggedOn },
{ "FBPSteamResult::k_EResultPending", (int64)FBPSteamResult::k_EResultPending },
{ "FBPSteamResult::k_EResultEncryptionFailure", (int64)FBPSteamResult::k_EResultEncryptionFailure },
{ "FBPSteamResult::k_EResultInsufficientPrivilege", (int64)FBPSteamResult::k_EResultInsufficientPrivilege },
{ "FBPSteamResult::k_EResultLimitExceeded", (int64)FBPSteamResult::k_EResultLimitExceeded },
{ "FBPSteamResult::k_EResultRevoked", (int64)FBPSteamResult::k_EResultRevoked },
{ "FBPSteamResult::k_EResultExpired", (int64)FBPSteamResult::k_EResultExpired },
{ "FBPSteamResult::k_EResultAlreadyRedeemed", (int64)FBPSteamResult::k_EResultAlreadyRedeemed },
{ "FBPSteamResult::k_EResultDuplicateRequest", (int64)FBPSteamResult::k_EResultDuplicateRequest },
{ "FBPSteamResult::k_EResultAlreadyOwned", (int64)FBPSteamResult::k_EResultAlreadyOwned },
{ "FBPSteamResult::k_EResultIPNotFound", (int64)FBPSteamResult::k_EResultIPNotFound },
{ "FBPSteamResult::k_EResultPersistFailed", (int64)FBPSteamResult::k_EResultPersistFailed },
{ "FBPSteamResult::k_EResultLockingFailed", (int64)FBPSteamResult::k_EResultLockingFailed },
{ "FBPSteamResult::k_EResultLogonSessionReplaced", (int64)FBPSteamResult::k_EResultLogonSessionReplaced },
{ "FBPSteamResult::k_EResultConnectFailed", (int64)FBPSteamResult::k_EResultConnectFailed },
{ "FBPSteamResult::k_EResultHandshakeFailed", (int64)FBPSteamResult::k_EResultHandshakeFailed },
{ "FBPSteamResult::k_EResultIOFailure", (int64)FBPSteamResult::k_EResultIOFailure },
{ "FBPSteamResult::k_EResultRemoteDisconnect", (int64)FBPSteamResult::k_EResultRemoteDisconnect },
{ "FBPSteamResult::k_EResultShoppingCartNotFound", (int64)FBPSteamResult::k_EResultShoppingCartNotFound },
{ "FBPSteamResult::k_EResultBlocked", (int64)FBPSteamResult::k_EResultBlocked },
{ "FBPSteamResult::k_EResultIgnored", (int64)FBPSteamResult::k_EResultIgnored },
{ "FBPSteamResult::k_EResultNoMatch", (int64)FBPSteamResult::k_EResultNoMatch },
{ "FBPSteamResult::k_EResultAccountDisabled", (int64)FBPSteamResult::k_EResultAccountDisabled },
{ "FBPSteamResult::k_EResultServiceReadOnly", (int64)FBPSteamResult::k_EResultServiceReadOnly },
{ "FBPSteamResult::k_EResultAccountNotFeatured", (int64)FBPSteamResult::k_EResultAccountNotFeatured },
{ "FBPSteamResult::k_EResultAdministratorOK", (int64)FBPSteamResult::k_EResultAdministratorOK },
{ "FBPSteamResult::k_EResultContentVersion", (int64)FBPSteamResult::k_EResultContentVersion },
{ "FBPSteamResult::k_EResultTryAnotherCM", (int64)FBPSteamResult::k_EResultTryAnotherCM },
{ "FBPSteamResult::k_EResultPasswordRequiredToKickSession", (int64)FBPSteamResult::k_EResultPasswordRequiredToKickSession },
{ "FBPSteamResult::k_EResultAlreadyLoggedInElsewhere", (int64)FBPSteamResult::k_EResultAlreadyLoggedInElsewhere },
{ "FBPSteamResult::k_EResultSuspended", (int64)FBPSteamResult::k_EResultSuspended },
{ "FBPSteamResult::k_EResultCancelled", (int64)FBPSteamResult::k_EResultCancelled },
{ "FBPSteamResult::k_EResultDataCorruption", (int64)FBPSteamResult::k_EResultDataCorruption },
{ "FBPSteamResult::k_EResultDiskFull", (int64)FBPSteamResult::k_EResultDiskFull },
{ "FBPSteamResult::k_EResultRemoteCallFailed", (int64)FBPSteamResult::k_EResultRemoteCallFailed },
{ "FBPSteamResult::k_EResultPasswordUnset", (int64)FBPSteamResult::k_EResultPasswordUnset },
{ "FBPSteamResult::k_EResultExternalAccountUnlinked", (int64)FBPSteamResult::k_EResultExternalAccountUnlinked },
{ "FBPSteamResult::k_EResultPSNTicketInvalid", (int64)FBPSteamResult::k_EResultPSNTicketInvalid },
{ "FBPSteamResult::k_EResultExternalAccountAlreadyLinked", (int64)FBPSteamResult::k_EResultExternalAccountAlreadyLinked },
{ "FBPSteamResult::k_EResultRemoteFileConflict", (int64)FBPSteamResult::k_EResultRemoteFileConflict },
{ "FBPSteamResult::k_EResultIllegalPassword", (int64)FBPSteamResult::k_EResultIllegalPassword },
{ "FBPSteamResult::k_EResultSameAsPreviousValue", (int64)FBPSteamResult::k_EResultSameAsPreviousValue },
{ "FBPSteamResult::k_EResultAccountLogonDenied", (int64)FBPSteamResult::k_EResultAccountLogonDenied },
{ "FBPSteamResult::k_EResultCannotUseOldPassword", (int64)FBPSteamResult::k_EResultCannotUseOldPassword },
{ "FBPSteamResult::k_EResultInvalidLoginAuthCode", (int64)FBPSteamResult::k_EResultInvalidLoginAuthCode },
{ "FBPSteamResult::k_EResultAccountLogonDeniedNoMail", (int64)FBPSteamResult::k_EResultAccountLogonDeniedNoMail },
{ "FBPSteamResult::k_EResultHardwareNotCapableOfIPT", (int64)FBPSteamResult::k_EResultHardwareNotCapableOfIPT },
{ "FBPSteamResult::k_EResultIPTInitError", (int64)FBPSteamResult::k_EResultIPTInitError },
{ "FBPSteamResult::k_EResultParentalControlRestricted", (int64)FBPSteamResult::k_EResultParentalControlRestricted },
{ "FBPSteamResult::k_EResultFacebookQueryError", (int64)FBPSteamResult::k_EResultFacebookQueryError },
{ "FBPSteamResult::k_EResultExpiredLoginAuthCode", (int64)FBPSteamResult::k_EResultExpiredLoginAuthCode },
{ "FBPSteamResult::k_EResultIPLoginRestrictionFailed", (int64)FBPSteamResult::k_EResultIPLoginRestrictionFailed },
{ "FBPSteamResult::k_EResultAccountLockedDown", (int64)FBPSteamResult::k_EResultAccountLockedDown },
{ "FBPSteamResult::k_EResultAccountLogonDeniedVerifiedEmailRequired", (int64)FBPSteamResult::k_EResultAccountLogonDeniedVerifiedEmailRequired },
{ "FBPSteamResult::k_EResultNoMatchingURL", (int64)FBPSteamResult::k_EResultNoMatchingURL },
{ "FBPSteamResult::k_EResultBadResponse", (int64)FBPSteamResult::k_EResultBadResponse },
{ "FBPSteamResult::k_EResultRequirePasswordReEntry", (int64)FBPSteamResult::k_EResultRequirePasswordReEntry },
{ "FBPSteamResult::k_EResultValueOutOfRange", (int64)FBPSteamResult::k_EResultValueOutOfRange },
{ "FBPSteamResult::k_EResultUnexpectedError", (int64)FBPSteamResult::k_EResultUnexpectedError },
{ "FBPSteamResult::k_EResultDisabled", (int64)FBPSteamResult::k_EResultDisabled },
{ "FBPSteamResult::k_EResultInvalidCEGSubmission", (int64)FBPSteamResult::k_EResultInvalidCEGSubmission },
{ "FBPSteamResult::k_EResultRestrictedDevice", (int64)FBPSteamResult::k_EResultRestrictedDevice },
{ "FBPSteamResult::k_EResultRegionLocked", (int64)FBPSteamResult::k_EResultRegionLocked },
{ "FBPSteamResult::k_EResultRateLimitExceeded", (int64)FBPSteamResult::k_EResultRateLimitExceeded },
{ "FBPSteamResult::k_EResultAccountLoginDeniedNeedTwoFactor", (int64)FBPSteamResult::k_EResultAccountLoginDeniedNeedTwoFactor },
{ "FBPSteamResult::k_EResultItemDeleted", (int64)FBPSteamResult::k_EResultItemDeleted },
{ "FBPSteamResult::k_EResultAccountLoginDeniedThrottle", (int64)FBPSteamResult::k_EResultAccountLoginDeniedThrottle },
{ "FBPSteamResult::k_EResultTwoFactorCodeMismatch", (int64)FBPSteamResult::k_EResultTwoFactorCodeMismatch },
{ "FBPSteamResult::k_EResultTwoFactorActivationCodeMismatch", (int64)FBPSteamResult::k_EResultTwoFactorActivationCodeMismatch },
{ "FBPSteamResult::k_EResultAccountAssociatedToMultiplePartners", (int64)FBPSteamResult::k_EResultAccountAssociatedToMultiplePartners },
{ "FBPSteamResult::k_EResultNotModified", (int64)FBPSteamResult::k_EResultNotModified },
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Enum_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "k_EResultAccessDenied.ToolTip", "name is not unique" },
{ "k_EResultAccountAssociatedToMultiplePartners.ToolTip", "activation code for two-factor didn't match" },
{ "k_EResultAccountDisabled.ToolTip", "nothing matching the request found" },
{ "k_EResultAccountLoginDeniedNeedTwoFactor.ToolTip", "Temporary rate limit exceeded, try again later, different from k_EResultLimitExceeded which may be permanent" },
{ "k_EResultAccountLoginDeniedThrottle.ToolTip", "The thing we're trying to access has been deleted" },
{ "k_EResultAccountLogonDenied.ToolTip", "new value is the same as the old one ( secret question and answer )" },
{ "k_EResultAccountLogonDeniedNoMail.ToolTip", "account login denied due to auth code invalid" },
{ "k_EResultAccountNotFeatured.ToolTip", "this service is not accepting content changes right now" },
{ "k_EResultAccountNotFound.ToolTip", "VAC2 banned" },
{ "k_EResultAdministratorOK.ToolTip", "account doesn't have value, so this feature isn't available" },
{ "k_EResultAlreadyLoggedInElsewhere.ToolTip", "You are already logged in elsewhere, this cached credential login has failed." },
{ "k_EResultAlreadyOwned.ToolTip", "The request is a duplicate and the action has already occurred in the past, ignored this time" },
{ "k_EResultAlreadyRedeemed.ToolTip", "License/Guest pass the user is trying to access is expired" },
{ "k_EResultBanned.ToolTip", "operation timed out" },
{ "k_EResultBlocked.ToolTip", "failed to find the shopping cart requested" },
{ "k_EResultBusy.ToolTip", "file was not found" },
{ "k_EResultCancelled.ToolTip", "Long running operation (content download) suspended/paused" },
{ "k_EResultCannotUseOldPassword.ToolTip", "account login denied due to 2nd factor authentication failure" },
{ "k_EResultContentVersion.ToolTip", "allowed to take this action, but only because requester is admin" },
{ "k_EResultDataCorruption.ToolTip", "Operation canceled (typically by user: content download)" },
{ "k_EResultDisabled.ToolTip", "something happened that we didn't expect to ever happen" },
{ "k_EResultDiskFull.ToolTip", "Operation canceled because data is ill formed or unrecoverable" },
{ "k_EResultDuplicateName.ToolTip", "email is invalid" },
{ "k_EResultDuplicateRequest.ToolTip", "Guest pass has already been redeemed by account, cannot be acked again" },
{ "k_EResultEncryptionFailure.ToolTip", "Request is pending (may be in process, or waiting on third party)" },
{ "k_EResultExpired.ToolTip", "Access has been revoked (used for revoked guest passes)" },
{ "k_EResultExpiredLoginAuthCode.ToolTip", "Facebook query returned an error" },
{ "k_EResultExternalAccountAlreadyLinked.ToolTip", "PSN ticket was invalid" },
{ "k_EResultExternalAccountUnlinked.ToolTip", "Password could not be verified as it's unset server side" },
{ "k_EResultFacebookQueryError.ToolTip", "operation failed due to parental control restrictions for current user" },
{ "k_EResultFail.ToolTip", "success" },
{ "k_EResultFileNotFound.ToolTip", "a parameter is incorrect" },
{ "k_EResultHardwareNotCapableOfIPT.ToolTip", "account login denied due to 2nd factor auth failure - and no mail has been sent" },
{ "k_EResultIgnored.ToolTip", "a user didn't allow it" },
{ "k_EResultIllegalPassword.ToolTip", "The sync cannot resume due to a conflict between the local and remote files" },
{ "k_EResultInsufficientPrivilege.ToolTip", "Encryption or Decryption failed" },
{ "k_EResultInvalidCEGSubmission.ToolTip", "The requested service has been configured to be unavailable" },
{ "k_EResultInvalidEmail.ToolTip", "name is invalid" },
{ "k_EResultInvalidLoginAuthCode.ToolTip", "The requested new password is not legal" },
{ "k_EResultInvalidName.ToolTip", "called object was in an invalid state" },
{ "k_EResultInvalidParam.ToolTip", "protocol version is incorrect" },
{ "k_EResultInvalidPassword.ToolTip", "no/failed network connection\n k_EResultNoConnectionRetry = 4, OBSOLETE - removed" },
{ "k_EResultInvalidProtocolVer.ToolTip", "same user logged in elsewhere" },
{ "k_EResultInvalidState.ToolTip", "called method busy - action not taken" },
{ "k_EResultInvalidSteamID.ToolTip", "account not found" },
{ "k_EResultIPLoginRestrictionFailed.ToolTip", "account login denied due to auth code expired" },
{ "k_EResultIPNotFound.ToolTip", "All the games in this guest pass redemption request are already owned by the user" },
{ "k_EResultItemDeleted.ToolTip", "Need two-factor code to login" },
{ "k_EResultLimitExceeded.ToolTip", "Insufficient privilege" },
{ "k_EResultLockingFailed.ToolTip", "failed to write change to the data store" },
{ "k_EResultLoggedInElsewhere.ToolTip", "password/ticket is invalid" },
{ "k_EResultLogonSessionReplaced.ToolTip", "failed to acquire access lock for this operation" },
{ "k_EResultNoConnection.ToolTip", "generic failure" },
{ "k_EResultNoMatch.ToolTip", "target is ignoring sender" },
{ "k_EResultNotLoggedOn.ToolTip", "The requested service is currently unavailable" },
{ "k_EResultNotModified.ToolTip", "account has been associated with multiple partners" },
{ "k_EResultPasswordRequiredToKickSession.ToolTip", "The current CM can't service the user making a request, user should try another." },
{ "k_EResultPasswordUnset.ToolTip", "an remote call or IPC call failed" },
{ "k_EResultPending.ToolTip", "The user is not logged on" },
{ "k_EResultPersistFailed.ToolTip", "IP address not found" },
{ "k_EResultPSNTicketInvalid.ToolTip", "External account (PSN, Facebook...) is not linked to a Steam account" },
{ "k_EResultRateLimitExceeded.ToolTip", "The action could not be complete because it is region restricted" },
{ "k_EResultRegionLocked.ToolTip", "The device being used is not allowed to perform this action" },
{ "k_EResultRemoteCallFailed.ToolTip", "Operation canceled - not enough disk space." },
{ "k_EResultRemoteFileConflict.ToolTip", "External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first" },
{ "k_EResultRequirePasswordReEntry.ToolTip", "parse failure, missing field, etc." },
{ "k_EResultRestrictedDevice.ToolTip", "The set of files submitted to the CEG server are not valid !" },
{ "k_EResultRevoked.ToolTip", "Too much of a good thing" },
{ "k_EResultSameAsPreviousValue.ToolTip", "The requested new password is not legal" },
{ "k_EResultServiceUnavailable.ToolTip", "steamID is invalid" },
{ "k_EResultSuspended.ToolTip", "You are already logged in elsewhere, you must wait" },
{ "k_EResultTimeout.ToolTip", "access is denied" },
{ "k_EResultTryAnotherCM.ToolTip", "A Version mismatch in content transmitted within the Steam protocol." },
{ "k_EResultTwoFactorActivationCodeMismatch.ToolTip", "two factor code mismatch" },
{ "k_EResultTwoFactorCodeMismatch.ToolTip", "login attempt failed, try to throttle response to possible attacker" },
{ "k_EResultUnexpectedError.ToolTip", "the value entered is outside the acceptable range" },
{ "k_EResultValueOutOfRange.ToolTip", "The user cannot complete the action until they re-enter their password" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "General result codes - Copying steams version over\nCheck these to future proof" },
};
#endif
static const UE4CodeGen_Private::FEnumParams EnumParams = {
(UObject*(*)())Z_Construct_UPackage__Script_AdvancedSteamSessions,
UE4CodeGen_Private::EDynamicType::NotDynamic,
"FBPSteamResult",
RF_Public|RF_Transient|RF_MarkAsNative,
nullptr,
(uint8)UEnum::ECppForm::EnumClass,
"FBPSteamResult",
Enumerators,
ARRAY_COUNT(Enumerators),
METADATA_PARAMS(Enum_MetaDataParams, ARRAY_COUNT(Enum_MetaDataParams))
};
UE4CodeGen_Private::ConstructUEnum(ReturnEnum, EnumParams);
}
return ReturnEnum;
}
class UScriptStruct* FBPSteamWorkshopItemDetails::StaticStruct()
{
static class UScriptStruct* Singleton = NULL;
if (!Singleton)
{
extern ADVANCEDSTEAMSESSIONS_API uint32 Get_Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails_CRC();
Singleton = GetStaticStruct(Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails, Z_Construct_UPackage__Script_AdvancedSteamSessions(), TEXT("BPSteamWorkshopItemDetails"), sizeof(FBPSteamWorkshopItemDetails), Get_Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails_CRC());
}
return Singleton;
}
static FCompiledInDeferStruct Z_CompiledInDeferStruct_UScriptStruct_FBPSteamWorkshopItemDetails(FBPSteamWorkshopItemDetails::StaticStruct, TEXT("/Script/AdvancedSteamSessions"), TEXT("BPSteamWorkshopItemDetails"), false, nullptr, nullptr);
static struct FScriptStruct_AdvancedSteamSessions_StaticRegisterNativesFBPSteamWorkshopItemDetails
{
FScriptStruct_AdvancedSteamSessions_StaticRegisterNativesFBPSteamWorkshopItemDetails()
{
UScriptStruct::DeferCppStructOps(FName(TEXT("BPSteamWorkshopItemDetails")),new UScriptStruct::TCppStructOps<FBPSteamWorkshopItemDetails>);
}
} ScriptStruct_AdvancedSteamSessions_StaticRegisterNativesFBPSteamWorkshopItemDetails;
UScriptStruct* Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails()
{
#if WITH_HOT_RELOAD
extern uint32 Get_Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails_CRC();
UPackage* Outer = Z_Construct_UPackage__Script_AdvancedSteamSessions();
static UScriptStruct* ReturnStruct = FindExistingStructIfHotReloadOrDynamic(Outer, TEXT("BPSteamWorkshopItemDetails"), sizeof(FBPSteamWorkshopItemDetails), Get_Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails_CRC(), false);
#else
static UScriptStruct* ReturnStruct = nullptr;
#endif
if (!ReturnStruct)
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Struct_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "WorkshopItemDetails Struct" },
};
#endif
auto NewStructOpsLambda = []() -> void* { return (UScriptStruct::ICppStructOps*)new UScriptStruct::TCppStructOps<FBPSteamWorkshopItemDetails>(); };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CreatorSteamID_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Steam ID of the user who created this content." },
};
#endif
static const UE4CodeGen_Private::FStrPropertyParams NewProp_CreatorSteamID = { UE4CodeGen_Private::EPropertyClass::Str, "CreatorSteamID", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, CreatorSteamID), METADATA_PARAMS(NewProp_CreatorSteamID_MetaData, ARRAY_COUNT(NewProp_CreatorSteamID_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bTagsTruncated_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "whether the list of tags was too long to be returned in the provided buffer" },
};
#endif
auto NewProp_bTagsTruncated_SetBit = [](void* Obj){ ((FBPSteamWorkshopItemDetails*)Obj)->bTagsTruncated = 1; };
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bTagsTruncated = { UE4CodeGen_Private::EPropertyClass::Bool, "bTagsTruncated", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(FBPSteamWorkshopItemDetails), &UE4CodeGen_Private::TBoolSetBitWrapper<decltype(NewProp_bTagsTruncated_SetBit)>::SetBit, METADATA_PARAMS(NewProp_bTagsTruncated_MetaData, ARRAY_COUNT(NewProp_bTagsTruncated_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bAcceptedForUse_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "developer has specifically flagged this item as accepted in the Workshop" },
};
#endif
auto NewProp_bAcceptedForUse_SetBit = [](void* Obj){ ((FBPSteamWorkshopItemDetails*)Obj)->bAcceptedForUse = 1; };
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bAcceptedForUse = { UE4CodeGen_Private::EPropertyClass::Bool, "bAcceptedForUse", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(FBPSteamWorkshopItemDetails), &UE4CodeGen_Private::TBoolSetBitWrapper<decltype(NewProp_bAcceptedForUse_SetBit)>::SetBit, METADATA_PARAMS(NewProp_bAcceptedForUse_MetaData, ARRAY_COUNT(NewProp_bAcceptedForUse_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bBanned_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "whether the file was banned" },
};
#endif
auto NewProp_bBanned_SetBit = [](void* Obj){ ((FBPSteamWorkshopItemDetails*)Obj)->bBanned = 1; };
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bBanned = { UE4CodeGen_Private::EPropertyClass::Bool, "bBanned", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(FBPSteamWorkshopItemDetails), &UE4CodeGen_Private::TBoolSetBitWrapper<decltype(NewProp_bBanned_SetBit)>::SetBit, METADATA_PARAMS(NewProp_bBanned_MetaData, ARRAY_COUNT(NewProp_bBanned_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CalculatedScore_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Calculated score" },
};
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_CalculatedScore = { UE4CodeGen_Private::EPropertyClass::Float, "CalculatedScore", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, CalculatedScore), METADATA_PARAMS(NewProp_CalculatedScore_MetaData, ARRAY_COUNT(NewProp_CalculatedScore_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_VotesDown_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
};
#endif
static const UE4CodeGen_Private::FIntPropertyParams NewProp_VotesDown = { UE4CodeGen_Private::EPropertyClass::Int, "VotesDown", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, VotesDown), METADATA_PARAMS(NewProp_VotesDown_MetaData, ARRAY_COUNT(NewProp_VotesDown_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_VotesUp_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Votes will be unlikely to go above signed limited" },
};
#endif
static const UE4CodeGen_Private::FIntPropertyParams NewProp_VotesUp = { UE4CodeGen_Private::EPropertyClass::Int, "VotesUp", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, VotesUp), METADATA_PARAMS(NewProp_VotesUp_MetaData, ARRAY_COUNT(NewProp_VotesUp_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ItemUrl_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Url for a video of website" },
};
#endif
static const UE4CodeGen_Private::FStrPropertyParams NewProp_ItemUrl = { UE4CodeGen_Private::EPropertyClass::Str, "ItemUrl", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, ItemUrl), METADATA_PARAMS(NewProp_ItemUrl_MetaData, ARRAY_COUNT(NewProp_ItemUrl_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Description_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Description of item" },
};
#endif
static const UE4CodeGen_Private::FStrPropertyParams NewProp_Description = { UE4CodeGen_Private::EPropertyClass::Str, "Description", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, Description), METADATA_PARAMS(NewProp_Description_MetaData, ARRAY_COUNT(NewProp_Description_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Title_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Title of item" },
};
#endif
static const UE4CodeGen_Private::FStrPropertyParams NewProp_Title = { UE4CodeGen_Private::EPropertyClass::Str, "Title", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, Title), METADATA_PARAMS(NewProp_Title_MetaData, ARRAY_COUNT(NewProp_Title_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ConsumerAppID_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
};
#endif
static const UE4CodeGen_Private::FIntPropertyParams NewProp_ConsumerAppID = { UE4CodeGen_Private::EPropertyClass::Int, "ConsumerAppID", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, ConsumerAppID), METADATA_PARAMS(NewProp_ConsumerAppID_MetaData, ARRAY_COUNT(NewProp_ConsumerAppID_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CreatorAppID_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "These two are listed as baked to an int, but is stored as a uint, think its safe to keep int" },
};
#endif
static const UE4CodeGen_Private::FIntPropertyParams NewProp_CreatorAppID = { UE4CodeGen_Private::EPropertyClass::Int, "CreatorAppID", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, CreatorAppID), METADATA_PARAMS(NewProp_CreatorAppID_MetaData, ARRAY_COUNT(NewProp_CreatorAppID_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FileType_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Type of file" },
};
#endif
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_FileType = { UE4CodeGen_Private::EPropertyClass::Enum, "FileType", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, FileType), Z_Construct_UEnum_AdvancedSteamSessions_FBPWorkshopFileType, METADATA_PARAMS(NewProp_FileType_MetaData, ARRAY_COUNT(NewProp_FileType_MetaData)) };
static const UE4CodeGen_Private::FBytePropertyParams NewProp_FileType_Underlying = { UE4CodeGen_Private::EPropertyClass::Byte, "UnderlyingType", RF_Public|RF_Transient|RF_MarkAsNative, 0x0000000000000000, 1, nullptr, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ResultOfRequest_MetaData[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Result of obtaining the details" },
};
#endif
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_ResultOfRequest = { UE4CodeGen_Private::EPropertyClass::Enum, "ResultOfRequest", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000015, 1, nullptr, STRUCT_OFFSET(FBPSteamWorkshopItemDetails, ResultOfRequest), Z_Construct_UEnum_AdvancedSteamSessions_FBPSteamResult, METADATA_PARAMS(NewProp_ResultOfRequest_MetaData, ARRAY_COUNT(NewProp_ResultOfRequest_MetaData)) };
static const UE4CodeGen_Private::FBytePropertyParams NewProp_ResultOfRequest_Underlying = { UE4CodeGen_Private::EPropertyClass::Byte, "UnderlyingType", RF_Public|RF_Transient|RF_MarkAsNative, 0x0000000000000000, 1, nullptr, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_CreatorSteamID,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_bTagsTruncated,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_bAcceptedForUse,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_bBanned,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_CalculatedScore,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_VotesDown,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_VotesUp,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_ItemUrl,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_Description,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_Title,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_ConsumerAppID,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_CreatorAppID,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_FileType,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_FileType_Underlying,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_ResultOfRequest,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_ResultOfRequest_Underlying,
};
static const UE4CodeGen_Private::FStructParams ReturnStructParams = {
(UObject* (*)())Z_Construct_UPackage__Script_AdvancedSteamSessions,
nullptr,
&UE4CodeGen_Private::TNewCppStructOpsWrapper<decltype(NewStructOpsLambda)>::NewCppStructOps,
"BPSteamWorkshopItemDetails",
RF_Public|RF_Transient|RF_MarkAsNative,
EStructFlags(0x00000001),
sizeof(FBPSteamWorkshopItemDetails),
alignof(FBPSteamWorkshopItemDetails),
PropPointers, ARRAY_COUNT(PropPointers),
METADATA_PARAMS(Struct_MetaDataParams, ARRAY_COUNT(Struct_MetaDataParams))
};
UE4CodeGen_Private::ConstructUScriptStruct(ReturnStruct, ReturnStructParams);
}
return ReturnStruct;
}
uint32 Get_Z_Construct_UScriptStruct_FBPSteamWorkshopItemDetails_CRC() { return 4132893010U; }
class UScriptStruct* FBPSteamWorkshopID::StaticStruct()
{
static class UScriptStruct* Singleton = NULL;
if (!Singleton)
{
extern ADVANCEDSTEAMSESSIONS_API uint32 Get_Z_Construct_UScriptStruct_FBPSteamWorkshopID_CRC();
Singleton = GetStaticStruct(Z_Construct_UScriptStruct_FBPSteamWorkshopID, Z_Construct_UPackage__Script_AdvancedSteamSessions(), TEXT("BPSteamWorkshopID"), sizeof(FBPSteamWorkshopID), Get_Z_Construct_UScriptStruct_FBPSteamWorkshopID_CRC());
}
return Singleton;
}
static FCompiledInDeferStruct Z_CompiledInDeferStruct_UScriptStruct_FBPSteamWorkshopID(FBPSteamWorkshopID::StaticStruct, TEXT("/Script/AdvancedSteamSessions"), TEXT("BPSteamWorkshopID"), false, nullptr, nullptr);
static struct FScriptStruct_AdvancedSteamSessions_StaticRegisterNativesFBPSteamWorkshopID
{
FScriptStruct_AdvancedSteamSessions_StaticRegisterNativesFBPSteamWorkshopID()
{
UScriptStruct::DeferCppStructOps(FName(TEXT("BPSteamWorkshopID")),new UScriptStruct::TCppStructOps<FBPSteamWorkshopID>);
}
} ScriptStruct_AdvancedSteamSessions_StaticRegisterNativesFBPSteamWorkshopID;
UScriptStruct* Z_Construct_UScriptStruct_FBPSteamWorkshopID()
{
#if WITH_HOT_RELOAD
extern uint32 Get_Z_Construct_UScriptStruct_FBPSteamWorkshopID_CRC();
UPackage* Outer = Z_Construct_UPackage__Script_AdvancedSteamSessions();
static UScriptStruct* ReturnStruct = FindExistingStructIfHotReloadOrDynamic(Outer, TEXT("BPSteamWorkshopID"), sizeof(FBPSteamWorkshopID), Get_Z_Construct_UScriptStruct_FBPSteamWorkshopID_CRC(), false);
#else
static UScriptStruct* ReturnStruct = nullptr;
#endif
if (!ReturnStruct)
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Struct_MetaDataParams[] = {
{ "BlueprintType", "true" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Using a custom struct because uint32 isn't blueprint supported and I don't want to cast to int32\ndue to the size of the workshop it could end up overflowing?" },
};
#endif
auto NewStructOpsLambda = []() -> void* { return (UScriptStruct::ICppStructOps*)new UScriptStruct::TCppStructOps<FBPSteamWorkshopID>(); };
static const UE4CodeGen_Private::FStructParams ReturnStructParams = {
(UObject* (*)())Z_Construct_UPackage__Script_AdvancedSteamSessions,
nullptr,
&UE4CodeGen_Private::TNewCppStructOpsWrapper<decltype(NewStructOpsLambda)>::NewCppStructOps,
"BPSteamWorkshopID",
RF_Public|RF_Transient|RF_MarkAsNative,
EStructFlags(0x00000001),
sizeof(FBPSteamWorkshopID),
alignof(FBPSteamWorkshopID),
nullptr, 0,
METADATA_PARAMS(Struct_MetaDataParams, ARRAY_COUNT(Struct_MetaDataParams))
};
UE4CodeGen_Private::ConstructUScriptStruct(ReturnStruct, ReturnStructParams);
}
return ReturnStruct;
}
uint32 Get_Z_Construct_UScriptStruct_FBPSteamWorkshopID_CRC() { return 681386365U; }
void UAdvancedSteamWorkshopLibrary::StaticRegisterNativesUAdvancedSteamWorkshopLibrary()
{
UClass* Class = UAdvancedSteamWorkshopLibrary::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "GetNumSubscribedWorkshopItems", (Native)&UAdvancedSteamWorkshopLibrary::execGetNumSubscribedWorkshopItems },
{ "GetSubscribedWorkshopItems", (Native)&UAdvancedSteamWorkshopLibrary::execGetSubscribedWorkshopItems },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs));
}
UFunction* Z_Construct_UFunction_UAdvancedSteamWorkshopLibrary_GetNumSubscribedWorkshopItems()
{
struct AdvancedSteamWorkshopLibrary_eventGetNumSubscribedWorkshopItems_Parms
{
int32 NumberOfItems;
};
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
static const UE4CodeGen_Private::FIntPropertyParams NewProp_NumberOfItems = { UE4CodeGen_Private::EPropertyClass::Int, "NumberOfItems", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000180, 1, nullptr, STRUCT_OFFSET(AdvancedSteamWorkshopLibrary_eventGetNumSubscribedWorkshopItems_Parms, NumberOfItems), METADATA_PARAMS(nullptr, 0) };
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_NumberOfItems,
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
};
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedSteamWorkshopLibrary, "GetNumSubscribedWorkshopItems", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04422401, sizeof(AdvancedSteamWorkshopLibrary_eventGetNumSubscribedWorkshopItems_Parms), PropPointers, ARRAY_COUNT(PropPointers), 0, 0, METADATA_PARAMS(Function_MetaDataParams, ARRAY_COUNT(Function_MetaDataParams)) };
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, FuncParams);
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_UAdvancedSteamWorkshopLibrary_GetSubscribedWorkshopItems()
{
struct AdvancedSteamWorkshopLibrary_eventGetSubscribedWorkshopItems_Parms
{
int32 NumberOfItems;
TArray<FBPSteamWorkshopID> ReturnValue;
};
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
static const UE4CodeGen_Private::FArrayPropertyParams NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Array, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000580, 1, nullptr, STRUCT_OFFSET(AdvancedSteamWorkshopLibrary_eventGetSubscribedWorkshopItems_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) };
static const UE4CodeGen_Private::FStructPropertyParams NewProp_ReturnValue_Inner = { UE4CodeGen_Private::EPropertyClass::Struct, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, 0x0000000000000000, 1, nullptr, 0, Z_Construct_UScriptStruct_FBPSteamWorkshopID, METADATA_PARAMS(nullptr, 0) };
static const UE4CodeGen_Private::FIntPropertyParams NewProp_NumberOfItems = { UE4CodeGen_Private::EPropertyClass::Int, "NumberOfItems", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000180, 1, nullptr, STRUCT_OFFSET(AdvancedSteamWorkshopLibrary_eventGetSubscribedWorkshopItems_Parms, NumberOfItems), METADATA_PARAMS(nullptr, 0) };
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_ReturnValue_Inner,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_NumberOfItems,
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[] = {
{ "Category", "Online|AdvancedSteamWorkshop" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
{ "ToolTip", "Returns IDs for subscribed workshop items, TArray length dictates how many" },
};
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedSteamWorkshopLibrary, "GetSubscribedWorkshopItems", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04422401, sizeof(AdvancedSteamWorkshopLibrary_eventGetSubscribedWorkshopItems_Parms), PropPointers, ARRAY_COUNT(PropPointers), 0, 0, METADATA_PARAMS(Function_MetaDataParams, ARRAY_COUNT(Function_MetaDataParams)) };
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UAdvancedSteamWorkshopLibrary_NoRegister()
{
return UAdvancedSteamWorkshopLibrary::StaticClass();
}
UClass* Z_Construct_UClass_UAdvancedSteamWorkshopLibrary()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
static UObject* (*const DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UBlueprintFunctionLibrary,
(UObject* (*)())Z_Construct_UPackage__Script_AdvancedSteamSessions,
};
static const FClassFunctionLinkInfo FuncInfo[] = {
{ &Z_Construct_UFunction_UAdvancedSteamWorkshopLibrary_GetNumSubscribedWorkshopItems, "GetNumSubscribedWorkshopItems" }, // 2627853409
{ &Z_Construct_UFunction_UAdvancedSteamWorkshopLibrary_GetSubscribedWorkshopItems, "GetSubscribedWorkshopItems" }, // 2771087718
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[] = {
{ "IncludePath", "AdvancedSteamWorkshopLibrary.h" },
{ "ModuleRelativePath", "Classes/AdvancedSteamWorkshopLibrary.h" },
};
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo = {
TCppClassTypeTraits<UAdvancedSteamWorkshopLibrary>::IsAbstract,
};
static const UE4CodeGen_Private::FClassParams ClassParams = {
&UAdvancedSteamWorkshopLibrary::StaticClass,
DependentSingletons, ARRAY_COUNT(DependentSingletons),
0x00000080u,
FuncInfo, ARRAY_COUNT(FuncInfo),
nullptr, 0,
nullptr,
&StaticCppClassTypeInfo,
nullptr, 0,
METADATA_PARAMS(Class_MetaDataParams, ARRAY_COUNT(Class_MetaDataParams))
};
UE4CodeGen_Private::ConstructUClass(OuterClass, ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UAdvancedSteamWorkshopLibrary, 63622373);
static FCompiledInDefer Z_CompiledInDefer_UClass_UAdvancedSteamWorkshopLibrary(Z_Construct_UClass_UAdvancedSteamWorkshopLibrary, &UAdvancedSteamWorkshopLibrary::StaticClass, TEXT("/Script/AdvancedSteamSessions"), TEXT("UAdvancedSteamWorkshopLibrary"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UAdvancedSteamWorkshopLibrary);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
|
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the WTFPLv2. See the LICENSE
* file for more details. */
#include "zstream.h"
#include <stdexcept>
#include <zlib.h>
namespace
{
const int chunk = 256 * 1024;
}
void compress(std::istream & input, std::ostream & output, int level, int window)
{
unsigned char in[chunk];
unsigned char out[chunk];
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
if(deflateInit2(&strm,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
window,
level,
Z_DEFAULT_STRATEGY) != Z_OK)
{
throw std::runtime_error("deflateInit");
}
int flush;
do
{
input.read(reinterpret_cast<char*>(in), chunk);
strm.avail_in = input.gcount();
flush = (input.eof() || input.fail()) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
do
{
strm.avail_out = chunk;
strm.next_out = out;
deflate(&strm, flush);
output.write(reinterpret_cast<char*>(out), chunk - strm.avail_out);
}
while (strm.avail_out == 0);
}
while(flush != Z_FINISH);
deflateEnd(&strm);
}
void decompress(std::istream & input, std::ostream & output, int window)
{
unsigned char in[chunk];
unsigned char out[chunk];
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
if(inflateInit2(&strm,
window))
{
throw std::runtime_error("inflateInit");
}
int ret;
do
{
input.read(reinterpret_cast<char*>(in), chunk);
strm.avail_in = input.gcount();
if(strm.avail_in == 0)
{
inflateEnd(&strm);
throw std::runtime_error("unexpected end of stream");
}
strm.next_in = in;
do
{
strm.avail_out = chunk;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
if(ret == Z_STREAM_ERROR ||
ret == Z_NEED_DICT ||
ret == Z_DATA_ERROR ||
ret == Z_MEM_ERROR)
{
inflateEnd(&strm);
throw std::runtime_error("inflate");
}
output.write(reinterpret_cast<char*>(out), chunk - strm.avail_out);
}
while(strm.avail_out == 0);
}
while(ret != Z_STREAM_END);
inflateEnd(&strm);
}
|
// 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 "chrome/browser/chromeos/ui/idle_logout_dialog_view.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/chromeos/kiosk_mode/mock_kiosk_mode_settings.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/widget/widget.h"
namespace chromeos {
class MockIdleLogoutSettingsProvider : public IdleLogoutSettingsProvider {
public:
explicit MockIdleLogoutSettingsProvider(KioskModeSettings* mock_settings)
: mock_settings_(mock_settings) {}
virtual base::TimeDelta GetCountdownUpdateInterval() OVERRIDE {
return base::TimeDelta::FromMilliseconds(0);
}
virtual KioskModeSettings* GetKioskModeSettings() OVERRIDE {
return mock_settings_;
}
virtual void LogoutCurrentUser(IdleLogoutDialogView* dialog) OVERRIDE {
dialog->GetWidget()->Close();
}
private:
KioskModeSettings* mock_settings_;
DISALLOW_COPY_AND_ASSIGN(MockIdleLogoutSettingsProvider);
};
class IdleLogoutDialogViewTest : public InProcessBrowserTest {
public:
IdleLogoutDialogViewTest() {}
virtual ~IdleLogoutDialogViewTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
mock_settings_.reset(new MockKioskModeSettings());
mock_provider_.reset(
new MockIdleLogoutSettingsProvider(mock_settings_.get()));
IdleLogoutDialogView::set_settings_provider(mock_provider_.get());
}
void ExpectOpenDialog() {
IdleLogoutDialogView* dialog = IdleLogoutDialogView::current_instance();
ASSERT_TRUE(dialog != NULL);
EXPECT_TRUE(dialog->visible());
}
void ExpectClosedDialog() {
EXPECT_TRUE(IdleLogoutDialogView::current_instance() == NULL);
}
private:
scoped_ptr<MockIdleLogoutSettingsProvider> mock_provider_;
scoped_ptr<MockKioskModeSettings> mock_settings_;
DISALLOW_COPY_AND_ASSIGN(IdleLogoutDialogViewTest);
};
IN_PROC_BROWSER_TEST_F(IdleLogoutDialogViewTest, ShowDialogAndClose) {
IdleLogoutDialogView::ShowDialog();
EXPECT_NO_FATAL_FAILURE(ExpectOpenDialog());
IdleLogoutDialogView::CloseDialog();
ExpectClosedDialog();
}
IN_PROC_BROWSER_TEST_F(IdleLogoutDialogViewTest, ShowDialogAndCloseView) {
IdleLogoutDialogView::ShowDialog();
EXPECT_NO_FATAL_FAILURE(ExpectOpenDialog());
IdleLogoutDialogView::CloseDialog();
content::RunAllPendingInMessageLoop();
ExpectClosedDialog();
}
IN_PROC_BROWSER_TEST_F(IdleLogoutDialogViewTest, ShowDialogAndCloseViewClose) {
IdleLogoutDialogView::ShowDialog();
EXPECT_NO_FATAL_FAILURE(ExpectOpenDialog());
IdleLogoutDialogView::CloseDialog();
content::RunAllPendingInMessageLoop();
IdleLogoutDialogView::CloseDialog();
ExpectClosedDialog();
}
IN_PROC_BROWSER_TEST_F(IdleLogoutDialogViewTest,
OutOfOrderMultipleShowDialogAndClose) {
IdleLogoutDialogView::CloseDialog();
ExpectClosedDialog();
IdleLogoutDialogView::ShowDialog();
EXPECT_NO_FATAL_FAILURE(ExpectOpenDialog());
IdleLogoutDialogView::ShowDialog();
EXPECT_NO_FATAL_FAILURE(ExpectOpenDialog());
IdleLogoutDialogView::CloseDialog();
ExpectClosedDialog();
IdleLogoutDialogView::CloseDialog();
ExpectClosedDialog();
}
IN_PROC_BROWSER_TEST_F(IdleLogoutDialogViewTest,
ShowDialogAndFinishCountdown) {
IdleLogoutDialogView::ShowDialog();
EXPECT_NO_FATAL_FAILURE(ExpectOpenDialog());
content::RunAllPendingInMessageLoop();
ExpectClosedDialog();
}
} // namespace chromeos
|
/*
* Copyright 2004-2020 Hewlett Packard Enterprise Development LP
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "mysystem.h"
#include "misc.h"
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
bool printSystemCommands = false;
int mysystem(const char* command,
const char* description,
bool ignoreStatus,
bool quiet) {
int status = 0;
if (printSystemCommands && !quiet) {
printf("\n# %s\n", description);
printf("%s\n", command);
fflush(stdout);
fflush(stderr);
}
// Treat a '#' at the start of a line as a comment
if (command[0] == '#')
return 0;
status = system(command);
if (status == -1) {
USR_FATAL("system() fork failed: %s", strerror(errno));
} else if (status != 0 && ignoreStatus == false) {
USR_FATAL(description);
}
return status;
}
|
#include "lf_gi_filter_pass.h"
#include <Engine/Common/IRenderingContext.h>
#include <Engine/Common/types/constant_buffer_info.h>
#include <Engine/Common/types/image_bind_type.h>
#include <Engine/Common/types/image_buffer_format.h>
#include <Engine/Common/types/image_buffer_info.h>
#include <Engine/Common/types/image_buffer_type.h>
#include <Engine/Common/types/shader_info.h>
#include <Engine/Common/types/shader_stage.h>
#include <Engine/IRenderer.h>
#include <rw_engine/rw_macro_constexpr.h>
using namespace rh::engine;
rw_raytracing_lib::LowFreqGIFilterPass::LowFreqGIFilterPass( size_t w, size_t h, float lf_scale )
{
auto allocator = g_pRHRenderer->GetGPUAllocator();
allocator->AllocateShader( {"shaders/d3d11/lf_gi_filter.hlsl",
"LowFreqGIFilter",
ShaderStage::Compute},
mLowFreqGIFilterCS );
allocator->AllocateShader( {"shaders/d3d11/lf_gi_prefilter.hlsl",
"LowFreqGIPreFilter",
ShaderStage::Compute},
mLowFreqGIPreFilterCS );
dispatchThreadsX = w / mThreadGroupSize;
dispatchThreadsY = h / mThreadGroupSize;
dispatchThreadsZ = 1;
ImageBufferInfo createInfo_{};
createInfo_.type = ImageBufferType::RenderTargetBuffer;
createInfo_.width = w;
createInfo_.height = h;
createInfo_.mipLevels = 1;
createInfo_.format = ImageBufferFormat::RGBA8;
allocator->AllocateImageBuffer( createInfo_, mFilterResult );
createInfo_.type = ImageBufferType::RenderTargetBuffer;
createInfo_.width = static_cast<uint32_t>( w * lf_scale );
createInfo_.height = static_cast<uint32_t>( h * lf_scale );
createInfo_.mipLevels = 1;
createInfo_.format = ImageBufferFormat::RGBA16;
allocator->AllocateImageBuffer( createInfo_, mPreFilteredSHY_Ping );
allocator->AllocateImageBuffer( createInfo_, mPreFilteredSHY_Pong );
createInfo_.type = ImageBufferType::RenderTargetBuffer;
createInfo_.width = static_cast<uint32_t>( w * lf_scale );
createInfo_.height = static_cast<uint32_t>( h * lf_scale );
createInfo_.mipLevels = 1;
createInfo_.format = ImageBufferFormat::RG16;
allocator->AllocateImageBuffer( createInfo_, mPreFilteredSHCoCg_Ping );
allocator->AllocateImageBuffer( createInfo_, mPreFilteredSHCoCg_Pong );
ConstantBufferInfo cb_info{};
cb_info.size = sizeof( LFFilterParams );
allocator->AllocateConstantBuffer( cb_info, mPreFilterParamsCB );
mPreFilterParams.fRenderingScale = lf_scale;
IRenderingContext *context = static_cast<IRenderingContext *>(
g_pRHRenderer->GetCurrentContext() );
context->UpdateBuffer( mPreFilterParamsCB, reinterpret_cast<void *>( &mPreFilterParams ), -1 );
}
rw_raytracing_lib::LowFreqGIFilterPass::~LowFreqGIFilterPass()
{
auto allocator = g_pRHRenderer->GetGPUAllocator();
allocator->FreeImageBuffer( mFilterResult, ImageBufferType::RenderTargetBuffer );
}
void *rw_raytracing_lib::LowFreqGIFilterPass::Execute(
void *gbPos, void *gbNormals, void *shY, void *shCoCg, void *gbColor, void *gbRadiance )
{
IRenderingContext *context = static_cast<IRenderingContext *>(
g_pRHRenderer->GetCurrentContext() );
// Pre filter low frequency spherical harmonics
mPreFilterParams.nPreFilterIteration = 0;
PreFilter( shY, shCoCg, mPreFilteredSHY_Ping, mPreFilteredSHCoCg_Ping, gbPos, gbNormals );
mPreFilterParams.nPreFilterIteration++;
for ( int i = 0; i < 1; i++ ) {
PreFilter( mPreFilteredSHY_Ping,
mPreFilteredSHCoCg_Ping,
mPreFilteredSHY_Pong,
mPreFilteredSHCoCg_Pong,
gbPos,
gbNormals );
mPreFilterParams.nPreFilterIteration++;
PreFilter( mPreFilteredSHY_Pong,
mPreFilteredSHCoCg_Pong,
mPreFilteredSHY_Ping,
mPreFilteredSHCoCg_Ping,
gbPos,
gbNormals );
mPreFilterParams.nPreFilterIteration++;
}
PreFilter( mPreFilteredSHY_Ping,
mPreFilteredSHCoCg_Ping,
mPreFilteredSHY_Pong,
mPreFilteredSHCoCg_Pong,
gbPos,
gbNormals );
// Project LowFrequency SH
context->BindShader( mLowFreqGIFilterCS );
context->BindImageBuffers( ImageBindType::UnorderedAccessTarget, {{0, mFilterResult}} );
context->BindImageBuffers( ImageBindType::CSResource,
{{0, gbPos},
{1, gbNormals},
{2, mPreFilteredSHY_Pong},
{3, mPreFilteredSHCoCg_Pong},
{4, gbColor},
{5, gbRadiance}} );
context->FlushCache();
context->DispatchThreads( dispatchThreadsX, dispatchThreadsY, dispatchThreadsZ );
context->ResetShader( mLowFreqGIFilterCS );
context->BindImageBuffers( ImageBindType::UnorderedAccessTarget, {{0, nullptr}} );
context->BindImageBuffers( ImageBindType::CSResource,
{{0, nullptr},
{1, nullptr},
{2, nullptr},
{3, nullptr},
{4, nullptr},
{5, nullptr}} );
context->FlushCache();
return mFilterResult;
}
void rw_raytracing_lib::LowFreqGIFilterPass::PreFilter(
void *shY_in, void *shCoCg_in, void *shY_out, void *shCoCg_out, void *gbPos, void *gbNormals )
{
IRenderingContext *context = static_cast<IRenderingContext *>(
g_pRHRenderer->GetCurrentContext() );
context->UpdateBuffer( mPreFilterParamsCB, reinterpret_cast<void *>( &mPreFilterParams ), -1 );
context->BindConstantBuffers( ShaderStage::Compute, {{1, mPreFilterParamsCB}} );
// Pre filter low frequency spherical harmonics
context->BindShader( mLowFreqGIPreFilterCS );
context->BindImageBuffers( ImageBindType::UnorderedAccessTarget,
{{0, shY_out}, {1, shCoCg_out}} );
context->BindImageBuffers( ImageBindType::CSResource,
{{0, gbPos}, {1, gbNormals}, {2, shY_in}, {3, shCoCg_in}} );
context->FlushCache();
context->DispatchThreads( dispatchThreadsX, dispatchThreadsY, dispatchThreadsZ );
context->ResetShader( mLowFreqGIPreFilterCS );
context->BindImageBuffers( ImageBindType::UnorderedAccessTarget, {{0, nullptr}, {1, nullptr}} );
context->BindImageBuffers( ImageBindType::CSResource,
{{0, nullptr}, {1, nullptr}, {2, nullptr}, {3, nullptr}} );
context->FlushCache();
}
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2012 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "iotests.h"
#include <map>
#include <climits>
#include <algorithm>
#include "internal.h" /* vbucket_* things from lcb_t */
#include "auth-priv.h"
#include <lcbio/iotable.h>
#include "bucketconfig/bc_http.h"
#define LOGARGS(instance, lvl) \
instance->settings, "tests-MUT", LCB_LOG_##lvl, __FILE__, __LINE__
extern "C" {
static void timings_callback(lcb_t, const void *cookie, lcb_timeunit_t,
lcb_U32, lcb_U32, lcb_U32, lcb_U32)
{
bool *bPtr = (bool *)cookie;
*bPtr = true;
}
}
TEST_F(MockUnitTest, testTimings)
{
lcb_t instance;
HandleWrap hw;
bool called = false;
createConnection(hw, instance);
lcb_enable_timings(instance);
lcb_store_cmd_t storecmd(LCB_SET, "counter", 7, "0", 1);
lcb_store_cmd_t *storecmds[] = { &storecmd };
lcb_store(instance, NULL, 1, storecmds);
lcb_wait(instance);
lcb_get_timings(instance, &called, timings_callback);
lcb_disable_timings(instance);
ASSERT_TRUE(called);
}
namespace {
struct TimingInfo {
lcb_U64 ns_start;
lcb_U64 ns_end;
size_t count;
TimingInfo() : ns_start(-1), ns_end(-1), count(-1) {}
bool operator<(const TimingInfo& other) const {
return other.ns_start > ns_start;
}
bool operator>(const TimingInfo& other) const {
return ns_start > other.ns_start;
}
bool valid() const {
return count != -1;
}
};
static lcb_U64 intervalToNsec(lcb_U64 interval, lcb_timeunit_t unit)
{
if (unit == LCB_TIMEUNIT_NSEC) {
return interval;
} else if (unit == LCB_TIMEUNIT_USEC) {
return interval * 1000;
} else if (unit == LCB_TIMEUNIT_MSEC) {
return interval * 1000000;
} else if (unit == LCB_TIMEUNIT_SEC) {
return interval * 1000000000;
} else {
return -1;
}
}
struct LcbTimings {
LcbTimings() {}
std::vector<TimingInfo> m_info;
void load(lcb_t);
void clear();
TimingInfo infoAt(hrtime_t duration, lcb_timeunit_t unit = LCB_TIMEUNIT_NSEC);
size_t countAt(hrtime_t duration, lcb_timeunit_t unit = LCB_TIMEUNIT_NSEC) {
return infoAt(duration, unit).count;
}
void dump() const;
};
extern "C" {
static void load_timings_callback(lcb_t, const void *cookie, lcb_timeunit_t unit,
lcb_U32 min, lcb_U32 max, lcb_U32 total, lcb_U32 maxtotal)
{
lcb_U64 start = intervalToNsec(min, unit);
lcb_U64 end = intervalToNsec(max, unit);
LcbTimings *timings = (LcbTimings *)cookie;
TimingInfo info;
info.ns_start = start;
info.ns_end = end;
info.count = total;
timings->m_info.push_back(info);
}
} // extern "C"
void
LcbTimings::load(lcb_t instance)
{
lcb_get_timings(instance, this, load_timings_callback);
std::sort(m_info.begin(), m_info.end());
}
TimingInfo
LcbTimings::infoAt(hrtime_t duration, lcb_timeunit_t unit)
{
duration = intervalToNsec(duration, unit);
std::vector<TimingInfo>::iterator ii;
for (ii = m_info.begin(); ii != m_info.end(); ++ii) {
if (ii->ns_start <= duration && ii->ns_end > duration) {
return *ii;
}
}
return TimingInfo();
}
void
LcbTimings::dump() const
{
std::vector<TimingInfo>::const_iterator ii = m_info.begin();
for (; ii != m_info.end(); ii++) {
if (ii->ns_end < 1000) {
printf("[%llu-%llu ns] %lu\n",
ii->ns_start, ii->ns_end, ii->count);
} else if (ii->ns_end < 10000000) {
printf("[%llu-%llu us] %lu\n",
ii->ns_start / 1000, ii->ns_end / 1000, ii->count);
} else {
printf("[%llu-%llu ms] %lu\n",
ii->ns_start / 1000000, ii->ns_end / 1000000, ii->count);
}
}
}
} // namespace{
struct UnitInterval {
lcb_U64 n;
lcb_timeunit_t unit;
UnitInterval(lcb_U64 n, lcb_timeunit_t unit) : n(n), unit(unit) {}
};
static void addTiming(lcb_t instance, const UnitInterval& interval)
{
hrtime_t n = intervalToNsec(interval.n, interval.unit);
lcb_histogram_record(instance->kv_timings, n);
}
TEST_F(MockUnitTest, testTimingsEx)
{
lcb_t instance;
HandleWrap hw;
createConnection(hw, instance);
lcb_disable_timings(instance);
lcb_enable_timings(instance);
std::vector<UnitInterval> intervals;
intervals.push_back(UnitInterval(1, LCB_TIMEUNIT_NSEC));
intervals.push_back(UnitInterval(250, LCB_TIMEUNIT_NSEC));
intervals.push_back(UnitInterval(4, LCB_TIMEUNIT_USEC));
intervals.push_back(UnitInterval(32, LCB_TIMEUNIT_USEC));
intervals.push_back(UnitInterval(942, LCB_TIMEUNIT_USEC));
intervals.push_back(UnitInterval(1243, LCB_TIMEUNIT_USEC));
intervals.push_back(UnitInterval(1732, LCB_TIMEUNIT_USEC));
intervals.push_back(UnitInterval(5630, LCB_TIMEUNIT_USEC));
intervals.push_back(UnitInterval(42, LCB_TIMEUNIT_MSEC));
intervals.push_back(UnitInterval(434, LCB_TIMEUNIT_MSEC));
intervals.push_back(UnitInterval(8234, LCB_TIMEUNIT_MSEC));
intervals.push_back(UnitInterval(1294, LCB_TIMEUNIT_MSEC));
intervals.push_back(UnitInterval(48, LCB_TIMEUNIT_SEC));
for (size_t ii = 0; ii < intervals.size(); ++ii) {
addTiming(instance, intervals[ii]);
}
// Ensure they all exist, at least. Currently we bundle everything
LcbTimings timings;
timings.load(instance);
//timings.dump();
// Measuring in < us
ASSERT_EQ(2, timings.countAt(50, LCB_TIMEUNIT_NSEC));
ASSERT_EQ(1, timings.countAt(4, LCB_TIMEUNIT_USEC));
ASSERT_EQ(1, timings.countAt(30, LCB_TIMEUNIT_USEC));
ASSERT_EQ(-1, timings.countAt(900, LCB_TIMEUNIT_USEC));
ASSERT_EQ(1, timings.countAt(940, LCB_TIMEUNIT_USEC));
ASSERT_EQ(1, timings.countAt(1200, LCB_TIMEUNIT_USEC));
ASSERT_EQ(1, timings.countAt(1250, LCB_TIMEUNIT_USEC));
ASSERT_EQ(1, timings.countAt(5600, LCB_TIMEUNIT_USEC));
ASSERT_EQ(1, timings.countAt(40, LCB_TIMEUNIT_MSEC));
ASSERT_EQ(1, timings.countAt(430, LCB_TIMEUNIT_MSEC));
ASSERT_EQ(1, timings.countAt(1, LCB_TIMEUNIT_SEC));
ASSERT_EQ(1, timings.countAt(8, LCB_TIMEUNIT_SEC));
ASSERT_EQ(1, timings.countAt(93, LCB_TIMEUNIT_SEC));
}
struct async_ctx {
int count;
lcbio_pTABLE table;
};
extern "C" {
static void dtor_callback(const void *cookie)
{
async_ctx *ctx = (async_ctx *)cookie;
ctx->count++;
IOT_STOP(ctx->table);
}
}
TEST_F(MockUnitTest, testAsyncDestroy)
{
lcb_t instance;
createConnection(instance);
lcbio_pTABLE iot = instance->iotable;
lcb_settings *settings = instance->settings;
storeKey(instance, "foo", "bar");
// Now destroy the instance
async_ctx ctx;
ctx.count = 0;
ctx.table = iot;
lcb_set_destroy_callback(instance, dtor_callback);
lcb_destroy_async(instance, &ctx);
lcb_settings_ref(settings);
lcbio_table_ref(iot);
lcb_run_loop(instance);
lcb_settings_unref(settings);
lcbio_table_unref(iot);
ASSERT_EQ(1, ctx.count);
}
TEST_F(MockUnitTest, testGetHostInfo)
{
lcb_t instance;
createConnection(instance);
lcb_config_transport_t tx;
const char *hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG, 0);
ASSERT_FALSE(hoststr == NULL);
hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG_CONNECTED, 0);
lcb_error_t err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_CONFIG_TRANSPORT, &tx);
ASSERT_EQ(LCB_SUCCESS, err);
if (tx == LCB_CONFIG_TRANSPORT_HTTP) {
ASSERT_FALSE(hoststr == NULL);
hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG_CONNECTED, 99);
ASSERT_FALSE(hoststr == NULL);
} else {
if (hoststr) {
printf("%s\n", hoststr);
}
ASSERT_TRUE(hoststr == NULL);
}
// Get any data node
using std::map;
using std::string;
map<string,bool> smap;
// Ensure we only get unique nodes
for (lcb_S32 ii = 0; ii < lcb_get_num_nodes(instance); ii++) {
const char *cur = lcb_get_node(instance, LCB_NODE_DATA, ii);
ASSERT_FALSE(cur == NULL);
ASSERT_FALSE(smap[cur]);
smap[cur] = true;
}
lcb_destroy(instance);
// Try with no connection
err = lcb_create(&instance, NULL);
ASSERT_EQ(LCB_SUCCESS, err);
hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG_CONNECTED, 0);
ASSERT_TRUE(NULL == hoststr);
hoststr = lcb_get_node(instance, LCB_NODE_HTCONFIG, 0);
ASSERT_TRUE(NULL == hoststr);
// These older API functions are special as they should never return NULL
hoststr = lcb_get_host(instance);
ASSERT_FALSE(hoststr == NULL);
ASSERT_STREQ("localhost", hoststr);
hoststr = lcb_get_port(instance);
ASSERT_FALSE(hoststr == NULL);
ASSERT_STREQ("8091", hoststr);
lcb_destroy(instance);
}
TEST_F(MockUnitTest, testEmptyKeys)
{
lcb_t instance;
HandleWrap hw;
createConnection(hw, instance);
union {
lcb_CMDGET get;
lcb_CMDSTORE store;
lcb_CMDCOUNTER counter;
lcb_CMDENDURE endure;
lcb_CMDOBSERVE observe;
lcb_CMDTOUCH touch;
lcb_CMDUNLOCK unlock;
lcb_CMDGETREPLICA rget;
lcb_CMDBASE base;
lcb_CMDSTATS stats;
} u;
memset(&u, 0, sizeof u);
lcb_sched_enter(instance);
ASSERT_EQ(LCB_EMPTY_KEY, lcb_get3(instance, NULL, &u.get));
ASSERT_EQ(LCB_EMPTY_KEY, lcb_store3(instance, NULL, &u.store));
ASSERT_EQ(LCB_EMPTY_KEY, lcb_counter3(instance, NULL, &u.counter));
ASSERT_EQ(LCB_EMPTY_KEY, lcb_touch3(instance, NULL, &u.touch));
ASSERT_EQ(LCB_EMPTY_KEY, lcb_unlock3(instance, NULL, &u.unlock));
ASSERT_EQ(LCB_EMPTY_KEY, lcb_rget3(instance, NULL, &u.rget));
// Observe and such
lcb_MULTICMD_CTX *ctx = lcb_observe3_ctxnew(instance);
ASSERT_EQ(LCB_EMPTY_KEY, ctx->addcmd(ctx, (lcb_CMDBASE*)&u.observe));
ctx->fail(ctx);
lcb_durability_opts_t dopts;
memset(&dopts, 0, sizeof dopts);
dopts.v.v0.persist_to = 1;
ctx = lcb_endure3_ctxnew(instance, &dopts, NULL);
ASSERT_TRUE(ctx != NULL);
ASSERT_EQ(LCB_EMPTY_KEY, ctx->addcmd(ctx, (lcb_CMDBASE*)&u.endure));
ctx->fail(ctx);
ASSERT_EQ(LCB_SUCCESS, lcb_stats3(instance, NULL, &u.stats));
lcb_sched_fail(instance);
}
template <typename T>
static bool ctlSet(lcb_t instance, int setting, T val)
{
lcb_error_t err = lcb_cntl(instance, LCB_CNTL_SET, setting, &val);
return err == LCB_SUCCESS;
}
template<>
bool ctlSet<const char*>(lcb_t instance, int setting, const char *val)
{
return lcb_cntl(instance, LCB_CNTL_SET, setting, (void*)val) == LCB_SUCCESS;
}
template <typename T>
static T ctlGet(lcb_t instance, int setting)
{
T tmp;
lcb_error_t err = lcb_cntl(instance, LCB_CNTL_GET, setting, &tmp);
EXPECT_EQ(LCB_SUCCESS, err);
return tmp;
}
template <typename T>
static void ctlGetSet(lcb_t instance, int setting, T val) {
EXPECT_TRUE(ctlSet<T>(instance, setting, val));
EXPECT_EQ(val, ctlGet<T>(instance, setting));
}
template <>
void ctlGetSet<const char*>(lcb_t instance, int setting, const char *val)
{
EXPECT_TRUE(ctlSet<const char*>(instance, setting, val));
EXPECT_STREQ(val, ctlGet<const char*>(instance, setting));
}
static bool ctlSetInt(lcb_t instance, int setting, int val) {
return ctlSet<int>(instance, setting, val);
}
static int ctlGetInt(lcb_t instance, int setting) {
return ctlGet<int>(instance, setting);
}
static bool ctlSetU32(lcb_t instance, int setting, lcb_U32 val) {
return ctlSet<lcb_U32>(instance, setting, val);
}
static lcb_U32 ctlGetU32(lcb_t instance, int setting) {
return ctlGet<lcb_U32>(instance, setting);
}
TEST_F(MockUnitTest, testCtls)
{
lcb_t instance;
HandleWrap hw;
lcb_error_t err;
createConnection(hw, instance);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_OP_TIMEOUT, UINT_MAX);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_VIEW_TIMEOUT, UINT_MAX);
ASSERT_EQ(LCB_TYPE_BUCKET, ctlGet<lcb_type_t>(instance, LCB_CNTL_HANDLETYPE));
ASSERT_FALSE(ctlSet<lcb_type_t>(instance, LCB_CNTL_HANDLETYPE, LCB_TYPE_BUCKET));
lcbvb_CONFIG *cfg = ctlGet<lcbvb_CONFIG*>(instance, LCB_CNTL_VBCONFIG);
// Do we have a way to verify this?
ASSERT_FALSE(cfg == NULL);
ASSERT_GT(cfg->nsrv, (unsigned int)0);
lcb_io_opt_t io = ctlGet<lcb_io_opt_t>(instance, LCB_CNTL_IOPS);
ASSERT_TRUE(io == instance->getIOT()->p);
// Try to set it?
ASSERT_FALSE(ctlSet<lcb_io_opt_t>(instance, LCB_CNTL_IOPS, (lcb_io_opt_t)"Hello"));
// Map a key
lcb_cntl_vbinfo_t vbi = { 0 };
vbi.v.v0.key = "123";
vbi.v.v0.nkey = 3;
err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_VBMAP, &vbi);
ASSERT_EQ(LCB_SUCCESS, err);
// Try to modify it?
err = lcb_cntl(instance, LCB_CNTL_SET, LCB_CNTL_VBMAP, &vbi);
ASSERT_NE(LCB_SUCCESS, err);
ctlGetSet<lcb_ipv6_t>(instance, LCB_CNTL_IP6POLICY, LCB_IPV6_DISABLED);
ctlGetSet<lcb_ipv6_t>(instance, LCB_CNTL_IP6POLICY, LCB_IPV6_ONLY);
ctlGetSet<lcb_SIZE>(instance, LCB_CNTL_CONFERRTHRESH, UINT_MAX);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_DURABILITY_TIMEOUT, UINT_MAX);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_DURABILITY_INTERVAL, UINT_MAX);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_HTTP_TIMEOUT, UINT_MAX);
ctlGetSet<int>(instance, LCB_CNTL_IOPS_DLOPEN_DEBUG, 55);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_CONFIGURATION_TIMEOUT, UINT_MAX);
ctlGetSet<int>(instance, LCB_CNTL_RANDOMIZE_BOOTSTRAP_HOSTS, 1);
ctlGetSet<int>(instance, LCB_CNTL_RANDOMIZE_BOOTSTRAP_HOSTS, 0);
ASSERT_EQ(0, ctlGetInt(instance, LCB_CNTL_CONFIG_CACHE_LOADED));
ASSERT_FALSE(ctlSetInt(instance, LCB_CNTL_CONFIG_CACHE_LOADED, 99));
ctlGetSet<const char*>(instance, LCB_CNTL_FORCE_SASL_MECH, "SECRET");
ctlGetSet<int>(instance, LCB_CNTL_MAX_REDIRECTS, SHRT_MAX);
ctlGetSet<int>(instance, LCB_CNTL_MAX_REDIRECTS, -1);
ctlGetSet<int>(instance, LCB_CNTL_MAX_REDIRECTS, 0);
// LCB_CNTL_LOGGER handled in other tests
ctlGetSet<lcb_U32>(instance, LCB_CNTL_CONFDELAY_THRESH, UINT_MAX);
// CONFIG_TRANSPORT. Test that we shouldn't be able to set it
ASSERT_FALSE(ctlSet<lcb_config_transport_t>(
instance, LCB_CNTL_CONFIG_TRANSPORT, LCB_CONFIG_TRANSPORT_LIST_END));
ctlGetSet<lcb_U32>(instance, LCB_CNTL_CONFIG_NODE_TIMEOUT, UINT_MAX);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_HTCONFIG_IDLE_TIMEOUT, UINT_MAX);
ASSERT_FALSE(ctlSet<const char*>(instance, LCB_CNTL_CHANGESET, "deadbeef"));
ASSERT_FALSE(ctlGet<const char*>(instance, LCB_CNTL_CHANGESET) == NULL);
ctlGetSet<const char*>(instance, LCB_CNTL_CONFIGCACHE, "/foo/bar/baz");
ASSERT_FALSE(ctlSetInt(instance, LCB_CNTL_SSL_MODE, 90));
ASSERT_GE(ctlGetInt(instance, LCB_CNTL_SSL_MODE), 0);
ASSERT_FALSE(ctlSet<const char*>(instance, LCB_CNTL_SSL_CACERT, "/tmp"));
lcb_U32 ro_in, ro_out;
ro_in = LCB_RETRYOPT_CREATE(LCB_RETRY_ON_SOCKERR, LCB_RETRY_CMDS_GET);
ASSERT_TRUE(ctlSet<lcb_U32>(instance, LCB_CNTL_RETRYMODE, ro_in));
ro_out = LCB_RETRYOPT_CREATE(LCB_RETRY_ON_SOCKERR, 0);
err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_RETRYMODE, &ro_out);
ASSERT_EQ(LCB_SUCCESS, err);
ASSERT_EQ(LCB_RETRY_CMDS_GET, LCB_RETRYOPT_GETPOLICY(ro_out));
ASSERT_EQ(LCB_SUCCESS, lcb_cntl_string(instance, "retry_policy", "topochange:get"));
ro_out = LCB_RETRYOPT_CREATE(LCB_RETRY_ON_TOPOCHANGE, 0);
err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_RETRYMODE, &ro_out);
ASSERT_EQ(LCB_RETRY_CMDS_GET, LCB_RETRYOPT_GETPOLICY(ro_out));
ctlGetSet<int>(instance, LCB_CNTL_HTCONFIG_URLTYPE, LCB_HTCONFIG_URLTYPE_COMPAT);
ctlGetSet<int>(instance, LCB_CNTL_COMPRESSION_OPTS, LCB_COMPRESS_FORCE);
ctlSetU32(instance, LCB_CNTL_CONLOGGER_LEVEL, 3);
lcb_U32 tmp;
err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_CONLOGGER_LEVEL, &tmp);
ASSERT_NE(LCB_SUCCESS, err);
ctlGetSet<int>(instance, LCB_CNTL_DETAILED_ERRCODES, 1);
ctlGetSet<lcb_U32>(instance, LCB_CNTL_RETRY_INTERVAL, UINT_MAX);
ctlGetSet<float>(instance, LCB_CNTL_RETRY_BACKOFF, (float)3.4);
ctlGetSet<lcb_SIZE>(instance, LCB_CNTL_HTTP_POOLSIZE, UINT_MAX);
ctlGetSet<int>(instance, LCB_CNTL_HTTP_REFRESH_CONFIG_ON_ERROR, 0);
// Allow timeouts to be expressed as fractional seconds.
err = lcb_cntl_string(instance, "operation_timeout", "1.0");
ASSERT_EQ(LCB_SUCCESS, err);
ASSERT_EQ(1000000, ctlGet<lcb_U32>(instance, LCB_CNTL_OP_TIMEOUT));
err = lcb_cntl_string(instance, "operation_timeout", "0.255");
ASSERT_EQ(LCB_SUCCESS, err);
ASSERT_EQ(255000, ctlGet<lcb_U32>(instance, LCB_CNTL_OP_TIMEOUT));
// Test default for nmv retry
int itmp = ctlGetInt(instance, LCB_CNTL_RETRY_NMV_IMM);
ASSERT_NE(0, itmp);
err = lcb_cntl_string(instance, "retry_nmv_imm", "0");
ASSERT_EQ(LCB_SUCCESS, err);
itmp = ctlGetInt(instance, LCB_CNTL_RETRY_NMV_IMM);
ASSERT_EQ(0, itmp);
}
TEST_F(MockUnitTest, testConflictingOptions)
{
HandleWrap hw;
lcb_t instance;
createConnection(hw, instance);
lcb_sched_enter(instance);
const char *key = "key";
size_t nkey = 3;
const char *value = "value";
size_t nvalue = 5;
lcb_CMDSTORE scmd = { 0 };
scmd.operation = LCB_APPEND;
scmd.exptime = 1;
LCB_CMD_SET_KEY(&scmd, key, nkey);
LCB_CMD_SET_VALUE(&scmd, value, nvalue);
lcb_error_t err;
err = lcb_store3(instance, NULL, &scmd);
ASSERT_EQ(LCB_OPTIONS_CONFLICT, err);
scmd.exptime = 0;
scmd.flags = 99;
err = lcb_store3(instance, NULL, &scmd);
ASSERT_EQ(LCB_OPTIONS_CONFLICT, err);
scmd.flags = 0;
scmd.exptime = 0;
err = lcb_store3(instance, NULL, &scmd);
ASSERT_EQ(LCB_SUCCESS, err);
scmd.operation = LCB_ADD;
scmd.cas = 0xdeadbeef;
err = lcb_store3(instance, NULL, &scmd);
ASSERT_EQ(LCB_OPTIONS_CONFLICT, err);
scmd.cas = 0;
err = lcb_store3(instance, NULL, &scmd);
ASSERT_EQ(LCB_SUCCESS, err);
lcb_CMDCOUNTER ccmd = { 0 };
LCB_CMD_SET_KEY(&ccmd, key, nkey);
ccmd.cas = 0xdeadbeef;
err = lcb_counter3(instance, NULL, &ccmd);
ASSERT_EQ(LCB_OPTIONS_CONFLICT, err);
ccmd.cas = 0;
err = lcb_counter3(instance, NULL, &ccmd);
ASSERT_EQ(LCB_SUCCESS, err);
ccmd.exptime = 10;
ccmd.initial = 0;
ccmd.create = 0;
err = lcb_counter3(instance, NULL, &ccmd);
ASSERT_EQ(LCB_OPTIONS_CONFLICT, err);
ccmd.create = 1;
err = lcb_counter3(instance, NULL, &ccmd);
ASSERT_EQ(LCB_SUCCESS, err);
lcb_CMDGET gcmd = { 0 };
LCB_CMD_SET_KEY(&gcmd, key, nkey);
gcmd.cas = 0xdeadbeef;
err = lcb_get3(instance, NULL, &gcmd);
ASSERT_EQ(LCB_OPTIONS_CONFLICT, err);
gcmd.cas = 0;
err = lcb_get3(instance, NULL, &gcmd);
ASSERT_EQ(LCB_SUCCESS, err);
lcb_sched_fail(instance);
}
TEST_F(MockUnitTest, testDump)
{
const char *fpname;
#ifdef _WIN32
fpname = "NUL:";
#else
fpname = "/dev/null";
#endif
FILE *fp = fopen(fpname, "w");
if (!fp) {
perror(fpname);
return;
}
// Simply try to dump the instance;
HandleWrap hw;
lcb_t instance;
createConnection(hw, instance);
std::vector<std::string> keys;
genDistKeys(LCBT_VBCONFIG(instance), keys);
for (size_t ii = 0; ii < keys.size(); ii++) {
storeKey(instance, keys[ii], keys[ii]);
}
lcb_dump(instance, fp, LCB_DUMP_ALL);
fclose(fp);
}
TEST_F(MockUnitTest, testRefreshConfig)
{
SKIP_UNLESS_MOCK();
HandleWrap hw;
lcb_t instance;
createConnection(hw, instance);
lcb_refresh_config(instance);
lcb_wait3(instance, LCB_WAIT_NOCHECK);
}
extern "C" {
static void tickOpCb(lcb_t, int, const lcb_RESPBASE *rb)
{
int *p = (int *)rb->cookie;
*p -= 1;
EXPECT_EQ(LCB_SUCCESS, rb->rc);
}
}
TEST_F(MockUnitTest, testTickLoop)
{
HandleWrap hw;
lcb_t instance;
lcb_error_t err;
createConnection(hw, instance);
const char *key = "tickKey";
const char *value = "tickValue";
lcb_install_callback3(instance, LCB_CALLBACK_STORE, tickOpCb);
lcb_CMDSTORE cmd = { 0 };
cmd.operation = LCB_SET;
LCB_CMD_SET_KEY(&cmd, key, strlen(key));
LCB_CMD_SET_VALUE(&cmd, value, strlen(value));
err = lcb_tick_nowait(instance);
if (err == LCB_CLIENT_FEATURE_UNAVAILABLE) {
fprintf(stderr, "Current event loop does not support tick!");
return;
}
lcb_sched_enter(instance);
int counter = 0;
for (int ii = 0; ii < 10; ii++) {
err = lcb_store3(instance, &counter, &cmd);
ASSERT_EQ(LCB_SUCCESS, err);
counter++;
}
lcb_sched_leave(instance);
while (counter) {
lcb_tick_nowait(instance);
}
}
TEST_F(MockUnitTest, testEmptyCtx)
{
HandleWrap hw;
lcb_t instance;
lcb_error_t err = LCB_SUCCESS;
createConnection(hw, instance);
lcb_MULTICMD_CTX *mctx;
lcb_durability_opts_t duropts = { 0 };
duropts.v.v0.persist_to = 1;
mctx = lcb_endure3_ctxnew(instance, &duropts, &err);
ASSERT_EQ(LCB_SUCCESS, err);
ASSERT_FALSE(mctx == NULL);
err = mctx->done(mctx, NULL);
ASSERT_NE(LCB_SUCCESS, err);
mctx = lcb_observe3_ctxnew(instance);
ASSERT_FALSE(mctx == NULL);
err = mctx->done(mctx, NULL);
ASSERT_NE(LCB_SUCCESS, err);
}
TEST_F(MockUnitTest, testMultiCreds)
{
SKIP_IF_CLUSTER_VERSION_IS_HIGHER_THAN(MockEnvironment::VERSION_50);
using lcb::Authenticator;
HandleWrap hw;
lcb_t instance;
createConnection(hw, instance);
lcb_BUCKETCRED cred;
cred[0] = "protected";
cred[1] = "secret";
lcb_error_t rc = lcb_cntl(instance, LCB_CNTL_SET, LCB_CNTL_BUCKET_CRED, cred);
ASSERT_EQ(LCB_SUCCESS, rc);
Authenticator& auth = *instance->settings->auth;
lcb::Authenticator::Map::const_iterator res = auth.buckets().find("protected");
ASSERT_NE(auth.buckets().end(), res);
ASSERT_EQ("secret", res->second);
}
extern "C" {
static void appendE2BIGcb(lcb_t, int, const lcb_RESPBASE *rb)
{
lcb_error_t *e = (lcb_error_t *)rb->cookie;
*e = rb->rc;
}
}
TEST_F(MockUnitTest, testAppendE2BIG)
{
HandleWrap hw;
lcb_t instance;
createConnection(hw, instance);
lcb_install_callback3(instance, LCB_CALLBACK_STORE, appendE2BIGcb);
lcb_error_t err, res;
const char *key = "key";
size_t nkey = strlen(key);
size_t nvalue1 = 20 * 1024 * 1024;
void *value1 = calloc(nvalue1, sizeof(char));
lcb_CMDSTORE scmd = { 0 };
scmd.operation = LCB_SET;
LCB_CMD_SET_KEY(&scmd, key, nkey);
LCB_CMD_SET_VALUE(&scmd, value1, nvalue1);
err = lcb_store3(instance, &res, &scmd);
lcb_wait(instance);
ASSERT_EQ(LCB_SUCCESS, res);
free(value1);
size_t nvalue2 = 1 * 1024 * 1024;
void *value2 = calloc(nvalue2, sizeof(char));
lcb_CMDSTORE acmd = { 0 };
acmd.operation = LCB_APPEND;
LCB_CMD_SET_KEY(&acmd, key, nkey);
LCB_CMD_SET_VALUE(&acmd, value2, nvalue2);
err = lcb_store3(instance, &res, &acmd);
lcb_wait(instance);
ASSERT_EQ(LCB_E2BIG, res);
free(value2);
}
|
//
// odbc_libodbc.hh - SQLite Backend libodbc
//
// Copyright (C) informave.org
// 2010, Daniel Vogelbacher <daniel@vogelbacher.name>
//
// BSD License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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.
//
///
/// @cond DEV_DOCS
/// @file
/// @brief SQLite Backend libodbc
/// @author Daniel Vogelbacher
/// @since 0.0.1
#ifndef INFORMAVE_DB_DAL_ODBC_LIBODBC_HH
#define INFORMAVE_DB_DAL_ODBC_LIBODBC_HH
#include "dbwtl/dal/engines/odbc_engine.hh"
#include "driver_odbc.hh"
DAL_NAMESPACE_BEGIN
#define DBWTL_ODBC_LOB_BUFSIZE 512
#define DBWTL_ODBC_MAX_STRING_SIZE (256*256)
#define DBWTL_ODBC_MAX_VARBINARY_SIZE (256*256)
class OdbcResult_libodbc;
class OdbcStmt_libodbc;
class OdbcDbc_libodbc;
class OdbcEnv_libodbc;
class OdbcData_libodbc;
class OdbcDiag_libodbc;
//------------------------------------------------------------------------------
///
/// @internal
/// @brief OdbcDiag implementation for libodbc
class DBWTL_EXPORT OdbcDiagnosticRec_libodbc : public OdbcDiagnosticRec
{
public:
OdbcDiagnosticRec_libodbc(const CodePosInfo & cpi,
dalstate_t dalstate,
SQLSTATE sqlstate,
const Variant &nativeCode,
const String &msg,
rownum_t rowNum = 0,
colnum_t colNum = 0,
const String &desc = String(),
const Variant &data = Variant());
virtual ~OdbcDiagnosticRec_libodbc(void)
{}
virtual OdbcDiagnosticRec_libodbc* clone(void) const;
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief OdbcDiag implementation for libodbc
class OdbcDiag_libodbc : public OdbcDiag
{
public:
OdbcDiag_libodbc(dalstate_t state,
CodePosInfo pos,
Variant what,
String description,
int odbc_code,
const std::string &sqlstate,
int nativecode);
OdbcDiag_libodbc(const OdbcDiag_libodbc& ref);
virtual ~OdbcDiag_libodbc(void);
virtual String str(void) const;
virtual OdbcDiag_libodbc* clone(void) const;
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief OdbcBlob implementation
class OdbcBlob_libodbc : public OdbcBlob
{
public:
OdbcBlob_libodbc(const OdbcData_libodbc& data, SQLLEN &ind);
virtual ~OdbcBlob_libodbc(void);
virtual bool isNull(void) const;
virtual ODBC30Drv* drv(void) const;
virtual SQLHSTMT getHandle(void) const;
protected:
virtual int_type underflow();
const OdbcData_libodbc& m_data;
char_type m_buf[DAL_STREAMBUF_BUFSIZE + DAL_STREAMBUF_PUTBACK];
SQLLEN &m_ind;
const std::size_t m_putback;
private:
OdbcBlob_libodbc(const OdbcBlob_libodbc&);
OdbcBlob_libodbc& operator=(const OdbcBlob_libodbc&);
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief OdbcMemo implementation
class OdbcMemo_libodbc : public OdbcMemo
{
public:
OdbcMemo_libodbc(const OdbcData_libodbc& data, SQLLEN &ind);
virtual ~OdbcMemo_libodbc(void);
virtual bool isNull(void) const;
virtual ODBC30Drv* drv(void) const;
virtual SQLHSTMT getHandle(void) const;
protected:
virtual int_type underflow();
const OdbcData_libodbc& m_data;
char_type m_buf[DAL_STREAMBUF_BUFSIZE + DAL_STREAMBUF_PUTBACK];
SQLLEN &m_ind;
const std::size_t m_putback;
private:
OdbcMemo_libodbc(const OdbcMemo_libodbc&);
OdbcMemo_libodbc& operator=(const OdbcMemo_libodbc&);
};
template<int T>
struct basic_odbcstr
{
};
template<>
struct basic_odbcstr<1>
{
basic_odbcstr(size_t size = 0)
: m_string()
{
m_string.resize(size);
}
explicit basic_odbcstr(const Variant &var, const std::string &charset)
: m_string()
{
if(!var.isnull())
{
std::string bs = var.asStr().to(charset);
std::copy(bs.begin(), bs.end(), std::back_inserter(m_string));
}
// unixODBC tracer ignores the length of a string but
// assumes SQL_NTS. For this and other broken implementations
// we always add a null-terminator.
// m_string.push_back(0);
}
explicit basic_odbcstr(const String &str, const std::string &charset)
: m_string()
{
std::string bs = str.to(charset);
std::copy(bs.begin(), bs.end(), std::back_inserter(m_string));
// unixODBC tracer ignores the length of a string but
// assumes SQL_NTS. For this and other broken implementations
// we always add a null-terminator.
// m_string.push_back(0);
}
SQLCHAR* ptr(void) const
{
return const_cast<SQLCHAR*>(m_string.data());
}
SQLLEN size(void) const
{
return this->m_string.size();// ? this->m_string.size()-1 : 0;
}
bool empty(void) const
{
return this->m_string.empty();// ||
//(this->m_string.size() == 1 && this->m_string[0] == 0);
}
size_t max_size(void) const
{
return this->m_string.max_size();
}
void resize(SQLLEN len) // in characters
{
this->m_string.resize(len);
}
String str(SQLLEN len, const std::string &charset) const
{
return str(len, charset.c_str());
}
String str(SQLLEN len, const char *charset) const
{
if(len == SQL_NTS)
{
len = 0;
while(m_string[len]) ++len;
}
assert(len >= 0 && (unsigned)len <= m_string.size());
if((unsigned)len > m_string.size())
throw std::out_of_range("length for str() is bigger than current string"); // should never happen
std::string s(reinterpret_cast<const char*>(m_string.data()), len);
return String(s, charset);
}
protected:
mutable std::basic_string<unsigned char> m_string;
};
template<>
struct basic_odbcstr<2>
{
basic_odbcstr(size_t size = 0)
: m_string()
{
m_string.resize(size);
}
explicit basic_odbcstr(const Variant &var)
: m_string()
{
if(!var.isnull())
{
std::wstring ws = var.asStr();
std::copy(ws.begin(), ws.end(), std::back_inserter(m_string));
}
// unixODBC tracer ignores the length of a string but
// assumes SQL_NTS. For this and other broken implementations
// we always add a null-terminator.
//m_string.push_back(0);
}
explicit basic_odbcstr(const String &str)
: m_string()
{
std::wstring ws = str;
std::copy(ws.begin(), ws.end(), std::back_inserter(m_string));
// unixODBC tracer ignores the length of a string but
// assumes SQL_NTS. For this and other broken implementations
// we always add a null-terminator.
// m_string.push_back(0);
}
SQLWCHAR* ptr(void) const
{
return const_cast<SQLWCHAR*>(m_string.data());
}
SQLLEN size(void) const
{
return this->m_string.size();// ? this->m_string.size()-1 : 0;
}
bool empty(void) const
{
return this->m_string.empty();// ||
//(this->m_string.size() == 1 && this->m_string[0] == 0);
}
size_t max_size(void) const
{
return this->m_string.max_size();
}
void resize(SQLLEN len) // in characters
{
this->m_string.resize(len);
}
String str(SQLLEN len) const
{
std::wstring ws;
if(len == SQL_NTS)
{
len = 0;
while(m_string[len]) ++len;
}
std::copy(m_string.begin(), m_string.begin()+len, std::back_inserter(ws));
return String(ws);
}
String str(void) const
{
std::wstring ws;
std::copy(m_string.begin(), m_string.end(), std::back_inserter(ws));
return String(ws);
}
protected:
#ifdef _WIN32
mutable std::basic_string<wchar_t> m_string;
#else
mutable std::basic_string<unsigned short> m_string;
#endif
};
typedef basic_odbcstr<sizeof(SQLWCHAR)> OdbcStrW;
typedef basic_odbcstr<sizeof(SQLCHAR)> OdbcStrA;
struct OdbcValue
{
OdbcValue(void)
: data(),
ind(SQL_NULL_DATA),
ctype(SQL_C_DEFAULT),
sqltype(SQL_UNKNOWN_TYPE),
size(0),
buf(0),
buflen(0),
is_unsigned(SQL_FALSE),
strbufW(),
strbufA(),
varbinary()
{}
union
{
SQLSCHAR sTinyInt;
SQLCHAR uTinyInt;
SQLINTEGER sLongInt;
SQLUINTEGER uLongInt;
SQLSMALLINT sShortInt;
SQLUSMALLINT uShortInt;
SQLBIGINT sBigInt;
SQLUBIGINT uBigInt;
SQLCHAR bit;
SQLREAL float_;
SQLDOUBLE double_;
SQL_DATE_STRUCT date;
SQL_TIME_STRUCT time;
SQL_TIMESTAMP_STRUCT timestamp;
SQL_NUMERIC_STRUCT numeric;
//SQLGUID guid;
SQL_INTERVAL_STRUCT interval;
SQLWCHAR wchar_dummy;
} data;
//char padding[128];
SQLLEN ind;
SQLSMALLINT ctype;
SQLSMALLINT sqltype;
SQLULEN size;
SQLPOINTER buf;
SQLINTEGER buflen;
SQLLEN is_unsigned;
OdbcStrW strbufW;
OdbcStrA strbufA;
TVarbinary varbinary; // used for parameter data
private:
OdbcValue(const OdbcValue &);
OdbcValue& operator=(const OdbcValue &);
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief OdbcData implementation for libodbc
class OdbcData_libodbc : public OdbcData
{
public:
OdbcData_libodbc(OdbcResult_libodbc& result, colnum_t colnum, bool locked);
virtual ~OdbcData_libodbc(void);
friend class OdbcBlob_libodbc;
friend class OdbcMemo_libodbc;
virtual OdbcBlob_libodbc* getBlobStream(void) const;
virtual UnicodeStreamBuf* getMemoStream(void) const;
virtual String getString(void) const;
virtual signed short int getSShort(void) const;
virtual unsigned short int getUShort(void) const;
virtual signed long int getSLong(void) const;
virtual unsigned long int getULong(void) const;
virtual float getFloat(void) const;
virtual double getDouble(void) const;
virtual unsigned char getBit(void) const;
virtual signed char getSTinyint(void) const;
virtual unsigned char getUTinyint(void) const;
virtual signed long long getSBigint(void) const;
virtual unsigned long long getUBigint(void) const;
virtual TVarbinary getBinary(void) const;
virtual unsigned long int getBookmark(void) const;
virtual const unsigned char* getVarbookmark(void) const;
virtual TDate getDate(void) const;
virtual TTime getTime(void) const;
virtual TTimestamp getTimestamp(void) const;
virtual TNumeric getNumeric(void) const;
virtual bool isnull(void) const;
virtual rowid_t getCurrentRowID(void) const;
virtual void refresh(void);
virtual bool bindcol(void);
virtual bool getdata(void);
virtual void initValue(void);
virtual daltype_t daltype(void) const;
virtual void fetchParts(void);
virtual BlobStream cast2BlobStream(std::locale loc) const;
virtual MemoStream cast2MemoStream(std::locale loc) const;
virtual Blob cast2Blob(std::locale loc) const;
virtual Memo cast2Memo(std::locale loc) const;
protected:
OdbcResult_libodbc& getResultset(void) const;
OdbcStmt_libodbc& getStmt(void) const;
SQLHSTMT getHandle(void) const;
ODBC30Drv* drv(void) const;
void bindIndicator(colnum_t colnum, SQLLEN *ind);
OdbcResult_libodbc& m_resultset;
colnum_t m_colnum;
mutable std::auto_ptr<OdbcBlob_libodbc> m_blobbuf;
mutable std::auto_ptr<OdbcMemo_libodbc> m_memobuf;
// This caches are used for MemoStream -> Memo conversions
// and must be reset if the cursor moves.
mutable std::shared_ptr<std::stringstream> m_blob_cache;
mutable std::shared_ptr<std::wstringstream> m_memo_cache;
/// @todo Used for ANSI memo data conversion
mutable std::auto_ptr<std::wstringstream> m_memostream;
//SQLSMALLINT m_type;
SQLLEN m_bufsize;
//void *m_buf;
//SQLLEN m_ind;
mutable OdbcValue m_value;
bool m_is_bound;
//std::vector<SQLWCHAR> m_strbufW;
//std::vector<SQLCHAR> m_strbufA;
//OdbcStrW m_strbufW;
//OdbcStrA m_strbufA;
//std::vector<unsigned char> m_binarybuf;
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief OdbcColumnDesc implementation for libodbc
class OdbcColumnDesc_libodbc : public OdbcColumnDesc
{
public:
OdbcColumnDesc_libodbc(colnum_t i, OdbcResult_libodbc &result);
virtual ~OdbcColumnDesc_libodbc(void)
{}
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief SQLite Resultset implementation for libodbc
class OdbcResult_libodbc : public OdbcResult
{
friend class OdbcStmt_libodbc;
public:
OdbcResult_libodbc(OdbcStmt_libodbc& stmt);
virtual ~OdbcResult_libodbc(void);
virtual void first(void);
virtual bool next(void);
virtual bool eof(void) const;
virtual void close(void);
virtual const OdbcVariant& column(colnum_t num);
virtual const OdbcVariant& column(String name);
// row methods
virtual rowcount_t rowCount(void) const;
virtual rowcount_t affectedRows(void) const;
virtual Variant lastInsertRowId(void);
// column methods
virtual size_t columnCount(void) const;
virtual colnum_t columnID(String name) const;
virtual String columnName(colnum_t num) const;
virtual rowid_t getCurrentRowID(void) const;
virtual ODBC30Drv* drv(void) const;
virtual const OdbcColumnDesc& describeColumn(colnum_t num) const;
virtual const OdbcColumnDesc& describeColumn(String name) const;
virtual OdbcDbc_libodbc& getDbc(void) const;
virtual OdbcStmt_libodbc& getStmt(void) const;
virtual SQLHSTMT getHandle(void) const;
virtual OdbcDiag& appendDiagRec(const OdbcDiag &diag);
// odbc specific
virtual void prepare(String sql);
virtual void execute(StmtBase::ParamMap& params);
protected:
typedef std::map<colnum_t, OdbcVariant*> VariantListT;
virtual void refreshMetadata(void);
virtual size_t paramCount(void) const;
void reset(void);
void bindParamBlob(StmtBase::ParamMapIterator param);
void bindParamMemo(StmtBase::ParamMapIterator param);
void bindParamNumeric(StmtBase::ParamMapIterator param);
void bindParamString(StmtBase::ParamMapIterator param);
OdbcStmt_libodbc &m_stmt;
rowid_t m_current_tuple;
int m_last_row_status;
bool m_isopen;
mutable SQLSMALLINT m_cached_resultcol_count;
std::map<colnum_t, std::shared_ptr<OdbcValue> > m_param_data;
///
/// @brief Stores the type information of all columns in the resultset
std::map<colnum_t, OdbcColumnDesc_libodbc> m_column_desc;
///
/// @brief Stores all column accessors (IVariants) requested by an user for
/// the current resultset.
///
/// @details The column accessors are created when an user requested one
/// and only get destroyed when the resultset becomes invalid (closed, destroyed..)
/// We use this container only for lookups if a reqeusted accessor is already allocated.
/// The accessors are stored in m_allocted_accessors, too - which cleanup
/// the accessors if thy are not needed anymore.
///
/// @note Do not delete (free) any of the elements, this task is
/// done by m_allocated_accessors's destructor.
VariantListT m_column_accessors;
///
/// @brief Stores all allocated accessors (IVariants) requested by an user for
/// the current resultset.
///
/// @note all objects (this container stores pointer to these) are free'd if
/// the user closes the resultset.
std::vector<informave::utils::SmartPtr<OdbcVariant,
informave::utils::RefCounted,
informave::utils::AllowConversion> > m_allocated_accessors;
private:
OdbcResult_libodbc(const OdbcResult_libodbc&);
OdbcResult_libodbc& operator=(const OdbcResult_libodbc&);
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief SQLite Statement implementation for libodbc
class OdbcStmt_libodbc : public OdbcStmt
{
typedef std::vector<OdbcResult_libodbc*> ResultsetVectorT;
friend class OdbcResult_libodbc;
public:
OdbcStmt_libodbc(OdbcDbc_libodbc& conn);
virtual ~OdbcStmt_libodbc(void);
virtual OdbcResult& resultset(void);
virtual const OdbcResult& resultset(void) const;
virtual void prepare(String sql);
virtual void execute(void);
virtual void execDirect(String sql);
//virtual void execDirect(std::istream src) = 0;
virtual void close(void);
virtual bool nextResultset(void);
virtual bool moreResultsets(void) const;
virtual size_t paramCount(void) const;
virtual rowid_t affectedRows(void) const;
virtual Variant lastInsertRowId(void);
virtual ODBC30Drv* drv(void) const;
virtual OdbcDbc_libodbc& getDbc(void) const; // interface
virtual OdbcDiag& appendDiagRec(const OdbcDiag &diag);
virtual SQLHSTMT getHandle(void) const;
// exttensions
virtual void openOdbcCatalogs(void);
virtual void openOdbcSchemas(const Variant &catalog);
virtual void openOdbcTables(const Variant &catalog, const Variant &schema, const Variant &type);
virtual void openOdbcColumns(const Variant &catalog, const Variant &schema, const Variant &table);
std::list<OdbcDiagnosticRec_libodbc> getDiagRecs(const CodePosInfo & cpi) const;
protected:
OdbcResult_libodbc* newResultset(void);
OdbcDbc_libodbc &m_conn;
ResultsetVectorT m_resultsets;
int m_currentResultset;
mutable SQLHSTMT m_handle;
//bool m_isPrepared;
private:
OdbcStmt_libodbc(const OdbcStmt_libodbc&);
OdbcStmt_libodbc& operator=(const OdbcStmt_libodbc&);
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief SQLite Connection implementation for libodbc
class OdbcDbc_libodbc : public OdbcDbc
{
public:
OdbcDbc_libodbc(OdbcEnv_libodbc& env);
virtual ~OdbcDbc_libodbc(void);
virtual OdbcStmt_libodbc* newStatement(void);
virtual IEnv& getEnv(void);
virtual void connect(String database,
String user = String(),
String password = String());
virtual void connect(IDbc::Options& options);
virtual void disconnect(void);
virtual String driverName(void) const;
virtual String dbmsName(void) const;
virtual std::string getDbcEncoding(void) const;
virtual SQLHDBC getHandle(void) const;
virtual ODBC30Drv* drv(void) const;
virtual OdbcDiag& appendDiagRec(const OdbcDiag &diag);
virtual void beginTrans(trx_mode mode,
access_mode access = trx_default,
String name = String());
virtual void commit(void);
virtual void savepoint(String name);
virtual void rollback(String name = String());
// ODBC extensions
virtual bool usingUnicode(void) const;
virtual const OdbcEnv_libodbc& getEnv(void) const { return this->m_env; }
virtual OdbcStmt* getOdbcCatalogs(void);
virtual OdbcStmt* getOdbcSchemas(const Variant &catalog);
virtual OdbcStmt* getOdbcTables(const Variant &catalog, const Variant &schema, const Variant &type);
virtual OdbcStmt* getOdbcColumns(const Variant &catalog, const Variant &schema, const Variant &table);
virtual Variant getCurrentCatalog(void);
virtual String quoteIdentifier(const String &id);
std::list<OdbcDiagnosticRec_libodbc> getDiagRecs(const CodePosInfo & cpi) const;
protected:
virtual void setDbcEncoding(std::string encoding);
ODBC30Drv *m_lib; /* lib is stored in ENV */
OdbcEnv_libodbc &m_env;
mutable SQLHDBC m_dbh;
bool m_useUnicode;
std::string m_ansics;
private:
OdbcDbc_libodbc(const OdbcDbc_libodbc&);
OdbcDbc_libodbc& operator=(const OdbcDbc_libodbc&);
};
//------------------------------------------------------------------------------
///
/// @internal
/// @brief SQLite Environment implementation for libodbc
class OdbcEnv_libodbc : public OdbcEnv
{
public:
OdbcEnv_libodbc(String lib = String());
virtual ~OdbcEnv_libodbc(void);
virtual OdbcDbc_libodbc* newConnection(void);
virtual ODBC30Drv* drv(void) const;
virtual OdbcDiag& appendDiagRec(const OdbcDiag &diag);
virtual SQLHENV getHandle(void) const;
std::list<OdbcDiagnosticRec_libodbc> getDiagRecs(const CodePosInfo & cpi) const;
protected:
mutable std::auto_ptr<ODBC30Drv> m_lib;
SQLHENV m_handle;
private:
OdbcEnv_libodbc(const OdbcEnv_libodbc&);
OdbcEnv_libodbc& operator=(const OdbcEnv_libodbc&);
};
/// @endcond
DAL_NAMESPACE_END
#endif
//
// Local Variables:
// mode: C++
// c-file-style: "bsd"
// c-basic-offset: 4
// indent-tabs-mode: nil
// End:
//
|
#include <filesystem>
namespace adiar
{
template <>
struct FILE_CONSTANTS<int>
{
static constexpr size_t files = 2u;
};
}
go_bandit([]() {
describe("adiar/file.h, adiar/file_stream.h, adiar/file_writer.h", [&]() {
describe("adiar/file.h", [&]() {
it("can construct fresh file<T> and make it read-only", [&]() {
file<int> f;
AssertThat(f.is_read_only(), Is().False());
f.make_read_only();
AssertThat(f.is_read_only(), Is().True());
});
it("can construct fresh __meta_file<T> and make it read-only", [&]() {
__meta_file<int> f;
AssertThat(f.is_read_only(), Is().False());
f.make_read_only();
AssertThat(f.is_read_only(), Is().True());
});
});
simple_file<int> test_file_simple;
simple_file<int> test_file_simple_sorted;
meta_file<int> test_file_meta_1;
meta_file<int> test_file_meta_2;
node_file node_test_file;
node_t n2 = create_node(1,1, create_sink_ptr(false), create_sink_ptr(true));
node_t n1 = create_node(1,0, create_sink_ptr(true), create_sink_ptr(false));
node_t n0 = create_node(0,0, create_node_ptr(1,1), create_node_ptr(1,0));
arc_file arc_test_file;
arc_t node_arc_1 = { create_node_ptr(0,0), create_node_ptr(1,0) };
arc_t sink_arc_1 = { flag(create_node_ptr(0,0)), create_sink_ptr(false) };
arc_t sink_arc_2 = { create_node_ptr(1,0), create_sink_ptr(true) };
arc_t sink_arc_3 = { flag(create_node_ptr(1,0)), create_sink_ptr(false) };
describe("adiar/file_writer", [&]() {
describe("simple_file_writer", [&]() {
it("can hook into and write to test_file_simple", [&]() {
AssertThat(test_file_simple.is_read_only(), Is().False());
simple_file_writer<int> fw(test_file_simple);
fw.unsafe_push(21);
fw.unsafe_push(42);
AssertThat(test_file_simple.is_read_only(), Is().False());
});
it("can sort after pushing out-of-order", [&]() {
AssertThat(test_file_simple_sorted.is_read_only(), Is().False());
simple_file_writer<int, std::less<int>> fw(test_file_simple_sorted);
fw.unsafe_push(5);
fw.unsafe_push(3);
fw.unsafe_push(4);
fw.unsafe_push(1);
fw.unsafe_push(2);
fw.sort();
AssertThat(test_file_simple_sorted.is_read_only(), Is().False());
});
it("does not break when source file is destructed early [simple_file]", [&]() {
simple_file<int>* f = new simple_file<int>();
simple_file_writer<int> fw(*f);
fw.unsafe_push(21);
delete f;
fw.unsafe_push(42);
});
});
describe("meta_file_writer", [&]() {
it("can hook into and write to test_file_meta_1", [&]() {
AssertThat(test_file_meta_1.is_read_only(), Is().False());
meta_file_writer<int> fw(test_file_meta_1);
fw.unsafe_push(21);
fw.unsafe_push(42);
fw.unsafe_push(create_level_info(0,2u));
AssertThat(test_file_meta_1.is_read_only(), Is().False());
});
it("can hook into and write to test_file_meta_2", [&]() {
meta_file_writer<int> fw(test_file_meta_2);
fw.unsafe_push(create_level_info(5,1u));
fw.unsafe_push(create_level_info(4,1u));
fw.unsafe_push(1); // Check idx argument is defaulted to 0
fw.unsafe_push(2, 0);
fw.unsafe_push(4, 1);
fw.unsafe_push(5, 1);
fw.unsafe_push(3, 0);
AssertThat(test_file_meta_2.is_read_only(), Is().False());
});
it("does not break when source file is destructed early [simple_file]", [&]() {
meta_file<int>* f = new meta_file<int>();
meta_file_writer fw(*f);
fw.unsafe_push(21);
delete f;
fw.unsafe_push(42);
fw.unsafe_push(create_level_info(0,1u));
});
describe("node_writer", [&]() {
it("can hook into and write to node_test_file", [&]() {
AssertThat(node_test_file.is_read_only(), Is().False());
node_writer nw(node_test_file);
nw << n2 << n1 << n0;
AssertThat(node_test_file.is_read_only(), Is().False());
});
it("can derive whether it is on canonical form [1]", [&]() {
node_file nf;
{
node_writer nw(nf);
nw << create_node(42, MAX_ID, create_sink_ptr(false), create_sink_ptr(true));
}
AssertThat(is_canonical(nf), Is().True());
});
it("can derive whether it is on canonical form [2]", [&]() {
node_file nf;
{
node_writer nw(nf);
nw << create_node(21, 42, create_sink_ptr(false), create_sink_ptr(true));
}
AssertThat(is_canonical(nf), Is().False());
});
it("can derive whether it is on canonical form [3]", [&]() {
node_file nf;
{
node_writer nw(nf);
nw << create_node(42, MAX_ID, create_sink_ptr(false), create_sink_ptr(true))
<< create_node(42, MAX_ID-1, create_sink_ptr(true), create_sink_ptr(false))
<< create_node(21, MAX_ID, create_node_ptr(42, MAX_ID), create_node_ptr(42, MAX_ID-1));
}
AssertThat(is_canonical(nf), Is().True());
});
it("can derive whether it is on canonical form [4]", [&]() {
node_file nf;
{
node_writer nw(nf);
nw << create_node(42, MAX_ID, create_sink_ptr(true), create_sink_ptr(false))
<< create_node(42, MAX_ID-1, create_sink_ptr(false), create_sink_ptr(true))
<< create_node(21, MAX_ID, create_node_ptr(42, MAX_ID), create_node_ptr(42, MAX_ID-1));
}
AssertThat(is_canonical(nf), Is().False());
});
it("can derive whether it is on canonical form [5]", [&]() {
node_file nf;
{
node_writer nw(nf);
nw << create_node(42, MAX_ID, create_sink_ptr(false), create_sink_ptr(true))
<< create_node(42, MAX_ID-1, create_sink_ptr(true), create_sink_ptr(false))
<< create_node(21, MAX_ID-1, create_node_ptr(42, MAX_ID), create_node_ptr(42, MAX_ID-1));
}
AssertThat(is_canonical(nf), Is().False());
});
it("can derive whether it is on canonical form [6]", [&]() {
node_file nf;
{
node_writer nw(nf);
nw << create_node(42, MAX_ID, create_sink_ptr(false), create_sink_ptr(true))
<< create_node(42, MAX_ID-2, create_sink_ptr(true), create_sink_ptr(false))
<< create_node(21, MAX_ID, create_node_ptr(42, MAX_ID), create_node_ptr(42, MAX_ID-2));
}
AssertThat(is_canonical(nf), Is().False());
});
});
describe("arc_writer", [&]() {
arc_writer aw(arc_test_file);
it("can hook into arc_test_file and write node arcs", [&]() {
AssertThat(arc_test_file.is_read_only(), Is().False());
aw.unsafe_push_node(node_arc_1);
});
it("can hook into arc_test_file and write level_info", [&]() {
aw.unsafe_push(create_level_info(0,1u));
aw.unsafe_push(create_level_info(1,1u));
});
it("can hook into arc_test_file and write sink arcs out of order", [&]() {
aw.unsafe_push_sink(sink_arc_3);
aw.unsafe_push_sink(sink_arc_1);
aw.unsafe_push_sink(sink_arc_2);
});
});
});
});
describe("adiar/file_stream.h", [&]() {
describe("simple_file_stream", [&]() {
it("locks the file to be read-only on attachment", [&]() {
AssertThat(test_file_simple.is_read_only(), Is().False());
file_stream<int, false> fs(test_file_simple);
AssertThat(test_file_simple.is_read_only(), Is().True());
});
it("can read test_file_simple [forwards]", [&]() {
file_stream<int, false> fs(test_file_simple);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
it("can peek test_file_simple [forwards]", [&]() {
file_stream<int, false> fs(test_file_simple);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.peek(), Is().EqualTo(21));
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.peek(), Is().EqualTo(42));
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
it("can read test_file_simple_sorted [reverse]", [&]() {
file_stream<int, true> fs(test_file_simple_sorted);
// This also tests, whether test_file_simple_sorted actually
// ended up being sorted.
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(5));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(4));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(3));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(2));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(1));
AssertThat(fs.can_pull(), Is().False());
});
it("does not break when source simple_file is destructed early", [&]() {
simple_file<int>* f = new simple_file<int>();
{ // Garbage collect the writer early, releasing it's reference counter
simple_file_writer<int> fw(*f);
fw.unsafe_push(21);
}
file_stream<int, false> fs(*f);
delete f;
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(21));
});
});
describe("meta_file_stream", [&]() {
it("locks the file to be read-only on attachment", [&]() {
AssertThat(test_file_meta_1.is_read_only(), Is().False());
meta_file_stream<int, 0, false> fs1(test_file_meta_1);
AssertThat(test_file_meta_1.is_read_only(), Is().True());
AssertThat(test_file_meta_2.is_read_only(), Is().False());
meta_file_stream<int, 0, false> fs2(test_file_meta_2);
AssertThat(test_file_meta_2.is_read_only(), Is().True());
});
it("can read test_file_meta_1 [forwards]", [&]() {
meta_file_stream<int, 0, false> fs(test_file_meta_1);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
it("can peek test_file_meta_1 [forwards]", [&]() {
meta_file_stream<int, 0, false> fs(test_file_meta_1);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.peek(), Is().EqualTo(21));
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.peek(), Is().EqualTo(42));
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
it("can read test_file_meta_1 [reverse]", [&]() {
meta_file_stream<int, 0, true> fs(test_file_meta_1);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.can_pull(), Is().False());
});
it("can peek test_file_1 [reverse]", [&]() {
meta_file_stream<int, 0, true> fs(test_file_meta_1);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.peek(), Is().EqualTo(42));
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.peek(), Is().EqualTo(21));
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.can_pull(), Is().False());
});
it("can read test_file_meta_2 [forwards]", [&]() {
meta_file_stream<int, 0, false> fs1(test_file_meta_2);
AssertThat(fs1.can_pull(), Is().True());
AssertThat(fs1.pull(), Is().EqualTo(1));
AssertThat(fs1.can_pull(), Is().True());
AssertThat(fs1.pull(), Is().EqualTo(2));
AssertThat(fs1.can_pull(), Is().True());
AssertThat(fs1.pull(), Is().EqualTo(3));
AssertThat(fs1.can_pull(), Is().False());
meta_file_stream<int, 1, false> fs2(test_file_meta_2);
AssertThat(fs2.can_pull(), Is().True());
AssertThat(fs2.pull(), Is().EqualTo(4));
AssertThat(fs2.can_pull(), Is().True());
AssertThat(fs2.pull(), Is().EqualTo(5));
AssertThat(fs2.can_pull(), Is().False());
});
it("can peek test_file_meta_2 [forwards]", [&]() {
meta_file_stream<int, 0, false> fs1(test_file_meta_2);
AssertThat(fs1.can_pull(), Is().True());
AssertThat(fs1.peek(), Is().EqualTo(1));
AssertThat(fs1.pull(), Is().EqualTo(1));
AssertThat(fs1.can_pull(), Is().True());
AssertThat(fs1.peek(), Is().EqualTo(2));
AssertThat(fs1.pull(), Is().EqualTo(2));
AssertThat(fs1.can_pull(), Is().True());
AssertThat(fs1.peek(), Is().EqualTo(3));
AssertThat(fs1.pull(), Is().EqualTo(3));
AssertThat(fs1.can_pull(), Is().False());
meta_file_stream<int, 1, false> fs2(test_file_meta_2);
AssertThat(fs2.can_pull(), Is().True());
AssertThat(fs2.peek(), Is().EqualTo(4));
AssertThat(fs2.pull(), Is().EqualTo(4));
AssertThat(fs2.can_pull(), Is().True());
AssertThat(fs2.peek(), Is().EqualTo(5));
AssertThat(fs2.pull(), Is().EqualTo(5));
AssertThat(fs2.can_pull(), Is().False());
});
it("can read test_file_1 forwards via fresh proxy object", [&]() {
meta_file<int> proxy(test_file_meta_1);
meta_file_stream<int, 0, false> fs(proxy);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
it("does not break when source meta_file is destructed early", [&]() {
meta_file<int>* f = new meta_file<int>();
{ // Garbage collect the writer early, releasing it's reference counter
meta_file_writer<int> fw(*f);
fw.unsafe_push(21, 0);
}
meta_file_stream<int, 0, false> fs(*f);
delete f;
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(21));
});
describe("level_info_stream", [&]() {
it("can read level_info stream of test_file_meta_1", [&]() {
level_info_stream ms(test_file_meta_1);
AssertThat(ms.can_pull(), Is().True());
AssertThat(ms.pull(), Is().EqualTo(create_level_info(0,2u)));
AssertThat(ms.can_pull(), Is().False());
});
it("can read level_info stream of node_test_file", [&]() {
level_info_stream ms(node_test_file);
AssertThat(ms.can_pull(), Is().True());
AssertThat(ms.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(ms.can_pull(), Is().True());
AssertThat(ms.pull(), Is().EqualTo(create_level_info(1,2u)));
AssertThat(ms.can_pull(), Is().False());
});
});
describe("node_stream", [&]() {
it("can read node stream of node_test_file", [&]() {
node_stream<> ns(node_test_file);
AssertThat(ns.can_pull(), Is().True());
AssertThat(ns.pull(), Is().EqualTo(n0));
AssertThat(ns.can_pull(), Is().True());
AssertThat(ns.pull(), Is().EqualTo(n1));
AssertThat(ns.can_pull(), Is().True());
AssertThat(ns.pull(), Is().EqualTo(n2));
AssertThat(ns.can_pull(), Is().False());
});
it("can read negated node stream of node_test_file", [&]() {
node_stream<> ns(node_test_file, true);
AssertThat(ns.can_pull(), Is().True());
AssertThat(ns.pull(), Is().EqualTo(!n0));
AssertThat(ns.can_pull(), Is().True());
AssertThat(ns.pull(), Is().EqualTo(!n1));
AssertThat(ns.can_pull(), Is().True());
AssertThat(ns.pull(), Is().EqualTo(!n2));
AssertThat(ns.can_pull(), Is().False());
});
});
describe("arc_streams", [&]() {
it("can read node arcs of arc_test_file", [&]() {
node_arc_stream<> as(arc_test_file);
AssertThat(as.can_pull(), Is().True());
AssertThat(as.pull(), Is().EqualTo(node_arc_1));
AssertThat(as.can_pull(), Is().False());
});
it("can read sink arcs of arc_test_file", [&]() {
sink_arc_stream<> as(arc_test_file);
// The stream has been sorted 1, 2, 3 yet the
// sink_arc_stream is per default in reverse, so we will
// expect 3, 2, 1.
AssertThat(as.can_pull(), Is().True());
AssertThat(as.pull(), Is().EqualTo(sink_arc_3));
AssertThat(as.can_pull(), Is().True());
AssertThat(as.pull(), Is().EqualTo(sink_arc_2));
AssertThat(as.can_pull(), Is().True());
AssertThat(as.pull(), Is().EqualTo(sink_arc_1));
AssertThat(as.can_pull(), Is().False());
});
});
});
});
describe("shared_file", [&]() {
describe("simple_file", [&]() {
it("can return a written to simple_file, that then can be read", [&]() {
auto t = []() {
simple_file<int> f;
simple_file_writer<int> fw(f);
fw.unsafe_push(42);
fw.unsafe_push(7);
return f;
};
simple_file<int> f = t();
file_stream<int> fs(f);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(7));
AssertThat(fs.can_pull(), Is().False());
});
it("can construct a new named simple_file", [&]() {
simple_file<int> file("simple_file_test.adiar");
AssertThat(std::filesystem::exists("simple_file_test.adiar"), Is().True());
{
simple_file_writer<int> fw(file);
fw.push(1);
fw.push(2);
fw.push(3);
}
AssertThat(file.is_read_only(), Is().False());
{
file_stream<int, false> fs(file);
AssertThat(file.is_read_only(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(1));
AssertThat(fs.pull(), Is().EqualTo(2));
AssertThat(fs.pull(), Is().EqualTo(3));
AssertThat(fs.can_pull(), Is().False());
}
AssertThat(file.is_read_only(), Is().True());
});
it("should have two temporary simple_files be two different files", [&]() {
simple_file<int> file1;
simple_file<int> file2;
AssertThat(file1._file_ptr, Is().Not().EqualTo(file2._file_ptr));
});
it("can construct a copy of a simple_file", [&]() {
simple_file<int> file1;
{ // Garbage collect the writer to detach it before the reader
simple_file_writer<int> fw(file1);
fw.push(42);
}
simple_file<int> file2(file1);
file_stream<int, false> fs(file2);
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
it("can construct a prior named simple_file (i.e. reopen a stored file)", [&]() {
AssertThat(std::filesystem::exists("simple_file_test.adiar"), Is().True());
simple_file<int> file("simple_file_test.adiar");
AssertThat(file.is_read_only(), Is().True());
file_stream<int, false> fs(file);
AssertThat(file.is_read_only(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(1));
AssertThat(fs.pull(), Is().EqualTo(2));
AssertThat(fs.pull(), Is().EqualTo(3));
AssertThat(fs.can_pull(), Is().False());
});
it("can compute sizes of test_file_simple", [&]() {
AssertThat(test_file_simple.size(), Is().EqualTo(2u));
AssertThat(test_file_simple.file_size(), Is().EqualTo(2u * sizeof(int)));
});
it("can sort a yet unread simple_file", [&]() {
simple_file<int> file;
{ // Garbage collect the writer to detach it before the reader
simple_file_writer<int> fw(file);
fw.push(42);
fw.push(7);
fw.push(21);
}
sort(file, std::less<>());
file_stream<int, false> fs(file);
AssertThat(fs.pull(), Is().EqualTo(7));
AssertThat(fs.pull(), Is().EqualTo(21));
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
});
describe("meta_file", [&]() {
it("can return a written to meta_file, that then can be read", [&]() {
auto t = []() {
meta_file<int> f;
meta_file_writer<int> fw(f);
fw.unsafe_push(42);
fw.unsafe_push(7);
return f;
};
meta_file<int> f = t();
meta_file_stream<int, 0, false> fs(f);
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().True());
AssertThat(fs.pull(), Is().EqualTo(7));
AssertThat(fs.can_pull(), Is().False());
});
it("should have two temporary meta_files be two different files", [&]() {
meta_file<int> file1;
meta_file<int> file2;
AssertThat(file1._file_ptr, Is().Not().EqualTo(file2._file_ptr));
});
it("can construct a copy of a meta_file", [&]() {
meta_file<int> file1;
{ // Garbage collect the writer to detach it before the reader
meta_file_writer<int> fw(file1);
fw.unsafe_push(42);
}
meta_file<int> file2(file1);
meta_file_stream<int, 0, false> fs(file2);
AssertThat(fs.pull(), Is().EqualTo(42));
AssertThat(fs.can_pull(), Is().False());
});
it("can compute sizes of test_file_meta_1", [&]() {
AssertThat(test_file_meta_1.size(), Is().EqualTo(2u));
AssertThat(test_file_meta_1.file_size(), Is().EqualTo(2u * sizeof(int) + 1u * sizeof(level_info_t)));
});
it("can compute size of test_file_meta_2", [&]() {
test_file_meta_2.make_read_only();
AssertThat(test_file_meta_2.size(), Is().EqualTo(5u));
AssertThat(test_file_meta_2.file_size(), Is().EqualTo(5u * sizeof(int) + 2u * sizeof(level_info_t)));
});
describe("node_file", [&]() {
node_file x0;
{
node_writer nw_0(x0);
nw_0 << create_node(0,MAX_ID,
create_sink_ptr(false),
create_sink_ptr(true));
}
node_file x0_and_x1;
{
node_writer nw_01(x0_and_x1);
nw_01 << create_node(1, MAX_ID,
create_sink_ptr(false),
create_sink_ptr(true));
nw_01 << create_node(0, MAX_ID,
create_sink_ptr(false),
create_node_ptr(1, MAX_ID));
}
node_file sink_T;
{
node_writer nw_T(sink_T);
nw_T << create_sink(true);
}
node_file sink_F;
{
node_writer nw_F(sink_F);
nw_F << create_sink(false);
}
describe("size computation", [&]() {
it("can compute size of node_test_file", [&]() {
AssertThat(node_test_file.size(), Is().EqualTo(3u));
AssertThat(node_test_file.meta_size(), Is().EqualTo(2u));
AssertThat(node_test_file.file_size(), Is().EqualTo(3u * sizeof(node_t) + 2u * sizeof(level_info_t)));
});
it("can compute size of x0", [&]() {
AssertThat(x0.size(), Is().EqualTo(1u));
AssertThat(x0.meta_size(), Is().EqualTo(1u));
AssertThat(x0.file_size(), Is().EqualTo(1u * sizeof(node_t) + 1u * sizeof(level_info_t)));
});
it("can compute size of x0 & x1", [&]() {
AssertThat(x0_and_x1.size(), Is().EqualTo(2u));
AssertThat(x0_and_x1.meta_size(), Is().EqualTo(2u));
AssertThat(x0_and_x1.file_size(), Is().EqualTo(2u * sizeof(node_t) + 2u * sizeof(level_info_t)));
});
it("can compute size of sink_T", [&]() {
AssertThat(sink_T.size(), Is().EqualTo(1u));
AssertThat(sink_T.meta_size(), Is().EqualTo(0u));
AssertThat(sink_T.file_size(), Is().EqualTo(1u * sizeof(node_t) + 0u * sizeof(level_info_t)));
});
});
describe("is_sink predicate", [&]() {
it("should reject x0 as a sink file", [&]() {
AssertThat(is_sink(x0, is_true), Is().False());
AssertThat(is_sink(x0, is_false), Is().False());
AssertThat(is_sink(x0), Is().False());
});
it("should reject x0 & x1 as a sink file", [&]() {
AssertThat(is_sink(x0_and_x1, is_true), Is().False());
AssertThat(is_sink(x0_and_x1, is_false), Is().False());
AssertThat(is_sink(x0_and_x1), Is().False());
});
it("should recognise a true sink", [&]() {
AssertThat(is_sink(sink_T, is_true), Is().True());
});
it("should recognise a false sink", [&]() {
AssertThat(is_sink(sink_F, is_false), Is().True());
});
it("should not recognise sink file as the other sink", [&]() {
AssertThat(is_sink(sink_T, is_false), Is().False());
AssertThat(is_sink(sink_F, is_true), Is().False());
});
it("should have any sink as default", [&]() {
AssertThat(is_sink(sink_T), Is().True());
AssertThat(is_sink(sink_F), Is().True());
});
});
describe("min_label and max_label", [&]() {
it("should extract labels from x0", [&]() {
AssertThat(min_label(x0), Is().EqualTo(0u));
AssertThat(max_label(x0), Is().EqualTo(0u));
});
it("should extract labels from x0_and_x1", [&]() {
AssertThat(min_label(x0_and_x1), Is().EqualTo(0u));
AssertThat(max_label(x0_and_x1), Is().EqualTo(1u));
});
it("should extract labels from node_test_file", [&]() {
AssertThat(min_label(node_test_file), Is().EqualTo(0u));
AssertThat(max_label(node_test_file), Is().EqualTo(1u));
});
});
});
});
});
});
});
|
/*
* 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.
*/
/**
* @file g2_model.hpp
* @brief This file include the class G2Model
*
*/
#ifndef __XF_FINTECH_G2MODEL_HPP_
#define __XF_FINTECH_G2MODEL_HPP_
#include "hls_math.h"
#include "ap_int.h"
#include "utils.hpp"
#ifndef __SYNTHESIS__
#include "iostream"
using namespace std;
#endif
namespace xf {
namespace fintech {
/**
* @brief Two-additive-factor gaussian model for Tree Engine
*
* @tparam DT data type supported include float and double
* @tparam Tree class TrinomialTree
* @tparam LEN2 maximum length of node of tree, which affects the latency and resources utilization.
*
*/
template <typename DT, typename Tree, int LEN2>
class G2Model {
private:
// constants
DT a_[2], tmp_[2], rho_, rate_;
DT da_[3];
public:
/**
* @brief constructor
*/
G2Model() {
#pragma HLS inline
}
/**
* @brief initialize parameters
*
* @param r floating benchmark annual interest rate
* @param a initial volatility of stock.
* @param sigma the volatility of volatility.
* @param b initial volatility of stock.
* @param eta the volatility of volatility.
* @param rho the correlation coefficient between price and variance.
*/
void initialization(DT r, DT a, DT sigma, DT b, DT eta, DT rho) {
#pragma HLS inline
a_[0] = a;
a_[1] = b;
tmp_[0] = sigma / a;
tmp_[1] = eta / b;
rho_ = rho;
rate_ = r;
}
/**
* @brief calculate the discount after time dt
*
* @param t the current timepoint
* @param dt the difference between the next timepoint and the current timepoint
* @param x underlying
* @param r invalid input
* @return discount
*/
DT discount(DT t, DT dt, DT* x, DT r = 0.0) {
#pragma HLS inline
#ifndef __SYNTHESIS__
DT temp1 = tmp_[0] * (1.0 - std::exp(-a_[0] * t));
DT temp2 = tmp_[1] * (1.0 - std::exp(-a_[1] * t));
#else
DT temp1 = tmp_[0] * (1.0 - hls::exp(-a_[0] * t));
DT temp2 = tmp_[1] * (1.0 - hls::exp(-a_[1] * t));
#endif
DT rate = 0.5 * (temp1 * temp1 + temp2 * temp2) + rho_ * temp1 * temp2 + rate_;
rate += x[0] + x[1];
#ifndef __SYNTHESIS__
DT discount = std::exp(-rate * dt);
#else
DT discount = hls::exp(-rate * dt);
#endif
return discount;
}
/**
* @brief calcutate short-rate of dt at t for TreeEngine
*
* @param tree class TrinomialTree
* @param endCnt end counter of timepoints
* @param time array timepoints
* @param dtime array the difference between the next timepoint and the current timepoint
* @param tmp_values1 process values
* @param tmp_values2 process values
* @param rates array short-rates
*/
void treeShortRate(Tree* tree,
int endCnt,
DT* time,
DT* dtime,
internal::xf_2D_array<DT, 4, LEN2>& tmp_values1,
internal::xf_2D_array<DT, 4, LEN2>& tmp_values2,
DT* rates) {
loop_compute_LEN:
for (int i = 0; i < endCnt - 1; i++) {
#pragma HLS pipeline
#pragma HLS loop_tripcount min = 50 max = 50
DT t = time[i];
DT dt = dtime[i];
tree[0].dxUpdate(i, t, dt);
tree[1].dxUpdate(i, t, dt);
}
}
}; // class
/**
* @brief Two-additive-factor gaussian model
*
* @tparam DT data type supported include float and double
*
*/
template <typename DT>
class G2Model<DT, void, 0> {
private:
// constants
DT a_[2], tmp_[2], rho_, rate_;
DT da_[3];
DT calcuV(DT t) {
#pragma HLS inline
#ifndef __SYNTHESIS__
DT expat = std::exp(-a_[0] * t);
DT expbt = std::exp(-a_[1] * t);
#else
DT expat = hls::exp(-a_[0] * t);
DT expbt = hls::exp(-a_[1] * t);
#endif
DT valuex = tmp_[0] * tmp_[0] * (t + (2.0 * expat - 0.5 * expat * expat - 1.5) * da_[0]);
DT valuey = tmp_[1] * tmp_[1] * (t + (2.0 * expbt - 0.5 * expbt * expbt - 1.5) * da_[1]);
DT value = 2.0 * rho_ * tmp_[0] * tmp_[1] *
(t + (expat - 1.0) * da_[0] + (expbt - 1.0) * da_[1] - (expat * expbt - 1.0) * da_[2]);
return valuex + valuey + value;
}
public:
/**
* @brief constructor
*/
G2Model() {
#pragma HLS inline
}
/**
* @brief initialize parameter
*
* @param r floating benchmark annual interest rate
* @param a initial volatility of stock.
* @param sigma the volatility of volatility.
* @param b initial volatility of stock.
* @param eta the volatility of volatility.
* @param rho the correlation coefficient between price and variance.
*/
void initialization(DT r, DT a, DT sigma, DT b, DT eta, DT rho) {
#pragma HLS inline
a_[0] = a;
a_[1] = b;
tmp_[0] = sigma / a;
tmp_[1] = eta / b;
rho_ = rho;
rate_ = r;
da_[0] = 1.0 / a;
da_[1] = 1.0 / b;
da_[2] = 1.0 / (a + b);
}
/**
* @brief calculate the discount after time dt
*
* @param t the current timepoint
* @param T the timepoint
* @param x underlying
* @return discount bond
*/
DT discountBond(DT t, DT T, DT* x) {
#pragma HLS inline
DT dt = T - t;
DT v1 = 0.5 * (calcuV(dt) - calcuV(T) + calcuV(t));
#ifndef __SYNTHESIS__
DT v2 = (1.0 - std::exp(-a_[0] * dt)) * x[0] * da_[0] + (1.0 - std::exp(-a_[1] * dt)) * x[1] * da_[1];
return std::exp(rate_ * (-dt) + v1 - v2);
#else
DT v2 = (1.0 - hls::exp(-a_[0] * dt)) * x[0] * da_[0] + (1.0 - hls::exp(-a_[1] * dt)) * x[1] * da_[1];
return hls::exp(rate_ * (-dt) + v1 - v2);
#endif
}
/**
* @brief calculate the short-rate
*
* @param t the current timepoint
* @param x underlying
* @param r float rate
* @return short-rate
*/
DT shortRate(DT t, DT* x, DT r) {
#pragma HLS inline
#ifndef __SYNTHESIS__
DT temp1 = tmp_[0] * (1.0 - std::exp(-a_[0] * t));
DT temp2 = tmp_[1] * (1.0 - std::exp(-a_[1] * t));
#else
DT temp1 = tmp_[0] * (1.0 - hls::exp(-a_[0] * t));
DT temp2 = tmp_[1] * (1.0 - hls::exp(-a_[1] * t));
#endif
DT rate = 0.5 * (temp1 * temp1 + temp2 * temp2) + rho_ * temp1 * temp2 + rate_;
return rate + x[0] + x[1];
}
}; // class
}
}
#endif
|
#ifndef OFFSETS_HEADER
#define OFFSETS_HEADER
#include <stdint.h>
const uintptr_t offsets_player_base = 0x00000;
const uintptr_t offsets_oneshot = 0x464E3;
#endif // OFFSETS_HEADER
|
// Copyright (c) 2019 The PIVX developers
// Copyright (c) 2021 The DECENOMY Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addressbook.h"
#include <string>
namespace AddressBook {
namespace AddressBookPurpose {
const std::string UNKNOWN{"unknown"};
const std::string RECEIVE{"receive"};
const std::string SEND{"send"};
}
bool CAddressBookData::isSendPurpose() const {
return purpose == AddressBookPurpose::SEND;
}
bool CAddressBookData::isReceivePurpose() const {
return purpose == AddressBookPurpose::RECEIVE;
}
}
|
//------------------------------------------------------------------------------
// This file was generated using the Faust compiler (https://faust.grame.fr),
// and the Faust post-processor (https://github.com/jpcima/faustpp).
//
// Source: stone_phaser.dsp
// Name: Stone Phaser
// Author: Jean Pierre Cimalando
// Copyright:
// License: CC0-1.0 or BSL-1.0
// Version: 1.2.2
//------------------------------------------------------------------------------
#include "StonePhaserDsp.hpp"
#include <utility>
#include <cmath>
class StonePhaserDsp::BasicDsp {
public:
virtual ~BasicDsp() {}
};
//------------------------------------------------------------------------------
// Begin the Faust code section
namespace {
template <class T> inline T min(T a, T b) { return (a < b) ? a : b; }
template <class T> inline T max(T a, T b) { return (a > b) ? a : b; }
class Meta {
public:
// dummy
void declare(...) {}
};
class UI {
public:
// dummy
void openHorizontalBox(...) {}
void openVerticalBox(...) {}
void closeBox(...) {}
void declare(...) {}
void addButton(...) {}
void addCheckButton(...) {}
void addVerticalSlider(...) {}
void addHorizontalSlider(...) {}
void addVerticalBargraph(...) {}
void addHorizontalBargraph(...) {}
};
typedef StonePhaserDsp::BasicDsp dsp;
} // namespace
#define FAUSTPP_VIRTUAL // do not declare any methods virtual
#define FAUSTPP_PRIVATE public // do not hide any members
#define FAUSTPP_PROTECTED public // do not hide any members
// define the DSP in the anonymous namespace
#define FAUSTPP_BEGIN_NAMESPACE namespace {
#define FAUSTPP_END_NAMESPACE }
#if defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#ifndef FAUSTPP_PRIVATE
# define FAUSTPP_PRIVATE private
#endif
#ifndef FAUSTPP_PROTECTED
# define FAUSTPP_PROTECTED protected
#endif
#ifndef FAUSTPP_VIRTUAL
# define FAUSTPP_VIRTUAL virtual
#endif
#ifndef FAUSTPP_BEGIN_NAMESPACE
# define FAUSTPP_BEGIN_NAMESPACE
#endif
#ifndef FAUSTPP_END_NAMESPACE
# define FAUSTPP_END_NAMESPACE
#endif
FAUSTPP_BEGIN_NAMESPACE
#ifndef FAUSTFLOAT
#define FAUSTFLOAT float
#endif
FAUSTPP_END_NAMESPACE
#include <algorithm>
#include <cmath>
#include <math.h>
FAUSTPP_BEGIN_NAMESPACE
class mydspSIG0 {
FAUSTPP_PRIVATE:
int iRec15[2];
public:
int getNumInputsmydspSIG0() {
return 0;
}
int getNumOutputsmydspSIG0() {
return 1;
}
int getInputRatemydspSIG0(int channel) {
int rate;
switch ((channel)) {
default: {
rate = -1;
break;
}
}
return rate;
}
int getOutputRatemydspSIG0(int channel) {
int rate;
switch ((channel)) {
case 0: {
rate = 0;
break;
}
default: {
rate = -1;
break;
}
}
return rate;
}
void instanceInitmydspSIG0(int sample_rate) {
for (int l10 = 0; (l10 < 2); l10 = (l10 + 1)) {
iRec15[l10] = 0;
}
}
void fillmydspSIG0(int count, float* table) {
for (int i = 0; (i < count); i = (i + 1)) {
iRec15[0] = (iRec15[1] + 1);
float fTemp0 = (0.0078125f * float((iRec15[0] + -1)));
float fTemp1 = float(int(fTemp0));
float fTemp2 = (fTemp0 - fTemp1);
table[i] = (1.0f - (1.02564108f * std::sin((2.69344211f * ((fTemp2 < 0.5f) ? fTemp2 : (fTemp1 + (1.0f - fTemp0)))))));
iRec15[1] = iRec15[0];
}
}
};
static mydspSIG0* newmydspSIG0() { return (mydspSIG0*)new mydspSIG0(); }
static void deletemydspSIG0(mydspSIG0* dsp) { delete dsp; }
static float ftbl0mydspSIG0[128];
#ifndef FAUSTCLASS
#define FAUSTCLASS mydsp
#endif
#ifdef __APPLE__
#define exp10f __exp10f
#define exp10 __exp10
#endif
class mydsp : public dsp {
FAUSTPP_PRIVATE:
int fSampleRate;
float fConst0;
float fConst1;
float fConst2;
FAUSTFLOAT fHslider0;
float fRec0_perm[4];
float fConst3;
float fRec6_perm[4];
float fConst4;
FAUSTFLOAT fHslider1;
float fRec8_perm[4];
FAUSTFLOAT fHslider2;
float fRec7_perm[4];
FAUSTFLOAT fHslider3;
float fRec10_perm[4];
float fConst5;
float fRec9_perm[4];
float fRec11_perm[4];
float fRec12_perm[4];
FAUSTFLOAT fHslider4;
float fRec14_perm[4];
float fRec13_perm[4];
float fConst6;
float fConst7;
float fConst8;
float fRec5_perm[4];
float fRec4_perm[4];
float fRec3_perm[4];
float fRec2_perm[4];
float fRec1_perm[4];
float fRec16_perm[4];
FAUSTFLOAT fCheckbox0;
float fRec17_perm[4];
FAUSTFLOAT fHbargraph0;
public:
void metadata(Meta* m) {
m->declare("author", "Jean Pierre Cimalando");
m->declare("basics.lib/name", "Faust Basic Element Library");
m->declare("basics.lib/version", "0.1");
m->declare("filename", "stone_phaser.dsp");
m->declare("filters.lib/fir:author", "Julius O. Smith III");
m->declare("filters.lib/fir:copyright", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>");
m->declare("filters.lib/fir:license", "MIT-style STK-4.3 license");
m->declare("filters.lib/iir:author", "Julius O. Smith III");
m->declare("filters.lib/iir:copyright", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>");
m->declare("filters.lib/iir:license", "MIT-style STK-4.3 license");
m->declare("filters.lib/lowpass0_highpass1", "Copyright (C) 2003-2019 by Julius O. Smith III <jos@ccrma.stanford.edu>");
m->declare("filters.lib/name", "Faust Filters Library");
m->declare("license", "CC0-1.0 or BSL-1.0");
m->declare("maths.lib/author", "GRAME");
m->declare("maths.lib/copyright", "GRAME");
m->declare("maths.lib/license", "LGPL with exception");
m->declare("maths.lib/name", "Faust Math Library");
m->declare("maths.lib/version", "2.1");
m->declare("name", "Stone Phaser");
m->declare("oscillators.lib/name", "Faust Oscillator Library");
m->declare("oscillators.lib/version", "0.0");
m->declare("signals.lib/name", "Faust Signal Routing Library");
m->declare("signals.lib/version", "0.0");
m->declare("version", "1.2.2");
}
FAUSTPP_VIRTUAL int getNumInputs() {
return 1;
}
FAUSTPP_VIRTUAL int getNumOutputs() {
return 1;
}
FAUSTPP_VIRTUAL int getInputRate(int channel) {
int rate;
switch ((channel)) {
case 0: {
rate = 0;
break;
}
default: {
rate = -1;
break;
}
}
return rate;
}
FAUSTPP_VIRTUAL int getOutputRate(int channel) {
int rate;
switch ((channel)) {
case 0: {
rate = 1;
break;
}
default: {
rate = -1;
break;
}
}
return rate;
}
static void classInit(int sample_rate) {
mydspSIG0* sig0 = newmydspSIG0();
sig0->instanceInitmydspSIG0(sample_rate);
sig0->fillmydspSIG0(128, ftbl0mydspSIG0);
deletemydspSIG0(sig0);
}
FAUSTPP_VIRTUAL void instanceConstants(int sample_rate) {
fSampleRate = sample_rate;
fConst0 = std::min<float>(192000.0f, std::max<float>(1.0f, float(fSampleRate)));
fConst1 = std::exp((0.0f - (10.0f / fConst0)));
fConst2 = (1.0f - fConst1);
fConst3 = std::exp((0.0f - (207.345108f / fConst0)));
fConst4 = (0.00999999978f * fConst2);
fConst5 = (1.0f / fConst0);
fConst6 = (0.5f * (fConst3 + 1.0f));
fConst7 = (0.0f - fConst6);
fConst8 = (2764.60156f / fConst0);
}
FAUSTPP_VIRTUAL void instanceResetUserInterface() {
fHslider0 = FAUSTFLOAT(50.0f);
fHslider1 = FAUSTFLOAT(75.0f);
fHslider2 = FAUSTFLOAT(1.0f);
fHslider3 = FAUSTFLOAT(500.0f);
fHslider4 = FAUSTFLOAT(0.20000000000000001f);
fCheckbox0 = FAUSTFLOAT(0.0f);
}
FAUSTPP_VIRTUAL void instanceClear() {
for (int l0 = 0; (l0 < 4); l0 = (l0 + 1)) {
fRec0_perm[l0] = 0.0f;
}
for (int l1 = 0; (l1 < 4); l1 = (l1 + 1)) {
fRec6_perm[l1] = 0.0f;
}
for (int l2 = 0; (l2 < 4); l2 = (l2 + 1)) {
fRec8_perm[l2] = 0.0f;
}
for (int l3 = 0; (l3 < 4); l3 = (l3 + 1)) {
fRec7_perm[l3] = 0.0f;
}
for (int l4 = 0; (l4 < 4); l4 = (l4 + 1)) {
fRec10_perm[l4] = 0.0f;
}
for (int l5 = 0; (l5 < 4); l5 = (l5 + 1)) {
fRec9_perm[l5] = 0.0f;
}
for (int l6 = 0; (l6 < 4); l6 = (l6 + 1)) {
fRec11_perm[l6] = 0.0f;
}
for (int l7 = 0; (l7 < 4); l7 = (l7 + 1)) {
fRec12_perm[l7] = 0.0f;
}
for (int l8 = 0; (l8 < 4); l8 = (l8 + 1)) {
fRec14_perm[l8] = 0.0f;
}
for (int l9 = 0; (l9 < 4); l9 = (l9 + 1)) {
fRec13_perm[l9] = 0.0f;
}
for (int l11 = 0; (l11 < 4); l11 = (l11 + 1)) {
fRec5_perm[l11] = 0.0f;
}
for (int l12 = 0; (l12 < 4); l12 = (l12 + 1)) {
fRec4_perm[l12] = 0.0f;
}
for (int l13 = 0; (l13 < 4); l13 = (l13 + 1)) {
fRec3_perm[l13] = 0.0f;
}
for (int l14 = 0; (l14 < 4); l14 = (l14 + 1)) {
fRec2_perm[l14] = 0.0f;
}
for (int l15 = 0; (l15 < 4); l15 = (l15 + 1)) {
fRec1_perm[l15] = 0.0f;
}
for (int l16 = 0; (l16 < 4); l16 = (l16 + 1)) {
fRec16_perm[l16] = 0.0f;
}
for (int l17 = 0; (l17 < 4); l17 = (l17 + 1)) {
fRec17_perm[l17] = 0.0f;
}
}
FAUSTPP_VIRTUAL void init(int sample_rate) {
classInit(sample_rate);
instanceInit(sample_rate);
}
FAUSTPP_VIRTUAL void instanceInit(int sample_rate) {
instanceConstants(sample_rate);
instanceResetUserInterface();
instanceClear();
}
FAUSTPP_VIRTUAL mydsp* clone() {
return new mydsp();
}
FAUSTPP_VIRTUAL int getSampleRate() {
return fSampleRate;
}
FAUSTPP_VIRTUAL void buildUserInterface(UI* ui_interface) {
ui_interface->openVerticalBox("Stone Phaser");
ui_interface->declare(&fCheckbox0, "0", "");
ui_interface->declare(&fCheckbox0, "symbol", "bypass");
ui_interface->addCheckButton("Bypass", &fCheckbox0);
ui_interface->declare(&fHslider2, "1", "");
ui_interface->declare(&fHslider2, "boolean", "");
ui_interface->declare(&fHslider2, "symbol", "color");
ui_interface->addHorizontalSlider("Color", &fHslider2, 1.0f, 0.0f, 1.0f, 1.0f);
ui_interface->declare(&fHslider4, "2", "");
ui_interface->declare(&fHslider4, "scale", "log");
ui_interface->declare(&fHslider4, "symbol", "lfo_frequency");
ui_interface->declare(&fHslider4, "unit", "Hz");
ui_interface->addHorizontalSlider("LFO frequency", &fHslider4, 0.200000003f, 0.00999999978f, 5.0f, 0.00999999978f);
ui_interface->declare(&fHslider1, "3", "");
ui_interface->declare(&fHslider1, "integer", "");
ui_interface->declare(&fHslider1, "symbol", "feedback_depth");
ui_interface->declare(&fHslider1, "unit", "%");
ui_interface->addHorizontalSlider("Feedback depth", &fHslider1, 75.0f, 0.0f, 99.0f, 1.0f);
ui_interface->declare(&fHslider3, "4", "");
ui_interface->declare(&fHslider3, "abbrev", "Fb bass cut");
ui_interface->declare(&fHslider3, "scale", "log");
ui_interface->declare(&fHslider3, "symbol", "feedback_hpf_cutoff");
ui_interface->declare(&fHslider3, "unit", "Hz");
ui_interface->addHorizontalSlider("Feedback bass cut", &fHslider3, 500.0f, 10.0f, 5000.0f, 1.0f);
ui_interface->declare(&fHslider0, "5", "");
ui_interface->declare(&fHslider0, "integer", "");
ui_interface->declare(&fHslider0, "symbol", "mix");
ui_interface->declare(&fHslider0, "unit", "%");
ui_interface->addHorizontalSlider("Dry/wet mix", &fHslider0, 50.0f, 0.0f, 100.0f, 1.0f);
ui_interface->declare(&fHbargraph0, "7", "");
ui_interface->declare(&fHbargraph0, "symbol", "bypass_meter");
ui_interface->addHorizontalBargraph("Bypass meter", &fHbargraph0, 0.0f, 1.0f);
ui_interface->closeBox();
}
FAUSTPP_VIRTUAL void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) {
FAUSTFLOAT* input0_ptr = inputs[0];
FAUSTFLOAT* output0_ptr = outputs[0];
float fSlow0 = (0.0157079641f * float(fHslider0));
float fSlow1 = (fConst2 * std::cos(fSlow0));
float fRec0_tmp[36];
float* fRec0 = &fRec0_tmp[4];
float fRec6_tmp[36];
float* fRec6 = &fRec6_tmp[4];
float fSlow2 = (fConst4 * float(fHslider1));
float fRec8_tmp[36];
float* fRec8 = &fRec8_tmp[4];
int iSlow3 = int(float(fHslider2));
float fRec7_tmp[36];
float* fRec7 = &fRec7_tmp[4];
float fSlow4 = (fConst2 * float(fHslider3));
float fRec10_tmp[36];
float* fRec10 = &fRec10_tmp[4];
float fZec0[32];
float fRec9_tmp[36];
float* fRec9 = &fRec9_tmp[4];
float fSlow5 = (fConst2 * (iSlow3 ? 39.4868202f : 62.3695068f));
float fRec11_tmp[36];
float* fRec11 = &fRec11_tmp[4];
float fSlow6 = (fConst2 * (iSlow3 ? 96.8631363f : 114.232643f));
float fRec12_tmp[36];
float* fRec12 = &fRec12_tmp[4];
float fSlow7 = (fConst2 * float(fHslider4));
float fRec14_tmp[36];
float* fRec14 = &fRec14_tmp[4];
float fZec1[32];
float fRec13_tmp[36];
float* fRec13 = &fRec13_tmp[4];
float fZec2[32];
float fZec3[32];
int iZec4[32];
float fZec5[32];
float fZec6[32];
float fRec5_tmp[36];
float* fRec5 = &fRec5_tmp[4];
float fRec4_tmp[36];
float* fRec4 = &fRec4_tmp[4];
float fRec3_tmp[36];
float* fRec3 = &fRec3_tmp[4];
float fRec2_tmp[36];
float* fRec2 = &fRec2_tmp[4];
float fRec1_tmp[36];
float* fRec1 = &fRec1_tmp[4];
float fSlow8 = (fConst2 * std::sin(fSlow0));
float fRec16_tmp[36];
float* fRec16 = &fRec16_tmp[4];
float fSlow9 = (fConst2 * float((1 - (float(fCheckbox0) > 0.5f))));
float fRec17_tmp[36];
float* fRec17 = &fRec17_tmp[4];
int vindex = 0;
/* Main loop */
for (vindex = 0; (vindex <= (count - 32)); vindex = (vindex + 32)) {
FAUSTFLOAT* input0 = &input0_ptr[vindex];
FAUSTFLOAT* output0 = &output0_ptr[vindex];
int vsize = 32;
/* Recursive loop 0 */
/* Pre code */
for (int j16 = 0; (j16 < 4); j16 = (j16 + 1)) {
fRec14_tmp[j16] = fRec14_perm[j16];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec14[i] = (fSlow7 + (fConst1 * fRec14[(i - 1)]));
}
/* Post code */
for (int j17 = 0; (j17 < 4); j17 = (j17 + 1)) {
fRec14_perm[j17] = fRec14_tmp[(vsize + j17)];
}
/* Recursive loop 1 */
/* Pre code */
for (int j18 = 0; (j18 < 4); j18 = (j18 + 1)) {
fRec13_tmp[j18] = fRec13_perm[j18];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec1[i] = (fRec13[(i - 1)] + (fConst5 * fRec14[(i - 1)]));
fRec13[i] = (fZec1[i] - std::floor(fZec1[i]));
}
/* Post code */
for (int j19 = 0; (j19 < 4); j19 = (j19 + 1)) {
fRec13_perm[j19] = fRec13_tmp[(vsize + j19)];
}
/* Vectorizable loop 2 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec3[i] = (128.0f * fRec13[i]);
}
/* Recursive loop 3 */
/* Pre code */
for (int j8 = 0; (j8 < 4); j8 = (j8 + 1)) {
fRec10_tmp[j8] = fRec10_perm[j8];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec10[i] = (fSlow4 + (fConst1 * fRec10[(i - 1)]));
}
/* Post code */
for (int j9 = 0; (j9 < 4); j9 = (j9 + 1)) {
fRec10_perm[j9] = fRec10_tmp[(vsize + j9)];
}
/* Vectorizable loop 4 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
iZec4[i] = int(fZec3[i]);
}
/* Recursive loop 5 */
/* Pre code */
for (int j4 = 0; (j4 < 4); j4 = (j4 + 1)) {
fRec8_tmp[j4] = fRec8_perm[j4];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec8[i] = (fSlow2 + (fConst1 * fRec8[(i - 1)]));
}
/* Post code */
for (int j5 = 0; (j5 < 4); j5 = (j5 + 1)) {
fRec8_perm[j5] = fRec8_tmp[(vsize + j5)];
}
/* Vectorizable loop 6 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec0[i] = std::exp((fConst5 * (0.0f - (6.28318548f * fRec10[i]))));
}
/* Recursive loop 7 */
/* Pre code */
for (int j12 = 0; (j12 < 4); j12 = (j12 + 1)) {
fRec11_tmp[j12] = fRec11_perm[j12];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec11[i] = (fSlow5 + (fConst1 * fRec11[(i - 1)]));
}
/* Post code */
for (int j13 = 0; (j13 < 4); j13 = (j13 + 1)) {
fRec11_perm[j13] = fRec11_tmp[(vsize + j13)];
}
/* Recursive loop 8 */
/* Pre code */
for (int j14 = 0; (j14 < 4); j14 = (j14 + 1)) {
fRec12_tmp[j14] = fRec12_perm[j14];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec12[i] = (fSlow6 + (fConst1 * fRec12[(i - 1)]));
}
/* Post code */
for (int j15 = 0; (j15 < 4); j15 = (j15 + 1)) {
fRec12_perm[j15] = fRec12_tmp[(vsize + j15)];
}
/* Vectorizable loop 9 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec5[i] = float(iZec4[i]);
}
/* Recursive loop 10 */
/* Pre code */
for (int j2 = 0; (j2 < 4); j2 = (j2 + 1)) {
fRec6_tmp[j2] = fRec6_perm[j2];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec6[i] = (float(input0[i]) + (fConst3 * fRec6[(i - 1)]));
}
/* Post code */
for (int j3 = 0; (j3 < 4); j3 = (j3 + 1)) {
fRec6_perm[j3] = fRec6_tmp[(vsize + j3)];
}
/* Recursive loop 11 */
/* Pre code */
for (int j6 = 0; (j6 < 4); j6 = (j6 + 1)) {
fRec7_tmp[j6] = fRec7_perm[j6];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec7[i] = ((fConst1 * fRec7[(i - 1)]) + (fConst2 * (iSlow3 ? fRec8[i] : (0.100000001f * fRec8[i]))));
}
/* Post code */
for (int j7 = 0; (j7 < 4); j7 = (j7 + 1)) {
fRec7_perm[j7] = fRec7_tmp[(vsize + j7)];
}
/* Vectorizable loop 12 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec2[i] = (fZec0[i] + 1.0f);
}
/* Vectorizable loop 13 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec6[i] = ((fConst8 * std::pow(2.0f, (0.0833333358f * ((fRec11[i] + ((fRec12[i] - fRec11[i]) * ((ftbl0mydspSIG0[iZec4[i]] * (fZec5[i] + (1.0f - fZec3[i]))) + ((fZec3[i] - fZec5[i]) * ftbl0mydspSIG0[((iZec4[i] + 1) % 128)])))) + -69.0f)))) + -1.0f);
}
/* Recursive loop 14 */
/* Pre code */
for (int j0 = 0; (j0 < 4); j0 = (j0 + 1)) {
fRec0_tmp[j0] = fRec0_perm[j0];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec0[i] = (fSlow1 + (fConst1 * fRec0[(i - 1)]));
}
/* Post code */
for (int j1 = 0; (j1 < 4); j1 = (j1 + 1)) {
fRec0_perm[j1] = fRec0_tmp[(vsize + j1)];
}
/* Recursive loop 15 */
/* Pre code */
for (int j10 = 0; (j10 < 4); j10 = (j10 + 1)) {
fRec9_tmp[j10] = fRec9_perm[j10];
}
for (int j20 = 0; (j20 < 4); j20 = (j20 + 1)) {
fRec5_tmp[j20] = fRec5_perm[j20];
}
for (int j22 = 0; (j22 < 4); j22 = (j22 + 1)) {
fRec4_tmp[j22] = fRec4_perm[j22];
}
for (int j24 = 0; (j24 < 4); j24 = (j24 + 1)) {
fRec3_tmp[j24] = fRec3_perm[j24];
}
for (int j26 = 0; (j26 < 4); j26 = (j26 + 1)) {
fRec2_tmp[j26] = fRec2_perm[j26];
}
for (int j28 = 0; (j28 < 4); j28 = (j28 + 1)) {
fRec1_tmp[j28] = fRec1_perm[j28];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec9[i] = (fRec1[(i - 1)] + (fRec9[(i - 1)] * fZec0[i]));
fRec5[i] = (((fConst7 * fRec6[(i - 1)]) + ((fRec7[i] * ((0.5f * (fRec9[i] * fZec2[i])) + (fRec9[(i - 1)] * (0.0f - (0.5f * fZec2[i]))))) + (fConst6 * fRec6[i]))) - (fRec5[(i - 1)] * fZec6[i]));
fRec4[i] = (fRec5[(i - 1)] + (fZec6[i] * (fRec5[i] - fRec4[(i - 1)])));
fRec3[i] = (fRec4[(i - 1)] + (fZec6[i] * (fRec4[i] - fRec3[(i - 1)])));
fRec2[i] = (fRec3[(i - 1)] + (fZec6[i] * (fRec3[i] - fRec2[(i - 1)])));
fRec1[i] = (fRec2[(i - 1)] + (fRec2[i] * fZec6[i]));
}
/* Post code */
for (int j11 = 0; (j11 < 4); j11 = (j11 + 1)) {
fRec9_perm[j11] = fRec9_tmp[(vsize + j11)];
}
for (int j21 = 0; (j21 < 4); j21 = (j21 + 1)) {
fRec5_perm[j21] = fRec5_tmp[(vsize + j21)];
}
for (int j23 = 0; (j23 < 4); j23 = (j23 + 1)) {
fRec4_perm[j23] = fRec4_tmp[(vsize + j23)];
}
for (int j25 = 0; (j25 < 4); j25 = (j25 + 1)) {
fRec3_perm[j25] = fRec3_tmp[(vsize + j25)];
}
for (int j27 = 0; (j27 < 4); j27 = (j27 + 1)) {
fRec2_perm[j27] = fRec2_tmp[(vsize + j27)];
}
for (int j29 = 0; (j29 < 4); j29 = (j29 + 1)) {
fRec1_perm[j29] = fRec1_tmp[(vsize + j29)];
}
/* Recursive loop 16 */
/* Pre code */
for (int j30 = 0; (j30 < 4); j30 = (j30 + 1)) {
fRec16_tmp[j30] = fRec16_perm[j30];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec16[i] = (fSlow8 + (fConst1 * fRec16[(i - 1)]));
}
/* Post code */
for (int j31 = 0; (j31 < 4); j31 = (j31 + 1)) {
fRec16_perm[j31] = fRec16_tmp[(vsize + j31)];
}
/* Recursive loop 17 */
/* Pre code */
for (int j32 = 0; (j32 < 4); j32 = (j32 + 1)) {
fRec17_tmp[j32] = fRec17_perm[j32];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec17[i] = (fSlow9 + (fConst1 * fRec17[(i - 1)]));
}
/* Post code */
for (int j33 = 0; (j33 < 4); j33 = (j33 + 1)) {
fRec17_perm[j33] = fRec17_tmp[(vsize + j33)];
}
/* Vectorizable loop 18 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fHbargraph0 = FAUSTFLOAT(fRec17[i]);
output0[i] = FAUSTFLOAT(((((float(input0[i]) * fRec0[i]) + (fRec1[i] * fRec16[i])) * fRec17[i]) + (float(input0[i]) * (1.0f - fRec17[i]))));
}
}
/* Remaining frames */
if (vindex < count) {
FAUSTFLOAT* input0 = &input0_ptr[vindex];
FAUSTFLOAT* output0 = &output0_ptr[vindex];
int vsize = (count - vindex);
/* Recursive loop 0 */
/* Pre code */
for (int j16 = 0; (j16 < 4); j16 = (j16 + 1)) {
fRec14_tmp[j16] = fRec14_perm[j16];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec14[i] = (fSlow7 + (fConst1 * fRec14[(i - 1)]));
}
/* Post code */
for (int j17 = 0; (j17 < 4); j17 = (j17 + 1)) {
fRec14_perm[j17] = fRec14_tmp[(vsize + j17)];
}
/* Recursive loop 1 */
/* Pre code */
for (int j18 = 0; (j18 < 4); j18 = (j18 + 1)) {
fRec13_tmp[j18] = fRec13_perm[j18];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec1[i] = (fRec13[(i - 1)] + (fConst5 * fRec14[(i - 1)]));
fRec13[i] = (fZec1[i] - std::floor(fZec1[i]));
}
/* Post code */
for (int j19 = 0; (j19 < 4); j19 = (j19 + 1)) {
fRec13_perm[j19] = fRec13_tmp[(vsize + j19)];
}
/* Vectorizable loop 2 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec3[i] = (128.0f * fRec13[i]);
}
/* Recursive loop 3 */
/* Pre code */
for (int j8 = 0; (j8 < 4); j8 = (j8 + 1)) {
fRec10_tmp[j8] = fRec10_perm[j8];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec10[i] = (fSlow4 + (fConst1 * fRec10[(i - 1)]));
}
/* Post code */
for (int j9 = 0; (j9 < 4); j9 = (j9 + 1)) {
fRec10_perm[j9] = fRec10_tmp[(vsize + j9)];
}
/* Vectorizable loop 4 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
iZec4[i] = int(fZec3[i]);
}
/* Recursive loop 5 */
/* Pre code */
for (int j4 = 0; (j4 < 4); j4 = (j4 + 1)) {
fRec8_tmp[j4] = fRec8_perm[j4];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec8[i] = (fSlow2 + (fConst1 * fRec8[(i - 1)]));
}
/* Post code */
for (int j5 = 0; (j5 < 4); j5 = (j5 + 1)) {
fRec8_perm[j5] = fRec8_tmp[(vsize + j5)];
}
/* Vectorizable loop 6 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec0[i] = std::exp((fConst5 * (0.0f - (6.28318548f * fRec10[i]))));
}
/* Recursive loop 7 */
/* Pre code */
for (int j12 = 0; (j12 < 4); j12 = (j12 + 1)) {
fRec11_tmp[j12] = fRec11_perm[j12];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec11[i] = (fSlow5 + (fConst1 * fRec11[(i - 1)]));
}
/* Post code */
for (int j13 = 0; (j13 < 4); j13 = (j13 + 1)) {
fRec11_perm[j13] = fRec11_tmp[(vsize + j13)];
}
/* Recursive loop 8 */
/* Pre code */
for (int j14 = 0; (j14 < 4); j14 = (j14 + 1)) {
fRec12_tmp[j14] = fRec12_perm[j14];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec12[i] = (fSlow6 + (fConst1 * fRec12[(i - 1)]));
}
/* Post code */
for (int j15 = 0; (j15 < 4); j15 = (j15 + 1)) {
fRec12_perm[j15] = fRec12_tmp[(vsize + j15)];
}
/* Vectorizable loop 9 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec5[i] = float(iZec4[i]);
}
/* Recursive loop 10 */
/* Pre code */
for (int j2 = 0; (j2 < 4); j2 = (j2 + 1)) {
fRec6_tmp[j2] = fRec6_perm[j2];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec6[i] = (float(input0[i]) + (fConst3 * fRec6[(i - 1)]));
}
/* Post code */
for (int j3 = 0; (j3 < 4); j3 = (j3 + 1)) {
fRec6_perm[j3] = fRec6_tmp[(vsize + j3)];
}
/* Recursive loop 11 */
/* Pre code */
for (int j6 = 0; (j6 < 4); j6 = (j6 + 1)) {
fRec7_tmp[j6] = fRec7_perm[j6];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec7[i] = ((fConst1 * fRec7[(i - 1)]) + (fConst2 * (iSlow3 ? fRec8[i] : (0.100000001f * fRec8[i]))));
}
/* Post code */
for (int j7 = 0; (j7 < 4); j7 = (j7 + 1)) {
fRec7_perm[j7] = fRec7_tmp[(vsize + j7)];
}
/* Vectorizable loop 12 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec2[i] = (fZec0[i] + 1.0f);
}
/* Vectorizable loop 13 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fZec6[i] = ((fConst8 * std::pow(2.0f, (0.0833333358f * ((fRec11[i] + ((fRec12[i] - fRec11[i]) * ((ftbl0mydspSIG0[iZec4[i]] * (fZec5[i] + (1.0f - fZec3[i]))) + ((fZec3[i] - fZec5[i]) * ftbl0mydspSIG0[((iZec4[i] + 1) % 128)])))) + -69.0f)))) + -1.0f);
}
/* Recursive loop 14 */
/* Pre code */
for (int j0 = 0; (j0 < 4); j0 = (j0 + 1)) {
fRec0_tmp[j0] = fRec0_perm[j0];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec0[i] = (fSlow1 + (fConst1 * fRec0[(i - 1)]));
}
/* Post code */
for (int j1 = 0; (j1 < 4); j1 = (j1 + 1)) {
fRec0_perm[j1] = fRec0_tmp[(vsize + j1)];
}
/* Recursive loop 15 */
/* Pre code */
for (int j10 = 0; (j10 < 4); j10 = (j10 + 1)) {
fRec9_tmp[j10] = fRec9_perm[j10];
}
for (int j20 = 0; (j20 < 4); j20 = (j20 + 1)) {
fRec5_tmp[j20] = fRec5_perm[j20];
}
for (int j22 = 0; (j22 < 4); j22 = (j22 + 1)) {
fRec4_tmp[j22] = fRec4_perm[j22];
}
for (int j24 = 0; (j24 < 4); j24 = (j24 + 1)) {
fRec3_tmp[j24] = fRec3_perm[j24];
}
for (int j26 = 0; (j26 < 4); j26 = (j26 + 1)) {
fRec2_tmp[j26] = fRec2_perm[j26];
}
for (int j28 = 0; (j28 < 4); j28 = (j28 + 1)) {
fRec1_tmp[j28] = fRec1_perm[j28];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec9[i] = (fRec1[(i - 1)] + (fRec9[(i - 1)] * fZec0[i]));
fRec5[i] = (((fConst7 * fRec6[(i - 1)]) + ((fRec7[i] * ((0.5f * (fRec9[i] * fZec2[i])) + (fRec9[(i - 1)] * (0.0f - (0.5f * fZec2[i]))))) + (fConst6 * fRec6[i]))) - (fRec5[(i - 1)] * fZec6[i]));
fRec4[i] = (fRec5[(i - 1)] + (fZec6[i] * (fRec5[i] - fRec4[(i - 1)])));
fRec3[i] = (fRec4[(i - 1)] + (fZec6[i] * (fRec4[i] - fRec3[(i - 1)])));
fRec2[i] = (fRec3[(i - 1)] + (fZec6[i] * (fRec3[i] - fRec2[(i - 1)])));
fRec1[i] = (fRec2[(i - 1)] + (fRec2[i] * fZec6[i]));
}
/* Post code */
for (int j11 = 0; (j11 < 4); j11 = (j11 + 1)) {
fRec9_perm[j11] = fRec9_tmp[(vsize + j11)];
}
for (int j21 = 0; (j21 < 4); j21 = (j21 + 1)) {
fRec5_perm[j21] = fRec5_tmp[(vsize + j21)];
}
for (int j23 = 0; (j23 < 4); j23 = (j23 + 1)) {
fRec4_perm[j23] = fRec4_tmp[(vsize + j23)];
}
for (int j25 = 0; (j25 < 4); j25 = (j25 + 1)) {
fRec3_perm[j25] = fRec3_tmp[(vsize + j25)];
}
for (int j27 = 0; (j27 < 4); j27 = (j27 + 1)) {
fRec2_perm[j27] = fRec2_tmp[(vsize + j27)];
}
for (int j29 = 0; (j29 < 4); j29 = (j29 + 1)) {
fRec1_perm[j29] = fRec1_tmp[(vsize + j29)];
}
/* Recursive loop 16 */
/* Pre code */
for (int j30 = 0; (j30 < 4); j30 = (j30 + 1)) {
fRec16_tmp[j30] = fRec16_perm[j30];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec16[i] = (fSlow8 + (fConst1 * fRec16[(i - 1)]));
}
/* Post code */
for (int j31 = 0; (j31 < 4); j31 = (j31 + 1)) {
fRec16_perm[j31] = fRec16_tmp[(vsize + j31)];
}
/* Recursive loop 17 */
/* Pre code */
for (int j32 = 0; (j32 < 4); j32 = (j32 + 1)) {
fRec17_tmp[j32] = fRec17_perm[j32];
}
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fRec17[i] = (fSlow9 + (fConst1 * fRec17[(i - 1)]));
}
/* Post code */
for (int j33 = 0; (j33 < 4); j33 = (j33 + 1)) {
fRec17_perm[j33] = fRec17_tmp[(vsize + j33)];
}
/* Vectorizable loop 18 */
/* Compute code */
for (int i = 0; (i < vsize); i = (i + 1)) {
fHbargraph0 = FAUSTFLOAT(fRec17[i]);
output0[i] = FAUSTFLOAT(((((float(input0[i]) * fRec0[i]) + (fRec1[i] * fRec16[i])) * fRec17[i]) + (float(input0[i]) * (1.0f - fRec17[i]))));
}
}
}
};
FAUSTPP_END_NAMESPACE
#if defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
//------------------------------------------------------------------------------
// End the Faust code section
StonePhaserDsp::StonePhaserDsp()
{
mydsp *dsp = new mydsp;
fDsp.reset(dsp);
dsp->instanceResetUserInterface();
}
StonePhaserDsp::~StonePhaserDsp()
{
}
void StonePhaserDsp::init(float sample_rate)
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.classInit(sample_rate);
dsp.instanceConstants(sample_rate);
clear();
}
void StonePhaserDsp::clear() noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.instanceClear();
}
void StonePhaserDsp::process(
const float *in0,
float *out0,
unsigned count) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
float *inputs[] = {
const_cast<float *>(in0),
};
float *outputs[] = {
out0,
};
dsp.compute(count, inputs, outputs);
}
const char *StonePhaserDsp::parameter_label(unsigned index) noexcept
{
switch (index) {
case 0:
return "Bypass";
case 1:
return "Color";
case 2:
return "LFO frequency";
case 3:
return "Feedback depth";
case 4:
return "Feedback bass cut";
case 5:
return "Dry/wet mix";
case 6:
return "Bypass meter";
default:
return 0;
}
}
const char *StonePhaserDsp::parameter_short_label(unsigned index) noexcept
{
switch (index) {
case 0:
return "";
case 1:
return "";
case 2:
return "";
case 3:
return "";
case 4:
return "Fb bass cut";
case 5:
return "";
case 6:
return "";
default:
return 0;
}
}
const char *StonePhaserDsp::parameter_symbol(unsigned index) noexcept
{
switch (index) {
case 0:
return "bypass";
case 1:
return "color";
case 2:
return "lfo_frequency";
case 3:
return "feedback_depth";
case 4:
return "feedback_hpf_cutoff";
case 5:
return "mix";
case 6:
return "bypass_meter";
default:
return 0;
}
}
const char *StonePhaserDsp::parameter_unit(unsigned index) noexcept
{
switch (index) {
case 0:
return "";
case 1:
return "";
case 2:
return "Hz";
case 3:
return "%";
case 4:
return "Hz";
case 5:
return "%";
case 6:
return "";
default:
return 0;
}
}
const StonePhaserDsp::ParameterRange *StonePhaserDsp::parameter_range(unsigned index) noexcept
{
switch (index) {
case 0: {
static const ParameterRange range = { 0, 0, 1 };
return ⦥
}
case 1: {
static const ParameterRange range = { 1, 0, 1 };
return ⦥
}
case 2: {
static const ParameterRange range = { 0.2, 0.0099999998, 5 };
return ⦥
}
case 3: {
static const ParameterRange range = { 75, 0, 99 };
return ⦥
}
case 4: {
static const ParameterRange range = { 500, 10, 5000 };
return ⦥
}
case 5: {
static const ParameterRange range = { 50, 0, 100 };
return ⦥
}
case 6: {
static const ParameterRange range = { 0, 0, 1 };
return ⦥
}
default:
return 0;
}
}
bool StonePhaserDsp::parameter_is_trigger(unsigned index) noexcept
{
switch (index) {
default:
return false;
}
}
bool StonePhaserDsp::parameter_is_boolean(unsigned index) noexcept
{
switch (index) {
case 0:
return true;
case 1:
return true;
default:
return false;
}
}
bool StonePhaserDsp::parameter_is_integer(unsigned index) noexcept
{
switch (index) {
case 0:
return true;
case 1:
return true;
case 3:
return true;
case 5:
return true;
default:
return false;
}
}
bool StonePhaserDsp::parameter_is_logarithmic(unsigned index) noexcept
{
switch (index) {
case 2:
return true;
case 4:
return true;
default:
return false;
}
}
float StonePhaserDsp::get_parameter(unsigned index) const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
switch (index) {
case 0:
return dsp.fCheckbox0;
case 1:
return dsp.fHslider2;
case 2:
return dsp.fHslider4;
case 3:
return dsp.fHslider1;
case 4:
return dsp.fHslider3;
case 5:
return dsp.fHslider0;
case 6:
return dsp.fHbargraph0;
default:
(void)dsp;
return 0;
}
}
void StonePhaserDsp::set_parameter(unsigned index, float value) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
switch (index) {
case 0:
dsp.fCheckbox0 = value;
break;
case 1:
dsp.fHslider2 = value;
break;
case 2:
dsp.fHslider4 = value;
break;
case 3:
dsp.fHslider1 = value;
break;
case 4:
dsp.fHslider3 = value;
break;
case 5:
dsp.fHslider0 = value;
break;
default:
(void)dsp;
(void)value;
break;
}
}
float StonePhaserDsp::get_bypass() const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
return dsp.fCheckbox0;
}
float StonePhaserDsp::get_color() const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
return dsp.fHslider2;
}
float StonePhaserDsp::get_lfo_frequency() const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
return dsp.fHslider4;
}
float StonePhaserDsp::get_feedback_depth() const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
return dsp.fHslider1;
}
float StonePhaserDsp::get_feedback_hpf_cutoff() const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
return dsp.fHslider3;
}
float StonePhaserDsp::get_mix() const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
return dsp.fHslider0;
}
float StonePhaserDsp::get_bypass_meter() const noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
return dsp.fHbargraph0;
}
void StonePhaserDsp::set_bypass(float value) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.fCheckbox0 = value;
}
void StonePhaserDsp::set_color(float value) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.fHslider2 = value;
}
void StonePhaserDsp::set_lfo_frequency(float value) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.fHslider4 = value;
}
void StonePhaserDsp::set_feedback_depth(float value) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.fHslider1 = value;
}
void StonePhaserDsp::set_feedback_hpf_cutoff(float value) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.fHslider3 = value;
}
void StonePhaserDsp::set_mix(float value) noexcept
{
mydsp &dsp = static_cast<mydsp &>(*fDsp);
dsp.fHslider0 = value;
}
|
#ifndef KX_REND_RENDERER_FWD_HPP
#define KX_REND_RENDERER_FWD_HPP
namespace kx::rend
{
class Renderer;
}
#endif // KX_REND_RENDERER_FWD_HPP
|
//
// PPD file import utility for the CUPS PPD Compiler.
//
// Copyright 2007-2011 by Apple Inc.
// Copyright 2002-2005 by Easy Software Products.
//
// Licensed under Apache License v2.0. See the file "LICENSE" for more information.
//
//
// Include necessary headers...
//
#include "ppdc-private.h"
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
//
// Local functions...
//
static void usage(void);
//
// 'main()' - Main entry for the PPD import utility.
//
int // O - Exit status
main(int argc, // I - Number of command-line arguments
char *argv[]) // I - Command-line arguments
{
int i; // Looping var
char *opt; // Current option
const char *srcfile; // Output file
ppdcSource *src; // PPD source file data
// Scan the command-line...
srcfile = NULL;
src = NULL;
for (i = 1; i < argc; i ++)
if (argv[i][0] == '-')
{
for (opt = argv[i] + 1; *opt; opt ++)
switch (*opt)
{
case 'o' : // Output file
if (srcfile || src)
usage();
i ++;
if (i >= argc)
usage();
srcfile = argv[i];
break;
case 'I' : // Include dir
i ++;
if (i >= argc)
usage();
ppdcSource::add_include(argv[i]);
break;
default : // Unknown
usage();
}
}
else
{
// Open and load the driver info file...
if (!srcfile)
srcfile = "ppdi.drv";
if (!src)
{
if (access(srcfile, 0))
src = new ppdcSource();
else
src = new ppdcSource(srcfile);
}
// Import the PPD file...
src->import_ppd(argv[i]);
}
// If no drivers have been loaded, display the program usage message.
if (!src)
usage();
// Write the driver info file back to disk...
src->write_file(srcfile);
// Delete the printer driver information...
src->release();
// Return with no errors.
return (0);
}
//
// 'usage()' - Show usage and exit.
//
static void
usage(void)
{
puts(_("Usage: ppdi [options] filename.ppd [ ... "
"filenameN.ppd ]"));
puts(_("Options:"));
puts(_(" -I include-dir Add include directory to "
"search path."));
puts(_(" -o filename.drv Set driver information "
"file (otherwise ppdi.drv)."));
exit(1);
}
|
/**
* @file test.cpp
* @The test file of md5.
* @author Jiewei Wei
* @mail weijieweijerry@163.com
* @github https://github.com/JieweiWei
* @data Oct 19 2014
*
*/
#include <iostream>
#include "../src/md5.h"
using std::cout;
using std::endl;
void printMD5(const string& message) {
cout << "md5(\"" << message << "\") = "
<< MD5(message).toStr() << endl;
}
int main() {
printMD5("");
printMD5("a");
printMD5("abc");
printMD5("message digest");
printMD5("abcdefghijklmnopqrstuvwxyz");
printMD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
return 0;
}
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef CONNECTIVITY_HVIEW_HXX
#define CONNECTIVITY_HVIEW_HXX
#include "connectivity/sdbcx/VView.hxx"
/** === begin UNO includes === **/
#include <com/sun/star/sdbcx/XAlterView.hpp>
/** === end UNO includes === **/
#include <comphelper/uno3.hxx>
#include <cppuhelper/implbase1.hxx>
//........................................................................
namespace connectivity { namespace hsqldb
{
//........................................................................
//====================================================================
//= HView
//====================================================================
typedef ::connectivity::sdbcx::OView HView_Base;
typedef ::cppu::ImplHelper1< ::com::sun::star::sdbcx::XAlterView > HView_IBASE;
class HView :public HView_Base
,public HView_IBASE
{
public:
HView(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
sal_Bool _bCaseSensitive,
const ::rtl::OUString& _rSchemaName,
const ::rtl::OUString& _rName
);
// UNO
DECLARE_XINTERFACE()
DECLARE_XTYPEPROVIDER()
// XAlterView
virtual void SAL_CALL alterCommand( const ::rtl::OUString& NewCommand ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
protected:
virtual ~HView();
protected:
// OPropertyContainer
virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle ) const;
private:
/** retrieves the current command of the View
@throws ::com::sun::star::lang::WrappedTargetException
if an error occurs while retrieving the command from the database and
<arg>_bAllowSQLExceptin</arg> is <FALSE/>
@throws ::com::sun::star::sdbc::SQLException
if an error occurs while retrieving the command from the database and
<arg>_bAllowSQLException</arg> is <TRUE/>
*/
::rtl::OUString impl_getCommand_throw( bool _bAllowSQLException ) const;
private:
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection;
private:
using HView_Base::getFastPropertyValue;
};
//........................................................................
} } // namespace connectivity::hsqldb
//........................................................................
#endif // CONNECTIVITY_HVIEW_HXX
|
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//USB HS/FS/LS OTG Controller
namespace UsbhsId{ ///<Identification Register
using Addr = Register::Address<0x40034000,0x00000000,0x00000000,unsigned>;
///Configuration number
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> id{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///no description available
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nid{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Tag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tag{};
///Revision
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,21),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> revision{};
///Version
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> version{};
///Version ID
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,29),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> versionid{};
}
namespace UsbhsHwgeneral{ ///<General Hardware Parameters Register
using Addr = Register::Address<0x40034004,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///PHY Mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> phym{};
///Serial mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> sm{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsHwhost{ ///<Host Hardware Parameters Register
using Addr = Register::Address<0x40034008,0x00000000,0x00000000,unsigned>;
///Host Capable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hc{};
///Number of Ports
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nport{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Transaction translator contexts.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ttasy{};
///Transaction translator periodic contexts.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ttper{};
}
namespace UsbhsHwdevice{ ///<Device Hardware Parameters Register
using Addr = Register::Address<0x4003400c,0x00000000,0x00000000,unsigned>;
///Device Capable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dc{};
///Device endpoints.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> devep{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsHwtxbuf{ ///<Transmit Buffer Hardware Parameters Register
using Addr = Register::Address<0x40034010,0x00000000,0x00000000,unsigned>;
///Transmit Burst.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> txburst{};
///Transmit Address.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> txadd{};
///Transmit Channel Address
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> txchanadd{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Transmit local Context Registers
enum class TxlcVal {
v0=0x00000000, ///<Store device transmit contexts in the TX FIFO
v1=0x00000001, ///<Store device transmit contexts in a register file
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,TxlcVal> txlc{};
namespace TxlcValC{
constexpr Register::FieldValue<decltype(txlc)::Type,TxlcVal::v0> v0{};
constexpr Register::FieldValue<decltype(txlc)::Type,TxlcVal::v1> v1{};
}
}
namespace UsbhsHwrxbuf{ ///<Receive Buffer Hardware Parameters Register
using Addr = Register::Address<0x40034014,0x00000000,0x00000000,unsigned>;
///Receive Burst.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rxburst{};
///Receive Address.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rxadd{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsUsbSbuscfg{ ///<System Bus Interface Configuration Register
using Addr = Register::Address<0x40034090,0x00000000,0x00000000,unsigned>;
///Burst mode
enum class BurstmodeVal {
v000=0x00000000, ///<INCR burst of unspecified length
v001=0x00000001, ///<INCR4, non-multiple transfers of INCR4 is decomposed into singles.
v010=0x00000002, ///<INCR8, non-multiple transfers of INCR8, is decomposed into INCR4 or singles.
v011=0x00000003, ///<INCR16, non-multiple transfers of INCR16, is decomposed into INCR8, INCR4 or singles.
v100=0x00000004, ///<Reserved, do not use.
v101=0x00000005, ///<INCR4, non-multiple transfers of INCR4 is decomposed into smaller unspecified length bursts.
v110=0x00000006, ///<INCR8, non-multiple transfers of INCR8 is decomposed into smaller unspecified length bursts.
v111=0x00000007, ///<INCR16, non-multiple transfers of INCR16 is decomposed into smaller unspecified length bursts.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,BurstmodeVal> burstmode{};
namespace BurstmodeValC{
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v000> v000{};
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v001> v001{};
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v010> v010{};
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v011> v011{};
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v100> v100{};
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v101> v101{};
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v110> v110{};
constexpr Register::FieldValue<decltype(burstmode)::Type,BurstmodeVal::v111> v111{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsHciversion{ ///<Host Controller Interface Version and Capability Registers Length Register
using Addr = Register::Address<0x40034100,0x00000000,0x00000000,unsigned>;
///Capability registers length
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> caplength{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///EHCI revision number
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hciversion{};
}
namespace UsbhsHcsparams{ ///<Host Controller Structural Parameters Register
using Addr = Register::Address<0x40034104,0x00000000,0x00000000,unsigned>;
///Number of Ports
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nPorts{};
///Power Port Control
enum class PpcVal {
v1=0x00000001, ///<Ports have power port switches
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,PpcVal> ppc{};
namespace PpcValC{
constexpr Register::FieldValue<decltype(ppc)::Type,PpcVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Number Ports per CC
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nPcc{};
///Number of Companion Controllers
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nCc{};
///Port Indicators
enum class PiVal {
v0=0x00000000, ///<No port indicator fields
v1=0x00000001, ///<The port status and control registers include a R/W field for controlling the state of the port indicator
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,PiVal> pi{};
namespace PiValC{
constexpr Register::FieldValue<decltype(pi)::Type,PiVal::v0> v0{};
constexpr Register::FieldValue<decltype(pi)::Type,PiVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Ports per Transaction Translator
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nPtt{};
///Number of Transaction Translators.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nTt{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsHccparams{ ///<Host Controller Capability Parameters Register
using Addr = Register::Address<0x40034108,0x00000000,0x00000000,unsigned>;
///64-bit addressing capability.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> adc{};
///Programmable Frame List flag
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> pfl{};
///Asynchronous Schedule Park capability
enum class AspVal {
v0=0x00000000, ///<Park not supported.
v1=0x00000001, ///<Park supported.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,AspVal> asp{};
namespace AspValC{
constexpr Register::FieldValue<decltype(asp)::Type,AspVal::v0> v0{};
constexpr Register::FieldValue<decltype(asp)::Type,AspVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Isochronous Scheduling Threshold
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ist{};
///EHCI Extended Capabilities Pointer
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> eecp{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsDciversion{ ///<Device Controller Interface Version
using Addr = Register::Address<0x40034122,0xffff0000,0x00000000,unsigned>;
///no description available
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dciversion{};
}
namespace UsbhsDccparams{ ///<Device Controller Capability Parameters
using Addr = Register::Address<0x40034124,0x00000000,0x00000000,unsigned>;
///Device Endpoint Number
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> den{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Device Capable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dc{};
///Host Capable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hc{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsUsbcmd{ ///<USB Command Register
using Addr = Register::Address<0x40034140,0x00000000,0x00000000,unsigned>;
///Run/Stop
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> rs{};
///Controller Reset
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rst{};
///Frame list Size
enum class FsVal {
v00=0x00000000, ///<When FS2 = 0, the size is 1024 elements (4096 bytes). When FS2 = 1, the size is 64 elements (256 bytes).
v01=0x00000001, ///<When FS2 = 0, the size is 512 elements (2048 bytes). When FS2 = 1, the size is 32 elements (128 bytes).
v10=0x00000002, ///<When FS2 = 0, the size is 256 elements (1024 bytes). When FS2 = 1, the size is 16 elements (64 bytes).
v11=0x00000003, ///<When FS2 = 0, the size is 128 elements (512 bytes). When FS2 = 1, the size is 8 elements (32 bytes).
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,FsVal> fs{};
namespace FsValC{
constexpr Register::FieldValue<decltype(fs)::Type,FsVal::v00> v00{};
constexpr Register::FieldValue<decltype(fs)::Type,FsVal::v01> v01{};
constexpr Register::FieldValue<decltype(fs)::Type,FsVal::v10> v10{};
constexpr Register::FieldValue<decltype(fs)::Type,FsVal::v11> v11{};
}
///Periodic Schedule Enable
enum class PseVal {
v0=0x00000000, ///<Do not process periodic schedule.
v1=0x00000001, ///<Use the PERIODICLISTBASE register to access the periodic schedule.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,PseVal> pse{};
namespace PseValC{
constexpr Register::FieldValue<decltype(pse)::Type,PseVal::v0> v0{};
constexpr Register::FieldValue<decltype(pse)::Type,PseVal::v1> v1{};
}
///Asynchronous Schedule Enable
enum class AseVal {
v0=0x00000000, ///<Do not process asynchronous schedule.
v1=0x00000001, ///<Use the ASYNCLISTADDR register to access asynchronous schedule.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,AseVal> ase{};
namespace AseValC{
constexpr Register::FieldValue<decltype(ase)::Type,AseVal::v0> v0{};
constexpr Register::FieldValue<decltype(ase)::Type,AseVal::v1> v1{};
}
///Interrupt on Async Advance doorbell
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> iaa{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Asynchronous Schedule Park mode count
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> asp{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Asynchronous Schedule Park mode Enable
enum class AspeVal {
v0=0x00000000, ///<Park mode disabled
v1=0x00000001, ///<Park mode enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,AspeVal> aspe{};
namespace AspeValC{
constexpr Register::FieldValue<decltype(aspe)::Type,AspeVal::v0> v0{};
constexpr Register::FieldValue<decltype(aspe)::Type,AspeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Setup TripWire
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> sutw{};
///Add dTD TripWire
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> atdtw{};
///Frame list Size 2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> fs2{};
///Interrupt Threshold Control
enum class ItcVal {
v0=0x00000000, ///<Immediate (no threshold)
v1=0x00000001, ///<1 microframe
v10=0x00000002, ///<2 microframes
v100=0x00000004, ///<4 microframes
v1000=0x00000008, ///<8 microframes
v10000=0x00000010, ///<16 microframes
v100000=0x00000020, ///<32 microframes
v1000000=0x00000040, ///<64 microframes
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,ItcVal> itc{};
namespace ItcValC{
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v0> v0{};
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v1> v1{};
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v10> v10{};
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v100> v100{};
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v1000> v1000{};
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v10000> v10000{};
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v100000> v100000{};
constexpr Register::FieldValue<decltype(itc)::Type,ItcVal::v1000000> v1000000{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsUsbsts{ ///<USB Status Register
using Addr = Register::Address<0x40034144,0x00000000,0x00000000,unsigned>;
///USB Interrupt (USBINT)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ui{};
///USB Error Interrupt
enum class UeiVal {
v0=0x00000000, ///<No error
v1=0x00000001, ///<Error detected
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,UeiVal> uei{};
namespace UeiValC{
constexpr Register::FieldValue<decltype(uei)::Type,UeiVal::v0> v0{};
constexpr Register::FieldValue<decltype(uei)::Type,UeiVal::v1> v1{};
}
///Port Change detect
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> pci{};
///Frame-list Rollover
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> fri{};
///System Error
enum class SeiVal {
v0=0x00000000, ///<Normal operation
v1=0x00000001, ///<Error
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,SeiVal> sei{};
namespace SeiValC{
constexpr Register::FieldValue<decltype(sei)::Type,SeiVal::v0> v0{};
constexpr Register::FieldValue<decltype(sei)::Type,SeiVal::v1> v1{};
}
///Interrupt on Async Advance
enum class AaiVal {
v0=0x00000000, ///<No async advance interrupt
v1=0x00000001, ///<Async advance interrupt
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,AaiVal> aai{};
namespace AaiValC{
constexpr Register::FieldValue<decltype(aai)::Type,AaiVal::v0> v0{};
constexpr Register::FieldValue<decltype(aai)::Type,AaiVal::v1> v1{};
}
///USB Reset received
enum class UriVal {
v0=0x00000000, ///<No reset received
v1=0x00000001, ///<Reset received
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,UriVal> uri{};
namespace UriValC{
constexpr Register::FieldValue<decltype(uri)::Type,UriVal::v0> v0{};
constexpr Register::FieldValue<decltype(uri)::Type,UriVal::v1> v1{};
}
///SOF Received
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> sri{};
///Device-controller suspend
enum class SliVal {
v0=0x00000000, ///<Active
v1=0x00000001, ///<Suspended
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SliVal> sli{};
namespace SliValC{
constexpr Register::FieldValue<decltype(sli)::Type,SliVal::v0> v0{};
constexpr Register::FieldValue<decltype(sli)::Type,SliVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///ULPI Interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ulpii{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Host Controller Halted
enum class HchVal {
v0=0x00000000, ///<Running
v1=0x00000001, ///<Halted
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,HchVal> hch{};
namespace HchValC{
constexpr Register::FieldValue<decltype(hch)::Type,HchVal::v0> v0{};
constexpr Register::FieldValue<decltype(hch)::Type,HchVal::v1> v1{};
}
///Reclamation
enum class RclVal {
v0=0x00000000, ///<Non-empty asynchronous schedule
v1=0x00000001, ///<Empty asynchronous schedule
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,RclVal> rcl{};
namespace RclValC{
constexpr Register::FieldValue<decltype(rcl)::Type,RclVal::v0> v0{};
constexpr Register::FieldValue<decltype(rcl)::Type,RclVal::v1> v1{};
}
///Periodic schedule Status
enum class PsVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,PsVal> ps{};
namespace PsValC{
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{};
}
///Asynchronous schedule Status
enum class AsVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,AsVal> as{};
namespace AsValC{
constexpr Register::FieldValue<decltype(as)::Type,AsVal::v0> v0{};
constexpr Register::FieldValue<decltype(as)::Type,AsVal::v1> v1{};
}
///NAK Interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> naki{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///USB host Asynchronous Interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> uai{};
///USB host Periodic Interrupt
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> upi{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///General purpose Timer 0 Interrupt
enum class Ti0Val {
v0=0x00000000, ///<No interrupt
v1=0x00000001, ///<Interrupt occurred
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,Ti0Val> ti0{};
namespace Ti0ValC{
constexpr Register::FieldValue<decltype(ti0)::Type,Ti0Val::v0> v0{};
constexpr Register::FieldValue<decltype(ti0)::Type,Ti0Val::v1> v1{};
}
///General purpose Timer 1 Interrupt
enum class Ti1Val {
v0=0x00000000, ///<No interrupt
v1=0x00000001, ///<Interrupt occurred
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,Ti1Val> ti1{};
namespace Ti1ValC{
constexpr Register::FieldValue<decltype(ti1)::Type,Ti1Val::v0> v0{};
constexpr Register::FieldValue<decltype(ti1)::Type,Ti1Val::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,26),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsUsbintr{ ///<USB Interrupt Enable Register
using Addr = Register::Address<0x40034148,0x00000000,0x00000000,unsigned>;
///USB interrupt Enable
enum class UeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,UeVal> ue{};
namespace UeValC{
constexpr Register::FieldValue<decltype(ue)::Type,UeVal::v0> v0{};
constexpr Register::FieldValue<decltype(ue)::Type,UeVal::v1> v1{};
}
///USB Error interrupt Enable
enum class UeeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,UeeVal> uee{};
namespace UeeValC{
constexpr Register::FieldValue<decltype(uee)::Type,UeeVal::v0> v0{};
constexpr Register::FieldValue<decltype(uee)::Type,UeeVal::v1> v1{};
}
///Port Change detect Enable
enum class PceVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,PceVal> pce{};
namespace PceValC{
constexpr Register::FieldValue<decltype(pce)::Type,PceVal::v0> v0{};
constexpr Register::FieldValue<decltype(pce)::Type,PceVal::v1> v1{};
}
///Frame list Rollover Enable
enum class FreVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,FreVal> fre{};
namespace FreValC{
constexpr Register::FieldValue<decltype(fre)::Type,FreVal::v0> v0{};
constexpr Register::FieldValue<decltype(fre)::Type,FreVal::v1> v1{};
}
///System Error Enable
enum class SeeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,SeeVal> see{};
namespace SeeValC{
constexpr Register::FieldValue<decltype(see)::Type,SeeVal::v0> v0{};
constexpr Register::FieldValue<decltype(see)::Type,SeeVal::v1> v1{};
}
///Interrupt on Async advance Enable
enum class AaeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,AaeVal> aae{};
namespace AaeValC{
constexpr Register::FieldValue<decltype(aae)::Type,AaeVal::v0> v0{};
constexpr Register::FieldValue<decltype(aae)::Type,AaeVal::v1> v1{};
}
///USB-Reset Enable
enum class UreVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,UreVal> ure{};
namespace UreValC{
constexpr Register::FieldValue<decltype(ure)::Type,UreVal::v0> v0{};
constexpr Register::FieldValue<decltype(ure)::Type,UreVal::v1> v1{};
}
///SOF-Received Enable
enum class SreVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,SreVal> sre{};
namespace SreValC{
constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{};
constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{};
}
///Sleep (DC suspend) Enable
enum class SleVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SleVal> sle{};
namespace SleValC{
constexpr Register::FieldValue<decltype(sle)::Type,SleVal::v0> v0{};
constexpr Register::FieldValue<decltype(sle)::Type,SleVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///ULPI Enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> ulpie{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///NAK Interrupt Enable
enum class NakeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,NakeVal> nake{};
namespace NakeValC{
constexpr Register::FieldValue<decltype(nake)::Type,NakeVal::v0> v0{};
constexpr Register::FieldValue<decltype(nake)::Type,NakeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///USB host Asynchronous Interrupt Enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> uaie{};
///USB host Periodic Interrupt Enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> upie{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///General purpose Timer 0 Interrupt Enable
enum class Tie0Val {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,Tie0Val> tie0{};
namespace Tie0ValC{
constexpr Register::FieldValue<decltype(tie0)::Type,Tie0Val::v0> v0{};
constexpr Register::FieldValue<decltype(tie0)::Type,Tie0Val::v1> v1{};
}
///General purpose Timer 1 Interrupt Enable
enum class Tie1Val {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,Tie1Val> tie1{};
namespace Tie1ValC{
constexpr Register::FieldValue<decltype(tie1)::Type,Tie1Val::v0> v0{};
constexpr Register::FieldValue<decltype(tie1)::Type,Tie1Val::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,26),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsFrindex{ ///<Frame Index Register
using Addr = Register::Address<0x4003414c,0x00000000,0x00000000,unsigned>;
///Frame Index
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,0),Register::ReadWriteAccess,unsigned> frindex{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reerved{};
}
namespace UsbhsPeriodiclistbase{ ///<Periodic Frame List Base Address Register
using Addr = Register::Address<0x40034154,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Base address
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,12),Register::ReadWriteAccess,unsigned> perbase{};
}
namespace UsbhsDeviceaddr{ ///<Device Address Register
using Addr = Register::Address<0x40034154,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Device Address Advance
enum class UsbadraVal {
v0=0x00000000, ///<Writes to USBADR are instantaneous.
v1=0x00000001, ///<When this bit is written to a 1 at the same time or before USBADR is written, the write to the USBADR field is staged and held in a hidden register. After an IN occurs on endpoint 0 and is ACKed, USBADR is loaded from the holding register.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,UsbadraVal> usbadra{};
namespace UsbadraValC{
constexpr Register::FieldValue<decltype(usbadra)::Type,UsbadraVal::v0> v0{};
constexpr Register::FieldValue<decltype(usbadra)::Type,UsbadraVal::v1> v1{};
}
///Device Address
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,25),Register::ReadWriteAccess,unsigned> usbadr{};
}
namespace UsbhsAsynclistaddr{ ///<Current Asynchronous List Address Register
using Addr = Register::Address<0x40034158,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Link pointer low (LPL)
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,5),Register::ReadWriteAccess,unsigned> asybase{};
}
namespace UsbhsEplistaddr{ ///<Endpoint List Address Register
using Addr = Register::Address<0x40034158,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Endpoint list address
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,11),Register::ReadWriteAccess,unsigned> epbase{};
}
namespace UsbhsTtctrl{ ///<Host TT Asynchronous Buffer Control
using Addr = Register::Address<0x4003415c,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TT Hub Address
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ttha{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reerved{};
}
namespace UsbhsBurstsize{ ///<Master Interface Data Burst Size Register
using Addr = Register::Address<0x40034160,0x00000000,0x00000000,unsigned>;
///Programable RX Burst length
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> rxpburst{};
///Programable TX Burst length
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> txpburst{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsTxfilltuning{ ///<Transmit FIFO Tuning Control Register
using Addr = Register::Address<0x40034164,0x00000000,0x00000000,unsigned>;
///Scheduler Overhead
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,0),Register::ReadWriteAccess,unsigned> txschoh{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Scheduler Health counter
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,8),Register::ReadWriteAccess,unsigned> txschhealth{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///FIFO burst Threshold
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,16),Register::ReadWriteAccess,unsigned> txfifothres{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,22),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsUlpiViewport{ ///<ULPI Register Access
using Addr = Register::Address<0x40034170,0x00000000,0x00000000,unsigned>;
///ULPI Data Write
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> ulpiDatwr{};
///ULPI Data Read
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ulpiDatrd{};
///ULPI data Address
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> ulpiAddr{};
///ULPI Port number
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ulpiPort{};
///ULPI Sync State
enum class UlpissVal {
v0=0x00000000, ///<Any other state (that is, carkit, serial, low power)
v1=0x00000001, ///<Normal sync state
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,UlpissVal> ulpiSs{};
namespace UlpissValC{
constexpr Register::FieldValue<decltype(ulpiSs)::Type,UlpissVal::v0> v0{};
constexpr Register::FieldValue<decltype(ulpiSs)::Type,UlpissVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///ULPI Read/Write
enum class UlpirwVal {
v0=0x00000000, ///<Read
v1=0x00000001, ///<Write
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,UlpirwVal> ulpiRw{};
namespace UlpirwValC{
constexpr Register::FieldValue<decltype(ulpiRw)::Type,UlpirwVal::v0> v0{};
constexpr Register::FieldValue<decltype(ulpiRw)::Type,UlpirwVal::v1> v1{};
}
///ULPI Run
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ulpiRun{};
///ULPI Wake-Up
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> ulpiWu{};
}
namespace UsbhsEndptnak{ ///<Endpoint NAK Register
using Addr = Register::Address<0x40034178,0x00000000,0x00000000,unsigned>;
///RX Endpoint NAK
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> eprn{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX Endpoint NAK
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> eptn{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEndptnaken{ ///<Endpoint NAK Enable Register
using Addr = Register::Address<0x4003417c,0x00000000,0x00000000,unsigned>;
///RX Endpoint NAK
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> eprne{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX Endpoint NAK
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> eptne{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsConfigflag{ ///<Configure Flag Register
using Addr = Register::Address<0x40034180,0x00000000,0x00000000,unsigned>;
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsPortsc1{ ///<Port Status and Control Registers
using Addr = Register::Address<0x40034184,0x00000000,0x00000000,unsigned>;
///Current Connect Status
enum class CcsVal {
v0=0x00000000, ///<No device present (host mode) or attached (device mode)
v1=0x00000001, ///<Device is present (host mode) or attached (device mode)
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,CcsVal> ccs{};
namespace CcsValC{
constexpr Register::FieldValue<decltype(ccs)::Type,CcsVal::v0> v0{};
constexpr Register::FieldValue<decltype(ccs)::Type,CcsVal::v1> v1{};
}
///Connect Change Status
enum class CscVal {
v0=0x00000000, ///<No change
v1=0x00000001, ///<Connect status has changed
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,CscVal> csc{};
namespace CscValC{
constexpr Register::FieldValue<decltype(csc)::Type,CscVal::v0> v0{};
constexpr Register::FieldValue<decltype(csc)::Type,CscVal::v1> v1{};
}
///Port Enabled/disabled
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> pe{};
///Port Enable/disable Change
enum class PecVal {
v0=0x00000000, ///<No change
v1=0x00000001, ///<Port disabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,PecVal> pec{};
namespace PecValC{
constexpr Register::FieldValue<decltype(pec)::Type,PecVal::v0> v0{};
constexpr Register::FieldValue<decltype(pec)::Type,PecVal::v1> v1{};
}
///Over-current active
enum class OcaVal {
v0=0x00000000, ///<Port not in over-current condition
v1=0x00000001, ///<Port currently in over-current condition
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,OcaVal> oca{};
namespace OcaValC{
constexpr Register::FieldValue<decltype(oca)::Type,OcaVal::v0> v0{};
constexpr Register::FieldValue<decltype(oca)::Type,OcaVal::v1> v1{};
}
///Over-Current Change
enum class OccVal {
v0=0x00000000, ///<No over-current
v1=0x00000001, ///<Over-current detect
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,OccVal> occ{};
namespace OccValC{
constexpr Register::FieldValue<decltype(occ)::Type,OccVal::v0> v0{};
constexpr Register::FieldValue<decltype(occ)::Type,OccVal::v1> v1{};
}
///Force Port Resume
enum class FprVal {
v0=0x00000000, ///<No resume (K-state) detected/driven on port
v1=0x00000001, ///<Resume detected/driven on port
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,FprVal> fpr{};
namespace FprValC{
constexpr Register::FieldValue<decltype(fpr)::Type,FprVal::v0> v0{};
constexpr Register::FieldValue<decltype(fpr)::Type,FprVal::v1> v1{};
}
///Suspend
enum class SuspVal {
v0=0x00000000, ///<Port not in suspend state
v1=0x00000001, ///<Port in suspend state
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,SuspVal> susp{};
namespace SuspValC{
constexpr Register::FieldValue<decltype(susp)::Type,SuspVal::v0> v0{};
constexpr Register::FieldValue<decltype(susp)::Type,SuspVal::v1> v1{};
}
///Port Reset
enum class PrVal {
v0=0x00000000, ///<Port is not in reset
v1=0x00000001, ///<Port is in reset
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,PrVal> pr{};
namespace PrValC{
constexpr Register::FieldValue<decltype(pr)::Type,PrVal::v0> v0{};
constexpr Register::FieldValue<decltype(pr)::Type,PrVal::v1> v1{};
}
///High Speed Port.
enum class HspVal {
v0=0x00000000, ///<FS or LS
v1=0x00000001, ///<HS
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,HspVal> hsp{};
namespace HspValC{
constexpr Register::FieldValue<decltype(hsp)::Type,HspVal::v0> v0{};
constexpr Register::FieldValue<decltype(hsp)::Type,HspVal::v1> v1{};
}
///Line Status
enum class LsVal {
v00=0x00000000, ///<SE0
v01=0x00000001, ///<J-state
v10=0x00000002, ///<K-state
v11=0x00000003, ///<Undefined
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,LsVal> ls{};
namespace LsValC{
constexpr Register::FieldValue<decltype(ls)::Type,LsVal::v00> v00{};
constexpr Register::FieldValue<decltype(ls)::Type,LsVal::v01> v01{};
constexpr Register::FieldValue<decltype(ls)::Type,LsVal::v10> v10{};
constexpr Register::FieldValue<decltype(ls)::Type,LsVal::v11> v11{};
}
///Port Power
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pp{};
///Port Owner
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> po{};
///Port Indicator Control
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> pic{};
///Port Test Control
enum class PtcVal {
v0000=0x00000000, ///<Not enabled
v0001=0x00000001, ///<J_STATE
v0010=0x00000002, ///<K_STATE
v0011=0x00000003, ///<SEQ_NAK
v0100=0x00000004, ///<Packet
v0101=0x00000005, ///<FORCE_ENABLE_HS
v0110=0x00000006, ///<FORCE_ENABLE_FS
v0111=0x00000007, ///<FORCE_ENABLE_LS
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,PtcVal> ptc{};
namespace PtcValC{
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0000> v0000{};
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0001> v0001{};
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0010> v0010{};
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0011> v0011{};
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0100> v0100{};
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0101> v0101{};
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0110> v0110{};
constexpr Register::FieldValue<decltype(ptc)::Type,PtcVal::v0111> v0111{};
}
///Wake on Connect enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> wkcn{};
///Wake on Disconnect enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> wkds{};
///Wake on Over-Current enable
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> wkoc{};
///PHY low power suspend
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> phcd{};
///Port force Full-Speed Connect
enum class PfscVal {
v0=0x00000000, ///<Allow the port to identify itself as high speed
v1=0x00000001, ///<Force the port to only connect at full speed
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,PfscVal> pfsc{};
namespace PfscValC{
constexpr Register::FieldValue<decltype(pfsc)::Type,PfscVal::v0> v0{};
constexpr Register::FieldValue<decltype(pfsc)::Type,PfscVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Port Speed
enum class PspdVal {
v00=0x00000000, ///<Full speed
v01=0x00000001, ///<Low speed
v10=0x00000002, ///<High speed
v11=0x00000003, ///<Undefined
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,26),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,PspdVal> pspd{};
namespace PspdValC{
constexpr Register::FieldValue<decltype(pspd)::Type,PspdVal::v00> v00{};
constexpr Register::FieldValue<decltype(pspd)::Type,PspdVal::v01> v01{};
constexpr Register::FieldValue<decltype(pspd)::Type,PspdVal::v10> v10{};
constexpr Register::FieldValue<decltype(pspd)::Type,PspdVal::v11> v11{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Port Transceiver Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> pts{};
}
namespace UsbhsOtgsc{ ///<On-the-Go Status and Control Register
using Addr = Register::Address<0x400341a4,0x00000000,0x00000000,unsigned>;
///VBUS Discharge
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> vd{};
///VBUS Charge
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> vc{};
///Hardware Assist Auto-Reset
enum class HaarVal {
v0=0x00000000, ///<Disabled.
v1=0x00000001, ///<Enable automatic reset after connect on host port.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,HaarVal> haar{};
namespace HaarValC{
constexpr Register::FieldValue<decltype(haar)::Type,HaarVal::v0> v0{};
constexpr Register::FieldValue<decltype(haar)::Type,HaarVal::v1> v1{};
}
///OTG Termination
enum class OtVal {
v0=0x00000000, ///<Disable pull-down on DM
v1=0x00000001, ///<Enable pull-down on DM
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,OtVal> ot{};
namespace OtValC{
constexpr Register::FieldValue<decltype(ot)::Type,OtVal::v0> v0{};
constexpr Register::FieldValue<decltype(ot)::Type,OtVal::v1> v1{};
}
///Data Pulsing
enum class DpVal {
v0=0x00000000, ///<The pull-up on DP is not asserted
v1=0x00000001, ///<The pull-up on DP is asserted for data pulsing during SRP
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,DpVal> dp{};
namespace DpValC{
constexpr Register::FieldValue<decltype(dp)::Type,DpVal::v0> v0{};
constexpr Register::FieldValue<decltype(dp)::Type,DpVal::v1> v1{};
}
///ID Pull-Up
enum class IdpuVal {
v0=0x00000000, ///<Disable pull-up. ID input not sampled.
v1=0x00000001, ///<Enable pull-up
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,IdpuVal> idpu{};
namespace IdpuValC{
constexpr Register::FieldValue<decltype(idpu)::Type,IdpuVal::v0> v0{};
constexpr Register::FieldValue<decltype(idpu)::Type,IdpuVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Hardware Assist B-Disconnect to A-connect
enum class HabaVal {
v0=0x00000000, ///<Disabled.
v1=0x00000001, ///<Enable automatic B-disconnect to A-connect sequence.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,HabaVal> haba{};
namespace HabaValC{
constexpr Register::FieldValue<decltype(haba)::Type,HabaVal::v0> v0{};
constexpr Register::FieldValue<decltype(haba)::Type,HabaVal::v1> v1{};
}
///USB ID
enum class IdVal {
v0=0x00000000, ///<A device
v1=0x00000001, ///<B device
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,IdVal> id{};
namespace IdValC{
constexpr Register::FieldValue<decltype(id)::Type,IdVal::v0> v0{};
constexpr Register::FieldValue<decltype(id)::Type,IdVal::v1> v1{};
}
///A VBus Valid
enum class AvvVal {
v0=0x00000000, ///<VBus is below A VBus valid threshold
v1=0x00000001, ///<VBus is above A VBus valid threshold
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,AvvVal> avv{};
namespace AvvValC{
constexpr Register::FieldValue<decltype(avv)::Type,AvvVal::v0> v0{};
constexpr Register::FieldValue<decltype(avv)::Type,AvvVal::v1> v1{};
}
///A Session Valid
enum class AsvVal {
v0=0x00000000, ///<VBus is below A session valid threshold
v1=0x00000001, ///<VBus is above A session valid threshold
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,AsvVal> asv{};
namespace AsvValC{
constexpr Register::FieldValue<decltype(asv)::Type,AsvVal::v0> v0{};
constexpr Register::FieldValue<decltype(asv)::Type,AsvVal::v1> v1{};
}
///B Session Valid
enum class BsvVal {
v0=0x00000000, ///<VBus is below B session valid threshold
v1=0x00000001, ///<VBus is above B session valid threshold
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,BsvVal> bsv{};
namespace BsvValC{
constexpr Register::FieldValue<decltype(bsv)::Type,BsvVal::v0> v0{};
constexpr Register::FieldValue<decltype(bsv)::Type,BsvVal::v1> v1{};
}
///B Session End
enum class BseVal {
v0=0x00000000, ///<VBus is above B session end threshold
v1=0x00000001, ///<VBus is below B session end threshold
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,BseVal> bse{};
namespace BseValC{
constexpr Register::FieldValue<decltype(bse)::Type,BseVal::v0> v0{};
constexpr Register::FieldValue<decltype(bse)::Type,BseVal::v1> v1{};
}
///1 Milli-Second timer Toggle
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mst{};
///Data bus Pulsing Status
enum class DpsVal {
v0=0x00000000, ///<No pulsing on port
v1=0x00000001, ///<Pulsing detected on port
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,DpsVal> dps{};
namespace DpsValC{
constexpr Register::FieldValue<decltype(dps)::Type,DpsVal::v0> v0{};
constexpr Register::FieldValue<decltype(dps)::Type,DpsVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///USB ID Interrupt Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> idis{};
///A VBUS Valid Interrupt Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> avvis{};
///A Session Valid Interrupt Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> asvis{};
///B Session Valid Interrupt Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> bsvis{};
///B Session End Interrupt Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> bseis{};
///1 Milli-Second timer interrupt Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> mss{};
///Data Pulse interrupt Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> dpis{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///USB ID Interrupt Enable
enum class IdieVal {
v0=0x00000000, ///<Disable
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IdieVal> idie{};
namespace IdieValC{
constexpr Register::FieldValue<decltype(idie)::Type,IdieVal::v0> v0{};
constexpr Register::FieldValue<decltype(idie)::Type,IdieVal::v1> v1{};
}
///A VBUS Valid Interrupt Enable
enum class AvvieVal {
v0=0x00000000, ///<Disable
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,AvvieVal> avvie{};
namespace AvvieValC{
constexpr Register::FieldValue<decltype(avvie)::Type,AvvieVal::v0> v0{};
constexpr Register::FieldValue<decltype(avvie)::Type,AvvieVal::v1> v1{};
}
///A Session Valid Interrupt Enable
enum class AsvieVal {
v0=0x00000000, ///<Disable
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,AsvieVal> asvie{};
namespace AsvieValC{
constexpr Register::FieldValue<decltype(asvie)::Type,AsvieVal::v0> v0{};
constexpr Register::FieldValue<decltype(asvie)::Type,AsvieVal::v1> v1{};
}
///B Session Valid Interrupt Enable
enum class BsvieVal {
v0=0x00000000, ///<Disable
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,BsvieVal> bsvie{};
namespace BsvieValC{
constexpr Register::FieldValue<decltype(bsvie)::Type,BsvieVal::v0> v0{};
constexpr Register::FieldValue<decltype(bsvie)::Type,BsvieVal::v1> v1{};
}
///B Session End Interrupt Enable
enum class BseieVal {
v0=0x00000000, ///<Disable
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,BseieVal> bseie{};
namespace BseieValC{
constexpr Register::FieldValue<decltype(bseie)::Type,BseieVal::v0> v0{};
constexpr Register::FieldValue<decltype(bseie)::Type,BseieVal::v1> v1{};
}
///1 Milli-Second timer interrupt Enable
enum class MseVal {
v0=0x00000000, ///<Disable
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,MseVal> mse{};
namespace MseValC{
constexpr Register::FieldValue<decltype(mse)::Type,MseVal::v0> v0{};
constexpr Register::FieldValue<decltype(mse)::Type,MseVal::v1> v1{};
}
///Data Pulse Interrupt Enable
enum class DpieVal {
v0=0x00000000, ///<Disable
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,DpieVal> dpie{};
namespace DpieValC{
constexpr Register::FieldValue<decltype(dpie)::Type,DpieVal::v0> v0{};
constexpr Register::FieldValue<decltype(dpie)::Type,DpieVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsUsbmode{ ///<USB Mode Register
using Addr = Register::Address<0x400341a8,0x00000000,0x00000000,unsigned>;
///Controller Mode
enum class CmVal {
v00=0x00000000, ///<Idle (default for the USBHS module)
v01=0x00000001, ///<Reserved
v10=0x00000002, ///<Device controller
v11=0x00000003, ///<Host controller
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,CmVal> cm{};
namespace CmValC{
constexpr Register::FieldValue<decltype(cm)::Type,CmVal::v00> v00{};
constexpr Register::FieldValue<decltype(cm)::Type,CmVal::v01> v01{};
constexpr Register::FieldValue<decltype(cm)::Type,CmVal::v10> v10{};
constexpr Register::FieldValue<decltype(cm)::Type,CmVal::v11> v11{};
}
///Endian Select
enum class EsVal {
v0=0x00000000, ///<Little endian. First byte referenced in least significant byte of 32-bit word.
v1=0x00000001, ///<Big endian. First byte referenced in most significant byte of 32-bit word.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,EsVal> es{};
namespace EsValC{
constexpr Register::FieldValue<decltype(es)::Type,EsVal::v0> v0{};
constexpr Register::FieldValue<decltype(es)::Type,EsVal::v1> v1{};
}
///Setup Lock-Out Mode
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> slom{};
///Stream DISable
enum class SdisVal {
v0=0x00000000, ///<Inactive
v1=0x00000001, ///<Active
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,SdisVal> sdis{};
namespace SdisValC{
constexpr Register::FieldValue<decltype(sdis)::Type,SdisVal::v0> v0{};
constexpr Register::FieldValue<decltype(sdis)::Type,SdisVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Tx to Tx HS Delay
enum class TxhsdVal {
v000=0x00000000, ///<10
v001=0x00000001, ///<11
v010=0x00000002, ///<12
v011=0x00000003, ///<13
v100=0x00000004, ///<14
v101=0x00000005, ///<15
v110=0x00000006, ///<16
v111=0x00000007, ///<17
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,TxhsdVal> txhsd{};
namespace TxhsdValC{
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v000> v000{};
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v001> v001{};
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v010> v010{};
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v011> v011{};
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v100> v100{};
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v101> v101{};
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v110> v110{};
constexpr Register::FieldValue<decltype(txhsd)::Type,TxhsdVal::v111> v111{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,15),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpsetupsr{ ///<Endpoint Setup Status Register
using Addr = Register::Address<0x400341ac,0x00000000,0x00000000,unsigned>;
///Setup Endpoint Status
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> epsetupstat{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpprime{ ///<Endpoint Initialization Register
using Addr = Register::Address<0x400341b0,0x00000000,0x00000000,unsigned>;
///Prime Endpoint Receive Buffer
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> perb{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Prime Endpoint tTansmit Buffer
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> petb{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpflush{ ///<Endpoint Flush Register
using Addr = Register::Address<0x400341b4,0x00000000,0x00000000,unsigned>;
///Flush Endpoint Receive Buffer
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> ferb{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Flush Endpoint Transmit Buffer
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> fetb{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpsr{ ///<Endpoint Status Register
using Addr = Register::Address<0x400341b8,0x00000000,0x00000000,unsigned>;
///Endpoint Receive Buffer Ready
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> erbr{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Endpoint Transmit Buffer Ready
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> etbr{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpcomplete{ ///<Endpoint Complete Register
using Addr = Register::Address<0x400341bc,0x00000000,0x00000000,unsigned>;
///Endpoint Receive Complete Event
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> erce{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Endpoint Transmit Complete Event
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> etce{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpcr0{ ///<Endpoint Control Register 0
using Addr = Register::Address<0x400341c0,0x00000000,0x00000000,unsigned>;
///RX endpoint Stall
enum class RxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RxsVal> rxs{};
namespace RxsValC{
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///RX endpoint Type
enum class RxtVal {
v00=0x00000000, ///<Control
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,RxtVal> rxt{};
namespace RxtValC{
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v00> v00{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///RX endpoint Enable
enum class RxeVal {
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,RxeVal> rxe{};
namespace RxeValC{
constexpr Register::FieldValue<decltype(rxe)::Type,RxeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX Endpoint Stall
enum class TxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,TxsVal> txs{};
namespace TxsValC{
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX Endpoint Type
enum class TxtVal {
v00=0x00000000, ///<Control
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,TxtVal> txt{};
namespace TxtValC{
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v00> v00{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX Endpoint Enable
enum class TxeVal {
v1=0x00000001, ///<Enable
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,TxeVal> txe{};
namespace TxeValC{
constexpr Register::FieldValue<decltype(txe)::Type,TxeVal::v1> v1{};
}
///This register is not defined in the EHCI specification. Every device implements endpoint 0 as a control endpoint.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsUsbgenctrl{ ///<USB General Control Register
using Addr = Register::Address<0x40034200,0x00000000,0x00000000,unsigned>;
///Wakeup Interrupt Enable
enum class WuieVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,WuieVal> wuIe{};
namespace WuieValC{
constexpr Register::FieldValue<decltype(wuIe)::Type,WuieVal::v0> v0{};
constexpr Register::FieldValue<decltype(wuIe)::Type,WuieVal::v1> v1{};
}
///Wakeup on ULPI Interrupt Event
enum class WuulpienVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,WuulpienVal> wuUlpiEn{};
namespace WuulpienValC{
constexpr Register::FieldValue<decltype(wuUlpiEn)::Type,WuulpienVal::v0> v0{};
constexpr Register::FieldValue<decltype(wuUlpiEn)::Type,WuulpienVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,2),Register::ReadWriteAccess,unsigned> reserved{};
///Wakeup Interrupt Clear
enum class WuintclrVal {
v0=0x00000000, ///<Default, no action.
v1=0x00000001, ///<Clear the wake-up interrupt.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,WuintclrVal> wuIntClr{};
namespace WuintclrValC{
constexpr Register::FieldValue<decltype(wuIntClr)::Type,WuintclrVal::v0> v0{};
constexpr Register::FieldValue<decltype(wuIntClr)::Type,WuintclrVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsGptimer0ld{ ///<General Purpose Timer n Load Register
using Addr = Register::Address<0x40034080,0x00000000,0x00000000,unsigned>;
///no description available
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,0),Register::ReadWriteAccess,unsigned> gptld{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsGptimer1ld{ ///<General Purpose Timer n Load Register
using Addr = Register::Address<0x40034088,0x00000000,0x00000000,unsigned>;
///no description available
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,0),Register::ReadWriteAccess,unsigned> gptld{};
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsGptimer0ctl{ ///<General Purpose Timer n Control Register
using Addr = Register::Address<0x40034084,0x00000000,0x00000000,unsigned>;
///Timer Count
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> gptcnt{};
///Timer Mode
enum class ModeVal {
v0=0x00000000, ///<One shot
v1=0x00000001, ///<Repeat
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,ModeVal> mode{};
namespace ModeValC{
constexpr Register::FieldValue<decltype(mode)::Type,ModeVal::v0> v0{};
constexpr Register::FieldValue<decltype(mode)::Type,ModeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Timer Reset
enum class RstVal {
v0=0x00000000, ///<No action
v1=0x00000001, ///<Load counter value
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,RstVal> rst{};
namespace RstValC{
constexpr Register::FieldValue<decltype(rst)::Type,RstVal::v0> v0{};
constexpr Register::FieldValue<decltype(rst)::Type,RstVal::v1> v1{};
}
///Timer Run
enum class RunVal {
v0=0x00000000, ///<Timer stop
v1=0x00000001, ///<Timer run
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,RunVal> run{};
namespace RunValC{
constexpr Register::FieldValue<decltype(run)::Type,RunVal::v0> v0{};
constexpr Register::FieldValue<decltype(run)::Type,RunVal::v1> v1{};
}
}
namespace UsbhsGptimer1ctl{ ///<General Purpose Timer n Control Register
using Addr = Register::Address<0x4003408c,0x00000000,0x00000000,unsigned>;
///Timer Count
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> gptcnt{};
///Timer Mode
enum class ModeVal {
v0=0x00000000, ///<One shot
v1=0x00000001, ///<Repeat
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,ModeVal> mode{};
namespace ModeValC{
constexpr Register::FieldValue<decltype(mode)::Type,ModeVal::v0> v0{};
constexpr Register::FieldValue<decltype(mode)::Type,ModeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///Timer Reset
enum class RstVal {
v0=0x00000000, ///<No action
v1=0x00000001, ///<Load counter value
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,RstVal> rst{};
namespace RstValC{
constexpr Register::FieldValue<decltype(rst)::Type,RstVal::v0> v0{};
constexpr Register::FieldValue<decltype(rst)::Type,RstVal::v1> v1{};
}
///Timer Run
enum class RunVal {
v0=0x00000000, ///<Timer stop
v1=0x00000001, ///<Timer run
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,RunVal> run{};
namespace RunValC{
constexpr Register::FieldValue<decltype(run)::Type,RunVal::v0> v0{};
constexpr Register::FieldValue<decltype(run)::Type,RunVal::v1> v1{};
}
}
namespace UsbhsEpcr1{ ///<Endpoint Control Register n
using Addr = Register::Address<0x400341c4,0x00000000,0x00000000,unsigned>;
///RX endpoint Stall
enum class RxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RxsVal> rxs{};
namespace RxsValC{
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v1> v1{};
}
///RX endpoint Data sink
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rxd{};
///RX endpoint Type
enum class RxtVal {
v00=0x00000000, ///<Control
v01=0x00000001, ///<Isochronous
v10=0x00000002, ///<Bulk
v11=0x00000003, ///<Interrupt
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,RxtVal> rxt{};
namespace RxtValC{
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v00> v00{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v01> v01{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v10> v10{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v11> v11{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///RX data toggle Inhibit
enum class RxiVal {
v0=0x00000000, ///<PID sequencing enabled
v1=0x00000001, ///<PID sequencing disabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,RxiVal> rxi{};
namespace RxiValC{
constexpr Register::FieldValue<decltype(rxi)::Type,RxiVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxi)::Type,RxiVal::v1> v1{};
}
///RX data toggle Reset
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rxr{};
///RX endpoint Enable
enum class RxeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,RxeVal> rxe{};
namespace RxeValC{
constexpr Register::FieldValue<decltype(rxe)::Type,RxeVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxe)::Type,RxeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX endpoint Stall
enum class TxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,TxsVal> txs{};
namespace TxsValC{
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v1> v1{};
}
///TX endpoint Data source
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> txd{};
///TX endpoint Type
enum class TxtVal {
v00=0x00000000, ///<Control
v01=0x00000001, ///<Isochronous
v10=0x00000002, ///<Bulk
v11=0x00000003, ///<Interrupt
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,TxtVal> txt{};
namespace TxtValC{
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v00> v00{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v01> v01{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v10> v10{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v11> v11{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX data toggle Inhibit
enum class TxiVal {
v0=0x00000000, ///<PID sequencing enabled
v1=0x00000001, ///<PID sequencing disabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,TxiVal> txi{};
namespace TxiValC{
constexpr Register::FieldValue<decltype(txi)::Type,TxiVal::v0> v0{};
constexpr Register::FieldValue<decltype(txi)::Type,TxiVal::v1> v1{};
}
///TX data toggle Reset
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> txr{};
///TX endpoint Enable
enum class TxeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,TxeVal> txe{};
namespace TxeValC{
constexpr Register::FieldValue<decltype(txe)::Type,TxeVal::v0> v0{};
constexpr Register::FieldValue<decltype(txe)::Type,TxeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpcr2{ ///<Endpoint Control Register n
using Addr = Register::Address<0x400341c8,0x00000000,0x00000000,unsigned>;
///RX endpoint Stall
enum class RxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RxsVal> rxs{};
namespace RxsValC{
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v1> v1{};
}
///RX endpoint Data sink
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rxd{};
///RX endpoint Type
enum class RxtVal {
v00=0x00000000, ///<Control
v01=0x00000001, ///<Isochronous
v10=0x00000002, ///<Bulk
v11=0x00000003, ///<Interrupt
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,RxtVal> rxt{};
namespace RxtValC{
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v00> v00{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v01> v01{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v10> v10{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v11> v11{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///RX data toggle Inhibit
enum class RxiVal {
v0=0x00000000, ///<PID sequencing enabled
v1=0x00000001, ///<PID sequencing disabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,RxiVal> rxi{};
namespace RxiValC{
constexpr Register::FieldValue<decltype(rxi)::Type,RxiVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxi)::Type,RxiVal::v1> v1{};
}
///RX data toggle Reset
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rxr{};
///RX endpoint Enable
enum class RxeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,RxeVal> rxe{};
namespace RxeValC{
constexpr Register::FieldValue<decltype(rxe)::Type,RxeVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxe)::Type,RxeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX endpoint Stall
enum class TxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,TxsVal> txs{};
namespace TxsValC{
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v1> v1{};
}
///TX endpoint Data source
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> txd{};
///TX endpoint Type
enum class TxtVal {
v00=0x00000000, ///<Control
v01=0x00000001, ///<Isochronous
v10=0x00000002, ///<Bulk
v11=0x00000003, ///<Interrupt
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,TxtVal> txt{};
namespace TxtValC{
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v00> v00{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v01> v01{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v10> v10{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v11> v11{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX data toggle Inhibit
enum class TxiVal {
v0=0x00000000, ///<PID sequencing enabled
v1=0x00000001, ///<PID sequencing disabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,TxiVal> txi{};
namespace TxiValC{
constexpr Register::FieldValue<decltype(txi)::Type,TxiVal::v0> v0{};
constexpr Register::FieldValue<decltype(txi)::Type,TxiVal::v1> v1{};
}
///TX data toggle Reset
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> txr{};
///TX endpoint Enable
enum class TxeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,TxeVal> txe{};
namespace TxeValC{
constexpr Register::FieldValue<decltype(txe)::Type,TxeVal::v0> v0{};
constexpr Register::FieldValue<decltype(txe)::Type,TxeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
namespace UsbhsEpcr3{ ///<Endpoint Control Register n
using Addr = Register::Address<0x400341cc,0x00000000,0x00000000,unsigned>;
///RX endpoint Stall
enum class RxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RxsVal> rxs{};
namespace RxsValC{
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxs)::Type,RxsVal::v1> v1{};
}
///RX endpoint Data sink
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rxd{};
///RX endpoint Type
enum class RxtVal {
v00=0x00000000, ///<Control
v01=0x00000001, ///<Isochronous
v10=0x00000002, ///<Bulk
v11=0x00000003, ///<Interrupt
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,RxtVal> rxt{};
namespace RxtValC{
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v00> v00{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v01> v01{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v10> v10{};
constexpr Register::FieldValue<decltype(rxt)::Type,RxtVal::v11> v11{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///RX data toggle Inhibit
enum class RxiVal {
v0=0x00000000, ///<PID sequencing enabled
v1=0x00000001, ///<PID sequencing disabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,RxiVal> rxi{};
namespace RxiValC{
constexpr Register::FieldValue<decltype(rxi)::Type,RxiVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxi)::Type,RxiVal::v1> v1{};
}
///RX data toggle Reset
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rxr{};
///RX endpoint Enable
enum class RxeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,RxeVal> rxe{};
namespace RxeValC{
constexpr Register::FieldValue<decltype(rxe)::Type,RxeVal::v0> v0{};
constexpr Register::FieldValue<decltype(rxe)::Type,RxeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX endpoint Stall
enum class TxsVal {
v0=0x00000000, ///<Endpoint OK
v1=0x00000001, ///<Endpoint stalled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,TxsVal> txs{};
namespace TxsValC{
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v0> v0{};
constexpr Register::FieldValue<decltype(txs)::Type,TxsVal::v1> v1{};
}
///TX endpoint Data source
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> txd{};
///TX endpoint Type
enum class TxtVal {
v00=0x00000000, ///<Control
v01=0x00000001, ///<Isochronous
v10=0x00000002, ///<Bulk
v11=0x00000003, ///<Interrupt
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,TxtVal> txt{};
namespace TxtValC{
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v00> v00{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v01> v01{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v10> v10{};
constexpr Register::FieldValue<decltype(txt)::Type,TxtVal::v11> v11{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
///TX data toggle Inhibit
enum class TxiVal {
v0=0x00000000, ///<PID sequencing enabled
v1=0x00000001, ///<PID sequencing disabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,TxiVal> txi{};
namespace TxiValC{
constexpr Register::FieldValue<decltype(txi)::Type,TxiVal::v0> v0{};
constexpr Register::FieldValue<decltype(txi)::Type,TxiVal::v1> v1{};
}
///TX data toggle Reset
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> txr{};
///TX endpoint Enable
enum class TxeVal {
v0=0x00000000, ///<Disabled
v1=0x00000001, ///<Enabled
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,TxeVal> txe{};
namespace TxeValC{
constexpr Register::FieldValue<decltype(txe)::Type,TxeVal::v0> v0{};
constexpr Register::FieldValue<decltype(txe)::Type,TxeVal::v1> v1{};
}
///Reserved
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> reserved{};
}
}
|
#include "testdata/no_30ms_audio_data.h"
alignas(16) const short g_no_30ms_audio_data[] = {5713,5735,5735,5737,5701,5691,5656,5633,5611,5552,5475,5394,5293,5177,5064,4924,4737,4599,4420,4237,4048,3828,3623,3413,3183,2915,2622,2308,1980,1657,1261,901,549,205,-85,-383,-688,-969,-1246,-1530,-1850,-2206,-2561,-2915,-3224,-3482,-3713,-3921,-4107,-4287,-4470,-4660,-4850,-5057,-5239,-5395,-5540,-5619,-5697,-5724,-5697,-5675,-5633,-5590,-5579,-5530,-5486,-5442,-5426,-5391,-5348,-5276,-5197,-5124,-5039,-4925,-4808,-4677,-4581,-4479,-4343,-4218,-4087,-3970,-3858,-3729,-3570,-3384,-3206,-3020,-2839,-2636,-2453,-2287,-2185,-2154,-1926,-1562,-1223,-758,-473,-64,395,599,880,814,938,1172,1498,1928,2127,2422,2608,2841,2937,2886,2815,2985,3324,3757,4152,4481,4652,4917,4965,4766,4583,4328,4503,4815,5118,5408,5682,5956,6082,6055,5744,5426,5341,5427,5606,5882,6065,6226,6428,6477,6385,6009,5728,5552,5439,5339,5200,5008,4947,4835,4614,4330,3887,3521,3111,2460,1983,1297,650,279,-353,-720,-1044,-1518,-1668,-2117,-2496,-2743,-3266,-3607,-3790,-4149,-4075,-4042,-4096,-3981,-4138,-4226,-4214,-4503,-4455,-4577,-4642,-4346,-4351,-4270,-4263,-4522,-4521,-4673,-4814,-4731,-4950,-5011,-5004,-5288,-5341,-5566,-5833,-5783,-5929,-5847,-5765,-5828,-5644,-5613,-5615,-5428,-5291,-5014,-4554,-4277,-3964,-3854,-3829,-3612,-3603,-3438,-3137,-2831,-2164,-1438,-939,-330,-156,46,242,73,242,220,239,542,565,739,872,801,857,676,543,586,567,828,1142,1490,1985,2508,2982,3438,3699,3939,4069,4178,4420,4622,4917,5338,5801,6285,6658,6963,7213,7233,7328,7176,7038,7031,6860,6957,6767,6599,6523,6212,6147,6063,5860,6020,6015,6033,6184,5722,5607,5016,4337,4063,3229,3080,3006,2804,3035,2541,2136,1879,1012,401,-575,-1584,-1930,-2278,-2485,-2477,-2712,-2747,-2766,-3320,-3592,-4188,-4669,-4672,-4939,-4789,-4426,-4203,-3674,-3563,-3656,-3759,-4067,-4257,-4522,-4970,-5204,-5237,-5139,-4907,-4911,-4917,-4921,-5007,-5230,-5654,-6122,-6464,-6733,-6948,-7067,-6972,-6800,-6520,-6132,-5830,-5382,-5091,-4797,-4546,-4472,-4362,-4350,-4235,-3851,-3454,-3144,-2735,-2341,-1845,-1262,-958,-549,-166,66,382,366,352,341,85,-13,-176,-303,-235,-341,-309,-227,-249,-50,143,384,874,1149,1552,2155,2767,3499,3994,4460,4920,5288,5569,5704,5881,6094,6461,6653,6803,7115,7311,7521,7612,7443,7380,7124,6742,6495,5964,5656,5415,5167,5656,5813,6027,6401,6351,6787,7019,6581,6512,5965,5308,5140,4336,4147,3899,3398,3360,2830,2624,1968,1026,395,-699,-1424,-2327,-3006,-3192,-3435,-3337,-3686,-3513,-3350,-3502,-3261,-3878,-4005,-4063,-4187,-3767,-3598,-3384,-3300,-3094,-2857,-3023,-3274,-3851,-4352,-4523,-4943,-5477,-5612,-5682,-5733,-5714,-5965,-6110,-5950,-6158,-6548,-6897,-7165,-7281,-7352,-7258,-7185,-6659,-5946,-5470,};
const unsigned int g_no_30ms_audio_data_size = 480;
|
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <winnt.h>
#include <minwindef.h>
#include <TlHelp32.h>
#include "../../include/asm/asm.h"
namespace asmkraken::assembly {
std::unique_ptr<uint8_t[]> PatchAsm(void* pDest, const void* pSrc, size_t size) {
auto* pOriginalBytes = new uint8_t[size];
DWORD oldProtection;
if (VirtualProtect(pDest, size, PAGE_EXECUTE_READWRITE, &oldProtection) == FALSE) {
return nullptr;
}
memcpy(pOriginalBytes, pDest, size);
memcpy(pDest, pSrc, size);
DWORD oldProtection2;
VirtualProtect(pDest, size, oldProtection, &oldProtection2);
return std::unique_ptr<uint8_t[]>(pOriginalBytes);
}
std::unique_ptr<uint8_t[]> Nop(void* pDest, size_t size) {
auto* nopArray = new uint8_t[size];
memset(nopArray, 0x90, size);
auto originalBytes = PatchAsm(pDest, nopArray, size);
delete[] nopArray;
return originalBytes;
}
void WriteRelayFunction(void* pDest, intptr_t hookTargetAddr, intptr_t hookFuncAddr, uint8_t* additionalInstructions, size_t additionalInstructionsSize) {
auto writeAddr = (intptr_t) pDest;
memcpy((void*) writeAddr, RelayFunctionPrologue, RelayFunctionPrologueSize);
writeAddr += RelayFunctionPrologueSize;
memcpy((void*) writeAddr, RelayFunctionTemplate, RelayFunctionContentSize);
*(intptr_t*) (writeAddr + RelayFunctionTargetAddrOffset) = hookFuncAddr;
writeAddr += RelayFunctionContentSize;
memcpy((void*) writeAddr, RelayFunctionEpilogue, RelayFunctionEpilogueSize);
writeAddr += RelayFunctionEpilogueSize;
if (additionalInstructions != nullptr) {
memcpy((void*) writeAddr, additionalInstructions, additionalInstructionsSize);
writeAddr += (intptr_t) additionalInstructionsSize;
}
memcpy((void*) writeAddr, JmpTemplate, JmpTemplateSize);
auto offsetToRelayFunc = (int32_t) abs(writeAddr - hookTargetAddr);
if (hookTargetAddr < writeAddr) {
offsetToRelayFunc = -offsetToRelayFunc;
}
*(int32_t*) (writeAddr + 1) = offsetToRelayFunc;
}
void SuspendOtherThreads(bool suspend) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hSnapshot != INVALID_HANDLE_VALUE) {
THREADENTRY32 te;
te.dwSize = sizeof(THREADENTRY32);
if (Thread32First(hSnapshot, &te)) {
do {
if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(DWORD))
&& te.th32OwnerProcessID == GetCurrentProcessId()
&& te.th32ThreadID != GetCurrentThreadId()) {
HANDLE thread = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
if (thread != nullptr) {
if (suspend) {
SuspendThread(thread);
} else {
ResumeThread(thread);
}
CloseHandle(thread);
}
}
} while (Thread32Next(hSnapshot, &te));
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "config.hpp"
#include "gates.hpp"
#include "simulatorinterface.hpp"
#include "util/openmp.hpp"
#include "wavefunction.hpp"
#include <map>
#include <numeric>
namespace Microsoft
{
namespace Quantum
{
namespace SIMULATOR
{
template <class WFN>
class Simulator : public Microsoft::Quantum::Simulator::SimulatorInterface
{
public:
using WaveFunctionType = WFN;
Simulator(unsigned maxlocal = 0u)
: psi()
{
}
std::size_t random(std::vector<double> const& d)
{
recursive_lock_type l(getmutex());
std::discrete_distribution<std::size_t> dist(d.begin(), d.end());
return dist(psi.rng());
}
std::size_t random(std::size_t n, double* d)
{
std::discrete_distribution<std::size_t> dist(d, d + n);
recursive_lock_type l(getmutex());
return dist(psi.rng());
}
double JointEnsembleProbability(std::vector<Gates::Basis> bs, std::vector<logical_qubit_id> qs)
{
removeIdentities(bs, qs);
if (bs.empty())
{
return 0.0;
}
recursive_lock_type l(getmutex());
changebasis(bs, qs, true);
double p = psi.jointprobability(qs);
changebasis(bs, qs, false);
return p;
}
bool InjectState(const std::vector<logical_qubit_id>& qubits, const std::vector<ComplexType>& amplitudes)
{
recursive_lock_type l(getmutex());
return psi.inject_state(qubits, amplitudes);
}
bool isclassical(logical_qubit_id q)
{
recursive_lock_type l(getmutex());
return psi.isclassical(q);
}
// allocate and release
logical_qubit_id allocate()
{
recursive_lock_type l(getmutex());
return psi.allocate_qubit();
}
std::vector<logical_qubit_id> allocate(unsigned n)
{
std::vector<logical_qubit_id> qubits;
qubits.reserve(n);
recursive_lock_type l(getmutex());
for (unsigned i = 0; i < n; ++i)
{
qubits.push_back(psi.allocate_qubit());
}
return qubits;
}
void allocateQubit(logical_qubit_id q)
{
recursive_lock_type l(getmutex());
psi.allocate_qubit(q);
}
void allocateQubit(std::vector<logical_qubit_id> const& qubits)
{
recursive_lock_type l(getmutex());
for (auto q : qubits)
psi.allocate_qubit(q);
}
bool release(logical_qubit_id q)
{
recursive_lock_type l(getmutex());
flush();
bool allok = isclassical(q);
if (allok)
allok = (psi.getvalue(q) == false);
else
M(q);
psi.release(q);
return allok;
}
bool release(std::vector<logical_qubit_id> const& qs)
{
recursive_lock_type l(getmutex());
bool allok = true;
for (auto q : qs)
allok = release(q) && allok;
return allok;
}
// single-qubit gates
#define GATE1IMPL(OP) \
void OP(logical_qubit_id q) \
{ \
recursive_lock_type l(getmutex()); \
psi.apply(Gates::OP(q)); \
}
#define GATE1CIMPL(OP) \
void C##OP(logical_qubit_id c, logical_qubit_id q) \
{ \
recursive_lock_type l(getmutex()); \
psi.apply_controlled(c, Gates::OP(q)); \
}
#define GATE1MCIMPL(OP) \
void C##OP(std::vector<logical_qubit_id> const& c, logical_qubit_id q) \
{ \
recursive_lock_type l(getmutex()); \
psi.apply_controlled(c, Gates::OP(q)); \
}
#define GATE1(OP) GATE1IMPL(OP) GATE1CIMPL(OP) GATE1MCIMPL(OP)
GATE1(X)
GATE1(Y)
GATE1(Z)
GATE1(H)
GATE1(HY)
GATE1(T)
GATE1(S)
GATE1(AdjHY)
GATE1(AdjT)
GATE1(AdjS)
#undef GATE1
#undef GATE1IMPL
#undef GATE1CIMPL
#undef GATE1MCIMPL
#define GATE1IMPL(OP) \
void OP(double phi, logical_qubit_id q) \
{ \
recursive_lock_type l(getmutex()); \
psi.apply(Gates::OP(phi, q)); \
}
#define GATE1CIMPL(OP) \
void C##OP(double phi, logical_qubit_id c, logical_qubit_id q) \
{ \
recursive_lock_type l(getmutex()); \
psi.apply_controlled(c, Gates::OP(phi, q)); \
}
#define GATE1MCIMPL(OP) \
void C##OP(double phi, std::vector<logical_qubit_id> const& c, logical_qubit_id q) \
{ \
recursive_lock_type l(getmutex()); \
psi.apply_controlled(c, Gates::OP(phi, q)); \
}
#define GATE1(OP) GATE1IMPL(OP) GATE1CIMPL(OP) GATE1MCIMPL(OP)
GATE1(Rx)
GATE1(Ry)
GATE1(Rz)
#undef GATE1
#undef GATE1IMPL
#undef GATE1CIMPL
#undef GATE1MCIMPL
// rotations
void R(Gates::Basis b, double phi, logical_qubit_id q)
{
recursive_lock_type l(getmutex());
psi.apply(Gates::R(b, phi, q));
}
// multi-controlled rotations
void CR(Gates::Basis b, double phi, std::vector<logical_qubit_id> const& c, logical_qubit_id q)
{
recursive_lock_type l(getmutex());
psi.apply_controlled(c, Gates::R(b, phi, q));
}
// Exponential of Pauli operators
void CExp(
std::vector<Gates::Basis> bs,
double phi,
std::vector<logical_qubit_id> const& cs,
std::vector<logical_qubit_id> qs)
{
if (bs.size() == 0) return;
logical_qubit_id somequbit = qs.front();
removeIdentities(bs, qs);
recursive_lock_type l(getmutex());
if (bs.size() == 0)
CR(Gates::PauliI, -2. * phi, cs, somequbit);
else if (bs.size() == 1)
CR(bs.front(), -2. * phi, cs, qs.front());
else
psi.apply_controlled_exp(bs, phi, cs, qs);
}
void Exp(std::vector<Gates::Basis> const& bs, double phi, std::vector<logical_qubit_id> const& qs)
{
recursive_lock_type l(getmutex());
CExp(bs, phi, std::vector<logical_qubit_id>(), qs);
}
// measurements
bool M(logical_qubit_id q)
{
recursive_lock_type l(getmutex());
return psi.measure(q);
}
std::vector<bool> MultiM(std::vector<logical_qubit_id> const& qs)
{
// ***TODO*** optimized implementation
recursive_lock_type l(getmutex());
std::vector<bool> res;
for (auto q : qs)
res.push_back(psi.measure(q));
return res;
}
bool Measure(std::vector<Gates::Basis> bs, std::vector<logical_qubit_id> qs)
{
recursive_lock_type l(getmutex());
removeIdentities(bs, qs);
// ***TODO*** optimized kernels
changebasis(bs, qs, true);
bool res = psi.jointmeasure(qs);
changebasis(bs, qs, false);
return res;
}
void seed(unsigned s)
{
recursive_lock_type l(getmutex());
psi.seed(s);
}
void reset()
{
recursive_lock_type l(getmutex());
psi.reset();
}
unsigned num_qubits() const
{
recursive_lock_type l(getmutex());
return psi.num_qubits();
}
void flush()
{
recursive_lock_type l(getmutex());
psi.flush();
}
ComplexType const* data() const
{
recursive_lock_type l(getmutex());
return psi.data().data();
}
void dump(bool (*callback)(size_t, double, double))
{
recursive_lock_type l(getmutex());
flush();
auto wfn = psi.data();
for (std::size_t i = 0; i < wfn.size(); i++)
{
if (!callback(i, wfn[i].real(), wfn[i].imag())) return;
}
}
void dump(TDumpToLocationCallback callback, TDumpLocation location) override
{
flush();
auto wfn = psi.data();
for (std::size_t i = 0; i < wfn.size(); i++)
{
if (!callback(i, wfn[i].real(), wfn[i].imag(), location)) return;
}
}
void dumpIds(void (*callback)(logical_qubit_id))
{
recursive_lock_type l(getmutex());
flush();
std::vector<logical_qubit_id> qubits = psi.get_qubit_ids();
for (logical_qubit_id q : qubits)
{
callback(q);
}
}
bool dumpQubits(std::vector<logical_qubit_id> const& qs, TDumpToLocationCallback callback, TDumpLocation location) override
{
assert(qs.size() <= num_qubits());
WavefunctionStorage wfn(1ull << qs.size());
if (subsytemwavefunction(qs, wfn, 1e-10))
{
for (std::size_t i = 0; i < wfn.size(); i++)
{
if (!callback(i, wfn[i].real(), wfn[i].imag(), location)) break;
}
return true;
}
else
{
return false;
}
}
bool dumpQubits(std::vector<logical_qubit_id> const& qs, bool (*callback)(size_t, double, double))
{
assert(qs.size() <= num_qubits());
WavefunctionStorage wfn(1ull << qs.size());
if (subsytemwavefunction(qs, wfn, 1e-10))
{
for (std::size_t i = 0; i < wfn.size(); i++)
{
if (!callback(i, wfn[i].real(), wfn[i].imag())) break;
}
return true;
}
else
{
return false;
}
}
// apply permutation of basis states to the wave function
void permuteBasis(
std::vector<logical_qubit_id> const& qs,
std::size_t table_size,
std::size_t const* permutation_table,
bool adjoint = false)
{
#ifndef NDEBUG
// check the permute function is bijective
auto test = std::vector<bool>(table_size, false);
for (size_t i = 0; i < table_size; ++i)
test.at(permutation_table[i]) = true;
assert(std::accumulate(test.begin(), test.end(), 0u) == table_size);
#endif
recursive_lock_type l(getmutex());
psi.permute_basis(qs, table_size, permutation_table, adjoint);
}
bool subsytemwavefunction(std::vector<logical_qubit_id> const& qs, WavefunctionStorage& qubitswfn, double tolerance)
{
recursive_lock_type l(getmutex());
flush();
return psi.subsytemwavefunction(qs, qubitswfn, tolerance);
}
private:
void changebasis(Gates::Basis b, logical_qubit_id q, bool back)
{
if (b == Gates::PauliX)
H(q);
else if (b == Gates::PauliY)
{
if (back)
AdjHY(q);
else
HY(q);
}
}
void changebasis(std::vector<Gates::Basis> const& bs, std::vector<logical_qubit_id> const& qs, bool back)
{
assert(bs.size() == qs.size());
for (unsigned i = 0; i < bs.size(); ++i)
changebasis(bs[i], qs[i], back);
}
inline static void removeIdentities(std::vector<Gates::Basis>& b, std::vector<logical_qubit_id>& qs)
{
unsigned i = 0;
while (i != b.size())
{
if (b[i] == Gates::PauliI)
{
b.erase(b.begin() + i);
qs.erase(qs.begin() + i);
}
else
++i;
}
}
WaveFunctionType psi;
};
using WavefunctionType = Wavefunction<ComplexType>;
using SimulatorType = Simulator<WavefunctionType>;
MICROSOFT_QUANTUM_DECL Microsoft::Quantum::Simulator::SimulatorInterface* createSimulator(unsigned = 0u);
} // namespace SIMULATOR
} // namespace Quantum
} // namespace Microsoft
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.