hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de6b5ce8e6a9acb4b25d367a376be02b46be8882 | 6,364 | cpp | C++ | PluginSDK/BasicRecon/Nlmeans.cpp | yangshadip/YAP-SELF | c715baa61c9504304629f28c05fd0f70b629f32a | [
"MIT"
] | null | null | null | PluginSDK/BasicRecon/Nlmeans.cpp | yangshadip/YAP-SELF | c715baa61c9504304629f28c05fd0f70b629f32a | [
"MIT"
] | null | null | null | PluginSDK/BasicRecon/Nlmeans.cpp | yangshadip/YAP-SELF | c715baa61c9504304629f28c05fd0f70b629f32a | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Nlmeans.h"
#include "Client/DataHelper.h"
#include "Implement/DataObject.h"
#include "Implement/LogUserImpl.h"
using namespace std;
using namespace Yap;
using namespace arma;
Nlmeans::Nlmeans(void):
ProcessorImpl(L"Nlmeans")
{
LOG_TRACE(L"Nlmeans constructor called.", L"BasicRecon");
AddInput(L"Input", 2, DataTypeFloat);
AddOutput(L"Output", 2, DataTypeFloat);
}
Yap::Nlmeans::Nlmeans(const Nlmeans & rhs) :
ProcessorImpl(rhs)
{
LOG_TRACE(L"Nlmeans constructor called.", L"BasicRecon");
}
Nlmeans::~Nlmeans()
{
LOG_TRACE(L"Nlmeans destructor called.", L"BasicRecon");
}
bool Yap::Nlmeans::Input(const wchar_t * name, IData * data)
{
assert((data != nullptr) && Yap::GetDataArray<float>(data) != nullptr);
assert(Inputs()->Find(name) != nullptr);
if (data->GetDataType() != DataTypeFloat)
return false;
DataHelper input_data(data);
unsigned int width = input_data.GetWidth();
unsigned int height = input_data.GetHeight();
float * fpI = GetDataArray<float>(data);
auto fpO = CreateData<float>(data);
// float Sigma = GetFloat(L"Sigma");
float Sigma = GetSigma(fpI, width, height);
unsigned int bloc, win;
float fFiltPar;
if (Sigma > 0.0f && Sigma <= 15.0f) {
win = 1;
bloc = 10;
fFiltPar = 0.4f;
}
else if (Sigma > 15.0f && Sigma <= 30.0f) {
win = 2;
bloc = 10;
fFiltPar = 0.4f;
}
else if (Sigma > 30.0f && Sigma <= 45.0f) {
win = 3;
bloc = 17;
fFiltPar = 0.35f;
}
else if (Sigma > 45.0f && Sigma <= 75.0f) {
win = 4;
bloc = 17;
fFiltPar = 0.35f;
}
else if (Sigma <= 100.0f) {
win = 5;
bloc = 17;
fFiltPar = 0.30f;
}
else
{
return false;
}
nlmeans_ipol(win, bloc, Sigma, fFiltPar, fpI, GetDataArray<float>(fpO.get()), width, height);
Feed(L"Output", fpO.get());
return true;
}
void Yap::Nlmeans::nlmeans_ipol(unsigned int iDWin, unsigned int iDBloc, float Sigma,
float fFiltPar, float * fpI, float * fpO, unsigned int iWidth, unsigned int iHeight)
{
unsigned int iwxh = iWidth * iHeight;
unsigned int ihwl = (2 * iDWin + 1);
unsigned int iwl = (2 * iDWin + 1) * (2 * iDWin + 1);
float Sigma2 = Sigma * Sigma;
float fH = fFiltPar * Sigma;
float fH2 = fH * fH;
fH2 *= (float)iwl;
unsigned int iLutLength = (unsigned int)rintf((float)LUTMAX * (float)LUTPRECISION);
float * fpLut = new float[iLutLength];//
wxFillExpLut(fpLut, iLutLength);
float * fpCount = new float[iwxh];//
for (unsigned int y = 0; y < iHeight; y++)
{
for (unsigned int x = 0; x < iWidth; x++)
{
int iDWin0 = MIN(iDWin, MIN(iWidth - 1 - x, MIN(iHeight - 1 - y, MIN(x, y))));
int imin = MAX(x - iDBloc, iDWin0);
int jmin = MAX(y - iDBloc, iDWin0);
int imax = MIN(x + iDBloc, iWidth - 1 - iDWin0);
int jmax = MIN(y + iDBloc, iHeight - 1 - iDWin0);
float fMaxWeight = 0.0f;
float fTotalWeight = 0.0f;
for (int j = jmin; j <= jmax; j++)
{
for (int i = imin; i <= imax; i++)
{
if (i != x || j != y)
{
float fDif = fiL2FloatDist(fpI, fpI, x, y, i, j, iDWin0, iWidth, iHeight);
fDif = MAX(fDif - 2.0f * (float)iwl * Sigma2, 0.0f);
fDif = fDif / fH2;
float fWeight = wxSLUT(fDif, fpLut);
if (fWeight > fMaxWeight)
{
fMaxWeight = fWeight;
}
fTotalWeight += fWeight;
for (int is = -iDWin0; is <= iDWin0; is++)
{
int aiindex = (iDWin + is) * ihwl + iDWin;
int ail = (j + is) * iWidth + i;
for (int ir = -iDWin0; ir <= iDWin0; ir++)
{
int iindex = aiindex + ir;
int il = ail + ir;
fpO[iindex] += fWeight * fpI[il];
}
}
}
for (int is = -iDWin0; is <= iDWin0; is++)
{
int aiindex = (iDWin + is) * ihwl + iDWin;
int ail = (y + is) * iWidth + x;
for (int ir = -iDWin0; ir <= iDWin0; ir++)
{
int iindex = aiindex + ir;
int il = ail + ir;
fpO[iindex] += fMaxWeight * fpI[il];
}
}
}
}
fTotalWeight += fMaxWeight;
if (fTotalWeight > fTiny)
{
for (int is = -iDWin0; is <= iDWin0; is++)
{
int aiindex = (iDWin + is) * ihwl + iDWin;
int ail = (y + is)*iWidth + x;
for (int ir = -iDWin0; ir <= iDWin0; ir++)
{
int iindex = aiindex + ir;
int il = ail + ir;
fpCount[il]++;
fpO[il] += fpO[iindex] / fTotalWeight;
}
}
}
}
}
for (int ii = 0; ii < iwxh; ii++)
{
if (fpCount[ii] > 0.0)
{
fpO[ii] /= fpCount[ii];
}
else
{
fpO[ii] = fpI[ii];
}
}
delete[] fpLut;
delete[] fpCount;
}
float Yap::Nlmeans::fiL2FloatDist(float * u0, float *u1, unsigned int i0,
unsigned int j0, unsigned int i1, unsigned int j1, int radius, unsigned int width0, unsigned int width1)
{
float dist = 0.0;
for (int s = -radius; s <= radius; s++) {
int l = (j0 + s)*width0 + (i0 - radius);
float *ptr0 = &u0[l];
l = (j1 + s)*width1 + (i1 - radius);
float *ptr1 = &u1[l];
for (int r = -radius; r <= radius; r++, ptr0++, ptr1++) {
float dif = (*ptr0 - *ptr1);
dist += (dif*dif);
}
}
return dist;
}
void Yap::Nlmeans::wxFillExpLut(float *lut, unsigned int size)
{
for (unsigned int i = 0; i < size; i++)
{
lut[i] = expf(-(float)i / LUTPRECISION);
}
}
float Yap::Nlmeans::wxSLUT(float dif, float *lut)
{
if (dif >= (float)LUTMAXM1) return 0.0;
unsigned int x = (unsigned int)floor((double)dif * (float)LUTPRECISION);
float y1 = lut[x];
float y2 = lut[x + 1];
return float(y1 + (y2 - y1)*(dif*LUTPRECISION - x));
}
float Yap::Nlmeans::GetSigma(float * input_img, unsigned int width, unsigned int height)
{
vector<float> input_data(width * height);
fmat input(height , width);
input.zeros();
memcpy(input_data.data(), input_img, width * height * sizeof(float));
for (unsigned int row = 0; row < height; ++row)
{
for (unsigned int col = 0; col < width; ++col)
{
input(row, col) = input_data[row * width + col];
}
}
fmat back_ground(20, 20);
back_ground.zeros();
back_ground(span(0, 9), span(0, 9)) = input(span(0, 9), span(0, 9));
back_ground(span(0, 9), span(10, 19)) = input(span(0, 9), span((width - 10), width - 1));
back_ground(span(10, 19), span(0, 9)) = input(span(height - 10, height - 1), span(0, 9));
back_ground(span(10, 19), span(10, 19)) = input(span(height - 10, height - 1), span(width - 10, width - 1));
auto sigma = stddev(vectorise(back_ground));
return sigma;
}
| 23.057971 | 109 | 0.588152 | [
"vector"
] |
de758f3407c68391cffd67dfa074b4bfa42c0f57 | 13,403 | cc | C++ | predict/src/tensor.cc | unseenme/mindspore | 4ba052f0cd9146ac0ccc4880a778706f1b2d0af8 | [
"Apache-2.0"
] | 7 | 2020-05-24T03:19:26.000Z | 2020-05-24T03:20:00.000Z | predict/src/tensor.cc | liyong126/mindspore | 930a1fb0a8fa9432025442c4f4732058bb7af592 | [
"Apache-2.0"
] | 7 | 2020-03-30T08:31:56.000Z | 2020-04-01T09:54:39.000Z | predict/src/tensor.cc | liyong126/mindspore | 930a1fb0a8fa9432025442c4f4732058bb7af592 | [
"Apache-2.0"
] | 1 | 2020-03-30T17:07:43.000Z | 2020-03-30T17:07:43.000Z | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "include/tensor.h"
#include "common/mslog.h"
#include "src/op_common.h"
#include "include/errorcode.h"
#include "securec/include/securec.h"
#include "common/common.h"
#include "src/runtime/allocator.h"
namespace mindspore {
namespace predict {
Tensor *Tensor::CopyFromTensorDef(const TensorDef &tensorDef) {
std::vector<int64_t> dims;
if (tensorDef.dims() == nullptr) {
MS_LOGD("tensorDef->dims is nullptr");
} else {
MS_ASSERT(tensorDef.dims()->data() != nullptr);
for (uint32_t j = 0; j < tensorDef.dims()->size(); j++) {
dims.push_back(tensorDef.dims()->data()[j]);
}
}
auto tensor =
std::unique_ptr<Tensor>(new (std::nothrow) Tensor(tensorDef.dataType(), dims, tensorDef.format(), nullptr));
if (tensor == nullptr) {
MS_LOGE("new Tensor failed");
return nullptr;
}
if (tensorDef.refCount() == MSConst_WEIGHT_REFCOUNT && tensorDef.data() != nullptr && tensorDef.data()->size() > 0) {
if (dims.size() < 1) {
tensor->SetDims({1});
}
auto ret = tensor->MallocData();
if (ret != RET_OK) {
MS_LOGE("malloc data fail,datasize %zu", tensor->GetDataSize());
return nullptr;
}
auto tensorData = tensorDef.data()->data();
ret = memcpy_sp(tensor->GetData(), tensor->GetDataSize(), tensorData, tensorDef.data()->size());
if (ret != RET_OK) {
MS_LOGE("copy data fail,dst size %zu, src size %u", tensor->GetDataSize(), tensorDef.data()->size());
return nullptr;
}
}
tensor->refCount = tensorDef.refCount();
return tensor.release();
}
Tensor::Tensor(const Tensor &tensor, bool copyData) {
format = tensor.format;
dlTensor.data = nullptr;
dlTensor.ctx.device_type = tensor.dlTensor.ctx.device_type;
dlTensor.ctx.device_id = tensor.dlTensor.ctx.device_id;
dlTensor.strides = nullptr;
dlTensor.byte_offset = tensor.dlTensor.byte_offset;
dlTensor.dtype.code = tensor.dlTensor.dtype.code;
dlTensor.dtype.bits = tensor.dlTensor.dtype.bits;
dlTensor.dtype.lanes = tensor.dlTensor.dtype.lanes;
dlTensor.ndim = tensor.dlTensor.ndim;
if (dlTensor.ndim > 0) {
dlTensor.shape = new (std::nothrow) int64_t[dlTensor.ndim];
if (dlTensor.shape != nullptr) {
for (int i = 0; i < dlTensor.ndim; i++) {
dlTensor.shape[i] = tensor.dlTensor.shape[i];
}
} else {
MS_LOGW("new shape fail,ndim %d", dlTensor.ndim);
}
} else {
dlTensor.shape = nullptr;
}
if (copyData) {
allocator = tensor.allocator;
refCount = tensor.refCount;
auto ret = MallocData();
if (ret != RET_OK) {
return;
}
size_t datasize = GetDataSize();
ret = memcpy_sp(dlTensor.data, datasize, tensor.dlTensor.data, datasize);
if (ret != RET_OK) {
return;
}
}
}
Tensor::Tensor(DataType dt, const std::vector<int64_t> &dims, Format format, void *data) {
this->format = format;
dlTensor.data = data;
dlTensor.ctx.device_type = DLDeviceType::kDLCPU;
dlTensor.ctx.device_id = 0;
dlTensor.strides = nullptr;
dlTensor.byte_offset = 0;
dlTensor.ndim = static_cast<int>(dims.size());
if (dlTensor.ndim > 0) {
dlTensor.shape = new (std::nothrow) int64_t[dlTensor.ndim];
if (dlTensor.shape != nullptr) {
for (int i = 0; i < dlTensor.ndim; i++) {
dlTensor.shape[i] = dims[i];
}
} else {
MS_LOGW("new shape fail,ndim %d", dlTensor.ndim);
}
} else {
dlTensor.shape = nullptr;
}
SetDataType(dt);
}
Tensor::~Tensor() { FreeTensor(); }
DLDataType Tensor::GetTensorDtype() const { return dlTensor.dtype; }
void *Tensor::GetData() const { return dlTensor.data; }
void Tensor::SetData(void *data) { dlTensor.data = data; }
DataType Tensor::GetDataType() const {
DataType dataType = DataType_DT_UNDEFINED;
switch (dlTensor.dtype.code) {
case kDLFloat:
if (dlTensor.dtype.bits == 32) {
dataType = DataType_DT_FLOAT;
} else if (dlTensor.dtype.bits == 16) {
dataType = DataType_DT_FLOAT16;
}
break;
case kDLInt:
if (dlTensor.dtype.bits == 32) {
dataType = DataType_DT_INT32;
} else if (dlTensor.dtype.bits == 8) {
dataType = DataType_DT_INT8;
}
break;
case kDLUInt:
if (dlTensor.dtype.bits == 32) {
dataType = DataType_DT_UINT32;
} else if (dlTensor.dtype.bits == 8) {
dataType = DataType_DT_UINT8;
}
break;
default:
break;
}
return dataType;
}
void Tensor::SetDataType(DataType dt) {
switch (dt) {
case DataType_DT_FLOAT:
dlTensor.dtype.code = kDLFloat;
dlTensor.dtype.bits = 32;
dlTensor.dtype.lanes = 1;
break;
case DataType_DT_FLOAT16:
dlTensor.dtype.code = kDLFloat;
dlTensor.dtype.bits = 16;
dlTensor.dtype.lanes = 1;
break;
case DataType_DT_INT8:
dlTensor.dtype.code = kDLInt;
dlTensor.dtype.bits = 8;
dlTensor.dtype.lanes = 1;
break;
case DataType_DT_UINT8:
dlTensor.dtype.code = kDLUInt;
dlTensor.dtype.bits = 8;
dlTensor.dtype.lanes = 1;
break;
case DataType_DT_INT32:
dlTensor.dtype.code = kDLInt;
dlTensor.dtype.bits = 32;
dlTensor.dtype.lanes = 1;
break;
case DataType_DT_UINT32:
dlTensor.dtype.code = kDLUInt;
dlTensor.dtype.bits = 32;
dlTensor.dtype.lanes = 1;
break;
default:
MS_LOGW(" DataType %d is not implemented.", dt);
MS_LOGW(" DataType DT_FLOAT is used.");
dlTensor.dtype.code = kDLFloat;
dlTensor.dtype.bits = 32;
dlTensor.dtype.lanes = 1;
return;
}
}
int Tensor::GetNDim() const { return dlTensor.ndim; }
std::vector<int64_t> Tensor::GetDims() const {
std::vector<int64_t> dims;
for (int i = 0; i < dlTensor.ndim; i++) {
dims.push_back(dlTensor.shape[i]);
}
return dims;
}
size_t Tensor::GetElementSize() const {
const int tile = 4;
if (format == Format_NC4HW4) {
size_t size = 1;
for (int i = 0; i < dlTensor.ndim; i++) {
auto var = static_cast<size_t>(dlTensor.shape[i]);
if (i == 1) {
var = UP_DIV(var, tile) * tile;
}
size *= var;
}
return size;
} else {
size_t size = 1;
for (int i = 0; i < dlTensor.ndim; i++) {
size *= static_cast<size_t>(dlTensor.shape[i]);
}
return size;
}
}
size_t Tensor::GetDataSize() const {
size_t size = GetElementSize();
const int BYTES = 8;
const int GAP = 7;
size *= (dlTensor.dtype.bits * dlTensor.dtype.lanes + GAP) / BYTES;
return size;
}
int Tensor::MallocData(std::shared_ptr<Allocator> allocator, int refCount) {
if (dlTensor.data != nullptr) {
this->refCount += refCount;
return RET_OK;
}
this->refCount = refCount;
size_t size = GetDataSize();
if (allocator) {
this->allocator = allocator;
dlTensor.data = allocator->Malloc(size);
} else {
if (size > MAX_MALLOC_SIZE) {
return RET_ERROR;
}
dlTensor.data = malloc(size);
}
if (dlTensor.data == nullptr) {
return RET_ERROR;
}
return RET_OK;
}
void Tensor::ForceFreeData() {
if (allocator) {
allocator->Free(dlTensor.data);
} else {
free(dlTensor.data);
}
dlTensor.data = nullptr;
}
void Tensor::FreeData() {
--refCount;
if (refCount <= 0) {
ForceFreeData();
}
}
bool Tensor::CompareShape(const Tensor &dst) {
if (dlTensor.ndim != dst.dlTensor.ndim || dlTensor.shape == nullptr || dst.dlTensor.shape == nullptr) {
MS_LOGE("param error, one.ndim: %d, other.ndim: %d, one shape %p,other shape %p", dlTensor.ndim, dst.dlTensor.ndim,
dlTensor.shape, dst.dlTensor.shape);
return false;
}
for (int i = 0; i < dlTensor.ndim; i++) {
if (dlTensor.shape[i] != dst.dlTensor.shape[i]) {
MS_LOGE("one.shape[%d]: %ld, other.shape[%d]: %ld", i, dlTensor.shape[i], i, dst.dlTensor.shape[i]);
return false;
}
}
return true;
}
bool Tensor::CompareShape(const std::vector<int64_t> &other) {
if (dlTensor.ndim != other.size() || dlTensor.shape == nullptr) {
return false;
}
for (int i = 0; i < dlTensor.ndim; i++) {
if (dlTensor.shape[i] != other[i]) {
return false;
}
}
return true;
}
int64_t Tensor::Height() const {
if (dlTensor.shape == nullptr) {
MS_LOGE("shape is null");
}
if (dlTensor.ndim != DIM_DEFAULT_SIZE) {
MS_LOGE("Tensor should be 4 dimensional.");
return -1;
}
switch (this->format) {
case Format_NCHW:
case Format_NC4HW4:
return dlTensor.shape[NCHW_H];
case Format_NHWC:
return dlTensor.shape[NHWC_H];
default:
MS_LOGE("Unsupported format: %d", this->format);
return -1;
}
}
int64_t Tensor::Width() const {
if (dlTensor.shape == nullptr) {
MS_LOGE("shape is null");
}
if (dlTensor.ndim != DIM_DEFAULT_SIZE) {
MS_LOGE("Tensor should be 4 dimensional.");
return -1;
}
switch (this->format) {
case Format_NCHW:
case Format_NC4HW4:
return dlTensor.shape[NCHW_W];
case Format_NHWC:
return dlTensor.shape[NHWC_W];
default:
MS_LOGE("Unsupported format: %d", this->format);
return -1;
}
}
int64_t Tensor::Channel() const {
if (dlTensor.shape == nullptr) {
MS_LOGE("shape is null");
}
if (dlTensor.ndim != DIM_DEFAULT_SIZE) {
MS_LOGE("Tensor should be 4 dimensional.");
return -1;
}
switch (this->format) {
case Format_NCHW:
case Format_NC4HW4:
return dlTensor.shape[NCHW_C];
case Format_NHWC:
return dlTensor.shape[NHWC_C];
default:
MS_LOGE("Unsupported format: %d", this->format);
return -1;
}
}
int64_t Tensor::Batch() const {
if (dlTensor.shape == nullptr) {
MS_LOGE("shape is null");
}
if (dlTensor.ndim != DIM_DEFAULT_SIZE) {
MS_LOGE("Tensor should be 4 dimensional.");
return -1;
}
switch (this->format) {
case Format_NCHW:
case Format_NC4HW4:
case Format_NHWC:
return dlTensor.shape[NCHW_N];
default:
MS_LOGE("Unsupported format: %d", this->format);
return -1;
}
}
int64_t Tensor::Stride(int index) const {
if (dlTensor.strides) {
return dlTensor.strides[index];
}
if (dlTensor.shape == nullptr) {
MS_LOGE("shape is null");
return -1;
}
int64_t stride = 1;
for (int i = index + 1; i < dlTensor.ndim; i++) {
stride *= dlTensor.shape[i];
}
return stride;
}
void Tensor::SetStride() {
if (dlTensor.strides == nullptr) {
if (dlTensor.ndim < 1) {
MS_LOGE("dims of dlTensor is empty.");
return;
}
dlTensor.strides = new (std::nothrow) int64_t[dlTensor.ndim - 1];
if (dlTensor.strides == nullptr) {
MS_LOGW("new stride fail, ndim %d.", dlTensor.ndim);
return;
}
}
for (int idx = 0; idx < dlTensor.ndim - 1; idx++) {
int64_t stride = 1;
if (dlTensor.ndim <= idx + 1) {
MS_LOGE("out of for loop upper limit.");
return;
}
for (int i = idx + 1; i < dlTensor.ndim; i++) {
stride *= dlTensor.shape[i];
}
dlTensor.strides[idx] = stride;
}
}
void Tensor::SetScale(bool isScale) { this->isScale = isScale; }
void Tensor::SetStride(int index, int64_t stride) {
if (index >= dlTensor.ndim) {
return;
}
if (dlTensor.strides == nullptr) {
SetStride();
}
dlTensor.strides[index] = stride;
return;
}
void Tensor::SetDims(const std::vector<int64_t> &dims) {
if (dlTensor.shape != nullptr) {
delete[] dlTensor.shape;
}
dlTensor.ndim = static_cast<int>(dims.size());
if (dlTensor.ndim > 0) {
dlTensor.shape = new (std::nothrow) int64_t[dlTensor.ndim];
if (dlTensor.shape != nullptr) {
for (int i = 0; i < dlTensor.ndim; i++) {
dlTensor.shape[i] = dims[i];
}
} else {
MS_LOGW("new shape fail,ndim %d", dlTensor.ndim);
}
} else {
dlTensor.shape = nullptr;
}
}
void Tensor::FreeTensor() {
if (dlTensor.shape != nullptr) {
delete[] dlTensor.shape;
dlTensor.shape = nullptr;
}
if (dlTensor.strides != nullptr) {
delete[] dlTensor.strides;
dlTensor.strides = nullptr;
}
dlTensor.ndim = 0;
if (allocator != nullptr) {
allocator->Free(dlTensor.data);
} else {
free(dlTensor.data);
}
dlTensor.data = nullptr;
}
size_t Tensor::GetNC4HW4ElementSize(bool isNhwc) {
int alignIndex = 1;
if (isNhwc) {
alignIndex = 3;
}
size_t size = 1;
for (int i = 0; i < dlTensor.ndim; i++) {
auto var = static_cast<size_t>(dlTensor.shape[i]);
if (i == alignIndex) {
var = ALIGN_UP4(var);
}
size *= var;
}
return size;
}
size_t Tensor::GetNC4HW4DataSize(bool isNhwc) {
size_t size = GetNC4HW4ElementSize(isNhwc);
const int BYTES = 8;
const int GAP = 7;
size *= (dlTensor.dtype.bits * dlTensor.dtype.lanes + GAP) / BYTES;
return size;
}
} // namespace predict
} // namespace mindspore
| 25.874517 | 119 | 0.625308 | [
"shape",
"vector"
] |
de7c0260080278b83852dee7d4d29bfbbc459648 | 1,388 | cpp | C++ | Level-1/18. Graphs/Is-Graph-Cyclic.cpp | anubhvshrma18/PepCoding | 1d5ebd43e768ad923bf007c8dd584e217df1f017 | [
"Apache-2.0"
] | 22 | 2021-06-02T04:25:55.000Z | 2022-01-30T06:25:07.000Z | Level-1/18. Graphs/Is-Graph-Cyclic.cpp | amitdubey6261/PepCoding | 1d5ebd43e768ad923bf007c8dd584e217df1f017 | [
"Apache-2.0"
] | 2 | 2021-10-17T19:26:10.000Z | 2022-01-14T18:18:12.000Z | Level-1/18. Graphs/Is-Graph-Cyclic.cpp | amitdubey6261/PepCoding | 1d5ebd43e768ad923bf007c8dd584e217df1f017 | [
"Apache-2.0"
] | 8 | 2021-07-21T09:55:15.000Z | 2022-01-31T10:32:51.000Z | #include<bits/stdc++.h>
using namespace std;
struct Edge{
int src;
int nbr;
int wt;
// Edge(){
//
// }
Edge(int src,int nbr,int wt){
this->src=src;
this->nbr=nbr;
this->wt=wt;
}
};
//BFS wala
bool isComponentCyclic(vector<vector<Edge*>> &graph,int src,vector<bool> &vis){
queue<int> q;
q.push(src);
while(q.size()>0){
int t=q.front();
q.pop();
if(vis[t]){
return true;
}
vis[t]=true;
for(Edge* edge:graph[src]){
if(!vis[edge->nbr]){
q.push(edge->nbr);
}
}
}
return false;
}
bool isGraphCyclic(vector<vector<Edge*>> &graph){
vector<bool> vis(graph.size(),false);
for(int v=0;v<graph.size();v++){
if(!vis[v]){
if(isComponentCyclic(graph,v,vis)){
return true;
}
}
}
return false;
}
int main(){
int v,e;
cin >> v >> e;
vector<vector<Edge*>> graph(v,vector<Edge*>());
for(int i=0;i<e;i++){
int v1,v2,wt;
cin >> v1 >> v2 >> wt;
Edge* e1=new Edge(v1,v2,wt);
Edge* e2=new Edge(v2,v1,wt);
graph[v1].push_back(e1);
graph[v2].push_back(e2);
}
if(isGraphCyclic(graph)){
cout << "true" << endl;
}
else{
cout << "false" << endl;
}
return 0;
} | 19.549296 | 79 | 0.466859 | [
"vector"
] |
de87c4d014eec105bad1f8236420643d80034e82 | 6,843 | cpp | C++ | Dino's_Journey/Motor2D/j1Collisions.cpp | vlaad96/Vlowup | 574310bae3d0d1695ac011b6e77459287a0aef32 | [
"MIT"
] | null | null | null | Dino's_Journey/Motor2D/j1Collisions.cpp | vlaad96/Vlowup | 574310bae3d0d1695ac011b6e77459287a0aef32 | [
"MIT"
] | null | null | null | Dino's_Journey/Motor2D/j1Collisions.cpp | vlaad96/Vlowup | 574310bae3d0d1695ac011b6e77459287a0aef32 | [
"MIT"
] | null | null | null | #include "j1Collisions.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Render.h"
#include "p2Log.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1Entities.h"
#include "Player.h"
j1Collisions::j1Collisions()
{
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
colliders[i] = nullptr;
}
name.create("Collision");
matrix[COLLIDER_NONE][COLLIDER_NONE] = false;
matrix[COLLIDER_NONE][COLLIDER_PLAYER] = false;
matrix[COLLIDER_NONE][COLLIDER_WALLS] = false;
matrix[COLLIDER_NONE][COLLIDER_SPIKES] = false;
matrix[COLLIDER_NONE][COLLIDER_ACID] = false;
matrix[COLLIDER_NONE][COLLIDER_FLAG] = false;
matrix[COLLIDER_WALLS][COLLIDER_NONE] = false;
matrix[COLLIDER_WALLS][COLLIDER_PLAYER] = true;
matrix[COLLIDER_WALLS][COLLIDER_SPIKES] = false;
matrix[COLLIDER_WALLS][COLLIDER_ACID] = false;
matrix[COLLIDER_WALLS][COLLIDER_FLAG] = false;
matrix[COLLIDER_WALLS][COLLIDER_WALLS] = false;
matrix[COLLIDER_PLAYER][COLLIDER_NONE] = false;
matrix[COLLIDER_PLAYER][COLLIDER_PLAYER] = false;
matrix[COLLIDER_PLAYER][COLLIDER_WALLS] = true;
matrix[COLLIDER_PLAYER][COLLIDER_SPIKES] = true;
matrix[COLLIDER_PLAYER][COLLIDER_ACID] = true;
matrix[COLLIDER_PLAYER][COLLIDER_FLAG] = true;
matrix[COLLIDER_SPIKES][COLLIDER_NONE] = false;
matrix[COLLIDER_SPIKES][COLLIDER_PLAYER] = true;
matrix[COLLIDER_SPIKES][COLLIDER_WALLS] = false;
matrix[COLLIDER_SPIKES][COLLIDER_ACID] = false;
matrix[COLLIDER_SPIKES][COLLIDER_FLAG] = false;
matrix[COLLIDER_SPIKES][COLLIDER_SPIKES] = false;
matrix[COLLIDER_ACID][COLLIDER_NONE] = true;
matrix[COLLIDER_ACID][COLLIDER_PLAYER] = true;
matrix[COLLIDER_ACID][COLLIDER_SPIKES] = false;
matrix[COLLIDER_ACID][COLLIDER_WALLS] = false;
matrix[COLLIDER_ACID][COLLIDER_FLAG] = false;
matrix[COLLIDER_ACID][COLLIDER_ACID] = false;
matrix[COLLIDER_FLAG][COLLIDER_NONE] = true;
matrix[COLLIDER_FLAG][COLLIDER_ACID] = false;
matrix[COLLIDER_FLAG][COLLIDER_PLAYER] = true;
matrix[COLLIDER_FLAG][COLLIDER_WALLS] = false;
matrix[COLLIDER_FLAG][COLLIDER_SPIKES] = false;
matrix[COLLIDER_FLAG][COLLIDER_FLAG] = false;
}
j1Collisions::~j1Collisions()
{
}
bool j1Collisions::PreUpdate()
{
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] != nullptr && colliders[i]->to_delete == true)
{
delete colliders[i];
colliders[i] = nullptr;
}
}
return true;
}
bool j1Collisions::Update(float dt)
{
Collider* col;
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] == nullptr || colliders[i]->type == COLLIDER_NONE || colliders[i]->type == COLLIDER_PLAYER)
continue;
if (colliders[i]->type == COLLIDER_WALLS)
{
if (colliders[i]->CheckBotCollider(App->entities->player->colPlayer->rect, ceil(App->entities->player->gravity))) //ceil rounds the number up, to the biggest possible. For example of 5.6, the ceil would be 6
App->entities->player->isTouchingGround = true;
if (colliders[i]->CheckTopCollider(App->entities->player->colPlayer->rect, ceil(App->entities->player->speed.y)))
App->entities->player->hasWallAbove = true;
if (colliders[i]->CheckLeftCollider(App->entities->player->colPlayer->rect, ceil(App->entities->player->speedMultiplierX)))
App->entities->player->hasWallBehind = true;
if (colliders[i]->CheckRightCollider(App->entities->player->colPlayer->rect, ceil(App->entities->player->speedMultiplierX)))
App->entities->player->hasWallInFront = true;
}
else if (colliders[i]->type == COLLIDER_ACID || colliders[i]->type == COLLIDER_SPIKES || colliders[i]->type == COLLIDER_FLAG)
{
col = colliders[i];
if (App->entities->player->colPlayer->CheckCollision(col->rect) == true)
{
if (matrix[App->entities->player->colPlayer->type][col->type])
{
if (col->type == COLLIDER_ACID || col->type == COLLIDER_SPIKES)
App->entities->player->isDead = true;
else if (col->type == COLLIDER_FLAG)
{
if (App->map->level == 0)
{
App->map->CleanUp();
App->map->Load("Newlevel2.tmx");
App->map->level = 1;
}
else if (App->map->level == 1)
{
App->map->CleanUp();
App->map->Load("Newlevel1.tmx");
App->map->level = 0;
}
}
}
}
}
}
DebugDraw();
return true;
}
bool j1Collisions::CleanUp()
{
LOG("Freeing all colliders");
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] != nullptr)
{
delete colliders[i];
colliders[i] = nullptr;
}
}
return true;
}
Collider* j1Collisions::AddCollider(SDL_Rect rect, COLLIDER_TYPE type, j1Module* callback)
{
Collider* ret = nullptr;
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] == nullptr)
{
ret = colliders[i] = new Collider(rect, type, callback);
break;
}
}
return ret;
}
void j1Collisions::DebugDraw()
{
if (App->input->GetKey(SDL_SCANCODE_F9) == KEY_DOWN) //collider draw
debug = !debug;
if (debug == false)
return;
Uint8 alpha = 80;
for (uint i = 0; i < MAX_COLLIDERS; ++i)
{
if (colliders[i] == nullptr)
continue;
switch (colliders[i]->type)
{
case COLLIDER_NONE: // white
App->render->DrawQuad(colliders[i]->rect, 255, 255, 255, alpha);
break;
case COLLIDER_WALLS: // red
App->render->DrawQuad(colliders[i]->rect, 255, 0, 0, alpha);
break;
case COLLIDER_PLAYER: // green
App->render->DrawQuad(colliders[i]->rect, 0, 255, 0, alpha);
break;
case COLLIDER_SPIKES:
App->render->DrawQuad(colliders[i]->rect, 0, 0, 255, alpha);
break;
case COLLIDER_ACID:
App->render->DrawQuad(colliders[i]->rect, 0, 0, 255, alpha);
break;
case COLLIDER_FLAG: // blue
App->render->DrawQuad(colliders[i]->rect, 0, 0, 128, alpha);
break;
}
}
}
bool Collider::CheckCollision(const SDL_Rect& r) const
{
return (rect.x <= r.x + r.w &&
rect.x + rect.w >= r.x &&
rect.y <= r.y + r.h &&
rect.h + rect.y >= r.y);
}
bool Collider::CheckLeftCollider(const SDL_Rect& r, int dist)const
{
bool ret;
if (r.y + r.h > rect.y &&
r.y < rect.y + rect.h &&
r.x < rect.x + rect.w + dist &&
r.x + r.w > rect.x)
{
ret = true;
}
else
ret = false;
return ret;
}
bool Collider::CheckRightCollider(const SDL_Rect& r, int dist)const
{
bool ret;
if (r.y + r.h > rect.y &&
r.y < rect.y + rect.h &&
r.x + r.w > rect.x - dist &&
r.x < rect.x + rect.w)
{
ret = true;
}
else
ret = false;
return ret;
}
bool Collider::CheckTopCollider(const SDL_Rect& r, int dist)const
{
bool ret;
if (r.y + r.h > rect.y &&
r.y < rect.y + rect.h + dist &&
r.x + r.w > rect.x &&
r.x < rect.x + rect.w)
{
ret = true;
}
else
ret = false;
return ret;
}
bool Collider::CheckBotCollider(const SDL_Rect& r, int dist)const
{
bool ret;
if (r.y < rect.y + rect.h &&
r.y + r.h > rect.y - dist &&
r.x + r.w > rect.x &&
r.x < rect.x + rect.w)
{
ret = true;
}
else
ret = false;
return ret;
} | 22.734219 | 210 | 0.659214 | [
"render"
] |
de88fab59ab30570dc03604092645e075a3fc1b4 | 9,284 | hpp | C++ | engine/alice/node.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | engine/alice/node.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | engine/alice/node.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-07-02T11:51:17.000Z | 2020-07-02T11:51:17.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
#include "engine/alice/backend/clock.hpp"
#include "engine/alice/component.hpp"
#include "engine/alice/components/Config.hpp"
#include "engine/alice/components/Pose.hpp"
#include "engine/alice/components/Sight.hpp"
#include "engine/core/assert.hpp"
#include "engine/gems/uuid/uuid.hpp"
namespace isaac {
namespace alice {
class Application;
class Clock;
class NodeBackend;
// An application consists of many nodes which each fulfills a certain purpose. For example
// localizing the robot or planning a path could be implemented via a node. Nodes are created out
// of various components which define the node's functionality.
class Node {
public:
// The lifecycle stage of the node
enum class Stage {
kInitial, // The C++ constructor of the node was called.
kConstructed, // The node was created.
kPreStart, // The node is starting up but not all its components are started yet.
kStarted, // The node and all its components are started.
kPreStopped, // the node is stopping but not all its components are stopped yet.
kStopped, // The node and all its components are stopped.
kDestructed // The node is destroyed and the C++ destructor will be called.
};
// A class which provides access to certain private functionality only for the NodeBackend.
class BackendAccess {
private:
// Only the NodeBackend has access.
friend class NodeBackend;
// Creates a node with the given name
static Node* ConstructNode(NodeBackend* backend, std::string name) {
Node* node = new Node();
node->backend_ = backend;
node->name_ = std::move(name);
return node;
}
// See `Node::synchronizeComponentList`
static void SynchronizeComponentList(Node* node) {
node->synchronizeComponentList();
}
// See `Node::setStage`
static void SetStage(Node* node, Stage stage) {
node->setStage(stage);
}
};
// The name of this node is useful for human readability but must not be unique
const std::string& name() const { return name_; }
// The app for this node
Application* app();
// The clock backend for this node
Clock* clock();
// Returns the current lifecycle stage of the node
Stage getStage() const { return stage_; }
// Returns true if the node was started
bool isStarted() const { return stage_ == Stage::kStarted; }
// Creates a new component of given type in a node. The component can be created with the given
// name or otherwise the typename is used as the basis of the name. Components must have unique
// names within a node, otherwise these functions will assert.
template <typename T>
T* addComponent();
template <typename T>
T* addComponent(std::string name);
Component* addComponent(const std::string& type_name, std::string name);
// Checks if this node has a component of the given type
template <typename T>
bool hasComponent() const;
// Returns the number of components in the node
size_t getComponentCount() const;
// Gets a list of components
std::vector<Component*> getComponents() const;
// Calls a callback for every component. Do not execute a lot of work in the callback as this
// function blocks until finished.
void iterateComponents(std::function<void(Component*)> callback);
// Gets all components with the given type
template <typename T>
std::vector<T*> getComponents() const;
// Gets component with the given type
// Asserts if there are multiple or no components of that type.
template <typename T>
T* getComponent() const;
// Gets component with the given type, or null if no such component or multiple components
template <typename T>
T* getComponentOrNull() const;
// Gets component with the given name, or null if no such component exists
Component* findComponentByName(const std::string& name) const;
// Returns true if this node has a component with this name
bool hasComponentByName(const std::string& name) const;
// Gets the component for the given type and if none exists creates one first
template <typename T>
T* getOrAddComponent();
// Gets the config component of this node (this component always exists)
Config& config() const { return getComponentCached(config_component_); }
// Gets the pose component (this component always exists)
Pose& pose() const { return getComponentCached(pose_component_); }
// Gets the sight visualization component (this component always exists)
Sight& sight() const { return getComponentCached(sight_component_); }
// Gets the status of the node based on the status of its components
Status getStatus() const {
Status combined = Status::SUCCESS;
for (const auto& x : components_) {
combined = Combine(combined, x->getStatus());
}
return combined;
}
// Set this to true if the node should not be started automatically when the applications starts.
// Note that nodes created at runtime are never started automatically and always need to be
// started manually with app->backend()->node_backed()->start(my_node);
bool disable_automatic_start = false;
// The order in which nodes will be started. The smaller the earliers. Note that this of course
// only applies to nodes which are started at the same time. If a node is started dynamically this
// does not have any effect.
int start_order = 0;
private:
// Derives a name for a component from its type
static std::string ComputeNameFromType(const std::string& type);
// Only NodeBackend can create instances
Node() {}
// Gets a component via a cache. This will get the component only once and from there one use
// the cache instead.
template <typename Component>
Component& getComponentCached(Component*& component) const {
if (component == nullptr) {
component = getComponent<Component>();
}
return *component;
}
// Adds components which where added while the node was starting to the general set of components
void synchronizeComponentList();
// Changes the stage in which the node is
void setStage(Stage stage) { stage_ = stage; }
NodeBackend* backend_;
Stage stage_ = Stage::kInitial;
std::string name_;
mutable std::mutex component_mutex_;
std::vector<std::unique_ptr<Component>> components_;
std::vector<std::unique_ptr<Component>> components_added_while_starting_;
mutable Config* config_component_ = nullptr;
mutable Pose* pose_component_ = nullptr;
mutable Sight* sight_component_ = nullptr;
};
// Implementation
template <typename T>
T* Node::addComponent() {
return addComponent<T>(ComputeNameFromType(ComponentName<T>::TypeName()));
}
template <typename T>
T* Node::addComponent(std::string name) {
auto ptr = addComponent(ComponentName<T>::TypeName(), name);
T* ptr_t = dynamic_cast<T*>(ptr);
ASSERT(ptr_t, "Failed to create component of correct type.");
return ptr_t;
}
template <typename T>
bool Node::hasComponent() const {
std::unique_lock<std::mutex> lock(component_mutex_);
for (const auto& uptr : components_) {
T* ptr = dynamic_cast<T*>(uptr.get());
if (ptr != nullptr) {
return true;
}
}
return false;
}
template <typename T>
std::vector<T*> Node::getComponents() const {
std::unique_lock<std::mutex> lock(component_mutex_);
std::vector<T*> result;
for (const auto& uptr : components_) {
T* ptr = dynamic_cast<T*>(uptr.get());
if (ptr != nullptr) {
result.push_back(ptr);
}
}
return result;
}
template <typename T>
T* Node::getComponent() const {
std::unique_lock<std::mutex> lock(component_mutex_);
T* result = nullptr;
for (const auto& uptr : components_) {
T* ptr = dynamic_cast<T*>(uptr.get());
if (ptr != nullptr) {
ASSERT(result == nullptr,
"Found multiple components of type '%s' in node '%s'. "
"Use `getComponents` to get multiple components.",
ComponentName<T>::TypeName(), name().c_str());
result = ptr;
}
}
ASSERT(result != nullptr,
"Could not find a component of type '%s' in node '%s'. "
"Use `hasComponent` or `getComponents` to check for components.",
ComponentName<T>::TypeName(), name().c_str());
return result;
}
template <typename T>
T* Node::getComponentOrNull() const {
std::unique_lock<std::mutex> lock(component_mutex_);
T* result = nullptr;
for (const auto& uptr : components_) {
T* ptr = dynamic_cast<T*>(uptr.get());
if (ptr != nullptr) {
if (result != nullptr) {
return nullptr;
}
result = ptr;
}
}
return result;
}
template <typename T>
T* Node::getOrAddComponent() {
if (hasComponent<T>()) {
return getComponent<T>();
} else {
return addComponent<T>();
}
}
} // namespace alice
} // namespace isaac
| 33.039146 | 100 | 0.70433 | [
"vector"
] |
de985233653994f41cc7b8c62c2a13645af2d584 | 14,418 | cpp | C++ | ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Transforms/NaCl/BackendCanonicalize.cpp | slightperturbation/Cobalt | 7b398d155d28f7ddf4068a6c25c8aa6aaae486d4 | [
"Apache-2.0"
] | null | null | null | ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Transforms/NaCl/BackendCanonicalize.cpp | slightperturbation/Cobalt | 7b398d155d28f7ddf4068a6c25c8aa6aaae486d4 | [
"Apache-2.0"
] | null | null | null | ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Transforms/NaCl/BackendCanonicalize.cpp | slightperturbation/Cobalt | 7b398d155d28f7ddf4068a6c25c8aa6aaae486d4 | [
"Apache-2.0"
] | null | null | null | //===- BackendCanonicalize.cpp --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Clean up some toolchain-side PNaCl ABI simplification passes. These passes
// allow PNaCl to have a simple and stable ABI, but they sometimes lead to
// harder-to-optimize code. This is desirable because LLVM's definition of
// "canonical" evolves over time, meaning that PNaCl's simple ABI can stay
// simple yet still take full advantage of LLVM's backend by having this pass
// massage the code into something that the backend prefers handling.
//
// It currently:
// - Re-generates shufflevector (not part of the PNaCl ABI) from insertelement /
// extractelement combinations. This is done by duplicating some of
// instcombine's implementation, and ignoring optimizations that should
// already have taken place.
// - Re-materializes constant loads, especially of vectors. This requires doing
// constant folding through bitcasts.
//
// The pass also performs limited DCE on instructions it knows to be dead,
// instead of performing a full global DCE.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Transforms/NaCl.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
// =============================================================================
// TODO(jfb) The following functions are as-is from instcombine. Make them
// reusable instead.
/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
/// elements from either LHS or RHS, return the shuffle mask and true.
/// Otherwise, return false.
static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
SmallVectorImpl<Constant*> &Mask) {
assert(LHS->getType() == RHS->getType() &&
"Invalid CollectSingleShuffleElements");
unsigned NumElts = V->getType()->getVectorNumElements();
if (isa<UndefValue>(V)) {
Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
return true;
}
if (V == LHS) {
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
return true;
}
if (V == RHS) {
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
i+NumElts));
return true;
}
if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
// If this is an insert of an extract from some other vector, include it.
Value *VecOp = IEI->getOperand(0);
Value *ScalarOp = IEI->getOperand(1);
Value *IdxOp = IEI->getOperand(2);
if (!isa<ConstantInt>(IdxOp))
return false;
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
// We can handle this if the vector we are inserting into is
// transitively ok.
if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
// If so, update the mask to reflect the inserted undef.
Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
return true;
}
} else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
if (isa<ConstantInt>(EI->getOperand(1))) {
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
// This must be extracting from either LHS or RHS.
if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
// We can handle this if the vector we are inserting into is
// transitively ok.
if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
// If so, update the mask to reflect the inserted value.
if (EI->getOperand(0) == LHS) {
Mask[InsertedIdx % NumElts] =
ConstantInt::get(Type::getInt32Ty(V->getContext()),
ExtractedIdx);
} else {
assert(EI->getOperand(0) == RHS);
Mask[InsertedIdx % NumElts] =
ConstantInt::get(Type::getInt32Ty(V->getContext()),
ExtractedIdx + NumLHSElts);
}
return true;
}
}
}
}
}
return false;
}
/// We are building a shuffle to create V, which is a sequence of insertelement,
/// extractelement pairs. If PermittedRHS is set, then we must either use it or
/// not rely on the second vector source. Return a std::pair containing the
/// left and right vectors of the proposed shuffle (or 0), and set the Mask
/// parameter as required.
///
/// Note: we intentionally don't try to fold earlier shuffles since they have
/// often been chosen carefully to be efficiently implementable on the target.
typedef std::pair<Value *, Value *> ShuffleOps;
static ShuffleOps CollectShuffleElements(Value *V,
SmallVectorImpl<Constant *> &Mask,
Value *PermittedRHS) {
assert(V->getType()->isVectorTy() && "Invalid shuffle!");
unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
if (isa<UndefValue>(V)) {
Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
return std::make_pair(
PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
}
if (isa<ConstantAggregateZero>(V)) {
Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
return std::make_pair(V, nullptr);
}
if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
// If this is an insert of an extract from some other vector, include it.
Value *VecOp = IEI->getOperand(0);
Value *ScalarOp = IEI->getOperand(1);
Value *IdxOp = IEI->getOperand(2);
if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
// Either the extracted from or inserted into vector must be RHSVec,
// otherwise we'd end up with a shuffle of three inputs.
if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Value *RHS = EI->getOperand(0);
ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
assert(LR.second == nullptr || LR.second == RHS);
if (LR.first->getType() != RHS->getType()) {
// We tried our best, but we can't find anything compatible with RHS
// further up the chain. Return a trivial shuffle.
for (unsigned i = 0; i < NumElts; ++i)
Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
return std::make_pair(V, nullptr);
}
unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Mask[InsertedIdx % NumElts] =
ConstantInt::get(Type::getInt32Ty(V->getContext()),
NumLHSElts+ExtractedIdx);
return std::make_pair(LR.first, RHS);
}
if (VecOp == PermittedRHS) {
// We've gone as far as we can: anything on the other side of the
// extractelement will already have been converted into a shuffle.
unsigned NumLHSElts =
EI->getOperand(0)->getType()->getVectorNumElements();
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(
Type::getInt32Ty(V->getContext()),
i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
return std::make_pair(EI->getOperand(0), PermittedRHS);
}
// If this insertelement is a chain that comes from exactly these two
// vectors, return the vector and the effective shuffle.
if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
Mask))
return std::make_pair(EI->getOperand(0), PermittedRHS);
}
}
}
// Otherwise, can't do anything fancy. Return an identity vector.
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
return std::make_pair(V, nullptr);
}
// =============================================================================
namespace {
class BackendCanonicalize : public FunctionPass,
public InstVisitor<BackendCanonicalize, bool> {
public:
static char ID; // Pass identification, replacement for typeid
BackendCanonicalize() : FunctionPass(ID), DL(0), TLI(0) {
initializeBackendCanonicalizePass(*PassRegistry::getPassRegistry());
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetLibraryInfoWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
virtual bool runOnFunction(Function &F);
// InstVisitor implementation. Unhandled instructions stay as-is.
bool visitInstruction(Instruction &I) { return false; }
bool visitInsertElementInst(InsertElementInst &IE);
bool visitBitCastInst(BitCastInst &C);
bool visitLoadInst(LoadInst &L);
private:
const DataLayout *DL;
const TargetLibraryInfo *TLI;
// List of instructions that are now obsolete, and should be DCE'd.
typedef SmallVector<Instruction *, 512> KillList;
KillList Kill;
/// Helper that constant folds an instruction.
bool visitConstantFoldableInstruction(Instruction *I);
/// Empty the kill list, making sure that all other dead instructions
/// up the chain (but in the current basic block) also get killed.
static void emptyKillList(KillList &Kill);
};
} // anonymous namespace
char BackendCanonicalize::ID = 0;
INITIALIZE_PASS(BackendCanonicalize, "backend-canonicalize",
"Canonicalize PNaCl bitcode for LLVM backends", false, false)
bool BackendCanonicalize::runOnFunction(Function &F) {
bool Modified = false;
DL = &F.getParent()->getDataLayout();
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
Modified |= visit(&*BI);
emptyKillList(Kill);
return Modified;
}
// This function is *almost* as-is from instcombine, avoiding silly
// cases that should already have been optimized.
bool BackendCanonicalize::visitInsertElementInst(InsertElementInst &IE) {
Value *ScalarOp = IE.getOperand(1);
Value *IdxOp = IE.getOperand(2);
// If the inserted element was extracted from some other vector, and if the
// indexes are constant, try to turn this into a shufflevector operation.
if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
unsigned NumInsertVectorElts = IE.getType()->getNumElements();
unsigned NumExtractVectorElts =
EI->getOperand(0)->getType()->getVectorNumElements();
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
return false;
if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
return false;
// If this insertelement isn't used by some other insertelement, turn it
// (and any insertelements it points to), into one big shuffle.
if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
typedef SmallVector<Constant *, 16> MaskT;
MaskT Mask;
Value *LHS, *RHS;
std::tie(LHS, RHS) = CollectShuffleElements(&IE, Mask, nullptr);
if (!RHS)
RHS = UndefValue::get(LHS->getType());
// We now have a shuffle of LHS, RHS, Mask.
if (isa<UndefValue>(LHS) && !isa<UndefValue>(RHS)) {
// Canonicalize shufflevector to always have undef on the RHS,
// and adjust the mask.
std::swap(LHS, RHS);
for (MaskT::iterator I = Mask.begin(), E = Mask.end(); I != E; ++I) {
unsigned Idx = cast<ConstantInt>(*I)->getZExtValue();
unsigned NewIdx = Idx >= NumInsertVectorElts
? Idx - NumInsertVectorElts
: Idx + NumInsertVectorElts;
*I = ConstantInt::get(Type::getInt32Ty(RHS->getContext()), NewIdx);
}
}
IRBuilder<> IRB(&IE);
IE.replaceAllUsesWith(
IRB.CreateShuffleVector(LHS, RHS, ConstantVector::get(Mask)));
// The chain of now-dead insertelement / extractelement
// instructions can be deleted.
Kill.push_back(&IE);
return true;
}
}
}
return false;
}
bool BackendCanonicalize::visitBitCastInst(BitCastInst &B) {
return visitConstantFoldableInstruction(&B);
}
bool BackendCanonicalize::visitLoadInst(LoadInst &L) {
return visitConstantFoldableInstruction(&L);
}
bool BackendCanonicalize::visitConstantFoldableInstruction(Instruction *I) {
if (Constant *Folded = ConstantFoldInstruction(I, *DL, TLI)) {
I->replaceAllUsesWith(Folded);
Kill.push_back(I);
return true;
}
return false;
}
void BackendCanonicalize::emptyKillList(KillList &Kill) {
while (!Kill.empty())
RecursivelyDeleteTriviallyDeadInstructions(Kill.pop_back_val());
}
FunctionPass *llvm::createBackendCanonicalizePass() {
return new BackendCanonicalize();
}
| 39.939058 | 80 | 0.632127 | [
"vector"
] |
de9bf722624b4f5993953d109928731a73914e7a | 26,015 | cpp | C++ | boost/numeric/mtl/interface/vpt.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 24 | 2019-03-26T15:25:45.000Z | 2022-03-26T10:00:45.000Z | boost/numeric/mtl/interface/vpt.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 2 | 2020-04-17T12:35:32.000Z | 2021-03-03T15:46:25.000Z | boost/numeric/mtl/interface/vpt.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 10 | 2019-12-01T13:40:30.000Z | 2022-01-14T08:39:54.000Z | #include <boost/numeric/mtl/interface/vpt.hpp>
#ifdef MTL_HAS_VPT
namespace mtl {
/// Namespace for Vampir Trace interface
namespace vpt {
// Categories:
// Utilities + very small functions: 0000
// Static size operations: 1000
// Vector operations: 2000
// Matrix Vector & single matrix: 3000
// Matrix matrix operations: 4000
// Factorizations, preconditioners: 5000
// Fused operations: 6000
// Iterative solvers: 7000
// Multigrid: 8000
// Utilities: < 1000
template <> std::string vampir_trace<1>::name("copysign");
template <> std::string vampir_trace<2>::name("Elem_raw_copy");
template <> std::string vampir_trace<3>::name("Get_real_part");
template <> std::string vampir_trace<4>::name("Info_contruct_vector");
template <> std::string vampir_trace<5>::name("right_scale_inplace");
template <> std::string vampir_trace<6>::name("sign_real_part_of_complex");
template <> std::string vampir_trace<7>::name("unrolling_expresion");
template <> std::string vampir_trace<8>::name("");
template <> std::string vampir_trace<9>::name("");
template <> std::string vampir_trace<10>::name("squared_abs_magnitudes");
template <> std::string vampir_trace<11>::name("squared_abs_complex");
template <> std::string vampir_trace<12>::name("squared_abs_magnitudes_template");
template <> std::string vampir_trace<13>::name("update_store");
template <> std::string vampir_trace<14>::name("update_plus");
template <> std::string vampir_trace<15>::name("update_minus");
template <> std::string vampir_trace<16>::name("update_times");
template <> std::string vampir_trace<17>::name("update_adapter");
template <> std::string vampir_trace<18>::name("");
template <> std::string vampir_trace<19>::name("");
template <> std::string vampir_trace<20>::name("update_proxy_<<");
template <> std::string vampir_trace<21>::name("update_proxy_=");
template <> std::string vampir_trace<22>::name("update_proxy_+=");
template <> std::string vampir_trace<23>::name("sfunctor::plus");
template <> std::string vampir_trace<24>::name("sfunctor::minus");
template <> std::string vampir_trace<25>::name("sfunctor::times");
template <> std::string vampir_trace<26>::name("sfunctor::divide");
template <> std::string vampir_trace<27>::name("sfunctor::assign");
template <> std::string vampir_trace<28>::name("sfunctor::plus_assign");
template <> std::string vampir_trace<29>::name("sfunctor::minus_assign");
template <> std::string vampir_trace<30>::name("sfunctor::times_assign");
template <> std::string vampir_trace<31>::name("sfunctor::divide_assign");
template <> std::string vampir_trace<32>::name("sfunctor::identity");
template <> std::string vampir_trace<33>::name("sfunctor::abs");
template <> std::string vampir_trace<34>::name("sfunctor::sqrt");
template <> std::string vampir_trace<35>::name("sfunctor::square");
template <> std::string vampir_trace<36>::name("sfunctor::negate");
template <> std::string vampir_trace<37>::name("sfunctor::compose");
template <> std::string vampir_trace<38>::name("sfunctor::compose_first");
template <> std::string vampir_trace<39>::name("sfunctor::compose_second");
template <> std::string vampir_trace<40>::name("sfunctor::compose_both");
template <> std::string vampir_trace<41>::name("sfunctor::compose_binary");
template <> std::string vampir_trace<42>::name("");
template <> std::string vampir_trace<43>::name("");
template <> std::string vampir_trace<44>::name("");
template <> std::string vampir_trace<45>::name("");
// Fine-grained vector operations
template <> std::string vampir_trace<236>::name("Vector_swapped_row");
// Static size operations: 1000
template <> std::string vampir_trace<1001>::name("stat_vec_expr");
template <> std::string vampir_trace<1002>::name("fsize_dmat_dmat_mult");
template <> std::string vampir_trace<1003>::name("vector_size_static");
template <> std::string vampir_trace<1004>::name("static_dispatch"); // ?? row_in_matrix.hpp:74
template <> std::string vampir_trace<1005>::name("copy_blocks_forward");
template <> std::string vampir_trace<1006>::name("copy_blocks_backward");
template <> std::string vampir_trace<1007>::name("Static_Size");
template <> std::string vampir_trace<1008>::name("fsize_mat_vect_mult");
template <> std::string vampir_trace<1009>::name("");
template <> std::string vampir_trace<1010>::name("");
template <> std::string vampir_trace<1011>::name("");
template <> std::string vampir_trace<1012>::name("");
template <> std::string vampir_trace<1013>::name("");
template <> std::string vampir_trace<1014>::name("");
template <> std::string vampir_trace<1015>::name("");
template <> std::string vampir_trace<1016>::name("");
template <> std::string vampir_trace<1017>::name("");
template <> std::string vampir_trace<1018>::name("");
template <> std::string vampir_trace<1019>::name("");
template <> std::string vampir_trace<1020>::name("");
// Vector operations: 2000
template <> std::string vampir_trace<2001>::name("gen_vector_copy");
template <> std::string vampir_trace<2002>::name("cross");
template <> std::string vampir_trace<2003>::name("dot");
template <> std::string vampir_trace<2004>::name("householder");
template <> std::string vampir_trace<2005>::name("householder_s");
template <> std::string vampir_trace<2006>::name("infinity_norm");
template <> std::string vampir_trace<2007>::name("look_at_each_nonzero");
template <> std::string vampir_trace<2008>::name("look_at_each_nonzero_pos");
template <> std::string vampir_trace<2009>::name("reduction");
template <> std::string vampir_trace<2010>::name("max");
template <> std::string vampir_trace<2011>::name("max_abs_pos");
template <> std::string vampir_trace<2012>::name("max_of_sums");
template <> std::string vampir_trace<2013>::name("max_pos");
template <> std::string vampir_trace<2014>::name("merge_complex_vector");
template <> std::string vampir_trace<2015>::name("one_norm");
template <> std::string vampir_trace<2016>::name("diagonal");
template <> std::string vampir_trace<2017>::name("dyn_vec_expr");
template <> std::string vampir_trace<2018>::name("Orthogonalize_Vectors");
template <> std::string vampir_trace<2019>::name("Orthogonalize_Factors");
template <> std::string vampir_trace<2020>::name("Vector_product");
template <> std::string vampir_trace<2021>::name("Vector_random");
template <> std::string vampir_trace<2022>::name("Vec_Vec_rank_update");
template <> std::string vampir_trace<2023>::name("Vector_dispatch");
template <> std::string vampir_trace<2024>::name("Vector_rscale");
template <> std::string vampir_trace<2025>::name("Multi-vector_mult");
template <> std::string vampir_trace<2026>::name("Transp_Multi-vector_mult");
template <> std::string vampir_trace<2027>::name("Hermitian_Multi-vector_mult");
template <> std::string vampir_trace<2028>::name("Vector_scal");
template <> std::string vampir_trace<2029>::name("Vector_set_zero");
template <> std::string vampir_trace<2030>::name("Vector_size1D");
template <> std::string vampir_trace<2031>::name("Vector_size_runtime");
template <> std::string vampir_trace<2032>::name("Vect_quicksort_lo_to_hi");
template <> std::string vampir_trace<2033>::name("Vect_quicksort_permutaion_lo_to_hi");
template <> std::string vampir_trace<2034>::name("split_complex_vector");
template <> std::string vampir_trace<2035>::name("Vect_entries_sum");
template <> std::string vampir_trace<2037>::name("Vector_const_trans");
template <> std::string vampir_trace<2038>::name("Vector_trans");
template <> std::string vampir_trace<2039>::name("two_norm");
template <> std::string vampir_trace<2040>::name("dot_simple");
template <> std::string vampir_trace<2041>::name("unary_dot");
template <> std::string vampir_trace<2042>::name("dense_copy_ctor");
template <> std::string vampir_trace<2043>::name("dense_tpl_copy_ctor");
template <> std::string vampir_trace<2044>::name("");
template <> std::string vampir_trace<2045>::name("");
template <> std::string vampir_trace<2046>::name("");
template <> std::string vampir_trace<2047>::name("");
template <> std::string vampir_trace<2048>::name("");
template <> std::string vampir_trace<2049>::name("");
template <> std::string vampir_trace<2050>::name("");
template <> std::string vampir_trace<2051>::name("");
template <> std::string vampir_trace<2052>::name("");
// Matrix Vector & single matrix: 3000
template <> std::string vampir_trace<3001>::name("matrix_copy_ele_times");
template <> std::string vampir_trace<3002>::name("gen_matrix_copy");
template <> std::string vampir_trace<3003>::name("copy");
template <> std::string vampir_trace<3004>::name("clone");
template <> std::string vampir_trace<3005>::name("compute_summand");
template <> std::string vampir_trace<3006>::name("crop");
template <> std::string vampir_trace<3007>::name("mat::diagonal");
template <> std::string vampir_trace<3008>::name("assign_each_nonzero");
template <> std::string vampir_trace<3009>::name("fill");
template <> std::string vampir_trace<3010>::name("frobenius_norm");
template <> std::string vampir_trace<3011>::name("mat::infinity_norm");
template <> std::string vampir_trace<3012>::name("invert_diagonal");
template <> std::string vampir_trace<3013>::name("iota");
template <> std::string vampir_trace<3014>::name("left_scale_inplace");
template <> std::string vampir_trace<3015>::name("mat::look_at_each_nonzero");
template <> std::string vampir_trace<3016>::name("mat::look_at_each_nonzero_pos");
template <> std::string vampir_trace<3017>::name("fsize_dense_mat_cvec_mult");
template <> std::string vampir_trace<3018>::name("dense_mat_cvec_mult");
template <> std::string vampir_trace<3019>::name("mvec_cvec_mult");
template <> std::string vampir_trace<3020>::name("trans_mvec_cvec_mult");
template <> std::string vampir_trace<3021>::name("herm_mvec_cvec_mult");
template <> std::string vampir_trace<3022>::name("sparse_row_cvec_mult"); // generic row-major sparse
template <> std::string vampir_trace<3023>::name("ccs_cvec_mult");
template <> std::string vampir_trace<3024>::name("mat::max_abs_pos");
template <> std::string vampir_trace<3025>::name("mat::one_norm");
template <> std::string vampir_trace<3026>::name("invert_diagonal(compressed)");
template <> std::string vampir_trace<3027>::name("mat_vect_mult");
template <> std::string vampir_trace<3028>::name("Vect_sparse_mat_mult");
template <> std::string vampir_trace<3029>::name("Matrix_scal");
template <> std::string vampir_trace<3030>::name("Vector_Secular_Equation");
template <> std::string vampir_trace<3031>::name("Matrix_set_zero");
template <> std::string vampir_trace<3032>::name("Matrix_size1D");
template <> std::string vampir_trace<3033>::name("Matrix_size_runtime");
template <> std::string vampir_trace<3034>::name("Matrix_LU");
template <> std::string vampir_trace<3035>::name("Vector_Matrix_LU");
template <> std::string vampir_trace<3036>::name("Sub_matrix_indices");
template <> std::string vampir_trace<3037>::name("Matrix_svd_reference");
template <> std::string vampir_trace<3038>::name("Matrix_svd_triplet");
template <> std::string vampir_trace<3039>::name("Matrix_swapped");
template <> std::string vampir_trace<3040>::name("Matrix_Trace");
template <> std::string vampir_trace<3041>::name("Matrix_const_trans");
template <> std::string vampir_trace<3042>::name("Matrix_trans");
template <> std::string vampir_trace<3043>::name("Matrix_upper_trisolve");
template <> std::string vampir_trace<3044>::name("Matrix_upper_trisolve_diagonal");
template <> std::string vampir_trace<3045>::name("Matrix_upper_trisolve_invers_diag");
template <> std::string vampir_trace<3046>::name("Matrix_upper_trisolve_DiaTag");
template <> std::string vampir_trace<3047>::name("scalar_assign");
template <> std::string vampir_trace<3048>::name("elest_cvec_mult");
template <> std::string vampir_trace<3049>::name("crs_cvec_mult");
template <> std::string vampir_trace<3050>::name("sparse_ins::ctor");
template <> std::string vampir_trace<3051>::name("sparse_ins::dtor");
template <> std::string vampir_trace<3052>::name("sparse_ins::stretch");
template <> std::string vampir_trace<3053>::name("sparse_ins::final_place");
template <> std::string vampir_trace<3054>::name("sparse_ins::insert_spare");
template <> std::string vampir_trace<3055>::name("mat_crtp_scal_assign");
template <> std::string vampir_trace<3056>::name("mat_crtp_mat_assign");
template <> std::string vampir_trace<3057>::name("mat_crtp_sum_assign");
template <> std::string vampir_trace<3058>::name("mat_crtp_diff_assign");
template <> std::string vampir_trace<3059>::name("mat_crtp_array_assign");
template <> std::string vampir_trace<3060>::name("mat_crtp_mvec_assign");
template <> std::string vampir_trace<3061>::name("copy_band_to_sparse");
template <> std::string vampir_trace<3062>::name("block_dia_times_cvec");
template <> std::string vampir_trace<3063>::name("laplacian_setup");
template <> std::string vampir_trace<3064>::name("vsmat_cvec_mult");
template <> std::string vampir_trace<3065>::name("adapt_crs_cvec_mult");
template <> std::string vampir_trace<3066>::name("dense2D_cvec_mult");
template <> std::string vampir_trace<3067>::name("square_cvec_mult");
template <> std::string vampir_trace<3068>::name("mat_crtp_mult_assign");
template <> std::string vampir_trace<3069>::name("sbanded_cvec_mult");
template <> std::string vampir_trace<3070>::name("mat_cvec_multiplier");
template <> std::string vampir_trace<3071>::name("");
template <> std::string vampir_trace<3072>::name("");
template <> std::string vampir_trace<3073>::name("");
template <> std::string vampir_trace<3074>::name("");
template <> std::string vampir_trace<3075>::name("");
template <> std::string vampir_trace<3076>::name("");
template <> std::string vampir_trace<3077>::name("");
template <> std::string vampir_trace<3078>::name("");
template <> std::string vampir_trace<3079>::name("");
// Matrix matrix operations: 4000
template <> std::string vampir_trace<4001>::name("cursor_dmat_dmat_mult");
template <> std::string vampir_trace<4002>::name("dmat_dmat_mult");
template <> std::string vampir_trace<4003>::name("tiling_dmat_dmat_mult");
template <> std::string vampir_trace<4004>::name("tiling_44_dmat_dmat_mult");
template <> std::string vampir_trace<4005>::name("tiling_22_dmat_dmat_mult");
template <> std::string vampir_trace<4006>::name("wrec_dmat_dmat_mult");
template <> std::string vampir_trace<4007>::name("recursive_dmat_dmat_mult");
template <> std::string vampir_trace<4008>::name("xgemm");
template <> std::string vampir_trace<4009>::name("");
template <> std::string vampir_trace<4010>::name("mult");
template <> std::string vampir_trace<4011>::name("gen_mult");
template <> std::string vampir_trace<4012>::name("mat_mat_mult");
template <> std::string vampir_trace<4013>::name("matrix_qr");
template <> std::string vampir_trace<4014>::name("matrix_qr_factors");
template <> std::string vampir_trace<4015>::name("matrix_random");
template <> std::string vampir_trace<4016>::name("matrix_scale_inplace");
template <> std::string vampir_trace<4017>::name("matrix_rscale");
template <> std::string vampir_trace<4018>::name("matrix_gen_smat_dmat_mult");
template <> std::string vampir_trace<4019>::name("matrix_gen_tiling_smat_dmat_mult");
template <> std::string vampir_trace<4020>::name("matrix_smat_smat_mult");
template <> std::string vampir_trace<4021>::name("");
template <> std::string vampir_trace<4022>::name("");
template <> std::string vampir_trace<4023>::name("");
template <> std::string vampir_trace<4024>::name("");
template <> std::string vampir_trace<4025>::name("");
template <> std::string vampir_trace<4026>::name("");
template <> std::string vampir_trace<4027>::name("");
template <> std::string vampir_trace<4028>::name("");
template <> std::string vampir_trace<4029>::name("");
template <> std::string vampir_trace<4030>::name("");
template <> std::string vampir_trace<4031>::name("");
template <> std::string vampir_trace<4032>::name("");
template <> std::string vampir_trace<4033>::name("");
template <> std::string vampir_trace<4034>::name("");
template <> std::string vampir_trace<4035>::name("");
template <> std::string vampir_trace<4036>::name("read_el_matrix");
template <> std::string vampir_trace<4037>::name("");
template <> std::string vampir_trace<4038>::name("");
template <> std::string vampir_trace<4039>::name("");
template <> std::string vampir_trace<4040>::name("");
template <> std::string vampir_trace<4041>::name("");
// Factorizations, preconditioners: 5000
template <> std::string vampir_trace<5001>::name("cholesky_base");
template <> std::string vampir_trace<5002>::name("cholesky_solve_base");
template <> std::string vampir_trace<5003>::name("cholesky_schur_base");
template <> std::string vampir_trace<5004>::name("cholesky_update_base");
template <> std::string vampir_trace<5005>::name("cholesky_schur_update");
template <> std::string vampir_trace<5006>::name("cholesky_tri_solve");
template <> std::string vampir_trace<5007>::name("cholesky_tri_schur");
template <> std::string vampir_trace<5008>::name("recursive cholesky");
template <> std::string vampir_trace<5009>::name("fill_matrix_for_cholesky");
template <> std::string vampir_trace<5010>::name("qr_sym_imp");
template <> std::string vampir_trace<5011>::name("qr_algo");
template <> std::string vampir_trace<5012>::name("eigenvalue_symmetric");
template <> std::string vampir_trace<5013>::name("hessenberg_q");
template <> std::string vampir_trace<5014>::name("hessenberg_factors");
template <> std::string vampir_trace<5015>::name("extract_householder_hessenberg");
template <> std::string vampir_trace<5016>::name("householder_hessenberg");
template <> std::string vampir_trace<5017>::name("extract_hessenberg");
template <> std::string vampir_trace<5018>::name("hessenberg");
template <> std::string vampir_trace<5019>::name("inv_upper");
template <> std::string vampir_trace<5020>::name("inv_lower");
template <> std::string vampir_trace<5021>::name("inv");
template <> std::string vampir_trace<5022>::name("lower_trisolve");
template <> std::string vampir_trace<5023>::name("lu");
template <> std::string vampir_trace<5024>::name("lu(pivot)");
template <> std::string vampir_trace<5025>::name("lu_f");
template <> std::string vampir_trace<5026>::name("lu_solve_straight");
template <> std::string vampir_trace<5027>::name("lu_apply");
template <> std::string vampir_trace<5028>::name("lu_solve");
template <> std::string vampir_trace<5029>::name("lu_adjoint_apply");
template <> std::string vampir_trace<5030>::name("lu_adjoint_solve");
template <> std::string vampir_trace<5031>::name("pc::id::solve");
template <> std::string vampir_trace<5032>::name("pc::id.solve");
template <> std::string vampir_trace<5033>::name("pc::id::adjoint_solve");
template <> std::string vampir_trace<5034>::name("pc::id.adjoint_solve");
template <> std::string vampir_trace<5035>::name("ic_0::factorize");
template <> std::string vampir_trace<5036>::name("ic_0::solve");
template <> std::string vampir_trace<5037>::name("ic_0::solve_nocopy");
template <> std::string vampir_trace<5038>::name("ilu_0::factorize");
template <> std::string vampir_trace<5039>::name("ilu_0::solve");
template <> std::string vampir_trace<5040>::name("ilu_0::adjoint_solve");
template <> std::string vampir_trace<5041>::name("lower_trisolve_kernel");
template <> std::string vampir_trace<5042>::name("upper_trisolve_row");
template <> std::string vampir_trace<5043>::name("upper_trisolve_col");
template <> std::string vampir_trace<5044>::name("ic_0::adjoint_solve");
template <> std::string vampir_trace<5045>::name("ic_0::adjoint_solve_nocopy");
template <> std::string vampir_trace<5046>::name("upper_trisolve_crs_compact");
template <> std::string vampir_trace<5047>::name("lower_trisolve_crs_compact");
template <> std::string vampir_trace<5048>::name("lower_unit_trisolve_crs_compact");
template <> std::string vampir_trace<5049>::name("ilut::factorize");
template <> std::string vampir_trace<5050>::name("diagonal::setup");
template <> std::string vampir_trace<5051>::name("diagonal::solve");
template <> std::string vampir_trace<5052>::name("imf::factor");
template <> std::string vampir_trace<5053>::name("imf::ctor");
template <> std::string vampir_trace<5054>::name("imf::solve");
template <> std::string vampir_trace<5055>::name("pc::solver::assign_to");
template <> std::string vampir_trace<5056>::name("sub_matrix_pc::solve");
template <> std::string vampir_trace<5057>::name("sub_matrix_pc::adjoint_solve");
template <> std::string vampir_trace<5058>::name("pc::concat::solve");
template <> std::string vampir_trace<5059>::name("pc::concat::adjoint_solve");
template <> std::string vampir_trace<5060>::name("umfpack::solver::ctor");
template <> std::string vampir_trace<5061>::name("umfpack::solver::dtor");
template <> std::string vampir_trace<5062>::name("umfpack::solve");
// Fused operations: 6000
template <> std::string vampir_trace<6001>::name("fused::fwd_eval_loop");
template <> std::string vampir_trace<6002>::name("fused::fwd_eval_loop_unrolled");
template <> std::string vampir_trace<6003>::name("fused::bwd_eval_loop");
template <> std::string vampir_trace<6004>::name("fused::bwd_eval_loop_unrolled");
// Iterative solvers: 7000
template <> std::string vampir_trace<7001>::name("cg_without_pc");
template <> std::string vampir_trace<7002>::name("cg");
template <> std::string vampir_trace<7003>::name("bicg");
template <> std::string vampir_trace<7004>::name("bicgstab");
template <> std::string vampir_trace<7005>::name("bicgstab_2");
template <> std::string vampir_trace<7006>::name("bicgstab_ell");
template <> std::string vampir_trace<7007>::name("cgs");
template <> std::string vampir_trace<7008>::name("qmr");
template <> std::string vampir_trace<7009>::name("tfqmr");
template <> std::string vampir_trace<7010>::name("idr_s");
// OpenMP
template <> std::string vampir_trace<8001>::name("omp::dot");
template <> std::string vampir_trace<8002>::name("omp::reduction");
template <> std::string vampir_trace<8003>::name("omp::dyn_vec_expr");
template <> std::string vampir_trace<8004>::name("omp::crs_cvec_mult");
// multigrid
template <> std::string vampir_trace<8501>::name("mtl::mg::v_cycle");
template <> std::string vampir_trace<8502>::name("mtl::mg::w_cycle");
template <> std::string vampir_trace<8503>::name("mtl::mg::fmg");
template <> std::string vampir_trace<8504>::name("mtl::mg::two_grid_cycle");
template <> std::string vampir_trace<8510>::name("mtl::mg::geometric_multigrid_solver_impl");
template <> std::string vampir_trace<8511>::name("mtl::mg::geometric_multigrid_solver_solve1");
template <> std::string vampir_trace<8512>::name("mtl::mg::geometric_multigrid_solver_solve2");
template <> std::string vampir_trace<8515>::name("mtl::mg::algebraic_multigrid_solver");
template <> std::string vampir_trace<8516>::name("amg_pc::solve");
template <> std::string vampir_trace<8520>::name("mtl::mg::linear_restriction");
template <> std::string vampir_trace<8521>::name("mtl::mg::linear_prolongation");
template <> std::string vampir_trace<8530>::name("mtl::mg::gauss_elimination");
template <> std::string vampir_trace<8531>::name("mtl::mg::back_substitution");
template <> std::string vampir_trace<8550>::name("mtl::mg::jacobi");
template <> std::string vampir_trace<8551>::name("mtl::mg::gauss_seidel");
template <> std::string vampir_trace<8552>::name("mtl::mg::jor");
template <> std::string vampir_trace<8553>::name("mtl::mg::sor");
template <> std::string vampir_trace<8572>::name("boundaries");
template <> std::string vampir_trace<8573>::name("viscosity");
template <> std::string vampir_trace<8574>::name("pressure_correction");
template <> std::string vampir_trace<8590>::name("mtl::mg::util::vtk_exporter");
template <> std::string vampir_trace<8591>::name("mtl::mg::util::csv_exporter");
template <> std::string vampir_trace<8610>::name("amg::amg_matrix_hierarchy");
template <> std::string vampir_trace<8611>::name("amg::compute_influence");
template <> std::string vampir_trace<8612>::name("amg::default_coarse_grid_detection::compute_C");
template <> std::string vampir_trace<8614>::name("amg::utils::compute_potentials");
template <> std::string vampir_trace<8615>::name("amg::utils::find_max_pos");
template <> std::string vampir_trace<8617>::name("amg::amg_prolongation");
template <> std::string vampir_trace<8618>::name("amg::compute_weight");
template <> std::string vampir_trace<8619>::name("amg::compute_mfactors");
template <> std::string vampir_trace<8620>::name("amg::strongly_influenced_points");
template <> std::string vampir_trace<8621>::name("amg::is_strongly_influenced");
template <> std::string vampir_trace<8622>::name("amg::strongly_influencing_points");
template <> std::string vampir_trace<8630>::name("amg::amg_operators::amg_restriction");
template <> std::string vampir_trace<8631>::name("amg::amg_operators::amg_prolongation");
template <> std::string vampir_trace<8635>::name("amg::amg_operators::amg_weight");
template <> std::string vampir_trace<8900>::name("NaSto::solve()");
template <> std::string vampir_trace<8910>::name("NaSto::computeGamma()");
template <> std::string vampir_trace<8920>::name("NaSto::computeBoundaries()");
template <> std::string vampir_trace<8930>::name("NaSto::computeImplViscosity()");
template <> std::string vampir_trace<8940>::name("NaSto::computePressureCorr()");
// Test blocks for performance debugging
template <> std::string vampir_trace<9901>::name("tb1");
template <> std::string vampir_trace<9902>::name("tb2");
template <> std::string vampir_trace<9903>::name("tb3");
template <> std::string vampir_trace<9904>::name("tb4");
template <> std::string vampir_trace<9999>::name("main");
// Only for testing
template <> std::string vampir_trace<9990>::name("helper_function");
template <> std::string vampir_trace<9991>::name("function");
}} //mtl::vpt
#endif //MTL_HAS_VPT
| 58.592342 | 101 | 0.731501 | [
"vector"
] |
de9d866c14ccc4df62dd47b58b66c67da75f8f8c | 1,296 | cpp | C++ | Algorithms/SubMatrixSum.cpp | RawRapter/CPlusPlus-Codes | 5c88fa6aaee47f6414fdfaafe8274522cb227605 | [
"MIT"
] | null | null | null | Algorithms/SubMatrixSum.cpp | RawRapter/CPlusPlus-Codes | 5c88fa6aaee47f6414fdfaafe8274522cb227605 | [
"MIT"
] | null | null | null | Algorithms/SubMatrixSum.cpp | RawRapter/CPlusPlus-Codes | 5c88fa6aaee47f6414fdfaafe8274522cb227605 | [
"MIT"
] | null | null | null | /*
Submatrix Sum:
Given a matrix MxN there are large number of queries to find subqueries sum. Input to Queries
are left top and right bottom indexes of submatrix is to find out.
Will use 2 D vector way
*/
#include<bits/stdc++.h>
using namespace std;
int sum(vector<vector<int>> v, int sr, int sc, int er, int ec){
int m=v.size(); //row size
int n=v[0].size(); //column size
//Creating copy
int M=m;
int N=n;
vector<vector<int>> aux = v;
vector<vector<int>> mat = v;
int tli=sr, tlj=sc, rbi=er, rbj=ec;
for (int i=0; i<N; i++)
aux[0][i] = mat[0][i];
// Do column wise sum
for (int i=1; i<M; i++)
for (int j=0; j<N; j++)
aux[i][j] = mat[i][j] + aux[i-1][j];
// Do row wise sum
for (int i=0; i<M; i++)
for (int j=1; j<N; j++)
aux[i][j] += aux[i][j-1];
int res = aux[rbi][rbj];
// Remove elements between (0, 0) and (tli-1, rbj)
if (tli > 0)
res = res - aux[tli-1][rbj];
// Remove elements between (0, 0) and (rbi, tlj-1)
if (tlj > 0)
res = res - aux[rbi][tlj-1];
// Add aux[tli-1][tlj-1] as elements between (0, 0)
// and (tli-1, tlj-1) are subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli-1][tlj-1];
return res;
} | 23.563636 | 93 | 0.536265 | [
"vector"
] |
de9fd7196b8e3139f7fb9a0a6daf2d646089d9a0 | 10,752 | cpp | C++ | src/game/KesslerSyndrome/elements/CloudLayerParticleSystem.cpp | ShamylZakariya/KesslerSyndrome | dce00108304fe2c1b528515dafc29c15011d4679 | [
"MIT"
] | null | null | null | src/game/KesslerSyndrome/elements/CloudLayerParticleSystem.cpp | ShamylZakariya/KesslerSyndrome | dce00108304fe2c1b528515dafc29c15011d4679 | [
"MIT"
] | null | null | null | src/game/KesslerSyndrome/elements/CloudLayerParticleSystem.cpp | ShamylZakariya/KesslerSyndrome | dce00108304fe2c1b528515dafc29c15011d4679 | [
"MIT"
] | null | null | null | //
// CloudLayerParticleSystem.cpp
// Kessler Syndrome
//
// Created by Shamyl Zakariya on 10/18/17.
//
#include "game/KesslerSyndrome/elements/CloudLayerParticleSystem.hpp"
#include "core/util/GlslProgLoader.hpp"
#include "core/filters/Filters.hpp"
using namespace core;
using namespace elements;
namespace game {
CloudLayerParticleSimulation::noise_config CloudLayerParticleSimulation::noise_config::parse(const XmlTree &node) {
noise_config n;
n.octaves = util::xml::readNumericAttribute<int>(node, "noise", n.octaves);
n.seed = util::xml::readNumericAttribute<int>(node, "seed", n.seed);
return n;
}
CloudLayerParticleSimulation::particle_config CloudLayerParticleSimulation::particle_config::parse(const XmlTree &node) {
particle_config pt;
pt.minRadius = util::xml::readNumericAttribute<double>(node, "minRadius", pt.minRadius);
pt.maxRadius = util::xml::readNumericAttribute<double>(node, "maxRadius", pt.maxRadius);
pt.minRadiusNoiseValue = util::xml::readNumericAttribute<double>(node, "minRadiusNoiseValue", pt.minRadiusNoiseValue);
pt.color = util::xml::readColorAttribute(node, "color", pt.color);
return pt;
}
CloudLayerParticleSimulation::config CloudLayerParticleSimulation::config::parse(const XmlTree &node) {
config c;
c.noise = noise_config::parse(node.getChild("noise"));
c.particle = particle_config::parse(node.getChild("particle"));
c.origin = util::xml::readPointAttribute(node, "origin", c.origin);
c.radius = util::xml::readNumericAttribute<double>(node, "radius", c.radius);
c.count = util::xml::readNumericAttribute<size_t>(node, "count", c.count);
c.period = util::xml::readNumericAttribute<seconds_t>(node, "period", c.period);
c.turbulence = util::xml::readNumericAttribute<double>(node, "turbulence", c.turbulence);
c.displacementForce = util::xml::readNumericAttribute<double>(node, "displacementForce", c.displacementForce);
c.returnForce = util::xml::readNumericAttribute<double>(node, "returnForce", c.returnForce);
return c;
}
/*
config _config;
ci::Perlin _noise;
core::seconds_t _time;
cpBB _bb;
vector<core::RadialGravitationCalculatorRef> _displacements;
vector<particle_physics> _physics;
*/
CloudLayerParticleSimulation::CloudLayerParticleSimulation(const config &c) :
_config(c),
_noise(c.noise.octaves, c.noise.seed),
_time(0) {
}
void CloudLayerParticleSimulation::onReady(ObjectRef parent, StageRef stage) {
//
// create store, set defult state, and run simulate() once to populate
//
setParticleCount(_config.count);
double a = 0;
double da = 2 * M_PI / getActiveCount();
auto state = _state.begin();
auto physics = _physics.begin();
for (size_t i = 0, N = getParticleCount(); i < N; i++, ++state, ++physics, a += da) {
// set up initial physics state
physics->position = physics->previous_position = physics->home = _config.origin + _config.radius * dvec2(cos(a), sin(a));
physics->damping = Rand::randFloat(0.4, 0.7);
physics->velocity = dvec2(0, 0);
physics->radius = 0;
state->atlasIdx = 0;
state->color = _config.particle.color;
state->additivity = 0;
state->position = physics->home;
state->active = true; // always active
}
simulate(stage->getTimeState());
}
void CloudLayerParticleSimulation::update(const time_state &timeState) {
_time += timeState.deltaT;
simulate(timeState);
}
void CloudLayerParticleSimulation::setParticleCount(size_t count) {
BaseParticleSimulation::setParticleCount(count);
_physics.resize(count);
}
void CloudLayerParticleSimulation::addGravityDisplacement(const RadialGravitationCalculatorRef &gravity) {
_displacements.push_back(gravity);
}
void CloudLayerParticleSimulation::simulate(const time_state &timeState) {
if (!_displacements.empty()) {
pruneDisplacements();
applyGravityDisplacements(timeState);
}
double a = 0;
const double TwoPi = 2 * M_PI;
const double da = TwoPi / getActiveCount();
const double cloudLayerRadius = _config.radius;
const double cloudLayerRadius2 = cloudLayerRadius * cloudLayerRadius;
const double particleRadiusDelta = _config.particle.maxRadius - _config.particle.minRadius;
const double particleMinRadius = _config.particle.minRadius;
const double noiseYAxis = _time / _config.period;
const double noiseMin = _config.particle.minRadiusNoiseValue;
const double noiseTurbulence = _config.turbulence;
const double rNoiseRange = 1.0 / (1.0 - noiseMin);
const double returnForce = _config.returnForce;
const double deltaT2 = timeState.deltaT * timeState.deltaT;
const dvec2 origin = _config.origin;
cpBB bounds = cpBBInvalid;
auto physics = _physics.begin();
auto state = _state.begin();
const auto end = _state.end();
for (; state != end; ++state, ++physics, a += da) {
//
// simplistic verlet integration
//
physics->velocity = (physics->position - physics->previous_position) * physics->damping;
physics->previous_position = physics->position;
dvec2 acceleration = (physics->home - physics->position) * returnForce;
physics->position += physics->velocity + (acceleration * deltaT2);
//
// move position back to circle
//
dvec2 dirToPosition = physics->position - origin;
double d2 = lengthSquared(dirToPosition);
if (d2 < cloudLayerRadius2 - 1e-1 || d2 > cloudLayerRadius2 + 1e-1) {
dirToPosition /= sqrt(d2);
physics->position = origin + cloudLayerRadius * dirToPosition;
}
//
// now update position scale and rotation
//
state->position = physics->position;
double angle;
if (lengthSquared(physics->position - physics->home) > 1e-2) {
angle = atan2(physics->position.y, physics->position.x) - M_PI_2;
} else {
angle = a - M_PI_2;
}
double fbm = _noise.fBm(a * noiseTurbulence, noiseYAxis);
double noise = (fbm + 1.0) * 0.5;
double radius = 0;
if (noise > noiseMin) {
double remappedNoiseVale = (noise - noiseMin) * rNoiseRange;
radius = particleMinRadius + remappedNoiseVale * particleRadiusDelta;
}
physics->radius = lrp(timeState.deltaT, physics->radius, radius);
//
// Compute the rotation axes
//
double cosa, sina;
__sincos(angle, &sina, &cosa);
state->right = physics->radius * dvec2(cosa, sina);
state->up = rotateCCW(state->right);
//
// we're using alpha as a flag to say this particle should or should not be drawn
//
state->color.a = physics->radius > 1e-2 ? 1 : 0;
//
// Update bounds
//
bounds = cpBBExpand(bounds, state->position, physics->radius);
}
_bb = bounds;
}
void CloudLayerParticleSimulation::pruneDisplacements() {
_displacements.erase(std::remove_if(_displacements.begin(), _displacements.end(), [](const GravitationCalculatorRef &g) {
return g->isFinished();
}), _displacements.end());
}
void CloudLayerParticleSimulation::applyGravityDisplacements(const time_state &timeState) {
for (const auto &g : _displacements) {
dvec2 centerOfMass = g->getCenterOfMass();
double magnitude = -1 * g->getMagnitude() * timeState.deltaT * _config.displacementForce;
for (auto physics = _physics.begin(), end = _physics.end(); physics != end; ++physics) {
dvec2 dir = physics->position - centerOfMass;
double d2 = length2(dir);
physics->position += magnitude * dir / d2;
}
}
}
#pragma mark - CloudLayerParticleSystemDrawComponent
CloudLayerParticleSystemDrawComponent::CloudLayerParticleSystemDrawComponent(config c, ColorA particleColor):
ParticleSystemDrawComponent(c)
{
auto clearColor = ColorA(particleColor, 0);
auto stack = make_shared<FilterStack>();
setFilterStack(stack, clearColor);
auto compositor = util::loadGlslAsset("kessler/filters/cloudlayer_compositor.glsl");
compositor->uniform("Alpha", particleColor.a);
stack->setScreenCompositeShader(compositor);
}
gl::GlslProgRef CloudLayerParticleSystemDrawComponent::createDefaultShader() const {
return util::loadGlslAsset("kessler/shaders/cloudlayer.glsl");
}
void CloudLayerParticleSystemDrawComponent::setShaderUniforms(const gl::GlslProgRef &program, const core::render_state &renderState) {
ParticleSystemDrawComponent::setShaderUniforms(program, renderState);
}
#pragma mark - CloudLayerParticleSystem
CloudLayerParticleSystem::config CloudLayerParticleSystem::config::parse(const XmlTree &node) {
config c;
c.drawConfig.drawLayer = DrawLayers::EFFECTS;
c.drawConfig = ParticleSystemDrawComponent::config::parse(node.getChild("draw"));
c.simulationConfig = CloudLayerParticleSimulation::config::parse(node.getChild("simulation"));
return c;
}
CloudLayerParticleSystemRef CloudLayerParticleSystem::create(config c) {
// alpha for cloud layer is applied in the compositor pass,
// so set alpha to 1 during initial rendering; and pass actual
// color to the draw component so it knows how to composite correctly
const auto particleColor = c.simulationConfig.particle.color;
c.simulationConfig.particle.color.a = 1;
auto simulation = make_shared<CloudLayerParticleSimulation>(c.simulationConfig);
auto draw = make_shared<CloudLayerParticleSystemDrawComponent>(c.drawConfig, particleColor);
return Object::create<CloudLayerParticleSystem>("CloudLayer", {draw, simulation});
}
CloudLayerParticleSystem::CloudLayerParticleSystem(string name) :
BaseParticleSystem(name) {
}
}
| 38.263345 | 138 | 0.635975 | [
"object",
"vector"
] |
dea021e7639aa4193af77cd54d9fc397268488c2 | 974 | cpp | C++ | Codeforces/106B - Choosing Laptop.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/106B - Choosing Laptop.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/106B - Choosing Laptop.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct info { int speed, ram, hdd, cost; };
int main() {
ios::sync_with_stdio(false);
int n;
cin >> n;
vector<info> arr(n);
vector<bool> marks(n, false);
for (auto &el: arr) cin >> el.speed >> el.ram >> el.hdd >> el.cost;
for (int i = 0; i < n; ++i) {
info &fir = arr[i];
for (int j = i + 1; j < n; ++j) {
info &sec = arr[j];
if (fir.speed < sec.speed && fir.hdd < sec.hdd && fir.ram < sec.ram)
marks[i] = true;
else if (sec.speed < fir.speed && sec.hdd < fir.hdd && sec.ram < fir.ram)
marks[j] = true;
}
}
int mn = numeric_limits<int>::max(), res ;
for (int i = 0; i < n; ++i) {
if (!marks[i]) {
if (arr[i].cost < mn) {
res = i + 1;
mn = arr[i].cost;
}
}
}
cout << res << endl;
return 0;
}
| 24.35 | 85 | 0.428131 | [
"vector"
] |
dea28d8ac9d8415c9c5de1fd050a37ad8de2b23e | 1,530 | cpp | C++ | day16a.cpp | henbr/aoc2019 | 30f6ff902c5c48536db188bac1516df5dff2cb48 | [
"MIT"
] | null | null | null | day16a.cpp | henbr/aoc2019 | 30f6ff902c5c48536db188bac1516df5dff2cb48 | [
"MIT"
] | null | null | null | day16a.cpp | henbr/aoc2019 | 30f6ff902c5c48536db188bac1516df5dff2cb48 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <array>
#include <math.h>
using namespace std;
static array<int, 4> pattern = {{0, 1, 0, -1}};
static string input = "59790677903322930697358770979456996712973859451709720515074487141246507419590039598329735611909754526681279087091321241889537569965210074382210124927546962637736867742660227796566466871680580005288100192670887174084077574258206307557682549836795598410624042549261801689113559881008629752048213862796556156681802163843211546443228186862314896620419832148583664829023116082772951046466358463667825025457939806789469683866009241229487708732435909544650428069263180522263909211986231581228330456441451927777125388590197170653962842083186914721611560451459928418815254443773460832555717155899456905676980728095392900218760297612453568324542692109397431554";
int get_pattern_num(int index, int output_index) {
return pattern[((index + 1) / (output_index + 1)) % pattern.size()];
}
string fft_phase(const string &in) {
string out;
for (int output_pos = 0; output_pos < in.size(); output_pos++) {
int res = 0;
for (int i = 0; i < in.size(); i++) {
int num = in[i] - '0';
res += num * get_pattern_num(i, output_pos);
}
res = abs(res) % 10;
out.push_back('0' + res);
}
return out;
}
int main() {
auto res = input;
for (int i = 0; i < 100; i++) {
res = fft_phase(res);
}
res = res.substr(0, 8);
cout << res << endl;
return 1;
}
| 31.875 | 675 | 0.731373 | [
"vector"
] |
deab39f40747ee90fc3540d8ccbb01ca76f4055a | 2,160 | cpp | C++ | effect_score_floater.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | effect_score_floater.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | effect_score_floater.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | /* Copyright (c) 2012-2013 Cheese and Bacon Games, LLC */
/* See the file docs/COPYING.txt for copying permission. */
#include "effect_score_floater.h"
#include "render.h"
#include "mirror.h"
#include "world.h"
#include "random_number_generator.h"
#include "holidays.h"
using namespace std;
Effect_Score_Floater::Effect_Score_Floater(uint64_t get_score,double get_x,double get_y){
exists=true;
move_speed=1.0;
x=get_x;
y=get_y;
score=get_score;
life=150;
if(random_range(0,99)<50){
moving_left=true;
}
else{
moving_left=false;
}
pixels_moved=0;
player.existing_effects_score_floater++;
}
void Effect_Score_Floater::move(){
if(exists){
//Move the score floater sideways.
if(pixels_moved>=18){
pixels_moved=0;
moving_left=!moving_left;
}
if(life%3==0){
if(moving_left){
x--;
}
else{
x++;
}
pixels_moved++;
}
y-=move_speed;
if(--life<=0){
exists=false;
player.existing_effects_score_floater--;
}
}
}
void Effect_Score_Floater::render(bool mirrored){
if(exists){
ss.clear();ss.str("");ss<<score;msg=ss.str();
if(x>=player.camera_x-(msg.length()*font.spacing_x) && x<=player.camera_x+player.camera_w && y>=player.camera_y-font.spacing_y && y<=player.camera_y+player.camera_h){
double render_x=x;
double render_y=y;
if(mirrored && touching_mirror(x+MIRROR_DISTANCE_X,y+MIRROR_DISTANCE_Y,msg.length()*font.spacing_x,16)){
render_x+=MIRROR_DISTANCE_X;
render_y+=MIRROR_DISTANCE_Y;
}
font.show((int)((int)render_x+2-(int)player.camera_x),(int)((int)render_y+2-(int)player.camera_y),msg,COLOR_BLACK);
font.show((int)((int)render_x-(int)player.camera_x),(int)((int)render_y-(int)player.camera_y),msg,return_gui_color(holiday,3));
}
else{
exists=false;
player.existing_effects_score_floater--;
}
}
}
| 24.545455 | 174 | 0.589352 | [
"render"
] |
deab9d75e873b2147651ea109d9bd9c538e313d4 | 2,726 | cpp | C++ | test/source/mazegenerator/Cell.cpp | danielplawrence/MazeGeneration | d9d0e878c94226aa379e6ee2a2681f1c99b2f792 | [
"Unlicense"
] | null | null | null | test/source/mazegenerator/Cell.cpp | danielplawrence/MazeGeneration | d9d0e878c94226aa379e6ee2a2681f1c99b2f792 | [
"Unlicense"
] | null | null | null | test/source/mazegenerator/Cell.cpp | danielplawrence/MazeGeneration | d9d0e878c94226aa379e6ee2a2681f1c99b2f792 | [
"Unlicense"
] | null | null | null | #include <doctest/doctest.h>
#include <mazegenerator/Cell.h>
#include <mazegenerator/Distances.h>
#include <algorithm>
#include <vector>
TEST_CASE("Cell") {
SUBCASE("A cell has a location") {
auto cell1 = Cell::create(0, 0);
std::pair<int, int> expectedLocation = {0, 0};
CHECK(cell1->getLocation() == expectedLocation);
}
SUBCASE("A cell has a table of links") {
auto cell1 = Cell::create(0, 0);
CHECK(cell1->getLinks() == std::vector<std::shared_ptr<Cell>>());
}
SUBCASE("A cell can be linked to another unidirectionally") {
auto cell1 = Cell::create(0, 0);
auto cell2 = Cell::create(1, 1);
cell1->link(cell2, false);
CHECK(cell1->linkedTo(cell2));
CHECK(!cell2->linkedTo(cell1));
}
SUBCASE("A cell can be linked to another bidirectionally") {
auto cell1 = Cell::create(0, 0);
auto cell2 = Cell::create(1, 1);
cell1->link(cell2, true);
CHECK(cell1->linkedTo(cell2));
CHECK(cell2->linkedTo(cell1));
}
SUBCASE("Unidirectional links can be unlinked") {
auto cell1 = Cell::create(0, 0);
auto cell2 = Cell::create(1, 1);
cell1->link(cell2);
CHECK(cell1->linkedTo(cell2));
cell1->unlink(cell2);
CHECK(!cell1->linkedTo(cell2));
}
SUBCASE("Bidirectional links can be unlinked") {
auto cell1 = Cell::create(0, 0);
auto cell2 = Cell::create(1, 1);
cell1->link(cell2, true);
CHECK(cell1->linkedTo(cell2));
CHECK(cell2->linkedTo(cell1));
cell1->unlink(cell2);
CHECK(!cell1->linkedTo(cell2));
CHECK(!cell2->linkedTo(cell1));
}
SUBCASE("A cell can list its neighbors") {
auto cell = Cell::create(0, 0);
auto cell2 = Cell::create(1, 1);
cell->neighbours.north = cell2;
cell->neighbours.south = cell2;
cell->neighbours.east = cell2;
cell->neighbours.west = cell2;
auto res = cell->getNeighbors();
CHECK(res.size() == 4);
}
SUBCASE("A cell returns an empty list for no neighbors") {
auto cell = Cell::create(0, 0);
auto res = cell->getNeighbors();
CHECK(res.size() == 0);
}
SUBCASE("A cell returns its distances") {
auto root = Cell::create(0, 0);
auto firstNode = Cell::create(0, 0);
auto secondNode = Cell::create(0, 0);
auto thirdNode = Cell::create(0, 0);
auto thirdNode2 = Cell::create(0, 0);
secondNode->link(thirdNode);
secondNode->link(thirdNode2);
firstNode->link(secondNode);
root->link(firstNode);
auto distances = root->getDistances();
CHECK(distances->get(thirdNode).value() == 3);
CHECK(distances->get(thirdNode2).value() == 3);
CHECK(distances->get(secondNode).value() == 2);
CHECK(distances->get(firstNode).value() == 1);
CHECK(distances->get(root).value() == 0);
}
} | 33.243902 | 69 | 0.632428 | [
"vector"
] |
deac4e2f1b0bcf642f6854539ec1988e0699b25e | 4,701 | cxx | C++ | src/gadget/main_maxpool_image.cxx | lejeunel/glia | 24b763a230627951139010cd07b0d0ff2356a365 | [
"MIT"
] | 11 | 2016-08-16T02:26:31.000Z | 2021-08-25T06:51:47.000Z | src/gadget/main_maxpool_image.cxx | lejeunel/glia | 24b763a230627951139010cd07b0d0ff2356a365 | [
"MIT"
] | 3 | 2017-05-26T15:33:42.000Z | 2018-04-27T12:12:24.000Z | src/gadget/main_maxpool_image.cxx | lejeunel/glia | 24b763a230627951139010cd07b0d0ff2356a365 | [
"MIT"
] | 9 | 2016-07-25T08:28:12.000Z | 2021-03-17T15:02:41.000Z | #include "util/image_io.hxx"
#include "util/text_cmd.hxx"
using namespace glia;
bool operation (std::string const& outputImageFile,
std::string const& inputImageFile,
std::vector<Int> const& skipDims, int n, bool compress)
{
std::unordered_set<Int> sd;
for (auto d: skipDims) { sd.insert(d); }
switch (readImageInfo(inputImageFile)->GetComponentType()) {
case itk::ImageIOBase::IOComponentType::UCHAR:
{
typedef itk::Image<unsigned char, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::CHAR:
{
typedef itk::Image<char, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::USHORT:
{
typedef itk::Image<unsigned short, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::SHORT:
{
typedef itk::Image<short, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::UINT:
{
typedef itk::Image<unsigned int, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::INT:
{
typedef itk::Image<int, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::ULONG:
{
typedef itk::Image<unsigned long, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::LONG:
{
typedef itk::Image<long, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::FLOAT:
{
typedef itk::Image<float, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
case itk::ImageIOBase::IOComponentType::DOUBLE:
{
typedef itk::Image<double, DIMENSION> Image;
auto image = readImage<Image>(inputImageFile);
for (int i = 0; i < n; ++i)
{ image = maxPoolImage(image, sd); }
writeImage(outputImageFile, image, compress);
break;
}
default: perr("Error: unsupported image pixel type...");
}
return true;
}
int main (int argc, char* argv[])
{
std::string inputImageFile, outputImageFile;
std::vector<Int> skipDims;
int n = 1;
bool compress = false;
bpo::options_description opts("Usage");
opts.add_options()
("help", "Print usage info")
("inputImage,i", bpo::value<std::string>(&inputImageFile)->required(),
"Input real image file name")
("skipDims,d", bpo::value<std::vector<Int>>(&skipDims),
"Skipped dimensions (e.g. use -d 2 to skip z) (optional)")
("nPool,n", bpo::value<int>(&n), "Number of pooling [default: 1]")
("compress,z", bpo::value<bool>(&compress),
"Whether to compress output image file(s) [default: false]")
("outputImage,o",
bpo::value<std::string>(&outputImageFile)->required(),
"Output real image file name");
return
parse(argc, argv, opts) &&
operation(outputImageFile, inputImageFile, skipDims, n, compress)?
EXIT_SUCCESS: EXIT_FAILURE;
}
| 35.613636 | 76 | 0.599234 | [
"vector"
] |
deacdabacda849211f29f9f87aeea27222c2ce21 | 10,359 | cpp | C++ | source/backend/cpu/x86_x64/AVX2Backend.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | source/backend/cpu/x86_x64/AVX2Backend.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | source/backend/cpu/x86_x64/AVX2Backend.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | //
// AVX2Backend.cpp
// MNN
//
// Created by MNN on 2021/05/16.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include <algorithm>
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
#include "AVX2Functions.hpp"
#include "AVX2Backend.hpp"
#include "core/BufferAllocator.hpp"
#include "core/TensorUtils.hpp"
#include "backend/cpu/CPURaster.hpp"
#include "backend/cpu/CPUReduction.hpp"
#include "backend/cpu/CPUSoftmax.hpp"
#include "backend/cpu/CPUTensorConvert.hpp"
#include "core/OpCommonUtils.hpp"
#include "backend/cpu/CPUCast.hpp"
namespace MNN {
bool AVX2Backend::isValid() {
return nullptr != AVX2Functions::get();
}
AVX2Backend::AVX2Backend(const CPURuntime* runtime, size_t flags) : CPUBackend(runtime, BackendConfig::Precision_Low, MNN_FORWARD_CPU_EXTENSION, flags) {
mCoreFunctions = AVX2Functions::get();
}
AVX2Backend::~AVX2Backend() {
// nothing to do
}
// TODO: Move to functions
static void _CopyC4ToC8(void* dstPtr, const void* srcPtr, int channelC4, int area) {
float* dst = static_cast<float*>(dstPtr);
const float* src = static_cast<const float*>(srcPtr);
int c8 = channelC4 / 2;
int cR = channelC4 % 2;
for (int z=0; z<c8; ++z) {
auto s0 = src + 2 * z * area * 4;
auto s1 = src + (2 * z + 1) * area * 4;
auto d = dst + z * area * 8;
for (int x=0; x<area; ++x) {
auto v0 = _mm_loadu_ps(s0);
auto v1 = _mm_loadu_ps(s1);
_mm_storeu_ps(d + 0, v0);
_mm_storeu_ps(d + 4, v1);
s0 += 4;
s1 += 4;
d += 8;
}
}
if (cR > 0) {
auto s0 = src + 2 * c8 * area * 4;
auto d = dst + c8 * area * 8;
auto v1 = _mm_setzero_ps();
for (int x=0; x<area; ++x) {
auto v0 = _mm_loadu_ps(s0);
_mm_storeu_ps(d + 0, v0);
_mm_storeu_ps(d + 4, v1);
s0 += 4;
d += 8;
}
}
}
static void _CopyC8ToC4(void* dstPtr, const void* srcPtr, int channelC4, int area) {
float* dst = static_cast<float*>(dstPtr);
const float* src = static_cast<const float*>(srcPtr);
int c8 = channelC4 / 2;
int cR = channelC4 % 2;
for (int z=0; z<c8; ++z) {
auto s0 = dst + 2 * z * area * 4;
auto s1 = dst + (2 * z + 1) * area * 4;
auto d = src + z * area * 8;
for (int x=0; x<area; ++x) {
auto v0 = _mm_loadu_ps(d);
auto v1 = _mm_loadu_ps(d + 4);
_mm_storeu_ps(s0, v0);
_mm_storeu_ps(s1, v1);
s0 += 4;
s1 += 4;
d+= 8;
}
}
if (cR > 0) {
auto s0 = dst + 2 * c8 * area * 4;
auto d = src + c8 * area * 8;
for (int x=0; x<area; ++x) {
auto v0 = _mm_loadu_ps(d);
_mm_storeu_ps(s0, v0);
s0 += 4;
d+= 8;
}
}
}
static void _CopyC4ToC8_int8(void* dstPtr, const void* srcPtr, int channelC4, int area) {
int8_t* dst = static_cast<int8_t*>(dstPtr);
const int8_t* src = static_cast<const int8_t*>(srcPtr);
int c8 = channelC4 / 2;
int cR = channelC4 % 2;
for (int z=0; z<c8; ++z) {
auto s0 = src + 2 * z * area * 4;
auto s1 = src + (2 * z + 1) * area * 4;
auto d = dst + z * area * 8;
for (int x=0; x<area; ++x) {
*(int*)d = *(int*)s0;
*((int*)d + 1) = *(int*)s1;
s0 += 4;
s1 += 4;
d += 8;
}
}
if (cR > 0) {
auto s0 = src + 2 * c8 * area * 4;
auto d = dst + c8 * area * 8;
for (int x=0; x<area; ++x) {
*(int*)d = *(int*)s0;
*((int*)d + 1) = 0;
s0 += 4;
d += 8;
}
}
}
static void _CopyC8ToC4_int8(void* dstPtr, const void* srcPtr, int channelC4, int area) {
int8_t* dst = static_cast<int8_t*>(dstPtr);
const int8_t* src = static_cast<const int8_t*>(srcPtr);
int c8 = channelC4 / 2;
int cR = channelC4 % 2;
for (int z=0; z<c8; ++z) {
auto s0 = dst + 2 * z * area * 4;
auto s1 = dst + (2 * z + 1) * area * 4;
auto d = src + z * area * 8;
for (int x=0; x<area; ++x) {
*(int*)s0 = *(int*)d;
*(int*)s1 = *((int*)d + 1);
s0 += 4;
s1 += 4;
d+= 8;
}
}
if (cR > 0) {
auto s0 = dst + 2 * c8 * area * 4;
auto d = src + c8 * area * 8;
for (int x=0; x<area; ++x) {
*(int*)s0 = *(int*)d;
s0 += 4;
d += 8;
}
}
}
Execution* AVX2Backend::onCreate(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs,
const MNN::Op* op) {
for (auto t : outputs) {
if (t->getType().code != halide_type_float) {
return nullptr;
}
}
auto inputQuantInfo = OpCommonUtils::getQuantInfo(inputs);
auto ouputQuantInfo = OpCommonUtils::getQuantInfo(outputs);
halide_type_t quantType = halide_type_of<float>();
if (inputQuantInfo.first) {
if (!ouputQuantInfo.first && !outputs.empty()) {
quantType = outputs[0]->getType();
} else {
quantType = TensorUtils::DataTypeToHalideType(inputQuantInfo.second);
}
}
auto originType = outputs.empty() ? halide_type_of<float>() : outputs[0]->getType();
auto runType = getRunType(op, quantType, originType);
if (runType == halide_type_of<int8_t>()) {
return nullptr;
}
if (op->type() == OpType_Raster) {
return new CPURaster(this);
}
bool originCreate = OpCommonUtils::opCompabilityForLowp(op);
if (originCreate || op->type() == OpType_Softmax || op->type() == OpType_Reduction) {
return CPUBackend::onCreate(inputs, outputs, op);
}
return nullptr;
}
bool AVX2Backend::onAcquireBuffer(const Tensor* nativeTensor, StorageType storageType) {
// arm82 backend tensor data type is fp16 default
auto tensor = const_cast<Tensor*>(nativeTensor);
auto& buffer = tensor->buffer();
auto tensorSize = getTensorSize(nativeTensor);
auto res = allocBuffer(tensorSize * buffer.type.bytes(), (Tensor*)nativeTensor, storageType);
if (!res) {
return false;
}
// Set mask in device for easy to determine
buffer.device = 1;
return true;
}
void AVX2Backend::onCopyBuffer(const Tensor* srcTensor, const Tensor* dstTensor) const {
auto& ib = srcTensor->buffer();
auto& ob = dstTensor->buffer();
std::unique_ptr<Tensor> wrapTensor;
if (ib.type.code != halide_type_float && ib.type != halide_type_of<int8_t>()) {
CPUBackend::onCopyBuffer(srcTensor, dstTensor);
return;
}
if (ib.type.code != ob.type.code) {
auto dimType = Tensor::CAFFE;
switch (TensorUtils::getDescribe(srcTensor)->dimensionFormat) {
case MNN_DATA_FORMAT_NCHW:
break;
case MNN_DATA_FORMAT_NC4HW4:
dimType = Tensor::CAFFE_C4;
break;
case MNN_DATA_FORMAT_NHWC:
dimType = Tensor::TENSORFLOW;
break;
default:
break;
}
wrapTensor.reset(Tensor::create(srcTensor->shape(), dstTensor->getType(), nullptr, dimType));
auto code = CPUCastCreator::cast(srcTensor, wrapTensor.get());
if (NO_ERROR != code) {
MNN_ERROR("Error in CPUBackend::onCopyBuffer:cast\n");
}
srcTensor = wrapTensor.get();
}
auto source = TensorUtils::getDescribe(srcTensor)->dimensionFormat;
auto dest = TensorUtils::getDescribe(dstTensor)->dimensionFormat;
auto srcType = MNN_FORWARD_CPU;
if (ib.device != 0) {
srcType = MNN_FORWARD_CPU_EXTENSION;
}
auto dstType = MNN_FORWARD_CPU;
if (ob.device != 0) {
dstType = MNN_FORWARD_CPU_EXTENSION;
}
if (srcType == dstType) {
if(srcType == MNN_FORWARD_CPU_EXTENSION) {
CPUTensorConverter::convert(srcTensor, dstTensor, mCoreFunctions);
} else {
CPUTensorConverter::convert(srcTensor, dstTensor, MNNGetCoreFunctions());
}
return;
}
if (source != MNN_DATA_FORMAT_NC4HW4 && dest != MNN_DATA_FORMAT_NC4HW4) {
CPUTensorConverter::convert(srcTensor, dstTensor, mCoreFunctions);
return;
}
if (source == MNN_DATA_FORMAT_NC4HW4 && dest == MNN_DATA_FORMAT_NC4HW4) {
// NC4HW4 <-> NC8HW8
if (1 == srcTensor->dimensions()) {
::memcpy(dstTensor->host<void>(), srcTensor->host<void>(), srcTensor->length(0) * srcTensor->getType().bytes());
return;
}
auto dims = CPUTensorConverter::splitDimensions(srcTensor->buffer(), source);
int area = std::get<1>(dims) * std::get<0>(dims);
int channel = std::get<2>(dims);
auto c4 = UP_DIV(channel, 4);
auto c8 = UP_DIV(channel, mCoreFunctions->pack);
auto c8toc4 = _CopyC8ToC4, c4toc8 = _CopyC4ToC8;
switch (ob.type.bytes()) {
case 1:
c8toc4 = _CopyC8ToC4_int8;
c4toc8 = _CopyC4ToC8_int8;
break;
case 4:
c8toc4 = _CopyC8ToC4;
c4toc8 = _CopyC4ToC8;
break;
default:
MNN_ASSERT(false);
break;
}
if (srcType == MNN_FORWARD_CPU_EXTENSION) {
c8toc4(dstTensor->host<void>(), srcTensor->host<void>(), c4, area);
} else {
c4toc8(dstTensor->host<void>(), srcTensor->host<void>(), c4, area);
}
return;
}
if (source == MNN_DATA_FORMAT_NC4HW4) {
if (srcType == MNN_FORWARD_CPU_EXTENSION) {
CPUTensorConverter::convert(srcTensor, dstTensor, mCoreFunctions);
} else {
CPUTensorConverter::convert(srcTensor, dstTensor, MNNGetCoreFunctions());
}
return;
}
if (dest == MNN_DATA_FORMAT_NC4HW4) {
if (dstType == MNN_FORWARD_CPU_EXTENSION) {
CPUTensorConverter::convert(srcTensor, dstTensor, mCoreFunctions);
} else {
CPUTensorConverter::convert(srcTensor, dstTensor, MNNGetCoreFunctions());
}
return;
}
MNN_ASSERT(false);
return;
}
} // namespace MNN
| 33.201923 | 153 | 0.549184 | [
"shape",
"vector"
] |
deb0476295ea05f9b2d8ad7e2fae311e76cdb72e | 2,195 | cpp | C++ | src/Vulkan/DebugMessenger.cpp | nishidate-yuki/vkray | 604714f09f9cf5b140c02ef04ce081e36387c763 | [
"MIT"
] | 9 | 2021-01-18T12:46:41.000Z | 2021-01-20T08:16:11.000Z | src/Vulkan/DebugMessenger.cpp | nishidate-yuki/vkray | 604714f09f9cf5b140c02ef04ce081e36387c763 | [
"MIT"
] | null | null | null | src/Vulkan/DebugMessenger.cpp | nishidate-yuki/vkray | 604714f09f9cf5b140c02ef04ce081e36387c763 | [
"MIT"
] | 1 | 2021-01-20T00:54:23.000Z | 2021-01-20T00:54:23.000Z | #include "vktiny/Vulkan/DebugMessenger.hpp"
#include "vktiny/Log.hpp"
#include <iostream>
#include <sstream>
VKAPI_ATTR VkBool32 VKAPI_CALL debugUtilsMessengerCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
VkDebugUtilsMessengerCallbackDataEXT const* pCallbackData,
void* /*pUserData*/)
{
std::stringstream ss;
ss << "DebugUtilsMessage: ";
if (messageTypes & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
ss << "General\n";
} else if (messageTypes & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
ss << "Validation\n";
} else {
ss << "Performance\n";
}
ss << "MessageID: " << pCallbackData->pMessageIdName << "\n";
// Validation Error...
std::string str = pCallbackData->pMessage;
//ss << str;
std::size_t next = str.find("Object ");
ss << str.substr(0, next) << std::endl;
str = str.substr(next);
// (cut)
next = str.find("|") + 2;
str = str.substr(next);
next = str.find("|") + 2;
str = str.substr(next);
// Message
next = str.find("The Vulkan spec");
if (next != std::string::npos) {
ss << str.substr(0, next) << std::endl;
str = str.substr(next);
}
ss << str << std::endl;
if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)) {
vkt::log::error(ss.str());
} else if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)) {
vkt::log::warn(ss.str());
} else {
vkt::log::info(ss.str());
}
return VK_FALSE;
}
namespace vkt
{
void DebugMessenger::initialize(const Instance& instance)
{
using vkMS = vk::DebugUtilsMessageSeverityFlagBitsEXT;
using vkMT = vk::DebugUtilsMessageTypeFlagBitsEXT;
vk::DebugUtilsMessengerCreateInfoEXT createInfo;
createInfo.setMessageSeverity(vkMS::eWarning | vkMS::eError);
createInfo.setMessageType(vkMT::eGeneral | vkMT::ePerformance | vkMT::eValidation);
createInfo.setPfnUserCallback(&debugUtilsMessengerCallback);
messenger = instance.get().createDebugUtilsMessengerEXTUnique(createInfo);
}
}
| 31.357143 | 91 | 0.656948 | [
"object"
] |
deb24106eb8aa7e37bb32bf126668db33f452436 | 246 | cpp | C++ | docs/mfc/codesnippet/CPP/diagnostic-services_19.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/mfc/codesnippet/CPP/diagnostic-services_19.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 3,272 | 2017-06-24T00:26:34.000Z | 2022-03-31T22:14:07.000Z | docs/mfc/codesnippet/CPP/diagnostic-services_19.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | #ifdef _DEBUG
//AfxDoForAllObjects will call the function DoForAllObjects
//For each CObject-derived object that is allocated on the heap
int nCount = 0;
AfxDoForAllObjects(DoForAllObjects, &nCount);
TRACE("%d Objects Checked\n", nCount);
#endif | 35.142857 | 63 | 0.792683 | [
"object"
] |
630e39a7c82553074ecf04c7aa428d01f802b45d | 16,144 | cpp | C++ | kdrive/src/knx/datapoint/Datapoint.cpp | weinzierl-engineering/baos | 306acc8e86da774fdeecec042dcf99734677fdc0 | [
"MIT"
] | 34 | 2015-09-16T10:10:14.000Z | 2022-02-19T16:11:04.000Z | kdrive/src/knx/datapoint/Datapoint.cpp | weinzierl-engineering/baos | 306acc8e86da774fdeecec042dcf99734677fdc0 | [
"MIT"
] | 17 | 2017-01-02T15:26:19.000Z | 2022-01-20T01:27:24.000Z | kdrive/src/knx/datapoint/Datapoint.cpp | weinzierl-engineering/baos | 306acc8e86da774fdeecec042dcf99734677fdc0 | [
"MIT"
] | 20 | 2016-12-12T22:18:08.000Z | 2022-03-15T16:20:20.000Z |
#include "pch/kdrive_pch.h"
#include "kdrive/knx/datapoint/Datapoint.h"
#include "kdrive/knx/datapoint/FloatConverter.h"
#include "kdrive/knx/core/ByteStream.h"
#include <Poco/Exception.h>
#include <Poco/DateTime.h>
#include <Poco/LocalDateTime.h>
#include <boost/assert.hpp>
using namespace kdrive::knx;using Poco::Dynamic::Var;using Poco::
DataFormatException;using Poco::DateTime;using Poco::LocalDateTime;namespace{
unsigned char z930e31f79d(const Datapoint&datapoint,std::size_t z6aeae56d87){
BOOST_ASSERT(z6aeae56d87&&
"\x50\x72\x65\x63\x6f\x6e\x64\x69\x74\x69\x6f\x6e\x20\x66\x61\x69\x6c\x65\x64");
const std::vector<unsigned char>&data=datapoint.getData();if(data.size()!=
z6aeae56d87){throw DataFormatException(
"\x49\x6e\x76\x61\x6c\x69\x64\x20\x64\x61\x74\x61\x20\x6c\x65\x6e\x67\x74\x68");
}return data.at((0x171a+3161-0x2373));}const std::vector<unsigned char>&getData(
const Datapoint&datapoint,std::size_t z6aeae56d87){BOOST_ASSERT(z6aeae56d87&&
"\x50\x72\x65\x63\x6f\x6e\x64\x69\x74\x69\x6f\x6e\x20\x66\x61\x69\x6c\x65\x64");
const std::vector<unsigned char>&data=datapoint.getData();if(data.size()!=
z6aeae56d87){throw DataFormatException(
"\x49\x6e\x76\x61\x6c\x69\x64\x20\x64\x61\x74\x61\x20\x6c\x65\x6e\x67\x74\x68");
}return data;}void setData(Datapoint&datapoint,const std::vector<unsigned char>&
data,std::size_t z6aeae56d87){BOOST_ASSERT(z6aeae56d87&&
"\x50\x72\x65\x63\x6f\x6e\x64\x69\x74\x69\x6f\x6e\x20\x66\x61\x69\x6c\x65\x64");
if(data.size()!=z6aeae56d87){throw DataFormatException(
"\x49\x6e\x76\x61\x6c\x69\x64\x20\x64\x61\x74\x61\x20\x6c\x65\x6e\x67\x74\x68");
}datapoint.setData(data);}}const std::string Datapoint::Id=
"\x44\x70\x74\x2e\x49\x64";const std::string Datapoint::Number=
"\x44\x70\x74\x2e\x4e\x75\x6d\x62\x65\x72";const std::string Datapoint::Name=
"\x44\x70\x74\x2e\x4e\x61\x6d\x65";const std::string Datapoint::Text=
"\x44\x70\x74\x2e\x54\x65\x78\x74";const std::string Datapoint::z564c074eac=
"\x44\x70\x74\x2e\x53\x69\x7a\x65\x49\x6e\x42\x69\x74";const std::string
Datapoint::Data="\x44\x70\x74\x2e\x44\x61\x74\x61";Datapoint::Datapoint(){}
Datapoint::Datapoint(const std::string id,const std::string&number,const std::
string&name,const std::string&text,const std::string&z8af7e44e6c){setProperty(Id
,id);setProperty(Number,number);setProperty(Name,name);setProperty(Text,text);
setProperty(z564c074eac,z8af7e44e6c);std::vector<unsigned char>data(
getSizeInBytes(),(0xd3b+5483-0x22a6));setProperty(Data,data);}Datapoint::
Datapoint(const Datapoint&datapoint):PropertyCollection(datapoint){}Datapoint::~
Datapoint(){}Datapoint&Datapoint::operator=(const Datapoint&datapoint){
PropertyCollection::operator=(datapoint);return*this;}const std::string&
Datapoint::zebc3066335()const{return z3c6aa0de0f(Id);}int Datapoint::z697f86f0e1
()const{return getProperty(Number);}const std::string&Datapoint::getName()const{
return z3c6aa0de0f(Name);}const std::string&Datapoint::getText()const{return
z3c6aa0de0f(Text);}int Datapoint::zb773295431()const{return getProperty(
z564c074eac);}int Datapoint::getSizeInBytes()const{return getSizeInBytes(
zb773295431());}const std::vector<unsigned char>&Datapoint::getData()const{const
Var&var=getProperty(Data);return var.extract<std::vector<unsigned char> >();}
void Datapoint::setData(const std::vector<unsigned char>&data){setProperty(Data,
data);}const std::string&Datapoint::z3c6aa0de0f(const std::string&key)const{
const Var&var=getProperty(key);return var.extract<std::string>();}int Datapoint
::getSizeInBytes(int z5e1f916d4c)const{return z5e1f916d4c<(0xcd1+4268-0x1d75)?
(0x1485+3422-0x21e2):z5e1f916d4c/(0x1b49+2457-0x24da);}void kdrive::knx::
z6bf2f75cea(Datapoint&datapoint,bool value){const std::vector<unsigned char>data
((0x491+3124-0x10c4),value);setData(datapoint,data,(0x3e6+3395-0x1128));}bool
kdrive::knx::decode_DPT1(const Datapoint&datapoint){return z930e31f79d(datapoint
,(0xf48+2434-0x18c9))?(0x4bd+4319-0x159b):(0x877+4912-0x1ba7);}void kdrive::knx
::encode_DPT2(Datapoint&datapoint,bool zaadaf6ab23,bool value){unsigned char
data=zaadaf6ab23?(0x872+7409-0x2561):(0x64c+5013-0x19e1);if(value){data|=
(0x4c4+3317-0x11b8);}const std::vector<unsigned char>v((0x2df+2945-0xe5f),data);
setData(datapoint,v,(0x1114+1674-0x179d));}void kdrive::knx::decode_DPT2(const
Datapoint&datapoint,bool&zaadaf6ab23,bool&value){const unsigned char data=
z930e31f79d(datapoint,(0x229+1165-0x6b5));zaadaf6ab23=(data&(0x11dc+1001-0x15c3)
)?true:false;value=(data&(0xbf6+3521-0x19b6))?true:false;}void kdrive::knx::
encode_DPT3(Datapoint&datapoint,bool zaadaf6ab23,unsigned char value){const
unsigned char data=(zaadaf6ab23?(0x26f+1394-0x7d9):(0x202+1950-0x9a0))|(value&
(0xa64+1015-0xe54));const std::vector<unsigned char>v((0x52a+454-0x6ef),data);
setData(datapoint,v,(0x25f+4583-0x1445));}void kdrive::knx::decode_DPT3(const
Datapoint&datapoint,bool&zaadaf6ab23,unsigned char&value){const unsigned char
data=z930e31f79d(datapoint,(0xf69+2020-0x174c));zaadaf6ab23=(data&
(0x795+2456-0x1125))?true:false;value=data&(0x1265+2245-0x1b23);}void kdrive::
knx::encode_DPT4(Datapoint&datapoint,unsigned char value){const std::vector<
unsigned char>data((0x1a36+2869-0x256a),value);setData(datapoint,data,
(0x3ef+8104-0x2396));}unsigned char kdrive::knx::decode_DPT4(const Datapoint&
datapoint){return z930e31f79d(datapoint,(0x484+1470-0xa41));}void kdrive::knx::
encode_DPT5(Datapoint&datapoint,unsigned char value){const std::vector<unsigned
char>data((0x1840+3475-0x25d2),value);setData(datapoint,data,(0xef+4057-0x10c7))
;}unsigned char kdrive::knx::decode_DPT5(const Datapoint&datapoint){return
z930e31f79d(datapoint,(0xd32+1760-0x1411));}void kdrive::knx::encode_DPT6(
Datapoint&datapoint,char value){const std::vector<unsigned char>data(
(0xb15+6474-0x245e),static_cast<unsigned char>(value));setData(datapoint,data,
(0x1213+414-0x13b0));}signed char kdrive::knx::decode_DPT6(const Datapoint&
datapoint){return static_cast<signed char>(z930e31f79d(datapoint,
(0x9e3+1294-0xef0)));}void kdrive::knx::encode_DPT7(Datapoint&datapoint,unsigned
short value){setData(datapoint,zd5c4ea2fc7<unsigned short,(0x7d6+6341-0x2099)>(
value),(0x1527+4362-0x262f));}unsigned short kdrive::knx::decode_DPT7(const
Datapoint&datapoint){const std::vector<unsigned char>&data=getData(datapoint,
(0xd87+3212-0x1a11));return ze378c24725<unsigned short,(0x1398+462-0x1564)>(&
data.at((0x1a87+2975-0x2626)),data.size());}void kdrive::knx::encode_DPT8(
Datapoint&datapoint,short value){setData(datapoint,zd5c4ea2fc7<short,
(0xaac+3586-0x18ac)>(value),(0x937+6681-0x234e));}signed short kdrive::knx::
decode_DPT8(const Datapoint&datapoint){const std::vector<unsigned char>&data=
getData(datapoint,(0x16d4+1316-0x1bf6));return ze378c24725<signed short,
(0xd79+2441-0x1700)>(&data.at((0xeb1+5363-0x23a4)),data.size());}void kdrive::
knx::encode_DPT9_Raw(Datapoint&datapoint,unsigned char zba1cbc76ee,unsigned char
z68419f84d9){std::vector<unsigned char>data;data.push_back(zba1cbc76ee);data.
push_back(z68419f84d9);setData(datapoint,data,(0xe91+2746-0x1949));}void kdrive
::knx::encode_DPT9(Datapoint&datapoint,float f){std::tuple<unsigned char,
unsigned char>t=zac29c93fda::zb219ab2908(f);encode_DPT9_Raw(datapoint,std::get<
(0x90+2343-0x9b7)>(t),std::get<(0x249d+356-0x2600)>(t));}unsigned short kdrive::
knx::decode_DPT9_Raw(const Datapoint&datapoint){const std::vector<unsigned char>
&data=getData(datapoint,(0x7f1+1885-0xf4c));return data.at((0x237d+726-0x2653))
<<(0x21d+2395-0xb70)|data.at((0x981+4465-0x1af1));}float kdrive::knx::
decode_DPT9(const Datapoint&datapoint){const std::vector<unsigned char>&data=
getData(datapoint,(0x1060+1571-0x1681));return zac29c93fda::zdfe51b7ee0(data.at(
(0xc90+789-0xfa5)),data.at((0xab1+5615-0x209f)));}void kdrive::knx::
encode_DPT10_Local(Datapoint&datapoint){LocalDateTime now;int day=now.dayOfWeek(
);if(!day){day=(0x13b1+2024-0x1b92);}return encode_DPT10(datapoint,day,now.hour(
),now.minute(),now.second());}void kdrive::knx::encode_DPT10_UTC(Datapoint&
datapoint){DateTime now;int day=now.dayOfWeek();if(!day){day=(0x616+5932-0x1d3b)
;}return encode_DPT10(datapoint,day,now.hour(),now.minute(),now.second());}void
kdrive::knx::encode_DPT10(Datapoint&datapoint,int day,int hour,int minute,int
second){std::vector<unsigned char>data;data.push_back(((day&(0xed7+4010-0x1e7a))
<<(0xe0+5853-0x17b8))|(hour&(0x122d+1869-0x195b)));data.push_back(minute&
(0xd36+523-0xf02));data.push_back(second&(0x1033+3759-0x1ea3));setData(datapoint
,data,(0x9a2+1275-0xe9a));}void kdrive::knx::decode_DPT10(const Datapoint&
datapoint,int&day,int&hour,int&minute,int&second){const std::vector<unsigned
char>&data=getData(datapoint,(0x402+261-0x504));const unsigned char z25275926f1=
data.at((0xe0+2602-0xb0a));const unsigned char ch1=data.at((0x1738+4018-0x26e9))
;const unsigned char z8d438dbe68=data.at((0x115b+4098-0x215b));day=z25275926f1>>
(0x164b+428-0x17f2);hour=z25275926f1&(0xcbf+6131-0x2493);minute=ch1&
(0x136c+976-0x16fd);second=z8d438dbe68&(0xba8+4145-0x1b9a);}void kdrive::knx::
encode_DPT11_Local(Datapoint&datapoint){LocalDateTime now;return z800ccce10f(
datapoint,now.year(),now.month(),now.day());}void kdrive::knx::encode_DPT11_UTC(
Datapoint&datapoint){DateTime now;return z800ccce10f(datapoint,now.year(),now.
month(),now.day());}void kdrive::knx::zdf135c0fa0(Datapoint&datapoint,int year,
int month,int day){encode_DPT11_knx(datapoint,year,month,day);}void kdrive::knx
::encode_DPT11_knx(Datapoint&datapoint,int year,int month,int day){if((year<
(0xd03+4975-0x2072))||(year>(0x24f7+59-0x24cf))){const std::string message=
"\x45\x78\x70\x65\x63\x74\x65\x64\x20\x66\x6f\x72\x20\x79\x65\x61\x72\x3a\x20\x30\x2e\x2e\x39\x39\x2e\x20\x47\x65\x74\x3a\x20"
+std::to_string(year);throw Poco::RangeException(message);}std::vector<unsigned
char>data;data.push_back(day&(0x17e5+3277-0x2493));data.push_back(month&
(0x1470+2071-0x1c78));data.push_back(year&(0xb37+3652-0x18fc));setData(datapoint
,data,(0x1264+4126-0x227f));}void kdrive::knx::z800ccce10f(Datapoint&datapoint,
int year,int month,int day){if((year<(0xccd+1066-0x931))||(year>
(0x1c86+4171-0x24a8))){const std::string message=
"\x45\x78\x70\x65\x63\x74\x65\x64\x20\x66\x6f\x72\x20\x79\x65\x61\x72\x3a\x20\x31\x39\x39\x30\x2e\x2e\x32\x30\x38\x39\x2e\x20\x47\x65\x74\x3a\x20"
+std::to_string(year);throw Poco::RangeException(message);}const int zc404dcd6bb
=(year<(0x125c+5199-0x1edb))?(year-(0xb8c+1432-0x9b8)):(year-
(0x1ea4+3822-0x25c2));encode_DPT11_knx(datapoint,zc404dcd6bb,month,day);}void
kdrive::knx::decode_DPT11(const Datapoint&datapoint,int&year,int&month,int&day){
decode_DPT11_knx(datapoint,year,month,day);}void kdrive::knx::decode_DPT11_knx(
const Datapoint&datapoint,int&year,int&month,int&day){const std::vector<unsigned
char>&data=getData(datapoint,(0x926+7305-0x25ac));const unsigned char
z25275926f1=data.at((0x8f+329-0x1d8));const unsigned char ch1=data.at(
(0x16a1+3449-0x2419));const unsigned char z8d438dbe68=data.at(
(0x1893+3236-0x2535));day=z25275926f1&(0x10bf+5377-0x25a1);month=ch1&
(0x13f+4432-0x1280);year=z8d438dbe68&(0x1485+2289-0x1cf7);}void kdrive::knx::
z4d7301ebb3(const Datapoint&datapoint,int&year,int&month,int&day){int
zc404dcd6bb=(0xe73+4702-0x20d1);decode_DPT11_knx(datapoint,zc404dcd6bb,month,day
);year=(zc404dcd6bb<(0x720+2654-0x1124))?(zc404dcd6bb+(0xe98+7254-0x231e)):
zc404dcd6bb+(0x25bf+699-0x210e);}void kdrive::knx::encode_DPT12(Datapoint&
datapoint,unsigned int value){setData(datapoint,zd5c4ea2fc7<unsigned int,
(0x123+6959-0x1c4e)>(value),(0x467+370-0x5d5));}unsigned int kdrive::knx::
decode_DPT12(const Datapoint&datapoint){const std::vector<unsigned char>&data=
getData(datapoint,(0x152b+1463-0x1ade));return ze378c24725<unsigned int,
(0x9b5+5688-0x1fe9)>(&data.at((0xee1+2272-0x17c1)),data.size());}void kdrive::
knx::encode_DPT13(Datapoint&datapoint,int value){setData(datapoint,zd5c4ea2fc7<
int,(0x1564+2909-0x20bd)>(value),(0xc80+1924-0x1400));}signed int kdrive::knx::
decode_DPT13(const Datapoint&datapoint){const std::vector<unsigned char>&data=
getData(datapoint,(0xaf9+5341-0x1fd2));return ze378c24725<signed int,
(0x5c5+4170-0x160b)>(&data.at((0x1cd1+2038-0x24c7)),data.size());}void kdrive::
knx::encode_DPT14(Datapoint&datapoint,float f){setData(datapoint,zd5c4ea2fc7<
float,(0x568+7858-0x2416)>(f),(0x1abc+2828-0x25c4));}float kdrive::knx::
decode_DPT14(const Datapoint&datapoint){const std::vector<unsigned char>&data=
getData(datapoint,(0xf90+2403-0x18ef));return ze378c24725<float,
(0x14bb+1677-0x1b44)>(&data.at((0x1133+2263-0x1a0a)),data.size());}void kdrive::
knx::encode_DPT15(Datapoint&datapoint,unsigned int z7c361264d7,bool error,bool
z3a4ce83def,bool zbadde329ec,bool zeb54d212c0,unsigned char index){std::vector<
unsigned char>v;v.push_back((z7c361264d7>>(0x372+391-0x4e9))&
(0x198a+1977-0x2044));v.push_back((z7c361264d7>>(0x73c+2196-0xfc8))&
(0x70c+3583-0x140c));v.push_back(z7c361264d7&(0x5c9+3920-0x141a));unsigned char
data=(0x1121+2047-0x1920);if(error){data|=(0xe62+305-0xf13);}if(z3a4ce83def){
data|=(0x34c+7774-0x216a);}if(zbadde329ec){data|=(0x30d+8415-0x23cc);}if(
zeb54d212c0){data|=(0x1df1+1531-0x23dc);}data|=index&(0x1262+4066-0x2235);v.
push_back(data);setData(datapoint,v,(0x1559+2243-0x1e18));}void kdrive::knx::
decode_DPT15(const Datapoint&datapoint,unsigned int&z7c361264d7,bool&error,bool&
z3a4ce83def,bool&zbadde329ec,bool&zeb54d212c0,unsigned char&index){const std::
vector<unsigned char>&data=getData(datapoint,(0x215+8575-0x2390));const unsigned
char z25275926f1=data.at((0xebf+1122-0x1321));const unsigned char ch1=data.at(
(0x60b+925-0x9a7));const unsigned char z8d438dbe68=data.at((0x18a+5578-0x1752));
const unsigned char z2e44465404=data.at((0xfc5+2870-0x1af8));z7c361264d7=(
z25275926f1<<(0x5d8+7531-0x2333))|(ch1<<(0x1cd4+924-0x2068))|z8d438dbe68;error=
z2e44465404&(0x6e7+7609-0x2420)?true:false;z3a4ce83def=z2e44465404&
(0xef4+704-0x1174)?true:false;zbadde329ec=z2e44465404&(0x1063+4037-0x2008)?true:
false;zeb54d212c0=z2e44465404&(0x13ff+3084-0x1ffb)?true:false;index=z2e44465404&
(0x47+8544-0x2198);}void kdrive::knx::encode_DPT16(Datapoint&datapoint,const std
::string&str){static const int zb18c852c31=(0xba8+4511-0x1d39);std::vector<
unsigned char>data;for(char ch:str){data.push_back(static_cast<unsigned char>(ch
));}if(data.size()<zb18c852c31){data.resize(zb18c852c31,(0xc78+3824-0x1b68));}
setData(datapoint,data,zb18c852c31);}std::string kdrive::knx::decode_DPT16(const
Datapoint&datapoint){std::string str;const std::vector<unsigned char>&data=
getData(datapoint,(0x65f+6153-0x1e5a));for(unsigned char ch:data){if(!ch){break;
}str+=static_cast<char>(ch);}return str;}void kdrive::knx::z2c0e220f97(Datapoint
&datapoint,unsigned char zeec3b2b0b5){const std::vector<unsigned char>data(
(0x14ad+4618-0x26b6),zeec3b2b0b5);setData(datapoint,data,(0x183d+1713-0x1eed));}
unsigned char kdrive::knx::z22d5a8ab0f(const Datapoint&datapoint){return
z930e31f79d(datapoint,(0x1ad+2359-0xae3));}void kdrive::knx::zba071ade45(
Datapoint&datapoint,bool zaadaf6ab23,unsigned char zeec3b2b0b5){unsigned char
data=zaadaf6ab23?(0x8bc+6672-0x224c):(0x666+7577-0x23ff);data|=zeec3b2b0b5&
(0x13df+3852-0x22ac);const std::vector<unsigned char>v((0x2410+302-0x253d),data)
;setData(datapoint,v,(0x1167+489-0x134f));}void kdrive::knx::z8015252426(const
Datapoint&datapoint,bool&zaadaf6ab23,unsigned char&zeec3b2b0b5){const unsigned
char data=z930e31f79d(datapoint,(0x1437+275-0x1549));zaadaf6ab23=(data&
(0x1717+3286-0x236d))?true:false;zeec3b2b0b5=data&(0x1594+2284-0x1e41);}void
kdrive::knx::z5e7b87bb95(Datapoint&datapoint,unsigned char r,unsigned char g,
unsigned char b){const std::vector<unsigned char>v={r,g,b};setData(datapoint,v,
(0x379+2492-0xd32));}void kdrive::knx::zc61cae9601(const Datapoint&datapoint,
unsigned char&r,unsigned char&g,unsigned char&b){const std::vector<unsigned char
>&data=getData(datapoint,(0x1cbc+2144-0x2519));r=data.at((0x378+8230-0x239e));g=
data.at((0xc9+5761-0x1749));b=data.at((0x8d4+7669-0x26c7));}
| 75.439252 | 147 | 0.771184 | [
"vector"
] |
631a2d835f797ba0b1bf7cd869399fff896dec36 | 15,260 | hpp | C++ | include/camp/detail/functionimpl.hpp | 16tons/camp | 3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8 | [
"MIT"
] | 1 | 2018-08-07T22:32:55.000Z | 2018-08-07T22:32:55.000Z | include/camp/detail/functionimpl.hpp | 16tons/camp | 3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8 | [
"MIT"
] | null | null | null | include/camp/detail/functionimpl.hpp | 16tons/camp | 3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company.
** Contact: Tegesoft Information (contact@tegesoft.com)
**
** This file is part of the CAMP library.
**
** The MIT License (MIT)
**
** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company.
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
** THE SOFTWARE.
**
****************************************************************************/
#pragma once
#include <camp/args.hpp>
#include <camp/function.hpp>
#include <camp/detail/callhelper.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/assign/list_of.hpp>
namespace camp
{
namespace detail
{
using boost::assign::list_of;
/**
* \brief Helper function which converts an argument to a C++ type
*
* The main purpose of this function is to convert any BadType error to
* a BadArgument one.
*
* \param args List of arguments
* \param index Index of the argument to convert
* \param function Name of the calling function, must be valid
*
* \return Value of args[index] converted to T
*
* \thrown BadArgument conversion triggered a BadType error
*/
template <typename T>
inline typename std::remove_reference<T>::type convertArg(const Args& args, std::size_t index, const char* function)
{
try
{
return args[index].to<typename std::remove_reference<T>::type>();
}
catch (const BadType&)
{
CAMP_ERROR(BadArgument(args[index].type(), mapType<T>(), index, function));
}
}
/**
* \class camp::detail::FunctionImpl
*
* \brief Typed specialization of camp::Function.
*
* The FunctionImpl class is a template which is specialized
* according to the underlying function prototype.
*/
template <typename F1, typename F2 = void> class FunctionImpl;
/*
* Specialization of FunctionImpl for functions taking no argument
*/
template <typename C, typename R>
class FunctionImpl<R (C)> : public Function
{
public:
/**
* \brief Constructor
*/
FunctionImpl(const char* name, boost::function<R (C)> function)
: Function(name, mapType<R>())
, m_function(function)
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args&) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>());
}
private:
boost::function<R (C)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for functions taking 1 argument
*/
template <typename C, typename R, typename A0>
class FunctionImpl<R (C, A0)> : public Function
{
public:
/**
* \brief Constructor
*/
FunctionImpl(const char* name, boost::function<R (C, A0)> function)
: Function(name, mapType<R>(), list_of(mapType<A0>()))
, m_function(function)
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name()));
}
private:
boost::function<R (C, A0)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for functions taking 2 arguments
*/
template <typename C, typename R, typename A0, typename A1>
class FunctionImpl<R (C, A0, A1)> : public Function
{
public:
/**
* \brief Constructor
*/
FunctionImpl(const char* name, boost::function<R (C, A0, A1)> function)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>()))
, m_function(function)
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name()));
}
private:
boost::function<R (C, A0, A1)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for functions taking 3 arguments
*/
template <typename C, typename R, typename A0, typename A1, typename A2>
class FunctionImpl<R (C, A0, A1, A2)> : public Function
{
public:
/**
* \brief Constructor
*/
FunctionImpl(const char* name, boost::function<R (C, A0, A1, A2)> function)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>())(mapType<A2>()))
, m_function(function)
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name())
, convertArg<A2>(args, 2, name()));
}
private:
boost::function<R (C, A0, A1, A2)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for functions taking 4 arguments
*/
template <typename C, typename R, typename A0, typename A1, typename A2, typename A3>
class FunctionImpl<R (C, A0, A1, A2, A3)> : public Function
{
public:
/**
* \brief Constructor
*/
FunctionImpl(const char* name, boost::function<R (C, A0, A1, A2, A3)> function)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>())(mapType<A2>())(mapType<A3>()))
, m_function(function)
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name())
, convertArg<A2>(args, 2, name())
, convertArg<A3>(args, 3, name()));
}
private:
boost::function<R (C, A0, A1, A2, A3)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for functions taking 5 arguments
*/
template <typename C, typename R, typename A0, typename A1, typename A2, typename A3, typename A4>
class FunctionImpl<R (C, A0, A1, A2, A3, A4)> : public Function
{
public:
/**
* \brief Constructor
*/
FunctionImpl(const char* name, boost::function<R (C, A0, A1, A2, A3, A4)> function)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>())(mapType<A2>())(mapType<A3>())(mapType<A4>()))
, m_function(function)
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name())
, convertArg<A2>(args, 2, name())
, convertArg<A3>(args, 3, name())
, convertArg<A4>(args, 4, name()));
}
private:
boost::function<R (C, A0, A1, A2, A3, A4)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for composed functions taking no argument
*/
template <typename C, typename N, typename M, typename R>
class FunctionImpl<R (N), M (C)> : public Function
{
public:
/**
* \brief Constructor
*/
template <typename F1, typename F2>
FunctionImpl(const char* name, F1 function, F2 accessor)
: Function(name, mapType<R>())
, m_function(boost::bind(function, boost::bind(accessor, _1)))
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args&) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>());
}
private:
boost::function<R (C)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for composed functions taking 1 argument
*/
template <typename C, typename N, typename M, typename R, typename A0>
class FunctionImpl<R (N, A0), M (C)> : public Function
{
public:
/**
* \brief Constructor
*/
template <typename F1, typename F2>
FunctionImpl(const char* name, F1 function, F2 accessor)
: Function(name, mapType<R>(), list_of(mapType<A0>()))
, m_function(boost::bind(function, boost::bind(accessor, _1), _2))
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name()));
}
private:
boost::function<R (C, A0)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for composed functions taking 2 arguments
*/
template <typename C, typename N, typename M, typename R, typename A0, typename A1>
class FunctionImpl<R (N, A0, A1), M (C)> : public Function
{
public:
/**
* \brief Constructor
*/
template <typename F1, typename F2>
FunctionImpl(const char* name, F1 function, F2 accessor)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>()))
, m_function(boost::bind(function, boost::bind(accessor, _1), _2, _3))
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name()));
}
private:
boost::function<R (C, A0, A1)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for composed functions taking 3 arguments
*/
template <typename C, typename N, typename M, typename R, typename A0, typename A1, typename A2>
class FunctionImpl<R (N, A0, A1, A2), M (C)> : public Function
{
public:
/**
* \brief Constructor
*/
template <typename F1, typename F2>
FunctionImpl(const char* name, F1 function, F2 accessor)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>())(mapType<A2>()))
, m_function(boost::bind(function, boost::bind(accessor, _1), _2, _3, _4))
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name())
, convertArg<A2>(args, 2, name()));
}
private:
boost::function<R (C, A0, A1, A2)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for composed functions taking 4 arguments
*/
template <typename C, typename N, typename M, typename R, typename A0, typename A1, typename A2, typename A3>
class FunctionImpl<R (N, A0, A1, A2, A3), M (C)> : public Function
{
public:
/**
* \brief Constructor
*/
template <typename F1, typename F2>
FunctionImpl(const char* name, F1 function, F2 accessor)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>())(mapType<A2>())(mapType<A3>()))
, m_function(boost::bind(function, boost::bind(accessor, _1), _2, _3, _4, _5))
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name())
, convertArg<A2>(args, 2, name())
, convertArg<A3>(args, 3, name()));
}
private:
boost::function<R (C, A0, A1, A2, A3)> m_function; ///< Object containing the actual function to call
};
/*
* Specialization of FunctionImpl for composed functions taking 5 arguments
*/
template <typename C, typename N, typename M, typename R, typename A0, typename A1, typename A2, typename A3, typename A4>
class FunctionImpl<R (N, A0, A1, A2, A3, A4), M (C)> : public Function
{
public:
/**
* \brief Constructor
*/
template <typename F1, typename F2>
FunctionImpl(const char* name, F1 function, F2 accessor)
: Function(name, mapType<R>(), list_of(mapType<A0>())(mapType<A1>())(mapType<A2>())(mapType<A3>())(mapType<A4>()))
, m_function(boost::bind(function, boost::bind(accessor, _1), _2, _3, _4, _5, _6))
{
}
protected:
/**
* \see Function::execute
*/
virtual Value execute(const UserObject& object, const Args& args) const override
{
return CallHelper<R, C>::call(m_function, object.get<C>()
, convertArg<A0>(args, 0, name())
, convertArg<A1>(args, 1, name())
, convertArg<A2>(args, 2, name())
, convertArg<A3>(args, 3, name())
, convertArg<A4>(args, 4, name()));
}
private:
boost::function<R (C, A0, A1, A2, A3, A4)> m_function; ///< Object containing the actual function to call
};
} // namespace detail
} // namespace camp
| 29.459459 | 122 | 0.596789 | [
"object"
] |
631cabb217e13957017f83f0ffd99f2e9b6cf737 | 11,087 | cpp | C++ | mpc/kmpc_casadi/casadi_windows/include/casadi/core/convexify.cpp | se-hwan/MIT_Driverless | 7674b29887ba518c134cfba805432f9c98f92270 | [
"MIT"
] | 1 | 2021-11-18T04:28:52.000Z | 2021-11-18T04:28:52.000Z | mpc/kmpc_casadi/casadi_windows/include/casadi/core/convexify.cpp | se-hwan/MIT_Driverless | 7674b29887ba518c134cfba805432f9c98f92270 | [
"MIT"
] | null | null | null | mpc/kmpc_casadi/casadi_windows/include/casadi/core/convexify.cpp | se-hwan/MIT_Driverless | 7674b29887ba518c134cfba805432f9c98f92270 | [
"MIT"
] | 1 | 2022-03-29T10:32:43.000Z | 2022-03-29T10:32:43.000Z | /*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* CasADi 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 CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "convexify.hpp"
using namespace std;
namespace casadi {
std::string strategy_to_string(casadi_convexify_strategy_t s) {
switch (s) {
case CVX_REGULARIZE: return "regularize";
case CVX_EIGEN_REFLECT: return "eigen-reflect";
case CVX_EIGEN_CLIP: return "eigen-clip";
}
return "unknown";
}
Convexify::Convexify(const MX& H, const Dict& opts) {
set_dep(H);
set_sparsity(setup(convexify_data_, H.sparsity(), opts, false));
}
size_t Convexify::sz_iw() const {
return convexify_data_.sz_iw;
}
size_t Convexify::sz_w() const {
return convexify_data_.sz_w;
}
std::string Convexify::disp(const std::vector<std::string>& arg) const {
return "convexify(" + arg.at(0) + ")";
}
void Convexify::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res) const {
Dict options;
options["strategy"] = strategy_to_string(convexify_data_.config.strategy);
options["margin"] = convexify_data_.config.margin;
options["max_iter_eig"] = convexify_data_.config.max_iter_eig;
res[0] = convexify(arg[0], options);
}
int Convexify::eval(const double** arg, double** res, casadi_int* iw, double* w) const {
int ret = convexify_eval(&convexify_data_.config, arg[0], res[0], iw, w);
casadi_assert(!ret, "Failure in convexification.");
return 0;
}
std::string Convexify::generate(CodeGenerator& g,
const ConvexifyData &d,
const std::string& Hin, const std::string& Hout,
const std::string& iw, const std::string& w) {
g.local("cvx_config", "struct casadi_convexify_config");
if (d.config.strategy==CVX_REGULARIZE) {
g << "cvx_config.strategy = CVX_REGULARIZE;\n";
} else if (d.config.strategy==CVX_EIGEN_CLIP) {
g << "cvx_config.strategy = CVX_EIGEN_CLIP;\n";
} else if (d.config.strategy==CVX_EIGEN_REFLECT) {
g << "cvx_config.strategy = CVX_EIGEN_REFLECT;\n";
}
if (d.config.type_in==CVX_SYMM) {
g << "cvx_config.type_in = CVX_SYMM;\n";
} else if (d.config.type_in==CVX_TRIL) {
g << "cvx_config.type_in = CVX_TRIL;\n";
} else if (d.config.type_in==CVX_TRIU) {
g << "cvx_config.type_in = CVX_TRIU;\n";
}
g << "cvx_config.Hsp = " << g.sparsity(d.Hsp) << ";\n";
g << "cvx_config.Hrsp = " << g.sparsity(d.Hrsp) << ";\n";
g << "cvx_config.margin = " << d.config.margin << ";\n";
g << "cvx_config.Hsp_project = " << d.config.Hsp_project << ";\n";
g << "cvx_config.scc_transform = " << d.config.scc_transform << ";\n";
g << "cvx_config.scc_offset = " << g.constant(d.scc_offset) << ";\n";
g << "cvx_config.scc_mapping = " << g.constant(d.scc_mapping) << ";\n";
g << "cvx_config.scc_offset_size = " << d.scc_offset.size() << ";\n";
g << "cvx_config.max_iter_eig = " << d.config.max_iter_eig << ";\n";
g << "cvx_config.verbose = " << d.config.verbose << ";\n";
return "convexify_eval(&cvx_config, " + Hin + "," + Hout + "," + iw + "," + "w)";
}
void Convexify::serialize_body(SerializingStream& s) const {
MXNode::serialize_body(s);
serialize(s, "", convexify_data_);
}
Convexify::Convexify(DeserializingStream& s) : MXNode(s) {
deserialize(s, "", convexify_data_);
}
void Convexify::serialize(SerializingStream& s, const std::string& prefix,
const ConvexifyData& d) {
s.version(prefix + "Convexify", 1);
s.pack(prefix + "Convexify::type_in", static_cast<int>(d.config.type_in));
s.pack(prefix + "Convexify::strategy", static_cast<int>(d.config.strategy));
s.pack(prefix + "Convexify::margin", d.config.margin);
s.pack(prefix + "Convexify::max_iter_eig", d.config.max_iter_eig);
s.pack(prefix + "Convexify::scc_offset", d.scc_offset);
s.pack(prefix + "Convexify::scc_mapping", d.scc_mapping);
s.pack(prefix + "Convexify::Hsp_project", d.config.Hsp_project);
s.pack(prefix + "Convexify::scc_transform", d.config.scc_transform);
s.pack(prefix + "Convexify::verbose", d.config.verbose);
s.pack(prefix + "Convexify::Hsp", d.Hsp);
s.pack(prefix + "Convexify::Hrsp", d.Hrsp);
}
void Convexify::deserialize(DeserializingStream& s, const std::string& prefix,
ConvexifyData& d) {
s.version(prefix + "Convexify", 1);
int type_in;
s.unpack(prefix + "Convexify::type_in", type_in);
d.config.type_in = static_cast<casadi_convexify_type_in_t>(type_in);
int strategy;
s.unpack(prefix + "Convexify::strategy", strategy);
d.config.strategy = static_cast<casadi_convexify_strategy_t>(strategy);
s.unpack(prefix + "Convexify::margin", d.config.margin);
s.unpack(prefix + "Convexify::max_iter_eig", d.config.max_iter_eig);
s.unpack(prefix + "Convexify::scc_offset", d.scc_offset);
s.unpack(prefix + "Convexify::scc_mapping", d.scc_mapping);
s.unpack(prefix + "Convexify::Hsp_project", d.config.Hsp_project);
s.unpack(prefix + "Convexify::scc_transform", d.config.scc_transform);
s.unpack(prefix + "Convexify::verbose", d.config.verbose);
s.unpack(prefix + "Convexify::Hsp", d.Hsp);
s.unpack(prefix + "Convexify::Hrsp", d.Hrsp);
d.config.scc_offset_size = d.scc_offset.size();
// Set pointers
d.config.Hsp = d.Hsp;
d.config.Hrsp = d.Hrsp;;
d.config.scc_offset = get_ptr(d.scc_offset);
d.config.scc_mapping = get_ptr(d.scc_mapping);
}
void Convexify::generate(CodeGenerator& g,
const std::vector<casadi_int>& arg,
const std::vector<casadi_int>& res) const {
std::string ret = g.convexify_eval(convexify_data_,
g.work(arg[0], dep(0).nnz()), g.work(res[0], nnz()), "iw", "w");
g << "if (" << ret << ") return 1;\n";
}
Sparsity Convexify::setup(ConvexifyData& d, const Sparsity& H, const Dict& opts, bool inplace) {
// Validate and categorize matrix input sparsity
casadi_assert(H.is_square(), "Convexify ");
if (H.is_symmetric()) {
d.config.type_in = CVX_SYMM;
} else if (H.is_tril()) {
d.config.type_in = CVX_TRIL;
} else if (H.is_triu()) {
d.config.type_in = CVX_TRIU;
} else {
casadi_error("Convexify operation requires symmetric or triangular input");
}
// Read options
d.config.margin = 1e-7;
d.config.max_iter_eig = 200;
std::string strategy = "eigen-clip";
d.config.verbose = false;
for (auto&& op : opts) {
if (op.first=="strategy") {
strategy = op.second.to_string();
} else if (op.first=="margin") {
d.config.margin = op.second;
casadi_assert(d.config.margin>=0, "Margin must be >=0");
} else if (op.first=="max_iter_eig") {
d.config.max_iter_eig = op.second;
} else if (op.first=="verbose") {
d.config.verbose = op.second;
} else {
casadi_error("Unknown option '" + op.first + "'.");
}
}
// Interpret strategy
if (strategy=="regularize") {
d.config.strategy = CVX_REGULARIZE;
casadi_assert(d.config.type_in==CVX_SYMM, "Only truly symmetric matrices supported");
} else if (strategy=="eigen-reflect") {
d.config.strategy = CVX_EIGEN_REFLECT;
} else if (strategy=="eigen-clip") {
d.config.strategy = CVX_EIGEN_CLIP;
} else {
casadi_error("Invalid convexify strategy. "
"Choose from regularize|eigen-reflect|eigen-clip. Got '" + strategy + "'.");
}
d.Hrsp = H;
d.config.scc_transform = 0;
Sparsity Hrsp = H+H.T();
casadi_int block_size = 0;
Sparsity& Hsp = d.Hsp;
if (d.config.strategy==CVX_EIGEN_REFLECT || d.config.strategy==CVX_EIGEN_CLIP) {
// Uncover strongly connected components
std::vector<casadi_int> scc_index;
casadi_int scc_nb = Hrsp.scc(scc_index, d.scc_offset);
// Represent Hessian as block-dense in permuted space
std::vector<Sparsity> sp;
for (casadi_int i=0;i<scc_nb;++i) {
casadi_int block = d.scc_offset.at(i+1)-d.scc_offset.at(i);
Sparsity stencil;
if (d.config.type_in==CVX_SYMM) {
stencil = Sparsity::dense(block, block);
} else if (d.config.type_in==CVX_TRIL) {
stencil = Sparsity::lower(block);
} else {
stencil = Sparsity::upper(block);
}
sp.push_back(stencil);
}
std::vector<casadi_int> ssc_perm = lookupvector(scc_index);
std::vector<casadi_int> mapping_dummy;
Hsp = diagcat(sp).sub(ssc_perm, ssc_perm, mapping_dummy);
Hsp.sub(scc_index, scc_index, d.scc_mapping);
// Find out size of maximum block
for (casadi_int i=0;i<scc_nb;++i) {
casadi_int block = d.scc_offset.at(i+1)-d.scc_offset.at(i);
if (block>block_size) block_size = block;
}
d.config.scc_transform = d.scc_offset!=range(H.size1());
if (d.config.verbose) casadi_message("Identified " + str(scc_nb) + " blocks "
"with maximum size " + str(block_size) + ".");
} else if (d.config.strategy==CVX_REGULARIZE) {
Hsp = Hrsp + Sparsity::diag(H.size1());
} else {
Hsp = Hrsp;
}
d.config.Hsp_project = Hsp!=Hrsp;
if (d.config.type_in==CVX_TRIL) {
Hsp = Sparsity::tril(Hsp);
} else if (d.config.type_in==CVX_TRIU) {
Hsp = Sparsity::triu(Hsp);
}
d.sz_iw = 0;
if (d.config.strategy==CVX_EIGEN_REFLECT || d.config.strategy==CVX_EIGEN_CLIP) {
d.sz_iw = 1+3* d.config.max_iter_eig;
}
d.sz_w = 0;
if (d.config.strategy==CVX_EIGEN_REFLECT || d.config.strategy==CVX_EIGEN_CLIP) {
d.sz_w = max(block_size, 2*(block_size-1)*d.config.max_iter_eig);
if (d.config.Hsp_project) d.sz_w = max(d.sz_w, Hsp.size1());
if (d.config.scc_transform) d.sz_w += block_size*block_size;
if (inplace) d.sz_w = max(d.sz_w, Hsp.size1()+d.Hrsp.nnz());
}
d.sz_w = Hsp.size1()+d.sz_w;
d.config.scc_offset_size = d.scc_offset.size();
// Set pointers
d.config.Hsp = Hsp;
d.config.Hrsp = d.Hrsp;
d.config.scc_offset = get_ptr(d.scc_offset);
d.config.scc_mapping = get_ptr(d.scc_mapping);
return Hsp;
}
} // namespace casadi
| 37.710884 | 98 | 0.637864 | [
"vector"
] |
6325c4cc07c24f84b6fab9ae06e6c4ea1997ee4c | 75,258 | cpp | C++ | test/main.cpp | SuReLI/naibx-mlc | 89839d475d134bdf9e8628aa8ccb4bcaec7bdaf1 | [
"MIT"
] | null | null | null | test/main.cpp | SuReLI/naibx-mlc | 89839d475d134bdf9e8628aa8ccb4bcaec7bdaf1 | [
"MIT"
] | null | null | null | test/main.cpp | SuReLI/naibx-mlc | 89839d475d134bdf9e8628aa8ccb4bcaec7bdaf1 | [
"MIT"
] | null | null | null | /**@file: main.cpp
*
* @author Luca Mossina
*
* kfold, STARTED: 22 aug 2016
*/
#include <iostream> // std::cin, std::cout
#include <vector>
#include <string> // std:string, std::stod, std::stoi
#include <algorithm> // std::max_element
#include <cstring> //
#include <cstdlib> // std::rand, std::srand
#include <ctime> // std::time
#include <cassert>
#include <chrono>
#include <fstream>
#include "include/managedata.hpp" // ImportData_nbx(), print_vector()
#include "include/naibx.hpp"
#include "include/metrics.hpp" // HammingLoss(), Accuracy(), ...
#include "include/bownaibx.hpp"
int main(int argc, char const *argv[])
{
/* Input parameters */
int num_features = 0, num_of_labels = 0; //, train_samples = 0;
int keep = 1; // obsolete
// bool see_m = false;
int avg_m = 0;
bool hamming = false, accuracy = false, precision = false;
bool zeroone = false, recall = false; //, f = false;
bool all = true; // if true, compute all loss metrics
bool load_model = false, save_model = false;
bool real_m = false;
bool laplacian_smoothing = true;
// bool print_original = false;
bool print_prediction = false;
bool save_output = false;
// bool top_m = true;
bool no_print = true;
// bool return_sizes = false;
std::string my_arff;
// bool import_data_in_nbx = false;
// bool import_data_in_arff = true;
int kfold = 1; // if 1, no k-fold cross-validation
double cv_split = 0.66; // default CV split ratio
int testfold = 0; // which partition to use for testing
std::string import_model, export_model; // names of handled models
std::string arg; // store argv[i], user input from command line
std::string data_format;
bool shufflerows = true;
bool bow_input = false;
bool bernoulli_bow = false;
int first_valid_data_column = 0; // ignore columns up to this one
bool features_first = true;
int features_numbering_starts_at = 0;
typedef std::chrono::high_resolution_clock clock;
double time_elapsed;
std::chrono::time_point<clock> start_count_time;
std::vector<double> labcard; // store folds cardinalities (estimated)
double training_time = 0.0;
double prediction_time = 0.0;
/* Parse command line parameters */
// PARSE: NO PRINT
for (int i = 1; i < argc; i++) {
arg = argv[i];
if (arg.find("no_print") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
if (input_value == "true") {
no_print = true;
}
}
}
// PARSE: HELP & OPTIONAL parameters
for (int i = 1; i < argc; i++) {
arg = argv[i];
// HELP requested?
if ((arg == "-h") || (arg == "--help")) {
std::cout << "--help [-h]: print this help message." << std::endl;;
std::cout << "" << std::endl;
std::cout << "dim_x:\tnumber of features in dataset" << std::endl;
std::cout << "labels:\tnumber of labels in dataset" << std::endl;
std::cout << "train:\tnumber of training samples" << std::endl;
std::cout << "EXAMPLE of usage:" << std::endl;
std::cout << argv[0] << " < ~/path/to/data dim_x=12 labels=3 train=1500 [hamming]" << std::endl;;
return 1; // EXIT main
}
// PRINT list of optional parameters
if ((arg == "-o") || (arg == "--optional")) {
std::cout << "optional input parameters:\n" << std::endl;
std::cout << "hamming: return hamming loss" << std::endl;
std::cout << "precision: ..." << std::endl;
// TODO: add the rest
return 1;
}
}
// PARSE: model parameters: dim(feature space), number of target labels etc..
for (int i = 1; i < argc; i++) {
arg = argv[i];
// Number of features, i.e. explanatory variables
if (arg.find("format") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
data_format = (input_value);
}
// data path
if (arg.find("data") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
my_arff = (input_value);
std::cout << "Input file: " << my_arff << std::endl;
}
// Number of features, i.e. explanatory variables
if (arg.find("dim_x") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
num_features = stoi(input_value);
}
if (arg.find("--bow") != std::string::npos) {
bow_input = true; // load model!!
std::cout << " --- Features are (multinomial) Bag-of-Words" << import_model << std::endl;
}
if (arg.find("--bernoulli") != std::string::npos) {
bernoulli_bow = true; // load model!!
std::cout << " --- Features are (bernoulli) Bag-of-Words" << import_model << std::endl;
}
if (arg.find("--no_shuffle") != std::string::npos) {
shufflerows = false; // load model!!
std::cout << " --- Entry row were NOT shuffled." << import_model << std::endl;
}
if (arg.find("skip") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
first_valid_data_column = stoi(input_value);
std::cout << "first_valid_data_column = " << first_valid_data_column << std::endl;
}
// Num of labels. if Y = {0, 1, ... K} => we have K+1 labels
if (arg.find("labels") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
num_of_labels = stoi(input_value);
}
if (arg.find("-lab_first") != std::string::npos) {
//std::size_t pos = arg.find("=");
//std::string input_value = arg.substr(pos + 1);
std::cout << "labels preceed features" << std::endl;
features_first = false;
}
if (arg.find("keep") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
keep = stoi(input_value);
}
if (arg.find("features_numbering_starts_at") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
features_numbering_starts_at = stoi(input_value);
}
// cross-validation split ratio
if (arg.find("cv_split") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
cv_split = stof(input_value);
if (!no_print) {
std::cout << "CV on " << cv_split*100 << "% of data" << std::endl;
}
}
// k-fold cross-validation. HOW MANY FOLDS:
if (arg.find("kfold") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
kfold = stoi(input_value);
if (!no_print) {
std::cout << "kfold = " << kfold << std::endl;
}
}
// TEMP HACK: specify which fold to use as TEST. specified by hand, to be reimplemented
// if (arg.find("testfold") != std::string::npos) {
// std::size_t pos = arg.find("=");
// std::string input_value = arg.substr(pos + 1);
// testfold = (stoi(input_value) - 1);
//
// // user must give a value in range: {1, 2, ..., K}, where K=numfolds
// assert(testfold >= 0 && testfold <= (kfold-1) && "specify TEST fold in range [1...kfold]");
// if (no_print) {
// std::cout << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")" << std::endl;
// }
// }
// /* top_m m */
// if (arg.find("top_m") != std::string::npos) {
// std::size_t pos = arg.find("=");
// std::string input_value = arg.substr(pos + 1);
//
// if (input_value == "true") {
// top_m = true;
// if (!no_print) {
// std::cout << "top_m:\tTRUE" << std::endl;
// }
// }
// }
// This option will prevent the algo from estimating "m", the length of the target vector
//
if (arg.find("real_m") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
if (input_value == "true") {
real_m = true;
if (!no_print) {
std::cout << "real_m:\tTRUE" << std::endl;
}
}
}
// if (arg.find("see_m") != std::string::npos) {
// std::size_t pos = arg.find("=");
// std::string input_value = arg.substr(pos + 1);
// if (input_value == "true") {
// see_m = true;
// if (!no_print) {
// std::cout << "real_m:\tTRUE" << std::endl;
// }
// }
// }
// specify by hand the size of target vectors
if (arg.find("avg_m") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
avg_m = stoi(input_value);
if (!no_print) {
std::cout << "avg_m = " << avg_m << std::endl;
}
}
// if (arg.find("print_original") != std::string::npos) {
// std::size_t pos = arg.find("=");
// std::string input_value = arg.substr(pos + 1);
//
// if (input_value == "true") {
// print_original = true;
// if (!no_print) {
// std::cout << "print_original:\tTRUE" << std::endl;
// }
// }
// }
if (arg.find("print_prediction") != std::string::npos) {
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
if (input_value == "true") {
print_prediction = true;
std::cout << "print_prediction:\tTRUE" << std::endl;
}
}
// if (arg.find("return_sizes") != std::string::npos) {
// std::size_t pos = arg.find("=");
// std::string input_value = arg.substr(pos + 1);
//
// if (input_value == "true") {
// return_sizes = true;
// if (!no_print) {
// std::cout << "return_sizes:\tTRUE" << std::endl;
// }
// }
// }
if (arg.find("load") != std::string::npos) {
load_model = true; // load model!!
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
import_model = input_value;
std::cout << "imported model: " << import_model << std::endl;
}
if (arg.find("save_model") != std::string::npos) {
save_model = true; // save_model model!!
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
export_model = input_value;
std::cout << "export model as: " << export_model << std::endl;
}
if (arg.find("save_output") != std::string::npos) {
save_output = true; // save_output model!!
std::size_t pos = arg.find("=");
std::string input_value = arg.substr(pos + 1);
export_model = input_value;
std::cout << "saving output in: " << export_model << std::endl;
}
}
// PARSE: optional arguments for loss metrics
for (int i = 1; i < argc; i++) {
arg = argv[i];
if (arg == "all") {
all = true;
break; // all metrics will be calculated
}
else if (arg == "hamming") {
hamming = true;
}
else if (arg == "zeroone") {
zeroone = true;
}
else if (arg == "accuracy") {
accuracy = true;
}
else if (arg == "recall") {
recall = true;
}
else if (arg == "precision") {
precision = true;
}
// else if (arg == "f") {
// f = true;
// }
}
/* import input_raw_data */
// init CONTAINERS
std::vector<std::vector<double> > cont_feat_array; // 2D vector to store explanatory variables
std::vector<std::map<int, int>> count_features_bow; // BOW features container
std::vector<std::map<int, double>> double_features_bow; // BOW features container
std::vector<std::vector<int> > labels_2D_array; // 2D vector to store labels
std::vector<std::string> input_raw_data; // container of raw data: all inputs as a string
std::vector<double> temp_features; // store one row, i.e. one observation (sample)
std::vector<int> temp_labels; // store one row, i.e. one observation (sample)
std::vector<int> observed_m; // store observed "m", to compare with predicted "m"
// Populate data containers
if (bow_input || bernoulli_bow){
ImportData_arff(
my_arff,
num_features, num_of_labels,
count_features_bow, labels_2D_array, observed_m,
shufflerows,
first_valid_data_column,
features_first,
features_numbering_starts_at);
}
else {
ImportData_arff(
my_arff,
num_features, num_of_labels,
cont_feat_array, labels_2D_array, observed_m,
shufflerows,
first_valid_data_column,
features_first);
}
/* Observed Label Cardinality */
int how_many_labs = 0;
for (int size : observed_m) how_many_labs += size;
int numobs = observed_m.size();
std::cout << "Label cardinality (OBSERVED) whole dataset = " << (double) how_many_labs/numobs << std::endl;
int lenfeat;
size_t nrows;
if (bow_input || bernoulli_bow) {
lenfeat = count_features_bow.size();
nrows = count_features_bow.size(); // nrow(dataset)
}
else {
lenfeat = cont_feat_array.size();
nrows = cont_feat_array.size(); // nrow(dataset)
}
int lenlab = labels_2D_array.size(); // nrow(dataset)
assert(lenfeat == lenlab && "problems with imported data. nrow features != nrow labels");
/* LOSS MEASURE CONTAINERS */
std::vector<double> hl_vec; std::vector<double> zo_vec;
std::vector<double> ac_vec; std::vector<double> re_vec;
std::vector<double> pr_vec;
/*
* Data-partition: SPLIT cross-validation
*/
if (save_model) {
cv_split = 1; // use all data to train model
std::cout << "all data used to TRAIN model" << std::endl;
}
if (load_model) {
cv_split = 0; // use all data to train model
std::cout << "all data used to PREDICT model" << std::endl;
}
if (bernoulli_bow) {
// std::cout << "ERROR: Bernoulli implementation is broken, use --bow" << std::endl;
// return 666;
// containers for CV procedure
std::vector<std::map<int, int> > training_expl;
std::vector<std::map<int, int> > test_features;
std::vector<std::vector<int> > training_labels;
std::vector<std::vector<int> > test_labels;
std::vector<int> observed_m_training;
std::vector<int> observed_m_test;
if (kfold == 1) {
/* TODO: implement function */
/* SPLIT: TRAINING vs TESTING */
// compute number of rows to be used in training
int const train_size = (int) count_features_bow.size() * cv_split;
// partition features
std::vector<std::map<int, int> > training_expl_TEMP(count_features_bow.begin(), count_features_bow.begin() + train_size);
std::vector<std::map<int, int> > test_features_TEMP(count_features_bow.begin() + train_size, count_features_bow.end());
// partition labels
std::vector<std::vector<int> > training_labels_TEMP(labels_2D_array.begin(), labels_2D_array.begin() + train_size);
std::vector<std::vector<int> > test_labels_TEMP(labels_2D_array.begin() + train_size, labels_2D_array.end());
// partition m: observed number of labels
std::vector<int> observed_m_training_TEMP(observed_m.begin(), observed_m.begin() + train_size);
std::vector<int> observed_m_test_TEMP(observed_m.begin() + train_size, observed_m.end());
training_expl.swap(training_expl_TEMP);
test_features.swap(test_features_TEMP);
training_labels.swap(training_labels_TEMP);
test_labels.swap(test_labels_TEMP);
observed_m_training.swap(observed_m_training_TEMP);
observed_m_test.swap(observed_m_test_TEMP);
/* TRAINING model */
assert( (training_expl.size() + test_features.size()) == nrows && "lost some observations during CV split");
/* STEP 1: init Classifier */
BernoulliBowNaibx my_naibx(num_features, num_of_labels, laplacian_smoothing, keep);
/* STEP 2: TRAINING the predictor with user inputs */
int learn_size = training_expl.size();
if (load_model == true) {
my_naibx.load_my_model(import_model);
}
else {
start_count_time = clock::now();
// train model, line by line
for (int i = 0; i < learn_size; i++) {
my_naibx.add_example(count_features_bow.at(i), labels_2D_array.at(i));
}
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
training_time += time_elapsed;
}
/* STEP 3: store model for future use */
if (save_model == true) {
my_naibx.save_model(export_model);
}
/* APPLICATION of Model to dataset */
// test obs vs predicted in training set
std::vector<std::vector<int> > predictions_on_testing;
std::vector<std::vector<int> > top_k_predictions;
std::vector<int> temp_pred; // store temp prediction labels[i]
/* Prediction on TEST Partition */
// int show_pred = 500;
// int iter = 0;
// const int tot_pred_steps = test_features.size();
// typedef std::chrono::high_resolution_clock clock;
start_count_time = clock::now();
for (auto it = test_features.begin(); it != test_features.end(); ++it) {
top_k_predictions.clear();
temp_pred.clear();
/* Good Ol NaiBX */
auto i = std::distance(test_features.begin(), it); // get i index
temp_pred = my_naibx.predict_y(*it, temp_pred, observed_m_test.at(i), real_m);
predictions_on_testing.push_back(temp_pred);
}
// std::cout << "" << std::endl;
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
prediction_time += time_elapsed;
/* OUTPUT results to file */
if ( save_output == true ) {
if (real_m == true) {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
else {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
}
// could be done directly inside naibx. Dumb shortcut here, re-computing m
std::vector<int> predicted_m_on_testing;
for (size_t i = 0; i < predictions_on_testing.size(); i++) {
predicted_m_on_testing.push_back(predictions_on_testing.at(i).size());
// PrintVector(predictions_on_testing.at(i));
// std::cout << "gino: " << predictions_on_testing.at(i).size() << std::endl;
}
double how_many_labs_pred = 0;
double how_many_labs_obs = 0;
for (int size : observed_m_test) how_many_labs_obs += size;
for (int size : predicted_m_on_testing) how_many_labs_pred += size;
size_t numobs_pred = predicted_m_on_testing.size();
// size_t numobs_obs = observed_m_test.size();
labcard.push_back( (double) how_many_labs_pred/numobs_pred);
/* LOSS MEASURES */
// std::cout << "LabelAccuracy:" << std::endl;
// LabelAccuracy(test_labels , predictions_on_testing, num_of_labels);
if (hamming == true || all == true) {
double hloss = HammingLoss(test_labels , predictions_on_testing, num_of_labels);
hl_vec.push_back(hloss);
std::string metric = "hamming";
if (save_output == true) {
ExportMetrics(my_arff, metric, hloss, real_m);
}
}
if (zeroone == true || all == true) {
double loss_m = ZeroOneLoss(test_labels , predictions_on_testing);
zo_vec.push_back(loss_m);
std::string metric = "zeroone";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (accuracy == true || all == true) {
double loss_m = Accuracy(test_labels , predictions_on_testing);
ac_vec.push_back(loss_m);
std::string metric = "accuracy";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (precision == true || all == true) {
double loss_m = Precision(test_labels , predictions_on_testing);
pr_vec.push_back(loss_m);
std::string metric = "precision";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (recall == true || all == true) {
double loss_m = Recall(test_labels , predictions_on_testing);
re_vec.push_back(loss_m);
std::string metric = "recall";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
}
/* Data-partition: K-FOLD validation */
if (kfold > 1) {
std::vector<int> fold_sizes = KFoldIndexes(nrows, kfold);
for (int i = 0; i < kfold; i++) {
// for (size_t i = 0; i < kfold; i++) {
testfold = i;
std::cout << "\n --- partition n." << (testfold + 1) << " --- " << std::endl;
SplitDataForKFold(
testfold, kfold,
// imported data
labels_2D_array, count_features_bow, observed_m,
// containers for CV procedure
fold_sizes,
training_expl, test_features,
training_labels, test_labels,
observed_m_training, observed_m_test);
/* TRAINING model */
assert(training_expl.size() + test_features.size() == nrows && "lost some observations during CV split");
/* STEP 1: init Classifier */
BernoulliBowNaibx my_naibx(num_features, num_of_labels, laplacian_smoothing, keep);
/* STEP 2: TRAINING the predictor with user inputs */
int learn_size = training_expl.size();
if (load_model == true) {
my_naibx.load_my_model(import_model);
}
else {
start_count_time = clock::now();
// train model, line by line
for (int i = 0; i < learn_size; i++) {
my_naibx.add_example(count_features_bow.at(i), labels_2D_array.at(i));
}
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
training_time += time_elapsed;
}
/* STEP 3: store model for future use */
if (save_model == true) {
my_naibx.save_model(export_model);
}
/* APPLICATION of Model to dataset */
// test obs vs predicted in training set
std::vector<std::vector<int> > predictions_on_testing;
std::vector<int> temp_pred; // store temp prediction labels[i]
/* Prediction on TEST Partition */
start_count_time = clock::now();
for (auto it = test_features.begin(); it != test_features.end(); ++it) {
temp_pred.clear();
/* Good Ol NaiBX */
auto i = std::distance(test_features.begin(), it); // get i index
temp_pred = my_naibx.predict_y(*it, temp_pred, observed_m_test.at(i), real_m);
predictions_on_testing.push_back(temp_pred);
}
// std::cout << "" << std::endl;
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
prediction_time += time_elapsed;
/* OUTPUT results to file */
if ( save_output == true ) {
if (real_m == true) {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
else {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
}
// could be done directly inside naibx. Dumb shortcut here, re-computing m
std::vector<int> predicted_m_on_testing;
for (size_t i = 0; i < predictions_on_testing.size(); i++) {
predicted_m_on_testing.push_back(predictions_on_testing.at(i).size());
// PrintVector(predictions_on_testing.at(i));
}
if (print_prediction) {
ComparePredictions(predictions_on_testing, test_labels);
}
double how_many_labs_pred = 0;
double how_many_labs_obs = 0;
for (int size : observed_m_test) how_many_labs_obs += size;
for (int size : predicted_m_on_testing) how_many_labs_pred += size;
// std::cout << "obser m" << std::endl;PrintVector(observed_m_test);
// std::cout << "predicted_m_on_testing" << std::endl;PrintVector(predicted_m_on_testing);
size_t numobs_pred = predicted_m_on_testing.size();
// size_t numobs_obs = observed_m_test.size();
labcard.push_back( (double) how_many_labs_pred/numobs_pred);
// std::cout << "test partition, LCard (OBSERVED) = " << (double) how_many_labs_obs/numobs_obs << std::endl;
/* LOSS MEASURES */
// std::cout << "LabelAccuracy:" << std::endl;
// LabelAccuracy(test_labels , predictions_on_testing, num_of_labels);
if (hamming == true || all == true) {
double hloss = HammingLoss(test_labels , predictions_on_testing, num_of_labels);
hl_vec.push_back(hloss);
// std::cout << "Hamming = " << hloss << std::endl;
std::string metric = "hamming";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, hloss, real_m);
// }
}
if (zeroone == true || all == true) {
double loss_m = ZeroOneLoss(test_labels , predictions_on_testing);
zo_vec.push_back(loss_m);
// std::cout << "ZeroOne = " << loss_m << std::endl;
std::string metric = "zeroone";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (accuracy == true || all == true) {
double loss_m = Accuracy(test_labels , predictions_on_testing);
ac_vec.push_back(loss_m);
// std::cout << "Accuracy = " << loss_m << std::endl;
std::string metric = "accuracy";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (precision == true || all == true) {
double loss_m = Precision(test_labels , predictions_on_testing);
pr_vec.push_back(loss_m);
// std::cout << "Precision = " << loss_m << std::endl;
std::string metric = "precision";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (recall == true || all == true) {
double loss_m = Recall(test_labels , predictions_on_testing);
re_vec.push_back(loss_m);
// std::cout << "Recall = " << loss_m << std::endl;
std::string metric = "recall";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
}
}
}
else if (bow_input) { // BoW input data, integer frequencies
// containers for CV procedure
std::vector<std::map<int, int> > training_expl;
std::vector<std::map<int, int> > test_features;
std::vector<std::vector<int> > training_labels;
std::vector<std::vector<int> > test_labels;
std::vector<int> observed_m_training;
std::vector<int> observed_m_test;
if (kfold == 1) {
/* TODO: implement function */
/* SPLIT: TRAINING vs TESTING */
// compute number of rows to be used in training
int const train_size = (int) count_features_bow.size() * cv_split;
// partition features
std::vector<std::map<int, int> > training_expl_TEMP(count_features_bow.begin(), count_features_bow.begin() + train_size);
std::vector<std::map<int, int> > test_features_TEMP(count_features_bow.begin() + train_size, count_features_bow.end());
// partition labels
std::vector<std::vector<int> > training_labels_TEMP(labels_2D_array.begin(), labels_2D_array.begin() + train_size);
std::vector<std::vector<int> > test_labels_TEMP(labels_2D_array.begin() + train_size, labels_2D_array.end());
// partition m: observed number of labels
std::vector<int> observed_m_training_TEMP(observed_m.begin(), observed_m.begin() + train_size);
std::vector<int> observed_m_test_TEMP(observed_m.begin() + train_size, observed_m.end());
training_expl.swap(training_expl_TEMP);
test_features.swap(test_features_TEMP);
training_labels.swap(training_labels_TEMP);
test_labels.swap(test_labels_TEMP);
observed_m_training.swap(observed_m_training_TEMP);
observed_m_test.swap(observed_m_test_TEMP);
/* TRAINING model */
assert(training_expl.size() + test_features.size() == nrows && "lost some observations during CV split");
/* STEP 1: init Classifier */
BowNaibx my_naibx(num_features, num_of_labels, laplacian_smoothing, keep);
/* STEP 2: TRAINING the predictor with user inputs */
int learn_size = training_expl.size();
if (load_model == true) {
my_naibx.load_my_model(import_model);
}
else {
start_count_time = clock::now();
// train model, line by line
for (int i = 0; i < learn_size; i++) {
my_naibx.add_example(count_features_bow.at(i), labels_2D_array.at(i));
}
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
training_time += time_elapsed;
}
/* STEP 3: store model for future use */
if (save_model == true) {
my_naibx.save_model(export_model);
}
/* APPLICATION of Model to dataset */
// test obs vs predicted in training set
std::vector<std::vector<int> > predictions_on_testing;
std::vector<std::vector<int> > top_k_predictions;
std::vector<int> temp_pred; // store temp prediction labels[i]
/* Prediction on TEST Partition */
// int show_pred = 500;
// int iter = 0;
// const int tot_pred_steps = test_features.size();
// typedef std::chrono::high_resolution_clock clock;
start_count_time = clock::now();
for (auto it = test_features.begin(); it != test_features.end(); ++it) {
top_k_predictions.clear();
temp_pred.clear();
/* Good Ol NaiBX */
auto i = std::distance(test_features.begin(), it); // get i index
temp_pred = my_naibx.predict_y(*it, temp_pred, observed_m_test.at(i), real_m);
predictions_on_testing.push_back(temp_pred);
}
// std::cout << "" << std::endl;
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
prediction_time += time_elapsed;
/* OUTPUT results to file */
if ( save_output == true ) {
if (real_m == true) {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
else {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
}
// could be done directly inside naibx. Dumb shortcut here, re-computing m
std::vector<int> predicted_m_on_testing;
for (size_t i = 0; i < predictions_on_testing.size(); i++) {
predicted_m_on_testing.push_back(predictions_on_testing.at(i).size());
// PrintVector(predictions_on_testing.at(i));
// std::cout << "gino: " << predictions_on_testing.at(i).size() << std::endl;
}
double how_many_labs_pred = 0;
double how_many_labs_obs = 0;
for (int size : observed_m_test) how_many_labs_obs += size;
for (int size : predicted_m_on_testing) how_many_labs_pred += size;
size_t numobs_pred = predicted_m_on_testing.size();
// size_t numobs_obs = observed_m_test.size();
labcard.push_back( (double) how_many_labs_pred/numobs_pred);
/* LOSS MEASURES */
// std::cout << "LabelAccuracy:" << std::endl;
// LabelAccuracy(test_labels , predictions_on_testing, num_of_labels);
if (hamming == true || all == true) {
double hloss = HammingLoss(test_labels , predictions_on_testing, num_of_labels);
hl_vec.push_back(hloss);
std::string metric = "hamming";
if (save_output == true) {
ExportMetrics(my_arff, metric, hloss, real_m);
}
}
if (zeroone == true || all == true) {
double loss_m = ZeroOneLoss(test_labels , predictions_on_testing);
zo_vec.push_back(loss_m);
std::string metric = "zeroone";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (accuracy == true || all == true) {
double loss_m = Accuracy(test_labels , predictions_on_testing);
ac_vec.push_back(loss_m);
std::string metric = "accuracy";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (precision == true || all == true) {
double loss_m = Precision(test_labels , predictions_on_testing);
pr_vec.push_back(loss_m);
std::string metric = "precision";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (recall == true || all == true) {
double loss_m = Recall(test_labels , predictions_on_testing);
re_vec.push_back(loss_m);
std::string metric = "recall";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
}
/* Data-partition: K-FOLD validation */
if (kfold > 1) {
const std::vector<int> fold_sizes = KFoldIndexes(nrows, kfold);
for (int i = 0; i < kfold; i++) {
testfold = i;
std::cout << "\n --- partition n." << (testfold + 1) << " --- " << std::endl;
SplitDataForKFold(
testfold, kfold,
// imported data
labels_2D_array, count_features_bow, observed_m,
// containers for CV procedure
fold_sizes,
training_expl, test_features,
training_labels, test_labels,
observed_m_training, observed_m_test);
/* TRAINING model */
assert(training_expl.size() + test_features.size() == nrows && "lost some observations during CV split");
/* STEP 1: init Classifier */
BowNaibx my_naibx(num_features, num_of_labels, laplacian_smoothing, keep);
/* STEP 2: TRAINING the predictor with user inputs */
int learn_size = training_expl.size();
if (load_model == true) {
my_naibx.load_my_model(import_model);
}
else {
start_count_time = clock::now();
// train model, line by line
for (int i = 0; i < learn_size; i++) {
my_naibx.add_example(count_features_bow.at(i), labels_2D_array.at(i));
}
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
training_time += time_elapsed;
}
/* STEP 3: store model for future use */
if (save_model == true) {
my_naibx.save_model(export_model);
}
/* APPLICATION of Model to dataset */
// test obs vs predicted in training set
std::vector<std::vector<int> > predictions_on_testing;
// std::vector<std::vector<int> > top_k_predictions;
std::vector<int> temp_pred; // store temp prediction labels[i]
/* Prediction on TEST Partition */
// int show_pred = 500;
// int iter = 0;
// const int tot_pred_steps = test_features.size();
// typedef std::chrono::high_resolution_clock clock;
start_count_time = clock::now();
for (auto it = test_features.begin(); it != test_features.end(); ++it) {
// top_k_predictions.clear();
// ++iter;
// // if (!no_print) {
// if (iter % show_pred == 0) {
// std::cout << (double) iter/tot_pred_steps * 100 << "% (done)" << std::endl;
// }
// // }
temp_pred.clear();
/* Good Ol NaiBX */
auto i = std::distance(test_features.begin(), it); // get i index
temp_pred = my_naibx.predict_y(*it, temp_pred, observed_m_test.at(i), real_m);
predictions_on_testing.push_back(temp_pred);
}
// std::cout << "" << std::endl;
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
prediction_time += time_elapsed;
/* OUTPUT results to file */
if ( save_output == true ) {
if (real_m == true) {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
else {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
}
// could be done directly inside naibx. Dumb shortcut here, re-computing m
std::vector<int> predicted_m_on_testing;
for (size_t i = 0; i < predictions_on_testing.size(); i++) {
predicted_m_on_testing.push_back(predictions_on_testing.at(i).size());
// PrintVector(predictions_on_testing.at(i));
// std::cout << "gino: " << predictions_on_testing.at(i).size() << std::endl;
}
if (print_prediction) {
ComparePredictions(predictions_on_testing, test_labels);
}
double how_many_labs_pred = 0;
double how_many_labs_obs = 0;
for (int size : observed_m_test) how_many_labs_obs += size;
for (int size : predicted_m_on_testing) how_many_labs_pred += size;
// std::cout << "obser m" << std::endl;PrintVector(observed_m_test);
// std::cout << "predicted_m_on_testing" << std::endl;PrintVector(predicted_m_on_testing);
size_t numobs_pred = predicted_m_on_testing.size();
// size_t numobs_obs = observed_m_test.size();
labcard.push_back( (double) how_many_labs_pred/numobs_pred);
// std::cout << "test partition, LCard (OBSERVED) = " << (double) how_many_labs_obs/numobs_obs << std::endl;
/* LOSS MEASURES */
// std::cout << "LabelAccuracy:" << std::endl;
// LabelAccuracy(test_labels , predictions_on_testing, num_of_labels);
if (hamming == true || all == true) {
double hloss = HammingLoss(test_labels , predictions_on_testing, num_of_labels);
hl_vec.push_back(hloss);
// std::cout << "Hamming = " << hloss << std::endl;
std::string metric = "hamming";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, hloss, real_m);
// }
}
if (zeroone == true || all == true) {
double loss_m = ZeroOneLoss(test_labels , predictions_on_testing);
zo_vec.push_back(loss_m);
// std::cout << "ZeroOne = " << loss_m << std::endl;
std::string metric = "zeroone";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (accuracy == true || all == true) {
double loss_m = Accuracy(test_labels , predictions_on_testing);
ac_vec.push_back(loss_m);
// std::cout << "Accuracy = " << loss_m << std::endl;
std::string metric = "accuracy";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (precision == true || all == true) {
double loss_m = Precision(test_labels , predictions_on_testing);
pr_vec.push_back(loss_m);
// std::cout << "Precision = " << loss_m << std::endl;
std::string metric = "precision";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (recall == true || all == true) {
double loss_m = Recall(test_labels , predictions_on_testing);
re_vec.push_back(loss_m);
// std::cout << "Recall = " << loss_m << std::endl;
std::string metric = "recall";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
}
}
}
else { // Continuous input data, X in R^d
// containers for CV procedure
std::vector<std::vector<double> > training_expl;
std::vector<std::vector<double> > test_features;
std::vector<std::vector<int> > training_labels;
std::vector<std::vector<int> > test_labels;
std::vector<int> observed_m_training;
std::vector<int> observed_m_test;
if (kfold == 1) {
/* TODO: implement function */
/* SPLIT: TRAINING vs TESTING */
// compute number of rows to be used in training
int const train_size = (int) lenfeat * cv_split;
// partition features
std::vector<std::vector<double> > training_expl_TEMP(cont_feat_array.begin(), cont_feat_array.begin() + train_size);
std::vector<std::vector<double> > test_features_TEMP(cont_feat_array.begin() + train_size, cont_feat_array.end());
// partition labels
std::vector<std::vector<int> > training_labels_TEMP(labels_2D_array.begin(), labels_2D_array.begin() + train_size);
std::vector<std::vector<int> > test_labels_TEMP(labels_2D_array.begin() + train_size, labels_2D_array.end());
// partition m: observed number of labels
std::vector<int> observed_m_training_TEMP(observed_m.begin(), observed_m.begin() + train_size);
std::vector<int> observed_m_test_TEMP(observed_m.begin() + train_size, observed_m.end());
training_expl.swap(training_expl_TEMP);
test_features.swap(test_features_TEMP);
training_labels.swap(training_labels_TEMP);
test_labels.swap(test_labels_TEMP);
observed_m_training.swap(observed_m_training_TEMP);
observed_m_test.swap(observed_m_test_TEMP);
/* TRAINING model */
assert(training_expl.size() + test_features.size() == nrows && "lost some observations during CV split");
/* STEP 1: init Classifier */
Naibx my_naibx(num_features, num_of_labels, laplacian_smoothing, keep);
/* STEP 2: TRAINING the predictor with user inputs */
int learn_size = training_expl.size();
if (load_model == true) {
my_naibx.load_my_model(import_model);
}
else {
start_count_time = clock::now();
// train model, line by line
for (int i = 0; i < learn_size; i++) {
my_naibx.add_example(cont_feat_array.at(i), labels_2D_array.at(i));
}
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
training_time += time_elapsed;
}
/* STEP 3: store model for future use */
if (save_model == true) {
my_naibx.save_model(export_model);
}
/* APPLICATION of Model to dataset */
// test obs vs predicted in training set
std::vector<std::vector<int> > predictions_on_testing;
std::vector<std::vector<int> > top_k_predictions;
std::vector<int> temp_pred; // store temp prediction labels[i]
/* Prediction on TEST Partition */
// int show_pred = 500;
// int iter = 0;
// const int tot_pred_steps = test_features.size();
// typedef std::chrono::high_resolution_clock clock;
start_count_time = clock::now();
for (auto it = test_features.begin(); it != test_features.end(); ++it) {
top_k_predictions.clear();
// ++iter;
// // if (!no_print) {
// if (iter % show_pred == 0) {
// std::cout << (double) iter/tot_pred_steps * 100 << "% (done)" << std::endl;
// }
// // }
temp_pred.clear();
/* Good Ol NaiBX */
auto i = std::distance(test_features.begin(), it); // get i index
temp_pred = my_naibx.predict_y(*it, temp_pred, observed_m_test.at(i), real_m);
// if (real_m == true && avg_m != 0) {
// temp_pred = my_naibx.predict_y(*it, temp_pred, avg_m, real_m);
// }
// else if (real_m == true) {
// auto i = std::distance(test_features.begin(), it); // get i index
// temp_pred = my_naibx.predict_y(*it, temp_pred, observed_m_test[i], real_m);
// }
predictions_on_testing.push_back(temp_pred);
}
// std::cout << "" << std::endl;
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
prediction_time += time_elapsed;
/* OUTPUT results to file */
if ( save_output == true ) {
if (real_m == true) {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
else {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
}
// could be done directly inside naibx. Dumb shortcut here, re-computing m
std::vector<int> predicted_m_on_testing;
for (size_t i = 0; i < predictions_on_testing.size(); i++) {
predicted_m_on_testing.push_back(predictions_on_testing.at(i).size());
// PrintVector(predictions_on_testing.at(i));
// std::cout << "gino: " << predictions_on_testing.at(i).size() << std::endl;
}
double how_many_labs_pred = 0;
double how_many_labs_obs = 0;
for (int size : observed_m_test) how_many_labs_obs += size;
for (int size : predicted_m_on_testing) how_many_labs_pred += size;
size_t numobs_pred = predicted_m_on_testing.size();
// size_t numobs_obs = observed_m_test.size();
labcard.push_back( (double) how_many_labs_pred/numobs_pred);
/* LOSS MEASURES */
// std::cout << "LabelAccuracy:" << std::endl;
// LabelAccuracy(test_labels , predictions_on_testing, num_of_labels);
if (hamming == true || all == true) {
double hloss = HammingLoss(test_labels , predictions_on_testing, num_of_labels);
hl_vec.push_back(hloss);
std::string metric = "hamming";
if (save_output == true) {
ExportMetrics(my_arff, metric, hloss, real_m);
}
}
if (zeroone == true || all == true) {
double loss_m = ZeroOneLoss(test_labels , predictions_on_testing);
zo_vec.push_back(loss_m);
std::string metric = "zeroone";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (accuracy == true || all == true) {
double loss_m = Accuracy(test_labels , predictions_on_testing);
ac_vec.push_back(loss_m);
std::string metric = "accuracy";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (precision == true || all == true) {
double loss_m = Precision(test_labels , predictions_on_testing);
pr_vec.push_back(loss_m);
std::string metric = "precision";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
if (recall == true || all == true) {
double loss_m = Recall(test_labels , predictions_on_testing);
re_vec.push_back(loss_m);
std::string metric = "recall";
if (save_output == true) {
ExportMetrics(my_arff, metric, loss_m, real_m);
}
}
}
/* Data-partition: K-FOLD validation */
if (kfold > 1) {
for (int i = 0; i < kfold; i++) {
testfold = i;
std::cout << "\n --- partition n." << (testfold + 1) << " --- " << std::endl;
/* split data */
std::vector<int> fold_sizes = KFoldIndexes(nrows, kfold);
SplitDataForKFold(
testfold, kfold,
// imported data
labels_2D_array, cont_feat_array, observed_m,
// containers for CV procedure
fold_sizes,
training_expl, test_features,
training_labels, test_labels,
observed_m_training, observed_m_test);
/* TRAINING model */
assert(training_expl.size() + test_features.size() == nrows && "lost some observations during CV split");
/* STEP 1: init Classifier */
Naibx my_naibx(num_features, num_of_labels, laplacian_smoothing, keep);
/* STEP 2: TRAINING the predictor with user inputs */
int learn_size = training_expl.size();
if (load_model == true) {
my_naibx.load_my_model(import_model);
}
else {
start_count_time = clock::now();
// train model, line by line
for (int i = 0; i < learn_size; i++) {
my_naibx.add_example(cont_feat_array.at(i), labels_2D_array.at(i));
}
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
training_time += time_elapsed;
}
/* STEP 3: store model for future use */
if (save_model == true) {
my_naibx.save_model(export_model);
}
/* APPLICATION of Model to dataset */
// test obs vs predicted in training set
std::vector<std::vector<int> > predictions_on_testing;
std::vector<std::vector<int> > top_k_predictions;
std::vector<int> temp_pred; // store temp prediction labels[i]
/* Prediction on TEST Partition */
// int show_pred = 500;
// int iter = 0;
// const int tot_pred_steps = test_features.size();
// typedef std::chrono::high_resolution_clock clock;
start_count_time = clock::now();
for (auto it = test_features.begin(); it != test_features.end(); ++it) {
top_k_predictions.clear();
// ++iter;
// // if (!no_print) {
// if (iter % show_pred == 0) {
// std::cout << (double) iter/tot_pred_steps * 100 << "% (done)" << std::endl;
// }
// // }
temp_pred.clear();
/* Good Ol NaiBX */
auto i = std::distance(test_features.begin(), it); // get i index
temp_pred = my_naibx.predict_y(*it, temp_pred, observed_m_test.at(i), real_m);
predictions_on_testing.push_back(temp_pred);
}
// std::cout << "" << std::endl;
time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_count_time).count();
prediction_time += time_elapsed;
/* OUTPUT results to file */
if ( save_output == true ) {
if (real_m == true) {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_pred_real_m.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
else {
std::string output_name;
std::size_t pos = my_arff.find(".");
if (pos != std::string::npos) {
output_name = my_arff.substr(0, pos) + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
else {
output_name = my_arff + "_predictions.txt" ;
// std::cout << "output title: " << output_name << std::endl;
}
std::ofstream my_output (output_name, std::ios_base::app);
if(my_output.is_open()) {
my_output << "testfold = " << (testfold + 1) << " (out of "<<kfold<<")\n";
for (auto line: predictions_on_testing) {
for (auto elem : line) {
my_output << elem << " " ;
}
my_output << "\n";
}
my_output.close();
}
}
}
// could be done directly inside naibx. Dumb shortcut here, re-computing m
std::vector<int> predicted_m_on_testing;
for (size_t i = 0; i < predictions_on_testing.size(); i++) {
predicted_m_on_testing.push_back(predictions_on_testing.at(i).size());
}
double how_many_labs_pred = 0;
double how_many_labs_obs = 0;
for (int size : observed_m_test) how_many_labs_obs += size;
for (int size : predicted_m_on_testing) how_many_labs_pred += size;
size_t numobs_pred = predicted_m_on_testing.size();
// size_t numobs_obs = observed_m_test.size();
labcard.push_back( (double) how_many_labs_pred/numobs_pred);
// std::cout << "test partition, LCard (OBSERVED) = " << (double) how_many_labs_obs/numobs_obs << std::endl;
/* LOSS MEASURES */
// std::cout << "LabelAccuracy:" << std::endl;
// LabelAccuracy(test_labels , predictions_on_testing, num_of_labels);
if (hamming == true || all == true) {
double hloss = HammingLoss(test_labels , predictions_on_testing, num_of_labels);
hl_vec.push_back(hloss);
std::string metric = "hamming";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, hloss, real_m);
// }
}
if (zeroone == true || all == true) {
double loss_m = ZeroOneLoss(test_labels , predictions_on_testing);
zo_vec.push_back(loss_m);
std::string metric = "zeroone";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (accuracy == true || all == true) {
double loss_m = Accuracy(test_labels , predictions_on_testing);
ac_vec.push_back(loss_m);
std::string metric = "accuracy";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (precision == true || all == true) {
double loss_m = Precision(test_labels , predictions_on_testing);
pr_vec.push_back(loss_m);
std::string metric = "precision";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
if (recall == true || all == true) {
double loss_m = Recall(test_labels , predictions_on_testing);
re_vec.push_back(loss_m);
std::string metric = "recall";
// if (save_output == true) {
// ExportMetrics(my_arff, metric, loss_m, real_m);
// }
}
}
}
}
double mn = 0;
std::cout << "Losses:" << std::endl;
mn = mean(hl_vec);
std::cout << "\tHL = " << mn << std::endl ;
mn = mean(zo_vec);
std::cout << "\tZO = " << mn << std::endl ;
mn = mean(ac_vec);
std::cout << "\tAC = " << mn << std::endl ;
mn = mean(pr_vec);
std::cout << "\tPR = " << mn << std::endl ;
mn = mean(re_vec);
std::cout << "\tRE = " << mn << std::endl ;
mn = mean(labcard);
std::cout << "\tLC = " << mn << std::endl ;
std::cout << " TRAINING TIME = " << training_time * 0.001 << " (secs)" << std::endl;
std::cout << "PREDICTION TIME = " << prediction_time * 0.001 << " (secs)" << std::endl;
return 0;
};
| 43.93345 | 133 | 0.478195 | [
"vector",
"model"
] |
632c616262fd059dd56e3d0e13f06be6df5d0087 | 1,278 | cpp | C++ | main.cpp | pLesur/Mediadexer | 853df81d84ea70c6f79f82a6fa8c987760c118fb | [
"Apache-2.0"
] | null | null | null | main.cpp | pLesur/Mediadexer | 853df81d84ea70c6f79f82a6fa8c987760c118fb | [
"Apache-2.0"
] | null | null | null | main.cpp | pLesur/Mediadexer | 853df81d84ea70c6f79f82a6fa8c987760c118fb | [
"Apache-2.0"
] | null | null | null | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QQuickView>
#include <memory>
#include <qqmlcontext.h>
#include "controllers/categorycontroller.h"
#include "controllers/searchcontroller.h"
#include "controllers/tabmanager.h"
#include "entities/category.h"
#include "entities/searchnode.h"
#include "model/model.h"
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
auto context = engine.rootContext();
auto model = std::make_shared<Model>(Model());
SearchController searchController(model);
CategoryController categoryController(model);
context->setContextProperty("CategoryController", &categoryController);
context->setContextProperty("SearchController", &searchController);
qmlRegisterType<SearchNode>("mediadexer.searchnode", 1, 0, "SearchNode");
engine.load(QUrl(QLatin1String("qrc:/views/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
auto tabView = engine.rootObjects().first()->findChild<QObject *>("tab_view");
TabManager tabManager(tabView, &categoryController, &searchController);
QObject::connect(tabView, SIGNAL(onCurrentIndexChanged(int)), &tabManager,
SLOT(onTabChanged(int)));
return app.exec();
}
| 33.631579 | 80 | 0.751174 | [
"model"
] |
632d208915a8032b7aaf2634a12343a64dcd0de2 | 7,547 | cpp | C++ | mainwindow.cpp | GabiAndi/WOL | 247b8575e04cc859c91f04c3c485329535c20e47 | [
"MIT"
] | null | null | null | mainwindow.cpp | GabiAndi/WOL | 247b8575e04cc859c91f04c3c485329535c20e47 | [
"MIT"
] | null | null | null | mainwindow.cpp | GabiAndi/WOL | 247b8575e04cc859c91f04c3c485329535c20e47 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Captura de las interfacez de red
getInterfaces();
// Se cargan los equipos guardados
readJsonData();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::sendMagicPackage(QString MAC, QString iface)
{
/* Para poder despertar un dispositivo mediante el protocolo Wake On Lan (WOL),
* se debe enviar una cadena de 6 bytes con el valor de 255 y luego 16 veces
* la dirección MAC del dispositivo a encender.
*
* Quedaria algo asi:
*
* FF:FF:FF:FF:FF:FF
* 10:20:30:50:40:60
* ................. <- 14 veces restantes la MAC
* 10:20:30:50:40:60
*
* Este paquete se manda mediante UDP al broadcast de la red por el puerto 9.
*
*/
MAC.remove(":");
QByteArray data1MAC = QByteArray::fromHex(MAC.toLocal8Bit());
QByteArray data6FF = QByteArray::fromHex("FFFFFFFFFFFF");
QByteArray data16MAC;
for (int i = 0; i < 16; i++)
{
data16MAC += data1MAC;
}
QByteArray magicPackage = data6FF + data16MAC;
// Se crea un scoket UDP
QUdpSocket qudpsocket;
// Se obtiene la interfaz de red
QNetworkInterface interface = QNetworkInterface::allInterfaces().at(QNetworkInterface::interfaceIndexFromName(iface) - 1);
QHostAddress address;
for (int i = 0 ; i < interface.addressEntries().length() ; i++)
{
// Se verifica si la IP es válida
if (interface.addressEntries().at(i).ip().toString().count(".") == 3)
{
address = interface.addressEntries().at(i).ip();
// De la IP se obtiene el broadcast
QString broadcastIP(address.toString().left(address.toString().lastIndexOf('.')).append(".255"));
// Se envia el paquete mágico al broadcd ast asi todos los equipor en la red lo escucharan
qudpsocket.writeDatagram(magicPackage, magicPackage.size(), QHostAddress(broadcastIP), 9);
}
}
}
void MainWindow::getInterfaces()
{
ui->comboBoxIfaces->clear();
// Se obtienen las interfaces de red
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
for (int i = 0 ; i < interfaces.length() ; i++)
{
ui->comboBoxIfaces->addItem(interfaces.at(i).name());
}
}
void MainWindow::saveJsonData()
{
QFile data(JsonFileName);
if (data.open(QIODevice::WriteOnly | QIODevice::Text))
{
QJsonDocument json;
QJsonObject obj;
QJsonArray values;
QJsonObject objs;
QByteArray dataJson;
// Se añaden los equipos que esten guardados
for (int i = 0 ; i < ui->treeWidgetEquipos->topLevelItemCount() ; i++)
{
// Se añaden los campos de valor
obj["desc"] = ui->treeWidgetEquipos->topLevelItem(i)->text(0);
obj["mac"] = ui->treeWidgetEquipos->topLevelItem(i)->text(1);
obj["iface"] = ui->treeWidgetEquipos->topLevelItem(i)->text(2);
// Se agrega el obj a un array
values.append(obj);
}
// Se almacenan todos los equipos en un objeto padre
objs["equipos"] = values;
json.setObject(objs);
dataJson = json.toJson();
// Se escribe el contenido en el archivo
data.write(dataJson);
data.close();
ui->statusBar->showMessage("Guardado correctamente el archivo de equipos");
}
else
{
ui->statusBar->showMessage("No se pudo guardar el archivo de equipos");
}
}
void MainWindow::readJsonData()
{
QFile data(JsonFileName);
if (data.open(QIODevice::ReadOnly | QIODevice::Text))
{
QJsonDocument json;
QJsonObject obj;
QJsonArray values;
QJsonObject objs;
QByteArray dataJson;
// Se lee el contenido del archivo
dataJson = data.readAll();
json = json.fromJson(dataJson);
objs = json.object();
values.append(objs["equipos"].toArray());
values = values.at(0).toArray();
// Se leen los equipos que esten guardados
for (int i = 0 ; i < values.size() ; i++)
{
// Se leen los campos de valor
QStringList equipo;
obj = values.at(i).toObject();
equipo.append(obj["desc"].toString());
equipo.append(obj["mac"].toString());
equipo.append(obj["iface"].toString());
ui->treeWidgetEquipos->addTopLevelItem(new QTreeWidgetItem(equipo));
}
// Se cierra el archivo
data.close();
ui->statusBar->showMessage("Leido correctamente el archivo de equipos");
}
else
{
ui->statusBar->showMessage("No se pudo leer el archivo de equipos");
}
}
void MainWindow::on_pushButtonWOL_clicked()
{
if (ui->treeWidgetEquipos->currentItem() != nullptr)
{
// Se extrae la MAC
QString mac(ui->treeWidgetEquipos->currentItem()->text(1));
// Se obtiene la interfaz de red
QString iface(ui->treeWidgetEquipos->currentItem()->text(2));
// Se envia el pulso de encendido
sendMagicPackage(mac, iface);
}
}
void MainWindow::on_actionActualizar_interfaces_triggered()
{
getInterfaces();
}
void MainWindow::on_actionSalir_triggered()
{
close();
}
void MainWindow::on_actionAcerca_de_triggered()
{
acercaDe = new AcercaDeWindow(this);
acercaDe->show();
}
void MainWindow::on_pushButtonGuardar_clicked()
{
// Si los campos de texto tiene algo lo guardamos
if (ui->lineEditMAC->text().length() > 0 && ui->lineEditDescripcion->text().length() > 0)
{
QStringList equipo;
equipo.append(ui->lineEditDescripcion->text());
equipo.append(ui->lineEditMAC->text());
equipo.append(ui->comboBoxIfaces->currentText());
ui->treeWidgetEquipos->addTopLevelItem(new QTreeWidgetItem(equipo));
saveJsonData();
}
}
void MainWindow::on_pushButtonEliminar_clicked()
{
if (ui->treeWidgetEquipos->currentItem() != nullptr)
{
// Se elimina el archivo
delete ui->treeWidgetEquipos->currentItem();
saveJsonData();
}
}
void MainWindow::on_pushButtonCargar_clicked()
{
if (ui->treeWidgetEquipos->currentItem() != nullptr)
{
// Se extran los datos
QString desc(ui->treeWidgetEquipos->currentItem()->text(0));
QString mac(ui->treeWidgetEquipos->currentItem()->text(1));
QString iface(ui->treeWidgetEquipos->currentItem()->text(2));
ui->lineEditDescripcion->setText(desc);
ui->lineEditMAC->setText(mac);
int index = ui->comboBoxIfaces->findText(iface);
if (index != -1)
{
ui->comboBoxIfaces->setCurrentIndex(index);
}
}
}
void MainWindow::on_treeWidgetEquipos_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
Q_UNUSED(column);
if (item != nullptr)
{
// Se extrae la MAC
QString mac(item->text(1));
// Se obtiene la interfaz de red
QString iface(item->text(2));
// Se envia el pulso de encendido
sendMagicPackage(mac, iface);
}
}
| 27.245487 | 127 | 0.591096 | [
"object"
] |
633804648473bd5c81532c2285ced2951ae1f4fd | 73,892 | cpp | C++ | SurfaceReconstruction/SurfaceReconstruction/Geometry/FlexibleMesh.cpp | pavelsevecek/TSR | ca411dedf178e5830f0536e361136f1e16751bc8 | [
"BSD-3-Clause"
] | 102 | 2017-10-17T10:10:59.000Z | 2022-01-19T02:10:29.000Z | SurfaceReconstruction/SurfaceReconstruction/Geometry/FlexibleMesh.cpp | pavelsevecek/TSR | ca411dedf178e5830f0536e361136f1e16751bc8 | [
"BSD-3-Clause"
] | 2 | 2019-12-21T11:59:15.000Z | 2020-09-08T11:38:36.000Z | SurfaceReconstruction/SurfaceReconstruction/Geometry/FlexibleMesh.cpp | pavelsevecek/TSR | ca411dedf178e5830f0536e361136f1e16751bc8 | [
"BSD-3-Clause"
] | 27 | 2017-10-18T09:37:34.000Z | 2022-03-22T01:30:51.000Z | /*
* Copyright (C) 2018 by Author: Aroudj, Samir
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#include "Math/MathHelper.h"
#include "Platform/Utilities/Array.h"
#include "SurfaceReconstruction/Geometry/Edge.h"
#include "SurfaceReconstruction/Geometry/FlexibleMesh.h"
#include "SurfaceReconstruction/Geometry/IslesEraser.h"
#include "SurfaceReconstruction/Geometry/Mesh.h"
#include "SurfaceReconstruction/Geometry/StaticMesh.h"
using namespace FailureHandling;
using namespace Math;
using namespace std;
using namespace Storage;
using namespace SurfaceReconstruction;
using namespace Utilities;
void FlexibleMesh::computeOffsetsForFiltering(uint32 *vertexOffsets, uint32 *edgeOffsets, uint32 *triangleOffsets,
const uint32 vertexCount, const uint32 edgeCount, const uint32 triangleCount,
const vector<uint32> *verticesToEdges, const Edge *edges, const uint32 *indices,
const IVertexChecker &vertexChecker)
{
memset(vertexOffsets, 0, sizeof(uint32) * (vertexCount + 1));
memset(edgeOffsets, 0, sizeof(uint32) * (edgeCount + 1));
memset(triangleOffsets, 0, sizeof(uint32) * (triangleCount + 1));
uint32 *const doomedVertices = vertexOffsets + 1;
uint32 *const doomedEdges = edgeOffsets + 1;
uint32 *const doomedTriangles = triangleOffsets + 1;
// find vertices, edges and triangles to be deleted
#pragma omp parallel for
for (int64 vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
{
// don't delete the vertex?
if (!vertexChecker.isBad((uint32) vertexIdx))
continue;
// delete this vertex
doomedVertices[vertexIdx] = 1;
// find doomed edge and triangles
const vector<uint32> &adjacentEdges = verticesToEdges[vertexIdx];
const uint32 localEdgeCount = (uint32) adjacentEdges.size();
for (uint32 localEdgeIdx = 0; localEdgeIdx < localEdgeCount; ++localEdgeIdx)
{
// doomed edge
const uint32 globalEdgeIdx = adjacentEdges[localEdgeIdx];
doomedEdges[globalEdgeIdx] = 1;
// doomed triangles and doomed edges (owing to no left neighboring triangles)
const Edge &edge = edges[globalEdgeIdx];
const uint32 *triangles = edge.getTriangleIndices();
for (uint32 sideIdx = 0; sideIdx < 2; ++sideIdx)
if (Triangle::INVALID_INDEX != triangles[sideIdx]) // invalid neighbor triangle anyway?
doomedTriangles[triangles[sideIdx]] = 1; // delete this triangle as its edge is deleted
}
}
// check for edges which should be deleted since they have no neighbor triangles anymore
#pragma omp parallel for
for (int64 triangleIdx = 0; triangleIdx < triangleCount; ++triangleIdx)
{
if (!doomedTriangles[triangleIdx])
continue;
// check for edges which might have no neighbor triangle left when triangle triangleIdx is deleted
const uint32 *triangle = indices + 3 * triangleIdx;
for (uint32 triangleEdgeIdx = 0; triangleEdgeIdx < 3; ++triangleEdgeIdx)
{
// current edge: (v0, v1) -> find global index via v0's adjacent edges and v1 vertex index
const uint32 v0 = triangle[triangleEdgeIdx];
const uint32 v1 = triangle[(triangleEdgeIdx + 1) % 3];
const vector<uint32> &adjacentEdges = verticesToEdges[v0];
// get edge object for (v0, v1) and check its neighbors for existence
const uint32 localEdgeCount = (uint32) adjacentEdges.size();
for (uint32 localEdgeIdx = 0; localEdgeIdx < localEdgeCount; ++localEdgeIdx)
{
// correct global edge?
const uint32 globalEdgeIdx = adjacentEdges[localEdgeIdx];
const Edge &edge = edges[globalEdgeIdx];
const uint32 candidateV1 = edge.getOtherVertex(v0);
if (candidateV1 != v1)
continue;
// does the edge have 0 neighbor triangles?
const uint32 otherTriangleIdx = edge.getOtherTriangle((uint32) triangleIdx);
if (Triangle::INVALID_INDEX == otherTriangleIdx || doomedTriangles[otherTriangleIdx])
doomedEdges[globalEdgeIdx] = 1;
}
}
}
// prefix sum on arrays of doom to get offsets for compaction
prefixSum(vertexOffsets, edgeOffsets, triangleOffsets, vertexCount, edgeCount, triangleCount);
}
void FlexibleMesh::computeTriangleOffsets(uint32 *triangleOffsets, const uint32 *vertexOffsets, const uint32 *indices, const uint32 indexCount, const bool *additionalSkipTriangles)
{
const uint32 triangleCount = indexCount / 3;
// prefix sum to find offsets for compaction of triangles
triangleOffsets[0] = 0;
for (uint32 oldTriangleIdx = 0; oldTriangleIdx < triangleCount; ++oldTriangleIdx)
{
triangleOffsets[oldTriangleIdx + 1] = triangleOffsets[oldTriangleIdx];
bool offsetTriangle = (additionalSkipTriangles ? additionalSkipTriangles[oldTriangleIdx] : false);
if (!offsetTriangle)
{
// has one of the triangle vertices been filtered (if true -> filter (offset) the triangle)
const uint32 oldTriangleStartOffset = 3 * oldTriangleIdx;
for (uint32 edgeIdx = 0; edgeIdx < 3; ++edgeIdx)
{
const uint32 oldVertexIdx = indices[oldTriangleStartOffset + edgeIdx];
if (vertexOffsets[oldVertexIdx] != vertexOffsets[oldVertexIdx + 1])
{
offsetTriangle = true;
break;
}
}
}
if (offsetTriangle)
++triangleOffsets[oldTriangleIdx + 1];
}
}
void FlexibleMesh::findVertexNeighbors(vector<uint32> *vertexNeighbors, const uint32 *indices, const uint32 indexCount)
{
// go over all triangles to go over all edges
for (uint32 startOffset = 0; startOffset < indexCount; startOffset += 3, indices += 3)
{
// go over all 3 edges and properly extend the corresponding vertex neighborss
uint32 edge[2] = { indices[0], indices[1] };
for (uint32 edgeIdx = 0; edgeIdx < 3; ++edgeIdx)
{
addToVertexNeighbors(vertexNeighbors[edge[0]], edge[1]);
addToVertexNeighbors(vertexNeighbors[edge[1]], edge[0]);
// next triangle edge
edge[0] = edge[1];
edge[1] = indices[(edgeIdx + 2) % 3];
}
}
}
void FlexibleMesh::addToVertexNeighbors(vector<uint32> &vertexNeighbood, const uint32 vertexIdx)
{
// already contained?
const uint32 count = (uint32) vertexNeighbood.size();
for (uint32 i = 0; i < count; ++i)
if (vertexNeighbood[i] == vertexIdx)
return;
vertexNeighbood.push_back(vertexIdx);
}
FlexibleMesh::FlexibleMesh(const Path &fileName) :
FlexibleMesh()
{
loadFromFile(fileName);
}
void FlexibleMesh::loadFromFile(const Path &fileName)
{
Mesh::loadFromFile(fileName);
findAdjacencies();
}
FlexibleMesh::FlexibleMesh(const uint32 vertexCount, const uint32 indexCount) :
FlexibleMesh()
{
resize(vertexCount, indexCount);
}
FlexibleMesh::FlexibleMesh()
{
clear();
}
FlexibleMesh::FlexibleMesh(const Mesh &m, IFlexibleMeshObserver *observer) :
mColors(m.getColors(), m.getColors() + m.getVertexCount()),
mNormals(m.getNormals(), m.getNormals() + m.getVertexCount()),
mPositions(m.getPositions(), m.getPositions() + m.getVertexCount()),
mScales(m.getScales(), m.getScales() + m.getVertexCount()),
mIndices(m.getIndices(), m.getIndices() + m.getIndexCount())
{
registerObserver(observer);
findAdjacencies();
}
FlexibleMesh::FlexibleMesh(const FlexibleMesh ©) :
mVerticesToEdges(copy.mVerticesToEdges),
mColors(copy.mColors),
mNormals(copy.mNormals),
mPositions(copy.mPositions),
mScales(copy.mScales),
mEdges(copy.mEdges),
mIndices(copy.mIndices),
mEdgeConflicts(copy.mEdgeConflicts)
{
}
FlexibleMesh::~FlexibleMesh()
{
clear();
}
void FlexibleMesh::clear()
{
Subject::clear();
// clear data of vertices
mVerticesToEdges.clear();
mColors.clear();
mNormals.clear();
mPositions.clear();
mScales.clear();
// clear data of edges
mEdges.clear();
// clear triangle data
mIndices.clear();
}
void FlexibleMesh::filterTriangles(uint32 *targetIndices, const uint32 *sourceIndices, const uint32 *triangleOffsets, const uint32 sourceIndexCount, const uint32 *vertexOffsets)
{
const uint32 triangleCount = sourceIndexCount / 3;
#pragma omp parallel for
for (int64 i = 0; i < triangleCount; ++i)
{
// filter this triangle?
const uint32 oldTriangleIdx = (uint32) i;
if (triangleOffsets[oldTriangleIdx] != triangleOffsets[oldTriangleIdx + 1])
continue;
// copy triangle data
const uint32 newTriangleIdx = oldTriangleIdx - triangleOffsets[oldTriangleIdx];
const uint32 newStartOffset = 3 * newTriangleIdx;
const uint32 oldStartOffset = 3 * oldTriangleIdx;
for (uint32 cornerIdx = 0; cornerIdx < 3; ++cornerIdx)
{
const uint32 oldVertexIndex = sourceIndices[oldStartOffset + cornerIdx];
targetIndices[newStartOffset + cornerIdx] = oldVertexIndex - vertexOffsets[oldVertexIndex];
}
}
}
void FlexibleMesh::computeScalesViaEdgeDistances()
{
const int64 vertexCount = mPositions.size();
#pragma omp parallel for
for (int64 i = 0; i < vertexCount; ++i)
{
// get vertex data
const uint32 vertexIdx = (uint32) i;
const vector<uint32> &edges = mVerticesToEdges[vertexIdx];
const uint32 edgeCount = (uint32) edges.size();
if (0 == edgeCount)
continue;
// scale = mean distance to neighbors
Real &scale = mScales[vertexIdx];
scale = 0.0f;
for (uint32 edgeIdx = 0; edgeIdx < edgeCount; ++edgeIdx)
{
// get vertex indices
const Edge &edge = mEdges[edges[edgeIdx]];
const uint32 v0 = edge.getVertexIndices()[0];
const uint32 v1 = edge.getVertexIndices()[1];
assert(v0 == vertexIdx || v1 == vertexIdx);
// add distance to current neighbor
const Vector3 diff = mPositions[v0] - mPositions[v1];
scale += diff.getLength();
}
scale /= edgeCount;
}
}
void FlexibleMesh::smoothByUmbrellaOp(Vector3 *vectorField, const vector<uint32> &vertices, const Real lambda)
{
const uint32 vertexCount = (uint32) vertices.size();
// compute movements
for (uint32 i = 0; i < vertexCount; ++i)
{
const uint32 vertexIdx = vertices[i];
vectorField[vertexIdx] = computeUmbrellaSmoothingMovement(vertexIdx, lambda);
}
// apply movements
for (uint32 i = 0; i < vertexCount; ++i)
{
// get vertex data
const uint32 vertexIdx = vertices[i];
const Vector3 &position = getPosition(vertexIdx);
const Vector3 &movement = vectorField[vertexIdx];
// move vertex
const Vector3 newPosition = position + movement;
setPosition(newPosition, vertexIdx);
}
}
Vector3 FlexibleMesh::computeUmbrellaSmoothingMovement(const uint32 vertexIdx, const Real lambda) const
{
Vector3 weightedSum(0.0f, 0.0f, 0.0f);
Real sumOfWeights = 0.0f;
// umbrella smoothing operator: condider all direct neighbors of vertex vertexIdx
const Vector3 &vertexPos = getPosition(vertexIdx);
const vector<uint32> &edges = mVerticesToEdges[vertexIdx];
const uint32 edgeCount = (uint32) edges.size();
// compute a weighted mean position of the neighbors
for (uint32 localEdgeIdx = 0; localEdgeIdx < edgeCount; ++localEdgeIdx)
{
// get neighbor vertex index and its position
const uint32 globalEdgeIdx = edges[localEdgeIdx];
const Edge &edge = mEdges[globalEdgeIdx];
const uint32 neighborVertexIdx = edge.getOtherVertex(vertexIdx);
const Vector3 &neighborPos = getPosition(neighborVertexIdx);
// weight & weighted position
const Real neighborWeight = Mesh::computeLaplacianWeight(vertexPos, neighborPos);
const Vector3 weightedPosition = neighborPos * neighborWeight;
// update sums
sumOfWeights += neighborWeight;
weightedSum += weightedPosition;
}
weightedSum /= sumOfWeights;
// return final umbrella smoothing movement vector
const Vector3 laplacian = (weightedSum - vertexPos);
const Vector3 umbrellaMove = laplacian * lambda;
return umbrellaMove;
}
void FlexibleMesh::updateVertexIndices(vector<vector<uint32>> &vertexSets, const uint32 *vertexOffsets)
{
// update vertex indices -> valid after compaction / deletion / subtraction of vertex offsets
const uint32 setCount = (uint32) vertexSets.size();
#pragma omp parallel for
for (int64 setIdx = 0; setIdx < setCount; ++setIdx)
{
// get hole
vector<uint32> &set = vertexSets[setIdx];
const uint32 setSize = (uint32) set.size();
// shift vertex indices
for (uint32 localVertexIdx = 0; localVertexIdx < setSize; ++localVertexIdx)
{
const uint32 oldIdx = set[localVertexIdx];
const uint32 newIdx = oldIdx - vertexOffsets[oldIdx];
set[localVertexIdx] = newIdx;
}
}
}
void FlexibleMesh::mergeEdges(vector<uint32> &edgesWithNewIndices, const vector<uint32> &edgeMergeCandidates)
{
const uint32 candidateCount = (uint32) edgeMergeCandidates.size();
if (0 == candidateCount)
return;
// offset arrays to define what elements are removed
const uint32 oldVertexCount = getVertexCount();
const uint32 oldEdgeCount = getEdgeCount();
const uint32 oldTriangleCount = getTriangleCount();
clearOffsets(oldVertexCount, oldEdgeCount, oldTriangleCount);
memset(mVertexOffsets.data(), 0, sizeof(uint32) * (oldVertexCount + 1));
memset(mEdgeOffsets.data(), 0, sizeof(uint32) * (oldEdgeCount + 1));
memset(mTriangleOffsets.data(), 0, sizeof(uint32) * (oldTriangleCount + 1));
// merging of edges, data structure compaction by deletion via prefix sum offsets
mergeEdgesWithoutFiltering(mVertexOffsets.data() + 1, mEdgeOffsets.data() + 1, mTriangleOffsets.data() + 1, edgeMergeCandidates);
for (uint32 edgeIdx = 0; edgeIdx < oldEdgeCount; ++edgeIdx)
{
const Edge &edge = mEdges[edgeIdx];
if ((Triangle::INVALID_INDEX == edge.getTriangleIndices()[0] && Triangle::INVALID_INDEX == edge.getTriangleIndices()[1]) &&
(Vertex::INVALID_INDEX != edge.getVertexIndices()[0] && Vertex::INVALID_INDEX != edge.getVertexIndices()[1]))
{
cerr << "This is not supposed to happen0: " << edgeIdx << " " << edge.getVertexIndices()[0] << " " << edge.getVertexIndices()[1] << endl;
}
}
prefixSum(mVertexOffsets.data(), mEdgeOffsets.data(), mTriangleOffsets.data(), oldVertexCount, oldEdgeCount, oldTriangleCount);
deleteGeometry(mVertexOffsets.data(), mEdgeOffsets.data(), mTriangleOffsets.data());
const uint32 newEdgeCount = getEdgeCount();
for (uint32 edgeIdx = 0; edgeIdx < newEdgeCount; ++edgeIdx)
{
const Edge &edge = mEdges[edgeIdx];
if ((Triangle::INVALID_INDEX == edge.getTriangleIndices()[0] && Triangle::INVALID_INDEX == edge.getTriangleIndices()[1]) &&
(Vertex::INVALID_INDEX != edge.getVertexIndices()[0] && Vertex::INVALID_INDEX != edge.getVertexIndices()[1]))
{
cerr << "This is not supposed to happen1: " << edgeIdx << " " << edge.getVertexIndices()[0] << " " << edge.getVertexIndices()[1] << endl;
}
}
// edgesWithNewIndices = applyEdgeOffsets(edgeMergeCandidates)
edgesWithNewIndices.clear();
edgesWithNewIndices.reserve(edgeMergeCandidates.size());
for (uint32 oldCandidateCount = 0; oldCandidateCount < candidateCount; ++oldCandidateCount)
{
const uint32 oldGlobalEdgeIdx = edgeMergeCandidates[oldCandidateCount];
if (mEdgeOffsets[oldGlobalEdgeIdx] != mEdgeOffsets[oldGlobalEdgeIdx + 1])
continue;
const uint32 newGlobalEdgeIdx = oldGlobalEdgeIdx - mEdgeOffsets[oldGlobalEdgeIdx];
edgesWithNewIndices.push_back(newGlobalEdgeIdx);
}
}
void FlexibleMesh::prefixSum(uint32 *vertexOffsets, uint32 *edgeOffsets, uint32 *triangleOffsets, const uint32 vertexCount, const uint32 edgeCount, const uint32 triangleCount)
{
for (uint32 i = 0; i < vertexCount; ++i)
vertexOffsets[i + 1] += vertexOffsets[i];
for (uint32 i = 0; i < edgeCount; ++i)
edgeOffsets[i + 1] += edgeOffsets[i];
for (uint32 i = 0; i < triangleCount; ++i)
triangleOffsets[i + 1] += triangleOffsets[i];
}
void FlexibleMesh::mergeEdgesWithoutFiltering(uint32 *globalDoomedVertices, uint32 *globalDoomedEdges, uint32 *globalDoomedTriangles,
const vector<uint32> &mergingEdges)
{
// merge each edge
const uint32 mergingEdgesCount = (uint32) mergingEdges.size();
for (uint32 localEdgeIdx = 0; localEdgeIdx < mergingEdgesCount; ++localEdgeIdx)
{
// get check global edge index
const uint32 doomedEdgeIdx = mergingEdges[localEdgeIdx];
if (globalDoomedEdges[doomedEdgeIdx])
continue;
mergeEdge(globalDoomedVertices, globalDoomedEdges, globalDoomedTriangles, doomedEdgeIdx);
}
}
void FlexibleMesh::mergeEdge(uint32 *globalDoomedVertices, uint32 *globalDoomedEdges, uint32 *globalDoomedTriangles,
const uint32 doomedEdgeIdx)
{
// get required indices
const Edge &doomedEdge = mEdges[doomedEdgeIdx];
const uint32 doomedT[2] = { doomedEdge.getTriangleIndices()[0], doomedEdge.getTriangleIndices()[1] };
const uint32 *doomedTris[2] = { getTriangle(doomedT[0]), getTriangle(doomedT[1]) };
const uint32 doomedVertex = doomedEdge.getVertexIndices()[1];
// get indices of kept vertices of triangles to be collapsed (keptV[0, 1, 2] stay, doomedV is deleted)
uint32 keptV[3];
keptV[0] = doomedEdge.getVertexIndices()[0];
keptV[1] = Triangle::getOtherVertex(doomedTris[0], keptV[0], doomedVertex);
keptV[2] = Triangle::getOtherVertex(doomedTris[1], keptV[0], doomedVertex);
uint32 doomedE[3] = { doomedEdgeIdx, getEdgeIndex(doomedVertex, keptV[1]), getEdgeIndex(doomedVertex, keptV[2])};
const uint32 keptE[2] = { getEdgeIndex(keptV[0], keptV[1]), getEdgeIndex(keptV[0], keptV[2])};
if (isInvalidEdgeMerge(keptV[2], keptE, doomedVertex, doomedT))
return;
// inform observers & interpolate vertex
const uint32 observerCount = (uint32) mObservers.size();
for (uint32 observerIdx = 0; observerIdx < observerCount; ++observerIdx)
mObservers[observerIdx]->onEdgeMerging(keptV[0], keptV[0], doomedVertex);
interpolateVertex(keptV[2], keptV[2], doomedVertex);
uint32 doomedV[3];
uint32 doomedVCount = 1;
doomedV[0] = doomedVertex;
if (keptV[1] != keptV[2])
{
// update connectivity & mark doomed elements
updateTriangleIndicesForEdgeMerge(keptV[0], doomedVertex, doomedT);
updateLinksForEdgeMerge(keptV, keptE, doomedVertex, doomedT, doomedE);
}
else
{
// special case: 2 invalid triangles sharing the same 3 edges
// keptV[2] == keptV[1] -> keptE[0] == keptE[1], doomedE[0] == doomedE[1], keptE should be removed
updateLinksForEdgeMerge(doomedV, doomedVCount, doomedE, keptE, keptV);
}
markDoomedElements(globalDoomedVertices, globalDoomedEdges, globalDoomedTriangles,
doomedV, doomedVCount, doomedE, 3, doomedT, 2);
}
bool FlexibleMesh::isInvalidEdgeMerge(const uint32 keptV, const uint32 keptE[2], const uint32 doomedV, const uint32 doomedT[2]) const
{
// edges adjacent to replaced vertex
const vector<uint32> &doomedVEdges = mVerticesToEdges[doomedV];
const uint32 doomedVEdgeCount = (uint32) doomedVEdges.size();
// for each edge affected by replacing vertex doomedV with vertex keptV
for (uint32 localDoomedEdgeIdx = 0; localDoomedEdgeIdx < doomedVEdgeCount; ++localDoomedEdgeIdx)
{
// get affected edge
const uint32 movingEdgeIdx = doomedVEdges[localDoomedEdgeIdx];
const Edge &movingEdge = mEdges[movingEdgeIdx];
// for each adjacent triangle of the affected edge
for (uint32 sideIdx = 0; sideIdx < 2; ++sideIdx)
{
// get triangle to move
const uint32 triangleIdx = movingEdge.getTriangleIndices()[sideIdx];
if (triangleIdx == doomedT[0] || triangleIdx == doomedT[1])
continue;
// does moving the triangle create an edge conflict? (more than 2 triangles connected to the same edge?)
// is a triangle corner moved by the replacement?
const uint32 *oldIndices = mIndices.data() + 3 * triangleIdx;
uint32 movingCornerIdx = Triangle::getLocalVertexIdx(oldIndices, doomedV);
if (Vertex::INVALID_INDEX == movingCornerIdx)
continue;
// edge conflict?
const uint32 newEdgeNeighbors[2] = { oldIndices[(movingCornerIdx + 1) % 3], oldIndices[(movingCornerIdx + 2) % 3] };
for (uint32 localEdgeIdx = 0; localEdgeIdx < 2; ++localEdgeIdx)
{
const uint32 globalEdgeIdx = getEdgeIndex(keptV, newEdgeNeighbors[localEdgeIdx]);
if (Edge::INVALID_INDEX == globalEdgeIdx || keptE[0] == globalEdgeIdx || keptE[1] == globalEdgeIdx)
continue;
return true;
}
}
}
return false;
}
void FlexibleMesh::updateTriangleIndicesForEdgeMerge(const uint32 keptVertex, const uint32 doomedVertex, const uint32 doomedT[2])
{
// update triangle indices: move from doomedVertex to keptV
const vector<uint32> &doomedVEdges = mVerticesToEdges[doomedVertex];
const uint32 doomedVEdgeCount = (uint32) doomedVEdges.size();
for (uint32 localDoomedEdgeIdx = 0; localDoomedEdgeIdx < doomedVEdgeCount; ++localDoomedEdgeIdx)
{
const uint32 movingEdgeIdx = doomedVEdges[localDoomedEdgeIdx];
const Edge &movingEdge = mEdges[movingEdgeIdx];
for (uint32 sideIdx = 0; sideIdx < 2; ++sideIdx)
{
const uint32 triangleIdx = movingEdge.getTriangleIndices()[sideIdx];
if (triangleIdx == doomedT[0] || triangleIdx == doomedT[1])
continue;
// update triangle corner indices
uint32 *indices = mIndices.data() + 3 * triangleIdx;
for (uint32 cornerIdx = 0; cornerIdx < 3; ++cornerIdx)
if (doomedVertex == indices[cornerIdx])
indices[cornerIdx] = keptVertex;
}
}
}
void FlexibleMesh::updateLinksForEdgeMerge(const uint32 keptV[3], const uint32 keptE[2],
const uint32 doomedV, const uint32 doomedT[2], const uint32 doomedE[3])
{
// remove doomed edges from vertices
removeVertexToEdgeLink(keptV[0], doomedE[0]);
removeVertexToEdgeLink(keptV[1], doomedE[1]);
removeVertexToEdgeLink(keptV[2], doomedE[2]);
removeVertexToEdgeLink(doomedV, doomedE[0]);
removeVertexToEdgeLink(doomedV, doomedE[1]);
removeVertexToEdgeLink(doomedV, doomedE[2]);
moveEdges(keptV[0], doomedV);
// update triangle links to go over the 2 merged / removed trianlges
for (uint32 sideIdx = 0; sideIdx < 2; ++sideIdx)
{
Edge &keptEdge = mEdges[keptE[sideIdx]];
const Edge &doomedEdge = mEdges[doomedE[sideIdx + 1]];
const uint32 replaced = doomedT[sideIdx];
const uint32 replacement = doomedEdge.getOtherTriangle(replaced);
keptEdge.replaceTriangle(replaced, replacement);
}
}
void FlexibleMesh::markDoomedElements(uint32 *globalDoomedVertices, uint32 *globalDoomedEdges, uint32 *globalDoomedTriangles,
const uint32 *doomedVertices, const uint32 doomedVertexCount,
const uint32 *doomedEdges, const uint32 doomedEdgeCount,
const uint32 *doomedTriangles, const uint32 doomedTriangleCount)
{
// doomed vertices
for (uint32 localVertexIdx = 0; localVertexIdx < doomedVertexCount; ++localVertexIdx)
globalDoomedVertices[doomedVertices[localVertexIdx]] = 1;
// doomed edges
for (uint32 localEdgeIdx = 0; localEdgeIdx < doomedEdgeCount; ++localEdgeIdx)
{
const uint32 globalIdx = doomedEdges[localEdgeIdx];
globalDoomedEdges[globalIdx] = 1;
Edge &edge = mEdges[globalIdx];
edge.setTriangles(Triangle::INVALID_INDEX, Triangle::INVALID_INDEX);
edge.setVertices(Vertex::INVALID_INDEX, Vertex::INVALID_INDEX);
}
// doomed triangles
for (uint32 sideIdx = 0; sideIdx < doomedTriangleCount; ++sideIdx)
{
const uint32 globalIdx = doomedTriangles[sideIdx];
globalDoomedTriangles[globalIdx] = 1;
uint32 *indices = mIndices.data() + 3 * globalIdx;
indices[0] = indices[1] = indices[2] = Vertex::INVALID_INDEX;
}
}
void FlexibleMesh::updateLinksForEdgeMerge(uint32 doomedV[3], uint32 &doomedVCount, uint32 doomedE[3],
const uint32 keptE[2], const uint32 keptV[2])
{
// keptV[1] == keptV[2] -> keptE[0] == keptE[1], doomedE[1] == doomedE[2], keptE should be removed
doomedE[2] = keptE[0];
// remove doomed edges from vertices
removeVertexToEdgeLink(doomedV[0], doomedE[0]);
removeVertexToEdgeLink(doomedV[0], doomedE[1]);
removeVertexToEdgeLink(keptV[0], doomedE[0]);
removeVertexToEdgeLink(keptV[0], doomedE[2]);
removeVertexToEdgeLink(keptV[1], doomedE[1]);
removeVertexToEdgeLink(keptV[1], doomedE[2]);
moveEdges(keptV[0], doomedV[0]);
// disconnected vertices keptV[0], keptV[1]?
for (uint32 i = 0; i < 2; ++i)
{
if (!mVerticesToEdges[keptV[i]].empty())
continue;
doomedV[doomedVCount] = keptV[i];
++doomedVCount;
}
}
void FlexibleMesh::moveEdges(const uint32 targetVertex, const uint32 sourceVertex)
{
// reconnect remaining / kept edges adjacent to doomedV to keptV[2]
vector<uint32> &sourceEdges = mVerticesToEdges[sourceVertex];
vector<uint32> &targetEdges = mVerticesToEdges[targetVertex];
const uint32 sourceCount = (uint32) sourceEdges.size();
targetEdges.reserve(targetEdges.size() + sourceCount);
for (uint32 localEdgeIdx = 0; localEdgeIdx < sourceCount; ++localEdgeIdx)
{
const uint32 globalEdgeIdx = sourceEdges[localEdgeIdx];
Edge &edge = mEdges[globalEdgeIdx];
edge.replaceVertex(sourceVertex, targetVertex);
targetEdges.push_back(globalEdgeIdx);
}
sourceEdges.clear();
}
void FlexibleMesh::subdivideEdges(const vector<uint32> &edges)
{
// anything to split?
const uint32 splitEdgeCount = (uint32) edges.size();
if (0 == splitEdgeCount)
return;
// old element counts & reserve
const uint32 oldVertexCount = getVertexCount();
const uint32 oldEdgeCount = getEdgeCount();
const uint32 oldTriangleCount = getTriangleCount();
// split edges
reserveForEdgeSplits(splitEdgeCount);
for (uint32 localEdgeIdx = 0; localEdgeIdx < splitEdgeCount; ++localEdgeIdx)
{
const uint32 globalEdgeIdx = edges[localEdgeIdx];
subdivideEdge(globalEdgeIdx);
}
onNewElements(oldVertexCount, oldEdgeCount, oldTriangleCount);
}
void FlexibleMesh::reserveForEdgeSplits(const uint32 splitEdgeCount)
{
const uint32 newVerticesPerSplit = 1;
const uint32 newEdgesPerSplit = 3;
const uint32 newTrianglesPerSplit = 2;
// new element counts
const uint32 newVertexCount = (uint32) (mPositions.size() + newVerticesPerSplit * splitEdgeCount);
const uint32 newEdgeCount = (uint32) (mEdges.size() + newEdgesPerSplit * splitEdgeCount);
const uint32 newIndexCount = (uint32) (mIndices.size() + splitEdgeCount * newTrianglesPerSplit * 3);
// reserve memory for vertices, edges & triangles
reserve(newVertexCount, newEdgeCount, newIndexCount);
}
void FlexibleMesh::subdivideEdge(const uint32 oldEdgeIdx)
{
// get edge & new vertex count
Edge &edge = mEdges[oldEdgeIdx];
const uint32 newVertexIdx = getVertexCount();
// indices of old adjacent traiangles & vertices
const uint32 oldEV[2] = { edge.getVertexIndices()[0], edge.getVertexIndices()[1] };
// create split vertex
resize(newVertexIdx + 1, getIndexCount());
interpolateEdgeSplitVertex(newVertexIdx, oldEV[0], oldEV[1]);
// shrink edge edgeIdx between 2 old triangles to one of its halves
removeVertexToEdgeLink(oldEV[1], oldEdgeIdx);
mVerticesToEdges[newVertexIdx].push_back(oldEdgeIdx);
mEdges[oldEdgeIdx].replaceVertex(oldEV[1], newVertexIdx);
// for each edge side: create 2 smaller triangles
const uint32 oldET[2] = { edge.getTriangleIndices()[0], edge.getTriangleIndices()[1] };
for (uint32 edgeSideIdx = 0; edgeSideIdx < 2; ++edgeSideIdx)
{
// get & check triangle idx
const uint32 oldTriangleIdx = oldET[edgeSideIdx];
if (Triangle::INVALID_INDEX == oldTriangleIdx)
continue;
// old triangle & index of its vertex opposite to the split edge
const uint32 *oldTriangle = getTriangle(oldTriangleIdx);
uint32 triangleIndices[3] = { oldTriangle[0], oldTriangle[1], oldTriangle[2] };
const uint32 oldOppoV = Triangle::getOtherVertex(triangleIndices, oldEV[0], oldEV[1]);
// 2 smaller triangles = old one shrinked + new neighbor triangle
shrinkOldEdgeSplitTriangles(newVertexIdx, oldEdgeIdx, oldEV, oldOppoV, oldTriangleIdx);
addNewEdgeSplitTriangles(triangleIndices, newVertexIdx, oldEV[0]);
}
//checkConnectivity("FlexibleMesh::subdivideEdge");
}
void FlexibleMesh::shrinkOldEdgeSplitTriangles(const uint32 newVertexIdx, const uint32 oldEdgeIdx,
const uint32 oldEV[2], const uint32 oldOppoV, const uint32 oldTriangleIdx)
{
// remove invalid edge connectivity of the old triangle and its old neighbor triangle adjacent to oldEV[1]
const uint32 invalidOuterEdge = getEdgeIndex(oldEV[1], oldOppoV);
mEdges[invalidOuterEdge].replaceTriangle(oldTriangleIdx, Triangle::INVALID_INDEX);
// update indices create 2 new edges
// reassign / shrink two old triangles
uint32 *t = mIndices.data() + 3 * oldTriangleIdx;
for (uint32 cornerIdx = 0; cornerIdx < 3; ++cornerIdx)
{
if (t[cornerIdx] != oldEV[1])
continue;
t[cornerIdx] = newVertexIdx;
break;
}
// create edge between old triangle and not yet existing neighbor split triangle
createEdge(newVertexIdx, oldOppoV, oldTriangleIdx);
}
void FlexibleMesh::addNewEdgeSplitTriangles(uint32 oldTriangle[3], const uint32 newIdx, const uint32 replacedIdx)
{
// new triangle within oldTriangleIndices but with one replaced index
for (uint32 cornerIdx = 0; cornerIdx < 3; ++cornerIdx)
{
if (oldTriangle[cornerIdx] != replacedIdx)
continue;
oldTriangle[cornerIdx] = newIdx;
break;
}
addTriangle(oldTriangle);
}
void FlexibleMesh::subdivideTriangles(vector<uint32> &doomedOnes, vector<uint32> *possiblyDoomedOnes)
{
// nothing to do?
const uint32 doomedCount = (uint32) doomedOnes.size();
if (0 == doomedCount)
return;
// reserve memory vertex & index buffer & possibly doomed triangles
reserveFor4Splits(doomedCount);
if (possiblyDoomedOnes)
{
const uint32 splitTrianglesPerDoomed = 16; // normal (& maximum count) case: 4 triangles -> 16 triangles
possiblyDoomedOnes->clear();
possiblyDoomedOnes->reserve(splitTrianglesPerDoomed * doomedCount);
}
// subdivide triangles
uint32 oldNeighborTriangles[3];
while (!doomedOnes.empty())
{
subdivideTriangle(doomedOnes.back(), oldNeighborTriangles, possiblyDoomedOnes);
// remove split traingles from doomedOnes to avoid spliting multiple times
doomedOnes.pop_back();
for (uint32 i = 0; i < 3; ++i)
{
if (Triangle::INVALID_INDEX == oldNeighborTriangles[i])
continue;
Array<uint32>::deleteFirstBySwapWithBack(doomedOnes, oldNeighborTriangles[i]);
}
}
cout << "subdivideTriangles" << endl;
checkEdges();
}
void FlexibleMesh::reserveFor4Splits(const uint32 splitTriangleCount)
{
// for each split triangle: how many new elements?
const uint32 newVerticesPerDoomed = 6;
const uint32 newEdgesPerDoomed = 15;
const uint32 newTrianglesPerDoomed = 12; // if a triangle is split into 4 and if t-vertices are avoided then there can be up to 12 additional triangles
// new element counts
const uint32 newVertexCount = (uint32) (mPositions.size() + splitTriangleCount * newVerticesPerDoomed);
const uint32 newEdgeCount = (uint32) (mEdges.size() + splitTriangleCount * newEdgesPerDoomed);
const uint32 newIndexCount = (uint32) (mIndices.size() + splitTriangleCount * newTrianglesPerDoomed * 3);
// reserve memory for vertices, edges & triangles
reserve(newVertexCount, newEdgeCount, newIndexCount);
}
void FlexibleMesh::subdivideTriangle(const uint32 triangleIdx, uint32 oldNeighborTriangles[3], vector<uint32> *splitTriangles)
{
if (Triangle::isInvalidIndex(triangleIdx))
{
assert(false);
throw Exception("FlexibleMesh::subdivideTriangle: Invalid triangle index for subdivision.");
}
const uint32 oldTriangleCount = (uint32) getTriangleCount();
uint32 newVertexIndices[6];
uint32 oldVertexIndices[6];
gatherIndicesForSplit(newVertexIndices, oldVertexIndices, oldNeighborTriangles, triangleIdx);
createNewVerticesForSubdivision(newVertexIndices, oldVertexIndices);
createSplitTriangles(newVertexIndices, oldVertexIndices, triangleIdx, oldNeighborTriangles);
gatherSplitTriangles(splitTriangles, triangleIdx, oldNeighborTriangles, oldTriangleCount);
}
void FlexibleMesh::gatherIndicesForSplit(uint32 newVertexIndices[6], uint32 oldVertexIndices[6], uint32 oldNeighborTriangles[3],
const uint32 triangleIdx) const
{
// partition triangle triangleIdx into 4 smaller triangles and also partition neighbor triangles into 4 triangles to avoid t-vertices
getTriangleNeighbors(oldNeighborTriangles, triangleIdx);
// get old triangle's vertex indices and indices of vertices opposite to the split edges of old triangle
// central triangle indices
const uint32 *oldTriangleStart = mIndices.data() + 3 * triangleIdx;
for (uint32 i = 0; i < 3; ++i)
oldVertexIndices[i] = oldTriangleStart[i];
// indices of vertices opposite to the edges of the old central triangle
for (uint32 i = 0; i < 3; ++i)
{
uint32 &oldIdx = oldVertexIndices[i + 3];
oldIdx = Vertex::INVALID_INDEX;
if (Triangle::isInvalidIndex(oldNeighborTriangles[i]))
continue;
const uint32 *neighborTriangle = mIndices.data() + oldNeighborTriangles[i] * 3;
const uint32 edgeVertex0 = oldVertexIndices[i];
const uint32 edgeVertex1 = oldVertexIndices[(i + 1) % 3];
oldIdx = Triangle::getOtherVertex(neighborTriangle, edgeVertex0, edgeVertex1);
}
// indices of new vertices from edge splits
const uint32 oldVertexCount = getVertexCount();
for (uint32 i = 0; i < 6; ++i)
newVertexIndices[i] = oldVertexCount + i;
}
void FlexibleMesh::createNewVerticesForSubdivision(const uint32 newVertexIndices[6], const uint32 oldVertexIndices[6])
{
// reserve memory depending on vertex count
const uint32 newVertexCount = (uint32) (mPositions.size() + 6);
resize(newVertexCount, getIndexCount());
// 3 split vertices within the inner triangle
for (uint32 i = 0; i < 3; ++i)
interpolateEdgeSplitVertex(newVertexIndices[i], oldVertexIndices[i], oldVertexIndices[(i + 1) % 3]);
// 3 split vertices at edges from previous 3 vertices and inner triangles 3 outer opposite corner vertices
for (uint32 i = 0; i < 3; ++i)
interpolateEdgeSplitVertex(newVertexIndices[i + 3], newVertexIndices[i], oldVertexIndices[i + 3]);
}
void FlexibleMesh::interpolateEdgeSplitVertex(const uint32 targetIdx, const uint32 v0, const uint32 v1, const Real f0)
{
interpolateVertex(targetIdx, v0, v1, f0);
const uint32 count = getObserverCount();
for (uint32 i = 0; i < count; ++i)
mObservers[i]->onEdgeSplitVertex(targetIdx, v0, v1);
}
void FlexibleMesh::interpolateVertex(const uint32 targetIdx, const uint32 v0, const uint32 v1, const Real f0)
{
const Real f1 = 1.0f - f0;
mPositions[targetIdx] = mPositions[v0] * f0 + mPositions[v1] * f1;
mColors[targetIdx] = mColors[v0] * f0 + mColors[v1] * f1;
mNormals[targetIdx] = mNormals[v0] * f0 + mNormals[v1] * f1;
mNormals[targetIdx].normalize();
mScales[targetIdx] = mScales[v0] * f0 + mScales[v1] * f1;
}
void FlexibleMesh::createSplitTriangles(const uint32 newVertexIndices[6], const uint32 oldVertexIndices[6],
const uint32 triangleIdx, const uint32 oldNeighborTriangles[3])
{
// replace central triangle and add 3 new triangles within old central triangle
replaceCentralTriangle(newVertexIndices, oldVertexIndices, triangleIdx);
for (uint32 i = 0; i < 3; ++i)
{
const uint32 indices[3] = { oldVertexIndices[i], newVertexIndices[i], newVertexIndices[(i + 2) % 3] };
addTriangle(indices);
}
// replace old neighbors by 4 new smaller triangles
for (uint32 i = 0; i < 3; ++i)
{
const uint32 neighborIdx = oldNeighborTriangles[i];
if (Triangle::isInvalidIndex(neighborIdx))
continue;
replaceNeighborTriangle(neighborIdx,
oldVertexIndices[i], newVertexIndices[i], oldVertexIndices[(i + 1) % 3],
newVertexIndices[i + 3], oldVertexIndices[i + 3]);
}
}
void FlexibleMesh::replaceCentralTriangle(const uint32 newVertexIndices[3], const uint32 oldVertexIndices[3], const uint32 triangleIdx)
{
// replace central triangle with smaller triangle between new split vertices
uint32 *targetTriangle = mIndices.data() + 3 * triangleIdx;
targetTriangle[0] = newVertexIndices[0];
targetTriangle[1] = newVertexIndices[1];
targetTriangle[2] = newVertexIndices[2];
// reset connectivity of triangle triangleIdx
reassignOldEdges(newVertexIndices, oldVertexIndices, triangleIdx);
}
void FlexibleMesh::reassignOldEdges(const uint32 newVertexIndices[3], const uint32 oldVertexIndices[3], const uint32 triangleIdx)
{
for (uint32 localEdgeIdx = 0; localEdgeIdx < 3; ++localEdgeIdx)
{
const uint32 temp = (localEdgeIdx + 1) % 3;
const uint32 newV0 = newVertexIndices[localEdgeIdx];
const uint32 newV1 = newVertexIndices[temp];
const uint32 oldV0 = oldVertexIndices[localEdgeIdx];
const uint32 oldV1 = oldVertexIndices[temp];
const uint32 globalEdgeIdx = getEdgeIndex(oldV0, oldV1);
// remove edge from old triangle
removeVertexToEdgeLink(oldV0, globalEdgeIdx);
removeVertexToEdgeLink(oldV1, globalEdgeIdx);
// completely reassign edge globalEdgeIdx
Edge &edge = mEdges[globalEdgeIdx];
edge.setTriangles(triangleIdx, Triangle::INVALID_INDEX);
edge.setVertices(newV0, newV1);
mVerticesToEdges[newV0].push_back(globalEdgeIdx);
mVerticesToEdges[newV1].push_back(globalEdgeIdx);
}
}
void FlexibleMesh::removeVertexToEdgeLink(const uint32 vertexIdx, const uint32 globalEdgeIdx)
{
std::vector<uint32> &edges = mVerticesToEdges[vertexIdx];
const size_t idx = Array<uint32>::deleteFirstBySwapWithBack(edges, globalEdgeIdx);
if ((size_t) -1 != idx)
return;
// wrong usage
string text = "Invalid call of FlexibleMesh::removeEdge()";
cerr << text << endl;
throw Exception(text);
}
void FlexibleMesh::replaceNeighborTriangle(const uint32 triangleIdx,
const uint32 splitEdgeV0, const uint32 splitEdgeCenterVertex, const uint32 splitEdgeV1,
const uint32 newCenterVertexIdx, const uint32 oldOppositeSplitVertex)
{
if (Triangle::isInvalidIndex(triangleIdx))
return;
// get vertex indices & edges
uint32 *triangle = mIndices.data() + 3 * triangleIdx;
const uint32 oldTriangleIndices[3] = { triangle[0], triangle[1], triangle[2] };
uint32 edgeIndices[3];
getEdgeIndices(edgeIndices, triangleIdx);
// keep connectivity to one neighbor triangle
uint32 replacedVertex = Vertex::INVALID_INDEX;
uint32 keptEdgeIdx = Edge::INVALID_INDEX;
for (uint32 localEdgeIdx = 0; localEdgeIdx < 3; ++localEdgeIdx)
{
// get & check edge index
const uint32 edgeIdx = edgeIndices[localEdgeIdx];
if (Edge::isInvalidIndex(edgeIdx))
continue;
// get & check edge
Edge &edge = mEdges[edgeIdx];
assert(edge.getTriangleIndices()[0] == triangleIdx || edge.getTriangleIndices()[1] == triangleIdx);
// only keep connectivity to one neighbor - other two neighbors will be created later
if (Edge::INVALID_INDEX != keptEdgeIdx)
{
// invalidate other edge link
edge.replaceTriangle(triangleIdx, Triangle::INVALID_INDEX);
continue;
}
// keep this edge and replace its opposite vertex to shrink the triangle
keptEdgeIdx = localEdgeIdx;
uint32 temp = (localEdgeIdx + 2) % 3;
replacedVertex = triangle[temp];
triangle[temp] = newCenterVertexIdx;
}
for (uint32 localEdgeIdx = 0; localEdgeIdx < 3; ++localEdgeIdx)
if (localEdgeIdx != keptEdgeIdx)
addEdge(triangleIdx, localEdgeIdx);
// 2 triangles adjacent to the split edge
addTriangle(splitEdgeCenterVertex, splitEdgeV0, newCenterVertexIdx);
addTriangle(splitEdgeV1, splitEdgeCenterVertex, newCenterVertexIdx);
// triangle adjacent oldOppositeSplitVertex and opposite to the kept edge
uint32 newTriangle[3];
for (uint32 i = 0; i < 3; ++i)
{
newTriangle[i] = oldTriangleIndices[i];
if (newTriangle[i] != replacedVertex && newTriangle[i] != oldOppositeSplitVertex)
newTriangle[i] = newCenterVertexIdx;
}
addTriangle(newTriangle);
}
bool FlexibleMesh::getAdjacentTriangleNormals(Math::Vector3 &n0, Math::Vector3 &n1, const uint32 edgeVertexIdx0, const uint32 edgeVertexIdx1) const
{
// does the edge exist?
const uint32 edgeIdx = getEdgeIndex(edgeVertexIdx0, edgeVertexIdx1);
if (Edge::INVALID_INDEX == edgeIdx)
return false;
// get the edge & its triangle indices
const Edge &edge = mEdges[edgeIdx];
const uint32 *indices = edge.getTriangleIndices();
// set n0
if (Triangle::isInvalidIndex(indices[0]))
{
n0.set(0.0f, 0.0f, 0.0f);
}
else
{
const uint32 *triangle = getTriangle(indices[0]);
Math::computeTriangleNormal(n0, mPositions[triangle[0]], mPositions[triangle[1]], mPositions[triangle[2]]);
}
// set n1
if (Triangle::isInvalidIndex(indices[1]))
{
n1.set(0.0f, 0.0f, 0.0f);
}
else
{
const uint32 *triangle = getTriangle(indices[1]);
Math::computeTriangleNormal(n1, mPositions[triangle[0]], mPositions[triangle[1]], mPositions[triangle[2]]);
}
return true;
}
uint32 FlexibleMesh::getEdgeIndex(const uint32 vertexIdx0, const uint32 vertexIdx1) const
{
// todo optimize this?
const vector<uint32> &edges = mVerticesToEdges[vertexIdx0];
const uint32 edgeCount = (uint32) edges.size();
// find the proper edge
for (uint32 i = 0; i < edgeCount; ++i)
{
const uint32 edgeIdx = edges[i];
const Edge &edge = mEdges[edgeIdx];
if (edge.isAdjacentToVertex(vertexIdx1))
return edgeIdx;
}
return Edge::INVALID_INDEX;
}
void FlexibleMesh::getEdgeIndices(uint32 edgeIndices[3], const uint32 triangleIdx) const
{
const uint32 *t = mIndices.data() + 3 * triangleIdx;
edgeIndices[0] = getEdgeIndex(t[0], t[1]);
edgeIndices[1] = getEdgeIndex(t[1], t[2]);
edgeIndices[2] = getEdgeIndex(t[2], t[0]);
}
void FlexibleMesh::findAdjacencies()
{
clearAdjacencies();
//cout << "Finding adjacency information of mesh elements." << endl;
// clear & reserve memory
const uint32 vertexCount = (uint32) mPositions.size();
const uint32 triangleCount = (uint32) mIndices.size() / 3;
mVerticesToEdges.resize(vertexCount);
mEdges.reserve(2 * vertexCount);
// for each triangle: add connectivity / edges
for (uint32 triangleIdx = 0; triangleIdx < triangleCount; ++triangleIdx)
for (uint32 edgeIdx = 0; edgeIdx < 3; ++edgeIdx) // process each triangle edge: new or already known?
addEdge(triangleIdx, edgeIdx);
//cout << "Computed connectivity of mesh elements." << endl;
}
void FlexibleMesh::clearAdjacencies()
{
// clean adjacency information (except triangles themselves)
const uint32 count = (uint32) mVerticesToEdges.size();
for (uint32 vertexIdx = 0; vertexIdx < count; ++vertexIdx)
mVerticesToEdges[vertexIdx].clear();
mEdges.clear();
}
void FlexibleMesh::addTriangle(const uint32 indices[3])
{
// add triangle neighbor
const uint32 newTriangleIdx = getTriangleCount();
const uint32 newTriangleCount = newTriangleIdx + 1;
// add vertex indices which represent the new triangle
mIndices.reserve(mIndices.size() + 3);
for (uint32 cornerIdx = 0; cornerIdx < 3; ++cornerIdx)
mIndices.push_back(indices[cornerIdx]);
// add connectivity
for (uint32 edgeIdx = 0; edgeIdx < 3; ++edgeIdx)
addEdge(newTriangleIdx, edgeIdx);
}
void FlexibleMesh::addEdge(const uint32 triangleIdx, const uint32 localEdgeIdx)
{
/// get ordered indices and edge index if it is new
const uint32 *triangle = mIndices.data() + 3 * triangleIdx;
const uint32 a = triangle[localEdgeIdx];
const uint32 b = triangle[(localEdgeIdx + 1) % 3];
const uint32 v0 = (a < b ? a : b);
const uint32 v1 = (a < b ? b : a);
// Does the edge <v0, v1> not exist?
const uint32 globalEdgeIdx = getEdgeIndex(v0, v1);
if (Edge::isInvalidIndex(globalEdgeIdx))
{
createEdge(v0, v1, triangleIdx);
return;
}
// each triangle can have up to 2 neighbor triangles
if (!mEdges[globalEdgeIdx].hasTwoNeighbors())
{
Edge &edge = mEdges[globalEdgeIdx];
edge.addTriangle(triangleIdx);
return;
}
// conflict
addEdgeConflict(globalEdgeIdx, triangleIdx);
}
uint32 FlexibleMesh::createEdge(const uint32 v0, const uint32 v1, const uint32 triangleIdx)
{
// new edge -> add it to the vertices' lists of links & edges
const uint32 nextGlobalEdgeIdx = (uint32) mEdges.size();
mVerticesToEdges[v0].push_back(nextGlobalEdgeIdx);
mVerticesToEdges[v1].push_back(nextGlobalEdgeIdx);
// create and add edge itself
Edge edge(v0, v1, triangleIdx);
mEdges.push_back(edge);
return nextGlobalEdgeIdx;
}
void FlexibleMesh::addEdgeConflict(const uint32 edgeIdx, const uint32 newTriangleIdx)
{
const Edge &edge = mEdges[edgeIdx];
const uint32 conflictCount = (uint32) mEdgeConflicts.size();
for (uint32 i = 0; i < conflictCount; ++i)
{
// does conflict edge already exist?
EdgeConflict &conflict = mEdgeConflicts[i];
if (edgeIdx != conflict.mEdgeIdx)
continue;
// found conflict edge - add triangle
conflict.mTriangles.push_back(newTriangleIdx);
return;
}
mEdgeConflicts.push_back(EdgeConflict(edge, edgeIdx));
mEdgeConflicts.back().mTriangles.push_back(newTriangleIdx);
// debug output for edge and conflict triangle
cerr << "Edge conflict!\n";
cerr << "New triangle " << newTriangleIdx << ", Edge " << edgeIdx << "\n";
cerr << edge << "\n";
// output adjacent triangle vertices
for (uint32 sideIdx = 0; sideIdx < 2; ++sideIdx)
{
const uint32 *t = getTriangle(edge.getTriangleIndices()[sideIdx]);
cerr << "Triangle " << sideIdx << ": (" << t[0] << "," << t[1] << "," << t[2] << ")\n";
}
cerr << flush;
throw Exception("BOOM");
}
void FlexibleMesh::getTriangleNeighbors(uint32 neighbors[3], const uint32 triangleIdx) const
{
const uint32 *indices = mIndices.data() + 3 * triangleIdx;
for (uint32 localEdgeIdx = 0; localEdgeIdx < 3; ++localEdgeIdx)
{
const uint32 v0 = indices[localEdgeIdx];
const uint32 v1 = indices[(localEdgeIdx + 1) % 3];
const uint32 globalEdgeIdx = getEdgeIndex(v0, v1);
const Edge &edge = mEdges[globalEdgeIdx];
neighbors[localEdgeIdx] = edge.getOtherTriangle(triangleIdx);
}
}
void FlexibleMesh::addVertex(const Math::Vector3 &color, const Math::Vector3 &normal, const Math::Vector3 &position, const Real scale)
{
const uint32 vertexIndex = getVertexCount();
resize(vertexIndex + 1, getIndexCount());
set(color, normal, position, scale, vertexIndex);
}
void FlexibleMesh::gatherSplitTriangles(vector<uint32> *splitTriangles,
const uint32 triangleIdx, const uint32 oldNeighborTriangles[3], const uint32 oldTriangleCount) const
{
// gather indices of triangles which were created by the 4 splits
if (!splitTriangles)
return;
const uint32 newTriangleCount = getTriangleCount();
splitTriangles->reserve(splitTriangles->size() + (newTriangleCount - oldTriangleCount));
splitTriangles->push_back(triangleIdx);
for (uint32 i = 0; i < 3; ++i)
if (!Triangle::isInvalidIndex(oldNeighborTriangles[i]))
splitTriangles->push_back(oldNeighborTriangles[i]);
for (uint32 splitTriangleIdx = oldTriangleCount; splitTriangleIdx < newTriangleCount; ++splitTriangleIdx)
splitTriangles->push_back(splitTriangleIdx);
}
void FlexibleMesh::getVertexNeighbors(vector<uint32> &neighbors, vector<uint32> &offsets) const
{
// clean start
neighbors.clear();
offsets.clear();
// compute offsets for quick access of actual neighbors
const uint32 vertexCount = getVertexCount();
offsets.resize(vertexCount + 1);
// prefix sum on neighbors sizes
uint32 totalNeighborCount = 0;
for (uint32 vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
{
offsets[vertexIdx] = totalNeighborCount;
const vector<uint32> &neighbors = mVerticesToEdges[vertexIdx];
const uint32 neighborCount = (uint32) neighbors.size();
totalNeighborCount += (uint32) neighborCount;
}
offsets[vertexCount] = totalNeighborCount;
// fill neighbors
neighbors.resize(totalNeighborCount);
#pragma omp parallel for
for (int64 vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
{
// get neighbors start & end
const uint32 start = offsets[vertexIdx];
const uint32 end = offsets[vertexIdx + 1];
const uint32 count = end - start;
// copy it to neighbors
const vector<uint32> &edges = mVerticesToEdges[vertexIdx];
uint32 *target = neighbors.data() + start;
for (uint32 localIdx = 0; localIdx < count; ++localIdx)
{
const uint32 edgeIdx = edges[localIdx];
const Edge &edge = mEdges[edgeIdx];
const uint32 neighborVertex = edge.getOtherVertex((uint32) vertexIdx);
target[localIdx] = neighborVertex;
}
}
}
FlexibleMesh &FlexibleMesh::operator =(const FlexibleMesh &rhs)
{
if (this == &rhs)
return *this;
// copy vertex data
mVerticesToEdges = rhs.mVerticesToEdges;
mColors = rhs.mColors;
mNormals = rhs.mNormals;
mPositions = rhs.mPositions;
mScales = rhs.mScales;
// edges & triangles
mEdges = rhs.mEdges;
mIndices = rhs.mIndices;
// remaining data
mEdgeConflicts = rhs.mEdgeConflicts;
return *this;
}
void FlexibleMesh::getEdges(uint32 edgeIndices[3], const uint32 triangleIdx) const
{
const uint32 *triangle = mIndices.data() + 3 * triangleIdx;
for (uint32 edgeIdx = 0; edgeIdx < 3; ++edgeIdx)
{
const uint32 v0 = triangle[edgeIdx];
const uint32 v1 = triangle[(edgeIdx + 1) % 3];
edgeIndices[edgeIdx] = getEdgeIndex(v0, v1);
}
}
void FlexibleMesh::deleteUnsupportedGeometry(const IVertexChecker &vertexChecker)
{
cout << "FlexibleMesh::deleteUnsupportedGeometry()" << endl;
const uint32 vertexCount = getVertexCount();
const uint32 edgeCount = getEdgeCount();
const uint32 triangleCount = getTriangleCount();
clearOffsets(vertexCount, edgeCount, triangleCount);
// detetect unsupported geometry & delete it
FlexibleMesh::computeOffsetsForFiltering(mVertexOffsets.data(), mEdgeOffsets.data(), mTriangleOffsets.data(),
vertexCount, edgeCount, triangleCount,
mVerticesToEdges.data(), mEdges.data(), mIndices.data(), vertexChecker);
deleteGeometry(mVertexOffsets.data(), mEdgeOffsets.data(), mTriangleOffsets.data());
}
void FlexibleMesh::clearOffsets(const uint32 vertexCount, const uint32 edgeCount, const uint32 triangleCount)
{
mVertexOffsets.clear();
mVertexOffsets.resize(vertexCount + 1);
mEdgeOffsets.clear();
mEdgeOffsets.resize(edgeCount + 1);
mTriangleOffsets.clear();
mTriangleOffsets.resize(triangleCount + 1);
}
void FlexibleMesh::deleteIsolatedGeometry(const uint32 triangleIslesMinSize)
{
cout << "FlexibleMesh::deleteIsolatedGeometry()" << endl;
const uint32 edgeCount = getEdgeCount();
const uint32 indexCount = getIndexCount();
const uint32 vertexCount = getVertexCount();
// detect isles & delete them
IslesEraser eraser(*this);
if (!eraser.computeOffsets(triangleIslesMinSize))
return;
deleteGeometry(eraser.getVertexOffsets(), eraser.getEdgeOffsets(), eraser.getTriangleOffsets());
cout << "Finished deletion of small isles (small isolated geometry parts)." << endl;
}
void FlexibleMesh::deleteGeometry(const uint32 *vertexOffsets, const uint32 *edgeOffsets, const uint32 *triangleOffsets)
{
cout << "FlexibleMesh::deleteGeometry()" << endl;
const uint32 vertexCount = getVertexCount();
const uint32 edgeCount = getEdgeCount();
const uint32 triangleCount = getTriangleCount();
// delete unsupported geometry
updateVertices(vertexOffsets, edgeOffsets);
updateEdges(vertexOffsets, edgeOffsets, triangleOffsets);
updateTriangles(vertexOffsets, triangleOffsets);
// update observers
const uint32 count = getObserverCount();
for (uint32 i = 0; i < count; ++i)
mObservers[i]->onFilterData(vertexOffsets, vertexCount, edgeOffsets, edgeCount, triangleOffsets, triangleCount);
}
void FlexibleMesh::updateVertices(const uint32 *vertexOffsets, const uint32 *edgeOffsets)
{
updateVertexData(vertexOffsets);
updateVertexToEdgeLinks(edgeOffsets);
}
void FlexibleMesh::updateVertexData(const uint32 *vertexOffsets)
{
const uint32 oldVertexCount = (uint32) mVerticesToEdges.size();
const uint32 newVertexCount = oldVertexCount - vertexOffsets[oldVertexCount];
// filter vertex data
Array<vector<uint32>>::compaction(mVerticesToEdges, vertexOffsets);
Array<Vector3>::compaction(mColors, vertexOffsets);
Array<Vector3>::compaction(mNormals, vertexOffsets);
Array<Vector3>::compaction(mPositions, vertexOffsets);
Array<Real>::compaction(mScales, vertexOffsets);
}
void FlexibleMesh::updateVertexToEdgeLinks(const uint32 *edgeOffsets)
{
// for each vertex: update edge links
const int64 vertexCount = mPositions.size();
#pragma omp parallel for
for (int64 vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
{
// process links (vertex -> edges)
vector<uint32> &adjacentEdges = mVerticesToEdges[vertexIdx];
for (uint32 localEdgeIdx = 0; localEdgeIdx < adjacentEdges.size(); )
{
// keep and update link to edge?
const uint32 oldGlobalEdgeIdx = adjacentEdges[localEdgeIdx];
if (edgeOffsets[oldGlobalEdgeIdx] == edgeOffsets[oldGlobalEdgeIdx + 1])
{
adjacentEdges[localEdgeIdx] = oldGlobalEdgeIdx - edgeOffsets[oldGlobalEdgeIdx];
++localEdgeIdx;
continue;
}
// delete edge link
adjacentEdges[localEdgeIdx] = adjacentEdges.back();
adjacentEdges.pop_back();
}
}
}
void FlexibleMesh::updateEdges(const uint32 *vertexOffsets, const uint32 *edgeOffsets, const uint32 *triangleOffsets)
{
updateEdgeData(edgeOffsets);
updateEdgeLinks(vertexOffsets, triangleOffsets);
}
void FlexibleMesh::updateEdgeData(const uint32 *edgeOffsets)
{
// remove deleted geometry
Array<Edge>::compaction(mEdges, edgeOffsets);
}
void FlexibleMesh::updateEdgeLinks(const uint32 *vertexOffsets, const uint32 *triangleOffsets)
{
// for each edge: update links to vertices and triangles
const int64 edgeCount = mEdges.size();
#pragma omp parallel for
for (int64 edgeIdx = 0; edgeIdx < edgeCount; ++edgeIdx)
{
Edge &edge = mEdges[edgeIdx];
// update links to vertices
const uint32 *oldVertices = edge.getVertexIndices();
edge.setVertices(oldVertices[0] - vertexOffsets[oldVertices[0]],
oldVertices[1] - vertexOffsets[oldVertices[1]]);
// update links to triangles
const uint32 *oldTriangles = edge.getTriangleIndices();
uint32 newTriangleIndices[2] = { Triangle::INVALID_INDEX, Triangle::INVALID_INDEX };
for (uint32 sideIdx = 0; sideIdx < 2; ++sideIdx)
{
const uint32 old = oldTriangles[sideIdx];
if (Triangle::INVALID_INDEX == old)
continue;
if (triangleOffsets[old] == triangleOffsets[old + 1])
newTriangleIndices[sideIdx] = old - triangleOffsets[old];
}
edge.setTriangles(newTriangleIndices[0], newTriangleIndices[1]);
}
}
void FlexibleMesh::updateTriangles(const uint32 *vertexOffsets, const uint32 *triangleOffsets)
{
updateTriangleData(vertexOffsets, triangleOffsets);
}
void FlexibleMesh::updateTriangleData(const uint32 *vertexOffsets, const uint32 *triangleOffsets)
{
// memory for new triangles
const uint32 oldIndexCount = (uint32) mIndices.size();
const uint32 oldTriangleCount = oldIndexCount / 3;
const uint32 newTriangleCount = oldTriangleCount - triangleOffsets[oldTriangleCount];
const uint32 newIndexCount = 3 * newTriangleCount;
// filter triangle indices
vector<uint32> newIndices(newIndexCount);
FlexibleMesh::filterTriangles(newIndices.data(), mIndices.data(), triangleOffsets, oldIndexCount, vertexOffsets);
mIndices.swap(newIndices);
}
void FlexibleMesh::set(const Vector3 &color, const Vector3 &normal, const Vector3 &position, const Real scale,
const uint32 vertexIdx)
{
if (vertexIdx >= getVertexCount())
{
// todo log this
return;
}
mColors[vertexIdx] = color;
mNormals[vertexIdx] = normal;
mPositions[vertexIdx] = position;
mScales[vertexIdx] = scale;
}
void FlexibleMesh::setIndices(const uint32 *indices, const uint32 indexCount)
{
mIndices.resize(indexCount);
memcpy(mIndices.data(), indices, sizeof(uint32) * indexCount);
findAdjacencies();
}
void FlexibleMesh::fillHoles()
{
vector<vector<uint32>> holeBorders(1);
vector<uint32> &border = holeBorders[0];
border.reserve(5000);
// find all edges at hole borders
const uint32 edgeCount = getEdgeCount();
#pragma omp parallel for
for (int64 i = 0; i < edgeCount; ++i)
{
// get edge data
const uint32 edgeIdx = (uint32) i;
const Edge &edge = mEdges[edgeIdx];
const uint32 *triangles = edge.getTriangleIndices();
// not a hole border edge?
if (Triangle::INVALID_INDEX != triangles[0] && Triangle::INVALID_INDEX != triangles[1])
continue;
const uint32 existingSide = (triangles[1] != Triangle::INVALID_INDEX);
const uint32 *triangle = getTriangle(triangles[existingSide]);
uint32 orderedVertices[2];
Triangle::getVerticesInWindingOrder(orderedVertices, triangle, edge.getVertexIndices());
#pragma omp critical (OMPPushBackHoleBorderEdge)
{
border.push_back(orderedVertices[0]);
border.push_back(orderedVertices[1]);
}
}
// find connected rings & fill holes
findBorderRings(holeBorders);
fillHoles(holeBorders);
}
void FlexibleMesh::findBorderRings(vector<vector<uint32>> &holeBorderEdges, const uint32 *vertexOffsets)
{
// remove emtpy border edge sets
for (uint32 borderIdx = 0; borderIdx < holeBorderEdges.size(); )
{
if (!holeBorderEdges[borderIdx].empty())
{
++borderIdx;
continue;
}
holeBorderEdges[borderIdx].swap(holeBorderEdges.back());
holeBorderEdges.pop_back();
}
// for each set of hole border edges: find all contained rings & store them separately in original/entered passing order
holeBorderEdges.resize(holeBorderEdges.size() + 1);
for (uint32 borderIdx = 0; borderIdx < holeBorderEdges.size() - 1; ++borderIdx)
{
vector<uint32> &potentiallyNewBorder = holeBorderEdges.back();
findBorderRing(potentiallyNewBorder, holeBorderEdges[borderIdx]);
if (!potentiallyNewBorder.empty())
holeBorderEdges.resize(holeBorderEdges.size() + 1);
}
if (holeBorderEdges.back().empty())
holeBorderEdges.pop_back();
removeDuplicatesInRings(holeBorderEdges, vertexOffsets);
}
void FlexibleMesh::findBorderRing(vector<uint32> &remainingEdges, vector<uint32> &edgeSet)
{
assert(remainingEdges.empty());
remainingEdges.clear();
const uint32 ringStart = edgeSet[0];
uint32 ringSize = 2;
//cout << "Processing border edges, edge count: " << edgeSet.size() << endl;
// find completely connected rings of border edges
const uint32 edgeCount = (uint32) edgeSet.size();
for (uint32 v0Idx = ringSize; v0Idx < edgeCount; )
{
//cout << "v0Idx, ring size, edge count << " << v0Idx << "," << ringSize << "," << edgeCount << endl;
const uint32 v1Idx = v0Idx + 1;
const uint32 edge[2] = { edgeSet[v0Idx], edgeSet[v1Idx] };
const uint32 ringEnd = edgeSet[ringSize - 1];
// does edge do not fit?
if (edge[0] != ringEnd)
{
v0Idx += 2;
continue;
}
extendBorderRing(ringSize, edgeSet, edge, v0Idx, v1Idx);
v0Idx = ringSize;
// no ring closure?
if (edge[1] != ringStart)
continue;
// more than 1 ring?
const uint32 remainingEdgeCount = edgeCount - ringSize;
if (0 == remainingEdgeCount)
return;
remainingEdges.reserve(remainingEdgeCount);
remainingEdges.insert(remainingEdges.end(), edgeSet.begin() + ringSize, edgeSet.end());
edgeSet.resize(ringSize);
return;
}
}
void FlexibleMesh::extendBorderRing(uint32 &size, vector<uint32> &edgeSet,
const uint32 edge[2], const uint32 v0Idx, const uint32 v1Idx)
{
// exchange edges & extend border ring
// preserve the edge at ring end memory location
const uint32 ringEnd0 = size;
const uint32 ringEnd1 = size + 1;
edgeSet[v0Idx] = edgeSet[ringEnd0];
edgeSet[v1Idx] = edgeSet[ringEnd1];
// extend ring
size += 2;
edgeSet[ringEnd0] = edge[0];
edgeSet[ringEnd1] = edge[1];
}
void FlexibleMesh::removeDuplicatesInRings(vector<vector<uint32>> &holeBorders, const uint32 *vertexOffsets)
{
// skip each second vertex and all vertices with vertexOffsets[vIdx] !+ vertexOffsets[vIdx + 1]
const uint32 ringCount = (uint32) holeBorders.size();
for (uint32 ringIdx = 0; ringIdx < ringCount; ++ringIdx)
{
vector<uint32> &ring = holeBorders[ringIdx];
const uint32 ringSize = (uint32) ring.size();
uint32 targetIdx = 0;
for (uint32 sourceIdx = 0; sourceIdx < ringSize; sourceIdx += 2)
{
const uint32 vIdx = ring[sourceIdx];
if (vertexOffsets && vertexOffsets[vIdx] != vertexOffsets[vIdx + 1])
continue;
ring[targetIdx++] = ring[sourceIdx];
}
ring.resize(targetIdx);
}
}
void FlexibleMesh::fillHoles(const vector<vector<uint32>> &holeBorderRings)
{
cout << "Filling surface holes." << endl;
// old element counts
const uint32 oldVertexCount = getVertexCount();
const uint32 oldEdgeCount = getEdgeCount();
const uint32 oldTriangleCount = getTriangleCount();
// reserve memory for new element counts
reserveForHoleFilling(holeBorderRings);
// fill each hole with a single vertex as mean of all corresponding hole border vertices
const uint32 holeCount = (uint32) holeBorderRings.size();
for (uint32 holeIdx = 0; holeIdx < holeCount; ++holeIdx)
{
const vector<uint32> &holeBorder = holeBorderRings[holeIdx];
const uint32 borderVertexCount = (uint32) holeBorder.size();
// hole center position
Vector3 center;
for (uint32 i = 0; i < borderVertexCount; ++i)
center += mPositions[holeBorder[i]];
center /= (Real) borderVertexCount;
fillHole(holeBorder.data(), borderVertexCount, center);
}
onNewElements(oldVertexCount, oldEdgeCount, oldTriangleCount);
//checkConnectivity("FlexibleMesh::fillHoles");
}
void FlexibleMesh::fillHole(const uint32 *borderVertices, const uint32 borderEdgeCount, const Vector3 ¢er)
{
// debug output
//cout << "fillHole" << (borderVertices ? " with borderVertices" : "") << ", size: " << borderEdgeCount << endl;
//if (borderVertices)
//{
// for (uint32 i = 0; i < borderEdgeCount; ++i)
// cout << borderVertices[i] << " ";
// cout << endl;
//}
if (borderEdgeCount <= 5)
{
fillHole(borderVertices, borderEdgeCount);
return;
}
// vertex counts
const uint32 oldVertexCount = getVertexCount();
const uint32 additionalVertexCount = borderEdgeCount / 2;
const uint32 newVertexCount = oldVertexCount + additionalVertexCount;
createHoleFillingRingVertices(borderVertices, borderEdgeCount, newVertexCount, center);
connectHoleFillingRings(borderVertices, borderEdgeCount, oldVertexCount, additionalVertexCount);
// do the same for a smaller problem size
fillHole(NULL, additionalVertexCount, center);
}
void FlexibleMesh::createHoleFillingRingVertices(const uint32 *borderVertices, const uint32 borderEdgeCount,
const uint32 newVertexCount, const Vector3 ¢er)
{
// create a smaller, inner ring and connect it to border
const uint32 oldVertexCount = getVertexCount();
resize(newVertexCount, getIndexCount());
// distance of new ring relative to last ring and center?
uint32 remainingRingCount = 0;
for (uint32 temp = borderEdgeCount; temp; temp >>= 1)
++remainingRingCount;
remainingRingCount -= 1;
const Real f0 = (remainingRingCount - 1) / (Real) remainingRingCount;
const Real f1 = 1.0f / remainingRingCount;
// position the ring
const uint32 previousRingStart = oldVertexCount - borderEdgeCount;
const uint32 lastVertex = newVertexCount - 1;
uint32 borderVertex = (borderVertices ? 0 : previousRingStart);
for (uint32 vertexIdx = oldVertexCount; vertexIdx < newVertexCount; ++vertexIdx)
{
const uint32 v0 = (borderVertices ? borderVertices[borderVertex] : borderVertex);
++borderVertex;
const uint32 v1 = (borderVertices ? borderVertices[borderVertex] : borderVertex);
++borderVertex;
uint32 v2;
if (vertexIdx == lastVertex)
v2 = (borderVertices ? borderVertices[0] : previousRingStart);
else
v2 = (borderVertices ? borderVertices[borderVertex] : borderVertex);
// set p to center of 2 edges & somewhat towars hole center
Vector3 &p = mPositions[vertexIdx];
p = mPositions[v0] + mPositions[v1] + mPositions[v2];
p = (p * (f0 / 3.0f) + center * f1);
}
}
void FlexibleMesh::connectHoleFillingRings(const uint32 *borderVertices, const uint32 borderEdgeCount,
const uint32 oldVertexCount, const uint32 additionalVertexCount)
{
// connect the ring new ring [oldVertexCount, newVertexCount) to the previous ring borderVertices or [oldVertexCount - borderEdgeCount, oldVertexCount)
// triangles with outer ring edges
//cout << "Adding outer triangles of new triangle ring.\n";
const uint32 outerRingStart = (borderVertices ? 0 : oldVertexCount - borderEdgeCount);
const uint32 lastInnerOffset = additionalVertexCount - 1;
const bool odd = (1 == (borderEdgeCount & 1));
for (uint32 outerOffset = outerRingStart, innerOffset = 0; innerOffset < additionalVertexCount; ++innerOffset)
{
const uint32 outerV0 = (borderVertices ? borderVertices[outerOffset] : outerOffset);
++outerOffset;
const uint32 outerV1 = (borderVertices ? borderVertices[outerOffset] : outerOffset);
++outerOffset;
uint32 outerV2 ;
if (!odd && innerOffset == lastInnerOffset)
outerV2 = (borderVertices ? borderVertices[outerRingStart] : outerRingStart);
else
outerV2 = (borderVertices ? borderVertices[outerOffset] : outerOffset);
//cout << "outerOffset " << outerOffset << " innerOffset " << innerOffset;
//cout << "outerV0 " << outerV0 << " outerV1 " << outerV1 << " inner " << (oldVertexCount + innerOffset);
addTriangle(outerV0, outerV1, oldVertexCount + innerOffset);
addTriangle(outerV1, outerV2, oldVertexCount + innerOffset);
}
// one more outer ring edge triangle due to odd border edge number?
if (odd)
{
//cout << "Adding outer triangle due to odd edge count.\n";
if (borderVertices)
addTriangle(borderVertices[borderEdgeCount - 1], borderVertices[0], getVertexCount() - 1);
else
addTriangle(oldVertexCount - 1, outerRingStart, getVertexCount() - 1);
}
// triangles with inner ring edges
//cout << "Adding inner triangles of new ring.\n";
//cout << "outerRingStart " << outerRingStart;
for (uint32 outerOffset = outerRingStart + 2, innerOffset = 0; innerOffset < additionalVertexCount; outerOffset += 2)
{
const uint32 innerV0 = oldVertexCount + innerOffset;
uint32 innerV1;
uint32 outerV;
++innerOffset;
if (innerOffset == additionalVertexCount)
{
innerV1 = oldVertexCount;
outerV = (borderVertices ? borderVertices[outerRingStart] : outerRingStart);
}
else
{
innerV1 = oldVertexCount + innerOffset;
outerV = (borderVertices ? borderVertices[outerOffset] : outerOffset);
}
//cout << "inner triangle: " << innerV0 << " " << outerV << " " << innerV1 << endl;
addTriangle(innerV0, outerV, innerV1);
}
}
void FlexibleMesh::fillHole(const uint32 *borderVertices, const uint32 borderEdgeCount)
{
// get indices for new triangles
uint32 indices[5];
if (borderVertices)
{
memcpy(indices, borderVertices, sizeof(uint32) * borderEdgeCount);
}
else
{
const uint32 start = getVertexCount() - borderEdgeCount;
for (uint32 i = 0; i < borderEdgeCount; ++i)
indices[i] = start + i;
}
// add up to 3 triangles to fill the hole without new vertices
addTriangle(indices[0], indices[1], indices[2]);
if (3 == borderEdgeCount)
return;
addTriangle(indices[2], indices[3], indices[0]);
if (4 == borderEdgeCount)
return;
addTriangle(indices[3], indices[4], indices[0]);
if (5 == borderEdgeCount)
return;
assert(false);
}
void FlexibleMesh::reserveForHoleFilling(const vector<vector<uint32>> &holeBorders)
{
const uint32 holeCount = (uint32) holeBorders.size();
uint32 newVertexCount = getVertexCount();
uint32 newEdgeCount = getEdgeCount();
uint32 newTriangleCount = getTriangleCount();
// each hole is filled whereas smaller rings are inserted until a ring size of 5 is reached
// each smaller ring has (previousRingSize / 2) new vertices
for (uint32 holeIdx = 0; holeIdx < holeCount; ++holeIdx)
{
const vector<uint32> &border = holeBorders[holeIdx];
const uint32 edgeCount = (uint32) border.size();
for (uint32 ringSize = edgeCount; ringSize > 5; )
{
if (ringSize > 5)
{
const uint32 nextRingSize = ringSize / 2;
newVertexCount += nextRingSize;
newEdgeCount += nextRingSize * 4 + (ringSize & 1);
newTriangleCount += ringSize + nextRingSize;
ringSize = nextRingSize;
continue;
}
if (ringSize < 3)
{
assert(false);
throw Exception("Wrongly implemented hole filling.");
}
// new elements if only 5, 4 or 3 border edges are left
// newVertexCount +=0;
newEdgeCount += ringSize - 3;
newTriangleCount += ringSize - 2;
break;
}
}
reserve(newVertexCount, newEdgeCount, newTriangleCount * 3);
}
Math::Vector3 FlexibleMesh::getCenterOfNeighbors(const uint32 vertexIdx) const
{
// neighborhood data
const vector<uint32> &edgeIndices = mVerticesToEdges[vertexIdx];
const uint32 neighborCount = (uint32) edgeIndices.size();
// sum of neighbor positions
Vector3 center;
for (uint32 neighborIdx = 0; neighborIdx < neighborCount; ++neighborIdx)
{
const uint32 edgeIdx = edgeIndices[neighborIdx];
const Edge &edge = mEdges[edgeIdx];
const uint32 neighborvertexIdx = edge.getOtherVertex(vertexIdx);
const Vector3 &p = mPositions[neighborvertexIdx];
center += p;
}
// average
center /= (Real) neighborCount;
return center;
}
void FlexibleMesh::onNewElements(const uint32 oldVertexCount, const uint32 oldEdgeCount, const uint32 oldTriangleCount)
{
// new element counts
const uint32 vertexCount = getVertexCount();
const uint32 edgeCount = getEdgeCount();
const uint32 triangleCount = getTriangleCount();
const uint32 observerCount = getObserverCount();
for (uint32 observerIdx = 0; observerIdx < observerCount; ++observerIdx)
mObservers[observerIdx]->onNewElements(oldVertexCount, vertexCount, oldEdgeCount, edgeCount, oldTriangleCount, triangleCount);
}
void FlexibleMesh::reserve(const uint32 newVertexCount, const uint32 newEdgeCount, const uint32 newIndexCount)
{
// vertices
mVerticesToEdges.reserve(newVertexCount);
mColors.reserve(newVertexCount);
mNormals.reserve(newVertexCount);
mPositions.reserve(newVertexCount);
mScales.reserve(newVertexCount);
// edges
mEdges.reserve(newEdgeCount);
// triangles & indices
mIndices.reserve(newIndexCount);
// update observers
const uint32 observerCount = getObserverCount();
for (uint32 observerIdx = 0; observerIdx < observerCount; ++observerIdx)
mObservers[observerIdx]->onReserveMemory(newVertexCount, newEdgeCount, newIndexCount);
}
void FlexibleMesh::allocateMemory(const uint32 vertexCount, const uint32 indexCount)
{
resize(vertexCount, indexCount);
}
void FlexibleMesh::resize(const uint32 newVertexCount, const uint32 newIndexCount)
{
// vertices
mVerticesToEdges.resize(newVertexCount);
mColors.resize(newVertexCount);
mNormals.resize(newVertexCount);
mPositions.resize(newVertexCount);
mScales.resize(newVertexCount);
// triangles
mIndices.resize(newIndexCount);
}
void FlexibleMesh::doSelfCheck() const
{
#ifdef _DEBUG
// check vertex data
const uint32 vertexCount = getVertexCount();
for (uint32 vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
{
const Vector3 &c = mColors[vertexIdx];
const Vector3 &n = mNormals[vertexIdx];
const Vector3 &p = mPositions[vertexIdx];
const Real &s = mScales[vertexIdx];
assert(!p.hasNaNComponent());
assert(!n.hasNaNComponent());
assert(!c.hasNaNComponent());
assert(!isNaN(s));
}
#endif // _DEBUG
}
void FlexibleMesh::checkEdges() const
{
// counts & edges
const uint32 vertexCount = getVertexCount();
const uint32 edgeCount = getEdgeCount();
const uint32 triangleCount = getTriangleCount();
// check vertices & triangles of each edge
for (uint32 i = 0; i < edgeCount; ++i)
{
const Edge &edge = mEdges[i];
const uint32 *triangles = edge.getTriangleIndices();
const uint32 *vertices = edge.getVertexIndices();
bool error = false;
for (uint32 sideIdx = 0; sideIdx < 2; ++sideIdx)
if (triangles[sideIdx] >= triangleCount || vertices[sideIdx] >= vertexCount)
error = true;
if (!error)
continue;
// debug output
string message = "checkEdges(): found a broken edge.\n";
cerr << message;
cerr << "Index: " << i << "\n";
cerr << edge << endl;
cout << message;
cout << "Index: " << i << "\n";
cout << edge << endl;
}
}
//void FlexibleMesh::checkConnectivity(const string &info,
// const uint32 *doomedVertices, const uint32 *doomedEdges, const uint32 *doomedTriangles) const
//{
// // check edges
// const uint32 edgeCount = getEdgeCount();
// #pragma omp parallel for
// for (int64 edgeIdx = 0; edgeIdx < edgeCount; ++edgeIdx)
// {
// if (doomedEdges && doomedEdges[edgeIdx])
// continue;
//
// const Edge &edge = mEdges[edgeIdx];
// const uint32 *triangles = edge.getTriangleIndices();
// const uint32 *vertices = edge.getVertexIndices();
//
// // is there a problem?
// bool error = false;
// error |= Triangle::INVALID_INDEX == triangles[0] || Triangle::INVALID_INDEX == triangles[1] ||
// Vertex::INVALID_INDEX == vertices[0] || Vertex::INVALID_INDEX == vertices[1];
// if (doomedVertices)
// error |= (doomedVertices[vertices[0]] || doomedVertices[vertices[1]]);
// if (doomedTriangles)
// error |= (doomedTriangles[triangles[0]] || doomedTriangles[triangles[1]]);
// if (!error)
// continue;
//
// #pragma omp critical (OMPCout)
// {
// cout << info << endl;
// cout << "Invalid edge: " << edgeIdx;
// cout << edge;
// cout << endl;
// }
// }
//
// // check vertices
// if (doomedVertices && doomedEdges)
// {
// const uint32 vertexCount = getVertexCount();
// #pragma omp parallel for
// for (int64 vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
// {
// if (doomedVertices[vertexIdx])
// continue;
//
// const vector<uint32> &edges = mVerticesToEdges[vertexIdx];
// const uint32 edgeCount = (uint32) edges.size();
// for (uint32 localEdgeIdx = 0; localEdgeIdx < edgeCount; ++localEdgeIdx)
// {
// const uint32 globalEdgeIdx = edges[localEdgeIdx];
// if (!doomedEdges[globalEdgeIdx])
// continue;
//
// const Edge &edge = mEdges[globalEdgeIdx];
// #pragma omp critical (OMPCout)
// {
// cout << info << endl;
// cout << "Invalid vertex to edge link: " << vertexIdx << "," << localEdgeIdx << "," << globalEdgeIdx << endl;
// cout << edge;
// cout << endl;
// }
// }
// }
// }
//
// // check triangles
// if (doomedVertices && doomedTriangles)
// {
// const uint32 triangleCount = getTriangleCount();
// #pragma omp parallel for
// for (int64 triangleIdx = 0; triangleIdx < triangleCount; ++triangleIdx)
// {
// if (doomedTriangles[triangleIdx])
// continue;
//
// const uint32 *triangle = getTriangle((uint32) triangleIdx);
// const bool error = (Vertex::INVALID_INDEX == triangle[0] || Vertex::INVALID_INDEX == triangle[1] || Vertex::INVALID_INDEX == triangle[2]);
// if (!error)
// continue;
//
// #pragma omp critical (OMPCout)
// {
// cout << info << endl;
// cout << "Invalid triangle: " << triangleIdx << ": " << triangle[0] << "," << triangle[1] << "," << triangle[2];
// cout << endl;
// }
// }
// }
//}
//FlexibleMesh copy(*this);
//copy.setColor(Vector3(1.0f, 0.0f, 0.0f), 2800);
//copy.setColor(Vector3(1.0f, 0.0f, 0.0f), 2801);
//copy.saveToFile("C:\\Dev\\Scenes\\ShellTower\\Results\\loaded", true, false);
//checkConnectivity("findAdjacencies"); | 33.587273 | 180 | 0.733571 | [
"mesh",
"geometry",
"object",
"vector"
] |
633d768c633e58e1e723aac7f32ed72e3d49b138 | 3,767 | cpp | C++ | testMain.cpp | Ellie-42/FlaxCoin-Core | 2d93dd8a73e46bf562356e526ca79da7dc7ffc37 | [
"MIT"
] | null | null | null | testMain.cpp | Ellie-42/FlaxCoin-Core | 2d93dd8a73e46bf562356e526ca79da7dc7ffc37 | [
"MIT"
] | null | null | null | testMain.cpp | Ellie-42/FlaxCoin-Core | 2d93dd8a73e46bf562356e526ca79da7dc7ffc37 | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include "blockChain.h"
#include <json/json.h>
#include <chrono>
#include "wallet.h"
#include "block.h"
int main()
{
std::cout<<"Compiled!"<<std::endl;
blockChain testNet;
std::shared_ptr<block> genBlockTest = testNet.getBlockAtIndex(0);
std::cout<<"Genesis Block\n"<<"-------------------"<<std::endl;
std::cout<<*genBlockTest;
std::cout<<"Combined data: " << genBlockTest->combineTxData()<<std::endl;
std::cout<<"\n-------------------\n"<<std::endl;
std::cout<<"JSON Testing on: " << "Genesis Block" <<std::endl;
Json::Value testData = genBlockTest->toJson();
std::shared_ptr<block> testBlockClone(new block(testData));
std::cout<<"\nLoad from JSON test:"<<std::endl;
std::cout<<*testBlockClone;
std::cout<<"Combined data: " << testBlockClone->combineTxData()<<std::endl;
std::cout<<"\n-------------------\n"<<std::endl;
std::vector<std::string> transData;
transData.push_back("This should be jsonified transaction data");
std::cout<<"Made some data."<<std::endl;
std::shared_ptr<block> blockTest=std::shared_ptr<block>(new block(1, genBlockTest->getCurHash(), std::time(nullptr), transData, 0));
mineAlgo miner(blockTest);
std::cout<<"Mining algo made."<<std::endl;
std::cout<<"Data!"<<std::endl;
miner.setBlockData(miner.mine());
std::cout<<"Block? Mined."<<std::endl;
if(testNet.addBlock(blockTest)==0)
{
std::cout<<"The addition of a new block has been successful.\nRaising the difficulty."<<std::endl;
}
else
{
std::cout<<"The new block did not validate. Exiting..."<<std::endl;
return -404;
}
transData.push_back("But is it? No.");
std::shared_ptr<block> blockTest2 = std::shared_ptr<block>(new block(2,blockTest->getCurHash(), std::time(nullptr),transData,5));
miner.setCurBlock(blockTest2);
miner.setBlockData(miner.mine());
if(testNet.addBlock(blockTest2)==0)
{
std::cout<<"The addition of the second new block has been successful.\nRaising the difficulty."<<std::endl;
}
else
{
std::cout<<"The second new block did not validate. Exiting..."<<std::endl;
return -405;
}
std::shared_ptr<block> blockTest3 = std::shared_ptr<block>(new block(3,blockTest2->getCurHash(), std::time(nullptr),transData,7));
miner.setCurBlock(blockTest3);
miner.setBlockData(miner.mine());
if(testNet.addBlock(blockTest3)==0)
{
std::cout<<"The addition of the thirds new block has been successful.\nRaising the difficulty."<<std::endl;
}
else
{
std::cout<<"The thirds new block did not validate. Exiting..."<<std::endl;
return -405;
}
std::cout<<"The block chain test has been successful. Good job.\nTesting wallet creation and recreation."<<std::endl;
wallet wal01;
std::string wallString01 = wal01.generateWallet("EllieIsCool");
std::cout<<"Seed: "<<wallString01<<std::endl;
std::cout<<"Regenerating a new wallet from the same seed."<<std::endl;
wallet wal02;
if(wal02.loadWalletFromSeed(wallString01, "EllieIsCool"))
{
std::cout<<"Load from seed is a success!"<<std::endl;
}
else
{
std::cout<<"Load from seed failed."<<std::endl;
}
if(wal01.getKeyAtIndex(0)._publicAddr == wal02.getKeyAtIndex(0)._publicAddr)
{
std::cout<<"The keys are the same."<<std::endl;
}
std::cout<<"Transaction testing! Once this is done, the genesis block will contain a single transaction out, containing the first "<< coin_symb <<" coin to an address known only to the creator, because it was randomly generated on her computer in a separate program." << std::endl;
return 0;
}
| 33.04386 | 285 | 0.637112 | [
"vector"
] |
634211e228e46bcc30cd4878383f3298439c9da6 | 46,436 | cpp | C++ | src/common/wfsadecoder/ActiveStateTable.cpp | atk-/bavieca-0014 | 031216739b4800285af717f22f44ecda54675139 | [
"Apache-2.0"
] | null | null | null | src/common/wfsadecoder/ActiveStateTable.cpp | atk-/bavieca-0014 | 031216739b4800285af717f22f44ecda54675139 | [
"Apache-2.0"
] | null | null | null | src/common/wfsadecoder/ActiveStateTable.cpp | atk-/bavieca-0014 | 031216739b4800285af717f22f44ecda54675139 | [
"Apache-2.0"
] | null | null | null | /*---------------------------------------------------------------------------------------------*
* Copyright (C) 2012 Daniel Bolaños - www.bltek.com - Boulder Language Technologies *
* *
* www.bavieca.org is the website of the Bavieca Speech Recognition Toolkit *
* *
* 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 "ActiveStateTable.h"
#include "BestPath.h"
#include "LMManager.h"
#include "LexiconManager.h"
#include "TimeUtils.h"
namespace Bavieca {
// contructor
ActiveStateTable::ActiveStateTable(float fPruningLikelihood, int iPruningMaxStates, unsigned int iActiveStatesMax, PhoneSet *phoneSet, LexiconManager *lexiconManager, HMMStateDecoding *hmmStatesDecoding, bool bLatticeGeneration, int iMaxWordSequencesState)
{
m_phoneSet = phoneSet;
m_lexiconManager = lexiconManager;
m_hmmStatesDecoding = hmmStatesDecoding;
m_fPruningLikelihood = fPruningLikelihood;
m_iPruningMaxStates = iPruningMaxStates;
m_iActiveStatesMax = iActiveStatesMax;
m_iHashBuckets = 2*iActiveStatesMax;
m_iHashEntries = m_iHashBuckets+m_iActiveStatesMax; // this guarantees that in the worst case scenario (all collisions), there are enough entries to store collisions
// lattice generation
m_bLatticeGeneration = bLatticeGeneration;
m_iMaxWordSequencesState = iMaxWordSequencesState;
m_iWSHashBuckets = UINT_MAX;
m_iWSHashEntries = UINT_MAX;
m_wshashEntries = NULL;
m_iWSHashEntryCollisionAvailable = -1;
m_iLexUnitPronSilence = m_lexiconManager->getLexUnitSilence()->iLexUnitPron;
m_iLexUnitPronUnknown = m_lexiconManager->m_lexUnitUnknown->iLexUnitPron;
m_activeStatesCurrent = NULL;
m_activeStatesNext = NULL;
m_hashEntries = NULL;
// history items
m_iHistoryItems = 0;
m_historyItems = NULL;
m_iHistoryItemAvailable = -1;
m_iTimeGarbageCollectionLast = -1;
// wrod-graph tokens
m_iWGTokens = 0;
m_wgTokens = NULL;
m_iWGTokenAvailable = -1;
m_iWGTokensUsed = 0;
m_iWordSequenceInitial = -1;
}
ActiveStateTable::~ActiveStateTable()
{
if (m_activeStatesCurrent) {
delete [] m_activeStatesCurrent;
}
if (m_activeStatesNext) {
delete [] m_activeStatesNext;
}
if (m_activeStatesEpsilon) {
delete [] m_activeStatesEpsilon;
}
if (m_hashEntries) {
delete [] m_hashEntries;
}
if (m_historyItems) {
delete [] m_historyItems;
}
if (m_wshashEntries) {
cleanHashWordSequences();
delete [] m_wshashEntries;
}
if (m_wgTokens) {
delete [] m_wgTokens;
}
}
// hash table related functions
void ActiveStateTable::initialize() {
// allocate memory for the hash table
m_hashEntries = new HashEntry[m_iHashEntries];
// set all the entries as "old"
for(int i=0 ; i < (int)m_iHashEntries ; ++i) {
m_hashEntries[i].iTime = -1;
}
m_iTimeCurrent = 0;
// allocate memory for the hash tables of active states
m_activeStatesCurrent = new ActiveState[m_iActiveStatesMax];
m_activeStatesNext = new ActiveState[m_iActiveStatesMax];
m_activeStatesEpsilon = new ActiveStateEpsilon[m_iActiveStatesMax];
m_activeStateAvailable = m_activeStatesNext;
m_activeStateEpsilonHead = m_activeStatesEpsilon;
m_activeStateEpsilonTail = m_activeStatesEpsilon;
m_iHashEntryCollisionAvailable = m_iHashBuckets;
m_iActiveStatesCurrent = 0;
// history item management
//m_iHistoryItems = m_iActiveStatesMax;
m_iHistoryItems = 100;
//m_iHistoryItems = 10000000;
m_historyItems = new HistoryItem[m_iHistoryItems];
for(unsigned int i=0 ; i < m_iHistoryItems-1 ; ++i) {
m_historyItems[i].iActive = -1;
m_historyItems[i].iPrev = i+1;
}
m_historyItems[m_iHistoryItems-1].iActive = -1;
m_historyItems[m_iHistoryItems-1].iPrev = -1;
m_iHistoryItemAvailable = 0;
m_iTimeGarbageCollectionLast = -1;
// lattice generation
if (m_bLatticeGeneration) {
// allocate memory for the hash table
m_iWSHashBuckets = 100000;
m_iWSHashEntries = 2*m_iWSHashBuckets;
m_wshashEntries = new WSHashEntry[m_iWSHashEntries];
// set all the entries as "old"
for(int i=0 ; i < (int)m_iWSHashEntries ; ++i) {
m_wshashEntries[i].iTime = -1;
}
m_iWSHashEntryCollisionAvailable = m_iWSHashBuckets;
// lattice token management
m_iWGTokens = m_iActiveStatesMax*m_iMaxWordSequencesState;
//m_iWGTokens = 30*m_iMaxWordSequencesState;
//m_iWGTokens = 10000000;
m_wgTokens = new WGToken[m_iWGTokens];
for(unsigned int i=0 ; i < m_iWGTokens-1 ; i += m_iMaxWordSequencesState) {
m_wgTokens[i].iActive = -1;
m_wgTokens[i].iPrev = i+m_iMaxWordSequencesState;
}
m_wgTokens[m_iWGTokens-m_iMaxWordSequencesState].iActive = -1;
m_wgTokens[m_iWGTokens-m_iMaxWordSequencesState].iPrev = -1;
m_iWGTokenAvailable = 0;
}
}
// compute the load factor of the hash table containing active states
float ActiveStateTable::computeLoadFactor() {
// count
unsigned int iValid = 0;
for(int i=0 ; i < (int)m_iHashBuckets ; ++i) {
if (m_hashEntries[i].iTime == m_iTimeCurrent) {
++iValid;
}
}
return ((float)iValid)/((float)m_iHashBuckets);
}
// compute the collision factor (# collisions / # valid entries in the table)
float ActiveStateTable::computeCollisionFactor() {
// count
unsigned int iValid = 0;
unsigned int iCollisions = 0;
for(unsigned int i=0 ; i < m_iHashEntries ; ++i) {
if (m_hashEntries[i].iTime == m_iTimeCurrent) {
if (i < m_iHashBuckets) {
++iValid;
} else {
++iCollisions;
}
}
}
if (iValid == 0) {
assert(iCollisions == 0);
return 0.0;
}
return ((float)iCollisions)/((float)iValid);
}
// compute the load factor of the hash table containing unque word sequences
float ActiveStateTable::computeLoadFactorHashWordSequences(int *iBucketsUsed, int *iCollisions) {
// count
*iBucketsUsed = 0;
*iCollisions = 0;
for(unsigned int i=0 ; i < m_iWSHashEntries ; ++i) {
if (m_wshashEntries[i].iTime > -1) {
if (i < m_iWSHashBuckets) {
++(*iBucketsUsed);
} else {
++(*iCollisions);
}
}
}
// load factor
return ((float)(*iBucketsUsed))/((float)m_iWSHashBuckets);
}
// shows object information
void ActiveStateTable::printInfo() {
float fLoadFactor = computeLoadFactor();
float fCollisionFactor = computeCollisionFactor();
float fSize = m_iActiveStatesMax*3*sizeof(ActiveState); // there are three tables of active states
fSize += m_iHashEntries*sizeof(HashEntry); // there is a hash table
fSize += m_iHistoryItems*sizeof(HistoryItem);
// convert to MB
fSize /= 1024*1024;
printf("-----------------------------------------\n");
printf("load factor: %8.4f\n",fLoadFactor);
printf("collision factor: %8.4f\n",fCollisionFactor);
printf("size: %8.2f MB\n",fSize);
printf("-----------------------------------------\n");
}
// activates the initial state
void ActiveStateTable::activateStateInitial(StateX *state) {
// create the <s> history item
int iHistoryItem = newHistoryItem();
HistoryItem *historyItem = m_historyItems+iHistoryItem;
historyItem->iLexUnitPron = m_lexiconManager->m_lexUnitBegSentence->iLexUnitPron;
historyItem->iEndFrame = -1;
historyItem->iPrev = -1;
historyItem->iActive = -1;
historyItem->iWGToken = -1;
// treat it like an epsilon state
m_activeStateEpsilonTail->state = state;
m_activeStateEpsilonTail->fScore = 0.0;
m_activeStateEpsilonTail->iHistoryItem = iHistoryItem;
if (m_bLatticeGeneration) {
// create the root lattice token
m_activeStateEpsilonTail->iWGToken = newWGToken();
(m_activeStateEpsilonTail->iWGToken+m_wgTokens)[0].iWordSequence = -2;
(m_activeStateEpsilonTail->iWGToken+m_wgTokens)[0].iLexUnitPron = m_iLexUnitPronUnknown;
(m_activeStateEpsilonTail->iWGToken+m_wgTokens)[0].fScore = 0.0;
(m_activeStateEpsilonTail->iWGToken+m_wgTokens)[0].iHistoryItem = iHistoryItem;
(m_activeStateEpsilonTail->iWGToken+m_wgTokens)[1].iWordSequence = -1;
m_iWordSequenceInitial = (m_activeStateEpsilonTail->iWGToken+m_wgTokens)[0].iWordSequence;
} else {
m_activeStateEpsilonTail->iWGToken = -1;
}
++m_activeStateEpsilonTail;
}
// process epsilon transitions in topological order
void ActiveStateTable::processEpsilonTransitions(float *fFeatureVector, float *fScoreBest) {
TransitionX *transition = NULL;
TransitionX *transitionEnd = NULL;
TransitionX *transitionAux = NULL;
float fScore = 0.0;
HMMStateDecoding *hmmStateDecoding = NULL;
unsigned int iLexUnitEndSentence = m_lexiconManager->m_lexUnitEndSentence->iLexUnit;
assert(m_activeStateEpsilonHead <= m_activeStateEpsilonTail);
while(m_activeStateEpsilonHead != m_activeStateEpsilonTail) {
//printf("# active epsilon states: %d\n",m_activeStateEpsilonTail-m_activeStateEpsilonHead);
transition = *m_activeStateEpsilonHead->state;
transitionEnd = *(m_activeStateEpsilonHead->state+1);
//printf("# transitions: %d\n",transitionEnd-transition);
while(transition != transitionEnd) {
//printf("%u %f %x\n",transition->iSymbol,transition->fWeight,transition->state);
//printTransition(transition);
// epsilon transition
if (transition->iSymbol & EPSILON_TRANSITION) {
// lattice generation
int iWGToken = -1;
if (m_bLatticeGeneration) {
assert(m_activeStateEpsilonHead->iWGToken != -1);
iWGToken = newWGToken(m_activeStateEpsilonHead->iWGToken);
WGToken *wgToken = iWGToken+m_wgTokens;
// update the scores
for(int i=0 ; ((i < m_iMaxWordSequencesState) && (wgToken[i].iWordSequence != -1)) ; ++i) {
wgToken[i].fScore += transition->fWeight;
}
}
// activate the state
activateStateEpsilon(transition->state,m_activeStateEpsilonHead->fScore+transition->fWeight,
m_activeStateEpsilonHead->iHistoryItem,iWGToken,0.0);
}
// fake transitions
else if (transition->iSymbol & FAKE_TRANSITION) {
}
// lexical unit transition
else if (transition->iSymbol & LEX_UNIT_TRANSITION) {
if ((transition->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT) == iLexUnitEndSentence) {
++transition;
continue;
}
// create a new history item
int iHistoryItem = newHistoryItem();
HistoryItem *historyItem = m_historyItems+iHistoryItem;
historyItem->iPrev = m_activeStateEpsilonHead->iHistoryItem;
historyItem->iLexUnitPron = transition->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT;
historyItem->iEndFrame = m_iTimeCurrent-1;
historyItem->fScore = m_activeStateEpsilonHead->fScore+transition->fWeight;
historyItem->iActive = -1;
// lattice generation
int iWGToken = -1;
int iWordSequence = -1;
if (m_bLatticeGeneration) {
// keep the best N word sequences arriving to the state
assert(m_activeStateEpsilonHead->iWGToken != -1);
historyItem->iWGToken = m_activeStateEpsilonHead->iWGToken;
// checks
for(int i=0 ; i < m_iMaxWordSequencesState ; ++i) {
if ((historyItem->iWGToken+m_wgTokens)[i].iWordSequence == -1) {
break;
}
m_lexiconManager->print(m_lexiconManager->getLexUnitPron(historyItem->iLexUnitPron));
assert(historyItem->iEndFrame > m_historyItems[(historyItem->iWGToken+m_wgTokens)[i].iHistoryItem].iEndFrame);
}
// generate a new hash value for the new word sequence
iWordSequence = hashWordSequence(historyItem);
}
for(transitionAux = *(transition->state) ; *(transition->state+1) ; ++transitionAux) {
if ((transitionAux->iSymbol & LEX_UNIT_TRANSITION) == iLexUnitEndSentence) {
continue;
} else {
//printTransition(transitionAux);
assert((transitionAux->iSymbol & LEX_UNIT_TRANSITION) == 0);
}
// epsilon-transition
if (transitionAux->iSymbol & EPSILON_TRANSITION) {
// preventive pruning
if (m_activeStateEpsilonHead->fScore+transition->fWeight+transitionAux->fWeight < (*fScoreBest-m_fPruningLikelihood)) {
continue;
}
// lattice generation
if (m_bLatticeGeneration) {
iWGToken = newWGToken(iWordSequence,m_activeStateEpsilonHead->fScore+transition->fWeight+transitionAux->fWeight,iHistoryItem);
}
// activate the state
activateStateEpsilon(transitionAux->state,
m_activeStateEpsilonHead->fScore+transition->fWeight+transitionAux->fWeight,iHistoryItem,iWGToken,0.0);
}
// fake transition
else if (transitionAux->iSymbol & FAKE_TRANSITION) {
}
// leaf-transition
else {
// compute emission probability
hmmStateDecoding = &m_hmmStatesDecoding[transitionAux->iSymbol];
#ifdef SIMD
fScore = hmmStateDecoding->computeEmissionProbabilityNearestNeighborSIMD(fFeatureVector,m_iTimeCurrent);
#else
fScore = hmmStateDecoding->computeEmissionProbabilityNearestNeighborPDE(fFeatureVector,m_iTimeCurrent);
#endif
// preventive pruning
if (m_activeStateEpsilonHead->fScore+transition->fWeight+transitionAux->fWeight+fScore < (*fScoreBest-m_fPruningLikelihood)) {
continue;
}
// lattice generation
if (m_bLatticeGeneration) {
iWGToken = newWGToken(iWordSequence,m_activeStateEpsilonHead->fScore+transition->fWeight+transitionAux->fWeight+fScore,iHistoryItem);
}
// activate the state
activateState(transitionAux->state,
m_activeStateEpsilonHead->fScore+transition->fWeight+transitionAux->fWeight+fScore,
fScoreBest,hmmStateDecoding,iHistoryItem,iWGToken,0.0);
}
}
}
// leaf transition
else {
// compute emission probability
hmmStateDecoding = &m_hmmStatesDecoding[transition->iSymbol];
#ifdef SIMD
float fScore = hmmStateDecoding->computeEmissionProbabilityNearestNeighborSIMD(fFeatureVector,0);
#else
float fScore = hmmStateDecoding->computeEmissionProbabilityNearestNeighborPDE(fFeatureVector,0);
#endif
// preventive pruning goes here
// lattice generation
int iWGToken = -1;
if (m_bLatticeGeneration) {
assert(m_activeStateEpsilonHead->iWGToken != -1);
iWGToken = newWGToken(m_activeStateEpsilonHead->iWGToken);
WGToken *wgToken = iWGToken+m_wgTokens;
// update the scores
for(int i=0 ; ((i < m_iMaxWordSequencesState) && (wgToken[i].iWordSequence != -1)) ; ++i) {
wgToken[i].fScore += transition->fWeight+fScore;
}
}
// activate the state
activateState(transition->state,m_activeStateEpsilonHead->fScore+transition->fWeight+fScore,fScoreBest,
hmmStateDecoding,m_activeStateEpsilonHead->iHistoryItem,iWGToken,0.0);
}
++transition;
}
++m_activeStateEpsilonHead;
if (m_activeStateEpsilonHead-m_activeStatesEpsilon == (int)m_iActiveStatesMax) {
m_activeStateEpsilonHead = m_activeStatesEpsilon;
}
}
}
// apply beam pruning to the set of active states
void ActiveStateTable::beamPruning(float *fScoreBest) {
unsigned int iActive = m_activeStateAvailable-m_activeStatesNext;
unsigned int iRemoved = 0;
int iNumberBins = BEAM_PRUNING_NUMBER_BINS;
float fScoreWorst = FLT_MAX;
//checkTokens();
//printf("t=%d pruning starts -------------------------------------------\n",m_iTimeCurrent);
// (1) standard beam-pruning O(n)
float fMinimumScore = *fScoreBest-m_fPruningLikelihood;
for(ActiveState *activeState = m_activeStatesNext ; activeState != m_activeStateAvailable ; ++activeState) {
if (activeState->fScore < fMinimumScore) {
activeState->state = NULL;
++iRemoved;
} else if (activeState->fScore < fScoreWorst) {
fScoreWorst = activeState->fScore;
}
//printf("%10.2f\n",activeState->fScore);
}
// (2) Histogram pruning O(n)
// check if it applies (only if the number of active states exceeds the maximum allowed)
if (iActive-iRemoved > (unsigned int)m_iPruningMaxStates) {
// (2.1) compute the size of each bin and initialize them
float fLength = *fScoreBest-fScoreWorst+1;
float fBinSize = ((float)fLength)/((float)iNumberBins);
assert(fBinSize > 0);
int iBins[iNumberBins];
for(int i = 0 ; i < iNumberBins ; ++i) {
iBins[i] = 0;
}
// (2.2) fill the bins, the first bin keeps the best tokens
int iBin;
float fAux = ((float)iNumberBins)/fLength;
for(ActiveState *activeState = m_activeStatesNext ; activeState != m_activeStateAvailable ; ++activeState) {
if (activeState->state != NULL) {
iBin = (int)(fabs(*fScoreBest-activeState->fScore)*fAux);
assert((iBin >= 0) && (iBin < iNumberBins));
iBins[iBin]++;
}
}
//for(int i = 0 ; i < iNumberBins ; ++i) {
// printf("bin %3d: %d\n",i,iBins[i]);
//}
// (2.3) actual pruning O(n), tokens in the last bin always survive
int iSurvivors = 0;
for(int i = 0 ; i < iNumberBins-1 ; ++i) {
iSurvivors += iBins[i];
// remove tokens in the remaining bins
if (iSurvivors >= m_iPruningMaxStates) {
float fThreshold = *fScoreBest-(((float)(i+1))*(fLength/((float)iNumberBins)));
for(ActiveState *activeState = m_activeStatesNext ; activeState != m_activeStateAvailable ; ++activeState) {
if (activeState->state != NULL) {
if (activeState->fScore < fThreshold) {
activeState->state = NULL;
++iRemoved;
}
}
}
break;
}
}
}
if (m_iTimeCurrent%100 == 0) {
printf("t=%5d # active states: %6u (removed: %6u, bestScore: %14.6f)\n",m_iTimeCurrent,iActive-iRemoved,iRemoved,*fScoreBest);
if (m_bLatticeGeneration) {
//printHashTableWordSequences();
}
}
m_iStatesPruned = iRemoved;
//printf("expanded: %10u active: %10u pruned: %10u\n",m_iStatesExpanded,m_iStatesActivated,m_iStatesPruned);
}
// garbage collection of history items and word-lattice tokens (lattice generation mode)
// (1) it starts by marking the active items by traversing back items from the active states
// (2) it adds inactive items to the queue of available items
// note: garbage collection of lattice tokens is necessary since every time there is
// a merge of two list of tokens (only the n-best tokens are kept at any state) the tree of
// lattice tokens belonging to the removed elements is lost
void ActiveStateTable::historyItemGarbageCollection() {
unsigned int iItemsActive = 0;
unsigned int iTokensActive = 0;
// (1) check if garbage collection was already run within the current time frame
// note: this is an undesirable situation because it requires an extra pass over the complete array of items
// it should be avoided by allocating a larger number of entries from the beginning
if (m_iTimeGarbageCollectionLast == m_iTimeCurrent) {
// mark all the history items and wg-tokens as inactive
for(unsigned int i=0 ; i < m_iHistoryItems ; ++i) {
m_historyItems[i].iActive = -1;
}
for(unsigned int i=0 ; i < m_iWGTokens ; i += m_iMaxWordSequencesState) {
m_wgTokens[i].iActive = -1;
}
}
bool *bTokensActive = new bool[m_iWGTokens];
for(unsigned int i=0 ; i < m_iWGTokens ; ++i) {
bTokensActive[i] = false;
}
// array to keep the active history items
int iHistoryItemActiveSize = 0;
int *iHistoryItemActive = new int[m_iHistoryItems];
// (1) mark items coming from active nodes as active
// (1.1) active nodes from current time frame
ActiveState *activeState = m_activeStatesCurrent;
ActiveState *activeStateCurrentLast = m_activeStatesCurrent+m_iActiveStatesCurrent;
while(activeState != activeStateCurrentLast) {
// skip pruned states
if (activeState->state == NULL) {
++activeState;
continue;
}
int iHistoryItem = activeState->iHistoryItem;
while((iHistoryItem != -1) && ((m_historyItems+iHistoryItem)->iActive != m_iTimeCurrent)) {
(m_historyItems+iHistoryItem)->iActive = m_iTimeCurrent;
iHistoryItemActive[iHistoryItemActiveSize++] = iHistoryItem;
iHistoryItem = (m_historyItems+iHistoryItem)->iPrev;
++iItemsActive;
}
if (m_bLatticeGeneration) {
// mark the wg-token as active
assert(activeState->iWGToken != -1);
(activeState->iWGToken+m_wgTokens)->iActive = m_iTimeCurrent;
assert((bTokensActive[activeState->iWGToken] == false));
bTokensActive[activeState->iWGToken] = true;
++iTokensActive;
// keep history items at the current wg-token
for(int i=0 ; (i < m_iMaxWordSequencesState) && ((activeState->iWGToken+m_wgTokens)[i].iWordSequence != -1) ; ++i) {
HistoryItem *historyItem = m_historyItems+(activeState->iWGToken+m_wgTokens)[i].iHistoryItem;
if (historyItem->iActive != m_iTimeCurrent) {
historyItem->iActive = m_iTimeCurrent;
assert(historyItem->iWGToken >= -1);
iHistoryItemActive[iHistoryItemActiveSize++] = historyItem-m_historyItems;
++iItemsActive;
}
}
}
++activeState;
}
// (1.2) epsilon states
assert(m_activeStateEpsilonHead <= m_activeStateEpsilonTail);
ActiveStateEpsilon *activeStateEpsilon = m_activeStateEpsilonHead;
while(activeStateEpsilon != m_activeStateEpsilonTail) {
assert(activeStateEpsilon->state != NULL);
int iHistoryItem = activeStateEpsilon->iHistoryItem;
while((iHistoryItem != -1) && ((m_historyItems+iHistoryItem)->iActive != m_iTimeCurrent)) {
(m_historyItems+iHistoryItem)->iActive = m_iTimeCurrent;
iHistoryItemActive[iHistoryItemActiveSize++] = iHistoryItem;
iHistoryItem = (m_historyItems+iHistoryItem)->iPrev;
++iItemsActive;
}
if (m_bLatticeGeneration) {
// mark the wg-token as active
assert(activeStateEpsilon->iWGToken != -1);
(activeStateEpsilon->iWGToken+m_wgTokens)->iActive = m_iTimeCurrent;
assert((bTokensActive[activeStateEpsilon->iWGToken] == false));
bTokensActive[activeStateEpsilon->iWGToken] = true;
++iTokensActive;
// keep history items at the current wg-token
for(int i=0 ; (i < m_iMaxWordSequencesState) && ((activeStateEpsilon->iWGToken+m_wgTokens)[i].iWordSequence != -1) ; ++i) {
HistoryItem *historyItem = m_historyItems+(activeStateEpsilon->iWGToken+m_wgTokens)[i].iHistoryItem;
if (historyItem->iActive != m_iTimeCurrent) {
historyItem->iActive = m_iTimeCurrent;
assert(historyItem->iWGToken >= -1);
iHistoryItemActive[iHistoryItemActiveSize++] = historyItem-m_historyItems;
++iItemsActive;
}
}
}
++activeStateEpsilon;
if (activeStateEpsilon-m_activeStatesEpsilon == (int)m_iActiveStatesMax) {
activeStateEpsilon = m_activeStatesEpsilon;
}
}
// (1.3) active nodes from next time frame
activeState = m_activeStatesNext;
while(activeState != m_activeStateAvailable) {
assert(activeState->state != NULL);
int iHistoryItem = activeState->iHistoryItem;
while((iHistoryItem != -1) && ((m_historyItems+iHistoryItem)->iActive != m_iTimeCurrent)) {
(m_historyItems+iHistoryItem)->iActive = m_iTimeCurrent;
iHistoryItemActive[iHistoryItemActiveSize++] = iHistoryItem;
iHistoryItem = (m_historyItems+iHistoryItem)->iPrev;
++iItemsActive;
}
if (m_bLatticeGeneration) {
// mark the wg-token as active
assert(activeState->iWGToken != -1);
(activeState->iWGToken+m_wgTokens)->iActive = m_iTimeCurrent;
assert((bTokensActive[activeState->iWGToken] == false));
bTokensActive[activeState->iWGToken] = true;
++iTokensActive;
// keep history items at the current wg-token
for(int i=0 ; (i < m_iMaxWordSequencesState) && ((activeState->iWGToken+m_wgTokens)[i].iWordSequence != -1) ; ++i) {
HistoryItem *historyItem = m_historyItems+(activeState->iWGToken+m_wgTokens)[i].iHistoryItem;
if (historyItem->iActive != m_iTimeCurrent) {
historyItem->iActive = m_iTimeCurrent;
assert(historyItem->iWGToken >= -1);
iHistoryItemActive[iHistoryItemActiveSize++] = historyItem-m_historyItems;
++iItemsActive;
}
}
}
++activeState;
}
if (m_bLatticeGeneration) {
while(iHistoryItemActiveSize > 0) {
HistoryItem *historyItem = m_historyItems+iHistoryItemActive[iHistoryItemActiveSize-1];
--iHistoryItemActiveSize;
if (historyItem->iWGToken != -1) {
(historyItem->iWGToken+m_wgTokens)->iActive = m_iTimeCurrent;
if (bTokensActive[historyItem->iWGToken] == false) {
bTokensActive[historyItem->iWGToken] = true;
++iTokensActive;
for(int i=0 ; ((i < m_iMaxWordSequencesState) && ((historyItem->iWGToken+m_wgTokens)[i].iWordSequence != -1)) ; ++i) {
HistoryItem *historyItem2 = m_historyItems+(historyItem->iWGToken+m_wgTokens)[i].iHistoryItem;
if (historyItem2->iActive != m_iTimeCurrent) {
historyItem2->iActive = m_iTimeCurrent;
iHistoryItemActive[iHistoryItemActiveSize++] = historyItem2-m_historyItems;
++iItemsActive;
}
}
}
}
}
}
//printf("time: %d\n",m_iTimeCurrent);
//printf("history item garbage collection...\n");
//printf("(items used: %d existing: %d)\n",iItemsActive,m_iHistoryItems);
// a bigger data structure to keep the new history items
// (* if we wait until all the items are active there will be many calls to the garbage collector
// when the array of reach a high occupation, that would introduce substantial overhead)
assert(iItemsActive <= m_iHistoryItems);
if (iItemsActive >= (0.20*m_iHistoryItems)) {
//printf("history item garbage collection...\n");
//printf("allocating space for new items (item sused: %d existing: %d)\n",iItemsActive,m_iHistoryItems);
// allocate a new data structure with double capacity
HistoryItem *historyItems = new HistoryItem[m_iHistoryItems*2];
// copy the active items from the old data structure
for(unsigned int i=0 ; i < m_iHistoryItems ; ++i) {
memcpy(historyItems+i,m_historyItems+i,sizeof(HistoryItem));
historyItems[i].iActive = m_iTimeCurrent;
}
// create the linked list of available items
for(unsigned int i=m_iHistoryItems ; i < (2*m_iHistoryItems)-1 ; ++i) {
historyItems[i].iPrev = i+1;
historyItems[i].iActive = -1;
}
historyItems[(2*m_iHistoryItems)-1].iPrev = -1;
historyItems[(2*m_iHistoryItems)-1].iActive = -1;
delete [] m_historyItems;
m_historyItems = historyItems;
m_iHistoryItemAvailable = m_iHistoryItems;
m_iHistoryItems *= 2;
}
// (2') there are inactive items: create a linked list with them
else {
int *iHistoryItemAux = &m_iHistoryItemAvailable;
for(unsigned int i = 0 ; i < m_iHistoryItems ; ++i) {
if (m_historyItems[i].iActive != m_iTimeCurrent) {
m_historyItems[i].iActive = -1;
m_historyItems[i].iEndFrame = -1;
*iHistoryItemAux = i;
iHistoryItemAux = &m_historyItems[i].iPrev;
}
}
*iHistoryItemAux = -1;
}
delete [] iHistoryItemActive;
//printf("wg-token garbage collection...\n");
//printf("(wg-tokens used: %d existing: %d)\n",iTokensActive,m_iWGTokens/m_iMaxWordSequencesState);
// lattice token garbage collection
if (m_bLatticeGeneration) {
assert(iTokensActive <= (m_iWGTokens/m_iMaxWordSequencesState));
if (iTokensActive >= 0.20*(m_iWGTokens/m_iMaxWordSequencesState)) {
//assert(0);
// allocate a new data structure with double capacity
WGToken *wgTokens = NULL;
try {
//printf("allocating wg-tokens: %d\n",m_iWGTokens*2);
wgTokens = new WGToken[m_iWGTokens*2];
}
catch (const std::bad_alloc&) {
int iMB = m_iWGTokens*2*sizeof(WGToken);
BVC_ERROR << "unable to allocate memory for the lattice tokens, " << iMB << "MBs needed";
}
//printf("WGTokens: from %d to %d\n",m_iWGTokens*sizeof(WGToken),m_iWGTokens*2*sizeof(WGToken));
// copy the active items from the old data structure
for(unsigned int i=0 ; i < m_iWGTokens ; ++i) {
memcpy(wgTokens+i,m_wgTokens+i,sizeof(WGToken));
wgTokens[i].iPrev = -1;
wgTokens[i].iActive = m_iTimeCurrent;
}
// create the linked list of available items
unsigned int iLastIndex = ((2*m_iWGTokens)-m_iMaxWordSequencesState);
for(unsigned int i=m_iWGTokens ; i < iLastIndex ; i += m_iMaxWordSequencesState) {
wgTokens[i].iPrev = i+m_iMaxWordSequencesState;
wgTokens[i].iActive = -1;
}
wgTokens[iLastIndex].iPrev = -1;
wgTokens[iLastIndex].iActive = -1;
// swap structures and delete the old one
delete [] m_wgTokens;
m_wgTokens = wgTokens;
m_iWGTokenAvailable = m_iWGTokens;
m_iWGTokens *= 2;
}
// there are inactive tokens: create a linked list with them
else {
//printf("WGTokens: relinking\n");
// the linked list goes from lower to higher memory addresses
int *iAux = &m_iWGTokenAvailable;
for(unsigned int i = 0 ; i < m_iWGTokens ; i += m_iMaxWordSequencesState) {
if (m_wgTokens[i].iActive != m_iTimeCurrent) {
*iAux = i;
iAux = &m_wgTokens[i].iPrev;
}
}
*iAux = -1;
}
}
delete [] bTokensActive;
m_iTimeGarbageCollectionLast = m_iTimeCurrent;
}
// recovers the best path from the list of active states
BestPath *ActiveStateTable::getBestPath(int iFeatureVectors) {
BestPath *bestPath = new BestPath(m_lexiconManager,-1.0);
// (1) get the best scoring active state
ActiveState *activeStateBest = NULL;
int iLexUnitLastBest = -1;
int iLexUnitLast = -1;
ActiveState *activeState = m_activeStatesNext;
float fScoreBest = -FLT_MAX;
while(activeState != m_activeStateAvailable) {
// get the last lexical unit
iLexUnitLast = -1;
// get the best transition to a lexical unit (the transition with smaller weight including the transition to </s>)
TransitionX *transitionBest = NULL;
float fScoreBestTransition = -FLT_MAX;
for(TransitionX *transition = *activeState->state ; transition != *(activeState->state+1) ; ++transition) {
if (transition->iSymbol & LEX_UNIT_TRANSITION) {
float fScore = transition->fWeight;
// find the transition to the end of sentence </s>
bool bFound = false;
float fScoreFinalBest = -FLT_MAX;
for(TransitionX *transition2 = *transition->state ; transition2 != *(transition->state+1) ; ++transition2) {
if (transition2->iSymbol & LEX_UNIT_TRANSITION) {
if ((int)(transition2->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT) == m_lexiconManager->m_lexUnitEndSentence->iLexUnit) {
if (transition2->fWeight > fScoreFinalBest) {
fScoreFinalBest = transition2->fWeight;
}
bFound = true;
//break;
}
} else if (transition2->iSymbol & EPSILON_TRANSITION) {
for(TransitionX *transition3 = *transition2->state ; transition3 != *(transition2->state+1) ; ++transition3) {
if (transition3->iSymbol & LEX_UNIT_TRANSITION) {
if ((int)(transition3->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT) == m_lexiconManager->m_lexUnitEndSentence->iLexUnit) {
if (transition2->fWeight + transition3->fWeight > fScoreFinalBest) {
fScoreFinalBest = transition2->fWeight + transition3->fWeight;
}
bFound = true;
break; // there can't be multiple epsilon symbols coming from a given state
}
} else if (transition3->iSymbol & EPSILON_TRANSITION) {
for(TransitionX *transition4 = *transition3->state ; transition4 != *(transition3->state+1) ; ++transition4) {
if (transition4->iSymbol & LEX_UNIT_TRANSITION) {
if ((int)(transition4->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT) == m_lexiconManager->m_lexUnitEndSentence->iLexUnit) {
if (transition2->fWeight + transition3->fWeight + transition4->fWeight > fScoreFinalBest) {
fScoreFinalBest = transition2->fWeight + transition3->fWeight + transition4->fWeight;
}
bFound = true;
break; // there can't be multiple epsilon symbols coming from a given state
}
}
}
}
}
/*if (bFound) {
break;
}*/
}
}
assert(bFound);
fScore += fScoreFinalBest;
if ((transitionBest == NULL) || (fScore > fScoreBestTransition)) {
transitionBest = transition;
fScoreBestTransition = fScore;
}
} else if (transition->iSymbol & EPSILON_TRANSITION) {
assert(0);
}
}
// only consider states that go to a lexical unit (end-of-word states)
if (transitionBest != NULL) {
activeState->fScore += fScoreBestTransition;
iLexUnitLast = transitionBest->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT;
if (activeState->fScore > fScoreBest) {
activeStateBest = activeState;
iLexUnitLastBest = iLexUnitLast;
fScoreBest = activeState->fScore;
}
}
++activeState;
}
if (activeStateBest == NULL) {
return NULL;
}
bestPath->setScore(fScoreBest);
// (2) get the sequence of lexical units from the best scoring active state
int iHistoryItem = activeStateBest->iHistoryItem;
int iFrameStart = 0;
while (iHistoryItem != -1) {
HistoryItem *historyItem = m_historyItems+iHistoryItem;
if (historyItem->iPrev != -1) {
iFrameStart = (m_historyItems+historyItem->iPrev)->iEndFrame+1;
} else {
iFrameStart = 0;
}
// get the observed lexical unit
LexUnit *lexUnit = m_lexiconManager->getLexUnitPron(historyItem->iLexUnitPron);
// add a new element
bestPath->newElementFront(iFrameStart,historyItem->iEndFrame,0.0,0.0,0.0,0.0,lexUnit,0.0);
//printf("%4d %4d %-20s \n",iFrameStart,historyItem->iEndFrame,m_lexiconManager->getStrLexUnit(historyItem->iLexUnit));
iHistoryItem = historyItem->iPrev;
}
// add the final lexical unit if any
if (iLexUnitLastBest != -1) {
LexUnit *lexUnit = m_lexiconManager->getLexUnitPron(iLexUnitLastBest);
if (activeStateBest->iHistoryItem != -1) {
iFrameStart = (m_historyItems+activeStateBest->iHistoryItem)->iEndFrame+1;
} else {
iFrameStart = 0;
}
bestPath->newElementBack(iFrameStart,iFeatureVectors-1,0.0,0.0,0.0,0.0,lexUnit,0.0);
}
// add the end of sentence
bestPath->newElementBack(iFeatureVectors,iFeatureVectors,0.0,0.0,0.0,0.0,m_lexiconManager->m_lexUnitEndSentence,0.0);
//bestPath->print(false);
//printf("best scoring token: %f\n",activeStateBest->fScore);
return bestPath;
}
// print the given best paths (useful for debugging)
void ActiveStateTable::printBestPaths(unsigned int iPaths) {
LActiveState lActiveState;
// put all the active states in a list
ActiveState *activeState = m_activeStatesNext;
while(activeState != m_activeStateAvailable) {
lActiveState.push_back(activeState);
++activeState;
}
// sort the list by score
lActiveState.sort(ActiveStateTable::activeStateComparisonScore);
// print the active states with their corresponding histories
unsigned int i = 0;
for(LActiveState::iterator it = lActiveState.begin() ; it != lActiveState.end() ; ++it, ++i) {
if (i == iPaths) {
break;
}
printf("%4u %.4f ",i,(*it)->fScore);
int iHistoryItem = (*it)->iHistoryItem;
while(iHistoryItem != -1) {
printf("%s ",m_lexiconManager->getStrLexUnitPron((m_historyItems+iHistoryItem)->iLexUnitPron));
iHistoryItem = (m_historyItems+iHistoryItem)->iPrev;
}
// does the state go to any lex-unit transition?
int iLexUnitFinal = -1;
for(TransitionX *transition = *(*it)->state ; transition != *((*it)->state+1) ; ++transition) {
if ((transition->iSymbol & LEX_UNIT_TRANSITION) != 0) {
iLexUnitFinal = transition->iSymbol-LEX_UNIT_TRANSITION;
printf("%s ",m_lexiconManager->getStrLexUnitPron(iLexUnitFinal));
break;
}
}
printf("\n");
}
}
// print stats connected to the hash table containing unique word-sequences
void ActiveStateTable::printHashTableWordSequences() {
int iBucketsUsed = 0;
int iCollisions = 0;
float fLoadFactor = computeLoadFactorHashWordSequences(&iBucketsUsed,&iCollisions);
printf("- hash table containing word-sequences ---\n");
printf(" # buckets: %8d\n",m_iWSHashBuckets);
printf(" # buckets used: %8d\n",iBucketsUsed);
printf(" # collisions: %8d\n",iCollisions);
printf(" # elements: %8d\n",iBucketsUsed+iCollisions);
printf(" load factor: %8.4f\n",fLoadFactor);
printf("------------------------------------------\n");
}
// build a hypothesis lattice for the utterance
HypothesisLattice *ActiveStateTable::getHypothesisLattice() {
double dTimeBegin = TimeUtils::getTimeMilliseconds();
VHistoryItem vHistoryItem;
// (1) create the list of history items from the active states
// note: active states that are final must go to a lexical-unit transition
int iLexUnitLast = -1;
ActiveState *activeState = m_activeStatesNext;
while(activeState != m_activeStateAvailable) {
// get the last lexical unit
iLexUnitLast = -1;
// get the best transition to a lexical unit (the transition with smaller weight including the transition to </s>)
for(TransitionX *transition = *activeState->state ; transition != *(activeState->state+1) ; ++transition) {
if (transition->iSymbol & LEX_UNIT_TRANSITION) {
float fScore = transition->fWeight;
// find the transition to the end of sentence </s>
bool bFound = false;
float fScoreFinalBest = -FLT_MAX;
for(TransitionX *transition2 = *transition->state ; transition2 != *(transition->state+1) ; ++transition2) {
// direct transition to: </s>
if (transition2->iSymbol & LEX_UNIT_TRANSITION) {
if ((int)(transition2->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT) == m_lexiconManager->m_lexUnitEndSentence->iLexUnit) {
if (transition2->fWeight > fScoreFinalBest) {
fScoreFinalBest = transition2->fWeight;
}
bFound = true;
}
}
// epsilon transition before transition to: </s>
else if (transition2->iSymbol & EPSILON_TRANSITION) {
for(TransitionX *transition3 = *transition2->state ; transition3 != *(transition2->state+1) ; ++transition3) {
if (transition3->iSymbol & LEX_UNIT_TRANSITION) {
if ((int)(transition3->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT) == m_lexiconManager->m_lexUnitEndSentence->iLexUnit) {
if (transition2->fWeight + transition3->fWeight > fScoreFinalBest) {
fScoreFinalBest = transition2->fWeight + transition3->fWeight;
}
bFound = true;
break; // there can't be multiple epsilon symbols coming from a given state
}
} else if (transition3->iSymbol & EPSILON_TRANSITION) {
for(TransitionX *transition4 = *transition3->state ; transition4 != *(transition3->state+1) ; ++transition4) {
if (transition4->iSymbol & LEX_UNIT_TRANSITION) {
if ((int)(transition4->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT) == m_lexiconManager->m_lexUnitEndSentence->iLexUnit) {
if (transition2->fWeight + transition3->fWeight + transition4->fWeight > fScoreFinalBest) {
fScoreFinalBest = transition2->fWeight + transition3->fWeight + transition4->fWeight;
}
bFound = true;
break; // there can't be multiple epsilon symbols coming from a given state
}
}
}
}
}
}
}
assert(bFound);
HistoryItem *historyItem = new HistoryItem();
historyItem->iLexUnitPron = transition->iSymbol & LEX_UNIT_TRANSITION_COMPLEMENT;
historyItem->iEndFrame = m_iTimeCurrent;
historyItem->fScore = activeState->fScore + fScore;
historyItem->iPrev = activeState->iHistoryItem;
historyItem->iActive = m_iTimeCurrent;
historyItem->iWGToken = activeState->iWGToken;
vHistoryItem.push_back(historyItem);
}
assert((transition->iSymbol & EPSILON_TRANSITION) == 0);
}
++activeState;
}
// if the vector is empty the lattice cannot be built
if (vHistoryItem.empty()) {
return NULL;
}
// create the initial node
LNode *lnodeInitial = HypothesisLattice::newNode(-1);
// create the final node
LNode *lnodeFinal = HypothesisLattice::newNode(m_iTimeCurrent);
MHistoryItemLNode mHistoryItemLNode;
int iNodes = 0;
int iEdges = 0;
// put all the history items in the list of items to process
for(VHistoryItem::iterator it = vHistoryItem.begin() ; it != vHistoryItem.end() ; ++it) {
HistoryItem *historyItem = *it;
assert(historyItem != NULL);
assert(historyItem->iWGToken != -1);
mHistoryItemLNode.insert(MHistoryItemLNode::value_type(historyItem,lnodeFinal));
}
// process all the history items
while(vHistoryItem.empty() == false) {
HistoryItem *historyItemAux = vHistoryItem.back();
vHistoryItem.pop_back();
// get the graph node for this history item
MHistoryItemLNode::iterator it = mHistoryItemLNode.find(historyItemAux);
assert(it != mHistoryItemLNode.end());
LNode *lnodeAux = it->second;
//printHistoryItem(historyItemAux);
// items that go to this item
//printf("----------------------------------------------------\n");
int iTokens = 0;
for(int i=0 ; ((i < m_iMaxWordSequencesState) && ((historyItemAux->iWGToken+m_wgTokens)[i].iWordSequence != -1)) ; ++i, ++iTokens) {
if ((historyItemAux->iWGToken+m_wgTokens)[i].iWordSequence == m_iWordSequenceInitial) {
if (iTokens == 0) {
//printf("connects to: <s>\n");
}
break;
}
//HistoryItem *historyItemPrev = historyItemAux->wgToken[i].historyItem;
HistoryItem *historyItemPrev = m_historyItems+(historyItemAux->iWGToken+m_wgTokens)[i].iHistoryItem;
LNode *lnodePrev = NULL;
LEdge *ledgePrev = NULL;
LexUnit *lexUnit = m_lexiconManager->getLexUnitPron(historyItemAux->iLexUnitPron);
MHistoryItemLNode::iterator jt = mHistoryItemLNode.find(historyItemPrev);
// the history item is not in the graph: create a graph node for it
if (jt == mHistoryItemLNode.end()) {
//printHistoryItem(historyItemPrev);
lnodePrev = HypothesisLattice::newNode(historyItemPrev->iEndFrame);
ledgePrev = HypothesisLattice::newEdge(historyItemPrev->iEndFrame+1,historyItemAux->iEndFrame,lexUnit,0.0,0.0,0.0);
mHistoryItemLNode.insert(MHistoryItemLNode::value_type(historyItemPrev,lnodePrev));
vHistoryItem.push_back(historyItemPrev);
++iNodes;
}
// the history item is in the graph: create a link
else {
ledgePrev = HypothesisLattice::newEdge(historyItemPrev->iEndFrame+1,historyItemAux->iEndFrame,lexUnit,0.0,0.0,0.0);
lnodePrev = jt->second;
}
++iEdges;
// make the connection
HypothesisLattice::connectEdge(lnodePrev,ledgePrev,lnodeAux);
}
// if no tokens then the node should connect to the initial node <s>
if (iTokens == 0) {
// make the connection
LexUnit *lexUnit = m_lexiconManager->getLexUnitPron(historyItemAux->iLexUnitPron);
LEdge *ledge = HypothesisLattice::newEdge(0,historyItemAux->iEndFrame,lexUnit,0.0,0.0,0.0);
// make the connection
HypothesisLattice::connectEdge(lnodeInitial,ledge,lnodeAux);
}
// delete only the items that were just created
if (historyItemAux->iEndFrame == m_iTimeCurrent) {
delete historyItemAux;
}
//printf("----------------------------------------------------\n");
}
assert(lnodeInitial->edgeNext != NULL);
HypothesisLattice *hypothesisLattice = new HypothesisLattice(m_phoneSet,m_lexiconManager);
hypothesisLattice->buildContainer(lnodeInitial,lnodeFinal);
double dTimeEnd = TimeUtils::getTimeMilliseconds();
double dTime = (dTimeEnd-dTimeBegin)/1000.0;
printf("Lattice building time: %.4fs\n",dTime);
//exit(-1);
return hypothesisLattice;
}
// merge two sets of word sequences by keeping the N best unique word sequences in wgToken1 (not commutative)
// 1) sorting: both sets are sorted so it is very efficient: O(n)
// 2) unique: this is linear too
bool ActiveStateTable::mergeWordSequences(int iWGToken1, int iWGToken2) {
WGToken *wgTokenTable = NULL;
WGToken *wgToken1 = iWGToken1+m_wgTokens;
WGToken *wgToken2 = iWGToken2+m_wgTokens;
int iLength1 = 0;
for( ; ((iLength1 < m_iMaxWordSequencesState) && (wgToken1[iLength1].iWordSequence != -1)) ; ++iLength1);
int iLength2 = 0;
for( ; ((iLength2 < m_iMaxWordSequencesState) && (wgToken2[iLength2].iWordSequence != -1)) ; ++iLength2);
assert(iWGToken1 != iWGToken2);
assert((iLength1 > 0) && (iLength2 > 0));
int k = iLength1-1;
int j = iLength2-1;
int iTotal = iLength1+iLength2;
// using a table of elements instead of pointers simplifies the "unique" process and makes it more efficient
wgTokenTable = new WGToken[iTotal];
// sort all the elements (not just the top N since there can be duplicated word-sequences)
bool bReturn = false;
for(int i=iTotal-1 ; i >= 0 ; --i) {
if (wgToken1[k].fScore < wgToken2[j].fScore) {
memcpy(&wgTokenTable[i],&wgToken1[k],sizeof(WGToken));
--k;
if (k < 0) {
for(int h=i-1 ; h >= 0 ; --h) {
assert(j>=0);
memcpy(&wgTokenTable[h],&wgToken2[j--],sizeof(WGToken));
}
bReturn = false;
break;
}
} else {
memcpy(&wgTokenTable[i],&wgToken2[j],sizeof(WGToken));
--j;
if (j < 0) {
for(int h=i-1 ; h >= 0 ; --h) {
assert(k>=0);
memcpy(&wgTokenTable[h],&wgToken1[k--],sizeof(WGToken));
}
bReturn = true;
break;
}
}
}
// unique
int iUniqueElements = 0;
memcpy(&wgToken1[0],&wgTokenTable[0],sizeof(WGToken));
for(int i=1 ; ((i < iTotal) && (iUniqueElements+1 < m_iMaxWordSequencesState)) ; ++i) {
bool bDuplicated = false;
for(int j=0 ; j < iUniqueElements+1 ; ++j) {
if (wgTokenTable[i].iWordSequence == wgToken1[j].iWordSequence) {
bDuplicated = true;
break;
}
}
if (bDuplicated == false) {
memcpy(&wgToken1[++iUniqueElements],&wgTokenTable[i],sizeof(WGToken));
}
}
if (iUniqueElements+1 < m_iMaxWordSequencesState) {
wgToken1[iUniqueElements+1].iWordSequence = -1;
}
delete [] wgTokenTable;
return bReturn;
}
}; // end-of-namespace
| 36.477612 | 256 | 0.684598 | [
"object",
"vector",
"3d"
] |
6342a8b7966b417e80e5ffa56ae616bfcbecfaef | 5,090 | cpp | C++ | addons/ofxIO/libs/ofxIO/src/ByteBuffer.cpp | MartinHN/openFrameworks | 14d17cd9589be0139de17bc6a11110439d86a4b1 | [
"MIT"
] | null | null | null | addons/ofxIO/libs/ofxIO/src/ByteBuffer.cpp | MartinHN/openFrameworks | 14d17cd9589be0139de17bc6a11110439d86a4b1 | [
"MIT"
] | null | null | null | addons/ofxIO/libs/ofxIO/src/ByteBuffer.cpp | MartinHN/openFrameworks | 14d17cd9589be0139de17bc6a11110439d86a4b1 | [
"MIT"
] | null | null | null | // =============================================================================
//
// Copyright (c) 2013 Christopher Baker <http://christopherbaker.net>
//
// 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 "ofx/IO/ByteBuffer.h"
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
namespace ofx {
namespace IO {
ByteBuffer::ByteBuffer()
{
}
ByteBuffer::ByteBuffer(uint8_t data)
{
writeByte(data);
}
ByteBuffer::ByteBuffer(const uint8_t* buffer, std::size_t size)
{
writeBytes(buffer, size);
}
ByteBuffer::ByteBuffer(const std::vector<uint8_t>& buffer)
{
writeBytes(buffer);
}
ByteBuffer::ByteBuffer(const std::string& buffer)
{
writeBytes(buffer);
}
ByteBuffer::~ByteBuffer()
{
}
std::size_t ByteBuffer::readBytes(uint8_t* buffer, std::size_t size) const
{
std::size_t numBytesToCopy = std::min(size, _buffer.size());
std::copy(_buffer.begin(), _buffer.begin() + numBytesToCopy, buffer);
return numBytesToCopy;
}
std::size_t ByteBuffer::readBytes(std::vector<uint8_t>& buffer) const
{
buffer.resize(_buffer.size());
buffer.insert(buffer.begin(), _buffer.begin(), _buffer.end());
return buffer.size();
}
std::size_t ByteBuffer::readBytes(std::string& buffer) const
{
buffer.resize(_buffer.size());
buffer.insert(buffer.begin(), _buffer.begin(), _buffer.end());
return buffer.size();
}
std::size_t ByteBuffer::readBytes(AbstractByteSink& buffer) const
{
return buffer.writeBytes(_buffer);
}
std::vector<uint8_t> ByteBuffer::readBytes() const
{
return _buffer;
}
std::size_t ByteBuffer::writeByte(uint8_t data)
{
_buffer.push_back(data);
return 1;
}
std::size_t ByteBuffer::writeBytes(const uint8_t* buffer, std::size_t size)
{
_buffer.reserve(_buffer.size() + size);
_buffer.insert(_buffer.end(), buffer, buffer + size);
return size;
}
std::size_t ByteBuffer::writeBytes(const std::vector<uint8_t>& buffer)
{
_buffer.reserve(_buffer.size() + buffer.size());
_buffer.insert(_buffer.end(), buffer.begin(), buffer.end());
return buffer.size();
}
std::size_t ByteBuffer::writeBytes(const std::string& buffer)
{
_buffer.reserve(_buffer.size() + buffer.size());
_buffer.insert(_buffer.end(), buffer.begin(), buffer.end());
return buffer.size();
}
std::size_t ByteBuffer::writeBytes(const AbstractByteSource& buffer)
{
return writeBytes(buffer.readBytes());
}
std::size_t ByteBuffer::size() const
{
return _buffer.size();
}
std::size_t ByteBuffer::capacity() const
{
return _buffer.capacity();
}
void ByteBuffer::clear()
{
_buffer.clear();
}
bool ByteBuffer::empty() const
{
return _buffer.empty();
}
std::size_t ByteBuffer::resize(std::size_t size, uint8_t fillByte)
{
_buffer.resize(size, fillByte);
return _buffer.size();
}
std::size_t ByteBuffer::reserve(std::size_t capacity)
{
_buffer.reserve(capacity);
return _buffer.capacity();
}
const std::vector<uint8_t>& ByteBuffer::getDataRef() const
{
return _buffer;
}
uint8_t& ByteBuffer::operator [] (std::size_t n)
{
return _buffer[n];
}
uint8_t ByteBuffer::operator [] (std::size_t n) const
{
return _buffer[n];
}
const uint8_t* ByteBuffer::getPtr() const
{
if (!_buffer.empty())
{
return &_buffer[0];
}
else
{
return 0;
}
}
uint8_t* ByteBuffer::getPtr()
{
if (!_buffer.empty())
{
return &_buffer[0];
}
else
{
return 0;
}
}
const char* ByteBuffer::getCharPtr() const
{
if (!_buffer.empty())
{
return reinterpret_cast<const char*>(&_buffer[0]);
}
else
{
return 0;
}
}
char* ByteBuffer::getCharPtr()
{
if (!_buffer.empty())
{
return reinterpret_cast<char*>(&_buffer[0]);
}
else
{
return 0;
}
}
std::string ByteBuffer::toString() const
{
std::stringstream ss;
ss << (*this);
return ss.str();
}
} } // namespace ofx::IO
| 19.207547 | 80 | 0.651866 | [
"vector"
] |
63433b696e32a0f5a8020038c03b0101ae4d7ce8 | 3,572 | cpp | C++ | GIDI/Src/GIDI_grid.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | GIDI/Src/GIDI_grid.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | GIDI/Src/GIDI_grid.cpp | Mathnerd314/gidiplus | ed4c48ab399a964fe782f73d0a065849b00090bb | [
"MIT-0",
"MIT"
] | null | null | null | /*
# <<BEGIN-copyright>>
# Copyright 2019, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: MIT
# <<END-copyright>>
*/
#include "GIDI.hpp"
#include <HAPI.hpp>
namespace GIDI {
/*! \class Grid
* Class to store a **GNDS grid** node.
*/
/* *********************************************************************************************************//**
*
* @param a_node [in] The **HAPI::Node** to be parsed and used to construct the Grid.
* @param a_setupInfo [in] Information create my the Protare constructor to help in parsing.
* @param a_useSystem_strtod [in] Flag passed to the function nfu_stringToListOfDoubles.
***********************************************************************************************************/
Grid::Grid( HAPI::Node const &a_node, SetupInfo &a_setupInfo, int a_useSystem_strtod ) :
Axis( a_node, a_setupInfo, FormType::grid ),
m_style( a_node.attribute_as_string( GIDI_styleChars ) ),
m_keyName( GIDI_indexChars ),
m_keyValue( a_node.attribute_as_string( GIDI_indexChars ) ) {
if( href( ) == "" ) {
HAPI::Node values = a_node.first_child( );
if( values.name( ) != std::string( GIDI_valuesChars ) ) throw Exception( "grid's first child not values" );
m_valueType = values.attribute_as_string( GIDI_valueTypeChars );
parseValuesOfDoubles( values, a_setupInfo, m_values, a_useSystem_strtod );
}
}
/* *********************************************************************************************************//**
* Copy constructor for Grid.
*
* @param a_grid [in] The Grid instance to copy.
***********************************************************************************************************/
Grid::Grid( Grid const &a_grid ) :
Axis( a_grid ),
m_style( a_grid.style( ) ),
m_keyName( a_grid.keyName( ) ),
m_keyValue( a_grid.keyValue( ) ),
m_valueType( a_grid.valueType( ) ),
m_values( a_grid.values( ) ) {
}
/* *********************************************************************************************************//**
* Fills the argument *a_writeInfo* with the XML lines that represent *this*. Recursively enters each sub-node.
*
* @param a_writeInfo [in/out] Instance containing incremental indentation and other information and stores the appended lines.
* @param a_indent [in] The amount to indent *this* node.
***********************************************************************************************************/
void Grid::toXMLList( WriteInfo &a_writeInfo, std::string const &a_indent ) const {
std::string indent2 = a_writeInfo.incrementalIndent( a_indent );
std::string attributes = a_writeInfo.addAttribute( GIDI_indexChars, intToString( index( ) ) );
if( href( ) == "" ) {
attributes += a_writeInfo.addAttribute( GIDI_labelChars, label( ) );
attributes += a_writeInfo.addAttribute( GIDI_unitChars, unit( ) );
attributes += a_writeInfo.addAttribute( GIDI_styleChars, style( ) );
a_writeInfo.addNodeStarter( a_indent, moniker( ), attributes );
doublesToXMLList( a_writeInfo, indent2, m_values.vector(), 0, true, m_valueType );
a_writeInfo.addNodeEnder( moniker( ) ); }
else {
attributes += a_writeInfo.addAttribute( GIDI_hrefChars, href( ) );
a_writeInfo.addNodeStarterEnder( a_indent, moniker( ), attributes );
}
}
}
| 42.52381 | 144 | 0.533315 | [
"vector"
] |
6348236a69c98ab1e4c651aee56d15528adb6948 | 1,350 | cpp | C++ | Lorenz/Analysis/Stats.cpp | GEslinger/PhysClass | 5e34167c34ca0e8779e4002063d95ffa24a24c9d | [
"BSD-2-Clause"
] | null | null | null | Lorenz/Analysis/Stats.cpp | GEslinger/PhysClass | 5e34167c34ca0e8779e4002063d95ffa24a24c9d | [
"BSD-2-Clause"
] | null | null | null | Lorenz/Analysis/Stats.cpp | GEslinger/PhysClass | 5e34167c34ca0e8779e4002063d95ffa24a24c9d | [
"BSD-2-Clause"
] | null | null | null | #include <vector>
#include <cmath>
#include <utility>
#include <iostream>
using namespace std;
// Functions for analyzing the error and creating the log-log plot!
double getAvg(vector<double> v){ // Get the arithmetic mean of a data set
double sum = 0;
for(int i = 0; i < v.size(); i++){ // Iterate through data
sum += v[i]; // Add number to sum
}
return sum/(double)v.size();// Output the average
}
pair<double,double> getLeastSquares(vector<double> x, vector<double> y){ // Pair of doubles for (a,b) of the linear least squares y=ax+b
double xbar = getAvg(x);
double ybar = getAvg(y);
double topSum = 0;
double botSum = 0;
for(int i = 0; i < x.size(); i++){ // Algorithm courtesy of Dr. Kroeger's Stats Class
topSum += (x[i] - xbar)*(y[i] - ybar);
botSum += (x[i] - xbar)*(x[i] - xbar);
}
double slope = topSum/botSum;
double intercept = ybar - slope*xbar;
return make_pair(slope,intercept); // Output!
}
vector<double> toLogLog(vector<double> x){ // Converts each number in a vector to its natural log
vector<double> out;
for(int i = 0; i < x.size(); i++){
out.push_back(log(x[i]));
}
return out;
}
double globalError(vector<double> x, vector<double> t){ // Calculates global error against x = e^-t using final values
double e = exp(-t.back())-x.back();
return fabs(e); // Return absolute value of the error
} | 29.347826 | 136 | 0.663704 | [
"vector"
] |
63525bebd6d8fdf34435c2af595425da3334d372 | 24,077 | cpp | C++ | LibUIDK/tvmem.cpp | swjsky/sktminest | 42fa47d9ffb0f50a5727e42811e949fff920bec9 | [
"MIT"
] | 3 | 2019-12-03T09:04:04.000Z | 2021-01-29T02:03:30.000Z | LibUIDK/tvmem.cpp | swjsky/sktminest | 42fa47d9ffb0f50a5727e42811e949fff920bec9 | [
"MIT"
] | null | null | null | LibUIDK/tvmem.cpp | swjsky/sktminest | 42fa47d9ffb0f50a5727e42811e949fff920bec9 | [
"MIT"
] | 2 | 2020-06-12T04:30:31.000Z | 2020-11-25T13:23:03.000Z | #include "StdAfx.h"
#include "treeview.h"
#if defined(MAINWIN)
#include <mainwin.h>
#endif
void TV_ScrollItems(PTREE pTree, int nItems, int iTopShownIndex, BOOL fDown);
// in:
// hItem item to delete
// flags controls how/what to delete
// TVDI_NORMAL delete this node and all children
// TVDI_NONOTIFY don't send notify messages
// TVDI_CHILDRENONLY just delete the kids (not the item)
void NEAR TV_DeleteItemRecurse(PTREE pTree, TREEITEM FAR *hItem, UINT flags)
{
TREEITEM FAR *hKid;
TREEITEM FAR *hNext;
TREEITEM FAR *hParent;
int i;
DBG_ValidateTreeItem(hItem, 0);
//
// We do this from DeleteItemRecurse(), kind of like how USER sends
// Destroy notifications from its FreeWindow() code, so that we get
// deletes for parent and children both.
//
MyNotifyWinEvent(EVENT_OBJECT_DESTROY, pTree->ci.hwnd, OBJID_CLIENT,
(LONG_PTR)hItem);
//
// While the item is still valid, clean up if it's the insertion point.
// The item needs to be valid because we're going to call other
// functions that validate their parameters...
//
if (hItem == pTree->htiInsert)
{
TV_SetInsertMark(pTree, NULL, FALSE);
_ASSERT(pTree->htiInsert == NULL);
}
// remove all kids (and their kids)
for (hKid = hItem->hKids; hKid; hKid = hNext)
{
hNext = hKid->hNext;
// recurse on each child
TV_DeleteItemRecurse(pTree, hKid, flags & ~TVDI_CHILDRENONLY);
}
if ((flags & TVDI_CHILDRENONLY) || !hItem->hParent)
{
return;
}
if (!(flags & TVDI_NONOTIFY)) // BUGBUG: this is not set by anyone
{
NM_TREEVIEW nm;
// Let the app clean up after itself
nm.itemOld.hItem = hItem;
nm.itemOld.lParam = hItem->lParam;
nm.itemNew.mask = 0;
nm.itemOld.mask = (TVIF_HANDLE | TVIF_PARAM);
CCSendNotify(&pTree->ci, TVN_DELETEITEM, &nm.hdr);
}
//
// If anybody has a watch on our item, let him know that it's gone.
//
i = DPA_GetPtrCount(pTree->hdpaWatch);
while (--i >= 0)
{
PTVWATCHEDITEM pwi = (PTVWATCHEDITEM)DPA_FastGetPtr(pTree->hdpaWatch, i);
_ASSERT(pwi);
if (pwi->hti == hItem)
{
pwi->hti = hItem->hNext;
pwi->fStale = TRUE;
}
}
hParent = hItem->hParent;
_ASSERT(hParent);
// unlink ourselves from the parent child chain
if (hParent->hKids == hItem)
{
hParent->hKids = hItem->hNext;
hKid = NULL;
}
else
{
// not the first child, find our previous item (linear search!)
hKid = TV_GetNextItem(pTree, hItem, TVGN_PREVIOUS);
_ASSERT(hKid);
hKid->hNext = hItem->hNext;
}
pTree->cItems--;
TV_ScrollBarsAfterRemove(pTree, hItem);
// reset tooltip after unlink from the parent child chain
if (pTree->hToolTip == hItem)
{
TV_SetToolTipTarget(pTree, NULL);
}
Str_Set(&hItem->lpstr, NULL);
TV_MarkAsDead(hItem);
// be careful from here down. hItem is unlinked but
// still has some valid fields
// Check to see if the user has deleted one of the
// special items that is stored in the main tree structure.
if (hItem == pTree->htiEdit)
{
pTree->htiEdit = NULL;
}
if (hItem == pTree->hDropTarget)
{
pTree->hDropTarget = NULL;
}
if (hItem == pTree->hOldDrop)
{
pTree->hOldDrop = NULL;
}
if (hItem == pTree->hHot)
{
pTree->hHot = NULL;
}
if (hItem == pTree->htiSearch)
{
pTree->htiSearch = NULL;
}
// if the caret escaped the collapsed area and landed on us, push it away
if (pTree->hCaret == hItem)
{
HTREEITEM hTemp;
if (hItem->hNext)
{
hTemp = hItem->hNext;
}
else
{
hTemp = VISIBLE_PARENT(hItem);
if (!hTemp)
{
hTemp = hKid; // set above when we unlinked from the previous item
}
}
// Reset the caret to NULL as to not try to reference our
// invalidated item.
pTree->hCaret = NULL;
TV_SelectItem(pTree, TVGN_CARET, hTemp, (flags & TVDI_NOSELCHANGE) ? 0 : TVSIF_NOTIFY, 0);
_ASSERT(pTree->hCaret != hItem);
}
// BUGBUG: might want to really do this
_ASSERT(pTree->hItemPainting != hItem);
ControlFree(pTree->hheap, hItem);
}
// ----------------------------------------------------------------------------
//
// Removes the given item and all children from the tree.
// Special case: if the given item is the hidden root, all children are
// removed, but the hidden root is NOT removed.
//
// sets cItems
//
// ----------------------------------------------------------------------------
BOOL NEAR TV_DeleteItem(PTREE pTree, TREEITEM FAR *hItem, UINT flags)
{
if (hItem == TVI_ROOT || !hItem)
{
hItem = pTree->hRoot;
}
// BUGUBG: send TVN_DELETEALLITEMS and TVDI_NONOTIFY if they respond
// if (hItem == pTree->hRoot)
// etc.
if (!ValidateTreeItem(hItem, 0))
{
return FALSE;
}
// Collapse first to speed things up (not as much scroll bar recalcs) and
// to set the top index correctly after the remove.
if (hItem != pTree->hRoot)
{
TV_Expand(pTree, TVE_COLLAPSE, hItem, FALSE);
}
else
{
// TV_Expand punts on the root item, so manually iterate through it's kids
TREEITEM *hKid = hItem->hKids;
while (hKid)
{
TV_Expand(pTree, TVE_COLLAPSE, hKid, FALSE);
if (!ValidateTreeItem(hKid, 0))
{
break; // callback during collapse could delete
}
hKid = hKid->hNext;
}
}
// Invalidate everything below this item; must be done AFTER setting the
// selection
if (hItem->hParent == pTree->hRoot || hItem == pTree->hRoot || ITEM_VISIBLE(hItem->hParent))
{
if (pTree->fRedraw)
{
InvalidateRect(pTree->ci.hwnd, NULL, TRUE);
}
}
else
{
TV_ScrollBelow(pTree, hItem->hParent, FALSE, FALSE);
}
// We can pass in the root to clear all items
if (hItem == pTree->hRoot)
{
flags |= TVDI_CHILDRENONLY;
}
TV_DeleteItemRecurse(pTree, hItem, flags);
_ASSERT(pTree->hRoot); // didn't go too far, did we?
// maybe everything's gone...
// check out our cleanup job
if (!pTree->hRoot->hKids)
{
// the tree itself
_ASSERT(pTree->cItems == 0);
pTree->cItems = 0; // just removed it all, didn't we?
// BUGBUG: this fails because we don't touch hTop if redraw is off
// in TV_DeleteItemRecurse()
// AssertMsg(pTree->hTop == NULL, TEXT("hTop not NULL, but empty tree"));
pTree->hTop = NULL;
//L AssertMsg(pTree->hCaret == NULL, TEXT("hCaret not NULL, but empty tree"));
pTree->hCaret = NULL;
pTree->fNameEditPending = FALSE;
pTree->cxMax = 0;
pTree->xPos = 0;
// the invisible root
_ASSERT(pTree->hRoot->hNext == NULL);
pTree->hRoot->hNext = NULL;
_ASSERT(pTree->hRoot->hParent == NULL);
pTree->hRoot->hParent = NULL;
_ASSERT(pTree->hRoot->hKids == NULL);
pTree->hRoot->hKids = NULL;
_ASSERT(pTree->hRoot->state & TVIS_EXPANDED);
pTree->hRoot->state |= (TVIS_EXPANDED | TVIS_EXPANDEDONCE);
_ASSERT(pTree->hRoot->iLevel == (BYTE) - 1);
pTree->hRoot->iLevel = (BYTE) - 1;
_ASSERT(pTree->hRoot->iShownIndex == (WORD) - 1);
pTree->hRoot->iShownIndex = (WORD) - 1;
}
return TRUE;
}
// ----------------------------------------------------------------------------
//
// Creates the hidden root node for the tree -- all items will trace up to
// this root, and the first child of the root is the first item in the tree.
//
// sets hRoot
//
// ----------------------------------------------------------------------------
const TCHAR c_szNULL[] = TEXT("");
BOOL NEAR PASCAL TV_CreateRoot(PTREE pTree)
{
TREEITEM FAR *hRoot = (TREEITEM *)ControlAlloc(pTree->hheap, sizeof(TREEITEM));
if (!hRoot)
{
return FALSE;
}
// hRoot->hNext = NULL;
// hRoot->hKids = NULL;
// hRoot->hParent = NULL;
hRoot->iLevel = (BYTE) - 1;
hRoot->state = (TVIS_EXPANDED | TVIS_EXPANDEDONCE);
hRoot->iShownIndex = (WORD) - 1;
hRoot->wSignature = TV_SIG;
pTree->hRoot = hRoot;
// OLEACC asks for the text of the root item (d'oh!)
Str_Set(&hRoot->lpstr, c_szNULL);
return TRUE;
}
#ifdef DEBUG
void NEAR DumpItem(TREEITEM FAR *hItem)
{
LPTSTR p;
if (hItem->lpstr == LPSTR_TEXTCALLBACK)
{
p = TEXT("(callback)");
}
else if (hItem->lpstr == NULL)
{
p = TEXT("(null)");
}
else
{
p = hItem->lpstr;
}
//L TraceMsg(TF_TREEVIEW, "%s", p);
//TraceMsg(TF_TREEVIEW, "\tstate:%4.4x show index:%3d level:%2d kids:%ld lparam:%4.4x",
// hItem->state, hItem->iShownIndex,
// hItem->iLevel, hItem->fKids, hItem->lParam);
}
#else
#define DumpItem(hItem)
#endif
// ----------------------------------------------------------------------------
//
// Adds the item described by the given arguments to the tree.
//
// sets hTop, cItems
//
// ----------------------------------------------------------------------------
#ifdef UNICODE
TREEITEM FAR *NEAR TV_InsertItemA(PTREE pTree, LPTV_INSERTSTRUCTA lpis)
{
LPSTR pszA = NULL;
TREEITEM *ptvi;
//HACK Alert! This code assumes that TV_INSERTSTRUCTA is exactly the same
// as TV_INSERTSTRUCTW except for the text pointer in the TVITEM
COMPILETIME_ASSERT(sizeof(TV_INSERTSTRUCTA) == sizeof(TV_INSERTSTRUCTW));
if (!IsFlagPtr(lpis) && (lpis->DUMMYUNION_MEMBER(item).mask & TVIF_TEXT) && !IsFlagPtr(lpis->DUMMYUNION_MEMBER(item).pszText))
{
pszA = lpis->DUMMYUNION_MEMBER(item).pszText;
lpis->DUMMYUNION_MEMBER(item).pszText = (LPSTR)ProduceWFromA(pTree->ci.uiCodePage, lpis->DUMMYUNION_MEMBER(item).pszText);
if (lpis->DUMMYUNION_MEMBER(item).pszText == NULL)
{
lpis->DUMMYUNION_MEMBER(item).pszText = pszA;
return NULL;
}
}
ptvi = TV_InsertItem(pTree, (LPTV_INSERTSTRUCTW)lpis);
if (pszA)
{
FreeProducedString(lpis->DUMMYUNION_MEMBER(item).pszText);
lpis->DUMMYUNION_MEMBER(item).pszText = pszA;
}
return ptvi;
}
#endif
TREEITEM FAR *NEAR TV_InsertItem(PTREE pTree, LPTV_INSERTSTRUCT lpis)
{
TREEITEM FAR *hNewItem, FAR *hItem;
TREEITEM FAR *hParent;
TREEITEM FAR *hInsertAfter;
UINT mask;
if (!lpis)
{
return NULL; //BUGBUG: Validate LPTV_INSERTSTRUCT
}
// initialize _after_ the check for NULL!
hParent = lpis->hParent;
hInsertAfter = lpis->hInsertAfter;
mask = lpis->DUMMYUNION_MEMBER(item).mask;
// don't allow undefined bits
//L AssertMsg((lpis->DUMMYUNION_MEMBER(item).mask & ~TVIF_ALL) == 0, TEXT("Invalid TVIF mask specified"));
if (mask & ~TVIF_ALL)
{
// if they used bogus bits,
// restrict to win95 bits only
// I'd like to fail completely, but for win95 compat, we can't
//
// this fixes QuaterDesk's CleanSweep which has bogus garbage on the stack for a mask
mask = (TVIF_WIN95 & mask);
}
TV_DismissEdit(pTree, FALSE);
//
// Zillions of apps pass garbage for hInsertAfter, so don't fail if
// it's invalid. Fortunately, we never dereference hInsertAfter, so
// garbage is okay.
if (!ValidateTreeItem(hParent, VTI_NULLOK)) // NULL means TVI_ROOT
{
return NULL;
}
DBG_ValidateTreeItem(hInsertAfter, 0);
hNewItem = (TREEITEM *)ControlAlloc(pTree->hheap, sizeof(TREEITEM));
if (!hNewItem)
{
//L TraceMsg(TF_ERROR, "TreeView: Out of memory");
return NULL;
}
hNewItem->wSignature = TV_SIG;
if (mask & TVIF_TEXT)
{
//
// We will setup the text string next, before we link our self in
// as to handle the case where we run out of memory and need to
// destroy ourself without having to unlink.
//
if (!lpis->DUMMYUNION_MEMBER(item).pszText)
{
hNewItem->lpstr = LPSTR_TEXTCALLBACK;
}
else
{
if (!Str_Set(&hNewItem->lpstr, lpis->DUMMYUNION_MEMBER(item).pszText))
{
// Memory allocation failure...
//L TraceMsg(TF_ERROR, "TreeView: Out of memory");
TV_MarkAsDead(hNewItem);
ControlFree(pTree->hheap, hNewItem);
return NULL;
}
}
}
else
{
Str_Set(&hNewItem->lpstr, c_szNULL);
}
//L AssertMsg(hNewItem->lpstr != NULL, TEXT("Item added with NULL text"));
if ((hParent == NULL) || (hParent == TVI_ROOT))
{
hParent = pTree->hRoot;
if (!pTree->hTop)
{
pTree->hTop = hNewItem;
}
}
else if (!pTree->hRoot->hKids)
{
TV_MarkAsDead(hNewItem);
ControlFree(pTree->hheap, hNewItem);
return NULL;
}
// We will do the sort later, so we can handle TEXTCALLBACK things
if ((hInsertAfter == TVI_FIRST || hInsertAfter == TVI_SORT) || !hParent->hKids)
{
hNewItem->hNext = hParent->hKids;
hParent->hKids = hNewItem;
}
else
{
// BUGBUG: we should cache the last insert after pointer to try to
// catch the case of consecutive adds to the end of a node
if (hInsertAfter == TVI_LAST)
for (hItem = hParent->hKids; hItem->hNext; hItem = hItem->hNext)
;
else
{
for (hItem = hParent->hKids; hItem->hNext; hItem = hItem->hNext)
if (hItem == hInsertAfter)
{
break;
}
}
hNewItem->hNext = hItem->hNext;
hItem->hNext = hNewItem;
}
// hNewItem->hKids = NULL;
hNewItem->hParent = hParent;
hNewItem->iLevel = hParent->iLevel + 1;
// hNewItem->iWidth = 0;
// hNewItem->state = 0;
if ((mask & TVIF_INTEGRAL) &&
LOWORD(lpis->DUMMYUNION_MEMBER(itemex).iIntegral) > 0)
{
hNewItem->iIntegral = LOWORD(lpis->DUMMYUNION_MEMBER(itemex).iIntegral);
}
else
{
#ifdef CHEEDEBUG
// just to get some variety
hNewItem->iIntegral = ((((int)hNewItem) / 100) % 2) + 1;
#else
hNewItem->iIntegral = 1;
#endif
}
if (pTree->hTop == hNewItem)
{
hNewItem->iShownIndex = 0; // calc me please!
}
else
{
hNewItem->iShownIndex = (WORD) - 1; // calc me please!
}
if (mask & TVIF_IMAGE)
{
hNewItem->iImage = (WORD) lpis->DUMMYUNION_MEMBER(item).iImage;
}
if (mask & TVIF_SELECTEDIMAGE)
{
hNewItem->iSelectedImage = (WORD) lpis->DUMMYUNION_MEMBER(item).iSelectedImage;
}
if (mask & TVIF_PARAM)
{
hNewItem->lParam = lpis->DUMMYUNION_MEMBER(item).lParam;
}
if (mask & TVIF_STATE)
{
hNewItem->state = lpis->DUMMYUNION_MEMBER(item).state & lpis->DUMMYUNION_MEMBER(item).stateMask;
}
// if we're in check box mode, inforce that it has a check box
if (pTree->ci.style & TVS_CHECKBOXES)
{
if ((hNewItem->state & TVIS_STATEIMAGEMASK) == 0)
{
hNewItem->state |= INDEXTOSTATEIMAGEMASK(1);
}
}
if ((hNewItem->state & TVIS_BOLD) && !pTree->hFontBold) //$BOLD
{
TV_CreateBoldFont(pTree); //$BOLD
}
// TraceMsg(TF_TRACE, "Tree: Inserting i = %d state = %d", TV_StateIndex(&lpis->item), lpis->item.state);
if (mask & TVIF_CHILDREN)
{
switch (lpis->DUMMYUNION_MEMBER(item).cChildren)
{
case I_CHILDRENCALLBACK:
hNewItem->fKids = KIDS_CALLBACK;
break;
case 0:
hNewItem->fKids = KIDS_FORCE_NO;
break;
default:
hNewItem->fKids = KIDS_FORCE_YES;
break;
}
}
// accept state bits on create?
// mask & TVIF_STATE
pTree->cItems++;
// I don't want to do any callbacks until the item is completed
// so sorting waits until the end
// special case an only child for speed
// (hKids && hKids->hNext means more than one child)
if ((hInsertAfter == TVI_SORT) && hParent->hKids && hParent->hKids->hNext)
{
TVITEMEX sThisItem, sNextItem;
TCHAR szThis[64], szNext[64]; // BUGBUG: these are too small
sThisItem.pszText = szThis;
sThisItem.cchTextMax = ARRAYSIZE(szThis);
TV_GetItem(pTree, hNewItem, TVIF_TEXT, &sThisItem);
// We know that the first kid of hParent is hNewItem
for (hItem = hNewItem->hNext; hItem; hItem = hItem->hNext)
{
sNextItem.pszText = szNext;
sNextItem.cchTextMax = ARRAYSIZE(szNext);
TV_GetItem(pTree, hItem, TVIF_TEXT, &sNextItem);
if (lstrcmpi(sThisItem.pszText, sNextItem.pszText) < 0)
{
break;
}
hInsertAfter = hItem;
}
// Check if this is still the first item
if (hInsertAfter != TVI_SORT)
{
// Move this item from the beginning to where it
// should be
hParent->hKids = hNewItem->hNext;
hNewItem->hNext = hInsertAfter->hNext;
hInsertAfter->hNext = hNewItem;
}
}
if ((hNewItem->hNext == pTree->hTop) && !pTree->fVert)
{
// there's no scrollbars and we got added before the top
// item. we're now the top.
hNewItem->iShownIndex = 0;
pTree->hTop = hNewItem;
}
if (pTree->fRedraw)
{
BOOL fVert = pTree->fVert;
RECT rc;
RECT rc2;
if (TV_ScrollBarsAfterAdd(pTree, hNewItem))
{
// scroll everything down one
if (ITEM_VISIBLE(hNewItem))
{
int iTop = hNewItem->iShownIndex - pTree->hTop->iShownIndex;
// if there wasn't a scrollbar and we're the 0th item,
// TV_ScrollBarsAfterAdd already scrolled us
if (iTop > 0 || !fVert)
{
TV_ScrollItems(pTree, hNewItem->iIntegral, iTop + hNewItem->iIntegral - 1, TRUE);
}
}
}
// connect the lines, add the buttons, etc. on the item above
// TV_GetPrevVisItem only works after TV_Scroll* stuff is done
if (TV_GetItemRect(pTree, hNewItem, &rc, FALSE))
{
// find the previous sibling or the parent if no prev sib.
if (hParent->hKids == hNewItem)
{
hItem = hParent;
}
else
{
hItem = hParent->hKids;
while (hItem->hNext != hNewItem)
{
_ASSERT(hItem->hNext);
hItem = hItem->hNext;
}
}
// invalidate from there to the new one
if (TV_GetItemRect(pTree, hItem, &rc2, FALSE))
{
rc.top = rc2.top;
}
RedrawWindow(pTree->ci.hwnd, &rc, NULL, RDW_INVALIDATE | RDW_ERASE);
}
}
// DumpItem(hNewItem);
MyNotifyWinEvent(EVENT_OBJECT_CREATE, pTree->ci.hwnd, OBJID_CLIENT, (LONG_PTR)hNewItem);
if (pTree->hToolTip)
{
TV_PopBubble(pTree);
}
return hNewItem;
}
void TV_DeleteHotFonts(PTREE pTree)
{
if (pTree->hFontHot)
{
DeleteObject(pTree->hFontHot);
}
if (pTree->hFontBoldHot)
{
DeleteObject(pTree->hFontBoldHot);
}
pTree->hFontHot = pTree->hFontBoldHot = NULL;
}
// ----------------------------------------------------------------------------
//
// Frees all allocated memory and objects associated with the tree.
//
// ----------------------------------------------------------------------------
void NEAR TV_DestroyTree(PTREE pTree)
{
HWND hwnd = pTree->ci.hwnd;
_ASSERT(pTree->hRoot);
pTree->fRedraw = FALSE;
TV_OnSetBkColor(pTree, (COLORREF)(-1));
if (pTree->hCurHot)
{
DestroyCursor(pTree->hCurHot);
}
if (IsWindow(pTree->hwndToolTips))
{
DestroyWindow(pTree->hwndToolTips);
}
pTree->hwndToolTips = NULL;
if (IsWindow(pTree->hwndEdit))
{
DestroyWindow(pTree->hwndEdit);
}
pTree->hwndEdit = NULL;
// BUGUBG: send TVN_DELETEALLITEMS and TVDI_NONOTIFY if they respond
TV_DeleteItem(pTree, pTree->hRoot, TVDI_CHILDRENONLY | TVDI_NOSELCHANGE);
if (pTree->hRoot)
{
Str_Set(&pTree->hRoot->lpstr, NULL);
// No point in marking dead since the entire control is going away
ControlFree(pTree->hheap, pTree->hRoot);
}
if (pTree->hdcBits)
{
if (pTree->hBmp)
{
SelectObject(pTree->hdcBits, pTree->hStartBmp);
DeleteObject(pTree->hBmp);
}
DeleteDC(pTree->hdcBits);
}
if (pTree->fCreatedFont && pTree->hFont)
{
DeleteObject(pTree->hFont);
}
if (pTree->hFontBold) //$BOLD
{
DeleteObject(pTree->hFontBold); //$BOLD
}
Str_Set(&pTree->pszTip, NULL);
#ifdef UNICODE
if (pTree->pszTipA)
{
LocalFree(pTree->pszTipA);
}
#endif
TV_DeleteHotFonts(pTree);
if (pTree->hdpaWatch)
{
IUI_DPA_Destroy(pTree->hdpaWatch);
}
IncrementSearchFree(&pTree->is);
NearFree(pTree);
// Don't try to use this var when window is destroyed...
SetWindowInt(hwnd, 0, 0);
}
void TV_CreateToolTips(PTREE pTree);
// ----------------------------------------------------------------------------
//
// Allocates space for the tree and initializes the tree's data
//
// ----------------------------------------------------------------------------
LRESULT NEAR TV_OnCreate(HWND hwnd, LPCREATESTRUCT lpCreate)
{
PTREE pTree = (PTREE)NearAlloc(sizeof(TREE));
if (!pTree)
{
return -1; // fail the create window
}
#ifdef WIN32
pTree->hheap = GetProcessHeap();
#endif
if (!TV_CreateRoot(pTree))
{
NearFree((HLOCAL)pTree);
return -1; // fail the create window
}
pTree->hdpaWatch = IUI_DPA_Create(8);
if (!pTree->hdpaWatch)
{
// No point in marking dead since the entire control is going away
ControlFree(pTree->hheap, pTree->hRoot);
NearFree((HLOCAL)pTree);
return -1; // fail the create window
}
SetWindowPtr(hwnd, 0, pTree);
CIInitialize(&pTree->ci, hwnd, lpCreate);
#ifdef WINDOWS_ME
if (lpCreate->dwExStyle & WS_EX_RTLREADING)
{
pTree->ci.style |= TVS_RTLREADING;
}
#endif
#ifdef DEBUG
if (GetAsyncKeyState(VK_SHIFT) < 0 &&
GetAsyncKeyState(VK_CONTROL) < 0)
{
pTree->ci.style |= TVS_SHOWSELALWAYS; // | TVS_CHECKBOXES;
SetWindowLong(pTree->ci.hwnd, GWL_STYLE, pTree->ci.style);
}
#endif
pTree->fRedraw = TRUE;
pTree->clrBk = (COLORREF) - 1;
pTree->clrText = (COLORREF) - 1;
pTree->clrim = CLR_DEFAULT;
pTree->clrLine = CLR_DEFAULT;
// pTree->fHorz = FALSE;
// pTree->fVert = FALSE;
// pTree->fFocus = FALSE;
// pTree->fNameEditPending = FALSE;
// pTree->cxMax = 0;
// pTree->cxWnd = 0;
// pTree->cyWnd = 0;
// pTree->hTop = NULL;
// pTree->hCaret = NULL;
// pTree->hDropTarget = NULL;
// pTree->hOldDrop = NULL;
// pTree->cItems = 0;
// pTree->cShowing = 0;
pTree->cFullVisible = 1;
// pTree->hdcBits = NULL;
// pTree->hBmp = NULL;
// pTree->hbrBk = NULL;
// pTree->xPos = 0;
// pTree->cxIndent = 0; // init this for real in TV_OnSetFont()
// pTree->dwCDDepth = 0;
pTree->uMaxScrollTime = SSI_DEFAULT;
TV_OnSetFont(pTree, NULL, TRUE);
// You cannot combine TVS_HASLINES and TVS_FULLROWSELECT
// because it doesn't work
if (pTree->ci.style & TVS_HASLINES)
{
if (pTree->ci.style & TVS_FULLROWSELECT)
{
//L DebugMsg(DM_ERROR, TEXT("Cannot combine TVS_HASLINES and TVS_FULLROWSELECT"));
}
pTree->ci.style &= ~TVS_FULLROWSELECT;
}
if (!(pTree->ci.style & TVS_NOTOOLTIPS))
{
TV_CreateToolTips(pTree);
}
SetScrollRange(hwnd, SB_HORZ, 0, 0, TRUE);
SetScrollRange(hwnd, SB_VERT, 0, 0, TRUE);
return 0; // success
}
void TV_CreateToolTips(PTREE pTree)
{
#if defined(MAINWIN)
/* IUENIX : On CDE, when tooltip comes up, WM activates tooltip window causing some
flashing due to activation/deactivation of various other windows. Hence asking WM
not to manage such tooltip windows */
DWORD exStyle = WS_EX_MW_UNMANAGED_WINDOW;
#else
DWORD exStyle = 0;
#endif
#ifdef WINDOWS_ME
if (pTree->ci.style & TVS_RTLREADING)
{
exStyle |= WS_EX_RTLREADING;
}
#endif // WINDOWS_ME
pTree->hwndToolTips = CreateWindowEx(exStyle, c_szSToolTipsClass, NULL,
WS_POPUP | TTS_NOPREFIX,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
pTree->ci.hwnd, NULL, NULL,
NULL);
if (pTree->hwndToolTips)
{
TOOLINFO ti;
ti.cbSize = sizeof(ti);
ti.uFlags = TTF_IDISHWND | TTF_TRANSPARENT;
ti.hwnd = pTree->ci.hwnd;
ti.uId = (UINT_PTR)pTree->ci.hwnd;
ti.lpszText = LPSTR_TEXTCALLBACK;
ti.lParam = 0;
SendMessage(pTree->hwndToolTips, TTM_ADDTOOL, 0,
(LPARAM)(LPTOOLINFO)&ti);
SendMessage(pTree->hwndToolTips, WM_SETFONT, (WPARAM)pTree->hFont, (LPARAM)TRUE);
#if 0
SendMessage(pTree->hwndToolTips, TTM_SETTIPBKCOLOR, (WPARAM)GetSysColor(COLOR_WINDOW), 0);
SendMessage(pTree->hwndToolTips, TTM_SETTIPTEXTCOLOR, (WPARAM)GetSysColor(COLOR_WINDOWTEXT), 0);
#endif
SendMessage(pTree->hwndToolTips, TTM_SETDELAYTIME, TTDT_INITIAL, (LPARAM)500);
}
else
{
pTree->ci.style |= (TVS_NOTOOLTIPS);
}
}
| 24.51833 | 128 | 0.61702 | [
"3d"
] |
63568a0fb4d1b7c466aafa86de2c4ae962b570fa | 6,552 | cpp | C++ | src/libs/JustFastUi/JustFastUi.cpp | Daniel-Boll/just-fast | a45c4b22553ab00a7f918bd93ec73373185ef1c2 | [
"MIT"
] | 19 | 2020-05-01T16:08:34.000Z | 2022-03-22T09:14:10.000Z | src/libs/JustFastUi/JustFastUi.cpp | Daniel-Boll/just-fast | a45c4b22553ab00a7f918bd93ec73373185ef1c2 | [
"MIT"
] | 10 | 2020-05-01T17:08:27.000Z | 2021-11-23T10:24:59.000Z | src/libs/JustFastUi/JustFastUi.cpp | Daniel-Boll/just-fast | a45c4b22553ab00a7f918bd93ec73373185ef1c2 | [
"MIT"
] | 6 | 2020-04-26T10:11:09.000Z | 2022-02-04T10:12:13.000Z | #include "JustFastUi.h"
#include <codecvt>
#include <ftxui/component/event.hpp>
#include <ftxui/screen/string.hpp>
#include <string>
#include <utility>
void JustFastUi::setQuitFunction(std::function<void()> q)
{
quit = std::move(q);
}
JustFastUi::JustFastUi(const JustFastOptions& options)
: statusMessage(L""), statusSelected(L"0"), currentPath { options.path }
, isShowingHiddenFile { options.showHiddenFiles }
{
int availableSpace = std::filesystem::space(currentPath).available / 1e9;
int capacity = std::filesystem::space(currentPath).capacity / 1e9;
diskSpaceAvailable = float(availableSpace) / float(capacity);
spaceInfo = L"Free Space:" + std::to_wstring(availableSpace) + L" GiB " + L"(Total:" + std::to_wstring(capacity) + L"GiB)";
currentPathCached = currentPath.wstring();
Add(currentFolder);
updateAllUi();
}
void JustFastUi::updateMainView(size_t cursorPosition)
{
currentFolderEntries.clear();
currentFolderSelected = cursorPosition;
try {
for (const auto& p : std::filesystem::directory_iterator(currentPath)) {
if (isShowingHiddenFile || p.path().filename().string()[0] != '.') {
currentFolderEntries.emplace_back(p.path().filename().wstring());
}
}
} catch (std::filesystem::filesystem_error& error) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
statusMessage = converter.from_bytes(error.what());
changePathAndUpdateViews(currentPath.parent_path());
}
}
void JustFastUi::updateParentView()
{
parentFolderEntries.clear();
for (const auto& p : std::filesystem::directory_iterator(currentPath.parent_path())) {
if (isShowingHiddenFile || p.path().filename().string()[0] != '.') {
parentFolderEntries.emplace_back(p.path().filename().wstring());
}
if (p.path().filename() == currentPath.filename()) {
parentFolderSelected = parentFolderEntries.size() - 1;
}
}
}
void JustFastUi::updateOperationView()
{
switch (filesystemOperations.getOperation()) {
case FileSystemOperations::Operation::NOT_SELECTED:
operationView = L"NO_MODE";
break;
case FileSystemOperations::Operation::COPY:
operationView = L"COPY";
break;
case FileSystemOperations::Operation::MOVE:
operationView = L"MOVE";
break;
case FileSystemOperations::Operation::DELETE:
operationView = L"DELETE";
break;
}
}
void JustFastUi::updateSelectedCounter()
{
statusSelected = L"(" + std::to_wstring(filesystemOperations.countSelectedFiles()) + L") ";
}
void JustFastUi::updateAllUi(size_t cursorPosition)
{
updateMainView(cursorPosition);
updateParentView();
updateOperationView();
updateSelectedCounter();
}
void JustFastUi::changePathAndUpdateViews(const std::filesystem::path& newPath)
{
if (!std::filesystem::is_directory(newPath)) {
return;
}
currentPath = newPath;
currentPathCached = currentPath.wstring();
updateMainView();
updateParentView();
}
void JustFastUi::selectFile(const std::filesystem::path& selectedFile)
{
filesystemOperations.appendSelectedFiles(selectedFile);
updateSelectedCounter();
}
void JustFastUi::toggleHiddenFiles()
{
isShowingHiddenFile = !isShowingHiddenFile;
updateMainView();
updateParentView();
}
void JustFastUi::selectOperation(FileSystemOperations::Operation o)
{
filesystemOperations.setOperation(o);
updateOperationView();
}
void JustFastUi::performOperation(const std::filesystem::path& dest)
{
try {
filesystemOperations.performOperation(dest);
updateAllUi();
} catch (std::filesystem::filesystem_error& error) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
statusMessage = converter.from_bytes(error.what());
changePathAndUpdateViews(currentPath.parent_path());
}
}
// clang-format off
ftxui::Element JustFastUi::Render()
{
using namespace ftxui;
if(filesystemOperations.lastOperationIsCompleated()){
updateAllUi(currentFolderSelected);
filesystemOperations.clearLastOperationStatus();
}
auto currentPathView = text(currentPathCached);
auto mainView =
hbox({
parentFolder->Render() | frame,
separator(),
currentFolder->Render() | flex | frame
});
auto statusLine =
hbox({
text(L"["),
gauge(0.5) | flex | size(WIDTH, EQUAL, 10),
text(L"] "),
text(spaceInfo),
text(statusMessage) | center | flex,
text(statusSelected + L" " + operationView)
});
return
window(
text(L"Just Fast") | bold | center,
vbox({
currentPathView,
separator(),
mainView | flex,
separator(),
statusLine
})
);
}
// clang-format on
bool JustFastUi::OnEvent(ftxui::Event event)
{
if (event == ftxui::Event::Character('l') || event == ftxui::Event::ArrowRight) {
if (currentFolderEntries.empty()) {
return true;
}
changePathAndUpdateViews(currentPath / currentFolderEntries[currentFolderSelected]);
return true;
}
if (event == ftxui::Event::Character('h') || event == ftxui::Event::ArrowLeft) {
changePathAndUpdateViews(currentPath.parent_path());
return true;
}
if (event == ftxui::Event::Character('f')) {
selectFile(currentPath / currentFolderEntries[currentFolderSelected]);
return true;
}
if (event == ftxui::Event::Character(' ')) {
performOperation(currentPath);
return true;
}
if (event == ftxui::Event::Character('c')) {
selectOperation(FileSystemOperations::Operation::COPY);
return true;
}
if (event == ftxui::Event::Character('m')) {
selectOperation(FileSystemOperations::Operation::MOVE);
return true;
}
if (event == ftxui::Event::Character('d')) {
selectOperation(FileSystemOperations::Operation::DELETE);
return true;
}
if (event == ftxui::Event::Character('a')) {
toggleHiddenFiles();
return true;
}
if (event == ftxui::Event::Escape) {
filesystemOperations.clearSelectedFiles();
return true;
}
if (event == ftxui::Event::Character('q')) {
quit();
}
return ComponentBase::OnEvent(event);
}
| 28 | 127 | 0.637973 | [
"render"
] |
635bece3e8f10d5372d6d59f9079b880b5ba4bf7 | 120,328 | cc | C++ | chrome/browser/ui/views/omnibox/omnibox_view_views.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/ui/views/omnibox/omnibox_view_views.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/ui/views/omnibox/omnibox_view_views.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright (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/ui/views/omnibox/omnibox_view_views.h"
#include <memory>
#include <set>
#include <utility>
#include "base/auto_reset.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/command_updater.h"
#include "chrome/browser/external_protocol/external_protocol_handler.h"
#include "chrome/browser/history_clusters/history_clusters_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/reputation/url_elision_policy.h"
#include "chrome/browser/send_tab_to_self/send_tab_to_self_desktop_util.h"
#include "chrome/browser/send_tab_to_self/send_tab_to_self_util.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/omnibox/clipboard_utils.h"
#include "chrome/browser/ui/omnibox/omnibox_theme.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_result_view.h"
#include "chrome/grit/generated_resources.h"
#include "components/omnibox/browser/autocomplete_input.h"
#include "components/omnibox/browser/autocomplete_match.h"
#include "components/omnibox/browser/location_bar_model.h"
#include "components/omnibox/browser/omnibox_client.h"
#include "components/omnibox/browser/omnibox_edit_controller.h"
#include "components/omnibox/browser/omnibox_edit_model.h"
#include "components/omnibox/browser/omnibox_field_trial.h"
#include "components/omnibox/browser/omnibox_popup_model.h"
#include "components/omnibox/browser/omnibox_prefs.h"
#include "components/prefs/pref_service.h"
#include "components/security_state/core/security_state.h"
#include "components/strings/grit/components_strings.h"
#include "components/url_formatter/elide_url.h"
#include "components/url_formatter/url_fixer.h"
#include "components/url_formatter/url_formatter.h"
#include "components/vector_icons/vector_icons.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/focused_node_details.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "extensions/common/constants.h"
#include "net/base/escape.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/base/url_util.h"
#include "third_party/metrics_proto/omnibox_event.pb.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/clipboard_buffer.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_edit_commands.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/ime/virtual_keyboard_controller.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/image_model.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/presentation_feedback.h"
#include "ui/gfx/selection_model.h"
#include "ui/gfx/text_elider.h"
#include "ui/gfx/text_utils.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/border.h"
#include "ui/views/button_drag_utils.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/metadata/metadata_impl_macros.h"
#include "ui/views/views_features.h"
#include "ui/views/widget/widget.h"
#include "url/gurl.h"
#if defined(OS_WIN)
#include "chrome/browser/browser_process.h"
#endif
namespace {
using ::metrics::OmniboxEventProto;
using ::ui::mojom::DragOperation;
// OmniboxState ---------------------------------------------------------------
// Stores omnibox state for each tab.
struct OmniboxState : public base::SupportsUserData::Data {
static const char kKey[];
OmniboxState(const OmniboxEditModel::State& model_state,
const std::vector<gfx::Range> selection,
const std::vector<gfx::Range> saved_selection_for_focus_change);
~OmniboxState() override;
const OmniboxEditModel::State model_state;
// We store both the actual selection and any saved selection (for when the
// omnibox is not focused). This allows us to properly handle cases like
// selecting text, tabbing out of the omnibox, switching tabs away and back,
// and tabbing back into the omnibox.
const std::vector<gfx::Range> selection;
const std::vector<gfx::Range> saved_selection_for_focus_change;
};
// static
const char OmniboxState::kKey[] = "OmniboxState";
OmniboxState::OmniboxState(
const OmniboxEditModel::State& model_state,
const std::vector<gfx::Range> selection,
const std::vector<gfx::Range> saved_selection_for_focus_change)
: model_state(model_state),
selection(selection),
saved_selection_for_focus_change(saved_selection_for_focus_change) {}
OmniboxState::~OmniboxState() = default;
bool IsClipboardDataMarkedAsConfidential() {
return ui::Clipboard::GetForCurrentThread()
->IsMarkedByOriginatorAsConfidential();
}
// Draws a rectangle of dimensions and position |rect| in |canvas|, colored
// with a gradient from |start_color| to |end_color|.
void DrawGradientRect(const gfx::Rect& rect,
SkColor start_color,
SkColor end_color,
gfx::Canvas* canvas) {
SkColor colors[2] = {start_color, end_color};
SkPoint points[2];
points[0].iset(rect.origin().x(), rect.origin().y());
points[1].iset(rect.right(), rect.y());
cc::PaintFlags flags;
flags.setShader(cc::PaintShader::MakeLinearGradient(points, colors, nullptr,
2, SkTileMode::kClamp));
canvas->DrawRect(rect, flags);
}
// Returns true if the substring indicated by |range| overflows
// |omnibox_view|'s current local bounds.
bool TextRangeOverflowsView(OmniboxViewViews* omnibox_view,
gfx::RenderText* render_text,
const gfx::Range& range) {
// The RenderText must be in NO_ELIDE mode to attempt to retrieve the bounds
// of |range| (which could be outside its display area).
DCHECK_EQ(gfx::NO_ELIDE, render_text->elide_behavior());
gfx::Rect range_rect;
for (const auto& rect : render_text->GetSubstringBounds(range))
range_rect.Union(rect);
return omnibox_view->GetLocalBounds().width() < range_rect.width();
}
} // namespace
OmniboxViewViews::ElideAnimation::ElideAnimation(OmniboxViewViews* view,
gfx::RenderText* render_text)
: AnimationDelegateViews(view), view_(view), render_text_(render_text) {
DCHECK(view_);
DCHECK(render_text_);
}
OmniboxViewViews::ElideAnimation::~ElideAnimation() = default;
// TODO(estark): this code doesn't work for URLs with RTL components. Will need
// to figure out another animation or just skip the animation entirely on URLs
// with RTL components.
void OmniboxViewViews::ElideAnimation::Start(
const gfx::Range& elide_to_bounds,
uint32_t delay_ms,
const std::vector<gfx::Range>& ranges_surrounding_simplified_domain,
SkColor starting_color,
SkColor ending_color) {
DCHECK(ranges_surrounding_simplified_domain.size() == 1 ||
ranges_surrounding_simplified_domain.size() == 2);
ranges_surrounding_simplified_domain_ = ranges_surrounding_simplified_domain;
starting_color_ = starting_color;
ending_color_ = ending_color;
// simplified_domain_bounds_ will be set to a rectangle surrounding the part
// of the URL that is never elided, on its original position before any
// animation runs. If ranges_surrounding_simplified_domain_ only contains one
// range it means we are not eliding on the right side, so we use the right
// side of elide_to_bounds as the range as it will always be the right limit
// of the simplified section.
gfx::Range simplified_domain_range(
ranges_surrounding_simplified_domain_[0].end(),
ranges_surrounding_simplified_domain_.size() == 2
? ranges_surrounding_simplified_domain_[1].start()
: elide_to_bounds.end());
for (auto rect : render_text_->GetSubstringBounds(simplified_domain_range)) {
simplified_domain_bounds_.Union(rect - render_text_->GetLineOffset(0));
}
// After computing |elide_to_rect_| below, |elide_to_bounds| aren't actually
// need anymore for the animation. However, the bounds provide a convenient
// way for the animation consumer to check if an animation is currently in
// progress to a specific range, so that the consumer can avoid starting a
// duplicate animation (to avoid flicker). So we save the bounds so that
// consumers can query them.
elide_to_bounds_ = elide_to_bounds;
animation_ =
std::make_unique<gfx::MultiAnimation>(gfx::MultiAnimation::Parts({
gfx::MultiAnimation::Part(base::TimeDelta::FromMilliseconds(delay_ms),
gfx::Tween::ZERO),
gfx::MultiAnimation::Part(base::TimeDelta::FromMilliseconds(300),
gfx::Tween::FAST_OUT_SLOW_IN),
}));
animation_->set_delegate(this);
animation_->set_continuous(false);
elide_from_rect_ = render_text_->display_rect();
elide_to_rect_ = gfx::Rect();
for (const auto& rect : render_text_->GetSubstringBounds(elide_to_bounds))
elide_to_rect_.Union(rect);
// The URL should never shift vertically while eliding to/from simplified
// domain.
elide_to_rect_.set_y(elide_from_rect_.y());
elide_to_rect_.set_height(elide_from_rect_.height());
// There is nothing to animate in this case, so return without starting.
if (elide_from_rect_ == elide_to_rect_ && starting_color_ == ending_color_)
return;
starting_display_offset_ = render_text_->GetUpdatedDisplayOffset().x();
// Shift the text to where |elide_to_bounds| starts, relative to the current
// display rect.
if (base::i18n::IsRTL()) {
ending_display_offset_ = starting_display_offset_ +
elide_from_rect_.right() - elide_to_rect_.right();
} else {
ending_display_offset_ =
starting_display_offset_ - (elide_to_rect_.x() - elide_from_rect_.x());
}
animation_->Start();
}
void OmniboxViewViews::ElideAnimation::Stop() {
// Reset the smoothing rectangles whenever the animation stops to prevent
// stale rectangles from showing at the start of the next animation.
view_->elide_animation_smoothing_rect_left_ = gfx::Rect();
view_->elide_animation_smoothing_rect_right_ = gfx::Rect();
if (animation_)
animation_->Stop();
}
bool OmniboxViewViews::ElideAnimation::IsAnimating() {
return animation_ && animation_->is_animating();
}
const gfx::Range& OmniboxViewViews::ElideAnimation::GetElideToBounds() const {
return elide_to_bounds_;
}
SkColor OmniboxViewViews::ElideAnimation::GetCurrentColor() const {
return animation_
? gfx::Tween::ColorValueBetween(animation_->GetCurrentValue(),
starting_color_, ending_color_)
: gfx::kPlaceholderColor;
}
gfx::MultiAnimation*
OmniboxViewViews::ElideAnimation::GetAnimationForTesting() {
return animation_.get();
}
void OmniboxViewViews::ElideAnimation::AnimationProgressed(
const gfx::Animation* animation) {
DCHECK(!view_->model()->user_input_in_progress());
DCHECK_EQ(animation, animation_.get());
if (animation->GetCurrentValue() == 0)
return;
// |bounds| contains the interpolated substring to show for this frame. Shift
// it to line up with the x position of the previous frame (|old_bounds|),
// because the animation should gradually bring the desired string into view
// at the leading edge. The y/height values shouldn't change because
// |elide_to_rect_| is set to have the same y and height values as
// |elide_to_rect_|.
gfx::Rect old_bounds = render_text_->display_rect();
gfx::Rect bounds = gfx::Tween::RectValueBetween(
animation->GetCurrentValue(), elide_from_rect_, elide_to_rect_);
DCHECK_EQ(bounds.y(), old_bounds.y());
DCHECK_EQ(bounds.height(), old_bounds.height());
gfx::Rect shifted_bounds(base::i18n::IsRTL()
? old_bounds.right() - bounds.width()
: old_bounds.x(),
old_bounds.y(), bounds.width(), old_bounds.height());
render_text_->SetDisplayRect(shifted_bounds);
current_offset_ = gfx::Tween::IntValueBetween(animation->GetCurrentValue(),
starting_display_offset_,
ending_display_offset_);
render_text_->SetDisplayOffset(current_offset_);
for (const auto& range : ranges_surrounding_simplified_domain_) {
view_->ApplyColor(GetCurrentColor(), range);
}
// TODO(crbug.com/1101472): The smoothing gradient mask is not yet implemented
// correctly for RTL UI.
if (base::i18n::IsRTL()) {
view_->SchedulePaint();
return;
}
// The gradient mask should be a fixed width, except if that width would
// cause it to mask the unelided section. In that case we set it to the
// maximum width possible that won't cover the unelided section.
int unelided_left_bound = simplified_domain_bounds_.x() + current_offset_;
int unelided_right_bound =
unelided_left_bound + simplified_domain_bounds_.width();
// GetSubstringBounds rounds up when calculating unelided_left_bound and
// unelided_right_bound, we subtract 1 pixel from the gradient widths to make
// sure they never overlap with the always visible part of the URL.
// gfx::Rect() switches negative values to 0, so this doesn't affect
// rectangles that were originally size 0.
int left_gradient_width = kSmoothingGradientMaxWidth < unelided_left_bound
? kSmoothingGradientMaxWidth - 1
: unelided_left_bound - 1;
int right_gradient_width =
shifted_bounds.right() - kSmoothingGradientMaxWidth > unelided_right_bound
? kSmoothingGradientMaxWidth - 1
: shifted_bounds.right() - unelided_right_bound - 1;
view_->elide_animation_smoothing_rect_left_ = gfx::Rect(
old_bounds.x(), old_bounds.y(), left_gradient_width, old_bounds.height());
view_->elide_animation_smoothing_rect_right_ =
gfx::Rect(shifted_bounds.right() - right_gradient_width, old_bounds.y(),
right_gradient_width, old_bounds.height());
view_->SchedulePaint();
}
// OmniboxViewViews -----------------------------------------------------------
OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller,
std::unique_ptr<OmniboxClient> client,
bool popup_window_mode,
LocationBarView* location_bar,
const gfx::FontList& font_list)
: OmniboxView(controller, std::move(client)),
popup_window_mode_(popup_window_mode),
clock_(base::DefaultClock::GetInstance()),
location_bar_view_(location_bar),
latency_histogram_state_(NOT_ACTIVE),
friendly_suggestion_text_prefix_length_(0) {
SetID(VIEW_ID_OMNIBOX);
SetFontList(font_list);
set_force_text_directionality(true);
// Unit tests may use a mock location bar that has no browser,
// or use no location bar at all.
if (location_bar_view_ && location_bar_view_->browser()) {
pref_change_registrar_.Init(
location_bar_view_->browser()->profile()->GetPrefs());
pref_change_registrar_.Add(
omnibox::kPreventUrlElisionsInOmnibox,
base::BindRepeating(&OmniboxViewViews::OnShouldPreventElisionChanged,
base::Unretained(this)));
}
// Sometimes there are additional ignored views, such as a View representing
// the cursor, inside the address bar's text field. These should always be
// ignored by accessibility since a plain text field should always be a leaf
// node in the accessibility trees of all the platforms we support.
GetViewAccessibility().OverrideIsLeaf(true);
}
OmniboxViewViews::~OmniboxViewViews() {
#if BUILDFLAG(IS_CHROMEOS_ASH)
chromeos::input_method::InputMethodManager::Get()->
RemoveCandidateWindowObserver(this);
#endif
// Explicitly teardown members which have a reference to us. Just to be safe
// we want them to be destroyed before destroying any other internal state.
popup_view_.reset();
}
void OmniboxViewViews::Init() {
set_controller(this);
SetTextInputType(ui::TEXT_INPUT_TYPE_URL);
GetRenderText()->SetElideBehavior(gfx::ELIDE_TAIL);
GetRenderText()->set_symmetric_selection_visual_bounds(true);
InstallPlaceholderText();
scoped_template_url_service_observation_.Observe(
model()->client()->GetTemplateURLService());
if (popup_window_mode_)
SetReadOnly(true);
if (location_bar_view_) {
// Initialize the popup view using the same font.
popup_view_ = std::make_unique<OmniboxPopupContentsView>(
this, model(), location_bar_view_);
if (OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() &&
!model()->ShouldPreventElision()) {
Observe(location_bar_view_->GetWebContents());
}
// Set whether the text should be used to improve typing suggestions.
SetShouldDoLearning(!location_bar_view_->profile()->IsOffTheRecord());
}
// Override the default FocusableBorder from Textfield, since the
// LocationBarView will indicate the focus state.
constexpr gfx::Insets kTextfieldInsets(3);
SetBorder(views::CreateEmptyBorder(kTextfieldInsets));
#if BUILDFLAG(IS_CHROMEOS_ASH)
chromeos::input_method::InputMethodManager::Get()->
AddCandidateWindowObserver(this);
#endif
}
void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) {
DCHECK(tab);
// We don't want to keep the IME status, so force quit the current
// session here. It may affect the selection status, so order is
// also important.
if (IsIMEComposing()) {
ConfirmCompositionText(/* keep_selection */ false);
GetInputMethod()->CancelComposition(this);
}
// NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
// important.
OmniboxEditModel::State state = model()->GetStateForTabSwitch();
tab->SetUserData(
OmniboxState::kKey,
std::make_unique<OmniboxState>(state, GetRenderText()->GetAllSelections(),
saved_selection_for_focus_change_));
}
void OmniboxViewViews::OnTabChanged(content::WebContents* web_contents) {
const OmniboxState* state = static_cast<OmniboxState*>(
web_contents->GetUserData(&OmniboxState::kKey));
model()->RestoreState(state ? &state->model_state : nullptr);
if (state) {
// This assumes that the omnibox has already been focused or blurred as
// appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
// goof up the selection. See comments on OnActiveTabChanged() call in
// Browser::ActiveTabChanged().
if (state->model_state.user_input_in_progress &&
state->model_state.user_text.empty() &&
state->model_state.keyword.empty()) {
// See comment in OmniboxEditModel::GetStateForTabSwitch() for details on
// this.
SelectAll(true);
saved_selection_for_focus_change_.clear();
} else {
SetSelectedRanges(state->selection);
saved_selection_for_focus_change_ =
state->saved_selection_for_focus_change;
}
}
// TODO(msw|oshima): Consider saving/restoring edit history.
ClearEditHistory();
// When the tab is changed, unelide the URL in case it had previously been
// elided to a simplified domain by a user interaction (when certain field
// trials are enabled).
ResetToHideOnInteraction();
if (OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() &&
!model()->ShouldPreventElision()) {
Observe(web_contents);
}
}
void OmniboxViewViews::ResetTabState(content::WebContents* web_contents) {
web_contents->SetUserData(OmniboxState::kKey, nullptr);
}
void OmniboxViewViews::InstallPlaceholderText() {
const TemplateURL* const default_provider =
model()->client()->GetTemplateURLService()->GetDefaultSearchProvider();
if (default_provider) {
SetPlaceholderText(l10n_util::GetStringFUTF16(
IDS_OMNIBOX_PLACEHOLDER_TEXT, default_provider->short_name()));
} else {
SetPlaceholderText(std::u16string());
}
}
bool OmniboxViewViews::GetSelectionAtEnd() const {
const gfx::Range sel = GetSelectedRange();
return sel.GetMin() == GetText().size();
}
void OmniboxViewViews::EmphasizeURLComponents() {
// Cancel any existing simplified URL animations.
if (hover_elide_or_unelide_animation_)
hover_elide_or_unelide_animation_->Stop();
if (elide_after_web_contents_interaction_animation_)
elide_after_web_contents_interaction_animation_->Stop();
// If the current contents is a URL, turn on special URL rendering mode in
// RenderText.
bool text_is_url = model()->CurrentTextIsURL();
GetRenderText()->SetDirectionalityMode(
text_is_url ? gfx::DIRECTIONALITY_AS_URL : gfx::DIRECTIONALITY_FROM_TEXT);
SetStyle(gfx::TEXT_STYLE_STRIKE, false);
std::u16string text = GetText();
UpdateTextStyle(text, text_is_url, model()->client()->GetSchemeClassifier());
if (model()->ShouldPreventElision())
return;
// If the text isn't eligible to be elided to a simplified domain, and
// simplified domain field trials are enabled, then ensure that as much of the
// text as will fit is visible.
if (!GetURLEligibleForSimplifiedDomainEliding() &&
(OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover())) {
FitToLocalBounds();
return;
}
// In the simplified domain field trials, elide or unelide according to the
// current state and field trial configuration. These elisions are not
// animated because we often don't want this to be a user-visible
// transformation; for example, a navigation should just show the URL in the
// desired state without drawing additional attention from the user.
if (OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction()) {
// In the hide-on-interaction field trial, elide or unelide the URL to the
// simplified domain depending on whether the user has already interacted
// with the page or not. This is a best guess at the correct elision state,
// which we don't really know for sure until a navigation has committed
// (because the elision behavior depends on whether the navigation is
// same-document and if it changes the path). We elide here based on the
// current elision setting; we'll then update the elision state as we get
// more information about the navigation in DidStartNavigation and
// DidFinishNavigation.
if (elide_after_web_contents_interaction_animation_) {
// This can cause a slight quirk in browser-initiated navigations that
// occur after the user interacts with the previous page. In this case,
// the simplified domain will be shown briefly before we show the full URL
// in DidStartNavigation().
ElideURL();
} else {
// Note that here we are only adjusting the display of the URL, not
// resetting any state associated with the animations (in particular, we
// are not calling ResetToHideOnInteraction()). This is, as above, because
// we don't know exactly how to set state until we know what kind of
// navigation is happening. Thus here we are only adjusting the display so
// things look right mid-navigation, and the final state will be set
// appropriately in DidFinishNavigation().
ShowFullURLWithoutSchemeAndTrivialSubdomain();
}
} else if (OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover()) {
// If reveal-on-hover is enabled and hide-on-interaction is disabled, elide
// to the simplified domain now.
ElideURL();
}
}
void OmniboxViewViews::Update() {
if (model()->ResetDisplayTexts()) {
RevertAll();
// Only select all when we have focus. If we don't have focus, selecting
// all is unnecessary since the selection will change on regaining focus.
if (model()->has_focus())
SelectAll(true);
} else {
// If the text is unchanged, we still need to re-emphasize the text, as the
// security state may be different from before the Update.
EmphasizeURLComponents();
}
}
std::u16string OmniboxViewViews::GetText() const {
// TODO(oshima): IME support
return Textfield::GetText();
}
void OmniboxViewViews::SetUserText(const std::u16string& text,
bool update_popup) {
saved_selection_for_focus_change_.clear();
OmniboxView::SetUserText(text, update_popup);
}
void OmniboxViewViews::SetAdditionalText(
const std::u16string& additional_text) {
// TODO (manukh): Ideally, OmniboxView wouldn't be responsible for its sibling
// label owned by LocationBarView. However, this is the only practical pathway
// between the OmniboxEditModel, which handles setting the omnibox match, and
// LocationBarView. Perhaps, if we decide to launch rich autocompletion we'll
// consider alternatives.
location_bar_view_->SetOmniboxAdditionalText(additional_text);
}
void OmniboxViewViews::EnterKeywordModeForDefaultSearchProvider() {
// Transition the user into keyword mode using their default search provider.
model()->EnterKeywordModeForDefaultSearchProvider(
OmniboxEventProto::KEYBOARD_SHORTCUT);
}
void OmniboxViewViews::GetSelectionBounds(
std::u16string::size_type* start,
std::u16string::size_type* end) const {
const gfx::Range range = GetSelectedRange();
*start = static_cast<size_t>(range.start());
*end = static_cast<size_t>(range.end());
}
size_t OmniboxViewViews::GetAllSelectionsLength() const {
size_t sum = 0;
for (auto s : GetRenderText()->GetAllSelections())
sum += s.length();
return sum;
}
void OmniboxViewViews::SelectAll(bool reversed) {
views::Textfield::SelectAll(reversed);
}
void OmniboxViewViews::RevertAll() {
saved_selection_for_focus_change_.clear();
OmniboxView::RevertAll();
}
void OmniboxViewViews::SetFocus(bool is_user_initiated) {
// Temporarily reveal the top-of-window views (if not already revealed) so
// that the location bar view is visible and is considered focusable. When it
// actually receives focus, ImmersiveFocusWatcher will add another lock to
// keep it revealed. |location_bar_view_| can be nullptr in unit tests.
std::unique_ptr<ImmersiveRevealedLock> focus_reveal_lock;
if (location_bar_view_) {
focus_reveal_lock.reset(
BrowserView::GetBrowserViewForBrowser(location_bar_view_->browser())
->immersive_mode_controller()
->GetRevealedLock(ImmersiveModeController::ANIMATE_REVEAL_YES));
}
const bool omnibox_already_focused = HasFocus();
if (is_user_initiated)
model()->Unelide();
RequestFocus();
if (omnibox_already_focused)
model()->ClearKeyword();
// If the user initiated the focus, then we always select-all, even if the
// omnibox is already focused. This can happen if the user pressed Ctrl+L
// while already typing in the omnibox.
//
// For renderer initiated focuses (like NTP or about:blank page load finish):
// - If the omnibox was not already focused, select-all. This handles the
// about:blank homepage case, where the location bar has initial focus.
// It annoys users if the URL is not pre-selected. https://crbug.com/45260.
// - If the omnibox is already focused, DO NOT select-all. This can happen
// if the user starts typing before the NTP finishes loading. If the NTP
// finishes loading and then does a renderer-initiated focus, performing
// a select-all here would surprisingly overwrite the user's first few
// typed characters. https://crbug.com/924935.
if (is_user_initiated || !omnibox_already_focused)
SelectAll(true);
// |is_user_initiated| is true for focus events from keyboard accelerators.
if (is_user_initiated)
model()->StartZeroSuggestRequest();
// Restore caret visibility if focus is explicitly requested. This is
// necessary because if we already have invisible focus, the RequestFocus()
// call above will short-circuit, preventing us from reaching
// OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
// omnibox regains focus after losing focus.
model()->SetCaretVisibility(true);
// If the user attempts to focus the omnibox, and the ctrl key is pressed, we
// want to prevent ctrl-enter behavior until the ctrl key is released and
// re-pressed. This occurs even if the omnibox is already focused and we
// re-request focus (e.g. pressing ctrl-l twice).
model()->ConsumeCtrlKey();
}
int OmniboxViewViews::GetTextWidth() const {
// Returns the width necessary to display the current text, including any
// necessary space for the cursor or border/margin.
return GetRenderText()->GetContentWidth() + GetInsets().width();
}
int OmniboxViewViews::GetUnelidedTextWidth() const {
auto elide_behavior = GetRenderText()->elide_behavior();
GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
auto width = GetTextWidth();
GetRenderText()->SetElideBehavior(elide_behavior);
return width;
}
bool OmniboxViewViews::IsImeComposing() const {
return IsIMEComposing();
}
gfx::Size OmniboxViewViews::GetMinimumSize() const {
const int kMinCharacters = 20;
return gfx::Size(
GetFontList().GetExpectedTextWidth(kMinCharacters) + GetInsets().width(),
GetPreferredSize().height());
}
void OmniboxViewViews::OnPaint(gfx::Canvas* canvas) {
if (latency_histogram_state_ == CHAR_TYPED) {
DCHECK(!insert_char_time_.is_null());
auto now = base::TimeTicks::Now();
UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency.ToPaint",
now - insert_char_time_);
latency_histogram_state_ = ON_PAINT_CALLED;
GetWidget()->GetCompositor()->RequestPresentationTimeForNextFrame(
base::BindOnce(
[](base::TimeTicks insert_timestamp,
base::TimeTicks paint_timestamp,
const gfx::PresentationFeedback& feedback) {
if (feedback.flags & gfx::PresentationFeedback::kFailure)
return;
UMA_HISTOGRAM_TIMES(
"Omnibox.CharTypedToRepaintLatency.PaintToPresent",
feedback.timestamp - paint_timestamp);
UMA_HISTOGRAM_TIMES(
"Omnibox.CharTypedToRepaintLatency.InsertToPresent",
feedback.timestamp - insert_timestamp);
},
insert_char_time_, now));
}
{
SCOPED_UMA_HISTOGRAM_TIMER("Omnibox.PaintTime");
Textfield::OnPaint(canvas);
}
if ((hover_elide_or_unelide_animation_ &&
hover_elide_or_unelide_animation_->IsAnimating()) ||
(elide_after_web_contents_interaction_animation_ &&
elide_after_web_contents_interaction_animation_->IsAnimating())) {
SkColor bg_color = GetBackgroundColor();
// We can't use the SK_ColorTRANSPARENT constant here because for purposes
// of the gradient the R,G,B values of the transparent color do matter, and
// need to be identical to the background color (SK_ColorTRANSPARENT is a
// transparent black, and results in the gradient looking gray).
SkColor bg_transparent = SkColorSetARGB(
0, SkColorGetR(bg_color), SkColorGetG(bg_color), SkColorGetB(bg_color));
DrawGradientRect(elide_animation_smoothing_rect_left_, bg_color,
bg_transparent, canvas);
DrawGradientRect(elide_animation_smoothing_rect_right_, bg_transparent,
bg_color, canvas);
}
}
void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
// In the base class, touch text selection is deactivated when a command is
// executed. Since we are not always calling the base class implementation
// here, we need to deactivate touch text selection here, too.
DestroyTouchSelection();
switch (command_id) {
// These commands don't invoke the popup via OnBefore/AfterPossibleChange().
case IDC_PASTE_AND_GO:
model()->PasteAndGo(GetClipboardText(/*notify_if_restricted=*/true));
return;
case IDC_SHOW_FULL_URLS:
case IDC_EDIT_SEARCH_ENGINES:
location_bar_view_->command_updater()->ExecuteCommand(command_id);
return;
case IDC_SEND_TAB_TO_SELF_SINGLE_TARGET:
send_tab_to_self::ShareToSingleTarget(
location_bar_view_->GetWebContents());
send_tab_to_self::RecordSendTabToSelfClickResult(
send_tab_to_self::kOmniboxMenu, SendTabToSelfClickResult::kClickItem);
return;
// These commands do invoke the popup.
case Textfield::kPaste:
ExecuteTextEditCommand(ui::TextEditCommand::PASTE);
return;
default:
if (Textfield::IsCommandIdEnabled(command_id)) {
// The Textfield code will invoke OnBefore/AfterPossibleChange() itself
// as necessary.
Textfield::ExecuteCommand(command_id, event_flags);
return;
}
OnBeforePossibleChange();
location_bar_view_->command_updater()->ExecuteCommand(command_id);
OnAfterPossibleChange(true);
return;
}
}
ui::TextInputType OmniboxViewViews::GetTextInputType() const {
ui::TextInputType input_type = views::Textfield::GetTextInputType();
// We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
// triggers URL-specific layout in software keyboards, e.g. adding top-level
// "/" and ".com" keys for English. However, this also causes IMEs to default
// to Latin character mode, which makes entering search queries difficult for
// IME users. Therefore, we try to guess whether an IME will be used based on
// the input language, and set the input type accordingly.
#if defined(OS_WIN)
if (input_type != ui::TEXT_INPUT_TYPE_NONE && location_bar_view_) {
ui::InputMethod* input_method =
location_bar_view_->GetWidget()->GetInputMethod();
if (input_method && input_method->IsInputLocaleCJK())
return ui::TEXT_INPUT_TYPE_SEARCH;
}
#endif
return input_type;
}
void OmniboxViewViews::AddedToWidget() {
views::Textfield::AddedToWidget();
scoped_compositor_observation_.Observe(GetWidget()->GetCompositor());
}
void OmniboxViewViews::RemovedFromWidget() {
views::Textfield::RemovedFromWidget();
scoped_compositor_observation_.Reset();
}
OmniboxViewViews::ElideAnimation*
OmniboxViewViews::GetHoverElideOrUnelideAnimationForTesting() {
return hover_elide_or_unelide_animation_.get();
}
OmniboxViewViews::ElideAnimation*
OmniboxViewViews::GetElideAfterInteractionAnimationForTesting() {
return elide_after_web_contents_interaction_animation_.get();
}
void OmniboxViewViews::OnThemeChanged() {
views::Textfield::OnThemeChanged();
const SkColor dimmed_text_color = GetOmniboxColor(
GetThemeProvider(), OmniboxPart::LOCATION_BAR_TEXT_DIMMED);
set_placeholder_text_color(dimmed_text_color);
if (!model()->ShouldPreventElision() &&
OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover()) {
hover_elide_or_unelide_animation_ =
std::make_unique<ElideAnimation>(this, GetRenderText());
}
EmphasizeURLComponents();
}
bool OmniboxViewViews::IsDropCursorForInsertion() const {
// Dragging text from within omnibox itself will behave like text input
// editor, showing insertion-style drop cursor as usual;
// but dragging text from outside omnibox will replace entire contents with
// paste-and-go behavior, so returning false in that case prevents the
// confusing insertion-style drop cursor.
return HasTextBeingDragged();
}
void OmniboxViewViews::ApplyColor(SkColor color, const gfx::Range& range) {
Textfield::ApplyColor(color, range);
}
void OmniboxViewViews::SetTextAndSelectedRanges(
const std::u16string& text,
const std::vector<gfx::Range>& ranges) {
DCHECK(!ranges.empty());
// Will try to fit as much of the text preceding the cursor as possible. If
// possible, guarantees at least |kPadLeading| chars of the text preceding the
// the cursor are visible. If possible given the prior guarantee, also
// guarantees |kPadTrailing| chars of the text following the cursor are
// visible.
static const uint32_t kPadTrailing = 30;
static const uint32_t kPadLeading = 10;
// We use SetTextWithoutCaretBoundsChangeNotification() in order to avoid
// triggering accessibility events multiple times.
SetTextWithoutCaretBoundsChangeNotification(text, ranges[0].end());
Scroll({0, std::min<size_t>(ranges[0].end() + kPadTrailing, text.size()),
ranges[0].end() - std::min(kPadLeading, ranges[0].end())});
// Setting the primary selected range will also fire an appropriate final
// accessibility event after the changes above.
SetSelectedRanges(ranges);
// Clear the additional text.
SetAdditionalText(std::u16string());
}
void OmniboxViewViews::SetSelectedRanges(
const std::vector<gfx::Range>& ranges) {
// Even when no text is selected, |ranges| should have at least 1 (empty)
// Range representing the cursor.
DCHECK(!ranges.empty());
SetSelectedRange(ranges[0]);
for (size_t i = 1; i < ranges.size(); i++)
AddSecondarySelectedRange(ranges[i]);
}
std::u16string OmniboxViewViews::GetSelectedText() const {
// TODO(oshima): Support IME.
return views::Textfield::GetSelectedText();
}
void OmniboxViewViews::OnOmniboxPaste() {
const std::u16string text(GetClipboardText(/*notify_if_restricted=*/true));
if (text.empty() ||
// When the fakebox is focused, ignore pasted whitespace because if the
// fakebox is hidden and there's only whitespace in the omnibox, it's
// difficult for the user to see that the focus moved to the omnibox.
(model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE &&
std::all_of(text.begin(), text.end(), base::IsUnicodeWhitespace))) {
return;
}
OnBeforePossibleChange();
// Record this paste, so we can do different behavior.
model()->OnPaste();
// Force a Paste operation to trigger the text_changed code in
// OnAfterPossibleChange(), even if identical contents are pasted.
state_before_change_.text.clear();
InsertOrReplaceText(text);
OnAfterPossibleChange(true);
}
bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent& event) {
// This must run before accelerator handling invokes a focus change on tab.
// Note the parallel with SkipDefaultKeyEventProcessing above.
if (!views::FocusManager::IsTabTraversalKeyEvent(event))
return false;
if (!model()->popup_model()->IsOpen())
return false;
model()->popup_model()->StepSelection(event.IsShiftDown()
? OmniboxPopupModel::kBackward
: OmniboxPopupModel::kForward,
OmniboxPopupModel::kStateOrLine);
return true;
}
#if defined(OS_MAC)
void OmniboxViewViews::AnnounceFriendlySuggestionText() {
GetViewAccessibility().AnnounceText(friendly_suggestion_text_);
}
#endif
void OmniboxViewViews::SetWindowTextAndCaretPos(const std::u16string& text,
size_t caret_pos,
bool update_popup,
bool notify_text_changed) {
const gfx::Range range(caret_pos);
SetTextAndSelectedRanges(text, {range});
if (update_popup)
UpdatePopup();
if (notify_text_changed)
TextChanged();
}
void OmniboxViewViews::SetCaretPos(size_t caret_pos) {
SetSelectedRange(gfx::Range(caret_pos, caret_pos));
}
bool OmniboxViewViews::IsSelectAll() const {
// TODO(oshima): IME support.
return !GetText().empty() && GetText() == GetSelectedText();
}
void OmniboxViewViews::UpdatePopup() {
// Prevent inline autocomplete when the caret isn't at the end of the text.
const gfx::Range sel = GetSelectedRange();
model()->UpdateInput(!sel.is_empty(), !GetSelectionAtEnd());
}
void OmniboxViewViews::ApplyCaretVisibility() {
SetCursorEnabled(model()->is_caret_visible());
// TODO(tommycli): Because the LocationBarView has a somewhat different look
// depending on whether or not the caret is visible, we have to resend a
// "focused" notification. Remove this once we get rid of the concept of
// "invisible focus".
if (location_bar_view_)
location_bar_view_->OnOmniboxFocused();
}
void OmniboxViewViews::OnTemporaryTextMaybeChanged(
const std::u16string& display_text,
const AutocompleteMatch& match,
bool save_original_selection,
bool notify_text_changed) {
if (save_original_selection)
saved_temporary_selection_ = GetRenderText()->GetAllSelections();
// SetWindowTextAndCaretPos will fire the accessibility notification,
// so do not also generate redundant notification here.
SetAccessibilityLabel(display_text, match, false);
SetWindowTextAndCaretPos(display_text, display_text.length(), false,
notify_text_changed);
}
void OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
const std::u16string& display_text,
std::vector<gfx::Range> selections,
size_t user_text_length) {
if (display_text == GetText())
return;
if (!IsIMEComposing()) {
SetTextAndSelectedRanges(display_text, selections);
} else if (location_bar_view_) {
// TODO(manukh) IME should be updated with prefix and split rich
// autocompletion if those features launch. Likewise, remove
// |user_text_length| param if it can be computed.
location_bar_view_->SetImeInlineAutocompletion(
display_text.substr(user_text_length));
}
EmphasizeURLComponents();
}
void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
// Hide the inline autocompletion for IME users.
if (location_bar_view_)
location_bar_view_->SetImeInlineAutocompletion(std::u16string());
}
void OmniboxViewViews::OnRevertTemporaryText(const std::u16string& display_text,
const AutocompleteMatch& match) {
// We got here because the user hit the Escape key. We explicitly don't call
// TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
// been called by now, and it would've called TextChanged() if it was
// warranted.
// However, it's important to notify accessibility that the value has changed,
// otherwise the screen reader will use the old accessibility label text.
SetAccessibilityLabel(display_text, match, true);
SetSelectedRanges(saved_temporary_selection_);
}
void OmniboxViewViews::ClearAccessibilityLabel() {
if (friendly_suggestion_text_.empty())
return;
friendly_suggestion_text_.clear();
friendly_suggestion_text_prefix_length_ = 0;
NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true);
}
void OmniboxViewViews::SetAccessibilityLabel(const std::u16string& display_text,
const AutocompleteMatch& match,
bool notify_text_changed) {
if (model()->popup_model()->selected_line() == OmniboxPopupModel::kNoMatch) {
// If nothing is selected in the popup, we are in the no-default-match edge
// case, and |match| is a synthetically generated match. In that case,
// bypass OmniboxPopupModel and get the label from our synthetic |match|.
friendly_suggestion_text_ = AutocompleteMatchType::ToAccessibilityLabel(
match, display_text, OmniboxPopupModel::kNoMatch,
model()->result().size(), std::u16string(),
&friendly_suggestion_text_prefix_length_);
} else {
friendly_suggestion_text_ =
model()->popup_model()->GetAccessibilityLabelForCurrentSelection(
display_text, true, &friendly_suggestion_text_prefix_length_);
}
if (notify_text_changed)
NotifyAccessibilityEvent(ax::mojom::Event::kValueChanged, true);
#if defined(OS_MAC)
// On macOS, the only way to get VoiceOver to speak the friendly suggestion
// text (for example, "how to open a pdf, search suggestion, 4 of 8") is
// with an explicit announcement. Use PostTask to ensure that this
// announcement happens after the text change notification, otherwise
// the text change can interrupt the announcement.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&OmniboxViewViews::AnnounceFriendlySuggestionText,
weak_factory_.GetWeakPtr()));
#endif
}
bool OmniboxViewViews::UnapplySteadyStateElisions(UnelisionGesture gesture) {
// If everything is selected, the user likely does not intend to edit the URL.
// But if the Home key is pressed, the user probably does want to interact
// with the beginning of the URL - in which case we unelide.
if (IsSelectAll() && gesture != UnelisionGesture::HOME_KEY_PRESSED)
return false;
// Get the original selection bounds so we can adjust it later.
size_t start, end;
GetSelectionBounds(&start, &end);
// Try to unelide. Early exit if there's no unelisions to perform.
std::u16string original_text = GetText();
std::u16string original_selected_text = GetSelectedText();
if (!model()->Unelide())
return false;
// Find the length of the prefix that was chopped off to form the elided URL.
// This simple logic only works because we elide only prefixes from the full
// URL. Otherwise, we would have to use the FormatURL offset adjustments.
size_t offset = GetText().find(original_text);
// Some intranet URLs have an elided form that's not a substring of the full
// URL string. e.g. "https://foobar" has the elided form "foobar/". This is
// to prevent elided URLs from looking like search terms. See
// AutocompleteInput::FormattedStringWithEquivalentMeaning for details.
//
// In this special case, chop off the trailing slash and search again.
if (offset == std::u16string::npos && !original_text.empty() &&
original_text.back() == u'/') {
offset = GetText().find(original_text.substr(0, original_text.size() - 1));
}
if (offset != std::u16string::npos) {
AutocompleteMatch match;
model()->ClassifyString(original_selected_text, &match, nullptr);
bool selection_classifes_as_search =
AutocompleteMatch::IsSearchType(match.type);
if (start != end && gesture == UnelisionGesture::MOUSE_RELEASE &&
!selection_classifes_as_search) {
// For user selections that look like a URL instead of a Search:
// If we are uneliding at the end of a drag-select (on mouse release),
// and the selection spans to the beginning of the elided URL, ensure that
// the new selection spans to the beginning of the unelided URL too.
// i.e. google.com/maps => https://www.google.com/maps
// ^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
if (start != 0)
start += offset;
if (end != 0)
end += offset;
} else {
start += offset;
end += offset;
}
// Since we are changing the text in the double-click event handler, we
// need to fix the cached indices of the double-clicked word.
OffsetDoubleClickWord(offset);
}
SetSelectedRange(gfx::Range(start, end));
return true;
}
void OmniboxViewViews::OnBeforePossibleChange() {
// Record our state.
GetState(&state_before_change_);
ime_composing_before_change_ = IsIMEComposing();
// User is editing or traversing the text, as opposed to moving
// through suggestions. Clear the accessibility label
// so that the screen reader reports the raw text in the field.
ClearAccessibilityLabel();
}
bool OmniboxViewViews::OnAfterPossibleChange(bool allow_keyword_ui_change) {
// See if the text or selection have changed since OnBeforePossibleChange().
State new_state;
GetState(&new_state);
OmniboxView::StateChanges state_changes =
GetStateChanges(state_before_change_, new_state);
state_changes.text_differs =
state_changes.text_differs ||
(ime_composing_before_change_ != IsIMEComposing());
bool something_changed = model()->OnAfterPossibleChange(
state_changes, allow_keyword_ui_change && !IsIMEComposing());
// Unapply steady state elisions in response to selection changes due to
// keystroke, tap gesture, and caret placement. Ignore selection changes while
// the mouse is down, as we generally defer handling that until mouse release.
if (state_changes.selection_differs && !is_mouse_pressed_ &&
UnapplySteadyStateElisions(UnelisionGesture::OTHER)) {
something_changed = true;
state_changes.text_differs = true;
}
// If only selection was changed, we don't need to call model()'s
// OnChanged() method, which is called in TextChanged().
// But we still need to call EmphasizeURLComponents() to make sure the text
// attributes are updated correctly.
if (something_changed &&
(state_changes.text_differs || state_changes.keyword_differs))
TextChanged();
else if (state_changes.selection_differs)
EmphasizeURLComponents();
return something_changed;
}
gfx::NativeView OmniboxViewViews::GetNativeView() const {
return GetWidget()->GetNativeView();
}
gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
return GetWidget()->GetTopLevelWidget()->GetNativeView();
}
int OmniboxViewViews::GetWidth() const {
return location_bar_view_ ? location_bar_view_->width() : 0;
}
bool OmniboxViewViews::IsImeShowingPopup() const {
#if BUILDFLAG(IS_CHROMEOS_ASH)
return ime_candidate_window_open_;
#else
return GetInputMethod() ? GetInputMethod()->IsCandidatePopupOpen() : false;
#endif
}
void OmniboxViewViews::ShowVirtualKeyboardIfEnabled() {
if (auto* input_method = GetInputMethod())
input_method->ShowVirtualKeyboardIfEnabled();
}
void OmniboxViewViews::HideImeIfNeeded() {
if (auto* input_method = GetInputMethod()) {
if (auto* keyboard = input_method->GetVirtualKeyboardController())
keyboard->DismissVirtualKeyboard();
}
}
int OmniboxViewViews::GetOmniboxTextLength() const {
// TODO(oshima): Support IME.
return static_cast<int>(GetText().length());
}
void OmniboxViewViews::SetEmphasis(bool emphasize, const gfx::Range& range) {
SkColor color = GetOmniboxColor(
GetThemeProvider(), emphasize ? OmniboxPart::LOCATION_BAR_TEXT_DEFAULT
: OmniboxPart::LOCATION_BAR_TEXT_DIMMED);
if (range.IsValid())
ApplyColor(color, range);
else
SetColor(color);
}
void OmniboxViewViews::UpdateSchemeStyle(const gfx::Range& range) {
DCHECK(range.IsValid());
DCHECK(!model()->user_input_in_progress());
// Do not style the scheme for non-http/https URLs. For such schemes, styling
// could be confusing or misleading. For example, the scheme isn't meaningful
// in about:blank URLs. Or in blob: or filesystem: URLs, which have an inner
// origin, the URL is likely too syntax-y to be able to meaningfully draw
// attention to any part of it.
if (!controller()->GetLocationBarModel()->GetURL().SchemeIsHTTPOrHTTPS())
return;
security_state::SecurityLevel security_level =
controller()->GetLocationBarModel()->GetSecurityLevel();
// Only SECURE and DANGEROUS levels (pages served over HTTPS or flagged by
// SafeBrowsing) get a special scheme color treatment. If the security level
// is NONE or WARNING, we do not override the text style
// previously applied to the scheme text range by SetEmphasis().
if (security_level == security_state::NONE ||
security_level == security_state::WARNING)
return;
ApplyColor(location_bar_view_->GetSecurityChipColor(security_level), range);
if (security_level == security_state::DANGEROUS)
ApplyStyle(gfx::TEXT_STYLE_STRIKE, true, range);
}
void OmniboxViewViews::OnMouseMoved(const ui::MouseEvent& event) {
if (location_bar_view_)
location_bar_view_->OnOmniboxHovered(true);
if (model()->ShouldPreventElision())
return;
if (!GetURLEligibleForSimplifiedDomainEliding())
return;
if (hover_start_time_ == base::Time() &&
GetURLEligibleForSimplifiedDomainEliding()) {
hover_start_time_ = clock_->Now();
}
if (!OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover())
return;
if (elide_after_web_contents_interaction_animation_)
elide_after_web_contents_interaction_animation_->Stop();
// When the reveal-on-hover field trial is enabled, we elide the path and
// optionally subdomains of the URL. We bring back the URL when the user
// hovers over the omnibox, as is happening now. This is done via an animation
// that slides both ends of the URL into view while shifting the text so that
// the visible text is aligned with the leading edge of the display area. The
// reverse animation occurs when the mouse exits the omnibox area (in
// OnMouseExited()).
//
// The animation shouldn't begin immediately on hover to avoid the URL
// flickering in and out as the user passes over the omnibox on their way to
// e.g. the tab strip. Thus we pass a delay threshold (configurable via field
// trial) to ElideAnimation so that the unelision animation only begins after
// this delay.
if (hover_elide_or_unelide_animation_) {
// There might already be an unelide in progress. If it's animating to the
// same state as we're targeting, then we don't need to do anything.
gfx::Range unelide_bounds = gfx::Range(0, GetText().size());
if (hover_elide_or_unelide_animation_->IsAnimating() &&
hover_elide_or_unelide_animation_->GetElideToBounds() ==
unelide_bounds) {
return;
}
SkColor starting_color =
hover_elide_or_unelide_animation_->GetCurrentColor();
if (starting_color == gfx::kPlaceholderColor)
starting_color = SK_ColorTRANSPARENT;
hover_elide_or_unelide_animation_->Stop();
// Figure out where we are uneliding from so that the hover animation can
// fade in the surrounding text (|ranges_to_fade_in|). If the user has
// already interacted with the page, then we elided to the simplified domain
// and that is what we are uneliding from now. Otherwise, only the scheme
// and possibly a trivial subdomain have been elided and those components
// now need to be faded in.
std::vector<gfx::Range> ranges_to_fade_in;
// |minimum_visible_range| will contain either the simplified domain or the
// full hostname, depending on which is currently supposed to be showing. If
// |minimum_visible_range| does not currently fit in the omnibox bounds,
// then we don't do any hover animation. This is for simplicity, because
// ElideAnimation doesn't know how to position the text so that the most
// important part of the hostname is showing if it doesn't all fit.
// Furthermore, it doesn't seem necessary to do hover animation when the
// hostname doesn't fit because nothing is being elided beyond what has to
// be to fit in the local bounds.
gfx::Range minimum_visible_range;
if (elide_after_web_contents_interaction_animation_ ||
!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction()) {
// The URL has been elided to the simplified domain. We want to fade in
// everything surrounding the simplified domain.
minimum_visible_range = GetSimplifiedDomainBounds(&ranges_to_fade_in);
} else {
// The full URL is showing, except for the scheme and trivial subdomain.
// We want to fade in the scheme and trivial subdomain.
url::Component host = GetHostComponentAfterTrivialSubdomain();
ranges_to_fade_in.emplace_back(0, host.begin);
minimum_visible_range = gfx::Range(host.begin, host.end());
}
if (TextRangeOverflowsView(this, GetRenderText(), minimum_visible_range))
return;
hover_elide_or_unelide_animation_->Start(
unelide_bounds, OmniboxFieldTrial::UnelideURLOnHoverThresholdMs(),
ranges_to_fade_in, starting_color,
GetOmniboxColor(GetThemeProvider(),
OmniboxPart::LOCATION_BAR_TEXT_DIMMED));
}
}
void OmniboxViewViews::OnMouseExited(const ui::MouseEvent& event) {
if (location_bar_view_)
location_bar_view_->OnOmniboxHovered(false);
// A histogram records the duration that the user has hovered continuously
// over the omnibox without focusing it.
if (hover_start_time_ != base::Time() && !recorded_hover_on_focus_) {
UmaHistogramTimes("Omnibox.HoverTime", clock_->Now() - hover_start_time_);
}
hover_start_time_ = base::Time();
recorded_hover_on_focus_ = false;
if (!OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover() ||
model()->ShouldPreventElision()) {
return;
}
if (!GetURLEligibleForSimplifiedDomainEliding())
return;
// When the reveal-on-hover field trial is enabled, we bring the URL into view
// when the user hovers over the omnibox and elide back to simplified domain
// when their mouse exits the omnibox area. The elision animation is the
// reverse of the unelision animation: we shrink the URL from both sides while
// shifting the text to the leading edge.
DCHECK(hover_elide_or_unelide_animation_);
SkColor starting_color =
hover_elide_or_unelide_animation_->IsAnimating()
? hover_elide_or_unelide_animation_->GetCurrentColor()
: GetOmniboxColor(GetThemeProvider(),
OmniboxPart::LOCATION_BAR_TEXT_DIMMED);
hover_elide_or_unelide_animation_->Stop();
// Elisions don't take display offset into account (see
// https://crbug.com/1099078), so the RenderText must be in NO_ELIDE mode to
// avoid over-eliding when some of the text is not visible due to display
// offset.
GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
// Figure out where to elide to. If the user has already interacted with the
// page or reveal-on-interaction is disabled, then elide to the simplified
// domain; otherwise just hide the scheme and trivial subdomain (if any).
if (elide_after_web_contents_interaction_animation_ ||
!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction()) {
std::vector<gfx::Range> ranges_surrounding_simplified_domain;
gfx::Range simplified_domain =
GetSimplifiedDomainBounds(&ranges_surrounding_simplified_domain);
// If the simplified domain overflows the local bounds, then hover
// animations are disabled for simplicity.
if (TextRangeOverflowsView(this, GetRenderText(), simplified_domain))
return;
hover_elide_or_unelide_animation_->Start(
simplified_domain, 0 /* delay_ms */,
ranges_surrounding_simplified_domain, starting_color,
SK_ColorTRANSPARENT);
} else {
std::u16string text = GetText();
url::Component host = GetHostComponentAfterTrivialSubdomain();
// If the hostname overflows the local bounds, then hover animations are
// disabled for simplicity.
if (TextRangeOverflowsView(this, GetRenderText(),
gfx::Range(host.begin, host.end()))) {
return;
}
hover_elide_or_unelide_animation_->Start(
gfx::Range(host.begin, text.size()), 0 /* delay_ms */,
std::vector<gfx::Range>{gfx::Range(0, host.begin)}, starting_color,
SK_ColorTRANSPARENT);
}
}
bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
return command_id == IDC_PASTE_AND_GO;
}
std::u16string OmniboxViewViews::GetLabelForCommandId(int command_id) const {
DCHECK_EQ(IDC_PASTE_AND_GO, command_id);
// Don't paste-and-go data that was marked by its originator as confidential.
constexpr size_t kMaxSelectionTextLength = 50;
const std::u16string clipboard_text =
IsClipboardDataMarkedAsConfidential()
? std::u16string()
: GetClipboardText(/*notify_if_restricted=*/false);
if (clipboard_text.empty())
return l10n_util::GetStringUTF16(IDS_PASTE_AND_GO_EMPTY);
std::u16string selection_text = gfx::TruncateString(
clipboard_text, kMaxSelectionTextLength, gfx::WORD_BREAK);
AutocompleteMatch match;
model()->ClassifyString(clipboard_text, &match, nullptr);
if (AutocompleteMatch::IsSearchType(match.type))
return l10n_util::GetStringFUTF16(IDS_PASTE_AND_SEARCH, selection_text);
// To ensure the search and url strings began to truncate at the exact same
// number of characters, the pixel width at which the url begins to elide is
// derived from the truncated selection text. However, ideally there would be
// a better way to do this.
const float kMaxSelectionPixelWidth =
GetStringWidthF(selection_text, Textfield::GetFontList());
std::u16string url = url_formatter::ElideUrl(
match.destination_url, Textfield::GetFontList(), kMaxSelectionPixelWidth);
return l10n_util::GetStringFUTF16(IDS_PASTE_AND_GO, url);
}
bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) {
PermitExternalProtocolHandler();
// Clear focus of buttons, but do not clear keyword mode.
if (model()->popup_model() && model()->popup_model()->selected_line_state() !=
OmniboxPopupModel::KEYWORD_MODE) {
model()->popup_model()->SetSelectedLineState(OmniboxPopupModel::NORMAL);
}
is_mouse_pressed_ = true;
select_all_on_mouse_release_ =
(event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
(!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE));
if (select_all_on_mouse_release_) {
// Restore caret visibility whenever the user clicks in the omnibox in a way
// that would give it focus. We must handle this case separately here
// because if the omnibox currently has invisible focus, the mouse event
// won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
model()->SetCaretVisibility(true);
// When we're going to select all on mouse release, invalidate any saved
// selection lest restoring it fights with the "select all" action. It's
// possible to later set select_all_on_mouse_release_ back to false, but
// that happens for things like dragging, which are cases where having
// invalidated this saved selection is still OK.
saved_selection_for_focus_change_.clear();
}
// Show on-focus suggestions if either:
// - The textfield doesn't already have focus.
// - Or if the textfield is empty, to cover the NTP ZeroSuggest case.
if (event.IsOnlyLeftMouseButton() && (!HasFocus() || GetText().empty()))
model()->StartZeroSuggestRequest();
bool handled = views::Textfield::OnMousePressed(event);
// Reset next double click length
if (event.GetClickCount() == 1)
next_double_click_selection_len_ = 0;
if (!select_all_on_mouse_release_) {
if (UnapplySteadyStateElisions(UnelisionGesture::OTHER)) {
// This ensures that when the user makes a double-click partial select, we
// perform the unelision at the same time as we make the partial
// selection, which is on mousedown.
TextChanged();
filter_drag_events_for_unelision_ = true;
} else if (event.GetClickCount() == 1 && event.IsLeftMouseButton()) {
// Select the current word and record it for later. This is done to handle
// an edge case where the wrong word is selected on a double click when
// the elided URL is selected prior to the dobule click. Unelision happens
// between the first and second click, causing the wrong word to be
// selected because it's based on the click position in the newly unelided
// URL. See https://crbug.com/1084406.
if (IsSelectAll()) {
SelectWordAt(event.location());
std::u16string shown_url = GetText();
std::u16string full_url =
controller()->GetLocationBarModel()->GetFormattedFullURL();
size_t offset = full_url.find(shown_url);
if (offset != std::u16string::npos) {
next_double_click_selection_len_ = GetSelectedText().length();
next_double_click_selection_offset_ =
offset + GetCursorPosition() - next_double_click_selection_len_;
}
// Reset selection
// Select all in the reverse direction so as not to scroll the caret
// into view and shift the contents jarringly.
SelectAll(true);
}
} else if (event.GetClickCount() == 2 && event.IsLeftMouseButton()) {
// If the user double clicked and we unelided between the first and second
// click, offset double click.
if (next_double_click_selection_len_ != 0) {
SetSelectedRange(gfx::Range(next_double_click_selection_offset_,
next_double_click_selection_offset_ +
next_double_click_selection_len_));
}
}
}
return handled;
}
bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) {
if (filter_drag_events_for_unelision_ &&
!ExceededDragThreshold(event.root_location() -
GetLastClickRootLocation())) {
return true;
}
if (HasTextBeingDragged())
CloseOmniboxPopup();
bool handled = views::Textfield::OnMouseDragged(event);
if (HasSelection() || ExceededDragThreshold(event.root_location() -
GetLastClickRootLocation())) {
select_all_on_mouse_release_ = false;
}
return handled;
}
void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) {
PermitExternalProtocolHandler();
views::Textfield::OnMouseReleased(event);
// When the user has clicked and released to give us focus, select all.
if ((event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
select_all_on_mouse_release_) {
// Select all in the reverse direction so as not to scroll the caret
// into view and shift the contents jarringly.
SelectAll(true);
}
select_all_on_mouse_release_ = false;
is_mouse_pressed_ = false;
filter_drag_events_for_unelision_ = false;
// Make an unelision check on mouse release. This handles the drag selection
// case, in which we defer uneliding until mouse release.
if (UnapplySteadyStateElisions(UnelisionGesture::MOUSE_RELEASE))
TextChanged();
}
void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) {
PermitExternalProtocolHandler();
static const bool kTakeFocusOnTapUp =
base::FeatureList::IsEnabled(views::features::kTextfieldFocusOnTapUp);
const bool gesture_should_take_focus =
!HasFocus() &&
event->type() ==
(kTakeFocusOnTapUp ? ui::ET_GESTURE_TAP : ui::ET_GESTURE_TAP_DOWN);
if (gesture_should_take_focus) {
select_all_on_gesture_tap_ = true;
// If we're trying to select all on tap, invalidate any saved selection lest
// restoring it fights with the "select all" action.
saved_selection_for_focus_change_.clear();
}
// Show on-focus suggestions if either:
// - The textfield is taking focus.
// - The textfield is focused but empty, to cover the NTP ZeroSuggest case.
if (gesture_should_take_focus || (HasFocus() && GetText().empty()))
model()->StartZeroSuggestRequest();
views::Textfield::OnGestureEvent(event);
if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP) {
// Select all in the reverse direction so as not to scroll the caret
// into view and shift the contents jarringly.
SelectAll(true);
}
if (event->type() == ui::ET_GESTURE_TAP ||
event->type() == ui::ET_GESTURE_TAP_CANCEL ||
event->type() == ui::ET_GESTURE_TWO_FINGER_TAP ||
event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
event->type() == ui::ET_GESTURE_LONG_PRESS ||
event->type() == ui::ET_GESTURE_LONG_TAP) {
select_all_on_gesture_tap_ = false;
}
}
void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse) {
views::Textfield::AboutToRequestFocusFromTabTraversal(reverse);
}
bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
const ui::KeyEvent& event) {
if (views::FocusManager::IsTabTraversalKeyEvent(event) &&
((model()->is_keyword_hint() && !event.IsShiftDown()) ||
model()->popup_model()->IsOpen())) {
return true;
}
if (event.key_code() == ui::VKEY_ESCAPE)
return model()->WillHandleEscapeKey();
return Textfield::SkipDefaultKeyEventProcessing(event);
}
void OmniboxViewViews::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kTextField;
node_data->SetName(l10n_util::GetStringUTF8(IDS_ACCNAME_LOCATION));
node_data->AddStringAttribute(ax::mojom::StringAttribute::kAutoComplete,
"both");
// Expose keyboard shortcut where it makes sense.
#if defined(OS_MAC)
// Use cloverleaf symbol for command key.
node_data->AddStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts,
base::WideToUTF8(L"\u2318L"));
#else
node_data->AddStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts,
"Ctrl+L");
#endif
if (friendly_suggestion_text_.empty()) {
// While user edits text, use the exact text displayed in the omnibox.
node_data->SetValue(GetText());
} else {
// While user navigates omnibox suggestions, use the current editable
// text decorated with additional friendly labelling text, such as the
// title of the page and the type of autocomplete, for example:
// "Google https://google.com location from history".
// The edited text is always a substring of the friendly label, so that
// users can navigate to specific characters in the friendly version using
// Braille display routing keys or other assistive technologies.
node_data->SetValue(friendly_suggestion_text_);
}
node_data->html_attributes.push_back(std::make_pair("type", "url"));
// Establish a "CONTROLS" relationship between the omnibox and the
// the popup. This allows a screen reader to understand the relationship
// between the omnibox and the list of suggestions, and determine which
// suggestion is currently selected, even though focus remains here on
// the omnibox.
if (model()->popup_model()->IsOpen()) {
int32_t popup_view_id =
popup_view_->GetViewAccessibility().GetUniqueId().Get();
node_data->AddIntListAttribute(ax::mojom::IntListAttribute::kControlsIds,
{popup_view_id});
OmniboxResultView* selected_result_view =
popup_view_->GetSelectedResultView();
if (selected_result_view) {
node_data->AddIntAttribute(
ax::mojom::IntAttribute::kActivedescendantId,
selected_result_view->GetViewAccessibility().GetUniqueId().Get());
}
}
std::u16string::size_type entry_start;
std::u16string::size_type entry_end;
// Selection information is saved separately when focus is moved off the
// current window - use that when there is no focus and it's valid.
if (!saved_selection_for_focus_change_.empty()) {
entry_start = saved_selection_for_focus_change_[0].start();
entry_end = saved_selection_for_focus_change_[0].end();
} else {
GetSelectionBounds(&entry_start, &entry_end);
}
node_data->AddIntAttribute(
ax::mojom::IntAttribute::kTextSelStart,
entry_start + friendly_suggestion_text_prefix_length_);
node_data->AddIntAttribute(
ax::mojom::IntAttribute::kTextSelEnd,
entry_end + friendly_suggestion_text_prefix_length_);
if (popup_window_mode_) {
node_data->SetRestriction(ax::mojom::Restriction::kReadOnly);
} else {
node_data->AddState(ax::mojom::State::kEditable);
}
}
bool OmniboxViewViews::HandleAccessibleAction(
const ui::AXActionData& action_data) {
if (GetReadOnly())
return Textfield::HandleAccessibleAction(action_data);
if (action_data.action == ax::mojom::Action::kSetValue) {
SetUserText(base::UTF8ToUTF16(action_data.value), true);
return true;
} else if (action_data.action == ax::mojom::Action::kReplaceSelectedText) {
model()->SetInputInProgress(true);
if (!saved_selection_for_focus_change_.empty()) {
SetSelectedRanges(saved_selection_for_focus_change_);
saved_selection_for_focus_change_.clear();
}
InsertOrReplaceText(base::UTF8ToUTF16(action_data.value));
TextChanged();
return true;
} else if (action_data.action == ax::mojom::Action::kSetSelection) {
// Adjust for friendly text inserted at the start of the url.
ui::AXActionData set_selection_action_data;
set_selection_action_data.action = ax::mojom::Action::kSetSelection;
set_selection_action_data.anchor_node_id = action_data.anchor_node_id;
set_selection_action_data.focus_node_id = action_data.focus_node_id;
set_selection_action_data.focus_offset =
action_data.focus_offset - friendly_suggestion_text_prefix_length_;
set_selection_action_data.anchor_offset =
action_data.anchor_offset - friendly_suggestion_text_prefix_length_;
return Textfield::HandleAccessibleAction(set_selection_action_data);
}
return Textfield::HandleAccessibleAction(action_data);
}
void OmniboxViewViews::OnBoundsChanged(const gfx::Rect& previous_bounds) {
Textfield::OnBoundsChanged(previous_bounds);
if (!OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover() &&
!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction()) {
return;
}
// When simplified domain display field trials are enabled,
// Textfield::OnBoundsChanged() may have undone the effect of any previous URL
// elisions, because it expands the Textfield's display rect to the local
// bounds, which may bring more of the URL into view than intended. Re-apply
// simplified domain elisions now.
// Cancel any running animations. This could cause some abrupt transitions,
// but we can't adapt running animations to new bounds.
if (hover_elide_or_unelide_animation_)
hover_elide_or_unelide_animation_->Stop();
if (elide_after_web_contents_interaction_animation_)
elide_after_web_contents_interaction_animation_->Stop();
// |elide_after_web_contents_interaction_animation_| is created when the user
// interacts with the page, if hide-on-interaction is enabled. If
// hide-on-interaction is disabled or the user has already interacted with the
// page, the simplified domain should have been showing before the bounds
// changed (or we would have been in the process of animating to the
// simplified domain).
if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
elide_after_web_contents_interaction_animation_) {
if (GetURLEligibleForSimplifiedDomainEliding() &&
!model()->ShouldPreventElision()) {
ElideURL();
}
} else {
// The user hasn't interacted with the page yet. This resets animation state
// and shows the partially elided URL with scheme and trivial subdomains
// hidden.
ResetToHideOnInteraction();
}
}
void OmniboxViewViews::OnFocus() {
views::Textfield::OnFocus();
// A histogram records the duration that the user has hovered continuously
// over the omnibox without focusing it.
if (hover_start_time_ != base::Time() && !recorded_hover_on_focus_) {
recorded_hover_on_focus_ = true;
UmaHistogramTimes("Omnibox.HoverTime", clock_->Now() - hover_start_time_);
}
// TODO(tommycli): This does not seem like it should be necessary.
// Investigate why it's needed and see if we can remove it.
model()->ResetDisplayTexts();
// TODO(oshima): Get control key state.
model()->OnSetFocus(false);
// Don't call controller()->OnSetFocus, this view has already acquired focus.
// Restore the selection we saved in OnBlur() if it's still valid.
if (!saved_selection_for_focus_change_.empty()) {
SetSelectedRanges(saved_selection_for_focus_change_);
saved_selection_for_focus_change_.clear();
}
ShowFullURL();
GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
// Focus changes can affect the visibility of any keyword hint.
if (location_bar_view_ && model()->is_keyword_hint())
location_bar_view_->Layout();
if (location_bar_view_)
location_bar_view_->OnOmniboxFocused();
}
void OmniboxViewViews::OnBlur() {
// Save the user's existing selection to restore it later.
saved_selection_for_focus_change_ = GetRenderText()->GetAllSelections();
// popup_model() can be null in tests.
OmniboxPopupModel* popup_model = model()->popup_model();
// If the view is showing text that's not user-text, revert the text to the
// permanent display text. This usually occurs if Steady State Elisions is on
// and the user has unelided, but not edited the URL.
//
// Because merely Alt-Tabbing to another window and back should not change the
// Omnibox state, we only revert the text only if the Omnibox is blurred in
// favor of some other View in the same Widget.
//
// Also revert if the text has been edited but currently exactly matches
// the permanent text. An example of this scenario is someone typing on the
// new tab page and then deleting everything using backspace/delete.
//
// This should never exit keyword mode.
if (GetWidget() && GetWidget()->IsActive() &&
!model()->is_keyword_selected() &&
((!model()->user_input_in_progress() &&
GetText() != model()->GetPermanentDisplayText()) ||
(model()->user_input_in_progress() &&
GetText() == model()->GetPermanentDisplayText()))) {
RevertAll();
}
views::Textfield::OnBlur();
model()->OnWillKillFocus();
// If ZeroSuggest is active, and there is evidence that there is a text
// update to show, revert to ensure that update is shown now. Otherwise,
// at least call CloseOmniboxPopup(), so that if ZeroSuggest is in the
// midst of running but hasn't yet opened the popup, it will be halted.
// If we fully reverted in this case, we'd lose the cursor/highlight
// information saved above.
if (!model()->user_input_in_progress() && popup_model &&
popup_model->IsOpen() &&
GetText() != model()->GetPermanentDisplayText()) {
RevertAll();
} else {
CloseOmniboxPopup();
}
// Tell the model to reset itself.
model()->OnKillFocus();
// Deselect the text. Ensures the cursor is an I-beam.
SetSelectedRange(gfx::Range(0));
// When deselected, elide and reset scroll position. After eliding, the old
// scroll offset is meaningless (since the string is guaranteed to fit within
// the view). The scroll must be reset or the text may be rendered partly or
// wholly off-screen.
//
// Important: Since the URL can contain bidirectional text, it is important to
// set the display offset directly to 0 (not simply scroll to the start of the
// text, since the start of the text may not be at the left edge).
gfx::RenderText* render_text = GetRenderText();
render_text->SetElideBehavior(gfx::ELIDE_TAIL);
// In cases where there's a lot of whitespace in the text being shown, we want
// the elision marker to be at the right of the text field, so don't elide
// whitespace to the left of the elision point.
render_text->SetWhitespaceElision(false);
render_text->SetDisplayOffset(0);
// Focus changes can affect the visibility of any keyword hint.
// |location_bar_view_| can be null in tests.
if (location_bar_view_) {
if (model()->is_keyword_hint())
location_bar_view_->Layout();
location_bar_view_->OnOmniboxBlurred();
// The location bar needs to repaint without a focus ring.
location_bar_view_->SchedulePaint();
}
ClearAccessibilityLabel();
// When the relevant field trial is enabled, reset state so that the URL will
// be elided/unelided on next user interaction or hover.
if (!model()->ShouldPreventElision()) {
if (OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover() &&
!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction()) {
// When reveal-on-hover is enabled but not hide-on-interaction, blur
// should unfocus the omnibox and return to the same state as on page
// load: the URL is elided to a simplified domain until the user hovers
// over the omnibox. There's no need to animate in this case because the
// omnibox's appearance already changes quite dramatically on blur
// (selection clearer, other URL transformations, etc.), so there's no
// need to make this change gradual.
hover_elide_or_unelide_animation_ =
std::make_unique<OmniboxViewViews::ElideAnimation>(this,
GetRenderText());
if (GetURLEligibleForSimplifiedDomainEliding()) {
ElideURL();
} else {
// If the text isn't eligible to be elided to a simplified domain, then
// ensure that as much of it is visible as will fit.
FitToLocalBounds();
}
} else if (OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction()) {
// When hide-on-interaction is enabled, this method ensures that, once the
// omnibox is blurred, the URL is visible and that the animation state is
// set so that the URL will be animated to the simplified domain the
// next time the user interacts with the page.
ResetToHideOnInteraction();
}
}
}
bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
if (command_id == Textfield::kPaste)
return !GetReadOnly() &&
!GetClipboardText(/*notify_if_restricted=*/false).empty();
if (command_id == IDC_PASTE_AND_GO) {
return !GetReadOnly() && !IsClipboardDataMarkedAsConfidential() &&
model()->CanPasteAndGo(
GetClipboardText(/*notify_if_restricted=*/false));
}
// Menu item is only shown when it is valid.
if (command_id == IDC_SHOW_FULL_URLS)
return true;
return Textfield::IsCommandIdEnabled(command_id) ||
location_bar_view_->command_updater()->IsCommandEnabled(command_id);
}
void OmniboxViewViews::DidStartNavigation(
content::NavigationHandle* navigation) {
if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
model()->ShouldPreventElision()) {
return;
}
// If navigating to a different page in a browser-initiated navigation, the
// new URL should be shown unelided while the navigation is in progress. For
// renderer-initiated navigations, the URL isn't displayed until the
// navigation commits, so there's no need to elide/unelide it now.
if (navigation->IsInMainFrame() && !navigation->IsSameDocument() &&
!navigation->IsRendererInitiated()) {
ResetToHideOnInteraction();
}
}
void OmniboxViewViews::DidFinishNavigation(
content::NavigationHandle* navigation) {
if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
model()->ShouldPreventElision()) {
return;
}
// Non-main-frame navigations don't change the visible URL, so no action is
// necessary for simplified domain elisions.
if (!navigation->IsInMainFrame())
return;
// If the navigation didn't commit, and it was renderer-initiated, then no
// action is needed, as the URL won't have been updated. But if it was
// browser-initiated, then the URL would have been updated to show the URL of
// the in-progress navigation; in this case, reset to show the full URL now
// that the navigation has finished without committing.
if (!navigation->HasCommitted()) {
if (navigation->IsRendererInitiated()) {
return;
}
ResetToHideOnInteraction();
return;
}
// Once a navigation finishes that changes the visible URL (besides just the
// ref), unelide and reset state so that we'll show the simplified domain on
// interaction. Same-document navigations that only change the ref are treated
// specially and don't cause the elision/unelision state to be altered. This
// is to avoid frequent eliding/uneliding within single-page apps that do
// frequent fragment navigations.
if (navigation->IsErrorPage() || !navigation->IsSameDocument() ||
!navigation->GetPreviousMainFrameURL().EqualsIgnoringRef(
navigation->GetURL())) {
ResetToHideOnInteraction();
}
}
void OmniboxViewViews::DidGetUserInteraction(
const blink::WebInputEvent& event) {
// Exclude mouse clicks from triggering the simplified domain elision. Mouse
// clicks can be done idly and aren't a good signal of real intent to interact
// with the page. Plus, it can be jarring when the URL elides when the user
// clicks on a link only to immediately come back as the navigation occurs.
if (blink::WebInputEvent::IsMouseEventType(event.GetType()))
return;
// Exclude modifier keys to prevent keyboard shortcuts (such as switching
// tabs) from eliding the URL. We don't want to count these shortcuts as
// interactions with the page content.
if (blink::WebInputEvent::IsKeyboardEventType(event.GetType()) &&
event.GetModifiers() & blink::WebInputEvent::kKeyModifiers) {
return;
}
MaybeElideURLWithAnimationFromInteraction();
}
void OmniboxViewViews::OnFocusChangedInPage(
content::FocusedNodeDetails* details) {
// Elide the URL to the simplified domain (the most security-critical
// information) when the user focuses a form text field, which is a key moment
// for making security decisions. Ignore the focus event if it didn't come
// from a mouse click/tap. Focus via keyboard will trigger elision from
// DidGetUserInteraction(), and we want to ignore focuses that aren't from an
// explicit user action (e.g., input fields that are autofocused on page
// load).
if (details->is_editable_node &&
details->focus_type == blink::mojom::FocusType::kMouse) {
MaybeElideURLWithAnimationFromInteraction();
}
}
std::u16string OmniboxViewViews::GetSelectionClipboardText() const {
return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
}
void OmniboxViewViews::DoInsertChar(char16_t ch) {
// When the fakebox is focused, ignore whitespace input because if the
// fakebox is hidden and there's only whitespace in the omnibox, it's
// difficult for the user to see that the focus moved to the omnibox.
if ((model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE) &&
base::IsUnicodeWhitespace(ch)) {
return;
}
// If |insert_char_time_| is not null, there's a pending insert char operation
// that hasn't been painted yet. Keep the earlier time.
if (insert_char_time_.is_null()) {
DCHECK_EQ(latency_histogram_state_, NOT_ACTIVE);
latency_histogram_state_ = CHAR_TYPED;
insert_char_time_ = base::TimeTicks::Now();
}
Textfield::DoInsertChar(ch);
}
bool OmniboxViewViews::IsTextEditCommandEnabled(
ui::TextEditCommand command) const {
switch (command) {
case ui::TextEditCommand::MOVE_UP:
case ui::TextEditCommand::MOVE_DOWN:
return !GetReadOnly();
case ui::TextEditCommand::PASTE:
return !GetReadOnly() &&
!GetClipboardText(show_rejection_ui_if_any_).empty();
default:
return Textfield::IsTextEditCommandEnabled(command);
}
}
void OmniboxViewViews::ExecuteTextEditCommand(ui::TextEditCommand command) {
// In the base class, touch text selection is deactivated when a command is
// executed. Since we are not always calling the base class implementation
// here, we need to deactivate touch text selection here, too.
DestroyTouchSelection();
base::AutoReset<bool> show_rejection_ui(&show_rejection_ui_if_any_, true);
if (!IsTextEditCommandEnabled(command))
return;
switch (command) {
case ui::TextEditCommand::MOVE_UP:
model()->OnUpOrDownKeyPressed(-1);
break;
case ui::TextEditCommand::MOVE_DOWN:
model()->OnUpOrDownKeyPressed(1);
break;
case ui::TextEditCommand::PASTE:
OnOmniboxPaste();
break;
default:
Textfield::ExecuteTextEditCommand(command);
break;
}
}
bool OmniboxViewViews::ShouldShowPlaceholderText() const {
return Textfield::ShouldShowPlaceholderText() &&
!model()->is_caret_visible() && !model()->is_keyword_selected();
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
void OmniboxViewViews::CandidateWindowOpened(
chromeos::input_method::InputMethodManager* manager) {
ime_candidate_window_open_ = true;
}
void OmniboxViewViews::CandidateWindowClosed(
chromeos::input_method::InputMethodManager* manager) {
ime_candidate_window_open_ = false;
}
#endif
void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
const std::u16string& new_contents) {}
bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
const ui::KeyEvent& event) {
PermitExternalProtocolHandler();
if (event.type() == ui::ET_KEY_RELEASED) {
// The omnibox contents may change while the control key is pressed.
if (event.key_code() == ui::VKEY_CONTROL)
model()->OnControlKeyChanged(false);
return false;
}
// Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
// Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
if (event.IsUnicodeKeyCode())
return false;
// Show a notification if the clipboard is restricted by the rules of the
// data leak prevention policy. This state is used by the
// IsTextEditCommandEnabled(ui::TextEditCommand::PASTE) cases below.
base::AutoReset<bool> show_rejection_ui(&show_rejection_ui_if_any_, true);
const bool shift = event.IsShiftDown();
const bool control = event.IsControlDown();
const bool alt = event.IsAltDown() || event.IsAltGrDown();
const bool command = event.IsCommandDown();
switch (event.key_code()) {
case ui::VKEY_RETURN: {
OmniboxPopupModel* popup_model = model()->popup_model();
if (popup_model && popup_model->TriggerSelectionAction(
popup_model->selection(), event.time_stamp())) {
return true;
} else if ((alt && !shift) || (shift && command)) {
model()->AcceptInput(WindowOpenDisposition::NEW_FOREGROUND_TAB,
event.time_stamp());
} else if (alt || command) {
model()->AcceptInput(WindowOpenDisposition::NEW_BACKGROUND_TAB,
event.time_stamp());
} else if (shift) {
model()->AcceptInput(WindowOpenDisposition::NEW_WINDOW,
event.time_stamp());
} else {
model()->AcceptInput(WindowOpenDisposition::CURRENT_TAB,
event.time_stamp());
}
return true;
}
case ui::VKEY_ESCAPE:
return model()->OnEscapeKeyPressed();
case ui::VKEY_CONTROL:
model()->OnControlKeyChanged(true);
break;
case ui::VKEY_DELETE:
if (shift && model()->popup_model()->IsOpen()) {
model()->popup_model()->TryDeletingLine(
model()->popup_model()->selected_line());
}
break;
case ui::VKEY_UP:
// Shift-up is handled by the text field class to enable text selection.
if (shift)
return false;
if (IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_UP)) {
ExecuteTextEditCommand(ui::TextEditCommand::MOVE_UP);
return true;
}
break;
case ui::VKEY_DOWN:
// Shift-down is handled by the text field class to enable text selection.
if (shift)
return false;
if (IsTextEditCommandEnabled(ui::TextEditCommand::MOVE_DOWN)) {
ExecuteTextEditCommand(ui::TextEditCommand::MOVE_DOWN);
return true;
}
break;
case ui::VKEY_PRIOR:
if (control || alt || shift || GetReadOnly())
return false;
if (!model()->MaybeStartQueryForPopup()) {
model()->popup_model()->StepSelection(OmniboxPopupModel::kBackward,
OmniboxPopupModel::kAllLines);
}
return true;
case ui::VKEY_NEXT:
if (control || alt || shift || GetReadOnly())
return false;
if (!model()->MaybeStartQueryForPopup()) {
model()->popup_model()->StepSelection(OmniboxPopupModel::kForward,
OmniboxPopupModel::kAllLines);
}
return true;
case ui::VKEY_V:
if (control && !alt &&
IsTextEditCommandEnabled(ui::TextEditCommand::PASTE)) {
ExecuteTextEditCommand(ui::TextEditCommand::PASTE);
return true;
}
break;
case ui::VKEY_INSERT:
if (shift && !control &&
IsTextEditCommandEnabled(ui::TextEditCommand::PASTE)) {
ExecuteTextEditCommand(ui::TextEditCommand::PASTE);
return true;
}
break;
case ui::VKEY_BACK:
// No extra handling is needed in keyword search mode, if there is a
// non-empty selection, or if the cursor is not leading the text.
if (model()->is_keyword_hint() || model()->keyword().empty() ||
HasSelection() || GetCursorPosition() != 0)
return false;
model()->ClearKeyword();
return true;
case ui::VKEY_HOME:
// The Home key indicates that the user wants to move the cursor to the
// beginning of the full URL, so it should always trigger an unelide.
if (UnapplySteadyStateElisions(UnelisionGesture::HOME_KEY_PRESSED)) {
if (shift) {
// After uneliding, we need to move the end of the selection range
// to the beginning of the full unelided URL.
size_t start, end;
GetSelectionBounds(&start, &end);
SetSelectedRange(gfx::Range(start, 0));
} else {
// After uneliding, move the caret to the beginning of the full
// unelided URL.
SetCaretPos(0);
}
TextChanged();
return true;
}
break;
case ui::VKEY_SPACE: {
OmniboxPopupModel* popup_model = model()->popup_model();
if (popup_model && !control && !alt && !shift &&
popup_model->selection().IsButtonFocused()) {
if (popup_model->TriggerSelectionAction(popup_model->selection(),
event.time_stamp())) {
return true;
}
}
break;
}
default:
break;
}
if (is_mouse_pressed_ && select_all_on_mouse_release_) {
// https://crbug.com/1063161 If the user presses the mouse button down and
// begins to type without releasing the mouse button, the subsequent release
// will delete any newly typed characters due to the SelectAll happening on
// mouse-up. If we detect this state, do the select-all immediately.
SelectAll(true);
select_all_on_mouse_release_ = false;
}
return HandleEarlyTabActions(event);
}
void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
OnBeforePossibleChange();
}
void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
OnAfterPossibleChange(true);
}
void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardBuffer clipboard_buffer) {
ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
std::u16string selected_text;
ui::DataTransferEndpoint data_dst = ui::DataTransferEndpoint(
ui::EndpointType::kDefault, /*notify_if_restricted=*/false);
cb->ReadText(clipboard_buffer, &data_dst, &selected_text);
GURL url;
bool write_url = false;
model()->AdjustTextForCopy(GetSelectedRange().GetMin(), &selected_text, &url,
&write_url);
if (IsSelectAll()) {
UMA_HISTOGRAM_COUNTS_1M(OmniboxEditModel::kCutOrCopyAllTextHistogram, 1);
if (clipboard_buffer != ui::ClipboardBuffer::kSelection &&
location_bar_view_) {
auto* web_contents = location_bar_view_->GetWebContents();
if (web_contents) {
if (auto* clusters_helper =
HistoryClustersTabHelper::FromWebContents(web_contents)) {
clusters_helper->OnOmniboxUrlCopied();
}
}
}
}
ui::ScopedClipboardWriter scoped_clipboard_writer(clipboard_buffer);
scoped_clipboard_writer.WriteText(selected_text);
// Regardless of |write_url|, don't write a hyperlink to the clipboard.
// Plaintext URLs are simply handled more consistently than hyperlinks.
}
void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
GURL url;
bool write_url;
std::u16string selected_text = GetSelectedText();
model()->AdjustTextForCopy(GetSelectedRange().GetMin(), &selected_text, &url,
&write_url);
data->SetString(selected_text);
if (write_url) {
gfx::Image favicon;
std::u16string title = selected_text;
if (IsSelectAll())
model()->GetDataForURLExport(&url, &title, &favicon);
button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
nullptr, *GetWidget(), data);
data->SetURL(url, title);
}
}
void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
std::u16string selected_text = GetSelectedText();
GURL url;
bool write_url;
model()->AdjustTextForCopy(GetSelectedRange().GetMin(), &selected_text, &url,
&write_url);
if (write_url)
*drag_operations |= ui::DragDropTypes::DRAG_LINK;
}
void OmniboxViewViews::AppendDropFormats(
int* formats,
std::set<ui::ClipboardFormatType>* format_types) {
*formats = *formats | ui::OSExchangeData::URL;
}
DragOperation OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
if (HasTextBeingDragged())
return DragOperation::kNone;
std::u16string text;
if (data.HasURL(ui::FilenameToURLPolicy::CONVERT_FILENAMES)) {
GURL url;
std::u16string title;
if (data.GetURLAndTitle(ui::FilenameToURLPolicy::CONVERT_FILENAMES, &url,
&title)) {
text = StripJavascriptSchemas(base::UTF8ToUTF16(url.spec()));
}
} else if (data.HasString() && data.GetString(&text)) {
text = StripJavascriptSchemas(base::CollapseWhitespace(text, true));
} else {
return DragOperation::kNone;
}
SetUserText(text);
if (!HasFocus())
RequestFocus();
SelectAll(false);
return DragOperation::kCopy;
}
void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
// Only add this menu entry if SendTabToSelf feature is enabled.
if (send_tab_to_self::ShouldOfferFeature(
location_bar_view_->GetWebContents())) {
int index = menu_contents->GetIndexOfCommandId(Textfield::kUndo);
// Add a separator if this is not the first item.
if (index)
menu_contents->InsertSeparatorAt(index++, ui::NORMAL_SEPARATOR);
if (send_tab_to_self::GetValidDeviceCount(location_bar_view_->profile()) ==
1) {
menu_contents->InsertItemAt(
index, IDC_SEND_TAB_TO_SELF_SINGLE_TARGET,
l10n_util::GetStringFUTF16(
IDS_CONTEXT_MENU_SEND_TAB_TO_SELF_SINGLE_TARGET,
send_tab_to_self::GetSingleTargetDeviceName(
location_bar_view_->profile())));
} else {
send_tab_to_self_sub_menu_model_ =
std::make_unique<send_tab_to_self::SendTabToSelfSubMenuModel>(
location_bar_view_->GetWebContents(),
send_tab_to_self::SendTabToSelfMenuType::kOmnibox);
menu_contents->InsertSubMenuWithStringIdAt(
index, IDC_SEND_TAB_TO_SELF, IDS_CONTEXT_MENU_SEND_TAB_TO_SELF,
send_tab_to_self_sub_menu_model_.get());
}
#if !defined(OS_MAC)
menu_contents->SetIcon(index,
ui::ImageModel::FromVectorIcon(kSendTabToSelfIcon));
#endif
menu_contents->InsertSeparatorAt(++index, ui::NORMAL_SEPARATOR);
}
int paste_position = menu_contents->GetIndexOfCommandId(Textfield::kPaste);
DCHECK_GE(paste_position, 0);
menu_contents->InsertItemWithStringIdAt(paste_position + 1, IDC_PASTE_AND_GO,
IDS_PASTE_AND_GO);
menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
IDS_EDIT_SEARCH_ENGINES);
const PrefService::Preference* show_full_urls_pref =
location_bar_view_->profile()->GetPrefs()->FindPreference(
omnibox::kPreventUrlElisionsInOmnibox);
if (!show_full_urls_pref->IsManaged()) {
menu_contents->AddCheckItemWithStringId(IDC_SHOW_FULL_URLS,
IDS_CONTEXT_MENU_SHOW_FULL_URLS);
}
}
bool OmniboxViewViews::IsCommandIdChecked(int id) const {
if (id == IDC_SHOW_FULL_URLS) {
return location_bar_view_->profile()->GetPrefs()->GetBoolean(
omnibox::kPreventUrlElisionsInOmnibox);
}
return false;
}
void OmniboxViewViews::OnCompositingDidCommit(ui::Compositor* compositor) {
if (latency_histogram_state_ == ON_PAINT_CALLED) {
// Advance the state machine.
latency_histogram_state_ = COMPOSITING_COMMIT;
} else if (latency_histogram_state_ == COMPOSITING_COMMIT) {
// If we get two commits in a row (without compositing end in-between), it
// means compositing wasn't done for the previous commit, which can happen
// due to occlusion. In such a case, reset the state to inactive and don't
// log the metric.
insert_char_time_ = base::TimeTicks();
latency_histogram_state_ = NOT_ACTIVE;
}
}
void OmniboxViewViews::OnCompositingStarted(ui::Compositor* compositor,
base::TimeTicks start_time) {
// Track the commit to completion. This state is necessary to ensure the ended
// event we get is the one we're waiting for (and not for a previous paint).
if (latency_histogram_state_ == COMPOSITING_COMMIT)
latency_histogram_state_ = COMPOSITING_STARTED;
}
void OmniboxViewViews::OnCompositingEnded(ui::Compositor* compositor) {
if (latency_histogram_state_ == COMPOSITING_STARTED) {
DCHECK(!insert_char_time_.is_null());
UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency",
base::TimeTicks::Now() - insert_char_time_);
insert_char_time_ = base::TimeTicks();
latency_histogram_state_ = NOT_ACTIVE;
}
}
void OmniboxViewViews::OnCompositingShuttingDown(ui::Compositor* compositor) {
scoped_compositor_observation_.Reset();
}
void OmniboxViewViews::OnTemplateURLServiceChanged() {
InstallPlaceholderText();
}
void OmniboxViewViews::PermitExternalProtocolHandler() {
ExternalProtocolHandler::PermitLaunchUrl();
}
gfx::Range OmniboxViewViews::GetSimplifiedDomainBounds(
std::vector<gfx::Range>* ranges_surrounding_simplified_domain) {
DCHECK(ranges_surrounding_simplified_domain);
DCHECK(ranges_surrounding_simplified_domain->empty());
std::u16string text = GetText();
url::Component host = GetHostComponentAfterTrivialSubdomain();
GURL url = url_formatter::FixupURL(base::UTF16ToUTF8(text), std::string());
if (!OmniboxFieldTrial::ShouldMaybeElideToRegistrableDomain() ||
!ShouldElideToRegistrableDomain(url)) {
ranges_surrounding_simplified_domain->emplace_back(0, host.begin);
ranges_surrounding_simplified_domain->emplace_back(host.end(), text.size());
return gfx::Range(host.begin, host.end());
}
// TODO(estark): push this inside ParseForEmphasizeComponents()?
std::u16string simplified_domain = url_formatter::IDNToUnicode(
net::registry_controlled_domains::GetDomainAndRegistry(
url, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES));
if (simplified_domain.empty()) {
ranges_surrounding_simplified_domain->emplace_back(0, host.begin);
ranges_surrounding_simplified_domain->emplace_back(host.end(), text.size());
return gfx::Range(host.begin, host.end());
}
size_t simplified_domain_pos = text.rfind(simplified_domain, host.end());
DCHECK_NE(simplified_domain_pos, std::string::npos);
ranges_surrounding_simplified_domain->emplace_back(0, simplified_domain_pos);
ranges_surrounding_simplified_domain->emplace_back(host.end(), text.size());
return gfx::Range(simplified_domain_pos, host.end());
}
bool OmniboxViewViews::GetURLEligibleForSimplifiedDomainEliding() const {
if (HasFocus() || model()->user_input_in_progress())
return false;
if (!model()->CurrentTextIsURL())
return false;
std::u16string text = GetText();
url::Parsed parts;
std::u16string scheme_str;
// Call Parse() here instead of ParseForEmphasizeComponents() because the
// latter parses the inner URL for blob:, filesystem:, and view-source: URLs.
// For those schemes, we want the outer scheme so that we can disable elision
// for those schemes.
AutocompleteInput::Parse(text, std::string(),
model()->client()->GetSchemeClassifier(), &parts,
&scheme_str, nullptr);
// TODO(crbug.com/1117631): Simplified domain elision can have bugs for some
// URLs with bidirectional hosts, disable elision for those URLs while the
// bugs are fixed.
const std::u16string url_host = text.substr(parts.host.begin, parts.host.len);
if (base::i18n::GetStringDirection(url_host) ==
base::i18n::TextDirection::UNKNOWN_DIRECTION) {
return false;
}
// Simplified domain display only makes sense for http/https schemes; for now
// we don't want to mess with the display of other URLs like data:, blob:,
// chrome:, etc.
return (scheme_str == base::UTF8ToUTF16(url::kHttpScheme) ||
scheme_str == base::UTF8ToUTF16(url::kHttpsScheme)) &&
!url_host.empty() &&
!net::HostStringIsLocalhost(
base::UTF16ToUTF8(text.substr(parts.host.begin, parts.host.len)));
}
void OmniboxViewViews::ResetToHideOnInteraction() {
if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
model()->ShouldPreventElision()) {
return;
}
// Delete the interaction animation; it'll get recreated in
// DidGetUserInteraction(). Recreate the hover animation now because the user
// can hover over the URL before interacting with the page to reveal the
// scheme and trivial subdomain (if any).
elide_after_web_contents_interaction_animation_.reset();
hover_elide_or_unelide_animation_ =
std::make_unique<OmniboxViewViews::ElideAnimation>(this, GetRenderText());
if (GetURLEligibleForSimplifiedDomainEliding()) {
ShowFullURLWithoutSchemeAndTrivialSubdomain();
} else {
if (!HasFocus() && !model()->user_input_in_progress())
GetRenderText()->SetElideBehavior(gfx::ELIDE_TAIL);
FitToLocalBounds();
}
}
void OmniboxViewViews::OnShouldPreventElisionChanged() {
Update();
if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() &&
!OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover()) {
return;
}
if (model()->ShouldPreventElision()) {
hover_elide_or_unelide_animation_.reset();
elide_after_web_contents_interaction_animation_.reset();
if (GetURLEligibleForSimplifiedDomainEliding())
ShowFullURL();
return;
}
if (OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction()) {
if (location_bar_view_)
Observe(location_bar_view_->GetWebContents());
ResetToHideOnInteraction();
} else if (OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover()) {
if (GetURLEligibleForSimplifiedDomainEliding()) {
ElideURL();
}
hover_elide_or_unelide_animation_ =
std::make_unique<ElideAnimation>(this, GetRenderText());
}
}
void OmniboxViewViews::MaybeElideURLWithAnimationFromInteraction() {
if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
model()->ShouldPreventElision()) {
return;
}
// If there's already a hover animation running, just let it run as we will
// end up at the same place.
if (hover_elide_or_unelide_animation_->IsAnimating())
return;
// This method runs when the user interacts with the page, such as scrolling
// or typing. In the hide-on-interaction field trial, the URL is shown until
// user interaction, at which point it's animated to a simplified version of
// the domain (hiding the path and, optionally, subdomains). The animation is
// designed to draw the user's attention and suggest that they can return to
// the omnibox to uncover the full URL.
// If we've already created and run the animation in an earlier call to this
// method, we don't need to do so again.
if (!GetURLEligibleForSimplifiedDomainEliding() ||
elide_after_web_contents_interaction_animation_) {
return;
}
GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
elide_after_web_contents_interaction_animation_ =
std::make_unique<ElideAnimation>(this, GetRenderText());
std::vector<gfx::Range> ranges_surrounding_simplified_domain;
gfx::Range simplified_domain =
GetSimplifiedDomainBounds(&ranges_surrounding_simplified_domain);
elide_after_web_contents_interaction_animation_->Start(
simplified_domain, 0 /* delay_ms */, ranges_surrounding_simplified_domain,
GetOmniboxColor(GetThemeProvider(),
OmniboxPart::LOCATION_BAR_TEXT_DIMMED),
SK_ColorTRANSPARENT);
}
void OmniboxViewViews::ElideURL() {
DCHECK(OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover());
DCHECK(GetURLEligibleForSimplifiedDomainEliding());
std::vector<gfx::Range> ranges_surrounding_simplified_domain;
gfx::Range simplified_domain_bounds =
GetSimplifiedDomainBounds(&ranges_surrounding_simplified_domain);
// Setting the elision behavior to anything other than NO_ELIDE would result
// in the string getting cut off shorter the simplified domain, because
// display offset isn't taken into account when RenderText elides the string.
// See https://crbug.com/1099078. It's important to set to NO_ELIDE before
// starting to calculate simplified domain bounds with GetSubstringBounds(),
// because GetSubstringBounds() will fail if the simplified domain isn't
// visible due to RenderText elision.
GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
// The simplified domain string must be a substring of the current display
// text in order to elide to it.
DCHECK_NE(
GetRenderText()->GetDisplayText().find(GetText().substr(
simplified_domain_bounds.start(), simplified_domain_bounds.end())),
std::string::npos);
SetCursorEnabled(false);
gfx::Rect simplified_domain_rect;
for (const auto& rect :
GetRenderText()->GetSubstringBounds(simplified_domain_bounds)) {
simplified_domain_rect.Union(rect);
}
// |simplified_domain_rect| gives us the current bounds of the simplified
// domain substring. We shift it to the leftmost (rightmost if UI is RTL) edge
// of the omnibox (as determined by the x position of the current display
// rect), and then scroll to where the simplified domain begins, so that the
// simplified domain appears at the leftmost/rightmost edge.
gfx::Rect old_bounds = GetRenderText()->display_rect();
int shifted_simplified_domain_x_pos;
// The x position of the elided domain will depend on whether the UI is LTR or
// RTL.
if (base::i18n::IsRTL()) {
shifted_simplified_domain_x_pos =
old_bounds.right() - simplified_domain_rect.width();
} else {
shifted_simplified_domain_x_pos = old_bounds.x();
}
// Use |old_bounds| for y and height values because the URL should never shift
// vertically while eliding to/from simplified domain.
gfx::Rect shifted_simplified_domain_rect(
shifted_simplified_domain_x_pos, old_bounds.y(),
simplified_domain_rect.width(), old_bounds.height());
// Now apply the display rect and offset so that exactly the simplified domain
// is visible.
// First check if the simplified domain fits in the local bounds. If it
// doesn't, then we need to scroll so that the rightmost side is visible (e.g.
// "evil.com" instead of "victim.com" if the full hostname
// "victim.com.evil.com"). This check is only necessary for LTR mode because
// in RTL mode, we scroll to the rightmost side of the domain automatically.
if (shifted_simplified_domain_rect.width() > GetLocalBounds().width() &&
!base::i18n::IsRTL()) {
FitToLocalBounds();
GetRenderText()->SetDisplayOffset(
GetRenderText()->GetUpdatedDisplayOffset().x() -
(simplified_domain_rect.right() -
GetRenderText()->display_rect().width()));
} else {
// The simplified domain fits in the local bounds, so we proceed to set the
// display rect and offset to make the simplified domain visible.
GetRenderText()->SetDisplayRect(shifted_simplified_domain_rect);
// Scroll the text to where the simplified domain begins, relative to the
// leftmost (rightmost if UI is RTL) edge of the current display rect.
if (base::i18n::IsRTL()) {
GetRenderText()->SetDisplayOffset(
GetRenderText()->GetUpdatedDisplayOffset().x() + old_bounds.right() -
simplified_domain_rect.right());
} else {
GetRenderText()->SetDisplayOffset(
GetRenderText()->GetUpdatedDisplayOffset().x() -
(simplified_domain_rect.x() - old_bounds.x()));
}
}
// GetSubstringBounds() rounds outward internally, so there may be small
// portions of text still showing. Set the ranges surrounding the simplified
// domain to transparent so that these artifacts don't show.
for (const auto& range : ranges_surrounding_simplified_domain)
ApplyColor(SK_ColorTRANSPARENT, range);
}
void OmniboxViewViews::ShowFullURL() {
if (!OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() &&
!OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover()) {
return;
}
if (hover_elide_or_unelide_animation_)
hover_elide_or_unelide_animation_->Stop();
if (elide_after_web_contents_interaction_animation_)
elide_after_web_contents_interaction_animation_->Stop();
ApplyCaretVisibility();
FitToLocalBounds();
// Previous animations or elisions might have faded the path and/or subdomains
// to transparent, so reset their color now that they should be visible.
ApplyColor(GetOmniboxColor(GetThemeProvider(),
OmniboxPart::LOCATION_BAR_TEXT_DIMMED),
gfx::Range(0, GetText().size()));
UpdateTextStyle(GetText(), model()->CurrentTextIsURL(),
model()->client()->GetSchemeClassifier());
GetRenderText()->SetElideBehavior(gfx::ELIDE_TAIL);
}
void OmniboxViewViews::ShowFullURLWithoutSchemeAndTrivialSubdomain() {
DCHECK(GetURLEligibleForSimplifiedDomainEliding());
DCHECK(OmniboxFieldTrial::ShouldHidePathQueryRefOnInteraction() ||
OmniboxFieldTrial::ShouldRevealPathQueryRefOnHover());
DCHECK(!model()->ShouldPreventElision());
// First show the full URL, then figure out what to elide.
ShowFullURL();
if (!GetURLEligibleForSimplifiedDomainEliding() ||
model()->ShouldPreventElision()) {
return;
}
// TODO(https://crbug.com/1099078): currently, we cannot set the elide
// behavior to anything other than NO_ELIDE when the display offset is 0, i.e.
// when we are not hiding the scheme and trivial subdomain. This is because
// RenderText does not take display offset into account when eliding, so it
// will over-elide by however much text is scrolled out of the display area.
GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
GetRenderText()->SetDisplayOffset(0);
const gfx::Rect& current_display_rect = GetRenderText()->display_rect();
// If the scheme and trivial subdomain should be elided, then we want to set
// the display offset to where the hostname after the trivial subdomain (if
// any) begins, relative to the current display rect.
std::u16string text = GetText();
url::Component host = GetHostComponentAfterTrivialSubdomain();
// First check if the full hostname can fit in the local bounds. If not, then
// show the rightmost portion of the hostname.
gfx::Rect display_url_bounds;
gfx::Range host_range(host.begin, host.end());
if (TextRangeOverflowsView(this, GetRenderText(), host_range)) {
gfx::Rect host_bounds;
for (const auto& rect : GetRenderText()->GetSubstringBounds(host_range))
host_bounds.Union(rect);
// The full hostname won't fit, so show as much of it as possible starting
// from the right side.
display_url_bounds.set_x(
current_display_rect.x() +
(host_bounds.right() - current_display_rect.right()));
display_url_bounds.set_y(current_display_rect.y());
display_url_bounds.set_width(current_display_rect.width());
display_url_bounds.set_height(current_display_rect.height());
} else {
for (const auto& rect : GetRenderText()->GetSubstringBounds(
gfx::Range(host.begin, text.size()))) {
display_url_bounds.Union(rect);
}
display_url_bounds.set_height(current_display_rect.height());
display_url_bounds.set_y(current_display_rect.y());
}
// Set the scheme and trivial subdomain to transparent. This isn't necessary
// to hide this portion of the text because it will be scrolled out of
// visibility anyway when we set the display offset below. However, if the
// user subsequently hovers over the URL to bring back the scheme and trivial
// subdomain, the hover animation assumes that the hidden text starts from
// transparent and fades it back in.
ApplyColor(SK_ColorTRANSPARENT, gfx::Range(0, host.begin));
// Before setting the display offset, set the display rect to the portion of
// the URL that won't be elided, or leave it at the local bounds, whichever is
// smaller. The display offset is capped at 0 if the text doesn't overflow the
// display rect, so we must fit the display rect to the text so that we can
// then set the display offset to scroll the scheme and trivial subdomain out
// of visibility.
GetRenderText()->SetDisplayRect(
gfx::Rect(base::i18n::IsRTL()
? current_display_rect.right() - display_url_bounds.width()
: current_display_rect.x(),
display_url_bounds.y(), display_url_bounds.width(),
display_url_bounds.height()));
GetRenderText()->SetDisplayOffset(
-1 * (display_url_bounds.x() - current_display_rect.x()));
}
url::Component OmniboxViewViews::GetHostComponentAfterTrivialSubdomain() const {
url::Component host;
url::Component unused_scheme;
std::u16string text = GetText();
AutocompleteInput::ParseForEmphasizeComponents(
text, model()->client()->GetSchemeClassifier(), &unused_scheme, &host);
url_formatter::StripWWWFromHostComponent(base::UTF16ToUTF8(text), &host);
return host;
}
BEGIN_METADATA(OmniboxViewViews, views::Textfield)
ADD_READONLY_PROPERTY_METADATA(bool, SelectionAtEnd)
ADD_READONLY_PROPERTY_METADATA(int, TextWidth)
ADD_READONLY_PROPERTY_METADATA(int, UnelidedTextWidth)
ADD_READONLY_PROPERTY_METADATA(int, Width)
ADD_READONLY_PROPERTY_METADATA(std::u16string, SelectedText)
ADD_READONLY_PROPERTY_METADATA(bool, URLEligibleForSimplifiedDomainEliding)
ADD_READONLY_PROPERTY_METADATA(url::Component,
HostComponentAfterTrivialSubdomain)
END_METADATA
| 41.180014 | 80 | 0.715586 | [
"geometry",
"vector",
"model"
] |
636bf82db0aec6a2ef9118b8f72bbdcd076c2570 | 8,483 | cpp | C++ | xsettlers/logic/playfield.cpp | Skarmux/X-Settlers | 9a27ef2fac99e4efa2e169f085206aaebd2ecbf7 | [
"Apache-2.0"
] | 8 | 2020-07-29T20:45:26.000Z | 2021-08-22T02:34:40.000Z | xsettlers/logic/playfield.cpp | PaweX/X-Settlers | 9a27ef2fac99e4efa2e169f085206aaebd2ecbf7 | [
"Apache-2.0"
] | null | null | null | xsettlers/logic/playfield.cpp | PaweX/X-Settlers | 9a27ef2fac99e4efa2e169f085206aaebd2ecbf7 | [
"Apache-2.0"
] | 3 | 2020-08-16T16:17:18.000Z | 2022-03-29T10:17:47.000Z | //#include "Playfield.h"
//
//PlayField::PlayField(const std::string& map_filepath) {
// loadMapFile(map_filepath);
//}
//
//PlayField::PlayField(uint32_t width, uint32_t height)
// : m_width(width), m_height(height)
//{
// m_walkable_mask = std::vector<std::vector<bool>>(width);
// m_movables = std::vector<std::vector<Movable*>>(width);
// for (uint32_t i = 0; i < width; i++) {
// m_walkable_mask[i] = std::vector<bool>(height, true);
// m_movables[i] = std::vector<Movable*>(height, nullptr);
// }
//
// // initialize play field border
// for (uint32_t row = 0; row < m_height; row++) {
// for (uint32_t col = 0; col < m_width; col++) {
// if (col == 0 || col == m_width - 1 || row == 0 || row == m_height - 1) {
// m_walkable_mask[col][row] = false;
// }
// }
// }
//
//}
//
//void PlayField::Update() {
// for (uint32_t y = 0; y < m_height; y++) {
// UpdateMovablesRow(y);
// }
// m_tick++;
//}
//
//bool PlayField::PlaceMovable(glm::ivec2& pos, Movable* m) {
// // TODO: Push idle Movable to side
// if (m_walkable_mask[pos.y][pos.x] == true && m_movables[pos.y][pos.x] == nullptr) {
// m->m_pos = pos;
// m->m_steps = 0;
// m->m_tick = m_tick;
// m_movables[pos.y][pos.x] = m;
// return true;
// }
// return false;
//}
//
//std::queue<glm::ivec2> PlayField::GetPath(glm::ivec2& start, glm::ivec2& goal) {
// //TODO AStarJPS()
//}
//
//void PlayField::UpdateMovablesRow(uint32_t& y) {
// for (uint32_t x = 0; x < m_width; x++)
// {
// if (m_movables[x][y] == nullptr) continue;
//
// Movable* m = m_movables[x][y];
//
// //m->m_lock.lock();
// if (m->m_steps > 1) { // moving
// m->m_steps -= m->m_speed;
// }
// else if (m->m_steps == 1) { // arriving
// // unblock trailing fields
// m_movables_mask[m->m_pos.x][m->m_pos.y] = false;
// m_movables[m->m_pos.x][m->m_pos.y] = nullptr;
// m->m_pos = m->m_tar;
// m->m_steps = 0;
// m_movables[m->m_pos.x][m->m_pos.y] = m;
// }
// else { // .. == 0
// if (m->m_path->empty()) { // switch to idle and unblock current field
// m_movables_mask[m->m_pos.x][m->m_pos.y] = false;
// }
// else { // start moving in next direction from path
// // 1) get pos of targeted field
// m->m_dir = Direction(m->m_pos, m->m_path->front());
// m->m_path->pop();
// m->m_tar = Step(m->m_pos, m->m_dir);
//
// // 2) check if target field is blocked
// if (m_movables_mask[m->m_tar.x][m->m_tar.y] == false) {
// // not blocked
// // 3.A) block field and start walking
// m_movables_mask[m->m_tar.x][m->m_tar.y] = true;
// m->m_steps = STEPS_PER_EDGE;
// }
// else {
// // blocked
// // 3.B) check if left/right are free
// DIR right_dir = static_cast<DIR>((m->m_dir + 1) % DIR::COUNT);
// glm::ivec2 right_tar = Step(m->m_pos, right_dir);
//
// DIR left_dir = static_cast<DIR>((m->m_dir - 1) % DIR::COUNT);
// glm::ivec2 left_tar = Step(m->m_pos, left_dir);
//
// if (m_walkable_mask[right_tar.x][right_tar.y] == false) {
// m_walkable_mask[right_tar.x][right_tar.y] = true;
// m->m_dir = right_dir;
// m->m_tar = right_tar;
// m->m_steps = STEPS_PER_EDGE;
// // >> calculate new or repair path here!
// }
// else if (m_walkable_mask[left_tar.x][left_tar.y] == false) {
// m_walkable_mask[left_tar.x][left_tar.y] = true;
// m->m_dir = left_dir;
// m->m_tar = left_tar;
// m->m_steps = STEPS_PER_EDGE;
// // >> calculate new or repair path here!
// }
// else {
// // just stand still for this round and cry..
// // \(;n; \) \( ;A; )/ (/ ;n;)/
// }
// }
// }
// }
// m->m_tick++;
// //m->m_lock.unlock();
// }
//}
//
//inline std::vector<glm::ivec2> PlayField::Neighbours(glm::ivec2 pos) {
// std::vector<glm::ivec2> neighbours;
// neighbours.reserve(6);
// neighbours.emplace_back(glm::ivec2(pos.x - 1, pos.y - 1));
// neighbours.emplace_back(glm::ivec2(pos.x, pos.y - 1));
// neighbours.emplace_back(glm::ivec2(pos.x - 1, pos.y));
// neighbours.emplace_back(glm::ivec2(pos.x + 1, pos.y));
// neighbours.emplace_back(glm::ivec2(pos.x, pos.y + 1));
// neighbours.emplace_back(glm::ivec2(pos.x + 1, pos.y + 1));
// return neighbours;
//}
//
//inline glm::ivec2 PlayField::Step(glm::ivec2& pos, DIR dir) {
// switch (dir) {
// case DIR::NE: return glm::ivec2(pos.x, pos.y - 1);
// case DIR::SW: return glm::ivec2(pos.x, pos.y + 1);
// case DIR::SE: return glm::ivec2(pos.x + 1, pos.y + 1);
// case DIR::NW: return glm::ivec2(pos.x - 1, pos.y - 1);
// case DIR::W: return glm::ivec2(pos.x - 1, pos.y);
// case DIR::E: return glm::ivec2(pos.x + 1, pos.y);
// }
//}
//
//inline DIR PlayField::Direction(glm::ivec2& start, glm::ivec2& goal) {
// if (start.x > goal.x) {
// if (start.y == goal.y) return DIR::W;
// if (start.y > goal.y) return DIR::NW;
// }
// else if (start.x < goal.x) {
// if (start.y < goal.y) return DIR::SE;
// if (start.y == goal.y) return DIR::E;
// }
// else {
// if (start.y > goal.y) return DIR::NE;
// if (start.y < goal.y) return DIR::SW;
// }
//
// if (start == goal) {
// throw std::runtime_error("ERROR :: Direction() :: start and goal position are the same!");
// }
// else {
// throw std::runtime_error("ERROR :: Direction() :: start and goal position aren't adjacent!");
// }
//}
//
//// Map File Access
//
//void PlayField::loadMapFile(const std::string& map_filepath) {
//
//}
//
//// Path Finding
//
//typedef std::pair<double, glm::ivec2> prioNode;
//void PlayField::AStarJPS(glm::ivec2& start, glm::ivec2& goal,
// std::unordered_map<glm::ivec2, glm::ivec2>& came_from,
// std::unordered_map<glm::ivec2, int>& cost_so_far)
//{
// std::priority_queue <prioNode, std::vector<prioNode>, std::greater<prioNode>> frontier;
// std::vector<glm::ivec2> neighbours = Neighbours(start);
// frontier.push(std::make_pair(0, start));
//
// came_from[start] = start;
// cost_so_far[start] = 0;
//
// glm::ivec2 current = start;
//
// while (!frontier.empty())
// {
// if (current == goal) {
// break;
// }
//
// for (glm::ivec2 next : neighbours) {
// // cost going from start to next
// int new_cost = cost_so_far[current] + 1;
//
// // if key not found OR cost is smaller that previous path to next
// if (cost_so_far.find(next) == cost_so_far.end() || new_cost < cost_so_far[next]) {
// cost_so_far[next] = new_cost;
// came_from[next] = current;
// double priority = new_cost + glm::distance(next, goal);
// frontier.push(std::make_pair(priority, next));
// }
// }
//
// current = frontier.top().second;
// //neighbours = Neighbours(current);
// neighbours = IdentifySuccessors(came_from[current], current, start, goal);
// }
//}
//
//inline std::vector<glm::ivec2> PlayField::IdentifySuccessors(glm::ivec2& parent, glm::ivec2& x, glm::ivec2& start, glm::ivec2& goal) {
// std::vector<glm::ivec2> successors;
// std::vector<glm::ivec2> neighbours = PrunedNeighbours(parent, x);
// for (glm::ivec2 n : neighbours) {
// n = Jump(x, Direction(x, n), start, goal);
// successors.push_back(n);
// }
// return successors;
//}
//
//inline glm::ivec2 PlayField::Jump(glm::ivec2& pos, DIR dir, glm::ivec2& start, glm::ivec2& goal) {
// glm::ivec2 n = Step(pos, dir);
// if (m_walkable_mask[n.x][n.y] == false) return glm::ivec2(0, 0);
// if (n == goal) return n;
//
// // if there is at least one "forced" neighbor (due to blocked areas)
// std::vector<glm::ivec2> neighbours = Neighbours(pos);
// if (neighbours.size() > 1) return n;
//
// return Jump(n, dir, start, goal);
//}
//
//inline std::vector<glm::ivec2> PlayField::PrunedNeighbours(glm::ivec2& parent, glm::ivec2& x) {
// std::vector<glm::ivec2> neighbours;
//
// DIR dir = Direction(parent, x);
//
// glm::ivec2 straight = Step(x, Direction(parent, x));
// if (m_walkable_mask[straight.x][straight.y] == true) {
// neighbours.push_back(straight);
// }
//
// glm::ivec2 left = Step(parent, static_cast<DIR>(dir + 1 % DIR::COUNT));
// if (m_walkable_mask[left.x][left.y] == false) {
// glm::ivec2 forced_left = Step(x, static_cast<DIR>(dir + 1 % DIR::COUNT));
// if (m_walkable_mask[forced_left.x][forced_left.y] == true)
// neighbours.push_back(forced_left);
// }
//
// glm::ivec2 right = Step(parent, static_cast<DIR>(dir - 1 % DIR::COUNT));
// if (m_walkable_mask[right.x][right.y] == false) {
// glm::ivec2 forced_right = Step(x, static_cast<DIR>(dir - 1 % DIR::COUNT));
// if (m_walkable_mask[forced_right.x][forced_right.y] == true)
// neighbours.push_back(forced_right);
// }
//
// return neighbours;
//} | 32.501916 | 136 | 0.60132 | [
"vector"
] |
6372a621b205e72be4893a41d3b04865ab2e0918 | 3,441 | cpp | C++ | src/Codecs/DataSource.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 198 | 2015-04-26T08:06:18.000Z | 2022-03-13T01:31:50.000Z | src/Codecs/DataSource.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 15 | 2015-07-07T19:47:08.000Z | 2022-02-04T05:56:51.000Z | src/Codecs/DataSource.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 96 | 2015-04-24T15:19:43.000Z | 2022-03-28T13:15:11.000Z | // Copyright (c) 2009, Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.
#include <Common/QuickFASTPch.h>
#include "DataSource.h"
#include <Common/Exceptions.h>
using namespace QuickFAST;
using namespace Codecs;
DataSource::DataSource()
: buffer_(0)
, size_(0)
, position_(0)
, echo_(0)
, raw_(false)
, hex_(true)
, verboseMessages_(true)
, verboseFields_(false)
, byteCount_(0)
, isPmap_(false)
{
}
DataSource::~DataSource()
{
}
int
DataSource::messageAvailable()
{
// the default implementation assumes that any data at all means the next message will
// appear when needed.
return bytesAvailable();
}
int
DataSource::bytesAvailable()
{
if(position_ >= size_)
{
position_ = 0;
size_ = 0;
(void)getBuffer(buffer_, size_);
}
return int(size_ - position_);
}
void
DataSource::doEcho(bool ok, uchar byte)
{
if(ok)
{
++byteCount_;
if(hex_)
{
(*echo_) << std::hex << std::setw(2) << std::setfill('0')
<< short(byte) << ' '
<< std::setfill(' ') << std::setw(0) << std::dec;
}
else if(raw_)
{
echo_->put(byte);
}
if(verboseFields_)
{
echoString_ += byte;
}
}
else
{
if(verboseMessages_)
{
(*echo_) << "*** End of data @" << std::hex << byteCount_ << std::dec << "***" << std::endl;
}
}
}
void
DataSource::setEcho(
std::ostream & echo,
const EchoType& echoType /* = HEX */,
bool verboseMessages/* = true */,
bool verboseFields/* = false */)
{
echo_ = &echo;
if (echoType == HEX)
{
raw_ = false;
hex_ = true;
}
else if (echoType == RAW)
{
raw_ = true;
hex_ = false;
}
else if (echoType == NONE)
{
raw_ = false;
hex_ = false;
}
verboseMessages_ = verboseMessages;
verboseFields_ = verboseFields;
}
void
DataSource::beginMessage()
{
if(echo_ && verboseMessages_)
{
(*echo_) << std::endl << "***MESSAGE @" << std::hex << byteCount_ << std::dec << "***" << std::endl;
}
}
void
DataSource::beginField(const std::string & name)
{
if(echo_ && verboseFields_)
{
if(!echoString_.empty())
{
if(isPmap_)
{
(*echo_) << std::endl << " PMAP: ";
for(size_t pos = 0; pos < echoString_.length(); ++pos)
{
unsigned char byte = echoString_[pos];
for(size_t b = 0; b < 7; ++b)
{
(*echo_) << ' ' << (short)(byte >>6 & 1);
byte <<= 1;
}
}
}
else
{
(*echo_) << std::endl << " Value: \"";
unsigned long long unsignedInt = 0;
long long signedInt = 0;
for(size_t pos = 0; pos < echoString_.length(); ++pos)
{
unsigned char byte = echoString_[pos];
char c = (byte & 0x7f);
if(c < ' ' || c == 0x7F) c = '.';
(*echo_) << c;
if(pos == 0 && (c & 0x40) != 0)
{
signedInt = -1;
}
signedInt <<= 7;
signedInt += (byte & 0x7F);
unsignedInt <<= 7;
unsignedInt += (byte & 0x7F);
}
(*echo_) << "\": " << signedInt;
if(signedInt < 0)
{
(*echo_) << " (" << unsignedInt << ')';
}
}
echoString_.erase();
}
isPmap_ = name == "PMAP";
(*echo_) << std::endl << "***Field: " << name << " @" << std::hex<< byteCount_ << std::dec << "***" << std::endl << " ";
}
}
| 20.728916 | 125 | 0.514095 | [
"object"
] |
6375d9c06933db62e0b719765fe7d1d08c5f144b | 8,564 | cc | C++ | src/ledger/bin/p2p_provider/impl/p2p_provider_impl_unittest.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | src/ledger/bin/p2p_provider/impl/p2p_provider_impl_unittest.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | null | null | null | src/ledger/bin/p2p_provider/impl/p2p_provider_impl_unittest.cc | winksaville/Fuchsia | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2018 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 "src/ledger/bin/p2p_provider/impl/p2p_provider_impl.h"
#include <fuchsia/overnet/cpp/fidl.h>
#include <lib/fidl/cpp/binding.h>
#include <lib/fit/function.h>
#include <algorithm>
#include <ostream>
#include <string>
// gtest matchers are in gmock.
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "peridot/lib/convert/convert.h"
#include "src/ledger/bin/p2p_provider/impl/make_client_id.h"
#include "src/ledger/bin/p2p_provider/impl/static_user_id_provider.h"
#include "src/ledger/bin/p2p_provider/public/user_id_provider.h"
#include "src/ledger/bin/testing/overnet/overnet_factory.h"
#include "src/ledger/bin/testing/test_with_environment.h"
#include "src/lib/fxl/macros.h"
namespace p2p_provider {
namespace {
class RecordingClient : public P2PProvider::Client {
public:
struct DeviceChange {
P2PClientId device;
DeviceChangeType change;
bool operator==(const DeviceChange& b) const {
return device == b.device && change == b.change;
}
};
struct Message {
P2PClientId source;
std::string data;
bool operator==(const Message& b) const { return source == b.source && data == b.data; }
};
void OnDeviceChange(const P2PClientId& device_name, DeviceChangeType change_type) override {
switch (change_type) {
case DeviceChangeType::NEW:
device_change_new.push_back(device_name);
break;
case DeviceChangeType::DELETED:
device_change_deleted.push_back(device_name);
break;
}
}
void OnNewMessage(const P2PClientId& device_name, convert::ExtendedStringView message) override {
messages.push_back(Message{device_name, message.ToString()});
}
FXL_WARN_UNUSED_RESULT bool HasDevicesChanges(size_t new_device_count,
size_t deleted_device_count) {
std::cout << device_change_new.size() << " " << device_change_deleted.size() << "\n";
return device_change_new.size() == new_device_count &&
device_change_deleted.size() == deleted_device_count;
}
std::vector<P2PClientId> device_change_new;
std::vector<P2PClientId> device_change_deleted;
std::vector<Message> messages;
};
// This test is templated with a boolean:
// In P2P, different code paths are taken depending on whether their overnet peer ID is greater or
// smaller than an other overnet peer ID.
// In order to test both code paths, the tests are also run with the IDs having their bits flipped.
class P2PProviderImplTest : public ledger::TestWithEnvironment,
public ::testing::WithParamInterface<bool> {
public:
P2PProviderImplTest() : overnet_factory_(dispatcher()) {}
~P2PProviderImplTest() override = default;
std::unique_ptr<P2PProvider> GetProvider(uint64_t host_id, std::string user_name) {
if (GetParam()) {
host_id = ~host_id;
}
fuchsia::overnet::OvernetPtr overnet;
overnet_factory_.AddBinding(host_id, overnet.NewRequest());
return std::make_unique<p2p_provider::P2PProviderImpl>(
std::move(overnet), std::make_unique<StaticUserIdProvider>(std::move(user_name)),
environment_.random());
}
protected:
void SetUp() override { ::testing::Test::SetUp(); }
ledger::OvernetFactory overnet_factory_;
private:
FXL_DISALLOW_COPY_AND_ASSIGN(P2PProviderImplTest);
};
TEST_P(P2PProviderImplTest, NoSelfPeerNoCrash) {
std::unique_ptr<P2PProvider> provider1 = GetProvider(1, "user1");
RecordingClient client1;
provider1->Start(&client1);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(0, 0));
}
TEST_P(P2PProviderImplTest, ThreeHosts_SameUser) {
std::unique_ptr<P2PProvider> provider1 = GetProvider(1, "user1");
RecordingClient client1;
provider1->Start(&client1);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(0, 0));
std::unique_ptr<P2PProvider> provider2 = GetProvider(2, "user1");
RecordingClient client2;
provider2->Start(&client2);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(1, 0));
EXPECT_TRUE(client2.HasDevicesChanges(1, 0));
std::unique_ptr<P2PProvider> provider3 = GetProvider(3, "user1");
RecordingClient client3;
provider3->Start(&client3);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(2, 0));
EXPECT_TRUE(client2.HasDevicesChanges(2, 0));
EXPECT_TRUE(client3.HasDevicesChanges(2, 0));
// Disconnect one host, and verify disconnection notices are sent.
provider2.reset();
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(2, 1));
EXPECT_TRUE(client2.HasDevicesChanges(2, 0));
EXPECT_TRUE(client3.HasDevicesChanges(2, 1));
}
TEST_P(P2PProviderImplTest, FourHosts_TwoUsers) {
std::unique_ptr<P2PProvider> provider1 = GetProvider(1, "user1");
RecordingClient client1;
provider1->Start(&client1);
std::unique_ptr<P2PProvider> provider2 = GetProvider(2, "user2");
RecordingClient client2;
provider2->Start(&client2);
std::unique_ptr<P2PProvider> provider3 = GetProvider(3, "user2");
RecordingClient client3;
provider3->Start(&client3);
std::unique_ptr<P2PProvider> provider4 = GetProvider(4, "user1");
RecordingClient client4;
provider4->Start(&client4);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(1, 0));
EXPECT_TRUE(client2.HasDevicesChanges(1, 0));
EXPECT_TRUE(client3.HasDevicesChanges(1, 0));
EXPECT_TRUE(client4.HasDevicesChanges(1, 0));
provider4.reset();
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(1, 1));
EXPECT_TRUE(client2.HasDevicesChanges(1, 0));
EXPECT_TRUE(client3.HasDevicesChanges(1, 0));
// |client4| should not be notified of any change because |provider4| was
// reset.
EXPECT_TRUE(client4.HasDevicesChanges(1, 0));
}
TEST_P(P2PProviderImplTest, TwoHosts_Messages) {
std::unique_ptr<P2PProvider> provider1 = GetProvider(1, "user1");
RecordingClient client1;
provider1->Start(&client1);
std::unique_ptr<P2PProvider> provider2 = GetProvider(2, "user1");
RecordingClient client2;
provider2->Start(&client2);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(1, 0));
EXPECT_TRUE(client2.HasDevicesChanges(1, 0));
P2PClientId client1_id_from_pov_of_client2 = client2.device_change_new[0];
P2PClientId client2_id_from_pov_of_client1 = client1.device_change_new[0];
// Send message
EXPECT_TRUE(provider1->SendMessage(client2_id_from_pov_of_client1, "foobar"));
RunLoopUntilIdle();
EXPECT_THAT(client1.messages, testing::ElementsAre());
EXPECT_THAT(client2.messages, testing::ElementsAre(RecordingClient::Message{
client1_id_from_pov_of_client2, "foobar"}));
}
TEST_P(P2PProviderImplTest, TwoHosts_MessagesThenDisconnect) {
std::unique_ptr<P2PProvider> provider1 = GetProvider(1, "user1");
RecordingClient client1;
provider1->Start(&client1);
std::unique_ptr<P2PProvider> provider2 = GetProvider(2, "user1");
RecordingClient client2;
provider2->Start(&client2);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(1, 0));
EXPECT_TRUE(client2.HasDevicesChanges(1, 0));
P2PClientId client1_id_from_pov_of_client2 = client2.device_change_new[0];
P2PClientId client2_id_from_pov_of_client1 = client1.device_change_new[0];
// Send message from client that got its peer from ListPeers
EXPECT_TRUE(provider1->SendMessage(client2_id_from_pov_of_client1, "foobar"));
provider1.reset();
RunLoopUntilIdle();
EXPECT_THAT(client2.messages, testing::ElementsAre(RecordingClient::Message{
client1_id_from_pov_of_client2, "foobar"}));
}
TEST_P(P2PProviderImplTest, TwoHosts_DisconnectThenReconnect) {
std::unique_ptr<P2PProvider> provider1 = GetProvider(1, "user1");
RecordingClient client1;
provider1->Start(&client1);
std::unique_ptr<P2PProvider> provider2 = GetProvider(2, "user1");
RecordingClient client2;
provider2->Start(&client2);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(1, 0));
provider2.reset();
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(1, 1));
std::unique_ptr<P2PProvider> provider2_bis = GetProvider(2, "user1");
RecordingClient client2_bis;
provider2_bis->Start(&client2_bis);
RunLoopUntilIdle();
EXPECT_TRUE(client1.HasDevicesChanges(2, 1));
}
INSTANTIATE_TEST_SUITE_P(P2PProviderImplTest, P2PProviderImplTest, testing::Values(false, true));
} // namespace
} // namespace p2p_provider
| 33.584314 | 99 | 0.739724 | [
"vector"
] |
6376cf00cf2a3eb0634228f34721319dcf4e439b | 1,199 | cpp | C++ | high-can-binding/high-viwi-binding-hat.cpp | rm-medina/high-level-viwi-service | 66abc905889c96e77a570d22551749354e352789 | [
"Apache-2.0"
] | 9 | 2017-06-05T19:37:24.000Z | 2019-12-30T19:20:22.000Z | high-can-binding/high-viwi-binding-hat.cpp | rm-medina/high-level-viwi-service | 66abc905889c96e77a570d22551749354e352789 | [
"Apache-2.0"
] | 1 | 2019-03-13T08:47:14.000Z | 2019-03-13T17:43:16.000Z | high-can-binding/high-viwi-binding-hat.cpp | rm-medina/high-level-viwi-service | 66abc905889c96e77a570d22551749354e352789 | [
"Apache-2.0"
] | 4 | 2018-11-14T13:35:12.000Z | 2019-03-28T21:25:21.000Z | #include "high-viwi-binding-hat.hpp"
#include <cstddef>
/// Interface between the daemon and the binding
static int init_service();
static const struct afb_verb_v2 verbs[]=
{
{ .verb= "subscribe", .callback= subscribe, .auth = NULL, .info = "subscribe to an ViWi object", .session = 0 },
{ .verb= "unsubscribe", .callback= unsubscribe, .auth = NULL, .info = "unsubscribe to a ViWi object", .session = 0 },
{ .verb= "get", .callback= get, .auth = NULL, .info = "Get informations about a resource or element", .session = 0 },
{ .verb= NULL, .callback=NULL, .auth = NULL, .info = NULL, .session = 0 }
};
const struct afb_binding_v2 afbBindingV2 = {
.api = "high-viwi",
.specification = "",
.info = "High CAN ViWi API connected to low-can AGL service",
.verbs = verbs,
.preinit = NULL,
.init = init_service,
.onevent = onEvent,
.noconcurrency = 1
};
/// @brief Initialize the binding.
///
/// @return Exit code, zero if success.
int init_service()
{
AFB_NOTICE("high level binding is initializing");
afb_daemon_require_api("low-can", 1);
initHigh();
AFB_NOTICE("high level binding is initialized and running");
return 0;
}
| 32.405405 | 129 | 0.647206 | [
"object"
] |
63787082ddfa1808881e099fd0f6aec6c3605c39 | 3,924 | hpp | C++ | genex/group/GlobalGroupSpace.hpp | mihinsumaria/genex | 34786b0cf5d573348b82e5d164dbc05e0411d6a8 | [
"MIT"
] | 2 | 2020-06-28T07:36:42.000Z | 2021-01-11T07:49:24.000Z | genex/group/GlobalGroupSpace.hpp | mihinsumaria/genex | 34786b0cf5d573348b82e5d164dbc05e0411d6a8 | [
"MIT"
] | null | null | null | genex/group/GlobalGroupSpace.hpp | mihinsumaria/genex | 34786b0cf5d573348b82e5d164dbc05e0411d6a8 | [
"MIT"
] | 1 | 2020-12-01T20:25:42.000Z | 2020-12-01T20:25:42.000Z | #ifndef GLOBAL_GROUP_SPACE_H
#define GLOBAL_GROUP_SPACE_H
#include <fstream>
#include <vector>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/split_member.hpp>
#include "group/LocalLengthGroupSpace.hpp"
#include "TimeSeries.hpp"
#include "TimeSeriesSet.hpp"
#include "distance/Distance.hpp"
#include "group/Group.hpp"
namespace genex {
vector<int> generateTraverseOrder(int queryLength, int totalLength);
/**
* The set of all groups of equal lengths for a dataset
*/
class GlobalGroupSpace
{
public:
/**
* @brief The constructor for the GlobalGroupSpace
*
* @param dataset the dataset to group
* @param threshold the threshold for similarity within a group
*/
GlobalGroupSpace(const TimeSeriesSet& dataset);
/**
* @brief The deconstructor for the GlobalGroupSpace
*/
~GlobalGroupSpace();
/**
* @brief clears the groups
*/
void reset();
/**
* @brief groups the dataset into groups of equal length
* using the metric to determine similarity
*
* @param metric the metric used to group by
* @param threshold the threshold to be group with
* @param wholeSeriesOnly if set to true group the largest length only
* @return the number of groups it creates
*/
int group(
const std::string& distance_name, data_t threshold, bool wholeSeriesOnly=false);
int groupMultiThreaded(
const std::string& distance_name, data_t threshold, int num_thread, bool wholeSeriesOnly=false);
int getTotalNumberOfGroups() const;
std::string getDistanceName() const;
data_t getThreshold() const;
/**
* @brief gets the most similar sequence in the dataset
*
* @param query gets most similar sequence to the query
* @return the best match in the dataset
*/
candidate_time_series_t getBestMatch(const TimeSeries& query);
/**
* @brief find k similar time series to the query
*
* @param query gets most similar sequence to the query
* @param k number of similar time series
* @param approx if true, return the approximated distance, otherwise return the exact distance
* @return the best match in the dataset
*/
std::vector<candidate_time_series_t> getKBestMatches(const TimeSeries& query, int k);
void saveGroupsOld(std::ofstream &fout, bool groupSizeOnly) const;
int loadGroupsOld(std::ifstream &fin);
private:
std::string distanceName;
std::vector<LocalLengthGroupSpace*> localLengthGroupSpace;
const TimeSeriesSet& dataset;
dist_t pairwiseDistance;
dist_t warpedDistance;
data_t threshold;
int totalNumberOfGroups = 0;
bool wholeSeriesOnly = false;
void _loadDistance(const std::string& distanceName);
int _group(int i);
int _getMinLength() const;
/*************************
* Start serialization
*************************/
friend class boost::serialization::access;
template<class A>
void save(A & ar, unsigned) const
{
size_t maxLen = this->localLengthGroupSpace.size();
size_t minLen = _getMinLength();
ar << minLen << maxLen << this->distanceName << this->threshold;
for (auto i = minLen; i < maxLen; i++) {
ar << *(this->localLengthGroupSpace[i]);
}
}
template<class A>
void load(A & ar, unsigned)
{
size_t maxLen, minLen;
ar >> minLen >> maxLen >> this->distanceName >> this->threshold;
this->_loadDistance(this->distanceName);
this->localLengthGroupSpace.resize(dataset.getMaxLength() + 1, nullptr);
this->totalNumberOfGroups = 0;
for (auto i = minLen; i < maxLen; i++) {
auto llgs = new LocalLengthGroupSpace(dataset, i);
ar >> *llgs;
this->localLengthGroupSpace[i] = llgs;
this->totalNumberOfGroups += llgs->getNumberOfGroups();
}
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
/*************************
* End serialization
*************************/
};
} // namespace genex
#endif //GLOBAL_GROUP_SPACE_H
| 28.642336 | 100 | 0.685015 | [
"vector"
] |
6379e7bff8c84aa51106c729e26f1684205cb0f4 | 19,401 | cc | C++ | chrome/browser/importer/importer.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | chrome/browser/importer/importer.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/importer/importer.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/importer.h"
#include "app/l10n_util.h"
#include "base/thread.h"
#include "base/values.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/browsing_instance.h"
#include "chrome/browser/importer/firefox_profile_lock.h"
#include "chrome/browser/importer/importer_bridge.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/notification_source.h"
#include "gfx/codec/png_codec.h"
#include "gfx/favicon_size.h"
#include "grit/generated_resources.h"
#include "skia/ext/image_operations.h"
#include "webkit/glue/image_decoder.h"
// TODO(port): Port these files.
#if defined(OS_WIN)
#include "app/win_util.h"
#include "chrome/browser/views/importer_lock_view.h"
#include "views/window/window.h"
#elif defined(OS_MACOSX)
#include "chrome/browser/ui/cocoa/importer_lock_dialog.h"
#elif defined(TOOLKIT_USES_GTK)
#include "chrome/browser/gtk/import_lock_dialog_gtk.h"
#endif
using webkit_glue::PasswordForm;
// Importer.
void Importer::Cancel() { cancelled_ = true; }
Importer::Importer()
: cancelled_(false),
import_to_bookmark_bar_(false),
bookmark_bar_disabled_(false) {
}
Importer::~Importer() {
}
// static
bool Importer::ReencodeFavicon(const unsigned char* src_data, size_t src_len,
std::vector<unsigned char>* png_data) {
// Decode the favicon using WebKit's image decoder.
webkit_glue::ImageDecoder decoder(gfx::Size(kFavIconSize, kFavIconSize));
SkBitmap decoded = decoder.Decode(src_data, src_len);
if (decoded.empty())
return false; // Unable to decode.
if (decoded.width() != kFavIconSize || decoded.height() != kFavIconSize) {
// The bitmap is not the correct size, re-sample.
int new_width = decoded.width();
int new_height = decoded.height();
calc_favicon_target_size(&new_width, &new_height);
decoded = skia::ImageOperations::Resize(
decoded, skia::ImageOperations::RESIZE_LANCZOS3, new_width, new_height);
}
// Encode our bitmap as a PNG.
gfx::PNGCodec::EncodeBGRASkBitmap(decoded, false, png_data);
return true;
}
// ImporterHost.
ImporterHost::ImporterHost()
: profile_(NULL),
observer_(NULL),
task_(NULL),
importer_(NULL),
waiting_for_bookmarkbar_model_(false),
installed_bookmark_observer_(false),
is_source_readable_(true),
headless_(false),
parent_window_(NULL),
importer_list_(new ImporterList) {
importer_list_->DetectSourceProfilesHack();
}
ImporterHost::ImporterHost(ImporterList::Observer* observer)
: profile_(NULL),
observer_(NULL),
task_(NULL),
importer_(NULL),
waiting_for_bookmarkbar_model_(false),
installed_bookmark_observer_(false),
is_source_readable_(true),
headless_(false),
parent_window_(NULL),
importer_list_(new ImporterList) {
importer_list_->DetectSourceProfiles(observer);
}
ImporterHost::~ImporterHost() {
if (NULL != importer_)
importer_->Release();
if (installed_bookmark_observer_) {
DCHECK(profile_); // Only way for waiting_for_bookmarkbar_model_ to be true
// is if we have a profile.
profile_->GetBookmarkModel()->RemoveObserver(this);
}
}
void ImporterHost::Loaded(BookmarkModel* model) {
DCHECK(model->IsLoaded());
model->RemoveObserver(this);
waiting_for_bookmarkbar_model_ = false;
installed_bookmark_observer_ = false;
importer_->set_import_to_bookmark_bar(!model->HasBookmarks());
InvokeTaskIfDone();
}
void ImporterHost::BookmarkModelBeingDeleted(BookmarkModel* model) {
installed_bookmark_observer_ = false;
}
void ImporterHost::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TEMPLATE_URL_MODEL_LOADED);
registrar_.RemoveAll();
InvokeTaskIfDone();
}
void ImporterHost::ShowWarningDialog() {
if (headless_) {
OnLockViewEnd(false);
} else {
#if defined(OS_WIN)
views::Window::CreateChromeWindow(NULL, gfx::Rect(),
new ImporterLockView(this))->Show();
#elif defined(TOOLKIT_USES_GTK)
ImportLockDialogGtk::Show(parent_window_, this);
#else
ImportLockDialogCocoa::ShowWarning(this);
#endif
}
}
void ImporterHost::OnLockViewEnd(bool is_continue) {
if (is_continue) {
// User chose to continue, then we check the lock again to make
// sure that Firefox has been closed. Try to import the settings
// if successful. Otherwise, show a warning dialog.
firefox_lock_->Lock();
if (firefox_lock_->HasAcquired()) {
is_source_readable_ = true;
InvokeTaskIfDone();
} else {
ShowWarningDialog();
}
} else {
// User chose to skip the import process. We should delete
// the task and notify the ImporterHost to finish.
delete task_;
task_ = NULL;
importer_ = NULL;
ImportEnded();
}
}
void ImporterHost::StartImportSettings(
const importer::ProfileInfo& profile_info,
Profile* target_profile,
uint16 items,
ProfileWriter* writer,
bool first_run) {
DCHECK(!profile_); // We really only support importing from one host at a
// time.
profile_ = target_profile;
// Preserves the observer and creates a task, since we do async import
// so that it doesn't block the UI. When the import is complete, observer
// will be notified.
writer_ = writer;
importer_ = ImporterList::CreateImporterByType(profile_info.browser_type);
// If we fail to create Importer, exit as we cannot do anything.
if (!importer_) {
ImportEnded();
return;
}
importer_->AddRef();
importer_->set_import_to_bookmark_bar(ShouldImportToBookmarkBar(first_run));
importer_->set_bookmark_bar_disabled(first_run);
scoped_refptr<ImporterBridge> bridge(
new InProcessImporterBridge(writer_.get(), this));
task_ = NewRunnableMethod(importer_, &Importer::StartImport,
profile_info, items, bridge);
CheckForFirefoxLock(profile_info, items, first_run);
#if defined(OS_WIN)
// For google toolbar import, we need the user to log in and store their GAIA
// credentials.
if (profile_info.browser_type == importer::GOOGLE_TOOLBAR5) {
if (!toolbar_importer_utils::IsGoogleGAIACookieInstalled()) {
win_util::MessageBox(
NULL,
l10n_util::GetString(IDS_IMPORTER_GOOGLE_LOGIN_TEXT).c_str(),
L"",
MB_OK | MB_TOPMOST);
GURL url("https://www.google.com/accounts/ServiceLogin");
BrowserList::GetLastActive()->AddSelectedTabWithURL(
url, PageTransition::TYPED);
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &ImporterHost::OnLockViewEnd, false));
is_source_readable_ = false;
}
}
#endif
CheckForLoadedModels(items);
AddRef();
InvokeTaskIfDone();
}
void ImporterHost::Cancel() {
if (importer_)
importer_->Cancel();
}
void ImporterHost::SetObserver(Observer* observer) {
observer_ = observer;
}
void ImporterHost::InvokeTaskIfDone() {
if (waiting_for_bookmarkbar_model_ || !registrar_.IsEmpty() ||
!is_source_readable_)
return;
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, task_);
}
void ImporterHost::ImportItemStarted(importer::ImportItem item) {
if (observer_)
observer_->ImportItemStarted(item);
}
void ImporterHost::ImportItemEnded(importer::ImportItem item) {
if (observer_)
observer_->ImportItemEnded(item);
}
void ImporterHost::ImportStarted() {
if (observer_)
observer_->ImportStarted();
}
void ImporterHost::ImportEnded() {
firefox_lock_.reset(); // Release the Firefox profile lock.
if (observer_)
observer_->ImportEnded();
Release();
}
bool ImporterHost::ShouldImportToBookmarkBar(bool first_run) {
bool import_to_bookmark_bar = first_run;
if (profile_ && profile_->GetBookmarkModel()->IsLoaded()) {
import_to_bookmark_bar = (!profile_->GetBookmarkModel()->HasBookmarks());
}
return import_to_bookmark_bar;
}
void ImporterHost::CheckForFirefoxLock(
const importer::ProfileInfo& profile_info, uint16 items, bool first_run) {
if (profile_info.browser_type == importer::FIREFOX2 ||
profile_info.browser_type == importer::FIREFOX3) {
DCHECK(!firefox_lock_.get());
firefox_lock_.reset(new FirefoxProfileLock(profile_info.source_path));
if (!firefox_lock_->HasAcquired()) {
// If fail to acquire the lock, we set the source unreadable and
// show a warning dialog, unless running without UI.
is_source_readable_ = false;
ShowWarningDialog();
}
}
}
void ImporterHost::CheckForLoadedModels(uint16 items) {
// BookmarkModel should be loaded before adding IE favorites. So we observe
// the BookmarkModel if needed, and start the task after it has been loaded.
if ((items & importer::FAVORITES) && !writer_->BookmarkModelIsLoaded()) {
profile_->GetBookmarkModel()->AddObserver(this);
waiting_for_bookmarkbar_model_ = true;
installed_bookmark_observer_ = true;
}
// Observes the TemplateURLModel if needed to import search engines from the
// other browser. We also check to see if we're importing bookmarks because
// we can import bookmark keywords from Firefox as search engines.
if ((items & importer::SEARCH_ENGINES) || (items & importer::FAVORITES)) {
if (!writer_->TemplateURLModelIsLoaded()) {
TemplateURLModel* model = profile_->GetTemplateURLModel();
registrar_.Add(this, NotificationType::TEMPLATE_URL_MODEL_LOADED,
Source<TemplateURLModel>(model));
model->Load();
}
}
}
ExternalProcessImporterHost::ExternalProcessImporterHost()
: items_(0),
import_to_bookmark_bar_(false),
cancelled_(false),
import_process_launched_(false) {
}
ExternalProcessImporterHost::ExternalProcessImporterHost(
ImporterList::Observer* observer)
: ImporterHost(observer),
items_(0),
import_to_bookmark_bar_(false),
cancelled_(false),
import_process_launched_(false) {
}
void ExternalProcessImporterHost::Loaded(BookmarkModel* model) {
DCHECK(model->IsLoaded());
model->RemoveObserver(this);
waiting_for_bookmarkbar_model_ = false;
installed_bookmark_observer_ = false;
// Because the import process is running externally, the decision whether
// to import to the bookmark bar must be stored here so that it can be
// passed to the importer when the import task is invoked.
import_to_bookmark_bar_ = (!model->HasBookmarks());
InvokeTaskIfDone();
}
void ExternalProcessImporterHost::Cancel() {
cancelled_ = true;
if (import_process_launched_)
client_->Cancel();
ImportEnded(); // Tells the observer that we're done, and releases us.
}
void ExternalProcessImporterHost::StartImportSettings(
const importer::ProfileInfo& profile_info,
Profile* target_profile,
uint16 items,
ProfileWriter* writer,
bool first_run) {
DCHECK(!profile_);
profile_ = target_profile;
writer_ = writer;
profile_info_ = &profile_info;
items_ = items;
ImporterHost::AddRef(); // Balanced in ImporterHost::ImportEnded.
import_to_bookmark_bar_ = ShouldImportToBookmarkBar(first_run);
CheckForFirefoxLock(profile_info, items, first_run);
CheckForLoadedModels(items);
InvokeTaskIfDone();
}
void ExternalProcessImporterHost::InvokeTaskIfDone() {
if (waiting_for_bookmarkbar_model_ || !registrar_.IsEmpty() ||
!is_source_readable_ || cancelled_)
return;
// The in-process half of the bridge which catches data from the IPC pipe
// and feeds it to the ProfileWriter. The external process half of the
// bridge lives in the external process -- see ProfileImportThread.
// The ExternalProcessImporterClient created in the next line owns this
// bridge, and will delete it.
InProcessImporterBridge* bridge =
new InProcessImporterBridge(writer_.get(), this);
client_ = new ExternalProcessImporterClient(this, *profile_info_, items_,
bridge, import_to_bookmark_bar_);
import_process_launched_ = true;
client_->Start();
}
ExternalProcessImporterClient::ExternalProcessImporterClient(
ExternalProcessImporterHost* importer_host,
const importer::ProfileInfo& profile_info,
int items,
InProcessImporterBridge* bridge,
bool import_to_bookmark_bar)
: bookmarks_options_(0),
total_bookmarks_count_(0),
total_history_rows_count_(0),
total_fav_icons_count_(0),
process_importer_host_(importer_host),
profile_import_process_host_(NULL),
profile_info_(profile_info),
items_(items),
import_to_bookmark_bar_(import_to_bookmark_bar),
bridge_(bridge),
cancelled_(FALSE) {
bridge_->AddRef();
process_importer_host_->ImportStarted();
}
ExternalProcessImporterClient::~ExternalProcessImporterClient() {
bridge_->Release();
}
void ExternalProcessImporterClient::Start() {
AddRef(); // balanced in Cleanup.
BrowserThread::ID thread_id;
CHECK(BrowserThread::GetCurrentThreadIdentifier(&thread_id));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&ExternalProcessImporterClient::StartProcessOnIOThread,
g_browser_process->resource_dispatcher_host(), thread_id));
}
void ExternalProcessImporterClient::StartProcessOnIOThread(
ResourceDispatcherHost* rdh,
BrowserThread::ID thread_id) {
profile_import_process_host_ =
new ProfileImportProcessHost(rdh, this, thread_id);
profile_import_process_host_->StartProfileImportProcess(profile_info_,
items_, import_to_bookmark_bar_);
}
void ExternalProcessImporterClient::Cancel() {
if (cancelled_)
return;
cancelled_ = true;
if (profile_import_process_host_) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&ExternalProcessImporterClient::CancelImportProcessOnIOThread));
}
Release();
}
void ExternalProcessImporterClient::CancelImportProcessOnIOThread() {
profile_import_process_host_->CancelProfileImportProcess();
}
void ExternalProcessImporterClient::NotifyItemFinishedOnIOThread(
importer::ImportItem import_item) {
profile_import_process_host_->ReportImportItemFinished(import_item);
}
void ExternalProcessImporterClient::OnProcessCrashed(int exit_code) {
if (cancelled_)
return;
process_importer_host_->Cancel();
}
void ExternalProcessImporterClient::Cleanup() {
if (cancelled_)
return;
if (process_importer_host_)
process_importer_host_->ImportEnded();
Release();
}
void ExternalProcessImporterClient::OnImportStart() {
if (cancelled_)
return;
bridge_->NotifyStarted();
}
void ExternalProcessImporterClient::OnImportFinished(bool succeeded,
std::string error_msg) {
if (cancelled_)
return;
if (!succeeded)
LOG(WARNING) << "Import failed. Error: " << error_msg;
Cleanup();
}
void ExternalProcessImporterClient::OnImportItemStart(int item_data) {
if (cancelled_)
return;
bridge_->NotifyItemStarted(static_cast<importer::ImportItem>(item_data));
}
void ExternalProcessImporterClient::OnImportItemFinished(int item_data) {
if (cancelled_)
return;
importer::ImportItem import_item =
static_cast<importer::ImportItem>(item_data);
bridge_->NotifyItemEnded(import_item);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&ExternalProcessImporterClient::NotifyItemFinishedOnIOThread,
import_item));
}
void ExternalProcessImporterClient::OnHistoryImportStart(
size_t total_history_rows_count) {
if (cancelled_)
return;
total_history_rows_count_ = total_history_rows_count;
history_rows_.reserve(total_history_rows_count);
}
void ExternalProcessImporterClient::OnHistoryImportGroup(
const std::vector<history::URLRow>& history_rows_group,
int visit_source) {
if (cancelled_)
return;
history_rows_.insert(history_rows_.end(), history_rows_group.begin(),
history_rows_group.end());
if (history_rows_.size() == total_history_rows_count_)
bridge_->SetHistoryItems(history_rows_,
static_cast<history::VisitSource>(visit_source));
}
void ExternalProcessImporterClient::OnHomePageImportReady(
const GURL& home_page) {
if (cancelled_)
return;
bridge_->AddHomePage(home_page);
}
void ExternalProcessImporterClient::OnBookmarksImportStart(
const std::wstring first_folder_name,
int options, size_t total_bookmarks_count) {
if (cancelled_)
return;
bookmarks_first_folder_name_ = first_folder_name;
bookmarks_options_ = options;
total_bookmarks_count_ = total_bookmarks_count;
bookmarks_.reserve(total_bookmarks_count);
}
void ExternalProcessImporterClient::OnBookmarksImportGroup(
const std::vector<ProfileWriter::BookmarkEntry>& bookmarks_group) {
if (cancelled_)
return;
// Collect sets of bookmarks from importer process until we have reached
// total_bookmarks_count_:
bookmarks_.insert(bookmarks_.end(), bookmarks_group.begin(),
bookmarks_group.end());
if (bookmarks_.size() == total_bookmarks_count_) {
bridge_->AddBookmarkEntries(bookmarks_, bookmarks_first_folder_name_,
bookmarks_options_);
}
}
void ExternalProcessImporterClient::OnFavIconsImportStart(
size_t total_fav_icons_count) {
if (cancelled_)
return;
total_fav_icons_count_ = total_fav_icons_count;
fav_icons_.reserve(total_fav_icons_count);
}
void ExternalProcessImporterClient::OnFavIconsImportGroup(
const std::vector<history::ImportedFavIconUsage>& fav_icons_group) {
if (cancelled_)
return;
fav_icons_.insert(fav_icons_.end(), fav_icons_group.begin(),
fav_icons_group.end());
if (fav_icons_.size() == total_fav_icons_count_)
bridge_->SetFavIcons(fav_icons_);
}
void ExternalProcessImporterClient::OnPasswordFormImportReady(
const webkit_glue::PasswordForm& form) {
if (cancelled_)
return;
bridge_->SetPasswordForm(form);
}
void ExternalProcessImporterClient::OnKeywordsImportReady(
const std::vector<TemplateURL>& template_urls,
int default_keyword_index, bool unique_on_host_and_path) {
if (cancelled_)
return;
std::vector<TemplateURL*> template_url_vec;
template_url_vec.reserve(template_urls.size());
std::vector<TemplateURL>::const_iterator iter;
for (iter = template_urls.begin();
iter != template_urls.end();
++iter) {
template_url_vec.push_back(new TemplateURL(*iter));
}
bridge_->SetKeywords(template_url_vec, default_keyword_index,
unique_on_host_and_path);
}
| 31.342488 | 80 | 0.727231 | [
"vector",
"model"
] |
637e528808d595c37ad57131f149479ab891700b | 3,648 | cpp | C++ | 2017/22/main.cpp | adrian-stanciu/adventofcode | 47b3d12226b0c71fff485ef140cd7731c9a5d72f | [
"MIT"
] | null | null | null | 2017/22/main.cpp | adrian-stanciu/adventofcode | 47b3d12226b0c71fff485ef140cd7731c9a5d72f | [
"MIT"
] | null | null | null | 2017/22/main.cpp | adrian-stanciu/adventofcode | 47b3d12226b0c71fff485ef140cd7731c9a5d72f | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
enum State {
Clean = 0,
Weakened,
Infected,
Flagged,
};
auto read_grid()
{
std::vector<std::string> grid;
std::string line;
while (getline(std::cin, line))
grid.push_back(std::move(line));
return grid;
}
std::string stringify(long r, long c)
{
std::stringstream ss;
ss << r;
ss << ";";
ss << c;
return ss.str();
}
auto grid_to_map1(const std::vector<std::string>& grid)
{
std::unordered_map<std::string, bool> map;
auto mid_r = grid.size() / 2;
auto mid_c = grid[mid_r].size() / 2;
for (auto i = 0U; i < grid.size(); ++i)
for (auto j = 0U; j < grid[i].size(); ++j)
map[stringify(mid_r - i, j - mid_c)] = (grid[i][j] == '#');
return map;
}
long count_turned_infected1(const std::vector<std::string>& grid,
long r, long c, long r_dir, long c_dir, size_t iters)
{
std::unordered_map<std::string, bool> map = grid_to_map1(grid);
long turned_infected = 0;
for (size_t i = 0; i < iters; ++i) {
auto& infected = map[stringify(r, c)];
if (infected) {
// turn right
if (r_dir != 0) {
c_dir = r_dir;
r_dir = 0;
} else {
r_dir = -c_dir;
c_dir = 0;
}
} else {
// turn left
if (r_dir != 0) {
c_dir = -r_dir;
r_dir = 0;
} else {
r_dir = c_dir;
c_dir = 0;
}
++turned_infected;
}
infected = !infected;
r += r_dir;
c += c_dir;
}
return turned_infected;
}
auto grid_to_map2(const std::vector<std::string>& grid)
{
std::unordered_map<std::string, State> map;
auto mid_r = grid.size() / 2;
auto mid_c = grid[mid_r].size() / 2;
for (auto i = 0U; i < grid.size(); ++i)
for (auto j = 0U; j < grid[i].size(); ++j)
map[stringify(mid_r - i, j - mid_c)] =
(grid[i][j] == '#') ? Infected : Clean;
return map;
}
long count_turned_infected2(const std::vector<std::string>& grid,
long r, long c, long r_dir, long c_dir, size_t iters)
{
std::unordered_map<std::string, State> map = grid_to_map2(grid);
long turned_infected = 0;
for (size_t i = 0; i < iters; ++i) {
auto& state = map[stringify(r, c)];
switch (state) {
case Clean:
// turn left
if (r_dir != 0) {
c_dir = -r_dir;
r_dir = 0;
} else {
r_dir = c_dir;
c_dir = 0;
}
state = Weakened;
break;
case Weakened:
// no turn
++turned_infected;
state = Infected;
break;
case Infected:
// turn right
if (r_dir != 0) {
c_dir = r_dir;
r_dir = 0;
} else {
r_dir = -c_dir;
c_dir = 0;
}
state = Flagged;
break;
case Flagged:
// turn back
r_dir = -r_dir;
c_dir = -c_dir;
state = Clean;
break;
}
r += r_dir;
c += c_dir;
}
return turned_infected;
}
int main()
{
auto grid = read_grid();
std::cout << count_turned_infected1(grid, 0, 0, 1, 0, 10000) << "\n";
std::cout << count_turned_infected2(grid, 0, 0, 1, 0, 10000000) << "\n";
return 0;
}
| 21.585799 | 76 | 0.467654 | [
"vector"
] |
638910cc4b9c72d265a3d5f2a727d660a0234a15 | 59,106 | cxx | C++ | model_server/ui_viewer/src/miniBrowser.h.cxx | kit-transue/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 2 | 2015-11-24T03:31:12.000Z | 2015-11-24T16:01:57.000Z | model_server/ui_viewer/src/miniBrowser.h.cxx | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | null | null | null | model_server/ui_viewer/src/miniBrowser.h.cxx | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 1 | 2019-05-19T02:26:08.000Z | 2019-05-19T02:26:08.000Z | /*************************************************************************
* Copyright (c) 2015, Synopsys, Inc. *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: *
* *
* 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 *
* 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 <XrefQuery.h>
#include <cLibraryFunctions.h>
#include <msg.h>
#include <genError.h>
#include <systemMessages.h>
#include <gtShell.h>
#include <gtForm.h>
#include <objOper.h>
#include <RTL.h>
#include <symbolPtr.h>
#include <proj.h>
#include <ddict.h>
#include <path.h>
#include <closure.h>
#include <Interpreter.h>
#include <SetsUI.h>
#include <gtBaseXm.h>
#include <gtArrowButton.h>
#include <gtPanedWindow.h>
#include <gtNoParent.h>
#include <gtTogB.h>
#include <gtRadioBox.h>
#include <gtPushButton.h>
#include <gtStringEd.h>
#include <gtRTL.h>
#include <gtCascadeB.h>
#include <gtPDMenu.h>
#include <gtMenuBar.h>
#include <gtSepar.h>
#include <gtOptionMenu.h>
#include <gtBitmap.h>
#include <Xm/RowColumn.h>
#include <Xm/Separator.h>
#include <Xm/LabelG.h>
#include <Xm/Text.h>
#include <Xm/Form.h>
#include <Xm/PushB.h>
#include <Question.h>
#include <viewerShell.h>
#include <ste_interface.h>
#include <browserShell.h>
#include <top_widgets.h>
#include <view_creation.h>
#include <driver.h>
#include <X11/StringDefs.h>
#include <xref_queries.h>
#include <miniBrowser.h>
#include <instanceBrowser.h>
#include <dd_utils.h>
#ifndef _groupHdr_h
#include <groupHdr.h>
#endif
#include <LanguageController.h>
#include <BrowserController.h>
#include <BrowserData.h>
#include <cliUI.h>
#include <Interpreter.h>
#define mb_on_width 16
#define mb_on_height 16
static char mb_on_bits[] = {
0xf8, 0x1f, 0xf8, 0x1f, 0x08, 0x10, 0x08, 0x10, 0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10, 0x58, 0x15, 0x08, 0x10, 0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10, 0x08, 0x10, 0xf8, 0x1f};
#define mb_off_width 16
#define mb_off_height 16
static char mb_off_bits[] = {
0xf8, 0x9f, 0xf8, 0x5f, 0x08, 0x30, 0x08, 0x10, 0x08, 0x18, 0x08, 0x14,
0x08, 0x12, 0x08, 0x11, 0xd8, 0x15, 0x48, 0x10, 0x28, 0x10, 0x18, 0x10,
0x08, 0x10, 0x0c, 0x10, 0x0a, 0x10, 0xf9, 0x1f};
extern projModulePtr projModule_of_symbol(symbolPtr& sym);
extern "C" void vs_display_mini_browser(Widget, int);
extern "C" void fill_selected_objects (symbolArr *selection); // ProjectQuery.C
// ProjectQuery.C
extern int save_array_into_file(symbolArr &array, FILE *svfp);
class FileNameDlg {
public:
FileNameDlg(RTL *r);
~FileNameDlg();
private:
static void ok_CB(gtPushButton*, gtEventPtr, void*, gtReason);
static void cancel_CB(gtPushButton*, gtEventPtr, void*, gtReason);
gtDialogTemplate *dlg;
gtStringEditor *file_name;
gtToggleButton *toggle;
RTL *rtl_to_write;
};
genArr(miniBrowserPtr);
static genArrOf(miniBrowserPtr) miniBrowser_instances;
class ProjectController : public miniBrowserRTL_API {
public:
ProjectController(projNode *node, miniBrowser *browser);
~ProjectController();
virtual void make_own_buttons(gtBase *parent, gtRTL *, RTL *rtl);
virtual void rtl_out_of_scope(RTL *rtl);
private:
static void UpButton(gtPushButton*, gtEvent*, void* pc, gtReason);
projNode *node;
miniBrowser *browser;
};
class ListHistoryEntry : public Obj {
public:
~ListHistoryEntry();
RTL *rtl;
int top_position;
int list_number; // Used to put it in the original list during remove operation
};
class RTLGarbager : public Relational {
public:
RTLGarbager() {} ;
};
defrel_many_to_many(RTLGarbager,trash_can,RTL,rtl);
init_rel_or_ptr(RTLGarbager,trash_can, 0,RTL,rtl, 0);
init_rel_or_ptr(miniBrowserRTL_API,APIhandler, relationMode::D,RTL,rtl, 0);
RTLGarbager garbage;
RTLGarbager controlled_rtls;
static GC miniBrowser_GC;
static int miniBrowser_gc_initialized = 0;
static Dimension miniBrowser_height;
static int miniBrowser_button_x;
static int miniBrowser_xdiff;
static int do_dragging = 0;
typedef struct {
Widget button;
Widget separator;
Dimension width;
int sep_pos;
int button_pos;
} miniBrowser_event_data;
//---------------------------------------------------------------
static RTL *copy_create_rtl(RTL *src_rtl)
{
Initialize(copy_rtl);
if(!src_rtl)
return NULL;
RTLNodePtr old_node = checked_cast(RTLNode, src_rtl->get_root());
// Create & copy rtl to new one to allow later deletion.
RTL *new_rtl = db_new(RTL, (NULL));
new_rtl->set_name(src_rtl->get_name());
new_rtl->set_phys_name(src_rtl->get_phys_name());
RTLNodePtr rtl_node = checked_cast(RTLNode, new_rtl->get_root());
symbolArr old_contents = old_node->rtl_contents();
for(int i = 0; i < old_contents.size(); i++){
rtl_node->rtl_insert(old_contents[i]);
}
return new_rtl;
}
void handle_rtl_deletion(RTL *rtl)
{
Initialize(handle_rtl_deletion);
objSet cans = rtl_get_trash_cans(rtl);
Obj *ob;
ForEach(ob, cans){
RTLGarbager *can = (RTLGarbager *)ob;
// Delete rtl if it was created by ourselfs
if(can == &garbage){
miniBrowserRTL_API *api = rtl_get_APIhandler(rtl);
if(api){
if(api->rtl_dying(rtl)){ // Ok to delete rtl
obj_unload(rtl);
break;
}
}else{
obj_unload(rtl);
break;
}
}else
if(can == &controlled_rtls){
trash_can_rem_rtl(&controlled_rtls, rtl);
}
}
}
//---------------------------------------------------------------
ProjectController::ProjectController(projNode *p_node, miniBrowser *p_browser)
{
this->node = p_node;
this->browser = p_browser;
}
ProjectController::~ProjectController()
{
// printf("ProjectController dying.\n");
// OSapi_fflush(stdout);
}
void ProjectController::rtl_out_of_scope(RTL *)
{
Initialize(ProjectController::rtl_out_of_scope);
// Since nothing to control anymore delete itself
delete this;
}
void ProjectController::make_own_buttons(gtBase *parent, gtRTL *, RTL *rtl)
{
Initialize(ProjectController::make_own_buttons);
if(rtl != projNode::get_project_rtl()){
gtPushButton *up_button = gtPushButton::create(parent, "up_button", "Up",
ProjectController::UpButton, this);
add_button(up_button);
}
}
void ProjectController::UpButton(gtPushButton*, gtEvent*, void* data, gtReason)
{
Initialize(ProjectController::UpButton);
ProjectController *pc = (ProjectController *)data;
if(!pc->node)
return;
projNode *parent_node = (projNode *)get_relation(parentProject_of_childProject, pc->node);
if(!parent_node){
RTL *rtl = projNode::get_project_rtl();
pc->browser->browse(rtl);
return;
}
projHeader *header = checked_cast(projHeader, parent_node->get_header());
if(!header)
return;
ProjectController *new_pc = new ProjectController(parent_node, pc->browser);
APIhandler_put_rtl(new_pc, header);
pc->browser->browse(header);
}
//---------------------------------------------------------------
ListHistoryEntry::~ListHistoryEntry()
{
handle_rtl_deletion(rtl);
}
//---------------------------------------------------------------
FileNameDlg::FileNameDlg(RTL *r)
{
Initialize(FileNameDlg::FileNameDlg);
rtl_to_write = r;
// Create the dialog.
dlg = gtDialogTemplate::create(NULL, "new_file", TXT("Write List"));
dlg->add_button("ok", TXT("OK"), ok_CB, this);
dlg->add_button("cancel", TXT("Cancel"), cancel_CB, this);
// dlg->add_help_button();
// dlg->help_context_name("Browser.File.NewFile.Help");
// Create the directory label.
gtLabel* label = gtLabel::create(dlg, "label", TXT("Enter file name:"));
label->alignment(gtBeginning);
label->attach(gtLeft);
label->attach(gtRight);
label->attach(gtTop);
label->manage();
// Create the directory answer text box.
file_name = gtStringEditor::create(dlg, "answer", NULL);
const int file_columns = 35; // max(30, strlen(current_name) + 15);
file_name->columns(file_columns);
file_name->attach(gtTop, label, 10);
file_name->attach(gtLeft);
file_name->attach(gtRight);
file_name->manage();
toggle = gtToggleButton::create(dlg, "toggle", "Logical/Physical name", NULL, NULL);
toggle->attach(gtTop, file_name, 10);
toggle->attach(gtLeft);
toggle->set(1, 0);
toggle->manage();
dlg->popup(1);
dlg->set_default_parent(NULL);
}
void FileNameDlg::ok_CB(gtPushButton*, gtEventPtr, void* data, gtReason)
{
Initialize(FileNameDlg::ok_CB);
FileNameDlg* fd = (FileNameDlg*)data;
char* file_name = fd->file_name->text();
genString full_name, mod_ln;
projNode* home = projNode::get_home_proj();
if(!fd->toggle->set()){
project_convert_filename(file_name, full_name);
home->fn_to_ln(full_name, mod_ln, FILE_TYPE, 0, 1);
}else{
home->ln_to_fn_imp(file_name, full_name, FILE_TYPE, 0, 1);
if(!full_name.length()){
msg("Unable to convert logical name into physical path.", error_sev) << eom;
return;
}
home->fn_to_ln(full_name, mod_ln, FILE_TYPE, 0, 1);
}
if (!mod_ln.length()){
genString msg;
msg.printf("No mapping for %s in pdf file.", (char *)full_name);
gtPushButton::next_help_context("Pset.Help.Groups.NoMapping");
int answer = popup_Question("Write", (const char *)msg.str(), "Save anyway", "Cancel");
if(answer != 1){
gtFree(file_name);
return;
}
}else{
projModule *module;
if (home->is_script())
{
projNode::create_global_script_modules(full_name, FILE_LANGUAGE_UNKNOWN, 0);
module = home->find_module(mod_ln);
}else
module = home->make_module(mod_ln);
if(module)
module->update_module();
}
FILE *svfp = OSapi_fopen((char *)full_name, "w");
if (!svfp) {
msg("Unable to create file: $1", error_sev) << file_name << eom;
gtFree(file_name);
return;
}
RTLNodePtr rtl_node = checked_cast(RTLNode, fd->rtl_to_write->get_root());
symbolArr& contents = rtl_node->rtl_contents();
save_array_into_file(contents, svfp);
OSapi_fclose(svfp);
gtFree(file_name);
delete fd;
}
FileNameDlg::~FileNameDlg()
{
delete dlg;
}
void FileNameDlg::cancel_CB(gtPushButton*, gtEventPtr, void* data, gtReason)
{
Initialize(FileNameDlg::cancel_CB);
delete (FileNameDlg*)data;
}
//---------------------------------------------------------------
miniBrowserRTL_API::miniBrowserRTL_API()
{
list = NULL;
}
void miniBrowserRTL_API::selection_callback(RTL *, symbolArr&, miniBrowser *)
{
}
int miniBrowserRTL_API::action_callback(RTL *, symbolArr&, miniBrowser *)
{
return 1;
}
int miniBrowserRTL_API::rtl_dying(RTL *)
{
return 1;
}
void miniBrowserRTL_API::rtl_out_of_scope(RTL *)
{
}
char *miniBrowserRTL_API::get_sort_spec(RTL *)
{
return NULL;
}
int miniBrowserRTL_API::need_vcr_control(RTL *)
{
return 0;
}
void miniBrowserRTL_API::make_own_buttons(gtBase *, gtRTL *, RTL *)
{
}
void miniBrowserRTL_API::set_list(gtList *l)
{
list = l;
}
void miniBrowserRTL_API::add_button(gtPrimitive *prim)
{
if(list){
list->add_button(prim);
}
}
gtBase *miniBrowserRTL_API::get_button_control(void)
{
if(list)
return list->get_button_form();
else
return NULL;
}
// --------------------------------------------------------------
miniBrowser::miniBrowser(void *parent_menu, void *parent_icon_place, void *parent)
{
Initialize(miniBrowser);
displayed = 1;
parent_viewershell = parent;
gtNoParent *parent_icon = gtNoParent::create(parent_icon_place);
gtBitmap *icon_on = gtBitmap::create(parent_icon, "browser_on", mb_on_bits, mb_on_width, mb_on_height);
gtBitmap *icon_off = gtBitmap::create(parent_icon, "browser_off", mb_off_bits, mb_off_width, mb_off_height);
icon_on->manage();
icon_off->manage();
on_button = gtPushButton::create(parent_icon, "icon_on", icon_on,
ToggleBrowser, this);
on_button->width(29);
on_button->height(29);
on_button->attach(gtLeft);
on_button->attach(gtTop);
on_button->attach(gtBottom);
on_button->attach(gtRight);
on_button->manage();
off_button = gtPushButton::create(parent_icon, "icon_off", icon_off,
ToggleBrowser, this);
off_button->width(29);
off_button->height(29);
off_button->attach(gtLeft);
off_button->attach(gtTop);
off_button->attach(gtBottom);
off_button->attach(gtRight);
mainForm = gtForm::create((Widget)parent, "mini_main");
mainForm->attach(gtTop);
mainForm->attach(gtBottom);
mainForm->attach(gtLeft);
mainForm->attach(gtRight);
mainForm->manage();
gtMenuBar *menubar = gtMenuBar::create(mainForm, "query_menu");
menubar->attach(gtTop);
menubar->attach(gtLeft);
menubar->attach(gtRight);
menubar->manage();
gtNoParent *parent_menubar = gtNoParent::create(parent_menu);
/*
gtCascadeButton* popup_browser = gtCascadeButton::create(
parent_menubar, "popup_browser", TXT("Minibrowser(ON) "), PopupBrowser, this);
popup_browser->manage();
*/
query_menu = gtCascadeButton::create(menubar, "query", TXT("Query"), NULL, NULL);
num_queries = 0;
query_menu->pulldown_menu("query_pulldown", gtMenuNull);
query_menu->event_handler(EnterWindowMask, FALSE,
(gtEventHandler) update_query_menu_CB, this);
query_menu->insert_entries(-1, gtMenuCheck, "closure", TXT("Closure"), this,
closure_CB, gtMenuNull);
pBController = LanguageController::GetBrowserController();
closure_button = (gtToggleButton*) query_menu->entry(0);
closure_button->set(get_closure_state(), 0);
query_menu->manage();
history_button = gtCascadeButton::create(menubar, "history", TXT("History"), NULL, NULL);
history_button->pulldown_menu("history_pulldown",
gtMenuNull);
history_button->manage();
group_button = gtCascadeButton::create(menubar, "group", TXT("Group"),
NULL, NULL);
// (gtCascadeCB)GroupButton, this);
group_button->pulldown_menu("group_pulldown",
gtMenuStandard, "group_create", TXT("Create Group"), this, GroupButton,
gtMenuStandard, "group_create", TXT("Group Manager"), this, GroupManagerButton,
// gtMenuStandard, "list_save_top", TXT("Write top list..."), this, SaveList1_CB,
// gtMenuStandard, "list_save_bottom", TXT("Write bottom list..."), this, SaveList2_CB,
gtMenuNull);
group_button->manage();
gtSeparator* separ = gtSeparator::create(mainForm, "sep", gtHORZ);
separ->attach(gtLeft);
separ->attach(gtRight);
separ->attach(gtTop, menubar, 3);
separ->manage();
paned = gtPanedWindow::create(mainForm, "paned_window");
paned->attach(gtTop, separ, 3);
paned->attach(gtLeft);
paned->attach(gtRight);
paned->attach(gtBottom);
paned->width(100);
paned->manage();
list1Form = gtForm::create(paned, "list_1_form");
list1Form->attach(gtTop);
list1Form->attach(gtLeft);
list1Form->attach(gtRight);
list1Form->manage();
// list1 = gtRTL::create(paned, "list_1", " ", gtExtended, NULL, 0);
list1 = gtRTL::create(list1Form, "list_1", " ", gtExtended, NULL, 0);
list1->handle_special_buttons(1);
list1->action_callback(list1_action, this);
list1->select_callback(list1_select, this);
list1->attach(gtLeft);
list1->attach(gtRight);
list1->attach(gtTop);
list1->attach(gtBottom);
list1->num_rows(8);
list1->manage();
RTLPtr rtl = projNode::get_project_rtl();
// RTLPtr new_rtl = copy_create_rtl(rtl);
RTLPtr new_rtl = rtl;
new_rtl->set_name("Top Level Projects");
list1->set_rtl(new_rtl);
add_rtl_to_history(new_rtl, 1);
title1("Top Level Projects");
selected_list = list1;
list2Form = gtForm::create(paned, "list_1_form");
list2Form->attach(gtTop);
list2Form->attach(gtLeft);
list2Form->attach(gtRight);
// list2 = gtRTL::create(paned, "list_2", " ", gtExtended, NULL, 0);
list2 = gtRTL::create(list2Form, "list_2", " ", gtExtended, NULL, 0);
list2->handle_special_buttons(1);
list2->action_callback(list2_action, this);
list2->select_callback(list2_select, this);
list2->attach(gtTop);
list2->attach(gtLeft);
list2->attach(gtRight);
list2->attach(gtBottom);
list2->manage();
Dimension height;
XtVaGetValues(paned->container()->rep()->widget(), XmNheight, &height, NULL);
XtVaSetValues(list2Form->rep()->widget(), XmNpaneMinimum, height / 2, NULL);
list2Form->manage();
XtVaSetValues(list2Form->rep()->widget(), XmNpaneMinimum, 100, NULL);
// XtVaSetValues(list2->container()->rep()->widget(), XmNpaneMinimum, height / 2, NULL);
// list2->manage();
// XtVaSetValues(list2->container()->rep()->widget(), XmNpaneMinimum, 100, NULL);
list1_prev_rtl = NULL;
list2_prev_rtl = NULL;
unmanaged_list = NULL;
new_form = NULL;
form_cleanup_callback = NULL;
cleanup_callback_data = NULL;
miniBrowserPtr p = this;
miniBrowser_instances.append(&p);
}
miniBrowser::~miniBrowser()
{
if(unmanaged_list == NULL){
if(form_cleanup_callback)
form_cleanup_callback(this, cleanup_callback_data);
restore_list();
}
int i;
for(i = 0; i < miniBrowser_instances.size(); i++){
miniBrowser *mb = *miniBrowser_instances[i];
if(mb == this){
miniBrowser_instances.remove(i);
break;
}
}
/* This code will not work... but it\'s good explanation that is going on below
RTL *rtl = list1->RTL();
if(rtl)
handle_rtl_deletion(rtl);
rtl = list2->RTL();
if(rtl)
handle_rtl_deletion(rtl);
*/
list1 = NULL;
list2 = NULL;
for(i = 0; i < history_list.size(); i++){
ListHistoryEntry *entry = (ListHistoryEntry *)history_list[i];
report_out_of_scope(entry->rtl);
delete entry;
}
objSet rtls = trash_can_get_rtls(&garbage);
ObjPtr ob;
ForEach(ob, rtls){
RTL *rtl = (RTL *)ob;
handle_rtl_deletion(rtl);
}
// Get the rest of rtls wich was controlled but slip throught other method\'s of notification.
rtls = trash_can_get_rtls(&controlled_rtls);
ObjPtr ob1;
ForEach(ob1, rtls){
RTL *rtl = (RTL *)ob1;
report_out_of_scope(rtl);
}
}
void miniBrowser::refresh(void)
{
symbolArr list1sel, list2sel;
if(unmanaged_list != list1){
list1->app_nodes (&list1sel);
list1->regenerate_rtl(list1->RTL(), 1, 2);
list1->post_selection (list1sel, false);
}
if(unmanaged_list != list2){
list2->app_nodes (&list2sel);
list2->regenerate_rtl(list2->RTL(), 1, 2);
list2->post_selection (list2sel, false);
}
}
void miniBrowser::title1(char *txt)
{
if(customize::miniBrowser_show_titles())
list1->gt_list()->get_label()->text(txt);
else
list1->gt_list()->get_label()->text("");
}
void miniBrowser::title2(char *txt)
{
if(customize::miniBrowser_show_titles())
list2->gt_list()->get_label()->text(txt);
else
list2->gt_list()->get_label()->text("");
}
void miniBrowser::visible(int flag)
{
Initialize(miniBrowser::visible);
displayed = flag;
if(!displayed)
clear_selection();
}
int miniBrowser::visible(void)
{
Initialize(miniBrowser::visible);
return displayed;
}
gtBase *miniBrowser::get_paned_window()
{
Initialize(miniBrowser::get_paned_window);
return paned;
}
gtBase *miniBrowser::get_main_form()
{
Initialize(miniBrowser::get_main_form);
return mainForm;
}
// Inserts form into minibrowser paned window
void miniBrowser::manage_into_paned_form(gtForm *form, int preffered_height)
{
Initialize(miniBrowser::manage_into_paned_form);
if(!form)
return;
if(preffered_height){
XtVaSetValues(form->container()->rep()->widget(), XmNpaneMinimum, preffered_height, NULL);
form->manage();
XtVaSetValues(form->container()->rep()->widget(), XmNpaneMinimum, 100, NULL);
}else
form->manage();
}
void miniBrowser::manage_into_main_form(gtForm *form)
{
Initialize(miniBrowser::manage_into_main_form);
if(!form)
return;
form->attach(gtLeft);
form->attach(gtRight);
form->attach(gtBottom);
form->manage();
paned->attach(gtBottom, form);
}
void miniBrowser::write_list(gtRTL *list)
{
Initialize(miniBrowser::write_list);
if(list->RTL()){
RTLNodePtr rtl_node = checked_cast(RTLNode, list->RTL()->get_root());
if(rtl_node && rtl_node->rtl_contents().size() != 0){
FileNameDlg *dlg = new FileNameDlg(list->RTL());
return;
}
}
msg("The list is empty.", warning_sev) << eom;
}
void *miniBrowser::get_cleanup_form_data(void)
{
return cleanup_callback_data;
}
void miniBrowser::set_list_cleanup_form(FormCleanupCallbackProc proc, void *data)
{
form_cleanup_callback = proc;
cleanup_callback_data = data;
}
// Unmanages list from form. list == 0 - top list list != 0 bottom list
// Create new form for elememt placing and return it
gtForm *miniBrowser::unmanage_list(int list)
{
gtForm *list_form;
if(list == 0){
list1->unmanage();
list1->detach(gtTop);
list1->detach(gtBottom);
list1->detach(gtLeft);
list1->detach(gtRight);
unmanaged_list = list1;
list_form = list1Form;
} else {
list2->unmanage();
list2->detach(gtTop);
list2->detach(gtBottom);
list2->detach(gtLeft);
list2->detach(gtRight);
unmanaged_list = list2;
list_form = list2Form;
}
new_form = gtForm::create(list_form, "temp_form");
new_form->attach(gtTop);
new_form->attach(gtLeft);
new_form->attach(gtRight);
new_form->attach(gtBottom);
new_form->manage();
return new_form;
}
int miniBrowser::restore_list(void)
{
int ret_val = -1;
if(new_form){
new_form->unmanage();
new_form->detach(gtTop);
new_form->detach(gtLeft);
new_form->detach(gtRight);
new_form->detach(gtBottom);
delete new_form;
new_form = NULL;
}
if(unmanaged_list == list1){
list1->attach(gtTop);
list1->attach(gtBottom);
list1->attach(gtLeft);
list1->attach(gtRight);
list1->manage();
ret_val = 0;
} else if (unmanaged_list == list2) {
list2->attach(gtTop);
list2->attach(gtBottom);
list2->attach(gtLeft);
list2->attach(gtRight);
list2->manage();
ret_val = 1;
}
unmanaged_list = NULL;
return ret_val;
}
void miniBrowser::SaveList1_CB(gtPushButton*, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::SaveList1_CB);
miniBrowser *browser = (miniBrowser *)mb;
browser->write_list(browser->list1);
}
void miniBrowser::SaveList2_CB(gtPushButton*, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::SaveList2_CB);
miniBrowser *browser = (miniBrowser *)mb;
browser->write_list(browser->list2);
}
void miniBrowser::history_CB(gtPushButton* b, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::history_CB);
miniBrowser *browser = (miniBrowser *)mb;
ListHistoryEntry *entry = (ListHistoryEntry *)b->userData();
if(!entry)
return;
// Special case for top level projects ! Always get them from project node.
if(entry == browser->history_list[0]){
RTLPtr rtl = projNode::get_project_rtl();
RTLPtr new_rtl = rtl;
new_rtl->set_name("Top Level Projects");
browser->browse(new_rtl, 1);
}else{
RTLPtr rtl = entry->rtl;
RTLPtr new_rtl = rtl;
objSet cans = rtl_get_trash_cans(rtl);
if(cans.includes(&garbage)){
// This rtl suppose to be deleted later, so create a copy and forget about this object
new_rtl = copy_create_rtl(rtl);
trash_can_put_rtl(&garbage, new_rtl);
}
miniBrowserRTL_API *api = rtl_get_APIhandler(rtl);
if(api){
if(new_rtl != rtl)
APIhandler_put_rtl(api, new_rtl);
}
browser->browse(new_rtl, entry->top_position);
}
/*
gtForm *f = gtForm::create(browser->get_main_form(), "test");
gtPushButton *b = gtPushButton::create(f, "ttt", TXT("OPTIONS"), NULL, NULL);
b->attach(gtLeft);
b->attach(gtRight);
b->attach(gtTop);
// b->attach(gtBottom);
b->manage();
browser->manage_into_main_form(f);
*/
}
void miniBrowser::report_out_of_scope(RTLPtr rtl)
// Report to API that rtl goes out of scope if it not displayed anywhere in minibrowser
{
Initialize(miniBrowser::report_out_of_scope);
miniBrowserRTL_API *api = rtl_get_APIhandler(rtl);
if(!api)
return;
if(!list1 || !list2)
api->rtl_out_of_scope(rtl);
else
if(list1->RTL() != rtl && list2->RTL() != rtl)
api->rtl_out_of_scope(rtl);
}
void miniBrowser::remove_from_history(RTLPtr rtl)
{
Initialize(miniBrowser::remove_from_history);
for(int i = 1; i < history_list.size(); i++){
ListHistoryEntry *entry = (ListHistoryEntry *)history_list[i];
if(entry->rtl == rtl){
// Shift list & remove buttons
int j;
for(j = i; j < history_list.size() - 1; j++){
history_button->remove_entry(i);
history_list[j] = history_list[j + 1];
}
history_button->remove_entry(i);
// Put buttons back
for(j = i; j < history_list.size() - 1; j++){
ListHistoryEntry *entry = (ListHistoryEntry *)history_list[j];
RTLPtr el = entry->rtl;
char *name = el->get_phys_name();
if(!name || name[0] == 0)
name = el->get_name();
history_button->insert_entries(-1, gtMenuStandard, "his_entry", name, this, history_CB,
gtMenuNull);
gtPrimitive *button = history_button->entry(j);
button->userData(entry);
}
// Finally make new history list (to update size)
objArr tmp = history_list;
history_list.removeAll();
for(j = 0; j < tmp.size() - 1; j++)
history_list.insert_last(tmp[j]);
report_out_of_scope(entry->rtl);
delete entry;
}
}
}
void miniBrowser::add_rtl_to_history(RTLPtr rtl, int position, int list_num)
{
Initialize(miniBrowser::add_rtl_to_history);
for(int i = 0; i < history_list.size(); i++){
ListHistoryEntry *entry = (ListHistoryEntry *)history_list[i];
if(entry->rtl == rtl)
return;
}
int last_button;
ListHistoryEntry *new_entry = new ListHistoryEntry;
new_entry->rtl = rtl;
new_entry->top_position = position;
new_entry->list_number = list_num;
if(history_list.size() >= customize::miniBrowser_history_length()){
if(history_list[1] != NULL){
ListHistoryEntry *entry = (ListHistoryEntry *)history_list[1];
report_out_of_scope(entry->rtl);
delete entry;
}
int i;
for(i = 1; i < history_list.size() - 1; i++){
history_button->remove_entry(1);
history_list[i] = history_list[i + 1];
}
history_button->remove_entry(1);
for(i = 1; i < history_list.size() - 1; i++){
ListHistoryEntry *entry = (ListHistoryEntry *)history_list[i];
RTLPtr el = entry->rtl;
char *name = el->get_phys_name();
if(!name || name[0] == 0)
name = el->get_name();
history_button->insert_entries(-1, gtMenuStandard, "his_entry", name, this, history_CB,
gtMenuNull);
gtPrimitive *button = history_button->entry(i);
button->userData(entry);
}
history_list[(last_button = history_list.size() - 1)] = new_entry;
}else{
history_list.insert_last(new_entry);
last_button = history_list.size() - 1;
}
char *name = rtl->get_phys_name();
if(!name || name[0] == 0)
name = rtl->get_name();
history_button->insert_entries(-1, gtMenuStandard, "his_entry", name, this, history_CB,
gtMenuNull);
gtPrimitive *button = history_button->entry(last_button);
button->userData(new_entry);
}
inline int shift_or_control(gtEventPtr e)
//
// Return true if the SHIFT or CONTROL keys were pressed in the event.
//
{
return e->xbutton.state & (ShiftMask | ControlMask);
}
void miniBrowser::list1_select(gtList*, gtEventPtr e, void* mb, gtReason)
//
// Selection callback for top list.
//
{
miniBrowser *m = (miniBrowser *)mb;
m->selected_list = m->list1;
SetNextRtl(NULL);
if (e){
if(!shift_or_control(e)){
m->list2->deselect_all();
m->list2_selection.removeAll();
}
m->list1_selection.removeAll();
m->list1->app_nodes(&m->list1_selection);
m->rtl_select(shift_or_control(e));
}else{
m->list2->deselect_all();
m->list2_selection.removeAll();
m->list1_selection.removeAll();
m->list1->app_nodes(&m->list1_selection);
m->rtl_select(0);
}
RTL *rtl = m->list1->RTL();
miniBrowserRTL_API *api;
if(rtl && (api = rtl_get_APIhandler(rtl))){
api->selection_callback(rtl, m->list1_selection, m);
}
}
void miniBrowser::list2_select(gtList*, gtEventPtr e, void* mb, gtReason)
//
// Selection callback for bottom list.
//
{
miniBrowser *m = (miniBrowser *)mb;
m->selected_list = m->list2;
SetNextRtl(NULL);
if (e){
if(!shift_or_control(e)){
m->list1->deselect_all();
m->list1_selection.removeAll();
}
m->list2_selection.removeAll();
m->list2->app_nodes(&m->list2_selection);
m->rtl_select(shift_or_control(e));
}else{
m->list1->deselect_all();
m->list1_selection.removeAll();
m->list2_selection.removeAll();
m->list2->app_nodes(&m->list2_selection);
m->rtl_select(0);
}
RTL *rtl = m->list2->RTL();
miniBrowserRTL_API *api;
if(rtl && (api = rtl_get_APIhandler(rtl))){
api->selection_callback(rtl, m->list2_selection, m);
}
}
void miniBrowser::rtl_select(int extend)
//
// Store selection in list.
//
{
Initialize(miniBrowser::rtl_select);
if (!extend) {
driver_instance->clear_selection(false);
}
selected_symbols.removeAll();
symbolArr selection;
selection.insert_last(list1_selection);
selection.insert_last(list2_selection);
if(selection.size())
{
for(int i = 0; i < selection.size(); ++i)
{
fsymbolPtr sym = selection[i];
if (sym.without_xrefp() || sym.is_ast() || sym.is_dataCell()) {
if(!selected_symbols.includes(sym))
selected_symbols.insert_last(sym);
} else {
fsymbolPtr xsym = sym.get_xrefSymbol();
if (xsym.xrisnull()) {
if ( selected_symbols.includes (sym) )
continue;
Relational *rel_ptr = (Relational *)sym;
if (is_RTL (rel_ptr)) {
RTL *rtl = (RTL *)rel_ptr;
RTLNode *instance_nodes =
checked_cast(RTLNode,((RTL *)rel_ptr)->get_root());
::obj_insert(rtl, REPLACE, instance_nodes, instance_nodes, NULL);
selected_symbols.insert_last (sym);
}
} else {
if(!selected_symbols.includes(sym))
selected_symbols.insert_last(sym);
}
}
}
symbolPtr sym = selection[selection.size() - 1];
genString info_msg;
if(sym.without_xrefp())
(void) get_display_string_from_symbol(sym, info_msg);
else {
fsymbolPtr xsym = sym.get_xrefSymbol();
if (xsym.xrisnotnull())
(void) get_display_string_from_symbol(xsym, info_msg);
}
if (info_msg.length())
msg("symbol_info:miniBrowser.h.C", normal_sev) << (char *)info_msg << eom;
}
}
void miniBrowser::remove(RTL *rtl)
{
Initialize(miniBrowser::remove);
remove_from_history(rtl);
gtRTL *old_selected = selected_list;
ListHistoryEntry *entry = NULL;
if(rtl == list1->RTL()){
// Scan throght history list & try to find most sutable replacement
for(int i = history_list.size() - 1; i > 0; i--){
ListHistoryEntry *e = (ListHistoryEntry *)history_list[i];
if(e->list_number == 1){
entry = e;
break;
}
}
selected_list = list2;
list1->set_rtl(NULL);
title1(" ");
handle_rtl_deletion(rtl);
}
if(rtl == list2->RTL()){
// Scan throght history list & try to find most sutable replacement
for(int i = history_list.size() - 1; i > 0; i--){
ListHistoryEntry *e = (ListHistoryEntry *)history_list[i];
if(e->list_number == 2){
entry = e;
break;
}
}
selected_list = list1;
list2->set_rtl(NULL);
title2(" ");
handle_rtl_deletion(rtl);
}
/*
if(entry){
RTL *new_rtl = entry->rtl;
objSet cans = rtl_get_trash_cans(entry->rtl);
if(cans.includes(&garbage)){
// This rtl suppose to be deleted later, so create a copy and forget about this object
new_rtl = copy_create_rtl(entry->rtl);
trash_can_put_rtl(&garbage, new_rtl);
}
miniBrowserRTL_API *api = rtl_get_APIhandler(entry->rtl);
if(api){
if(new_rtl != rtl)
APIhandler_put_rtl(api, new_rtl);
}
browse(new_rtl, entry->top_position);
// remove_from_history(entry->rtl);
}
*/
selected_list = old_selected;
}
void miniBrowser::browse(appTree *app_node, int position)
{
Initialize(miniBrowser::browse_appTree);
RTL *rtl = checked_cast(RTL, get_relation(header_of_tree, app_node));
if(rtl){
trash_can_put_rtl(&garbage, rtl);
browse(rtl, position);
}
}
static gtList *list_to_set = NULL; // Used only for list_position_set!!!
static int list_pos; // Used only for list_position_set!!!
static void list_position_set(void *pos)
{
int position = *(int *)pos;
if(list_to_set){
if(list_to_set->num_items() >= position)
list_to_set->set_pos(position);
}
}
void miniBrowser::set_output_window(int window_index) /* index - 0 - top window, 1 - bottom window */
{
Initialize(miniBrowser::set_output_window);
if(window_index){
selected_list = list1;
} else {
selected_list = list2;
}
}
int miniBrowser::get_next_window(void) /* returns 0 - top window, 1 - bottom window */
{
if(selected_list == list1)
return 1;
else
return 0;
}
void miniBrowser::browse(RTLPtr rtl_head, int position)
{
Initialize(miniBrowser::browse);
if(!visible())
vs_display_mini_browser((Widget)parent_viewershell, 1);
trash_can_put_rtl(&controlled_rtls, rtl_head);
RTLPtr old_rtl = NULL;
int old_position;
int old_list_num;
if(selected_list == list1){
if(unmanaged_list == list2){
if(form_cleanup_callback)
form_cleanup_callback(this, cleanup_callback_data);
restore_list();
}
old_rtl = list2->RTL();
old_position = list2->gt_list()->top_item_position();
old_list_num = 2;
list2->set_rtl_reset_filters(rtl_head);
title2(rtl_head->get_name());
list_to_set = list2->gt_list();
}else{
if(unmanaged_list == list1){
if(form_cleanup_callback)
form_cleanup_callback(this, cleanup_callback_data);
restore_list();
}
old_rtl = list1->RTL();
old_position = list1->gt_list()->top_item_position();
old_list_num = 1;
list1->set_rtl_reset_filters(rtl_head);
title1(rtl_head->get_name());
list_to_set = list1->gt_list();
}
list_pos = position;
pset_send_own_callback(list_position_set, &list_pos);
if(old_rtl){
add_rtl_to_history(old_rtl, old_position, old_list_num);
}
}
void miniBrowser::switch_window(void)
{
if(selected_list == list1)
selected_list = list2;
else
selected_list = list1;
}
void miniBrowser::open_module(symbolPtr sym)
{
Initialize(open_module);
projModule *mod = NULL;
if(sym.relationalp()){
view_create(sym, Rep_UNKNOWN);
view_create_flush();
return;
}else{
if(sym.is_xrefSymbol()){
if(sym.get_kind() == DD_MODULE)
mod = projModule_of_symbol(sym);
if(mod){
view_create(sym, Rep_UNKNOWN);
view_create_flush();
return;
}
}
if(!mod){
appPtr app_head = checked_cast(app, sym.get_def_app());
if(app_head){
appTreePtr app_root = checked_cast(appTree, app_head->get_root());
view_create(app_root);
view_create_flush();
return;
}
genString fn = sym.get_name();
if(fn.length()){
view_create(fn);
view_create_flush();
}
return;
}
}
if(!mod)
return;
genString fn;
mod->get_phys_filename(fn);
projNode *pn = mod->get_project();
projNode *lpn = pn;
genString ln;
if(!fn.length())
return;
projHeader::fn_to_ln(fn, ln, &lpn, 0, 1);
projModule *lmod = mod;
if (pn && lpn)
{
if (pn != lpn)
lmod = lpn->find_module(ln);
}
appPtr app = lmod->restore_module();
if(app)
view_create(app);
else
view_create(fn);
view_create_flush();
}
void miniBrowser::list1_action(gtList*, gtEventPtr, void* mb, gtReason)
{
Initialize(miniBrowser::list1_action);
miniBrowser *browser = (miniBrowser *)mb;
RTL *rtl = browser->list1->RTL();
miniBrowserRTL_API *api;
int ret_val = 1;
if(rtl && (api = rtl_get_APIhandler(rtl))){
ret_val = api->action_callback(rtl, browser->list1_selection, browser);
}
if(ret_val)
browser->list_action();
browser->clear_selections();
}
void miniBrowser::list2_action(gtList*, gtEventPtr, void* mb, gtReason)
{
Initialize(miniBrowser::list2_action);
miniBrowser *browser = (miniBrowser *)mb;
RTL *rtl = browser->list2->RTL();
miniBrowserRTL_API *api;
int ret_val = 1;
if(rtl && (api = rtl_get_APIhandler(rtl))){
ret_val = api->action_callback(rtl, browser->list2_selection, browser);
}
if(ret_val)
browser->list_action();
browser->clear_selections();
}
void miniBrowser::list_action(void)
{
Initialize(miniBrowser::list_action);
push_busy_cursor();
BrowserData* bd = LanguageController::GetBrowserData();
for (int i = 0; i < selected_symbols.size(); i++)
{
const char* cmd = bd->get_action_cmd(selected_symbols[i].get_kind());
if (cmd != NULL)
{
Interpreter* intr = GetActiveInterpreter();
if (strlen(cmd) > 0 && intr)
{
symbolArr sel, dummy;
sel.insert_last(selected_symbols[i]);
intr->EvalQuery((char*)cmd, sel, dummy);
}
}
else
{
symbolPtr sym = selected_symbols[i];
symbolPtr xsym;
if(sym.get_kind() == DD_SMT || sym.get_kind() == DD_REGION || sym.is_instance() || sym.is_ast() || sym.is_dataCell())
xsym = sym; // do not get xrefSymbol for these types (will try to open view on smt/position)
else
xsym = sym.get_xrefSymbol();
if (!xsym.is_ast() && !xsym.is_dataCell() && xsym.xrisnull() && !sym.without_xrefp()) {
Relational *rel_ptr = (Relational *)sym;
if (is_RTL (rel_ptr)) {
RTL *rtl = (RTL *)rel_ptr;
RTLNode *instance_nodes =
checked_cast(RTLNode,((RTL *)rel_ptr)->get_root());
::obj_insert(rtl, REPLACE, instance_nodes, instance_nodes, NULL);
RTLNode *childs = checked_cast(RTLNode, get_relation(tree_of_header, rel_ptr));
if(childs){
// Create & copy rtl to new one to allow later deletion.
RTL *rtl = checked_cast(RTL, get_relation(header_of_tree, childs));
RTL *new_rtl = rtl;
browse(new_rtl);
}
}
} else {
// boris: Allow new Relational DD_MODULE and DD_PROJECT to go here with xrefSymbols
ddKind knd = (xsym.xrisnull()) ? sym.get_kind() : xsym.get_kind();
switch (knd)
{
case DD_PROJECT:
{ projHeader *rtl_head = checked_cast(projHeader, sym.get_def_app());
if(rtl_head){
projNodePtr proj_root = projNodePtr(rtl_head->get_root());
proj_root->refresh();
RTL *new_rtl = rtl_head;
ProjectController *pc = new ProjectController(proj_root, this);
APIhandler_put_rtl(pc, new_rtl);
browse(new_rtl);
} }
break;
case DD_MODULE:
ste_finalize();
open_module(sym);
break;
case DD_SUBSYSTEM:
ste_finalize();
view_create(xsym, Rep_OODT_Inheritance);
view_create_flush();
break;
case DD_IFL_SRC:
case DD_RELATION:
msg("Unable to open view for this symbol.", error_sev) << eom;
break;
case DD_SMT:
case DD_REGION:
ste_finalize();
view_create(xsym, Rep_UNKNOWN, 1);
view_create_flush();
break;
default:
if (xsym.is_ast() || sym.is_dataCell() || xsym.xrisnotnull()) {
ste_finalize();
view_create(xsym, Rep_UNKNOWN, 1);
view_create_flush();
}
break;
}
}
}
}
pop_cursor();
}
void miniBrowser::make_list2_visible(void)
{
Initialize(miniBrowser::make_list2_visible);
Dimension height;
Dimension list_height;
// XtVaSetValues(paned->container()->rep()->widget(), XmNunitType, XmPIXELS, NULL);
XtVaGetValues(paned->container()->rep()->widget(), XmNheight, &height, NULL);
XtVaGetValues(list2->container()->rep()->widget(), XmNheight, &list_height, NULL);
if(list_height >= height / 2)
return;
list2->unmanage();
XtVaSetValues(list2->container()->rep()->widget(), XmNpaneMinimum, height / 2, NULL);
list2->manage();
XtVaSetValues(list2->container()->rep()->widget(), XmNpaneMinimum, 100, NULL);
selected_list = list1;
}
void miniBrowser::GroupManagerButton(gtPushButton*, gtEvent*, void*, gtReason)
{
Initialize(miniBrowser::GroupManagerButton);
SetsUI::Invoke(NULL);
}
void miniBrowser::GroupButton(gtPushButton*, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::GroupButton);
symbolArr selection;
fill_selected_objects(&selection);
if(selection.size() == 0){
msg("Nothing_selected:miniBrowser.h.C", error_sev) << eom;
return;
}
call_cli_callback(GetActiveInterpreter(), "mini_capture_list", "", &selection, NULL);
}
void miniBrowser::PopupBrowser(gtCascadeButton *b, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::PopupBrowser);
miniBrowser *browser = (miniBrowser *)mb;
if(browser->visible()){
vs_display_mini_browser((Widget)browser->parent_viewershell, 0);
b->label("Minibrowser(OFF)");
}
else{
vs_display_mini_browser((Widget)browser->parent_viewershell, 1);
b->label("Minibrowser(ON) ");
}
}
void miniBrowser::ToggleBrowser(gtPushButton *, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::ToggleBrowser);
miniBrowser *browser = (miniBrowser *)mb;
if(browser->visible()){
vs_display_mini_browser((Widget)browser->parent_viewershell, 0);
browser->on_button->unmanage();
browser->off_button->manage();
}
else{
vs_display_mini_browser((Widget)browser->parent_viewershell, 1);
browser->off_button->unmanage();
browser->on_button->manage();
}
}
int cli_eval_query(const char* cmd, symbolArr& scope, symbolArr&);
void miniBrowser::QueryButton(gtPushButton* b, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::QueryButton);
miniBrowser *browser = (miniBrowser *)mb;
char *title = b->title();
symbolArr selection;
fill_selected_objects(&selection);
if(selection.size() == 0){
// If nothing is selected get current viewed module.
viewerShell* vsh = view_target_viewer()->get_shell();
viewPtr view = vsh->get_current_view();
if(view){
switch(repType(view->get_type()))
{
case Rep_VertHierarchy: // Operate on app of view.
case Rep_FlowChart:
case Rep_TextDiagram:
case Rep_TextText:
case Rep_TextFullDiagram:
case Rep_SmtText:
{
ldrPtr ldr_head = view_get_ldr(view);
if(ldr_head){
appPtr app_head = ldr_get_app(ldr_head);
if(app_head)
selection.insert_last(app_head->get_module());
}
}
break;
case Rep_RawText:
msg("Unable to query Raw Text.", error_sev) << eom;
break;
default:
msg("Unable to query unknown Text type.", error_sev) << eom;
break;
}
}
if(selection.size() == 0)
{
browser->remove_queries();
return;
}
}
push_busy_cursor();
RTL *rtl = db_new(RTL, (NULL));
RTLNodePtr rtl_node = checked_cast(RTLNode, rtl->get_root());
genString selected_name = selection[0].get_name();
char *nm = (char *)selected_name;
genString name;
if(selected_name.length() > 25)
nm[25 - 1] = '\0';
name.printf("%s: %s", (char *)selected_name, title);
rtl->set_name((char *)name);
symbolArr& results = rtl_node->rtl_contents();
results.removeAll();
const char* cmd = browser->pBController->get_query_command(title);
if (cmd && strlen(cmd) > 0)
{
genString command;
browser->pBController->handle_closure(cmd, command);
cli_eval_query(command, selection, results);
}
gtFree(title);
if(results.size() == 0){
msg("Query_found_no_matches:miniBrowser.h.C", normal_sev) << (char *)name << eom;
if(rtl)
obj_delete(rtl);
}else{
trash_can_put_rtl(&garbage, rtl); // Store this object to delete when we don\'t need it any more
if(strcmp(cmd, "where used") == 0 || strcmp(cmd, "where referenced") == 0)
{
// Convert selection to xrefSymbols !!! to make sure that any change will keep array consistent
symbolArr xselection;
for(int i = 0; i < selection.size(); i++){
symbolPtr xsym = selection[i].get_xrefSymbol();
if(!xsym.isnull())
xselection.insert_last(xsym);
}
InstanceAPI *instance = new InstanceAPI(xselection);
APIhandler_put_rtl(instance, rtl);
}
browser->browse(rtl);
}
//browser->remove_queries();
pop_cursor();
}
void miniBrowser::SlideButton(gtArrowButton*, gtEvent*, void* mb, gtReason)
{
Initialize(miniBrowser::SlideButton);
miniBrowser *browser = (miniBrowser *)mb;
vs_display_mini_browser((Widget)browser->parent_viewershell, 0);
}
void miniBrowser::init_search_path(symbolArr& selection)
{
Initialize(miniBrowser::init_search_path);
objArr proj_arr;
// First scan for projects
int i;
for(i = 0; i < selection.size(); i++){
symbolPtr sym = selection[i];
if(sym.get_kind() == DD_PROJECT){
projHeader *rtl_head = checked_cast(projHeader, sym.get_def_app());
if(rtl_head){
projNodePtr proj_root = projNodePtr(rtl_head->get_root());
proj_arr.insert_last(proj_root);
}
}
}
scope.set_domain(proj_arr);
// Add selected modules
for(i = 0; i < selection.size(); i++){
symbolPtr sym = selection[i];
if(sym.get_kind() == DD_MODULE) {
symbolPtr xsym = sym.get_xrefSymbol();
if (xsym.xrisnotnull())
scope.add_module(sym);
else if (sym.without_xrefp())
scope.add_module(sym);
}
}
}
void miniBrowser::clear_selection(void)
{
Initialize(miniBrowser::clear_selection);
list1->deselect_all();
list2->deselect_all();
list1_selection.removeAll();
list2_selection.removeAll();
selected_symbols.removeAll();
}
// Static function
void miniBrowser::clear_selections(void)
{
Initialize(miniBrowser::clear_selections);
for(int i = 0; i < miniBrowser_instances.size(); i++){
miniBrowser *mb = *miniBrowser_instances[i];
mb->clear_selection();
}
}
// Static function
void miniBrowser::fill_selected_nodes(symbolArr& array)
{
Initialize(miniBrowser::fill_selected_nodes);
for(int i = 0; i < miniBrowser_instances.size(); i++){
miniBrowser *mb = *miniBrowser_instances[i];
array.insert_last(mb->selected_symbols);
}
}
static void miniBrowser_initialize_GC(Widget w)
{
XGCValues values;
if(miniBrowser_gc_initialized)
return;
values.foreground = 0xEEEEEE;
values.function = GXxor;
values.subwindow_mode = IncludeInferiors;
miniBrowser_GC = XtGetGC(w, GCForeground | GCFunction | GCSubwindowMode, &values);
miniBrowser_gc_initialized = 1;
}
extern "C" void miniBrowser_start_dragging(Widget w, void *data, XEvent *ev, Boolean *cont)
{
if(do_dragging){
// Do not dispatch this event further
*cont = False;
return;
}
if(ev->xbutton.button != Button1)
return;
do_dragging = 1;
Widget parent = XtParent(w);
XtVaSetValues(parent, XmNunitType, XmPIXELS, NULL);
XtVaSetValues(w, XmNunitType, XmPIXELS, NULL);
XtVaGetValues(parent, XmNheight, &miniBrowser_height, NULL);
XtVaGetValues(w, XmNleftOffset, &miniBrowser_button_x, NULL);
Widget separator = (Widget)data;
int separator_x;
XtVaSetValues(separator, XmNunitType, XmPIXELS, NULL);
XtVaGetValues(separator, XmNleftOffset, &separator_x, NULL);
miniBrowser_xdiff = separator_x - miniBrowser_button_x;
XDrawLine(XtDisplay(parent), XtWindow(parent), miniBrowser_GC, separator_x, 15,
separator_x, miniBrowser_height);
}
extern "C" void miniBrowser_do_dragging(Widget w, void *, XEvent *ev, Boolean *)
{
if(!do_dragging)
return;
Widget parent = XtParent(w);
XDrawLine(XtDisplay(parent), XtWindow(parent), miniBrowser_GC, miniBrowser_button_x + miniBrowser_xdiff,
15, miniBrowser_button_x + miniBrowser_xdiff, miniBrowser_height);
Dimension width;
XtVaGetValues(parent, XmNwidth, &width, NULL);
int x;
XtVaGetValues(w, XmNleftOffset, &x, NULL);
miniBrowser_button_x = x + ev->xbutton.x;
if(miniBrowser_button_x < 40)
miniBrowser_button_x = 40;
if(miniBrowser_button_x > width - 40)
miniBrowser_button_x = width - 40;
XDrawLine(XtDisplay(parent), XtWindow(parent), miniBrowser_GC, miniBrowser_button_x + miniBrowser_xdiff,
15, miniBrowser_button_x + miniBrowser_xdiff, miniBrowser_height);
}
extern "C" void miniBrowser_end_dragging(Widget w, void *data, XEvent *ev, Boolean *)
{
if(ev->xbutton.button != Button1)
return;
miniBrowser_event_data *form_data = (miniBrowser_event_data *)data;
do_dragging = 0;
Widget parent = XtParent(w);
XDrawLine(XtDisplay(parent), XtWindow(parent), miniBrowser_GC, miniBrowser_button_x + miniBrowser_xdiff,
15, miniBrowser_button_x + miniBrowser_xdiff, miniBrowser_height);
XtVaSetValues(w, XmNleftOffset, miniBrowser_button_x,
NULL);
Widget separator = form_data->separator;
XtVaSetValues(separator, XmNleftOffset, miniBrowser_button_x + miniBrowser_xdiff,
NULL);
form_data->button_pos = miniBrowser_button_x;
form_data->sep_pos = miniBrowser_button_x + miniBrowser_xdiff;
}
extern "C" void miniBrowser_form_resize(Widget, void *data, XEvent *ev)
{
miniBrowser_event_data *form_data = (miniBrowser_event_data *)data;
if(ev->type != ConfigureNotify)
return;
if(form_data->width == 0){
Dimension total_form_width;
XtVaSetValues(form_data->separator, XmNunitType, XmPIXELS, NULL);
XtVaSetValues(form_data->button, XmNunitType, XmPIXELS, NULL);
XtVaSetValues(XtParent(form_data->button), XmNunitType, XmPIXELS, NULL);
XtVaSetValues(XtParent(XtParent(form_data->button)), XmNunitType, XmPIXELS, NULL);
XtVaGetValues(XtParent(XtParent(form_data->button)), XmNwidth, &total_form_width, NULL);
if(total_form_width < 840){
XtVaSetValues(form_data->separator, XmNleftOffset, (form_data->sep_pos = total_form_width - 150), NULL);
XtVaSetValues(form_data->button, XmNleftOffset, (form_data->button_pos = total_form_width - 154), NULL);
}else{
XtVaGetValues(form_data->separator, XmNleftOffset, &form_data->sep_pos, NULL);
XtVaGetValues(form_data->button, XmNleftOffset, &form_data->button_pos, NULL);
}
XtVaGetValues(XtParent(form_data->button), XmNwidth, &form_data->width, NULL);
// form_data->width = ev->xconfigure.width;
return;
}
if(form_data->width == ev->xconfigure.width)
return;
float rel = (float)form_data->sep_pos / form_data->width;
float new_pos = rel * ev->xconfigure.width;
form_data->button_pos = (int)new_pos - (form_data->sep_pos - form_data->button_pos);
form_data->sep_pos = (int)new_pos;
form_data->width = ev->xconfigure.width;
XtVaSetValues(form_data->separator, XmNleftOffset, form_data->sep_pos,
NULL);
XtVaSetValues(form_data->button, XmNleftOffset, form_data->button_pos,
NULL);
}
extern "C" void miniBrowser_destroy_callback(Widget, void *data, void *)
{
miniBrowser_event_data *form_data = (miniBrowser_event_data *)data;
delete form_data;
}
extern "C" void miniBrowser_initialize_slide_button(Widget button, Widget separator)
{
miniBrowser_initialize_GC(XtParent(button));
// Following structure would be freed in the event handler
miniBrowser_event_data *data = new miniBrowser_event_data;
data->button = button;
data->separator = separator;
data->width = 0;
XtAddEventHandler(button, ButtonPressMask, FALSE, (XtEventHandler)miniBrowser_start_dragging,
(XtPointer)separator);
XtAddEventHandler(button, PointerMotionMask, FALSE, (XtEventHandler)miniBrowser_do_dragging,
(XtPointer)separator);
XtAddEventHandler(button, ButtonReleaseMask, FALSE, (XtEventHandler)miniBrowser_end_dragging,
(XtPointer)data);
XtAddEventHandler(XtParent(button), StructureNotifyMask, FALSE,
(XtEventHandler)miniBrowser_form_resize, (XtPointer)data);
XtAddCallback(XtParent(button), XtNdestroyCallback, (XtCallbackProc)miniBrowser_destroy_callback,
(XtPointer)data);
}
extern "C" void miniBrowser_initialize_slide_separator(Widget)
{
}
//------------------------------------------
// closure button handling
//------------------------------------------
void miniBrowser::closure(bool enabled) {
Initialize(miniBrowser::closure);
closure_button->set(enabled, 0);
}
void miniBrowser::closure_CB(gtToggleButton* but, gtEvent*, void*, gtReason) {
Initialize(miniBrowser::closure_CB);
if (but) {
set_closure_state(but->set());
}
}
//------------------------------------------
void miniBrowser::cleanup_lists()
{
RTL *rtl1 = list1->RTL();
list1->set_rtl(NULL);
title1(" ");
handle_rtl_deletion(rtl1);
RTL *rtl2 = list2->RTL();
list2->set_rtl(NULL);
title2(" ");
handle_rtl_deletion(rtl2);
while(history_list.size() > 1){
history_button->remove_entry(1);
ListHistoryEntry *entry = (ListHistoryEntry *)history_list[1];
report_out_of_scope(entry->rtl);
history_list.remove(entry);
delete entry;
}
objSet rtls = trash_can_get_rtls(&garbage);
ObjPtr ob;
ForEach(ob, rtls){
RTL *rtl = (RTL *)ob;
handle_rtl_deletion(rtl);
}
// Get the rest of rtls wich was controlled but slip throught other method\'s of notification.
rtls = trash_can_get_rtls(&controlled_rtls);
ObjPtr ob1;
ForEach(ob1, rtls){
RTL *rtl = (RTL *)ob1;
report_out_of_scope(rtl);
}
/*
RTLPtr new_rtl = projNode::get_project_rtl();
new_rtl->set_name("Top Level Projects");
list1->set_rtl(new_rtl);
add_rtl_to_history(new_rtl, 1);
title1("Top Level Projects");
selected_list = list1;
*/
}
void cleanup_miniBrowsers()
{
for(int i = 0; i < miniBrowser_instances.size(); i++){
miniBrowser *mb = *miniBrowser_instances[i];
if ( mb )
mb->cleanup_lists();
}
}
void miniBrowser::update_query_menu_CB(void* data, caddr_t browser, gtEventPtr)
{
miniBrowser* mb = (miniBrowser*)browser;
mb->update_query_menu();
}
void get_ddKinds(genMask& mask, const symbolArr& syms);
void miniBrowser::update_query_menu()
{
Initialize(miniBrowser::update_query_menu);
symbolArr selection;
fill_selected_objects(&selection);
if(selection.size() == 0){
// If nothing is selected get current viewed module.
viewerShell* vsh = view_target_viewer()->get_shell();
viewPtr view = vsh->get_current_view();
if(view){
switch(repType(view->get_type()))
{
case Rep_VertHierarchy: // Operate on app of view.
case Rep_FlowChart:
case Rep_TextDiagram:
case Rep_TextText:
case Rep_TextFullDiagram:
case Rep_SmtText:
{
ldrPtr ldr_head = view_get_ldr(view);
if(ldr_head){
appPtr app_head = ldr_get_app(ldr_head);
if(app_head)
selection.insert_last(app_head->get_module());
}
}
break;
case Rep_RawText:
msg("Unable to query Raw Text.", error_sev) << eom;
break;
default:
msg("Unable to query unknown Text type.", error_sev) << eom;
break;
}
}
}
genMask sel;
get_ddKinds(sel, selection);
if (sel == old_selection)
return; //no need to change queries
remove_queries();
old_selection = sel;
int j;
genArrCharPtr queries;
genArrCharPtr subqueries;
pBController->get_queries_with_submenus(sel, queries);
for (int i = 0; i < queries.size(); i++)
{
num_queries++;
if (!pBController->is_submenu(*queries[i]))
{
query_menu->insert_entries(num_queries, gtMenuStandard, "menu_item",
*queries[i], this, QueryButton, gtMenuNull);
}
else // for sub menues
{
char label[10];
// need this label not to break regressions
OSapi_sprintf(label, "submenu%d",
pBController->get_submenu_index(*queries[i]) + 1);
query_menu->insert_entries(num_queries, gtMenuCascade, label,
*queries[i], this, QueryButton, gtMenuNull);
pBController->get_submenu_items(selection, *queries[i], subqueries);
gtCascadeButton* button = (gtCascadeButton*)query_menu->entry(num_queries);
button->pulldown_menu(label, gtMenuNull);
for (j = 0; j < subqueries.size(); j++)
{
button->insert_entries(-1, gtMenuStandard, "submenu_item",
*subqueries[j], this, QueryButton, gtMenuNull);
}
}
}
}
void miniBrowser::remove_queries()
{
/* remove all entries from query_menu except for "Closure" */
for (int i = 1; i <= num_queries; i++)
{
gtPrimitive* entry = query_menu->entry(1);
const char* name = entry->name();
if (strcmp(name, "menu_item") != 0) //if this is a submenu
{
gtCascadeButton* button = (gtCascadeButton*) entry;
gtPrimitive *p, *old_p;
do
{
old_p = button->entry(0);
button->remove_entry(0);
p = button->entry(0);
}
while (p && p != old_p);
}
query_menu->remove_entry(1);
}
num_queries = 0;
old_selection.clear();
}
| 28.959334 | 123 | 0.660796 | [
"object"
] |
638993a39bf00ef215e85d2a14611554422892d6 | 579 | hpp | C++ | src/utilities/config-handler/config-handler.hpp | zenitheesc/daemons-framework | 6115cb083c70db5ef23766307b7c9c3f32fac893 | [
"MIT"
] | 2 | 2021-09-10T20:40:27.000Z | 2021-09-22T01:03:21.000Z | src/utilities/config-handler/config-handler.hpp | zenitheesc/daemons-framework | 6115cb083c70db5ef23766307b7c9c3f32fac893 | [
"MIT"
] | null | null | null | src/utilities/config-handler/config-handler.hpp | zenitheesc/daemons-framework | 6115cb083c70db5ef23766307b7c9c3f32fac893 | [
"MIT"
] | null | null | null | #include <fstream>
#include <nlohmann/json.hpp>
class ConfigHandler {
private:
static nlohmann::json m_config;
std::string m_fileName;
const std::vector<std::string> m_requiredFields {
"data", "services", "serviceId"
};
public:
explicit ConfigHandler(const std::string& fileName);
void read(const std::string& fileName);
void read();
auto operator[](const std::string& field) const -> const nlohmann::json;
private:
[[nodiscard]] auto getConfig(const std::string& field) const -> const nlohmann::json;
void validateConfig();
};
| 26.318182 | 89 | 0.680484 | [
"vector"
] |
638c4ca6998db7c84c41ca33fe273f3bd5a4e385 | 452 | hpp | C++ | parameters.hpp | ruben-cohen/jcr_pde1d | 228306f6e06ff97ca317349cb3feb28e508683cf | [
"BSD-3-Clause"
] | null | null | null | parameters.hpp | ruben-cohen/jcr_pde1d | 228306f6e06ff97ca317349cb3feb28e508683cf | [
"BSD-3-Clause"
] | null | null | null | parameters.hpp | ruben-cohen/jcr_pde1d | 228306f6e06ff97ca317349cb3feb28e508683cf | [
"BSD-3-Clause"
] | null | null | null |
#ifndef PARAMETERS_HPP
#define PARAMETERS_HPP
#include <vector>
// this class is only the initialization of the three parameters needed to create the matrix
namespace project{
class Parameters {
public:
Parameters(double vol, double rate, double theta);
double Get_Vol() const;
double Get_Rate() const;
double Get_Theta() const;
~Parameters();
private:
double pa_vol;
double pa_Rate;
double pa_Theta;
};
}
#endif | 14.580645 | 93 | 0.714602 | [
"vector"
] |
b0d39bea3e6764352ef1a76f74d9c09c44bb3d22 | 1,547 | cpp | C++ | src/picotorrent/applicationoptions.cpp | kk7945287/pictorr | 09bf9ccbd89f0b459cb07e3012ced9c35bea005c | [
"MIT"
] | null | null | null | src/picotorrent/applicationoptions.cpp | kk7945287/pictorr | 09bf9ccbd89f0b459cb07e3012ced9c35bea005c | [
"MIT"
] | null | null | null | src/picotorrent/applicationoptions.cpp | kk7945287/pictorr | 09bf9ccbd89f0b459cb07e3012ced9c35bea005c | [
"MIT"
] | null | null | null | #include "applicationoptions.hpp"
#include <wx/filename.h>
#include "picojson.hpp"
using pt::ApplicationOptions;
std::shared_ptr<ApplicationOptions> ApplicationOptions::JsonDecode(wxString json)
{
picojson::value val;
std::string err = picojson::parse(val, json.ToStdString());
if (!err.empty())
{
return nullptr;
}
picojson::object obj = val.get<picojson::object>();
picojson::array files = obj.at("files").get<picojson::array>();
picojson::array magnets = obj.at("magnet_links").get<picojson::array>();
auto opts = std::make_shared<ApplicationOptions>();
for (auto item : files)
{
opts->files.push_back(item.get<std::string>());
}
for (auto item : magnets)
{
opts->magnet_links.push_back(item.get<std::string>());
}
return opts;
}
wxString ApplicationOptions::JsonEncode(std::shared_ptr<ApplicationOptions> opts)
{
picojson::array files;
picojson::array magnets;
for (auto item : opts->files)
{
wxFileName fn(item);
fn.MakeAbsolute();
files.push_back(picojson::value(fn.GetFullPath().ToStdString()));
}
for (auto item : opts->magnet_links)
{
magnets.push_back(picojson::value(item.ToStdString()));
}
picojson::object obj;
obj.insert({ "files", picojson::value(files) });
obj.insert({ "magnet_links", picojson::value(magnets) });
return wxString::FromUTF8(picojson::value(obj).serialize());
}
| 24.951613 | 82 | 0.616031 | [
"object"
] |
b0d7b5de26c250081ce4da2df3a444d5bb3136b7 | 6,368 | cc | C++ | pdf/pdfium/fuzzers/pdfium_fuzzer.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | pdf/pdfium/fuzzers/pdfium_fuzzer.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | pdf/pdfium/fuzzers/pdfium_fuzzer.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This fuzzer is simplified & cleaned up pdfium/samples/pdfium_test.cc
#include <assert.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <list>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "third_party/pdfium/public/fpdf_dataavail.h"
#include "third_party/pdfium/public/fpdf_ext.h"
#include "third_party/pdfium/public/fpdf_formfill.h"
#include "third_party/pdfium/public/fpdf_text.h"
#include "third_party/pdfium/public/fpdfview.h"
#include "third_party/pdfium/testing/test_support.h"
#include "v8/include/v8.h"
static int ExampleAppAlert(IPDF_JSPLATFORM*,
FPDF_WIDESTRING,
FPDF_WIDESTRING,
int,
int) {
return 0;
}
static void ExampleDocGotoPage(IPDF_JSPLATFORM*, int pageNumber) {}
static void ExampleUnsupportedHandler(UNSUPPORT_INFO*, int type) {}
FPDF_BOOL Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) {
return true;
}
static void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) {}
static bool RenderPage(const FPDF_DOCUMENT& doc,
const FPDF_FORMHANDLE& form,
const int page_index) {
FPDF_PAGE page = FPDF_LoadPage(doc, page_index);
if (!page)
return false;
FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page);
FORM_OnAfterLoadPage(page, form);
FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN);
const double scale = 1.0;
int width = static_cast<int>(FPDF_GetPageWidth(page) * scale);
int height = static_cast<int>(FPDF_GetPageHeight(page) * scale);
FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0);
if (bitmap) {
FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0);
FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0);
FPDFBitmap_Destroy(bitmap);
}
FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
FORM_OnBeforeClosePage(page, form);
FPDFText_ClosePage(text_page);
FPDF_ClosePage(page);
return !!bitmap;
}
static void RenderPdf(const char* pBuf, size_t len) {
IPDF_JSPLATFORM platform_callbacks;
memset(&platform_callbacks, '\0', sizeof(platform_callbacks));
platform_callbacks.version = 3;
platform_callbacks.app_alert = ExampleAppAlert;
platform_callbacks.Doc_gotoPage = ExampleDocGotoPage;
FPDF_FORMFILLINFO form_callbacks;
memset(&form_callbacks, '\0', sizeof(form_callbacks));
form_callbacks.version = 1;
form_callbacks.m_pJsPlatform = &platform_callbacks;
TestLoader loader(pBuf, len);
FPDF_FILEACCESS file_access;
memset(&file_access, '\0', sizeof(file_access));
file_access.m_FileLen = static_cast<unsigned long>(len);
file_access.m_GetBlock = TestLoader::GetBlock;
file_access.m_Param = &loader;
FX_FILEAVAIL file_avail;
memset(&file_avail, '\0', sizeof(file_avail));
file_avail.version = 1;
file_avail.IsDataAvail = Is_Data_Avail;
FX_DOWNLOADHINTS hints;
memset(&hints, '\0', sizeof(hints));
hints.version = 1;
hints.AddSegment = Add_Segment;
FPDF_DOCUMENT doc;
int nRet = PDF_DATA_NOTAVAIL;
bool bIsLinearized = false;
FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access);
if (FPDFAvail_IsLinearized(pdf_avail) == PDF_LINEARIZED) {
doc = FPDFAvail_GetDocument(pdf_avail, nullptr);
if (doc) {
while (nRet == PDF_DATA_NOTAVAIL) {
nRet = FPDFAvail_IsDocAvail(pdf_avail, &hints);
}
if (nRet == PDF_DATA_ERROR) {
return;
}
nRet = FPDFAvail_IsFormAvail(pdf_avail, &hints);
if (nRet == PDF_FORM_ERROR || nRet == PDF_FORM_NOTAVAIL) {
return;
}
bIsLinearized = true;
}
} else {
doc = FPDF_LoadCustomDocument(&file_access, nullptr);
}
if (!doc) {
FPDFAvail_Destroy(pdf_avail);
return;
}
(void)FPDF_GetDocPermissions(doc);
FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnvironment(doc, &form_callbacks);
FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD);
FPDF_SetFormFieldHighlightAlpha(form, 100);
FORM_DoDocumentJSAction(form);
FORM_DoDocumentOpenAction(form);
int page_count = FPDF_GetPageCount(doc);
for (int i = 0; i < page_count; ++i) {
if (bIsLinearized) {
nRet = PDF_DATA_NOTAVAIL;
while (nRet == PDF_DATA_NOTAVAIL) {
nRet = FPDFAvail_IsPageAvail(pdf_avail, i, &hints);
}
if (nRet == PDF_DATA_ERROR) {
return;
}
}
RenderPage(doc, form, i);
}
FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC);
FPDFDOC_ExitFormFillEnvironment(form);
FPDF_CloseDocument(doc);
FPDFAvail_Destroy(pdf_avail);
}
std::string ProgramPath() {
#ifdef _MSC_VER
wchar_t wpath[MAX_PATH];
char path[MAX_PATH];
DWORD res = GetModuleFileName(NULL, wpath, MAX_PATH);
assert(res != 0);
wcstombs(path, wpath, MAX_PATH);
return std::string(path, res);
#else
char* path = new char[PATH_MAX + 1];
assert(path);
ssize_t sz = readlink("/proc/self/exe", path, PATH_MAX);
assert(sz > 0);
std::string result(path, sz);
delete[] path;
return result;
#endif
}
struct TestCase {
TestCase() {
InitializeV8ForPDFium(ProgramPath(), "", &natives_blob, &snapshot_blob,
&platform);
memset(&config, '\0', sizeof(config));
config.version = 2;
config.m_pUserFontPaths = nullptr;
config.m_pIsolate = nullptr;
config.m_v8EmbedderSlot = 0;
FPDF_InitLibraryWithConfig(&config);
memset(&unsupport_info, '\0', sizeof(unsupport_info));
unsupport_info.version = 1;
unsupport_info.FSDK_UnSupport_Handler = ExampleUnsupportedHandler;
FSDK_SetUnSpObjProcessHandler(&unsupport_info);
}
v8::Platform* platform;
v8::StartupData natives_blob;
v8::StartupData snapshot_blob;
FPDF_LIBRARY_CONFIG config;
UNSUPPORT_INFO unsupport_info;
};
static TestCase* testCase = new TestCase();
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
RenderPdf(reinterpret_cast<const char*>(data), size);
return 0;
}
| 28.556054 | 79 | 0.704774 | [
"vector"
] |
b0e1b28c8605f514684f80a9afa5ae633adf0309 | 3,052 | cpp | C++ | Rotas/Rotas/src/domain/cidade.cpp | fredrhae/rotas | fe63d474cfd7bff85f0d1a98851f6b8d98a23316 | [
"Apache-2.0"
] | null | null | null | Rotas/Rotas/src/domain/cidade.cpp | fredrhae/rotas | fe63d474cfd7bff85f0d1a98851f6b8d98a23316 | [
"Apache-2.0"
] | null | null | null | Rotas/Rotas/src/domain/cidade.cpp | fredrhae/rotas | fe63d474cfd7bff85f0d1a98851f6b8d98a23316 | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include "cidade.h"
using namespace std;
namespace rotas
{
namespace domain
{
string Cidade::get_nome() {
return nome;
}
int Cidade::get_id() {
return id;
}
bool Cidade::is_mediana() {
return mediana;
}
void Cidade::set_mediana(bool is_mediana) {
mediana = is_mediana;
}
int Cidade::get_id_mediana() {
return id_mediana;
}
void Cidade::set_id_mediana(int id) {
id_mediana = id;
}
void Cidade::add_rota(Rota rota)
{
rotas.push_back(rota);
}
void Cidade::set_rotas(vector<Rota> novas_rotas)
{
rotas.clear();
rotas = novas_rotas;
}
void Cidade::set_demanda(double nova_demanda)
{
this->demanda = nova_demanda;
}
void Cidade::set_capacidade(double capacidade)
{
this->capacidade = capacidade;
}
vector<Rota> Cidade::get_rotas()
{
return rotas;
}
double Cidade::get_distancia(Cidade destino) {
return get_distancia(destino.get_id());
}
double Cidade::get_distancia(Cidade *destino) {
return get_distancia(destino->get_id());
}
double Cidade::get_distancia(int id_destino) {
size_t size_rotas = rotas.size();
for (size_t i = 0; i < size_rotas; i++) {
if (rotas[i].get_id_destino() == id_destino) {
return rotas[i].get_distancia();
}
}
return 0.0;
}
double Cidade::get_demanda()
{
return demanda;
}
double Cidade::get_capacidade()
{
return capacidade;
}
bool Cidade::compara_distancia(Cidade destino_a, Cidade destino_b) {
return this->get_distancia(destino_a) < this->get_distancia(destino_b);
}
vector<Cidade*>* Cidade::ordena_por_distancia(vector<Cidade> *destinos) {
vector<Cidade*> *cidades_em_ordem = new vector<Cidade*>();
cidades_em_ordem->push_back(&(destinos->at(0)));
struct _compara_distancia {
Cidade *origem;
bool operator() (Cidade *a, Cidade *b) { return origem->get_distancia(*a) < origem->get_distancia(*b); }
} compara_distancia;
compara_distancia.origem = this;
for (size_t i = 1; i < destinos->size(); i++) {
auto it = upper_bound(cidades_em_ordem->begin(), cidades_em_ordem->end(), &(destinos->at(i)), compara_distancia);
cidades_em_ordem->insert(it, &(destinos->at(i)));
}
return cidades_em_ordem;
}
Cidade* Cidade::encontra_mais_proxima(vector<Cidade> *destinos)
{
Cidade *mais_proxima = &(destinos->at(0));
double menor_distancia = this->get_distancia(*mais_proxima);
for (unsigned int i = 0; i < destinos->size(); i++) {
double distancia = this->get_distancia(destinos->at(i));
if (distancia < menor_distancia) {
menor_distancia = distancia;
mais_proxima = &(destinos->at(i));
}
}
return mais_proxima;
}
bool Cidade::aloca_demanda(double demanda)
{
if (demanda > capacidade) {
return false;
}
else {
capacidade -= demanda;
return true;
}
}
} // domain
} // rotas | 21.8 | 118 | 0.625819 | [
"vector"
] |
b0e2e7b61faa5afbad69a240a50b8677a54f208d | 1,699 | cpp | C++ | android-31/javax/net/SocketFactory.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/javax/net/SocketFactory.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/javax/net/SocketFactory.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JString.hpp"
#include "../../java/net/InetAddress.hpp"
#include "../../java/net/Socket.hpp"
#include "./SocketFactory.hpp"
namespace javax::net
{
// Fields
// QJniObject forward
SocketFactory::SocketFactory(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
javax::net::SocketFactory SocketFactory::getDefault()
{
return callStaticObjectMethod(
"javax.net.SocketFactory",
"getDefault",
"()Ljavax/net/SocketFactory;"
);
}
java::net::Socket SocketFactory::createSocket() const
{
return callObjectMethod(
"createSocket",
"()Ljava/net/Socket;"
);
}
java::net::Socket SocketFactory::createSocket(JString arg0, jint arg1) const
{
return callObjectMethod(
"createSocket",
"(Ljava/lang/String;I)Ljava/net/Socket;",
arg0.object<jstring>(),
arg1
);
}
java::net::Socket SocketFactory::createSocket(java::net::InetAddress arg0, jint arg1) const
{
return callObjectMethod(
"createSocket",
"(Ljava/net/InetAddress;I)Ljava/net/Socket;",
arg0.object(),
arg1
);
}
java::net::Socket SocketFactory::createSocket(JString arg0, jint arg1, java::net::InetAddress arg2, jint arg3) const
{
return callObjectMethod(
"createSocket",
"(Ljava/lang/String;ILjava/net/InetAddress;I)Ljava/net/Socket;",
arg0.object<jstring>(),
arg1,
arg2.object(),
arg3
);
}
java::net::Socket SocketFactory::createSocket(java::net::InetAddress arg0, jint arg1, java::net::InetAddress arg2, jint arg3) const
{
return callObjectMethod(
"createSocket",
"(Ljava/net/InetAddress;ILjava/net/InetAddress;I)Ljava/net/Socket;",
arg0.object(),
arg1,
arg2.object(),
arg3
);
}
} // namespace javax::net
| 23.273973 | 132 | 0.685109 | [
"object"
] |
b0e5465558a589cc735b8c1ebb39d87f8be21a27 | 11,504 | cpp | C++ | estun/src/renderer/context/device.cpp | ibvfteh/watersim | 8a524f9290c49b84889785160ce875d524ed190b | [
"MIT"
] | null | null | null | estun/src/renderer/context/device.cpp | ibvfteh/watersim | 8a524f9290c49b84889785160ce875d524ed190b | [
"MIT"
] | null | null | null | estun/src/renderer/context/device.cpp | ibvfteh/watersim | 8a524f9290c49b84889785160ce875d524ed190b | [
"MIT"
] | null | null | null | #include "renderer/context/device.h"
#include "renderer/context/instance.h"
#include "renderer/context/surface.h"
#include "renderer/context/validation_layers.h"
#include <set>
#include <iostream>
estun::Device *estun::DeviceLocator::currDevice = nullptr;
estun::Device::~Device()
{
vkDestroyDevice(logicalDevice, nullptr);
}
estun::Device::Device(estun::Instance *instance, estun::Surface *surface)
{
PickPhysicalDevice(instance, surface);
CreateLogicalDevice(instance, surface);
}
uint32_t estun::Device::GetQueueFamilyIndex(std::vector<VkQueueFamilyProperties> queueFamilyProperties, VkQueueFlagBits queueFlags)
{
if (queueFlags & VK_QUEUE_COMPUTE_BIT)
{
for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilyProperties.size()); i++)
{
if ((queueFamilyProperties[i].queueFlags & queueFlags) && ((queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0))
{
return i;
break;
}
}
}
if (queueFlags & VK_QUEUE_TRANSFER_BIT)
{
for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilyProperties.size()); i++)
{
if ((queueFamilyProperties[i].queueFlags & queueFlags) && ((queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0) && ((queueFamilyProperties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) == 0))
{
return i;
break;
}
}
}
for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilyProperties.size()); i++)
{
if (queueFamilyProperties[i].queueFlags & queueFlags)
{
return i;
break;
}
}
ES_CORE_ASSERT("Could not find a matching queue family index");
}
estun::QueueFamilyIndices estun::Device::FindQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface)
{
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
indices.graphicsFamily = GetQueueFamilyIndex(queueFamilies, VK_QUEUE_GRAPHICS_BIT);
indices.computeFamily = GetQueueFamilyIndex(queueFamilies, VK_QUEUE_COMPUTE_BIT);
indices.transferFamily = GetQueueFamilyIndex(queueFamilies, VK_QUEUE_TRANSFER_BIT);
for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilies.size()); i++)
{
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
if (presentSupport)
{
indices.presentFamily = i;
}
}
return indices;
}
bool estun::Device::CheckDeviceExtensionSupport(VkPhysicalDevice device)
{
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto &extension : availableExtensions)
{
requiredExtensions.erase(extension.extensionName);
}
for (const auto &extension : requiredExtensions)
{
ES_CORE_WARN(std::string("Could not find extention: ") + extension);
}
return requiredExtensions.empty();
}
bool estun::Device::IsDeviceSuitable(VkPhysicalDevice device, estun::Surface *surface)
{
QueueFamilyIndices indices = FindQueueFamilies(device, surface->GetSurface());
bool extensionsSupported = CheckDeviceExtensionSupport(device);
VkPhysicalDeviceFeatures supportedFeatures;
vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
bool swapChainAdequate = false;
if (extensionsSupported)
{
SwapChainSupportDetails swapChainSupport = QuerySwapChainSupport(device, surface);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
}
return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
}
VkSampleCountFlagBits estun::Device::GetMaxUsableSampleCount()
{
VkPhysicalDeviceProperties physicalDeviceProperties;
vkGetPhysicalDeviceProperties(physicalDevice, &physicalDeviceProperties);
VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
if (counts & VK_SAMPLE_COUNT_64_BIT)
{
return VK_SAMPLE_COUNT_64_BIT;
}
if (counts & VK_SAMPLE_COUNT_32_BIT)
{
return VK_SAMPLE_COUNT_32_BIT;
}
if (counts & VK_SAMPLE_COUNT_16_BIT)
{
return VK_SAMPLE_COUNT_16_BIT;
}
if (counts & VK_SAMPLE_COUNT_8_BIT)
{
return VK_SAMPLE_COUNT_8_BIT;
}
if (counts & VK_SAMPLE_COUNT_4_BIT)
{
return VK_SAMPLE_COUNT_4_BIT;
}
if (counts & VK_SAMPLE_COUNT_2_BIT)
{
return VK_SAMPLE_COUNT_2_BIT;
}
return VK_SAMPLE_COUNT_1_BIT;
}
void estun::Device::PickPhysicalDevice(estun::Instance *instance, estun::Surface *surface)
{
physicalDevice = VK_NULL_HANDLE;
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(*instance->GetVulkanInstance(), &deviceCount, nullptr);
if (deviceCount == 0)
{
ES_CORE_ASSERT("Failed to find GPUs with Vulkan support");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(*instance->GetVulkanInstance(), &deviceCount, devices.data());
for (const auto &device : devices)
{
if (IsDeviceSuitable(device, surface))
{
physicalDevice = device;
msaaSamples = GetMaxUsableSampleCount();
break;
}
}
if (physicalDevice == VK_NULL_HANDLE)
{
ES_CORE_ASSERT("Failed to find a suitable GPU");
}
}
void estun::Device::CreateLogicalDevice(estun::Instance *instance, estun::Surface *surface)
{
currIndices = FindQueueFamilies(physicalDevice, surface->GetSurface());
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies = {currIndices.graphicsFamily.value(),
currIndices.presentFamily.value(),
currIndices.computeFamily.value(),
currIndices.transferFamily.value()};
float queuePriority = 1.0f;
for (uint32_t queueFamily : uniqueQueueFamilies)
{
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures = {};
deviceFeatures.samplerAnisotropy = VK_TRUE;
deviceFeatures.shaderClipDistance = VK_TRUE;
deviceFeatures.geometryShader = VK_TRUE;
deviceFeatures.fillModeNonSolid = VK_TRUE;
VkPhysicalDeviceDescriptorIndexingFeaturesEXT indexingFeatures = {};
indexingFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT;
indexingFeatures.runtimeDescriptorArray = true;
VkPhysicalDeviceBufferDeviceAddressFeatures deviceAddressFeatures = {};
deviceAddressFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES;
deviceAddressFeatures.pNext = &indexingFeatures;
deviceAddressFeatures.bufferDeviceAddress = VK_TRUE;
VkDeviceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.pNext = &deviceAddressFeatures; // deviceAddressFeatures
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
if (ValidationLayers::IsEnabled())
{
createInfo.enabledLayerCount = static_cast<uint32_t>(instance->GetValidationLayers()->GetLayers()->size());
createInfo.ppEnabledLayerNames = instance->GetValidationLayers()->GetLayers()->data();
}
else
{
createInfo.enabledLayerCount = 0;
}
VK_CHECK_RESULT(vkCreateDevice(physicalDevice, &createInfo, nullptr, &logicalDevice), "Failed to create logical device");
vkGetDeviceQueue(logicalDevice, currIndices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(logicalDevice, currIndices.presentFamily.value(), 0, &presentQueue);
vkGetDeviceQueue(logicalDevice, currIndices.computeFamily.value(), 0, &computeQueue);
vkGetDeviceQueue(logicalDevice, currIndices.transferFamily.value(), 0, &transferQueue);
}
estun::QueueFamilyIndices estun::Device::GetQueueFamilyIndices() const
{
return currIndices;
}
VkSampleCountFlagBits estun::Device::GetMsaaSamples() const
{
return msaaSamples;
}
VkPhysicalDevice &estun::Device::GetPhysicalDevice()
{
return physicalDevice;
}
VkDevice &estun::Device::GetLogicalDevice()
{
return logicalDevice;
}
VkQueue estun::Device::GetGraphicsQueue()
{
return graphicsQueue;
}
VkQueue estun::Device::GetPresentQueue()
{
return presentQueue;
}
VkQueue estun::Device::GetComputeQueue()
{
return computeQueue;
}
VkQueue estun::Device::GetTransferQueue()
{
return transferQueue;
}
void estun::Device::WaitIdle() const
{
VK_CHECK_RESULT(vkDeviceWaitIdle(logicalDevice), "Wait for device idle");
}
estun::SwapChainSupportDetails
estun::Device::QuerySwapChainSupport(VkPhysicalDevice device, estun::Surface *surface)
{
SwapChainSupportDetails details;
VkSurfaceKHR rawSurface = surface->GetSurface();
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, rawSurface, &details.capabilities);
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, rawSurface, &formatCount, nullptr);
if (formatCount != 0)
{
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, rawSurface, &formatCount, details.formats.data());
}
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, rawSurface, &presentModeCount, nullptr);
if (presentModeCount != 0)
{
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, rawSurface, &presentModeCount, details.presentModes.data());
}
return details;
}
estun::Device &estun::DeviceLocator::GetDevice()
{
if (currDevice == nullptr)
{
ES_CORE_ASSERT("Failed to request vulkan device");
}
return *currDevice;
};
VkDevice &estun::DeviceLocator::GetLogicalDevice()
{
if (currDevice == nullptr)
{
ES_CORE_ASSERT("Failed to request vulkan device");
}
return currDevice->GetLogicalDevice();
};
VkPhysicalDevice &estun::DeviceLocator::GetPhysicalDevice()
{
if (currDevice == nullptr)
{
ES_CORE_ASSERT("Failed to request vulkan device");
}
return currDevice->GetPhysicalDevice();
};
| 32.22409 | 210 | 0.715838 | [
"vector"
] |
b0ed7d8928fa7c667f9956e956b9834d6a5a7733 | 5,818 | cpp | C++ | interpreter/src/sm_state_machine.cpp | straceX/asminterpreter | e06d650989a69008c6ac277575982ca09ff51339 | [
"Apache-2.0"
] | null | null | null | interpreter/src/sm_state_machine.cpp | straceX/asminterpreter | e06d650989a69008c6ac277575982ca09ff51339 | [
"Apache-2.0"
] | null | null | null | interpreter/src/sm_state_machine.cpp | straceX/asminterpreter | e06d650989a69008c6ac277575982ca09ff51339 | [
"Apache-2.0"
] | null | null | null | #include "sm_state_machine.h"
#include <functional>
#include <iostream>
using namespace SM;
StateMachine::StateMachine(std::vector<std::tuple<int, std::string, std::optional<int>>> &afterTokens)
{
for (const auto &line : afterTokens)
m_stackExecute.emplace_back(std::make_pair(std::get<1>(line), std::get<2>(line)));
m_stackExecute.emplace_back(std::make_pair("NULL", std::nullopt));
}
//READ: reads an integer on stdin and push the value on the stack, or exit if input is invalid
auto StateMachine::READ() noexcept
-> void
{
int pushIval;
std::cin >> pushIval;
if (std::cin.fail())
return;
m_stateMachineStack.push(pushIval);
//std::cout << "User entered integer: " << pushIval;
++m_stackExecuteIndex;
}
//WRITE : pops the top value of the stack, and prints it on stdout
auto StateMachine::WRITE() noexcept
-> void
{
std::cout << *m_stateMachineStack.pop();
++m_stackExecuteIndex;
}
//DUP : duplicate the value on top of the stack
auto StateMachine::DUP() noexcept
-> void
{
m_stateMachineStack.push(*m_stateMachineStack.top());
++m_stackExecuteIndex;
}
//MUL : pops the two top value of the stack, multiply them and push the result on top of the stack
auto StateMachine::MUL() noexcept
-> void
{
if (m_stateMachineStack.getSize() < 2)
{
++m_stackExecuteIndex;
return;
}
auto ivalTop = *m_stateMachineStack.pop();
auto ivalBottom = *m_stateMachineStack.pop();
m_stateMachineStack.push(ivalTop * ivalBottom); //TODO: stack safe
++m_stackExecuteIndex;
}
//ADD : pops the two top value of the stack, add them and push the result on top of the stack
auto StateMachine::ADD() noexcept
-> void
{
auto ivalTop = *m_stateMachineStack.pop();
auto ivalBottom = *m_stateMachineStack.pop();
m_stateMachineStack.push(ivalTop + ivalBottom);
++m_stackExecuteIndex;
}
//SUB : pops the two top value of the stack, sub the TOP with the SECOND and push the result on the stack
auto StateMachine::SUB() noexcept
-> void
{
auto ivalTop = *m_stateMachineStack.pop();
auto ivalBottom = *m_stateMachineStack.pop();
m_stateMachineStack.push(ivalTop - ivalBottom);
++m_stackExecuteIndex;
}
//GT : pops the two top values from the stack, compare them for TOP > SECOND and push the result as 0 or 1 on the stack
auto StateMachine::GT() noexcept
-> void
{
auto ivalTop = *m_stateMachineStack.pop();
auto ivalBottom = *m_stateMachineStack.pop();
m_stateMachineStack.push(ivalTop > ivalBottom ? 1 : 0);
++m_stackExecuteIndex;
}
//LT : pops the two top values from the stack, compare them for TOP < SECOND and push the result as 0 or 1 on the stack
auto StateMachine::LT() noexcept
-> void
{
auto ivalTop = *m_stateMachineStack.pop();
auto ivalBottom = *m_stateMachineStack.pop();
m_stateMachineStack.push(ivalTop < ivalBottom ? 1 : 0);
++m_stackExecuteIndex;
}
//EQ : pops the two top values from the stack, compare them for TOP == SECOND and push the result as 0 or 1 on the stack
auto StateMachine::EQ() noexcept
-> void
{
auto ivalTop = *m_stateMachineStack.pop();
auto ivalBottom = *m_stateMachineStack.pop();
m_stateMachineStack.push(ivalTop == ivalBottom ? 1 : 0);
++m_stackExecuteIndex;
}
//JMPZ : pops the two top value of the stack. Jump to the <n>th instruction, where <n> was the first value on the stack,
//if the second value is null. Otherwise just drop these two values
auto StateMachine::JMPZ() noexcept
-> void
{
//m_stateMachineStack.printStack();
auto ivalTop = *m_stateMachineStack.pop();
if (auto ivalBottom = m_stateMachineStack.pop(); ivalBottom.has_value() && *ivalBottom == 0) {
m_stackExecuteIndex = ivalTop;
return;
}
//m_stateMachineStack.printStack();
++m_stackExecuteIndex;
}
//PUSH <n> : push the integer value <n> on the stack
auto StateMachine::PUSH(int newElement) noexcept
-> void
{
m_stateMachineStack.push(newElement); //TODO: emplace(C++11)
++m_stackExecuteIndex;
}
//POP <n> : pop n value from the stack
auto StateMachine::POP(int deleteCount) noexcept
-> void
{
if (deleteCount < 1) return;
m_stateMachineStack.deleteStackElements(deleteCount);
++m_stackExecuteIndex;
}
//ROT <n> : perform a circular rotation on the first n value of the stack toward the top
//for instance the stack : BOTTOM[1, 2, 4, 8] TOP becomes BOTTOM [1, 8, 2, 4] TOP after ROT 3
auto StateMachine::ROT(int rotateNumber) noexcept
-> void
{
if (rotateNumber > m_stateMachineStack.getSize()) return;
m_stateMachineStack.rotate(rotateNumber);
++m_stackExecuteIndex;
}
auto StateMachine::convertKeytoExecute(std::string key, std::optional<int> extraCommand = std::nullopt) noexcept
-> void
{
if (extraCommand.has_value())
{
if (const auto res = m_executeMapOneParam.find(key); res != m_executeMapOneParam.cend())
{
std::invoke(res->second, this, *extraCommand);
}
else
{
std::cout << key << "...\n";
std::cerr << "Error: " << __FILE__ << ':' << __LINE__ << '\n';
m_stackExecuteIndex++;
}
return;
}
if (const auto res = m_executeMap.find(key); res != m_executeMap.cend())
{
std::invoke(res->second, this);
}
else
{
std::cout << key << ",,,\n";
std::cerr << "Error: " << __FILE__ << ':' << __LINE__ << '\n';
m_stackExecuteIndex++;
}
}
auto StateMachine::execute() noexcept
-> void
{
while (m_stackExecute[m_stackExecuteIndex].first != "NULL")
{
convertKeytoExecute(m_stackExecute[m_stackExecuteIndex].first, m_stackExecute[m_stackExecuteIndex].second);
}
} | 31.112299 | 121 | 0.662427 | [
"vector"
] |
b0ed7f9e92232b595d8dc1c945c65e0d23a7e3dd | 3,861 | cc | C++ | MathUtils/test/measurement_format.cc | yimuchen/UserUtils | 1a5c55d286f325424f4cfd23f22da63cfa6fb6a9 | [
"MIT"
] | null | null | null | MathUtils/test/measurement_format.cc | yimuchen/UserUtils | 1a5c55d286f325424f4cfd23f22da63cfa6fb6a9 | [
"MIT"
] | 1 | 2021-12-10T15:04:04.000Z | 2022-01-10T18:56:53.000Z | MathUtils/test/measurement_format.cc | yimuchen/UserUtils | 1a5c55d286f325424f4cfd23f22da63cfa6fb6a9 | [
"MIT"
] | 1 | 2018-06-05T14:08:08.000Z | 2018-06-05T14:08:08.000Z | /*******************************************************************************
*
* Filename : parameter_format.cc
* Description : Unit testing for parameter formatting functions
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#ifdef CMSSW_GIT_HASH
#include "UserUtils/Common/interface/STLUtils.hpp"
#include "UserUtils/MathUtils/interface/Measurement.hpp"
#else
#include "UserUtils/Common/STLUtils.hpp"
#include "UserUtils/MathUtils/Measurement.hpp"
#endif
#include <boost/format.hpp>
#include <iostream>
#include <regex>
using namespace std;
using namespace usr;
int
main( int argc, char const* argv[] )
{
/*----------------------------------------------------------------------------*/
cout << separator() << endl
<< ">>> decimal reinterfacing test testing" << endl;
{
for( int i = -1; i < 15; ++i ){
usr::fout( "Precision: %2d | %30s\n"
, i
, usr::fmt::decimal( 12345679123456, i ) );
}
for( int i = -1; i < 15; ++i ){
usr::fout( "Precision: %2d | %30s\n"
, i, usr::fmt::decimal( 12345679.123456, i ) );
}
}
/*----------------------------------------------------------------------------*/
cout << separator() << endl
<< ">>> scientific reinterfacing test testing" << endl;
{
for( int i = -1; i < 15; ++i ){
usr::fout( "Precision: %2d | %30s\n"
, i
, usr::fmt::scientific( 12345679123456, i ) );
}
for( int i = -1; i < 15; ++i ){
usr::fout( "Precision: %2d | %30s\n"
, i, usr::fmt::scientific( 12345679.123456, i ) );
}
}
/*----------------------------------------------------------------------------*/
cout << separator() << endl
<< ">>> Generic test" << endl;
{
const Measurement x( 123, 23, 0.01 );
const Measurement y( 123, 10.23, 10.21 );
for( int i = 0; i < 6; ++i ){
usr::fout( "%35s|%45s\n", fmt::decimal( x, i ), fmt::scientific( x, i ) );
}
for( int i = 0; i < 6; ++i ){
usr::fout( "%35s|%45s\n", fmt::decimal( y, i ), fmt::scientific( y, i ) );
}
}
/*----------------------------------------------------------------------------*/
cout << separator() << endl
<< "Auto-precision testing" << endl;
{
const vector<Measurement> list = {
Measurement( 20.1, 1, 0.1 ),
Measurement( 20.1, 1, 1.2 ),
Measurement( 201, 1, 1.2 ),
Measurement( 2.055, 1, 1.2 )
};
for( const auto& m : list ){
usr::fout( "%20s|%40s\n"
, fmt::decimal( m, -1 )
, fmt::scientific( m, -1 ) );
}
}
/*----------------------------------------------------------------------------*/
cout << separator() << endl
<< "Common distribution testing: Poisson" << endl;
{
usr::fout( "%20s | %20s | %20s\n"
, "Lazy", "Minos", "CMS StatComm" );
for( const auto val : {0, 1, 2, 3, 4} ){
usr::fout( "%20s | %20s | %20s\n"
, fmt::decimal( Poisson::Lazy( val ), -1 )
, fmt::decimal( Poisson::Minos( val ), -1 )
, fmt::decimal( Poisson::CMSStatCom( val ), -1 )
);
}
}
/*----------------------------------------------------------------------------*/
cout << separator() << endl
<< "Common distribution testing: Binomial" << endl;
{
usr::fout( "%20s | %20s | %20s\n"
, "Lazy", "Minos", "CP method" );
for( const auto val : {0, 1, 2, 3, 4} ){
usr::fout( "%20s | %20s | %20s\n"
, fmt::decimal( Efficiency::Lazy( 149.9, 7780 ), -1 )
, fmt::decimal( Efficiency::Minos( 149.9, 7780 ), -1 )
, fmt::decimal( Efficiency::ClopperPearson( 149.9, 7780 ), -1 )
);
}
}
return 0;
}
| 30.401575 | 80 | 0.418544 | [
"vector"
] |
b0f252b56008e5bc244bd3717239813631701bf3 | 2,531 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_dal/dal_MatrixDriver.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_dal/dal_MatrixDriver.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_dal/dal_MatrixDriver.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #ifndef INCLUDED_DAL_MATRIXDRIVER
#include "dal_MatrixDriver.h"
#define INCLUDED_DAL_MATRIXDRIVER
#endif
// Library headers.
// PCRaster library headers.
// Module headers.
#ifndef INCLUDED_DAL_UTILS
#include "dal_Utils.h"
#define INCLUDED_DAL_UTILS
#endif
/*!
\file
This file contains the implementation of the MatrixDriver class.
*/
namespace dal {
//------------------------------------------------------------------------------
// DEFINITION OF STATIC MATRIXDRIVER MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF MATRIXDRIVER MEMBERS
//------------------------------------------------------------------------------
//! Constructor.
/*!
\param name Name of the driver.
\param description Description of the driver.
*/
MatrixDriver::MatrixDriver(
Format const& format)
: Driver(format)
{
}
//! Destructor.
/*!
*/
MatrixDriver::~MatrixDriver()
{
}
//! Opens the matrix with name \a name and reads the data.
/*!
\return Pointer to Matrix object.
\exception Exception In case the matrix cannot be opened.
\sa read(std::string&, Matrix&)
This function will return a Matrix object or throw an exception.
The matrix is read using the matrix properties deduced by
open(std::string const&). If the matrix properties are known by the client
than it should call open(std::string const& name), configure the matrix
and call read(std::string const&, Matrix*).
*/
Matrix* MatrixDriver::read(std::string const& name) const
{
Matrix* matrix = dynamic_cast<Matrix*>(open(name));
if(!matrix) {
throwCannotBeOpened(name, MATRIX);
}
read(name, *matrix);
return matrix;
}
void MatrixDriver::read(
void* cell,
TypeId
#ifdef DEBUG_BUILD
typeId
#endif
,
std::string const& /* name */,
DataSpace const& /* space */,
DataSpaceAddress const& /* address */) const
{
assert(typeId == TI_REAL4);
pcr::setMV(*static_cast<REAL4*>(cell));
}
//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------
} // namespace dal
| 21.449153 | 80 | 0.505334 | [
"object"
] |
7c0a1baad8aeb7f0bed851cae7a8824b84146877 | 953 | cpp | C++ | graph-source-code/389-D/5899258.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/389-D/5899258.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/389-D/5899258.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include<bits/stdc++.h>
using namespace std;
#define REP0(i,n) for(int i=0;i<n;++i)
#define REP1(i,n) for(int i=1;i<=n;++i)
#define ALL(c) (c).begin(),(c).end()
vector<string> G(1000);
int now=1;
void con(int a,int b){
// if(b==1 || a==1) cout << a << b << endl;
G[a][b]='Y';
G[b][a]='Y';
return;
}
int main(){
int k;
cin >> k;
string sss(1000,'N');
REP0(i,1000) G[i]=sss;
for(int i=0;k>0;i++){
if(k%10){
REP1(p,k%10){
con(0,now+p);
con(now+k%10+1,now+p);
}
now=now+k%10+1;
REP0(j,i){
REP1(p,10){
con(now,now+p);
con(now+11,now+p);
}
now=now+11;
}
REP0(j,20-2*i){
con(now,now+1);
now++;
}
con(now,1);
now++;
}
k/=10;
if(k==0) break;
}
cout << now << endl;
REP0(i,now){
REP0(j,now){
//if(G[i][j]=='Y') cout << i << " " << j << endl;
cout << G[i][j];
}
cout << endl;
}
return 0;
} | 16.719298 | 53 | 0.452256 | [
"vector"
] |
7c176f2d7e93022bda171daed28c8b452ffabcc2 | 7,706 | cpp | C++ | ref-impl/src/impl/ImplAAFSoundDescriptor.cpp | Phygon/aaf | faef720e031f501190481e1d1fc1870a7dc8f98b | [
"Linux-OpenIB"
] | null | null | null | ref-impl/src/impl/ImplAAFSoundDescriptor.cpp | Phygon/aaf | faef720e031f501190481e1d1fc1870a7dc8f98b | [
"Linux-OpenIB"
] | null | null | null | ref-impl/src/impl/ImplAAFSoundDescriptor.cpp | Phygon/aaf | faef720e031f501190481e1d1fc1870a7dc8f98b | [
"Linux-OpenIB"
] | null | null | null | //=---------------------------------------------------------------------=
//
// $Id$ $Name$
//
// The contents of this file are subject to the AAF SDK Public Source
// License Agreement Version 2.0 (the "License"); You may not use this
// file except in compliance with the License. The License is available
// in AAFSDKPSL.TXT, or you may obtain a copy of the License from the
// Advanced Media Workflow Association, Inc., or its successor.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and limitations
// under the License. Refer to Section 3.3 of the License for proper use
// of this Exhibit.
//
// WARNING: Please contact the Advanced Media Workflow Association,
// Inc., for more information about any additional licenses to
// intellectual property covering the AAF Standard that may be required
// to create and distribute AAF compliant products.
// (http://www.amwa.tv/policies).
//
// Copyright Notices:
// The Original Code of this file is Copyright 1998-2009, licensor of the
// Advanced Media Workflow Association. All rights reserved.
//
// The Initial Developer of the Original Code of this file and the
// licensor of the Advanced Media Workflow Association is
// Avid Technology.
// All rights reserved.
//
//=---------------------------------------------------------------------=
#include "OMAssertions.h"
#include "ImplAAFSoundDescriptor.h"
#include "AAFPropertyIDs.h"
ImplAAFSoundDescriptor::ImplAAFSoundDescriptor() :
_compression( PID_SoundDescriptor_Compression, L"Compression"),
_channels( PID_SoundDescriptor_Channels, L"Channels"),
_audioSamplingRate( PID_SoundDescriptor_AudioSamplingRate, L"AudioSamplingRate"),
_locked( PID_SoundDescriptor_Locked, L"Locked"),
_electroSpatial( PID_SoundDescriptor_ElectroSpatial, L"ElectroSpatial"),
_audioRefLevel( PID_SoundDescriptor_AudioRefLevel, L"AudioRefLevel"),
_dialNorm( PID_SoundDescriptor_DialNorm, L"DialNorm"),
_quantizationBits( PID_SoundDescriptor_QuantizationBits, L"QuantizationBits")
{
_persistentProperties.put( _compression.address() );
_persistentProperties.put( _channels.address() );
_persistentProperties.put( _audioSamplingRate.address() );
_persistentProperties.put( _locked.address() );
_persistentProperties.put( _electroSpatial.address() );
_persistentProperties.put( _audioRefLevel.address() );
_persistentProperties.put( _dialNorm.address() );
_persistentProperties.put( _quantizationBits.address() );
// Initialize the required properties with bogus values.
// Initialize() may be called to complete initialization
// of the object.
_channels = 0;
const aafRational_t null_rational = { 0, 0 };
_audioSamplingRate = null_rational;
_quantizationBits = 0;
}
ImplAAFSoundDescriptor::~ImplAAFSoundDescriptor()
{
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::Initialize()
{
// ImplAAFSoundDescriptor::Initialize() cannot be called directly by a client
// application because an Initialize() method was omitted from
// IAAFSoundDescriptor.
// As a result, this implementation does not require the object to be
// initialized. However, to support derived classes, which may have
// public Initialize() methods that wish in turn to initialize this
// class, this Initialize() method is provided.
// It doesn't do anything beyond that done in the constructor.
ASSERTU( !isInitialized() );
// Initialize required properties
_channels = 0;
const aafRational_t null_rational = { 0, 0 };
_audioSamplingRate = null_rational;
_quantizationBits = 0;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetCompression(
const aafUID_t& compression )
{
_compression = compression;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::GetCompression(
aafUID_t* pCompression )
{
if( pCompression == 0 )
{
return AAFRESULT_NULL_PARAM;
}
if( !_compression.isPresent() )
{
return AAFRESULT_PROP_NOT_PRESENT;
}
*pCompression = _compression;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetChannelCount(
aafUInt32 channelCount )
{
_channels = channelCount;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::GetChannelCount(
aafUInt32* pChannelCount )
{
if( pChannelCount == 0 )
{
return AAFRESULT_NULL_PARAM;
}
*pChannelCount = _channels;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetAudioSamplingRate(
aafRational_t rate )
{
_audioSamplingRate = rate;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::GetAudioSamplingRate(
aafRational_t* pRate )
{
if( pRate == 0 )
{
return AAFRESULT_NULL_PARAM;
}
*pRate = _audioSamplingRate;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetIsLocked(
aafBoolean_t locked )
{
_locked = locked;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::IsLocked(
aafBoolean_t* pLocked )
{
if( pLocked == 0 )
{
return AAFRESULT_NULL_PARAM;
}
if( !_locked.isPresent() )
{
return AAFRESULT_PROP_NOT_PRESENT;
}
*pLocked = _locked;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetElectroSpatialFormulation(
aafElectroSpatialFormulation_t electroSpatialFormulation )
{
_electroSpatial = electroSpatialFormulation;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::GetElectroSpatialFormulation(
aafElectroSpatialFormulation_t* pElectroSpatialFormulation )
{
if( pElectroSpatialFormulation == 0 )
{
return AAFRESULT_NULL_PARAM;
}
if( !_electroSpatial.isPresent() )
{
return AAFRESULT_PROP_NOT_PRESENT;
}
*pElectroSpatialFormulation = _electroSpatial;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetAudioRefLevel(
aafInt8 level )
{
_audioRefLevel = level;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::GetAudioRefLevel(
aafInt8* pLevel )
{
if( pLevel == 0 )
{
return AAFRESULT_NULL_PARAM;
}
if( !_audioRefLevel.isPresent() )
{
return AAFRESULT_PROP_NOT_PRESENT;
}
*pLevel = _audioRefLevel;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetDialNorm(
aafInt8 dialNorm )
{
_dialNorm = dialNorm;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::GetDialNorm(
aafInt8* pDialNorm )
{
if( pDialNorm == 0 )
{
return AAFRESULT_NULL_PARAM;
}
if( !_dialNorm.isPresent() )
{
return AAFRESULT_PROP_NOT_PRESENT;
}
*pDialNorm = _dialNorm;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::SetQuantizationBits(
aafUInt32 bitsCount )
{
_quantizationBits = bitsCount;
return AAFRESULT_SUCCESS;
}
AAFRESULT STDMETHODCALLTYPE ImplAAFSoundDescriptor::GetQuantizationBits(
aafUInt32* pBitsCount )
{
if( pBitsCount == 0 )
{
return AAFRESULT_NULL_PARAM;
}
*pBitsCount = _quantizationBits;
return AAFRESULT_SUCCESS;
}
| 22.017143 | 86 | 0.709058 | [
"object"
] |
7c297ff015ee6600f14f2d5c540c76d2b40af1b5 | 15,603 | cpp | C++ | src/ppmdu/pmd2/pmd2_gameloader.cpp | SkyTemple/ppmdu | 9731ea103affd66f2e8c1202c9acb2ebfd4c9924 | [
"CC0-1.0"
] | 37 | 2015-10-30T21:56:26.000Z | 2021-11-30T15:33:26.000Z | src/ppmdu/pmd2/pmd2_gameloader.cpp | SkyTemple/ppmdu | 9731ea103affd66f2e8c1202c9acb2ebfd4c9924 | [
"CC0-1.0"
] | 27 | 2015-01-06T05:45:55.000Z | 2020-01-29T21:40:22.000Z | src/ppmdu/pmd2/pmd2_gameloader.cpp | SkyTemple/ppmdu | 9731ea103affd66f2e8c1202c9acb2ebfd4c9924 | [
"CC0-1.0"
] | 8 | 2016-02-07T23:31:03.000Z | 2020-07-12T08:51:41.000Z | #include "pmd2_gameloader.hpp"
#include <utils/utility.hpp>
#include <utils/library_wide.hpp>
#include <ppmdu/pmd2/pmd2.hpp>
#include <fstream>
using namespace std;
using utils::logutil::slog;
namespace pmd2
{
//===========================================================================================
// GameDataLoader
//===========================================================================================
GameDataLoader::GameDataLoader( const std::string & romroot, const std::string & gamelangxml )
:m_romroot(romroot), m_configfile(gamelangxml),m_bAnalyzed(false)
{}
GameDataLoader::~GameDataLoader()
{
slog()<<"<!>-GameDataLoader: Deallocating..\n";
//We delete the unique ptr in order here, to avoid issues with circular ownership
m_audio .reset(nullptr);
m_graphics.reset(nullptr);
m_stats .reset(nullptr);
m_asmmanip.reset(nullptr);
//Levels depend on script via shared ptr, so delete it before deleting scripts!
m_levels .reset(nullptr);
m_scripts .reset();
//Text has to be destroyed last after scripts and stats to avoid possible circular ownership lockups
if( m_text.use_count() > 0 )
slog()<<"<!>- Warning! While destroying the Gameloader object, there were still " <<m_text.use_count() <<" others owner of the GameText pointer!!\n";
m_text.reset();
}
void GameDataLoader::AnalyseGame()
{
//Look for arm9.bin, then for the data/MESSAGE and data/BALANCE folder content
auto filelst = utils::ListDirContent_FilesAndDirs( m_romroot, true, true );
bool bfoundarm9 = false;
bool bfoundoverlay = false;
bool bfounddata = false;
slog()<<"<!>-GameDataLoader: Analyzing game folder..\n";
for( const auto & fname : filelst )
{
if( fname == DirName_DefData )
bfounddata = true;
else if( fname == DirName_DefOverlay )
{
stringstream sstoverlays;
sstoverlays << utils::TryAppendSlash(m_romroot) <<DirName_DefOverlay;
auto overlaycnt = utils::ListDirContent_FilesAndDirs( sstoverlays.str(), true );
bfoundoverlay = !overlaycnt.empty();
}
else if( fname == FName_ARM9Bin )
bfoundarm9 = true;
if( bfoundarm9 && bfoundoverlay && bfounddata )
break;
}
#if 0
//If we can't find a directory named data, try to find one that contains the typical PMD2 files
if( !bfounddata )
{
slog() <<"<!>- Couldn't find data directory under \"" <<m_romroot <<"\". Attempting to search for ROM data directory..\n";
//Found the directory that contains the PMD2 filetree
auto pathlst = utils::ListDirContent_FilesAndDirs( m_romroot, false );
for( const auto & fpath : pathlst )
{
if( utils::isFolder(fpath) )
{
if( pmd2::AnalyzeDirForPMD2Dirs(fpath) != pmd2::eGameVersion::Invalid )
{
size_t lastslashpos = string::npos;
for( size_t i = 0; i < fpath.size(); ++i )
{
if( (i != (fpath.size()-1)) && fpath[i] == '/' || fpath[i] == '\\' )
lastslashpos = i;
}
if( lastslashpos != string::npos )
{
slog() <<"<*>- ROM data directory seems to be \"" <<fpath <<"\"!\n";
bfounddata = true;
m_datadiroverride = fpath.substr( lastslashpos+1 );
}
break;
}
}
}
}
#endif
//Save the result of our analysis.
m_nodata = !bfounddata;
m_noarm9 = !bfoundarm9;
m_nooverlays = !bfoundoverlay;
m_bAnalyzed = true;
slog()<<"<!>-GameDataLoader: Loading configuration..\n";
if( m_noarm9 || (!m_noarm9 && !LoadConfigUsingARM9()) )
{
slog()<<"<!>-GameDataLoader: Falling back to \"romfs content\" game version detection method..\n";
//Fallback to old method of finding game version, if we don't have the arm9 handy, or if the arm9 scan didn't work
stringstream fsroot;
fsroot << utils::TryAppendSlash(m_romroot) <<DirName_DefData;
auto result = DetermineGameVersionAndLocale( fsroot.str() );
if( result.first != eGameVersion::Invalid && result.second != eGameRegion::Invalid )
{
MainPMD2ConfigWrapper::Instance().InitConfig(result.first, result.second, m_configfile);
}
else
throw std::runtime_error("GameDataLoader::AnalyseGame(): Couldn't determine the version of the pmd2 ROM data!");
}
slog()<<"<!>-GameDataLoader: Configuration loaded!\n";
//Compatibility check
if( !MainPMD2ConfigWrapper::CfgInstance().GetGameVersion().issupported )
{
stringstream ssunsup;
ssunsup << "<!>- WARNING: " << MainPMD2ConfigWrapper::CfgInstance().GetGameVersion().id <<" is not flagged as a supported version of the game!\n";
const string strunsup = ssunsup.str();
cout << strunsup;
if(utils::LibWide().isLogOn())
slog() << strunsup;
}
}
bool GameDataLoader::LoadConfigUsingARM9()
{
stringstream arm9path;
slog()<<"<!>-GameDataLoader: Comparing arm9 binary magic value at offset 0xE with XML presets..\n";
try
{
uint16_t arm9off14 = 0;
arm9path << utils::TryAppendSlash(m_romroot) <<FName_ARM9Bin;
ifstream arm9f( arm9path.str(), std::ios::in | std::ios::binary );
arm9f.exceptions(ifstream::badbit);
arm9f.seekg(14);
utils::ReadIntFromBytes( arm9off14, std::istreambuf_iterator<char>(arm9f.rdbuf()), std::istreambuf_iterator<char>() );
if( arm9off14 != 0 )
{
MainPMD2ConfigWrapper::Instance().InitConfig(arm9off14, m_configfile);
return true;
}
else
{
slog() <<"<!>- GameDataLoader::AnalyseGame(): The 14th byte in \"" + FName_ARM9Bin + "\" file didn't match anything. Falling back to other detection method.\n";
return false;
}
}
catch(const std::exception&)
{
stringstream ss;
ss << "GameDataLoader::LoadConfigUsingARM9(): Error loading arm9 \"" <<arm9path.str()
<<"\" and or config file \"" <<m_configfile <<"\"!";
std::throw_with_nested( std::runtime_error(ss.str()) );
}
}
// ======================== Loading ========================
//void GameDataLoader::Init()
//{
// DoCommonInit();
// InitGameText();
// InitScripts(DefConfigOptions);
// InitLevels(Default_Level_Options);
// InitGraphics();
// InitStats();
// InitAudio();
// InitAsm();
//}
void GameDataLoader::DoCommonInit( bool bcheckdata )
{
if(!m_bAnalyzed)
AnalyseGame();
if( bcheckdata && m_nodata )
throw EX_NoRomDataAvailable( "GameDataLoader::DoCommonInit(): Couldn't open or load the data directory!" );
}
GameText * GameDataLoader::InitGameText()
{
DoCommonInit();
if( !m_text )
{
slog()<<"<!>-GameDataLoader: Requested loading of text data!\n";
stringstream gamefsroot;
gamefsroot << utils::TryAppendSlash(m_romroot) << DirName_DefData;
if( MainPMD2ConfigWrapper::Instance().GetConfig() )
{
m_text.reset( new GameText( gamefsroot.str(), MainPMD2ConfigWrapper::CfgInstance() ) );
m_text->Load();
}
else
slog() <<"<!>- GameDataLoader::LoadGameText(): No game config data was loaded! Skipping on loading game text!\n";
}
return m_text.get();
}
GameScripts * GameDataLoader::InitScripts(const scriptprocoptions & options)
{
DoCommonInit();
if( !m_scripts )
{
slog()<<"<!>-GameDataLoader: Requested loading of script data!\n";
stringstream scriptdir;
scriptdir << utils::TryAppendSlash(m_romroot) << DirName_DefData <<"/" <<DirName_SCRIPT;
m_scripts.reset( new GameScripts(scriptdir.str(), MainPMD2ConfigWrapper::CfgInstance(), options) );
}
return m_scripts.get();
}
GameLevels * GameDataLoader::InitLevels(const lvlprocopts & options)
{
//!NOTE: Have to do this, so statsutil compiles
#ifndef PPMDU_STATSUTIL
DoCommonInit();
if(!m_scripts)
InitScripts(DefConfigOptions);
if(!m_levels)
{
slog()<<"<!>-GameDataLoader: Requested loading of level data!\n";
stringstream gamefsroot;
gamefsroot << utils::TryAppendSlash(m_romroot) << DirName_DefData;
m_levels.reset( new GameLevels(gamefsroot.str(), MainPMD2ConfigWrapper::CfgInstance(), shared_ptr<GameScripts>(m_scripts), options) );
}
#endif
return m_levels.get();
}
GameGraphics * GameDataLoader::InitGraphics()
{
DoCommonInit();
//Stuff
slog()<<"<!>-GameDataLoader: Requested loading of graphics data!\n";
assert(false);
return m_graphics.get();
}
GameStats * GameDataLoader::InitStats()
{
DoCommonInit();
//Need to load game text for this
if( !m_text )
InitGameText();
if( !m_stats )
{
slog()<<"<!>-GameDataLoader: Requested loading of game statistics data!\n";
m_stats.reset( new GameStats( m_romroot, GetGameVersion(), GetGameRegion(), shared_ptr<GameText>(m_text) ) );
m_stats->Load();
}
return m_stats.get();
}
GameAudio * GameDataLoader::InitAudio()
{
DoCommonInit();
//Stuff
slog()<<"<!>-GameDataLoader: Requested loading of audio data!\n";
assert(false);
return m_audio.get();
}
PMD2_ASM * GameDataLoader::InitAsm()
{
DoCommonInit(false); //Don't check for data, we don't need it!
if( m_noarm9 && m_nooverlays )
return nullptr;
if( !m_asmmanip )
{
slog()<<"<!>-GameDataLoader: Requested loading of asm data!\n";
m_asmmanip.reset( new PMD2_ASM( m_romroot, MainPMD2ConfigWrapper::CfgInstance() ) );
}
return m_asmmanip.get();
}
// ======================== DeInit ========================
//void GameDataLoader::DeInit()
//{
// DoCommonInit();
// if( m_text != nullptr )
// DeInitGameText();
// if (m_levels != nullptr)
// DeInitLevels();
// if( m_scripts != nullptr )
// DeInitScripts();
// if( m_graphics != nullptr )
// DeInitGraphics();
// if( m_stats != nullptr )
// DeInitStats();
// if( m_audio != nullptr )
// DeInitAudio();
// //if( m_asmmanip != nullptr )
// // WriteAsm();
//}
void GameDataLoader::DeInitGameText()
{
DoCommonInit();
if( !m_text )
{
slog() <<"<!>- GameDataLoader::WriteGameText(): Nothing to write!\n";
return;
}
slog()<<"<!>-GameDataLoader: Requested writing of text data!\n";
m_text->Write();
}
void GameDataLoader::DeInitScripts()
{
//NOTHING to do here
//if(!m_bAnalyzed)
// AnalyseGame();
//if( m_nodata )
// return;
//if( !m_scripts )
//{
// slog() <<"<!>- GameDataLoader::WriteScripts(): Nothing to write!\n";
// return;
//}
// m_scripts->Write();
}
void GameDataLoader::DeInitLevels()
{
DoCommonInit();
slog()<<"<!>-GameDataLoader: Requested writing of level data!\n";
//Stuff
assert(false);
}
void GameDataLoader::DeInitGraphics()
{
DoCommonInit();
if( !m_graphics )
return;
//Stuff
assert(false);
}
void GameDataLoader::DeInitStats()
{
DoCommonInit();
if( !m_stats )
{
slog() <<"<!>- GameDataLoader::WriteStats(): Nothing to write!\n";
return;
}
slog()<<"<!>-GameDataLoader: Requested writing of game statistics data!\n";
m_stats->Write();
}
void GameDataLoader::DeInitAudio()
{
DoCommonInit();
if( !m_audio )
return;
//Stuff
assert(false);
}
//void GameDataLoader::WriteAsm()
//{
// if(!m_bAnalyzed)
// AnalyseGame();
// if( m_noarm9 && m_nooverlays )
// return;
// if( !m_asmmanip )
// {
// slog() <<"<!>- GameDataLoader::WriteAsm(): Nothing to write!\n";
// return;
// }
// //m_asmmanip->Write();
//}
// ======================== Data Access ========================
void GameDataLoader::SetRomRoot(const std::string & romroot) { m_romroot = romroot; }
const std::string & GameDataLoader::GetRomRoot() const { return m_romroot; }
GameText * GameDataLoader::GetGameText() { return m_text.get(); }
const GameText * GameDataLoader::GetGameText() const { return m_text.get(); }
GameScripts * GameDataLoader::GetScripts() { return m_scripts.get(); }
const GameScripts * GameDataLoader::GetScripts() const { return m_scripts.get(); }
GameLevels * GameDataLoader::GetLevels() { return m_levels.get(); }
const GameLevels * GameDataLoader::GetLevels() const { return m_levels.get(); }
GameGraphics * GameDataLoader::GetGraphics() { return m_graphics.get(); }
const GameGraphics * GameDataLoader::GetGraphics() const { return m_graphics.get(); }
GameStats * GameDataLoader::GetStats() { return m_stats.get(); }
const GameStats * GameDataLoader::GetStats() const { return m_stats.get(); }
GameAudio * GameDataLoader::GetAudio() { return m_audio.get(); }
const GameAudio * GameDataLoader::GetAudio() const { return m_audio.get(); }
PMD2_ASM * GameDataLoader::GetAsm() { return m_asmmanip.get(); }
const PMD2_ASM * GameDataLoader::GetAsm() const { return m_asmmanip.get(); }
//const ConfigLoader * GameDataLoader::GetConfig() const
//{
// //!#TODO: It would be nice to make use of weak_ptr here, as it was intended!!
// return MainPMD2ConfigWrapper.get();
//}
};
| 35.062921 | 176 | 0.52099 | [
"object"
] |
7c2e8d25f16d863ee8cde77074ce78fc47fb5e57 | 2,748 | cpp | C++ | tests/compile/many_variables.cpp | nasailja/gensimcell | 65726d0bfffff3f4dfd526a925974c32b37cec5e | [
"BSD-3-Clause"
] | null | null | null | tests/compile/many_variables.cpp | nasailja/gensimcell | 65726d0bfffff3f4dfd526a925974c32b37cec5e | [
"BSD-3-Clause"
] | null | null | null | tests/compile/many_variables.cpp | nasailja/gensimcell | 65726d0bfffff3f4dfd526a925974c32b37cec5e | [
"BSD-3-Clause"
] | null | null | null | /*
Tests whether a cell with multiple variables compiles.
Copyright 2013, 2014, 2015, 2016 Ilja Honkonen
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 copyright holders nor the names of their 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 "array"
#include "cstdlib"
#include "tuple"
#include "vector"
#include "gensimcell.hpp"
struct test_variable1 {
using data_type = int;
};
struct test_variable2 {
using data_type = double;
};
struct test_variable3 {
using data_type = float;
};
struct test_variable4 {
using data_type = uint64_t;
};
struct test_variable5 {
using data_type = std::array<double, 3>;
};
struct test_variable6 {
using data_type = std::tuple<int, float, test_variable5>;
};
struct test_variable7 {
using data_type = std::vector<int>;
};
int main(int, char**)
{
gensimcell::Cell<
gensimcell::Never_Transfer,
test_variable1,
test_variable2,
test_variable3,
test_variable4,
test_variable5,
test_variable6,
test_variable7
> cell1;
#ifdef HAVE_MPI
gensimcell::Cell<
gensimcell::Always_Transfer,
test_variable1,
test_variable2,
test_variable3,
test_variable4,
test_variable5,
test_variable6,
test_variable7
> cell2;
gensimcell::Cell<
gensimcell::Optional_Transfer,
test_variable1,
test_variable2,
test_variable3,
test_variable4,
test_variable5,
test_variable6,
test_variable7
> cell3;
#endif // ifdef HAVE_MPI
return 0;
}
| 24.756757 | 80 | 0.776565 | [
"vector"
] |
7c3262dda6142c33c042f2bb9943d570e169cc78 | 2,831 | cc | C++ | coral/test_utils_test.cc | hjonnala/libcoral | 3b1e06417cd239172912f87448b864226953762c | [
"Apache-2.0"
] | 38 | 2020-10-27T12:46:12.000Z | 2022-03-26T13:15:44.000Z | coral/test_utils_test.cc | hjonnala/libcoral | 3b1e06417cd239172912f87448b864226953762c | [
"Apache-2.0"
] | 19 | 2020-11-12T02:37:53.000Z | 2022-03-24T14:28:07.000Z | coral/test_utils_test.cc | hjonnala/libcoral | 3b1e06417cd239172912f87448b864226953762c | [
"Apache-2.0"
] | 17 | 2020-11-21T16:35:46.000Z | 2022-03-26T07:46:21.000Z | /* Copyright 2019-2021 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
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 "coral/test_utils.h"
#include <cmath>
#include "absl/strings/str_format.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace coral {
namespace {
using ::testing::Eq;
TEST(TestUtilsTest, TopKContains) {
const std::vector<Class> top_k = {
{121, 0.95}, {135, 0.90}, {71, 0.85}, {1, 0.55}};
EXPECT_TRUE(TopKContains(top_k, 121));
EXPECT_TRUE(TopKContains(top_k, 135));
EXPECT_TRUE(TopKContains(top_k, 71));
EXPECT_FALSE(TopKContains(top_k, 2));
}
TEST(TestUtilsTest, ImageResizeBMP) {
// expected_output_image is resized from input_image with TF2.1:
// tf.image.resize(images, size, method=ResizeMethod.BILINEAR,
// preserve_aspect_ratio=False, antialias=False, name=None)
for (const auto& dims : std::vector<ImageDims>{{224, 224, 3},
{229, 229, 3},
{300, 300, 3},
{513, 513, 3},
{200, 300, 3}}) {
ImageDims real_dims;
auto expected = ReadBmp(TestDataPath(absl::StrFormat(
"checker%dX%d.bmp", dims.height, dims.width)),
&real_dims);
ASSERT_EQ(real_dims, dims);
auto resized = GetInputFromImage(TestDataPath("checker800X600.bmp"), dims);
ASSERT_EQ(resized.size(), expected.size());
for (int i = 0; i < expected.size(); ++i)
EXPECT_LE(std::abs(expected[i] - resized[i]), 1);
}
}
TEST(TestUtilsTest, ReadBMPImage) {
ImageDims dims;
EXPECT_THAT(ReadBmp(TestDataPath("rgb6X4.bmp"), &dims),
Eq(std::vector<uint8_t>{
255, 0, 255, 255, 0, 255, 0, 255, 0, 0, 255, 0,
255, 0, 255, 255, 0, 255, 0, 255, 0, 0, 255, 0,
255, 0, 255, 255, 0, 255, 0, 255, 0, 0, 255, 0,
0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255}));
EXPECT_THAT(dims, Eq(ImageDims{6, 4, 3}));
}
} // namespace
} // namespace coral
| 39.319444 | 80 | 0.564112 | [
"vector"
] |
7c3d95a662e95cc0df04211d2833d38eb237ee85 | 1,659 | cpp | C++ | advent-of-code/2021/day-9/problem-1.cpp | kpagacz/spoj | 8bff809c6c5227a6e85e9b12f808dd921f24e587 | [
"MIT"
] | 1 | 2021-12-06T16:01:55.000Z | 2021-12-06T16:01:55.000Z | advent-of-code/2021/day-9/problem-1.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | advent-of-code/2021/day-9/problem-1.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | // link to the problem https://adventofcode.com/2021/day/9
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<numeric>
#define DEBUG 0
typedef std::vector<std::vector<int>*> smokemap;
bool is_low_point(smokemap map, int x, int y) {
std::vector<int> x_perturb;
if (x > 0)
x_perturb.push_back(-1);
if (x < map.size() - 1)
x_perturb.push_back(1);
for(const auto& i : x_perturb) {
if (DEBUG) std::cout << x + 1 << " " << y << "\n";
if (!(map[x + i]->at(y) > map[x]->at(y)))
return false;
}
std::vector<int> y_perturb;
if (y > 0)
y_perturb.push_back(-1);
if (y < map[0]->size() - 1)
y_perturb.push_back(1);
for(const auto& i : y_perturb) {
if (DEBUG) std::cout << x << " " << y + 1 << "\n";
if (!(map[x]->at(y + i) > map[x]->at(y)))
return false;
}
return true;
}
int main() {
std::string line;
smokemap heightmap;
while(std::getline(std::cin, line)) {
std::vector<int>* row_heights = new std::vector<int>();
for(const auto& c : line)
row_heights->push_back(c - '0');
heightmap.push_back(row_heights);
}
// for(const auto& v : heightmap) {
// for(const auto& i : *v)
// std::cout << i << " ";
// std::cout << '\n';
// }
int total_risk = 0;
for (int i = 0; i < heightmap.size(); i++) {
for (int j = 0; j < heightmap[0]->size(); j++) {
if (is_low_point(heightmap, i, j)) {
if (DEBUG) std::cout << "Low point: " << i << " " << j << " value: " << heightmap[i]->at(j) << '\n';
total_risk += heightmap[i]->at(j) + 1;
}
}
}
std::cout << "Total risk: " << total_risk << '\n';
}
| 25.921875 | 108 | 0.538276 | [
"vector"
] |
7c4177b69b2b962c9df523961370f0876c30823e | 75,074 | cxx | C++ | admin/netui/acledit/acledit/ntfsacl.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/acledit/acledit/ntfsacl.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/acledit/acledit/ntfsacl.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
NTFSAcl.cxx
This file contains the implementation for the NT File System ACL
Editor. It is just a front end for the Generic ACL Editor that is
specific to the NTFS.
FILE HISTORY:
Johnl 30-Dec-1991 Created
*/
#include <ntincl.hxx>
extern "C"
{
#include <ntioapi.h>
#include <ntseapi.h>
}
#include <ntmasks.hxx>
#define INCL_NETCONS
#define INCL_NETLIB
#define INCL_WINDOWS
#define INCL_NETERRORS
#define INCL_DOSERRORS
#define INCL_NETACCESS // For NET_ACCESS_1 reference
#define INCL_NETUSE
#include <lmui.hxx>
#define INCL_BLT_CONTROL
#define INCL_BLT_DIALOG
#define INCL_BLT_MSGPOPUP
#include <blt.hxx>
#include <dbgstr.hxx>
#include <string.hxx>
#include <strnumer.hxx>
#include <security.hxx>
#include <ntacutil.hxx>
#include <uibuffer.hxx>
#include <strlst.hxx>
#include <fsenum.hxx>
#include <errmap.hxx>
#include <lmodev.hxx>
#include <lmoacces.hxx>
extern "C"
{
#include <netlib.h> // For NetpGetPrivilege
#include <mpr.h>
#include <npapi.h>
}
#include <wfext.h>
#include <fmx.hxx>
extern "C"
{
#include <sedapi.h>
#include <helpnums.h>
}
#include <cncltask.hxx>
#include <uiassert.hxx>
#include <ipermapi.hxx>
#include <permprg.hxx>
#include <permstr.hxx>
#include <ntfsacl.hxx>
DWORD SedCallback( HWND hwndParent,
HANDLE hInstance,
ULONG_PTR ulCallbackContext,
PSECURITY_DESCRIPTOR psecdesc,
PSECURITY_DESCRIPTOR psecdescNewObjects,
BOOLEAN fApplyToSubContainers,
BOOLEAN fApplyToSubObjects,
LPDWORD StatusReturn
) ;
typedef struct _NTFS_CALLBACK_INFO
{
HWND hwndFMXOwner ;
enum SED_PERM_TYPE sedpermtype ;
} NTFS_CALLBACK_INFO ;
void InitializeNTFSGenericMapping( PGENERIC_MAPPING pNTFSGenericMapping,
BOOL fIsDirectory ) ;
APIERR GetSecurity( const TCHAR * pszFileName,
BUFFER * pbuffSecDescData,
enum SED_PERM_TYPE sedpermtype,
BOOL * pfAuditPrivAdjusted ) ;
APIERR CompareNTFSSecurityIntersection( HWND hwndFMX,
enum SED_PERM_TYPE sedpermtype,
PSECURITY_DESCRIPTOR psecdesc,
BOOL * pfOwnerEqual,
BOOL * pfACLEqual,
NLS_STR * pnlsFailingFile,
PGENERIC_MAPPING pGenericMapping,
PGENERIC_MAPPING pGenericMappingObjects,
BOOL fMapGenAll,
BOOL fIsContainer ) ;
/* The following two arrays define the permission names for NT Files. Note
* that each index in one array corresponds to the index in the other array.
* The second array will be modifed to contain a string pointer pointing to
* the corresponding IDS_* in the first array.
*/
MSGID msgidFilePermNames[] =
{
IDS_FILE_PERM_SPEC_READ,
IDS_FILE_PERM_SPEC_WRITE,
IDS_FILE_PERM_SPEC_EXECUTE,
IDS_FILE_PERM_SPEC_DELETE,
IDS_FILE_PERM_SPEC_CHANGE_PERM,
IDS_FILE_PERM_SPEC_CHANGE_OWNER,
IDS_FILE_PERM_GEN_NO_ACCESS,
IDS_FILE_PERM_GEN_READ,
IDS_FILE_PERM_GEN_MODIFY,
IDS_FILE_PERM_GEN_ALL
} ;
SED_APPLICATION_ACCESS sedappaccessFilePerms[] =
{
{ SED_DESC_TYPE_RESOURCE_SPECIAL, FILE_PERM_SPEC_READ, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, FILE_PERM_SPEC_WRITE, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, FILE_PERM_SPEC_EXECUTE, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, FILE_PERM_SPEC_DELETE, 0, NULL },
//{ SED_DESC_TYPE_RESOURCE_SPECIAL, FILE_PERM_SPEC_READ_PERM, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, FILE_PERM_SPEC_CHANGE_PERM, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, FILE_PERM_SPEC_CHANGE_OWNER, 0, NULL },
{ SED_DESC_TYPE_RESOURCE, FILE_PERM_GEN_NO_ACCESS, 0, NULL },
{ SED_DESC_TYPE_RESOURCE, FILE_PERM_GEN_READ, 0, NULL },
{ SED_DESC_TYPE_RESOURCE, FILE_PERM_GEN_MODIFY, 0, NULL }
,
{ SED_DESC_TYPE_RESOURCE, FILE_PERM_GEN_ALL, 0, NULL }
} ;
#define COUNT_FILEPERMS_ARRAY (sizeof(sedappaccessFilePerms)/sizeof(SED_APPLICATION_ACCESS))
/* The following two arrays define the permission names for NT directories. Note
* that each index in one array corresponds to the index in the other array.
* The second array will be modifed to contain a string pointer pointing to
* the corresponding IDS_* in the first array.
*/
MSGID msgidDirPermNames[] =
{
IDS_DIR_PERM_SPEC_READ,
IDS_DIR_PERM_SPEC_WRITE,
IDS_DIR_PERM_SPEC_EXECUTE,
IDS_DIR_PERM_SPEC_DELETE,
IDS_DIR_PERM_SPEC_CHANGE_PERM,
IDS_DIR_PERM_SPEC_CHANGE_OWNER,
IDS_DIR_PERM_GEN_NO_ACCESS,
IDS_DIR_PERM_GEN_LIST,
IDS_DIR_PERM_GEN_READ,
IDS_DIR_PERM_GEN_DEPOSIT,
IDS_DIR_PERM_GEN_PUBLISH,
IDS_DIR_PERM_GEN_MODIFY,
IDS_DIR_PERM_GEN_ALL,
IDS_NEWFILE_PERM_SPEC_READ,
IDS_NEWFILE_PERM_SPEC_WRITE,
IDS_NEWFILE_PERM_SPEC_EXECUTE,
IDS_NEWFILE_PERM_SPEC_DELETE,
IDS_NEWFILE_PERM_SPEC_CHANGE_PERM,
IDS_NEWFILE_PERM_SPEC_CHANGE_OWNER
} ;
SED_APPLICATION_ACCESS sedappaccessDirPerms[] =
{
{ SED_DESC_TYPE_RESOURCE_SPECIAL, DIR_PERM_SPEC_READ, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, DIR_PERM_SPEC_WRITE, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, DIR_PERM_SPEC_EXECUTE, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, DIR_PERM_SPEC_DELETE, 0, NULL },
//{ SED_DESC_TYPE_RESOURCE_SPECIAL, DIR_PERM_SPEC_READ_PERM, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, DIR_PERM_SPEC_CHANGE_PERM, 0, NULL },
{ SED_DESC_TYPE_RESOURCE_SPECIAL, DIR_PERM_SPEC_CHANGE_OWNER,0, NULL },
{ SED_DESC_TYPE_CONT_AND_NEW_OBJECT, DIR_PERM_GEN_NO_ACCESS,NEWFILE_PERM_GEN_NO_ACCESS, NULL },
{ SED_DESC_TYPE_CONT_AND_NEW_OBJECT, DIR_PERM_GEN_LIST, NEWFILE_PERM_GEN_LIST, NULL },
{ SED_DESC_TYPE_CONT_AND_NEW_OBJECT, DIR_PERM_GEN_READ, NEWFILE_PERM_GEN_READ, NULL },
{ SED_DESC_TYPE_CONT_AND_NEW_OBJECT, DIR_PERM_GEN_DEPOSIT, NEWFILE_PERM_GEN_DEPOSIT, NULL },
{ SED_DESC_TYPE_CONT_AND_NEW_OBJECT, DIR_PERM_GEN_PUBLISH, NEWFILE_PERM_GEN_PUBLISH, NULL },
{ SED_DESC_TYPE_CONT_AND_NEW_OBJECT, DIR_PERM_GEN_MODIFY, NEWFILE_PERM_GEN_MODIFY, NULL },
{ SED_DESC_TYPE_CONT_AND_NEW_OBJECT, DIR_PERM_GEN_ALL, NEWFILE_PERM_GEN_ALL, NULL },
{ SED_DESC_TYPE_NEW_OBJECT_SPECIAL, NEWFILE_PERM_SPEC_READ, 0, NULL },
{ SED_DESC_TYPE_NEW_OBJECT_SPECIAL, NEWFILE_PERM_SPEC_WRITE, 0, NULL },
{ SED_DESC_TYPE_NEW_OBJECT_SPECIAL, NEWFILE_PERM_SPEC_EXECUTE, 0, NULL },
{ SED_DESC_TYPE_NEW_OBJECT_SPECIAL, NEWFILE_PERM_SPEC_DELETE, 0, NULL },
{ SED_DESC_TYPE_NEW_OBJECT_SPECIAL, NEWFILE_PERM_SPEC_CHANGE_PERM, 0, NULL },
{ SED_DESC_TYPE_NEW_OBJECT_SPECIAL, NEWFILE_PERM_SPEC_CHANGE_OWNER, 0, NULL }
} ;
#define COUNT_DIRPERMS_ARRAY (sizeof(sedappaccessDirPerms)/sizeof(SED_APPLICATION_ACCESS))
/* The following two arrays define the auditting names for NT directories and
* directories.
*/
MSGID msgidFileAuditNames[] =
{
IDS_FILE_AUDIT_READ,
IDS_FILE_AUDIT_WRITE,
IDS_FILE_AUDIT_EXECUTE,
IDS_FILE_AUDIT_DELETE,
IDS_FILE_AUDIT_CHANGE_PERM,
IDS_FILE_AUDIT_CHANGE_OWNER
} ;
SED_APPLICATION_ACCESS sedappaccessFileAudits[] =
{
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_READ, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_WRITE, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_EXECUTE, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_DELETE, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_CHANGE_PERM, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_CHANGE_OWNER,0, NULL }
} ;
#define COUNT_FILE_AUDITPERMS_ARRAY (sizeof(sedappaccessFileAudits)/sizeof(SED_APPLICATION_ACCESS))
/* The following two arrays define the auditting names for NT directories and
* directories.
*/
MSGID msgidDirAuditNames[] =
{
IDS_DIR_AUDIT_READ,
IDS_DIR_AUDIT_WRITE,
IDS_DIR_AUDIT_EXECUTE,
IDS_DIR_AUDIT_DELETE,
IDS_DIR_AUDIT_CHANGE_PERM,
IDS_DIR_AUDIT_CHANGE_OWNER
} ;
SED_APPLICATION_ACCESS sedappaccessDirAudits[] =
{
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_READ, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_WRITE, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_EXECUTE, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_DELETE, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_CHANGE_PERM, 0, NULL },
{ SED_DESC_TYPE_AUDIT, FILE_AUDIT_CHANGE_OWNER,0, NULL }
} ;
#define COUNT_DIR_AUDITPERMS_ARRAY (sizeof(sedappaccessDirAudits)/sizeof(SED_APPLICATION_ACCESS))
extern HINSTANCE hModule; // Exported from libmain
/*******************************************************************
NAME: EditNTFSAcl
SYNOPSIS: This Procedure prepares the structures necessary for the
generic ACL editor, specifically for NT FS (FileSystem)
ACLs.
ENTRY: hwndParent - Parent window handle, this should be the
FMX Window handle
pszServer - Name of server the resource resides on
(in the form "\\server")
pszResource - Fully qualified name of resource we will
edit (suitable for passing to GetFileSecurity)
sedpermtype - either SED_ACCESSES or SED_AUDITS
fIsFile - TRUE if the resource is a file, FALSE if the
resource is a directory
EXIT:
RETURNS:
NOTES: We assume we are dealing with an NTFS volume by the time
this function is called.
HISTORY:
Johnl 25-Dec-1992 Created
********************************************************************/
APIERR EditNTFSAcl( HWND hwndParent,
const TCHAR * pszServer,
const TCHAR * pszResource,
enum SED_PERM_TYPE sedpermtype,
BOOL fIsFile )
{
APIERR err ;
BUFFER buffSecDescData( 1024 ) ;
BOOL fCantRead = FALSE ; // Did we read the Owner?
BOOL fCantWrite = FALSE ; // Is it read only?
BOOL fPrivAdjusted = FALSE ; // Do we need to restore our token?
BOOL fCheckSecurity= TRUE ; // Check security unless bad intersection
const TCHAR * pszSecCheckFile = pszResource ;
do { // error breakout
PSECURITY_DESCRIPTOR pSecurityDesc = NULL ;
switch ( err = ::GetSecurity( pszResource,
&buffSecDescData,
sedpermtype,
&fPrivAdjusted ) )
{
case ERROR_ACCESS_DENIED:
fCantRead = TRUE ;
//
// If they can't read the SACL then they don't have the privilege
//
if ( sedpermtype == SED_AUDITS )
{
err = ERROR_PRIVILEGE_NOT_HELD ;
break ;
}
err = NERR_Success ;
break ;
case NO_ERROR:
pSecurityDesc = (PSECURITY_DESCRIPTOR) buffSecDescData.QueryPtr() ;
break ;
default:
break ;
}
if ( err )
break ;
GENERIC_MAPPING NTFSGenericMapping ;
InitializeNTFSGenericMapping( &NTFSGenericMapping, !fIsFile ) ;
FMX fmx( hwndParent ) ;
BOOL fIsMultiSelect = fmx.QuerySelCount() > 1 ;
//
// We may need to substitute our own security descriptor here
// depending on the intersection of security descriptors because
// we can't set a NULL owner on a self relative security descriptor
// (which we will most likely get).
//
OS_SECURITY_DESCRIPTOR ossecdesc( fIsMultiSelect ?
pSecurityDesc : NULL, TRUE ) ;
OS_ACL osacl( NULL ) ;
DEC_STR nlsSelectCount( fmx.QuerySelCount() ) ;
if ( fIsMultiSelect )
{
BOOL fOwnerEqual = FALSE, fACLEqual = FALSE ;
NLS_STR nlsFailingFile ;
MSGID idsPromptToContinue = IDS_BAD_INTERSECTION ;
if ( fCantRead ||
(err = ossecdesc.QueryError()) ||
(err = nlsSelectCount.QueryError()) ||
(err = CompareNTFSSecurityIntersection( hwndParent,
sedpermtype,
pSecurityDesc,
&fOwnerEqual,
&fACLEqual,
&nlsFailingFile,
&NTFSGenericMapping,
&NTFSGenericMapping,
TRUE,
!fIsFile )) )
{
//
// If we didn't have access to read one of the security
// descriptors, then give the user the option of continuing
//
if ( fCantRead || err == ERROR_ACCESS_DENIED )
{
pszResource = fCantRead ? pszResource :
nlsFailingFile.QueryPch() ;
idsPromptToContinue = IERR_MULTI_SELECT_AND_CANT_READ ;
fCantRead = TRUE ;
err = NERR_Success ;
}
else
{
break ;
}
}
//
// Substitute the blank security descriptor only if we need to
//
if ( !fACLEqual || !fOwnerEqual || fCantRead )
{
pSecurityDesc = ossecdesc.QueryDescriptor() ;
}
if ( !fACLEqual || fCantRead )
{
switch ( ::MsgPopup( hwndParent,
(MSGID) idsPromptToContinue,
MPSEV_WARNING,
MP_YESNO,
pszResource,
nlsFailingFile,
MP_YES ))
{
case IDYES:
{
if ( (err = ossecdesc.SetDACL( TRUE, &osacl )) ||
(err = ossecdesc.SetSACL( TRUE, &osacl )) ||
(err = ossecdesc.SetOwner( FALSE, NULL, 0 )) ||
(err = ossecdesc.SetGroup( FALSE, NULL, 0 )) )
{
break ;
}
//
// We've just made the ACL equal. Note that we don't
// check the security if the ACLs aren't equal (some
// may allow access, others may not).
//
fACLEqual = TRUE ;
fCantRead = FALSE ;
fCheckSecurity = FALSE ;
}
break ;
case IDNO:
default:
break ;
}
}
if ( err || !fACLEqual || fCantRead )
break ;
if ( !fOwnerEqual &&
(err = ossecdesc.SetOwner( FALSE, NULL, 0 )) )
{
break ;
}
} // if IsMultiSelect
/* Retrieve the resource strings appropriate for the type of object we
* are looking at
*/
MSGID msgidTypeName = fIsFile ? IDS_FILE : IDS_DIRECTORY ;
MSGID msgidApplySubCont = sedpermtype == SED_ACCESSES ?
IDS_NT_ASSIGN_PERM_TITLE:
IDS_NT_ASSIGN_AUDITS_TITLE ;
MSGID msgidApplySubObj =sedpermtype == SED_ACCESSES ?
IDS_NT_ASSIGN_FILE_PERM_TITLE :
IDS_NT_ASSIGN_FILE_AUDITS_TITLE ;
RESOURCE_STR nlsTypeName( msgidTypeName ) ;
RESOURCE_STR nlsSpecial( fIsFile ? IDS_NT_FILE_SPECIAL_ACCESS :
IDS_NT_DIR_SPECIAL_ACCESS ) ;
RESOURCE_STR nlsDefaultPermName( fIsFile ? IDS_FILE_PERM_GEN_READ :
IDS_DIR_PERM_GEN_READ ) ;
RESOURCE_STR nlsHelpFileName ( IDS_FILE_PERM_HELP_FILE ) ;
RESOURCE_STR nlsResourceName ( fIsFile ? IDS_FILE_MULTI_SEL :
IDS_DIRECTORY_MULTI_SEL ) ;
NLS_STR nlsApplyToSubCont ;
NLS_STR nlsApplyToSubObj ;
NLS_STR nlsSpecialNewObj ;
NLS_STR nlsApplyToSubContConfirmation ;
/* We only need the ApplyTo title and the NewObjSpecial strings if
* this resource is a directory.
*/
if ( !fIsFile )
{
if ( (err = nlsApplyToSubCont.Load( msgidApplySubCont )) ||
(err = nlsApplyToSubObj.Load( msgidApplySubObj )) ||
(err = nlsSpecialNewObj.Load(IDS_NT_NEWOBJ_SPECIAL_ACCESS)) ||
(err = nlsApplyToSubContConfirmation.Load( IDS_TREE_APPLY_WARNING )))
{
/* Fall through
*/
}
}
if ( err ||
( err = nlsTypeName.QueryError() ) ||
( err = nlsSpecial.QueryError() ) ||
( err = nlsDefaultPermName.QueryError()) ||
( err = nlsHelpFileName.QueryError()) )
{
break ;
}
//
// Replace the resource name with the "X files selected" string
// if we are in a multi-select situation
//
if ( fIsMultiSelect )
{
if ( (err = nlsResourceName.QueryError()) ||
(err = nlsResourceName.InsertParams( nlsSelectCount )))
{
break ;
}
pszResource = nlsResourceName.QueryPch() ;
}
SED_OBJECT_TYPE_DESCRIPTOR sedobjdesc ;
SED_HELP_INFO sedhelpinfo ;
sedhelpinfo.pszHelpFileName = (LPWSTR) nlsHelpFileName.QueryPch() ;
sedobjdesc.Revision = SED_REVISION1 ;
sedobjdesc.IsContainer = !fIsFile ;
sedobjdesc.AllowNewObjectPerms = !fIsFile ;
sedobjdesc.MapSpecificPermsToGeneric = TRUE ;
sedobjdesc.GenericMapping = &NTFSGenericMapping ;
sedobjdesc.GenericMappingNewObjects = &NTFSGenericMapping ;
sedobjdesc.HelpInfo = &sedhelpinfo ;
sedobjdesc.ObjectTypeName = (LPTSTR) nlsTypeName.QueryPch() ;
sedobjdesc.ApplyToSubContainerTitle = (LPTSTR) nlsApplyToSubCont.QueryPch() ;
sedobjdesc.ApplyToObjectsTitle = (LPTSTR) nlsApplyToSubObj.QueryPch() ;
sedobjdesc.ApplyToSubContainerConfirmation
= (LPTSTR) nlsApplyToSubContConfirmation.QueryPch() ;
sedobjdesc.SpecialObjectAccessTitle = (LPTSTR) nlsSpecial.QueryPch() ;
sedobjdesc.SpecialNewObjectAccessTitle = (LPTSTR) nlsSpecialNewObj.QueryPch() ;
/* Now we need to load the global arrays with the permission names
* from the resource file.
*/
UINT cArrayItems ;
MSGID * msgidPermNames ;
PSED_APPLICATION_ACCESS pappaccess ;
ULONG hcMainDlg, hcSpecial, hcNewItemSpecial, hcAddUser,
hcAddMemberLG, hcAddMemberGG, hcAddSearch ;
ACCESS_MASK WriteAccessReq ;
// NTRAID#NTBUG9-574280-2002/03/07-artm Prefast: Local declaration hides function level declaration.
// A little tricky to figure out, but this declaration probably is unintentional. The code
// outside the scope of the do{}while() loop that checks fPrivAdjusted will never be
// executed b/c fPrivAdjusted is always set to FALSE outside the loop.
//
// This function appears to be used.
BOOL fPrivAdjusted = FALSE;
ULONG ulAuditPriv = SE_SECURITY_PRIVILEGE ;
switch ( sedpermtype )
{
case SED_ACCESSES:
hcAddUser = HC_SED_USER_BROWSER_DIALOG ;
hcAddMemberLG = HC_SED_USER_BROWSER_LOCALGROUP ;
hcAddMemberGG = HC_SED_USER_BROWSER_GLOBALGROUP ;
hcAddSearch = HC_SED_USER_BROWSER_FINDUSER ;
WriteAccessReq = WRITE_DAC ;
if ( fIsFile )
{
cArrayItems = COUNT_FILEPERMS_ARRAY ;
msgidPermNames = msgidFilePermNames ;
pappaccess = sedappaccessFilePerms ;
hcMainDlg = HC_SED_NT_FILE_PERMS_DLG ;
hcSpecial = HC_SED_NT_SPECIAL_FILES_FM ;
}
else
{
cArrayItems = COUNT_DIRPERMS_ARRAY ;
msgidPermNames = msgidDirPermNames ;
pappaccess = sedappaccessDirPerms ;
hcMainDlg = HC_SED_NT_DIR_PERMS_DLG ;
hcSpecial = HC_SED_NT_SPECIAL_DIRS_FM ;
hcNewItemSpecial = HC_SED_NT_SPECIAL_NEW_FILES_FM ;
}
break ;
case SED_AUDITS:
hcAddUser = HC_SED_USER_BROWSER_AUDIT_DLG ;
hcAddMemberLG = HC_SED_USER_BR_AUDIT_LOCALGROUP ;
hcAddMemberGG = HC_SED_USER_BR_AUDIT_GLOBALGROUP ;
hcAddSearch = HC_SED_USER_BR_AUDIT_FINDUSER ;
WriteAccessReq = ACCESS_SYSTEM_SECURITY ;
if ( fCheckSecurity )
{
if (err = ::NetpGetPrivilege( 1, &ulAuditPriv ) )
{
break ;
}
else
fPrivAdjusted = TRUE ;
}
if ( fIsFile )
{
cArrayItems = COUNT_FILE_AUDITPERMS_ARRAY ;
msgidPermNames = msgidFileAuditNames ;
pappaccess = sedappaccessFileAudits ;
hcMainDlg = HC_SED_NT_FILE_AUDITS_DLG ;
}
else
{
cArrayItems = COUNT_DIR_AUDITPERMS_ARRAY ;
msgidPermNames = msgidDirAuditNames ;
pappaccess = sedappaccessDirAudits ;
hcMainDlg = HC_SED_NT_DIR_AUDITS_DLG ;
}
break ;
default:
UIASSERT(!SZ("Bad permission type")) ;
err = ERROR_GEN_FAILURE ;
break ;
}
if ( err )
break ;
if ( fCheckSecurity )
{
BOOL fCanWrite ;
if ( err = ::CheckFileSecurity( pszSecCheckFile,
WriteAccessReq,
&fCanWrite ) )
{
break ;
}
fCantWrite = !fCanWrite ;
if ( fPrivAdjusted )
NetpReleasePrivilege() ;
}
/* Loop through each permission title retrieving the text from the
* resource file and setting the pointer in the array. The memory
* will be deleted when strlistPermNames is destructed.
*/
STRLIST strlistPermNames ;
for ( UINT i = 0 ; i < cArrayItems ; i++ )
{
RESOURCE_STR * pnlsPermName = new RESOURCE_STR( msgidPermNames[i]) ;
err = (pnlsPermName==NULL) ? ERROR_NOT_ENOUGH_MEMORY :
pnlsPermName->QueryError() ;
if ( err ||
(err = strlistPermNames.Add( pnlsPermName )) )
{
delete pnlsPermName ;
break ;
}
pappaccess[i].PermissionTitle = (LPTSTR) pnlsPermName->QueryPch() ;
}
if ( err )
break ;
SED_APPLICATION_ACCESSES SedAppAccesses ;
SedAppAccesses.Count = cArrayItems ;
SedAppAccesses.AccessGroup = pappaccess ;
SedAppAccesses.DefaultPermName = (LPTSTR) nlsDefaultPermName.QueryPch() ;
sedhelpinfo.aulHelpContext[HC_MAIN_DLG] = hcMainDlg ;
sedhelpinfo.aulHelpContext[HC_SPECIAL_ACCESS_DLG] = hcSpecial ;
sedhelpinfo.aulHelpContext[HC_NEW_ITEM_SPECIAL_ACCESS_DLG] = hcNewItemSpecial ;
sedhelpinfo.aulHelpContext[HC_ADD_USER_DLG] = hcAddUser ;
sedhelpinfo.aulHelpContext[HC_ADD_USER_MEMBERS_LG_DLG] = hcAddMemberLG ;
sedhelpinfo.aulHelpContext[HC_ADD_USER_MEMBERS_GG_DLG] = hcAddMemberGG ;
sedhelpinfo.aulHelpContext[HC_ADD_USER_SEARCH_DLG] = hcAddSearch ;
DWORD dwSedReturnStatus ;
NTFS_CALLBACK_INFO callbackinfo ;
callbackinfo.hwndFMXOwner = hwndParent ;
switch ( sedpermtype )
{
case SED_ACCESSES:
callbackinfo.sedpermtype= SED_ACCESSES ;
err = SedDiscretionaryAclEditor( hwndParent,
::hModule,
(LPTSTR) pszServer,
&sedobjdesc,
&SedAppAccesses,
(LPTSTR) pszResource,
(PSED_FUNC_APPLY_SEC_CALLBACK) SedCallback,
(ULONG_PTR) &callbackinfo,
pSecurityDesc,
(BOOLEAN)fCantRead,
(BOOLEAN)fCantWrite,
&dwSedReturnStatus,
0 ) ;
break ;
case SED_AUDITS:
callbackinfo.sedpermtype = SED_AUDITS ;
err = SedSystemAclEditor( hwndParent,
::hModule,
(LPTSTR) pszServer,
&sedobjdesc,
&SedAppAccesses,
(LPTSTR) pszResource,
(PSED_FUNC_APPLY_SEC_CALLBACK) SedCallback,
(ULONG_PTR) &callbackinfo,
pSecurityDesc,
fCantRead || fCantWrite,
&dwSedReturnStatus,
0 ) ;
break ;
default:
UIASSERT(!SZ("Bad type") ) ;
err = ERROR_GEN_FAILURE ;
break ;
}
if ( err )
break ;
} while (FALSE) ;
/* We need to revert to ourselves if we were doing auditting
*/
if ( fPrivAdjusted )
{
APIERR errTmp = NetpReleasePrivilege() ;
if ( errTmp )
{
DBGEOL("::EditNTFSAcl - Warning: NetpReleasePrivilege return error "
<< errTmp ) ;
}
}
TRACEEOL(SZ("::EditNTFSAcl returning error code ") << (ULONG) err ) ;
if ( err )
{
::MsgPopup( hwndParent, (MSGID) err ) ;
}
return err ;
}
/*******************************************************************
NAME: SedCallback
SYNOPSIS: Security Editor callback for the NTFS ACL Editor
ENTRY: See sedapi.hxx
EXIT:
RETURNS:
NOTES: The callback context should be the FMX Window handle. This
is so we can support setting permissions on multiple files/
directories if we ever decide to do that.
HISTORY:
Johnl 17-Mar-1992 Filled out
********************************************************************/
DWORD SedCallback( HWND hwndParent,
HANDLE hInstance,
ULONG_PTR ulCallbackContext,
PSECURITY_DESCRIPTOR psecdesc,
PSECURITY_DESCRIPTOR psecdescNewObjects,
BOOLEAN fApplyToSubContainers,
BOOLEAN fApplyToSubObjects,
LPDWORD StatusReturn
)
{
UNREFERENCED( hInstance ) ;
APIERR err = NO_ERROR ;
NTFS_CALLBACK_INFO *pcallbackinfo = (NTFS_CALLBACK_INFO *)ulCallbackContext;
HWND hwndFMXWindow = pcallbackinfo->hwndFMXOwner ;
OS_SECURITY_INFORMATION osSecInfo ;
BOOL fDepthFirstTraversal = TRUE ;
BOOL fApplyToDirContents = FALSE ;
BOOL fIsFile ;
BOOL fBlowAwayDACLOnCont = FALSE ;
NLS_STR nlsSelItem( 128 ) ;
RESOURCE_STR nlsCancelDialogTitle( IDS_CANCEL_TASK_APPLY_DLG_TITLE ) ;
BOOL fPrivAdjusted = FALSE;
if ( (err = nlsSelItem.QueryError()) ||
(err = nlsCancelDialogTitle.QueryError()) ||
(err = ::GetSelItem( hwndFMXWindow, 0, &nlsSelItem, &fIsFile )) )
{
*StatusReturn = SED_STATUS_FAILED_TO_MODIFY ;
::MsgPopup( hwndParent, (MSGID) err ) ;
return err ;
}
switch ( pcallbackinfo->sedpermtype )
{
case SED_ACCESSES:
osSecInfo.SetDACLReference( TRUE ) ;
fApplyToDirContents = !fIsFile && fApplyToSubObjects ;
//
// Check to see if we should do a depth first or breadth first
// traversal of the selected directory. If we have traverse
// on the directory already, then do depth first. If we don't,
// then do a breadth first and hope we are granting ourselves
// traverse.
//
if ( fApplyToSubContainers || fApplyToDirContents )
{
if ( err = ::CheckFileSecurity( nlsSelItem,
FILE_TRAVERSE | FILE_LIST_DIRECTORY,
&fDepthFirstTraversal ))
{
DBGEOL("SedCallBack - ::CheckFileSecurity failed with error " << err ) ;
*StatusReturn = SED_STATUS_FAILED_TO_MODIFY ;
::MsgPopup( hwndParent, (MSGID) err ) ;
return err ;
}
TRACEEOL("SedCallBack - Depth first = " << fDepthFirstTraversal ) ;
}
break ;
case SED_AUDITS:
{
osSecInfo.SetSACLReference( TRUE ) ;
fApplyToDirContents = !fIsFile && fApplyToSubObjects ;;
ULONG ulAuditPriv = SE_SECURITY_PRIVILEGE ;
if (err = ::NetpGetPrivilege( 1, &ulAuditPriv ) )
{
break ;
}
else
fPrivAdjusted = TRUE ;
}
break ;
case SED_OWNER:
osSecInfo.SetOwnerReference( TRUE ) ;
//
// Do a breadth first traversal since taking ownership grants
// additional privileges
//
fDepthFirstTraversal = FALSE ;
//
// Containers and objects get the same security descriptor
//
psecdescNewObjects = psecdesc ;
if ( !fIsFile )
{
switch ( ::MsgPopup( hwndParent,
IDS_OWNER_APPLY_TO_DIR_PROMPT,
MPSEV_INFO,
MP_YESNOCANCEL ))
{
case IDYES:
fApplyToSubContainers = TRUE ;
fApplyToSubObjects = TRUE ;
fBlowAwayDACLOnCont = TRUE ;
fApplyToDirContents = TRUE ;
break ;
case IDNO:
fApplyToSubContainers = FALSE ;
fApplyToSubObjects = FALSE ;
fBlowAwayDACLOnCont = FALSE ;
fApplyToDirContents = FALSE ;
break ;
case IDCANCEL:
default:
*StatusReturn = SED_STATUS_FAILED_TO_MODIFY ;
return ERROR_GEN_FAILURE ; // any nonzero error code
}
}
break ;
default:
UIASSERT( FALSE ) ;
*StatusReturn = SED_STATUS_FAILED_TO_MODIFY ;
return ERROR_GEN_FAILURE ;
}
FMX fmx( hwndFMXWindow );
UINT uiCount = fmx.QuerySelCount() ;
BOOL fDismissDlg = TRUE ;
//
// QuerySelCount only returns the number of selections in the files window,
// thus if the focus is in the directory window, then we will just make
// the selection count one for out "for" loop.
//
if ( fmx.QueryFocus() == FMFOCUS_TREE )
{
uiCount = 1 ;
}
//
// If we only have to apply permissions to a single item or we are
// taking ownership of a file, then just
// do it w/o bringing up the cancel task dialog.
//
if ( uiCount == 1 &&
!fApplyToSubContainers &&
!fApplyToSubObjects &&
!fApplyToDirContents )
{
// Try Admins Group First
OS_SECURITY_DESCRIPTOR osSecAdmin;
OS_SID ossidAdmins;
NT_ACCOUNTS_UTILITY::QuerySystemSid( UI_SID_Admins,
&ossidAdmins );
osSecAdmin.SetOwner(ossidAdmins);
osSecAdmin.SetGroup(ossidAdmins);
//
// CODEWORK We skip this hack unless taking ownership. Note that the
// osSecAdmin and ossidAdmins should also be removed.
//
if ( SED_OWNER != pcallbackinfo->sedpermtype
|| !::SetFileSecurity( (LPTSTR) nlsSelItem.QueryPch(),
osSecInfo,
osSecAdmin.QueryDescriptor() ) )
{// if it fails try owner account
if ( !::SetFileSecurity( (LPTSTR) nlsSelItem.QueryPch(),
osSecInfo,
psecdesc ) )
{
err = ::GetLastError() ;
}
}
if ( err )
{
DBGEOL("NTFS SedCallback - Error " << (ULONG)err << " applying security to " <<
nlsSelItem ) ;
::MsgPopup( hwndParent, (MSGID) err ) ;
*StatusReturn = SED_STATUS_FAILED_TO_MODIFY ;
}
}
else
{
NTFS_TREE_APPLY_CONTEXT Ctxt( nlsSelItem, osSecInfo ) ;
Ctxt.State = APPLY_SEC_FMX_SELECTION ;
Ctxt.hwndFMXWindow = hwndFMXWindow ;
Ctxt.sedpermtype = pcallbackinfo->sedpermtype ;
Ctxt.iCurrent = 0 ;
Ctxt.uiCount = uiCount ;
Ctxt.fDepthFirstTraversal = fDepthFirstTraversal ;
Ctxt.fApplyToDirContents = fApplyToDirContents ;
Ctxt.fBlowAwayDACLOnCont = fBlowAwayDACLOnCont ;
Ctxt.StatusReturn = StatusReturn ;
Ctxt.psecdesc = psecdesc ;
Ctxt.psecdescNewObjects = psecdescNewObjects ;
Ctxt.fApplyToSubContainers= fApplyToSubContainers ;
Ctxt.fApplyToSubObjects = fApplyToSubObjects ;
NTFS_CANCEL_TREE_APPLY CancelTreeApply( hwndParent,
&Ctxt,
nlsCancelDialogTitle ) ;
if ( (err = CancelTreeApply.QueryError()) ||
(err = CancelTreeApply.Process( &fDismissDlg )) )
{
*StatusReturn = SED_STATUS_FAILED_TO_MODIFY ;
::MsgPopup( hwndParent, (MSGID) err ) ;
}
}
if ( !err )
{
//
// Refresh the file manager window if permissions is updated
// (Take ownership of a tree also writes a new DACL)
//
if ( pcallbackinfo->sedpermtype == SED_ACCESSES ||
pcallbackinfo->sedpermtype == SED_OWNER )
{
fmx.Refresh();
}
if ( *StatusReturn == 0 )
*StatusReturn = SED_STATUS_MODIFIED ;
}
if ( fPrivAdjusted )
{
APIERR errTmp = NetpReleasePrivilege() ;
if ( errTmp )
{
DBGEOL("::EditNTFSAcl - Warning: NetpReleasePrivilege return error "
<< errTmp ) ;
}
}
if ( !err && !fDismissDlg )
{
//
// Don't dismiss the dialog if the user canceled the tree
// apply. This tells the ACL editor not to dismiss the permissions
// dialog (or auditing or owner).
//
err = ERROR_GEN_FAILURE ;
}
return err ;
}
/*******************************************************************
NAME: CANCEL_TREE_APPLY::DoOneItem
SYNOPSIS: This is the time slice call for the tree apply
ENTRY: ulContext - Context passed to the constructor
RETURNS: NERR_Success if this time slice was successful, error
code otherwise (which will be displayed to the user).
NOTES:
HISTORY:
Johnl 22-Oct-1992 Created
********************************************************************/
APIERR CANCEL_TREE_APPLY::DoOneItem( ULONG_PTR ulContext,
BOOL *pfContinue,
BOOL *pfDisplayErrors,
MSGID *pmsgidAlternateMessage )
{
TREE_APPLY_CONTEXT * pCtxt = (TREE_APPLY_CONTEXT*) ulContext ;
*pfDisplayErrors = TRUE ;
*pfContinue = TRUE ;
APIERR err = NERR_Success ;
APIERR errTrav = NERR_Success;
BOOL fSuccess ;
switch ( pCtxt->State )
{
case APPLY_SEC_IN_FS_ENUM:
{
UIASSERT( pCtxt->pfsenum != NULL ) ;
fSuccess = pCtxt->pfsenum->Next() ;
NLS_STR nlsFileName ;
if ( (err = nlsFileName.QueryError()) ||
(err = pCtxt->pfsenum->QueryName( &nlsFileName )))
{
break ;
}
REQUIRE( UpdateStatus( nlsFileName ) == NERR_Success ) ;
//
// Only write the security if the enumeration was successful
//
if ( fSuccess )
{
ApplySecurity:
err = WriteSecurity( ulContext,
nlsFileName,
!(pCtxt->pfsenum->QueryAttr()&_A_SUBDIR),
pfContinue ) ;
if ( !*pfContinue )
{
delete pCtxt->pfsenum ;
pCtxt->pfsenum = NULL ;
}
//
// Report any traversal errors after attempting to apply
// security to the container we failed to traverse
//
if ( errTrav )
err = errTrav;
break ;
}
else if ((err = pCtxt->pfsenum->QueryLastError()) != ERROR_NO_MORE_FILES)
{
*pmsgidAlternateMessage = IDS_CANCEL_TASK_TRAV_ERROR_MSG ;
//
// Apply security even in the error case if we're not at the
// selected directory. This handles the case of hitting a no
// access directory as the only selection
//
if ( pCtxt->pfsenum->QueryTotalFiles() )
{
errTrav = err;
goto ApplySecurity;
}
//
// falls through and deletes the enumerator
//
}
else
{
//
// Running out of files is a success error code
//
err = NERR_Success ;
TRACEEOL("SedCallBack - Traversed " << pCtxt->pfsenum->QueryTotalFiles() <<
" files and directories") ;
}
delete pCtxt->pfsenum ;
pCtxt->pfsenum = NULL ;
pCtxt->State = APPLY_SEC_FMX_POST_FS_ENUM ;
}
break ;
case APPLY_SEC_FMX_POST_FS_ENUM:
//
// Apply security to the container after everything under this has
// been applied if we are doing a depth first traversal.
//
if ( pCtxt->fDepthFirstTraversal )
{
UpdateStatus( pCtxt->nlsSelItem ) ;
if ( err = WriteSecurity( ulContext,
pCtxt->nlsSelItem,
pCtxt->fIsSelFile,
pfContinue ))
{
// Fall through
}
}
pCtxt->State = APPLY_SEC_FMX_SELECTION ;
break ;
case APPLY_SEC_FMX_SELECTION:
/* Have we went through all of the selected items?
*/
if ( pCtxt->iCurrent >= pCtxt->uiCount )
{
*pfContinue = FALSE ;
break ;
}
/* Get the current selection and apply the permissions
*/
if (err = ::GetSelItem( pCtxt->hwndFMXWindow,
pCtxt->iCurrent++,
&pCtxt->nlsSelItem,
&pCtxt->fIsSelFile ) )
{
break ;
}
//
// If we're doing the breadthfirst traversal, then apply to the
// container before traversing, else apply after traversing.
// If it's a file, then always apply.
//
if (( !pCtxt->fDepthFirstTraversal || pCtxt->fIsSelFile ) ||
( (!pCtxt->fApplyToSubContainers && !pCtxt->fApplyToDirContents) &&
!pCtxt->fIsSelFile ))
{
UpdateStatus( pCtxt->nlsSelItem ) ;
if ( err = WriteSecurity( ulContext,
pCtxt->nlsSelItem,
pCtxt->fIsSelFile,
pfContinue ))
{
break ;
}
}
//
// If the user checked the apply to tree box or apply to existing file
// checkbox and this is a container then apply the
// permissions down the sub-tree optionally to files
//
if ( (pCtxt->fApplyToSubContainers || pCtxt->fApplyToDirContents)
&& !pCtxt->fIsSelFile )
{
UpdateStatus( pCtxt->nlsSelItem ) ;
//
// Determine whether we should apply permissions to both
// directories and files, directories only or files only
//
enum FILE_TYPE filetype ;
switch ((pCtxt->fApplyToSubContainers << 1) + pCtxt->fApplyToDirContents )
{
case 3:
filetype = FILTYP_ALL_FILES ;
break ;
case 2:
filetype = FILTYP_DIRS ;
break ;
case 1:
filetype = FILTYP_FILES ;
break ;
default:
UIASSERT( FALSE ) ;
}
pCtxt->pfsenum = new W32_FS_ENUM( pCtxt->nlsSelItem,
SZ("*.*"),
filetype,
pCtxt->fDepthFirstTraversal,
pCtxt->fApplyToSubContainers ?
0xffffffff : 0 ) ;
err = ERROR_NOT_ENOUGH_MEMORY ;
if ( pCtxt == NULL ||
(err = pCtxt->pfsenum->QueryError() ))
{
break ;
}
//
// Next time around, start doing the enumeration
//
pCtxt->State = APPLY_SEC_IN_FS_ENUM ;
}
break ;
}
if ( err && *pCtxt->StatusReturn == 0 )
{
*pCtxt->StatusReturn = (pCtxt->iCurrent-1 ? SED_STATUS_NOT_ALL_MODIFIED :
SED_STATUS_FAILED_TO_MODIFY);
}
return err ;
}
/*******************************************************************
NAME: NTFS_CANCEL_TREE_APPLY::WriteSecurity
SYNOPSIS: Write security to an NTFS volume
ENTRY: ulContext - Pointer to NTFS_TREE_APPLY_CONTEXT
pszFileName - File to apply to
fIsFile - TRUE if object, FALSE if container
pfContinue - Set to FALSE if the apply should be
terminated.
RETURNS: NERR_Success if successful, error code otherwise
HISTORY:
Johnl 23-Oct-1992 Created
********************************************************************/
APIERR NTFS_CANCEL_TREE_APPLY::WriteSecurity( ULONG_PTR ulContext,
const TCHAR * pszFileName,
BOOL fIsFile,
BOOL * pfContinue )
{
APIERR err = NERR_Success ;
NTFS_TREE_APPLY_CONTEXT * pCtxt = (NTFS_TREE_APPLY_CONTEXT*) ulContext ;
SECURITY_INFORMATION SecInfoTmp = (SECURITY_INFORMATION) pCtxt->osSecInfo ;
*pfContinue = TRUE ;
//
// If any of the "container" flags are set and we are looking at a
// file, then use the object security descriptor, else use the container
// /object security descriptor.
//
PSECURITY_DESCRIPTOR psecdescTmp = fIsFile &&
(pCtxt->fApplyToSubContainers ||
pCtxt->fApplyToSubObjects ||
pCtxt->fApplyToDirContents) ?
pCtxt->psecdescNewObjects :
pCtxt->psecdesc ;
//
// Taking ownership also optionally blows away the DACL at the user's
// request
//
if ( !fIsFile && (pCtxt->sedpermtype == SED_OWNER) )
{
OS_ACL osDACL ;
OS_ACE osACE ;
OS_SID ossidUser ;
OS_SECURITY_DESCRIPTOR ossecdesc( psecdescTmp, TRUE ) ;
if ( (err = osDACL.QueryError()) ||
(err = osACE.QueryError()) ||
(err = ossidUser.QueryError()) ||
(err = ossecdesc.QueryError()) ||
(err = NT_ACCOUNTS_UTILITY::QuerySystemSid( UI_SID_CurrentProcessOwner,
&ossidUser )) )
{
// Fall through
}
if ( !err )
{
//
// Put an ACE that grants full control and that will be
// inherited to new objects and new containers on this
// container. The SID is the currently logged on user.
//
osACE.SetType( ACCESS_ALLOWED_ACE_TYPE ) ;
osACE.SetInheritFlags( OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE ) ;
osACE.SetAccessMask( GENERIC_ALL ) ;
if ( (err = osACE.SetSID( ossidUser )) ||
(err = osDACL.AddACE( 0, osACE )) ||
(err = ossecdesc.SetDACL( TRUE, &osDACL )) )
{
// Fall through
}
}
if ( !err)
{
OS_SECURITY_DESCRIPTOR osSecAdmin;
OS_SID ossidAdmins;
NT_ACCOUNTS_UTILITY::QuerySystemSid( UI_SID_Admins,
&ossidAdmins );
osSecAdmin.SetOwner(ossidAdmins);
osSecAdmin.SetGroup(ossidAdmins);
osSecAdmin.SetDACL( TRUE, &osDACL );
// Try Admins Group First
if ( !::SetFileSecurity( (LPTSTR) pszFileName,
SecInfoTmp,
osSecAdmin.QueryDescriptor() ) )
{
// if it fails try owner account
if (!::SetFileSecurity( (LPTSTR) pszFileName, // Take ownership
SecInfoTmp,
ossecdesc ))
{
err = ::GetLastError() ;
}
}
}
//
// Now check if they have traversal permission. If they do, then
// leave the ACL alone, else ask them if they want to blow away the
// DACL
//
BOOL fCanTraverse ;
if ( !err &&
!(err = ::CheckFileSecurity( (LPTSTR) pszFileName,
FILE_TRAVERSE | FILE_LIST_DIRECTORY,
&fCanTraverse )) &&
!fCanTraverse )
{
switch ( ::MsgPopup( this,
IDS_OWNER_NUKE_DACL_WARNING,
MPSEV_INFO,
MP_YES| MP_CANCEL,
pszFileName ))
{
case IDYES:
if ( !::SetFileSecurity( (LPTSTR) pszFileName, // Blow away DACL
DACL_SECURITY_INFORMATION,
ossecdesc ))
{
err = ::GetLastError() ;
}
break ;
default:
case IDNO:
case IDCANCEL:
*pfContinue = FALSE ;
break ;
}
}
}
else // if ( !fIsFile && (pCtxt->sedpermtype == SED_OWNER) )
{
if ((pCtxt->sedpermtype == SED_OWNER))
{
OS_SECURITY_DESCRIPTOR osSecAdmin;
OS_SID ossidAdmins;
NT_ACCOUNTS_UTILITY::QuerySystemSid( UI_SID_Admins,
&ossidAdmins );
osSecAdmin.SetOwner(ossidAdmins);
osSecAdmin.SetGroup(ossidAdmins);
// Try Admins Group First
if ( !::SetFileSecurity( (LPTSTR) pszFileName,
SecInfoTmp,
osSecAdmin.QueryDescriptor() ) )
{
// if it fails try owner account
if ( !::SetFileSecurity( (LPTSTR) pszFileName,
SecInfoTmp,
psecdescTmp ))
{
err = ::GetLastError() ;
}
}
}
else if ( !::SetFileSecurity( (LPTSTR) pszFileName,
SecInfoTmp,
psecdescTmp ))
{
err = ::GetLastError() ;
}
}
return err ;
}
/*******************************************************************
NAME: CompareNTFSSecurityIntersection
SYNOPSIS: Determines if the files/dirs currently selected have
equivalent security descriptors
ENTRY: hwndFMX - FMX Hwnd used for getting selection
sedpermtype - Interested in DACL or SACL
psecdesc - Baseline security descriptor to compare against
pfOwnerEqual - Set to TRUE if all the owners are equal
pfACLEqual - Set to TRUE if all of the DACLs/SACLs are
equal. If FALSE, then pfOwnerEqual should be ignored
RETURNS: NERR_Success if successful, error code otherwise
NOTES: The first non-equal ACL causes the function to exit.
On a 20e with 499 files selected locally, it took 35.2 minutes
to read the security descriptors from the disk and 14 seconds
to determine the intersection. So even though the Compare
method uses an n^2 algorithm, it only takes up 0.6% of the
wait time.
HISTORY:
Johnl 05-Nov-1992 Created
********************************************************************/
APIERR CompareNTFSSecurityIntersection( HWND hwndFMX,
enum SED_PERM_TYPE sedpermtype,
PSECURITY_DESCRIPTOR psecdesc,
BOOL * pfOwnerEqual,
BOOL * pfACLEqual,
NLS_STR * pnlsFailingFile,
PGENERIC_MAPPING pGenericMapping,
PGENERIC_MAPPING pGenericMappingObjects,
BOOL fMapGenAll,
BOOL fIsContainer )
{
TRACEEOL("::CompareNTFSSecurityIntersection - Entered @ " << ::GetTickCount()/100) ;
FMX fmx( hwndFMX );
UIASSERT( fmx.QuerySelCount() > 1 ) ;
APIERR err ;
OS_SECURITY_DESCRIPTOR ossecdesc1( psecdesc ) ;
UINT cSel = fmx.QuerySelCount() ;
NLS_STR nlsSel( PATHLEN ) ;
BUFFER buffSecDescData( 1024 ) ;
if ( (err = nlsSel.QueryError()) ||
(err = buffSecDescData.QueryError()) )
{
return err ;
}
*pfOwnerEqual = TRUE ;
*pfACLEqual = TRUE ;
for ( UINT i = 1 ; i < cSel ; i++ )
{
if ( (err = ::GetSelItem( hwndFMX, i, &nlsSel, NULL )) ||
(err = ::GetSecurity( nlsSel,
&buffSecDescData,
sedpermtype,
NULL )) )
{
break ;
}
BOOL fACLEqual = FALSE ;
BOOL fOwnerEqual = FALSE ;
PSECURITY_DESCRIPTOR psecdesc2 = (PSECURITY_DESCRIPTOR)
buffSecDescData.QueryPtr() ;
OS_SECURITY_DESCRIPTOR ossecdesc2( psecdesc2 ) ;
if ( (err = ossecdesc2.QueryError()) ||
(err = ossecdesc1.Compare( &ossecdesc2,
&fOwnerEqual,
NULL,
sedpermtype == SED_ACCESSES ?
&fACLEqual : NULL,
sedpermtype == SED_AUDITS ?
&fACLEqual : NULL ,
pGenericMapping,
pGenericMappingObjects,
fMapGenAll,
fIsContainer )) )
{
break ;
}
if ( !fACLEqual )
{
*pfACLEqual = FALSE ;
return pnlsFailingFile->CopyFrom( nlsSel ) ;
}
if ( *pfOwnerEqual && !fOwnerEqual )
{
*pfOwnerEqual = FALSE ;
}
}
//
// Some errors aren't fatal (like ERROR_ACCESS_DENIED)
//
APIERR errtmp = pnlsFailingFile->CopyFrom( nlsSel ) ;
if ( errtmp )
err = errtmp ;
TRACEEOL("::CompareNTFSSecurityIntersection - Left @ " << ::GetTickCount()/100) ;
return err ;
}
/*******************************************************************
NAME: EditOwnerInfo
SYNOPSIS: This function sets up the parameters for calling the
SedTakeOwnership API.
ENTRY: hwndFMXWindow - Window handle received by the File manager
extensions.
NOTES:
HISTORY:
Johnl 13-Feb-1992 Implemented with real code
********************************************************************/
void EditOwnerInfo( HWND hwndFMXWindow )
{
AUTO_CURSOR cursorHourGlass ;
APIERR err = NERR_Success;
BOOL fIsFile ;
BOOL fCantRead = FALSE ; // Did we read the Owner?
BOOL fCantWrite = FALSE ; // Can we write the owner?
UINT uiCount ;
NLS_STR nlsSelItem;
PSECURITY_DESCRIPTOR psecdesc = NULL ;
BUFFER buffSecDescData( 1024 ) ;
RESOURCE_STR nlsHelpFileName( IDS_FILE_PERM_HELP_FILE ) ;
if ( ( err = buffSecDescData.QueryError() )
|| ( err = nlsHelpFileName.QueryError() )
)
{
::MsgPopup( hwndFMXWindow, (MSGID) err ) ;
return ;
}
FMX fmx( hwndFMXWindow );
/* If the focus is in tree portion of the filemanager (left pane) then
* one directory is selected.
*/
uiCount = (fmx.QueryFocus() == FMFOCUS_TREE ? 1 : fmx.QuerySelCount()) ;
DBGEOL( SZ("::EditOwnerInfo - ") << uiCount << SZ(" files selected")) ;
BOOL fIsNTFS ;
BOOL fIsLocal ;
NLS_STR nlsServer( RMLEN ) ;
if ( (err = ::GetSelItem( hwndFMXWindow, 0, &nlsSelItem, &fIsFile )) ||
(err = ::IsNTFS( nlsSelItem, &fIsNTFS )) ||
(err = nlsServer.QueryError()))
{
::MsgPopup( hwndFMXWindow, (MSGID) err ) ;
return ;
}
err = ::TargetServerFromDosPath( nlsSelItem,
&fIsLocal,
&nlsServer );
if ( err == NERR_InvalidDevice )
{
NLS_STR nlsDrive( nlsSelItem );
ISTR istr( nlsDrive );
err = nlsDrive.QueryError();
if ( err == NERR_Success )
{
istr += 2;
nlsDrive.DelSubStr( istr );
err = WNetFMXEditPerm( (LPWSTR) nlsDrive.QueryPch(),
hwndFMXWindow,
WNPERM_DLG_OWNER );
}
}
if ( err != NERR_Success )
{
::MsgPopup( hwndFMXWindow, (MSGID) err );
return;
}
if ( !fIsNTFS )
{
::MsgPopup( hwndFMXWindow, (MSGID) IERR_OWNER_NOT_NTFS_VOLUME ) ;
return ;
}
/* We display the filename and get the security descriptor
* if there is only 1 item selected
*/
if ( uiCount == 1)
{
switch ( err = ::GetSecurity( nlsSelItem,
&buffSecDescData,
SED_OWNER,
NULL ) )
{
case NO_ERROR:
psecdesc = (PSECURITY_DESCRIPTOR) buffSecDescData.QueryPtr() ;
break ;
case ERROR_ACCESS_DENIED:
err = NERR_Success ;
fCantRead = TRUE ;
psecdesc = NULL ;
break ;
default:
{
::MsgPopup( hwndFMXWindow, (MSGID) err ) ;
return ;
}
}
}
MSGID msgidObjType = 0, msgidObjName = 0 ;
if ( uiCount > 1 )
{
msgidObjType = IDS_FILES_AND_DIRS ;
}
else
{
if ( fIsFile )
msgidObjType = IDS_FILE ;
else
msgidObjType = IDS_DIRECTORY ;
BOOL fPrivAdjusted = FALSE;
ULONG ulOwnerPriv = SE_TAKE_OWNERSHIP_PRIVILEGE ;
if ( (err = ::NetpGetPrivilege( 1, &ulOwnerPriv )) &&
(err != ERROR_PRIVILEGE_NOT_HELD) )
{
::MsgPopup( hwndFMXWindow, (MSGID) err ) ;
return ;
}
else
{
BOOL fCanWrite ;
if ( err = ::CheckFileSecurity( nlsSelItem,
WRITE_OWNER,
&fCanWrite ))
{
::MsgPopup( hwndFMXWindow, (MSGID) err ) ;
::NetpReleasePrivilege() ;
return ;
}
fCantWrite = !fCanWrite ;
::NetpReleasePrivilege() ;
}
}
RESOURCE_STR nlsTypeName( msgidObjType ) ;
if ( (err = nlsSelItem.QueryError() ) ||
(err = nlsTypeName.QueryError()) )
{
::MsgPopup( hwndFMXWindow, (MSGID) err ) ;
return ;
}
NTFS_CALLBACK_INFO callbackinfo ;
callbackinfo.hwndFMXOwner = hwndFMXWindow ;
callbackinfo.sedpermtype= SED_OWNER ;
DWORD dwSedStatus ;
SED_HELP_INFO sedhelpinfo ;
sedhelpinfo.pszHelpFileName = (LPWSTR) nlsHelpFileName.QueryPch() ;
sedhelpinfo.aulHelpContext[HC_MAIN_DLG] = HC_TAKEOWNERSHIP_DIALOG ;
err = SedTakeOwnership( hwndFMXWindow,
::hModule,
fIsLocal ? NULL : (LPTSTR) nlsServer.QueryPch(),
(LPTSTR) nlsTypeName.QueryPch(),
uiCount==1 ? (LPTSTR)nlsSelItem.QueryPch() : NULL,
uiCount,
SedCallback,
(ULONG_PTR) &callbackinfo,
psecdesc,
(BOOLEAN)fCantRead,
(BOOLEAN)fCantWrite,
&dwSedStatus,
&sedhelpinfo,
0
) ;
}
/*******************************************************************
NAME: ::GetSecurity
SYNOPSIS: Retrieves a security descriptor from an NTFS file/directory
ENTRY: pszFileName - Name of file/dir to get security desc. for
pbuffSecDescData - Buffer to store the data into
sedpermtype - Are we getting audit/access info
pfAuditPrivAdjusted - Set to TRUE if audit priv was enabled.
Set this to NULL if the privilege has already been adjusted
RETURNS: NERR_Success if successful, error code otherwise
NOTES:
HISTORY:
Johnl 05-Nov-1992 Broke out
********************************************************************/
APIERR GetSecurity( const TCHAR * pszFileName,
BUFFER * pbuffSecDescData,
enum SED_PERM_TYPE sedpermtype,
BOOL * pfAuditPrivAdjusted )
{
OS_SECURITY_INFORMATION osSecInfo ;
DWORD dwLengthNeeded ;
APIERR err = NERR_Success ;
if ( pfAuditPrivAdjusted )
*pfAuditPrivAdjusted = FALSE ;
do { // error breakout
if ( (err = pbuffSecDescData->QueryError()) )
{
break ;
}
switch ( sedpermtype )
{
case SED_ACCESSES:
osSecInfo.SetDACLReference() ;
//
// Fall through, we want the owner and group if we are getting
// the DACL
//
case SED_OWNER:
osSecInfo.SetOwnerReference() ;
osSecInfo.SetGroupReference() ;
break ;
case SED_AUDITS:
osSecInfo.SetSACLReference() ;
if ( pfAuditPrivAdjusted != NULL )
{
/* We will need to enable the SeAuditPrivilege to read/write the
* SACL for NT.
*/
ULONG ulAuditPriv = SE_SECURITY_PRIVILEGE ;
if ( err = ::NetpGetPrivilege( 1, &ulAuditPriv ))
{
break ;
}
*pfAuditPrivAdjusted = TRUE ;
}
break ;
default:
UIASSERT(FALSE) ;
err = ERROR_GEN_FAILURE ;
break ;
}
if ( err )
break ;
//
// Try once with a 1k buffer, if it doesn't fit then we will try again
// with the known required size which should succeed unless another
// error occurs, in which case we bail.
//
BOOL fCantRead = FALSE ; // Did we read the ACL?
PSECURITY_DESCRIPTOR pSecurityDesc = NULL ;
if (!::GetFileSecurity( (LPTSTR) pszFileName,
osSecInfo,
(PSECURITY_DESCRIPTOR)pbuffSecDescData->QueryPtr(),
pbuffSecDescData->QuerySize(),
&dwLengthNeeded ))
{
err = ::GetLastError() ;
switch ( err )
{
case ERROR_INSUFFICIENT_BUFFER:
{
err = pbuffSecDescData->Resize( (UINT) dwLengthNeeded ) ;
if ( err )
break ;
/* If this guy fails then we bail
*/
if (!::GetFileSecurity( (LPTSTR) pszFileName,
osSecInfo,
(PSECURITY_DESCRIPTOR)pbuffSecDescData->QueryPtr(),
pbuffSecDescData->QuerySize(),
&dwLengthNeeded ))
{
err = ::GetLastError() ;
break ;
}
}
break ;
default:
/* Fall through to the next switch statement which is the error
* handler for this block
*/
break ;
}
}
} while ( FALSE ) ;
return err ;
}
/*******************************************************************
NAME: InitializeNTFSGenericMapping
SYNOPSIS: Initializes the passed generic mapping structure
appropriately depending on whether this is a file
or a directory.
ENTRY: pNTFSGenericMapping - Pointer to GENERIC_MAPPING to be init.
fIsDirectory - TRUE if directory, FALSE if file
EXIT:
RETURNS:
NOTES: Note that Delete Child was removed from Generic Write.
HISTORY:
Johnl 27-Feb-1992 Created
********************************************************************/
void InitializeNTFSGenericMapping( PGENERIC_MAPPING pNTFSGenericMapping,
BOOL fIsDirectory )
{
UNREFERENCED( fIsDirectory ) ;
pNTFSGenericMapping->GenericRead = FILE_GENERIC_READ ;
pNTFSGenericMapping->GenericWrite = FILE_GENERIC_WRITE ;
pNTFSGenericMapping->GenericExecute = FILE_GENERIC_EXECUTE ;
pNTFSGenericMapping->GenericAll = FILE_ALL_ACCESS ;
}
/*******************************************************************
NAME: ::IsNTFS
SYNOPSIS: This function checks the given resource and attempts to
determine if it points to an NTFS partition.
ENTRY: pszResource - Pointer to file/directory name (may be UNC)
pfIsNTFS - Pointer to BOOL that will receive the results
RETURNS: NERR_Success if successful, error code otherwise
NOTES:
HISTORY:
Johnl 08-May-1992 Created
********************************************************************/
APIERR IsNTFS( const TCHAR * pszResource, BOOL * pfIsNTFS )
{
UIASSERT( pszResource != NULL && pfIsNTFS != NULL ) ;
*pfIsNTFS = FALSE ;
APIERR err = NERR_Success ;
DWORD dwAttributes;
TCHAR szResourceTemp[2 * MAX_PATH]; // Allow for long computer and share names
do { // error breakout
lstrcpyn( szResourceTemp, pszResource, sizeof(szResourceTemp) / sizeof(TCHAR) );
// Strip the path to root form, acceptable to GetVolumeInformation
if ((szResourceTemp[0] == TEXT('\\')) && (szResourceTemp[1] == TEXT('\\')))
{
// It's a UNC path. Find the fourth backslash (if there is
// one) and truncate after that character
int cBackslashes = 2;
TCHAR* pChar = &(szResourceTemp[2]);
while ((*pChar) && (cBackslashes < 4))
{
if (*pChar == TEXT('\\'))
{
cBackslashes++;
}
pChar = CharNext(pChar);
}
if (*pChar)
{
*pChar = TEXT('\0');
}
else
{
// A bogus path was passed in
err = ERROR_FILE_NOT_FOUND;
break;
}
}
else
{
// It's a drive-based path. Truncate after the first three
// characters ("x:\")
szResourceTemp[3] = TEXT('\0');
}
if ( FALSE == GetVolumeInformation( szResourceTemp,
NULL,
NULL,
NULL,
NULL,
&dwAttributes,
NULL,
NULL))
{
// If we failed because we were denied access, then
// we can probably assume the filesystem supports ACLs
if ( GetLastError() == ERROR_ACCESS_DENIED )
{
DBGEOL("::IsNTFS - Unable to determine volume information "
<< " (access denied) assuming the file system is NTFS") ;
*pfIsNTFS = TRUE;
break;
}
// Otherwise, set an error code and break out
err = GetLastError();
DBGEOL("::IsNTFS - GetVolumeInformation failed with error "
<< (ULONG) err ) ;
break;
}
TRACEEOL("::IsNTFS - File system attributes are " << (HEX_STR) dwAttributes ) ;
if ( dwAttributes & FS_PERSISTENT_ACLS )
{
*pfIsNTFS = TRUE;
}
} while ( FALSE );
return err ;
}
/*******************************************************************
NAME: CheckFileSecurity
SYNOPSIS: Checks to see if the current user has access to the file or
directory
ENTRY: pszFileName - File or directory name
DesiredAccess - Access to check for
pfAccessGranted - Set to TRUE if access was granted
RETURNS: NERR_Success if successful, error code otherwise
NOTES: If the check requires enabled privileges, they must be enabled
before this call.
HISTORY:
Johnl 15-Jan-1993 Created
********************************************************************/
APIERR CheckFileSecurity( const TCHAR * pszFileName,
ACCESS_MASK DesiredAccess,
BOOL * pfAccessGranted )
{
APIERR err = NERR_Success ;
*pfAccessGranted = TRUE ;
do { // error breakout
//
// Convert the DOS device name ("X:\") to an NT device name
// (looks something like "\dosdevices\X:\")
//
int cbFileName = strlenf( pszFileName ) * sizeof( TCHAR ) ;
UNICODE_STRING UniStrNtFileName ;
::memsetf( (PVOID)&UniStrNtFileName, '\0', sizeof(UniStrNtFileName) );
if (!RtlDosPathNameToNtPathName_U( pszFileName,
&UniStrNtFileName,
NULL,
NULL))
{
UIASSERT( FALSE ) ;
err = ERROR_NOT_ENOUGH_MEMORY ;
break ;
}
OBJECT_ATTRIBUTES oa ;
IO_STATUS_BLOCK StatusBlock ;
InitializeObjectAttributes( &oa,
&UniStrNtFileName,
OBJ_CASE_INSENSITIVE,
0,
0 );
//
// Check to see if we have permission/privilege to read the security
//
HANDLE hFile ;
if ( (err = ERRMAP::MapNTStatus(::NtOpenFile(
&hFile,
DesiredAccess,
&oa,
&StatusBlock,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0 ))) )
{
TRACEEOL("CheckFileSecurity - check failed with error " << err <<
" with desired access " << (HEX_STR) DesiredAccess ) ;
if ( err == ERROR_ACCESS_DENIED )
{
*pfAccessGranted = FALSE ;
err = NERR_Success ;
}
}
else
::NtClose( hFile ) ;
if (UniStrNtFileName.Buffer != 0)
RtlFreeUnicodeString( &UniStrNtFileName );
} while ( FALSE ) ;
return err ;
}
| 35.869087 | 104 | 0.481991 | [
"object"
] |
7c420e2bcdd465961a6c06696f4a27683325f6c8 | 1,718 | hpp | C++ | src/Enzo/enzo_EnzoComputeSmoothJacobi.hpp | drreynolds/cello_drreynolds | c75e36b99f9928b24d1bd421412c53dcf04a34d8 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/Enzo/enzo_EnzoComputeSmoothJacobi.hpp | drreynolds/cello_drreynolds | c75e36b99f9928b24d1bd421412c53dcf04a34d8 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/Enzo/enzo_EnzoComputeSmoothJacobi.hpp | drreynolds/cello_drreynolds | c75e36b99f9928b24d1bd421412c53dcf04a34d8 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | // See LICENSE_CELLO file for license and copyright information
/// @file enzo_EnzoComputeSmoothJacobi.hpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2015-04-30 18:45:58
/// @brief [\ref Enzo] Declaration of the EnzoComputeSmoothJacobi class
#ifndef ENZO_ENZO_COMPUTE_SMOOTH_JACOBI_HPP
#define ENZO_ENZO_COMPUTE_SMOOTH_JACOBI_HPP
class EnzoComputeSmoothJacobi : public Compute {
/// @class EnzoComputeSmoothJacobi
/// @ingroup Enzo
/// @brief [\ref Enzo]
public: // interface
/// Constructor
EnzoComputeSmoothJacobi(Matrix * A,
int ix,
int ib,
int ir,
int id,
double weight=1.0,
int iter_max = 1) throw();
/// Charm++ PUP::able declarations
PUPable_decl(EnzoComputeSmoothJacobi);
/// Charm++ PUP::able migration constructor
EnzoComputeSmoothJacobi (CkMigrateMessage *m) {}
/// CHARM++ Pack / Unpack function
void pup (PUP::er &p)
{
TRACEPUP;
Compute::pup(p);
p | A_;
p | ix_;
p | ib_;
p | ir_;
p | id_;
p | w_;
p | n_;
}
public: // virtual functions
virtual void compute ( Block * block) throw();
private: // functions
/// Implementation of compute() for given precision
template <typename T>
void compute_(Block * block);
private: // attributes
// NOTE: change pup() function whenever attributes change
/// Matrix A for smoothing A*X = B
Matrix * A_;
/// Field index for vector X
int ix_;
/// Field index for rhs B
int ib_;
/// Field index for residual R
int ir_;
/// Field index for matrix diagonal D
int id_;
/// Weighting
double w_;
/// Number of iterations
int n_;
};
#endif /* ENZO_ENZO_COMPUTE_SMOOTH_JACOBI_HPP */
| 19.522727 | 74 | 0.652503 | [
"vector"
] |
7c42c2bb4abaa45badcc063cfc81827b004e6bc8 | 2,923 | cpp | C++ | src/main.cpp | ajulyav/Kalman-Filter | 7d0b937ca12e603408e76d711e8c45ba476ed28a | [
"MIT"
] | 1 | 2021-07-23T06:35:08.000Z | 2021-07-23T06:35:08.000Z | src/main.cpp | ajulyav/Kalman-Filter | 7d0b937ca12e603408e76d711e8c45ba476ed28a | [
"MIT"
] | null | null | null | src/main.cpp | ajulyav/Kalman-Filter | 7d0b937ca12e603408e76d711e8c45ba476ed28a | [
"MIT"
] | null | null | null | /* Applied Video Analysis of Sequences (AVSA)
* LAB3: Object Tracking
*/
//system libraries
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
//openCV
#include <opencv2/opencv.hpp>
#include <opencv2/video/background_segm.hpp>
#include "FgSegment.hpp"
#include "Kalman.hpp"
#include "ShowManyImages.hpp"
//namespaces
using namespace cv;
using namespace std;
//main function
int main(int argc, char ** argv)
{
//std::string inputvideo = "/home/avsa/AVSA2020datasets/dataset_lab3/lab3.3/abandonedBox_600_1000_clip.mp4"; //Video Seq works well with the given params
//std::string inputvideo = "/home/avsa/AVSA2020datasets/dataset_lab3/lab3.3/boats_6950_7900_clip.mp4";
//std::string inputvideo = "/home/avsa/AVSA2020datasets/dataset_lab3/lab3.3/pedestrians_800_1025_clip.mp4";
std::string inputvideo = "/home/avsa/AVSA2020datasets/dataset_lab3/lab3.3/streetCornerAtNight_0_100_clip.mp4";
//INIT NEW VARIABLES
int int_counter = 0;
Mat frame, fgmask;
Mat frame_blob, frame_measurment, frame_common, frame_trajectory; //to show later results
Kalman kalman(2); // 1 - velocity, 2 - acceleration
FgSegment fgseg; // measurement extraction
VideoCapture cap;
//Read video
cap.open(inputvideo);
if (!cap.isOpened())
{
std::cout << "Could not open video file " << inputvideo << std::endl;
return -1;
}
cap >> frame; //get first video frame
//Go through all video
while(true)
{
cap.read(frame);
if(!frame.data){cout<<"Finished";break;};
// copy exact image for
frame.copyTo(frame_trajectory);
frame.copyTo(frame_blob);
frame.copyTo(frame_measurment);
frame.copyTo(frame_common);
//fg_segmentation
fgmask = fgseg.bkg_subtraction(frame);
//morphological_opening
fgmask = fgseg.MorphologicalOpen(fgmask);
//extract blobs
fgseg.extractBlobs(fgmask);
//Kalman filter
kalman.predict(fgseg.getBlobCenters(),fgseg.BlobExists());
//draw results
kalman.draw(fgseg.getBlobCenters(), frame_common, frame_measurment, frame_trajectory);
//Show videos
ShowManyImages("frame | fgmask | blob || measurement | common | trajectory", 6,
frame,
fgmask,
fgseg.paintBlobImage(frame_blob, fgseg.getBloblist()),
fgseg.paintBlobImage(frame_measurment, fgseg.getBloblist()),
fgseg.paintBlobImage(frame_common, fgseg.getBloblist()),
fgseg.paintBlobImage(frame_trajectory, fgseg.getBloblist())
);
if(waitKey(30) == 27) break;
int_counter++;
}
cap.release();
destroyAllWindows();
waitKey(0);
return 0;
}
| 27.064815 | 158 | 0.63428 | [
"object"
] |
7c4a11af9b33d605b6e2dbef2f5eb603e96a06c2 | 3,479 | hpp | C++ | Mediator.hpp | jetpotion/MonteCarloOptionPricer | 0024c9c900d1c968fca8946aa438ba07453272d8 | [
"MIT"
] | 2 | 2020-12-13T00:07:01.000Z | 2021-01-14T00:40:33.000Z | Mediator.hpp | jetpotion/MonteCarloOptionPricer | 0024c9c900d1c968fca8946aa438ba07453272d8 | [
"MIT"
] | null | null | null | Mediator.hpp | jetpotion/MonteCarloOptionPricer | 0024c9c900d1c968fca8946aa438ba07453272d8 | [
"MIT"
] | null | null | null | #include "Builder.hpp"
#include "StopWatch.hpp"
#include <fstream>
#include <iostream>
#include <omp.h>
#include <memory>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/prepared_statement.h>
#ifndef MEDIATOR_HPP
#define MEDIATOR_HPP
//One FileOutput at a time throughout the program make sure that this is a truly unique and
static std::unique_ptr<std::ofstream> filewriter = std::make_unique<std::ofstream>("Output.csv", std::ios::out);
struct Mediator
{
//All the fields are public. I use a struct to easily modify the data fields of equation, It also not necessary to store Mediator as a class.Sine mediator in this case
//Will not be polymorphic
StochasticEquation eq; //EQ
FiniteDifferenceMethod method; //Method
RandomNumberGenerator rng; //Rng
Pricers type; //Type of option
std::vector<double>resolution; //Resoluton operator
std::size_t NSIM; //Number of file writer
int sample_num = 1; //The current option data number
Mediator() = default;
//Construct the parts from the builder methods
Mediator(const std::tuple<FiniteDifferenceMethod, RandomNumberGenerator, StochasticEquation, Pricers>& parts, std::size_t Nsim)
{
eq = std::get<2>(parts);
method = std::get<0>(parts);
rng = std::get<1>(parts);
type = std::get<3>(parts);
resolution = std::vector<double>(method->NT + 1);
NSIM = Nsim;
(*filewriter) << "NSIM: " << NSIM << " NT:" << method->NT << "\n";
}
void start()
{
//start the watch
StopWatch watch;
watch.StartStopWatch();
//Parallelizd for loop with 2 threads. One thread for the outer loop and the collpase directive to specify that 2 threads are working in parallel in each loop
resolution[0] = eq->InitialCondition();
//Only parallaelize if its 2000000 ops , V0ld AND Vnew are instantiated constantly, The number of threads allocated will be
#pragma omp parallel for if(NSIM*resolution.size()>= 1'000'000)
for (int i = 1; i <= NSIM; ++i)
{ // Calculate a path at each iteration. Make sure at most one thread is acess this critical point
for (int n = 0; n < resolution.size()-1; n++)
{
//It is my job to reduce the requirement and necessity of inter loop dependcies. Intead of starting at 1 we start at zero and we will reduce the need for inter loop depeendcies
resolution[n+1] = method->advance(resolution[n], method->RequestIncrement(n), method->k,rng ->generateRandomNumber());
}
//Store the result into the resolution array
//Process the path an calculate hay off at the end of each simulation
type->ProcessPath(resolution);
}
//Stop the stop watch
watch.StopStopWatch((*filewriter));
//Print the process
type->PostProcess();
//close the fiile after we are done using it
(*filewriter).close();
}
void WriteToDb(std::unique_ptr<sql::Connection> con,std::shared_ptr<sql::Statement> stmt)
{
con->setSchema("OptionPrices");
stmt = con->createStatement();
stmt->execute("DROP TABLE IF EXISTS OptionPrices");
stmt->execute("CREATE TABLE OptionPrices(sample_num INTEGER, price INTEGER(11,6)");
stmt->prepareStatement"INSERT INTO OptionPrices(?,?)");
stmt->setInt(1, sample_num);
stmt->setDouble(2, type->price);
stmt->execute();
}
//Method to write it a file and increment the sample number
void WriteToFile()
{
(*filewriter) << "Output # " << sample_num << " Price: " << type ->Price() << "\n";
sample_num++;
}
};
#endif // ! MEDIATOR | 37.408602 | 180 | 0.704513 | [
"vector"
] |
7c53bcd97d39cd34f91ecf10cf19d66db9f70ba7 | 351 | hpp | C++ | TGEngine/public/graphics/vulkan/VulkanGraphicsModule.hpp | MrTroble/TEngine | 9e364840b5db3b3d642c2921264e07b5148783f2 | [
"Apache-2.0"
] | 9 | 2018-03-22T16:01:54.000Z | 2022-01-12T02:27:10.000Z | TGEngine/public/graphics/vulkan/VulkanGraphicsModule.hpp | MrTroble/TEngine | 9e364840b5db3b3d642c2921264e07b5148783f2 | [
"Apache-2.0"
] | 20 | 2018-03-11T12:35:55.000Z | 2020-02-19T17:36:47.000Z | TGEngine/public/graphics/vulkan/VulkanGraphicsModule.hpp | MrTroble/TGEngine | 9e364840b5db3b3d642c2921264e07b5148783f2 | [
"Apache-2.0"
] | 6 | 2019-02-26T13:59:55.000Z | 2021-07-15T14:11:10.000Z | #pragma once
#include "../GameGraphicsModule.hpp"
#include <vector>
#include <array>
#include <string>
#ifndef APPLICATION_NAME
#define APPLICATION_NAME "unknown"
#endif
#ifndef APPLICATION_VERSION
#define APPLICATION_VERSION VK_MAKE_VERSION(1, 0, 0)
#endif
namespace tge::graphics {
APILayer *getNewVulkanModule();
} // namespace tge::graphics
| 16.714286 | 52 | 0.77208 | [
"vector"
] |
7c5625aa96a137821aa2c385fbc0b99dabae4359 | 3,953 | cc | C++ | tensorflow_text/core/kernels/sentencepiece/sentencepiece_detokenizer_kernel.cc | sun1638650145/text | c5c14d7739e4d3a0368f196e8a733e9654df6d20 | [
"Apache-2.0"
] | 2 | 2021-10-31T03:30:37.000Z | 2022-02-16T06:59:02.000Z | tensorflow_text/core/kernels/sentencepiece/sentencepiece_detokenizer_kernel.cc | sun1638650145/text | c5c14d7739e4d3a0368f196e8a733e9654df6d20 | [
"Apache-2.0"
] | null | null | null | tensorflow_text/core/kernels/sentencepiece/sentencepiece_detokenizer_kernel.cc | sun1638650145/text | c5c14d7739e4d3a0368f196e8a733e9654df6d20 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 TF.Text Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* Copyright 2020 The TensorFlow 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 "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow_text/core/kernels/sentencepiece/optimized_decoder.h"
#include "tensorflow_text/core/kernels/sentencepiece/sentencepiece_detokenizer.h"
namespace tensorflow {
namespace text {
template <typename Tsplits>
class TFSentencepieceDetokenizerOp : public tensorflow::OpKernel {
public:
explicit TFSentencepieceDetokenizerOp(tensorflow::OpKernelConstruction* ctx)
: OpKernel(ctx) {}
void Compute(tensorflow::OpKernelContext* ctx) override {
const auto& model_tensor = ctx->input(kSPModelIndex);
const auto& input_values_tensor = ctx->input(kInputIndex);
const auto input_values_flat =
input_values_tensor.flat<tensorflow::int32>();
const auto& input_splits_tensor = ctx->input(kInputSplits);
const auto input_splits_flat = input_splits_tensor.flat<Tsplits>();
const int num_of_sentences = input_splits_flat.size() - 1;
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(ctx,
ctx->allocate_output(0, {num_of_sentences}, &output_tensor));
auto output_flat = output_tensor->flat<tensorflow::tstring>();
std::vector<int> codes_for_split;
int input_offset = 0;
for (int i = 0; i < num_of_sentences; i++) {
// Create a vector of int32 from input according to spans.
const int split_size = input_splits_flat(i + 1) - input_splits_flat(i);
codes_for_split.clear();
codes_for_split.reserve(split_size);
for (int j = 0; j < split_size; ++j) {
codes_for_split.push_back(input_values_flat(input_offset++));
}
const auto res = sentencepiece::DecodeString(
codes_for_split, model_tensor.data());
OP_REQUIRES(
ctx,
res.type ==
sentencepiece::DecoderResultType::SUCCESS,
tensorflow::Status(tensorflow::error::INTERNAL,
"Sentencepiece conversion failed"));
output_flat(i) = res.decoded;
}
}
};
} // namespace text
} // namespace tensorflow
REGISTER_KERNEL_BUILDER(
Name("TFText>FastSentencepieceDetokenize")
.Device(tensorflow::DEVICE_CPU)
.TypeConstraint<tensorflow::int32>("Tsplits"),
tensorflow::text::TFSentencepieceDetokenizerOp<tensorflow::int32>);
REGISTER_KERNEL_BUILDER(
Name("TFText>FastSentencepieceDetokenize")
.Device(tensorflow::DEVICE_CPU)
.TypeConstraint<tensorflow::int64>("Tsplits"),
tensorflow::text::TFSentencepieceDetokenizerOp<tensorflow::int64>);
| 42.505376 | 81 | 0.714394 | [
"vector"
] |
7c6a3562995df299b75cd9ef400fa244195dfed9 | 581 | cpp | C++ | code/binary-tree-level-order-traversal-1.cpp | tqgy/interview | 1f51a70fd6b86ba15a900aed072a138524e84609 | [
"CC0-1.0"
] | 4 | 2018-04-09T12:57:46.000Z | 2019-07-30T00:25:40.000Z | code/binary-tree-level-order-traversal-1.cpp | tqgy/interview | 1f51a70fd6b86ba15a900aed072a138524e84609 | [
"CC0-1.0"
] | null | null | null | code/binary-tree-level-order-traversal-1.cpp | tqgy/interview | 1f51a70fd6b86ba15a900aed072a138524e84609 | [
"CC0-1.0"
] | 3 | 2018-11-19T03:11:15.000Z | 2021-07-28T11:48:30.000Z | // Binary Tree Level Order Traversal
// 递归版,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int>> result;
traverse(root, 1, result);
return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
if (!root) return;
if (level > result.size())
result.push_back(vector<int>());
result[level-1].push_back(root->val);
traverse(root->left, level+1, result);
traverse(root->right, level+1, result);
}
}; | 27.666667 | 78 | 0.598967 | [
"vector"
] |
7c6bf61d9a37c70a67eea9ece37366623615f452 | 4,117 | cpp | C++ | code/test/hybrid_map.cpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/test/hybrid_map.cpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/test/hybrid_map.cpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include "geodb/hybrid_map.hpp"
#include <boost/range/algorithm/equal.hpp>
using namespace geodb;
TEST_CASE("hybrid map lookup", "[hybrid-map]") {
hybrid_map<int, long, 512> map(2);
map.insert(10, 15);
{
auto pos = map.find(10);
REQUIRE(pos != map.end());
REQUIRE(pos->first == 10);
REQUIRE(pos->second == 15);
}
map.insert(30, 35);
map.insert(20, 25);
REQUIRE(map.is_external());
{
auto pos = map.find(20);
REQUIRE(pos != map.end());
REQUIRE(pos->first == 20);
REQUIRE(pos->second == 25);
}
{
auto pos = map.find(123);
REQUIRE(pos == map.end());
}
}
TEST_CASE("hybrid map migration", "[hybrid-map]") {
hybrid_map<int, long, 512> map(4);
map.insert(3, 4);
map.insert(1, 2);
map.insert(4, 5);
map.insert(2, 3);
REQUIRE(map.is_internal());
REQUIRE(map.limit() == 4);
REQUIRE(map.size() == 4);
{
std::vector<std::pair<const int, long>> expected{
{1, 2}, {2, 3}, {3, 4}, {4, 5}
};
REQUIRE(boost::equal(map, expected));
}
map.insert(-5, -4);
map.insert(10, 11);
REQUIRE(map.is_external());
REQUIRE(map.size() == 6);
{
std::vector<std::pair<const int, long>> expected{
{-5, -4}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {10, 11}
};
REQUIRE(boost::equal(map, expected));
}
}
TEST_CASE("hybrid map replace", "[hybrid-map]") {
hybrid_map<int, long, 512> map(2);
map.insert(1, 2);
map.insert(3, 4);
auto pos = map.find(1);
REQUIRE(pos != map.end());
map.replace(pos, 123);
pos = map.find(3);
REQUIRE(pos != map.end());
map.replace(pos, 456);
{
std::vector<std::pair<const int, long>> expected{
{1, 123}, {3, 456}
};
REQUIRE(boost::equal(map, expected));
}
map.insert(12, 13);
map.insert(10, 11);
pos = map.find(10);
REQUIRE(pos != map.end());
map.replace(pos, 121);
pos = map.find(12);
REQUIRE(pos != map.end());
map.replace(pos, 169);
{
std::vector<std::pair<const int, long>> expected{
{1, 123}, {3, 456}, {10, 121}, {12, 169}
};
REQUIRE(boost::equal(map, expected));
}
REQUIRE(map.size() == 4);
REQUIRE(map.is_external());
}
TEST_CASE("hybrid map insert collions", "[hybrid-map") {
hybrid_map<int, long, 512> map(2);
map.insert(1, 2);
map.insert(3, 4);
map.insert(3, 5);
map.insert(1, 7);
REQUIRE(map.size() == 2);
{
std::vector<std::pair<const int, long>> expected{
{1, 2}, {3, 4}
};
REQUIRE(boost::equal(map, expected));
}
map.insert(7, 8);
map.insert(-1, 11);
REQUIRE(map.is_external());
map.insert(7, 123);
map.insert(-1, 123213);
REQUIRE(map.size() == 4);
{
std::vector<std::pair<const int, long>> expected{
{-1, 11}, {1, 2}, {3, 4}, {7, 8}
};
REQUIRE(boost::equal(map, expected));
}
}
TEST_CASE("hybrid map larger dataset", "[hybrid-map]") {
hybrid_map<int, int, 4096> map(1024);
static constexpr int max = 64 * 1024;
for (int i = 0; i < max; ++i) {
map.insert(i, i * 2);
}
REQUIRE(map.is_external());
REQUIRE(map.size() == max);
int count = 0;
for (const auto& pair : map) {
if (pair.first != count) {
FAIL("expected key " << count << ", but found " << pair.first);
}
if (pair.second != count * 2) {
FAIL("expected value " << count * 2 << ", but found " << pair.second);
}
++count;
}
REQUIRE(count == max);
}
TEST_CASE("hybrid map custom location", "[hybrid-map]") {
temp_dir dir("asd");
hybrid_map<int, int, 4096> map(dir.path() / "123", 1024);
for (int i = 0; i < 4000; ++i) {
map.insert(i, i * 2);
}
REQUIRE(map.is_external());
REQUIRE(map.size() == 4000);
REQUIRE(fs::exists(dir.path() / "123"));
REQUIRE(fs::exists(dir.path() / "123" / "map.tree"));
}
| 22.745856 | 82 | 0.510323 | [
"vector"
] |
7c6da318463c6ee1b68ebc32387b1a2ee25796f4 | 2,594 | cc | C++ | src/XeSimEventData.cc | l-althueser/XeSim | 972ea62a35db7c80c6e4b3349987e31945651399 | [
"BSD-3-Clause"
] | null | null | null | src/XeSimEventData.cc | l-althueser/XeSim | 972ea62a35db7c80c6e4b3349987e31945651399 | [
"BSD-3-Clause"
] | null | null | null | src/XeSimEventData.cc | l-althueser/XeSim | 972ea62a35db7c80c6e4b3349987e31945651399 | [
"BSD-3-Clause"
] | null | null | null | #include "XeSimEventData.hh"
XeSimEventData::XeSimEventData() {
m_iEventId = 0;
m_iNbPhotoDetHits = 0;
m_pPhotoDetHits = new vector<int>;
m_pPhotoDetHitID = new vector<int>;
m_pPhotoDetHitTime = new vector<double>;
m_pPhotoDetHitEnergy = new vector<float>;
m_pPhotoDetHitTheta = new vector<float>;
m_pPhotoDetHitPhi = new vector<float>;
//m_pPhotoDetHitVolumeName = new vector<string>;
m_pPhotoDetHitX = new vector<float>;
m_pPhotoDetHitY = new vector<float>;
m_pPhotoDetHitZ = new vector<float>;
m_fTotalEnergyDeposited = 0.;
m_iNbSteps = 0;
m_pTrackId = new vector<int>;
m_pParentId = new vector<int>;
m_pParticleType = new vector<string>;
m_pParentType = new vector<string>;
m_pCreatorProcess = new vector<string>;
m_pDepositingProcess = new vector<string>;
m_pX = new vector<float>;
m_pY = new vector<float>;
m_pZ = new vector<float>;
m_pEnergyDeposited = new vector<float>;
m_pKineticEnergy = new vector<float>;
m_pTime = new vector<double>;
m_pPrimaryParticleType = new vector<string>;
m_fPrimaryEnergy = 0.;
m_fPrimaryX = 0.;
m_fPrimaryY = 0.;
m_fPrimaryZ = 0.;
m_fPrimaryVolume = "";
}
XeSimEventData::~XeSimEventData() {
delete m_pPhotoDetHits;
delete m_pPhotoDetHitID;
delete m_pPhotoDetHitTime;
delete m_pPhotoDetHitEnergy;
delete m_pPhotoDetHitTheta;
delete m_pPhotoDetHitPhi;
delete m_pPhotoDetHitX;
delete m_pPhotoDetHitY;
delete m_pPhotoDetHitZ;
delete m_pTrackId;
delete m_pParentId;
delete m_pParticleType;
delete m_pParentType;
delete m_pCreatorProcess;
delete m_pDepositingProcess;
delete m_pX;
delete m_pY;
delete m_pZ;
delete m_pEnergyDeposited;
delete m_pKineticEnergy;
delete m_pTime;
delete m_pPrimaryParticleType;
}
void XeSimEventData::Clear() {
m_iEventId = 0;
m_iNbPhotoDetHits = 0;
m_pPhotoDetHits->clear();
m_pPhotoDetHitID->clear();
m_pPhotoDetHitTime->clear();
m_pPhotoDetHitEnergy->clear();
m_pPhotoDetHitTheta->clear();
m_pPhotoDetHitPhi->clear();
m_pPhotoDetHitX->clear();
m_pPhotoDetHitY->clear();
m_pPhotoDetHitZ->clear();
m_fTotalEnergyDeposited = 0.0;
m_iNbSteps = 0;
m_pTrackId->clear();
m_pParentId->clear();
m_pParticleType->clear();
m_pParentType->clear();
m_pCreatorProcess->clear();
m_pDepositingProcess->clear();
m_pX->clear();
m_pY->clear();
m_pZ->clear();
m_pEnergyDeposited->clear();
m_pKineticEnergy->clear();
m_pTime->clear();
m_pPrimaryParticleType->clear();
m_fPrimaryEnergy = 0.;
m_fPrimaryX = 0.;
m_fPrimaryY = 0.;
m_fPrimaryZ = 0.;
m_fPrimaryVolume = "";
}
| 24.471698 | 49 | 0.728604 | [
"vector"
] |
7c7a1ed419e9d0b38031b86b4b988dc85afb4b1a | 3,297 | cpp | C++ | SDK/Extras/Rayshade/Sources/Rayshade/LibCommon/sampling.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 24 | 2019-10-28T07:01:48.000Z | 2022-03-04T16:10:39.000Z | SDK/Extras/Rayshade/Sources/Rayshade/LibCommon/sampling.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 8 | 2020-04-22T19:42:45.000Z | 2021-04-30T16:28:32.000Z | SDK/Extras/Rayshade/Sources/Rayshade/LibCommon/sampling.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 6 | 2019-09-22T14:44:15.000Z | 2021-04-01T20:04:29.000Z | /*
* sampling.c
*
* Copyright (C) 1989, 1991, Craig E. Kolb, Rod G. Bogart
* All rights reserved.
*
* This software may be freely copied, modified, and redistributed
* provided that this copyright notice is preserved on all copies.
*
* You may not distribute this software, in whole or in part, as part of
* any commercial product without the express consent of the authors.
*
* There is no warranty or other guarantee of fitness of this software
* for any purpose. It is provided solely "as is".
*
* $Id: sampling.cpp,v 1.1 2002-12-18 18:36:41 pepe Exp $
*
* $Log: not supported by cvs2svn $
* Revision 4.0 91/07/17 14:31:55 kolb
* Initial version.
*
*/
#include <stdlib.h>
#include "common.h"
#include "sampling.h"
#include "expr.h"
SampleInfo Sampling; /* sampling information */
/*
* Set sampling options.
*/
void
SamplingSetOptions(int n,int gaussian,Float width)
{
Float norm, u, v;
int x, y;
Sampling.sidesamples = n;
Sampling.totsamples = n*n;
Sampling.weight = 1. / (Float)Sampling.totsamples;
Sampling.spacing = 1. / (Float)Sampling.sidesamples;
Sampling.filterwidth = width;
Sampling.filterdelta = Sampling.filterwidth * Sampling.spacing;
Sampling.gaussian = gaussian;
Sampling.filter = (Float **)Malloc(Sampling.sidesamples
*sizeof(Float *));
for (y = 0; y < Sampling.sidesamples; y++) {
Sampling.filter[y] = (Float *)Malloc(Sampling.sidesamples *
sizeof(Float));
}
if (Sampling.gaussian) {
norm = 0.;
u = -0.5*Sampling.filterwidth +
0.5*Sampling.filterwidth*Sampling.spacing;
for (x = 0; x < Sampling.sidesamples; x++) {
v = -0.5*Sampling.filterwidth +
0.5*Sampling.filterwidth*Sampling.spacing;
for (y = 0; y < Sampling.sidesamples; y++) {
Sampling.filter[x][y] = exp(-0.5*(u*u+v*v));
norm += Sampling.filter[x][y];
v += Sampling.spacing *
Sampling.filterwidth;
}
u += Sampling.spacing * Sampling.filterwidth;
}
for (x = 0; x < Sampling.sidesamples; x++)
for (y = 0; y < Sampling.sidesamples; y++)
Sampling.filter[x][y] /= norm;
} else {
/* Box filter. Yawn. */
for (x = 0; x < Sampling.sidesamples; x++)
for (y = 0; y < Sampling.sidesamples; y++)
Sampling.filter[x][y] = Sampling.weight;
}
}
/*
* Set start time and duration of frame.
*/
void
SamplingSetTime(Float starttime,Float shutter,int frame)
{
Sampling.starttime = starttime;
Sampling.shutter = shutter;
Sampling.framenum = frame;
TimeSet(Sampling.starttime);
FrameSet((Float)frame);
}
/*
* Find a point on a unit circle that is separated from other random
* points by some jitter spacing.
*
* It should do the above, but the temporary hack below just finds a
* jittered point in a unit square.
*/
void
UnitCirclePoint(Vector *pnt,int sample)
{
/*
* This picks a random point on a -1 to 1 square. The jitter stuff
* is correct enough to avoid excessive noise. An extremely blurry
* bright highlight will look squarish, not roundish. Sorry.
*/
Float jit;
if (sample >= 0) {
jit = 2. * Sampling.spacing;
pnt->x = nrand()*jit - 1.0 +
(sample % Sampling.sidesamples) * jit;
pnt->y = nrand()*jit - 1.0 +
(sample / Sampling.sidesamples) * jit;
pnt->z = 0.0;
} else {
pnt->x = nrand() * 2.0 - 1.0;
pnt->y = nrand() * 2.0 - 1.0;
pnt->z = 0.0;
}
}
| 26.376 | 72 | 0.659994 | [
"vector"
] |
7c7af79865d6729fe1a5e9656945188d2253b8b5 | 3,894 | cc | C++ | src/exception.cc | Mons/tarantool | 35daf23419c88e12758d49c7c60d2cc5f8a00ad1 | [
"BSD-2-Clause"
] | null | null | null | src/exception.cc | Mons/tarantool | 35daf23419c88e12758d49c7c60d2cc5f8a00ad1 | [
"BSD-2-Clause"
] | null | null | null | src/exception.cc | Mons/tarantool | 35daf23419c88e12758d49c7c60d2cc5f8a00ad1 | [
"BSD-2-Clause"
] | null | null | null | /*
* 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 <COPYRIGHT HOLDER> ``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
* <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 "exception.h"
#include "say.h"
#include "fiber.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <typeinfo>
/** out_of_memory::size is zero-initialized by the linker. */
static OutOfMemory out_of_memory(__FILE__, __LINE__,
sizeof(OutOfMemory), "malloc", "exception");
void *
Exception::operator new(size_t size)
{
struct fiber *fiber = fiber();
if (fiber->exception && fiber->exception->size == 0)
fiber->exception = NULL;
if (fiber->exception) {
/* Explicitly call destructor for previous exception */
fiber->exception->~Exception();
if (fiber->exception->size >= size) {
/* Reuse memory allocated for exception */
return fiber->exception;
}
free(fiber->exception);
}
fiber->exception = (Exception *) malloc(size);
if (fiber->exception) {
fiber->exception->size = size;
return fiber->exception;
}
fiber->exception = &out_of_memory;
throw fiber->exception;
}
void
Exception::operator delete(void * /* ptr */)
{
/* Unsupported */
assert(false);
}
Exception::Exception(const char *file, unsigned line)
: m_file(file), m_line(line)
{
m_errmsg[0] = 0;
}
Exception::Exception(const Exception& e)
: Object(), m_file(e.m_file), m_line(e.m_line)
{
memcpy(m_errmsg, e.m_errmsg, sizeof(m_errmsg));
}
const char *
Exception::type() const
{
const char *name = typeid(*this).name();
/** A quick & dirty version of name demangle for class names */
char *res = NULL;
(void) strtol(name, &res, 10);
return res && strlen(res) ? res : name;
}
void
Exception::log() const
{
_say(S_ERROR, m_file, m_line, m_errmsg, "%s", type());
}
SystemError::SystemError(const char *file, unsigned line)
: Exception(file, line),
m_errno(errno)
{
/* nothing */
}
SystemError::SystemError(const char *file, unsigned line,
const char *format, ...)
:Exception(file, line),
m_errno(errno)
{
va_list ap;
va_start(ap, format);
init(format, ap);
va_end(ap);
}
void
SystemError::init(const char *format, ...)
{
va_list ap;
va_start(ap, format);
init(format, ap);
va_end(ap);
}
void
SystemError::init(const char *format, va_list ap)
{
vsnprintf(m_errmsg, sizeof(m_errmsg), format, ap);
}
void
SystemError::log() const
{
_say(S_SYSERROR, m_file, m_line, strerror(m_errno), "SystemError %s",
m_errmsg);
}
OutOfMemory::OutOfMemory(const char *file, unsigned line,
size_t amount, const char *allocator,
const char *object)
:SystemError(file, line)
{
m_errno = ENOMEM;
snprintf(m_errmsg, sizeof(m_errmsg),
"Failed to allocate %u bytes in %s for %s",
(unsigned) amount, allocator, object);
}
| 25.122581 | 70 | 0.705958 | [
"object"
] |
75aba085e1bca89f0458ee4ac8e02d13d30727e5 | 20,044 | cpp | C++ | Source/3rdParty/FrankLuna/d3dApp.cpp | trevortheblack/Physically_Based_Renderer | 18fb422c6d8c6de8ed3471c3558b0aa2b5ba4344 | [
"MIT"
] | 1 | 2020-09-16T19:42:06.000Z | 2020-09-16T19:42:06.000Z | Source/3rdParty/FrankLuna/d3dApp.cpp | trevordblack/Physically_Based_Renderer | 18fb422c6d8c6de8ed3471c3558b0aa2b5ba4344 | [
"MIT"
] | null | null | null | Source/3rdParty/FrankLuna/d3dApp.cpp | trevordblack/Physically_Based_Renderer | 18fb422c6d8c6de8ed3471c3558b0aa2b5ba4344 | [
"MIT"
] | null | null | null | //***************************************************************************************
// d3dApp.cpp by Frank Luna (C) 2015 All Rights Reserved.
//***************************************************************************************
#include "d3dApp.h"
#include <WindowsX.h>
using Microsoft::WRL::ComPtr;
using namespace std;
using namespace DirectX;
LRESULT CALLBACK
MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// Forward hwnd on because we can get messages (e.g., WM_CREATE)
// before CreateWindow returns, and thus before mhMainWnd is valid.
return D3DApp::GetApp()->MsgProc(hwnd, msg, wParam, lParam);
}
D3DApp* D3DApp::m_App = nullptr;
D3DApp* D3DApp::GetApp()
{
return m_App;
}
D3DApp::D3DApp(HINSTANCE hInstance)
: m_hAppInst(hInstance)
{
// Only one D3DApp can be constructed.
assert(m_App == nullptr);
m_App = this;
}
D3DApp::~D3DApp()
{
if(m_D3dDevice != nullptr)
FlushCommandQueue();
}
HINSTANCE D3DApp::AppInst()const
{
return m_hAppInst;
}
HWND D3DApp::MainWnd()const
{
return m_hMainWnd;
}
float D3DApp::AspectRatio()const
{
return static_cast<float>(m_clientWidth) / m_clientHeight;
}
bool D3DApp::Get4xMsaaState()const
{
return m_4xMsaaState;
}
void D3DApp::Set4xMsaaState(bool value)
{
if(m_4xMsaaState != value)
{
m_4xMsaaState = value;
// Recreate the swapchain and buffers with new multisample settings.
CreateSwapChain();
OnResize();
}
}
int D3DApp::Run()
{
MSG msg = {0};
m_Timer.Reset();
while(msg.message != WM_QUIT)
{
// If there are Window messages then process them.
if(PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
// Otherwise, do animation/game stuff.
else
{
m_Timer.Tick();
__int64 countsPerSec;
QueryPerformanceFrequency((LARGE_INTEGER*) &countsPerSec);
double secondsPerCount = 1.0 / (double) countsPerSec;
__int64 currTime;
QueryPerformanceCounter((LARGE_INTEGER*) &currTime);
double startFrameTime = currTime * secondsPerCount;
if( !m_appPaused )
{
CalculateFrameStats();
Update(m_Timer);
Draw(m_Timer);
if(m_FPSLockState != 0)
{ // sleep to fps count
__int64 newTime;
QueryPerformanceCounter((LARGE_INTEGER*) &newTime);
double endFrameTime = newTime * secondsPerCount;
double frameDuration = (endFrameTime - startFrameTime) * 1000.0f;
float frameMS = m_FPSLockState == 1 ? 16.667f : 8.333f;
Sleep(frameMS - frameDuration);
}
}
else
{
Sleep(100);
}
}
}
return (int)msg.wParam;
}
bool D3DApp::Initialize()
{
if(!InitMainWindow())
return false;
if(!InitDirect3D())
return false;
// Do the initial resize code.
OnResize();
return true;
}
void D3DApp::CreateRtvAndDsvDescriptorHeaps()
{
D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc;
rtvHeapDesc.NumDescriptors = SWAP_CHAIN_BUFFER_COUNT;
rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
rtvHeapDesc.NodeMask = 0;
ThrowIfFailed(m_D3dDevice->CreateDescriptorHeap(
&rtvHeapDesc, IID_PPV_ARGS(m_RtvHeap.GetAddressOf())));
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc;
dsvHeapDesc.NumDescriptors = 1;
dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
dsvHeapDesc.NodeMask = 0;
ThrowIfFailed(m_D3dDevice->CreateDescriptorHeap(
&dsvHeapDesc, IID_PPV_ARGS(m_DsvHeap.GetAddressOf())));
}
void D3DApp::OnResize()
{
assert(m_D3dDevice);
assert(m_SwapChain);
assert(m_DirectCmdListAlloc);
// Flush before changing any resources.
FlushCommandQueue();
ThrowIfFailed(m_CommandList->Reset(m_DirectCmdListAlloc.Get(), nullptr));
// Release the previous resources we will be recreating.
for (int i = 0; i < SWAP_CHAIN_BUFFER_COUNT; ++i)
m_SwapChainBuffer[i].Reset();
m_DepthStencilBuffer.Reset();
// Resize the swap chain.
ThrowIfFailed(m_SwapChain->ResizeBuffers(
SWAP_CHAIN_BUFFER_COUNT,
m_clientWidth, m_clientHeight,
m_BackBufferFormat,
DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH));
m_currBackBuffer = 0;
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle(m_RtvHeap->GetCPUDescriptorHandleForHeapStart());
for (UINT i = 0; i < SWAP_CHAIN_BUFFER_COUNT; i++)
{
ThrowIfFailed(m_SwapChain->GetBuffer(i, IID_PPV_ARGS(&m_SwapChainBuffer[i])));
m_D3dDevice->CreateRenderTargetView(m_SwapChainBuffer[i].Get(), nullptr, rtvHeapHandle);
rtvHeapHandle.Offset(1, m_RtvDescriptorSize);
}
// Create the depth/stencil buffer and view.
D3D12_RESOURCE_DESC depthStencilDesc;
depthStencilDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
depthStencilDesc.Alignment = 0;
depthStencilDesc.Width = m_clientWidth;
depthStencilDesc.Height = m_clientHeight;
depthStencilDesc.DepthOrArraySize = 1;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.Format = DXGI_FORMAT_R24G8_TYPELESS; // Typeless for SSAO
depthStencilDesc.SampleDesc.Count = m_4xMsaaState ? 4 : 1;
depthStencilDesc.SampleDesc.Quality = m_4xMsaaState ? (m_4xMsaaQuality - 1) : 0;
depthStencilDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
depthStencilDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
D3D12_CLEAR_VALUE optClear;
optClear.Format = m_DepthStencilFormat;
optClear.DepthStencil.Depth = 1.0f;
optClear.DepthStencil.Stencil = 0;
ThrowIfFailed(m_D3dDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&depthStencilDesc,
D3D12_RESOURCE_STATE_COMMON,
&optClear,
IID_PPV_ARGS(m_DepthStencilBuffer.GetAddressOf())));
// Create descriptor to mip level 0 of entire resource using the format of the resource.
D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc;
dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
dsvDesc.Format = m_DepthStencilFormat;
dsvDesc.Texture2D.MipSlice = 0;
m_D3dDevice->CreateDepthStencilView(m_DepthStencilBuffer.Get(), &dsvDesc, DepthStencilView());
// Transition the resource from its initial state to be used as a depth buffer.
m_CommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_DepthStencilBuffer.Get(),
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE));
// Execute the resize commands.
ThrowIfFailed(m_CommandList->Close());
ID3D12CommandList* cmdsLists[] = { m_CommandList.Get() };
m_CommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
// Wait until resize is complete.
FlushCommandQueue();
// Update the viewport transform to cover the client area.
m_ScreenViewport.TopLeftX = 0;
m_ScreenViewport.TopLeftY = 0;
m_ScreenViewport.Width = static_cast<float>(m_clientWidth);
m_ScreenViewport.Height = static_cast<float>(m_clientHeight);
m_ScreenViewport.MinDepth = 0.0f;
m_ScreenViewport.MaxDepth = 1.0f;
m_ScissorRect = { 0, 0, m_clientWidth, m_clientHeight };
}
LRESULT D3DApp::MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch( msg )
{
// WM_ACTIVATE is sent when the window is activated or deactivated.
// We pause the game when the window is deactivated and unpause it
// when it becomes active.
case WM_ACTIVATE:
if( LOWORD(wParam) == WA_INACTIVE )
{
m_appPaused = true;
m_Timer.Stop();
}
else
{
m_appPaused = false;
m_Timer.Start();
}
return 0;
// WM_SIZE is sent when the user resizes the window.
case WM_SIZE:
// Save the new client area dimensions.
m_clientWidth = LOWORD(lParam);
m_clientHeight = HIWORD(lParam);
if( m_D3dDevice )
{
if( wParam == SIZE_MINIMIZED )
{
m_appPaused = true;
m_minimized = true;
m_maximized = false;
}
else if( wParam == SIZE_MAXIMIZED )
{
m_appPaused = false;
m_minimized = false;
m_maximized = true;
OnResize();
}
else if( wParam == SIZE_RESTORED )
{
// Restoring from minimized state?
if( m_minimized )
{
m_appPaused = false;
m_minimized = false;
OnResize();
}
// Restoring from maximized state?
else if( m_maximized )
{
m_appPaused = false;
m_maximized = false;
OnResize();
}
else if( m_resizing )
{
// If user is dragging the resize bars, we do not resize
// the buffers here because as the user continuously
// drags the resize bars, a stream of WM_SIZE messages are
// sent to the window, and it would be pointless (and slow)
// to resize for each WM_SIZE message received from dragging
// the resize bars. So instead, we reset after the user is
// done resizing the window and releases the resize bars, which
// sends a WM_EXITSIZEMOVE message.
}
else // API call such as SetWindowPos or mSwapChain->SetFullscreenState.
{
OnResize();
}
}
}
return 0;
// WM_EXITSIZEMOVE is sent when the user grabs the resize bars.
case WM_ENTERSIZEMOVE:
m_appPaused = true;
m_resizing = true;
m_Timer.Stop();
return 0;
// WM_EXITSIZEMOVE is sent when the user releases the resize bars.
// Here we reset everything based on the new window dimensions.
case WM_EXITSIZEMOVE:
m_appPaused = false;
m_resizing = false;
m_Timer.Start();
OnResize();
return 0;
// WM_DESTROY is sent when the window is being destroyed.
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// The WM_MENUCHAR message is sent when a menu is active and the user presses
// a key that does not correspond to any mnemonic or accelerator key.
case WM_MENUCHAR:
// Don't beep when we alt-enter.
return MAKELRESULT(0, MNC_CLOSE);
// Catch this message so to prevent the window from becoming too small.
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 200;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 200;
return 0;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
OnMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
OnMouseUp(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MOUSEHWHEEL:
OnMouseWheel(wParam, GET_WHEEL_DELTA_WPARAM(wParam));
return 0;
case WM_MOUSEMOVE:
OnMouseMove(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_KEYUP:
if(wParam == VK_ESCAPE)
{
PostQuitMessage(0);
}
else if((int) wParam == VK_F1)
m_isWireframe = !m_isWireframe;
else if((int) wParam == VK_F2)
Set4xMsaaState(!m_4xMsaaState);
else if((int) wParam == VK_F3)
{
m_FPSLockState++;
m_FPSLockState = m_FPSLockState % 3;
}
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
bool D3DApp::InitMainWindow()
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = MainWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = m_hAppInst;
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = L"MainWnd";
if( !RegisterClass(&wc) )
{
MessageBox(0, L"RegisterClass Failed.", 0, 0);
return false;
}
// Compute window rectangle dimensions based on requested client area dimensions.
RECT R = { 0, 0, m_clientWidth, m_clientHeight };
AdjustWindowRect(&R, WS_OVERLAPPEDWINDOW, false);
int width = R.right - R.left;
int height = R.bottom - R.top;
m_hMainWnd = CreateWindow(L"MainWnd", m_MainWndCaption.c_str(),
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, m_hAppInst, 0);
if( !m_hMainWnd )
{
MessageBox(0, L"CreateWindow Failed.", 0, 0);
return false;
}
ShowWindow(m_hMainWnd, SW_SHOW);
UpdateWindow(m_hMainWnd);
return true;
}
bool D3DApp::InitDirect3D()
{
#if defined(DEBUG) || defined(_DEBUG)
// Enable the D3D12 debug layer.
{
ComPtr<ID3D12Debug> debugController;
ThrowIfFailed(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)));
debugController->EnableDebugLayer();
}
#endif
ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&m_DxgiFactory)));
// Try to create hardware device.
HRESULT hardwareResult = D3D12CreateDevice(
nullptr, // default adapter
D3D_FEATURE_LEVEL_11_0,
IID_PPV_ARGS(&m_D3dDevice));
// Fallback to WARP device.
if(FAILED(hardwareResult))
{
ComPtr<IDXGIAdapter> pWarpAdapter;
ThrowIfFailed(m_DxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&pWarpAdapter)));
ThrowIfFailed(D3D12CreateDevice(
pWarpAdapter.Get(),
D3D_FEATURE_LEVEL_11_0,
IID_PPV_ARGS(&m_D3dDevice)));
}
ThrowIfFailed(m_D3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE,
IID_PPV_ARGS(&m_Fence)));
m_RtvDescriptorSize = m_D3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
m_DsvDescriptorSize = m_D3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
m_CbvSrvUavDescriptorSize = m_D3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
// Check 4X MSAA quality support for our back buffer format.
// All Direct3D 11 capable devices support 4X MSAA for all render
// target formats, so we only need to check quality support.
D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msQualityLevels;
msQualityLevels.Format = m_BackBufferFormat;
msQualityLevels.SampleCount = 4;
msQualityLevels.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE;
msQualityLevels.NumQualityLevels = 0;
ThrowIfFailed(m_D3dDevice->CheckFeatureSupport(
D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS,
&msQualityLevels,
sizeof(msQualityLevels)));
m_4xMsaaQuality = msQualityLevels.NumQualityLevels;
assert(m_4xMsaaQuality > 0 && "Unexpected MSAA quality level.");
#ifdef _DEBUG
LogAdapters();
#endif
CreateCommandObjects();
CreateSwapChain();
CreateRtvAndDsvDescriptorHeaps();
return true;
}
void D3DApp::CreateCommandObjects()
{
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
ThrowIfFailed(m_D3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_CommandQueue)));
ThrowIfFailed(m_D3dDevice->CreateCommandAllocator(
D3D12_COMMAND_LIST_TYPE_DIRECT,
IID_PPV_ARGS(m_DirectCmdListAlloc.GetAddressOf())));
ThrowIfFailed(m_D3dDevice->CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE_DIRECT,
m_DirectCmdListAlloc.Get(), // Associated command allocator
nullptr, // Initial PipelineStateObject
IID_PPV_ARGS(m_CommandList.GetAddressOf())));
// Start off in a closed state. This is because the first time we refer
// to the command list we will Reset it, and it needs to be closed before
// calling Reset.
m_CommandList->Close();
}
void D3DApp::CreateSwapChain()
{
// Release the previous swapchain we will be recreating.
m_SwapChain.Reset();
DXGI_SWAP_CHAIN_DESC sd;
sd.BufferDesc.Width = m_clientWidth;
sd.BufferDesc.Height = m_clientHeight;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferDesc.Format = m_BackBufferFormat;
sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
sd.SampleDesc.Count = m_4xMsaaState ? 4 : 1;
sd.SampleDesc.Quality = m_4xMsaaState ? (m_4xMsaaQuality - 1) : 0;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = SWAP_CHAIN_BUFFER_COUNT;
sd.OutputWindow = m_hMainWnd;
sd.Windowed = true;
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
// Note: Swap chain uses queue to perform flush.
ThrowIfFailed(m_DxgiFactory->CreateSwapChain(
m_CommandQueue.Get(),
&sd,
m_SwapChain.GetAddressOf()));
}
void D3DApp::FlushCommandQueue()
{
// Advance the fence value to mark commands up to this fence point.
m_currentFence++;
// Add an instruction to the command queue to set a new fence point. Because we
// are on the GPU timeline, the new fence point won't be set until the GPU finishes
// processing all the commands prior to this Signal().
ThrowIfFailed(m_CommandQueue->Signal(m_Fence.Get(), m_currentFence));
// Wait until the GPU has completed commands up to this fence point.
if(m_Fence->GetCompletedValue() < m_currentFence)
{
HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS);
// Fire event when GPU hits current fence.
ThrowIfFailed(m_Fence->SetEventOnCompletion(m_currentFence, eventHandle));
// Wait until the GPU hits current fence event is fired.
WaitForSingleObject(eventHandle, INFINITE);
CloseHandle(eventHandle);
}
}
ID3D12Resource* D3DApp::CurrentBackBuffer()const
{
return m_SwapChainBuffer[m_currBackBuffer].Get();
}
D3D12_CPU_DESCRIPTOR_HANDLE D3DApp::CurrentBackBufferView()const
{
return CD3DX12_CPU_DESCRIPTOR_HANDLE(
m_RtvHeap->GetCPUDescriptorHandleForHeapStart(),
m_currBackBuffer,
m_RtvDescriptorSize);
}
D3D12_CPU_DESCRIPTOR_HANDLE D3DApp::DepthStencilView()const
{
return m_DsvHeap->GetCPUDescriptorHandleForHeapStart();
}
void D3DApp::CalculateFrameStats()
{
// Code computes the average frames per second, and also the
// average time it takes to render one frame. These stats
// are appended to the window caption bar.
static int frameCnt = 0;
static float timeElapsed = 0.0f;
frameCnt++;
// Compute averages over one second period.
if( (m_Timer.TotalTime() - timeElapsed) >= 1.0f )
{
float fps = (float)frameCnt; // fps = frameCnt / 1
float mspf = 1000.0f / fps;
wstring fpsStr = to_wstring(fps);
wstring mspfStr = to_wstring(mspf);
wstring windowText = m_MainWndCaption +
L" fps: " + fpsStr +
L" mspf: " + mspfStr;
SetWindowText(m_hMainWnd, windowText.c_str());
// Reset for next average.
frameCnt = 0;
timeElapsed += 1.0f;
}
}
void D3DApp::LogAdapters()
{
UINT i = 0;
IDXGIAdapter* adapter = nullptr;
std::vector<IDXGIAdapter*> adapterList;
while(m_DxgiFactory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND)
{
DXGI_ADAPTER_DESC desc;
adapter->GetDesc(&desc);
std::wstring text = L"***Adapter: ";
text += desc.Description;
text += L"\n";
OutputDebugString(text.c_str());
adapterList.push_back(adapter);
++i;
}
for(size_t i = 0; i < adapterList.size(); ++i)
{
LogAdapterOutputs(adapterList[i]);
ReleaseCom(adapterList[i]);
}
}
void D3DApp::LogAdapterOutputs(IDXGIAdapter* adapter)
{
UINT i = 0;
IDXGIOutput* output = nullptr;
while(adapter->EnumOutputs(i, &output) != DXGI_ERROR_NOT_FOUND)
{
DXGI_OUTPUT_DESC desc;
output->GetDesc(&desc);
std::wstring text = L"***Output: ";
text += desc.DeviceName;
text += L"\n";
OutputDebugString(text.c_str());
LogOutputDisplayModes(output, m_BackBufferFormat);
ReleaseCom(output);
++i;
}
}
void D3DApp::LogOutputDisplayModes(IDXGIOutput* output, DXGI_FORMAT format)
{
UINT count = 0;
UINT flags = 0;
// Call with nullptr to get list count.
output->GetDisplayModeList(format, flags, &count, nullptr);
std::vector<DXGI_MODE_DESC> modeList(count);
output->GetDisplayModeList(format, flags, &count, &modeList[0]);
for(auto& x : modeList)
{
UINT n = x.RefreshRate.Numerator;
UINT d = x.RefreshRate.Denominator;
std::wstring text =
L"Width = " + std::to_wstring(x.Width) + L" " +
L"Height = " + std::to_wstring(x.Height) + L" " +
L"Refresh = " + std::to_wstring(n) + L"/" + std::to_wstring(d) +
L"\n";
::OutputDebugString(text.c_str());
}
} | 28.512091 | 115 | 0.703702 | [
"render",
"vector",
"transform"
] |
75b1737468f8d2eb2727febc20e9ea909143dd58 | 8,105 | cpp | C++ | modules/vf_unfinished/graphics/vf_OuterGlowStyle.cpp | jrlanglois/VFLib | 95c662c435d6e6df1b2ebca4cdcdc3e84bc69e2b | [
"MIT"
] | 27 | 2015-05-07T02:10:39.000Z | 2021-06-22T14:52:50.000Z | modules/vf_unfinished/graphics/vf_OuterGlowStyle.cpp | jrlanglois/VFLib | 95c662c435d6e6df1b2ebca4cdcdc3e84bc69e2b | [
"MIT"
] | null | null | null | modules/vf_unfinished/graphics/vf_OuterGlowStyle.cpp | jrlanglois/VFLib | 95c662c435d6e6df1b2ebca4cdcdc3e84bc69e2b | [
"MIT"
] | 14 | 2015-09-12T12:00:22.000Z | 2022-03-08T22:24:24.000Z | /*============================================================================*/
/*
VFLib: https://github.com/vinniefalco/VFLib
Copyright (C) 2008 by Vinnie Falco <vinnie.falco@gmail.com>
This library contains portions of other open source products covered by
separate licenses. Please see the corresponding source files for specific
terms.
VFLib is provided under the terms of The MIT License (MIT):
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.
*/
/*============================================================================*/
/*
Experimental notes:
- The outer border of the glow has a fade, in addition to the alpha of the
interpolated gradient colour.
- For Precise, the fade starts at radius = 76% of the size, rounded up.
- Range, Contour, and Jitter do not affect alpha of the fade (Softer and Precise)
- Spread affects fade. Increasing spread reduces the amount of fade for Softer and Precise.
- There is no fade at 100% spread
- Contour accepts "Adjusted Distance" as x and outputs position in gradient as Y
- Previewing Range changes is very fast for "Softer" at 0% spread.
- Fade extends 1 pixel past "size". 99% Spread at 250px yields fade at 251 distance
- Range has no effect when the gradient is a single solid colour at both ends.
- Varying the Size when Spread = 0% is very fast. It gets slower as spread tends
towards 100%.
Data
Technique Size Spread Fade (px) (1-Spread)*Size Fade%
-----------------------------------------------------------------
Precise 250 0 60 250 24%
Precise 250 25 44 188 23%
Precise 250 50 30 125 24%
Precise 250 75 14 63 22%
Precise 250 100 0 0
Precise 100 0 24 100 24%
Precise 100 25 18 75 24%
Precise 100 50 12 50 24%
Precise 100 75 6 25 24%
Precise 100 100 0 0
Softer 250
*/
#if 0
struct StackBlur
{
int radius;
StackBlur (int radius_)
: radius (radius_)
{
jassert (radius > 0);
}
template <class Map>
void operator() (Map map)
{
int[] pix=img.pixels;
int w=map.getCols ();
int h=map.getRows ();
int wm=w-1;
int hm=h-1;
int wh=w*h;
int div=radius+radius+1;
int r[]=new int[wh];
int g[]=new int[wh];
int b[]=new int[wh];
int rsum,gsum,bsum,x,y,i,p,yp,yi,yw;
int vmin[] = new int[max(w,h)];
int divsum=(div+1)>>1;
divsum*=divsum;
int dv[]=new int[256*divsum];
for (i=0;i<256*divsum;i++){
dv[i]=(i/divsum);
}
yw=yi=0;
int[][] stack=new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1=radius+1;
int routsum,goutsum,boutsum;
int rinsum,ginsum,binsum;
for (y=0;y<h;y++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
for(i=-radius;i<=radius;i++){
p=pix[yi+min(wm,max(i,0))];
sir=stack[i+radius];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rbs=r1-abs(i);
rsum+=sir[0]*rbs;
gsum+=sir[1]*rbs;
bsum+=sir[2]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
}
stackpointer=radius;
for (x=0;x<w;x++){
r[yi]=dv[rsum];
g[yi]=dv[gsum];
b[yi]=dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(y==0){
vmin[x]=min(x+radius+1,wm);
}
p=pix[yw+vmin[x]];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[(stackpointer)%div];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi++;
}
yw+=w;
}
for (x=0;x<w;x++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
yp=-radius*w;
for(i=-radius;i<=radius;i++){
yi=max(0,yp)+x;
sir=stack[i+radius];
sir[0]=r[yi];
sir[1]=g[yi];
sir[2]=b[yi];
rbs=r1-abs(i);
rsum+=r[yi]*rbs;
gsum+=g[yi]*rbs;
bsum+=b[yi]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
if(i<hm){
yp+=w;
}
}
yi=x;
stackpointer=radius;
for (y=0;y<h;y++){
pix[yi]=0xff000000 | (dv[rsum]<<16) | (dv[gsum]<<8) | dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(x==0){
vmin[y]=min(y+r1,hm)*w;
}
p=x+vmin[y];
sir[0]=r[p];
sir[1]=g[p];
sir[2]=b[p];
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[stackpointer];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi+=w;
}
}
}
};
#endif
void OuterGlowStyle::operator() (Pixels destPixels, Pixels maskPixels)
{
if (!active)
return;
SharedTable <Colour> table = colours.createLookupTable ();
if (precise)
{
#if 1
DistanceTransform::Meijster::calculateAntiAliasedLoop (
RenderPixelAntiAliased (
destPixels,
opacity,
spread,
size,
table),
GetMask (maskPixels),
maskPixels.getWidth (),
maskPixels.getHeight (),
DistanceTransform::Meijster::EuclideanMetric ());
#else
DistanceTransform::Meijster::calculate (
RenderPixel (
destPixels,
opacity,
spread,
size,
table),
DistanceTransform::BlackTest (maskPixels),
maskPixels.getWidth (),
maskPixels.getHeight (),
DistanceTransform::Meijster::ChessMetric ());
#endif
}
else
{
// "Softer"
// code here
}
}
| 25.170807 | 91 | 0.527205 | [
"solid"
] |
75b9ab4104655d434bd6c333faba1f0975b28265 | 1,025 | hpp | C++ | src/include/duckdb/planner/operator/logical_table_function.hpp | rainmaple/duckdb | d3df77ba6740b8b089bddbfef77e2b969245b5cf | [
"MIT"
] | null | null | null | src/include/duckdb/planner/operator/logical_table_function.hpp | rainmaple/duckdb | d3df77ba6740b8b089bddbfef77e2b969245b5cf | [
"MIT"
] | null | null | null | src/include/duckdb/planner/operator/logical_table_function.hpp | rainmaple/duckdb | d3df77ba6740b8b089bddbfef77e2b969245b5cf | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/planner/operator/logical_table_function.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/planner/logical_operator.hpp"
namespace duckdb {
//! LogicalTableFunction represents a call to a table-producing function
class LogicalTableFunction : public LogicalOperator {
public:
LogicalTableFunction(TableFunctionCatalogEntry *function, idx_t table_index,
vector<unique_ptr<Expression>> parameters)
: LogicalOperator(LogicalOperatorType::TABLE_FUNCTION), function(function), table_index(table_index) {
expressions = move(parameters);
}
//! The function
TableFunctionCatalogEntry *function;
//! The table index of the table-producing function
idx_t table_index;
public:
vector<ColumnBinding> GetColumnBindings() override;
protected:
void ResolveTypes() override;
};
} // namespace duckdb
| 28.472222 | 107 | 0.626341 | [
"vector"
] |
75bb24211d2eaa4c1c088c3e09f3f6f3a6d97e40 | 4,102 | cpp | C++ | benchmarks/halide/wrapper_convolution_layer.cpp | akmaru/tiramisu | 8ca4173547b6d12cff10575ef0dc48cf93f7f414 | [
"MIT"
] | 23 | 2017-05-03T13:06:34.000Z | 2018-06-07T07:12:43.000Z | benchmarks/halide/wrapper_convolution_layer.cpp | akmaru/tiramisu | 8ca4173547b6d12cff10575ef0dc48cf93f7f414 | [
"MIT"
] | 2 | 2017-04-25T08:59:09.000Z | 2017-05-11T16:41:55.000Z | benchmarks/halide/wrapper_convolution_layer.cpp | akmaru/tiramisu | 8ca4173547b6d12cff10575ef0dc48cf93f7f414 | [
"MIT"
] | 5 | 2017-02-16T14:26:40.000Z | 2018-05-30T16:49:27.000Z | #include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <fstream>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include "configure.h"
#include "wrapper_convolution_layer.h"
#include <tiramisu/utils.h>
using namespace std;
int main(int, char**)
{
Halide::Buffer<float> input(N+K, N+K, FIn, BATCH_SIZE);
Halide::Buffer<float> filter(K+1, K+1, FIn, FOut);
Halide::Buffer<float> bias(FOut);
Halide::Buffer<float> convolution_layer_halide(N, N, FOut, BATCH_SIZE);
Halide::Buffer<float> convolution_layer_tiramisu_buff(N, N, FOut, BATCH_SIZE);
Halide::Buffer<int> parameters(5);
std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;
/****************************************** Initialize Buffers *********************************************/
srand (1);
for (int n = 0; n < BATCH_SIZE; ++n)
for (int z = 0; z < FIn; ++z)
for (int y = 0; y < N+K; ++y)
for (int x = 0; x < N+K; ++x)
//input(x, y, z, n) = rand()%10;
input(x, y, z, n) = 5;
for (int z = 0; z < FOut; ++z)
bias(z) = 1;
for (int y = 0; y < K+1; ++y)
for (int x = 0; x < K+1; ++x)
for (int z = 0; z < FIn; ++z)
for (int q = 0; q < FOut; ++q)
filter(x, y, z, q) = 1;
std::cout << "\t\tBuffers initialized" << std::endl;
/****************************************** Halide Part ********************************************************/
for (int i=0; i<NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
convolution_layer_ref(input.raw_buffer(),filter.raw_buffer(), bias.raw_buffer(),convolution_layer_halide.raw_buffer());
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration = end1 - start1;
duration_vector_1.push_back(duration);
}
std::cout << "\t\tHalide convolution_layer duration" << ": " << median(duration_vector_1)/1000 << "; " << std::endl;
// Write the result
/* std::ofstream halide_resultfile;
halide_resultfile.open ("/home/dina/tiramisuOut/convolution_layer_halide_result.txt");
for (int n = 0; n < BATCH_SIZE; ++n)
for (int z = 0; z < FOut; ++z)
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x) halide_resultfile <<convolution_layer_halide(x, y, z, n);
halide_resultfile.close();*/
/****************************************** Tiramisu Part ********************************************************/
// Initialize parameters[]
parameters(0) = N;
parameters(1) = K;
parameters(2) = FIn;
parameters(3) = FOut;
parameters(4) = BATCH_SIZE;
for (int i=0; i<NB_TESTS; i++)
{
// srand (1);
auto start1 = std::chrono::high_resolution_clock::now();
convolution_layer_tiramisu(parameters.raw_buffer(), input.raw_buffer(), filter.raw_buffer(), bias.raw_buffer(),convolution_layer_tiramisu_buff.raw_buffer());
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration = end1 - start1;
duration_vector_2.push_back(duration);
}
std::cout << "\t\tTiramisu convolution_layer duration" << ": " << median(duration_vector_2)/1000 << "; " << std::endl;
// Write the result
/*std::ofstream resultfile;
resultfile.open ("/home/dina/tiramisuOut/convolution_layer_tiramisu_result.txt");
for (int n = 0; n < BATCH_SIZE; ++n)
for (int z = 0; z < FOut; ++z)
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x) resultfile <<convolution_layer_tiramisu_buff(x, y, z, n);
resultfile.close();*/
/*************************** Comparaison of the result of Halide & Tiramisu******************************/
compare_4D_buffers("comparing Tiramisu output with Halide output", convolution_layer_tiramisu_buff, convolution_layer_halide, 5);
return 0;
} | 37.290909 | 165 | 0.556314 | [
"vector"
] |
75bbf0bd26a2666d31add6fd8d9072755a0b14ea | 1,101 | hpp | C++ | shadow/algorithm/detect_faster_rcnn.hpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 20 | 2017-07-04T11:22:47.000Z | 2022-01-16T03:58:32.000Z | shadow/algorithm/detect_faster_rcnn.hpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 2 | 2017-12-03T13:07:39.000Z | 2021-01-13T11:11:52.000Z | shadow/algorithm/detect_faster_rcnn.hpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 10 | 2017-09-30T05:06:30.000Z | 2020-11-13T05:43:44.000Z | #ifndef SHADOW_ALGORITHM_DETECT_FASTER_RCNN_HPP_
#define SHADOW_ALGORITHM_DETECT_FASTER_RCNN_HPP_
#include "method.hpp"
#include "core/network.hpp"
namespace Shadow {
class DetectFasterRCNN final : public Method {
public:
DetectFasterRCNN() = default;
void Setup(const std::string& model_file) override;
void Predict(const cv::Mat& im_mat, const RectF& roi, VecBoxF* boxes,
std::vector<VecPointF>* Gpoints) override;
private:
void Process(const VecFloat& in_data, const VecInt& in_shape,
const VecFloat& im_info, float height, float width,
VecBoxF* boxes);
void CalculateScales(float height, float width, float max_side,
const VecFloat& min_side, VecFloat* scales);
Network net_;
VecFloat in_data_, min_side_, scales_, im_info_;
VecInt in_shape_;
std::string in_str_, im_info_str_, rois_str_, bbox_pred_str_, cls_prob_str_;
int num_classes_;
float max_side_, threshold_, nms_threshold_;
bool is_bgr_, class_agnostic_;
};
} // namespace Shadow
#endif // SHADOW_ALGORITHM_DETECT_FASTER_RCNN_HPP_
| 28.230769 | 78 | 0.730245 | [
"vector"
] |
75bd7af4480b7981dad16806c7c53c4ffd1d877e | 3,514 | cc | C++ | src/JMessage.cc | omnetpp/jsimplemodule | 3c969af136fcea8063afdaf6e7913d4257b39474 | [
"BSD-2-Clause"
] | null | null | null | src/JMessage.cc | omnetpp/jsimplemodule | 3c969af136fcea8063afdaf6e7913d4257b39474 | [
"BSD-2-Clause"
] | null | null | null | src/JMessage.cc | omnetpp/jsimplemodule | 3c969af136fcea8063afdaf6e7913d4257b39474 | [
"BSD-2-Clause"
] | null | null | null | //
// This file is part of the OMNeT++ JSimpleModule project.
//
// Copyright 2009-2021 OpenSim Ltd and Andras Varga.
//
// 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 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 "JMessage.h"
#include "JUtil.h"
using namespace omnetpp;
using namespace JUtil; // for jenv, checkExceptions(), findMethod(), etc
//#define DEBUGPRINTF printf
#define DEBUGPRINTF (void)
JMessage::JMessage(const char *name, int kind, int) : cMessage(name, kind)
{
javaPeer = 0;
cloneMethod = 0;
}
JMessage::JMessage(const JMessage& msg)
{
javaPeer = 0;
cloneMethod = 0;
operator=(msg);
}
JMessage::~JMessage()
{
if (jenv && javaPeer)
jenv->DeleteGlobalRef(javaPeer);
}
std::string JMessage::info() const
{
// return the first line of toString()
std::string str = toString();
const char *s = str.c_str();
const char *p = strchr(s, '\n');
if (p)
str.erase(str.begin()+(p-s), str.end());
return str;
}
std::string JMessage::detailedInfo() const
{
return toString();
}
JMessage& JMessage::operator=(const JMessage& msg)
{
cMessage::operator=(msg);
if (!jenv)
return *this;
if (javaPeer)
jenv->DeleteGlobalRef(javaPeer);
javaPeer = 0;
cloneMethod = 0;
if (msg.javaPeer)
{
// must clone() the other Java object
javaPeer = msg.javaPeer; // then we'll clone it
cloneMethod = msg.cloneMethod;
if (!cloneMethod)
{
jclass clazz = jenv->GetObjectClass(javaPeer);
cloneMethod = jenv->GetMethodID(clazz, "clone", "()Ljava/lang/Object;");
const_cast<JMessage&>(msg).cloneMethod = cloneMethod;
checkExceptions();
}
javaPeer = jenv->CallObjectMethod(javaPeer, cloneMethod);
checkExceptions();
javaPeer = jenv->NewGlobalRef(javaPeer);
checkExceptions();
}
JObjectAccess::setObject(javaPeer);
return *this;
}
void JMessage::swigSetJavaPeer(jobject msgObject)
{
ASSERT(javaPeer==0);
javaPeer = jenv->NewGlobalRef(msgObject);
JObjectAccess::setObject(javaPeer);
}
jobject JMessage::swigJavaPeerOf(cMessage *object)
{
JMessage *msg = dynamic_cast<JMessage *>(object);
return msg ? msg->swigJavaPeer() : 0;
}
| 29.041322 | 84 | 0.683552 | [
"object"
] |
75c1131768632ad80b050c3d12b3f8ac2b055b45 | 47,038 | hh | C++ | core/include/ceps_ast.hh | cepsdev/ceps | badd1ac7582034f9b4f000ee93828bd584cf858b | [
"MIT"
] | 3 | 2018-09-11T11:40:24.000Z | 2021-07-02T10:24:36.000Z | core/include/ceps_ast.hh | cepsdev/ceps | badd1ac7582034f9b4f000ee93828bd584cf858b | [
"MIT"
] | null | null | null | core/include/ceps_ast.hh | cepsdev/ceps | badd1ac7582034f9b4f000ee93828bd584cf858b | [
"MIT"
] | null | null | null | /*
Copyright 2021 Tomas Prerovsky (cepsdev@hotmail.com).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef CEPS_AST_H_
#define CEPS_AST_H_
#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <initializer_list>
#include <stdexcept>
#include <valarray>
#include <array>
#include <memory>
#include "global_defs.hh"
#include "typefunc.hh" //We need some type functions used later on.
#include "si_units.hh"
#include "si_literals.hh"
#include "include_gen/ceps.tab.hh"
#include <cctype>
namespace ceps {
namespace ast {
/**
* The following list defines all Node-kinds currently available. The type of a node is "computed" at compile time.
* One of the ingredients every node type depends upon is it's kind.
*/
enum class Ast_node_kind {
root,
structdef,
identifier,
string_literal,
int_literal,
float_literal,
expr,
si_unit_or_derived,
binary_operator, /*8*/
stmts,
stmt,
valdef,
lambda,
formal_parameters,
formal_parameter,
lambda_body,
rawmap, /*16*/
atoms,
vector,
unary_operator,
scope,
func_call,
call_parameters,
long_literal,
unsigned_long_literal,
kind_def,
kind,
symbol, /*27*/
loop,
for_loop_head,
nodeset, /* 30*/
nodeset_path_expr,
template_definition,
template_id,
ifelse,
ret,
byte_array,
error,
undef,
none,
macro_definition,/*40*/
algorithm_definition,
label,
let,
undefined = 4999,
user_defined = 5000
};
}
}
/**
* @brief Specialization of the generic getNth_type template for YaMDL AST nodes.
* Inductive case.
*/
template<int N,ceps::ast::Ast_node_kind K,template <ceps::ast::Ast_node_kind,typename...> class T,typename... Ts>
struct getNth_type<N, T <K,Ts...> >
{
using Base = getNth_type<N, Ts... >;
using type = typename Base::type;
};
/**
* @brief Specialization of the generich getNth_type template for YaMDL AST nodes.
* Base case.
*/
template<ceps::ast::Ast_node_kind K,template <ceps::ast::Ast_node_kind,typename...> class T,typename... Ts>
struct getNth_type<0, T <K,Ts...> >
{
using Base = getNth_type<0, Ts... >;
using type = typename Base::type;
};
namespace ceps {
namespace ast {
/**
* @brief Maps AST kinds to human readable descriptions.
*/
extern const char * ast_node_kind_to_text[];
/**
* @brief Maps AST kinds to text.
*/
inline const char * c_str(Ast_node_kind k);
/**
* The template 'type_map_is_leaf' and its specializations define a mapping AST KIND -> BOOL which is computed
* at compile time. It enables us to perform some compile time optimizations, e.g. leafs need no storage for child nodes.
*/
/**
* Default is a non leaf
*/
template<Ast_node_kind what>
struct type_map_is_leaf
{
static const bool yes = false;
};
/**
* Macro which saves us from typeing to much.
*/
#define AST_NODE_IS_LEAF(kind_name) template<>\
struct type_map_is_leaf<Ast_node_kind::kind_name>\
{\
static const bool yes = true;\
};
#define AST_NODE_IS_NON_LEAF(kind_name)
/**
* Strings,integers and floats have no child nodes.
*/
AST_NODE_IS_LEAF(string_literal)
AST_NODE_IS_LEAF(int_literal)
AST_NODE_IS_LEAF(float_literal)
AST_NODE_IS_LEAF(long_literal)
AST_NODE_IS_LEAF(unsigned_long_literal)
inline bool is_leaf(Ast_node_kind kind){
return kind == Ast_node_kind::string_literal ||
kind == Ast_node_kind::int_literal ||
kind == Ast_node_kind::float_literal ||
kind == Ast_node_kind::long_literal ||
kind == Ast_node_kind::unsigned_long_literal;
}
/**
* All AST nodes are derived from Nodebase
*/
class Nodebase;
std::ostream& operator << (std::ostream & out, Nodebase const & n);
class Nodebase
{
public:
static const int PRETTY_PRINT_INDENT_STEP_SIZE = 2 ;//Indendation used for pretty printing
static const int iword_index; //Used by the pretty_print ostream manipulator, see chapter 15.6 in [Josuttis: "The C++ Standard Library, 2nd edition"]
Ast_node_kind kind_;// we store the kind of a node at runtime
/**
* @brief returns reference to kind of node.
*/
Ast_node_kind & kind()
{
return kind_;
}
/**
* @brief returns kind of node
*/
Ast_node_kind kind() const
{
return kind_;
}
/**
* @brief A node has a unique representation as S-Expression (see https://en.wikipedia.org/wiki/S-expression). The
* virtual members print/print_content compute the unique S-Expression for a node.
*
*/
virtual void print(std::ostream& out,bool pretty_print = false,int indent = 0) const;
virtual void print_content(std::ostream& ,bool pretty_print = false,int indent = 0) const
{
}
virtual void print_value(std::ostream& ) const
{
}
virtual ~Nodebase() {}
virtual Nodebase* clone() = 0;
virtual void copy_children(std::vector<Nodebase*> &)
{
}
/**
* ostream manipulator turning pretty printing on.
* see chapter 15.6 in [Josuttis: "The C++ Standard Library, 2nd edition"]
*/
static std::ostream& pretty_print(std::ostream& os);
/**
* ostream manipulator turning pretty printing off.
* see chapter 15.6 in [Josuttis: "The C++ Standard Library, 2nd edition"]
*/
static std::ostream& pretty_print_off(std::ostream& os);
protected:
/**
* Helper function printing n >= 0 blanks
*/
void print_ws(std::ostream& out,int n) const;
};
using Nodebase_ptr = Nodebase*;
/*
* A node which is a leaf, inherits from Leafbase.
*/
struct Leafbase
{
Leafbase(Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
{
}
};
/**
* Nonleafs have child nodes.
*/
struct Nonleafbase
{
using Container_t = std::vector<Nodebase_ptr>;
std::vector<Nodebase_ptr> children_;
bool owns_children_{true};
bool& owns_children () {return owns_children_ ;}
bool owns_children () const {return owns_children_ ;}
Nonleafbase(Nonleafbase const & rhs)
{
for(auto p : rhs.children_)
{
children_.push_back(p->clone());
}
}
std::vector<Nodebase_ptr> & children()
{
return children_;
}
std::vector<Nodebase_ptr> const & children() const
{
return children_;
}
Nodebase_ptr left()
{
return children_[0];
}
Nodebase_ptr right()
{
return children_[1];
}
Nodebase_ptr first()
{
return children_[0];
}
Nodebase_ptr second()
{
return children_[1];
}
bool empty() const
{
return children_.size() == 0;
}
Nonleafbase(Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
{
if (child1 == nullptr) return;
children().push_back(child1);
if (child2 == nullptr) return;
children().push_back(child2);
if (child3 == nullptr) return;
children().push_back(child3);
}
virtual void copy_children(std::vector<Nodebase*> & v)
{
for(auto e: children()) if (e) v.push_back(e->clone());
}
virtual ~Nonleafbase()
{
if (!owns_children ()) return;
//for (auto e: children()) if (e) delete e;
children().clear();
}
};
template <Ast_node_kind what,typename... members>
struct ast_node;
template <Ast_node_kind what>
struct ast_node<what> : public select_type< type_map_is_leaf<what>::yes ,Leafbase,Nonleafbase >::type, public
Nodebase
{
using First_base = typename select_type< type_map_is_leaf<what>::yes ,Leafbase,Nonleafbase >::type;
using This_type = ast_node<what>;
ast_node(Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr):First_base{child1,child2,child3}
{
kind() = what;
}
/*
* @brief: Prints content if leaf
*/
void print_content_helper(std::ostream& out, True_type const &,bool pretty_print,int indent) const
{}
/**
* @brief: Prints content if non leaf
*/
void print_content_helper(std::ostream& out, False_type const &,bool pretty_print,int indent) const
{
int pre_indent = indent;
indent+=PRETTY_PRINT_INDENT_STEP_SIZE;
for(auto p : Nonleafbase::children())
{
if (!p) continue;
if(pretty_print)
{
out << "\n";
Nodebase::print_ws(out,indent);
}
p->print(out,pretty_print,indent);
}
indent = pre_indent;
if(pretty_print){out << "\n";Nodebase::print_ws(out,indent);}
}
void print_content(std::ostream& out,bool pretty_print,int indent) const override
{
print_content_helper(out,typename Select_bool_type<type_map_is_leaf<what>::yes >::type{},pretty_print,indent);
}
virtual void print_value(std::ostream& out) const override
{
}
Nodebase* clone() override;
/*{
owns_children () = true;
return new This_type(*this);
}*/
};
template <Ast_node_kind what,typename T,typename... rest>
struct ast_node<what,T,rest...>: public ast_node<what,rest...>
{
T x;
using Base = ast_node<what,rest...>;
using This_type = ast_node<what,T,rest...>;
ast_node(T val_1,rest... args,Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
: Base{args...,child1,child2,child3},x{val_1}
{
}
void print_content(std::ostream& out,bool pretty_print,int indent) const override
{
out << x<< " "; Base::print_content(out,pretty_print,indent);
}
virtual void print_value(std::ostream& out) const override
{
out << x<< "";Base::print_value(out);
}
Nodebase* clone()
{
return new This_type(*this);
}
};
template <Ast_node_kind what,typename... rest>
struct ast_node<what,std::vector<Nodebase_ptr>,rest...>: public ast_node<what,rest...>
{
using T = std::vector<Nodebase_ptr>;
T x;
using Base = ast_node<what,rest...>;
using This_type = ast_node<what,std::vector<Nodebase_ptr>,rest...>;
ast_node(T val_1,rest... args,Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
: Base(args...,child1,child2,child3),x(val_1)
{
}
void print_content(std::ostream& out,bool pretty_print,int indent) const override
{
Base::print_content(out,pretty_print,indent);
}
virtual void print_value(std::ostream& out) const override
{
Base::print_value(out);
}
Nodebase* clone()
{
return new This_type(*this);
}
};
template <Ast_node_kind what,typename... rest>
struct ast_node<what,std::string,rest...>: public ast_node<what,rest...>
{
using T = std::string;
T x;
using Base = ast_node<what,rest...>;
using This_type = ast_node<what,std::string,rest...>;
ast_node(T val_1,rest... args,Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
: Base(args...,child1,child2,child3),x(val_1)
{
}
void print_content(std::ostream& out,bool pretty_print,int indent) const override
{
out << "\""<< x<< "\" "; Base::print_content(out,pretty_print,indent);
}
virtual void print_value(std::ostream& out) const override
{
out <<"\""<< x<< "\"";Base::print_value(out);
}
virtual ~ast_node<what,std::string,rest...>() {}
Nodebase* clone() override;
};
template<>
ceps::ast::Nodebase* ast_node<Ast_node_kind::structdef,std::string>::clone();
template<>
ceps::ast::Nodebase* ast_node<Ast_node_kind::symbol,std::string,std::string>::clone();
template<>
ceps::ast::Nodebase* ast_node<Ast_node_kind::string_literal,std::string>::clone();
template <Ast_node_kind what,typename... rest>
struct ast_node<what,std::vector<std::string>,rest...>: public ast_node<what,rest...>
{
using T = std::vector<std::string>;
T x;
using Base = ast_node<what,rest...>;
using This_type = ast_node<what,std::vector<std::string>,rest...>;
ast_node(T val_1,rest... args,Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
: Base(args...,child1,child2,child3),x(val_1)
{
}
void print_content(std::ostream& out,bool pretty_print,int indent) const override
{
for(auto const & s : x)
{
out << "\""<< s <<"\" ";
}
Base::print_content(out,pretty_print,indent);
}
virtual void print_value(std::ostream& out) const override
{
for(auto const & s : x)
{
out << "\""<< s <<"\" ";
}
Base::print_value(out);
}
virtual ~ast_node<what,std::vector<std::string>,rest...>() {}
Nodebase* clone() override
{
return new This_type(*this);
}
};
template <Ast_node_kind what,typename... rest>
struct ast_node<what,std::vector<unsigned char>,rest...>: public ast_node<what,rest...>
{
using T = std::vector<unsigned char>;
T x;
using Base = ast_node<what,rest...>;
using This_type = ast_node<what,std::vector<unsigned char>,rest...>;
ast_node(T val_1,rest... args,Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
: Base(args...,child1,child2,child3),x(val_1)
{
}
void print_content(std::ostream& out,bool pretty_print,int indent) const override
{
for(auto const & s : x)
{
out << " "<< (int)s;
}
Base::print_content(out,pretty_print,indent);
}
virtual void print_value(std::ostream& out) const override
{
for(auto const & s : x)
{
out << " "<< (int)s;
}
Base::print_value(out);
}
Nodebase* clone() override
{
return new This_type(*this);
}
virtual ~ast_node<what,std::vector<unsigned char>,rest...>(){
}
};
template <typename... rest>
struct ast_node<Ast_node_kind::binary_operator,int,rest...>: public ast_node<Ast_node_kind::binary_operator,rest...>
{
using T = int;
T x;
using Base = ast_node<Ast_node_kind::binary_operator,rest...>;
using This_type = ast_node<Ast_node_kind::binary_operator,int,rest...>;
ast_node(T val_1,rest... args,Nodebase_ptr child1=nullptr,Nodebase_ptr child2=nullptr,Nodebase_ptr child3=nullptr)
: Base(args...,child1,child2,child3),x(val_1)
{
}
void print_content(std::ostream& out,bool pretty_print,int indent) const override
{
if (x < ceps::Cepsparser::token::DOTDOT)
out << (char)x << " ";
else if (x == ceps::Cepsparser::token::DOTDOT)
out << ".." << " ";
else if (x == ceps::Cepsparser::token::REL_OP_EQ)
out << "==" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_NEQ)
out << "!=" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_GT)
out << ">" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_LT)
out << "<" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_GT_EQ)
out << ">=" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_LT_EQ)
out << "<=" << " ";
Base::print_content(out,pretty_print,indent);
}
virtual void print_value(std::ostream& out) const override
{
if (x < ceps::Cepsparser::token::DOTDOT)
out << (char)x << " ";
else if (x == ceps::Cepsparser::token::DOTDOT)
out << ".." << "";
else if (x == ceps::Cepsparser::token::REL_OP_EQ)
out << "==" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_NEQ)
out << "!=" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_GT)
out << ">" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_LT)
out << "<" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_GT_EQ)
out << ">=" << " ";
else if (x == ceps::Cepsparser::token::REL_OP_LT_EQ)
out << "<=" << " ";
Base::print_value(out);
}
Nodebase* clone() override;
virtual ~ast_node<Ast_node_kind::binary_operator,int,rest...>(){
}
};
template<int N,Ast_node_kind what,typename... Ts>
struct peel_off_base;
template<Ast_node_kind what,typename T,typename... Ts>
struct peel_off_base<0,what,T,Ts...>
{
using type = ast_node<what,T,Ts...>;
};
template<int N,Ast_node_kind what,typename T,typename... Ts>
struct peel_off_base<N,what,T,Ts...>:public peel_off_base<N-1,what,Ts...>
{
};
template<int N,Ast_node_kind what,typename... Ts>
typename getNth_type<N,Ts...>::type& get( ast_node<what,Ts...> & n)
{
return static_cast< typename peel_off_base<N,what,Ts...>::type&>(n).x;
}
inline Nonleafbase* nlf_ptr(Nodebase* n)
{
return dynamic_cast<Nonleafbase*>(n);
}
struct Unit_rep
{
using sc_t = signed char;
sc_t m;
sc_t kg;
sc_t s;
sc_t ampere;
sc_t kelvin;
sc_t mol;
sc_t candela;
Unit_rep()
:m{},kg{},s{},ampere{},kelvin{},mol{},candela{}
{}
Unit_rep(sc_t p1,sc_t p2,sc_t p3, sc_t p4,sc_t p5,sc_t p6,sc_t p7)
:m{p1},kg{p2},s{p3},ampere{p4},kelvin{p5},mol{p6},candela{p7}
{}
};
inline bool operator == (Unit_rep const & u1, Unit_rep const & u2)
{
return (u1.m == u2.m) &&
(u1.kg == u2.kg) &&
(u1.s == u2.s) &&
(u1.ampere == u2.ampere) &&
(u1.kelvin == u2.kelvin) &&
(u1.mol == u2.mol) &&
(u1.candela == u2.candela);
}
inline bool operator != (Unit_rep const & u1, Unit_rep const & u2)
{
return ! (u1 == u2);
}
inline Unit_rep operator + (Unit_rep const & u1, Unit_rep & u2)
{
return Unit_rep{(Unit_rep::sc_t)(u1.m + u2.m),
(Unit_rep::sc_t)(u1.kg + u2.kg),
(Unit_rep::sc_t)(u1.s + u2.s),
(Unit_rep::sc_t)(u1.ampere + u2.ampere),
(Unit_rep::sc_t)(u1.kelvin + u2.kelvin),
(Unit_rep::sc_t)(u1.mol + u2.mol),
(Unit_rep::sc_t)(u1.candela + u2.candela)
};
}
inline Unit_rep operator - (Unit_rep const & u1, Unit_rep & u2)
{
return Unit_rep{(Unit_rep::sc_t)(u1.m - u2.m),
(Unit_rep::sc_t)(u1.kg - u2.kg),
(Unit_rep::sc_t)(u1.s - u2.s),
(Unit_rep::sc_t)(u1.ampere - u2.ampere),
(Unit_rep::sc_t)(u1.kelvin - u2.kelvin),
(Unit_rep::sc_t)(u1.mol - u2.mol),
(Unit_rep::sc_t)(u1.candela - u2.candela)
};
}
inline std::ostream& operator << (std::ostream& os, Unit_rep const & u)
{
if (u.m != 0) os << "m^" << (int)u.m;
if (u.kg != 0) os << "kg^" << (int)u.kg;
if (u.s != 0) os << "s^" << (int)u.s;
if (u.ampere != 0) os << "A^" << (int)u.ampere;
if (u.kelvin != 0) os << "K^" << (int)u.kelvin;
if (u.mol != 0) os << "mol^" << (int)u.mol;
if (u.candela != 0) os << "cd^" << (int)u.candela;
return os;
}
inline Unit_rep operator * (int scalar, Unit_rep & u)
{
return Unit_rep{(Unit_rep::sc_t)(scalar*u.m),
(Unit_rep::sc_t)(scalar*u.kg),
(Unit_rep::sc_t)(scalar*u.s),
(Unit_rep::sc_t)(scalar*u.ampere),
(Unit_rep::sc_t)(scalar*u.kelvin),
(Unit_rep::sc_t)(scalar*u.mol),
(Unit_rep::sc_t)(scalar*u.candela)
};
}
inline Unit_rep all_one_unit()
{
return Unit_rep{1,1,1,1,1,1,1};
}
inline Unit_rep all_zero_unit()
{
return Unit_rep{0,0,0,0,0,0,0};
}
inline Unit_rep m_unit()
{
return Unit_rep{1,0,0,0,0,0,0};
}
inline Unit_rep kg_unit()
{
return Unit_rep{0,1,0,0,0,0,0};
}
inline Unit_rep s_unit()
{
return Unit_rep{0,0,1,0,0,0,0};
}
inline Unit_rep ampere_unit()
{
return Unit_rep{0,0,0,1,0,0,0};
}
inline Unit_rep kelvin_unit()
{
return Unit_rep{0,0,0,0,1,0,0};
}
inline Unit_rep mol_unit()
{
return Unit_rep{0,0,0,0,0,1,0};
}
inline Unit_rep candela_unit()
{
return Unit_rep{0,0,0,0,0,0,1};
}
typedef ast_node<Ast_node_kind::root> Root;
typedef ast_node<Ast_node_kind::expr> Expression;
typedef ast_node<Ast_node_kind::binary_operator,int,std::string> Binary_operator;
typedef ast_node<Ast_node_kind::unary_operator,char> Unary_operator;
typedef ast_node<Ast_node_kind::structdef,std::string> Struct;
typedef ast_node<Ast_node_kind::identifier,std::string> Identifier;
typedef ast_node<Ast_node_kind::string_literal,std::string> String;
typedef ast_node<Ast_node_kind::int_literal,
int, //value
Unit_rep // SI Unit
> Int;
typedef ast_node<Ast_node_kind::long_literal,
long, //value
Unit_rep // SI Unit
> Int64;
typedef ast_node<Ast_node_kind::unsigned_long_literal,
unsigned long, //value
Unit_rep // SI Unit
> Uint64;
typedef ast_node<Ast_node_kind::float_literal,
double, //value
Unit_rep // SI Unit
> Double;
//typedef ast_node<Ast_node_kind::si_unit_or_derived,short int> SI_unit;
typedef ast_node<Ast_node_kind::stmts> Stmts;
typedef ast_node<Ast_node_kind::stmt> Stmt;
typedef ast_node<Ast_node_kind::valdef,std::string> Valdef;
typedef ast_node<Ast_node_kind::kind,std::string> Kind;
typedef ast_node<Ast_node_kind::kind_def,std::string> Kinddef;
typedef ast_node<Ast_node_kind::symbol,std::string,std::string> Symbol;
typedef ast_node<Ast_node_kind::lambda> Lambda;
typedef ast_node<Ast_node_kind::lambda_body> Lambda_body;
typedef ast_node<Ast_node_kind::formal_parameters> Formal_parameters;
typedef ast_node<Ast_node_kind::formal_parameter> Formal_parameter;
typedef ast_node<Ast_node_kind::rawmap> Rawmap;
typedef ast_node<Ast_node_kind::atoms> Atoms;
typedef ast_node<Ast_node_kind::vector> Vector;
typedef ast_node<Ast_node_kind::scope> Scope;
typedef ast_node<Ast_node_kind::func_call> Func_call;
typedef ast_node<Ast_node_kind::call_parameters> Call_parameters;
typedef ast_node<Ast_node_kind::loop> Loop;
typedef ast_node<Ast_node_kind::for_loop_head> Loop_head;
typedef ast_node<Ast_node_kind::nodeset,std::string> Ast_nodeset;
typedef ast_node<Ast_node_kind::nodeset_path_expr> Nodeset_path_expr;
typedef ast_node<Ast_node_kind::template_definition,std::string,std::vector<std::string>> Template_defintion;
typedef ast_node<Ast_node_kind::template_id,std::string> Template_id;
typedef ast_node<Ast_node_kind::ifelse> Ifelse;
typedef ast_node<Ast_node_kind::ret> Return;
typedef ast_node<Ast_node_kind::byte_array, std::vector<unsigned char> > Byte_array;
typedef ast_node<Ast_node_kind::macro_definition,std::string /*name*/, void* /*symbol entry*/, std::vector<Nodebase_ptr> /* attributes */> Macrodef;
typedef ast_node<Ast_node_kind::label,std::string /*name*/, std::vector<Nodebase_ptr> /* attributes */, void* /*symbol entry*/> Label;
typedef ast_node<Ast_node_kind::let,std::string /*lhs*/> Let;
typedef ast_node<Ast_node_kind::error, std::string , int , void* > Error;
typedef ast_node<Ast_node_kind::undef> Undefined;
typedef ast_node<Ast_node_kind::none> None;
typedef ast_node<Ast_node_kind::user_defined,int,void*> User_defined;
TYPE_ALIAS(Root_ptr , Root*)
TYPE_ALIAS(Expression_ptr , Expression*)
TYPE_ALIAS(Binary_operator_ptr , Binary_operator*)
TYPE_ALIAS(Unary_operator_ptr , Unary_operator*)
TYPE_ALIAS(Struct_ptr , Struct*)
TYPE_ALIAS(Identifier_ptr , Identifier*)
TYPE_ALIAS(String_ptr , String*)
TYPE_ALIAS(Int_ptr , Int*)
TYPE_ALIAS(Double_ptr , Double*)
//TYPE_ALIAS(SI_ptr , SI*)
TYPE_ALIAS(Stmts_ptr , Stmts*)
TYPE_ALIAS(Stmt_ptr , Stmt*)
TYPE_ALIAS(Valdef_ptr , Valdef*)
TYPE_ALIAS(Lambda_ptr , Lambda*)
TYPE_ALIAS(Lambda_body_ptr , Lambda_body*)
TYPE_ALIAS(Formal_parameters_ptr , Formal_parameters*)
TYPE_ALIAS(Formal_parameter_ptr , Formal_parameter*)
TYPE_ALIAS(Rawmap_ptr , Rawmap*)
TYPE_ALIAS(Atoms_ptr , Atoms*)
TYPE_ALIAS(Scope_ptr , Scope*)
TYPE_ALIAS(Vector_ptr , Vector*)
TYPE_ALIAS(Loop_ptr , Loop*)
TYPE_ALIAS(Loop_head_ptr , Loop_head*)
TYPE_ALIAS(Ast_nodeset_ptr, Ast_nodeset*)
TYPE_ALIAS(Nodeset_path_expr_ptr, Nodeset_path_expr*)
typedef ast_node<Ast_node_kind::error, std::string , int , void* > Error;
///////////// helper functions
Nodebase_ptr get_first_child(Nodebase_ptr node);
///////////// is_* predicates
template<ceps::ast::Ast_node_kind k> bool is(Nodebase_ptr p) {
return p->kind() == k;
}
inline bool is_binop(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::binary_operator;
}
inline bool is_a_symbol(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::symbol;
}
inline bool is_a_nodeset(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::nodeset;
}
inline bool is_an_identifier(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::identifier;
}
inline bool is_a_struct(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::structdef;
}
inline bool is_a_byte_array(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::byte_array;
}
inline bool is_an_error(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::error;
}
inline bool is_a_string(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::string_literal;
}
inline bool is_a_let(Nodebase_ptr p)
{
return p->kind() == ceps::ast::Ast_node_kind::let;
}
/////////// as_* casts
inline Call_parameters& as_call_params_ref(Nodebase_ptr p){
return *static_cast<Call_parameters*>(p);
}
inline Let* as_let_ptr(Nodebase_ptr p)
{
return static_cast<Let*>(p);
}
inline Let& as_let_ref(Nodebase_ptr p)
{
return *static_cast<Let*>(p);
}
inline Unary_operator* as_unary_op_ptr(Nodebase_ptr p)
{
return static_cast<Unary_operator*>(p);
}
inline Unary_operator& as_unary_op_ref(Nodebase_ptr p)
{
return *static_cast<Unary_operator*>(p);
}
inline Label* as_label_ptr(Nodebase_ptr p)
{
return static_cast<Label*>(p);
}
inline Label& as_label_ref(Nodebase_ptr p)
{
return *static_cast<Label*>(p);
}
inline Valdef* as_valdef_ptr(Nodebase_ptr p)
{
return static_cast<Valdef*>(p);
}
inline Valdef& as_valdef_ref(Nodebase_ptr p)
{
return *static_cast<Valdef*>(p);
}
inline Macrodef* as_macrodef_ptr(Nodebase_ptr p)
{
return static_cast<Macrodef*>(p);
}
inline Macrodef & as_macrodef_ref(Nodebase_ptr p)
{
return *as_macrodef_ptr(p);
}
inline Nodebase_ptr func_call_target(Func_call& fc){
return fc.children()[0];
}
inline Func_call& as_func_call_ref(Nodebase_ptr p){
return *dynamic_cast<ceps::ast::Func_call*>(p);
}
inline Error* as_error_ptr(Nodebase_ptr p)
{
return dynamic_cast<Error*>(p);
}
inline Error & as_error_ref(Nodebase_ptr p)
{
return *as_error_ptr(p);
}
inline Byte_array* as_byte_array_ptr(Nodebase_ptr p)
{
return dynamic_cast<Byte_array*>(p);
}
inline Byte_array & as_byte_array_ref(Nodebase_ptr p)
{
return *as_byte_array_ptr(p);
}
inline Return* as_return_ptr(Nodebase_ptr p)
{
return dynamic_cast<Return*>(p);
}
inline Return & as_return_ref(Nodebase_ptr p)
{
return *as_return_ptr(p);
}
inline User_defined* as_user_defined_ptr(Nodebase_ptr p)
{
return static_cast<User_defined*>(p);
}
inline User_defined & as_user_defined_ref(Nodebase_ptr p)
{
return *as_user_defined_ptr(p);
}
inline Ifelse* as_ifelse_ptr(Nodebase_ptr p)
{
return static_cast<Ifelse*>(p);
}
inline Ifelse & as_ifelse_ref(Nodebase_ptr p)
{
return *as_ifelse_ptr(p);
}
inline Double_ptr as_double_ptr(Nodebase_ptr p)
{
return static_cast<Double_ptr>(p);
}
inline Double & as_double_ref(Nodebase_ptr p)
{
return *as_double_ptr(p);
}
inline Int_ptr as_int_ptr(Nodebase_ptr p)
{
return static_cast<Int_ptr>(p);
}
inline Int & as_int_ref(Nodebase_ptr p)
{
return *as_int_ptr(p);
}
inline Int64* as_int64_ptr(Nodebase_ptr p)
{
return static_cast<Int64*>(p);
}
inline Int64 & as_int64_ref(Nodebase_ptr p)
{
return *as_int64_ptr(p);
}
inline Uint64* as_uint64_ptr(Nodebase_ptr p)
{
return static_cast<Uint64*>(p);
}
inline Uint64 & as_uint64_ref(Nodebase_ptr p)
{
return *as_uint64_ptr(p);
}
inline Identifier & as_id_ref(Nodebase_ptr p)
{
return *static_cast<Identifier_ptr>(p);
}
inline Identifier const & as_id_ref_const(Nodebase_ptr p)
{
return *dynamic_cast<Identifier const *>(p);
}
inline Template_defintion* as_template_definition_ptr(Nodebase_ptr p)
{
return dynamic_cast<Template_defintion*>(p);
}
inline Template_defintion& as_template_definition_ref(Nodebase_ptr p)
{
return *as_template_definition_ptr(p);
}
inline Template_id* as_template_id_ptr(Nodebase_ptr p)
{
return dynamic_cast<Template_id*>(p);
}
inline Template_id& as_template_id_ref(Nodebase_ptr p)
{
return *as_template_id_ptr(p);
}
inline Loop_ptr as_loop_ptr(Nodebase_ptr p)
{
return dynamic_cast<Loop_ptr>(p);
}
inline Loop & as_loop_ref(Nodebase_ptr p)
{
return *as_loop_ptr(p);
}
inline Binary_operator* as_binop_ptr(Nodebase_ptr p)
{
return static_cast<Binary_operator*>(p);
}
inline Binary_operator & as_binop_ref(Nodebase_ptr p)
{
return *as_binop_ptr(p);
}
inline Struct_ptr as_struct_ptr(Nodebase_ptr p)
{
return static_cast<Struct_ptr>(p);
}
inline Struct & as_struct_ref(Nodebase_ptr p)
{
return *as_struct_ptr(p);
}
inline String_ptr as_string_ptr(Nodebase_ptr p)
{
return dynamic_cast<String_ptr>(p);
}
inline String & as_string_ref(Nodebase_ptr p)
{
return *as_string_ptr(p);
}
inline Stmts_ptr as_stmts_ptr(Nodebase_ptr p)
{
return dynamic_cast<Stmts_ptr>(p);
}
inline Stmts & as_stmts_ref(Nodebase_ptr p)
{
return *as_stmts_ptr(p);
}
inline Rawmap_ptr as_rawmap_ptr(Nodebase_ptr p)
{
return dynamic_cast<Rawmap_ptr>(p);
}
inline Rawmap & as_rawmap_ref(Nodebase_ptr p)
{
return *as_rawmap_ptr(p);
}
inline Atoms_ptr as_atoms_ptr(Nodebase_ptr p)
{
return dynamic_cast<Atoms_ptr>(p);
}
inline Symbol & as_symbol_ref(Nodebase_ptr p)
{
return *static_cast<Symbol*>(p);
}
inline Symbol* as_symbol_ptr(Nodebase_ptr p)
{
return static_cast<Symbol*>(p);
}
inline Loop_head & as_loop_head_ref(Nodebase_ptr p)
{
return *static_cast<Loop_head_ptr>(p);
}
inline Loop_head const & as_loop_head_ref_const(Nodebase_ptr p)
{
return *static_cast<Loop_head_ptr>(p);
}
inline Loop_head_ptr as_loop_head_ptr(Nodebase_ptr p)
{
return static_cast<Loop_head_ptr>(p);
}
inline Ast_nodeset & as_ast_nodeset_ref(Nodebase_ptr p)
{
return *static_cast<Ast_nodeset_ptr>(p);
}
inline Ast_nodeset_ptr as_ast_nodeset_ptr(Nodebase_ptr p)
{
return static_cast<Ast_nodeset_ptr>(p);
}
inline Scope & as_scope_ref(Nodebase_ptr p)
{
return *static_cast<Scope*>(p);
}
inline Scope* as_scope_ptr(Nodebase_ptr p)
{
return dynamic_cast<Scope*>(p);
}
inline Kinddef & as_kinddef_ref(Nodebase_ptr p)
{
return *static_cast<Kinddef*>(p);
}
inline Kinddef * as_kinddef_ptr(Nodebase_ptr p)
{
return static_cast<Kinddef*>(p);
}
inline Ast_nodeset_ptr create_ast_nodeset(std::string index_operator_argument,std::vector<Nodebase_ptr> const & children)
{
Ast_nodeset_ptr t = new ast_node<Ast_node_kind::nodeset,std::string>(index_operator_argument, nullptr, nullptr, nullptr);
t->children().insert(t->children().end(),children.begin(),children.end());
return t;
}
inline Nodeset_path_expr & as_ast_nodeset_path_expr_ref(Nodebase_ptr p)
{
return *dynamic_cast<Nodeset_path_expr_ptr>(p);
}
inline Nodeset_path_expr_ptr as_nodeset_path_expr_ptr(Nodebase_ptr p)
{
return dynamic_cast<Nodeset_path_expr_ptr>(p);
}
Nodebase_ptr box(int j);
Nodebase_ptr box(unsigned int j);
Nodebase_ptr box(long j);
Nodebase_ptr box(unsigned long j);
Nodebase_ptr box(double d);
Nodebase_ptr box(std::string const & s);
template<typename T, size_t N>
Nodebase_ptr box(std::array<T,N> const & v)
{
Vector_ptr vv = new Vector;
for(int i = 0; i < N; ++i)
{
vv->children().push_back(box(v[i]));
}
return vv;
}
template<typename T> auto get0th(T & x) -> typename getNth_type<0,T>::type
{
return get<0>(x);
}
// Binary Operator
inline getNth_type<0, Binary_operator >::type & op(Binary_operator& x)
{
return get<0>(x);
}
inline getNth_type<1, Binary_operator >::type & op_str(Binary_operator& x)
{
return get<1>(x);
}
inline std::string op_val(Binary_operator& x){
if (op_str(x).size()) return op_str(x);
if(op(x) == '.') return ".";
if(op(x) == '+') return "+";
if(op(x) == '-') return "-";
if(op(x) == '*') return "*";
if(op(x) == '/') return "/";
if(op(x) == '%') return "%";
if(op(x) == '!') return "!";
if(op(x) == '~') return "~";
if(op(x) == '=') return "=";
if(op(x) == '>') return ">";
if(op(x) == '<') return "<";
if(op(x) == '&') return "&&";
if(op(x) == '|') return "||";
if(op(x) == ',') return ",";
if(op(x) == ':') return ":";
if(op(x) == ';') return ";";
if(op(x) == ceps::Cepsparser::token::DOTDOT) return "..";
if(op(x) == ceps::Cepsparser::token::NOT) return "!";
if(op(x) == ceps::Cepsparser::token::REL_OP_EQ) return "==";
if(op(x) == ceps::Cepsparser::token::REL_OP_GT) return ">";
if(op(x) == ceps::Cepsparser::token::REL_OP_LT) return "<";
if(op(x) == ceps::Cepsparser::token::REL_OP_GT_EQ) return ">=";
if(op(x) == ceps::Cepsparser::token::REL_OP_LT_EQ) return "<=";
if(op(x) == ceps::Cepsparser::token::REL_OP_NEQ) return "!=";
if ((unsigned int)op(x) <= 255){
std::string t;
t.push_back(op(x));
return t;
}
return "";
}
// Unary Operator
inline getNth_type<0, Unary_operator >::type & op(Unary_operator& x)
{
return get<0>(x);
}
// User Defined
inline getNth_type<0, User_defined >::type & id(User_defined& x)
{
return get<0>(x);
}
// Label
inline getNth_type<0, Label >::type & name(Label& x)
{
return get<0>(x);
}
inline getNth_type<1, Label >::type & attributes(Label& x)
{
return get<1>(x);
}
inline getNth_type<2, Label >::type & tag_data(Label& x)
{
return get<2>(x);
}
// Struct
inline getNth_type<0, Struct >::type & name(Struct& x)
{
return get<0>(x);
}
// Identifier
inline getNth_type<0, Identifier>::type & name(Identifier& x)
{
return get<0>(x);
}
// String
inline getNth_type<0, String >::type & value(String& x)
{
return get<0>(x);
}
// Double
inline getNth_type<0, Double >::type & value(Double& x)
{
return get<0>(x);
}
inline getNth_type<0, Double>::type & neg(Double& x)
{
return get<0>(x) = - get<0>(x);
}
inline getNth_type<1, Double>::type & unit(Double& x)
{
return get<1>(x);
}
// Int
inline getNth_type<0, Int>::type & value(Int& x)
{
return get<0>(x);
}
inline getNth_type<0, Int>::type & neg(Int& x)
{
return get<0>(x) = - get<0>(x);
}
inline getNth_type<1, Int>::type & unit(Int& x)
{
return get<1>(x);
}
// Int64
inline getNth_type<0, Int64>::type & value(Int64& x)
{
return get<0>(x);
}
inline getNth_type<0, Int64>::type & neg(Int64& x)
{
return get<0>(x) = - get<0>(x);
}
inline getNth_type<1, Int64>::type & unit(Int64& x)
{
return get<1>(x);
}
// Uint64
inline getNth_type<0, Uint64>::type & value(Uint64& x)
{
return get<0>(x);
}
inline getNth_type<0, Uint64>::type & neg(Uint64& x)
{
return get<0>(x) = - get<0>(x);
}
inline getNth_type<1, Uint64>::type & unit(Uint64& x)
{
return get<1>(x);
}
// Valdef
inline getNth_type<0, Valdef>::type & name(Valdef& x)
{
return get<0>(x);
}
// Symbol
inline getNth_type<0, Symbol >::type & name(Symbol & x)
{
return get<0>(x);
}
inline getNth_type<1, Symbol >::type & kind(Symbol & x)
{
return get<1>(x);
}
// Ast_nodeset
inline getNth_type<0, Ast_nodeset >::type & apply_idx_op_operand(Ast_nodeset& x)
{
return get<0>(x);
}
// Byte_array
inline getNth_type<0, Byte_array >::type & bytes(Byte_array& x)
{
return get<0>(x);
}
// Error
inline getNth_type<0, Error >::type & err_msg(Error& x)
{
return get<0>(x);
}
inline getNth_type<1, Error >::type & err_code(Error& x)
{
return get<1>(x);
}
inline getNth_type<2, Error >::type & err_tag_data(Error& x)
{
return get<2>(x);
}
// Macrodef
inline getNth_type<0, Macrodef >::type & name(Macrodef& x)
{
return get<0>(x);
}
inline getNth_type<1, Macrodef >::type & symbol_table_info(Macrodef& x)
{
return get<1>(x);
}
inline getNth_type<2, Macrodef >::type & attributes(Macrodef& x)
{
return get<2>(x);
}
// Let
inline getNth_type<0, Let >::type & name(Let& x)
{
return get<0>(x);
}
// Kinddef
inline getNth_type<0, Kinddef >::type & kind(Kinddef& x)
{
return get<0>(x);
}
inline std::pair<bool,int> is_int(Nodebase_ptr p)
{
auto i = 0;
auto r = p->kind() == ceps::ast::Ast_node_kind::int_literal;
if (r) i = ceps::ast::value(ceps::ast::as_int_ref(p));
return std::make_pair(r,i);
}
void flatten_func_args(ceps::ast::Nodebase_ptr r, std::vector<ceps::ast::Nodebase_ptr>& v);
using node_t = Nodebase_ptr;
using node_symbol_t = ceps::ast::Symbol*;
using node_vec_t = std::vector<node_t>;
using node_root_t = ceps::ast::Root*;
using node_stmts_t = ceps::ast::Stmts*;
using node_stmt_t = ceps::ast::Stmt*;
using node_struct_t = ceps::ast::Struct*;
using node_scope_t = ceps::ast::Scope*;
using node_callparameters_t = ceps::ast::Call_parameters*;
using node_nodeset_t = ceps::ast::Ast_nodeset*;
using nodes_t = std::vector<ceps::ast::node_t>;
using function_target_t = std::string;
node_symbol_t mk_symbol(std::string name, std::string kind);
node_t mk_string(std::string v);
node_t get_node_by_path(std::vector<std::string> v, std::vector<node_t> const & ns);
node_root_t mk_root();
node_stmts_t mk_stmts();
node_stmt_t mk_stmt();
node_struct_t mk_struct(std::string);
node_scope_t mk_scope();
node_callparameters_t mk_callparameters();
node_nodeset_t mk_nodeset ();
node_t mk_ifelse(node_t,node_t,node_t);
node_t mk_none();
void gc(node_t);
std::vector<node_t> extract_functioncall_arguments_from_param_block(ceps::ast::Call_parameters& params);
template <typename T, typename U>
bool shallow_traverse(T const & ns, U f){
for(auto n : ns){
if(is<Ast_node_kind::stmts>(n) || is<Ast_node_kind::stmt>(n)) {
if(!shallow_traverse(nlf_ptr(n)->children(),f)) return false;
} else if (!f(n)) return false;
}//for
return true;
}
template <typename T1, typename T2, typename T3>
bool shallow_traverse_ex(T1 const & ns, T2 f, T3 p){
for(auto n : ns){ if (n == nullptr) continue;
if(p(n)) {
if(!is_leaf(n->kind()))
if(!shallow_traverse_ex(nlf_ptr(n)->children(),f,p)) return false;
} else if (!f(n)) return false;
}
return true;
}
template <typename T1, typename T2, typename T3, typename T4>
bool shallow_traverse_ex2(T1 const & ns, T2 f, T3 p, T4 arguments){
for(auto n : ns){ if (n == nullptr) continue;
if(p(n,arguments)) {
if(!is_leaf(n->kind()))
if(!shallow_traverse_ex2(nlf_ptr(n)->children(),f,p,arguments)) return false;
} else if (!f(n,arguments)) return false;
}
return true;
}
inline bool traversable_fragment(Nodebase_ptr tree_node){
return is<Ast_node_kind::stmt>(tree_node) || is<Ast_node_kind::stmts>(tree_node) ||
is<Ast_node_kind::structdef>(tree_node) || is<Ast_node_kind::scope>(tree_node) ||
is<Ast_node_kind::ifelse>(tree_node) || is<Ast_node_kind::func_call>(tree_node) ||
is<Ast_node_kind::expr>(tree_node) || is<Ast_node_kind::binary_operator>(tree_node) ||
is<Ast_node_kind::unary_operator>(tree_node) || is<Ast_node_kind::for_loop_head>(tree_node);
}
template <typename T>
inline size_t num_of_children(const T& n){
return n.children().size();
}
template <typename T>
inline auto& children(T& n){
return n.children();
}
template <typename T>
inline auto& children(T* n){
return n->children();
}
/***************************** Parsetree ***********************************/
class Parsetree
{
public:
Parsetree():root_{nullptr}
{
}
Parsetree(Nodebase_ptr r):root_{r}
{
}
Nodebase_ptr get_root()
{
return root_;
}
private:
Nodebase_ptr root_;
};
/*************************** Utilities **********************************/
struct strct
{
Struct_ptr p_strct;
template<typename... Ts> strct(std::string const & name,Ts /*const &*/...);
strct() = delete;
strct(const strct & rhs)
{
p_strct = (rhs.p_strct != nullptr ? (Struct_ptr)rhs.p_strct->clone(): nullptr);
//p_strct = rhs.p_strct;
//b_copy = true;
}
strct(strct && rhs)
{
p_strct = rhs.p_strct;
rhs.p_strct = nullptr;
}
Struct_ptr get_root() {return p_strct;}
~strct()
{
if (p_strct != nullptr)
{
//std::cout << "!!"<<std::endl;
delete p_strct;
p_strct = nullptr;
}
}
};
struct ident{
std::string v;
ident(std::string s):v{s}{}
ident() = default;
};
Nodebase_ptr box(ident const & s);
Struct_ptr make_struct(std::string const & name);
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, Symbol& sym,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
mk_symbol(ceps::ast::name(sym),kind(sym)));
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, ident i,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Identifier{i.v});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, int n,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Int{n,Unit_rep{}});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, unsigned int n,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Int{(int)n,Unit_rep{}});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, long n,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Int64{n,Unit_rep{}});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, unsigned long n,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Uint64{n,Unit_rep{}});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, double n,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Double{n,Unit_rep{}});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, std::string const & s,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new String{s});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, Rawmap * rawmap,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
if (rawmap != nullptr) p->children().insert(
p->children().begin(),
rawmap);
return p;
}
template<typename U,typename... Ts>
Struct_ptr make_struct(std::string const & name, SI::Quantity<U,double> const & v,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Double{v.value_,Unit_rep{U::m,U::kg,U::s,U::A,U::K,U::mol,U::cd}});
return p;
}
template<typename U,typename... Ts>
Struct_ptr make_struct(std::string const & name, SI::Quantity<U,int> const & v,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
p->children().insert(
p->children().begin(),
new Int{v.value_,Unit_rep{U::m,U::kg,U::s,U::A,U::K,U::mol,U::cd}});
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, const char * sz,Ts const &... args)
{
return make_struct(name,std::string{sz},args...);
}
template<typename T,typename... Ts>
Struct_ptr make_struct(std::string const & name, T * p,Ts const &... args)
{
return make_struct(name,*p,args...);
}
template<typename T,typename... Ts>
Struct_ptr make_struct(std::string const & name, std::vector<T> const & il ,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
for (auto it = il.crbegin();it!=il.crend();++it)
{
T const & elem = *it;
p->children().insert(
p->children().begin(),box(elem));
}
return p;
}
template<typename T, size_t N, typename... Ts>
Struct_ptr make_struct(std::string const & name, std::array<T,N> const & arr ,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
for (size_t i = 0; i < N; ++i)
{
p->children().push_back(
box(arr[i]));
}
return p;
}
template<typename T,typename... Ts>
Struct_ptr make_struct(std::string const & name, std::vector<T *> const & il ,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
for (auto it = il.crbegin();it!=il.crend();++it)
{
auto elem = *it;
p->children().insert(
p->children().begin(),elem);
}
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, std::vector<strct> const & il ,Ts const &... args)
{
Struct_ptr p = make_struct(name,args...);
//std::cout << p << std::endl;
for (auto it = il.crbegin();it!=il.crend();++it)
{
//std::cout << it->p_strct << std::endl;
Struct* elem = (Struct*)it->p_strct->clone();
p->children().insert(
p->children().begin(),elem);
}
return p;
}
template<typename... Ts>
Struct_ptr make_struct(std::string const & name, strct const & strct_,Ts... args)
{
Struct_ptr p1 = (Struct_ptr)strct_.p_strct->clone();
Struct_ptr p2 = make_struct(name,args...);
p2->children().insert(
p2->children().begin(),
p1);
return p2;
}
template<typename... Ts>
strct::strct(std::string const & name,Ts /*const &*/... args)
{
p_strct = make_struct(name,args...);
}
/****************************** I/O *************************************/
std::ostream& operator << (std::ostream& out, strct & s);
Nodebase_ptr read_xml_file(std::string path);
inline bool
is_a_funccall( Nodebase_ptr p,
std::string& func_id,
std::string& fkind,
std::string& sym_name,
Nodebase_ptr& ftarget,
std::vector<ceps::ast::Nodebase_ptr>& args)
{
using namespace ceps::ast;
if(!is<ceps::ast::Ast_node_kind::func_call>(p)) return false;
auto& func_call = as_func_call_ref(p);
ftarget = children(func_call)[0];
auto& params = as_call_params_ref( children(func_call)[1]);
if (is<Ast_node_kind::identifier>(ftarget)){
ceps::ast::Identifier& id = *dynamic_cast<ceps::ast::Identifier*>(func_call.children()[0]);
func_id = name(id);
} else if (is<Ast_node_kind::symbol>(ftarget)){
fkind = kind(as_symbol_ref(ftarget));
sym_name = name(as_symbol_ref(ftarget));
} else return false;
if (children(params).size()) flatten_func_args(children(params)[0],args);
return true;
}
inline bool
is_a_simple_funccall( Nodebase_ptr p,
std::string& func_id,
std::vector<ceps::ast::Nodebase_ptr>& args){
using namespace ceps::ast;
std::string fkind;
std::string sym_name;
Nodebase_ptr ftarget;
if(!is_a_funccall( p,
func_id,
fkind,
sym_name,
ftarget,
args)) return false;
if (is<Ast_node_kind::identifier>(ftarget)) return true;
return false;
}
inline bool
is_a_symbol_with_arguments( Nodebase_ptr p,
std::string& sym_name,
std::string& sym_kind,
std::vector<ceps::ast::Nodebase_ptr>& args){
using namespace ceps::ast;
std::string fkind;
std::string id_name;
Nodebase_ptr ftarget;
if(!is_a_funccall( p,
id_name,
sym_kind,
sym_name,
ftarget,
args)) return false;
if (is<Ast_node_kind::symbol>(ftarget)) return true;
return false;
}
}//namespace ast
}//namespace ceps
#endif
| 23.137236 | 150 | 0.669735 | [
"vector"
] |
75c25827a65ec4d835f621bb6af8853fd080f635 | 15,860 | cpp | C++ | src/IO/AssimpLoader/AssimpGeometryDataLoader.cpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | 1 | 2018-04-16T13:55:45.000Z | 2018-04-16T13:55:45.000Z | src/IO/AssimpLoader/AssimpGeometryDataLoader.cpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | src/IO/AssimpLoader/AssimpGeometryDataLoader.cpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | #include <IO/AssimpLoader/AssimpGeometryDataLoader.hpp>
#include <assimp/mesh.h>
#include <assimp/scene.h>
#include <Core/Asset/GeometryData.hpp>
#include <Core/Utils/Log.hpp>
#include <IO/AssimpLoader/AssimpWrapper.hpp>
#include <Core/Asset/BlinnPhongMaterialData.hpp>
namespace Ra {
namespace IO {
Triplet::Triplet( const Core::Math::Vector3& v ) : m_v( v ) {}
bool Triplet::operator==( const Triplet& t ) const {
return ( m_v.isApprox( t.m_v ) );
}
bool Triplet::operator<( const Triplet& t ) const {
if ( m_v[0] < t.m_v[0] )
{
return true;
}
if ( m_v[0] == t.m_v[0] )
{
if ( m_v[1] < t.m_v[1] )
{
return true;
}
if ( m_v[1] == t.m_v[1] )
{
return ( m_v[2] < t.m_v[2] );
}
}
return false;
}
AssimpGeometryDataLoader::AssimpGeometryDataLoader( const std::string& filepath,
const bool VERBOSE_MODE ) :
DataLoader<Core::Asset::GeometryData>( VERBOSE_MODE ),
m_filepath( filepath ) {}
AssimpGeometryDataLoader::~AssimpGeometryDataLoader() {}
/// LOADING
void AssimpGeometryDataLoader::loadData( const aiScene* scene,
std::vector<std::unique_ptr<Core::Asset::GeometryData>>& data ) {
data.clear();
if ( scene == nullptr )
{
LOG( Core::Utils::logINFO ) << "AssimpGeometryDataLoader : scene is nullptr.";
return;
}
if ( !sceneHasGeometry( scene ) )
{
LOG( Core::Utils::logINFO ) << "AssimpGeometryDataLoader : scene has no mesh.";
return;
}
if ( m_verbose )
{
LOG( Core::Utils::logINFO ) << "File contains geometry.";
LOG( Core::Utils::logINFO ) << "Geometry Loading begin...";
}
loadGeometryData( scene, data );
if ( m_verbose )
{
LOG( Core::Utils::logINFO ) << "Geometry Loading end.\n";
}
}
bool AssimpGeometryDataLoader::sceneHasGeometry( const aiScene* scene ) const {
return ( sceneGeometrySize( scene ) != 0 );
}
uint AssimpGeometryDataLoader::sceneGeometrySize( const aiScene* scene ) const {
uint mesh_size = 0;
if ( scene->HasMeshes() )
{
const uint size = scene->mNumMeshes;
for ( uint i = 0; i < size; ++i )
{
aiMesh* mesh = scene->mMeshes[i];
if ( mesh->HasPositions() )
{
++mesh_size;
}
}
}
return mesh_size;
}
void AssimpGeometryDataLoader::loadMeshData( const aiMesh& mesh, Core::Asset::GeometryData& data,
std::set<std::string>& usedNames ) {
fetchName( mesh, data, usedNames );
fetchType( mesh, data );
fetchVertices( mesh, data );
if ( data.isLineMesh() )
{
fetchEdges( mesh, data );
} else
{ fetchFaces( mesh, data ); }
if ( data.isTetraMesh() || data.isHexMesh() )
{
fetchPolyhedron( mesh, data );
}
if ( mesh.HasNormals() )
{
fetchNormals( mesh, data );
}
if ( mesh.HasTangentsAndBitangents() )
{
fetchTangents( mesh, data );
fetchBitangents( mesh, data );
}
// FIXME( Charly ) << "Is it safe to only consider texcoord 0 ?
if ( mesh.HasTextureCoords( 0 ) )
{
fetchTextureCoordinates( mesh, data );
}
/*
if( mesh.HasVertexColors() ) {
fetchColors( mesh, data );
}
*/
/*
if (mesh.HasBones())
{
fetchBoneWeights(mesh, data);
}
*/
}
void AssimpGeometryDataLoader::loadMeshFrame(
const aiNode* node, const Core::Math::Transform& parentFrame, const std::map<uint, uint>& indexTable,
std::vector<std::unique_ptr<Core::Asset::GeometryData>>& data ) const {
const uint child_size = node->mNumChildren;
const uint mesh_size = node->mNumMeshes;
if ( ( child_size == 0 ) && ( mesh_size == 0 ) )
{
return;
}
Core::Math::Transform frame = parentFrame * assimpToCore( node->mTransformation );
for ( uint i = 0; i < mesh_size; ++i )
{
const uint ID = node->mMeshes[i];
auto it = indexTable.find( ID );
if ( it != indexTable.end() )
{
data[it->second]->setFrame( frame );
}
}
for ( uint i = 0; i < child_size; ++i )
{
loadMeshFrame( node->mChildren[i], frame, indexTable, data );
}
}
void AssimpGeometryDataLoader::fetchName( const aiMesh& mesh, Core::Asset::GeometryData& data,
std::set<std::string>& usedNames ) const {
std::string name = assimpToCore( mesh.mName );
while ( usedNames.find( name ) != usedNames.end() )
{
name.append( "_" );
}
usedNames.insert( name );
data.setName( name );
}
void AssimpGeometryDataLoader::fetchType( const aiMesh& mesh, Core::Asset::GeometryData& data ) const {
data.setType( Core::Asset::GeometryData::UNKNOWN );
uint face_type = 0;
for ( uint i = 0; i < mesh.mNumFaces; ++i )
{
face_type = std::max( face_type, mesh.mFaces[i].mNumIndices );
}
if ( face_type != 1 )
{
switch ( face_type )
{
case 0:
{ data.setType( Core::Asset::GeometryData::POINT_CLOUD ); }
break;
case 2:
{ data.setType( Core::Asset::GeometryData::LINE_MESH ); }
break;
case 3:
{ data.setType( Core::Asset::GeometryData::TRI_MESH ); }
break;
case 4:
{ data.setType( Core::Asset::GeometryData::QUAD_MESH ); }
break;
default:
{ data.setType( Core::Asset::GeometryData::POLY_MESH ); }
break;
}
}
}
void AssimpGeometryDataLoader::fetchVertices( const aiMesh& mesh, Core::Asset::GeometryData& data ) {
const uint size = mesh.mNumVertices;
auto& vertex = data.getVertices();
vertex.reserve( size );
auto& duplicateTable = data.getDuplicateTable();
duplicateTable.reserve( size );
std::map<Triplet, uint> uniqueTable;
for ( uint i = 0; i < size; ++i )
{
const Core::Math::Vector3 v = assimpToCore( mesh.mVertices[i] );
const Triplet t( v );
auto it = uniqueTable.find( t );
if ( it == uniqueTable.end() || data.isLoadingDuplicates() )
{
duplicateTable.push_back( vertex.size() );
uniqueTable[t] = vertex.size();
vertex.push_back( v );
} else
{ duplicateTable.push_back( it->second ); }
}
vertex.shrink_to_fit();
duplicateTable.shrink_to_fit();
}
/// EDGE
void AssimpGeometryDataLoader::fetchEdges( const aiMesh& mesh, Core::Asset::GeometryData& data ) const {
const uint size = mesh.mNumFaces;
auto& edge = data.getEdges();
edge.resize( size );
#pragma omp parallel for
for ( uint i = 0; i < size; ++i )
{
edge[i] = assimpToCore( mesh.mFaces[i].mIndices, mesh.mFaces[i].mNumIndices ).cast<uint>();
if ( !data.isLoadingDuplicates() )
{
edge[i][0] = data.getDuplicateTable().at( edge[i][0] );
edge[i][1] = data.getDuplicateTable().at( edge[i][1] );
}
}
}
void AssimpGeometryDataLoader::fetchFaces( const aiMesh& mesh, Core::Asset::GeometryData& data ) const {
const uint size = mesh.mNumFaces;
auto& face = data.getFaces();
face.resize( size );
#pragma omp parallel for
for ( uint i = 0; i < size; ++i )
{
face[i] = assimpToCore( mesh.mFaces[i].mIndices, mesh.mFaces[i].mNumIndices ).cast<uint>();
if ( !data.isLoadingDuplicates() )
{
const uint face_vertices = mesh.mFaces[i].mNumIndices;
for ( uint j = 0; j < face_vertices; ++j )
{
face[i][j] = data.getDuplicateTable().at( face[i][j] );
}
}
}
}
void AssimpGeometryDataLoader::fetchPolyhedron( const aiMesh& mesh,
Core::Asset::GeometryData& data ) const {
// TO DO
}
void AssimpGeometryDataLoader::fetchNormals( const aiMesh& mesh, Core::Asset::GeometryData& data ) const {
auto& normal = data.getNormals();
normal.resize( data.getVerticesSize(), Core::Math::Vector3::Zero() );
#pragma omp parallel for if ( data.isLoadingDuplicates() )
for ( uint i = 0; i < mesh.mNumVertices; ++i )
{
normal.at( data.getDuplicateTable().at( i ) ) += assimpToCore( mesh.mNormals[i] );
}
#pragma omp parallel for
for ( uint i = 0; i < uint( normal.size() ); ++i )
{
normal[i].normalize();
}
}
void AssimpGeometryDataLoader::fetchTangents( const aiMesh& mesh,
Core::Asset::GeometryData& data ) const {
#if defined( RADIUM_WITH_TEXTURES )
const uint size = mesh.mNumVertices;
auto& tangent = data.getTangents();
tangent.resize( size, Core::Math::Vector3::Zero() );
# pragma omp parallel for
for ( uint i = 0; i < size; ++i )
{
tangent[i] = assimpToCore( mesh.mTangents[i] );
}
#endif
}
void AssimpGeometryDataLoader::fetchBitangents( const aiMesh& mesh,
Core::Asset::GeometryData& data ) const {
#if defined( RADIUM_WITH_TEXTURES )
const uint size = mesh.mNumVertices;
auto& bitangent = data.getBiTangents();
bitangent.resize( size );
# pragma omp parallel for
for ( uint i = 0; i < size; ++i )
{
bitangent[i] = assimpToCore( mesh.mBitangents[i] );
}
#endif
}
void AssimpGeometryDataLoader::fetchTextureCoordinates( const aiMesh& mesh,
Core::Asset::GeometryData& data ) const {
#if ( defined( RADIUM_WITH_TEXTURES ) )
const uint size = mesh.mNumVertices;
auto& texcoord = data.getTexCoords();
texcoord.resize( data.getVerticesSize() );
# pragma omp parallel for
for ( uint i = 0; i < size; ++i )
{
// FIXME(Charly): Is it safe to only consider texcoords[0] ?
texcoord.at( i ) = assimpToCore( mesh.mTextureCoords[0][i] );
}
#endif
}
void AssimpGeometryDataLoader::fetchColors( const aiMesh& mesh, Core::Asset::GeometryData& data ) const {
// TO DO
}
void AssimpGeometryDataLoader::fetchBoneWeights( const aiMesh& mesh,
Core::Asset::GeometryData& data ) const {
#if 0
GeometryData::WeightArray weights(data.getVerticesSize());
for (uint i = 0; i < mesh.mNumBones; ++i)
{
aiBone* bone = mesh.mBones[i];
for (uint j = 0; j < bone->mNumWeights; ++j)
{
aiVertexWeight w = bone->mWeights[j];
uint id = w.mVertexId;
CORE_ASSERT(id < data.getVerticesSize(), "Vertex ID is out of bounds");
weights[id].push_back({w.mWeight, i});
}
}
data.setWeights(weights);
#endif
}
void AssimpGeometryDataLoader::loadMaterial( const aiMaterial& material,
Core::Asset::GeometryData& data ) const {
std::string matName;
aiString assimpName;
if ( AI_SUCCESS == material.Get( AI_MATKEY_NAME, assimpName ) )
{
matName = assimpName.C_Str();
}
// TODO : use AI_MATKEY_SHADING_MODEL to select the apropriate model
// (http://assimp.sourceforge.net/lib_html/material_8h.html#a93e23e0201d6ed86fb4287e15218e4cf)
/*
aiShadingMode shading;
if( AI_SUCCESS == material.Get( AI_MATKEY_SHADING_MODEL, shading ) )
{
LOG(Core::Utils::logINFO) << "Got a " << shading << " shading model.";
}
else
{
LOG(Core::Utils::logINFO) << "Unable to retrieve shading model.";
}
*/
Core::Asset::BlinnPhongMaterialData* blinnPhongMaterial =
new Core::Asset::BlinnPhongMaterialData( matName );
aiColor4D color;
float shininess;
float opacity;
aiString name;
if ( AI_SUCCESS == material.Get( AI_MATKEY_COLOR_DIFFUSE, color ) )
{
blinnPhongMaterial->m_hasDiffuse = true;
blinnPhongMaterial->m_diffuse = assimpToCore( color );
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_COLOR_SPECULAR, color ) )
{
blinnPhongMaterial->m_hasSpecular = true;
blinnPhongMaterial->m_specular = assimpToCore( color );
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_SHININESS, shininess ) )
{
blinnPhongMaterial->m_hasShininess = true;
blinnPhongMaterial->m_shininess = shininess;
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_OPACITY, opacity ) )
{
blinnPhongMaterial->m_hasOpacity = true;
// NOTE(charly): Due to collada way of handling objects that have an alpha map, we must
// ensure
// we do not have zeros in here.
blinnPhongMaterial->m_opacity = opacity < 1e-5 ? 1 : opacity;
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_TEXTURE( aiTextureType_DIFFUSE, 0 ), name ) )
{
blinnPhongMaterial->m_texDiffuse = m_filepath + "/" + assimpToCore( name );
blinnPhongMaterial->m_hasTexDiffuse = true;
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_TEXTURE( aiTextureType_SPECULAR, 0 ), name ) )
{
blinnPhongMaterial->m_texSpecular = m_filepath + "/" + assimpToCore( name );
blinnPhongMaterial->m_hasTexSpecular = true;
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_TEXTURE( aiTextureType_SHININESS, 0 ), name ) )
{
blinnPhongMaterial->m_texShininess = m_filepath + "/" + assimpToCore( name );
blinnPhongMaterial->m_hasTexShininess = true;
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_TEXTURE( aiTextureType_NORMALS, 0 ), name ) )
{
blinnPhongMaterial->m_texNormal = m_filepath + "/" + assimpToCore( name );
blinnPhongMaterial->m_hasTexNormal = true;
}
// Assimp loads objs bump maps as height maps, gj bro
if ( AI_SUCCESS == material.Get( AI_MATKEY_TEXTURE( aiTextureType_HEIGHT, 0 ), name ) )
{
blinnPhongMaterial->m_texNormal = m_filepath + "/" + assimpToCore( name );
blinnPhongMaterial->m_hasTexNormal = true;
}
if ( AI_SUCCESS == material.Get( AI_MATKEY_TEXTURE( aiTextureType_OPACITY, 0 ), name ) )
{
blinnPhongMaterial->m_texOpacity = m_filepath + "/" + assimpToCore( name );
blinnPhongMaterial->m_hasTexOpacity = true;
}
data.setMaterial( blinnPhongMaterial );
}
void AssimpGeometryDataLoader::loadGeometryData(
const aiScene* scene, std::vector<std::unique_ptr<Core::Asset::GeometryData>>& data ) {
const uint size = scene->mNumMeshes;
std::map<uint, uint> indexTable;
std::set<std::string> usedNames;
for ( uint i = 0; i < size; ++i )
{
aiMesh* mesh = scene->mMeshes[i];
if ( mesh->HasPositions() )
{
Core::Asset::GeometryData* geometry = new Core::Asset::GeometryData();
#ifdef RADIUM_WITH_TEXTURES
geometry->setLoadDuplicates( true );
#endif
loadMeshData( *mesh, *geometry, usedNames );
if ( scene->HasMaterials() )
{
const uint matID = mesh->mMaterialIndex;
if ( matID < scene->mNumMaterials )
{
aiMaterial* material = scene->mMaterials[matID];
loadMaterial( *material, *geometry );
}
}
data.push_back( std::unique_ptr<Core::Asset::GeometryData>( geometry ) );
indexTable[i] = data.size() - 1;
if ( m_verbose )
{
geometry->displayInfo();
}
}
}
loadMeshFrame( scene->mRootNode, Core::Math::Transform::Identity(), indexTable, data );
}
} // namespace IO
} // namespace Ra
| 31.656687 | 106 | 0.580706 | [
"mesh",
"geometry",
"vector",
"model",
"transform"
] |
75c5165508f6476c9d1fb58673b7d2f59377a5bd | 4,226 | cpp | C++ | Graphs/Directed/Kosaraju SCC/kosaraju_scc.cpp | fork52/CPP_fork52 | 61c3967dc65985e2148184427161bc89a15c36ad | [
"Apache-2.0"
] | 5 | 2021-05-12T09:10:27.000Z | 2022-03-11T17:34:54.000Z | Graphs/Directed/Kosaraju SCC/kosaraju_scc.cpp | fork52/CPP_fork52 | 61c3967dc65985e2148184427161bc89a15c36ad | [
"Apache-2.0"
] | 1 | 2021-05-10T12:01:17.000Z | 2021-05-10T15:31:50.000Z | Graphs/Directed/Kosaraju SCC/kosaraju_scc.cpp | fork52/CP-ALGOS-DS | 61c3967dc65985e2148184427161bc89a15c36ad | [
"Apache-2.0"
] | 1 | 2021-05-29T10:43:11.000Z | 2021-05-29T10:43:11.000Z | #include <bits\stdc++.h>
using namespace std;
using ll = long long;
template<typename T1>
void disp_vec(vector<T1> arr){
int n = arr.size();
for(auto a: arr){
cout << a << " ";
}
cout << "\n";
}
/*
References:
https://cp-algorithms.com/graph/strongly-connected-components.html
https://youtu.be/QtdE7QPsWiU
*/
template<typename T1>
class Kosaraju_SCC {
public:
ll n;
vector<vector<T1>> graph, rev_graph;
stack<T1> st;
vector<vector<T1>> components;
vector<bool> vis;
vector<T1> node_to_sccRoot; // For mapping node to scc Reperesntative.
vector<vector<T1>> condensation_graph;
Kosaraju_SCC(vector<vector<T1>> &adj_list){
n = adj_list.size();
graph = adj_list;
}
// Step 1: DFS to populate the stack
void _dfs1(T1 node){
vis[node] = true;
for(auto nei : graph[node]){
if(vis[nei] == false){
_dfs1(nei);
}
}
st.push(node);
}
// Step 2: Create the rev copy of the graph
void _create_reverse_graph(){
rev_graph = vector<vector<T1>>(n);
for(T1 u = 0; u < n; u++){
for(auto v : graph[u]){
rev_graph[v].push_back(u);
}
}
}
// Step 3: DFS for finding the components
void _dfs2(T1 node, int comp_ind){
vis[node] = true;
components[comp_ind].push_back(node);
node_to_sccRoot[node] = comp_ind;
for(auto nei : rev_graph[node]){
if(vis[nei] == false){
_dfs2(nei, comp_ind);
}
}
}
/*
Finds the Strongly connected components in the directed graph.
Stores the components in the 2D vector `components`.
*/
void find_SCCs(){
vis = vector<bool>(n, false);
// Random order dfs on the graph to generate a stack
for(T1 node = 0; node < n; node++){
if(vis[node] == false){
_dfs1(node);
}
}
// Create a reversed/transposed copy the graph `rev_graph`
_create_reverse_graph();
fill(vis.begin(), vis.end(), false);
// Perform dfs again in the order present in stack to find SCCs
int component_index = 0;
node_to_sccRoot.resize(n);
while(!st.empty()){
T1 node = st.top(); st.pop();
if(vis[node] == false){
components.push_back(vector<T1>());
_dfs2(node, component_index);
component_index++;
}
}
}
/*
Call find_SCCs first before generating the condensation graph.
It is guaranteed that the condensation graph will be a DAG.
*/
void generate_condensation_graph(){
int no_of_components = components.size();
condensation_graph = vector<vector<T1>>(no_of_components);
for(int node = 0; node < n; node++){
int sccRoot1 = node_to_sccRoot[node];
for(auto nei : graph[node]){
int sccRoot2 = node_to_sccRoot[nei];
if(sccRoot1 != sccRoot2){
condensation_graph[sccRoot1].push_back(sccRoot2);
}
}
}
}
};
int main(){
vector<vector<int>> sample_graph = {
{1},
{2},
{0, 4},
{4},
{5, 6},
{3},
{7},
{6}
};
Kosaraju_SCC<int> obj(sample_graph);
// Findin the SCCs
obj.find_SCCs();
// Generating the condensation graph
obj.generate_condensation_graph();
// Printing out the components in each SCC of the graph
cout << "No of components: " << obj.components.size() << "\n";
for(int c = 0; c < obj.components.size(); c++){
disp_vec(obj.components[c]);
}
// Printing out the condensation graph. It is guaranteeed to be a DAG.
cout << "\nCondensation graph : \n";
for(int c = 0; c < obj.condensation_graph.size(); c++){
cout << c << " : "; disp_vec(obj.condensation_graph[c]);
}
/*
Expected output:
No of components: 3
0 2 1
4 3 5
6 7
Condensation graph :
0 : 1
1 : 2
2 :
*/
} | 23.608939 | 86 | 0.530762 | [
"vector"
] |
75cddd4be4241b43b3ee0580ba1a1acf4589eceb | 20,207 | cc | C++ | src/callbacks.cc | LLNL/bindee | 3df620803ef5b198a32732341e52971342493863 | [
"MIT"
] | 5 | 2020-02-19T08:10:46.000Z | 2021-02-03T01:28:34.000Z | src/callbacks.cc | LLNL/bindee | 3df620803ef5b198a32732341e52971342493863 | [
"MIT"
] | null | null | null | src/callbacks.cc | LLNL/bindee | 3df620803ef5b198a32732341e52971342493863 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020, Lawrence Livermore National Security, LLC and other
* bindee developers. See the top-level LICENSE file for details.
*
* SPDX-License-Identifier: MIT
*/
#include <unordered_set>
#include <iostream>
#include <sstream>
#include "callbacks.hh"
#include "database.hh"
#include "bindee.hh"
#include "options.hh"
#include "clang/Lex/Lexer.h"
namespace Bindee {
BindeeCallback::
BindeeCallback(Database &db, const clang::PrintingPolicy pp, const clang::LangOptions lo)
: clang::ast_matchers::MatchFinder::MatchCallback(),
_db(db),
_pp(pp),
_lo(lo)
{
}
std::unordered_map<std::string, FunctionCallback::QualAliasMap> FunctionCallback::qualAliasMaps =
std::unordered_map<std::string, FunctionCallback::QualAliasMap>();
// qualify helpers
namespace {
bool
qualifyAlias(std::string &typeName, const FunctionCallback::QualAliasMap *map)
{
if (!map) { return false; }
bool ret = false;
for (const auto &kv : *map) {
const auto &alias = kv.first;
std::stringstream ss;
std::string::size_type start{0};
std::string::size_type pos{0};
while ((pos = typeName.find(alias, start)) != std::string::npos) {
ss << typeName.substr(start, pos-start);
start = pos + alias.size();
if (pos > 0) {
auto c = typeName.at(pos-1);
if (std::isalnum(c) || c == '_' || c == ':') {
ss << typeName.substr(pos, alias.size());
continue;
}
}
if (start < typeName.size()) {
auto c = typeName.at(start);
if (std::isalnum(c) || c == '_') {
ss << typeName.substr(pos, alias.size());
continue;
}
} else {
continue;
}
ss << kv.second;
ret = true;
}
ss << typeName.substr(start);
typeName = ss.str();
}
return false;
} // qualifyAlias
bool
qualifyTemplate(std::string &typeName, clang::QualType qualType)
{
bool ret = false;
const auto *p = qualType->getAs<clang::PointerType>();
const auto *r = qualType->getAs<clang::ReferenceType>();
// Strip pointers and references.
while (p || r) {
qualType = p ? p->getPointeeType() : r->getPointeeType();
p = qualType->getAs<clang::PointerType>();
r = qualType->getAs<clang::ReferenceType>();
}
// Find class template.
const auto *inst = qualType->getAs<clang::TemplateSpecializationType>();
if (inst) {
const auto *templateDecl = inst->getTemplateName().getAsTemplateDecl();
if (templateDecl) {
const std::string instName = templateDecl->getNameAsString();
const std::string qualInstName = templateDecl->getQualifiedNameAsString();
std::stringstream ss;
std::string::size_type start{0};
std::string::size_type pos{0};
while ((pos = typeName.find(instName, start)) != std::string::npos) {
ss << typeName.substr(start, pos-start);
start = pos + instName.size();
if (pos > 0) {
auto c = typeName.at(pos-1);
if (std::isalnum(c) || c == '_' || c == ':') {
ss << typeName.substr(pos, instName.size());
continue;
}
}
if (start < typeName.size()) {
auto c = typeName.at(start);
if (c != '<') {
ss << typeName.substr(pos, instName.size());
continue;
}
} else {
continue;
}
ss << qualInstName;
ret = true;
}
ss << typeName.substr(start);
typeName = ss.str();
}
}
return ret;
} // qualifyTemplate
} // anonymous namespace
std::string
BindeeCallback::
methodSignature(const clang::CXXMethodDecl *method)
{
std::string ret;
std::stringstream ss;
// return type
const auto retType = method->getReturnType();
std::string retName = retType.getAsString(_pp);
qualifyTemplate(retName, retType);
ss << retName;
// name
ss << method->getNameAsString();
// params
std::vector<std::string> params;
for (const auto *param : method->parameters()) {
auto qualType = param->getType();
std::string typeName = qualType.getAsString(_pp);
qualifyTemplate(typeName, qualType);
ss << typeName;
}
// const
ss << method->isConst();
ret = ss.str();
return ret;
} //signature
void
RecordCallback::
run(const clang::ast_matchers::MatchFinder::MatchResult &result)
{
const clang::CXXRecordDecl *record = result.Nodes.getNodeAs<clang::CXXRecordDecl>("record");
if (!record) { return; }
if (record->getNameAsString().empty()) { return; }
std::string qualName = record->getQualifiedNameAsString();
std::string qualCls = qualName;
std::vector<std::string> templateParams;
std::vector<std::string> qualBases;
int numBases = record->bases().end() - record->bases().begin();
for (const auto &base : record->bases()) {
const auto qualType = base.getType();
std::string typeName = qualType.getAsString(_pp);
if (const auto *baseRecord = qualType->getAsCXXRecordDecl()) {
qualBases.push_back(baseRecord->getQualifiedNameAsString());
} else {
if (qualifyTemplate(typeName, qualType)) {
qualBases.push_back(typeName);
}
}
}
// Skip anonymous ancestor.
const clang::RecordDecl *recordDecl = record;
std::string prev = qualName;
while ((recordDecl = recordDecl->getOuterLexicalRecordContext())) {
if (recordDecl->getNameAsString().empty()) { return; }
if (recordDecl->getQualifiedNameAsString() == prev) { break; }
else { prev = recordDecl->getQualifiedNameAsString(); }
}
// Get number of template parameters.
const auto *classTemplateDecl = record->getDescribedClassTemplate();
if (classTemplateDecl) {
for (const auto *param : *(classTemplateDecl->getTemplateParameters())) {
templateParams.push_back(param->getNameAsString());
}
}
RecordBindee bindee(qualName, qualCls, templateParams, qualBases, numBases);
_db.add(bindee);
}
void
FunctionCallback::
run(const clang::ast_matchers::MatchFinder::MatchResult &result)
{
const clang::FunctionDecl *function = result.Nodes.getNodeAs<clang::FunctionDecl>("function");
if (!function) { return; }
if (function->isInvalidDecl()
|| function->isImplicit()
|| function->isDeleted())
{ return; }
static const std::string CLASS_ = "class ";
static const std::string STRUCT_ = "struct ";
static const std::string ENUM_ = "enum ";
std::string qualName = function->getQualifiedNameAsString();
const auto retType = function->getReturnType();
std::string ret = retType.getAsString(_pp);
int numTemplateParams = 0;
std::vector<Param> params;
std::string qualCls;
bool isConst = false;
bool isStatic = false;
const auto &OPERATOR = FunctionBindee::OPERATOR;
const auto &validOps = FunctionBindee::validOps;
std::string name(function->getNameAsString());
bool isOperator = false;
if (name.compare(0, OPERATOR.size(), OPERATOR) == 0) {
const auto c{name.at(OPERATOR.size())};
if (!(std::isalnum(c) || c == '_')) {
isOperator = true;
}
}
std::unordered_map<std::string, std::string> *qualAliasMap = nullptr;
const auto *method = dynamic_cast<const clang::CXXMethodDecl *>(function);
if (method) {
qualCls = method->getParent()->getQualifiedNameAsString();
isConst = method->isConst();
isStatic = method->isStatic();
// Skip out-of-class nodes.
if (method->getPreviousDecl()) { return; }
// Skip constructors abstract classes.
const clang::CXXRecordDecl *parent = method->getParent();
if (parent->isAbstract()) {
if (dynamic_cast<const clang::CXXConstructorDecl*>(method)) { return; }
}
// Skip bad member operator overloads.
if (isOperator) {
if (validOps.find(name.substr(OPERATOR.size())) == validOps.end()) {
std::cerr << "bindee: info: skipping unsupported operator overload: "
<< qualName << "\n";
return;
}
}
// Skip if inside anonymous record.
const clang::RecordDecl *recordDecl = method->getParent();
std::string prev = qualCls;
while ((recordDecl = recordDecl->getOuterLexicalRecordContext())) {
if (recordDecl->getNameAsString().empty()) { return; }
if (recordDecl->getQualifiedNameAsString() == prev) { break; }
else { prev = recordDecl->getQualifiedNameAsString(); }
}
// Skip overrides if desired.
if (!opts.bindOverrides && method->isVirtual()) {
std::string thisSig = methodSignature(method);
bool skipOverride = false;
if (method->size_overridden_methods() == 0) {
// Check for override in templated base.
for (const auto &base : parent->bases()) {
// Ultimately want the CXXRecordDecl for the template instantiation.
const auto qualType = base.getType();
const auto *inst = qualType->getAs<clang::TemplateSpecializationType>();
if (!inst) { continue; }
const auto *a = inst->getTemplateName().getAsTemplateDecl();
if (!a) { continue; }
const auto *b = dynamic_cast<const clang::ClassTemplateDecl*>(a);
if (!b) { continue; }
const auto *cxxRecordDecl = b->getTemplatedDecl();
if (!cxxRecordDecl) { continue; }
for (const auto *cxxMethodDecl : cxxRecordDecl->methods()) {
if (!cxxMethodDecl->isVirtual()) { continue; }
if (thisSig == methodSignature(cxxMethodDecl)) {
skipOverride = true;
}
}
}
} else {
// Need to bind override if there is an overload.
skipOverride = true;
for (const auto other : parent->methods()) {
if (name == other->getNameAsString() && thisSig != methodSignature(other)) {
skipOverride = false;
}
}
}
if (skipOverride) {
std::cerr << "bindee: toggle: skipping overriding method: "
<< qualName << "\n";
return;
}
}
// Map aliases to their qualified names.
std::string className = parent->getQualifiedNameAsString();
if (qualAliasMaps.count(className) == 0) {
qualAliasMaps[className];
for (const auto *decl : parent->decls()) {
if (const auto *alias = dynamic_cast<const clang::TypedefNameDecl *>(decl)) {
qualAliasMaps[className][alias->getNameAsString()] = alias->getQualifiedNameAsString();
}
}
}
qualAliasMap = &(qualAliasMaps.at(className));
} else if (isOperator) {
std::cerr << "bindee: info: skipping non-member operator overload: "
<< qualName << "\n";
return;
}
auto replace = [](const std::string &s, const std::string &old, const std::string &rep) {
std::stringstream ss;
std::string::size_type start{0};
std::string::size_type pos{0};
while ((pos = s.find(old, start)) != std::string::npos) {
ss << s.substr(start, pos-start);
start = pos + old.size();
if (pos > 0) {
auto c = s.at(pos-1);
if (std::isalnum(c) || c == '_') {
ss << s.substr(pos, old.size());
continue;
}
}
if (start < s.size()) {
auto c = s.at(start);
if (std::isalnum(c) || c == '_') {
ss << s.substr(pos, old.size());
continue;
}
}
ss << rep;
}
ss << s.substr(start);
return ss.str();
};
// Skip rvalue bindees.
if ((int) ret.find("&&") != -1) {
return;
}
// Qualify return type.
qualifyAlias(ret, qualAliasMap);
qualifyTemplate(ret, retType);
// Erase template parameters from constructors.
if (!isOperator) {
auto pos = qualName.find("<");
if (pos != std::string::npos) {
qualName.erase(pos, qualName.size() - pos);
}
}
// Get number of template parameters.
std::unordered_map<std::string, int> templateParams;
const auto *functionTemplateDecl = function->getDescribedFunctionTemplate();
if (functionTemplateDecl) {
for (const auto *param : *(functionTemplateDecl->getTemplateParameters())) {
templateParams[param->getNameAsString()] = numTemplateParams++;
}
}
// Erase "class ", "struct ", and "enum " substring.
auto erase = [](std::string &s) {
auto pos = s.find(CLASS_);
if (pos != std::string::npos) {
s.erase(pos, CLASS_.size());
}
pos = s.find(STRUCT_);
if (pos != std::string::npos) {
s.erase(pos, STRUCT_.size());
}
pos = s.find(ENUM_);
if (pos != std::string::npos) {
s.erase(pos, ENUM_.size());
}
};
erase(ret);
// Convert ret type if template type;
for (const auto &kv : templateParams) {
std::string rep = "@T" + std::to_string(templateParams.at(kv.first)) + "@";
ret = replace(ret, kv.first, rep);
}
// Collect parameters.
for (const auto *param : function->parameters()) {
auto qualType = param->getType();
std::string typeName = qualType.getAsString(_pp);
// Skip if pointer to builtin.
if (!opts.bindImmutables) {
const auto *p = qualType->getAs<clang::PointerType>();
const auto *r = qualType->getAs<clang::ReferenceType>();
if (p || r) {
if (p) {
qualType = p->getPointeeType();
} else if (r) {
qualType = r->getPointeeType();
}
if (!qualType.isConstQualified()
&& (qualType->isBuiltinType()
|| qualType.getAsString(_pp) == "std::string")) {
std::cerr << "bindee: toggle: skipping method with python-immutable parameter: "
<< qualName << "\n";
return;
}
}
}
// Skip rvalue bindees.
if ((int) typeName.find("&&") != -1) {
return;
}
// Erase "class " and "struct " substring.
erase(typeName);
// Qualify parameter.
qualifyAlias(typeName, qualAliasMap);
qualifyTemplate(typeName, qualType);
// Fill in function template parameters.
for (const auto &kv : templateParams) {
std::string rep = "@T" + std::to_string(templateParams.at(kv.first)) + "@";
typeName = replace(typeName, kv.first, rep);
}
std::string defaultArg;
if (param->hasDefaultArg()) {
defaultArg = clang::Lexer::getSourceText(
clang::CharSourceRange(param->getDefaultArg()->getSourceRange(), true),
param->getASTContext().getSourceManager(),
_lo)
.str();
}
params.emplace_back(typeName, param->getNameAsString(), defaultArg);
}
// Skip unsupported unary operator overload.
if (isOperator) {
bool isUnary = (qualCls.empty() && params.size() == 1)
|| (!qualCls.empty() && params.size() == 0);
if (isUnary) {
std::string op = name.substr(OPERATOR.size());
if (!(op == "+" || op == "-")) {
std::cerr << "bindee: info: skipping unsupported unary operator overload: "
<< qualName << "\n";
return;
}
}
}
FunctionBindee bindee(qualName, qualCls, numTemplateParams, ret, params,
isConst, isStatic);
_db.add(bindee);
}
void
VariableCallback::
run(const clang::ast_matchers::MatchFinder::MatchResult &result) {
const clang::DeclaratorDecl *decl = result.Nodes.getNodeAs<clang::DeclaratorDecl>("variable");
if (!decl) { return; }
std::string qualName = decl->getQualifiedNameAsString();
std::string qualCls = "";
bool isConst = decl->getType().isConstQualified();
bool isStatic = false;
const auto *type = decl->getType()->getAsTagDecl();
if (type && type->getNameAsString().empty()) { return; }
if (const auto *varDecl = dynamic_cast<const clang::VarDecl*>(decl)) {
if (varDecl->isCXXClassMember()) {
isStatic = varDecl->isStaticDataMember();
int pos = qualName.rfind(":")-1;
if (pos > 0) {
qualCls = qualName.substr(0, qualName.rfind(":")-1);
}
}
}
if (const auto *fieldDecl = dynamic_cast<const clang::FieldDecl*>(decl)) {
if (const auto *recordDecl = fieldDecl->getParent()) {
qualCls = recordDecl->getQualifiedNameAsString();
// Skip if inside inner record.
if (recordDecl->getOuterLexicalRecordContext()->getQualifiedNameAsString()
!= qualCls) { return; }
// Skip if inside anonymous record.
std::string prev = qualCls;
while ((recordDecl = recordDecl->getOuterLexicalRecordContext())) {
if (recordDecl->getNameAsString().empty()) { return; }
if (recordDecl->getQualifiedNameAsString() == prev) { break; }
else { prev = recordDecl->getQualifiedNameAsString(); }
}
}
}
VariableBindee bindee(qualName, qualCls, isConst, isStatic);
_db.add(bindee);
}
void EnumCallback::
run(const clang::ast_matchers::MatchFinder::MatchResult &result) {
const clang::EnumDecl *decl = result.Nodes.getNodeAs<clang::EnumDecl>("enum");
if (!decl) { return; }
std::string qualName = decl->getQualifiedNameAsString();
std::string qualCls = "";
std::vector<std::string> templateParams;
std::vector<std::string> values;
bool isScoped = decl->isScoped();
// Get qualCls and templateParams, if applicable.
const auto *parent = decl->getParent();
if (parent) {
const auto *record = parent->getOuterLexicalRecordContext();
if (record) {
const auto *cxxRecordDecl = dynamic_cast<const clang::CXXRecordDecl*>(record);
qualCls = cxxRecordDecl->getQualifiedNameAsString();
if (decl->getAccess() != clang::AS_public) {
return;
}
const auto *classTemplateDecl = cxxRecordDecl->getDescribedClassTemplate();
if (classTemplateDecl) {
// in template
for (const auto *param : *(classTemplateDecl->getTemplateParameters())) {
templateParams.push_back(param->getNameAsString());
}
}
}
}
// Get values.
for (const auto val : decl->enumerators()) {
values.push_back(val->getNameAsString());
}
EnumBindee bindee(qualName, qualCls, templateParams, values, isScoped);
_db.add(bindee);
}
} // namespace Bindee
| 34.018519 | 107 | 0.545009 | [
"vector"
] |
75d43430a3d9a14887e205d6cd7707f337831f11 | 7,252 | cpp | C++ | Testing/vtkALBA/vtkALBAExtrudeToCircleTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Testing/vtkALBA/vtkALBAExtrudeToCircleTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Testing/vtkALBA/vtkALBAExtrudeToCircleTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: vtkALBAExtrudeToCircleTest
Authors: Nigel McFarlane
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "albaDefines.h"
#include <cppunit/config/SourcePrefix.h>
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkInteractorStyleTrackballCamera.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkProperty.h"
#include "vtkPolyData.h"
#include "vtkCylinderSource.h"
#include "vtkFeatureEdges.h"
#include "vtkPolyDataConnectivityFilter.h"
#include "vtkCleanPolyData.h"
#include "vtkALBAExtrudeToCircle.h"
#include "vtkALBAExtrudeToCircleTest.h"
#include "albaConfigure.h"
static const bool renderingOn = false ; // switch interactive rendering on
void vtkALBAExtrudeToCircleTest::BeforeTest()
{
m_testData = NULL ;
m_extrusion = NULL ;
}
void vtkALBAExtrudeToCircleTest::AfterTest()
{
vtkDEL(m_testData);
vtkDEL(m_extrusion);
}
void vtkALBAExtrudeToCircleTest::TestFixture()
{
}
//------------------------------------------------------------------------------
// render the input and output data
void vtkALBAExtrudeToCircleTest::RenderExtrusion()
//------------------------------------------------------------------------------
{
// Create a Renderer, a RenderWindow and a RenderWindowInteractor
vtkRenderer *R = vtkRenderer::New();
R->SetBackground(0.5, 0.5, 0.5);
R->SetLightFollowCamera(1);
vtkRenderWindow *RW = vtkRenderWindow::New();
RW->AddRenderer(R);
RW->AddRenderer(R);
RW->SetSize(400, 400);
vtkRenderWindowInteractor *RWI = vtkRenderWindowInteractor::New();
RWI->SetRenderWindow(RW);
vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New() ;
RWI->SetInteractorStyle(style) ;
// set up pipeline to visualize original data
vtkPolyDataMapper *mapper1 = vtkPolyDataMapper::New();
mapper1->SetInput(m_testData) ;
vtkActor *A1 = vtkActor::New();
A1->SetMapper(mapper1);
// set up pipeline to visualize the extrusion
vtkPolyDataMapper *mapper2 = vtkPolyDataMapper::New();
mapper2->SetInput(m_extrusion);
vtkActor *A2 = vtkActor::New();
A2->SetMapper(mapper2);
A2->GetProperty()->SetColor(1,1,0) ;
// -------------------------------
// Reset the camera and initialize
// -------------------------------
R->AddActor( A1 );
R->AddActor( A2 );
R->ResetCamera();
R->ResetCameraClippingRange();
RW->Render();
RWI->Initialize();
RWI->Start();
R->Delete() ;
RW->Delete() ;
RWI->Delete() ;
style->Delete() ;
mapper1->Delete();
A1->Delete();
mapper2->Delete();
A2->Delete();
}
//------------------------------------------------------------------------------
// Create test data
void vtkALBAExtrudeToCircleTest::CreateTestData()
//------------------------------------------------------------------------------
{
// create a cylinder with open ends
vtkCylinderSource *cyl = vtkCylinderSource::New() ;
cyl->SetResolution(10) ;
cyl->SetHeight(10) ;
cyl->SetRadius(1.0) ;
cyl->SetCapping(0) ;
cyl->GetOutput()->Update() ;
m_testData = vtkPolyData::New() ;
m_testData->DeepCopy(cyl->GetOutput()) ;
// mess up the shape of the cylinder.
int i ;
double xa[3], xb[3] ;
double xinc[10] = {0.303844709,0.342944797,0.325211305,-0.081062732,-0.37609408,-0.513841563,-0.190581172,-0.394675426,0.127765989,0.456488174} ;
double zinc[10] = {-0.119779481,0.12174925,0.355289816,0.463100679,0.458244457,-0.240880002,-0.119889833,-0.347051271,-0.23729248,-0.333491135} ;
// change the shape of the ends, keeping points in same plane
for (i = 0 ; i < 10 ; i++){
m_testData->GetPoint(2*i, xa) ;
m_testData->GetPoints()->SetPoint(2*i, xa[0]+xinc[i], xa[1], xa[2]+zinc[i]) ;
m_testData->GetPoint(2*i+1, xb) ;
m_testData->GetPoints()->SetPoint(2*i+1, xb[0]+xinc[i], xb[1], xb[2]+zinc[i]) ;
}
// shear the cylinder
for (i = 0 ; i < 10 ; i++){
m_testData->GetPoint(2*i, xa) ;
m_testData->GetPoints()->SetPoint(2*i, xa[0], xa[1]+0.2*xa[0], xa[2]) ;
m_testData->GetPoint(2*i+1, xb) ;
m_testData->GetPoints()->SetPoint(2*i+1, xb[0], xb[1]+0.2*xb[0], xb[2]) ;
}
cyl->Delete() ;
}
//------------------------------------------------------------------------------
// Test extrusion filter
void vtkALBAExtrudeToCircleTest::TestExtrusion()
//------------------------------------------------------------------------------
{
//----------------------------------------------------------------------------
// Create the test polydata
//----------------------------------------------------------------------------
CreateTestData() ;
//----------------------------------------------------------------------------
// Find and select holes in input polydata
//----------------------------------------------------------------------------
// This filter extracts the edge features of the mesh
vtkFeatureEdges *fEdges1 = vtkFeatureEdges::New() ;
fEdges1->BoundaryEdgesOn() ;
fEdges1->FeatureEdgesOff() ;
fEdges1->NonManifoldEdgesOff() ;
fEdges1->ManifoldEdgesOff() ;
fEdges1->SetInput(m_testData) ;
// This filter extracts connected regions of the polydata.
// Note: it does this by changing the cells, but it does not delete the points !!
vtkPolyDataConnectivityFilter *PDCF = vtkPolyDataConnectivityFilter::New() ;
PDCF->SetInput(fEdges1->GetOutput()) ;
PDCF->SetExtractionModeToSpecifiedRegions() ; // sets mode to extract only requested regions
PDCF->InitializeSpecifiedRegionList() ;
PDCF->AddSpecifiedRegion(0) ; // request this region to be extracted
// Clean the unused points from the polydata
vtkCleanPolyData *CPD = vtkCleanPolyData::New() ;
CPD->SetInput(PDCF->GetOutput()) ;
//----------------------------------------------------------------------------
// Extrusion Pipeline
//----------------------------------------------------------------------------
vtkALBAExtrudeToCircle *ETC = vtkALBAExtrudeToCircle::New() ;
ETC->SetInput(CPD->GetOutput()) ;
double direc[3] = {0.0, -1.0, 0.0} ;
ETC->SetDirection(direc) ;
ETC->GetOutput()->Update() ;
m_extrusion = vtkPolyData::New() ;
m_extrusion->DeepCopy(ETC->GetOutput()) ;
// render the data
if (renderingOn)
RenderExtrusion() ;
// delete vtk objects
fEdges1->Delete() ;
PDCF->Delete() ;
CPD->Delete() ;
ETC->Delete() ;
}
| 30.216667 | 147 | 0.570739 | [
"mesh",
"render",
"shape"
] |
75d923048c50bf227e28c0a7d4c9335426d1e559 | 4,499 | cpp | C++ | src/behavior.cpp | berlala/CarND-Path-Planning-Project | 684825bfcd24e0a5c8700ed6864e7287fad19d7f | [
"MIT"
] | null | null | null | src/behavior.cpp | berlala/CarND-Path-Planning-Project | 684825bfcd24e0a5c8700ed6864e7287fad19d7f | [
"MIT"
] | null | null | null | src/behavior.cpp | berlala/CarND-Path-Planning-Project | 684825bfcd24e0a5c8700ed6864e7287fad19d7f | [
"MIT"
] | null | null | null | //
// behavior.cpp
// In this file, the decision whether change lane or not will be made
//
#include "behavior.hpp"
int BehaviorPlanner::lanePlanner(double s, double d, vector<vector<double>> sensor_fusion) {
int lane = laneCalc(d);
int new_lane;
double distance = closestVehicle(s, lane, sensor_fusion, true)[0];
curr_lane = lane; // Keep the current lane to later calculate desired move
// check if blocked, i.e. car is within 20 meters
if (distance > 20) { // if lots of space, stay in lane and go near the speed limit,不变道
new_lane = lane;
target_vehicle_speed = 22 - 0.5;
avg_scores = {0,0,0}; // Reset average scores for laneScore()
return 0;
} else {//变道
new_lane = laneScore(s, lane, sensor_fusion);
vector <double> vehicle = closestVehicle(s, new_lane, sensor_fusion, true);
target_vehicle_speed = vehicle[1];
}
// Space between middle of each lane is four meters, so move accordingly
if (new_lane == lane) {
return 0;
} else if (new_lane < lane) {
return -4;
} else {
return 4;
}
}
int BehaviorPlanner::laneCalc(double d) {
// Check which lane the d-value comes from
// Left is 0, middle is 1, right is 2
//通过d判断当前所在的车道
int lane;
if (d < 4) {
lane = 0;
} else if (d < 8) {
lane = 1;
} else {
lane = 2;
}
return lane;
}
//某车道上最近车的距离和速度
vector<double> BehaviorPlanner::closestVehicle(double s, int lane, vector<vector<double>> sensor_fusion, bool direction) {
double dist = 10000;
double velocity = 22; // Set in case of no cars, 22.35m/s around 50 miles/hours
double vehicle_s;
double vehicle_d;
double vehicle_v;
int vehicle_lane;
// Check each vehicle in sensor range
for(int vehicle = 0; vehicle < sensor_fusion.size(); vehicle++) {
vehicle_s = sensor_fusion[vehicle][5]; // the car's s position in Frenet coordinate
vehicle_d = sensor_fusion[vehicle][6]; // the car's d position in Frenet coordinate
vehicle_v = sqrt(pow(sensor_fusion[vehicle][3], 2)+pow(sensor_fusion[vehicle][4], 2)); // currently velocity
vehicle_lane = laneCalc(vehicle_d);//被测车所在当前车道
if (vehicle_lane == lane) { // if same lane
if (direction == true) {
if (vehicle_s > s and (vehicle_s - s) < dist) { // and ahead of my vehicle
dist = vehicle_s - s;
velocity = vehicle_v;
}
} else {
if (s >= vehicle_s and (s - vehicle_s) < dist) { // if behind my vehicle
dist = s - vehicle_s;
velocity = vehicle_v;
}
}
}
}
if (dist <= 0) { // Avoid dividing by zero in laneScore()
dist = 1.0;
}
if (lane == curr_lane and direction == true) {
curr_lead_vehicle_speed = velocity;
}
return {dist, velocity};
}
int BehaviorPlanner::laneScore(double s, int lane, vector<vector<double>> sensor_fusion) {
vector <double> scores = {0,0,0};
vector <double> front_vehicle;
vector <double> back_vehicle;
for (int i = 0; i < 3; i++) {
if (i == lane) { // benefit to keeping lane 保持车道
scores[i] += 0.5;
}
front_vehicle = closestVehicle(s, i, sensor_fusion, true);
back_vehicle = closestVehicle(s, i, sensor_fusion, false);
if (front_vehicle[0] > 1000 and back_vehicle[0] > 1000) {
scores[i] += 5; // if wide open lane, move into that lane
} else {
if (front_vehicle[0] < 10) {
scores[i] -= 5; // if car too close in front, negative score
}
if (back_vehicle[0] < 10) {
scores[i] -= 5; // if car too close in back, negative score
}
scores[i] += 1 - (10/(front_vehicle[0]/3)); // benefit for large open distance in lane in front
scores[i] += 1 - (10/(back_vehicle[0]/3)); // benefit for large open distance in lane in back
scores[i] += 1 - (10/(front_vehicle[1]/2)); // benefit for faster car speed in lane in front
scores[i] += 1 / (back_vehicle[1]/2); // benefit for slower car speed in lane in back
}
// Simple in-exact calculation for scores over the last ten iterations
avg_scores[i] = (avg_scores[i] * 10) - avg_scores[i];
avg_scores[i] += scores[i];
avg_scores[i] /= 10;
}
// Only compare applicable lanes
if (lane == 0) {
return max_element(avg_scores.begin(), avg_scores.end() - 1) - avg_scores.begin();
} else if (lane == 1) {
return max_element(avg_scores.begin(), avg_scores.end()) - avg_scores.begin();
} else {
return max_element(avg_scores.begin() + 1, avg_scores.end()) - avg_scores.begin();
}
} | 34.607692 | 122 | 0.630807 | [
"vector"
] |
75dc02b333654d3e5ccc17b685c4676123a90f9c | 22,901 | cpp | C++ | src/terminal/Terminal.cpp | KeinR/Etermal | 9bf66f6be6ae8585b763dd902701e72013a5abcc | [
"MIT"
] | null | null | null | src/terminal/Terminal.cpp | KeinR/Etermal | 9bf66f6be6ae8585b763dd902701e72013a5abcc | [
"MIT"
] | null | null | null | src/terminal/Terminal.cpp | KeinR/Etermal | 9bf66f6be6ae8585b763dd902701e72013a5abcc | [
"MIT"
] | null | null | null | #include "Terminal.h"
#include <iostream>
#include <algorithm>
#include <cmath>
#include "util/termError.h"
#include "render/opengl.h"
#include "../TermInput.h"
#include "../EShell.h"
#include "State.h"
#include "codec.h"
#include "Line.h"
#include "Resources.h"
#include "util/debug.h"
#include "textmods/Mod.h"
#include "textmods/mods.h"
/**
* The default error callback.
* @param [in] error The error object
*/
static void defaultErrorCallback(const etm::termError &error);
void defaultErrorCallback(const etm::termError &error) {
std::cerr
<< "---------------------------\n"
<< "ETERMAL::TERMINAL::ERROR:\n"
<< "location = " << error.location << "\n"
<< "code = 0x" << std::hex << error.code << std::dec << " (dec = " << error.code << ")" << "\n"
<< "severe = " << (error.severe ? "TRUE" : "FALSE") << "\n"
<< "message = \"" << error.message << "\"\n"
<< "---------------------------\n";
}
etm::Terminal::Terminal(bool postponeInit):
Terminal(defaultErrorCallback, postponeInit)
{
}
etm::Terminal::Terminal(const std::shared_ptr<EtmFont> &font, bool postponeInit):
Terminal(defaultErrorCallback, postponeInit)
{
setFont(font);
}
etm::Terminal::Terminal(const errCallback_t &errorCallback, const std::shared_ptr<EtmFont> &font, bool postponeInit):
// Make sure that the provided callback is valid
Terminal(errorCallback ? errorCallback : defaultErrorCallback, postponeInit)
{
setFont(font);
}
etm::Terminal::Terminal(const errCallback_t &errorCallback, bool postponeInit):
errorCallback(errorCallback),
resources(new Resources(*this)),
viewport(0, 0, 100, 100),
scroll(resources),
scrollbar(resources, scroll),
scrollSensitivity(25.0f),
display(resources, scroll, 30),
background(resources),
focused(true),
takeInput(false),
escapeNext(false),
cursorBlink(500),
shell(nullptr),
dragging(false),
framebufValid(false),
isInit(false)
{
if (!postponeInit) {
init();
}
setBackgroundColor(0x080808);
setTextColor(0xf0f0f0);
scrollbar.setWidth(22);
scrollbar.setSideMargin(2);
scrollbar.setSliderColor(0xbababa);
scrollbar.setBarColor(0xf5f5f5);
// Wait for the shell to tell us that it wants input
display.setCursorEnabled(false);
if (!postponeInit) {
updatePosition();
}
}
etm::Terminal::~Terminal() {
if (resources != nullptr) {
delete resources;
}
}
etm::Terminal::Terminal(Terminal &&other):
// This is a terrible solution.
errorCallback(std::move(other.errorCallback)),
resources(std::move(other.resources)),
viewport(std::move(other.viewport)),
scroll(std::move(other.scroll)),
scrollbar(std::move(other.scrollbar)),
scrollSensitivity(std::move(other.scrollSensitivity)),
display(std::move(other.display)),
background(std::move(other.background)),
displayBuffer(std::move(other.displayBuffer)),
inputRequests(std::move(other.inputRequests)),
focused(std::move(other.focused)),
takeInput(std::move(other.takeInput)),
escapeNext(std::move(other.escapeNext)),
cursorBlink(std::move(other.cursorBlink)),
shell(std::move(other.shell)),
windowSetCursorDefault(std::move(other.windowSetCursorDefault)),
windowSetCursorIBeam(std::move(other.windowSetCursorIBeam)),
hovering(std::move(other.hovering)),
dragging(std::move(other.dragging)),
dragX(std::move(other.dragX)),
dragY(std::move(other.dragY)),
framebufValid(std::move(other.framebufValid)),
isInit(std::move(other.isInit))
{
finishMove(other);
}
etm::Terminal &etm::Terminal::operator=(Terminal &&other) {
errorCallback = std::move(other.errorCallback);
resources = std::move(other.resources);
viewport = std::move(other.viewport);
scroll = std::move(other.scroll);
scrollbar = std::move(other.scrollbar);
scrollSensitivity = std::move(other.scrollSensitivity);
display = std::move(other.display);
background = std::move(other.background);
displayBuffer = std::move(other.displayBuffer);
inputRequests = std::move(other.inputRequests);
focused = std::move(other.focused);
takeInput = std::move(other.takeInput);
escapeNext = std::move(other.escapeNext);
cursorBlink = std::move(other.cursorBlink);
shell = std::move(other.shell);
windowSetCursorDefault = std::move(other.windowSetCursorDefault);
windowSetCursorIBeam = std::move(other.windowSetCursorIBeam);
hovering = std::move(other.hovering);
dragging = std::move(other.dragging);
dragX = std::move(other.dragX);
dragY = std::move(other.dragY);
windowSetCursorIBeam = std::move(other.windowSetCursorIBeam);
framebufValid = std::move(other.framebufValid);
isInit = std::move(other.isInit);
finishMove(other);
return *this;
}
void etm::Terminal::finishMove(Terminal &other) {
other.resources = nullptr;
display.setScroll(scroll);
scrollbar.setScroll(scroll);
}
void etm::Terminal::init() {
resources->init();
isInit = true;
updatePosition();
}
void etm::Terminal::deInit() {
resources->deInit();
isInit = false;
}
void etm::Terminal::setFont(const std::shared_ptr<EtmFont> &font) {
resources->setFont(font);
scroll.setAlign(resources->getFont()->getCharHeight());
updatePosition();
}
void etm::Terminal::invalidate() {
framebufValid = false;
}
void etm::Terminal::validate() {
framebufValid = true;
}
void etm::Terminal::notifyScroll() {
scrollbar.update();
invalidate();
}
void etm::Terminal::initTex() {
if (isInit) {
resources->initTermTex(viewport.width, viewport.height);
}
}
bool etm::Terminal::ignoreCodepoint(const Line::codepoint &c) {
// Basically if it's a carrige return, we don't want it.
return c == '\r';
}
void etm::Terminal::prepareInput() {
// Cursor to the end of the text
display.jumpCursor();
// Lock the cursor's position so that it can't move backwards
display.lockCursor();
// Show it
display.setCursorEnabled(true);
}
bool etm::Terminal::acceptInput() {
return takeInput || inputRequests.size();
}
/// 0------------- streambuf overrides -----------------0
int etm::Terminal::sync() {
flush();
return 0;
}
std::streamsize etm::Terminal::showmanyc() {
return displayBuffer.size();
}
std::streamsize etm::Terminal::xsgetn(char *out, std::streamsize size) {
size = std::min(size, static_cast<std::streamsize>(displayBuffer.size()));
displayBuffer.copy(out, size);
displayBuffer.erase(0, size);
return size;
}
int etm::Terminal::underflow() {
if (displayBuffer.size()) {
return displayBuffer.back();
} else {
return std::char_traits<char>::eof();
}
}
int etm::Terminal::uflow() {
if (displayBuffer.size()) {
char c = displayBuffer.back();
displayBuffer.pop_back();
return c;
} else {
return std::char_traits<char>::eof();
}
}
int etm::Terminal::pbackfail(int c) {
if (std::char_traits<char>::eof() != c) {
displayBuffer.insert(displayBuffer.begin(), c);
}
return c;
}
std::streamsize etm::Terminal::xsputn(const char *s, std::streamsize n) {
displayBuffer.reserve(displayBuffer.size() + n);
for (std::streamsize i = 0; i < n; i++) {
displayBuffer.push_back(s[i]);
if (s[i] == '\n') {
flush();
}
}
return n;
}
int etm::Terminal::overflow(int c) {
if (std::char_traits<char>::eof() != c) {
displayBuffer.push_back(c);
if (c == '\n') {
flush();
}
}
return c;
}
/// 0------------- end streambuf overrides -----------------0
void etm::Terminal::pushInput(const std::string &input) {
display.setCursorEnabled(false);
// For convineince
typedef std::string::const_iterator iterator_t;
std::string filtered;
filtered.reserve(input.size());
bool escaped = false;
for (iterator_t it = input.begin(); it < input.end(); ++it) {
// Don't need to check for codepoint headers
// because a value of a header can only ever be < 128
// if it's a one-length ASCII char, and we only ever
// check ASCII chars.
if (escaped) {
escaped = false;
if (*it == '\n') {
filtered.push_back(' ');
} else {
filtered.push_back(*it);
}
} else if (*it == '\\') {
escaped = true;
} else {
filtered.push_back(*it);
}
}
if (inputRequests.size()) {
inputRequests.front()->terminalInput(filtered);
inputRequests.pop_front();
} else if (shell != nullptr) {
shell->input(filtered);
} else {
resources->postError(
"Terminal::flushInputBuffer()",
"Shell is nullptr (not set)",
0,
false
);
}
// Only re-enable the cursor if there are still input requests
if (acceptInput()) {
prepareInput();
}
}
void etm::Terminal::postError(const termError &error) {
errorCallback(error);
}
void etm::Terminal::setCursorDefault(const winActionCB_t &callback) {
windowSetCursorDefault = callback;
}
void etm::Terminal::setCursorIBeam(const winActionCB_t &callback) {
windowSetCursorIBeam = callback;
}
void etm::Terminal::setHovering(bool value) {
if (hovering != value) {
hovering = value;
if (hovering) {
if (windowSetCursorIBeam) {
windowSetCursorIBeam();
}
} else if (windowSetCursorDefault) {
windowSetCursorDefault();
}
}
}
void etm::Terminal::setErrorCallback(const errCallback_t &callback) {
if (callback) {
errorCallback = callback;
}
}
void etm::Terminal::clearInput() {
display.clearInput();
display.jumpCursor();
}
void etm::Terminal::clear() {
display.clear();
displayBuffer.clear();
displayBuffer.shrink_to_fit();
}
void etm::Terminal::setBackgroundColor(const Color &color) {
background.setColor(color);
display.setDefBackGColor(color);
}
void etm::Terminal::setTextColor(const Color &color) {
display.setDefForeGColor(color);
}
void etm::Terminal::setScrollSensitivity(float value) {
scrollSensitivity = value;
}
void etm::Terminal::setScrollCooldown(int millis) {
scrollbar.setScrollCooldown(millis);
}
void etm::Terminal::setScrollWait(int millis) {
scrollbar.setScrollWait(millis);
}
// The shell is where user input will be directed
void etm::Terminal::setShell(EShell &shell) {
this->shell = &shell;
}
void etm::Terminal::setTakeInput(bool value) {
if (takeInput != value) {
if (!acceptInput()) {
prepareInput();
}
takeInput = value;
}
}
void etm::Terminal::requestInput(TermInput &callback) {
if (!acceptInput()) {
prepareInput();
}
inputRequests.push_back(&callback);
}
void etm::Terminal::cancelInputRequest(TermInput *callback) {
typedef inputRequests_t::iterator it_t;
for (it_t it = inputRequests.begin(); it < inputRequests.end();) {
if (*it == callback) {
it = inputRequests.erase(it);
} else {
++it;
}
}
if (!acceptInput()) {
display.setCursorEnabled(false);
}
}
void etm::Terminal::clearInputRequests() {
inputRequests.clear();
if (!takeInput) {
display.setCursorEnabled(false);
}
}
std::string etm::Terminal::pollInput() {
return display.pollInput();
}
void etm::Terminal::dispText(const std::string &str) {
displayBuffer += str;
}
int etm::Terminal::readHexFromStr(const std::string &str, std::string::size_type &i) {
i++;
int result = 0;
for (std::string::size_type end = i + 6; i < str.size() && i < end && str[i] != ';'; i++) {
if ('0' <= str[i] && str[i] <= '9') {
// Shift one hex diget to the left for every new diget we find
result = (result * 16) + str[i] - '0';
} else {
// Sets to lowercase (kinda' a hack)
const char c = str[i] | 0x20;
if ('a' <= c && c <= 'f') {
result = (result * 16) + c - 'a' + 10;
} else {
break;
}
}
}
// Decriment so that is on the last char in the hex
i--;
return result;
}
void etm::Terminal::flush() {
softFlush();
// Disrupt the cursor
display.jumpCursor();
display.lockCursor();
}
void etm::Terminal::softFlush() {
constexpr char ESCAPE = '\x1b';
// Required when appending
display.prepare();
for (std::string::size_type i = 0; i < displayBuffer.size();) {
// Escape char
// 1 for the [, 1 for the spec (b/f)
if (displayBuffer[i] == ESCAPE && i + 2 < displayBuffer.size() && displayBuffer[i+1] == '[') {
std::string::size_type fi = i + 2;
std::shared_ptr<tm::Mod> mod;
switch (displayBuffer[fi]) {
case 'b':
mod = std::make_shared<tm::Background>(readHexFromStr(displayBuffer, fi));
break;
case 'f':
mod = std::make_shared<tm::Foreground>(readHexFromStr(displayBuffer, fi));
break;
case 'B':
mod = std::make_shared<tm::RevBackground>();
break;
case 'F':
mod = std::make_shared<tm::RevForeground>();
break;
case 'r':
mod = std::make_shared<tm::Revert>();
break;
}
if (mod) {
i = fi+1;
// Skip the optional semicolon
if (i < displayBuffer.size() && displayBuffer[i] == ';') {
i++;
}
display.pushMod(mod);
continue;
}
}
const int size = utf8::test(displayBuffer[i]);
if (i + size <= displayBuffer.size()) {
Line::codepoint c(displayBuffer.begin() + i, displayBuffer.begin() + (i + size));
display.append(c);
}
i += size;
}
displayBuffer.clear();
// Jump to end if the user is scrolled to the end
const bool jump = scroll.getOffset() + 1 >= scroll.getMaxOffset();
scroll.setGrossHeight(display.getHeight());
if (jump) {
scroll.jump();
}
scrollbar.update();
invalidate();
}
bool etm::Terminal::shouldUpdate() {
return !framebufValid || cursorBlink.hasEnded();
}
void etm::Terminal::setX(float x) {
viewport.x = x;
updatePosition();
}
void etm::Terminal::setY(float y) {
viewport.y = y;
updatePosition();
}
void etm::Terminal::setWidth(int width) {
viewport.width = width;
updatePosition();
}
void etm::Terminal::setHeight(int height) {
viewport.height = height;
updatePosition();
}
void etm::Terminal::setColumns(int columns) {
viewport.width = resources->getFont()->getCharWidth() * columns;
updatePosition();
}
void etm::Terminal::setRows(int rows, int margin) {
viewport.height = resources->getFont()->getCharHeight() * rows;
viewport.height += margin;
updatePosition();
}
void etm::Terminal::setFontSize(unsigned int size) {
resources->getFont()->setSize(size);
// Align to char height
scroll.setAlign(resources->getFont()->getCharHeight());
updatePosition();
}
void etm::Terminal::setMaxLines(TextBuffer::lines_number_t count) {
display.setMaxLines(count);
}
void etm::Terminal::updatePosition() {
background.setX(0);
background.setY(0);
background.setWidth(viewport.width - scrollbar.getWidth());
background.setHeight(viewport.height);
scrollbar.setX(0 + viewport.width - scrollbar.getWidth());
scrollbar.setY(0);
scrollbar.setHeight(viewport.height);
if (resources->getFont()) {
// Align net height to the character height
scroll.setNetHeight(viewport.height - (static_cast<int>(viewport.height) % resources->getFont()->getCharHeight()));
// Takes number of columns
display.setWidth(background.getWidth() / resources->getFont()->getCharWidth());
}
initTex();
invalidate();
}
void etm::Terminal::inputChar(unsigned int codepoint) {
std::string encoded = utf8::encode(codepoint);
Line::codepoint c(encoded.cbegin(), encoded.cend());
inputChar(c);
}
void etm::Terminal::inputChar(const Line::codepoint &c) {
if (acceptInput()) {
doInputChar(c);
// When inputting, scroll to focus on the input
// area, which is always at the bottom (or should be...)
scroll.setGrossHeight(display.getHeight());
scroll.jump();
scrollbar.update();
invalidate();
}
}
void etm::Terminal::doInputChar(const Line::codepoint &c) {
if (!ignoreCodepoint(c)) {
if (!escapeNext) {
switch (*c.start) {
case '\n': {
// Don't actually include the newline
// in the input
std::string input = display.pollInput();
display.append(c);
pushInput(input);
break;
}
case '\\': // Fallthrough
escapeNext = true;
default:
display.insertAtCursor(c);
}
} else {
escapeNext = false;
display.insertAtCursor(c);
}
invalidate();
}
}
void etm::Terminal::inputString(const std::string &text) {
for (std::string::const_iterator it = text.begin(); it < text.end();) {
if (!acceptInput()) break;
const int size = utf8::test(*it);
// Don't trust the offset given
if (it + size <= text.end()) {
Line::codepoint c(it, it + size);
inputChar(c);
}
it += size;
}
}
void etm::Terminal::inputActionKey(actionKey key) {
// Parts of the function depend on a valid shell
if (shell == nullptr) {
resources->postError(
"Terminal::inputActionKey(actionKey)",
"Shell is nullptr (not set)",
0,
false
);
return;
}
switch (key) {
case ENTER:
inputChar('\n');
break;
case BACKSPACE:
display.eraseAtCursor();
invalidate();
break;
case UP:
if (!display.moveCursorRow(-1)) {
shell->cursorUp();
}
break;
case DOWN:
if (!display.moveCursorRow(1)) {
shell->cursorDown();
}
break;
case LEFT:
display.moveCursorCollumnWrap(-1);
break;
case RIGHT:
display.moveCursorCollumnWrap(1);
break;
// Ignore if there's no match
}
}
void etm::Terminal::inputMouseScroll(float yOffset, float mouseX, float mouseY) {
if (viewport.hasPoint(mouseX, mouseY)) {
// Negate to align properly
scroll.scroll(-yOffset * scrollSensitivity);
}
}
void etm::Terminal::inputMouseClick(bool isPressed, float mouseX, float mouseY) {
mouseX -= viewport.x;
mouseY -= viewport.y;
scrollbar.mouseClick(isPressed, mouseX, mouseY);
if (isPressed) {
focused = background.hasPoint(mouseX, mouseY);
dragging = focused;
if (dragging) {
// Text highlighting
TextBuffer::lines_number_t row;
TextBuffer::line_index_t column;
mapCoords(mouseX, mouseY, row, column);
display.initSelection(row, column);
invalidate();
}
} else {
dragging = false;
}
}
void etm::Terminal::inputMouseMove(float mouseX, float mouseY) {
mouseX -= viewport.x;
mouseY -= viewport.y;
scrollbar.mouseMove(mouseX, mouseY);
setHovering(background.hasPoint(mouseX, mouseY));
if (dragging) {
// Text highlighting
TextBuffer::lines_number_t row;
TextBuffer::line_index_t column;
mapCoords(mouseX, mouseY, row, column);
display.setSelectionEnd(row, column);
invalidate();
}
}
void etm::Terminal::mapCoords(float x, float y, TextBuffer::lines_number_t &row, TextBuffer::line_index_t &column) {
row = std::max(std::floor((y + scroll.getOffset()) / resources->getFont()->getCharHeight()), 0.0f);
column = std::max(std::floor(x / resources->getFont()->getCharWidth()), 0.0f);
}
void etm::Terminal::render() {
// Preserve caller state (important!)
State state;
state.set();
resources->setTerminal(*this);
// Run animiations
if (cursorBlink.hasEnded()) {
display.toggleCursor();
cursorBlink.start();
}
scrollbar.animate();
// Render
if (!framebufValid) {
Framebuffer::State fbState;
// None of the called functions in this
// block should throw exceptions
GLint callerViewport[4];
glGetIntegerv(GL_VIEWPORT, callerViewport);
resources->bindTermFramebuffer();
glViewport(0, 0, viewport.width, viewport.height);
resources->initViewport();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Render
resources->bindPrimitiveShader();
background.render();
scrollbar.render();
// After scrollbar renders, the text shader is set
// due to the rendering of the triangle textures,
// so display doesn't need to set it.
display.render();
// Revalidate cache (important!)
validate();
glViewport(callerViewport[0], callerViewport[1], callerViewport[2], callerViewport[3]);
}
// We won't be changing the viewport
resources->initViewport();
resources->bindTextureShader();
resources->bindTermFramebufferTex();
viewport.set(resources);
resources->renderRectangle();
// Redering the cursor every time isn't a big deal,
// and we have to isolate it anyways because it's
// an animation
display.renderCursor(viewport.x, viewport.y);
// Check for errors
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
resources->postError(
"Terminal::render()",
std::string("OpenGL error - ") + getGLErrorStr(error),
error,
true
);
}
}
bool etm::Terminal::isFocused() {
return focused;
}
void etm::Terminal::setFocused(bool val) {
focused = val;
}
std::string etm::Terminal::getTextSelection() {
return display.getSelectionText();
}
std::string etm::Terminal::getText() {
return display.getTextFromRange(
TextBuffer::pos(0, 0),
TextBuffer::pos(display.getCountRows() + 1, 0)
);
}
| 28.203202 | 123 | 0.595913 | [
"render",
"object"
] |
75e1107137024b0051913bf9c60e73e588f937c9 | 27,485 | hpp | C++ | src/batteries/status.hpp | tonyastolfi/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-04T20:28:17.000Z | 2022-01-04T20:28:17.000Z | src/batteries/status.hpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 2 | 2020-06-04T14:02:24.000Z | 2020-06-04T14:03:18.000Z | src/batteries/status.hpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-03T20:24:31.000Z | 2022-01-03T20:24:31.000Z | // Copyright 2021 Anthony Paul Astolfi
//
#pragma once
#ifndef BATTERIES_STATUS_HPP
#define BATTERIES_STATUS_HPP
#include <batteries/assert.hpp>
#include <batteries/int_types.hpp>
#include <batteries/stream_util.hpp>
#include <batteries/strong_typedef.hpp>
#include <batteries/utility.hpp>
#include <boost/preprocessor/cat.hpp>
#include <atomic>
#include <cstring>
#include <limits>
#include <mutex>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <vector>
#ifdef BATT_GLOG_AVAILABLE
#include <glog/logging.h>
#endif // BATT_GLOG_AVAILABLE
namespace batt {
#ifdef BATT_STATUS_CUSTOM_MESSSAGES
#error This feature is not ready yet!
#endif
class StatusBase
{
public:
StatusBase() noexcept;
};
// Intentionally value-compatible with Abseil's StatusCode.
//
enum class StatusCode : int {
kOk = 0,
kCancelled = 1,
kUnknown = 2,
kInvalidArgument = 3,
kDeadlineExceeded = 4,
kNotFound = 5,
kAlreadyExists = 6,
kPermissionDenied = 7,
kResourceExhausted = 8,
kFailedPrecondition = 9,
kAborted = 10,
kOutOfRange = 11,
kUnimplemented = 12,
kInternal = 13,
kUnavailable = 14,
kDataLoss = 15,
kUnauthenticated = 16,
// ...
// This range reserved for future allocation of Abseil status codes.
// ...
kClosed = 100,
kGrantUnavailable = 101,
};
enum ErrnoValue {};
class BATT_WARN_UNUSED_RESULT Status;
class Status : private StatusBase
{
public:
BATT_STRONG_TYPEDEF(usize, PinGroup);
using value_type = i32;
static constexpr i32 kMaxCodeNumericRange = 0xffff;
static constexpr i32 kGroupSizeBits = 12 /*-> 4096*/;
static constexpr i32 kGroupSize = i32{1} << kGroupSizeBits;
static constexpr i32 kLocalMask = (i32{1} << kGroupSizeBits) - 1;
static constexpr i32 kGroupMask = ~kLocalMask;
static constexpr i32 kMaxGroups = 0x7fffff00l - kGroupSize;
struct CodeEntry {
value_type code;
int enum_value;
std::string message;
};
struct CodeGroup {
std::type_index enum_type_index{typeid(int)};
usize index;
int min_enum_value;
std::vector<usize> enum_value_to_code;
std::vector<CodeEntry> entries;
};
static const std::string& unknown_enum_value_message()
{
static const std::string s = "(Unknown enum value; not registered via batt::Status::register_codes)";
return s;
}
template <typename EnumT>
static const CodeGroup& code_group_for_type()
{
return code_group_for_type_internal<EnumT>();
}
template <typename EnumT>
static bool register_codes(const std::vector<std::pair<EnumT, std::string>>& codes);
static std::string_view message_from_code(value_type value)
{
const usize index_of_group = get_index_of_group(value);
const usize index_within_group = get_index_within_group(value);
{
std::unique_lock<std::mutex> lock{global_mutex()};
const auto& all_groups = registered_groups();
BATT_ASSERT_LT(index_of_group, all_groups.size());
BATT_ASSERT_LT(index_within_group, all_groups[index_of_group]->entries.size());
return all_groups[index_of_group]->entries[index_within_group].message;
}
}
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
// Construct a no-error status object.
//
Status() : Status(StatusCode::kOk)
{
}
// This is a regular copyable value type.
//
Status(const Status&) = default;
Status& operator=(const Status&) = default;
// Implicitly convert enumerated types to Status. The given type `EnumT` must have been registered
// via `Status::register_codes` prior to invoking this constructor.
//
template <typename EnumT, typename = std::enable_if_t<std::is_enum_v<EnumT>>>
/*implicit*/ Status(EnumT enum_value) noexcept
{
const CodeGroup& group = code_group_for_type<EnumT>();
BATT_ASSERT_GE(static_cast<int>(enum_value), group.min_enum_value);
const int index_within_enum = static_cast<int>(enum_value) - group.min_enum_value;
BATT_ASSERT_LT(index_within_enum, static_cast<int>(group.enum_value_to_code.size()))
<< BATT_INSPECT(group.index) << BATT_INSPECT(group.enum_type_index.name());
this->value_ = group.enum_value_to_code[index_within_enum];
#ifdef BATT_STATUS_CUSTOM_MESSSAGES
const usize index_within_group = get_index_within_group(this->value_);
this->message_ = group.entries[index_within_group].message;
#endif
}
#ifdef BATT_STATUS_CUSTOM_MESSSAGES
template <typename EnumT, typename = std::enable_if_t<std::is_enum_v<EnumT>>>
explicit Status(EnumT enum_value, const std::string_view& custom_message) noexcept : Status{enum_value}
{
this->message_ = custom_message;
}
#endif
bool ok() const noexcept BATT_WARN_UNUSED_RESULT
{
return (this->value_ & kLocalMask) == 0;
}
value_type code() const noexcept
{
return this->value_;
}
std::string_view message() const noexcept
{
#ifdef BATT_STATUS_CUSTOM_MESSSAGES
return this->message_;
#else
return message_from_code(this->value_);
#endif
}
const CodeGroup& group() const
{
const usize index_of_group = get_index_of_group(this->value_);
{
std::unique_lock<std::mutex> lock{global_mutex()};
const auto& all_groups = registered_groups();
BATT_ASSERT_LT(index_of_group, all_groups.size());
BATT_ASSERT_NOT_NULLPTR(all_groups[index_of_group]);
return *all_groups[index_of_group];
}
}
void IgnoreError() const noexcept
{
// do nothing
}
void Update(const Status& new_status)
{
if (this->ok()) {
*this = new_status;
}
}
private:
friend class StatusBase;
static usize next_group_index()
{
static std::atomic<i32> next_index{0};
return next_index.fetch_add(1);
}
static std::mutex& global_mutex()
{
static std::mutex m;
return m;
}
static std::vector<CodeGroup*>& registered_groups()
{
static std::vector<CodeGroup*> all_groups;
return all_groups;
}
template <typename EnumT>
static CodeGroup& code_group_for_type_internal()
{
static CodeGroup group;
return group;
}
static usize get_index_of_group(value_type value)
{
return (value & kGroupMask) >> kGroupSizeBits;
}
static usize get_index_within_group(value_type value)
{
return value & kLocalMask;
}
template <typename EnumT>
static bool register_codes_internal(const std::vector<std::pair<EnumT, std::string>>& codes);
value_type value_;
#ifdef BATT_STATUS_CUSTOM_MESSSAGES
std::string_view message_;
#endif
};
static_assert(sizeof(Status) <= sizeof(void*), "");
//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+---------------
inline std::ostream& operator<<(std::ostream& out, const Status& t)
{
return out << t.code() << ":" << t.message();
}
inline bool operator==(const Status& l, const Status& r)
{
return l.code() == r.code() || (l.ok() && r.ok());
}
inline bool operator!=(const Status& l, const Status& r)
{
return !(l == r);
}
inline Status OkStatus()
{
return Status{};
}
//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+---------------
template <typename T>
class BATT_WARN_UNUSED_RESULT StatusOr;
template <typename T>
class StatusOr
{
template <typename U>
friend class StatusOr;
public:
using value_type = T;
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
// Constructors
explicit StatusOr() noexcept : status_{StatusCode::kUnknown}
{
BATT_ASSERT(!this->ok());
}
/*implicit*/ StatusOr(const Status& s) : status_{s}
{
BATT_CHECK(!this->ok()) << "StatusOr must not be constructed with an Ok Status value.";
}
StatusOr(StatusOr&& that) : status_{StatusCode::kUnknown}
{
if (that.ok()) {
new (&this->storage_) T(std::move(that.value()));
this->status_ = OkStatus();
that.value().~T();
that.status_ = StatusCode::kUnknown;
} else {
this->status_ = std::move(that.status_);
}
}
StatusOr(const StatusOr& that) : status_{that.status_}
{
if (this->ok()) {
new (&this->storage_) T(that.value());
}
}
/*implicit*/ StatusOr(const T& obj) noexcept(noexcept(T(std::declval<const T&>()))) : status_{OkStatus()}
{
new (&this->storage_) T(obj);
}
/*implicit*/ StatusOr(T&& obj) noexcept(noexcept(T(std::declval<T&&>()))) : status_{OkStatus()}
{
new (&this->storage_) T(std::move(obj));
}
template <
typename U, typename = EnableIfNoShadow<StatusOr, U&&>,
typename = std::enable_if_t<!std::is_same_v<std::decay_t<U>, T> && std::is_constructible_v<T, U&&>>,
typename = void>
/*implicit*/ StatusOr(U&& obj) noexcept(noexcept(T(std::declval<U&&>()))) : status_{OkStatus()}
{
new (&this->storage_) T(BATT_FORWARD(obj));
}
template <typename U, typename = std::enable_if_t<!std::is_same_v<std::decay_t<U>, T> &&
std::is_constructible_v<T, U&&>>>
/*implicit*/ StatusOr(StatusOr<U>&& that) noexcept(noexcept(T(std::declval<U&&>())))
: status_{StatusCode::kUnknown}
{
if (that.status_.ok()) {
new (&this->storage_) T(std::move(that.value()));
this->status_ = OkStatus();
that.value().~U();
that.status_ = StatusCode::kUnknown;
} else {
this->status_ = std::move(that).status();
}
}
template <typename U, typename = std::enable_if_t<!std::is_same_v<std::decay_t<U>, T> &&
std::is_constructible_v<T, const U&>>>
/*implicit*/ StatusOr(const StatusOr<U>& that) noexcept(noexcept(T(std::declval<const U&>())))
: status_{StatusCode::kUnknown}
{
if (that.status_.ok()) {
new (&this->storage_) T(that.value());
this->status_ = OkStatus();
} else {
this->status_ = that.status_;
}
}
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
// Destructor
~StatusOr()
{
if (this->ok()) {
this->value().~T();
}
}
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
// Assignment operator overloads
StatusOr& operator=(T&& obj)
{
if (this->ok()) {
this->value().~T();
}
this->status_ = OkStatus();
new (&this->storage_) T(std::move(obj));
return *this;
}
StatusOr& operator=(const T& obj)
{
if (this->ok()) {
this->value().~T();
}
this->status_ = OkStatus();
new (&this->storage_) T(obj);
return *this;
}
template <typename U, typename = std::enable_if_t<!std::is_same_v<std::decay_t<U>, T> &&
std::is_constructible_v<T, U&&>>>
StatusOr& operator=(U&& obj) noexcept(noexcept(T(std::declval<U&&>())))
{
if (this->ok()) {
this->value().~T();
}
this->status_ = OkStatus();
new (&this->storage_) T(BATT_FORWARD(obj));
return *this;
}
StatusOr& operator=(const StatusOr& that) noexcept(
noexcept(T(std::declval<const T&>())) && noexcept(std::declval<T&>() = std::declval<const T&>()))
{
if (BATT_HINT_TRUE(this != &that)) {
if (this->ok()) {
if (that.ok()) {
this->value() = that.value();
} else {
this->value().~T();
}
} else {
if (that.ok()) {
new (&this->storage_) T(that.value());
}
}
this->status_ = that.status_;
}
return *this;
}
StatusOr& operator=(StatusOr&& that) noexcept(
noexcept(T(std::declval<T&&>())) && noexcept(std::declval<T&>() = std::move(std::declval<T&>())))
{
if (BATT_HINT_TRUE(this != &that)) {
if (this->ok()) {
if (that.ok()) {
this->value() = std::move(that.value());
} else {
this->value().~T();
}
} else {
if (that.ok()) {
new (&this->storage_) T(std::move(that.value()));
}
}
this->status_ = that.status_;
}
return *this;
}
StatusOr& operator=(const Status& new_status) noexcept
{
BATT_CHECK(!new_status.ok()) << "StatusOr must not be constructed with an Ok Status value.";
if (this->ok()) {
this->value().~T();
}
this->status_ = new_status;
return *this;
}
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
void IgnoreError() const noexcept
{
// do nothing
}
bool ok() const noexcept
{
return this->status_.ok();
}
const Status& status() const&
{
return this->status_;
}
T& value() noexcept
{
BATT_ASSERT(this->status_.ok()) << BATT_INSPECT(this->status_);
return *reinterpret_cast<T*>(&this->storage_);
}
const T& value() const noexcept
{
BATT_ASSERT(this->status_.ok()) << BATT_INSPECT(this->status_);
return *reinterpret_cast<const T*>(&this->storage_);
}
T& operator*() & noexcept
{
return this->value();
}
const T& operator*() const& noexcept
{
return this->value();
}
T operator*() && noexcept
{
return std::move(this->value());
}
const T* operator->() const noexcept
{
return &(this->value());
}
T* operator->() noexcept
{
return &(this->value());
}
private:
Status status_;
std::aligned_storage_t<sizeof(T), alignof(T)> storage_;
};
//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+---------------
// StatusOr<Status> == Status.
//
template <>
class StatusOr<Status> : public Status
{
public:
using Status::Status;
/*implicit*/ StatusOr(const Status& status) : Status{status}
{
}
/*implicit*/ StatusOr(Status&& status) : Status{std::move(status)}
{
}
};
static_assert(sizeof(Status) == sizeof(StatusOr<Status>), "");
//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+---------------
// StatusOr<StatusOr<T>> == StatusOr<T>
//
template <typename T>
class StatusOr<StatusOr<T>> : public StatusOr<T>
{
public:
using StatusOr<T>::StatusOr;
/*implicit*/ StatusOr(const StatusOr<T>& status_or) : StatusOr<T>{status_or}
{
}
/*implicit*/ StatusOr(StatusOr<T>&& status_or) : StatusOr<T>{std::move(status_or)}
{
}
};
static_assert(sizeof(StatusOr<StatusOr<int>>) == sizeof(StatusOr<int>), "");
//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+---------------
template <typename T, typename U, typename = std::enable_if_t<CanBeEqCompared<T, U>{}>>
inline bool operator==(const StatusOr<T>& l, const StatusOr<U>& r)
{
return (l.ok() && r.ok() && *l == *r) || (l.status() == r.status());
}
// If `T` (and `U`) can't be equality-compared, then we define StatusOr<T> to be equal iff the non-ok status
// values are equal.
//
template <typename T, typename U, typename = std::enable_if_t<!CanBeEqCompared<T, U>{}>, typename = void>
inline bool operator==(const StatusOr<T>& l, const StatusOr<U>& r)
{
return (!l.ok() && !r.ok() && l.status() == r.status());
}
template <typename T, typename U>
inline bool operator!=(const StatusOr<T>& l, const StatusOr<U>& r)
{
return !(l == r);
}
//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+---------------
template <typename T>
struct IsStatusOr_Impl : std::false_type {
};
template <typename T>
struct IsStatusOr_Impl<StatusOr<T>> : std::true_type {
};
template <typename T>
using IsStatusOr = IsStatusOr_Impl<std::decay_t<T>>;
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
template <typename T>
struct RemoveStatusOrImpl;
template <typename T>
struct RemoveStatusOrImpl<StatusOr<T>> : batt::StaticType<T> {
};
template <typename T>
using RemoveStatusOr = typename RemoveStatusOrImpl<T>::type;
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
inline bool is_ok_status(const std::error_code& ec)
{
return !ec;
}
template <typename T>
bool is_ok_status(const T& val)
{
return val.ok();
}
enum struct LogLevel { kFatal, kError, kWarning, kInfo, kDebug, kVerbose };
class NotOkStatusWrapper
{
public:
explicit NotOkStatusWrapper(const char* file, int line, Status&& status) noexcept
: file_{file}
, line_{line}
, status_(std::move(status))
{
*this << this->status_ << "; ";
}
explicit NotOkStatusWrapper(const char* file, int line, const Status& status) noexcept
: file_{file}
, line_{line}
, status_(status)
{
#ifndef BATT_GLOG_AVAILABLE
*this << "(" << this->file_ << ":" << this->line_ << ") ";
#endif // BATT_GLOG_AVAILALBE
*this << this->status_ << "; ";
}
~NotOkStatusWrapper() noexcept
{
#ifdef BATT_GLOG_AVAILABLE
switch (this->level_) {
case LogLevel::kFatal:
::google::LogMessage(this->file_, this->line_, google::GLOG_FATAL).stream()
<< this->output_.str();
break;
case LogLevel::kError:
::google::LogMessage(this->file_, this->line_, google::GLOG_ERROR).stream()
<< this->output_.str();
break;
case LogLevel::kWarning:
::google::LogMessage(this->file_, this->line_, google::GLOG_WARNING).stream()
<< this->output_.str();
break;
case LogLevel::kInfo:
::google::LogMessage(this->file_, this->line_, google::GLOG_INFO).stream() << this->output_.str();
break;
case LogLevel::kDebug:
DLOG(INFO) << " [" << this->file_ << ":" << this->line_ << "] " << this->output_.str();
break;
case LogLevel::kVerbose:
VLOG(1) << " [" << this->file_ << ":" << this->line_ << "] " << this->output_.str();
break;
}
#endif // BATT_GLOG_AVAILABLE
}
operator Status() noexcept
{
return std::move(this->status_);
}
template <typename T>
operator StatusOr<T>() noexcept
{
return StatusOr<T>{std::move(this->status_)};
}
NotOkStatusWrapper& operator<<(LogLevel new_level)
{
this->level_ = new_level;
return *this;
}
template <typename T>
NotOkStatusWrapper& operator<<(T&& val)
{
this->output_ << BATT_FORWARD(val);
return *this;
}
private:
const char* file_;
int line_;
Status status_;
LogLevel level_{LogLevel::kVerbose};
std::ostringstream output_;
};
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
inline Status to_status(const std::error_code& ec)
{
// TODO [tastolfi 2021-10-13] support these so we don't lose information.
(void)ec;
return Status{StatusCode::kInternal};
}
template <typename T, typename = std::enable_if_t<IsStatusOr<T>{}>>
inline decltype(auto) to_status(T&& v)
{
return BATT_FORWARD(v).status();
}
template <typename T, typename = std::enable_if_t<std::is_same_v<std::decay_t<T>, Status>>, typename = void>
inline decltype(auto) to_status(T&& s)
{
return BATT_FORWARD(s);
}
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
#define BATT_REQUIRE_OK(expr) \
if (!::batt::is_ok_status(expr)) \
return ::batt::NotOkStatusWrapper \
{ \
__FILE__, __LINE__, ::batt::to_status(BATT_FORWARD(expr)) \
}
#define BATT_ASSIGN_OK_RESULT(lvalue_expr, statusor_expr) \
auto BOOST_PP_CAT(BATTERIES_temp_StatusOr_result_, __LINE__) = statusor_expr; \
BATT_REQUIRE_OK(BOOST_PP_CAT(BATTERIES_temp_StatusOr_result_, __LINE__)); \
lvalue_expr = std::move(*BOOST_PP_CAT(BATTERIES_temp_StatusOr_result_, __LINE__))
#define BATT_OK_RESULT_OR_PANIC(expr) \
[&](auto&& status_or) { \
BATT_CHECK(status_or.ok()) << BATT_INSPECT(status_or.status()); \
return std::move(*BATT_FORWARD(status_or)); \
}(expr)
inline Status status_from_errno(int code)
{
return static_cast<ErrnoValue>(code);
}
template <typename T>
inline Status status_from_retval(T retval)
{
if (retval >= 0) {
return OkStatus();
}
return status_from_errno(errno);
}
template <typename T>
inline T&& ok_result_or_panic(StatusOr<T>&& result)
{
BATT_CHECK(result.ok()) << result.status();
return std::move(*result);
}
template <typename T, typename = std::enable_if_t<IsStatusOr<std::decay_t<T>>{} &&
!std::is_same_v<std::decay_t<T>, StatusOr<Status>>>>
std::ostream& operator<<(std::ostream& out, T&& status_or)
{
if (!status_or.ok()) {
return out << "Status{" << status_or.status() << "}";
}
return out << "Ok{" << make_printable(*status_or) << "}";
}
inline bool status_is_retryable(const Status& s)
{
return s == StatusCode::kUnavailable //
|| s == static_cast<ErrnoValue>(EAGAIN) //
|| s == static_cast<ErrnoValue>(EINTR) //
;
}
//#=##=##=#==#=#==#===#+==#+==========+==+=+=+=+=+=++=+++=+++++=-++++=-+++++++++++
inline StatusBase::StatusBase() noexcept
{
static bool initialized = [] {
Status::register_codes_internal<StatusCode>({
{StatusCode::kOk, "Ok"},
{StatusCode::kCancelled, "Cancelled"},
{StatusCode::kUnknown, "Unknown"},
{StatusCode::kInvalidArgument, "Invalid Argument"},
{StatusCode::kDeadlineExceeded, "Deadline Exceeded"},
{StatusCode::kNotFound, "Not Found"},
{StatusCode::kAlreadyExists, "Already Exists"},
{StatusCode::kPermissionDenied, "Permission Denied"},
{StatusCode::kResourceExhausted, "Resource Exhausted"},
{StatusCode::kFailedPrecondition, "Failed Precondition"},
{StatusCode::kAborted, "Aborted"},
{StatusCode::kOutOfRange, "Out of Range"},
{StatusCode::kUnimplemented, "Unimplemented"},
{StatusCode::kInternal, "Internal"},
{StatusCode::kUnavailable, "Unavailable"},
{StatusCode::kDataLoss, "Data Loss"},
{StatusCode::kUnauthenticated, "Unauthenticated"},
{StatusCode::kClosed, "Closed"},
{StatusCode::kGrantUnavailable, "The requested grant count exceeds available count"},
});
std::vector<std::pair<ErrnoValue, std::string>> errno_codes;
for (int code = 0; code < Status::kGroupSize; ++code) {
const char* msg = std::strerror(code);
if (msg) {
errno_codes.emplace_back(static_cast<ErrnoValue>(code), std::string(msg));
}
}
return Status::register_codes_internal<ErrnoValue>(errno_codes);
}();
BATT_ASSERT(initialized);
}
template <typename EnumT>
inline bool Status::register_codes(const std::vector<std::pair<EnumT, std::string>>& codes)
{
static StatusBase base;
return register_codes_internal<EnumT>(codes);
}
template <typename EnumT>
inline bool Status::register_codes_internal(const std::vector<std::pair<EnumT, std::string>>& codes)
{
static bool exactly_once = [&]() -> bool {
[&] {
CodeGroup group;
group.enum_type_index = std::type_index{typeid(EnumT)};
group.index = next_group_index();
BATT_CHECK_LT(group.index, kMaxGroups) << "Status::register_codes called too many times!";
if (codes.empty()) {
return;
}
int min_enum_value = std::numeric_limits<int>::max();
int max_enum_value = std::numeric_limits<int>::min();
Status::value_type next_code = group.index * kGroupSize;
for (auto& [value, message] : codes) {
const int enum_value = static_cast<int>(value);
min_enum_value = std::min(min_enum_value, enum_value);
max_enum_value = std::max(max_enum_value, enum_value);
group.entries.emplace_back(CodeEntry{
next_code,
enum_value,
std::move(message),
});
next_code += 1;
}
BATT_CHECK_LE(max_enum_value - min_enum_value, kMaxCodeNumericRange)
<< "The maximum numeric range of codes was exceeded. min_enum_value=" << min_enum_value
<< " max_enum_value=" << max_enum_value;
group.min_enum_value = min_enum_value;
group.enum_value_to_code.resize(max_enum_value - min_enum_value + 1);
std::fill(group.enum_value_to_code.begin(), group.enum_value_to_code.end(), next_code);
for (const CodeEntry& e : group.entries) {
group.enum_value_to_code[e.enum_value - group.min_enum_value] = e.code;
}
// Insert an entry at the end of the group for all unknown values.
//
group.entries.emplace_back(
CodeEntry{next_code, max_enum_value + 1, unknown_enum_value_message()});
// Atomically insert the new code group.
{
std::unique_lock<std::mutex> lock{Status::global_mutex()};
CodeGroup& global_group = Status::code_group_for_type_internal<EnumT>();
BATT_CHECK(global_group.entries.empty())
<< "A status code group may only be registered once!";
global_group = std::move(group);
std::vector<CodeGroup*>& all_groups = Status::registered_groups();
if (all_groups.size() < global_group.index + 1) {
all_groups.resize(global_group.index + 1);
}
all_groups[global_group.index] = &global_group;
}
// Done!
}();
return true;
}();
return exactly_once;
}
} // namespace batt
#endif // BATTERIES_STATUS_HPP
| 29.364316 | 110 | 0.550373 | [
"object",
"vector"
] |
75e808976dbd37bee9ca73caf6f7c872ffa5f133 | 1,172 | cc | C++ | Codeforces/260 Division 2/Problem A/A.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/260 Division 2/Problem A/A.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/260 Division 2/Problem A/A.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<set>
#include<vector>
#include<utility>
#include<queue>
#include<stack>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);
#define tr(x) cout<<x<<endl;
#define tr2(x,y) cout<<x<<" "<<y<<endl;
#define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl;
#define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl;
using namespace std;
int n, mx;
vector<pair<int, int> > l;
int main(){
sd(n);
for(int i = 0; i < n; i++){
int a, b;
sd2(a,b);
l.pb(mp(a,b));
}
sort(l.begin(), l.end());
mx = l[0].se;
for(int i = 1; i < n; i++){
if(l[i].se < mx){
puts("Happy Alex"); return 0;
}
mx = max(mx, l[i].se);
}
puts("Poor Alex");
return 0;
}
| 21.703704 | 79 | 0.587884 | [
"vector"
] |
75ebea6ea54618c9dba7d2d66cef97acb8397dcd | 2,481 | cpp | C++ | test/framework/net/net_exec_test_bm.cpp | baajur/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | [
"Apache-2.0"
] | 533 | 2018-05-18T06:14:04.000Z | 2022-03-23T11:46:30.000Z | test/framework/net/net_exec_test_bm.cpp | baajur/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | [
"Apache-2.0"
] | 100 | 2018-05-26T08:32:48.000Z | 2022-03-17T03:26:25.000Z | test/framework/net/net_exec_test_bm.cpp | baajur/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | [
"Apache-2.0"
] | 167 | 2018-05-18T06:14:35.000Z | 2022-02-14T01:44:20.000Z | #include <string>
#include "net_test.h"
#include "saber/funcs/timer.h"
#include "saber/core/tensor_op.h"
#include <chrono>
#include "debug.h"
#ifdef ENABLE_OP_TIMER
#include "saber/funcs/impl/impl_base.h"
#endif
std::string g_model_path = "";
std::string g_bmodel_path = "";
int g_batch_size = 1;
#ifdef USE_BM_PLACE
TEST(NetTest, net_execute_base_test) {
LOG(INFO) << "begin test";
auto ctx_p = std::make_shared<Context<BM>>();
ctx_p->set_bmodel_path(g_bmodel_path);
Graph<BM, Precision::FP32>* graph = new Graph<BM, Precision::FP32>();
LOG(WARNING) << "load anakin model file from " << g_model_path << " ...";
// load anakin model files.
auto status = graph->load(g_model_path);
if (!status) {
LOG(FATAL) << " [ERROR] " << status.info();
}
std::vector<std::string>& vin_name = graph->get_ins();
LOG(INFO) << "number of input tensor: " << vin_name.size();
for (int j = 0; j < vin_name.size(); ++j) {
graph->ResetBatchSize("input_0", g_batch_size);
}
graph->fusion_optimize();
Net<BM, Precision::FP32> net_executer(true);
#if 1
net_executer.fusion_init(*graph, ctx_p, true);
auto in_tensor_list = net_executer.get_in_list();
auto out_tensor_list = net_executer.get_out_list();
Tensor<BM> h_tensor_in;
for (int j = 0; j < vin_name.size(); ++j)
{
auto d_tensor_in_p = net_executer.get_in(vin_name[j]);
LOG(INFO) << "input name " << vin_name[j];
LOG(INFO) << "input tensor size: " << d_tensor_in_p->size();
auto shape_in = d_tensor_in_p->valid_shape();
for (int i = 0; i < shape_in.size(); i++) {
LOG(INFO) << "detect input_0 dims[" << i << "]" << shape_in[i];
}
}
net_executer.fusion_prediction();
#endif
delete graph;
}
int main(int argc, const char** argv) {
LOG(INFO)<< "usage:";
LOG(INFO)<< argv[0] << " <anakin model> <bmodel> <num> ";
LOG(INFO)<< " anakin model: path to anakin model";
LOG(INFO)<< " bmodel : path to bmodel";
LOG(INFO)<< " num: batchSize default to 1";
g_model_path = std::string(argv[1]);
g_bmodel_path = std::string(argv[2]);
if (argc > 3) {
g_batch_size = atoi(argv[3]);
}
Env<BM>::env_init();
// initial logger
logger::init(argv[0]);
InitTest();
RUN_ALL_TESTS(argv[0]);
return 0;
}
#else
int main(int argc, const char** argv) {
return 0;
}
#endif
| 26.393617 | 77 | 0.59734 | [
"vector",
"model"
] |
75f16253386ac1da8129ae6599db1816f1304059 | 335 | cpp | C++ | examples/automobile/main.cpp | 3dh-de/clean-code-r | 44053a4bca4f08a8ec17d1beff1394c7ecfd6d67 | [
"Unlicense"
] | null | null | null | examples/automobile/main.cpp | 3dh-de/clean-code-r | 44053a4bca4f08a8ec17d1beff1394c7ecfd6d67 | [
"Unlicense"
] | null | null | null | examples/automobile/main.cpp | 3dh-de/clean-code-r | 44053a4bca4f08a8ec17d1beff1394c7ecfd6d67 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include "auto.h"
using namespace std;
/**
* @brief main
* @return != 0 for any errors
*/
int main()
{
Auto *pVW = new VW();
if (!pVW) {
cerr << "Error: failed to initialize automobile object!" << endl;
return -1;
}
pVW->starten();
pVW->beschleunigen();
return 0;
}
| 13.4 | 73 | 0.546269 | [
"object"
] |
75f1ea6d991eaa31cba3e51ebea540714fc36bbd | 9,427 | cpp | C++ | src/cpu/CPU.cpp | MartensCedric/emuboy | 4dc7a774d77b9cde01a60509ad7e7a0e9477fdef | [
"MIT"
] | 1 | 2021-12-17T17:32:47.000Z | 2021-12-17T17:32:47.000Z | src/cpu/CPU.cpp | MartensCedric/gameboy | 4dc7a774d77b9cde01a60509ad7e7a0e9477fdef | [
"MIT"
] | null | null | null | src/cpu/CPU.cpp | MartensCedric/gameboy | 4dc7a774d77b9cde01a60509ad7e7a0e9477fdef | [
"MIT"
] | null | null | null | //
// Created by cedric on 2021-06-16.
//
#include "cpu/CPU.h"
#include <cstring>
#include <stdexcept>
#include <util/opcode_parsing_8bit_lsm.h>
#include <util/opcode_parsing_8bit_arithmetic.h>
#include <util/opcode_parsing_16bit_lsm.h>
#include <util/opcode_parsing_16bit_arithmetic.h>
#include <util/opcode_parsing_8bit_rotation_shifts.h>
#include <util/opcode_parsing_jump_calls.h>
#include <util/opcode_parsing_misc.h>
#include "safety.h"
#include "memory/memory_management_unit.h"
CPU::CPU() {
memset(this->registers, 0, NUM_REGISTERS);
this->stack_pointer = NUM_MEMORY_BYTES;
this->program_counter = 0x100;
this->arithmetic_unit = new ArithmeticUnit(this);
this->logic_unit = new LogicUnit(this);
this->shifting_unit = new ShiftingUnit(this);
register_8bit_rotation_shifts_opcodes(this);
register_16bit_arithmetic_opcodes(this);
register_8bit_arithmetic_opcodes(this);
register_jump_calls_opcodes(this);
register_16bit_lsm_opcodes(this);
register_8bit_lsm_opcodes(this);
register_misc_opcodes(this);
}
uint16_t CPU::get_program_counter() const {
return this->program_counter;
}
uint16_t CPU::get_stack_pointer() const {
return this->stack_pointer;
}
uint8_t CPU::fetch_byte() const {
return this->mmu[this->get_program_counter()];
}
uint8_t CPU::fetch_next_byte() {
if (this->should_increment_pc)
this->increment_pc();
return this->fetch_byte();
}
uint16_t CPU::fetch_word() const {
if (this->program_counter >= NUM_MEMORY_BYTES)
return static_cast<uint16_t>(fetch_byte());
uint8_t low_byte = this->mmu[this->program_counter];
uint8_t high_byte = this->mmu[this->program_counter + 1];
uint16_t word = (static_cast<uint16_t>(high_byte) << 8) + low_byte;
return word;
}
uint16_t CPU::fetch_next_word() {
uint8_t low_byte = fetch_next_byte();
uint8_t high_byte = fetch_next_byte();
uint16_t word = (static_cast<uint16_t>(high_byte) << 8) + low_byte;
return word;
}
void CPU::fetch_cycle() {
this->should_increment_pc = true;
this->process_opcode();
this->fetch_next_byte();
}
uint16_t CPU::next_opcode() const {
uint8_t first_byte = this->fetch_byte();
if (first_byte != 0xCB) {
return first_byte;
}
if (this->program_counter >= NUM_MEMORY_BYTES)
throw std::runtime_error("Rest of opcode out of bounds!");
uint16_t second_byte = this->mmu[this->program_counter + 1];
return (static_cast<uint16_t>(first_byte) << 8) + second_byte;
}
void CPU::process_opcode() {
bool opcode_executed = false;
for (std::vector<Opcode *>::iterator it = opcodes.begin(); it != opcodes.end() && !opcode_executed; it++) {
uint16_t opcode_word = this->next_opcode();
if ((*it)->should_execute(opcode_word)) {
(*it)->execute(this);
opcode_executed = true;
}
}
if (!opcode_executed) {
throw std::runtime_error("Could not find opcode!");
}
}
void CPU::jump_to_address(uint16_t address) {
this->program_counter = address;
this->should_increment_pc = false;
}
void CPU::increment_pc() {
this->increment_pc(1);
}
void CPU::increment_pc(uint16_t bytes_to_increment) {
this->program_counter += bytes_to_increment;
}
void CPU::load_16bit_register_immediate(uint8_t reg_x, uint16_t value) {
switch (reg_x) {
case REGISTER_AF_INDEX:
this->registers[REGISTER_A_INDEX] = static_cast<uint8_t>((value & 0xFF00) >> 8);
this->registers[REGISTER_F_INDEX] = static_cast<uint8_t>(value & 0x00FF);
break;
case REGISTER_BC_INDEX:
this->registers[REGISTER_B_INDEX] = static_cast<uint8_t>((value & 0xFF00) >> 8);
this->registers[REGISTER_C_INDEX] = static_cast<uint8_t>(value & 0x00FF);
break;
case REGISTER_DE_INDEX:
this->registers[REGISTER_D_INDEX] = static_cast<uint8_t>((value & 0xFF00) >> 8);
this->registers[REGISTER_E_INDEX] = static_cast<uint8_t>(value & 0x00FF);
break;
case REGISTER_HL_INDEX:
this->registers[REGISTER_H_INDEX] = static_cast<uint8_t>((value & 0xFF00) >> 8);
this->registers[REGISTER_L_INDEX] = static_cast<uint8_t>(value & 0x00FF);
break;
case REGISTER_SP_INDEX:
this->stack_pointer = value;
break;
default:
throw std::runtime_error("16bit register index out of bounds!");
}
}
void CPU::load_register_immediate(uint8_t reg_x, uint8_t value) {
validate_leq_than<uint8_t>(reg_x, 0x08);
this->registers[reg_x] = value;
}
void CPU::load_register_indirect(uint8_t reg_x, uint8_t reg_y) {
validate_leq_than<uint8_t>(reg_x, 0x08);
validate_leq_than<uint8_t>(reg_y, 0x08);
this->registers[reg_x] = this->registers[reg_y];
}
void CPU::load_memory_indirect(uint8_t reg_x, uint16_t memory_address) {
validate_leq_than<uint8_t>(reg_x, 0x08);
this->registers[reg_x] = this->mmu[memory_address];
}
void CPU::store_memory_indirect(uint16_t memory_address, uint8_t reg_x) {
validate_leq_than<uint8_t>(reg_x, 0x08);
this->mmu[memory_address] = this->registers[reg_x];
}
void CPU::store_memory_immediate(uint16_t memory_address, uint8_t value) {
this->mmu[memory_address] = value;
}
const uint8_t *CPU::get_registers() const {
return this->registers;
}
uint16_t CPU::get_16bit_register(uint8_t index) const {
switch (index) {
case REGISTER_AF_INDEX:
return ((static_cast<uint16_t>(this->registers[REGISTER_A_INDEX])) << 8) +
(static_cast<uint16_t>(this->registers[REGISTER_F_INDEX]));
case REGISTER_BC_INDEX:
return ((static_cast<uint16_t>(this->registers[REGISTER_B_INDEX])) << 8) +
(static_cast<uint16_t>(this->registers[REGISTER_C_INDEX]));
case REGISTER_DE_INDEX:
return ((static_cast<uint16_t>(this->registers[REGISTER_D_INDEX])) << 8) +
(static_cast<uint16_t>(this->registers[REGISTER_E_INDEX]));
case REGISTER_HL_INDEX:
return ((static_cast<uint16_t>(this->registers[REGISTER_H_INDEX])) << 8) +
(static_cast<uint16_t>(this->registers[REGISTER_L_INDEX]));
case REGISTER_SP_INDEX:
return this->stack_pointer;
default:
throw std::runtime_error("16bit register index out of bounds!");
}
}
void CPU::call(uint16_t address) {
this->push(this->get_program_counter() + 3);
this->jump_to_address(address);
}
void CPU::push(uint16_t value) {
this->mmu[--this->stack_pointer] = value & 0x00FF;
this->mmu[--this->stack_pointer] = (value & 0xFF00) >> 8;
}
uint16_t CPU::peek() const {
if (this->stack_pointer >= NUM_MEMORY_BYTES)
throw std::runtime_error("Stack pointer out of bounds");
uint16_t value = static_cast<uint16_t>(this->mmu[this->stack_pointer]) << 8;
value += this->mmu[this->stack_pointer + 1];
return value;
}
uint16_t CPU::pop() {
uint16_t value = peek();
this->stack_pointer += 2;
return value;
}
void CPU::stop() {
lcd_display_active = false;
cpu_active = false;
}
void CPU::halt() {
cpu_active = false;
}
void CPU::enable_interrupts() {
interrupts_enabled = true;
}
void CPU::disable_interrupts() {
interrupts_enabled = false;
}
void CPU::set_zero_flag(bool isOn) {
this->registers[REGISTER_F_INDEX] &= 0x7F;
this->registers[REGISTER_F_INDEX] |= (int(isOn) << 7);
}
void CPU::set_subtract_flag(bool isOn) {
this->registers[REGISTER_F_INDEX] &= 0xBF;
this->registers[REGISTER_F_INDEX] |= (int(isOn) << 6);
}
void CPU::set_half_carry_flag(bool isOn) {
this->registers[REGISTER_F_INDEX] &= 0xDF;
this->registers[REGISTER_F_INDEX] |= (int(isOn) << 5);
}
void CPU::set_carry_flag(bool isOn) {
this->registers[REGISTER_F_INDEX] &= 0xEF;
this->registers[REGISTER_F_INDEX] |= (int(isOn) << 4);
}
bool CPU::is_zero_flag_on() {
return this->registers[REGISTER_F_INDEX] & (1 << 7);
}
bool CPU::is_subtract_flag_on() {
return this->registers[REGISTER_F_INDEX] & (1 << 6);
}
bool CPU::is_half_carry_flag_on() {
return this->registers[REGISTER_F_INDEX] & (1 << 5);
}
bool CPU::is_carry_flag_on() {
return this->registers[REGISTER_F_INDEX] & (1 << 4);
}
ArithmeticUnit *CPU::get_arithmetic_unit() const {
return arithmetic_unit;
}
LogicUnit *CPU::get_logic_unit() const {
return logic_unit;
}
ShiftingUnit *CPU::get_shifting_unit() const {
return shifting_unit;
}
bool CPU::is_lcd_display_active() const {
return lcd_display_active;
}
bool CPU::is_cpu_active() const {
return cpu_active;
}
uint8_t CPU::get_byte_memory_indirect(uint8_t reg_x) {
return this->mmu[get_16bit_register(reg_x)];
}
uint16_t CPU::get_word_memory_indirect(uint8_t reg_x) {
throw std::runtime_error("Not implemented"); // todo: do this
}
void CPU::register_opcode(const char *name, std::function<bool(uint16_t)> opcode_condition,
std::function<void(CPU *)> opcode_execution) {
Opcode *opcode = new Opcode(name, opcode_condition, opcode_execution);
this->opcodes.push_back(opcode);
}
CPU::~CPU() {
for (std::vector<Opcode *>::iterator it = opcodes.begin(); it != opcodes.end(); it++) {
delete *it;
}
delete[] registers;
delete arithmetic_unit;
delete logic_unit;
}
| 29.006154 | 111 | 0.675719 | [
"vector"
] |
75f500cb4e5133df048fa9a51dca08e6983aacda | 3,558 | cpp | C++ | src/basis/structures/kdtree.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | 1 | 2021-09-16T10:15:50.000Z | 2021-09-16T10:15:50.000Z | src/basis/structures/kdtree.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | null | null | null | src/basis/structures/kdtree.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | null | null | null |
#include "kdtree.h"
#include "esinfo/envinfo.h"
#include "esinfo/eslog.h"
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cstdio>
#include <functional>
#include <utility>
using namespace mesio;
KDTree::KDTree(const std::vector<Point> &coordinates, size_t bucketsize)
: coordinates(coordinates)
{
if (coordinates.size()) {
min = coordinates.front();
max = coordinates.front();
for (size_t i = 1; i < coordinates.size(); ++i) {
min.x = std::min(coordinates[i].x, min.x);
min.y = std::min(coordinates[i].y, min.y);
min.z = std::min(coordinates[i].z, min.z);
max.x = std::max(coordinates[i].x, max.x);
max.y = std::max(coordinates[i].y, max.y);
max.z = std::max(coordinates[i].z, max.z);
}
}
build(bucketsize);
}
KDTree::KDTree(const std::vector<Point> &coordinates, Point &min, Point &max)
: coordinates(coordinates), min(min), max(max)
{
build();
}
void KDTree::build(size_t bucketsize)
{
auto compxyz = [&] (esint i, esint j) {
if (coordinates[i].x == coordinates[j].x) {
if (coordinates[i].y == coordinates[j].y) {
return coordinates[i].z < coordinates[j].z;
}
return coordinates[i].y < coordinates[j].y;
}
return coordinates[i].x < coordinates[j].x;
};
size = max - min;
permutation.resize(coordinates.size());
std::iota(permutation.begin(), permutation.end(), 0);
levels = coordinates.size() < bucketsize ? 0 : std::floor(std::log2(coordinates.size() / bucketsize));
splitters.resize(std::exp2(levels));
Point box = size; // uniform division (denoted by the level)
for (esint ll = 0, intervals = 1; ll < levels; ++ll, intervals *= 2) {
int splitter = box.x < box.y ? box.y < box.z ? 2 : 1 : box.x < box.z ? 2 : 0;
box[splitter] /= 2;
if(ll + 1 == levels){
this->leaf_intervals.resize(intervals);
}
#pragma omp parallel for
for (esint i = 0; i < intervals; ++i) {
esint index = std::exp2(ll) + i;
esint begin = this->begin(index);
esint end = this->end(index);
if(ll + 1 == levels){
this->leaf_intervals[i].begin = begin;
this->leaf_intervals[i].end = end;
}
splitters[index].d = splitter;
splitters[index].index = begin + (end - begin) / 2;
std::nth_element(permutation.begin() + begin, permutation.begin() + splitters[index].index, permutation.begin() + end, [&] (esint i, esint j) {
return coordinates[i][splitters[index].d] < coordinates[j][splitters[index].d];
});
if (end - begin) {
splitters[index].value = coordinates[permutation[splitters[index].index]][splitters[index].d];
}
while ( // move to the last coordinate with the same value as mid
splitters[index].index + 1 < end &&
coordinates[permutation[splitters[index].index]][splitters[index].d] == coordinates[permutation[splitters[index].index + 1]][splitters[index].d]) {
++splitters[index].index;
}
for (esint c = splitters[index].index + 2; c < end; ++c) { // there can be another in the rest of array
if (coordinates[permutation[splitters[index].index]][splitters[index].d] == coordinates[permutation[c]][splitters[index].d]) {
std::swap(permutation[++splitters[index].index], permutation[c--]);
}
}
splitters[index].index = std::min(splitters[index].index + 1, end);
if (ll + 1 == levels) {
std::sort(permutation.begin() + begin, permutation.begin() + splitters[index].index, compxyz);
std::sort(permutation.begin() + splitters[index].index, permutation.begin() + end, compxyz);
}
}
}
if (levels == 0) {
std::sort(permutation.begin(), permutation.end(), compxyz);
}
}
| 32.944444 | 152 | 0.646431 | [
"vector"
] |
2f0de65a9ca45b46e406a65a8d0d77cdd6a4db4f | 7,268 | cpp | C++ | src/s_curve/include/scurve_one_dof_coefs_and_sampling.cpp | mahmoud-a-ali/S_curve | 1a3a4041876bff0d3cb1e98d3a5f22531eeba236 | [
"MIT"
] | 1 | 2021-08-02T08:31:13.000Z | 2021-08-02T08:31:13.000Z | src/s_curve/include/scurve_one_dof_coefs_and_sampling.cpp | mahmoud-a-ali/S_curve | 1a3a4041876bff0d3cb1e98d3a5f22531eeba236 | [
"MIT"
] | null | null | null | src/s_curve/include/scurve_one_dof_coefs_and_sampling.cpp | mahmoud-a-ali/S_curve | 1a3a4041876bff0d3cb1e98d3a5f22531eeba236 | [
"MIT"
] | null | null | null | #include"scurve_equations.cpp"
//============================== one_dof_scurve_coef ===========================
/* the main function that will be called to compute the scurve coeffients for specific trajectory with specific max limits of Pos, Vel, Acc, Jrk
input argument:
P_wpt: waypoints, ref_T: reference time for the trajectory, sm: max_Pos, vm: max_vel, am: max_acc, jm: max_jerk
output_arg:
jrk: jrk per each segment in the path (whenever the direction changes we consider anew segment in the path)
traj_T: vector of times of the inflection points for each segment in scurve the scurve
*/
void compute_1dof_scurve_coef( std::vector<double> P_wpt, double ref_T, std::vector< std::vector<double> > &traj_T, std::vector<double> & jrk,
std::vector<double> &seg_idx, double sm, double vm, double am, double jm){
// std::cout<< " ====== one_dof_scurve_coef ============ "<< std::endl;
int n_pts = P_wpt.size(); // number of waypoints
//calculate n_traj per joint, when the direction is reversed, a new segment is considered
std::vector<double> trajs_idx;
trajs_idx.push_back(0);
int n_trajs=1;
for(int pt=0; pt<n_pts-1; pt++){
if( P_wpt[pt]*P_wpt[pt+1] < 0 ){
n_trajs++;
trajs_idx.push_back(pt);
}
}
trajs_idx.push_back(n_pts-1);
for(int seg=0; seg<trajs_idx.size() ; seg++)
seg_idx.push_back( P_wpt[trajs_idx[seg]] );
// std::cout<< "number of traj_segments (direction_change): "<< n_trajs << " index wpts: " << std::endl;
// variables
traj_T[0].resize(n_trajs); // Tj
traj_T[1].resize(n_trajs); // Ta
traj_T[2].resize(n_trajs); // Tv
traj_T[3].resize(n_trajs); // T
jrk.resize(n_trajs); // Jrk
std::vector<double> Ds;
std::vector<int> Ds_sgn;
Ds.resize(n_trajs);
Ds_sgn.resize(n_trajs);
// for each seg or change in dir
for (int trj=0; trj< n_trajs; trj++){
double p0 = P_wpt[ trajs_idx[trj] ];
double pf = P_wpt[ trajs_idx[trj+1] ];
Ds[trj]= pf - p0;
Ds_sgn[trj] = (Ds[trj] > 0) ? 1 : ((Ds[trj] < 0) ? -1 : 0);
if(fabs(Ds[trj])<=1e-5){
Ds[trj] = 0;
Ds_sgn[trj] = 0;
traj_T[0][trj]= 0;
traj_T[1][trj]= 0;
traj_T[2][trj]= 0;
traj_T[3][trj]= 0;
jrk[trj]= 0;
// std::cout<< "Ds["<< trj <<"] is zero ";
continue;
}
// std::cout<< "Ds["<< trj <<"]= " << Ds[trj];
double t = compute_time_for_jrk(fabs(Ds[trj]),traj_T[0][trj], traj_T[1][trj], traj_T[2][trj], sm, vm, am, jm );
traj_T[3][trj] = t;
jrk[trj] = Ds_sgn[trj]*jm;
}
if(ref_T > 0){
double T_opt = 0;
for (auto& t : traj_T[3]) //total optimal time for all phases (max_jek, max_vel, max_acc)
T_opt += t;
if( ref_T < T_opt)
throw(std::invalid_argument("reference time is less than optimal time"));
std::vector<double> DT;
DT.resize(n_trajs);
double dt = ref_T - T_opt;
// std::cout<< "ref_T, T_opt: "<< ref_T << " "<< T_opt <<std::endl;
for (int trj=0; trj< n_trajs; trj++){
DT[trj] = traj_T[3][trj]*dt / T_opt;
// std::cout<< "T, DT, Ds, Tj,Ta,Tv: "<< traj_T[3][trj]<<" "<< DT[trj]<<" "<< Ds[trj]<<" "<< traj_T[0][trj]<<" "<< traj_T[1][trj]<<" "<< traj_T[2][trj]<< std::endl;
jrk[trj]= Ds_sgn[trj]*compute_jerk_for_time( traj_T[3][trj], DT[trj], fabs(Ds[trj]), traj_T[0][trj], traj_T[1][trj], traj_T[2][trj], sm, vm, am, jm );
// std::cout<< "new_jrk: "<< jrk[trj] << std::endl << std::endl ;
}
}
}
//========================= Sample function ==========================
/* to make this implementation similar to the joint_trajectory_controller
it takes as input the coef computed by the one_dof_scurve_coef function
and calculate vel, acc, jrk at each sample, for each sample we get vector TPVA has time, vel, acc, jrk at this sample
*/
bool sample_1dof_scurve( double tg, std::vector<std::vector<double>> &traj_T, std::vector<double> &TPVA, std::vector<double> jrk, std::vector<double> seg_idx){
// which segment
// std::cout<< " ====== sample_scurve ============ "<< std::endl;
int n_trajs = jrk.size();
double T_tot = 0;
for (auto& t : traj_T[3])
T_tot += t;
if( tg<0 || tg> T_tot )
return false;
std::vector<double> t_idx;
t_idx.resize(n_trajs +1);
t_idx[0]=0;
double ts=0;
for (int trj=0; trj<n_trajs; trj++) {
ts += traj_T[3][trj];
t_idx[trj+1]=ts;
}
int traj_idx =0;
for (int trj=0; trj<n_trajs; trj++) {
if( tg> t_idx[trj] && tg<= t_idx[trj+1] )
traj_idx = trj;
}
// for(auto& p: t_idx)
// std::cout<< p <<std::endl;
double t = tg-t_idx[traj_idx];
// std::cout<< "tg: " << tg <<" t: " << t <<"traj_idx "<< traj_idx<<std::endl;
double P0=0, V0=0, A0=0;
// update ipts time
std::vector<double> T_ipt;
T_ipt.resize(8);
update_ip_time(T_ipt, traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx]);
// std::cout<< "time was updated "<<std::endl;
// for(auto& t: T_ipt)
// std::cout<< t <<std::endl;
// second update the ipt_time pos vel acc
std::vector<double> P_ipt, V_ipt, A_ipt;
P_ipt.resize(8);
V_ipt.resize(8);
A_ipt.resize(8);
update_ip_pos_vel_acc(P_ipt, V_ipt, A_ipt, T_ipt, jrk[traj_idx], P0, V0, A0);
// for(auto& p: P_ipt)
// std::cout<< p <<std::endl;
// which phase this traj segment located
// std::cout<< "PVA was updated "<<std::endl;
// std::cout<< "t: "<<t<< " jrk: "<< jrk[traj_idx]<<std::endl;
double p=0, v=0, a=0;
if( t>=T_ipt[0] && t<T_ipt[1])
phase_j1 ( traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx], P0, V0, A0, jrk[traj_idx], t, a, v, p);
else if(t<T_ipt[2])
phase_a1 ( traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx], P0, V0, A0, jrk[traj_idx], t, a, v, p);
else if(t<T_ipt[3])
phase_j2 ( traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx], P0, V0, A0, jrk[traj_idx], t, a, v, p);
else if(t<T_ipt[4])
phase_v ( traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx], P0, V0, A0, jrk[traj_idx], t, a, v, p);
else if(t<T_ipt[5])
phase_j3 ( traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx], P0, V0, A0, jrk[traj_idx], t, a, v, p);
else if(t<T_ipt[6])
phase_a2 ( traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx], P0, V0, A0, jrk[traj_idx], t, a, v, p);
else if(t<=T_ipt[7])
phase_j4 ( traj_T[0][traj_idx], traj_T[1][traj_idx], traj_T[2][traj_idx], P0, V0, A0, jrk[traj_idx], t, a, v, p);
else
return false;
TPVA[0]= t;
TPVA[1]= p + seg_idx[traj_idx];
TPVA[2]= v;
TPVA[3]= a;
return true;
}
| 42.752941 | 179 | 0.53481 | [
"vector"
] |
2f106fc9dd43810f8a1bd676f2e91a38dac8e17f | 7,008 | cpp | C++ | AnimationProgramming/AnimationClip.cpp | FelixPog/AnimationEngine | f153dfc10d7db075d559cfc6a5bfae78334dfb5a | [
"Apache-2.0"
] | null | null | null | AnimationProgramming/AnimationClip.cpp | FelixPog/AnimationEngine | f153dfc10d7db075d559cfc6a5bfae78334dfb5a | [
"Apache-2.0"
] | null | null | null | AnimationProgramming/AnimationClip.cpp | FelixPog/AnimationEngine | f153dfc10d7db075d559cfc6a5bfae78334dfb5a | [
"Apache-2.0"
] | null | null | null | #include "AnimationClip.h"
#include "Quaternion/Quaternion.h"
#include "Skeleton.h"
#include "Data.h"
#include "Interpolation.h"
#include "Engine.h"
// TRANSFORM
Transform::Transform(const LibMath::Vector3& pTranslation, const LibMath::Quaternion& pRotation)
{
translation = pTranslation;
rotation = pRotation;
}
Transform Transform::operator*(const Transform& other) const
{
Transform transform;
transform.translation = (other.rotation * this->translation) + other.translation;
transform.rotation = other.rotation * this->rotation;
return transform;
}
// KEY FRAME
KeyFrame::KeyFrame(const int keyIndex)
: m_index(keyIndex)
{}
void KeyFrame::InitTransform(const Skeleton* skeleton, KeyFrame* animationPose, const int boneIndex, const char* animName)
{
if (skeleton == nullptr || animationPose == nullptr)
{
return;
}
const Bone* bone = skeleton->GetBoneByIndex(boneIndex);
if (bone == nullptr || bone->IsIK())
{
return;
}
// TODO Replace by getting saved local transform
Transform bindPoseTransform;
GetSkeletonBoneLocalBindTransform(boneIndex, bindPoseTransform.translation.x, bindPoseTransform.translation.y, bindPoseTransform.translation.z, bindPoseTransform.rotation.W, bindPoseTransform.rotation.X, bindPoseTransform.rotation.Y, bindPoseTransform.rotation.Z);
Transform animTransform;
GetAnimLocalBoneTransform(animName, boneIndex, animationPose->GetIndex(), animTransform.translation.x, animTransform.translation.y, animTransform.translation.z, animTransform.rotation.W, animTransform.rotation.X, animTransform.rotation.Y, animTransform.rotation.Z);
animTransform = animTransform * bindPoseTransform;
if (boneIndex > 0)
{
const Transform& parentTransform = animationPose->GetTransform(bone->indexParent);
animTransform = animTransform * parentTransform;
}
animationPose->AddTransform(animTransform);
}
void KeyFrame::AddTransform(const Transform& transform)
{
m_transforms.emplace_back(transform);
}
int KeyFrame::GetIndex() const
{
return m_index;
}
const Transform& KeyFrame::GetTransform(const int boneIndex) const
{
return m_transforms[boneIndex];
}
// ANIMATION CLIP
void AnimationClip::Init(const Skeleton* skeleton, const char* name, const int duration)
{
if (skeleton == nullptr || name == nullptr)
{
return;
}
m_name = name;
m_keyCount = GetAnimKeyCount(name);
m_timeBetweenKey = static_cast<float>(duration) / static_cast<float>(m_keyCount);
m_timeBeforeNextKey = m_timeBetweenKey;
m_skeleton = skeleton;
for (size_t keyFrame = 0; keyFrame < m_keyCount; keyFrame++)
{
InitKeyFrame(m_skeleton, AddKeyFrame(keyFrame), name);
}
}
void AnimationClip::InitKeyFrame(const Skeleton* skeleton, KeyFrame* animationPose, const char* animName)
{
if (skeleton == nullptr || animationPose == nullptr || animName == nullptr)
{
return;
}
for (size_t boneIndex = 0; boneIndex < m_skeleton->GetBoneCount(); boneIndex++)
{
animationPose->InitTransform(skeleton, animationPose, boneIndex, animName);
}
}
KeyFrame* AnimationClip::AddKeyFrame(const int keyIndex)
{
m_keyFrames.emplace_back(keyIndex);
return &m_keyFrames[m_keyFrames.size() - 1];
}
const Transform& AnimationClip::GetBoneTransform(const int keyIndex, const int boneIndex) const
{
return m_keyFrames[keyIndex].GetTransform(boneIndex);
}
const std::string& AnimationClip::GetName() const
{
return m_name;
}
int AnimationClip::GetKeyCount() const
{
return m_keyCount;
}
int AnimationClip::GetKeyToDraw() const
{
return m_currentKeyToDraw;
}
float AnimationClip::GetInterpolateValue() const
{
return m_interpolateValue;
}
void AnimationClip::UpdateKeyToDraw(const float deltaTime)
{
m_timeBeforeNextKey -= deltaTime;
m_interpolateValue += deltaTime / m_timeBetweenKey;
while (m_timeBeforeNextKey <= 0.0f)
{
GoToNextKey();
m_interpolateValue -= 1.0f;
}
}
void AnimationClip::GoToNextKey()
{
m_currentKeyToDraw++;
if (m_currentKeyToDraw > static_cast<int>(m_keyCount) - 1)
{
m_currentKeyToDraw = 0;
}
m_timeBeforeNextKey += m_timeBetweenKey ;
}
void AnimationClip::DrawAnimSkeleton(const int keyToDraw)
{
if (m_skeleton == nullptr)
{
return;
}
for (size_t nbBone = 1; nbBone < m_skeleton->GetBoneCount(); nbBone++)
{
DrawAnimOneBoneSkeleton(keyToDraw, nbBone);
}
}
void AnimationClip::UpdateAnimMatrices(const float deltaTime)
{
if (m_skeleton == nullptr)
{
return;
}
m_animMatrices.clear();
m_animMatrices.reserve(61);
for (size_t nbBone = 0; nbBone < m_skeleton->GetBoneCount() - nb_of_ik_bone; nbBone++)
{
LibMath::Matrix4 matAnim = LibMath::Matrix4::Identity();
matAnim.Rotate(InterpolateRotation(m_currentKeyToDraw, nbBone, m_interpolateValue));
matAnim.Translate(InterpolateTranslation(m_currentKeyToDraw, nbBone, m_interpolateValue));
matAnim *= m_skeleton->GetBoneByIndex(nbBone)->inverseBindPose;
m_animMatrices.push_back(matAnim);
}
}
void AnimationClip::SendAnimMatricesToShader()
{
if (m_skeleton == nullptr)
{
return;
}
SetSkinningPose(reinterpret_cast<float*>(m_animMatrices.data()), m_skeleton->GetBoneCount() - nb_of_ik_bone);
}
const LibMath::Matrix4& AnimationClip::GetAnimMatrixByIndex(const int boneIndex) const
{
return m_animMatrices[boneIndex];
}
bool AnimationClip::HaveSameSkeleton(const AnimationClip& other) const
{
return m_skeleton == other.m_skeleton;
}
LibMath::Quaternion AnimationClip::InterpolateRotation(const int keyIndex, const int boneIndex, const float interpolateValue) const
{
LibMath::Quaternion firstKeyRotation = GetBoneTransform(keyIndex, boneIndex).rotation;
LibMath::Quaternion secondKeyRotation;
if (keyIndex == m_keyCount - 1)
{
secondKeyRotation = GetBoneTransform(0, boneIndex).rotation;
}
else
{
secondKeyRotation = GetBoneTransform(keyIndex + 1, boneIndex).rotation;
}
return LibMath::Interpolation::Slerp(firstKeyRotation, secondKeyRotation, m_interpolateValue);
}
LibMath::Vector3 AnimationClip::InterpolateTranslation(const int keyIndex, const int boneIndex, const float interpolateValue) const
{
LibMath::Vector3 firstKeyTranslation = GetBoneTransform(keyIndex, boneIndex).translation;
LibMath::Vector3 secondKeyTranslation;
if (keyIndex == m_keyCount - 1)
{
secondKeyTranslation = GetBoneTransform(0, boneIndex).translation;
}
else
{
secondKeyTranslation = GetBoneTransform(keyIndex + 1, boneIndex).translation;
}
return LibMath::Interpolation::Lerp(firstKeyTranslation, secondKeyTranslation, m_interpolateValue);
}
void AnimationClip::DrawAnimOneBoneSkeleton(const int indexKey, const int boneIndex)
{
if (m_skeleton == nullptr)
{
return;
}
const Bone* bone = m_skeleton->GetBoneByIndex(boneIndex);
if (bone == nullptr || bone->IsIK())
{
return;
}
const Transform& sqt = GetBoneTransform(indexKey, boneIndex);
const Transform& sqtParent = GetBoneTransform(indexKey, bone->indexParent);
DrawLine(sqt.translation.x, sqt.translation.y + y_offset, sqt.translation.z, sqtParent.translation.x, sqtParent.translation.y + y_offset, sqtParent.translation.z, 1, 0, 1);
}
| 25.67033 | 266 | 0.76484 | [
"transform"
] |
2f1b0ae4ce8eb2a9f894dd2bacb3670e46e94c84 | 875 | cpp | C++ | AutoFaceModifier/cubic_solver.cpp | TianYe2017/AutoWrappingToolBox | 7ea1088825772224a354aa3d24717bfa3cae936e | [
"MIT"
] | 1 | 2020-11-12T01:53:14.000Z | 2020-11-12T01:53:14.000Z | AutoFaceModifier/cubic_solver.cpp | TianYe2017/AutoWrappingToolBox | 7ea1088825772224a354aa3d24717bfa3cae936e | [
"MIT"
] | null | null | null | AutoFaceModifier/cubic_solver.cpp | TianYe2017/AutoWrappingToolBox | 7ea1088825772224a354aa3d24717bfa3cae936e | [
"MIT"
] | null | null | null | #include "cubic_solver.h"
using namespace std;
vector<float> SolveCubic(vector<float>coef)
{
vector<float> ans;
cv::solveCubic(coef, ans);
return ans;
}
vector<float> SolveForInverseRange(float a, float range, float y)
{
vector<float> coef = { a / (range*range), 2.0f * a / range, a - 1.0f, y };
vector<float> candiates;
cv::solveCubic(coef, candiates);
vector<float> ans;
for (int i = 0; i < candiates.size(); i++)
{
if (candiates[i] > 0.01f && candiates[i] < range)
{
ans.push_back(candiates[i]);
}
}
return ans;
}
void TestSCIR(void)
{
for (float a = -1.0f; a <= 1.0f; a += 0.1f)
{
for (float y = 0.0f; y <= 20.0f; y += 1.0f)
{
vector<float> v = SolveForInverseRange(a, 20.0f, y);
cout << "a: " << a << " y: " << y << endl;
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
cout << "" << endl;
}
}
} | 19.444444 | 75 | 0.557714 | [
"vector"
] |
2f1d1367a890b60616dde7ba5d1727a826c5e909 | 34,987 | cpp | C++ | src/modelmanager.cpp | wxthss82/openvino_model_server | 93541522d301163a130751e4b4d3d9c40d869f2b | [
"Apache-2.0"
] | null | null | null | src/modelmanager.cpp | wxthss82/openvino_model_server | 93541522d301163a130751e4b4d3d9c40d869f2b | [
"Apache-2.0"
] | null | null | null | src/modelmanager.cpp | wxthss82/openvino_model_server | 93541522d301163a130751e4b4d3d9c40d869f2b | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2020 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 "modelmanager.hpp"
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <memory>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <utility>
#include <vector>
#include <dlfcn.h>
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include <rapidjson/prettywriter.h>
#include <sys/stat.h>
#include "azurefilesystem.hpp"
#include "config.hpp"
#include "customloaders.hpp"
#include "filesystem.hpp"
#include "gcsfilesystem.hpp"
#include "localfilesystem.hpp"
#include "logging.hpp"
#include "pipeline.hpp"
#include "pipeline_factory.hpp"
#include "s3filesystem.hpp"
#include "schema.hpp"
namespace ovms {
static bool watcherStarted = false;
Status ModelManager::start() {
auto& config = ovms::Config::instance();
watcherIntervalSec = config.filesystemPollWaitSeconds();
Status status;
if (config.configPath() != "") {
status = startFromFile(config.configPath());
} else {
status = startFromConfig();
}
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Couldn't start model manager");
return status;
}
startWatcher();
return status;
}
void ModelManager::startWatcher() {
if ((!watcherStarted) && (watcherIntervalSec > 0)) {
std::future<void> exitSignal = exit.get_future();
std::thread t(std::thread(&ModelManager::watcher, this, std::move(exitSignal)));
watcherStarted = true;
monitor = std::move(t);
}
}
Status ModelManager::startFromConfig() {
auto& config = ovms::Config::instance();
auto [it, success] = servedModelConfigs.emplace(
config.modelName(),
ModelConfig{
config.modelName(),
config.modelPath(),
config.targetDevice(),
config.batchSize(),
config.nireq()});
if (!success) {
return StatusCode::UNKNOWN_ERROR;
}
ModelConfig& modelConfig = it->second;
auto status = modelConfig.parsePluginConfig(config.pluginConfig());
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Couldn't parse plugin config");
return status;
}
status = modelConfig.parseModelVersionPolicy(config.modelVersionPolicy());
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Couldn't parse model version policy. {}", status.string());
return status;
}
status = modelConfig.parseShapeParameter(config.shape());
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Couldn't parse shape parameter");
return status;
}
bool batchSizeSet = (modelConfig.getBatchingMode() != FIXED || modelConfig.getBatchSize() != 0);
bool shapeSet = (modelConfig.getShapes().size() > 0);
SPDLOG_DEBUG("Batch size set: {}, shape set: {}", batchSizeSet, shapeSet);
if (batchSizeSet && shapeSet) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "Both shape and batch size have been defined. Batch size parameter will be ignored.");
modelConfig.setBatchingMode(FIXED);
modelConfig.setBatchSize(0);
}
return reloadModelWithVersions(modelConfig);
}
Status ModelManager::startFromFile(const std::string& jsonFilename) {
Status status = loadConfig(jsonFilename);
if (!status.ok()) {
return status;
}
return StatusCode::OK;
}
void processNodeInputs(const std::string nodeName, const rapidjson::Value::ConstMemberIterator& itro, pipeline_connections_t& connections) {
for (const auto& nodeInput : itro->value.GetArray()) {
for (const auto& objectNameValue : nodeInput.GetObject()) {
const std::string inputName = objectNameValue.name.GetString();
const std::string sourceNodeName = objectNameValue.value.GetObject()["node_name"].GetString();
const std::string sourceOutputName = objectNameValue.value.GetObject()["data_item"].GetString();
SPDLOG_DEBUG("Creating node dependencies mapping request. Node: {} input: {} <- SourceNode: {} output: {}",
nodeName, inputName, sourceNodeName, sourceOutputName);
if (connections.find(nodeName) == connections.end()) {
connections[nodeName] = {
{sourceNodeName,
{{sourceOutputName, inputName}}}};
} else {
if (connections[nodeName].find(sourceNodeName) == connections[nodeName].end()) {
connections[nodeName].insert({sourceNodeName,
{{sourceOutputName, inputName}}});
} else {
connections[nodeName][sourceNodeName].push_back({sourceOutputName, inputName});
}
}
}
}
}
void processPipelineInputs(const rapidjson::Value::ConstMemberIterator& pipelineInputsPtr, const std::string& nodeName, std::unordered_map<std::string, std::string>& nodeOutputNameAlias, const std::string& pipelineName) {
for (const auto& pipelineInput : pipelineInputsPtr->value.GetArray()) {
const std::string pipelineInputName = pipelineInput.GetString();
SPDLOG_DEBUG("Mapping node:{} output:{}, under alias:{}",
nodeName, pipelineInputName, pipelineInputName);
auto result = nodeOutputNameAlias.insert({pipelineInputName, pipelineInputName});
if (!result.second) {
SPDLOG_ERROR("Pipeline {} has duplicated input declaration", pipelineName);
}
}
}
void processNodeOutputs(const rapidjson::Value::ConstMemberIterator& nodeOutputsItr, const std::string& nodeName, const std::string& modelName, std::unordered_map<std::string, std::string>& nodeOutputNameAlias) {
for (const auto& nodeOutput : nodeOutputsItr->value.GetArray()) {
const std::string modelOutputName = nodeOutput.GetObject()["data_item"].GetString();
const std::string nodeOutputName = nodeOutput.GetObject()["alias"].GetString();
SPDLOG_DEBUG("Mapping node: {} model_name: {} output: {}, under alias: {}",
nodeName, modelName, modelOutputName, nodeOutputName);
nodeOutputNameAlias[nodeOutputName] = modelOutputName;
}
}
void processPipelineConfig(rapidjson::Document& configJson, const rapidjson::Value& pipelineConfig, std::set<std::string>& pipelinesInConfigFile, PipelineFactory& factory, ModelManager& manager) {
const std::string pipelineName = pipelineConfig["name"].GetString();
SPDLOG_LOGGER_INFO(modelmanager_logger, "Reading pipeline: {} configuration", pipelineName);
auto itr2 = pipelineConfig.FindMember("nodes");
std::vector<NodeInfo> info{
{NodeKind::ENTRY, ENTRY_NODE_NAME}};
processPipelineInputs(pipelineConfig.FindMember("inputs"), ENTRY_NODE_NAME, info[0].outputNameAliases, pipelineName);
pipeline_connections_t connections;
for (const auto& nodeConfig : itr2->value.GetArray()) {
std::string nodeName;
nodeName = nodeConfig["name"].GetString();
std::string modelName;
modelName = nodeConfig["model_name"].GetString();
const std::string nodeKindStr = nodeConfig["type"].GetString();
auto nodeOutputsItr = nodeConfig.FindMember("outputs");
if (nodeOutputsItr == nodeConfig.MemberEnd() || !nodeOutputsItr->value.IsArray()) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "Pipeline: {} does not have valid outputs configuration", pipelineName);
return;
}
std::unordered_map<std::string, std::string> nodeOutputNameAlias; // key:alias, value realName
processNodeOutputs(nodeOutputsItr, nodeName, modelName, nodeOutputNameAlias);
std::optional<model_version_t> modelVersion;
if (nodeConfig.HasMember("version")) {
modelVersion = nodeConfig["version"].GetUint64();
} else {
modelVersion = std::nullopt;
}
NodeKind nodeKind;
auto status = toNodeKind(nodeKindStr, nodeKind);
if (!status.ok()) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "Parsing node kind failed: {}", nodeKindStr);
return;
}
SPDLOG_DEBUG("Creating node: {} type: {} model_name: {} modelVersion: {}",
nodeName, nodeKindStr, modelName, modelVersion.value_or(0));
info.emplace_back(std::move(NodeInfo{nodeKind, nodeName, modelName, modelVersion, nodeOutputNameAlias}));
auto nodeInputItr = nodeConfig.FindMember("inputs");
processNodeInputs(nodeName, nodeInputItr, connections);
}
const auto iteratorOutputs = pipelineConfig.FindMember("outputs");
// pipeline outputs are node exit inputs
processNodeInputs(EXIT_NODE_NAME, iteratorOutputs, connections);
info.emplace_back(std::move(NodeInfo(NodeKind::EXIT, EXIT_NODE_NAME, "", std::nullopt, {})));
if (!factory.definitionExists(pipelineName)) {
SPDLOG_DEBUG("Pipeline:{} was not loaded so far. Triggering load", pipelineName);
auto status = factory.createDefinition(pipelineName, info, connections, manager);
pipelinesInConfigFile.insert(pipelineName);
return;
}
SPDLOG_DEBUG("Pipeline:{} is already loaded. Triggering reload", pipelineName);
auto status = factory.reloadDefinition(pipelineName,
std::move(info),
std::move(connections),
manager);
pipelinesInConfigFile.insert(pipelineName);
}
Status ModelManager::loadPipelinesConfig(rapidjson::Document& configJson) {
const auto itrp = configJson.FindMember("pipeline_config_list");
if (itrp == configJson.MemberEnd() || !itrp->value.IsArray()) {
SPDLOG_LOGGER_INFO(modelmanager_logger, "Configuration file doesn't have pipelines property.");
pipelineFactory.retireOtherThan({}, *this);
return StatusCode::OK;
}
std::set<std::string> pipelinesInConfigFile;
for (const auto& pipelineConfig : itrp->value.GetArray()) {
processPipelineConfig(configJson, pipelineConfig, pipelinesInConfigFile, pipelineFactory, *this);
}
pipelineFactory.retireOtherThan(std::move(pipelinesInConfigFile), *this);
return ovms::StatusCode::OK;
}
Status ModelManager::createCustomLoader(CustomLoaderConfig& loaderConfig) {
auto& customloaders = ovms::CustomLoaders::instance();
std::string loaderName = loaderConfig.getLoaderName();
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Check if loader is already loaded");
if (customloaders.find(loaderName) == nullptr) {
// this is where library or custom loader is loaded
void* handleCL = dlopen(const_cast<char*>(loaderConfig.getLibraryPath().c_str()), RTLD_LAZY | RTLD_LOCAL);
if (!handleCL) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Cannot open library: {} {}", loaderConfig.getLibraryPath(), dlerror());
return StatusCode::CUSTOM_LOADER_LIBRARY_INVALID;
}
// load the symbols
createCustomLoader_t* customObj = (createCustomLoader_t*)dlsym(handleCL, "createCustomLoader");
const char* dlsym_error = dlerror();
if (dlsym_error || (customObj == nullptr)) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Cannot load symbol create: {} ", dlsym_error);
return StatusCode::CUSTOM_LOADER_LIBRARY_LOAD_FAILED;
}
std::shared_ptr<CustomLoaderInterface> customLoaderIfPtr{customObj()};
try {
customLoaderIfPtr->loaderInit(loaderConfig.getLoaderConfigFile());
} catch (std::exception& e) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Cannot create or initialize the custom loader. Failed with error {}", e.what());
return StatusCode::CUSTOM_LOADER_INIT_FAILED;
} catch (...) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Cannot create or initialize the custom loader");
return StatusCode::CUSTOM_LOADER_INIT_FAILED;
}
customloaders.add(loaderName, customLoaderIfPtr, handleCL);
} else {
// Loader is already in the existing loaders. Move it to new loaders.
// Reload of customloader is not supported yet
customloaders.move(loaderName);
}
return StatusCode::OK;
}
Status ModelManager::loadCustomLoadersConfig(rapidjson::Document& configJson) {
const auto itrp = configJson.FindMember("custom_loader_config_list");
if (itrp == configJson.MemberEnd() || !itrp->value.IsArray()) {
return StatusCode::OK;
}
// Load Customer Loaders as per the configuration
SPDLOG_DEBUG("Using Customloader");
for (const auto& configs : itrp->value.GetArray()) {
const std::string loaderName = configs["config"]["loader_name"].GetString();
SPDLOG_INFO("Reading Custom Loader: {} configuration", loaderName);
CustomLoaderConfig loaderConfig;
auto status = loaderConfig.parseNode(configs["config"]);
if (status != StatusCode::OK) {
SPDLOG_ERROR("Parsing loader: {} config failed", loaderName);
return status;
}
auto retVal = createCustomLoader(loaderConfig);
if (retVal != StatusCode::OK) {
SPDLOG_ERROR("Creation of loader: {} failed", loaderName);
}
}
// All loaders are the done. Finalize the list by deleting removed loaders in config
auto& customloaders = ovms::CustomLoaders::instance();
customloaders.finalize();
return ovms::StatusCode::OK;
}
Status ModelManager::loadModelsConfig(rapidjson::Document& configJson, std::vector<ModelConfig>& gatedModelConfigs) {
const auto itr = configJson.FindMember("model_config_list");
if (itr == configJson.MemberEnd() || !itr->value.IsArray()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Configuration file doesn't have models property.");
return StatusCode::JSON_INVALID;
}
std::set<std::string> modelsInConfigFile;
std::unordered_map<std::string, ModelConfig> newModelConfigs;
for (const auto& configs : itr->value.GetArray()) {
ModelConfig modelConfig;
auto status = modelConfig.parseNode(configs["config"]);
const auto modelName = modelConfig.getName();
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Parsing model: {} config failed", modelName);
continue;
}
if (pipelineDefinitionExists(modelName)) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Model name: {} is already occupied by pipeline definition.", modelName);
continue;
}
if (modelsInConfigFile.find(modelName) != modelsInConfigFile.end()) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "Duplicated model names: {} defined in config file. Only first definition will be loaded.", modelName);
continue;
}
status = reloadModelWithVersions(modelConfig);
modelsInConfigFile.emplace(modelName);
if (!status.ok()) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Cannot reload model: {} with versions due to error: {}", modelName, status.string());
}
if (status != StatusCode::REQUESTED_DYNAMIC_PARAMETERS_ON_SUBSCRIBED_MODEL) {
newModelConfigs.emplace(modelName, std::move(modelConfig));
} else {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Will retry to reload model({}) after pipelines are revalidated", modelName);
auto it = this->servedModelConfigs.find(modelName);
if (it == this->servedModelConfigs.end()) {
continue;
}
gatedModelConfigs.emplace_back(std::move(modelConfig));
newModelConfigs.emplace(modelName, std::move(it->second));
this->servedModelConfigs.erase(modelName);
}
}
this->servedModelConfigs = std::move(newModelConfigs);
retireModelsRemovedFromConfigFile(modelsInConfigFile);
return ovms::StatusCode::OK;
}
Status ModelManager::tryReloadGatedModelConfigs(std::vector<ModelConfig>& gatedModelConfigs) {
for (auto& modelConfig : gatedModelConfigs) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Trying to reload model({}) configuration", modelConfig.getName());
auto status = reloadModelWithVersions(modelConfig);
if (!status.ok()) {
continue;
}
auto it = this->servedModelConfigs.find(modelConfig.getName());
if (it == this->servedModelConfigs.end()) {
continue;
}
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Successfully retried to load new model({}) configuration after unsubscribed from pipeline", modelConfig.getName());
this->servedModelConfigs.at(modelConfig.getName()) = std::move(modelConfig);
}
return StatusCode::OK;
}
Status ModelManager::loadConfig(const std::string& jsonFilename) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Loading configuration from {}", jsonFilename);
std::ifstream ifs(jsonFilename.c_str());
if (!ifs.good()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "File is invalid {}", jsonFilename);
return StatusCode::FILE_INVALID;
}
rapidjson::Document configJson;
rapidjson::IStreamWrapper isw(ifs);
if (configJson.ParseStream(isw).HasParseError()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Configuration file is not a valid JSON file.");
return StatusCode::JSON_INVALID;
}
if (validateJsonAgainstSchema(configJson, MODELS_CONFIG_SCHEMA) != StatusCode::OK) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Configuration file is not in valid configuration format");
return StatusCode::JSON_INVALID;
}
configFilename = jsonFilename;
Status status;
// load the custom loader config, if available
status = loadCustomLoadersConfig(configJson);
if (status != StatusCode::OK) {
return status;
}
std::vector<ModelConfig> gatedModelConfigs;
status = loadModelsConfig(configJson, gatedModelConfigs);
if (status != StatusCode::OK) {
return status;
}
status = loadPipelinesConfig(configJson);
tryReloadGatedModelConfigs(gatedModelConfigs);
return StatusCode::OK;
}
void ModelManager::retireModelsRemovedFromConfigFile(const std::set<std::string>& modelsExistingInConfigFile) {
std::set<std::string> modelsCurrentlyLoaded;
for (auto& nameModelPair : getModels()) {
modelsCurrentlyLoaded.insert(nameModelPair.first);
}
std::vector<std::string> modelsToUnloadAllVersions(getModels().size());
auto it = std::set_difference(
modelsCurrentlyLoaded.begin(), modelsCurrentlyLoaded.end(),
modelsExistingInConfigFile.begin(), modelsExistingInConfigFile.end(),
modelsToUnloadAllVersions.begin());
modelsToUnloadAllVersions.resize(it - modelsToUnloadAllVersions.begin());
for (auto& modelName : modelsToUnloadAllVersions) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Retiring all versions of model: {}", modelName);
try {
models.at(modelName)->retireAllVersions();
} catch (const std::out_of_range& e) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Unknown error occurred when tried to retire all versions of model: {}", modelName);
}
}
}
void ModelManager::updateConfigurationWithoutConfigFile() {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Checking if something changed with model versions");
for (auto& [name, config] : servedModelConfigs) {
reloadModelWithVersions(config);
}
pipelineFactory.revalidatePipelines(*this);
}
void ModelManager::watcher(std::future<void> exit) {
SPDLOG_LOGGER_INFO(modelmanager_logger, "Started config watcher thread");
int64_t lastTime;
struct stat statTime;
stat(configFilename.c_str(), &statTime);
lastTime = statTime.st_ctime;
while (exit.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout) {
std::this_thread::sleep_for(std::chrono::seconds(watcherIntervalSec));
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Watcher thread check cycle begin");
stat(configFilename.c_str(), &statTime);
if (lastTime != statTime.st_ctime) {
lastTime = statTime.st_ctime;
loadConfig(configFilename);
}
updateConfigurationWithoutConfigFile();
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Watcher thread check cycle end");
}
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Exited config watcher thread");
}
void ModelManager::join() {
if (watcherStarted) {
exit.set_value();
if (monitor.joinable()) {
monitor.join();
watcherStarted = false;
}
}
}
void ModelManager::getVersionsToChange(
const ModelConfig& newModelConfig,
const std::map<model_version_t, std::shared_ptr<ModelInstance>>& modelVersionsInstances,
model_versions_t requestedVersions,
std::shared_ptr<model_versions_t>& versionsToStartIn,
std::shared_ptr<model_versions_t>& versionsToReloadIn,
std::shared_ptr<model_versions_t>& versionsToRetireIn) {
std::sort(requestedVersions.begin(), requestedVersions.end());
model_versions_t registeredModelVersions;
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Currently registered model: {} versions count: {}", newModelConfig.getName(), modelVersionsInstances.size());
for (const auto& [version, versionInstance] : modelVersionsInstances) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "model: {} version: {} state: {}", newModelConfig.getName(), version, ovms::ModelVersionStateToString(versionInstance->getStatus().getState()));
registeredModelVersions.push_back(version);
}
model_versions_t alreadyRegisteredVersionsWhichAreRequested(requestedVersions.size());
model_versions_t::iterator it = std::set_intersection(
requestedVersions.begin(), requestedVersions.end(),
registeredModelVersions.begin(), registeredModelVersions.end(),
alreadyRegisteredVersionsWhichAreRequested.begin());
alreadyRegisteredVersionsWhichAreRequested.resize(it - alreadyRegisteredVersionsWhichAreRequested.begin());
std::shared_ptr<model_versions_t> versionsToReload = std::make_shared<model_versions_t>();
for (const auto& version : alreadyRegisteredVersionsWhichAreRequested) {
try {
if (modelVersionsInstances.at(version)->getStatus().willEndUnloaded() ||
modelVersionsInstances.at(version)->getModelConfig().isReloadRequired(newModelConfig)) {
versionsToReload->push_back(version);
}
} catch (std::out_of_range& e) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Data race occured during versions update. Could not found version. Details: {}", e.what());
}
}
std::shared_ptr<model_versions_t> versionsToRetire = std::make_shared<model_versions_t>(registeredModelVersions.size());
it = std::set_difference(
registeredModelVersions.begin(), registeredModelVersions.end(),
requestedVersions.begin(), requestedVersions.end(),
versionsToRetire->begin());
versionsToRetire->resize(it - versionsToRetire->begin());
try {
it = std::remove_if(versionsToRetire->begin(),
versionsToRetire->end(),
[&modelVersionsInstances](model_version_t version) {
return modelVersionsInstances.at(version)->getStatus().willEndUnloaded();
});
} catch (std::out_of_range& e) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Data race occured during versions update. Could not found version. Details: {}", e.what());
}
versionsToRetire->resize(it - versionsToRetire->begin());
std::shared_ptr<model_versions_t> versionsToStart = std::make_shared<model_versions_t>(requestedVersions.size());
it = std::set_difference(
requestedVersions.begin(), requestedVersions.end(),
registeredModelVersions.begin(), registeredModelVersions.end(),
versionsToStart->begin());
versionsToStart->resize(it - versionsToStart->begin());
versionsToStartIn = std::move(versionsToStart);
versionsToReloadIn = std::move(versionsToReload);
versionsToRetireIn = std::move(versionsToRetire);
}
std::shared_ptr<ovms::Model> ModelManager::getModelIfExistCreateElse(const std::string& modelName) {
std::unique_lock modelsLock(modelsMtx);
auto modelIt = models.find(modelName);
if (models.end() == modelIt) {
models.insert({modelName, modelFactory(modelName)});
}
return models[modelName];
}
std::shared_ptr<FileSystem> ModelManager::getFilesystem(const std::string& basePath) {
if (basePath.rfind(S3FileSystem::S3_URL_PREFIX, 0) == 0) {
Aws::SDKOptions options;
Aws::InitAPI(options);
return std::make_shared<S3FileSystem>(options, basePath);
}
if (basePath.rfind(GCSFileSystem::GCS_URL_PREFIX, 0) == 0) {
return std::make_shared<ovms::GCSFileSystem>();
}
if (basePath.rfind(AzureFileSystem::AZURE_URL_FILE_PREFIX, 0) == 0) {
return std::make_shared<ovms::AzureFileSystem>();
}
if (basePath.rfind(AzureFileSystem::AZURE_URL_BLOB_PREFIX, 0) == 0) {
return std::make_shared<ovms::AzureFileSystem>();
}
return std::make_shared<LocalFileSystem>();
}
Status ModelManager::readAvailableVersions(std::shared_ptr<FileSystem>& fs, const std::string& base, model_versions_t& versions) {
files_list_t dirs;
bool is_directory = false;
if (FileSystem::isPathEscaped(base)) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Path {} escape with .. is forbidden.", base);
return StatusCode::PATH_INVALID;
}
auto status = fs->isDirectory(base, &is_directory);
if (status != StatusCode::OK) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Couldn't check directory: {}", base);
return status;
}
if (!is_directory) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Directory does not exist: {}", base);
return StatusCode::PATH_INVALID;
}
status = fs->getDirectorySubdirs(base, &dirs);
if (status != StatusCode::OK) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Couldn't list directories in path: {}", base);
return status;
}
for (const auto& entry : dirs) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Detected version folder: {}", entry);
try {
ovms::model_version_t version = std::stoll(entry);
if (version <= 0) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "Expected version directory name to be a number greater than 0. Got: {}", version);
continue;
}
versions.push_back(version);
} catch (const std::invalid_argument& e) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "Expected version directory name to be in number format. Got: {}", entry);
} catch (const std::out_of_range& e) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Directory name is out of range for supported version format. Got: {}", entry);
}
}
if (0 == versions.size()) {
SPDLOG_LOGGER_WARN(modelmanager_logger, "No version found for model in path: {}", base);
return StatusCode::NO_MODEL_VERSION_AVAILABLE;
}
return StatusCode::OK;
}
Status ModelManager::addModelVersions(std::shared_ptr<ovms::Model>& model, std::shared_ptr<FileSystem>& fs, ModelConfig& config, std::shared_ptr<model_versions_t>& versionsToStart, std::shared_ptr<model_versions_t> versionsFailed) {
Status status = StatusCode::OK;
try {
status = model->addVersions(versionsToStart, config, fs, versionsFailed);
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Error occurred while loading model: {} versions; error: {}",
config.getName(),
status.string());
}
} catch (std::exception& e) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Exception occurred while loading model: {};", e.what());
}
return status;
}
Status ModelManager::reloadModelVersions(std::shared_ptr<ovms::Model>& model, std::shared_ptr<FileSystem>& fs, ModelConfig& config, std::shared_ptr<model_versions_t>& versionsToReload, std::shared_ptr<model_versions_t> versionsFailed) {
Status status = StatusCode::OK;
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Reloading model versions");
try {
auto status = model->reloadVersions(versionsToReload, config, fs, versionsFailed);
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Error occurred while reloading model: {}; versions; error: {}",
config.getName(),
status.string());
}
} catch (std::exception& e) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Exception occurred while reloading model: {};", e.what());
}
return status;
}
Status ModelManager::reloadModelWithVersions(ModelConfig& config) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Started applying config changes to model: {}", config.getName());
auto model = getModelIfExistCreateElse(config.getName());
if (model->isAnyVersionSubscribed() && config.isDynamicParameterEnabled()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Requested setting dynamic parameters for model {} but it is used in pipeline. Cannot reload model configuration.", config.getName());
return StatusCode::REQUESTED_DYNAMIC_PARAMETERS_ON_SUBSCRIBED_MODEL;
}
auto fs = ModelManager::getFilesystem(config.getBasePath());
std::vector<model_version_t> availableVersions;
Status blocking_status = readAvailableVersions(fs, config.getBasePath(), availableVersions);
if (!blocking_status.ok()) {
return blocking_status;
}
auto requestedVersions = config.getModelVersionPolicy()->filter(availableVersions);
std::shared_ptr<model_versions_t> versionsToStart;
std::shared_ptr<model_versions_t> versionsToReload;
std::shared_ptr<model_versions_t> versionsToRetire;
std::shared_ptr<model_versions_t> versionsFailed = std::make_shared<model_versions_t>();
// first reset custom loader name to empty string so that any changes to name can be captured
model->resetCustomLoaderName();
if (config.isCustomLoaderRequiredToLoadModel()) {
custom_loader_options_config_t customLoaderOptionsConfig = config.getCustomLoaderOptionsConfigMap();
const std::string loaderName = customLoaderOptionsConfig["loader_name"];
auto& customloaders = ovms::CustomLoaders::instance();
auto loaderPtr = customloaders.find(loaderName);
if (loaderPtr != nullptr) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Custom Loader to be used : {}", loaderName);
model->setCustomLoaderName(loaderName);
// check existing version for blacklist
for (const auto& [version, versionInstance] : model->getModelVersions()) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "The model {} checking for blacklist", versionInstance->getName());
CustomLoaderStatus bres = loaderPtr->getModelBlacklistStatus(versionInstance->getName(), version);
if (bres != CustomLoaderStatus::OK) {
SPDLOG_LOGGER_INFO(modelmanager_logger, "The model {} is blacklisted", versionInstance->getName());
requestedVersions.erase(std::remove(requestedVersions.begin(), requestedVersions.end(), version), requestedVersions.end());
}
}
} else {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Specified custom loader {} not found. In case any models are loaded, will be unloading them", loaderName);
model->retireAllVersions();
return StatusCode::OK;
}
}
getVersionsToChange(config, model->getModelVersions(), requestedVersions, versionsToStart, versionsToReload, versionsToRetire);
while (versionsToStart->size() > 0) {
blocking_status = addModelVersions(model, fs, config, versionsToStart, versionsFailed);
SPDLOG_LOGGER_TRACE(modelmanager_logger, "Adding new versions. Status: {};", blocking_status.string());
if (!blocking_status.ok()) {
for (const auto version : *versionsFailed) {
SPDLOG_LOGGER_DEBUG(modelmanager_logger, "Removing available version {} due to load failure; ", version);
if (std::binary_search(availableVersions.begin(), availableVersions.end(), version)) {
availableVersions.erase(std::remove(availableVersions.begin(), availableVersions.end(), version), availableVersions.end());
}
}
requestedVersions = config.getModelVersionPolicy()->filter(availableVersions);
getVersionsToChange(config, model->getModelVersions(), requestedVersions, versionsToStart, versionsToReload, versionsToRetire);
} else {
break;
}
}
if (versionsToReload->size() > 0) {
reloadModelVersions(model, fs, config, versionsToReload, versionsFailed);
}
for (const auto version : *versionsFailed) {
SPDLOG_LOGGER_TRACE(modelmanager_logger, "Removing available version {} due to load failure.", version);
if (std::binary_search(availableVersions.begin(), availableVersions.end(), version)) {
availableVersions.erase(std::remove(availableVersions.begin(), availableVersions.end(), version), availableVersions.end());
}
}
// refresh versions to retire based on failed reloads
requestedVersions = config.getModelVersionPolicy()->filter(availableVersions);
getVersionsToChange(config, model->getModelVersions(), requestedVersions, versionsToStart, versionsToReload, versionsToRetire);
if (versionsToRetire->size() > 0) {
auto status = model->retireVersions(versionsToRetire);
if (!status.ok()) {
SPDLOG_LOGGER_ERROR(modelmanager_logger, "Error occurred while unloading model: {}; versions; error: {}",
config.getName(),
status.string());
}
}
return blocking_status;
}
const std::shared_ptr<Model> ModelManager::findModelByName(const std::string& name) const {
std::shared_lock lock(modelsMtx);
auto it = models.find(name);
return it != models.end() ? it->second : nullptr;
}
} // namespace ovms
| 46.463479 | 236 | 0.681796 | [
"shape",
"vector",
"model"
] |
2f234c555f5a751c47a906e3e0f4405271e2d4ce | 6,791 | cpp | C++ | pelican/server/src/DataReceiver.cpp | pelican/pelican | 834ae2e5d0e58009500286eb7f7891611d02b50c | [
"BSD-3-Clause"
] | 3 | 2015-10-11T07:30:59.000Z | 2016-06-03T04:27:40.000Z | pelican/server/src/DataReceiver.cpp | pelican/pelican | 834ae2e5d0e58009500286eb7f7891611d02b50c | [
"BSD-3-Clause"
] | null | null | null | pelican/server/src/DataReceiver.cpp | pelican/pelican | 834ae2e5d0e58009500286eb7f7891611d02b50c | [
"BSD-3-Clause"
] | 2 | 2016-05-09T09:52:38.000Z | 2019-05-17T06:08:24.000Z | /*
* Copyright (c) 2013, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford 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 "server/DataReceiver.h"
#include "utility/pelicanTimer.h"
#include <QtCore/QIODevice>
#include <QtCore/QTimer>
#include <QtCore/QFile>
#include <iostream>
using namespace std;
#define USE_SIGNALS 1
namespace pelican {
/**
* @details
* DataReceiver constructor.
*/
DataReceiver::DataReceiver(AbstractChunker* chunker)
: QThread(), _active(false), _chunker(chunker), _device(0)
{
if (!chunker)
throw QString("DataReceiver: Invalid chunker.");
}
/**
* @details
* DataReceiver destructor. This ensures that the thread has finished
* executing (calling quit() if necessary) before returning.
*/
DataReceiver::~DataReceiver()
{
// Setting active to false marks the destructor disconnect.
_active = false;
_chunker->stop();
if (isRunning()) {
do quit();
while (!wait(10)); // {terminate();}
}
delete _device;
}
/**
* @details
* Runs the thread owned by the DataReceiver object.
* The thread creates and opens the socket and connects the readyRead()
* socket signal to the private _processIncomingData() slot using a direct
* connection, before entering its own event loop.
*/
void DataReceiver::run()
{
_active = true;
// Open up the device to use.
// N.B. must be done in this thread (i.e. in run())
_setupDevice();
if (_device) {
// process any existing data on the stream
if (_device->bytesAvailable() > 0) {
_processIncomingData();
}
}
// At this point the event loop takes over to call the chunker
// next method
#if 0
cout << "DataReceiver starting event loop for chunker. "
<< "(" << _chunker->chunkTypes()[0].toStdString() << ", "
<< _chunker->name().toStdString() << ")" << endl;
#endif
#if USE_SIGNALS
// enter main event loop (until quit() is called)
exec();
#else
while (_active) {
//cout << "DataReceiver: checking for data ... " << endl;
// NOTE while this check seems like a good idea it fails in some of
// the unit tests...
if (!_device) {
cerr << "DataReceiver ERROR: Invalid device pointer!" << endl;
_active = false;
break;
}
if (_device && _device->bytesAvailable() > 0) {
_chunker->next(_device);
}
// If the device is a socket handle error conditions
if (QAbstractSocket* s = dynamic_cast<QAbstractSocket*>(_device)) {
// if (s->error())
// _processError();
if (s->state() == QAbstractSocket::UnconnectedState)
_reconnect();
}
// For devices with no reconnect exit the event loop if the
// device becomes unreadable.
else if (!_device->isReadable()) {
cerr << "DataReceiver ERROR: Device not readable!" << endl;
_active = false;
break;
}
usleep(1); // how long should this be.
}
#endif
}
// NOTE this function is only called if using signals.
//
void DataReceiver::_processIncomingData()
{
_chunker->next(_device);
if (_device && _device->bytesAvailable() > 0) {
emit dataRemaining();
}
}
void DataReceiver::_processError() {
std::cerr << "DataReceiver: socket error: " <<
_device->errorString().toStdString() << std::endl;
if (_active) _reconnect();
}
void DataReceiver::_reconnect() {
std::cerr << "DataReceiver Attempting to reconnect." << std::endl;
_deleteDevice();
if (_active)
_setupDevice();
}
void DataReceiver::_setupDevice()
{
_device = _chunker->newDevice();
_chunker->activate();
#if USE_SIGNALS
if (_device) {
// Call the chunker->next() method if there is data to process.
connect(_device, SIGNAL(readyRead()), SLOT(_processIncomingData()),
Qt::DirectConnection);
connect(this, SIGNAL(dataRemaining()), SLOT(_processIncomingData()),
Qt::DirectConnection);
// If its a socket we must try and catch the failure conditions
if (QAbstractSocket* s = dynamic_cast<QAbstractSocket*>(_device)) {
_registerSocket(s);
}
}
#endif
}
// NOTE this function is not called if not using signals
void DataReceiver::_registerSocket(QAbstractSocket* socket)
{
Q_ASSERT(USE_SIGNALS);
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
SLOT(_processError()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()),
SLOT(_reconnect()), Qt::DirectConnection);
}
void DataReceiver::_deleteDevice()
{
_chunker->stop(); // TODO is this only if the chunker writer respects
// the AbstractChunker::_active attribute ?
_device->disconnect(); // Disconnects all signals in this object from
// receiver's method.
_device->deleteLater(); // Note: deleteLater() acts on the current pointer
// (i.e. takes a copy of the current pointer for
// deletion) therefore it is safe to set to null
// or reassign immediately
_device = 0;
}
} // namespace pelican
| 31.882629 | 79 | 0.646297 | [
"object"
] |
2f237b3a3671a09f8cbfed366a27594958e4e40e | 7,287 | hpp | C++ | include/CSSHSession.hpp | clockworkengineer/Antikythera_mechanism | 572dc5c83303548134adf8325f77c795c02481f2 | [
"MIT"
] | 1 | 2021-03-04T07:04:50.000Z | 2021-03-04T07:04:50.000Z | include/CSSHSession.hpp | clockworkengineer/Antikythera_mechanism | 572dc5c83303548134adf8325f77c795c02481f2 | [
"MIT"
] | null | null | null | include/CSSHSession.hpp | clockworkengineer/Antikythera_mechanism | 572dc5c83303548134adf8325f77c795c02481f2 | [
"MIT"
] | 1 | 2021-11-29T08:24:52.000Z | 2021-11-29T08:24:52.000Z | #ifndef CSSHSESSION_HPP
#define CSSHSESSION_HPP
//
// C++ STL
//
#include <stdexcept>
#include <vector>
#include <memory>
#include <cassert>
#include <mutex>
//
// Antik classes
//
#include "CommonAntik.hpp"
//
// Libssh
//
#include <libssh/libssh.h>
#include <libssh/callbacks.h> // Threading intialisation
// =========
// NAMESPACE
// =========
namespace Antik::SSH
{
// ==========================
// PUBLIC TYPES AND CONSTANTS
// ==========================
enum UserAuthorizationType
{
None = 0x1,
Password = 0x2,
PublicKey = 0x4,
Interactice = 0x8
};
// ================
// CLASS DEFINITION
// ================
class CSSHSession
{
public:
// ==========================
// PUBLIC TYPES AND CONSTANTS
// ==========================
//
// Class exception
//
struct Exception
{
Exception(CSSHSession &session, const std::string &functionName) : m_errorCode{session.getErrorCode()},
m_errorMessage{session.getError()}, m_functionName{functionName}
{
}
Exception(const std::string &errorMessage, const std::string &functionName) : m_errorMessage{errorMessage},
m_functionName{functionName}
{
}
int getCode() const
{
return m_errorCode;
}
std::string getMessage() const
{
return static_cast<std::string>("CSSHSession Failure: (") + m_functionName + ") [" + m_errorMessage + "]";
}
private:
int m_errorCode{SSH_OK}; // SSH error code
std::string m_errorMessage; // SSH error message
std::string m_functionName; // Current function name
};
//
// Custom deleter for re-mapped libssh session data structures.
//
struct Deleter
{
void operator()(ssh_key key) const
{
ssh_key_free(key);
}
};
using Option = ssh_options_e;
//
// Encapsulate libssh session data in unique pointers.
//
using Key = std::unique_ptr<std::pointer_traits<ssh_key>::element_type, Deleter>;
// ============
// CONSTRUCTORS
// ============
//
// Main constructors
//
explicit CSSHSession();
CSSHSession(CSSHSession &session);
// ==========
// DESTRUCTOR
// ==========
virtual ~CSSHSession();
// ==============
// PUBLIC METHODS
// ==============
//
// Set session details
//
void setServer(const std::string &server);
void setPort(unsigned int port);
void setUser(const std::string &user);
void setUserPassword(const std::string &password);
//
// Connect/disconnect sessions
//
void connect();
void disconnect(bool silent = false);
//
// User authorization functions
//
int userAuthorizationList();
//
// Overridable user authorization functions
//
virtual int userAuthorizationNone();
virtual int userAuthorizationWithPublicKeyAuto();
virtual int userAuthorizationWithPassword();
virtual int userAuthorizationWithPublicKey();
virtual int userAuthorizationWithKeyboardInteractive();
//
// Verify server
//
int isServerKnown();
//
// Write server details away to local config
//
void writeKnownHost();
//
// Get names of session cipher/HMAC in/out methods, key exchange algorithm
//
std::string getCipherIn();
std::string getCipherOut();
std::string getHMACIn();
std::string getHMACOut();
std::string getKeyExchangeAlgorithm();
//
// Public key methods
//
Key getPublicKey();
void getPublicKeyHash(Key &serverPublicKey, std::vector<unsigned char> &keyHash);
std::string convertKeyHashToHex(std::vector<unsigned char> &keyHash);
//
// Get various banners and disconnect message
//
std::string getBanner() const;
std::string getClientBanner() const;
std::string getServerBanner() const;
std::string getDisconnectMessage() const;
//
// Get SSH/OpenSSH versions
//
int getSSHVersion() const;
int getOpenSSHVersion() const;
//
// Session status methods
//
int getStatus() const;
bool isConnected() const;
bool isAuthorized() const;
//
// Get/Set option values for a session and also copy options,
//
void setOption(Option sessionOption, const void *optionValue);
void getOption(Option sessionOption, std::string &optionValue);
void copyOptions(CSSHSession &source);
//
// Get SSH error code and message
//
std::string getError() const;
int getErrorCode() const;
//
// Get libssh session structure
//
ssh_session getSession() const;
//
// Get session user authorization type
//
std::uint32_t getAuthorizarionType() const;
//
// Set logging verbosity
//
void setLogging(int logging);
// ================
// PUBLIC VARIABLES
// ================
private:
// ===========================
// PRIVATE TYPES AND CONSTANTS
// ===========================
// ===========================================
// DISABLED CONSTRUCTORS/DESTRUCTORS/OPERATORS
// ===========================================
CSSHSession(const CSSHSession &orig) = delete;
CSSHSession(const CSSHSession &&orig) = delete;
CSSHSession &operator=(CSSHSession other) = delete;
// ===============
// PRIVATE METHODS
// ===============
//
// Initialisation
//
static void initialise();
// =================
// PRIVATE VARIABLES
// =================
ssh_session m_session; // libssh session
int m_logging{SSH_LOG_NOLOG}; // libssh logging
std::string m_server; // SSH server name
unsigned int m_port{22}; // SSH server port
std::string m_user; // SSH server login account name
std::string m_password; // SSH server login account password
bool m_authorized{false}; // SSH session authorised
std::uint32_t m_authorizarionType{UserAuthorizationType::None}; // SSH session user authorization type
};
} // namespace Antik::SSH
#endif /* CSSHSESSION_HPP */
| 32.824324 | 143 | 0.485934 | [
"vector"
] |
2f2a1ac5c8a89a74aa3fb6729d9de98ba9c4b01d | 897 | hpp | C++ | core/engine/inc/engine/service/AnimatorService.hpp | rawbby/WS20-CG-Pra-Dungeon-Crawler | 4c1b372649a92fb08b8908054d82624ae2b68af5 | [
"MIT"
] | null | null | null | core/engine/inc/engine/service/AnimatorService.hpp | rawbby/WS20-CG-Pra-Dungeon-Crawler | 4c1b372649a92fb08b8908054d82624ae2b68af5 | [
"MIT"
] | null | null | null | core/engine/inc/engine/service/AnimatorService.hpp | rawbby/WS20-CG-Pra-Dungeon-Crawler | 4c1b372649a92fb08b8908054d82624ae2b68af5 | [
"MIT"
] | null | null | null | #pragma once
#include "CollisionService.hpp"
#include <engine/component/DynamicCollisionCircle.hpp>
#include <engine/component/StaticCollisionLine.hpp>
#include <engine/component/PositionComponent.hpp>
#include <model/Types.hpp>
#include <model/Skin.hpp>
#include <model/SkinnedMesh.hpp>
#include <model/SkinAnimation.hpp>
#include <model/SkinTransitionAnimator.hpp>
#include <glm/ext/quaternion_common.hpp>
#include <entt/entt.hpp>
namespace engine::service
{
class Animator
{
public:
void update (entt::registry ®, float delta)
{
auto ator_entities = reg.view<model::SkinTransitionAnimator>();
for (const auto ator_entity: ator_entities)
{
auto &ator = reg.get<model::SkinTransitionAnimator>(ator_entity);
model::update_transition_animation(ator, delta);
}
}
};
}
| 24.243243 | 81 | 0.675585 | [
"model"
] |
2f2b03896b3f6adebcdfbdf512d464beffebaf5a | 2,172 | cpp | C++ | Week 6-7/Cplus-OOP-Circlep/Circle.cpp | ToyVo/CSIIStout | c9b0f2adfa9eb60f078413c2a17f30b44d85059f | [
"MIT"
] | null | null | null | Week 6-7/Cplus-OOP-Circlep/Circle.cpp | ToyVo/CSIIStout | c9b0f2adfa9eb60f078413c2a17f30b44d85059f | [
"MIT"
] | null | null | null | Week 6-7/Cplus-OOP-Circlep/Circle.cpp | ToyVo/CSIIStout | c9b0f2adfa9eb60f078413c2a17f30b44d85059f | [
"MIT"
] | null | null | null | // This program uses a constructor to initialize a member variable.
#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
// Circle class declaration
class Circle
{ private:
double radius;
public: // Member function prototypes
Circle();
void setRadius(double);
double getArea();
};
// Circle member function implementation section
/********************************************
* Circle::Circle *
* This is the constructor. It initializes *
* the radius class member variable. *
********************************************/
Circle::Circle()
{ radius = 1.0;
}
/********************************************
* Circle::setRadius *
* This function validates the value passed *
* to it before assigning it to the radius *
* member variable. *
********************************************/
void Circle::setRadius(double r)
{ if (r >= 0.0)
radius = r;
// else leave it set to its previous value
}
/**********************************************
* Circle::getArea *
* This function calculates and returns the *
* Circle object's area. It does not need any *
* parameters because it can directly access *
* the member variable radius. *
**********************************************/
double Circle::getArea()
{ return 3.14 * pow(radius, 2);
}
/***************************************
* main *
* The main function creates and uses *
* 2 Circle objects. *
***************************************/
int main()
{
// Define a Circle object. Because the setRadius function
// is never called for it, it will keep the value set
// by the constructor.
Circle circle1;
// Define a second Circle object and set its radius to 2.5
Circle circle2;
circle2.setRadius(2.5);
// Get and display each circle's area
cout << "The area of circle1 is " << circle1.getArea() << endl;
cout << "The area of circle2 is " << circle2.getArea() << endl;
system("pause");
return 0;
} | 28.96 | 67 | 0.496777 | [
"object"
] |
2f33e91beda84cb2b0ff9ce43ed8c0dcbc7e138f | 4,589 | hpp | C++ | rbst/treap.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 69 | 2020-11-06T05:21:42.000Z | 2022-03-29T03:38:35.000Z | rbst/treap.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 21 | 2020-07-25T04:47:12.000Z | 2022-02-01T14:39:29.000Z | rbst/treap.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 9 | 2020-11-06T11:55:10.000Z | 2022-03-20T04:45:31.000Z | #pragma once
#include "../misc/rng.hpp"
template <typename Node>
struct TreapBase {
using Ptr = Node *;
template <typename... Args>
inline Ptr my_new(Args... args) {
return new Node(args...);
}
Ptr make_tree() { return nullptr; }
// for avoiding memory leak, activate below
/*
using Ptr = shared_ptr<Node>;
template <typename... Args>
inline Ptr my_new(Args... args) {
return make_shared<Node>(args...);
}
Ptr make_tree() {return Ptr();}
*/
int size(Ptr t) const { return count(t); }
Ptr merge(Ptr l, Ptr r) {
if (!l || !r) return l ? l : r;
if (l->pr >= r->pr) {
push(l);
l->r = merge(l->r, r);
return update(l);
} else {
push(r);
r->l = merge(l, r->l);
return update(r);
}
}
pair<Ptr, Ptr> split(Ptr t, int k) {
if (!t) return {nullptr, nullptr};
push(t);
if (k <= count(t->l)) {
auto s = split(t->l, k);
t->l = s.second;
return {s.first, update(t)};
} else {
auto s = split(t->r, k - count(t->l) - 1);
t->r = s.first;
return {update(t), s.second};
}
}
Ptr build(const vector<decltype(Node::key)> &v) {
int n = v.size();
vector<Ptr> ps;
ps.reserve(n);
for (int i = 0; i < n; i++) ps.push_back(my_new(v[i]));
vector<int> p(n, -1), st;
for (int i = 0; i < n; i++) {
int prv = -1;
while (!st.empty() && ps[i]->pr > ps[st.back()]->pr) {
prv = st.back();
st.pop_back();
}
if (prv != -1) p[prv] = i;
if (!st.empty()) p[i] = st.back();
st.push_back(i);
}
int root = -1;
for (int i = 0; i < n; i++) {
if (p[i] != -1) {
if (i < p[i]) {
ps[p[i]]->l = ps[i];
} else {
ps[p[i]]->r = ps[i];
}
} else
root = i;
}
dfs(ps[root]);
return ps[root];
}
template <typename... Args>
void insert(Ptr &t, int k, const Args &... args) {
auto x = split(t, k);
t = merge(merge(x.first, my_new(args...)), x.second);
}
void erase(Ptr &t, int k) {
auto x = split(t, k);
t = merge(x.first, split(x.second, 1).second);
}
protected:
void dfs(Ptr r) {
if (r->l) dfs(r->l);
if (r->r) dfs(r->r);
update(r);
}
inline int count(const Ptr t) const { return t ? t->cnt : 0; }
virtual void push(Ptr) {}
virtual Ptr update(Ptr) = 0;
};
template <typename T, typename E>
struct LazyReversibleTreapNode {
using Treap = TreapBase<LazyReversibleTreapNode>;
typename Treap::Ptr l, r;
T key, sum;
E lazy;
int cnt;
uint32_t pr;
bool rev;
LazyReversibleTreapNode(const T &t = T(), const E &e = E())
: l(),
r(),
key(t),
sum(t),
lazy(e),
cnt(1),
pr(my_rand::rng()),
rev(false) {}
};
template <typename T, typename E, T (*f)(T, T), T (*g)(T, E), E (*h)(E, E),
T (*ts)(T)>
struct LazyReversibleTreap : TreapBase<LazyReversibleTreapNode<T, E>> {
using Node = LazyReversibleTreapNode<T, E>;
using base = TreapBase<LazyReversibleTreapNode<T, E>>;
using base::merge;
using base::split;
using typename base::Ptr;
LazyReversibleTreap() = default;
void toggle(Ptr t) {
swap(t->l, t->r);
t->sum = ts(t->sum);
t->rev ^= true;
}
T fold(Ptr &t, int a, int b) {
auto x = split(t, a);
auto y = split(x.second, b - a);
auto ret = sum(y.first);
t = merge(x.first, merge(y.first, y.second));
return ret;
}
void reverse(Ptr &t, int a, int b) {
auto x = split(t, a);
auto y = split(x.second, b - a);
toggle(y.first);
t = merge(x.first, merge(y.first, y.second));
}
void apply(Ptr &t, int a, int b, const E &e) {
auto x = split(t, a);
auto y = split(x.second, b - a);
propagate(y.first, e);
t = merge(x.first, merge(y.first, y.second));
}
protected:
inline T sum(const Ptr t) const { return t ? t->sum : T(); }
Ptr update(Ptr t) override {
push(t);
t->cnt = 1;
t->sum = t->key;
if (t->l) t->cnt += t->l->cnt, t->sum = f(t->l->sum, t->sum);
if (t->r) t->cnt += t->r->cnt, t->sum = f(t->sum, t->r->sum);
return t;
}
void push(Ptr t) override {
if (t->rev) {
if (t->l) toggle(t->l);
if (t->r) toggle(t->r);
t->rev = false;
}
if (t->lazy != E()) {
if (t->l) propagate(t->l, t->lazy);
if (t->r) propagate(t->r, t->lazy);
t->lazy = E();
}
}
void propagate(Ptr t, const E &x) {
t->lazy = h(t->lazy, x);
t->key = g(t->key, x);
t->sum = g(t->sum, x);
}
};
/**
* @brief 遅延伝搬反転可能Treap
*/
| 22.385366 | 75 | 0.503813 | [
"vector"
] |
2f36fdaac88d3b7974f39ce766b2c0f6c0e4eb36 | 1,792 | cpp | C++ | dev/g++/test/networkThread.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/test/networkThread.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/test/networkThread.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | 1 | 2017-01-27T12:53:50.000Z | 2017-01-27T12:53:50.000Z | #include <iostream>
#include <iomanip>
#include "networkThread.h"
#include "channelManager.h"
networkThread::networkThread(const std::string & p_hostAddr, const int p_hostLocalPort, const int p_hostRemotePort) :
_host(p_hostAddr, p_hostLocalPort),
_remote(p_hostAddr, p_hostRemotePort) {
std::clog << ">>> networkThread::ctor" << std::endl;
std::clog << "socket: " << _host.toString() << std::endl;
std::clog << "socket: " << _remote.toString() << std::endl;
_udp = raspberryComm::channelManager::getInstance().createChannel(raspberryComm::abstractChannel::udp, _host, _remote);
std::clog << "Channel id: " << std::dec << _udp << std::endl;
}
void networkThread::stop() {
std::clog << ">>> networkThread::stop" << std::endl;
raspberryComm::channelManager::getInstance().getChannel(_udp).disconnect();
raspberryComm::channelManager::getInstance().removeChannel(_udp);
}
void networkThread::run() {
std::clog << ">>> networkThread::run" << std::endl;
_running = true;
while (_running == true) {
std::vector<unsigned char> vdatas { (unsigned char)0xff, (unsigned char)0x01, (unsigned char)0x41 };
raspberryComm::channelManager::getInstance().getChannel(_udp).write(vdatas);
std::vector<unsigned char> result(3);
raspberryComm::channelManager::getInstance().getChannel(_udp).read(result);
std::clog << "Receive data: " << std::endl;
int idx = 0;
for (std::vector<unsigned char>::iterator it = result.begin(); it != result.end(); ++it, idx++) {
std::clog << "result[" << idx << "] = 0x" << std::hex << std::setw(2) << std::setfill('0') << (int)*it << std::endl;
} // End of 'for' statement
std::cout << ".";
usleep(50);
} // End of 'while' statement
std::clog << "<<< networkThread::run" << std::endl;
}
| 36.571429 | 122 | 0.651228 | [
"vector"
] |
2f378d7cce6ea1133a02f89c4bddd5dd72090630 | 10,506 | cpp | C++ | frontend/src/ArrayIndexClassifier.cpp | uwplse/stng | ce12c2c079516df873382a5aa3c18c407833d130 | [
"MIT"
] | 14 | 2017-03-07T00:14:33.000Z | 2022-02-09T00:59:22.000Z | frontend/src/ArrayIndexClassifier.cpp | uwplse/stng | ce12c2c079516df873382a5aa3c18c407833d130 | [
"MIT"
] | 11 | 2016-11-22T13:14:55.000Z | 2021-12-14T00:56:51.000Z | frontend/src/ArrayIndexClassifier.cpp | uwplse/stng | ce12c2c079516df873382a5aa3c18c407833d130 | [
"MIT"
] | 6 | 2016-11-07T13:38:45.000Z | 2021-04-04T12:13:31.000Z | #include "ArrayIndexClassifier.h"
#include "debug.h"
namespace StencilTranslator
{
TaintLattice::TaintLattice ()
{
this->taint = Uninitialized;
}
TaintLattice::TaintLattice (const TaintLattice & o)
{
this->taint = o.taint;
}
void TaintLattice::initialize () {}
Lattice *
TaintLattice::copy () const
{
return new TaintLattice(*this);
}
void
TaintLattice::copy (Lattice * o)
{
TaintLattice * other = dynamic_cast<TaintLattice *>(o);
this->taint = other->taint;
}
bool
TaintLattice::operator== (Lattice * o)
{
TaintLattice * other = dynamic_cast<TaintLattice *>(o);
return (other->taint == this->taint);
}
std::string
TaintLattice::str (std::string indent)
{
std::ostringstream out;
out << indent;
switch (taint)
{
case Uninitialized: { out << "[Uninitialized]"; break; }
case NonArray: { out << "[Non Array]"; break; }
case Array: { out << "[Array]"; break; }
default: { ASSERT(false, "unknown taint value: " + taint); break; }
}
return out.str();
}
std::ostream&
operator<< (std::ostream &o, TaintLattice &t)
{
o << t.str("");
return o;
}
bool
TaintLattice::meetUpdate (Lattice * o)
{
TaintLattice * other = dynamic_cast<TaintLattice *>(o);
Taint otherTaint = other->taint;
bool modified;
if (taint == Uninitialized)
{
if (otherTaint == Uninitialized)
modified = false;
else
{
this->taint = otherTaint;
modified = true;
}
}
else if (taint == NonArray)
{
if (otherTaint == NonArray)
modified = false;
else if (otherTaint == Array)
{
this->taint = Array;
modified = true;
}
else
ASSERT(false, "unknown taint value: " + otherTaint);
}
else if (taint == Array)
modified = false;
else
ASSERT(false, "unknown taint value: " + taint);
return modified;
}
TaintLattice::Taint TaintLattice::getTaint () { return this->taint; }
void TaintLattice::setTaint (Taint t) { this->taint = t; }
/* ArrayIndexAnalysis */
ArrayIndexAnalysis::ArrayIndexAnalysis (LiveDeadVarsAnalysis * ldva) :
ldva(ldva)
{ }
void
ArrayIndexAnalysis::genInitState (const Function &f, const DataflowNode &n, const NodeState &state,
std::vector<Lattice *> &initLattices, std::vector<NodeFact *> &initFacts)
{
std::map<varID, Lattice *> emptyM;
FiniteVarsExprsProductLattice * l = new FiniteVarsExprsProductLattice((Lattice*) new TaintLattice(), emptyM,
(Lattice*) NULL, ldva, n, state);
initLattices.push_back(l);
this->taints[n.getNode()] = TaintLattice::Uninitialized;
//std::cout << "init called on: " << n.getNode()->sage_class_name()
// << " v: " << n.getNode()->unparseToString() << "\n";
}
bool
ArrayIndexAnalysis::transfer (const Function &f, const DataflowNode &n, NodeState &state,
const std::vector<Lattice *> &dfInfo)
{
/*
FiniteVarsExprsProductLattice * prodLat = dynamic_cast<FiniteVarsExprsProductLattice *>(*(dfInfo.begin()));
const std::vector<Lattice *> &lattices = prodLat->getLattices();
for (std::vector<Lattice *>::const_iterator it = lattices.begin(); it != lattices.end(); ++it)
(dynamic_cast<TaintLattice *>(*it))->initialize();
std::cout << "running analysis on: " << n.getNode()->sage_class_name() << " v: "
<< n.getNode()->unparseToString()
<< " lat: " << prodLat->getLattices().size() << "\n";
if (isSgExpression(n.getNode()))
{
varID id = SgExpr2Var(isSgExpression(n.getNode()));
TaintLattice * taint = dynamic_cast<TaintLattice *>(prodLat->getVarLattice(id));
std::cout << "taint: " << taint << "\n";
}
return false;
*/
assert(0);
/*
std::cout << "transfer on: " << n.getNode()->sage_class_name() << " v: "
<< n.getNode()->unparseToString() << "\n";
std::cout << "transfer A prodLat="<<(*dfInfo.begin()) <<"="<< (*dfInfo.begin())->str(" ")<<"\n";
return false;
*/
}
boost::shared_ptr<IntraDFTransferVisitor>
ArrayIndexAnalysis::getTransferVisitor (const Function &f, const DataflowNode &n, NodeState &s,
const std::vector<Lattice *> &dfInfo)
{
//std::cout << "get transfer called\n";
return boost::shared_ptr<IntraDFTransferVisitor>(new TaintAnalysisVisitor(f, n, s, dfInfo, this));
//return IntraFWDataflow::getTransferVisitor(f, n, s, dfInfo);
}
/* TaintAnalysisVisitor */
int debugLevel = 2;
TaintAnalysisVisitor::TaintAnalysisVisitor (const Function &f, const DataflowNode &n, NodeState &s,
const std::vector<Lattice *> &dfInfo, ArrayIndexAnalysis * aia) :
VariableStateTransfer<TaintLattice>(f, n, s, dfInfo, debugLevel), aia(aia)
{
//std::cout << "transfer A prodLat="<<(*dfInfo.begin()) <<"="<< (*dfInfo.begin())->str(" ")<<"\n";
}
bool
TaintAnalysisVisitor::finish ()
{
return modified;
}
void
TaintAnalysisVisitor::visit (SgAssignOp * op)
{
TaintLattice * lhs = getLattice(op->get_lhs_operand());
TaintLattice * rhs = getLattice(op->get_rhs_operand());
TaintLattice * r = getLattice(op);
std::cout << "lhs: " << lhs << " v: " << op->get_lhs_operand()->unparseToString()
<< " type: " << op->get_lhs_operand()->sage_class_name() << "\n";
if (lhs)
{
lhs->setTaint(rhs->getTaint());
aia->taints[op->get_lhs_operand()] = rhs->getTaint();
modified = true;
std::cout << "assign lhs result: " << *lhs << " v: " << op->unparseToString() << "\n";
}
else
std::cout << "assign lhs (dead) " << op->unparseToString() << "\n";
if (r != rhs)
{
r->setTaint(rhs->getTaint());
aia->taints[op] = rhs->getTaint();
modified = true;
}
else
modified = false;
if (r)
std::cout << "assign result: " << *r << " v: " << op->unparseToString() << "\n";
else
std::cout << "assign result: (dead) v: " << op->unparseToString() << "\n";
}
void
TaintAnalysisVisitor::visit (SgPntrArrRefExp * arr)
{
TaintLattice * r = getLattice(arr);
if (r && r->getTaint() != TaintLattice::Array)
{
r->setTaint(TaintLattice::Array);
aia->taints[arr] = TaintLattice::Array;
modified = true;
}
else
modified = false;
if (r)
std::cout << "arr access result: " << *r << " v: " << arr->unparseToString() << "\n";
else
std::cout << "arr access result (dead) v: " << arr->unparseToString() << "\n";
}
void
TaintAnalysisVisitor::visit (SgValueExp * lit)
{
TaintLattice * r = getLattice(lit);
if (r && r->getTaint() != TaintLattice::NonArray)
{
r->setTaint(TaintLattice::NonArray);
aia->taints[lit] = TaintLattice::NonArray;
modified = true;
}
else
modified = false;
if (r)
std::cout << "lit result: " << *r << " v: " << lit->unparseToString() << "\n";
else
std::cout << "lit result: (dead) v: " << lit->unparseToString() << "\n";
}
void
TaintAnalysisVisitor::visit (SgNullExpression * lit)
{
TaintLattice * r = getLattice(lit);
if (r && r->getTaint() != TaintLattice::NonArray)
{
r->setTaint(TaintLattice::NonArray);
aia->taints[lit] = TaintLattice::NonArray;
modified = true;
}
else
modified = false;
if (r)
std::cout << "null result: " << *r << " v: " << lit->unparseToString() << "\n";
else
std::cout << "null result: (dead) v: " << lit->unparseToString() << "\n";
}
void
TaintAnalysisVisitor::visit (SgBinaryOp * op)
{
TaintLattice * lhs = getLattice(op->get_lhs_operand());
TaintLattice * rhs = getLattice(op->get_rhs_operand());
TaintLattice * r = getLattice(op);
if (isSgAddOp(op) || isSgAndOp(op) || isSgBitAndOp(op) || isSgBitOrOp(op) ||
isSgBitXorOp(op) || isSgConcatenationOp(op) || isSgDivideOp(op) ||
isSgEqualityOp(op) || isSgExponentiationOp(op) || isSgGreaterThanOp(op) ||
isSgIntegerDivideOp(op) || isSgIsNotOp(op) || isSgIsOp(op) ||
isSgLessOrEqualOp(op) || isSgLessThanOp(op) || isSgLshiftOp(op) ||
isSgMembershipOp(op) || isSgModOp(op) || isSgMultiplyOp(op) ||
isSgNonMembershipOp(op) || isSgNotEqualOp(op) || isSgOrOp(op) ||
isSgRshiftOp(op) || isSgSubtractOp(op))
{
if ( r && (lhs->getTaint() == TaintLattice::Array || rhs->getTaint() == TaintLattice::Array) &&
r->getTaint() != TaintLattice::Array)
{
r->setTaint(TaintLattice::Array);
aia->taints[op] = TaintLattice::Array;
modified = true;
}
else
modified = false;
}
else
ASSERT(0, "unknown binary op: " + op->unparseToString());
if (r)
std::cout << "binop result: " << *r << " v: " << op->unparseToString() << "\n";
else
std::cout << "binop result (dead) v: " << op->unparseToString() << "\n";
//std::cout << "assign: " << assign->unparseToString() << " lhs: " << assign->get_lhs_operand()->unparseToString() << " rhs: " << assign->get_rhs_operand()->unparseToString() << "\n";
//std::cout << "lhs: " << lhs << " rhs: " << rhs << "\n";
}
void
TaintAnalysisVisitor::visit (SgUnaryOp * op)
{
TaintLattice * operand = getLattice(op->get_operand());
TaintLattice * r = getLattice(op);
if (isSgBitComplementOp(op) || isSgCastExp(op) || isSgMinusMinusOp(op) ||
isSgMinusOp(op) || isSgNotOp(op) || isSgPlusPlusOp(op) || isSgUnaryAddOp(op))
{
if (r && operand->getTaint() != r->getTaint())
{
r->setTaint(operand->getTaint());
aia->taints[op] = operand->getTaint();
modified = true;
}
else
modified = false;
}
else
ASSERT(0, "unknown unary op: " + op->unparseToString());
if (r)
std::cout << "unop result: " << *r << " v: " << op->unparseToString() << "\n";
else
std::cout << "unop result (dead) v: " << op->unparseToString() << "\n";
}
void
TaintAnalysisVisitor::visit (SgExpression * e)
{
if (! (isSgVarRefExp(e) || isSgExprListExp(e)) )
ASSERT(0, "unknown exp: " + e->unparseToString() + " type: " + e->sage_class_name());
//ROSE_VisitorPatternDefaultBase::visit((SgExpression*)e);
}
void
ArrayIndexAnalysis::printResults ()
{
for (std::map<SgNode *, TaintLattice::Taint>::const_iterator it = taints.begin(); it != taints.end(); ++it)
{
SgNode * k = it->first;
TaintLattice::Taint t = it->second;
std::cout << "key: " << k->unparseToString() << " v: " << t << "\n";
}
}
TaintLattice::Taint
ArrayIndexAnalysis::getTaint (SgNode * n)
{
if (taints.find(n) == taints.end())
ASSERT(0, "cannot find taint for: " + n->unparseToString());
else
return taints[n];
}
}
| 27.359375 | 185 | 0.602894 | [
"vector"
] |
2f39f80c1f5afb4d3a4912821110be366725e3bc | 27,346 | cpp | C++ | source/exprjit/src/exprjit.cpp | Archie3d/exprjit | 84c6b97d157a81e6a069bdc580f7887ec754cf0e | [
"MIT"
] | 1 | 2019-08-03T21:48:48.000Z | 2019-08-03T21:48:48.000Z | source/exprjit/src/exprjit.cpp | Archie3d/exprjit | 84c6b97d157a81e6a069bdc580f7887ec754cf0e | [
"MIT"
] | null | null | null | source/exprjit/src/exprjit.cpp | Archie3d/exprjit | 84c6b97d157a81e6a069bdc580f7887ec754cf0e | [
"MIT"
] | null | null | null | #include <cmath>
#include <istream>
#include <sstream>
#include <map>
#include <functional>
#include "NativeJIT/CodeGen/ExecutionBuffer.h"
#include "NativeJIT/CodeGen/FunctionBuffer.h"
#include "NativeJIT/Function.h"
#include "exprjit.h"
// Size of the JIT compiler buffers
constexpr size_t CODE_BUFFER_SIZE = 16384;
namespace nj = NativeJIT;
// Enable generated code assembly output
//#define EXPRJIT_ENABLE_ASM_OUTPUT
//----------------------------------------------------------
// Helper class to contruct error messages
//----------------------------------------------------------
class MessageConstructor final
{
public:
MessageConstructor(std::string &str)
: m_str(str)
{
}
~MessageConstructor()
{
m_str = m_ss.str();
}
template <typename T>
MessageConstructor& operator << (const T &v)
{
m_ss << v;
return *this;
}
private:
std::stringstream m_ss;
std::string &m_str;
};
//----------------------------------------------------------
// Standard functions
//----------------------------------------------------------
namespace func {
// 1-argument functions
static ExprJIT::Real abs(ExprJIT::Real x) { return ::abs(x); }
static ExprJIT::Real sqrt(ExprJIT::Real x) { return ::sqrt(x); }
static ExprJIT::Real exp(ExprJIT::Real x) { return ::exp(x); }
static ExprJIT::Real exp2(ExprJIT::Real x) { return ::exp2(x); }
static ExprJIT::Real log(ExprJIT::Real x) { return ::log(x); }
static ExprJIT::Real log2(ExprJIT::Real x) { return ::log2(x); }
static ExprJIT::Real log10(ExprJIT::Real x) { return ::log10(x); }
static ExprJIT::Real sin(ExprJIT::Real x) { return ::sin(x); }
static ExprJIT::Real cos(ExprJIT::Real x) { return ::cos(x); }
static ExprJIT::Real tan(ExprJIT::Real x) { return ::tan(x); }
static ExprJIT::Real asin(ExprJIT::Real x) { return ::asin(x); }
static ExprJIT::Real acos(ExprJIT::Real x) { return ::acos(x); }
static ExprJIT::Real atan(ExprJIT::Real x) { return ::atan(x); }
static ExprJIT::Real sinh(ExprJIT::Real x) { return ::sinh(x); }
static ExprJIT::Real cosh(ExprJIT::Real x) { return ::cosh(x); }
static ExprJIT::Real tanh(ExprJIT::Real x) { return ::tanh(x); }
static ExprJIT::Real asinh(ExprJIT::Real x) { return ::asinh(x); }
static ExprJIT::Real acosh(ExprJIT::Real x) { return ::acosh(x); }
static ExprJIT::Real atanh(ExprJIT::Real x) { return ::atanh(x); }
static ExprJIT::Real round(ExprJIT::Real x) { return ::round(x); }
static ExprJIT::Real ceil(ExprJIT::Real x) { return ::ceil(x); }
static ExprJIT::Real floor(ExprJIT::Real x) { return ::floor(x); }
// 2-argument functions
static ExprJIT::Real min(ExprJIT::Real x, ExprJIT::Real y) { return (x < y) ? x : y; }
static ExprJIT::Real max(ExprJIT::Real x, ExprJIT::Real y) { return (x > y) ? x : y; }
static ExprJIT::Real pow(ExprJIT::Real x, ExprJIT::Real y) { return ::pow(x, y); }
static ExprJIT::Real mod(ExprJIT::Real x, ExprJIT::Real y) { return ::fmod(x, y); }
static ExprJIT::Real atan2(ExprJIT::Real x, ExprJIT::Real y) { return ::atan2(x, y); }
static ExprJIT::Real hypot(ExprJIT::Real x, ExprJIT::Real y) { return ::hypot(x, y); }
// 3-argument functions
static ExprJIT::Real clamp(ExprJIT::Real x, ExprJIT::Real a, ExprJIT::Real b)
{
if (x < a) {
return a;
} else if (x > b) {
return b;
}
return x;
}
} // namespace func
//----------------------------------------------------------
// Symbols table
//----------------------------------------------------------
class SymbolTable
{
public:
SymbolTable()
: m_vars()
{
defineStandardFunctions();
}
void defineStandardFunctions()
{
setFunc("abs", func::abs);
setFunc("sqrt", func::sqrt);
setFunc("exp", func::exp);
setFunc("exp2", func::exp2);
setFunc("log", func::log);
setFunc("log2", func::log2);
setFunc("log10", func::log10);
setFunc("sin", func::sin);
setFunc("cos", func::cos);
setFunc("tan", func::tan);
setFunc("asin", func::asin);
setFunc("acos", func::acos);
setFunc("atan", func::atan);
setFunc("sinh", func::sinh);
setFunc("cosh", func::cosh);
setFunc("tanh", func::tanh);
setFunc("asinh", func::asinh);
setFunc("acosh", func::acosh);
setFunc("atanh", func::atanh);
setFunc("round", func::round);
setFunc("ceil", func::ceil);
setFunc("floor", func::floor);
setFunc("min", func::min);
setFunc("max", func::max);
setFunc("pow", func::pow);
setFunc("mod", func::mod);
setFunc("atan2", func::atan2);
setFunc("hypot", func::hypot);
setFunc("clamp", func::clamp);
}
ExprJIT::Real* varPtr(const std::string &name)
{
if (m_vars.find(name) != m_vars.end()) {
return &m_vars[name];
}
return nullptr;
}
ExprJIT::Function1Ptr func1Ptr(const std::string &name)
{
if (m_func1.find(name) != m_func1.end()) {
return m_func1.at(name);
}
return nullptr;
}
ExprJIT::Function2Ptr func2Ptr(const std::string &name)
{
if (m_func2.find(name) != m_func2.end()) {
return m_func2.at(name);
}
return nullptr;
}
ExprJIT::Function3Ptr func3Ptr(const std::string &name)
{
if (m_func3.find(name) != m_func3.end()) {
return m_func3.at(name);
}
return nullptr;
}
void setVar(const std::string &name, const ExprJIT::Real value)
{
m_vars[name] = value;
}
void setFunc(const std::string &name, ExprJIT::Function1Ptr func)
{
m_func1[name] = func;
}
void setFunc(const std::string &name, ExprJIT::Function2Ptr func)
{
m_func2[name] = func;
}
void setFunc(const std::string &name, ExprJIT::Function3Ptr func)
{
m_func3[name] = func;
}
private:
std::map<std::string, ExprJIT::Real> m_vars;
std::map<std::string, ExprJIT::Function1Ptr> m_func1; ///< With 1 argument
std::map<std::string, ExprJIT::Function2Ptr> m_func2; ///< With 2 arguments
std::map<std::string, ExprJIT::Function3Ptr> m_func3; ///< With 3 arguments
};
//----------------------------------------------------------
// Expression parser
//----------------------------------------------------------
class Parser final
{
public:
using Node = nj::Node<ExprJIT::Real>;
Parser(nj::ExpressionNodeFactory &nodeFactory, SymbolTable &symbols)
: m_nodeFactory(nodeFactory),
m_symbols(symbols),
m_error(false),
m_message(),
m_symbolsCache()
{
}
inline bool error() const { return m_error; }
const std::string& message() const { return m_message; }
Node& parse(const std::string &str, bool &isConstant, ExprJIT::Real &constValue)
{
m_symbolsCache.clear();
std::istringstream ss(str);
return parseExpression(ss, isConstant, constValue);
}
private:
// Helper macro to generate parsing error messages
#define PARSE_ERR m_error=true; MessageConstructor(m_message) << in.tellg() << ": "
static void markUnused(Node &node)
{
// TODO: What is the right way to optimize-out a node?
node.IncrementParentCount();
}
/**
* @brief Tells whether a character is a shitespace.
* @param c
* @return
*/
static inline bool isSpace(int c)
{
return (c == ' ') || (c == '\t') || (c == '\r') || (c == '\n');
}
/**
* @brief Skip whitespaces in the input stream.
*
* This will advance the input stream until there is a non-whitespace
* character in there, or end of stream.
*
* @param in
*/
static void skipSpace(std::istream &in)
{
while(Parser::isSpace(in.peek())) {
in.get();
}
}
/**
* @brief Extract a positive integer value from the stream.
* @param in
* @param value
* @return
*/
static bool parseInteger(std::istream &in, long long int &value)
{
long long int tmp = 0;
bool ok = false;
auto c = in.peek();
while (c >= '0' && c <= '9') {
tmp = 10*tmp + in.get() - '0';
c = in.peek();
ok = true;
}
if (ok) {
value = tmp;
}
return ok;
}
/**
* @brief 1/x function
*
* NativeJIT does not provide division operation, so we have
* to implement it as a function.
*
* @param x
* @return
*/
static ExprJIT::Real invf(ExprJIT::Real x)
{
return 1.0 / x;
}
/**
* @brief Parse a floating point number.
* @param in
* @param value Parsed value
* @return Floating point immediate value JIT node.
*/
Node& parseNumber(std::istream &in, ExprJIT::Real &value)
{
ExprJIT::Real tmp = 0.0;
long long int tmp_i = 0;
long long int tmp_r = 0;
long long int tmp_e = 0;
bool neg = false;
Parser::skipSpace(in);
auto c = in.peek();
if (c == '-') {
in.get();
neg = true;
}
bool ok = parseInteger(in, tmp_i);
if (ok) {
c = in.peek();
if (c == '.') {
in.get();
ok = parseInteger(in, tmp_r);
c = in.peek();
}
if (ok && (c == 'E' || c == 'e')) {
in.get();
c = in.peek();
bool neg = false;
if (c == '-') {
in.get();
neg = true;
}
ok = parseInteger(in, tmp_e);
if (ok && neg) {
tmp_e = -tmp_e;
}
}
}
if (ok) {
tmp = static_cast<ExprJIT::Real>(tmp_i);
long long int i = tmp_r;
long long int r = 1;
while (i > 0) {
i /= 10;
r *= 10;
}
tmp += static_cast<ExprJIT::Real>(tmp_r) / static_cast<ExprJIT::Real>(r);
if (tmp_e != 0) {
tmp *= pow(10.0, tmp_e);
}
if (neg) {
tmp *= -1.0;
}
} else {
PARSE_ERR << "Unable to parse number";
}
value = tmp;
return m_nodeFactory.Immediate(tmp);
}
/**
* @brief Parse an expression
* @param in
* @return
*/
Node& parseExpression(std::istream &in, bool &isConstant, ExprJIT::Real &constValue)
{
return parseAddSub(in, isConstant, constValue);
}
/**
* @brief Parse a symbol (function or names constant).
* @param in
* @return
*/
Node& parseSymbol(std::istream &in, bool &isConstant, ExprJIT::Real &constValue)
{
isConstant = false;
skipSpace(in);
auto c = in.peek();
std::string identifier;
while ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '_')) {
identifier += static_cast<char>(in.get());
c = in.peek();
}
skipSpace(in);
c = in.peek();
if (c == '(') {
// Function call
in.get();
bool isC0 = false;
ExprJIT::Real cVal0;
Node &arg0 = parseTerm(in, isC0, cVal0);
Parser::skipSpace(in);
c = in.peek();
if (c == ')') {
in.get();
// 1-argument function
auto funcPtr = m_symbols.func1Ptr(identifier);
if (funcPtr != nullptr) {
if (isC0) {
isConstant = true;
constValue = funcPtr(cVal0);
markUnused(arg0);
return m_nodeFactory.Immediate(constValue);
}
auto &func = m_nodeFactory.Immediate(funcPtr);
return m_nodeFactory.Call(func, arg0);
}
} else if (c == ',') {
in.get();
bool isC1 = false;
ExprJIT::Real cVal1;
Node &arg1 = parseTerm(in, isC1, cVal1);
Parser::skipSpace(in);
c = in.peek();
if (c == ')') {
in.get();
// 2-arguments
auto funcPtr = m_symbols.func2Ptr(identifier);
if (funcPtr != nullptr) {
if (isC0 && isC1) {
isConstant = true;
constValue = funcPtr(cVal0, cVal1);
markUnused(arg0);
markUnused(arg1);
return m_nodeFactory.Immediate(constValue);
}
auto &func = m_nodeFactory.Immediate(funcPtr);
return m_nodeFactory.Call(func, arg0, arg1);
}
} else if (c == ',') {
in.get();
bool isC2 = false;
ExprJIT::Real cVal2;
Node &arg2 = parseTerm(in, isC2, cVal2);
Parser::skipSpace(in);
c = in.peek();
if (c == ')') {
in.get();
// 3-arguments
auto funcPtr = m_symbols.func3Ptr(identifier);
if (funcPtr != nullptr) {
if (isC0 && isC1 && isC2) {
isConstant = true;
constValue = funcPtr(cVal0, cVal1, cVal2);
markUnused(arg0);
markUnused(arg1);
markUnused(arg2);
return m_nodeFactory.Immediate(constValue);
}
auto &func = m_nodeFactory.Immediate(funcPtr);
return m_nodeFactory.Call(func, arg0, arg1, arg2);
}
} else if (c == ',') {
// Too many arguments
PARSE_ERR << "Too many arguments for '" << identifier << "' function call";
return m_nodeFactory.Immediate(0.0);
}
}
}
} else {
// Variable reference
ExprJIT::Real *ptr = m_symbols.varPtr(identifier);
if (ptr != nullptr) {
// Look of there is a cached node for this variable
auto it = m_symbolsCache.find(identifier);
if (it == m_symbolsCache.end()) {
// Create the reference node and cache it
auto &imm = m_nodeFactory.Immediate(ptr);
auto &node = m_nodeFactory.Deref(imm);
m_symbolsCache.insert(std::pair<std::string, Node&>(identifier, node));
return node;
} else {
// Return cached node
return it->second;
}
}
}
PARSE_ERR << "Unknown symbol '" << identifier << "'";
return m_nodeFactory.Immediate(0.0);
}
Node& parseTerm(std::istream &in, bool &isConstant, ExprJIT::Real &constValue)
{
isConstant = false;
skipSpace(in);
auto c = in.peek();
if ((c >= '0' && c <= '9')) {
isConstant = true;
return parseNumber(in, constValue);
} else if (c == '-') {
in.get();
c = in.peek();
if ((c >= '0' && c <= '9')) {
in.putback('-');
isConstant = true;
return parseNumber(in, constValue);
} else {
bool isC = false;
ExprJIT::Real cVal;
Node &rnode = parseTerm(in, isC, cVal);
if (isC) {
markUnused(rnode);
cVal = -cVal;
isConstant = true;
constValue = cVal;
return m_nodeFactory.Immediate(cVal);
} else {
Node &lnode = m_nodeFactory.Immediate(0.0);
return m_nodeFactory.Sub(lnode, rnode);
}
}
} else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_')) {
return parseSymbol(in, isConstant, constValue);
} else if (c == '(') {
in.get();
auto &n = parseExpression(in, isConstant, constValue);
if (!m_error) {
skipSpace(in);
c = in.peek();
if (c == ')') {
in.get();
} else {
PARSE_ERR << "Expected ')'";
}
}
return n;
} else {
PARSE_ERR << "Unexpected character '" << static_cast<char>(c) << "'";
}
return m_nodeFactory.Immediate(0.0);
}
Node& parseMulDiv(std::istream &in, bool &isConstant, ExprJIT::Real &constValue)
{
bool isC = false;
ExprJIT::Real cVal;
isConstant = false;
ExprJIT::Real accumulator = 1.0;
std::vector<std::reference_wrapper<Node> > mulNodes;
std::vector<std::reference_wrapper<Node> > divNodes;
Node &lnode = parseTerm(in, isC, cVal);
if (isC) {
accumulator = cVal;
markUnused(lnode);
} else {
mulNodes.push_back(lnode);
}
if (!error()) {
bool done = false;
do {
skipSpace(in);
auto c = in.peek();
if (c == '*') {
in.get();
Node &rnode = parseTerm(in, isC, cVal);
if (isC) {
accumulator *= cVal;
markUnused(rnode);
} else {
mulNodes.push_back(rnode);
}
} else if (c == '/') {
in.get();
Node &rnode = parseTerm(in, isC, cVal);
if (isC) {
accumulator /= cVal;
markUnused(rnode);
} else {
divNodes.push_back(rnode);
}
} else {
done = true;
}
} while (!done);
}
// There is no division node so we have to implement is as a function call
if (!mulNodes.empty()) {
std::reference_wrapper<Node> n = mulNodes.front();
for (size_t i = 1; i < mulNodes.size(); i++) {
Node &p = mulNodes.at(i);
n = m_nodeFactory.Mul(n.get(), p);
}
if (!divNodes.empty()) {
std::reference_wrapper<Node> p = divNodes.front();
for (size_t i = 1; i < divNodes.size(); i++) {
Node &d = divNodes.at(i);
p = m_nodeFactory.Mul(p.get(), d);
}
auto &call = m_nodeFactory.Immediate(Parser::invf);
p = m_nodeFactory.Call(call, p.get());
n = m_nodeFactory.Mul(n.get(), p.get());
}
if (accumulator != 1.0) {
n = m_nodeFactory.Mul(n.get(), m_nodeFactory.Immediate(accumulator));
}
return n.get();
}
if (!divNodes.empty()) {
std::reference_wrapper<Node> n = divNodes.front();
for (size_t i = 1; i < divNodes.size(); i++) {
Node &p = divNodes.at(i);
n = m_nodeFactory.Mul(n.get(), p);
}
auto &call = m_nodeFactory.Immediate(Parser::invf);
n = m_nodeFactory.Call(call, n.get());
if (accumulator != 1.0) {
n = m_nodeFactory.Mul(n.get(), m_nodeFactory.Immediate(accumulator));
}
return n.get();
}
isConstant = true;
constValue = accumulator;
return m_nodeFactory.Immediate(constValue);
}
Node& parseAddSub(std::istream &in, bool &isConstant, ExprJIT::Real &constValue)
{
bool isC = false;
ExprJIT::Real cVal;
isConstant = false;
ExprJIT::Real accumulator = 0.0;
std::vector<std::reference_wrapper<Node> > addNodes;
std::vector<std::reference_wrapper<Node> > subNodes;
Node &lnode = parseMulDiv(in, isC, cVal);
if (isC) {
accumulator = cVal;
markUnused(lnode);
} else {
addNodes.push_back(lnode);
}
if (!error()) {
bool done = false;
do {
skipSpace(in);
auto c = in.peek();
if (c == '+') {
in.get();
Node &rnode = parseMulDiv(in, isC, cVal);
if (isC) {
accumulator += cVal;
markUnused(rnode);
} else {
addNodes.push_back(rnode);
}
} else if (c == '-') {
in.get();
Node &rnode = parseMulDiv(in, isC, cVal);
if (isC) {
accumulator -= cVal;
markUnused(rnode);
} else {
subNodes.push_back(rnode);
}
} else {
done = true;
}
} while (!done);
}
if (!addNodes.empty()) {
std::reference_wrapper<Node> n = addNodes.front();
for (size_t i = 1; i < addNodes.size(); i++) {
Node &p = addNodes.at(i);
n = m_nodeFactory.Add(n.get(), p);
}
for (auto &&p : subNodes) {
n = m_nodeFactory.Sub(n.get(), p.get());
}
if (accumulator != 0.0) {
n = m_nodeFactory.Add(n.get(), m_nodeFactory.Immediate(accumulator));
}
return n;
}
if (!subNodes.empty()) {
std::reference_wrapper<Node> n = m_nodeFactory.Immediate(accumulator);
for (auto &&p : subNodes) {
n = m_nodeFactory.Sub(n.get(), p.get());
}
return n;
}
isConstant = true;
constValue = accumulator;
return m_nodeFactory.Immediate(constValue);
}
#undef PARSE_ERR
nj::ExpressionNodeFactory &m_nodeFactory;
SymbolTable &m_symbols; ///< External variables.
bool m_error; ///< Parsing error flag.
std::string m_message; ///< Error message.
/// Cache for variables Deref nodes.
std::map<std::string, Node&> m_symbolsCache;
};
//----------------------------------------------------------
// NativeJIT compiler wrapper
//----------------------------------------------------------
struct Compiler
{
nj::ExecutionBuffer codeAllocator;
nj::Allocator allocator;
nj::FunctionBuffer code;
nj::Function<ExprJIT::Real> expression;
nj::Function<ExprJIT::Real>::FunctionType func = nullptr;
Parser parser;
static ExprJIT::Real returnZero()
{
return 0.0;
}
Compiler(SymbolTable &symbols, const size_t capacity = CODE_BUFFER_SIZE)
: codeAllocator(capacity),
allocator(capacity),
code(codeAllocator, static_cast<unsigned>(capacity)),
expression(allocator, code),
func(Compiler::returnZero),
parser(expression, symbols)
{
// This will output generated assembly
#ifdef EXPRJIT_ENABLE_ASM_OUTPUT
code.EnableDiagnostics(std::cout);
#endif
}
bool compile(const std::string &str)
{
bool isConstant;
ExprJIT::Real constValue;
Parser::Node& node = parser.parse(str, isConstant, constValue);
if (!parser.error()) {
func = expression.Compile(node);
}
return !parser.error();
}
ExprJIT::Real eval() const
{
// func should always point to a valid function,
// either to returnZero() one or the one being compiled.
return func();
}
};
//----------------------------------------------------------
// ExprJIT private implementation
//----------------------------------------------------------
struct ExprJIT::Impl
{
SymbolTable symbols;
std::unique_ptr<Compiler> compiler;
Impl()
: compiler(nullptr)
{
}
bool compile(const std::string &str)
{
compiler = std::make_unique<Compiler>(symbols, CODE_BUFFER_SIZE);
return compiler->compile(str);
}
std::string error() const
{
if (compiler != nullptr) {
return compiler->parser.message();
}
return std::string();
}
ExprJIT::Real eval() const
{
return compiler->eval();
}
};
//----------------------------------------------------------
// ExprJIT::SymbolReference
//----------------------------------------------------------
ExprJIT::SymbolReference::SymbolReference(ExprJIT &exprjit, const std::string &name)
: m_exprjit(exprjit),
m_name(name)
{
}
ExprJIT::SymbolReference& ExprJIT::SymbolReference::operator =(const ExprJIT::Real value)
{
m_exprjit.setSymbol(m_name, value);
return *this;
}
ExprJIT::SymbolReference& ExprJIT::SymbolReference::operator =(Function1Ptr func)
{
m_exprjit.setSymbol(m_name, func);
return *this;
}
ExprJIT::SymbolReference& ExprJIT::SymbolReference::operator =(Function2Ptr func)
{
m_exprjit.setSymbol(m_name, func);
return *this;
}
ExprJIT::SymbolReference& ExprJIT::SymbolReference::operator =(Function3Ptr func)
{
m_exprjit.setSymbol(m_name, func);
return *this;
}
//----------------------------------------------------------
// ExprJIT public interface
//----------------------------------------------------------
ExprJIT::ExprJIT()
: d(std::make_unique<Impl>())
{
}
ExprJIT::~ExprJIT() = default;
bool ExprJIT::compile(const std::string &str)
{
return d->compile(str);
}
std::string ExprJIT::error() const
{
return d->error();
}
ExprJIT::Real ExprJIT::eval() const
{
return d->eval();
}
ExprJIT::SymbolReference ExprJIT::operator[](const std::string &name)
{
return SymbolReference(*this, name);
}
void ExprJIT::setSymbol(const std::string &name, const ExprJIT::Real value)
{
d->symbols.setVar(name, value);
}
void ExprJIT::setSymbol(const std::string &name, Function1Ptr func)
{
d->symbols.setFunc(name, func);
}
void ExprJIT::setSymbol(const std::string &name, Function2Ptr func)
{
d->symbols.setFunc(name, func);
}
void ExprJIT::setSymbol(const std::string &name, Function3Ptr func)
{
d->symbols.setFunc(name, func);
}
| 29.659436 | 99 | 0.475133 | [
"vector"
] |
2f4157cd896851828bb7702f2a307e60c7ba17dd | 1,975 | cpp | C++ | code/cpp/IMGresize.cpp | element-doo/ekade | 9430572dff420c926bccf1872dbfdf2fdaa1c7e5 | [
"BSD-3-Clause"
] | null | null | null | code/cpp/IMGresize.cpp | element-doo/ekade | 9430572dff420c926bccf1872dbfdf2fdaa1c7e5 | [
"BSD-3-Clause"
] | null | null | null | code/cpp/IMGresize.cpp | element-doo/ekade | 9430572dff420c926bccf1872dbfdf2fdaa1c7e5 | [
"BSD-3-Clause"
] | null | null | null | #define cimg_display 0
#define PIC "pic."
#define PIC_RES "picresize."
#define PORT 10020
#include <iostream>
#include <fstream>
#include <sstream>
#include "CImg.h"
#include "base64.h"
#include <jsonrpc/rpc.h>
#include "abstractimgserver.h"
using namespace jsonrpc;
using namespace std;
using namespace Json;
class IMGServer : public AbstractIMGServer{
public:
IMGServer();
virtual Value resize(const string& width, const string& format, const string& height, const string& maxWidth, const string& maxHeight, const string& body);
};
IMGServer::IMGServer():AbstractIMGServer(new HttpServer(PORT)){
}
Value IMGServer::resize(const string& body, const string& format, const string& height, const string& maxHeight, const string& maxWidth, const string& width){
string picFilename(PIC);
picFilename+=format;
string picResizeFilename(PIC_RES);
picResizeFilename+=format;
fstream pic(picFilename.c_str(), ofstream::binary | ofstream::out);
vector<BYTE> decode = base64_decode(body);
for(int i=0; i<decode.size(); ++i) pic.write((const char*)&decode[i], 1);
pic.close();
Value ret;
cimg_library::CImg<float> img(picFilename.c_str());
if(img.width()>atoi(maxWidth.c_str()) || img.height()>atoi(maxHeight.c_str())){
ret["error"]="400";
stringstream error;
error<<"Slika je veličine: "<<img.width()<<" x "<<img.height()<<", a maksimalno podržano je: "<<maxWidth<<" x "<<maxHeight<<".";
ret["errorMsg"]=error.str();
return ret;
}
img.resize(atoi(width.c_str()), atoi(height.c_str()));
img.save(picResizeFilename.c_str());
vector<BYTE> raw;
pic.open(picResizeFilename.c_str(), ofstream::binary | ofstream::in);
char buffer;
for(pic.read(&buffer, 1); !pic.eof(); raw.push_back(buffer), pic.read(&buffer, 1));
pic.close();
string encode = base64_encode(&raw[0], raw.size());
ret["resizedBody"]=encode.c_str();
return ret;
}
int main()
{
IMGServer s;
s.StartListening();
getchar();
s.StopListening();
return 0;
}
| 27.054795 | 163 | 0.700759 | [
"vector"
] |
2f4622047b2fce6828eed8099117c95dcf041716 | 2,786 | cpp | C++ | aws-cpp-sdk-transcribe/source/model/ContentRedaction.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-transcribe/source/model/ContentRedaction.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-transcribe/source/model/ContentRedaction.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/transcribe/model/ContentRedaction.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace TranscribeService
{
namespace Model
{
ContentRedaction::ContentRedaction() :
m_redactionType(RedactionType::NOT_SET),
m_redactionTypeHasBeenSet(false),
m_redactionOutput(RedactionOutput::NOT_SET),
m_redactionOutputHasBeenSet(false),
m_piiEntityTypesHasBeenSet(false)
{
}
ContentRedaction::ContentRedaction(JsonView jsonValue) :
m_redactionType(RedactionType::NOT_SET),
m_redactionTypeHasBeenSet(false),
m_redactionOutput(RedactionOutput::NOT_SET),
m_redactionOutputHasBeenSet(false),
m_piiEntityTypesHasBeenSet(false)
{
*this = jsonValue;
}
ContentRedaction& ContentRedaction::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("RedactionType"))
{
m_redactionType = RedactionTypeMapper::GetRedactionTypeForName(jsonValue.GetString("RedactionType"));
m_redactionTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("RedactionOutput"))
{
m_redactionOutput = RedactionOutputMapper::GetRedactionOutputForName(jsonValue.GetString("RedactionOutput"));
m_redactionOutputHasBeenSet = true;
}
if(jsonValue.ValueExists("PiiEntityTypes"))
{
Array<JsonView> piiEntityTypesJsonList = jsonValue.GetArray("PiiEntityTypes");
for(unsigned piiEntityTypesIndex = 0; piiEntityTypesIndex < piiEntityTypesJsonList.GetLength(); ++piiEntityTypesIndex)
{
m_piiEntityTypes.push_back(PiiEntityTypeMapper::GetPiiEntityTypeForName(piiEntityTypesJsonList[piiEntityTypesIndex].AsString()));
}
m_piiEntityTypesHasBeenSet = true;
}
return *this;
}
JsonValue ContentRedaction::Jsonize() const
{
JsonValue payload;
if(m_redactionTypeHasBeenSet)
{
payload.WithString("RedactionType", RedactionTypeMapper::GetNameForRedactionType(m_redactionType));
}
if(m_redactionOutputHasBeenSet)
{
payload.WithString("RedactionOutput", RedactionOutputMapper::GetNameForRedactionOutput(m_redactionOutput));
}
if(m_piiEntityTypesHasBeenSet)
{
Array<JsonValue> piiEntityTypesJsonList(m_piiEntityTypes.size());
for(unsigned piiEntityTypesIndex = 0; piiEntityTypesIndex < piiEntityTypesJsonList.GetLength(); ++piiEntityTypesIndex)
{
piiEntityTypesJsonList[piiEntityTypesIndex].AsString(PiiEntityTypeMapper::GetNameForPiiEntityType(m_piiEntityTypes[piiEntityTypesIndex]));
}
payload.WithArray("PiiEntityTypes", std::move(piiEntityTypesJsonList));
}
return payload;
}
} // namespace Model
} // namespace TranscribeService
} // namespace Aws
| 27.86 | 143 | 0.775305 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.